public function upsert_post($post, $silent = false)
 {
     global $wpdb;
     // reject the post if it's not a WP_Post
     if (!$post instanceof WP_Post) {
         return;
     }
     $post = $post->to_array();
     // reject posts without an ID
     if (!isset($post['ID'])) {
         return;
     }
     $now = current_time('mysql');
     $now_gmt = get_gmt_from_date($now);
     $defaults = array('ID' => 0, 'post_author' => '0', 'post_content' => '', 'post_content_filtered' => '', 'post_title' => '', 'post_name' => '', 'post_excerpt' => '', 'post_status' => 'draft', 'post_type' => 'post', 'comment_status' => 'closed', 'comment_count' => '0', 'ping_status' => '', 'post_password' => '', 'to_ping' => '', 'pinged' => '', 'post_parent' => 0, 'menu_order' => 0, 'guid' => '', 'post_date' => $now, 'post_date_gmt' => $now_gmt, 'post_modified' => $now, 'post_modified_gmt' => $now_gmt);
     $post = array_intersect_key($post, $defaults);
     $post = sanitize_post($post, 'db');
     unset($post['filter']);
     $exists = $wpdb->get_var($wpdb->prepare("SELECT EXISTS( SELECT 1 FROM {$wpdb->posts} WHERE ID = %d )", $post['ID']));
     if ($exists) {
         $wpdb->update($wpdb->posts, $post, array('ID' => $post['ID']));
     } else {
         $wpdb->insert($wpdb->posts, $post);
     }
     clean_post_cache($post['ID']);
 }
 public static function wpsc_attachment_fields_filter($form_fields, $post)
 {
     if (!$post->post_parent) {
         return $form_fields;
     }
     $parent = get_post($post->post_parent);
     if ($parent->post_type !== 'wpsc-product') {
         return $form_fields;
     }
     $edit_post = sanitize_post($post, 'edit');
     if (is_array($form_fields) && count($form_fields) > 0) {
         $number_field = 0;
         $field_post_excerpt = array('label' => 'Caption', 'input' => 'html', 'html' => wp_caption_input_textarea($edit_post));
         foreach ($form_fields as $form_key => $form_values) {
             if ($number_field == 1 && is_array($field_post_excerpt)) {
                 $new_form_fields['post_excerpt'] = $field_post_excerpt;
                 $field_post_excerpt = '';
             }
             $new_form_fields[$form_key] = $form_values;
             $number_field++;
         }
         $form_fields = $new_form_fields;
     }
     $exclude_image = (int) get_post_meta($post->ID, '_wpsc_exclude_image', true);
     $label = __('Exclude image', 'wpsc_dgallery');
     $html = '<input type="checkbox" ' . checked($exclude_image, 1, false) . ' name="attachments[' . $post->ID . '][wpsc_exclude_image]" id="attachments[' . $post->ID . '][wpsc_exclude_image]" />';
     $form_fields['wpsc_exclude_image'] = array('label' => $label, 'input' => 'html', 'html' => $html, 'value' => '', 'helps' => __('Enabling this option will hide it from the product page image gallery. If assigned to variations below the image will show when option is selected. (Show Product Variations in Gallery is a', 'wpsc_dgallery') . ' <a href="http://a3rev.com/shop/wp-e-commerce-dynamic-gallery/" target="_blank">' . __('Pro Version', 'wpsc_dgallery') . '</a> ' . __('only feature', 'wpsc_dgallery') . ')');
     return $form_fields;
 }
Example #3
0
 /**
  * @param array $posts
  * @return array
  */
 public static function maybe_set_preview($posts)
 {
     if (is_array($posts) && isset($_GET['preview']) && $_GET['preview'] && isset($_GET['preview_id']) && $_GET['preview_id'] && current_user_can('edit_post', $_GET['preview_id'])) {
         // No need to check the nonce, that already happened in _show_post_preview on init
         $preview_id = $_GET['preview_id'];
         foreach ($posts as &$post) {
             if (is_object($post) && $post->ID == $preview_id) {
                 // Based on _set_preview( $post ), but adds import_custom
                 $preview = wp_get_post_autosave($preview_id);
                 if (is_object($preview)) {
                     $preview = sanitize_post($preview);
                     $post->post_content = $preview->post_content;
                     $post->post_title = $preview->post_title;
                     $post->post_excerpt = $preview->post_excerpt;
                     $post->import_custom($preview_id);
                     add_filter('get_the_terms', '_wp_preview_terms_filter', 10, 3);
                 }
             }
         }
     }
     return $posts;
 }
/**
 * wp_insert_attachment() - Insert an attachment
 *
 * {@internal Missing Long Description}}
 *
 * @package WordPress
 * @subpackage Post
 * @since 2.0
 *
 * @uses $wpdb
 * @uses $user_ID
 *
 * @param object $object attachment object
 * @param string $file filename
 * @param int $post_parent parent post ID
 * @return int {@internal Missing Description}}
 */
function wp_insert_attachment($object, $file = false, $parent = 0)
{
    global $wpdb, $user_ID;
    $defaults = array('post_status' => 'draft', 'post_type' => 'post', 'post_author' => $user_ID, 'ping_status' => get_option('default_ping_status'), 'post_parent' => 0, 'menu_order' => 0, 'to_ping' => '', 'pinged' => '', 'post_password' => '', 'guid' => '', 'post_content_filtered' => '', 'post_excerpt' => '');
    $object = wp_parse_args($object, $defaults);
    if (!empty($parent)) {
        $object['post_parent'] = $parent;
    }
    $object = sanitize_post($object, 'db');
    // export array as variables
    extract($object, EXTR_SKIP);
    // Make sure we set a valid category
    if (0 == count($post_category) || !is_array($post_category)) {
        $post_category = array(get_option('default_category'));
    }
    if (empty($post_author)) {
        $post_author = $user_ID;
    }
    $post_type = 'attachment';
    $post_status = 'inherit';
    // Are we updating or creating?
    $update = false;
    if (!empty($ID)) {
        $update = true;
        $post_ID = (int) $ID;
    }
    // Create a valid post name.
    if (empty($post_name)) {
        $post_name = sanitize_title($post_title);
    } else {
        $post_name = sanitize_title($post_name);
    }
    // expected_slashed ($post_name)
    $post_name_check = $wpdb->get_var($wpdb->prepare("SELECT post_name FROM {$wpdb->posts} WHERE post_name = '{$post_name}' AND post_status = 'inherit' AND ID != %d LIMIT 1", $post_ID));
    if ($post_name_check) {
        $suffix = 2;
        while ($post_name_check) {
            $alt_post_name = $post_name . "-{$suffix}";
            // expected_slashed ($alt_post_name, $post_name)
            $post_name_check = $wpdb->get_var($wpdb->prepare("SELECT post_name FROM {$wpdb->posts} WHERE post_name = '{$alt_post_name}' AND post_status = 'inherit' AND ID != %d AND post_parent = %d LIMIT 1", $post_ID, $post_parent));
            $suffix++;
        }
        $post_name = $alt_post_name;
    }
    if (empty($post_date)) {
        $post_date = current_time('mysql');
    }
    if (empty($post_date_gmt)) {
        $post_date_gmt = current_time('mysql', 1);
    }
    if (empty($post_modified)) {
        $post_modified = $post_date;
    }
    if (empty($post_modified_gmt)) {
        $post_modified_gmt = $post_date_gmt;
    }
    if (empty($comment_status)) {
        if ($update) {
            $comment_status = 'closed';
        } else {
            $comment_status = get_option('default_comment_status');
        }
    }
    if (empty($ping_status)) {
        $ping_status = get_option('default_ping_status');
    }
    if (isset($to_ping)) {
        $to_ping = preg_replace('|\\s+|', "\n", $to_ping);
    } else {
        $to_ping = '';
    }
    if (isset($post_parent)) {
        $post_parent = (int) $post_parent;
    } else {
        $post_parent = 0;
    }
    if (isset($menu_order)) {
        $menu_order = (int) $menu_order;
    } else {
        $menu_order = 0;
    }
    if (!isset($post_password)) {
        $post_password = '';
    }
    if (!isset($pinged)) {
        $pinged = '';
    }
    // expected_slashed (everything!)
    $data = compact(array('post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_content_filtered', 'post_title', 'post_excerpt', 'post_status', 'post_type', 'comment_status', 'ping_status', 'post_password', 'post_name', 'to_ping', 'pinged', 'post_modified', 'post_modified_gmt', 'post_parent', 'menu_order', 'post_mime_type', 'guid'));
    $data = stripslashes_deep($data);
    if ($update) {
        $wpdb->update($wpdb->posts, $data, array('ID' => $post_ID));
    } else {
        $wpdb->insert($wpdb->posts, $data);
        $post_ID = (int) $wpdb->insert_id;
    }
    if (empty($post_name)) {
        $post_name = sanitize_title($post_title, $post_ID);
        $wpdb->update($wpdb->posts, compact("post_name"), array('ID' => $post_ID));
    }
    wp_set_post_categories($post_ID, $post_category);
    if ($file) {
        update_attached_file($post_ID, $file);
    }
    clean_post_cache($post_ID);
    if ($update) {
        do_action('edit_attachment', $post_ID);
    } else {
        do_action('add_attachment', $post_ID);
    }
    return $post_ID;
}
Example #5
0
 /**
  * Retrieve the posts based on query variables.
  *
  * There are a few filters and actions that can be used to modify the post
  * database query.
  *
  * @since 1.5.0
  * @access public
  * @uses do_action_ref_array() Calls 'pre_get_posts' hook before retrieving posts.
  *
  * @return array List of posts.
  */
 function &get_posts()
 {
     global $wpdb, $user_ID, $_wp_using_ext_object_cache;
     do_action_ref_array('pre_get_posts', array(&$this));
     // Shorthand.
     $q =& $this->query_vars;
     $q = $this->fill_query_vars($q);
     // First let's clear some variables
     $distinct = '';
     $whichcat = '';
     $whichauthor = '';
     $whichmimetype = '';
     $where = '';
     $limits = '';
     $join = '';
     $search = '';
     $groupby = '';
     $fields = "{$wpdb->posts}.*";
     $post_status_join = false;
     $page = 1;
     if (!isset($q['caller_get_posts'])) {
         $q['caller_get_posts'] = false;
     }
     if (!isset($q['suppress_filters'])) {
         $q['suppress_filters'] = false;
     }
     if (!isset($q['cache_results'])) {
         if ($_wp_using_ext_object_cache) {
             $q['cache_results'] = false;
         } else {
             $q['cache_results'] = true;
         }
     }
     if (!isset($q['update_post_term_cache'])) {
         $q['update_post_term_cache'] = true;
     }
     if (!isset($q['update_post_meta_cache'])) {
         $q['update_post_meta_cache'] = true;
     }
     if (!isset($q['post_type'])) {
         if ($this->is_search) {
             $q['post_type'] = 'any';
         } else {
             $q['post_type'] = '';
         }
     }
     $post_type = $q['post_type'];
     if (!isset($q['posts_per_page']) || $q['posts_per_page'] == 0) {
         $q['posts_per_page'] = get_option('posts_per_page');
     }
     if (isset($q['showposts']) && $q['showposts']) {
         $q['showposts'] = (int) $q['showposts'];
         $q['posts_per_page'] = $q['showposts'];
     }
     if (isset($q['posts_per_archive_page']) && $q['posts_per_archive_page'] != 0 && ($this->is_archive || $this->is_search)) {
         $q['posts_per_page'] = $q['posts_per_archive_page'];
     }
     if (!isset($q['nopaging'])) {
         if ($q['posts_per_page'] == -1) {
             $q['nopaging'] = true;
         } else {
             $q['nopaging'] = false;
         }
     }
     if ($this->is_feed) {
         $q['posts_per_page'] = get_option('posts_per_rss');
         $q['nopaging'] = false;
     }
     $q['posts_per_page'] = (int) $q['posts_per_page'];
     if ($q['posts_per_page'] < -1) {
         $q['posts_per_page'] = abs($q['posts_per_page']);
     } else {
         if ($q['posts_per_page'] == 0) {
             $q['posts_per_page'] = 1;
         }
     }
     if (!isset($q['comments_per_page']) || $q['comments_per_page'] == 0) {
         $q['comments_per_page'] = get_option('comments_per_page');
     }
     if ($this->is_home && (empty($this->query) || $q['preview'] == 'true') && 'page' == get_option('show_on_front') && get_option('page_on_front')) {
         $this->is_page = true;
         $this->is_home = false;
         $q['page_id'] = get_option('page_on_front');
     }
     if (isset($q['page'])) {
         $q['page'] = trim($q['page'], '/');
         $q['page'] = absint($q['page']);
     }
     // If true, forcibly turns off SQL_CALC_FOUND_ROWS even when limits are present.
     if (isset($q['no_found_rows'])) {
         $q['no_found_rows'] = (bool) $q['no_found_rows'];
     } else {
         $q['no_found_rows'] = false;
     }
     // If a month is specified in the querystring, load that month
     if ($q['m']) {
         $q['m'] = '' . preg_replace('|[^0-9]|', '', $q['m']);
         $where .= " AND YEAR({$wpdb->posts}.post_date)=" . substr($q['m'], 0, 4);
         if (strlen($q['m']) > 5) {
             $where .= " AND MONTH({$wpdb->posts}.post_date)=" . substr($q['m'], 4, 2);
         }
         if (strlen($q['m']) > 7) {
             $where .= " AND DAYOFMONTH({$wpdb->posts}.post_date)=" . substr($q['m'], 6, 2);
         }
         if (strlen($q['m']) > 9) {
             $where .= " AND HOUR({$wpdb->posts}.post_date)=" . substr($q['m'], 8, 2);
         }
         if (strlen($q['m']) > 11) {
             $where .= " AND MINUTE({$wpdb->posts}.post_date)=" . substr($q['m'], 10, 2);
         }
         if (strlen($q['m']) > 13) {
             $where .= " AND SECOND({$wpdb->posts}.post_date)=" . substr($q['m'], 12, 2);
         }
     }
     if ('' !== $q['hour']) {
         $where .= " AND HOUR({$wpdb->posts}.post_date)='" . $q['hour'] . "'";
     }
     if ('' !== $q['minute']) {
         $where .= " AND MINUTE({$wpdb->posts}.post_date)='" . $q['minute'] . "'";
     }
     if ('' !== $q['second']) {
         $where .= " AND SECOND({$wpdb->posts}.post_date)='" . $q['second'] . "'";
     }
     if ($q['year']) {
         $where .= " AND YEAR({$wpdb->posts}.post_date)='" . $q['year'] . "'";
     }
     if ($q['monthnum']) {
         $where .= " AND MONTH({$wpdb->posts}.post_date)='" . $q['monthnum'] . "'";
     }
     if ($q['day']) {
         $where .= " AND DAYOFMONTH({$wpdb->posts}.post_date)='" . $q['day'] . "'";
     }
     // If we've got a post_type AND its not "any" post_type.
     if (!empty($q['post_type']) && 'any' != $q['post_type']) {
         foreach ((array) $q['post_type'] as $_post_type) {
             $ptype_obj = get_post_type_object($_post_type);
             if (!$ptype_obj || !$ptype_obj->query_var || empty($q[$ptype_obj->query_var])) {
                 continue;
             }
             if (!$ptype_obj->hierarchical || strpos($q[$ptype_obj->query_var], '/') === false) {
                 // Non-hierarchical post_types & parent-level-hierarchical post_types can directly use 'name'
                 $q['name'] = $q[$ptype_obj->query_var];
             } else {
                 // Hierarchical post_types will operate through the
                 $q['pagename'] = $q[$ptype_obj->query_var];
                 $q['name'] = '';
             }
             // Only one request for a slug is possible, this is why name & pagename are overwritten above.
             break;
         }
         //end foreach
         unset($ptype_obj);
     }
     if ('' != $q['name']) {
         $q['name'] = sanitize_title($q['name']);
         $where .= " AND {$wpdb->posts}.post_name = '" . $q['name'] . "'";
     } elseif ('' != $q['pagename']) {
         if (isset($this->queried_object_id)) {
             $reqpage = $this->queried_object_id;
         } else {
             if ('page' != $q['post_type']) {
                 foreach ((array) $q['post_type'] as $_post_type) {
                     $ptype_obj = get_post_type_object($_post_type);
                     if (!$ptype_obj || !$ptype_obj->hierarchical) {
                         continue;
                     }
                     $reqpage = get_page_by_path($q['pagename'], OBJECT, $_post_type);
                     if ($reqpage) {
                         break;
                     }
                 }
                 unset($ptype_obj);
             } else {
                 $reqpage = get_page_by_path($q['pagename']);
             }
             if (!empty($reqpage)) {
                 $reqpage = $reqpage->ID;
             } else {
                 $reqpage = 0;
             }
         }
         $page_for_posts = get_option('page_for_posts');
         if ('page' != get_option('show_on_front') || empty($page_for_posts) || $reqpage != $page_for_posts) {
             $q['pagename'] = str_replace('%2F', '/', urlencode(urldecode($q['pagename'])));
             $page_paths = '/' . trim($q['pagename'], '/');
             $q['pagename'] = sanitize_title(basename($page_paths));
             $q['name'] = $q['pagename'];
             $where .= " AND ({$wpdb->posts}.ID = '{$reqpage}')";
             $reqpage_obj = get_page($reqpage);
             if (is_object($reqpage_obj) && 'attachment' == $reqpage_obj->post_type) {
                 $this->is_attachment = true;
                 $post_type = $q['post_type'] = 'attachment';
                 $this->is_page = true;
                 $q['attachment_id'] = $reqpage;
             }
         }
     } elseif ('' != $q['attachment']) {
         $q['attachment'] = str_replace('%2F', '/', urlencode(urldecode($q['attachment'])));
         $attach_paths = '/' . trim($q['attachment'], '/');
         $q['attachment'] = sanitize_title(basename($attach_paths));
         $q['name'] = $q['attachment'];
         $where .= " AND {$wpdb->posts}.post_name = '" . $q['attachment'] . "'";
     }
     if ($q['w']) {
         $where .= ' AND ' . _wp_mysql_week("`{$wpdb->posts}`.`post_date`") . " = '" . $q['w'] . "'";
     }
     if (intval($q['comments_popup'])) {
         $q['p'] = absint($q['comments_popup']);
     }
     // If an attachment is requested by number, let it supercede any post number.
     if ($q['attachment_id']) {
         $q['p'] = absint($q['attachment_id']);
     }
     // If a post number is specified, load that post
     if ($q['p']) {
         $where .= " AND {$wpdb->posts}.ID = " . $q['p'];
     } elseif ($q['post__in']) {
         $post__in = implode(',', array_map('absint', $q['post__in']));
         $where .= " AND {$wpdb->posts}.ID IN ({$post__in})";
     } elseif ($q['post__not_in']) {
         $post__not_in = implode(',', array_map('absint', $q['post__not_in']));
         $where .= " AND {$wpdb->posts}.ID NOT IN ({$post__not_in})";
     }
     if (is_numeric($q['post_parent'])) {
         $where .= $wpdb->prepare(" AND {$wpdb->posts}.post_parent = %d ", $q['post_parent']);
     }
     if ($q['page_id']) {
         if ('page' != get_option('show_on_front') || $q['page_id'] != get_option('page_for_posts')) {
             $q['p'] = $q['page_id'];
             $where = " AND {$wpdb->posts}.ID = " . $q['page_id'];
         }
     }
     // If a search pattern is specified, load the posts that match
     if (!empty($q['s'])) {
         // added slashes screw with quote grouping when done early, so done later
         $q['s'] = stripslashes($q['s']);
         if (!empty($q['sentence'])) {
             $q['search_terms'] = array($q['s']);
         } else {
             preg_match_all('/".*?("|$)|((?<=[\\s",+])|^)[^\\s",+]+/', $q['s'], $matches);
             $q['search_terms'] = array_map('_search_terms_tidy', $matches[0]);
         }
         $n = !empty($q['exact']) ? '' : '%';
         $searchand = '';
         foreach ((array) $q['search_terms'] as $term) {
             $term = addslashes_gpc($term);
             $search .= "{$searchand}(({$wpdb->posts}.post_title LIKE '{$n}{$term}{$n}') OR ({$wpdb->posts}.post_content LIKE '{$n}{$term}{$n}'))";
             $searchand = ' AND ';
         }
         $term = esc_sql($q['s']);
         if (empty($q['sentence']) && count($q['search_terms']) > 1 && $q['search_terms'][0] != $q['s']) {
             $search .= " OR ({$wpdb->posts}.post_title LIKE '{$n}{$term}{$n}') OR ({$wpdb->posts}.post_content LIKE '{$n}{$term}{$n}')";
         }
         if (!empty($search)) {
             $search = " AND ({$search}) ";
             if (!is_user_logged_in()) {
                 $search .= " AND ({$wpdb->posts}.post_password = '') ";
             }
         }
     }
     // Allow plugins to contextually add/remove/modify the search section of the database query
     $search = apply_filters_ref_array('posts_search', array($search, &$this));
     // Category stuff
     if (empty($q['cat']) || $q['cat'] == '0' || $this->is_singular) {
         $whichcat = '';
     } else {
         $q['cat'] = '' . urldecode($q['cat']) . '';
         $q['cat'] = addslashes_gpc($q['cat']);
         $cat_array = preg_split('/[,\\s]+/', $q['cat']);
         $q['cat'] = '';
         $req_cats = array();
         foreach ((array) $cat_array as $cat) {
             $cat = intval($cat);
             $req_cats[] = $cat;
             $in = $cat > 0;
             $cat = abs($cat);
             if ($in) {
                 $q['category__in'][] = $cat;
                 $q['category__in'] = array_merge($q['category__in'], get_term_children($cat, 'category'));
             } else {
                 $q['category__not_in'][] = $cat;
                 $q['category__not_in'] = array_merge($q['category__not_in'], get_term_children($cat, 'category'));
             }
         }
         $q['cat'] = implode(',', $req_cats);
     }
     if (!empty($q['category__in'])) {
         $join = " INNER JOIN {$wpdb->term_relationships} ON ({$wpdb->posts}.ID = {$wpdb->term_relationships}.object_id) INNER JOIN {$wpdb->term_taxonomy} ON ({$wpdb->term_relationships}.term_taxonomy_id = {$wpdb->term_taxonomy}.term_taxonomy_id) ";
         $whichcat .= " AND {$wpdb->term_taxonomy}.taxonomy = 'category' ";
         $include_cats = "'" . implode("', '", $q['category__in']) . "'";
         $whichcat .= " AND {$wpdb->term_taxonomy}.term_id IN ({$include_cats}) ";
     }
     if (!empty($q['category__not_in'])) {
         $cat_string = "'" . implode("', '", $q['category__not_in']) . "'";
         $whichcat .= " AND {$wpdb->posts}.ID NOT IN ( SELECT tr.object_id FROM {$wpdb->term_relationships} AS tr INNER JOIN {$wpdb->term_taxonomy} AS tt ON tr.term_taxonomy_id = tt.term_taxonomy_id WHERE tt.taxonomy = 'category' AND tt.term_id IN ({$cat_string}) )";
     }
     // Category stuff for nice URLs
     if ('' != $q['category_name'] && !$this->is_singular) {
         $q['category_name'] = implode('/', array_map('sanitize_title', explode('/', $q['category_name'])));
         $reqcat = get_category_by_path($q['category_name']);
         $q['category_name'] = str_replace('%2F', '/', urlencode(urldecode($q['category_name'])));
         $cat_paths = '/' . trim($q['category_name'], '/');
         $q['category_name'] = sanitize_title(basename($cat_paths));
         $cat_paths = '/' . trim(urldecode($q['category_name']), '/');
         $q['category_name'] = sanitize_title(basename($cat_paths));
         $cat_paths = explode('/', $cat_paths);
         $cat_path = '';
         foreach ((array) $cat_paths as $pathdir) {
             $cat_path .= ($pathdir != '' ? '/' : '') . sanitize_title($pathdir);
         }
         //if we don't match the entire hierarchy fallback on just matching the nicename
         if (empty($reqcat)) {
             $reqcat = get_category_by_path($q['category_name'], false);
         }
         if (!empty($reqcat)) {
             $reqcat = $reqcat->term_id;
         } else {
             $reqcat = 0;
         }
         $q['cat'] = $reqcat;
         $join = " INNER JOIN {$wpdb->term_relationships} ON ({$wpdb->posts}.ID = {$wpdb->term_relationships}.object_id) INNER JOIN {$wpdb->term_taxonomy} ON ({$wpdb->term_relationships}.term_taxonomy_id = {$wpdb->term_taxonomy}.term_taxonomy_id) ";
         $whichcat = " AND {$wpdb->term_taxonomy}.taxonomy = 'category' ";
         $in_cats = array($q['cat']);
         $in_cats = array_merge($in_cats, get_term_children($q['cat'], 'category'));
         $in_cats = "'" . implode("', '", $in_cats) . "'";
         $whichcat .= "AND {$wpdb->term_taxonomy}.term_id IN ({$in_cats})";
         $groupby = "{$wpdb->posts}.ID";
     }
     // Tags
     if ('' != $q['tag']) {
         if (strpos($q['tag'], ',') !== false) {
             $tags = preg_split('/[,\\s]+/', $q['tag']);
             foreach ((array) $tags as $tag) {
                 $tag = sanitize_term_field('slug', $tag, 0, 'post_tag', 'db');
                 $q['tag_slug__in'][] = $tag;
             }
         } else {
             if (preg_match('/[+\\s]+/', $q['tag']) || !empty($q['cat'])) {
                 $tags = preg_split('/[+\\s]+/', $q['tag']);
                 foreach ((array) $tags as $tag) {
                     $tag = sanitize_term_field('slug', $tag, 0, 'post_tag', 'db');
                     $q['tag_slug__and'][] = $tag;
                 }
             } else {
                 $q['tag'] = sanitize_term_field('slug', $q['tag'], 0, 'post_tag', 'db');
                 $q['tag_slug__in'][] = $q['tag'];
             }
         }
     }
     if (!empty($q['category__in']) || !empty($q['meta_key']) || !empty($q['tag__in']) || !empty($q['tag_slug__in'])) {
         $groupby = "{$wpdb->posts}.ID";
     }
     if (!empty($q['tag__in']) && empty($q['cat'])) {
         $join = " INNER JOIN {$wpdb->term_relationships} ON ({$wpdb->posts}.ID = {$wpdb->term_relationships}.object_id) INNER JOIN {$wpdb->term_taxonomy} ON ({$wpdb->term_relationships}.term_taxonomy_id = {$wpdb->term_taxonomy}.term_taxonomy_id) ";
         $whichcat .= " AND {$wpdb->term_taxonomy}.taxonomy = 'post_tag' ";
         $include_tags = "'" . implode("', '", $q['tag__in']) . "'";
         $whichcat .= " AND {$wpdb->term_taxonomy}.term_id IN ({$include_tags}) ";
         $reqtag = term_exists($q['tag__in'][0], 'post_tag');
         if (!empty($reqtag)) {
             $q['tag_id'] = $reqtag['term_id'];
         }
     }
     if (!empty($q['tag_slug__in']) && empty($q['cat'])) {
         $join = " INNER JOIN {$wpdb->term_relationships} ON ({$wpdb->posts}.ID = {$wpdb->term_relationships}.object_id) INNER JOIN {$wpdb->term_taxonomy} ON ({$wpdb->term_relationships}.term_taxonomy_id = {$wpdb->term_taxonomy}.term_taxonomy_id) INNER JOIN {$wpdb->terms} ON ({$wpdb->term_taxonomy}.term_id = {$wpdb->terms}.term_id) ";
         $whichcat .= " AND {$wpdb->term_taxonomy}.taxonomy = 'post_tag' ";
         $include_tags = "'" . implode("', '", $q['tag_slug__in']) . "'";
         $whichcat .= " AND {$wpdb->terms}.slug IN ({$include_tags}) ";
         $reqtag = get_term_by('slug', $q['tag_slug__in'][0], 'post_tag');
         if (!empty($reqtag)) {
             $q['tag_id'] = $reqtag->term_id;
         }
     }
     if (!empty($q['tag__not_in'])) {
         $tag_string = "'" . implode("', '", $q['tag__not_in']) . "'";
         $whichcat .= " AND {$wpdb->posts}.ID NOT IN ( SELECT tr.object_id FROM {$wpdb->term_relationships} AS tr INNER JOIN {$wpdb->term_taxonomy} AS tt ON tr.term_taxonomy_id = tt.term_taxonomy_id WHERE tt.taxonomy = 'post_tag' AND tt.term_id IN ({$tag_string}) )";
     }
     // Tag and slug intersections.
     $intersections = array('category__and' => 'category', 'tag__and' => 'post_tag', 'tag_slug__and' => 'post_tag', 'tag__in' => 'post_tag', 'tag_slug__in' => 'post_tag');
     $tagin = array('tag__in', 'tag_slug__in');
     // These are used to make some exceptions below
     foreach ($intersections as $item => $taxonomy) {
         if (empty($q[$item])) {
             continue;
         }
         if (in_array($item, $tagin) && empty($q['cat'])) {
             continue;
         }
         // We should already have what we need if categories aren't being used
         if ($item != 'category__and') {
             $reqtag = term_exists($q[$item][0], 'post_tag');
             if (!empty($reqtag)) {
                 $q['tag_id'] = $reqtag['term_id'];
             }
         }
         if (in_array($item, array('tag_slug__and', 'tag_slug__in'))) {
             $taxonomy_field = 'slug';
         } else {
             $taxonomy_field = 'term_id';
         }
         $q[$item] = array_unique($q[$item]);
         $tsql = "SELECT p.ID FROM {$wpdb->posts} p INNER JOIN {$wpdb->term_relationships} tr ON (p.ID = tr.object_id) INNER JOIN {$wpdb->term_taxonomy} tt ON (tr.term_taxonomy_id = tt.term_taxonomy_id) INNER JOIN {$wpdb->terms} t ON (tt.term_id = t.term_id)";
         $tsql .= " WHERE tt.taxonomy = '{$taxonomy}' AND t.{$taxonomy_field} IN ('" . implode("', '", $q[$item]) . "')";
         if (!in_array($item, $tagin)) {
             // This next line is only helpful if we are doing an and relationship
             $tsql .= " GROUP BY p.ID HAVING count(p.ID) = " . count($q[$item]);
         }
         $post_ids = $wpdb->get_col($tsql);
         if (count($post_ids)) {
             $whichcat .= " AND {$wpdb->posts}.ID IN (" . implode(', ', $post_ids) . ") ";
         } else {
             $whichcat = " AND 0 = 1";
             break;
         }
     }
     // Taxonomies
     if ($this->is_tax) {
         if ('' != $q['taxonomy']) {
             $taxonomy = $q['taxonomy'];
             $tt[$taxonomy] = $q['term'];
         } else {
             foreach ($GLOBALS['wp_taxonomies'] as $taxonomy => $t) {
                 if ($t->query_var && '' != $q[$t->query_var]) {
                     $tt[$taxonomy] = $q[$t->query_var];
                     break;
                 }
             }
         }
         $terms = get_terms($taxonomy, array('slug' => $tt[$taxonomy], 'hide_empty' => !is_taxonomy_hierarchical($taxonomy)));
         if (is_wp_error($terms) || empty($terms)) {
             $whichcat = " AND 0 ";
         } else {
             foreach ($terms as $term) {
                 $term_ids[] = $term->term_id;
                 if (is_taxonomy_hierarchical($taxonomy)) {
                     $children = get_term_children($term->term_id, $taxonomy);
                     $term_ids = array_merge($term_ids, $children);
                 }
             }
             $post_ids = get_objects_in_term($term_ids, $taxonomy);
             if (!is_wp_error($post_ids) && !empty($post_ids)) {
                 $whichcat .= " AND {$wpdb->posts}.ID IN (" . implode(', ', $post_ids) . ") ";
                 if (empty($post_type)) {
                     $post_type = 'any';
                     $post_status_join = true;
                 } elseif (in_array('attachment', (array) $post_type)) {
                     $post_status_join = true;
                 }
             } else {
                 $whichcat = " AND 0 ";
             }
         }
     }
     // Author/user stuff
     if (empty($q['author']) || $q['author'] == '0') {
         $whichauthor = '';
     } else {
         $q['author'] = (string) urldecode($q['author']);
         $q['author'] = addslashes_gpc($q['author']);
         if (strpos($q['author'], '-') !== false) {
             $eq = '!=';
             $andor = 'AND';
             $q['author'] = explode('-', $q['author']);
             $q['author'] = (string) absint($q['author'][1]);
         } else {
             $eq = '=';
             $andor = 'OR';
         }
         $author_array = preg_split('/[,\\s]+/', $q['author']);
         $_author_array = array();
         foreach ($author_array as $key => $_author) {
             $_author_array[] = "{$wpdb->posts}.post_author " . $eq . ' ' . absint($_author);
         }
         $whichauthor .= ' AND (' . implode(" {$andor} ", $_author_array) . ')';
         unset($author_array, $_author_array);
     }
     // Author stuff for nice URLs
     if ('' != $q['author_name']) {
         if (strpos($q['author_name'], '/') !== false) {
             $q['author_name'] = explode('/', $q['author_name']);
             if ($q['author_name'][count($q['author_name']) - 1]) {
                 $q['author_name'] = $q['author_name'][count($q['author_name']) - 1];
                 // no trailing slash
             } else {
                 $q['author_name'] = $q['author_name'][count($q['author_name']) - 2];
                 // there was a trailling slash
             }
         }
         $q['author_name'] = sanitize_title($q['author_name']);
         $q['author'] = get_user_by('slug', $q['author_name']);
         if ($q['author']) {
             $q['author'] = $q['author']->ID;
         }
         $whichauthor .= " AND ({$wpdb->posts}.post_author = " . absint($q['author']) . ')';
     }
     // MIME-Type stuff for attachment browsing
     if (isset($q['post_mime_type']) && '' != $q['post_mime_type']) {
         $table_alias = $post_status_join ? $wpdb->posts : '';
         $whichmimetype = wp_post_mime_type_where($q['post_mime_type'], $table_alias);
     }
     $where .= $search . $whichcat . $whichauthor . $whichmimetype;
     if (empty($q['order']) || strtoupper($q['order']) != 'ASC' && strtoupper($q['order']) != 'DESC') {
         $q['order'] = 'DESC';
     }
     // Order by
     if (empty($q['orderby'])) {
         $q['orderby'] = "{$wpdb->posts}.post_date " . $q['order'];
     } elseif ('none' == $q['orderby']) {
         $q['orderby'] = '';
     } else {
         // Used to filter values
         $allowed_keys = array('author', 'date', 'title', 'modified', 'menu_order', 'parent', 'ID', 'rand', 'comment_count');
         if (!empty($q['meta_key'])) {
             $allowed_keys[] = $q['meta_key'];
             $allowed_keys[] = 'meta_value';
             $allowed_keys[] = 'meta_value_num';
         }
         $q['orderby'] = urldecode($q['orderby']);
         $q['orderby'] = addslashes_gpc($q['orderby']);
         $orderby_array = explode(' ', $q['orderby']);
         $q['orderby'] = '';
         foreach ($orderby_array as $i => $orderby) {
             // Only allow certain values for safety
             if (!in_array($orderby, $allowed_keys)) {
                 continue;
             }
             switch ($orderby) {
                 case 'menu_order':
                     break;
                 case 'ID':
                     $orderby = "{$wpdb->posts}.ID";
                     break;
                 case 'rand':
                     $orderby = 'RAND()';
                     break;
                 case $q['meta_key']:
                 case 'meta_value':
                     $orderby = "{$wpdb->postmeta}.meta_value";
                     break;
                 case 'meta_value_num':
                     $orderby = "{$wpdb->postmeta}.meta_value+0";
                     break;
                 case 'comment_count':
                     $orderby = "{$wpdb->posts}.comment_count";
                     break;
                 default:
                     $orderby = "{$wpdb->posts}.post_" . $orderby;
             }
             $q['orderby'] .= ($i == 0 ? '' : ',') . $orderby;
         }
         // append ASC or DESC at the end
         if (!empty($q['orderby'])) {
             $q['orderby'] .= " {$q['order']}";
         }
         if (empty($q['orderby'])) {
             $q['orderby'] = "{$wpdb->posts}.post_date " . $q['order'];
         }
     }
     if (is_array($post_type)) {
         $post_type_cap = 'multiple_post_type';
     } else {
         $post_type_object = get_post_type_object($post_type);
         if (!empty($post_type_object)) {
             $post_type_cap = $post_type_object->capability_type;
         } else {
             $post_type_cap = $post_type;
         }
     }
     $exclude_post_types = '';
     $in_search_post_types = get_post_types(array('exclude_from_search' => false));
     if (!empty($in_search_post_types)) {
         $exclude_post_types .= $wpdb->prepare(" AND {$wpdb->posts}.post_type IN ('" . join("', '", $in_search_post_types) . "')");
     }
     if ('any' == $post_type) {
         $where .= $exclude_post_types;
     } elseif (!empty($post_type) && is_array($post_type)) {
         $where .= " AND {$wpdb->posts}.post_type IN ('" . join("', '", $post_type) . "')";
     } elseif (!empty($post_type)) {
         $where .= " AND {$wpdb->posts}.post_type = '{$post_type}'";
         $post_type_object = get_post_type_object($post_type);
     } elseif ($this->is_attachment) {
         $where .= " AND {$wpdb->posts}.post_type = 'attachment'";
         $post_type_object = get_post_type_object('attachment');
     } elseif ($this->is_page) {
         $where .= " AND {$wpdb->posts}.post_type = 'page'";
         $post_type_object = get_post_type_object('page');
     } else {
         $where .= " AND {$wpdb->posts}.post_type = 'post'";
         $post_type_object = get_post_type_object('post');
     }
     if (!empty($post_type_object)) {
         $post_type_cap = $post_type_object->capability_type;
         $edit_cap = $post_type_object->cap->edit_post;
         $read_cap = $post_type_object->cap->read_post;
         $edit_others_cap = $post_type_object->cap->edit_others_posts;
         $read_private_cap = $post_type_object->cap->read_private_posts;
     } else {
         $edit_cap = 'edit_' . $post_type_cap;
         $read_cap = 'read_' . $post_type_cap;
         $edit_others_cap = 'edit_others_' . $post_type_cap . 's';
         $read_private_cap = 'read_private_' . $post_type_cap . 's';
     }
     if (isset($q['post_status']) && '' != $q['post_status']) {
         $statuswheres = array();
         $q_status = explode(',', $q['post_status']);
         $r_status = array();
         $p_status = array();
         $e_status = array();
         if ($q['post_status'] == 'any') {
             foreach (get_post_stati(array('exclude_from_search' => true)) as $status) {
                 $e_status[] = "{$wpdb->posts}.post_status <> '{$status}'";
             }
         } else {
             foreach (get_post_stati() as $status) {
                 if (in_array($status, $q_status)) {
                     if ('private' == $status) {
                         $p_status[] = "{$wpdb->posts}.post_status = '{$status}'";
                     } else {
                         $r_status[] = "{$wpdb->posts}.post_status = '{$status}'";
                     }
                 }
             }
         }
         if (empty($q['perm']) || 'readable' != $q['perm']) {
             $r_status = array_merge($r_status, $p_status);
             unset($p_status);
         }
         if (!empty($e_status)) {
             $statuswheres[] = "(" . join(' AND ', $e_status) . ")";
         }
         if (!empty($r_status)) {
             if (!empty($q['perm']) && 'editable' == $q['perm'] && !current_user_can($edit_others_cap)) {
                 $statuswheres[] = "({$wpdb->posts}.post_author = {$user_ID} " . "AND (" . join(' OR ', $r_status) . "))";
             } else {
                 $statuswheres[] = "(" . join(' OR ', $r_status) . ")";
             }
         }
         if (!empty($p_status)) {
             if (!empty($q['perm']) && 'readable' == $q['perm'] && !current_user_can($read_private_cap)) {
                 $statuswheres[] = "({$wpdb->posts}.post_author = {$user_ID} " . "AND (" . join(' OR ', $p_status) . "))";
             } else {
                 $statuswheres[] = "(" . join(' OR ', $p_status) . ")";
             }
         }
         if ($post_status_join) {
             $join .= " LEFT JOIN {$wpdb->posts} AS p2 ON ({$wpdb->posts}.post_parent = p2.ID) ";
             foreach ($statuswheres as $index => $statuswhere) {
                 $statuswheres[$index] = "({$statuswhere} OR ({$wpdb->posts}.post_status = 'inherit' AND " . str_replace($wpdb->posts, 'p2', $statuswhere) . "))";
             }
         }
         foreach ($statuswheres as $statuswhere) {
             $where .= " AND {$statuswhere}";
         }
     } elseif (!$this->is_singular) {
         $where .= " AND ({$wpdb->posts}.post_status = 'publish'";
         // Add public states.
         $public_states = get_post_stati(array('public' => true));
         foreach ((array) $public_states as $state) {
             if ('publish' == $state) {
                 // Publish is hard-coded above.
                 continue;
             }
             $where .= " OR {$wpdb->posts}.post_status = '{$state}'";
         }
         if (is_admin()) {
             // Add protected states that should show in the admin all list.
             $admin_all_states = get_post_stati(array('protected' => true, 'show_in_admin_all_list' => true));
             foreach ((array) $admin_all_states as $state) {
                 $where .= " OR {$wpdb->posts}.post_status = '{$state}'";
             }
         }
         if (is_user_logged_in()) {
             // Add private states that are limited to viewing by the author of a post or someone who has caps to read private states.
             $private_states = get_post_stati(array('private' => true));
             foreach ((array) $private_states as $state) {
                 $where .= current_user_can($read_private_cap) ? " OR {$wpdb->posts}.post_status = '{$state}'" : " OR {$wpdb->posts}.post_author = {$user_ID} AND {$wpdb->posts}.post_status = '{$state}'";
             }
         }
         $where .= ')';
     }
     // postmeta queries
     if (!empty($q['meta_key']) || !empty($q['meta_value'])) {
         $join .= " JOIN {$wpdb->postmeta} ON ({$wpdb->posts}.ID = {$wpdb->postmeta}.post_id) ";
     }
     if (!empty($q['meta_key'])) {
         $where .= $wpdb->prepare(" AND {$wpdb->postmeta}.meta_key = %s ", $q['meta_key']);
     }
     if (!empty($q['meta_value'])) {
         if (empty($q['meta_compare']) || !in_array($q['meta_compare'], array('=', '!=', '>', '>=', '<', '<='))) {
             $q['meta_compare'] = '=';
         }
         $where .= $wpdb->prepare("AND {$wpdb->postmeta}.meta_value {$q['meta_compare']} %s ", $q['meta_value']);
     }
     // Apply filters on where and join prior to paging so that any
     // manipulations to them are reflected in the paging by day queries.
     if (!$q['suppress_filters']) {
         $where = apply_filters_ref_array('posts_where', array($where, &$this));
         $join = apply_filters_ref_array('posts_join', array($join, &$this));
     }
     // Paging
     if (empty($q['nopaging']) && !$this->is_singular) {
         $page = absint($q['paged']);
         if (empty($page)) {
             $page = 1;
         }
         if (empty($q['offset'])) {
             $pgstrt = '';
             $pgstrt = ($page - 1) * $q['posts_per_page'] . ', ';
             $limits = 'LIMIT ' . $pgstrt . $q['posts_per_page'];
         } else {
             // we're ignoring $page and using 'offset'
             $q['offset'] = absint($q['offset']);
             $pgstrt = $q['offset'] . ', ';
             $limits = 'LIMIT ' . $pgstrt . $q['posts_per_page'];
         }
     }
     // Comments feeds
     if ($this->is_comment_feed && ($this->is_archive || $this->is_search || !$this->is_singular)) {
         if ($this->is_archive || $this->is_search) {
             $cjoin = "JOIN {$wpdb->posts} ON ({$wpdb->comments}.comment_post_ID = {$wpdb->posts}.ID) {$join} ";
             $cwhere = "WHERE comment_approved = '1' {$where}";
             $cgroupby = "{$wpdb->comments}.comment_id";
         } else {
             // Other non singular e.g. front
             $cjoin = "JOIN {$wpdb->posts} ON ( {$wpdb->comments}.comment_post_ID = {$wpdb->posts}.ID )";
             $cwhere = "WHERE post_status = 'publish' AND comment_approved = '1'";
             $cgroupby = '';
         }
         if (!$q['suppress_filters']) {
             $cjoin = apply_filters_ref_array('comment_feed_join', array($cjoin, &$this));
             $cwhere = apply_filters_ref_array('comment_feed_where', array($cwhere, &$this));
             $cgroupby = apply_filters_ref_array('comment_feed_groupby', array($cgroupby, &$this));
             $corderby = apply_filters_ref_array('comment_feed_orderby', array('comment_date_gmt DESC', &$this));
             $climits = apply_filters_ref_array('comment_feed_limits', array('LIMIT ' . get_option('posts_per_rss'), &$this));
         }
         $cgroupby = !empty($cgroupby) ? 'GROUP BY ' . $cgroupby : '';
         $corderby = !empty($corderby) ? 'ORDER BY ' . $corderby : '';
         $this->comments = (array) $wpdb->get_results("SELECT {$distinct} {$wpdb->comments}.* FROM {$wpdb->comments} {$cjoin} {$cwhere} {$cgroupby} {$corderby} {$climits}");
         $this->comment_count = count($this->comments);
         $post_ids = array();
         foreach ($this->comments as $comment) {
             $post_ids[] = (int) $comment->comment_post_ID;
         }
         $post_ids = join(',', $post_ids);
         $join = '';
         if ($post_ids) {
             $where = "AND {$wpdb->posts}.ID IN ({$post_ids}) ";
         } else {
             $where = "AND 0";
         }
     }
     $orderby = $q['orderby'];
     // Apply post-paging filters on where and join.  Only plugins that
     // manipulate paging queries should use these hooks.
     if (!$q['suppress_filters']) {
         $where = apply_filters_ref_array('posts_where_paged', array($where, &$this));
         $groupby = apply_filters_ref_array('posts_groupby', array($groupby, &$this));
         $join = apply_filters_ref_array('posts_join_paged', array($join, &$this));
         $orderby = apply_filters_ref_array('posts_orderby', array($orderby, &$this));
         $distinct = apply_filters_ref_array('posts_distinct', array($distinct, &$this));
         $limits = apply_filters_ref_array('post_limits', array($limits, &$this));
         $fields = apply_filters_ref_array('posts_fields', array($fields, &$this));
     }
     // Announce current selection parameters.  For use by caching plugins.
     do_action('posts_selection', $where . $groupby . $orderby . $limits . $join);
     // Filter again for the benefit of caching plugins.  Regular plugins should use the hooks above.
     if (!$q['suppress_filters']) {
         $where = apply_filters_ref_array('posts_where_request', array($where, &$this));
         $groupby = apply_filters_ref_array('posts_groupby_request', array($groupby, &$this));
         $join = apply_filters_ref_array('posts_join_request', array($join, &$this));
         $orderby = apply_filters_ref_array('posts_orderby_request', array($orderby, &$this));
         $distinct = apply_filters_ref_array('posts_distinct_request', array($distinct, &$this));
         $fields = apply_filters_ref_array('posts_fields_request', array($fields, &$this));
         $limits = apply_filters_ref_array('post_limits_request', array($limits, &$this));
     }
     if (!empty($groupby)) {
         $groupby = 'GROUP BY ' . $groupby;
     }
     if (!empty($orderby)) {
         $orderby = 'ORDER BY ' . $orderby;
     }
     $found_rows = '';
     if (!$q['no_found_rows'] && !empty($limits)) {
         $found_rows = 'SQL_CALC_FOUND_ROWS';
     }
     $this->request = " SELECT {$found_rows} {$distinct} {$fields} FROM {$wpdb->posts} {$join} WHERE 1=1 {$where} {$groupby} {$orderby} {$limits}";
     if (!$q['suppress_filters']) {
         $this->request = apply_filters_ref_array('posts_request', array($this->request, &$this));
     }
     $this->posts = $wpdb->get_results($this->request);
     // Raw results filter.  Prior to status checks.
     if (!$q['suppress_filters']) {
         $this->posts = apply_filters_ref_array('posts_results', array($this->posts, &$this));
     }
     if (!empty($this->posts) && $this->is_comment_feed && $this->is_singular) {
         $cjoin = apply_filters_ref_array('comment_feed_join', array('', &$this));
         $cwhere = apply_filters_ref_array('comment_feed_where', array("WHERE comment_post_ID = '{$this->posts[0]->ID}' AND comment_approved = '1'", &$this));
         $cgroupby = apply_filters_ref_array('comment_feed_groupby', array('', &$this));
         $cgroupby = !empty($cgroupby) ? 'GROUP BY ' . $cgroupby : '';
         $corderby = apply_filters_ref_array('comment_feed_orderby', array('comment_date_gmt DESC', &$this));
         $corderby = !empty($corderby) ? 'ORDER BY ' . $corderby : '';
         $climits = apply_filters_ref_array('comment_feed_limits', array('LIMIT ' . get_option('posts_per_rss'), &$this));
         $comments_request = "SELECT {$wpdb->comments}.* FROM {$wpdb->comments} {$cjoin} {$cwhere} {$cgroupby} {$corderby} {$climits}";
         $this->comments = $wpdb->get_results($comments_request);
         $this->comment_count = count($this->comments);
     }
     if (!$q['no_found_rows'] && !empty($limits)) {
         $found_posts_query = apply_filters_ref_array('found_posts_query', array('SELECT FOUND_ROWS()', &$this));
         $this->found_posts = $wpdb->get_var($found_posts_query);
         $this->found_posts = apply_filters_ref_array('found_posts', array($this->found_posts, &$this));
         $this->max_num_pages = ceil($this->found_posts / $q['posts_per_page']);
     }
     // Check post status to determine if post should be displayed.
     if (!empty($this->posts) && ($this->is_single || $this->is_page)) {
         $status = get_post_status($this->posts[0]);
         $post_status_obj = get_post_status_object($status);
         //$type = get_post_type($this->posts[0]);
         if (!$post_status_obj->public) {
             if (!is_user_logged_in()) {
                 // User must be logged in to view unpublished posts.
                 $this->posts = array();
             } else {
                 if ($post_status_obj->protected) {
                     // User must have edit permissions on the draft to preview.
                     if (!current_user_can($edit_cap, $this->posts[0]->ID)) {
                         $this->posts = array();
                     } else {
                         $this->is_preview = true;
                         if ('future' != $status) {
                             $this->posts[0]->post_date = current_time('mysql');
                         }
                     }
                 } elseif ($post_status_obj->private) {
                     if (!current_user_can($read_cap, $this->posts[0]->ID)) {
                         $this->posts = array();
                     }
                 } else {
                     $this->posts = array();
                 }
             }
         }
         if ($this->is_preview && current_user_can($edit_cap, $this->posts[0]->ID)) {
             $this->posts[0] = apply_filters_ref_array('the_preview', array($this->posts[0], &$this));
         }
     }
     // Put sticky posts at the top of the posts array
     $sticky_posts = get_option('sticky_posts');
     if ($this->is_home && $page <= 1 && is_array($sticky_posts) && !empty($sticky_posts) && !$q['caller_get_posts']) {
         $num_posts = count($this->posts);
         $sticky_offset = 0;
         // Loop over posts and relocate stickies to the front.
         for ($i = 0; $i < $num_posts; $i++) {
             if (in_array($this->posts[$i]->ID, $sticky_posts)) {
                 $sticky_post = $this->posts[$i];
                 // Remove sticky from current position
                 array_splice($this->posts, $i, 1);
                 // Move to front, after other stickies
                 array_splice($this->posts, $sticky_offset, 0, array($sticky_post));
                 // Increment the sticky offset.  The next sticky will be placed at this offset.
                 $sticky_offset++;
                 // Remove post from sticky posts array
                 $offset = array_search($sticky_post->ID, $sticky_posts);
                 unset($sticky_posts[$offset]);
             }
         }
         // If any posts have been excluded specifically, Ignore those that are sticky.
         if (!empty($sticky_posts) && !empty($q['post__not_in'])) {
             $sticky_posts = array_diff($sticky_posts, $q['post__not_in']);
         }
         // Fetch sticky posts that weren't in the query results
         if (!empty($sticky_posts)) {
             $stickies__in = implode(',', array_map('absint', $sticky_posts));
             // honor post type(s) if not set to any
             $stickies_where = '';
             if ('any' != $post_type && '' != $post_type) {
                 if (is_array($post_type)) {
                     $post_types = join("', '", $post_type);
                 } else {
                     $post_types = $post_type;
                 }
                 $stickies_where = "AND {$wpdb->posts}.post_type IN ('" . $post_types . "')";
             }
             $stickies = $wpdb->get_results("SELECT * FROM {$wpdb->posts} WHERE {$wpdb->posts}.ID IN ({$stickies__in}) {$stickies_where}");
             foreach ($stickies as $sticky_post) {
                 // Ignore sticky posts the current user cannot read or are not published.
                 if ('publish' != $sticky_post->post_status) {
                     continue;
                 }
                 array_splice($this->posts, $sticky_offset, 0, array($sticky_post));
                 $sticky_offset++;
             }
         }
     }
     if (!$q['suppress_filters']) {
         $this->posts = apply_filters_ref_array('the_posts', array($this->posts, &$this));
     }
     $this->post_count = count($this->posts);
     // Sanitize before caching so it'll only get done once
     for ($i = 0; $i < $this->post_count; $i++) {
         $this->posts[$i] = sanitize_post($this->posts[$i], 'raw');
     }
     if ($q['cache_results']) {
         update_post_caches($this->posts, $post_type, $q['update_post_term_cache'], $q['update_post_meta_cache']);
     }
     if ($this->post_count > 0) {
         $this->post = $this->posts[0];
     }
     return $this->posts;
 }
 public function save_job($job_id, WP_Post $job)
 {
     $bbl_post_public = Babble::get('post_public');
     $bbl_taxonomies = Babble::get('taxonomies');
     if ($this->no_recursion) {
         return;
     }
     if ('bbl_job' != $job->post_type) {
         return;
     }
     $edit_post_nonce = isset($_POST['_bbl_translation_edit_post']) ? $_POST['_bbl_translation_edit_post'] : false;
     $edit_terms_nonce = isset($_POST['_bbl_translation_edit_terms']) ? $_POST['_bbl_translation_edit_terms'] : false;
     $edit_meta_nonce = isset($_POST['_bbl_translation_edit_meta']) ? $_POST['_bbl_translation_edit_meta'] : false;
     $origin_post_nonce = isset($_POST['_bbl_translation_origin_post']) ? $_POST['_bbl_translation_origin_post'] : false;
     $origin_term_nonce = isset($_POST['_bbl_translation_origin_term']) ? $_POST['_bbl_translation_origin_term'] : false;
     $lang_code_nonce = isset($_POST['_bbl_translation_lang_code']) ? $_POST['_bbl_translation_lang_code'] : false;
     if ($lang_code_nonce and wp_verify_nonce($lang_code_nonce, "bbl_translation_lang_code_{$job->ID}")) {
         wp_set_object_terms($job->ID, stripslashes(sanitize_text_field($_POST['bbl_lang_code'])), 'bbl_job_language', false);
     }
     $language = get_the_terms($job, 'bbl_job_language');
     if (empty($language)) {
         return false;
     } else {
         $lang_code = reset($language)->name;
     }
     $objects = $this->get_job_objects($job);
     if ($origin_post_nonce and wp_verify_nonce($origin_post_nonce, "bbl_translation_origin_post_{$job->ID}")) {
         if ($origin_post = get_post(absint($_POST['bbl_origin_post']))) {
             add_post_meta($job->ID, 'bbl_job_post', "{$origin_post->post_type}|{$origin_post->ID}", true);
             foreach ($this->get_post_terms_to_translate($origin_post, $lang_code) as $taxo => $terms) {
                 foreach ($terms as $term_id => $term) {
                     add_post_meta($job->ID, 'bbl_job_term', "{$taxo}|{$term_id}", false);
                 }
             }
             foreach ($this->get_post_meta_to_translate($origin_post, $lang_code) as $key => $field) {
                 add_post_meta($job->ID, 'bbl_job_meta', $key, false);
             }
         }
         # @TODO else wp_die()?
     }
     # @TODO not implemented:
     if ($origin_term_nonce and wp_verify_nonce($origin_term_nonce, "bbl_translation_origin_term_{$job->ID}")) {
         if ($origin_term = get_term(absint($_POST['bbl_origin_term']), $_POST['bbl_origin_taxonomy'])) {
             add_post_meta($job->ID, 'bbl_job_term', "{$origin_term->taxonomy}|{$origin_term->term_id}", false);
         }
         # @TODO else wp_die()?
     }
     if ($edit_post_nonce and wp_verify_nonce($edit_post_nonce, "bbl_translation_edit_post_{$job->ID}")) {
         $post_data = stripslashes_deep($_POST['bbl_translation']['post']);
         if ($post_data['post_name']) {
             $post_data['post_name'] = sanitize_title($post_data['post_name']);
         }
         $post_info = get_post_meta($job->ID, 'bbl_job_post', true);
         list($post_type, $post_id) = explode('|', $post_info);
         $post = get_post($post_id);
         update_post_meta($job->ID, "bbl_post_{$post_id}", sanitize_post($post_data, 'db'));
         if ('pending' == $job->post_status) {
             # Nothing.
         }
         if ('complete' == $job->post_status) {
             # The ability to complete a translation of a post directly
             # maps to the ability to publish the origin post.
             if (current_user_can('publish_post', $job->ID)) {
                 if (!($trans = $bbl_post_public->get_post_in_lang($post, $lang_code, false))) {
                     $trans = $bbl_post_public->initialise_translation($post, $lang_code);
                 }
                 $post_data['ID'] = $trans->ID;
                 $post_data['post_status'] = $post->post_status;
                 $this->no_recursion = true;
                 wp_update_post($post_data, true);
                 $this->no_recursion = false;
             } else {
                 # Just in case. Switch the job back to in-progress status.
                 # It would be nice to be able to use the 'publish' status because then we get the built-in
                 # publish_post cap checks, but we can't control the post status label on a per-post-type basis yet.
                 $this->no_recursion = true;
                 wp_update_post(array('ID' => $job->ID, 'post_status' => 'in-progress'), true);
                 $this->no_recursion = false;
             }
         }
         if ($edit_meta_nonce and wp_verify_nonce($edit_meta_nonce, "bbl_translation_edit_meta_{$job->ID}")) {
             $meta_data = stripslashes_deep($_POST['bbl_translation']['meta']);
             if (true === is_array($meta_data)) {
                 array_walk_recursive($meta_data, array($this, 'wp_kses_post_by_reference'));
             } else {
                 $meta_data = sanitize_text_field($meta_data);
             }
             foreach ($objects['meta'] as $meta_key => $meta_field) {
                 $value = apply_filters('bbl_meta_before_save', $meta_data[$meta_key], $job, $meta_key, $meta_field, $meta_data);
                 update_post_meta($job->ID, "bbl_meta_{$meta_key}", $value);
                 if ('complete' == $job->post_status) {
                     if (current_user_can('publish_post', $job->ID)) {
                         update_post_meta($trans->ID, $meta_key, $value);
                     }
                 }
             }
         }
     }
     if ($edit_terms_nonce and wp_verify_nonce($edit_terms_nonce, "bbl_translation_edit_terms_{$job->ID}")) {
         $terms_data = stripslashes_deep($_POST['bbl_translation']['terms']);
         if (true === is_array($terms_data)) {
             array_walk_recursive($terms_data, array($this, 'sanitize_text_field_by_reference'));
         } else {
             $terms_data = sanitize_text_field($terms_data);
         }
         $job_terms = $objects['terms'];
         foreach ($job_terms as $taxo => $terms) {
             foreach ($terms as $term_info) {
                 $term_id = $term_info->term_id;
                 $term = get_term($term_id, $taxo);
                 if (true === is_wp_error($term)) {
                     continue;
                 }
                 $terms_data[$term_id]['slug'] = sanitize_title($terms_data[$term_id]['slug']);
                 update_post_meta($job->ID, "bbl_term_{$term_id}", $terms_data[$term_id]);
                 if ('complete' == $job->post_status) {
                     # @TODO if current user can edit term
                     $trans = $bbl_taxonomies->get_term_in_lang($term, $taxo, $lang_code, false);
                     if (!$trans) {
                         $trans = $bbl_taxonomies->initialise_translation($term, $taxo, $lang_code);
                     }
                     $terms_data[$term->term_id]['term_id'] = $trans->term_id;
                     $args = array('name' => wp_kses_post($terms_data[$term->term_id]['name']), 'slug' => '');
                     wp_update_term(absint($trans->term_id), $trans->taxonomy, $args);
                 }
             }
         }
     }
 }
function pmxi_insert_attachment($object, $file = false, $parent = 0)
{
    global $wpdb;
    $user_id = get_current_user_id();
    $defaults = array('post_status' => 'inherit', 'post_type' => 'post', 'post_author' => $user_id, 'ping_status' => get_option('default_ping_status'), 'post_parent' => 0, 'post_title' => '', 'menu_order' => 0, 'to_ping' => '', 'pinged' => '', 'post_password' => '', 'post_content' => '', 'guid' => '', 'post_content_filtered' => '', 'post_excerpt' => '', 'import_id' => 0, 'context' => '');
    $object = wp_parse_args($object, $defaults);
    if (!empty($parent)) {
        $object['post_parent'] = $parent;
    }
    unset($object['filter']);
    $object = sanitize_post($object, 'db');
    // export array as variables
    extract($object, EXTR_SKIP);
    if (empty($post_author)) {
        $post_author = $user_id;
    }
    $post_type = 'attachment';
    if (!in_array($post_status, array('inherit', 'private'))) {
        $post_status = 'inherit';
    }
    if (!empty($post_category)) {
        $post_category = array_filter($post_category);
    }
    // Filter out empty terms
    // Make sure we set a valid category.
    if (empty($post_category) || 0 == count($post_category) || !is_array($post_category)) {
        $post_category = array();
    }
    // Are we updating or creating?
    if (!empty($ID)) {
        $update = true;
        $post_ID = (int) $ID;
    } else {
        $update = false;
        $post_ID = 0;
    }
    // Create a valid post name.
    if (empty($post_name)) {
        $post_name = sanitize_title($post_title);
    } else {
        $post_name = sanitize_title($post_name);
    }
    // expected_slashed ($post_name)
    $post_name = wp_unique_post_slug($post_name, $post_ID, $post_status, $post_type, $post_parent);
    if (empty($post_date)) {
        $post_date = current_time('mysql');
    }
    if (empty($post_date_gmt)) {
        $post_date_gmt = current_time('mysql', 1);
    }
    if (empty($post_modified)) {
        $post_modified = $post_date;
    }
    if (empty($post_modified_gmt)) {
        $post_modified_gmt = $post_date_gmt;
    }
    if (empty($comment_status)) {
        if ($update) {
            $comment_status = 'closed';
        } else {
            $comment_status = get_option('default_comment_status');
        }
    }
    if (empty($ping_status)) {
        $ping_status = get_option('default_ping_status');
    }
    if (isset($to_ping)) {
        $to_ping = preg_replace('|\\s+|', "\n", $to_ping);
    } else {
        $to_ping = '';
    }
    if (isset($post_parent)) {
        $post_parent = (int) $post_parent;
    } else {
        $post_parent = 0;
    }
    if (isset($menu_order)) {
        $menu_order = (int) $menu_order;
    } else {
        $menu_order = 0;
    }
    if (!isset($post_password)) {
        $post_password = '';
    }
    if (!isset($pinged)) {
        $pinged = '';
    }
    // expected_slashed (everything!)
    $data = compact(array('post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_content_filtered', 'post_title', 'post_excerpt', 'post_status', 'post_type', 'comment_status', 'ping_status', 'post_password', 'post_name', 'to_ping', 'pinged', 'post_modified', 'post_modified_gmt', 'post_parent', 'menu_order', 'post_mime_type', 'guid'));
    $data = wp_unslash($data);
    if ($update) {
        $wpdb->update($wpdb->posts, $data, array('ID' => $post_ID));
    } else {
        // If there is a suggested ID, use it if not already present
        if (!empty($import_id)) {
            $import_id = (int) $import_id;
            if (!$wpdb->get_var($wpdb->prepare("SELECT ID FROM {$wpdb->posts} WHERE ID = %d", $import_id))) {
                $data['ID'] = $import_id;
            }
        }
        $wpdb->insert($wpdb->posts, $data);
        $post_ID = (int) $wpdb->insert_id;
    }
    if (empty($post_name)) {
        $post_name = sanitize_title($post_title, $post_ID);
        $wpdb->update($wpdb->posts, compact("post_name"), array('ID' => $post_ID));
    }
    if ($file) {
        update_attached_file($post_ID, $file);
    }
    clean_post_cache($post_ID);
    if (!empty($context)) {
        add_post_meta($post_ID, '_wp_attachment_context', $context, true);
    }
    return $post_ID;
}
/**
 * Sets up the post object for preview based on the post autosave.
 *
 * @since 2.7.0
 * @access private
 *
 * @param WP_Post $post
 * @return WP_Post|false
 */
function _set_preview($post)
{
    if (!is_object($post)) {
        return $post;
    }
    $preview = wp_get_post_autosave($post->ID);
    if (!is_object($preview)) {
        return $post;
    }
    $preview = sanitize_post($preview);
    $post->post_content = $preview->post_content;
    $post->post_title = $preview->post_title;
    $post->post_excerpt = $preview->post_excerpt;
    add_filter('get_the_terms', '_wp_preview_terms_filter', 10, 3);
    return $post;
}
 function the_posts($posts)
 {
     if (!is_admin() && isset($this->settings['show_untranslated_blog_posts']) && $this->settings['show_untranslated_blog_posts'] && $this->get_current_language() != $this->get_default_language()) {
         // show untranslated posts
         global $wpdb, $wp_query;
         $default_language = $this->get_default_language();
         $current_language = $this->get_current_language();
         $debug_backtrace = $this->get_backtrace(4, true);
         //Limit to first 4 stack frames, since 3 is the highest index we use
         /** @var $custom_wp_query WP_Query */
         $custom_wp_query = isset($debug_backtrace[3]['object']) ? $debug_backtrace[3]['object'] : false;
         //exceptions
         if ($current_language == $default_language || $wp_query != $custom_wp_query || !$custom_wp_query->is_posts_page && !$custom_wp_query->is_home || $wp_query->is_singular || !empty($custom_wp_query->query_vars['category__not_in']) || !empty($custom_wp_query->query_vars['tag__not_in']) || !empty($custom_wp_query->query_vars['post__in']) || !empty($custom_wp_query->query_vars['post__not_in']) || !empty($custom_wp_query->query_vars['post_parent'])) {
             return $posts;
         }
         // get the posts in the default language instead
         $this_lang = $this->this_lang;
         $this->this_lang = $default_language;
         remove_filter('the_posts', array($this, 'the_posts'));
         $custom_wp_query->query_vars['suppress_filters'] = 0;
         if (isset($custom_wp_query->query_vars['pagename']) && !empty($custom_wp_query->query_vars['pagename'])) {
             if (isset($custom_wp_query->queried_object_id) && !empty($custom_wp_query->queried_object_id)) {
                 $page_id = $custom_wp_query->queried_object_id;
             } else {
                 // urlencode added for languages that have urlencoded post_name field value
                 $custom_wp_query->query_vars['pagename'] = urlencode($custom_wp_query->query_vars['pagename']);
                 $page_id = $wpdb->get_var("SELECT ID FROM {$wpdb->posts} WHERE post_name='{$custom_wp_query->query_vars['pagename']}' AND post_type='page'");
             }
             if ($page_id) {
                 $tr_page_id = icl_object_id($page_id, 'page', false, $default_language);
                 if ($tr_page_id) {
                     $custom_wp_query->query_vars['pagename'] = $wpdb->get_var("SELECT post_name FROM {$wpdb->posts} WHERE ID={$tr_page_id}");
                 }
             }
         }
         // look for posts without translations
         if ($posts) {
             $pids = false;
             foreach ($posts as $p) {
                 $pids[] = $p->ID;
             }
             if ($pids) {
                 $trids = $wpdb->get_col("\r\n\t\t\t\t\t\tSELECT trid\r\n\t\t\t\t\t\tFROM {$wpdb->prefix}icl_translations\r\n\t\t\t\t\t\tWHERE element_type='post_post' AND element_id IN (" . join(',', $pids) . ") AND language_code = '" . $this_lang . "'");
                 if (!empty($trids)) {
                     $posts_not_translated = $wpdb->get_col("\r\n\t\t\t\t\t\t\tSELECT element_id, COUNT(language_code) AS c\r\n\t\t\t\t\t\t\tFROM {$wpdb->prefix}icl_translations\r\n\t\t\t\t\t\t\tWHERE trid IN (" . join(',', $trids) . ") GROUP BY trid HAVING c = 1\r\n\t\t\t\t\t\t");
                     if (!empty($posts_not_translated)) {
                         $GLOBALS['__icl_the_posts_posts_not_translated'] = $posts_not_translated;
                         add_filter('posts_where', array($this, '_posts_untranslated_extra_posts_where'), 99);
                     }
                 }
             }
         }
         //fix page for posts
         unset($custom_wp_query->query_vars['pagename']);
         unset($custom_wp_query->query_vars['page_id']);
         unset($custom_wp_query->query_vars['p']);
         $my_query = new WP_Query($custom_wp_query->query_vars);
         add_filter('the_posts', array($this, 'the_posts'));
         $this->this_lang = $this_lang;
         // create a map of the translated posts
         foreach ($posts as $post) {
             $trans_posts[$post->ID] = $post;
         }
         // loop original posts
         foreach ($my_query->posts as $k => $post) {
             // loop posts in the default language
             $trid = $this->get_element_trid($post->ID);
             $translations = $this->get_element_translations($trid);
             // get translations
             if (isset($translations[$current_language])) {
                 // if there is a translation in the current language
                 if (isset($trans_posts[$translations[$current_language]->element_id])) {
                     //check the map of translated posts
                     $my_query->posts[$k] = $trans_posts[$translations[$current_language]->element_id];
                 } else {
                     // check if the translated post exists in the database still
                     $_post = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$wpdb->posts} WHERE ID = %d AND post_status='publish' LIMIT 1", $translations[$current_language]->element_id));
                     if (!empty($_post)) {
                         $_post = sanitize_post($_post);
                         $my_query->posts[$k] = $_post;
                     } else {
                         $my_query->posts[$k]->original_language = true;
                     }
                 }
             } else {
                 $my_query->posts[$k]->original_language = true;
             }
         }
         if ($custom_wp_query == $wp_query) {
             $wp_query->max_num_pages = $my_query->max_num_pages;
         }
         $posts = $my_query->posts;
         unset($GLOBALS['__icl_the_posts_posts_not_translated']);
         remove_filter('posts_where', array($this, '_posts_untranslated_extra_posts_where'), 99);
     }
     // cache translated posts
     $this->cache_translations($posts);
     return $posts;
 }
Example #10
0
 /**
  * Create a post for an item (a class or a function).
  *
  * Anything that needs to be dealt identically for functions or methods should go in this function.
  * Anything more specific should go in either import_function() or import_class() as appropriate.
  *
  * @param array $data           Data.
  * @param int   $parent_post_id Optional; post ID of the parent (class or function) this item belongs to. Defaults to zero (no parent).
  * @param bool  $import_ignored Optional; defaults to false. If true, functions or classes marked `@ignore` will be imported.
  *                              Disabled, not remove to prevent PHP Warning
  * @param array $arg_overrides  Optional; array of parameters that override the defaults passed to wp_update_post().
  *
  * @return bool|int Post ID of this item, false if any failure.
  */
 public function import_item(array $data, $parent_post_id = 0, $import_ignored = false, array $arg_overrides = array())
 {
     /** @var \wpdb $wpdb */
     global $wpdb;
     $is_new_post = true;
     $slug = sanitize_title(str_replace('::', '-', $data['name']));
     $post_data = wp_parse_args($arg_overrides, array('post_content' => $data['doc']['long_description'], 'post_excerpt' => $data['doc']['description'], 'post_name' => $slug, 'post_parent' => (int) $parent_post_id, 'post_status' => 'publish', 'post_title' => $data['name'], 'post_type' => $this->post_type_function));
     $post_type_name_to_log = substr($post_data['post_type'], 10);
     // Don't import items marked @ignore
     if (wp_list_filter($data['doc']['tags'], array('name' => 'ignore'))) {
         $indent = $parent_post_id ? "\t\t" : "\t";
         global $wpdb;
         if ($ignore = $wpdb->get_col($wpdb->prepare("SELECT DISTINCT ID FROM {$wpdb->posts} WHERE post_name = %s AND post_type = %s", $slug, $post_data['post_type']))) {
             $this->logger->info($indent . sprintf('Deleting @ignore-d %s "%s"', $post_type_name_to_log, $data['name']));
             foreach ($ignore as $ignore_post_id) {
                 if (wp_list_filter(get_post_meta($ignore_post_id, '_wp-parser_tags', true), array('name' => 'ignore'))) {
                     if (!wp_delete_post($ignore_post_id, true)) {
                         $this->errors[] = $indent . sprintf('Problem deleting @ignore-d post for %s "%s"', $post_type_name_to_log, $data['name']);
                     }
                 }
             }
         }
         return false;
     }
     /**
      * Filter whether to proceed with adding/updating a prospective import item.
      *
      * Returning a falsey value to the filter will short-circuit addition of the import item.
      *
      * @param bool  $display         Whether to proceed with adding/updating the import item. Default true.
      * @param array $data            Data
      * @param int   $parent_post_id  Optional; post ID of the parent (class or function) this item belongs to. Defaults to zero (no parent).
      * @param bool  $import_ignored  Optional; defaults to false. If true, functions or classes marked `@ignore` will be imported.
      * @param array $arg_overrides   Optional; array of parameters that override the defaults passed to wp_update_post().
      */
     if (!apply_filters('wp_parser_pre_import_item', true, $data, $parent_post_id, $import_ignored, $arg_overrides)) {
         return false;
     }
     // Look for an existing post for this item
     $existing_post_id = $wpdb->get_col($wpdb->prepare("SELECT DISTINCT ID FROM {$wpdb->posts} WHERE post_name = %s AND post_type = %s ORDER BY post_date ASC", $slug, $post_data['post_type']));
     // If the file or this items is deprecated not import, if exists deleted
     if ($this->file_meta['deprecated'] || wp_list_filter($data['doc']['tags'], array('name' => 'deprecated'))) {
         if (!empty($existing_post_id)) {
             $indent = $parent_post_id ? "\t\t" : "\t";
             $this->logger->info($indent . sprintf('Deleting deprecated %s "%s"', $post_type_name_to_log, $data['name']));
             $deleted_with_error = array();
             foreach ($existing_post_id as $exists_post_id) {
                 if ($this->file_meta['deprecated'] || wp_list_filter(get_post_meta($exists_post_id, '_wp-parser_tags', true), array('name' => 'deprecated'))) {
                     if (!wp_delete_post($exists_post_id, true)) {
                         $deleted_with_error[] = $exists_post_id;
                     }
                 }
             }
             if ($deleted_with_error) {
                 $this->errors[] = $indent . sprintf('Problem deleting deprecated post for %s "%s"', $post_type_name_to_log, $data['name']);
             }
         }
         return false;
     }
     /**
      * Filter an import item's post data before it is updated or inserted.
      *
      * @param array   $post_data          Array of post data.
      * @param array   $existing_post_id   ID if the post already exists, empty otherwise.
      */
     $post_data = apply_filters('wp_parser_import_item_post_data', $post_data, $existing_post_id);
     // Insert/update the item post
     if (!empty($existing_post_id)) {
         $is_new_post = false;
         $post_id = $post_data['ID'] = (int) array_shift($existing_post_id);
         $post_needed_update = array_diff_assoc(sanitize_post($post_data, 'db'), get_post($post_id, ARRAY_A, 'db'));
         if ($existing_post_id) {
             $indent = $parent_post_id ? "\t\t" : "\t";
             $this->errors[] = $indent . sprintf('Possible Duplicate posts of the %s "%s"', $post_type_name_to_log, $data['name']);
         }
         if ($post_needed_update) {
             $post_id = wp_update_post(wp_slash($post_data), true);
         }
     } else {
         $post_id = wp_insert_post(wp_slash($post_data), true);
     }
     $anything_updated = array();
     if (!$post_id || is_wp_error($post_id)) {
         $indent = $parent_post_id ? "\t\t" : "\t";
         $this->errors[] = $indent . sprintf('Problem inserting/updating post for %s "%s"', $post_type_name_to_log, $data['name']);
         return false;
     }
     // If the item has @since markup, assign the taxonomy
     $since_versions = wp_list_filter($data['doc']['tags'], array('name' => 'since'));
     if (!empty($since_versions)) {
         // Loop through all @since versions.
         foreach ($since_versions as $since_version) {
             if (!empty($since_version['content'])) {
                 $since_term = $this->insert_term($since_version['content'], $this->taxonomy_since_version);
                 // Assign the tax item to the post
                 if (!is_wp_error($since_term)) {
                     $added_term_relationship = did_action('added_term_relationship');
                     wp_set_object_terms($post_id, (int) $since_term['term_id'], $this->taxonomy_since_version, true);
                     if (did_action('added_term_relationship') > $added_term_relationship) {
                         $anything_updated[] = true;
                     }
                 } else {
                     $this->logger->warning("\tCannot set @since term: " . $since_term->get_error_message());
                 }
             }
         }
     }
     $packages = array('main' => wp_list_filter($data['doc']['tags'], array('name' => 'package')), 'sub' => wp_list_filter($data['doc']['tags'], array('name' => 'subpackage')));
     // If the @package/@subpackage is not set by the individual function or class, get it from the file scope
     if (empty($packages['main'])) {
         $packages['main'] = wp_list_filter($this->file_meta['docblock']['tags'], array('name' => 'package'));
     }
     if (empty($packages['sub'])) {
         $packages['sub'] = wp_list_filter($this->file_meta['docblock']['tags'], array('name' => 'subpackage'));
     }
     $main_package_id = false;
     $package_term_ids = array();
     // If the item has any @package/@subpackage markup (or has inherited it from file scope), assign the taxonomy.
     foreach ($packages as $pack_name => $pack_value) {
         if (empty($pack_value)) {
             continue;
         }
         $pack_value = array_shift($pack_value);
         $pack_value = $pack_value['content'];
         $package_term_args = array('parent' => 0);
         // Set the parent term_id to look for, as the package taxonomy is hierarchical.
         if ('sub' === $pack_name && is_int($main_package_id)) {
             $package_term_args = array('parent' => $main_package_id);
         }
         // If the package doesn't already exist in the taxonomy, add it
         $package_term = $this->insert_term($pack_value, $this->taxonomy_package, $package_term_args);
         $package_term_ids[] = (int) $package_term['term_id'];
         if ('main' === $pack_name && false === $main_package_id && !is_wp_error($package_term)) {
             $main_package_id = (int) $package_term['term_id'];
         }
         if (is_wp_error($package_term)) {
             if (is_int($main_package_id)) {
                 $this->logger->warning("\tCannot create @subpackage term: " . $package_term->get_error_message());
             } else {
                 $this->logger->warning("\tCannot create @package term: " . $package_term->get_error_message());
             }
         }
     }
     $added_term_relationship = did_action('added_term_relationship');
     wp_set_object_terms($post_id, $package_term_ids, $this->taxonomy_package);
     if (did_action('added_term_relationship') > $added_term_relationship) {
         $anything_updated[] = true;
     }
     // Set other taxonomy and post meta to use in the theme templates
     $added_item = did_action('added_term_relationship');
     wp_set_object_terms($post_id, $this->file_meta['term_id'], $this->taxonomy_file);
     if (did_action('added_term_relationship') > $added_item) {
         $anything_updated[] = true;
     }
     if ($post_data['post_type'] !== $this->post_type_class) {
         $anything_updated[] = update_post_meta($post_id, '_wp-parser_args', $data['arguments']);
     }
     $anything_updated[] = update_post_meta($post_id, '_wp-parser_line_num', (string) $data['line']);
     $anything_updated[] = update_post_meta($post_id, '_wp-parser_end_line_num', (string) $data['end_line']);
     $anything_updated[] = update_post_meta($post_id, '_wp-parser_tags', $data['doc']['tags']);
     // If the post didn't need to be updated, but meta or tax changed, update it to bump last modified.
     if (!$is_new_post && !$post_needed_update && array_filter($anything_updated)) {
         wp_update_post(wp_slash($post_data), true);
     }
     $action = $is_new_post ? 'Imported' : 'Updated';
     $indent = $parent_post_id ? "\t\t" : "\t";
     $this->logger->info("{$indent}{$action} {$post_type_name_to_log} \"{$data['name']}\"");
     /**
      * Action at the end of importing an item.
      *
      * @param int   $post_id   Optional; post ID of the inserted or updated item.
      * @param array $data PHPDoc data for the item we just imported
      * @param array $post_data WordPress data of the post we just inserted or updated
      */
     do_action('wp_parser_import_item', $post_id, $data, $post_data);
     $this->imported[$post_data['post_type']][] = $post_id;
     return $post_id;
 }
Example #11
0
 /**
  * Create a post for an item (a class or a function).
  *
  * Anything that needs to be dealt identically for functions or methods should go in this function.
  * Anything more specific should go in either import_function() or import_class() as appropriate.
  *
  * @param array $data           Data.
  * @param int   $parent_post_id Optional; post ID of the parent (class or function) this item belongs to. Defaults to zero (no parent).
  * @param bool  $import_ignored Optional; defaults to false. If true, functions or classes marked `@ignore` will be imported.
  * @param array $arg_overrides  Optional; array of parameters that override the defaults passed to wp_update_post().
  *
  * @return bool|int Post ID of this item, false if any failure.
  */
 public function import_item(array $data, $parent_post_id = 0, $import_ignored = false, array $arg_overrides = array())
 {
     /** @var \wpdb $wpdb */
     global $wpdb;
     $is_new_post = true;
     $ns_name = empty($data['namespace']) || 'global' === $data['namespace'] ? $data['name'] : $data['namespace'] . '\\' . $data['name'];
     $slug = sanitize_title(str_replace('\\', '-', str_replace('::', '-', $ns_name)));
     $post_data = wp_parse_args($arg_overrides, array('post_content' => $data['doc']['long_description'], 'post_excerpt' => $data['doc']['description'], 'post_name' => $slug, 'post_parent' => (int) $parent_post_id, 'post_status' => 'publish', 'post_title' => $data['name'], 'post_type' => $this->post_type_function));
     // Don't import items marked `@ignore` unless explicitly requested. See https://github.com/WordPress/phpdoc-parser/issues/16
     if (!$import_ignored && wp_list_filter($data['doc']['tags'], array('name' => 'ignore'))) {
         switch ($post_data['post_type']) {
             case $this->post_type_class:
                 $this->logger->info("\t" . sprintf('Skipped importing @ignore-d class "%1$s"', $ns_name));
                 break;
             case $this->post_type_method:
                 $this->logger->info("\t\t" . sprintf('Skipped importing @ignore-d method "%1$s"', $ns_name));
                 break;
             case $this->post_type_hook:
                 $indent = $parent_post_id ? "\t\t" : "\t";
                 $this->logger->info($indent . sprintf('Skipped importing @ignore-d hook "%1$s"', $ns_name));
                 break;
             default:
                 $this->logger->info("\t" . sprintf('Skipped importing @ignore-d function "%1$s"', $ns_name));
         }
         return false;
     }
     if (wp_list_filter($data['doc']['tags'], array('name' => 'ignore'))) {
         return false;
     }
     /**
      * Filter whether to proceed with adding/updating a prospective import item.
      *
      * Returning a falsey value to the filter will short-circuit addition of the import item.
      *
      * @param bool  $display         Whether to proceed with adding/updating the import item. Default true.
      * @param array $data            Data
      * @param int   $parent_post_id  Optional; post ID of the parent (class or function) this item belongs to. Defaults to zero (no parent).
      * @param bool  $import_ignored Optional; defaults to false. If true, functions or classes marked `@ignore` will be imported.
      * @param array $arg_overrides   Optional; array of parameters that override the defaults passed to wp_update_post().
      */
     if (!apply_filters('wp_parser_pre_import_item', true, $data, $parent_post_id, $import_ignored, $arg_overrides)) {
         return false;
     }
     // Look for an existing post for this item
     $existing_post_id = $wpdb->get_var($q = $wpdb->prepare("SELECT ID FROM {$wpdb->posts} WHERE post_name = %s AND post_type = %s AND post_parent = %d LIMIT 1", $slug, $post_data['post_type'], (int) $parent_post_id));
     /**
      * Filter an import item's post data before it is updated or inserted.
      *
      * @param array       $post_data        Array of post data.
      * @param string|null $existing_post_id ID if the post already exists, null otherwise.
      */
     $post_data = apply_filters('wp_parser_import_item_post_data', $post_data, $existing_post_id);
     // Insert/update the item post
     if (!empty($existing_post_id)) {
         $is_new_post = false;
         $post_id = $post_data['ID'] = (int) $existing_post_id;
         $post_needed_update = array_diff_assoc(sanitize_post($post_data, 'db'), get_post($existing_post_id, ARRAY_A, 'db'));
         if ($post_needed_update) {
             $post_id = wp_update_post(wp_slash($post_data), true);
         }
     } else {
         $post_id = wp_insert_post(wp_slash($post_data), true);
     }
     $anything_updated = array();
     if (!$post_id || is_wp_error($post_id)) {
         switch ($post_data['post_type']) {
             case $this->post_type_class:
                 $this->errors[] = "\t" . sprintf('Problem inserting/updating post for class "%1$s"', $ns_name, $post_id->get_error_message());
                 break;
             case $this->post_type_method:
                 $this->errors[] = "\t\t" . sprintf('Problem inserting/updating post for method "%1$s"', $ns_name, $post_id->get_error_message());
                 break;
             case $this->post_type_hook:
                 $indent = $parent_post_id ? "\t\t" : "\t";
                 $this->errors[] = $indent . sprintf('Problem inserting/updating post for hook "%1$s"', $ns_name, $post_id->get_error_message());
                 break;
             default:
                 $this->errors[] = "\t" . sprintf('Problem inserting/updating post for function "%1$s"', $ns_name, $post_id->get_error_message());
         }
         return false;
     }
     $namespaces = !empty($data['namespace']) ? explode('\\', $data['namespace']) : array();
     $this->_set_namespaces($post_id, $namespaces);
     // If the item has @since markup, assign the taxonomy
     $since_versions = wp_list_filter($data['doc']['tags'], array('name' => 'since'));
     if (!empty($since_versions)) {
         // Loop through all @since versions.
         foreach ($since_versions as $since_version) {
             if (!empty($since_version['content'])) {
                 $since_term = $this->insert_term($since_version['content'], $this->taxonomy_since_version);
                 // Assign the tax item to the post
                 if (!is_wp_error($since_term)) {
                     $added_term_relationship = did_action('added_term_relationship');
                     wp_set_object_terms($post_id, (int) $since_term['term_id'], $this->taxonomy_since_version, true);
                     if (did_action('added_term_relationship') > $added_term_relationship) {
                         $anything_updated[] = true;
                     }
                 } else {
                     $this->logger->warning("\tCannot set @since term: " . $since_term->get_error_message());
                 }
             }
         }
     }
     $packages = array('main' => wp_list_filter($data['doc']['tags'], array('name' => 'package')), 'sub' => wp_list_filter($data['doc']['tags'], array('name' => 'subpackage')));
     // If the @package/@subpackage is not set by the individual function or class, get it from the file scope
     if (empty($packages['main'])) {
         $packages['main'] = wp_list_filter($this->file_meta['docblock']['tags'], array('name' => 'package'));
     }
     if (empty($packages['sub'])) {
         $packages['sub'] = wp_list_filter($this->file_meta['docblock']['tags'], array('name' => 'subpackage'));
     }
     $main_package_id = false;
     $package_term_ids = array();
     // If the item has any @package/@subpackage markup (or has inherited it from file scope), assign the taxonomy.
     foreach ($packages as $pack_name => $pack_value) {
         if (empty($pack_value)) {
             continue;
         }
         $pack_value = array_shift($pack_value);
         $pack_value = $pack_value['content'];
         $package_term_args = array('parent' => 0);
         // Set the parent term_id to look for, as the package taxonomy is hierarchical.
         if ('sub' === $pack_name && is_int($main_package_id)) {
             $package_term_args = array('parent' => $main_package_id);
         }
         // If the package doesn't already exist in the taxonomy, add it
         $package_term = $this->insert_term($pack_value, $this->taxonomy_package, $package_term_args);
         $package_term_ids[] = (int) $package_term['term_id'];
         if ('main' === $pack_name && false === $main_package_id && !is_wp_error($package_term)) {
             $main_package_id = (int) $package_term['term_id'];
         }
         if (is_wp_error($package_term)) {
             if (is_int($main_package_id)) {
                 $this->logger->warning("\tCannot create @subpackage term: " . $package_term->get_error_message());
             } else {
                 $this->logger->warning("\tCannot create @package term: " . $package_term->get_error_message());
             }
         }
     }
     $added_term_relationship = did_action('added_term_relationship');
     wp_set_object_terms($post_id, $package_term_ids, $this->taxonomy_package);
     if (did_action('added_term_relationship') > $added_term_relationship) {
         $anything_updated[] = true;
     }
     // Set other taxonomy and post meta to use in the theme templates
     $added_item = did_action('added_term_relationship');
     wp_set_object_terms($post_id, $this->file_meta['term_id'], $this->taxonomy_file);
     if (did_action('added_term_relationship') > $added_item) {
         $anything_updated[] = true;
     }
     // If the file is deprecated do something
     if (!empty($this->file_meta['deprecated'])) {
         $data['doc']['tags']['deprecated'] = $this->file_meta['deprecated'];
     }
     if ($post_data['post_type'] !== $this->post_type_class) {
         $anything_updated[] = update_post_meta($post_id, '_wp-parser_args', $data['arguments']);
     }
     // If the post type is using namespace aliases, record them.
     if (!empty($data['aliases'])) {
         $anything_updated[] = update_post_meta($post_id, '_wp_parser_aliases', (array) $data['aliases']);
     }
     // Recored the namespace if there is one.
     if (!empty($data['namespace'])) {
         $anything_updated[] = update_post_meta($post_id, '_wp_parser_namespace', (string) addslashes($data['namespace']));
     }
     $anything_updated[] = update_post_meta($post_id, '_wp-parser_line_num', (string) $data['line']);
     $anything_updated[] = update_post_meta($post_id, '_wp-parser_end_line_num', (string) $data['end_line']);
     $anything_updated[] = update_post_meta($post_id, '_wp-parser_tags', $data['doc']['tags']);
     // If the post didn't need to be updated, but meta or tax changed, update it to bump last modified.
     if (!$is_new_post && !$post_needed_update && array_filter($anything_updated)) {
         wp_update_post(wp_slash($post_data), true);
     }
     $action = $is_new_post ? 'Imported' : 'Updated';
     switch ($post_data['post_type']) {
         case $this->post_type_class:
             $this->logger->info("\t" . sprintf('%1$s class "%2$s"', $action, $ns_name));
             break;
         case $this->post_type_hook:
             $indent = $parent_post_id ? "\t\t" : "\t";
             $this->logger->info($indent . sprintf('%1$s hook "%2$s"', $action, $ns_name));
             break;
         case $this->post_type_method:
             $this->logger->info("\t\t" . sprintf('%1$s method "%2$s"', $action, $ns_name));
             break;
         default:
             $this->logger->info("\t" . sprintf('%1$s function "%2$s"', $action, $ns_name));
     }
     /**
      * Action at the end of importing an item.
      *
      * @param int   $post_id   Optional; post ID of the inserted or updated item.
      * @param array $data PHPDoc data for the item we just imported
      * @param array $post_data WordPress data of the post we just inserted or updated
      */
     do_action('wp_parser_import_item', $post_id, $data, $post_data);
     return $post_id;
 }
Example #12
0
 public static function get_recent_pages($orders, $pagination, $allow_autodrafts = false)
 {
     global $wpdb;
     if (!array_key_exists('date', $orders)) {
         $orders['date'] = 'DESC';
     }
     $sql_autodrafts = " AND post_status != 'auto-draft' ";
     if ($allow_autodrafts) {
         $sql_autodrafts = '';
     }
     $total_items = $wpdb->get_var("SELECT count(*) FROM {$wpdb->posts} WHERE post_type = 'page' {$sql_autodrafts}");
     $current_page = !empty($pagination['current_page']) ? $pagination['current_page'] : 1;
     $nb_per_page = !empty($pagination['nb_per_page']) ? $pagination['nb_per_page'] : 10;
     $total_pages = $nb_per_page > 0 ? ceil($total_items / $nb_per_page) : 0;
     if ($current_page > $total_pages) {
         $current_page = $total_pages;
     }
     $offset = $nb_per_page * ($current_page - 1);
     $orderby_data = self::get_sql_orderby_data($orders);
     $join = $orderby_data['join'];
     $order_by = $orderby_data['order_by'];
     //Retrieve Recent page, then cache retrieved data:
     //Cannot use get_pages() here because we want to filter/order by Templates,
     //marked page infos etc... but we're forgiven if we cache the data after, no?
     $sql = "SELECT * FROM {$wpdb->posts} AS p \r\n\t\t\t\t\t\t {$join}\r\n\t\t\t\t\t\t WHERE post_type = 'page' \r\n\t\t\t\t\t\t {$sql_autodrafts}\r\n\t\t\t\t\t\t {$order_by} \r\n\t\t\t\t\t\t LIMIT {$offset}, {$nb_per_page}\r\n\t\t\t\t\t\t ";
     $pages = $wpdb->get_results($sql);
     //Inspired from WP get_pages() :
     //Sanitize before caching so it'll only get done once
     $num_pages = count($pages);
     for ($i = 0; $i < $num_pages; $i++) {
         $pages[$i] = sanitize_post($pages[$i], 'raw');
     }
     // Update cache.
     update_post_cache($pages);
     return array('pages' => $pages, 'pagination' => compact('current_page', 'nb_per_page', 'total_items', 'total_pages'));
 }
 function post($args, $options, $postfix = '')
 {
     global $wpdb;
     extract($args);
     $form_data = tdomf_get_form_data($tdomf_form_id);
     $modifypost = false;
     if ($options['post-title'] || $options['a'] || $options['img'] || $options['attach-a'] || $options['attach-thumb-a'] || $options['thumb-a']) {
         // Grab existing data
         $post = wp_get_single_post($post_ID, ARRAY_A);
         if (!empty($post['post_content'])) {
             $post = add_magic_quotes($post);
         }
         $content = $post['post_content'];
         $title = $post['post_title'];
         $cats = $post['post_category'];
     }
     $filecount = 0;
     $theirfiles = $form_data['uploadfiles_' . $tdomf_form_id . '_' . $postfix];
     for ($i = 0; $i < $options['max']; $i++) {
         if (!file_exists($theirfiles[$i]['path'])) {
             unset($theirfiles[$i]);
         } else {
             $filecount++;
             // move file
             $postdir = $options['path'] . DIRECTORY_SEPARATOR . $post_ID;
             tdomf_recursive_mkdir($postdir, TDOMF_UPLOAD_PERMS);
             $newpath = $postdir . DIRECTORY_SEPARATOR . $theirfiles[$i]['name'];
             if (rename($theirfiles[$i]['path'], $newpath)) {
                 $newpath = realpath($newpath);
                 // to support multiple files, we have to avoid clashes without instances
                 $j = $this->getFreeIndexPostMeta($post_ID, TDOMF_KEY_DOWNLOAD_PATH, $i);
                 // store info about files on post
                 //
                 add_post_meta($post_ID, TDOMF_KEY_DOWNLOAD_COUNT . $j, 0, true);
                 add_post_meta($post_ID, TDOMF_KEY_DOWNLOAD_TYPE . $j, $theirfiles[$i]['type'], true);
                 // escape the "path" incase it contains '\' as WP will strip these out!
                 add_post_meta($post_ID, TDOMF_KEY_DOWNLOAD_PATH . $j, $wpdb->escape($newpath), true);
                 add_post_meta($post_ID, TDOMF_KEY_DOWNLOAD_NAME . $j, $theirfiles[$i]['name'], true);
                 // keep a list of the uploaded/created files
                 //
                 $this->addToFileList($post_ID, $postfix, $newpath);
                 tdomf_log_message("File " . $theirfiles[$i]['name'] . " saved from tmp area to " . $newpath . " with type " . $theirfiles[$i]['type'] . " for post {$post_ID}");
                 // Execute user command
                 //
                 if ($options['cmd'] != "") {
                     $cmd_output = shell_exec($options['cmd'] . " " . $newpath);
                     tdomf_log_message("Executed user command on file {$newpath}<br/><pre>{$cmd_output}</pre>");
                     add_post_meta($post_ID, TDOMF_KEY_DOWNLOAD_CMD_OUTPUT . $i, $cmd_output, true);
                 }
                 // Use direct links or wrapper
                 //
                 if ($options['nohandler'] && trim($options['url']) != "") {
                     $uri = trailingslashit($options['url']) . "{$post_ID}/" . $theirfiles[$i]['name'];
                 } else {
                     $uri = trailingslashit(get_bloginfo('wpurl')) . '?tdomf_download=' . $post_ID . '&id=' . $i;
                 }
                 // Modify Post
                 //
                 // modify post title
                 if ($options['post-title']) {
                     $modifypost = true;
                     $title = $theirfiles[$i]['name'];
                 }
                 // add download link (inc name and file size)
                 if ($options['a']) {
                     $modifypost = true;
                     // $content .= "<p><a href=\"$uri\">".$theirfiles[$i]['name']." (".tdomf_filesize_format(filesize($newpath)).")</a></p>";
                 }
                 // add image link (inc name and file size)
                 if ($options['img']) {
                     $modifypost = true;
                     // Commented out image link in post by Alexander Rea 2/28/10
                     // $content .= "<p><img src=\"$uri\" /></p>";
                 }
                 // Use user-defined custom key
                 if ($options['custom'] && !empty($options['custom-key'])) {
                     add_post_meta($post_ID, $options['custom-key'], $uri);
                 }
                 // Insert upload as an attachment to post!
                 if ($options['attach']) {
                     // Create the attachment (not sure if these values are correct)
                     //
                     $attachment = array("post_content" => "", "post_title" => $theirfiles[$i]['name'], "post_name" => sanitize_title($theirfiles[$i]['name']), "post_status" => 'inherit', "post_parent" => $post_ID, "guid" => $uri, "post_type" => 'attachment', "post_mime_type" => $theirfiles[$i]['type'], "menu_order" => $i, "post_category" => $cats);
                     // I dont' know if this is a wp2.8 thing, but you have to
                     // URI for it to be properly handled as an attachment, yet...
                     // how does it know where to generate the thumbs?
                     $attachment_ID = wp_insert_attachment($attachment, $uri, $post_ID);
                     // Weirdly, I have to do this now to access the wp_generate_attachement_metadata
                     // functino from within the widget class
                     //
                     require_once ABSPATH . 'wp-admin/includes/image.php';
                     // Generate meta data (which includes thumbnail!)
                     //
                     $attachment_metadata = wp_generate_attachment_metadata($attachment_ID, $newpath);
                     // add link to attachment page
                     if ($options['attach-a']) {
                         $content .= "<p><a href=\"" . get_permalink($attachment_ID) . "\">" . $theirfiles[$i]['name'] . " (" . tdomf_filesize_format(filesize($newpath)) . ")</a></p>";
                     }
                     if (tdomf_wp23()) {
                         // Did Wordpress generate a thumbnail?
                         if (isset($attachment_metadata['thumb'])) {
                             // Wordpress 2.3 uses basename and generates only the "name" of the thumb,
                             // in general it creates it in the same place as the file!
                             $thumbpath = $postdir . DIRECTORY_SEPARATOR . $attachment_metadata['thumb'];
                             if (file_exists($thumbpath)) {
                                 add_post_meta($post_ID, TDOMF_KEY_DOWNLOAD_THUMB . $j, $thumbpath, true);
                                 // add to list
                                 //
                                 $this->addToFileList($post_ID, $postfix, $thumbpath);
                                 // WARNING: Don't modify the 'thumb' as this is used by Wordpress to know
                                 // if there is a thumb by using basename and the file path of the actual file
                                 // attachment
                                 //
                                 // Use direct links *or* wrapper
                                 //
                                 if ($options['nohandler'] && trim($options['url']) != "") {
                                     $thumburi = $options['url'] . "/{$post_ID}/" . $attachment_metadata['thumb'];
                                 } else {
                                     $thumburi = get_bloginfo('wpurl') . '/?tdomf_download=' . $post_ID . '&id=' . $j . '&thumb';
                                 }
                                 // store a copy of the thumb uri
                                 add_post_meta($post_ID, TDOMF_KEY_DOWNLOAD_THUMBURI . $j, $thumburi, true);
                                 //$attachment_metadata['thumb'] = $thumb_uri;
                                 //$attachment_metadata['thumb'] = $thumbpath;
                                 // add thumbnail link to attachment page
                                 if ($options['attach-thumb-a']) {
                                     $modifypost = true;
                                     $content .= "<p><a href=\"" . get_permalink($attachment_ID) . "\"><img src=\"{$thumburi}\" alt=\"" . $theirfiles[$i]['name'] . " (" . tdomf_filesize_format(filesize($newpath)) . ")\" /></a></p>";
                                 }
                                 // add thumbnail link directly to file
                                 if ($options['thumb-a']) {
                                     $modifypost = true;
                                     $content .= "<p><a href=\"{$uri}\"><img src=\"{$thumburi}\" alt=\"" . $theirfiles[$i]['name'] . " (" . tdomf_filesize_format(filesize($newpath)) . ")\" /></a></p>";
                                 }
                             } else {
                                 tdomf_log_message("Could not find thumbnail {$thumbpath}!", TDOMF_LOG_ERROR);
                             }
                         }
                     } else {
                         // In Wordpress 2.5 the attachment data structure is changed,
                         // it only generates a thumbnail if it needs to...
                         // Medium sized images can also sometimes be created, make a note of it
                         //
                         if (isset($attachment_metadata['sizes']['medium'])) {
                             $medpath = $postdir . DIRECTORY_SEPARATOR . $attachment_metadata['sizes']['medium']['file'];
                             if (file_exists($medpath)) {
                                 $this->addToFileList($post_ID, $postfix, $medpath);
                             }
                         }
                         if (isset($attachment_metadata['sizes']['thumbnail'])) {
                             $thumbpath = $postdir . DIRECTORY_SEPARATOR . $attachment_metadata['sizes']['thumbnail']['file'];
                             if (file_exists($thumbpath)) {
                                 add_post_meta($post_ID, TDOMF_KEY_DOWNLOAD_THUMB . $j, $thumbpath, true);
                                 // add to list
                                 //
                                 $this->addToFileList($post_ID, $postfix, $thumbpath);
                                 // Use direct links *or* wrapper
                                 //
                                 if ($options['nohandler'] && trim($options['url']) != "") {
                                     $thumburi = $options['url'] . "/{$post_ID}/" . $attachment_metadata['sizes']['thumbnail']['file'];
                                 } else {
                                     $thumburi = get_bloginfo('wpurl') . '/?tdomf_download=' . $post_ID . '&id=' . $j . '&thumb';
                                 }
                                 // store a copy of the thumb uri
                                 add_post_meta($post_ID, TDOMF_KEY_DOWNLOAD_THUMBURI . $j, $thumburi, true);
                                 // add thumbnail link to attachment page
                                 if ($options['attach-thumb-a']) {
                                     $modifypost = true;
                                     $content .= "<p><a href=\"" . get_permalink($attachment_ID) . "\"><img src=\"{$thumburi}\" alt=\"" . $theirfiles[$i]['name'] . " (" . tdomf_filesize_format(filesize($newpath)) . ")\" /></a></p>";
                                 }
                                 // add thumbnail link directly to file
                                 if ($options['thumb-a']) {
                                     $modifypost = true;
                                     $content .= "<p><a href=\"{$uri}\"><img src=\"{$thumburi}\" alt=\"" . $theirfiles[$i]['name'] . " (" . tdomf_filesize_format(filesize($newpath)) . ")\" /></a></p>";
                                 }
                             } else {
                                 tdomf_log_message("Could not find thumbnail {$thumbpath}!", TDOMF_LOG_ERROR);
                             }
                         } else {
                             if (wp_attachment_is_image($attachment_ID) && ($options['attach-thumb-a'] || $options['thumb-a'])) {
                                 // Thumbnail not generated automatically, this means that the image
                                 // is smaller than a thumbnail => use as thumbnail
                                 tdomf_log_message("No thumbnail created => image is too small. Use image as thumbnail.", TDOMF_LOG_ERROR);
                                 $modifypost = true;
                                 $sizeit = "";
                                 $h = get_option("thumbnail_size_h");
                                 $w = get_option("thumbnail_size_w");
                                 if ($attachment_metadata['height'] > $h || $attachment_metadata['width'] > $w) {
                                     if ($attachment_metadata['height'] > $attachment_metadata['width']) {
                                         $sizeit = " height=\"{$h}px\" ";
                                     } else {
                                         $sizeit = " height=\"{$w}px\" ";
                                     }
                                 }
                                 // store a the uri as a the thumburi
                                 add_post_meta($post_ID, TDOMF_KEY_DOWNLOAD_THUMBURI . $j, $uri, true);
                                 // add thumbnail link to attachment page
                                 if ($options['attach-thumb-a']) {
                                     $content .= "<p><a href=\"" . get_permalink($attachment_ID) . "\"><img src=\"{$uri}\" {$sizeit} alt=\"" . $theirfiles[$i]['name'] . " (" . tdomf_filesize_format(filesize($newpath)) . ")\" /></a></p>";
                                 }
                                 // add just the image (no point linking to thumbnail)
                                 if ($options['thumb-a']) {
                                     $content .= "<p><img src=\"{$uri}\" {$sizeit} alt=\"" . $theirfiles[$i]['name'] . " (" . tdomf_filesize_format(filesize($newpath)) . ")\" /></p>";
                                 }
                             }
                         }
                     }
                     // Add meta data
                     //
                     wp_update_attachment_metadata($attachment_ID, $attachment_metadata);
                     tdomf_log_message("Added " . $theirfiles[$i]['name'] . " as attachment");
                 }
             } else {
                 tdomf_log_message("Failed to move " . $theirfiles[$i]['name'] . "!", TDOMF_LOG_ERROR);
                 return __("Failed to move uploaded file from temporary location!", "tdomf");
             }
         }
     }
     if ($modifypost) {
         tdomf_log_message("Attempting to update post with file upload info");
         $post = array("ID" => $post_ID, "post_content" => $content, "post_title" => $title, "post_name" => sanitize_title($title));
         sanitize_post($post, "db");
         wp_update_post($post);
     }
     return NULL;
 }
Example #14
0
<?php

global $ym_formgen;
$email_id = ym_post('email_id');
$defaults = array('email_subject' => '', 'email_content' => '');
$postarr = wp_parse_args($_POST, $defaults);
$postarr = sanitize_post($postarr, 'db');
// export array as variables
extract($postarr, EXTR_SKIP);
$ym_month_email_date = ym_post('ym_month_email_date');
$ym_date_email_date = ym_post('ym_date_email_date');
$ym_year_email_date = ym_post('ym_year_email_date');
$ym_hour_email_date = ym_post('ym_hour_email_date');
$ym_min_email_date = ym_post('ym_min_email_date');
$recipient_list = ym_post('recipient_list');
do_action('mailmanager_broadcast_precontent');
if ($ym_month_email_date) {
    $time = array($ym_month_email_date, $ym_date_email_date, $ym_year_email_date, $ym_hour_email_date, $ym_min_email_date);
} else {
    $time = time();
}
if (!$email_id && (!$email_content || !$email_subject) && $_POST) {
    ym_box_top(__('Broadcast Error', 'ym_mailmanager'));
    echo '<p>' . __('You must provide a Email to send or fill in the a email content and subject', 'ym_mailmanager') . '</p>';
    ym_box_bottom();
} else {
    if (ym_post('submit')) {
        // swotch the time back to unix time
        if (is_array($time)) {
            $value = array();
            $value['month'] = array_shift($time);
function get_post($post = null, $output = OBJECT, $filter = 'raw')
{
    if (empty($post) && isset($GLOBALS['post'])) {
        $post = $GLOBALS['post'];
    }
    // pr($post);die;
    if ($post instanceof WP_Post) {
        $_post = $post;
    } elseif (is_object($post)) {
        if (empty($post->filter)) {
            $_post = sanitize_post($post, 'raw');
            $_post = new WP_Post($_post);
        } elseif ('raw' == $post->filter) {
            $_post = new WP_Post($post);
        } else {
            $_post = WP_Post::get_instance($post->ID);
        }
    } else {
        $_post = WP_Post::get_instance($post);
    }
    // pr($_post);die;
    if (!$_post) {
        return null;
    }
    $_post = $_post->filter($filter);
    if ($output == ARRAY_A) {
        return $_post->to_array();
    } elseif ($output == ARRAY_N) {
        return array_values($_post->to_array());
    }
    return $_post;
}
function pmxi_insert_post($postarr, $wp_error = false)
{
    global $wpdb;
    $user_id = get_current_user_id();
    $defaults = array('post_status' => 'draft', 'post_type' => 'post', 'post_author' => $user_id, 'ping_status' => get_option('default_ping_status'), 'post_parent' => 0, 'menu_order' => 0, 'to_ping' => '', 'pinged' => '', 'post_password' => '', 'guid' => '', 'post_content_filtered' => '', 'post_excerpt' => '', 'import_id' => 0, 'post_content' => '', 'post_title' => '');
    $postarr = wp_parse_args($postarr, $defaults);
    $postarr = sanitize_post($postarr, 'db');
    // export array as variables
    extract($postarr, EXTR_SKIP);
    // Are we updating or creating?
    $post_ID = 0;
    $update = false;
    if (!empty($ID)) {
        $update = true;
        // Get the post ID and GUID
        $post_ID = $ID;
        $post_before = get_post($post_ID);
        if (is_null($post_before)) {
            if ($wp_error) {
                return new WP_Error('invalid_post', __('Invalid post ID.'));
            }
            return 0;
        }
        $guid = get_post_field('guid', $post_ID);
        $previous_status = get_post_field('post_status', $ID);
    } else {
        $previous_status = 'new';
    }
    if (empty($post_type)) {
        $post_type = 'post';
    }
    if (empty($post_status)) {
        $post_status = 'draft';
    }
    // Make sure we set a valid category.
    if (empty($post_category) || 0 == count($post_category) || !is_array($post_category)) {
        // 'post' requires at least one category.
        if ('post' == $post_type && 'auto-draft' != $post_status) {
            $post_category = array(get_option('default_category'));
        } else {
            $post_category = array();
        }
    }
    if (empty($post_author)) {
        $post_author = $user_id;
    }
    // Create a valid post name. Drafts and pending posts are allowed to have an empty
    // post name.
    if (empty($post_name)) {
        if (!in_array($post_status, array('draft', 'pending', 'auto-draft'))) {
            $post_name = sanitize_title($post_title);
        } else {
            $post_name = '';
        }
    } else {
        // On updates, we need to check to see if it's using the old, fixed sanitization context.
        $check_name = sanitize_title($post_name, '', 'old-save');
        if ($update && strtolower(urlencode($post_name)) == $check_name && get_post_field('post_name', $ID) == $check_name) {
            $post_name = $check_name;
        } else {
            // new post, or slug has changed.
            $post_name = sanitize_title($post_name);
        }
    }
    // If the post date is empty (due to having been new or a draft) and status is not 'draft' or 'pending', set date to now
    if (empty($post_date) || '0000-00-00 00:00:00' == $post_date) {
        $post_date = current_time('mysql');
    }
    // validate the date
    $mm = substr($post_date, 5, 2);
    $jj = substr($post_date, 8, 2);
    $aa = substr($post_date, 0, 4);
    $valid_date = wp_checkdate($mm, $jj, $aa, $post_date);
    if (!$valid_date) {
        if ($wp_error) {
            return new WP_Error('invalid_date', __('Whoops, the provided date is invalid.'));
        } else {
            return 0;
        }
    }
    if (empty($post_date_gmt) || '0000-00-00 00:00:00' == $post_date_gmt) {
        if (!in_array($post_status, array('draft', 'pending', 'auto-draft'))) {
            $post_date_gmt = get_gmt_from_date($post_date);
        } else {
            $post_date_gmt = '0000-00-00 00:00:00';
        }
    }
    if ($update || '0000-00-00 00:00:00' == $post_date) {
        $post_modified = current_time('mysql');
        $post_modified_gmt = current_time('mysql', 1);
    } else {
        $post_modified = $post_date;
        $post_modified_gmt = $post_date_gmt;
    }
    if ('publish' == $post_status) {
        $now = gmdate('Y-m-d H:i:59');
        if (mysql2date('U', $post_date_gmt, false) > mysql2date('U', $now, false)) {
            $post_status = 'future';
        }
    } elseif ('future' == $post_status) {
        $now = gmdate('Y-m-d H:i:59');
        if (mysql2date('U', $post_date_gmt, false) <= mysql2date('U', $now, false)) {
            $post_status = 'publish';
        }
    }
    if (empty($comment_status)) {
        if ($update) {
            $comment_status = 'closed';
        } else {
            $comment_status = get_option('default_comment_status');
        }
    }
    if (empty($ping_status)) {
        $ping_status = get_option('default_ping_status');
    }
    if (isset($to_ping)) {
        $to_ping = sanitize_trackback_urls($to_ping);
    } else {
        $to_ping = '';
    }
    if (!isset($pinged)) {
        $pinged = '';
    }
    if (isset($post_parent)) {
        $post_parent = (int) $post_parent;
    } else {
        $post_parent = 0;
    }
    // Check the post_parent to see if it will cause a hierarchy loop
    $post_parent = apply_filters('wp_insert_post_parent', $post_parent, $post_ID, compact(array_keys($postarr)), $postarr);
    if (isset($menu_order)) {
        $menu_order = (int) $menu_order;
    } else {
        $menu_order = 0;
    }
    $post_name = wp_unique_post_slug($post_name, $post_ID, $post_status, $post_type, $post_parent);
    // expected_slashed (everything!)
    $data = compact(array('post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_content_filtered', 'post_title', 'post_excerpt', 'post_status', 'post_type', 'comment_status', 'ping_status', 'post_password', 'post_name', 'to_ping', 'pinged', 'post_modified', 'post_modified_gmt', 'post_parent', 'menu_order', 'guid'));
    $data = wp_unslash($data);
    $where = array('ID' => $post_ID);
    if ($update) {
        if (false === $wpdb->update($wpdb->posts, $data, $where)) {
            if ($wp_error) {
                return new WP_Error('db_update_error', __('Could not update post in the database'), $wpdb->last_error);
            } else {
                return 0;
            }
        }
    } else {
        if (isset($post_mime_type)) {
            $data['post_mime_type'] = wp_unslash($post_mime_type);
        }
        // This isn't in the update
        if (false === $wpdb->insert($wpdb->posts, $data)) {
            if ($wp_error) {
                return new WP_Error('db_insert_error', __('Could not insert post into the database'), $wpdb->last_error);
            } else {
                return 0;
            }
        }
        $post_ID = (int) $wpdb->insert_id;
        // use the newly generated $post_ID
        $where = array('ID' => $post_ID);
    }
    if (isset($tags_input) && is_object_in_taxonomy($post_type, 'post_tag')) {
        wp_set_post_tags($post_ID, $tags_input);
    }
    $current_guid = get_post_field('guid', $post_ID);
    // Set GUID
    if (!$update && '' == $current_guid) {
        $wpdb->update($wpdb->posts, array('guid' => get_permalink($post_ID)), $where);
    }
    return $post_ID;
}
Example #17
0
function etwp_insert_post($postarr, $wp_error = false)
{
    //global $wpdb, $user_ID;
    global $user_ID;
    $mydb = new wpdb(DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);
    //重新建立数据库连接
    $user_id = $user_ID;
    $defaults = array('post_status' => 'draft', 'post_type' => 'post', 'post_author' => $user_id, 'ping_status' => get_option('default_ping_status'), 'post_parent' => 0, 'menu_order' => 0, 'to_ping' => '', 'pinged' => '', 'post_password' => '', 'guid' => '', 'post_content_filtered' => '', 'post_excerpt' => '', 'import_id' => 0, 'post_content' => '', 'post_title' => '', 'context' => '');
    $postarr = wp_parse_args($postarr, $defaults);
    unset($postarr['filter']);
    $postarr = sanitize_post($postarr, 'raw');
    //zzcity modi
    // Are we updating or creating?
    $post_ID = 0;
    $update = false;
    $guid = $postarr['guid'];
    if (!empty($postarr['ID'])) {
        $update = true;
        // Get the post ID and GUID.
        $post_ID = $postarr['ID'];
        $post_before = get_post($post_ID);
        if (is_null($post_before)) {
            if ($wp_error) {
                return new WP_Error('invalid_post', __('Invalid post ID.'));
            }
            return 0;
        }
        $guid = get_post_field('guid', $post_ID);
        $previous_status = get_post_field('post_status', $post_ID);
    } else {
        $previous_status = 'new';
    }
    $post_type = empty($postarr['post_type']) ? 'post' : $postarr['post_type'];
    $post_title = $postarr['post_title'];
    $post_content = $postarr['post_content'];
    $post_excerpt = $postarr['post_excerpt'];
    if (isset($postarr['post_name'])) {
        $post_name = $postarr['post_name'];
    }
    $maybe_empty = 'attachment' !== $post_type && !$post_content && !$post_title && !$post_excerpt && post_type_supports($post_type, 'editor') && post_type_supports($post_type, 'title') && post_type_supports($post_type, 'excerpt');
    if (apply_filters('wp_insert_post_empty_content', $maybe_empty, $postarr)) {
        if ($wp_error) {
            return new WP_Error('empty_content', __('Content, title, and excerpt are empty.'));
        } else {
            return 0;
        }
    }
    $post_status = empty($postarr['post_status']) ? 'draft' : $postarr['post_status'];
    if ('attachment' === $post_type && !in_array($post_status, array('inherit', 'private', 'trash'))) {
        $post_status = 'inherit';
    }
    if (!empty($postarr['post_category'])) {
        // Filter out empty terms.
        $post_category = array_filter($postarr['post_category']);
    }
    // Make sure we set a valid category.
    if (empty($post_category) || 0 == count($post_category) || !is_array($post_category)) {
        // 'post' requires at least one category.
        if ('post' == $post_type && 'auto-draft' != $post_status) {
            $post_category = array(get_option('default_category'));
        } else {
            $post_category = array();
        }
    }
    // Don't allow contributors to set the post slug for pending review posts.
    if ('pending' == $post_status && !current_user_can('publish_posts')) {
        $post_name = '';
    }
    /*
     * Create a valid post name. Drafts and pending posts are allowed to have
     * an empty post name.
     */
    if (empty($post_name)) {
        if (!in_array($post_status, array('draft', 'pending', 'auto-draft'))) {
            $post_name = sanitize_title($post_title);
        } else {
            $post_name = '';
        }
    } else {
        // On updates, we need to check to see if it's using the old, fixed sanitization context.
        $check_name = sanitize_title($post_name, '', 'old-save');
        if ($update && strtolower(urlencode($post_name)) == $check_name && get_post_field('post_name', $post_ID) == $check_name) {
            $post_name = $check_name;
        } else {
            // new post, or slug has changed.
            $post_name = sanitize_title($post_name);
        }
    }
    /*
     * If the post date is empty (due to having been new or a draft) and status
     * is not 'draft' or 'pending', set date to now.
     */
    if (empty($postarr['post_date']) || '0000-00-00 00:00:00' == $postarr['post_date']) {
        $post_date = current_time('mysql');
    } else {
        $post_date = $postarr['post_date'];
    }
    // Validate the date.
    $mm = substr($post_date, 5, 2);
    $jj = substr($post_date, 8, 2);
    $aa = substr($post_date, 0, 4);
    $valid_date = wp_checkdate($mm, $jj, $aa, $post_date);
    if (!$valid_date) {
        if ($wp_error) {
            return new WP_Error('invalid_date', __('Whoops, the provided date is invalid.'));
        } else {
            return 0;
        }
    }
    if (empty($postarr['post_date_gmt']) || '0000-00-00 00:00:00' == $postarr['post_date_gmt']) {
        if (!in_array($post_status, array('draft', 'pending', 'auto-draft'))) {
            $post_date_gmt = get_gmt_from_date($post_date);
        } else {
            $post_date_gmt = '0000-00-00 00:00:00';
        }
    } else {
        $post_date_gmt = $postarr['post_date_gmt'];
    }
    if ($update || '0000-00-00 00:00:00' == $post_date) {
        $post_modified = current_time('mysql');
        $post_modified_gmt = current_time('mysql', 1);
    } else {
        $post_modified = $post_date;
        $post_modified_gmt = $post_date_gmt;
    }
    if ('attachment' !== $post_type) {
        if ('publish' == $post_status) {
            $now = gmdate('Y-m-d H:i:59');
            if (mysql2date('U', $post_date_gmt, false) > mysql2date('U', $now, false)) {
                $post_status = 'future';
            }
        } elseif ('future' == $post_status) {
            $now = gmdate('Y-m-d H:i:59');
            if (mysql2date('U', $post_date_gmt, false) <= mysql2date('U', $now, false)) {
                $post_status = 'publish';
            }
        }
    }
    if (empty($postarr['comment_status'])) {
        if ($update) {
            $comment_status = 'closed';
        } else {
            $comment_status = get_option('default_comment_status');
        }
    } else {
        $comment_status = $postarr['comment_status'];
    }
    // These variables are needed by compact() later.
    $post_content_filtered = $postarr['post_content_filtered'];
    $post_author = empty($postarr['post_author']) ? $user_id : $postarr['post_author'];
    $ping_status = empty($postarr['ping_status']) ? get_option('default_ping_status') : $postarr['ping_status'];
    $to_ping = isset($postarr['to_ping']) ? sanitize_trackback_urls($postarr['to_ping']) : '';
    $pinged = isset($postarr['pinged']) ? $postarr['pinged'] : '';
    $import_id = isset($postarr['import_id']) ? $postarr['import_id'] : 0;
    /*
     * The 'wp_insert_post_parent' filter expects all variables to be present.
     * Previously, these variables would have already been extracted
     */
    if (isset($postarr['menu_order'])) {
        $menu_order = (int) $postarr['menu_order'];
    } else {
        $menu_order = 0;
    }
    $post_password = isset($postarr['post_password']) ? $postarr['post_password'] : '';
    if ('private' == $post_status) {
        $post_password = '';
    }
    if (isset($postarr['post_parent'])) {
        $post_parent = (int) $postarr['post_parent'];
    } else {
        $post_parent = 0;
    }
    /**
     * Filter the post parent -- used to check for and prevent hierarchy loops.
     *
     * @since 3.1.0
     *
     * @param int   $post_parent Post parent ID.
     * @param int   $post_ID     Post ID.
     * @param array $new_postarr Array of parsed post data.
     * @param array $postarr     Array of sanitized, but otherwise unmodified post data.
     */
    $post_parent = apply_filters('wp_insert_post_parent', $post_parent, $post_ID, compact(array_keys($postarr)), $postarr);
    $post_name = wp_unique_post_slug($post_name, $post_ID, $post_status, $post_type, $post_parent);
    // Don't unslash.
    $post_mime_type = isset($postarr['post_mime_type']) ? $postarr['post_mime_type'] : '';
    // Expected_slashed (everything!).
    $data = compact('post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_content_filtered', 'post_title', 'post_excerpt', 'post_status', 'post_type', 'comment_status', 'ping_status', 'post_password', 'post_name', 'to_ping', 'pinged', 'post_modified', 'post_modified_gmt', 'post_parent', 'menu_order', 'post_mime_type', 'guid');
    if ('attachment' === $post_type) {
        /**
         * Filter attachment post data before it is updated in or added to the database.
         *
         * @since 3.9.0
         *
         * @param array $data    An array of sanitized attachment post data.
         * @param array $postarr An array of unsanitized attachment post data.
         */
        $data = apply_filters('wp_insert_attachment_data', $data, $postarr);
    } else {
        /**
         * Filter slashed post data just before it is inserted into the database.
         *
         * @since 2.7.0
         *
         * @param array $data    An array of slashed post data.
         * @param array $postarr An array of sanitized, but otherwise unmodified post data.
         */
        $data = apply_filters('wp_insert_post_data', $data, $postarr);
    }
    $data = wp_unslash($data);
    $where = array('ID' => $post_ID);
    if ($update) {
        do_action('pre_post_update', $post_ID, $data);
        if (false === $wpdb->update($wpdb->posts, $data, $where)) {
            if ($wp_error) {
                return new WP_Error('db_update_error', __('Could not update post in the database'), $wpdb->last_error);
            } else {
                return 0;
            }
        }
    } else {
        // If there is a suggested ID, use it if not already present.
        if (!empty($import_id)) {
            $import_id = (int) $import_id;
            if (!$wpdb->get_var($wpdb->prepare("SELECT ID FROM {$wpdb->posts} WHERE ID = %d", $import_id))) {
                $data['ID'] = $import_id;
            }
        }
        if (false === $wpdb->insert($wpdb->posts, $data)) {
            if ($wp_error) {
                return new WP_Error('db_insert_error', __('Could not insert post into the database'), $wpdb->last_error);
            } else {
                return 0;
            }
        }
        $post_ID = (int) $wpdb->insert_id;
        // Use the newly generated $post_ID.
        $where = array('ID' => $post_ID);
    }
    if (empty($data['post_name']) && !in_array($data['post_status'], array('draft', 'pending', 'auto-draft'))) {
        $data['post_name'] = sanitize_title($data['post_title'], $post_ID);
        $wpdb->update($wpdb->posts, array('post_name' => $data['post_name']), $where);
    }
    if (is_object_in_taxonomy($post_type, 'category')) {
        wp_set_post_categories($post_ID, $post_category);
    }
    if (isset($postarr['tags_input']) && is_object_in_taxonomy($post_type, 'post_tag')) {
        wp_set_post_tags($post_ID, $postarr['tags_input']);
    }
    // New-style support for all custom taxonomies.
    if (!empty($postarr['tax_input'])) {
        foreach ($postarr['tax_input'] as $taxonomy => $tags) {
            $taxonomy_obj = get_taxonomy($taxonomy);
            // array = hierarchical, string = non-hierarchical.
            if (is_array($tags)) {
                $tags = array_filter($tags);
            }
            if (current_user_can($taxonomy_obj->cap->assign_terms)) {
                wp_set_post_terms($post_ID, $tags, $taxonomy);
            }
        }
    }
    $current_guid = get_post_field('guid', $post_ID);
    // Set GUID.
    if (!$update && '' == $current_guid) {
        $wpdb->update($wpdb->posts, array('guid' => get_permalink($post_ID)), $where);
    }
    if ('attachment' === $postarr['post_type']) {
        if (!empty($postarr['file'])) {
            update_attached_file($post_ID, $postarr['file']);
        }
        if (!empty($postarr['context'])) {
            add_post_meta($post_ID, '_wp_attachment_context', $postarr['context'], true);
        }
    }
    clean_post_cache($post_ID);
    $post = get_post($post_ID);
    add_post_meta($post_ID, 'views', rand(200, 500));
    if (!empty($postarr['page_template']) && 'page' == $data['post_type']) {
        $post->page_template = $postarr['page_template'];
        $page_templates = wp_get_theme()->get_page_templates($post);
        if ('default' != $postarr['page_template'] && !isset($page_templates[$postarr['page_template']])) {
            if ($wp_error) {
                return new WP_Error('invalid_page_template', __('The page template is invalid.'));
            } else {
                return 0;
            }
        }
        update_post_meta($post_ID, '_wp_page_template', $postarr['page_template']);
    }
    if ('attachment' !== $postarr['post_type']) {
        wp_transition_post_status($data['post_status'], $previous_status, $post);
    } else {
        if ($update) {
            /**
             * Fires once an existing attachment has been updated.
             *
             * @since 2.0.0
             *
             * @param int $post_ID Attachment ID.
             */
            do_action('edit_attachment', $post_ID);
        } else {
            /**
             * Fires once an attachment has been added.
             *
             * @since 2.0.0
             *
             * @param int $post_ID Attachment ID.
             */
            do_action('add_attachment', $post_ID);
        }
        return $post_ID;
    }
    if ($update) {
        /**
         * Fires once an existing post has been updated.
         *
         * @since 1.2.0
         *
         * @param int     $post_ID Post ID.
         * @param WP_Post $post    Post object.
         */
        do_action('edit_post', $post_ID, $post);
        $post_after = get_post($post_ID);
        /**
         * Fires once an existing post has been updated.
         *
         * @since 3.0.0
         *
         * @param int     $post_ID      Post ID.
         * @param WP_Post $post_after   Post object following the update.
         * @param WP_Post $post_before  Post object before the update.
         */
        do_action('post_updated', $post_ID, $post_after, $post_before);
    }
    /**
     * Fires once a post has been saved.
     *
     * The dynamic portion of the hook name, $post->post_type, refers to
     * the post type slug.
     *
     * @since 3.7.0
     *
     * @param int     $post_ID Post ID.
     * @param WP_Post $post    Post object.
     * @param bool    $update  Whether this is an existing post being updated or not.
     */
    do_action("save_post_{$post->post_type}", $post_ID, $post, $update);
    /**
     * Fires once a post has been saved.
     *
     * @since 1.5.0
     *
     * @param int     $post_ID Post ID.
     * @param WP_Post $post    Post object.
     * @param bool    $update  Whether this is an existing post being updated or not.
     */
    do_action('save_post', $post_ID, $post, $update);
    /**
     * Fires once a post has been saved.
     *
     * @since 2.0.0
     *
     * @param int     $post_ID Post ID.
     * @param WP_Post $post    Post object.
     * @param bool    $update  Whether this is an existing post being updated or not.
     */
    do_action('wp_insert_post', $post_ID, $post, $update);
    return $post_ID;
}
 /**
  * Adds posts and pages to the sitemap.
  *
  * @since 1.3
  */
 protected function posts()
 {
     global $wpdb;
     $post_type = $this->get_info('content_type');
     $post_type_is_page = $post_type == 'page';
     $post_type_is_post = $post_type == 'post';
     if (!($post_type_is_post || $post_type_is_page)) {
         return false;
     }
     $post_ids = $post_attachments = array();
     $post_not_in = '';
     $limit = $this->getLimit();
     $exclude = $this->db->getOption($this->sitemap_type, array(), 'exclude');
     if ($exclude && ($ids = wp_parse_id_list($exclude))) {
         $post_not_in = 'ID NOT IN (' . implode(',', $ids) . ') AND';
     }
     if ($post_type_is_page) {
         $this->pageForPosts = (int) get_option('page_for_posts');
     }
     // We retrieve a few more fields than needed to make get_permalink() work properly
     $posts = $wpdb->get_results("SELECT ID, post_date, post_status, post_name, post_modified, post_parent, post_type\n\t\t\t FROM {$wpdb->posts}\n\t\t\t WHERE {$post_not_in} post_type = '{$post_type}' AND post_status = 'publish' AND post_password = ''\n\t\t\t ORDER BY post_modified DESC\n\t\t\t LIMIT {$limit}");
     if (!$posts) {
         return false;
     }
     foreach ($posts as $index => $post) {
         $post = sanitize_post($post, 'raw');
         $post_ids[] = $post->ID;
     }
     if ($post_type_is_post && $this->blog) {
         $this->blog->post_modified = $posts[0]->post_modified;
     }
     if ($this->db->getOption('images', true)) {
         $ids = implode(',', $post_ids);
         $attachments = $wpdb->get_results("SELECT ID, post_title, post_content, post_excerpt, post_parent, post_type\n\t\t\t\t FROM {$wpdb->posts}\n\t\t\t\t WHERE post_parent IN ({$ids}) AND post_type = 'attachment' AND post_mime_type LIKE 'image/%'\n\t\t\t\t ORDER BY post_modified DESC");
         if ($attachments) {
             $this->isImageSitemap = true;
             foreach ($attachments as $attachment) {
                 $attachment = sanitize_post($attachment, 'raw');
                 $post_ids[] = $attachment->ID;
                 $post_attachments[$attachment->post_parent][] = $attachment;
             }
             update_post_cache($attachments);
         }
     }
     // Retrieves and stores into the cache the metadata we need later
     update_meta_cache('post', $post_ids);
     // This hack lets us save a lot of queries that would be performed when we call get_permalink()
     update_post_cache($posts);
     $changefreq = $this->get_info('changefreq');
     $priority = $this->get_info('priority');
     foreach ($posts as $post) {
         $images = null;
         if (isset($post_attachments[$post->ID])) {
             $images =& $post_attachments[$post->ID];
         }
         if ($post->ID == $this->pageOnFront) {
             $this->home = $post;
             $this->home->images = $images;
             continue;
         } elseif ($post->ID == $this->pageForPosts) {
             $this->blog = $post;
             $this->blog->changefreq = $changefreq;
             $this->blog->priority = $priority;
             $this->blog->images = $images;
             continue;
         }
         $this->addUrlItem(get_permalink($post), $post->post_modified, $this->db->getPostMeta($post->ID, 'changefreq', $changefreq), $this->db->getPostMeta($post->ID, 'priority', $priority), $images);
     }
 }
Example #19
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;
 }
function wppa_user_upload()
{
    global $wpdb;
    static $done;
    wppa_dbg_msg('Usr_upl entered');
    if ($done) {
        return;
    }
    // Already done
    $done = true;
    // Mark as done
    // Upload possible?
    $may_upload = wppa_switch('user_upload_on');
    if (wppa_switch('user_upload_login')) {
        if (!is_user_logged_in()) {
            $may_upload = false;
        }
        // Must login
    }
    // Create album possible?
    $may_create = wppa_switch('user_create_on');
    if (wppa_switch('user_create_login')) {
        if (!is_user_logged_in()) {
            $may_create = false;
        }
        // Must login
    }
    // Edit album possible?
    $may_edit = wppa_switch('user_album_edit_on');
    // Do create
    if ($may_create) {
        if (wppa_get_post('wppa-fe-create')) {
            // Create album
            $nonce = wppa_get_post('nonce');
            if (wppa_get_post('wppa-album-name')) {
                $albumname = trim(strip_tags(wppa_get_post('wppa-album-name')));
            }
            if (!wppa_sanitize_file_name($albumname)) {
                $albumname = __('New Album', 'wp-photo-album-plus');
            }
            $ok = wp_verify_nonce($nonce, 'wppa-album-check');
            if (!$ok) {
                die('<b>' . __('ERROR: Illegal attempt to create an album.', 'wp-photo-album-plus') . '</b>');
            }
            // Check captcha
            if (wppa_switch('user_create_captcha')) {
                $captkey = wppa_get_randseed('session');
                if (!wppa_check_captcha($captkey)) {
                    wppa_alert(__('Wrong captcha, please try again', 'wp-photo-album-plus'));
                    return;
                }
            }
            $parent = strval(intval(wppa_get_post('wppa-album-parent')));
            if (!wppa_user_is('administrator') && wppa_switch('default_parent_always')) {
                $parent = wppa_opt('default_parent');
            }
            $album = wppa_create_album_entry(array('name' => $albumname, 'description' => strip_tags(wppa_get_post('wppa-album-desc')), 'a_parent' => $parent, 'owner' => wppa_switch('frontend_album_public') ? '--- public ---' : wppa_get_user()));
            if ($album) {
                if (wppa_switch('fe_alert')) {
                    wppa_alert(sprintf(__('Album #%s created', 'wp-photo-album-plus'), $album));
                }
                wppa_flush_treecounts($parent);
                wppa_create_pl_htaccess();
            } else {
                wppa_alert(__('Could not create album', 'wp-photo-album-plus'));
            }
        }
    }
    // Do Upload
    if ($may_upload) {
        $blogged = false;
        if (wppa_get_post('wppa-upload-album')) {
            // Upload photo
            $nonce = wppa_get_post('nonce');
            $ok = wp_verify_nonce($nonce, 'wppa-check');
            if (!$ok) {
                die('<b>' . __('ERROR: Illegal attempt to upload a file.', 'wp-photo-album-plus') . '</b>');
            }
            $alb = wppa_get_post('wppa-upload-album');
            $alb = strval(intval($alb));
            // Force numeric
            if (!wppa_album_exists($alb)) {
                $alert = sprintf(__('Album %s does not exist', 'wp-photo-album-plus'), $alb);
                wppa_alert($alert);
                return;
            }
            $uploaded_ids = array();
            if (is_array($_FILES)) {
                $iret = true;
                $filecount = '1';
                $done = '0';
                $fail = '0';
                foreach ($_FILES as $file) {
                    if (!is_array($file['error'])) {
                        $iret = wppa_do_frontend_file_upload($file, $alb);
                        // this should no longer happen since the name is incl []
                        if ($iret) {
                            $uploaded_ids[] = $iret;
                            $done++;
                            wppa_set_last_album($alb);
                        } else {
                            $fail++;
                        }
                    } else {
                        $filecount = count($file['error']);
                        for ($i = '0'; $i < $filecount; $i++) {
                            if ($iret) {
                                $f['error'] = $file['error'][$i];
                                $f['tmp_name'] = $file['tmp_name'][$i];
                                $f['name'] = $file['name'][$i];
                                $f['type'] = $file['type'][$i];
                                $f['size'] = $file['size'][$i];
                                $iret = wppa_do_frontend_file_upload($f, $alb);
                                if ($iret) {
                                    $uploaded_ids[] = $iret;
                                    $done++;
                                    wppa_set_last_album($alb);
                                } else {
                                    $fail++;
                                }
                            }
                        }
                    }
                }
                $points = '0';
                $alert = '';
                $reload = wppa_switch('home_after_upload') && $done ? 'home' : false;
                if ($done) {
                    // SUCCESSFUL UPLOAD, Blog It?
                    if (current_user_can('edit_posts') && isset($_POST['wppa-blogit'])) {
                        $title = $_POST['wppa-post-title'];
                        if (!$title) {
                            $title = wppa_local_date();
                        }
                        $pretxt = $_POST['wppa-blogit-pretext'];
                        $posttxt = $_POST['wppa-blogit-posttext'];
                        $status = wppa_switch('blog_it_moderate') ? 'pending' : 'publish';
                        $post_content = $pretxt;
                        foreach ($uploaded_ids as $id) {
                            $post_content .= str_replace('#id', $id, wppa_opt('blog_it_shortcode'));
                        }
                        $post_content .= $posttxt;
                        $post = array('post_title' => $title, 'post_content' => $post_content, 'post_status' => $status);
                        $post = sanitize_post($post, 'db');
                        $iret = wp_insert_post($post);
                        $blogged = true;
                    }
                    // ADD POINTS
                    $points = wppa_opt('cp_points_upload') * $done;
                    $bret = wppa_add_credit_points($points, __('Photo upload', 'wp-photo-album-plus'));
                    $alert .= sprintf(_n('%d photo successfully uploaded', '%d photos successfully uploaded', $done, 'wp-photo-album-plus'), $done);
                    if ($bret) {
                        $alert .= ' ' . sprintf(__('%s points added', 'wp-photo-album-plus'), $points);
                    }
                    if (wppa_switch('fe_alert')) {
                        wppa_alert($alert, $reload);
                    } else {
                        wppa_alert('', $reload);
                    }
                    // Blogged?
                    if ($blogged) {
                        if (wppa_switch('fe_alert')) {
                            if ($status == 'pending') {
                                wppa_alert(__('Your post is awaiting moderation.', 'wp-photo-album-plus'));
                            }
                        }
                        echo '<script type="text/javascript" >document.location.href=\'' . home_url() . '\';</script>';
                        wppa_exit();
                    }
                }
                if ($fail) {
                    if (!$done) {
                        $alert .= __('Upload failed', 'wp-photo-album-plus');
                    } else {
                        $alert .= sprintf(_n('%d upload failed', '%d uploads failed', $fail, 'wp-photo-album-plus'), $fail);
                    }
                    wppa_alert($alert, $reload);
                }
            }
        }
    }
    // Do Edit
    if ($may_edit) {
        if (wppa_get_post('wppa-albumeditsubmit')) {
            // Get album id
            $alb = wppa_get_post('wppa-albumeditid');
            if (!$alb || !wppa_album_exists($alb)) {
                die('Security check failure');
            }
            // Valid request?
            if (!wp_verify_nonce(wppa_get_post('wppa-albumeditnonce'), 'wppa_nonce_' . $alb)) {
                die('Security check failure');
            }
            // Name
            $name = wppa_get_post('wppa-albumeditname');
            $name = trim(strip_tags($name));
            if (!$name) {
                // Empty album name is not allowed
                $name = 'Album-#' . $alb;
            }
            // Description
            $description = wppa_get_post('wppa-albumeditdesc');
            // Custom data
            $custom = wppa_get_album_item($alb, 'custom');
            if ($custom) {
                $custom_data = unserialize($custom);
            } else {
                $custom_data = array('', '', '', '', '', '', '', '', '', '');
            }
            $idx = '0';
            while ($idx < '10') {
                if (isset($_POST['custom_' . $idx])) {
                    $value = wppa_get_post('custom_' . $idx);
                    $custom_data[$idx] = wppa_sanitize_custom_field($value);
                }
                $idx++;
            }
            $custom = serialize($custom_data);
            // Update
            wppa_update_album(array('id' => $alb, 'name' => $name, 'description' => $description, 'custom' => $custom, 'modified' => time()));
            wppa_index_update('album', $alb);
            wppa_create_pl_htaccess();
        }
    }
}
 function r18368($post, $raw_post)
 {
     if (isset($post['filter']) || isset($raw_post['filter'])) {
         unset($post['filter'], $raw_post['filter']);
         // to ensure the post is properly sanitized
         $post = sanitize_post($post, 'db');
     }
     if (empty($post['ID'])) {
         unset($post['ID']);
     }
     // sanitize_post
     unset($post['filter']);
     // sanitize_post
     return $post;
 }
Example #22
0
 /**
  * {@Missing Summary}
  *
  * @param string $filter Filter.
  * @return $this|array|bool|object|WP_Post
  */
 public function filter($filter)
 {
     if ($this->filter == $filter) {
         return $this;
     }
     if ($filter == 'raw') {
         return self::get_instance($this->ID);
     }
     return sanitize_post($this, $filter);
 }
function get_attachment_fields_to_edit($post, $errors = null)
{
    if (is_int($post)) {
        $post =& get_post($post);
    }
    if (is_array($post)) {
        $post = (object) $post;
    }
    $edit_post = sanitize_post($post, 'edit');
    $file = wp_get_attachment_url($post->ID);
    $link = get_attachment_link($post->ID);
    $form_fields = array('post_title' => array('label' => __('Title'), 'value' => $edit_post->post_title), 'post_excerpt' => array('label' => __('Caption'), 'value' => $edit_post->post_excerpt), 'post_content' => array('label' => __('Description'), 'value' => $edit_post->post_content, 'input' => 'textarea'), 'url' => array('label' => __('Link URL'), 'input' => 'html', 'html' => "\n\t\t\t\t<input type='text' name='attachments[{$post->ID}][url]' value='" . attribute_escape($file) . "' /><br />\n\t\t\t\t<button type='button' class='button url-{$post->ID}' value=''>" . __('None') . "</button>\n\t\t\t\t<button type='button' class='button url-{$post->ID}' value='" . attribute_escape($file) . "'>" . __('File URL') . "</button>\n\t\t\t\t<button type='button' class='button url-{$post->ID}' value='" . attribute_escape($link) . "'>" . __('Post URL') . "</button>\n\t\t\t\t<script type='text/javascript'>\n\t\t\t\tjQuery('button.url-{$post->ID}').bind('click', function(){jQuery(this).siblings('input').val(this.value);});\n\t\t\t\t</script>\n", 'helps' => __('Enter a link URL or click above for presets.')));
    foreach (get_attachment_taxonomies($post) as $taxonomy) {
        $t = (array) get_taxonomy($taxonomy);
        if (empty($t['label'])) {
            $t['label'] = $taxonomy;
        }
        if (empty($t['args'])) {
            $t['args'] = array();
        }
        $terms = get_object_term_cache($post->ID, $taxonomy);
        if (empty($terms)) {
            $terms = wp_get_object_terms($post->ID, $taxonomy, $t['args']);
        }
        $values = array();
        foreach ($terms as $term) {
            $values[] = $term->name;
        }
        $t['value'] = join(', ', $values);
        $form_fields[$taxonomy] = $t;
    }
    // Merge default fields with their errors, so any key passed with the error (e.g. 'error', 'helps', 'value') will replace the default
    // The recursive merge is easily traversed with array casting: foreach( (array) $things as $thing )
    $form_fields = array_merge_recursive($form_fields, (array) $errors);
    $form_fields = apply_filters('attachment_fields_to_edit', $form_fields, $post);
    return $form_fields;
}
Example #24
0
/**
 * {@internal Missing Short Description}}
 *
 * @since 2.5.0
 *
 * @param object $post
 * @param array $errors
 * @return array
 */
function get_attachment_fields_to_edit($post, $errors = null)
{
    if (is_int($post)) {
        $post = get_post($post);
    }
    if (is_array($post)) {
        $post = new WP_Post((object) $post);
    }
    $image_url = wp_get_attachment_url($post->ID);
    $edit_post = sanitize_post($post, 'edit');
    $form_fields = array('post_title' => array('label' => __('Title'), 'value' => $edit_post->post_title), 'image_alt' => array(), 'post_excerpt' => array('label' => __('Caption'), 'input' => 'html', 'html' => wp_caption_input_textarea($edit_post)), 'post_content' => array('label' => __('Description'), 'value' => $edit_post->post_content, 'input' => 'textarea'), 'url' => array('label' => __('Link URL'), 'input' => 'html', 'html' => image_link_input_fields($post, get_option('image_default_link_type')), 'helps' => __('Enter a link URL or click above for presets.')), 'menu_order' => array('label' => __('Order'), 'value' => $edit_post->menu_order), 'image_url' => array('label' => __('File URL'), 'input' => 'html', 'html' => "<input type='text' class='text urlfield' readonly='readonly' name='attachments[{$post->ID}][url]' value='" . esc_attr($image_url) . "' /><br />", 'value' => wp_get_attachment_url($post->ID), 'helps' => __('Location of the uploaded file.')));
    foreach (get_attachment_taxonomies($post) as $taxonomy) {
        $t = (array) get_taxonomy($taxonomy);
        if (!$t['public'] || !$t['show_ui']) {
            continue;
        }
        if (empty($t['label'])) {
            $t['label'] = $taxonomy;
        }
        if (empty($t['args'])) {
            $t['args'] = array();
        }
        $terms = get_object_term_cache($post->ID, $taxonomy);
        if (false === $terms) {
            $terms = wp_get_object_terms($post->ID, $taxonomy, $t['args']);
        }
        $values = array();
        foreach ($terms as $term) {
            $values[] = $term->slug;
        }
        $t['value'] = join(', ', $values);
        $form_fields[$taxonomy] = $t;
    }
    // Merge default fields with their errors, so any key passed with the error (e.g. 'error', 'helps', 'value') will replace the default
    // The recursive merge is easily traversed with array casting: foreach( (array) $things as $thing )
    $form_fields = array_merge_recursive($form_fields, (array) $errors);
    // This was formerly in image_attachment_fields_to_edit().
    if (substr($post->post_mime_type, 0, 5) == 'image') {
        $alt = get_post_meta($post->ID, '_wp_attachment_image_alt', true);
        if (empty($alt)) {
            $alt = '';
        }
        $form_fields['post_title']['required'] = true;
        $form_fields['image_alt'] = array('value' => $alt, 'label' => __('Alternative Text'), 'helps' => __('Alt text for the image, e.g. &#8220;The Mona Lisa&#8221;'));
        $form_fields['align'] = array('label' => __('Alignment'), 'input' => 'html', 'html' => image_align_input_fields($post, get_option('image_default_align')));
        $form_fields['image-size'] = image_size_input_fields($post, get_option('image_default_size', 'medium'));
    } else {
        unset($form_fields['image_alt']);
    }
    /**
     * Filter the attachment fields to edit.
     *
     * @since 2.5.0
     *
     * @param array   $form_fields An array of attachment form fields.
     * @param WP_Post $post        The WP_Post attachment object.
     */
    $form_fields = apply_filters('attachment_fields_to_edit', $form_fields, $post);
    return $form_fields;
}
Example #25
0
/**
 * {@internal Missing Short Description}}
 *
 * @since unknown
 *
 * @param unknown_type $post
 * @param unknown_type $errors
 * @return unknown
 */
function get_attachment_fields_to_edit($post, $errors = null)
{
    if (is_int($post)) {
        $post =& get_post($post);
    }
    if (is_array($post)) {
        $post = (object) $post;
    }
    $image_url = wp_get_attachment_url($post->ID);
    $edit_post = sanitize_post($post, 'edit');
    $form_fields = array('post_title' => array('label' => __('Title'), 'value' => $edit_post->post_title), 'post_excerpt' => array('label' => __('Caption'), 'value' => $edit_post->post_excerpt), 'post_content' => array('label' => __('Description'), 'value' => $edit_post->post_content, 'input' => 'textarea'), 'url' => array('label' => __('Link URL'), 'input' => 'html', 'html' => image_link_input_fields($post, get_option('image_default_link_type')), 'helps' => __('Enter a link URL or click above for presets.')), 'menu_order' => array('label' => __('Order'), 'value' => $edit_post->menu_order), 'image_url' => array('label' => __('File URL'), 'input' => 'html', 'html' => "<input type='text' class='urlfield' readonly='readonly' name='attachments[{$post->ID}][url]' value='" . esc_attr($image_url) . "' /><br />", 'value' => isset($edit_post->post_url) ? $edit_post->post_url : '', 'helps' => __('Location of the uploaded file.')));
    foreach (get_attachment_taxonomies($post) as $taxonomy) {
        $t = (array) get_taxonomy($taxonomy);
        if (empty($t['label'])) {
            $t['label'] = $taxonomy;
        }
        if (empty($t['args'])) {
            $t['args'] = array();
        }
        $terms = get_object_term_cache($post->ID, $taxonomy);
        if (empty($terms)) {
            $terms = wp_get_object_terms($post->ID, $taxonomy, $t['args']);
        }
        $values = array();
        foreach ($terms as $term) {
            $values[] = $term->name;
        }
        $t['value'] = join(', ', $values);
        $form_fields[$taxonomy] = $t;
    }
    // Merge default fields with their errors, so any key passed with the error (e.g. 'error', 'helps', 'value') will replace the default
    // The recursive merge is easily traversed with array casting: foreach( (array) $things as $thing )
    $form_fields = array_merge_recursive($form_fields, (array) $errors);
    $form_fields = apply_filters('attachment_fields_to_edit', $form_fields, $post);
    return $form_fields;
}
 public static function getPostByTitle($title)
 {
     $post_arr = sanitize_post(array("post_title" => $title), 'db');
     $post_arr = $post_arr["post_title"];
     global $wpdb;
     $post = $wpdb->get_var($wpdb->prepare("SELECT ID FROM {$wpdb->posts} WHERE post_title = %s AND post_type='post'", $title));
     if ($post) {
         return get_post($post, OBJECT);
     }
     return null;
 }
Example #27
0
/**
 * Retrieve a list of pages.
 *
 * @global wpdb $wpdb WordPress database abstraction object.
 *
 * @since 1.5.0
 *
 * @param array|string $args {
 *     Optional. Array or string of arguments to retrieve pages.
 *
 *     @type int          $child_of     Page ID to return child and grandchild pages of. Note: The value
 *                                      of `$hierarchical` has no bearing on whether `$child_of` returns
 *                                      hierarchical results. Default 0, or no restriction.
 *     @type string       $sort_order   How to sort retrieved pages. Accepts 'ASC', 'DESC'. Default 'ASC'.
 *     @type string       $sort_column  What columns to sort pages by, comma-separated. Accepts 'post_author',
 *                                      'post_date', 'post_title', 'post_name', 'post_modified', 'menu_order',
 *                                      'post_modified_gmt', 'post_parent', 'ID', 'rand', 'comment_count'.
 *                                      'post_' can be omitted for any values that start with it.
 *                                      Default 'post_title'.
 *     @type bool         $hierarchical Whether to return pages hierarchically. If false in conjunction with
 *                                      `$child_of` also being false, both arguments will be disregarded.
 *                                      Default true.
 *     @type array        $exclude      Array of page IDs to exclude. Default empty array.
 *     @type array        $include      Array of page IDs to include. Cannot be used with `$child_of`,
 *                                      `$parent`, `$exclude`, `$meta_key`, `$meta_value`, or `$hierarchical`.
 *                                      Default empty array.
 *     @type string       $meta_key     Only include pages with this meta key. Default empty.
 *     @type string       $meta_value   Only include pages with this meta value. Requires `$meta_key`.
 *                                      Default empty.
 *     @type string       $authors      A comma-separated list of author IDs. Default empty.
 *     @type int          $parent       Page ID to return direct children of. Default -1, or no restriction.
 *     @type string|array $exclude_tree Comma-separated string or array of page IDs to exclude.
 *                                      Default empty array.
 *     @type int          $number       The number of pages to return. Default 0, or all pages.
 *     @type int          $offset       The number of pages to skip before returning. Requires `$number`.
 *                                      Default 0.
 *     @type string       $post_type    The post type to query. Default 'page'.
 *     @type string       $post_status  A comma-separated list of post status types to include.
 *                                      Default 'publish'.
 * }
 * @return array|false List of pages matching defaults or `$args`.
 */
function get_pages($args = array())
{
    global $wpdb;
    $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' => array(), 'number' => '', 'offset' => 0, 'post_type' => 'page', 'post_status' => 'publish');
    $r = wp_parse_args($args, $defaults);
    $number = (int) $r['number'];
    $offset = (int) $r['offset'];
    $child_of = (int) $r['child_of'];
    $hierarchical = $r['hierarchical'];
    $exclude = $r['exclude'];
    $meta_key = $r['meta_key'];
    $meta_value = $r['meta_value'];
    $parent = $r['parent'];
    $post_status = $r['post_status'];
    // Make sure the post type is hierarchical.
    $hierarchical_post_types = get_post_types(array('hierarchical' => true));
    if (!in_array($r['post_type'], $hierarchical_post_types)) {
        return false;
    }
    if ($parent > 0 && !$child_of) {
        $hierarchical = false;
    }
    // Make sure we have a valid post status.
    if (!is_array($post_status)) {
        $post_status = explode(',', $post_status);
    }
    if (array_diff($post_status, get_post_stati())) {
        return false;
    }
    // $args can be whatever, only use the args defined in defaults to compute the key.
    $key = md5(serialize(wp_array_slice_assoc($r, array_keys($defaults))));
    $last_changed = wp_cache_get('last_changed', 'posts');
    if (!$last_changed) {
        $last_changed = microtime();
        wp_cache_set('last_changed', $last_changed, 'posts');
    }
    $cache_key = "get_pages:{$key}:{$last_changed}";
    if ($cache = wp_cache_get($cache_key, 'posts')) {
        // Convert to WP_Post instances.
        $pages = array_map('get_post', $cache);
        /** This filter is documented in wp-includes/post.php */
        $pages = apply_filters('get_pages', $pages, $r);
        return $pages;
    }
    $inclusions = '';
    if (!empty($r['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($r['include']);
        if (!empty($incpages)) {
            $inclusions = ' AND ID IN (' . implode(',', $incpages) . ')';
        }
    }
    $exclusions = '';
    if (!empty($exclude)) {
        $expages = wp_parse_id_list($exclude);
        if (!empty($expages)) {
            $exclusions = ' AND ID NOT IN (' . implode(',', $expages) . ')';
        }
    }
    $author_query = '';
    if (!empty($r['authors'])) {
        $post_authors = preg_split('/[\\s,]+/', $r['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_user_by('login', $post_author);
                    if (empty($post_author)) {
                        continue;
                    }
                    if (empty($post_author->ID)) {
                        continue;
                    }
                    $post_author = $post_author->ID;
                }
                if ('' == $author_query) {
                    $author_query = $wpdb->prepare(' post_author = %d ', $post_author);
                } else {
                    $author_query .= $wpdb->prepare(' OR post_author = %d ', $post_author);
                }
            }
            if ('' != $author_query) {
                $author_query = " AND ({$author_query})";
            }
        }
    }
    $join = '';
    $where = "{$exclusions} {$inclusions} ";
    if ('' !== $meta_key || '' !== $meta_value) {
        $join = " LEFT JOIN {$wpdb->postmeta} ON ( {$wpdb->posts}.ID = {$wpdb->postmeta}.post_id )";
        // meta_key and meta_value might be slashed
        $meta_key = wp_unslash($meta_key);
        $meta_value = wp_unslash($meta_value);
        if ('' !== $meta_key) {
            $where .= $wpdb->prepare(" AND {$wpdb->postmeta}.meta_key = %s", $meta_key);
        }
        if ('' !== $meta_value) {
            $where .= $wpdb->prepare(" AND {$wpdb->postmeta}.meta_value = %s", $meta_value);
        }
    }
    if (is_array($parent)) {
        $post_parent__in = implode(',', array_map('absint', (array) $parent));
        if (!empty($post_parent__in)) {
            $where .= " AND post_parent IN ({$post_parent__in})";
        }
    } elseif ($parent >= 0) {
        $where .= $wpdb->prepare(' AND post_parent = %d ', $parent);
    }
    if (1 == count($post_status)) {
        $where_post_type = $wpdb->prepare("post_type = %s AND post_status = %s", $r['post_type'], reset($post_status));
    } else {
        $post_status = implode("', '", $post_status);
        $where_post_type = $wpdb->prepare("post_type = %s AND post_status IN ('{$post_status}')", $r['post_type']);
    }
    $orderby_array = array();
    $allowed_keys = array('author', 'post_author', 'date', 'post_date', 'title', 'post_title', 'name', 'post_name', 'modified', 'post_modified', 'modified_gmt', 'post_modified_gmt', 'menu_order', 'parent', 'post_parent', 'ID', 'rand', 'comment_count');
    foreach (explode(',', $r['sort_column']) as $orderby) {
        $orderby = trim($orderby);
        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 'comment_count':
                $orderby = "{$wpdb->posts}.comment_count";
                break;
            default:
                if (0 === strpos($orderby, 'post_')) {
                    $orderby = "{$wpdb->posts}." . $orderby;
                } else {
                    $orderby = "{$wpdb->posts}.post_" . $orderby;
                }
        }
        $orderby_array[] = $orderby;
    }
    $sort_column = !empty($orderby_array) ? implode(',', $orderby_array) : "{$wpdb->posts}.post_title";
    $sort_order = strtoupper($r['sort_order']);
    if ('' !== $sort_order && !in_array($sort_order, array('ASC', 'DESC'))) {
        $sort_order = 'ASC';
    }
    $query = "SELECT * FROM {$wpdb->posts} {$join} WHERE ({$where_post_type}) {$where} ";
    $query .= $author_query;
    $query .= " ORDER BY " . $sort_column . " " . $sort_order;
    if (!empty($number)) {
        $query .= ' LIMIT ' . $offset . ',' . $number;
    }
    $pages = $wpdb->get_results($query);
    if (empty($pages)) {
        /** This filter is documented in wp-includes/post.php */
        $pages = apply_filters('get_pages', array(), $r);
        return $pages;
    }
    // Sanitize before caching so it'll only get done once.
    $num_pages = count($pages);
    for ($i = 0; $i < $num_pages; $i++) {
        $pages[$i] = sanitize_post($pages[$i], 'raw');
    }
    // Update cache.
    update_post_cache($pages);
    if ($child_of || $hierarchical) {
        $pages = get_page_children($child_of, $pages);
    }
    if (!empty($r['exclude_tree'])) {
        $exclude = wp_parse_id_list($r['exclude_tree']);
        foreach ($exclude as $id) {
            $children = get_page_children($id, $pages);
            foreach ($children as $child) {
                $exclude[] = $child->ID;
            }
        }
        $num_pages = count($pages);
        for ($i = 0; $i < $num_pages; $i++) {
            if (in_array($pages[$i]->ID, $exclude)) {
                unset($pages[$i]);
            }
        }
    }
    $page_structure = array();
    foreach ($pages as $page) {
        $page_structure[] = $page->ID;
    }
    wp_cache_set($cache_key, $page_structure, 'posts');
    // Convert to WP_Post instances
    $pages = array_map('get_post', $pages);
    /**
     * Filter the retrieved list of pages.
     *
     * @since 2.1.0
     *
     * @param array $pages List of pages to retrieve.
     * @param array $r     Array of get_pages() arguments.
     */
    return apply_filters('get_pages', $pages, $r);
}
<?php

require "db.phpo";
if (isset($_POST['submit'])) {
    $first_name = sanitize_post('first_name');
    $last_name = $_POST['last_name'];
    $username = $_POST['username'];
    $pass1 = $_POST['pass1'];
    $pass2 = $_POST['pass2'];
    $ok = 1;
    $query = search('login_data', 'username', $username);
    $row = mysqli_fetch_array($query);
    if ($row['username'] == $username) {
        echo "This username is already taken<br><br>";
        $ok = 0;
    }
    if ($pass1 != $pass2) {
        echo "The two passwords don't match<br><br>";
        $ok = 0;
    }
    if ($ok) {
        //TODO:make password encryption
        $password = $pass1;
        $sql = "INSERT INTO login_data (first_name, last_name, username, password) VALUES ('{$first_name}', '{$last_name}', '{$username}', '{$password}');";
        mysqli_query($conn, $sql) or die(mysqli_error($conn));
        ?>
    <p style = "font-size: 25px; color: red"> Registered successfully </p>
    <?php 
    }
}
?>
Example #29
0
function _set_preview($post)
{
    if (!is_object($post)) {
        return $post;
    }
    $preview = wp_get_post_autosave($post->ID);
    if (!is_object($preview)) {
        return $post;
    }
    $preview = sanitize_post($preview);
    $post->post_content = $preview->post_content;
    $post->post_title = $preview->post_title;
    $post->post_excerpt = $preview->post_excerpt;
    return $post;
}
Example #30
0
function wp_insert_attachment($object, $file = false, $parent = 0)
{
    global $wpdb, $user_ID;
    $defaults = array('post_status' => 'draft', 'post_type' => 'post', 'post_author' => $user_ID, 'ping_status' => get_option('default_ping_status'), 'post_parent' => 0, 'menu_order' => 0, 'to_ping' => '', 'pinged' => '', 'post_password' => '');
    $object = wp_parse_args($object, $defaults);
    if (!empty($parent)) {
        $object['post_parent'] = $parent;
    }
    $object = sanitize_post($object, 'db');
    // export array as variables
    extract($object, EXTR_SKIP);
    // Make sure we set a valid category
    if (0 == count($post_category) || !is_array($post_category)) {
        $post_category = array(get_option('default_category'));
    }
    if (empty($post_author)) {
        $post_author = $user_ID;
    }
    $post_type = 'attachment';
    $post_status = 'inherit';
    // Are we updating or creating?
    $update = false;
    if (!empty($ID)) {
        $update = true;
        $post_ID = (int) $ID;
    }
    // Create a valid post name.
    if (empty($post_name)) {
        $post_name = sanitize_title($post_title);
    } else {
        $post_name = sanitize_title($post_name);
    }
    $post_name_check = $wpdb->get_var("SELECT post_name FROM {$wpdb->posts} WHERE post_name = '{$post_name}' AND post_status = 'inherit' AND ID != '{$post_ID}' LIMIT 1");
    if ($post_name_check) {
        $suffix = 2;
        while ($post_name_check) {
            $alt_post_name = $post_name . "-{$suffix}";
            $post_name_check = $wpdb->get_var("SELECT post_name FROM {$wpdb->posts} WHERE post_name = '{$alt_post_name}' AND post_status = 'inherit' AND ID != '{$post_ID}' AND post_parent = '{$post_parent}' LIMIT 1");
            $suffix++;
        }
        $post_name = $alt_post_name;
    }
    if (empty($post_date)) {
        $post_date = current_time('mysql');
    }
    if (empty($post_date_gmt)) {
        $post_date_gmt = current_time('mysql', 1);
    }
    if (empty($comment_status)) {
        if ($update) {
            $comment_status = 'closed';
        } else {
            $comment_status = get_option('default_comment_status');
        }
    }
    if (empty($ping_status)) {
        $ping_status = get_option('default_ping_status');
    }
    if (isset($to_ping)) {
        $to_ping = preg_replace('|\\s+|', "\n", $to_ping);
    } else {
        $to_ping = '';
    }
    if (isset($post_parent)) {
        $post_parent = (int) $post_parent;
    } else {
        $post_parent = 0;
    }
    if (isset($menu_order)) {
        $menu_order = (int) $menu_order;
    } else {
        $menu_order = 0;
    }
    if (!isset($post_password)) {
        $post_password = '';
    }
    if (!isset($pinged)) {
        $pinged = '';
    }
    if ($update) {
        $wpdb->query("UPDATE {$wpdb->posts} SET\n\t\t\tpost_author = '{$post_author}',\n\t\t\tpost_date = '{$post_date}',\n\t\t\tpost_date_gmt = '{$post_date_gmt}',\n\t\t\tpost_content = '{$post_content}',\n\t\t\tpost_content_filtered = '{$post_content_filtered}',\n\t\t\tpost_title = '{$post_title}',\n\t\t\tpost_excerpt = '{$post_excerpt}',\n\t\t\tpost_status = '{$post_status}',\n\t\t\tpost_type = '{$post_type}',\n\t\t\tcomment_status = '{$comment_status}',\n\t\t\tping_status = '{$ping_status}',\n\t\t\tpost_password = '******',\n\t\t\tpost_name = '{$post_name}',\n\t\t\tto_ping = '{$to_ping}',\n\t\t\tpinged = '{$pinged}',\n\t\t\tpost_modified = '" . current_time('mysql') . "',\n\t\t\tpost_modified_gmt = '" . current_time('mysql', 1) . "',\n\t\t\tpost_parent = '{$post_parent}',\n\t\t\tmenu_order = '{$menu_order}',\n\t\t\tpost_mime_type = '{$post_mime_type}',\n\t\t\tguid = '{$guid}'\n\t\t\tWHERE ID = {$post_ID}");
    } else {
        $wpdb->query("INSERT INTO {$wpdb->posts}\n\t\t\t(post_author, post_date, post_date_gmt, post_content, post_content_filtered, post_title, post_excerpt,  post_status, post_type, comment_status, ping_status, post_password, post_name, to_ping, pinged, post_modified, post_modified_gmt, post_parent, menu_order, post_mime_type, guid)\n\t\t\tVALUES\n\t\t\t('{$post_author}', '{$post_date}', '{$post_date_gmt}', '{$post_content}', '{$post_content_filtered}', '{$post_title}', '{$post_excerpt}', '{$post_status}', '{$post_type}', '{$comment_status}', '{$ping_status}', '{$post_password}', '{$post_name}', '{$to_ping}', '{$pinged}', '{$post_date}', '{$post_date_gmt}', '{$post_parent}', '{$menu_order}', '{$post_mime_type}', '{$guid}')");
        $post_ID = (int) $wpdb->insert_id;
    }
    if (empty($post_name)) {
        $post_name = sanitize_title($post_title, $post_ID);
        $wpdb->query("UPDATE {$wpdb->posts} SET post_name = '{$post_name}' WHERE ID = '{$post_ID}'");
    }
    wp_set_post_categories($post_ID, $post_category);
    if ($file) {
        update_attached_file($post_ID, $file);
    }
    clean_post_cache($post_ID);
    if ($update) {
        do_action('edit_attachment', $post_ID);
    } else {
        do_action('add_attachment', $post_ID);
    }
    return $post_ID;
}