public function test_register_carf_post_status()
 {
     $post_status_object = get_post_status_object('carf');
     $this->assertNull($post_status_object);
     register_extended_post_status('carf', ['label' => 'Car']);
     $post_status_object = get_post_status_object('carf');
     $this->assertSame('Car', $post_status_object->label);
 }
 /**
  * Get a specific post status
  *
  * @param WP_REST_Request $request
  * @return array|WP_Error
  */
 public function get_item($request)
 {
     $obj = get_post_status_object($request['status']);
     if (empty($obj)) {
         return new WP_Error('rest_status_invalid', __('Invalid status.'), array('status' => 404));
     }
     return $this->prepare_item_for_response($obj, $request);
 }
Example #3
0
/**
 * Output the ID row.
 *
 * @since	1.0
 * @param	int	$ticket_id	The ticket ID
 * @param	obj	$kbs_ticket	The ticket WP_Post object
 * @return	str
 */
function kb_tickets_post_column_id($ticket_id, $kbs_ticket)
{
    do_action('kb_pre_tickets_column_id', $kbs_ticket);
    $output = '<a href="' . get_edit_post_link($ticket_id) . '">#' . $ticket_id . '</a>';
    $output .= '<br />';
    $output .= get_post_status_object($kbs_ticket->post_status)->label;
    do_action('kb_post_tickets_column_id', $kbs_ticket);
    return apply_filters('kb_tickets_post_column_id', $output, $ticket_id);
}
Example #4
0
 /**
  * Returns true if a post can be "reacted" upon, false if not
  */
 public static function can_react_to_post($post_ID)
 {
     $post = get_post($post_ID);
     if (!$post || is_wp_error($post)) {
         return false;
     }
     if ('inherit' === $post->post_status) {
         $parent_post = get_post($post->post_parent);
         $post_password = $parent_post->post_password;
         $post_status_obj = get_post_status_object($parent_post->post_status);
         $post_status = $parent_post->post_status;
     } else {
         $post_status_obj = get_post_status_object($post->post_status);
         $post_status = $post->post_status;
         $post_password = $post->post_password;
     }
     if (!$post_status_obj->public) {
         if (is_user_logged_in()) {
             if ($post_status_obj->protected) {
                 if (!current_user_can('edit_post', $post->ID)) {
                     return false;
                 }
             } elseif ($post_status_obj->private) {
                 if (!current_user_can('read_post', $post->ID)) {
                     return false;
                 }
             } else {
                 return false;
             }
         } else {
             return false;
         }
     }
     if (in_array($post_status, array('draft', 'pending', 'future', 'trash'))) {
         return false;
     }
     if (strlen($post_password) && !current_user_can('read_post', $post->ID)) {
         return false;
     }
     if ('off' === get_option('emoji_reactions_allow_guest_reactions', 'off') && !is_user_logged_in()) {
         return false;
     }
     if (is_user_logged_in()) {
         $check_count_against = array('user_id' => get_current_user_id());
     } else {
         $check_count_against = array('search' => preg_replace('/[^0-9a-fA-F:., ]/', '', $_SERVER['REMOTE_ADDR']));
     }
     $allowed_reactions_per_user = get_option('emoji_reactions_num_per_user_per_post', 10);
     if ($allowed_reactions_per_user > 0) {
         $check_count_against = array('type' => 'emoji-reaction', 'count' => true) + $check_count_against;
         $current_user_reaction_count = get_comments($check_count_against);
         if ($current_user_reaction_count >= $allowed_reactions_per_user) {
             return false;
         }
     }
     return true;
 }
Example #5
0
 public static function create_comment($entry_id, $form_id)
 {
     $comment_post_ID = isset($_POST['comment_post_ID']) ? (int) $_POST['comment_post_ID'] : 0;
     $post = get_post($comment_post_ID);
     if (empty($post->comment_status)) {
         return;
     }
     // get_post_status() will get the parent status for attachments.
     $status = get_post_status($post);
     $status_obj = get_post_status_object($status);
     if (!comments_open($comment_post_ID)) {
         do_action('comment_closed', $comment_post_ID);
         //wp_die( __( 'Sorry, comments are closed for this item.') );
         return;
     } else {
         if ('trash' == $status) {
             do_action('comment_on_trash', $comment_post_ID);
             return;
         } else {
             if (!$status_obj->public && !$status_obj->private) {
                 do_action('comment_on_draft', $comment_post_ID);
                 return;
             } else {
                 if (post_password_required($comment_post_ID)) {
                     do_action('comment_on_password_protected', $comment_post_ID);
                     return;
                 } else {
                     do_action('pre_comment_on_post', $comment_post_ID);
                 }
             }
         }
     }
     $comment_content = isset($_POST['comment']) ? trim($_POST['comment']) : '';
     // If the user is logged in
     $user_ID = get_current_user_id();
     if ($user_ID) {
         global $current_user;
         $display_name = !empty($current_user->display_name) ? $current_user->display_name : $current_user->user_login;
         $comment_author = $display_name;
         $comment_author_email = '';
         //get email from field
         $comment_author_url = $current_user->user_url;
     } else {
         $comment_author = isset($_POST['author']) ? trim(strip_tags($_POST['author'])) : '';
         $comment_author_email = isset($_POST['email']) ? trim($_POST['email']) : '';
         $comment_author_url = isset($_POST['url']) ? trim($_POST['url']) : '';
     }
     $comment_type = '';
     if (!$user_ID && get_option('require_name_email') && (6 > strlen($comment_author_email) || $comment_author == '')) {
         return;
     }
     if ($comment_content == '') {
         return;
     }
     $commentdata = compact('comment_post_ID', 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_content', 'comment_type', 'user_ID');
     wp_new_comment($commentdata);
 }
 public static function register_post_stati()
 {
     if (get_post_status_object('btb_canceled')) {
         return;
     }
     $args = array('label' => _x('Booked', 'Status General Name', 'bt-booking'), 'label_count' => _n_noop('Booked <span class="count">(%s)</a>', 'Booked <span class="count">(%s)</a>', 'bt-booking'), 'protected' => true, 'show_in_admin_status_list' => true, 'exclude_from_search' => false);
     register_post_status('btb_booked', $args);
     $args = array('label' => _x('Prebooked', 'Status General Name', 'bt-booking'), 'label_count' => _n_noop('Prebooked <span class="count">(%s)</a>', 'Prebooked <span class="count">(%s)</a>', 'bt-booking'), 'protected' => true, 'show_in_admin_status_list' => true, 'exclude_from_search' => false);
     register_post_status('btb_prebook', $args);
     $args = array('label' => _x('Canceled', 'Status General Name', 'bt-booking'), 'label_count' => _n_noop('Canceled <span class="count">(%s)</a>', 'Canceled <span class="count">(%s)</a>', 'bt-booking'), 'protected' => true, 'show_in_admin_status_list' => true, 'exclude_from_search' => false);
     register_post_status('btb_canceled', $args);
 }
 function get_data($item)
 {
     $data = array('title-attr' => $item->get_permalink());
     $post = $item->get_object();
     if ('publish' != $post->post_status) {
         $status_obj = get_post_status_object($post->post_status);
         if ($status_obj) {
             $data['status']['text'] = $status_obj->label;
         }
     }
     return $data;
 }
Example #8
0
 /**
  * Setup the list table and render the list table page, or call the given
  * action.
  *
  * @param string                        $page_title
  * @param WordPress\Orm\Admin\ListTable $list_table
  */
 public static function render_list_table_page($page_title, $list_table)
 {
     // We pass the class to filters & actions
     $list_table_class = get_class($list_table);
     // Get stuff
     $pagenum = $list_table->get_pagenum();
     $action = $list_table->current_action();
     if ($action) {
         check_admin_referer('bulk-posts');
         $sendback = remove_query_arg(array('trashed', 'untrashed', 'deleted', 'locked', 'ids'), wp_get_referer());
         // Comment this
         if (!$sendback) {
             $sendback = admin_url('admin.php?page=test-venues');
         }
         // Add the current page to the sendback URL
         $sendback = add_query_arg('paged', $pagenum, $sendback);
         // ?
         if (strpos($sendback, 'post.php') !== false) {
             $sendback = admin_url($post_new_file);
         }
         // Get the post ids to operate on
         if ('delete_all' == $doaction) {
             $post_status = preg_replace('/[^a-z0-9_-]+/i', '', $_REQUEST['post_status']);
             if (get_post_status_object($post_status)) {
                 $post_ids = $wpdb->get_col($wpdb->prepare("SELECT ID FROM {$wpdb->posts} WHERE post_type=%s AND post_status = %s", $post_type, $post_status));
             }
             $doaction = 'delete';
         } elseif (isset($_REQUEST['media'])) {
             $post_ids = $_REQUEST['media'];
         } elseif (isset($_REQUEST['ids'])) {
             $post_ids = explode(',', $_REQUEST['ids']);
         } elseif (!empty($_REQUEST['post'])) {
             $post_ids = array_map('intval', $_REQUEST['post']);
         }
         if (!isset($post_ids)) {
             wp_redirect($sendback);
             exit;
         }
         // Plugins need to do their thing here
         do_action('wporm:list_table:action', $action, $post_ids, $list_table, $list_table_class);
         // Redirect the user
         $sendback = remove_query_arg(['action', 'action2', 'tags_input', 'post_author', 'comment_status', 'ping_status', '_status', 'post', 'bulk_edit', 'post_view'], $sendback);
         wp_redirect($sendback);
         exit;
     } elseif (!empty($_REQUEST['_wp_http_referer'])) {
         wp_redirect(remove_query_arg(array('_wp_http_referer', '_wpnonce'), wp_unslash($_SERVER['REQUEST_URI'])));
         exit;
     }
     $list_table->prepare_items();
     require ABSPATH . 'wp-admin/admin-header.php';
     require __DIR__ . '/../views/list-table.php';
 }
function sv_render_status_column($column_name, $post_id)
{
    global $post;
    if ($column_name === 'status') {
        $currentPostStatus = $post->post_status;
        $statusObject = get_post_status_object($currentPostStatus);
        if ($statusObject != null) {
            printf('<mark class="%1$s tips" data-tip="%2$s">%3$s</mark>', $statusObject->name, $statusObject->label, $statusObject->label);
        } else {
            printf('<mark class="$1%s tips" data-tip="$1%s">$1%s</mark>', $currentPostStatus);
        }
    }
}
 /**
  * Hooks the WP get_comments_number filter to get the number of comments
  * across all posts in the translation group.
  *
  * @param int $count The number of comments on the single translation
  * @param int $post_id The post ID of the single translation
  * @return int The count of all comments on published posts in this translation group
  **/
 public function get_comments_number($count, $post_id)
 {
     $translations = bbl_get_post_translations($post_id);
     $count = 0;
     foreach ($translations as &$translation) {
         $post_status = get_post_status_object($translation->post_status);
         // FIXME: I'm not entirely sure about using publicly_queryable here… what I want to avoid is draft, private, etc statii.
         if ($post_status->publicly_queryable) {
             $count += $translation->comment_count;
         }
     }
     return $count;
 }
 function fix_table_edit_reqd_caps($rs_reqd_caps, $orig_meta_cap, $_post, $object_type_obj)
 {
     foreach (array('edit', 'delete') as $op) {
         if (in_array($orig_meta_cap, array("{$op}_post", "{$op}_page"))) {
             $status_obj = get_post_status_object($_post->post_status);
             foreach (array('public' => 'published', 'private' => 'private') as $status_prop => $cap_suffix) {
                 if (!empty($status_obj->{$status_prop})) {
                     $cap_prop = "{$op}_{$cap_suffix}_posts";
                     $rs_reqd_caps[] = $object_type_obj->cap->{$cap_prop};
                     $GLOBALS['revisionary']->skip_revision_allowance = true;
                 }
             }
         }
     }
     return $rs_reqd_caps;
 }
/**
 * Helper function for checking if a user can read forums, topics, or replies. We need this to handle 
 * users who are not logged in but should have permission to read (e.g, non-private forums).  This 
 * function is meant to be used in conjunction with a filter on `map_meta_cap`.
 *
 * @since  1.0.0
 * @access public
 * @param  int     $user_id
 * @param  string  $cap
 * @param  int     $post_id
 * @return bool
 */
function mb_user_can($user_id, $cap, $post_id)
{
    // @todo Check hierarchy.
    if (in_array($cap, array('read_forum', 'read_topic', 'read_reply'))) {
        if ('read_forum' === $cap) {
            $status_obj = get_post_status_object(mb_get_forum_status($post_id));
        } elseif ('read_topic' === $cap) {
            $status_obj = get_post_status_object(mb_get_topic_status($post_id));
        } elseif ('read_forum' === $cap) {
            $status_obj = get_post_status_object(mb_get_reply_status($post_id));
        }
        if (false === $status_obj->private && false === $status_obj->protected) {
            return true;
        }
    }
    return user_can($user_id, $cap, $post_id);
}
function _pp_flt_map_media_meta_cap($caps, $cap, $user_id, $args)
{
    if (!empty($args[0])) {
        $post = is_object($args[0]) ? $args[0] : get_post($args[0]);
        if ($post && 'attachment' == $post->post_type) {
            if (!empty($post->post_parent)) {
                $post_status = get_post_status($post->ID);
            } elseif ('inherit' == $post->post_status) {
                $post_status = pp_get_option('unattached_files_private') ? 'private' : 'publish';
            } else {
                $post_status = $post->post_status;
            }
            $post_type = get_post_type_object($post->post_type);
            $post_author_id = $post->post_author;
            $caps = array_diff($caps, (array) $cap);
            switch ($cap) {
                case 'read_post':
                case 'read_page':
                    $status_obj = get_post_status_object($post_status);
                    if ($status_obj->public || $status_obj->private && $user_id == $post_author_id) {
                        $caps[] = $post_type->cap->read;
                        break;
                    }
                    // If no author set yet, default to current user for cap checks.
                    if (!$post_author_id) {
                        $post_author_id = $user_id;
                    }
                    if ($status_obj->private) {
                        $caps[] = $post_type->cap->read_private_posts;
                    } else {
                        $caps = map_meta_cap('edit_post', $user_id, $post->ID);
                    }
                    $caps = apply_filters('pp_map_attachment_read_caps', $caps, $post, $user_id);
                    break;
                default:
                    require_once dirname(__FILE__) . '/media-edit-metacap-workaround_pp.php';
                    $args = array_merge($args, compact('post', 'post_status', 'post_type', 'post_author_id'));
                    $caps = _ppff_flt_map_media_edit_meta_cap($caps, $cap, $user_id, $args);
            }
        }
    }
    return $caps;
}
 /**
  * Produce the column values for the custom columns we created
  */
 function action_manage_posts_custom_column($column_name, $ticket_id)
 {
     switch ($column_name) {
         case 'updated':
             $modified_gmt = get_post_modified_time('U', true, $ticket_id);
             echo sprintf(__('%s ago', 'supportflow'), human_time_diff($modified_gmt));
             break;
         case 'sf_excerpt':
             $replies = SupportFlow()->get_ticket_replies($ticket_id, array('posts_per_page' => 1, 'order' => 'ASC'));
             if (!isset($replies[0])) {
                 echo '—';
                 break;
             }
             $first_reply = $replies[0]->post_content;
             if (strlen($first_reply) > 50) {
                 $first_reply = substr($first_reply, 0, 50);
             }
             echo $first_reply;
             break;
         case 'customers':
             $customers = SupportFlow()->get_ticket_customers($ticket_id, array('fields' => 'emails'));
             if (empty($customers)) {
                 echo '—';
                 break;
             }
             foreach ($customers as $key => $customer_email) {
                 $args = array(SupportFlow()->customers_tax => SupportFlow()->get_email_hash($customer_email), 'post_type' => SupportFlow()->post_type);
                 $customer_photo = get_avatar($customer_email, 16);
                 $customer_link = '<a class="customer_link" href="' . esc_url(add_query_arg($args, admin_url('edit.php'))) . '">' . $customer_email . '</a>';
                 $customers[$key] = $customer_photo . '&nbsp;' . $customer_link;
             }
             echo implode('<br />', $customers);
             break;
         case 'status':
             $post_status = get_post_status($ticket_id);
             $args = array('post_type' => SupportFlow()->post_type, 'post_status' => $post_status);
             $status_name = get_post_status_object($post_status)->label;
             $filter_link = add_query_arg($args, admin_url('edit.php'));
             echo '<a href="' . esc_url($filter_link) . '">' . esc_html($status_name) . '</a>';
             break;
         case 'email':
             $email_account_id = get_post_meta($ticket_id, 'email_account', true);
             $email_accounts = SupportFlow()->extend->email_accounts->get_email_accounts();
             $args = array('post_type' => SupportFlow()->post_type, 'email_account' => $email_account_id);
             if (!isset($email_accounts[$email_account_id])) {
                 echo '—';
                 break;
             }
             $email_account_username = $email_accounts[$email_account_id]['username'];
             $filter_link = add_query_arg($args, admin_url('edit.php'));
             echo '<a href="' . esc_url($filter_link) . '">' . esc_html($email_account_username) . '</a>';
             break;
         case 'sf_replies':
             $replies = SupportFlow()->get_ticket_replies_count($ticket_id);
             echo '<div class="post-com-count-wrapper">';
             echo "<span class='replies-count'>{$replies}</span>";
             echo '</div>';
             break;
         case 'created':
             $created_time = get_the_time(get_option('time_format') . ' T', $ticket_id);
             $created_date = get_the_time(get_option('date_format'), $ticket_id);
             echo sprintf(__('%s<br />%s', 'supportflow'), $created_time, $created_date);
             break;
     }
 }
 /**
  * Parsing the column based on the $column_name.
  *
  * @param string    $column_name
  * @param stdobject $rec
  *
  * @return string
  */
 protected function parse_column($column_name, $rec)
 {
     static $date_format;
     if ($date_format == null) {
         $date_format = get_option('date_format');
     }
     switch ($column_name) {
         case 'col_page_title':
             $column_value = $this->parse_page_title_column($rec);
             break;
         case 'col_page_slug':
             $permalink = get_permalink($rec->ID);
             $display_slug = str_replace(get_bloginfo('url'), '', $permalink);
             $column_value = sprintf('<a href="%2$s" target="_blank">%1$s</a>', stripslashes($display_slug), esc_url($permalink));
             break;
         case 'col_post_type':
             $post_type = get_post_type_object($rec->post_type);
             $column_value = $post_type->labels->singular_name;
             break;
         case 'col_post_status':
             $post_status = get_post_status_object($rec->post_status);
             $column_value = $post_status->label;
             break;
         case 'col_post_date':
             $column_value = date_i18n($date_format, strtotime($rec->post_date));
             break;
         case 'col_row_action':
             $column_value = sprintf('<a href="#" class="wpseo-save" data-id="%1$s">Save</a> | <a href="#" class="wpseo-save-all">Save All</a>', $rec->ID);
             break;
     }
     if (!empty($column_value)) {
         return $column_value;
     }
 }
Example #16
0
/**
 * Rename $_POST data from form names to DB post columns.
 *
 * Manipulates $_POST directly.
 *
 * @package WordPress
 * @since 2.6.0
 *
 * @param bool $update Are we updating a pre-existing post?
 * @param array $post_data Array of post data. Defaults to the contents of $_POST.
 * @return object|bool WP_Error on failure, true on success.
 */
function _wp_translate_postdata($update = false, $post_data = null)
{
    if (empty($post_data)) {
        $post_data =& $_POST;
    }
    if ($update) {
        $post_data['ID'] = (int) $post_data['post_ID'];
    }
    $ptype = get_post_type_object($post_data['post_type']);
    if ($update && !current_user_can('edit_post', $post_data['ID'])) {
        if ('page' == $post_data['post_type']) {
            return new WP_Error('edit_others_pages', __('Sorry, you are not allowed to edit pages as this user.'));
        } else {
            return new WP_Error('edit_others_posts', __('Sorry, you are not allowed to edit posts as this user.'));
        }
    } elseif (!$update && !current_user_can($ptype->cap->create_posts)) {
        if ('page' == $post_data['post_type']) {
            return new WP_Error('edit_others_pages', __('Sorry, you are not allowed to create pages as this user.'));
        } else {
            return new WP_Error('edit_others_posts', __('Sorry, you are not allowed to create posts as this user.'));
        }
    }
    if (isset($post_data['content'])) {
        $post_data['post_content'] = $post_data['content'];
    }
    if (isset($post_data['excerpt'])) {
        $post_data['post_excerpt'] = $post_data['excerpt'];
    }
    if (isset($post_data['parent_id'])) {
        $post_data['post_parent'] = (int) $post_data['parent_id'];
    }
    if (isset($post_data['trackback_url'])) {
        $post_data['to_ping'] = $post_data['trackback_url'];
    }
    $post_data['user_ID'] = get_current_user_id();
    if (!empty($post_data['post_author_override'])) {
        $post_data['post_author'] = (int) $post_data['post_author_override'];
    } else {
        if (!empty($post_data['post_author'])) {
            $post_data['post_author'] = (int) $post_data['post_author'];
        } else {
            $post_data['post_author'] = (int) $post_data['user_ID'];
        }
    }
    if (isset($post_data['user_ID']) && $post_data['post_author'] != $post_data['user_ID'] && !current_user_can($ptype->cap->edit_others_posts)) {
        if ($update) {
            if ('page' == $post_data['post_type']) {
                return new WP_Error('edit_others_pages', __('Sorry, you are not allowed to edit pages as this user.'));
            } else {
                return new WP_Error('edit_others_posts', __('Sorry, you are not allowed to edit posts as this user.'));
            }
        } else {
            if ('page' == $post_data['post_type']) {
                return new WP_Error('edit_others_pages', __('Sorry, you are not allowed to create pages as this user.'));
            } else {
                return new WP_Error('edit_others_posts', __('Sorry, you are not allowed to create posts as this user.'));
            }
        }
    }
    if (!empty($post_data['post_status'])) {
        $post_data['post_status'] = sanitize_key($post_data['post_status']);
        // No longer an auto-draft
        if ('auto-draft' === $post_data['post_status']) {
            $post_data['post_status'] = 'draft';
        }
        if (!get_post_status_object($post_data['post_status'])) {
            unset($post_data['post_status']);
        }
    }
    // What to do based on which button they pressed
    if (isset($post_data['saveasdraft']) && '' != $post_data['saveasdraft']) {
        $post_data['post_status'] = 'draft';
    }
    if (isset($post_data['saveasprivate']) && '' != $post_data['saveasprivate']) {
        $post_data['post_status'] = 'private';
    }
    if (isset($post_data['publish']) && '' != $post_data['publish'] && (!isset($post_data['post_status']) || $post_data['post_status'] != 'private')) {
        $post_data['post_status'] = 'publish';
    }
    if (isset($post_data['advanced']) && '' != $post_data['advanced']) {
        $post_data['post_status'] = 'draft';
    }
    if (isset($post_data['pending']) && '' != $post_data['pending']) {
        $post_data['post_status'] = 'pending';
    }
    if (isset($post_data['ID'])) {
        $post_id = $post_data['ID'];
    } else {
        $post_id = false;
    }
    $previous_status = $post_id ? get_post_field('post_status', $post_id) : false;
    if (isset($post_data['post_status']) && 'private' == $post_data['post_status'] && !current_user_can($ptype->cap->publish_posts)) {
        $post_data['post_status'] = $previous_status ? $previous_status : 'pending';
    }
    $published_statuses = array('publish', 'future');
    // Posts 'submitted for approval' present are submitted to $_POST the same as if they were being published.
    // Change status from 'publish' to 'pending' if user lacks permissions to publish or to resave published posts.
    if (isset($post_data['post_status']) && (in_array($post_data['post_status'], $published_statuses) && !current_user_can($ptype->cap->publish_posts))) {
        if (!in_array($previous_status, $published_statuses) || !current_user_can('edit_post', $post_id)) {
            $post_data['post_status'] = 'pending';
        }
    }
    if (!isset($post_data['post_status'])) {
        $post_data['post_status'] = 'auto-draft' === $previous_status ? 'draft' : $previous_status;
    }
    if (isset($post_data['post_password']) && !current_user_can($ptype->cap->publish_posts)) {
        unset($post_data['post_password']);
    }
    if (!isset($post_data['comment_status'])) {
        $post_data['comment_status'] = 'closed';
    }
    if (!isset($post_data['ping_status'])) {
        $post_data['ping_status'] = 'closed';
    }
    foreach (array('aa', 'mm', 'jj', 'hh', 'mn') as $timeunit) {
        if (!empty($post_data['hidden_' . $timeunit]) && $post_data['hidden_' . $timeunit] != $post_data[$timeunit]) {
            $post_data['edit_date'] = '1';
            break;
        }
    }
    if (!empty($post_data['edit_date'])) {
        $aa = $post_data['aa'];
        $mm = $post_data['mm'];
        $jj = $post_data['jj'];
        $hh = $post_data['hh'];
        $mn = $post_data['mn'];
        $ss = $post_data['ss'];
        $aa = $aa <= 0 ? date('Y') : $aa;
        $mm = $mm <= 0 ? date('n') : $mm;
        $jj = $jj > 31 ? 31 : $jj;
        $jj = $jj <= 0 ? date('j') : $jj;
        $hh = $hh > 23 ? $hh - 24 : $hh;
        $mn = $mn > 59 ? $mn - 60 : $mn;
        $ss = $ss > 59 ? $ss - 60 : $ss;
        $post_data['post_date'] = sprintf("%04d-%02d-%02d %02d:%02d:%02d", $aa, $mm, $jj, $hh, $mn, $ss);
        $valid_date = wp_checkdate($mm, $jj, $aa, $post_data['post_date']);
        if (!$valid_date) {
            return new WP_Error('invalid_date', __('Whoops, the provided date is invalid.'));
        }
        $post_data['post_date_gmt'] = get_gmt_from_date($post_data['post_date']);
    }
    if (isset($post_data['post_category'])) {
        $category_object = get_taxonomy('category');
        if (!current_user_can($category_object->cap->assign_terms)) {
            unset($post_data['post_category']);
        }
    }
    return $post_data;
}
 /**
  * Outputs the contents of a meta editing table.
  * 
  * @since 2.9
  * 
  * @param string $genus The type of object being handled (either 'post' or 'term')
  * @param string $tab The ID of the current tab; used to generate a URL hash (e.g. #$tab)
  * @param string $type The type of post/taxonomy type being edited (examples: post, page, attachment, category, post_tag)
  * @param string $type_label The singular label for the post/taxonomy type (examples: Post, Page, Attachment, Category, Post Tag)
  * @param array $fields The array of meta fields that the user can edit with the tables. The data for each meta field are stored in an array with these elements: "type" (can be textbox, textarea, or checkbox), "name" (the meta field, e.g. title or description), "term_settings_key" (the key of the setting for cases when term meta data are stored in the settings array), and "label" (the internationalized label of the field, e.g. "Meta Description" or "Title Tag")
  */
 function meta_edit_table($genus, $tab, $type, $type_label, $fields)
 {
     //Pseudo-constant
     $per_page = 100;
     //Sanitize parameters
     if (!is_array($fields) || !count($fields)) {
         return false;
     }
     if (!isset($fields[0]) || !is_array($fields[0])) {
         $fields = array($fields);
     }
     //Get search query
     $type_s = $type . '_s';
     $search = isset($_REQUEST[$type_s]) ? $_REQUEST[$type_s] : '';
     //Save meta if applicable
     if ($is_update = $this->is_action('update') && !strlen(trim($search))) {
         foreach ($_POST as $key => $value) {
             $value = stripslashes($value);
             if (sustr::startswith($key, $genus . '_')) {
                 foreach ($fields as $field) {
                     if (preg_match("/{$genus}_([0-9]+)_{$field['name']}/", $key, $matches)) {
                         $id = (int) $matches[1];
                         switch ($genus) {
                             case 'post':
                                 update_post_meta($id, "_su_{$field['name']}", $value);
                                 break;
                             case 'term':
                                 $this->update_setting($field['term_settings_key'], $value, null, $id);
                                 break;
                         }
                         continue 2;
                         //Go to next $_POST item
                     }
                 }
             }
         }
     }
     $pagenum = isset($_GET[$type . '_paged']) ? absint($_GET[$type . '_paged']) : 0;
     if (empty($pagenum)) {
         $pagenum = 1;
     }
     //Load up the objects based on the genus
     switch ($genus) {
         case 'post':
             //Get the posts
             wp(array('post_type' => $type, 'posts_per_page' => $per_page, 'post_status' => 'any', 'paged' => $pagenum, 'order' => 'ASC', 'orderby' => 'title', 's' => $search));
             global $wp_query;
             $objects =& $wp_query->posts;
             $num_pages = $wp_query->max_num_pages;
             $total_objects = $wp_query->found_posts;
             break;
         case 'term':
             $objects = get_terms($type, array('search' => $search));
             $total_objects = count($objects);
             $num_pages = ceil($total_objects / $per_page);
             $objects = array_slice($objects, $per_page * ($pagenum - 1), $per_page);
             break;
         default:
             return false;
             break;
     }
     if ($total_objects < 1) {
         return false;
     }
     echo "\n<div class='su-meta-edit-table'>\n";
     $page_links = paginate_links(array('base' => add_query_arg($type . '_paged', '%#%') . '#' . $tab, 'format' => '', 'prev_text' => __('&laquo;'), 'next_text' => __('&raquo;'), 'total' => $num_pages, 'current' => $pagenum));
     if ($page_links) {
         $page_links_text = '<div class="tablenav"><div class="tablenav-pages">';
         $page_links_text .= sprintf('<span class="displaying-num">' . __('Displaying %s&#8211;%s of %s') . '</span>%s', number_format_i18n(($pagenum - 1) * $per_page + 1), number_format_i18n(min($pagenum * $per_page, $total_objects)), number_format_i18n($total_objects), $page_links);
         $page_links_text .= "</div></div>\n";
         echo $page_links_text;
     } else {
         $page_links_text = '';
     }
     //Get object identification headers
     $headers = array('actions' => __('Actions', 'seo-ultimate'), 'id' => __('ID', 'seo-ultimate'), 'name' => $type_label);
     //Get meta field headers
     foreach ($fields as $field) {
         $headers[$field['name']] = $field['label'];
     }
     //Output all headers
     $this->admin_wftable_start($headers);
     //Output rows
     foreach ($objects as $object) {
         switch ($genus) {
             case 'post':
                 $id = intval($object->ID);
                 $name = $object->post_title;
                 $view_url = get_permalink($id);
                 $edit_url = get_edit_post_link($id);
                 $status_obj = get_post_status_object($object->post_status);
                 switch ($object->post_status) {
                     case 'publish':
                         $status = '';
                         break;
                     case 'inherit':
                         $status = '';
                         break;
                     case 'auto-draft':
                         continue;
                         break;
                     default:
                         $status = $status_obj->label;
                         break;
                 }
                 if ($status) {
                     $name .= "<span class='su-meta-table-post-status'> &mdash; {$status}</span>";
                 }
                 break;
             case 'term':
                 $id = intval($object->term_id);
                 $name = $object->name;
                 $view_url = get_term_link($id, $type);
                 $edit_url = suwp::get_edit_term_link($id, $type);
                 break;
             default:
                 return false;
                 break;
         }
         $view_url = su_esc_attr($view_url);
         $edit_url = su_esc_attr($edit_url);
         $actions = array(sprintf('<a href="%s">%s</a>', $view_url, __('View', 'seo-ultimate')));
         if ($edit_url) {
             $actions[] = sprintf('<a href="%s">%s</a>', $edit_url, __('Edit', 'seo-ultimate'));
         }
         $actions = implode(' | ', $actions);
         $cells = compact('actions', 'id', 'name');
         //Get meta field cells
         foreach ($fields as $field) {
             $inputid = "{$genus}_{$id}_{$field['name']}";
             switch ($genus) {
                 case 'post':
                     $value = $this->get_postmeta($field['name'], $id);
                     break;
                 case 'term':
                     $value = $this->get_setting($field['term_settings_key'], array());
                     $value = isset($value[$id]) ? $value[$id] : null;
                     break;
             }
             if ($is_update && $field['type'] == 'checkbox' && $value == '1' && !isset($_POST[$inputid])) {
                 switch ($genus) {
                     case 'post':
                         delete_post_meta($id, "_su_{$field['name']}");
                         $value = 0;
                         break;
                     case 'term':
                         $this->update_setting($field['term_settings_key'], false, null, $id);
                         break;
                 }
             }
             $cells[$field['name']] = $this->get_input_element($field['type'], $inputid, $value, isset($field['options']) ? $field['options'] : false);
         }
         //Output all cells
         $this->table_row($cells, $id, $type);
     }
     //End table
     $this->admin_wftable_end();
     echo $page_links_text;
     echo "</div>\n";
     return true;
 }
/**
 * Map meta capabilities to primitive capabilities.
 *
 * This does not actually compare whether the user ID has the actual capability,
 * just what the capability or capabilities are. Meta capability list value can
 * be 'delete_user', 'edit_user', 'remove_user', 'promote_user', 'delete_post',
 * 'delete_page', 'edit_post', 'edit_page', 'read_post', or 'read_page'.
 *
 * @since 2.0.0
 *
 * @param string $cap Capability name.
 * @param int $user_id User ID.
 * @return array Actual capabilities for meta capability.
 */
function map_meta_cap($cap, $user_id)
{
    $args = array_slice(func_get_args(), 2);
    $caps = array();
    switch ($cap) {
        case 'remove_user':
            $caps[] = 'remove_users';
            break;
        case 'promote_user':
            $caps[] = 'promote_users';
            break;
        case 'edit_user':
        case 'edit_users':
            // Allow user to edit itself
            if ('edit_user' == $cap && isset($args[0]) && $user_id == $args[0]) {
                break;
            }
            // In multisite the user must have manage_network_users caps. If editing a super admin, the user must be a super admin.
            if (is_multisite() && (!is_super_admin($user_id) && 'edit_user' === $cap && is_super_admin($args[0]) || !user_can($user_id, 'manage_network_users'))) {
                $caps[] = 'do_not_allow';
            } else {
                $caps[] = 'edit_users';
                // edit_user maps to edit_users.
            }
            break;
        case 'delete_post':
        case 'delete_page':
            $post = get_post($args[0]);
            if ('revision' == $post->post_type) {
                $post = get_post($post->post_parent);
            }
            $post_type = get_post_type_object($post->post_type);
            if (!$post_type) {
                /* translators: 1: post type, 2: capability name */
                _doing_it_wrong(__FUNCTION__, sprintf(__('The post type %1$s is not registered, so it may not be reliable to check the capability "%2$s" against a post of that type.'), $post->post_type, $cap), '4.4.0');
                $caps[] = 'edit_others_posts';
                break;
            }
            if (!$post_type->map_meta_cap) {
                $caps[] = $post_type->cap->{$cap};
                // Prior to 3.1 we would re-call map_meta_cap here.
                if ('delete_post' == $cap) {
                    $cap = $post_type->cap->{$cap};
                }
                break;
            }
            // If the post author is set and the user is the author...
            if ($post->post_author && $user_id == $post->post_author) {
                // If the post is published...
                if ('publish' == $post->post_status) {
                    $caps[] = $post_type->cap->delete_published_posts;
                } elseif ('trash' == $post->post_status) {
                    if ('publish' == get_post_meta($post->ID, '_wp_trash_meta_status', true)) {
                        $caps[] = $post_type->cap->delete_published_posts;
                    }
                } else {
                    // If the post is draft...
                    $caps[] = $post_type->cap->delete_posts;
                }
            } else {
                // The user is trying to edit someone else's post.
                $caps[] = $post_type->cap->delete_others_posts;
                // The post is published, extra cap required.
                if ('publish' == $post->post_status) {
                    $caps[] = $post_type->cap->delete_published_posts;
                } elseif ('private' == $post->post_status) {
                    $caps[] = $post_type->cap->delete_private_posts;
                }
            }
            break;
            // edit_post breaks down to edit_posts, edit_published_posts, or
            // edit_others_posts
        // edit_post breaks down to edit_posts, edit_published_posts, or
        // edit_others_posts
        case 'edit_post':
        case 'edit_page':
            $post = get_post($args[0]);
            if (empty($post)) {
                $caps[] = 'do_not_allow';
                break;
            }
            if ('revision' == $post->post_type) {
                $post = get_post($post->post_parent);
            }
            $post_type = get_post_type_object($post->post_type);
            if (!$post_type) {
                /* translators: 1: post type, 2: capability name */
                _doing_it_wrong(__FUNCTION__, sprintf(__('The post type %1$s is not registered, so it may not be reliable to check the capability "%2$s" against a post of that type.'), $post->post_type, $cap), '4.4.0');
                $caps[] = 'edit_others_posts';
                break;
            }
            if (!$post_type->map_meta_cap) {
                $caps[] = $post_type->cap->{$cap};
                // Prior to 3.1 we would re-call map_meta_cap here.
                if ('edit_post' == $cap) {
                    $cap = $post_type->cap->{$cap};
                }
                break;
            }
            // If the post author is set and the user is the author...
            if ($post->post_author && $user_id == $post->post_author) {
                // If the post is published...
                if ('publish' == $post->post_status) {
                    $caps[] = $post_type->cap->edit_published_posts;
                } elseif ('trash' == $post->post_status) {
                    if ('publish' == get_post_meta($post->ID, '_wp_trash_meta_status', true)) {
                        $caps[] = $post_type->cap->edit_published_posts;
                    }
                } else {
                    // If the post is draft...
                    $caps[] = $post_type->cap->edit_posts;
                }
            } else {
                // The user is trying to edit someone else's post.
                $caps[] = $post_type->cap->edit_others_posts;
                // The post is published, extra cap required.
                if ('publish' == $post->post_status) {
                    $caps[] = $post_type->cap->edit_published_posts;
                } elseif ('private' == $post->post_status) {
                    $caps[] = $post_type->cap->edit_private_posts;
                }
            }
            break;
        case 'read_post':
        case 'read_page':
            $post = get_post($args[0]);
            if ('revision' == $post->post_type) {
                $post = get_post($post->post_parent);
            }
            $post_type = get_post_type_object($post->post_type);
            if (!$post_type) {
                /* translators: 1: post type, 2: capability name */
                _doing_it_wrong(__FUNCTION__, sprintf(__('The post type %1$s is not registered, so it may not be reliable to check the capability "%2$s" against a post of that type.'), $post->post_type, $cap), '4.4.0');
                $caps[] = 'edit_others_posts';
                break;
            }
            if (!$post_type->map_meta_cap) {
                $caps[] = $post_type->cap->{$cap};
                // Prior to 3.1 we would re-call map_meta_cap here.
                if ('read_post' == $cap) {
                    $cap = $post_type->cap->{$cap};
                }
                break;
            }
            $status_obj = get_post_status_object($post->post_status);
            if ($status_obj->public) {
                $caps[] = $post_type->cap->read;
                break;
            }
            if ($post->post_author && $user_id == $post->post_author) {
                $caps[] = $post_type->cap->read;
            } elseif ($status_obj->private) {
                $caps[] = $post_type->cap->read_private_posts;
            } else {
                $caps = map_meta_cap('edit_post', $user_id, $post->ID);
            }
            break;
        case 'publish_post':
            $post = get_post($args[0]);
            $post_type = get_post_type_object($post->post_type);
            if (!$post_type) {
                /* translators: 1: post type, 2: capability name */
                _doing_it_wrong(__FUNCTION__, sprintf(__('The post type %1$s is not registered, so it may not be reliable to check the capability "%2$s" against a post of that type.'), $post->post_type, $cap), '4.4.0');
                $caps[] = 'edit_others_posts';
                break;
            }
            $caps[] = $post_type->cap->publish_posts;
            break;
        case 'edit_post_meta':
        case 'delete_post_meta':
        case 'add_post_meta':
            $post = get_post($args[0]);
            $caps = map_meta_cap('edit_post', $user_id, $post->ID);
            $meta_key = isset($args[1]) ? $args[1] : false;
            if ($meta_key && has_filter("auth_post_meta_{$meta_key}")) {
                /**
                 * Filter whether the user is allowed to add post meta to a post.
                 *
                 * The dynamic portion of the hook name, `$meta_key`, refers to the
                 * meta key passed to {@see map_meta_cap()}.
                 *
                 * @since 3.3.0
                 *
                 * @param bool   $allowed  Whether the user can add the post meta. Default false.
                 * @param string $meta_key The meta key.
                 * @param int    $post_id  Post ID.
                 * @param int    $user_id  User ID.
                 * @param string $cap      Capability name.
                 * @param array  $caps     User capabilities.
                 */
                $allowed = apply_filters("auth_post_meta_{$meta_key}", false, $meta_key, $post->ID, $user_id, $cap, $caps);
                if (!$allowed) {
                    $caps[] = $cap;
                }
            } elseif ($meta_key && is_protected_meta($meta_key, 'post')) {
                $caps[] = $cap;
            }
            break;
        case 'edit_comment':
            $comment = get_comment($args[0]);
            if (empty($comment)) {
                break;
            }
            $post = get_post($comment->comment_post_ID);
            /*
             * If the post doesn't exist, we have an orphaned comment.
             * Fall back to the edit_posts capability, instead.
             */
            if ($post) {
                $caps = map_meta_cap('edit_post', $user_id, $post->ID);
            } else {
                $caps = map_meta_cap('edit_posts', $user_id);
            }
            break;
        case 'unfiltered_upload':
            if (defined('ALLOW_UNFILTERED_UPLOADS') && ALLOW_UNFILTERED_UPLOADS && (!is_multisite() || is_super_admin($user_id))) {
                $caps[] = $cap;
            } else {
                $caps[] = 'do_not_allow';
            }
            break;
        case 'unfiltered_html':
            // Disallow unfiltered_html for all users, even admins and super admins.
            if (defined('DISALLOW_UNFILTERED_HTML') && DISALLOW_UNFILTERED_HTML) {
                $caps[] = 'do_not_allow';
            } elseif (is_multisite() && !is_super_admin($user_id)) {
                $caps[] = 'do_not_allow';
            } else {
                $caps[] = $cap;
            }
            break;
        case 'edit_files':
        case 'edit_plugins':
        case 'edit_themes':
            // Disallow the file editors.
            if (defined('DISALLOW_FILE_EDIT') && DISALLOW_FILE_EDIT) {
                $caps[] = 'do_not_allow';
            } elseif (defined('DISALLOW_FILE_MODS') && DISALLOW_FILE_MODS) {
                $caps[] = 'do_not_allow';
            } elseif (is_multisite() && !is_super_admin($user_id)) {
                $caps[] = 'do_not_allow';
            } else {
                $caps[] = $cap;
            }
            break;
        case 'update_plugins':
        case 'delete_plugins':
        case 'install_plugins':
        case 'upload_plugins':
        case 'update_themes':
        case 'delete_themes':
        case 'install_themes':
        case 'upload_themes':
        case 'update_core':
            // Disallow anything that creates, deletes, or updates core, plugin, or theme files.
            // Files in uploads are excepted.
            if (defined('DISALLOW_FILE_MODS') && DISALLOW_FILE_MODS) {
                $caps[] = 'do_not_allow';
            } elseif (is_multisite() && !is_super_admin($user_id)) {
                $caps[] = 'do_not_allow';
            } elseif ('upload_themes' === $cap) {
                $caps[] = 'install_themes';
            } elseif ('upload_plugins' === $cap) {
                $caps[] = 'install_plugins';
            } else {
                $caps[] = $cap;
            }
            break;
        case 'activate_plugins':
            $caps[] = $cap;
            if (is_multisite()) {
                // update_, install_, and delete_ are handled above with is_super_admin().
                $menu_perms = get_site_option('menu_items', array());
                if (empty($menu_perms['plugins'])) {
                    $caps[] = 'manage_network_plugins';
                }
            }
            break;
        case 'delete_user':
        case 'delete_users':
            // If multisite only super admins can delete users.
            if (is_multisite() && !is_super_admin($user_id)) {
                $caps[] = 'do_not_allow';
            } else {
                $caps[] = 'delete_users';
            }
            // delete_user maps to delete_users.
            break;
        case 'create_users':
            if (!is_multisite()) {
                $caps[] = $cap;
            } elseif (is_super_admin($user_id) || get_site_option('add_new_users')) {
                $caps[] = $cap;
            } else {
                $caps[] = 'do_not_allow';
            }
            break;
        case 'manage_links':
            if (get_option('link_manager_enabled')) {
                $caps[] = $cap;
            } else {
                $caps[] = 'do_not_allow';
            }
            break;
        case 'customize':
            $caps[] = 'edit_theme_options';
            break;
        case 'delete_site':
            $caps[] = 'manage_options';
            break;
        default:
            // Handle meta capabilities for custom post types.
            $post_type_meta_caps = _post_type_meta_capabilities();
            if (isset($post_type_meta_caps[$cap])) {
                $args = array_merge(array($post_type_meta_caps[$cap], $user_id), $args);
                return call_user_func_array('map_meta_cap', $args);
            }
            // If no meta caps match, return the original cap.
            $caps[] = $cap;
    }
    /**
     * Filter a user's capabilities depending on specific context and/or privilege.
     *
     * @since 2.8.0
     *
     * @param array  $caps    Returns the user's actual capabilities.
     * @param string $cap     Capability name.
     * @param int    $user_id The user ID.
     * @param array  $args    Adds the context to the cap. Typically the object ID.
     */
    return apply_filters('map_meta_cap', $caps, $cap, $user_id, $args);
}
 function display_rows()
 {
     $records = $this->items;
     list($columns, $hidden) = $this->get_column_info();
     if (is_array($records) && $records !== array() && (is_array($columns) && $columns !== array())) {
         foreach ($records as $rec) {
             echo '<tr id="record_' . $rec->ID . '">';
             foreach ($columns as $column_name => $column_display_name) {
                 $class = sprintf('class="%1$s column-%1$s"', $column_name);
                 $style = '';
                 if (in_array($column_name, $hidden)) {
                     $style = ' style="display:none;"';
                 }
                 $attributes = $class . $style;
                 switch ($column_name) {
                     case 'col_page_title':
                         echo sprintf('<td %2$s><strong>%1$s</strong>', stripslashes($rec->post_title), $attributes);
                         $post_type_object = get_post_type_object($rec->post_type);
                         $can_edit_post = current_user_can($post_type_object->cap->edit_post, $rec->ID);
                         $actions = array();
                         if ($can_edit_post && 'trash' != $rec->post_status) {
                             $actions['edit'] = '<a href="' . esc_url(get_edit_post_link($rec->ID, true)) . '" title="' . esc_attr(__('Edit this item')) . '">' . __('Edit') . '</a>';
                         }
                         if ($post_type_object->public) {
                             if (in_array($rec->post_status, array('pending', 'draft', 'future'))) {
                                 if ($can_edit_post) {
                                     $actions['view'] = '<a href="' . esc_url(add_query_arg('preview', 'true', get_permalink($rec->ID))) . '" title="' . esc_attr(sprintf(__('Preview &#8220;%s&#8221;'), $rec->post_title)) . '">' . __('Preview') . '</a>';
                                 }
                             } elseif ('trash' != $rec->post_status) {
                                 $actions['view'] = '<a href="' . esc_url(get_permalink($rec->ID)) . '" title="' . esc_attr(sprintf(__('View &#8220;%s&#8221;'), $rec->post_title)) . '" rel="bookmark">' . __('View') . '</a>';
                             }
                         }
                         echo $this->row_actions($actions);
                         echo '</td>';
                         break;
                     case 'col_page_slug':
                         $permalink = get_permalink($rec->ID);
                         $display_slug = str_replace(get_bloginfo('url'), '', $permalink);
                         echo sprintf('<td %2$s><a href="%3$s" target="_blank">%1$s</a></td>', stripslashes($display_slug), $attributes, esc_url($permalink));
                         break;
                     case 'col_post_type':
                         $post_type = get_post_type_object($rec->post_type);
                         echo sprintf('<td %2$s>%1$s</td>', $post_type->labels->singular_name, $attributes);
                         break;
                     case 'col_post_status':
                         $post_status = get_post_status_object($rec->post_status);
                         echo sprintf('<td %2$s>%1$s</td>', $post_status->label, $attributes);
                         break;
                     case 'col_existing_yoast_seo_title':
                         echo sprintf('<td %2$s id="wpseo-existing-title-%3$s">%1$s</td>', $rec->seo_title ? $rec->seo_title : '', $attributes, $rec->ID);
                         break;
                     case 'col_new_yoast_seo_title':
                         $input = sprintf('<input type="text" id="%1$s" name="%1$s" class="wpseo-new-title" data-id="%2$s" />', 'wpseo-new-title-' . $rec->ID, $rec->ID);
                         echo sprintf('<td %2$s>%1$s</td>', $input, $attributes);
                         break;
                     case 'col_row_action':
                         $actions = sprintf('<a href="#" class="wpseo-save" data-id="%1$s">Save</a> | <a href="#" class="wpseo-save-all">Save All</a>', $rec->ID);
                         echo sprintf('<td %2$s>%1$s</td>', $actions, $attributes);
                         break;
                 }
             }
             echo '</tr>';
         }
     }
 }
 private function user_can_view_post($post)
 {
     if (!$post || is_wp_error($post)) {
         return false;
     }
     if ('inherit' === $post->post_status) {
         $parent_post = get_post($post->post_parent);
         $post_status_obj = get_post_status_object($parent_post->post_status);
     } else {
         $post_status_obj = get_post_status_object($post->post_status);
     }
     $authorized = $post_status_obj->public || is_user_logged_in() && ($post_status_obj->protected && current_user_can('edit_post', $post->ID) || $post_status_obj->private && current_user_can('read_post', $post->ID) || 'trash' === $post->post_status && current_user_can('edit_post', $post->ID) || 'auto-draft' === $post->post_status);
     if (!$authorized) {
         return new WP_Error('unauthorized', 'User cannot view post', 403);
     }
     if (-1 == get_option('blog_public') && !apply_filters('wpcom_json_api_user_can_view_post', current_user_can('read_post', $post->ID), $post)) {
         return new WP_Error('unauthorized', 'User cannot view post', array('status_code' => 403, 'error' => 'private_blog'));
     }
     if (strlen($post->post_password) && !current_user_can('edit_post', $post->ID)) {
         return new WP_Error('unauthorized', 'User cannot view password protected post', array('status_code' => 403, 'error' => 'password_protected'));
     }
     return true;
 }
Example #21
0
 /**
  * Ping AngelList when a post is published
  * AngelList may associate the article with a "press" mention in its company profiles
  * Sets a post meta key of 'angellist-notified' to enforce one ping per post
  *
  * @since 1.1
  * @param int $post_id post identifier
  * @param array $companies AngelList companies stored with the post
  */
 public static function ping($post_id, array $companies)
 {
     if (!is_int($post_id) || $post_id < 1 || empty($companies)) {
         return;
     }
     $post = get_post($post_id);
     // only notify for public post types
     $post_type = get_post_type($post);
     if (!$post_type) {
         return;
     }
     $post_type_object = get_post_type_object($post_type);
     if (!($post_type_object && isset($post_type_object->public) && $post_type_object->public)) {
         return;
     }
     unset($post_type);
     unset($post_type_object);
     // only notify for public posts
     $post_status = get_post_status($post_id);
     if (!$post_status) {
         return;
     }
     $post_status_object = get_post_status_object($post_status);
     if (!($post_status_object && isset($post_status_object->public) && $post_status_object->public)) {
         return;
     }
     unset($post_status);
     unset($post_status_object);
     // only notify AngelList once per post, even if list of companies has changed
     $notify_once_meta_key = 'angellist-notified';
     if (get_post_meta($post_id, $notify_once_meta_key, true)) {
         return;
     }
     // absolute URIs only. no internal Intranet URIs
     $post_url = esc_url_raw(get_permalink($post_id), array('http', 'https'));
     if (!$post_url) {
         return;
     }
     // allow a publisher to short-circuit pings
     // also ties into the blog_public, cutting off the ping request if robots blocked
     $ping_url = 'https://angel.co/embed/post_published/';
     if (!apply_filters('option_ping_sites', array($ping_url), $post_id)) {
         return;
     }
     $http_args = array('redirection' => 0, 'httpversion' => '1.1', 'blocking' => false);
     foreach ($companies as $company) {
         if (!(array_key_exists('id', $company) && array_key_exists('name', $company))) {
             return;
         }
         // fire and forget
         wp_remote_get($ping_url . '?' . http_build_query(array('type' => 'Startup', 'name' => $company['name'], 'id' => $company['id'], 'perma_link' => $post_url), '', '&'), $http_args);
     }
     add_post_meta($post_id, $notify_once_meta_key, '1', true);
 }
Example #22
0
/**
 * Handles the submission of a comment, usually posted to wp-comments-post.php via a comment form.
 *
 * This function expects unslashed data, as opposed to functions such as `wp_new_comment()` which
 * expect slashed data.
 *
 * @since 4.4.0
 *
 * @param array $comment_data {
 *     Comment data.
 *
 *     @type string|int $comment_post_ID             The ID of the post that relates to the comment.
 *     @type string     $author                      The name of the comment author.
 *     @type string     $email                       The comment author email address.
 *     @type string     $url                         The comment author URL.
 *     @type string     $comment                     The content of the comment.
 *     @type string|int $comment_parent              The ID of this comment's parent, if any. Default 0.
 *     @type string     $_wp_unfiltered_html_comment The nonce value for allowing unfiltered HTML.
 * }
 * @return WP_Comment|WP_Error A WP_Comment object on success, a WP_Error object on failure.
 */
function wp_handle_comment_submission($comment_data)
{
    $comment_post_ID = $comment_parent = 0;
    $comment_author = $comment_author_email = $comment_author_url = $comment_content = $_wp_unfiltered_html_comment = null;
    if (isset($comment_data['comment_post_ID'])) {
        $comment_post_ID = (int) $comment_data['comment_post_ID'];
    }
    if (isset($comment_data['author']) && is_string($comment_data['author'])) {
        $comment_author = trim(strip_tags($comment_data['author']));
    }
    if (isset($comment_data['email']) && is_string($comment_data['email'])) {
        $comment_author_email = trim($comment_data['email']);
    }
    if (isset($comment_data['url']) && is_string($comment_data['url'])) {
        $comment_author_url = trim($comment_data['url']);
    }
    if (isset($comment_data['comment']) && is_string($comment_data['comment'])) {
        $comment_content = trim($comment_data['comment']);
    }
    if (isset($comment_data['comment_parent'])) {
        $comment_parent = absint($comment_data['comment_parent']);
    }
    if (isset($comment_data['_wp_unfiltered_html_comment']) && is_string($comment_data['_wp_unfiltered_html_comment'])) {
        $_wp_unfiltered_html_comment = trim($comment_data['_wp_unfiltered_html_comment']);
    }
    $post = get_post($comment_post_ID);
    if (empty($post->comment_status)) {
        /**
         * Fires when a comment is attempted on a post that does not exist.
         *
         * @since 1.5.0
         *
         * @param int $comment_post_ID Post ID.
         */
        do_action('comment_id_not_found', $comment_post_ID);
        return new WP_Error('comment_id_not_found');
    }
    // get_post_status() will get the parent status for attachments.
    $status = get_post_status($post);
    $status_obj = get_post_status_object($status);
    if (!comments_open($comment_post_ID)) {
        /**
         * Fires when a comment is attempted on a post that has comments closed.
         *
         * @since 1.5.0
         *
         * @param int $comment_post_ID Post ID.
         */
        do_action('comment_closed', $comment_post_ID);
        return new WP_Error('comment_closed', __('Sorry, comments are closed for this item.'), 403);
    } elseif ('trash' == $status) {
        /**
         * Fires when a comment is attempted on a trashed post.
         *
         * @since 2.9.0
         *
         * @param int $comment_post_ID Post ID.
         */
        do_action('comment_on_trash', $comment_post_ID);
        return new WP_Error('comment_on_trash');
    } elseif (!$status_obj->public && !$status_obj->private) {
        /**
         * Fires when a comment is attempted on a post in draft mode.
         *
         * @since 1.5.1
         *
         * @param int $comment_post_ID Post ID.
         */
        do_action('comment_on_draft', $comment_post_ID);
        return new WP_Error('comment_on_draft');
    } elseif (post_password_required($comment_post_ID)) {
        /**
         * Fires when a comment is attempted on a password-protected post.
         *
         * @since 2.9.0
         *
         * @param int $comment_post_ID Post ID.
         */
        do_action('comment_on_password_protected', $comment_post_ID);
        return new WP_Error('comment_on_password_protected');
    } else {
        /**
         * Fires before a comment is posted.
         *
         * @since 2.8.0
         *
         * @param int $comment_post_ID Post ID.
         */
        do_action('pre_comment_on_post', $comment_post_ID);
    }
    // If the user is logged in
    $user = wp_get_current_user();
    if ($user->exists()) {
        if (empty($user->display_name)) {
            $user->display_name = $user->user_login;
        }
        $comment_author = $user->display_name;
        $comment_author_email = $user->user_email;
        $comment_author_url = $user->user_url;
        if (current_user_can('unfiltered_html')) {
            if (!isset($comment_data['_wp_unfiltered_html_comment']) || !wp_verify_nonce($comment_data['_wp_unfiltered_html_comment'], 'unfiltered-html-comment_' . $comment_post_ID)) {
                kses_remove_filters();
                // start with a clean slate
                kses_init_filters();
                // set up the filters
            }
        }
    } else {
        if (get_option('comment_registration') || 'private' == $status) {
            return new WP_Error('not_logged_in', __('Sorry, you must be logged in to post a comment.'), 403);
        }
    }
    $comment_type = '';
    if (get_option('require_name_email') && !$user->exists()) {
        if (6 > strlen($comment_author_email) || '' == $comment_author) {
            return new WP_Error('require_name_email', __('<strong>ERROR</strong>: please fill the required fields (name, email).'), 200);
        } elseif (!is_email($comment_author_email)) {
            return new WP_Error('require_valid_email', __('<strong>ERROR</strong>: please enter a valid email address.'), 200);
        }
    }
    if ('' == $comment_content) {
        return new WP_Error('require_valid_comment', __('<strong>ERROR</strong>: please type a comment.'), 200);
    }
    $commentdata = compact('comment_post_ID', 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_content', 'comment_type', 'comment_parent', 'user_ID');
    $comment_id = wp_new_comment(wp_slash($commentdata));
    if (!$comment_id) {
        return new WP_Error('comment_save_error', __('<strong>ERROR</strong>: The comment could not be saved. Please try again later.'), 500);
    }
    return get_comment($comment_id);
}
Example #23
0
$comment_post_ID = isset($_POST['comment_post_ID']) ? (int) $_POST['comment_post_ID'] : 0;
$post = get_post($comment_post_ID);
if (empty($post->comment_status)) {
    /**
     * Fires when a comment is attempted on a post that does not exist.
     *
     * @since 1.5.0
     *
     * @param int $comment_post_ID Post ID.
     */
    do_action('comment_id_not_found', $comment_post_ID);
    exit;
}
// get_post_status() will get the parent status for attachments.
$status = get_post_status($post);
$status_obj = get_post_status_object($status);
if (!comments_open($comment_post_ID)) {
    /**
     * Fires when a comment is attempted on a post that has comments closed.
     *
     * @since 1.5.0
     *
     * @param int $comment_post_ID Post ID.
     */
    do_action('comment_closed', $comment_post_ID);
    wp_die(__('Sorry, comments are closed for this item.'), 403);
} elseif ('trash' == $status) {
    /**
     * Fires when a comment is attempted on a trashed post.
     *
     * @since 2.9.0
Example #24
0
 /**
  * Retrieve the posts based on query variables.
  *
  * There are a few filters and actions that can be used to modify the post
  * database query.
  *
  * @since 1.5.0
  * @access public
  *
  * @return array List of posts.
  */
 public function get_posts()
 {
     $this->parse_query();
     /**
      * Fires after the query variable object is created, but before the actual query is run.
      *
      * Note: If using conditional tags, use the method versions within the passed instance
      * (e.g. $this->is_main_query() instead of is_main_query()). This is because the functions
      * like is_main_query() test against the global $wp_query instance, not the passed one.
      *
      * @since 2.0.0
      *
      * @param WP_Query &$this The WP_Query instance (passed by reference).
      */
     do_action_ref_array('pre_get_posts', array(&$this));
     // Shorthand.
     $q =& $this->query_vars;
     // Fill again in case pre_get_posts unset some vars.
     $q = $this->fill_query_vars($q);
     // Parse meta query
     $this->meta_query = new WP_Meta_Query();
     $this->meta_query->parse_query_vars($q);
     // Set a flag if a pre_get_posts hook changed the query vars.
     $hash = md5(serialize($this->query_vars));
     if ($hash != $this->query_vars_hash) {
         $this->query_vars_changed = true;
         $this->query_vars_hash = $hash;
     }
     unset($hash);
     // First let's clear some variables
     $distinct = '';
     $whichauthor = '';
     $whichmimetype = '';
     $where = '';
     $limits = '';
     $join = '';
     $search = '';
     $groupby = '';
     $post_status_join = false;
     $page = 1;
     if (isset($q['caller_get_posts'])) {
         _deprecated_argument('WP_Query', '3.1.0', __('"caller_get_posts" is deprecated. Use "ignore_sticky_posts" instead.'));
         if (!isset($q['ignore_sticky_posts'])) {
             $q['ignore_sticky_posts'] = $q['caller_get_posts'];
         }
     }
     if (!isset($q['ignore_sticky_posts'])) {
         $q['ignore_sticky_posts'] = false;
     }
     if (!isset($q['suppress_filters'])) {
         $q['suppress_filters'] = false;
     }
     if (!isset($q['cache_results'])) {
         if (wp_using_ext_object_cache()) {
             $q['cache_results'] = false;
         } else {
             $q['cache_results'] = true;
         }
     }
     if (!isset($q['update_post_term_cache'])) {
         $q['update_post_term_cache'] = true;
     }
     if (!isset($q['lazy_load_term_meta'])) {
         $q['lazy_load_term_meta'] = $q['update_post_term_cache'];
     }
     if (!isset($q['update_post_meta_cache'])) {
         $q['update_post_meta_cache'] = true;
     }
     if (!isset($q['post_type'])) {
         if ($this->is_search) {
             $q['post_type'] = 'any';
         } else {
             $q['post_type'] = '';
         }
     }
     $post_type = $q['post_type'];
     if (empty($q['posts_per_page'])) {
         $q['posts_per_page'] = get_option('posts_per_page');
     }
     if (isset($q['showposts']) && $q['showposts']) {
         $q['showposts'] = (int) $q['showposts'];
         $q['posts_per_page'] = $q['showposts'];
     }
     if (isset($q['posts_per_archive_page']) && $q['posts_per_archive_page'] != 0 && ($this->is_archive || $this->is_search)) {
         $q['posts_per_page'] = $q['posts_per_archive_page'];
     }
     if (!isset($q['nopaging'])) {
         if ($q['posts_per_page'] == -1) {
             $q['nopaging'] = true;
         } else {
             $q['nopaging'] = false;
         }
     }
     if ($this->is_feed) {
         // This overrides posts_per_page.
         if (!empty($q['posts_per_rss'])) {
             $q['posts_per_page'] = $q['posts_per_rss'];
         } else {
             $q['posts_per_page'] = get_option('posts_per_rss');
         }
         $q['nopaging'] = false;
     }
     $q['posts_per_page'] = (int) $q['posts_per_page'];
     if ($q['posts_per_page'] < -1) {
         $q['posts_per_page'] = abs($q['posts_per_page']);
     } elseif ($q['posts_per_page'] == 0) {
         $q['posts_per_page'] = 1;
     }
     if (!isset($q['comments_per_page']) || $q['comments_per_page'] == 0) {
         $q['comments_per_page'] = get_option('comments_per_page');
     }
     if ($this->is_home && (empty($this->query) || $q['preview'] == 'true') && 'page' == get_option('show_on_front') && get_option('page_on_front')) {
         $this->is_page = true;
         $this->is_home = false;
         $q['page_id'] = get_option('page_on_front');
     }
     if (isset($q['page'])) {
         $q['page'] = trim($q['page'], '/');
         $q['page'] = absint($q['page']);
     }
     // If true, forcibly turns off SQL_CALC_FOUND_ROWS even when limits are present.
     if (isset($q['no_found_rows'])) {
         $q['no_found_rows'] = (bool) $q['no_found_rows'];
     } else {
         $q['no_found_rows'] = false;
     }
     switch ($q['fields']) {
         case 'ids':
             $fields = "{$this->db->posts}.ID";
             break;
         case 'id=>parent':
             $fields = "{$this->db->posts}.ID, {$this->db->posts}.post_parent";
             break;
         default:
             $fields = "{$this->db->posts}.*";
     }
     if ('' !== $q['menu_order']) {
         $where .= " AND {$this->db->posts}.menu_order = " . $q['menu_order'];
     }
     // The "m" parameter is meant for months but accepts datetimes of varying specificity
     if ($q['m']) {
         $where .= " AND YEAR({$this->db->posts}.post_date)=" . substr($q['m'], 0, 4);
         if (strlen($q['m']) > 5) {
             $where .= " AND MONTH({$this->db->posts}.post_date)=" . substr($q['m'], 4, 2);
         }
         if (strlen($q['m']) > 7) {
             $where .= " AND DAYOFMONTH({$this->db->posts}.post_date)=" . substr($q['m'], 6, 2);
         }
         if (strlen($q['m']) > 9) {
             $where .= " AND HOUR({$this->db->posts}.post_date)=" . substr($q['m'], 8, 2);
         }
         if (strlen($q['m']) > 11) {
             $where .= " AND MINUTE({$this->db->posts}.post_date)=" . substr($q['m'], 10, 2);
         }
         if (strlen($q['m']) > 13) {
             $where .= " AND SECOND({$this->db->posts}.post_date)=" . substr($q['m'], 12, 2);
         }
     }
     // Handle the other individual date parameters
     $date_parameters = array();
     if ('' !== $q['hour']) {
         $date_parameters['hour'] = $q['hour'];
     }
     if ('' !== $q['minute']) {
         $date_parameters['minute'] = $q['minute'];
     }
     if ('' !== $q['second']) {
         $date_parameters['second'] = $q['second'];
     }
     if ($q['year']) {
         $date_parameters['year'] = $q['year'];
     }
     if ($q['monthnum']) {
         $date_parameters['monthnum'] = $q['monthnum'];
     }
     if ($q['w']) {
         $date_parameters['week'] = $q['w'];
     }
     if ($q['day']) {
         $date_parameters['day'] = $q['day'];
     }
     if ($date_parameters) {
         $date_query = new WP_Date_Query(array($date_parameters));
         $where .= $date_query->get_sql();
     }
     unset($date_parameters, $date_query);
     // Handle complex date queries
     if (!empty($q['date_query'])) {
         $this->date_query = new WP_Date_Query($q['date_query']);
         $where .= $this->date_query->get_sql();
     }
     // If we've got a post_type AND it's not "any" post_type.
     if (!empty($q['post_type']) && 'any' != $q['post_type']) {
         foreach ((array) $q['post_type'] as $_post_type) {
             $ptype_obj = get_post_type_object($_post_type);
             if (!$ptype_obj || !$ptype_obj->query_var || empty($q[$ptype_obj->query_var])) {
                 continue;
             }
             if (!$ptype_obj->hierarchical) {
                 // Non-hierarchical post types can directly use 'name'.
                 $q['name'] = $q[$ptype_obj->query_var];
             } else {
                 // Hierarchical post types will operate through 'pagename'.
                 $q['pagename'] = $q[$ptype_obj->query_var];
                 $q['name'] = '';
             }
             // Only one request for a slug is possible, this is why name & pagename are overwritten above.
             break;
         }
         //end foreach
         unset($ptype_obj);
     }
     if ('' !== $q['title']) {
         $where .= $this->db->prepare(" AND {$this->db->posts}.post_title = %s", stripslashes($q['title']));
     }
     // Parameters related to 'post_name'.
     if ('' != $q['name']) {
         $q['name'] = sanitize_title_for_query($q['name']);
         $where .= " AND {$this->db->posts}.post_name = '" . $q['name'] . "'";
     } elseif ('' != $q['pagename']) {
         if (isset($this->queried_object_id)) {
             $reqpage = $this->queried_object_id;
         } else {
             if ('page' != $q['post_type']) {
                 foreach ((array) $q['post_type'] as $_post_type) {
                     $ptype_obj = get_post_type_object($_post_type);
                     if (!$ptype_obj || !$ptype_obj->hierarchical) {
                         continue;
                     }
                     $reqpage = get_page_by_path($q['pagename'], OBJECT, $_post_type);
                     if ($reqpage) {
                         break;
                     }
                 }
                 unset($ptype_obj);
             } else {
                 $reqpage = get_page_by_path($q['pagename']);
             }
             if (!empty($reqpage)) {
                 $reqpage = $reqpage->ID;
             } else {
                 $reqpage = 0;
             }
         }
         $page_for_posts = get_option('page_for_posts');
         if ('page' != get_option('show_on_front') || empty($page_for_posts) || $reqpage != $page_for_posts) {
             $q['pagename'] = sanitize_title_for_query(wp_basename($q['pagename']));
             $q['name'] = $q['pagename'];
             $where .= " AND ({$this->db->posts}.ID = '{$reqpage}')";
             $reqpage_obj = get_post($reqpage);
             if (is_object($reqpage_obj) && 'attachment' == $reqpage_obj->post_type) {
                 $this->is_attachment = true;
                 $post_type = $q['post_type'] = 'attachment';
                 $this->is_page = true;
                 $q['attachment_id'] = $reqpage;
             }
         }
     } elseif ('' != $q['attachment']) {
         $q['attachment'] = sanitize_title_for_query(wp_basename($q['attachment']));
         $q['name'] = $q['attachment'];
         $where .= " AND {$this->db->posts}.post_name = '" . $q['attachment'] . "'";
     } elseif (is_array($q['post_name__in']) && !empty($q['post_name__in'])) {
         $q['post_name__in'] = array_map('sanitize_title_for_query', $q['post_name__in']);
         $post_name__in = "'" . implode("','", $q['post_name__in']) . "'";
         $where .= " AND {$this->db->posts}.post_name IN ({$post_name__in})";
     }
     // If an attachment is requested by number, let it supersede any post number.
     if ($q['attachment_id']) {
         $q['p'] = absint($q['attachment_id']);
     }
     // If a post number is specified, load that post
     if ($q['p']) {
         $where .= " AND {$this->db->posts}.ID = " . $q['p'];
     } elseif ($q['post__in']) {
         $post__in = implode(',', array_map('absint', $q['post__in']));
         $where .= " AND {$this->db->posts}.ID IN ({$post__in})";
     } elseif ($q['post__not_in']) {
         $post__not_in = implode(',', array_map('absint', $q['post__not_in']));
         $where .= " AND {$this->db->posts}.ID NOT IN ({$post__not_in})";
     }
     if (is_numeric($q['post_parent'])) {
         $where .= $this->db->prepare(" AND {$this->db->posts}.post_parent = %d ", $q['post_parent']);
     } elseif ($q['post_parent__in']) {
         $post_parent__in = implode(',', array_map('absint', $q['post_parent__in']));
         $where .= " AND {$this->db->posts}.post_parent IN ({$post_parent__in})";
     } elseif ($q['post_parent__not_in']) {
         $post_parent__not_in = implode(',', array_map('absint', $q['post_parent__not_in']));
         $where .= " AND {$this->db->posts}.post_parent NOT IN ({$post_parent__not_in})";
     }
     if ($q['page_id']) {
         if ('page' != get_option('show_on_front') || $q['page_id'] != get_option('page_for_posts')) {
             $q['p'] = $q['page_id'];
             $where = " AND {$this->db->posts}.ID = " . $q['page_id'];
         }
     }
     // If a search pattern is specified, load the posts that match.
     if (strlen($q['s'])) {
         $search = $this->parse_search($q);
     }
     if (!$q['suppress_filters']) {
         /**
          * Filters the search SQL that is used in the WHERE clause of WP_Query.
          *
          * @since 3.0.0
          *
          * @param string   $search Search SQL for WHERE clause.
          * @param WP_Query $this   The current WP_Query object.
          */
         $search = apply_filters_ref_array('posts_search', array($search, &$this));
     }
     // Taxonomies
     if (!$this->is_singular) {
         $this->parse_tax_query($q);
         $clauses = $this->tax_query->get_sql($this->db->posts, 'ID');
         $join .= $clauses['join'];
         $where .= $clauses['where'];
     }
     if ($this->is_tax) {
         if (empty($post_type)) {
             // Do a fully inclusive search for currently registered post types of queried taxonomies
             $post_type = array();
             $taxonomies = array_keys($this->tax_query->queried_terms);
             foreach (get_post_types(array('exclude_from_search' => false)) as $pt) {
                 $object_taxonomies = $pt === 'attachment' ? get_taxonomies_for_attachments() : get_object_taxonomies($pt);
                 if (array_intersect($taxonomies, $object_taxonomies)) {
                     $post_type[] = $pt;
                 }
             }
             if (!$post_type) {
                 $post_type = 'any';
             } elseif (count($post_type) == 1) {
                 $post_type = $post_type[0];
             }
             $post_status_join = true;
         } elseif (in_array('attachment', (array) $post_type)) {
             $post_status_join = true;
         }
     }
     /*
      * Ensure that 'taxonomy', 'term', 'term_id', 'cat', and
      * 'category_name' vars are set for backward compatibility.
      */
     if (!empty($this->tax_query->queried_terms)) {
         /*
          * Set 'taxonomy', 'term', and 'term_id' to the
          * first taxonomy other than 'post_tag' or 'category'.
          */
         if (!isset($q['taxonomy'])) {
             foreach ($this->tax_query->queried_terms as $queried_taxonomy => $queried_items) {
                 if (empty($queried_items['terms'][0])) {
                     continue;
                 }
                 if (!in_array($queried_taxonomy, array('category', 'post_tag'))) {
                     $q['taxonomy'] = $queried_taxonomy;
                     if ('slug' === $queried_items['field']) {
                         $q['term'] = $queried_items['terms'][0];
                     } else {
                         $q['term_id'] = $queried_items['terms'][0];
                     }
                     // Take the first one we find.
                     break;
                 }
             }
         }
         // 'cat', 'category_name', 'tag_id'
         foreach ($this->tax_query->queried_terms as $queried_taxonomy => $queried_items) {
             if (empty($queried_items['terms'][0])) {
                 continue;
             }
             if ('category' === $queried_taxonomy) {
                 $the_cat = get_term_by($queried_items['field'], $queried_items['terms'][0], 'category');
                 if ($the_cat) {
                     $this->set('cat', $the_cat->term_id);
                     $this->set('category_name', $the_cat->slug);
                 }
                 unset($the_cat);
             }
             if ('post_tag' === $queried_taxonomy) {
                 $the_tag = get_term_by($queried_items['field'], $queried_items['terms'][0], 'post_tag');
                 if ($the_tag) {
                     $this->set('tag_id', $the_tag->term_id);
                 }
                 unset($the_tag);
             }
         }
     }
     if (!empty($this->tax_query->queries) || !empty($this->meta_query->queries)) {
         $groupby = "{$this->db->posts}.ID";
     }
     // Author/user stuff
     if (!empty($q['author']) && $q['author'] != '0') {
         $q['author'] = addslashes_gpc('' . urldecode($q['author']));
         $authors = array_unique(array_map('intval', preg_split('/[,\\s]+/', $q['author'])));
         foreach ($authors as $author) {
             $key = $author > 0 ? 'author__in' : 'author__not_in';
             $q[$key][] = abs($author);
         }
         $q['author'] = implode(',', $authors);
     }
     if (!empty($q['author__not_in'])) {
         $author__not_in = implode(',', array_map('absint', array_unique((array) $q['author__not_in'])));
         $where .= " AND {$this->db->posts}.post_author NOT IN ({$author__not_in}) ";
     } elseif (!empty($q['author__in'])) {
         $author__in = implode(',', array_map('absint', array_unique((array) $q['author__in'])));
         $where .= " AND {$this->db->posts}.post_author IN ({$author__in}) ";
     }
     // Author stuff for nice URLs
     if ('' != $q['author_name']) {
         if (strpos($q['author_name'], '/') !== false) {
             $q['author_name'] = explode('/', $q['author_name']);
             if ($q['author_name'][count($q['author_name']) - 1]) {
                 $q['author_name'] = $q['author_name'][count($q['author_name']) - 1];
                 // no trailing slash
             } else {
                 $q['author_name'] = $q['author_name'][count($q['author_name']) - 2];
                 // there was a trailing slash
             }
         }
         $q['author_name'] = sanitize_title_for_query($q['author_name']);
         $q['author'] = get_user_by('slug', $q['author_name']);
         if ($q['author']) {
             $q['author'] = $q['author']->ID;
         }
         $whichauthor .= " AND ({$this->db->posts}.post_author = " . absint($q['author']) . ')';
     }
     // MIME-Type stuff for attachment browsing
     if (isset($q['post_mime_type']) && '' != $q['post_mime_type']) {
         $whichmimetype = wp_post_mime_type_where($q['post_mime_type'], $this->db->posts);
     }
     $where .= $search . $whichauthor . $whichmimetype;
     if (!empty($this->meta_query->queries)) {
         $clauses = $this->meta_query->get_sql('post', $this->db->posts, 'ID', $this);
         $join .= $clauses['join'];
         $where .= $clauses['where'];
     }
     $rand = isset($q['orderby']) && 'rand' === $q['orderby'];
     if (!isset($q['order'])) {
         $q['order'] = $rand ? '' : 'DESC';
     } else {
         $q['order'] = $rand ? '' : $this->parse_order($q['order']);
     }
     // Order by.
     if (empty($q['orderby'])) {
         /*
          * Boolean false or empty array blanks out ORDER BY,
          * while leaving the value unset or otherwise empty sets the default.
          */
         if (isset($q['orderby']) && (is_array($q['orderby']) || false === $q['orderby'])) {
             $orderby = '';
         } else {
             $orderby = "{$this->db->posts}.post_date " . $q['order'];
         }
     } elseif ('none' == $q['orderby']) {
         $orderby = '';
     } elseif ($q['orderby'] == 'post__in' && !empty($post__in)) {
         $orderby = "FIELD( {$this->db->posts}.ID, {$post__in} )";
     } elseif ($q['orderby'] == 'post_parent__in' && !empty($post_parent__in)) {
         $orderby = "FIELD( {$this->db->posts}.post_parent, {$post_parent__in} )";
     } elseif ($q['orderby'] == 'post_name__in' && !empty($post_name__in)) {
         $orderby = "FIELD( {$this->db->posts}.post_name, {$post_name__in} )";
     } else {
         $orderby_array = array();
         if (is_array($q['orderby'])) {
             foreach ($q['orderby'] as $_orderby => $order) {
                 $orderby = addslashes_gpc(urldecode($_orderby));
                 $parsed = $this->parse_orderby($orderby);
                 if (!$parsed) {
                     continue;
                 }
                 $orderby_array[] = $parsed . ' ' . $this->parse_order($order);
             }
             $orderby = implode(', ', $orderby_array);
         } else {
             $q['orderby'] = urldecode($q['orderby']);
             $q['orderby'] = addslashes_gpc($q['orderby']);
             foreach (explode(' ', $q['orderby']) as $i => $orderby) {
                 $parsed = $this->parse_orderby($orderby);
                 // Only allow certain values for safety.
                 if (!$parsed) {
                     continue;
                 }
                 $orderby_array[] = $parsed;
             }
             $orderby = implode(' ' . $q['order'] . ', ', $orderby_array);
             if (empty($orderby)) {
                 $orderby = "{$this->db->posts}.post_date " . $q['order'];
             } elseif (!empty($q['order'])) {
                 $orderby .= " {$q['order']}";
             }
         }
     }
     // Order search results by relevance only when another "orderby" is not specified in the query.
     if (!empty($q['s'])) {
         $search_orderby = '';
         if (!empty($q['search_orderby_title']) && (empty($q['orderby']) && !$this->is_feed) || isset($q['orderby']) && 'relevance' === $q['orderby']) {
             $search_orderby = $this->parse_search_order($q);
         }
         if (!$q['suppress_filters']) {
             /**
              * Filters the ORDER BY used when ordering search results.
              *
              * @since 3.7.0
              *
              * @param string   $search_orderby The ORDER BY clause.
              * @param WP_Query $this           The current WP_Query instance.
              */
             $search_orderby = apply_filters('posts_search_orderby', $search_orderby, $this);
         }
         if ($search_orderby) {
             $orderby = $orderby ? $search_orderby . ', ' . $orderby : $search_orderby;
         }
     }
     if (is_array($post_type) && count($post_type) > 1) {
         $post_type_cap = 'multiple_post_type';
     } else {
         if (is_array($post_type)) {
             $post_type = reset($post_type);
         }
         $post_type_object = get_post_type_object($post_type);
         if (empty($post_type_object)) {
             $post_type_cap = $post_type;
         }
     }
     if (isset($q['post_password'])) {
         $where .= $this->db->prepare(" AND {$this->db->posts}.post_password = %s", $q['post_password']);
         if (empty($q['perm'])) {
             $q['perm'] = 'readable';
         }
     } elseif (isset($q['has_password'])) {
         $where .= sprintf(" AND {$this->db->posts}.post_password %s ''", $q['has_password'] ? '!=' : '=');
     }
     if (!empty($q['comment_status'])) {
         $where .= $this->db->prepare(" AND {$this->db->posts}.comment_status = %s ", $q['comment_status']);
     }
     if (!empty($q['ping_status'])) {
         $where .= $this->db->prepare(" AND {$this->db->posts}.ping_status = %s ", $q['ping_status']);
     }
     if ('any' == $post_type) {
         $in_search_post_types = get_post_types(array('exclude_from_search' => false));
         if (empty($in_search_post_types)) {
             $where .= ' AND 1=0 ';
         } else {
             $where .= " AND {$this->db->posts}.post_type IN ('" . join("', '", $in_search_post_types) . "')";
         }
     } elseif (!empty($post_type) && is_array($post_type)) {
         $where .= " AND {$this->db->posts}.post_type IN ('" . join("', '", $post_type) . "')";
     } elseif (!empty($post_type)) {
         $where .= " AND {$this->db->posts}.post_type = '{$post_type}'";
         $post_type_object = get_post_type_object($post_type);
     } elseif ($this->is_attachment) {
         $where .= " AND {$this->db->posts}.post_type = 'attachment'";
         $post_type_object = get_post_type_object('attachment');
     } elseif ($this->is_page) {
         $where .= " AND {$this->db->posts}.post_type = 'page'";
         $post_type_object = get_post_type_object('page');
     } else {
         $where .= " AND {$this->db->posts}.post_type = 'post'";
         $post_type_object = get_post_type_object('post');
     }
     $edit_cap = 'edit_post';
     $read_cap = 'read_post';
     if (!empty($post_type_object)) {
         $edit_others_cap = $post_type_object->cap->edit_others_posts;
         $read_private_cap = $post_type_object->cap->read_private_posts;
     } else {
         $edit_others_cap = 'edit_others_' . $post_type_cap . 's';
         $read_private_cap = 'read_private_' . $post_type_cap . 's';
     }
     $user_id = get_current_user_id();
     $q_status = array();
     if (!empty($q['post_status'])) {
         $statuswheres = array();
         $q_status = $q['post_status'];
         if (!is_array($q_status)) {
             $q_status = explode(',', $q_status);
         }
         $r_status = array();
         $p_status = array();
         $e_status = array();
         if (in_array('any', $q_status)) {
             foreach (get_post_stati(array('exclude_from_search' => true)) as $status) {
                 if (!in_array($status, $q_status)) {
                     $e_status[] = "{$this->db->posts}.post_status <> '{$status}'";
                 }
             }
         } else {
             foreach (get_post_stati() as $status) {
                 if (in_array($status, $q_status)) {
                     if ('private' == $status) {
                         $p_status[] = "{$this->db->posts}.post_status = '{$status}'";
                     } else {
                         $r_status[] = "{$this->db->posts}.post_status = '{$status}'";
                     }
                 }
             }
         }
         if (empty($q['perm']) || 'readable' != $q['perm']) {
             $r_status = array_merge($r_status, $p_status);
             unset($p_status);
         }
         if (!empty($e_status)) {
             $statuswheres[] = "(" . join(' AND ', $e_status) . ")";
         }
         if (!empty($r_status)) {
             if (!empty($q['perm']) && 'editable' == $q['perm'] && !current_user_can($edit_others_cap)) {
                 $statuswheres[] = "({$this->db->posts}.post_author = {$user_id} " . "AND (" . join(' OR ', $r_status) . "))";
             } else {
                 $statuswheres[] = "(" . join(' OR ', $r_status) . ")";
             }
         }
         if (!empty($p_status)) {
             if (!empty($q['perm']) && 'readable' == $q['perm'] && !current_user_can($read_private_cap)) {
                 $statuswheres[] = "({$this->db->posts}.post_author = {$user_id} " . "AND (" . join(' OR ', $p_status) . "))";
             } else {
                 $statuswheres[] = "(" . join(' OR ', $p_status) . ")";
             }
         }
         if ($post_status_join) {
             $join .= " LEFT JOIN {$this->db->posts} AS p2 ON ({$this->db->posts}.post_parent = p2.ID) ";
             foreach ($statuswheres as $index => $statuswhere) {
                 $statuswheres[$index] = "({$statuswhere} OR ({$this->db->posts}.post_status = 'inherit' AND " . str_replace($this->db->posts, 'p2', $statuswhere) . "))";
             }
         }
         $where_status = implode(' OR ', $statuswheres);
         if (!empty($where_status)) {
             $where .= " AND ({$where_status})";
         }
     } elseif (!$this->is_singular) {
         $where .= " AND ({$this->db->posts}.post_status = 'publish'";
         // Add public states.
         $public_states = get_post_stati(array('public' => true));
         foreach ((array) $public_states as $state) {
             if ('publish' == $state) {
                 // Publish is hard-coded above.
                 continue;
             }
             $where .= " OR {$this->db->posts}.post_status = '{$state}'";
         }
         if ($this->is_admin) {
             // Add protected states that should show in the admin all list.
             $admin_all_states = get_post_stati(array('protected' => true, 'show_in_admin_all_list' => true));
             foreach ((array) $admin_all_states as $state) {
                 $where .= " OR {$this->db->posts}.post_status = '{$state}'";
             }
         }
         if (is_user_logged_in()) {
             // Add private states that are limited to viewing by the author of a post or someone who has caps to read private states.
             $private_states = get_post_stati(array('private' => true));
             foreach ((array) $private_states as $state) {
                 $where .= current_user_can($read_private_cap) ? " OR {$this->db->posts}.post_status = '{$state}'" : " OR {$this->db->posts}.post_author = {$user_id} AND {$this->db->posts}.post_status = '{$state}'";
             }
         }
         $where .= ')';
     }
     /*
      * Apply filters on where and join prior to paging so that any
      * manipulations to them are reflected in the paging by day queries.
      */
     if (!$q['suppress_filters']) {
         /**
          * Filters the WHERE clause of the query.
          *
          * @since 1.5.0
          *
          * @param string   $where The WHERE clause of the query.
          * @param WP_Query &$this The WP_Query instance (passed by reference).
          */
         $where = apply_filters_ref_array('posts_where', array($where, &$this));
         /**
          * Filters the JOIN clause of the query.
          *
          * @since 1.5.0
          *
          * @param string   $where The JOIN clause of the query.
          * @param WP_Query &$this The WP_Query instance (passed by reference).
          */
         $join = apply_filters_ref_array('posts_join', array($join, &$this));
     }
     // Paging
     if (empty($q['nopaging']) && !$this->is_singular) {
         $page = absint($q['paged']);
         if (!$page) {
             $page = 1;
         }
         // If 'offset' is provided, it takes precedence over 'paged'.
         if (isset($q['offset']) && is_numeric($q['offset'])) {
             $q['offset'] = absint($q['offset']);
             $pgstrt = $q['offset'] . ', ';
         } else {
             $pgstrt = absint(($page - 1) * $q['posts_per_page']) . ', ';
         }
         $limits = 'LIMIT ' . $pgstrt . $q['posts_per_page'];
     }
     // Comments feeds
     if ($this->is_comment_feed && !$this->is_singular) {
         if ($this->is_archive || $this->is_search) {
             $cjoin = "JOIN {$this->db->posts} ON ({$this->db->comments}.comment_post_ID = {$this->db->posts}.ID) {$join} ";
             $cwhere = "WHERE comment_approved = '1' {$where}";
             $cgroupby = "{$this->db->comments}.comment_id";
         } else {
             // Other non singular e.g. front
             $cjoin = "JOIN {$this->db->posts} ON ( {$this->db->comments}.comment_post_ID = {$this->db->posts}.ID )";
             $cwhere = "WHERE ( post_status = 'publish' OR ( post_status = 'inherit' && post_type = 'attachment' ) ) AND comment_approved = '1'";
             $cgroupby = '';
         }
         if (!$q['suppress_filters']) {
             /**
              * Filters the JOIN clause of the comments feed query before sending.
              *
              * @since 2.2.0
              *
              * @param string   $cjoin The JOIN clause of the query.
              * @param WP_Query &$this The WP_Query instance (passed by reference).
              */
             $cjoin = apply_filters_ref_array('comment_feed_join', array($cjoin, &$this));
             /**
              * Filters the WHERE clause of the comments feed query before sending.
              *
              * @since 2.2.0
              *
              * @param string   $cwhere The WHERE clause of the query.
              * @param WP_Query &$this  The WP_Query instance (passed by reference).
              */
             $cwhere = apply_filters_ref_array('comment_feed_where', array($cwhere, &$this));
             /**
              * Filters the GROUP BY clause of the comments feed query before sending.
              *
              * @since 2.2.0
              *
              * @param string   $cgroupby The GROUP BY clause of the query.
              * @param WP_Query &$this    The WP_Query instance (passed by reference).
              */
             $cgroupby = apply_filters_ref_array('comment_feed_groupby', array($cgroupby, &$this));
             /**
              * Filters the ORDER BY clause of the comments feed query before sending.
              *
              * @since 2.8.0
              *
              * @param string   $corderby The ORDER BY clause of the query.
              * @param WP_Query &$this    The WP_Query instance (passed by reference).
              */
             $corderby = apply_filters_ref_array('comment_feed_orderby', array('comment_date_gmt DESC', &$this));
             /**
              * Filters the LIMIT clause of the comments feed query before sending.
              *
              * @since 2.8.0
              *
              * @param string   $climits The JOIN clause of the query.
              * @param WP_Query &$this   The WP_Query instance (passed by reference).
              */
             $climits = apply_filters_ref_array('comment_feed_limits', array('LIMIT ' . get_option('posts_per_rss'), &$this));
         }
         $cgroupby = !empty($cgroupby) ? 'GROUP BY ' . $cgroupby : '';
         $corderby = !empty($corderby) ? 'ORDER BY ' . $corderby : '';
         $comments = (array) $this->db->get_results("SELECT {$distinct} {$this->db->comments}.* FROM {$this->db->comments} {$cjoin} {$cwhere} {$cgroupby} {$corderby} {$climits}");
         // Convert to WP_Comment
         $this->comments = array_map('get_comment', $comments);
         $this->comment_count = count($this->comments);
         $post_ids = array();
         foreach ($this->comments as $comment) {
             $post_ids[] = (int) $comment->comment_post_ID;
         }
         $post_ids = join(',', $post_ids);
         $join = '';
         if ($post_ids) {
             $where = "AND {$this->db->posts}.ID IN ({$post_ids}) ";
         } else {
             $where = "AND 0";
         }
     }
     $pieces = array('where', 'groupby', 'join', 'orderby', 'distinct', 'fields', 'limits');
     /*
      * Apply post-paging filters on where and join. Only plugins that
      * manipulate paging queries should use these hooks.
      */
     if (!$q['suppress_filters']) {
         /**
          * Filters the WHERE clause of the query.
          *
          * Specifically for manipulating paging queries.
          *
          * @since 1.5.0
          *
          * @param string   $where The WHERE clause of the query.
          * @param WP_Query &$this The WP_Query instance (passed by reference).
          */
         $where = apply_filters_ref_array('posts_where_paged', array($where, &$this));
         /**
          * Filters the GROUP BY clause of the query.
          *
          * @since 2.0.0
          *
          * @param string   $groupby The GROUP BY clause of the query.
          * @param WP_Query &$this   The WP_Query instance (passed by reference).
          */
         $groupby = apply_filters_ref_array('posts_groupby', array($groupby, &$this));
         /**
          * Filters the JOIN clause of the query.
          *
          * Specifically for manipulating paging queries.
          *
          * @since 1.5.0
          *
          * @param string   $join  The JOIN clause of the query.
          * @param WP_Query &$this The WP_Query instance (passed by reference).
          */
         $join = apply_filters_ref_array('posts_join_paged', array($join, &$this));
         /**
          * Filters the ORDER BY clause of the query.
          *
          * @since 1.5.1
          *
          * @param string   $orderby The ORDER BY clause of the query.
          * @param WP_Query &$this   The WP_Query instance (passed by reference).
          */
         $orderby = apply_filters_ref_array('posts_orderby', array($orderby, &$this));
         /**
          * Filters the DISTINCT clause of the query.
          *
          * @since 2.1.0
          *
          * @param string   $distinct The DISTINCT clause of the query.
          * @param WP_Query &$this    The WP_Query instance (passed by reference).
          */
         $distinct = apply_filters_ref_array('posts_distinct', array($distinct, &$this));
         /**
          * Filters the LIMIT clause of the query.
          *
          * @since 2.1.0
          *
          * @param string   $limits The LIMIT clause of the query.
          * @param WP_Query &$this  The WP_Query instance (passed by reference).
          */
         $limits = apply_filters_ref_array('post_limits', array($limits, &$this));
         /**
          * Filters the SELECT clause of the query.
          *
          * @since 2.1.0
          *
          * @param string   $fields The SELECT clause of the query.
          * @param WP_Query &$this  The WP_Query instance (passed by reference).
          */
         $fields = apply_filters_ref_array('posts_fields', array($fields, &$this));
         /**
          * Filters all query clauses at once, for convenience.
          *
          * Covers the WHERE, GROUP BY, JOIN, ORDER BY, DISTINCT,
          * fields (SELECT), and LIMITS clauses.
          *
          * @since 3.1.0
          *
          * @param array    $clauses The list of clauses for the query.
          * @param WP_Query &$this   The WP_Query instance (passed by reference).
          */
         $clauses = (array) apply_filters_ref_array('posts_clauses', array(compact($pieces), &$this));
         $where = isset($clauses['where']) ? $clauses['where'] : '';
         $groupby = isset($clauses['groupby']) ? $clauses['groupby'] : '';
         $join = isset($clauses['join']) ? $clauses['join'] : '';
         $orderby = isset($clauses['orderby']) ? $clauses['orderby'] : '';
         $distinct = isset($clauses['distinct']) ? $clauses['distinct'] : '';
         $fields = isset($clauses['fields']) ? $clauses['fields'] : '';
         $limits = isset($clauses['limits']) ? $clauses['limits'] : '';
     }
     /**
      * Fires to announce the query's current selection parameters.
      *
      * For use by caching plugins.
      *
      * @since 2.3.0
      *
      * @param string $selection The assembled selection query.
      */
     do_action('posts_selection', $where . $groupby . $orderby . $limits . $join);
     /*
      * Filters again for the benefit of caching plugins.
      * Regular plugins should use the hooks above.
      */
     if (!$q['suppress_filters']) {
         /**
          * Filters the WHERE clause of the query.
          *
          * For use by caching plugins.
          *
          * @since 2.5.0
          *
          * @param string   $where The WHERE clause of the query.
          * @param WP_Query &$this The WP_Query instance (passed by reference).
          */
         $where = apply_filters_ref_array('posts_where_request', array($where, &$this));
         /**
          * Filters the GROUP BY clause of the query.
          *
          * For use by caching plugins.
          *
          * @since 2.5.0
          *
          * @param string   $groupby The GROUP BY clause of the query.
          * @param WP_Query &$this   The WP_Query instance (passed by reference).
          */
         $groupby = apply_filters_ref_array('posts_groupby_request', array($groupby, &$this));
         /**
          * Filters the JOIN clause of the query.
          *
          * For use by caching plugins.
          *
          * @since 2.5.0
          *
          * @param string   $join  The JOIN clause of the query.
          * @param WP_Query &$this The WP_Query instance (passed by reference).
          */
         $join = apply_filters_ref_array('posts_join_request', array($join, &$this));
         /**
          * Filters the ORDER BY clause of the query.
          *
          * For use by caching plugins.
          *
          * @since 2.5.0
          *
          * @param string   $orderby The ORDER BY clause of the query.
          * @param WP_Query &$this   The WP_Query instance (passed by reference).
          */
         $orderby = apply_filters_ref_array('posts_orderby_request', array($orderby, &$this));
         /**
          * Filters the DISTINCT clause of the query.
          *
          * For use by caching plugins.
          *
          * @since 2.5.0
          *
          * @param string   $distinct The DISTINCT clause of the query.
          * @param WP_Query &$this    The WP_Query instance (passed by reference).
          */
         $distinct = apply_filters_ref_array('posts_distinct_request', array($distinct, &$this));
         /**
          * Filters the SELECT clause of the query.
          *
          * For use by caching plugins.
          *
          * @since 2.5.0
          *
          * @param string   $fields The SELECT clause of the query.
          * @param WP_Query &$this  The WP_Query instance (passed by reference).
          */
         $fields = apply_filters_ref_array('posts_fields_request', array($fields, &$this));
         /**
          * Filters the LIMIT clause of the query.
          *
          * For use by caching plugins.
          *
          * @since 2.5.0
          *
          * @param string   $limits The LIMIT clause of the query.
          * @param WP_Query &$this  The WP_Query instance (passed by reference).
          */
         $limits = apply_filters_ref_array('post_limits_request', array($limits, &$this));
         /**
          * Filters all query clauses at once, for convenience.
          *
          * For use by caching plugins.
          *
          * Covers the WHERE, GROUP BY, JOIN, ORDER BY, DISTINCT,
          * fields (SELECT), and LIMITS clauses.
          *
          * @since 3.1.0
          *
          * @param array    $pieces The pieces of the query.
          * @param WP_Query &$this  The WP_Query instance (passed by reference).
          */
         $clauses = (array) apply_filters_ref_array('posts_clauses_request', array(compact($pieces), &$this));
         $where = isset($clauses['where']) ? $clauses['where'] : '';
         $groupby = isset($clauses['groupby']) ? $clauses['groupby'] : '';
         $join = isset($clauses['join']) ? $clauses['join'] : '';
         $orderby = isset($clauses['orderby']) ? $clauses['orderby'] : '';
         $distinct = isset($clauses['distinct']) ? $clauses['distinct'] : '';
         $fields = isset($clauses['fields']) ? $clauses['fields'] : '';
         $limits = isset($clauses['limits']) ? $clauses['limits'] : '';
     }
     if (!empty($groupby)) {
         $groupby = 'GROUP BY ' . $groupby;
     }
     if (!empty($orderby)) {
         $orderby = 'ORDER BY ' . $orderby;
     }
     $found_rows = '';
     if (!$q['no_found_rows'] && !empty($limits)) {
         $found_rows = 'SQL_CALC_FOUND_ROWS';
     }
     $this->request = $old_request = "SELECT {$found_rows} {$distinct} {$fields} FROM {$this->db->posts} {$join} WHERE 1=1 {$where} {$groupby} {$orderby} {$limits}";
     if (!$q['suppress_filters']) {
         /**
          * Filters the completed SQL query before sending.
          *
          * @since 2.0.0
          *
          * @param string   $request The complete SQL query.
          * @param WP_Query &$this   The WP_Query instance (passed by reference).
          */
         $this->request = apply_filters_ref_array('posts_request', array($this->request, &$this));
     }
     /**
      * Filters the posts array before the query takes place.
      *
      * Return a non-null value to bypass WordPress's default post queries.
      *
      * Filtering functions that require pagination information are encouraged to set
      * the `found_posts` and `max_num_pages` properties of the WP_Query object,
      * passed to the filter by reference. If WP_Query does not perform a database
      * query, it will not have enough information to generate these values itself.
      *
      * @since 4.6.0
      *
      * @param array|null $posts Return an array of post data to short-circuit WP's query,
      *                          or null to allow WP to run its normal queries.
      * @param WP_Query   $this  The WP_Query instance, passed by reference.
      */
     $this->posts = apply_filters_ref_array('posts_pre_query', array(null, &$this));
     if ('ids' == $q['fields']) {
         if (null === $this->posts) {
             $this->posts = $this->db->get_col($this->request);
         }
         $this->posts = array_map('intval', $this->posts);
         $this->post_count = count($this->posts);
         $this->set_found_posts($q, $limits);
         return $this->posts;
     }
     if ('id=>parent' == $q['fields']) {
         if (null === $this->posts) {
             $this->posts = $this->db->get_results($this->request);
         }
         $this->post_count = count($this->posts);
         $this->set_found_posts($q, $limits);
         $r = array();
         foreach ($this->posts as $key => $post) {
             $this->posts[$key]->ID = (int) $post->ID;
             $this->posts[$key]->post_parent = (int) $post->post_parent;
             $r[(int) $post->ID] = (int) $post->post_parent;
         }
         return $r;
     }
     if (null === $this->posts) {
         $split_the_query = $old_request == $this->request && "{$this->db->posts}.*" == $fields && !empty($limits) && $q['posts_per_page'] < 500;
         /**
          * Filters whether to split the query.
          *
          * Splitting the query will cause it to fetch just the IDs of the found posts
          * (and then individually fetch each post by ID), rather than fetching every
          * complete row at once. One massive result vs. many small results.
          *
          * @since 3.4.0
          *
          * @param bool     $split_the_query Whether or not to split the query.
          * @param WP_Query $this            The WP_Query instance.
          */
         $split_the_query = apply_filters('split_the_query', $split_the_query, $this);
         if ($split_the_query) {
             // First get the IDs and then fill in the objects
             $this->request = "SELECT {$found_rows} {$distinct} {$this->db->posts}.ID FROM {$this->db->posts} {$join} WHERE 1=1 {$where} {$groupby} {$orderby} {$limits}";
             /**
              * Filters the Post IDs SQL request before sending.
              *
              * @since 3.4.0
              *
              * @param string   $request The post ID request.
              * @param WP_Query $this    The WP_Query instance.
              */
             $this->request = apply_filters('posts_request_ids', $this->request, $this);
             $ids = $this->db->get_col($this->request);
             if ($ids) {
                 $this->posts = $ids;
                 $this->set_found_posts($q, $limits);
                 _prime_post_caches($ids, $q['update_post_term_cache'], $q['update_post_meta_cache']);
             } else {
                 $this->posts = array();
             }
         } else {
             $this->posts = $this->db->get_results($this->request);
             $this->set_found_posts($q, $limits);
         }
     }
     // Convert to WP_Post objects.
     if ($this->posts) {
         $this->posts = array_map('get_post', $this->posts);
     }
     if (!$q['suppress_filters']) {
         /**
          * Filters the raw post results array, prior to status checks.
          *
          * @since 2.3.0
          *
          * @param array    $posts The post results array.
          * @param WP_Query &$this The WP_Query instance (passed by reference).
          */
         $this->posts = apply_filters_ref_array('posts_results', array($this->posts, &$this));
     }
     if (!empty($this->posts) && $this->is_comment_feed && $this->is_singular) {
         /** This filter is documented in wp-includes/query.php */
         $cjoin = apply_filters_ref_array('comment_feed_join', array('', &$this));
         /** This filter is documented in wp-includes/query.php */
         $cwhere = apply_filters_ref_array('comment_feed_where', array("WHERE comment_post_ID = '{$this->posts[0]->ID}' AND comment_approved = '1'", &$this));
         /** This filter is documented in wp-includes/query.php */
         $cgroupby = apply_filters_ref_array('comment_feed_groupby', array('', &$this));
         $cgroupby = !empty($cgroupby) ? 'GROUP BY ' . $cgroupby : '';
         /** This filter is documented in wp-includes/query.php */
         $corderby = apply_filters_ref_array('comment_feed_orderby', array('comment_date_gmt DESC', &$this));
         $corderby = !empty($corderby) ? 'ORDER BY ' . $corderby : '';
         /** This filter is documented in wp-includes/query.php */
         $climits = apply_filters_ref_array('comment_feed_limits', array('LIMIT ' . get_option('posts_per_rss'), &$this));
         $comments_request = "SELECT {$this->db->comments}.* FROM {$this->db->comments} {$cjoin} {$cwhere} {$cgroupby} {$corderby} {$climits}";
         $comments = $this->db->get_results($comments_request);
         // Convert to WP_Comment
         $this->comments = array_map('get_comment', $comments);
         $this->comment_count = count($this->comments);
     }
     // Check post status to determine if post should be displayed.
     if (!empty($this->posts) && ($this->is_single || $this->is_page)) {
         $status = get_post_status($this->posts[0]);
         if ('attachment' === $this->posts[0]->post_type && 0 === (int) $this->posts[0]->post_parent) {
             $this->is_page = false;
             $this->is_single = true;
             $this->is_attachment = true;
         }
         $post_status_obj = get_post_status_object($status);
         // If the post_status was specifically requested, let it pass through.
         if (!$post_status_obj->public && !in_array($status, $q_status)) {
             if (!is_user_logged_in()) {
                 // User must be logged in to view unpublished posts.
                 $this->posts = array();
             } else {
                 if ($post_status_obj->protected) {
                     // User must have edit permissions on the draft to preview.
                     if (!current_user_can($edit_cap, $this->posts[0]->ID)) {
                         $this->posts = array();
                     } else {
                         $this->is_preview = true;
                         if ('future' != $status) {
                             $this->posts[0]->post_date = current_time('mysql');
                         }
                     }
                 } elseif ($post_status_obj->private) {
                     if (!current_user_can($read_cap, $this->posts[0]->ID)) {
                         $this->posts = array();
                     }
                 } else {
                     $this->posts = array();
                 }
             }
         }
         if ($this->is_preview && $this->posts && current_user_can($edit_cap, $this->posts[0]->ID)) {
             /**
              * Filters the single post for preview mode.
              *
              * @since 2.7.0
              *
              * @param WP_Post  $post_preview  The Post object.
              * @param WP_Query &$this         The WP_Query instance (passed by reference).
              */
             $this->posts[0] = get_post(apply_filters_ref_array('the_preview', array($this->posts[0], &$this)));
         }
     }
     // Put sticky posts at the top of the posts array
     $sticky_posts = get_option('sticky_posts');
     if ($this->is_home && $page <= 1 && is_array($sticky_posts) && !empty($sticky_posts) && !$q['ignore_sticky_posts']) {
         $num_posts = count($this->posts);
         $sticky_offset = 0;
         // Loop over posts and relocate stickies to the front.
         for ($i = 0; $i < $num_posts; $i++) {
             if (in_array($this->posts[$i]->ID, $sticky_posts)) {
                 $sticky_post = $this->posts[$i];
                 // Remove sticky from current position
                 array_splice($this->posts, $i, 1);
                 // Move to front, after other stickies
                 array_splice($this->posts, $sticky_offset, 0, array($sticky_post));
                 // Increment the sticky offset. The next sticky will be placed at this offset.
                 $sticky_offset++;
                 // Remove post from sticky posts array
                 $offset = array_search($sticky_post->ID, $sticky_posts);
                 unset($sticky_posts[$offset]);
             }
         }
         // If any posts have been excluded specifically, Ignore those that are sticky.
         if (!empty($sticky_posts) && !empty($q['post__not_in'])) {
             $sticky_posts = array_diff($sticky_posts, $q['post__not_in']);
         }
         // Fetch sticky posts that weren't in the query results
         if (!empty($sticky_posts)) {
             $stickies = get_posts(array('post__in' => $sticky_posts, 'post_type' => $post_type, 'post_status' => 'publish', 'nopaging' => true));
             foreach ($stickies as $sticky_post) {
                 array_splice($this->posts, $sticky_offset, 0, array($sticky_post));
                 $sticky_offset++;
             }
         }
     }
     // If comments have been fetched as part of the query, make sure comment meta lazy-loading is set up.
     if (!empty($this->comments)) {
         wp_queue_comments_for_comment_meta_lazyload($this->comments);
     }
     if (!$q['suppress_filters']) {
         /**
          * Filters the array of retrieved posts after they've been fetched and
          * internally processed.
          *
          * @since 1.5.0
          *
          * @param array    $posts The array of retrieved posts.
          * @param WP_Query &$this The WP_Query instance (passed by reference).
          */
         $this->posts = apply_filters_ref_array('the_posts', array($this->posts, &$this));
     }
     // Ensure that any posts added/modified via one of the filters above are
     // of the type WP_Post and are filtered.
     if ($this->posts) {
         $this->post_count = count($this->posts);
         $this->posts = array_map('get_post', $this->posts);
         if ($q['cache_results']) {
             update_post_caches($this->posts, $post_type, $q['update_post_term_cache'], $q['update_post_meta_cache']);
         }
         $this->post = reset($this->posts);
     } else {
         $this->post_count = 0;
         $this->posts = array();
     }
     if ($q['lazy_load_term_meta']) {
         wp_queue_posts_for_term_meta_lazyload($this->posts);
     }
     return $this->posts;
 }
 public function process_bulk_action()
 {
     global $pagenow, $wpdb;
     if (!isset($_REQUEST['_wpnonce'])) {
         return;
     }
     $nonce = esc_attr($_REQUEST['_wpnonce']);
     if (!wp_verify_nonce($nonce, 'bulk-donations')) {
         wp_die(__('Invalid Nonce for deleting WC Donation Orders', WC_QD_TXT));
     }
     $doaction = $this->current_action();
     if ($doaction) {
         $pagenum = $this->get_pagenum();
         $sendback = remove_query_arg(array('trashed', 'untrashed', 'deleted', 'locked', 'ids'), wp_get_referer());
         if (!$sendback) {
             $sendback = admin_url($parent_file);
         }
         $sendback = add_query_arg('paged', $pagenum, $sendback);
         if (strpos($sendback, 'post.php') !== false) {
             $sendback = admin_url($post_new_file);
         }
         if (isset($_REQUEST['post'])) {
             $post_ids = array_map('intval', $_REQUEST['post']);
         }
         var_dump($this->screen);
         if ('delete_all' == $doaction) {
             // Prepare for deletion of all posts with a specified post status (i.e. Empty trash).
             $post_status = preg_replace('/[^a-z0-9_-]+/i', '', 'trash');
             // Validate the post status exists.
             if (get_post_status_object($post_status)) {
                 $post_ids = $wpdb->get_col($wpdb->prepare("SELECT ID FROM {$wpdb->posts} WHERE post_type=%s AND post_status = %s", 'shop_order', $post_status));
             }
             $doaction = 'delete';
         }
         $total_post = count($post_ids);
         $ids = implode(', ', $post_ids);
         $Notice_Txt = '';
         switch ($doaction) {
             case 'trash':
                 $trashed = $locked = 0;
                 foreach ((array) $post_ids as $post_id) {
                     if (!current_user_can('delete_post', $post_id)) {
                         wp_die(__('You are not allowed to move this item to the Trash.'));
                     }
                     if (wp_check_post_lock($post_id)) {
                         $locked++;
                         continue;
                     }
                     if (!wp_trash_post($post_id)) {
                         wp_die(__('Error in moving to Trash.'));
                     }
                     $trashed++;
                     $Notice_Txt = ' Trashed ';
                 }
                 $sendback = add_query_arg(array('trashed' => $trashed, 'ids' => join(',', $post_ids), 'locked' => $locked), $sendback);
                 wc_qd_notice(sprintf(_n('%s Donation Order Trashed  ( %s )', '%s Donation Orders Trashed  ( %s )', $total_post, $ids, WC_QD_TXT), $total_post, $ids));
                 break;
             case 'untrash':
                 $untrashed = 0;
                 foreach ((array) $post_ids as $post_id) {
                     if (!current_user_can('delete_post', $post_id)) {
                         wp_die(__('You are not allowed to restore this item from the Trash.'));
                     }
                     if (!wp_untrash_post($post_id)) {
                         wp_die(__('Error in restoring from Trash.'));
                     }
                     $untrashed++;
                 }
                 $sendback = add_query_arg('untrashed', $untrashed, $sendback);
                 wc_qd_notice(sprintf(_n('%s Donation Order restored from trash  ( %s )', '%s Donation Orders restored from trash ( %s )', $total_post, $ids, WC_QD_TXT), $total_post, $ids));
                 break;
             case 'delete':
                 $deleted = 0;
                 foreach ((array) $post_ids as $post_id) {
                     $post_del = get_post($post_id);
                     if (!current_user_can('delete_post', $post_id)) {
                         wp_die(__('You are not allowed to delete this item.'));
                     }
                     if ($post_del->post_type == 'attachment') {
                         if (!wp_delete_attachment($post_id)) {
                             wp_die(__('Error in deleting.'));
                         }
                     } else {
                         if (!wp_delete_post($post_id)) {
                             wp_die(__('Error in deleting.'));
                         }
                     }
                     $deleted++;
                 }
                 $sendback = add_query_arg('deleted', $deleted, $sendback);
                 wc_qd_notice(sprintf(_n('%s Donation Order permanently deleted  ( %s )', '%s Donation Orders permanently deleted ( %s )', $total_post, $ids, WC_QD_TXT), $total_post, $ids));
                 break;
             case 'edit':
                 if (isset($_REQUEST['bulk_edit'])) {
                     $done = bulk_edit_posts($_REQUEST);
                     if (is_array($done)) {
                         $done['updated'] = count($done['updated']);
                         $done['skipped'] = count($done['skipped']);
                         $done['locked'] = count($done['locked']);
                         $sendback = add_query_arg($done, $sendback);
                     }
                 }
                 break;
         }
     }
     $sendback = remove_query_arg(array('action', 'action2', 'tags_input', 'post_author', 'comment_status', 'ping_status', '_status', 'post', 'bulk_edit', 'post_view'), $sendback);
     wp_redirect($sendback);
     exit;
 }
 function flt_get_pages($results, $args = array())
 {
     $results = (array) $results;
     global $wpdb;
     // === BEGIN Role Scoper ADDITION: global var; various special case exemption checks ===
     //
     global $scoper, $current_rs_user;
     // need to skip cache retrieval if QTranslate is filtering get_pages with a priority of 1 or less
     $no_cache = !defined('SCOPER_QTRANSLATE_COMPAT') && awp_is_plugin_active('qtranslate');
     // buffer titles in case they were filtered previously
     $titles = scoper_get_property_array($results, 'ID', 'post_title');
     // depth is not really a get_pages arg, but remap exclude arg to exclude_tree if wp_list_terms called with depth=1
     if (!empty($args['exclude']) && empty($args['exclude_tree']) && !empty($args['depth']) && 1 == $args['depth']) {
         if (0 !== strpos($args['exclude'], ',')) {
             // work around wp_list_pages() bug of attaching leading comma if a plugin uses wp_list_pages_excludes filter
             $args['exclude_tree'] = $args['exclude'];
         }
     }
     //
     // === END Role Scoper ADDITION ===
     // =================================
     $defaults = array('child_of' => 0, 'sort_order' => 'ASC', 'sort_column' => 'post_title', 'hierarchical' => 1, 'exclude' => array(), 'include' => array(), 'meta_key' => '', 'meta_value' => '', 'authors' => '', 'parent' => -1, 'exclude_tree' => '', 'number' => '', 'offset' => 0, 'post_type' => 'page', 'post_status' => 'publish', 'depth' => 0, 'suppress_filters' => 0, 'remap_parents' => -1, 'enforce_actual_depth' => -1, 'remap_thru_excluded_parent' => -1);
     // Role Scoper arguments added above
     // === BEGIN Role Scoper ADDITION: support front-end optimization
     $post_type = isset($args['post_type']) ? $args['post_type'] : $defaults['post_type'];
     $use_post_types = (array) scoper_get_option('use_post_types');
     if (empty($use_post_types[$post_type])) {
         return $results;
     }
     if ($scoper->is_front()) {
         if ('page' == $post_type && defined('SCOPER_GET_PAGES_LEAN')) {
             // custom types are likely to have custom fields
             $defaults['fields'] = "{$wpdb->posts}.ID, {$wpdb->posts}.post_title, {$wpdb->posts}.post_parent, {$wpdb->posts}.post_date, {$wpdb->posts}.post_date_gmt, {$wpdb->posts}.post_status, {$wpdb->posts}.post_name, {$wpdb->posts}.post_modified, {$wpdb->posts}.post_modified_gmt, {$wpdb->posts}.guid, {$wpdb->posts}.menu_order, {$wpdb->posts}.comment_count";
         } else {
             $defaults['fields'] = "{$wpdb->posts}.*";
             if (!defined('SCOPER_FORCE_PAGES_CACHE')) {
                 $no_cache = true;
             }
             // serialization / unserialization of post_content for all pages is too memory-intensive for sites with a lot of pages
         }
     } else {
         // required for xmlrpc getpagelist method
         $defaults['fields'] = "{$wpdb->posts}.*";
         if (!defined('SCOPER_FORCE_PAGES_CACHE')) {
             $no_cache = true;
         }
     }
     // === END Role Scoper MODIFICATION ===
     $r = wp_parse_args($args, $defaults);
     extract($r, EXTR_SKIP);
     $number = (int) $number;
     $offset = (int) $offset;
     $child_of = (int) $child_of;
     // Role Scoper modification: null value will confuse children array check
     // Make sure the post type is hierarchical
     $hierarchical_post_types = get_post_types(array('public' => true, 'hierarchical' => true));
     if (!in_array($post_type, $hierarchical_post_types)) {
         return $results;
     }
     // Make sure we have a valid post status
     if (!in_array($post_status, get_post_stati())) {
         return $results;
     }
     // for the page parent dropdown, return no available selections for a published main page if the logged user isn't allowed to de-associate it from Main
     if (!empty($name) && 'parent_id' == $name) {
         global $post;
         if (!$post->post_parent && !$GLOBALS['scoper_admin_filters']->user_can_associate_main($post_type)) {
             $status_obj = get_post_status_object($post->post_status);
             if ($status_obj->public || $status_obj->private) {
                 return array();
             }
         }
         if (!empty($post) && $post_type == $post->post_type) {
             if ($post->post_parent) {
                 $append_page = get_post($post->post_parent);
             }
             $exclude_tree = $post->ID;
         }
     }
     //$scoper->last_get_pages_args = $r; // don't copy entire args array unless it proves necessary
     $scoper->last_get_pages_depth = $depth;
     $scoper->last_get_pages_suppress_filters = $suppress_filters;
     if ($suppress_filters) {
         return $results;
     }
     // === BEGIN Role Scoper MODIFICATION: wp-cache key and flag specific to access type and user/groups
     //
     if (!scoper_get_otype_option('use_object_roles', 'post', $post_type)) {
         return $results;
     }
     $key = md5(serialize(compact(array_keys($defaults))));
     $ckey = md5($key . CURRENT_ACCESS_NAME_RS);
     $cache_flag = 'rs_get_pages';
     $cache = $current_rs_user->cache_get($cache_flag);
     if (false !== $cache) {
         if (!is_array($cache)) {
             $cache = array();
         }
         if (!$no_cache && isset($cache[$ckey])) {
             // alternate filter name (WP core already applied get_pages filter)
             return apply_filters('get_pages_rs', $cache[$ckey], $r);
         }
     }
     //
     // === END Role Scoper MODIFICATION ===
     // ====================================
     $inclusions = '';
     if (!empty($include)) {
         $child_of = 0;
         //ignore child_of, parent, exclude, meta_key, and meta_value params if using include
         $parent = -1;
         $exclude = '';
         $meta_key = '';
         $meta_value = '';
         $hierarchical = false;
         $incpages = wp_parse_id_list($include);
         if (!empty($incpages)) {
             foreach ($incpages as $incpage) {
                 if (empty($inclusions)) {
                     $inclusions = ' AND ( ID = ' . intval($incpage) . ' ';
                 } else {
                     $inclusions .= ' OR ID = ' . intval($incpage) . ' ';
                 }
             }
         }
     }
     if (!empty($inclusions)) {
         $inclusions .= ')';
     }
     $exclusions = '';
     if (!empty($exclude)) {
         $expages = wp_parse_id_list($exclude);
         if (!empty($expages)) {
             foreach ($expages as $expage) {
                 if (empty($exclusions)) {
                     $exclusions = ' AND ( ID <> ' . intval($expage) . ' ';
                 } else {
                     $exclusions .= ' AND ID <> ' . intval($expage) . ' ';
                 }
             }
         }
     }
     if (!empty($exclusions)) {
         $exclusions .= ')';
     }
     $author_query = '';
     if (!empty($authors)) {
         $post_authors = wp_parse_id_list($authors);
         if (!empty($post_authors)) {
             foreach ($post_authors as $post_author) {
                 //Do we have an author id or an author login?
                 if (0 == intval($post_author)) {
                     $post_author = get_userdatabylogin($post_author);
                     if (empty($post_author)) {
                         continue;
                     }
                     if (empty($post_author->ID)) {
                         continue;
                     }
                     $post_author = $post_author->ID;
                 }
                 if ('' == $author_query) {
                     $author_query = ' post_author = ' . intval($post_author) . ' ';
                 } else {
                     $author_query .= ' OR post_author = ' . intval($post_author) . ' ';
                 }
             }
             if ('' != $author_query) {
                 $author_query = " AND ({$author_query})";
             }
         }
     }
     $join = '';
     $where = "{$exclusions} {$inclusions} ";
     if (!empty($meta_key) || !empty($meta_value)) {
         $join = " INNER JOIN {$wpdb->postmeta} ON {$wpdb->posts}.ID = {$wpdb->postmeta}.post_id";
         // Role Scoper modification: was LEFT JOIN in WP 3.0 core (TODO: would that botch uro join results?
         // meta_key and meta_value might be slashed
         $meta_key = stripslashes($meta_key);
         $meta_value = stripslashes($meta_value);
         if (!empty($meta_key)) {
             $where .= $wpdb->prepare(" AND {$wpdb->postmeta}.meta_key = %s", $meta_key);
         }
         if (!empty($meta_value)) {
             $where .= $wpdb->prepare(" AND {$wpdb->postmeta}.meta_value = %s", $meta_value);
         }
     }
     if ($parent >= 0) {
         $where .= $wpdb->prepare(' AND post_parent = %d ', $parent);
     }
     // === BEGIN Role Scoper MODIFICATION:
     // allow pages of multiple statuses to be displayed (requires default status=publish to be ignored)
     //
     $where_post_type = $wpdb->prepare("post_type = '%s'", $post_type);
     $where_status = '';
     $is_front = $scoper->is_front();
     $is_teaser_active = $scoper->is_front() && scoper_get_otype_option('do_teaser', 'post') && scoper_get_otype_option('use_teaser', 'post', $post_type);
     $private_teaser = $is_teaser_active && scoper_get_otype_option('use_teaser', 'post', $post_type) && !scoper_get_otype_option('teaser_hide_private', 'post', $post_type);
     if ($is_front && (!empty($current_rs_user->ID) || $private_teaser)) {
         $frontend_list_private = scoper_get_otype_option('private_items_listable', 'post', 'page');
     } else {
         $frontend_list_private = false;
     }
     // WP core does not include private pages in query.  Include private statuses in anticipation of user-specific filtering
     if ($post_status && ('publish' != $post_status || $is_front && !$frontend_list_private)) {
         $where_status = $wpdb->prepare("post_status = '%s'", $post_status);
     } else {
         // since we will be applying status clauses based on content-specific roles and restrictions, only a sanity check safeguard is needed when post_status is unspecified or defaulted to "publish"
         $safeguard_statuses = array();
         foreach (get_post_stati(array('internal' => false), 'object') as $status_name => $status_obj) {
             if (!$is_front || $status_obj->private || $status_obj->public) {
                 $safeguard_statuses[] = $status_name;
             }
         }
         $where_status = "post_status IN ('" . implode("','", $safeguard_statuses) . "')";
     }
     $query = "SELECT {$fields} FROM {$wpdb->posts} {$join} WHERE 1=1 AND {$where_post_type} AND ( {$where_status} {$where} {$author_query} ) ORDER BY {$sort_column} {$sort_order}";
     if (!empty($number)) {
         $query .= ' LIMIT ' . $offset . ',' . $number;
     }
     if ($is_teaser_active && !defined('SCOPER_TEASER_HIDE_PAGE_LISTING')) {
         // We are in the front end and the teaser is enabled for pages
         $query = apply_filters('objects_request_rs', $query, 'post', $post_type, array('force_teaser' => true));
         $pages = scoper_get_results($query);
         // execute unfiltered query
         // Pass results of unfiltered query through the teaser filter.
         // If listing private pages is disabled, they will be omitted completely, but restricted published pages
         // will still be teased.  This is a slight design compromise to satisfy potentially conflicting user goals without yet another option
         $pages = apply_filters('objects_results_rs', $pages, 'post', (array) $post_type, array('request' => $query, 'force_teaser' => true, 'object_type' => $post_type));
         // restore buffered titles in case they were filtered previously
         scoper_restore_property_array($pages, $titles, 'ID', 'post_title');
         $pages = apply_filters('objects_teaser_rs', $pages, 'post', $post_type, array('request' => $query, 'force_teaser' => true));
         if ($frontend_list_private) {
             if (!scoper_get_otype_option('teaser_hide_private', 'post', $post_type)) {
                 $tease_all = true;
             }
         }
     } else {
         $_args = array('skip_teaser' => true);
         if (in_array($GLOBALS['pagenow'], array('post.php', 'post-new.php'))) {
             if ($post_type_obj = get_post_type_object($post_type)) {
                 $plural_name = plural_name_from_cap_rs($post_type_obj);
                 $_args['alternate_reqd_caps'][0] = array("create_child_{$plural_name}");
             }
         }
         // Pass query through the request filter
         $query = apply_filters('objects_request_rs', $query, 'post', $post_type, $_args);
         // Execute the filtered query
         $pages = scoper_get_results($query);
         // restore buffered titles in case they were filtered previously
         scoper_restore_property_array($pages, $titles, 'ID', 'post_title');
     }
     if (empty($pages)) {
         // alternate hook name (WP core already applied get_pages filter)
         return apply_filters('get_pages_rs', array(), $r);
     }
     //
     // === END Role Scoper MODIFICATION ===
     // ====================================
     // Role Scoper note: WP core get_pages has already updated wp_cache and pagecache with unfiltered results.
     update_page_cache($pages);
     // === BEGIN Role Scoper MODIFICATION: Support a disjointed pages tree with some parents hidden ========
     if ($child_of || empty($tease_all)) {
         // if we're including all pages with teaser, no need to continue thru tree remapping
         $ancestors = ScoperAncestry::get_page_ancestors();
         // array of all ancestor IDs for keyed page_id, with direct parent first
         $orderby = $sort_column;
         if ($parent > 0 || !$hierarchical) {
             $remap_parents = false;
         } else {
             // if these settings were passed into this get_pages call, use them
             if (-1 === $remap_parents) {
                 $remap_parents = scoper_get_option('remap_page_parents');
             }
             if ($remap_parents) {
                 if (-1 === $enforce_actual_depth) {
                     $enforce_actual_depth = scoper_get_option('enforce_actual_page_depth');
                 }
                 if (-1 === $remap_thru_excluded_parent) {
                     $remap_thru_excluded_parent = scoper_get_option('remap_thru_excluded_page_parent');
                 }
             }
         }
         $remap_args = compact('child_of', 'parent', 'exclude', 'depth', 'orderby', 'remap_parents', 'enforce_actual_depth', 'remap_thru_excluded_parent');
         // one or more of these args may have been modified after extraction
         ScoperHardway::remap_tree($pages, $ancestors, 'ID', 'post_parent', $remap_args);
     }
     // === END Role Scoper MODIFICATION ===
     // ====================================
     if (!empty($exclude_tree)) {
         $exclude = array();
         $exclude = (int) $exclude_tree;
         $children = get_page_children($exclude, $pages);
         // RS note: okay to use unfiltered function here since it's only used for excluding
         $excludes = array();
         foreach ($children as $child) {
             $excludes[] = $child->ID;
         }
         $excludes[] = $exclude;
         $total = count($pages);
         for ($i = 0; $i < $total; $i++) {
             if (in_array($pages[$i]->ID, $excludes)) {
                 unset($pages[$i]);
             }
         }
     }
     if (!empty($append_page) && !empty($pages)) {
         $found = false;
         foreach (array_keys($pages) as $key) {
             if ($post->post_parent == $pages[$key]->ID) {
                 $found = true;
                 break;
             }
         }
         if (empty($found)) {
             $pages[] = $append_page;
         }
     }
     // re-index the array, just in case anyone cares
     $pages = array_values($pages);
     // === BEGIN Role Scoper MODIFICATION: cache key and flag specific to access type and user/groups
     //
     if (!$no_cache) {
         $cache[$ckey] = $pages;
         $current_rs_user->cache_set($cache, $cache_flag);
     }
     // alternate hook name (WP core already applied get_pages filter)
     $pages = apply_filters('get_pages_rs', $pages, $r);
     //
     // === END Role Scoper MODIFICATION ===
     // ====================================
     return $pages;
 }
Example #27
0
function ajax_comment()
{
    global $wpdb;
    //nocache_headers();
    $comment_post_ID = isset($_POST['comment_post_ID']) ? (int) $_POST['comment_post_ID'] : 0;
    $post = get_post($comment_post_ID);
    $post_author = $post->post_author;
    if (empty($post->comment_status)) {
        do_action('comment_id_not_found', $comment_post_ID);
        ajax_comment_err(__('Invalid comment status.', 'Lophita'));
    }
    $status = get_post_status($post);
    $status_obj = get_post_status_object($status);
    if (!comments_open($comment_post_ID)) {
        do_action('comment_closed', $comment_post_ID);
        ajax_comment_err(__('Sorry, comments are closed for this item.', 'Lophita'));
    } elseif ('trash' == $status) {
        do_action('comment_on_trash', $comment_post_ID);
        ajax_comment_err(__('Invalid comment status.', 'Lophita'));
    } elseif (!$status_obj->public && !$status_obj->private) {
        do_action('comment_on_draft', $comment_post_ID);
        ajax_comment_err(__('Invalid comment status.', 'Lophita'));
    } elseif (post_password_required($comment_post_ID)) {
        do_action('comment_on_password_protected', $comment_post_ID);
        ajax_comment_err(__('Password Protected', 'Lophita'));
    } else {
        do_action('pre_comment_on_post', $comment_post_ID);
    }
    $comment_author = isset($_POST['author']) ? trim(strip_tags($_POST['author'])) : null;
    $comment_author_email = isset($_POST['email']) ? trim($_POST['email']) : null;
    $comment_author_url = isset($_POST['url']) ? trim($_POST['url']) : null;
    $comment_content = isset($_POST['comment']) ? trim($_POST['comment']) : null;
    $edit_id = isset($_POST['edit_id']) ? $_POST['edit_id'] : null;
    $user = wp_get_current_user();
    if ($user->exists()) {
        if (empty($user->display_name)) {
            $user->display_name = $user->user_login;
        }
        $comment_author = $wpdb->escape($user->display_name);
        $comment_author_email = $wpdb->escape($user->user_email);
        $comment_author_url = $wpdb->escape($user->user_url);
        $user_ID = $wpdb->escape($user->ID);
        if (current_user_can('unfiltered_html')) {
            if (wp_create_nonce('unfiltered-html-comment_' . $comment_post_ID) != $_POST['_wp_unfiltered_html_comment']) {
                kses_remove_filters();
                kses_init_filters();
            }
        }
    } else {
        if (get_option('comment_registration') || 'private' == $status) {
            ajax_comment_err(__('Sorry, you must be logged in to post a comment.', 'Lophita'));
        }
    }
    $comment_type = '';
    if (get_option('require_name_email') && !$user->exists()) {
        if (6 > strlen($comment_author_email) || '' == $comment_author) {
            ajax_comment_err(__('Error: please fill the required fields (name, email).', 'Lophita'));
        } elseif (!is_email($comment_author_email)) {
            ajax_comment_err(__('Error: please enter a valid email address.', 'Lophita'));
        }
    }
    if ('' == $comment_content) {
        ajax_comment_err(__('Error: please type a comment.', 'Lophita'));
    }
    $dupe = "SELECT comment_ID FROM {$wpdb->comments} WHERE comment_post_ID = '{$comment_post_ID}' AND ( comment_author = '{$comment_author}' ";
    if ($comment_author_email) {
        $dupe .= "OR comment_author_email = '{$comment_author_email}' ";
    }
    $dupe .= ") AND comment_content = '{$comment_content}' LIMIT 1";
    if ($wpdb->get_var($dupe)) {
        ajax_comment_err(__('Duplicate comment detected; it looks as though you&#8217;ve already said that!', 'Lophita'));
    }
    if ($lasttime = $wpdb->get_var($wpdb->prepare("SELECT comment_date_gmt FROM {$wpdb->comments} WHERE comment_author = %s ORDER BY comment_date DESC LIMIT 1", $comment_author))) {
        $time_lastcomment = mysql2date('U', $lasttime, false);
        $time_newcomment = mysql2date('U', current_time('mysql', 1), false);
        $flood_die = apply_filters('comment_flood_filter', false, $time_lastcomment, $time_newcomment);
        if ($flood_die) {
            ajax_comment_err(__('You are posting comments too quickly.  Slow down.', 'Lophita'));
        }
    }
    $comment_parent = isset($_POST['comment_parent']) ? absint($_POST['comment_parent']) : 0;
    $commentdata = compact('comment_post_ID', 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_content', 'comment_type', 'comment_parent', 'user_ID');
    if ($edit_id) {
        $comment_id = $commentdata['comment_ID'] = $edit_id;
        if (ihacklog_user_can_edit_comment($commentdata, $comment_id)) {
            wp_update_comment($commentdata);
        } else {
            ajax_comment_err(__('Cheatin&#8217; uh?', 'Lophita'));
        }
    } else {
        $comment_id = wp_new_comment($commentdata);
    }
    $comment = get_comment($comment_id);
    do_action('set_comment_cookies', $comment, $user);
    $comment_depth = 1;
    $tmp_c = $comment;
    while ($tmp_c->comment_parent != 0) {
        $comment_depth++;
        $tmp_c = get_comment($tmp_c->comment_parent);
    }
    $GLOBALS['comment'] = $comment;
    ?>
<li <?php 
    comment_class();
    ?>
 id="li-comment-<?php 
    comment_ID();
    ?>
">
	<article id="comment-<?php 
    comment_ID();
    ?>
" class="comment-container">
		<div class="comment-header">
			<span class="comment-name"><?php 
    printf(__('%s'), get_comment_author_link());
    ?>
</span>
			<time class="comment-date" datetime="<?php 
    comment_time('Y/m/d H:i:s');
    ?>
"><?php 
    echo time_ago();
    ?>
</time>
		</div>
		<?php 
    if ('0' == $comment->comment_approved) {
        ?>
			<p class="comment-awaiting-moderation">您的评论正在排队等待审核,请稍后再来!</p>
		<?php 
    }
    ?>

		<div class="comment-content">
			<?php 
    comment_text();
    ?>
		</div>
	</article>

    <?php 
    die;
}
/**
 * Map meta capabilities to primitive capabilities.
 *
 * This does not actually compare whether the user ID has the actual capability,
 * just what the capability or capabilities are. Meta capability list value can
 * be 'delete_user', 'edit_user', 'remove_user', 'promote_user', 'delete_post',
 * 'delete_page', 'edit_post', 'edit_page', 'read_post', or 'read_page'.
 *
 * @since 2.0.0
 *
 * @param string $cap Capability name.
 * @param int $user_id User ID.
 * @return array Actual capabilities for meta capability.
 */
function map_meta_cap($cap, $user_id)
{
    $args = array_slice(func_get_args(), 2);
    $caps = array();
    switch ($cap) {
        case 'remove_user':
            $caps[] = 'remove_users';
            break;
        case 'promote_user':
            $caps[] = 'promote_users';
            break;
        case 'edit_user':
            // Allow user to edit itself
            if (isset($args[0]) && $user_id == $args[0]) {
                break;
            }
            // Fall through
        // Fall through
        case 'edit_users':
            // If multisite these caps are allowed only for super admins.
            if (is_multisite() && !is_super_admin($user_id)) {
                $caps[] = 'do_not_allow';
            } else {
                $caps[] = 'edit_users';
            }
            // Explicit due to primitive fall through
            break;
        case 'delete_post':
        case 'delete_page':
            $author_data = get_userdata($user_id);
            $post = get_post($args[0]);
            if ('revision' == $post->post_type) {
                $post = get_post($post->post_parent);
            }
            $post_type = get_post_type_object($post->post_type);
            if (!$post_type->map_meta_cap) {
                $caps[] = $post_type->cap->{$cap};
                // Prior to 3.1 we would re-call map_meta_cap here.
                if ('delete_post' == $cap) {
                    $cap = $post_type->cap->{$cap};
                }
                break;
            }
            if ('' != $post->post_author) {
                $post_author_data = get_userdata($post->post_author);
            } else {
                // No author set yet, so default to current user for cap checks.
                $post_author_data = $author_data;
            }
            // If the user is the author...
            if (is_object($post_author_data) && $user_id == $post_author_data->ID) {
                // If the post is published...
                if ('publish' == $post->post_status) {
                    $caps[] = $post_type->cap->delete_published_posts;
                } elseif ('trash' == $post->post_status) {
                    if ('publish' == get_post_meta($post->ID, '_wp_trash_meta_status', true)) {
                        $caps[] = $post_type->cap->delete_published_posts;
                    }
                } else {
                    // If the post is draft...
                    $caps[] = $post_type->cap->delete_posts;
                }
            } else {
                // The user is trying to edit someone else's post.
                $caps[] = $post_type->cap->delete_others_posts;
                // The post is published, extra cap required.
                if ('publish' == $post->post_status) {
                    $caps[] = $post_type->cap->delete_published_posts;
                } elseif ('private' == $post->post_status) {
                    $caps[] = $post_type->cap->delete_private_posts;
                }
            }
            break;
            // edit_post breaks down to edit_posts, edit_published_posts, or
            // edit_others_posts
        // edit_post breaks down to edit_posts, edit_published_posts, or
        // edit_others_posts
        case 'edit_post':
        case 'edit_page':
            $author_data = get_userdata($user_id);
            $post = get_post($args[0]);
            if ('revision' == $post->post_type) {
                $post = get_post($post->post_parent);
            }
            $post_type = get_post_type_object($post->post_type);
            if (!$post_type->map_meta_cap) {
                $caps[] = $post_type->cap->{$cap};
                // Prior to 3.1 we would re-call map_meta_cap here.
                if ('edit_post' == $cap) {
                    $cap = $post_type->cap->{$cap};
                }
                break;
            }
            if ('' != $post->post_author) {
                $post_author_data = get_userdata($post->post_author);
            } else {
                // No author set yet, so default to current user for cap checks.
                $post_author_data = $author_data;
            }
            //echo "current user id : $user_id, post author id: " . $post_author_data->ID . "<br />";
            // If the user is the author...
            if (is_object($post_author_data) && $user_id == $post_author_data->ID) {
                // If the post is published...
                if ('publish' == $post->post_status) {
                    $caps[] = $post_type->cap->edit_published_posts;
                } elseif ('trash' == $post->post_status) {
                    if ('publish' == get_post_meta($post->ID, '_wp_trash_meta_status', true)) {
                        $caps[] = $post_type->cap->edit_published_posts;
                    }
                } else {
                    // If the post is draft...
                    $caps[] = $post_type->cap->edit_posts;
                }
            } else {
                // The user is trying to edit someone else's post.
                $caps[] = $post_type->cap->edit_others_posts;
                // The post is published, extra cap required.
                if ('publish' == $post->post_status) {
                    $caps[] = $post_type->cap->edit_published_posts;
                } elseif ('private' == $post->post_status) {
                    $caps[] = $post_type->cap->edit_private_posts;
                }
            }
            break;
        case 'read_post':
        case 'read_page':
            $author_data = get_userdata($user_id);
            $post = get_post($args[0]);
            if ('revision' == $post->post_type) {
                $post = get_post($post->post_parent);
            }
            $post_type = get_post_type_object($post->post_type);
            if (!$post_type->map_meta_cap) {
                $caps[] = $post_type->cap->{$cap};
                // Prior to 3.1 we would re-call map_meta_cap here.
                if ('read_post' == $cap) {
                    $cap = $post_type->cap->{$cap};
                }
                break;
            }
            $status_obj = get_post_status_object($post->post_status);
            if ($status_obj->public) {
                $caps[] = $post_type->cap->read;
                break;
            }
            if ('' != $post->post_author) {
                $post_author_data = get_userdata($post->post_author);
            } else {
                // No author set yet, so default to current user for cap checks.
                $post_author_data = $author_data;
            }
            if (is_object($post_author_data) && $user_id == $post_author_data->ID) {
                $caps[] = $post_type->cap->read;
            } elseif ($status_obj->private) {
                $caps[] = $post_type->cap->read_private_posts;
            } else {
                $caps = map_meta_cap('edit_post', $user_id, $post->ID);
            }
            break;
        case 'edit_post_meta':
        case 'delete_post_meta':
        case 'add_post_meta':
            $post = get_post($args[0]);
            $post_type_object = get_post_type_object($post->post_type);
            $caps = map_meta_cap($post_type_object->cap->edit_post, $user_id, $post->ID);
            $meta_key = isset($args[1]) ? $args[1] : false;
            if ($meta_key && has_filter("auth_post_meta_{$meta_key}")) {
                $allowed = apply_filters("auth_post_meta_{$meta_key}", false, $meta_key, $post->ID, $user_id, $cap, $caps);
                if (!$allowed) {
                    $caps[] = $cap;
                }
            } elseif ($meta_key && is_protected_meta($meta_key, 'post')) {
                $caps[] = $cap;
            }
            break;
        case 'edit_comment':
            $comment = get_comment($args[0]);
            $post = get_post($comment->comment_post_ID);
            $post_type_object = get_post_type_object($post->post_type);
            $caps = map_meta_cap($post_type_object->cap->edit_post, $user_id, $post->ID);
            break;
        case 'unfiltered_upload':
            if (defined('ALLOW_UNFILTERED_UPLOADS') && ALLOW_UNFILTERED_UPLOADS && (!is_multisite() || is_super_admin($user_id))) {
                $caps[] = $cap;
            } else {
                $caps[] = 'do_not_allow';
            }
            break;
        case 'edit_files':
        case 'edit_plugins':
        case 'edit_themes':
            if (defined('DISALLOW_FILE_EDIT') && DISALLOW_FILE_EDIT) {
                $caps[] = 'do_not_allow';
                break;
            }
            // Fall through if not DISALLOW_FILE_EDIT.
        // Fall through if not DISALLOW_FILE_EDIT.
        case 'update_plugins':
        case 'delete_plugins':
        case 'install_plugins':
        case 'update_themes':
        case 'delete_themes':
        case 'install_themes':
        case 'update_core':
            // Disallow anything that creates, deletes, or edits core, plugin, or theme files.
            // Files in uploads are excepted.
            if (defined('DISALLOW_FILE_MODS') && DISALLOW_FILE_MODS) {
                $caps[] = 'do_not_allow';
                break;
            }
            // Fall through if not DISALLOW_FILE_MODS.
        // Fall through if not DISALLOW_FILE_MODS.
        case 'unfiltered_html':
            // Disallow unfiltered_html for all users, even admins and super admins.
            if (defined('DISALLOW_UNFILTERED_HTML') && DISALLOW_UNFILTERED_HTML) {
                $caps[] = 'do_not_allow';
                break;
            }
            // Fall through if not DISALLOW_UNFILTERED_HTML
        // Fall through if not DISALLOW_UNFILTERED_HTML
        case 'delete_user':
        case 'delete_users':
            // If multisite these caps are allowed only for super admins.
            if (is_multisite() && !is_super_admin($user_id)) {
                $caps[] = 'do_not_allow';
            } else {
                if ('delete_user' == $cap) {
                    $cap = 'delete_users';
                }
                $caps[] = $cap;
            }
            break;
        case 'create_users':
            if (!is_multisite()) {
                $caps[] = $cap;
            } elseif (is_super_admin() || get_site_option('add_new_users')) {
                $caps[] = $cap;
            } else {
                $caps[] = 'do_not_allow';
            }
            break;
        default:
            // Handle meta capabilities for custom post types.
            $post_type_meta_caps = _post_type_meta_capabilities();
            if (isset($post_type_meta_caps[$cap])) {
                $args = array_merge(array($post_type_meta_caps[$cap], $user_id), $args);
                return call_user_func_array('map_meta_cap', $args);
            }
            // If no meta caps match, return the original cap.
            $caps[] = $cap;
    }
    return apply_filters('map_meta_cap', $caps, $cap, $user_id, $args);
}
 /**
  * Helper method for wp_newPost and wp_editPost, containing shared logic.
  *
  * @since 3.4.0
  * @uses wp_insert_post()
  *
  * @param WP_User $user The post author if post_author isn't set in $content_struct.
  * @param array|IXR_Error $content_struct Post data to insert.
  */
 protected function _insert_post($user, $content_struct)
 {
     $defaults = array('post_status' => 'draft', 'post_type' => 'post', 'post_author' => 0, 'post_password' => '', 'post_excerpt' => '', 'post_content' => '', 'post_title' => '');
     $post_data = wp_parse_args($content_struct, $defaults);
     $post_type = get_post_type_object($post_data['post_type']);
     if (!$post_type) {
         return new IXR_Error(403, __('Invalid post type'));
     }
     $update = !empty($post_data['ID']);
     if ($update) {
         if (!get_post($post_data['ID'])) {
             return new IXR_Error(401, __('Invalid post ID.'));
         }
         if (!current_user_can('edit_post', $post_data['ID'])) {
             return new IXR_Error(401, __('Sorry, you are not allowed to edit this post.'));
         }
         if ($post_data['post_type'] != get_post_type($post_data['ID'])) {
             return new IXR_Error(401, __('The post type may not be changed.'));
         }
     } else {
         if (!current_user_can($post_type->cap->create_posts) || !current_user_can($post_type->cap->edit_posts)) {
             return new IXR_Error(401, __('Sorry, you are not allowed to post on this site.'));
         }
     }
     switch ($post_data['post_status']) {
         case 'draft':
         case 'pending':
             break;
         case 'private':
             if (!current_user_can($post_type->cap->publish_posts)) {
                 return new IXR_Error(401, __('Sorry, you are not allowed to create private posts in this post type'));
             }
             break;
         case 'publish':
         case 'future':
             if (!current_user_can($post_type->cap->publish_posts)) {
                 return new IXR_Error(401, __('Sorry, you are not allowed to publish posts in this post type'));
             }
             break;
         default:
             if (!get_post_status_object($post_data['post_status'])) {
                 $post_data['post_status'] = 'draft';
             }
             break;
     }
     if (!empty($post_data['post_password']) && !current_user_can($post_type->cap->publish_posts)) {
         return new IXR_Error(401, __('Sorry, you are not allowed to create password protected posts in this post type'));
     }
     $post_data['post_author'] = absint($post_data['post_author']);
     if (!empty($post_data['post_author']) && $post_data['post_author'] != $user->ID) {
         if (!current_user_can($post_type->cap->edit_others_posts)) {
             return new IXR_Error(401, __('You are not allowed to create posts as this user.'));
         }
         $author = get_userdata($post_data['post_author']);
         if (!$author) {
             return new IXR_Error(404, __('Invalid author ID.'));
         }
     } else {
         $post_data['post_author'] = $user->ID;
     }
     if (isset($post_data['comment_status']) && $post_data['comment_status'] != 'open' && $post_data['comment_status'] != 'closed') {
         unset($post_data['comment_status']);
     }
     if (isset($post_data['ping_status']) && $post_data['ping_status'] != 'open' && $post_data['ping_status'] != 'closed') {
         unset($post_data['ping_status']);
     }
     // Do some timestamp voodoo
     if (!empty($post_data['post_date_gmt'])) {
         // We know this is supposed to be GMT, so we're going to slap that Z on there by force
         $dateCreated = rtrim($post_data['post_date_gmt']->getIso(), 'Z') . 'Z';
     } elseif (!empty($post_data['post_date'])) {
         $dateCreated = $post_data['post_date']->getIso();
     }
     if (!empty($dateCreated)) {
         $post_data['post_date'] = get_date_from_gmt(iso8601_to_datetime($dateCreated));
         $post_data['post_date_gmt'] = iso8601_to_datetime($dateCreated, 'GMT');
     }
     if (!isset($post_data['ID'])) {
         $post_data['ID'] = get_default_post_to_edit($post_data['post_type'], true)->ID;
     }
     $post_ID = $post_data['ID'];
     if ($post_data['post_type'] == 'post') {
         // Private and password-protected posts cannot be stickied.
         if ($post_data['post_status'] == 'private' || !empty($post_data['post_password'])) {
             // Error if the client tried to stick the post, otherwise, silently unstick.
             if (!empty($post_data['sticky'])) {
                 return new IXR_Error(401, __('Sorry, you cannot stick a private post.'));
             }
             if ($update) {
                 unstick_post($post_ID);
             }
         } elseif (isset($post_data['sticky'])) {
             if (!current_user_can($post_type->cap->edit_others_posts)) {
                 return new IXR_Error(401, __('Sorry, you are not allowed to stick this post.'));
             }
             if ($post_data['sticky']) {
                 stick_post($post_ID);
             } else {
                 unstick_post($post_ID);
             }
         }
     }
     if (isset($post_data['post_thumbnail'])) {
         // empty value deletes, non-empty value adds/updates
         if (!$post_data['post_thumbnail']) {
             delete_post_thumbnail($post_ID);
         } elseif (!get_post(absint($post_data['post_thumbnail']))) {
             return new IXR_Error(404, __('Invalid attachment ID.'));
         }
         set_post_thumbnail($post_ID, $post_data['post_thumbnail']);
         unset($content_struct['post_thumbnail']);
     }
     if (isset($post_data['custom_fields'])) {
         $this->set_custom_fields($post_ID, $post_data['custom_fields']);
     }
     if (isset($post_data['terms']) || isset($post_data['terms_names'])) {
         $post_type_taxonomies = get_object_taxonomies($post_data['post_type'], 'objects');
         // accumulate term IDs from terms and terms_names
         $terms = array();
         // first validate the terms specified by ID
         if (isset($post_data['terms']) && is_array($post_data['terms'])) {
             $taxonomies = array_keys($post_data['terms']);
             // validating term ids
             foreach ($taxonomies as $taxonomy) {
                 if (!array_key_exists($taxonomy, $post_type_taxonomies)) {
                     return new IXR_Error(401, __('Sorry, one of the given taxonomies is not supported by the post type.'));
                 }
                 if (!current_user_can($post_type_taxonomies[$taxonomy]->cap->assign_terms)) {
                     return new IXR_Error(401, __('Sorry, you are not allowed to assign a term to one of the given taxonomies.'));
                 }
                 $term_ids = $post_data['terms'][$taxonomy];
                 $terms[$taxonomy] = array();
                 foreach ($term_ids as $term_id) {
                     $term = get_term_by('id', $term_id, $taxonomy);
                     if (!$term) {
                         return new IXR_Error(403, __('Invalid term ID'));
                     }
                     $terms[$taxonomy][] = (int) $term_id;
                 }
             }
         }
         // now validate terms specified by name
         if (isset($post_data['terms_names']) && is_array($post_data['terms_names'])) {
             $taxonomies = array_keys($post_data['terms_names']);
             foreach ($taxonomies as $taxonomy) {
                 if (!array_key_exists($taxonomy, $post_type_taxonomies)) {
                     return new IXR_Error(401, __('Sorry, one of the given taxonomies is not supported by the post type.'));
                 }
                 if (!current_user_can($post_type_taxonomies[$taxonomy]->cap->assign_terms)) {
                     return new IXR_Error(401, __('Sorry, you are not allowed to assign a term to one of the given taxonomies.'));
                 }
                 // for hierarchical taxonomies, we can't assign a term when multiple terms in the hierarchy share the same name
                 $ambiguous_terms = array();
                 if (is_taxonomy_hierarchical($taxonomy)) {
                     $tax_term_names = get_terms($taxonomy, array('fields' => 'names', 'hide_empty' => false));
                     // count the number of terms with the same name
                     $tax_term_names_count = array_count_values($tax_term_names);
                     // filter out non-ambiguous term names
                     $ambiguous_tax_term_counts = array_filter($tax_term_names_count, array($this, '_is_greater_than_one'));
                     $ambiguous_terms = array_keys($ambiguous_tax_term_counts);
                 }
                 $term_names = $post_data['terms_names'][$taxonomy];
                 foreach ($term_names as $term_name) {
                     if (in_array($term_name, $ambiguous_terms)) {
                         return new IXR_Error(401, __('Ambiguous term name used in a hierarchical taxonomy. Please use term ID instead.'));
                     }
                     $term = get_term_by('name', $term_name, $taxonomy);
                     if (!$term) {
                         // term doesn't exist, so check that the user is allowed to create new terms
                         if (!current_user_can($post_type_taxonomies[$taxonomy]->cap->edit_terms)) {
                             return new IXR_Error(401, __('Sorry, you are not allowed to add a term to one of the given taxonomies.'));
                         }
                         // create the new term
                         $term_info = wp_insert_term($term_name, $taxonomy);
                         if (is_wp_error($term_info)) {
                             return new IXR_Error(500, $term_info->get_error_message());
                         }
                         $terms[$taxonomy][] = (int) $term_info['term_id'];
                     } else {
                         $terms[$taxonomy][] = (int) $term->term_id;
                     }
                 }
             }
         }
         $post_data['tax_input'] = $terms;
         unset($post_data['terms'], $post_data['terms_names']);
     } else {
         // do not allow direct submission of 'tax_input', clients must use 'terms' and/or 'terms_names'
         unset($post_data['tax_input'], $post_data['post_category'], $post_data['tags_input']);
     }
     if (isset($post_data['post_format'])) {
         $format = set_post_format($post_ID, $post_data['post_format']);
         if (is_wp_error($format)) {
             return new IXR_Error(500, $format->get_error_message());
         }
         unset($post_data['post_format']);
     }
     // Handle enclosures
     $enclosure = isset($post_data['enclosure']) ? $post_data['enclosure'] : null;
     $this->add_enclosure_if_new($post_ID, $enclosure);
     $this->attach_uploads($post_ID, $post_data['post_content']);
     /**
      * Filter post data array to be inserted via XML-RPC.
      *
      * @since 3.4.0
      *
      * @param array $post_data      Parsed array of post data.
      * @param array $content_struct Post data array.
      */
     $post_data = apply_filters('xmlrpc_wp_insert_post_data', $post_data, $content_struct);
     $post_ID = $update ? wp_update_post($post_data, true) : wp_insert_post($post_data, true);
     if (is_wp_error($post_ID)) {
         return new IXR_Error(500, $post_ID->get_error_message());
     }
     if (!$post_ID) {
         return new IXR_Error(401, __('Sorry, your entry could not be posted. Something wrong happened.'));
     }
     return strval($post_ID);
 }
Example #30
0
 /**
  * Retrieve the posts based on query variables.
  *
  * There are a few filters and actions that can be used to modify the post
  * database query.
  *
  * @since 1.5.0
  * @access public
  * @uses do_action_ref_array() Calls 'pre_get_posts' hook before retrieving posts.
  *
  * @return array List of posts.
  */
 function &get_posts()
 {
     global $wpdb, $user_ID, $_wp_using_ext_object_cache;
     $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;
 }