public function toggle_sticky_state($sticky) { if (!$this->validate_request()) { exit; } $success = false; $res = array(); if (isset($_GET['note_id'])) { $note_id = (int) $_GET['note_id']; $note_post = get_post($note_id); if ($note_post && $note_post->post_type == $this->note_post_type) { if ($sticky) { stick_post($note_id); } else { unstick_post($note_id); } $success = true; $note_obj = new USIN_Note($note_id); $user_id = $note_obj->get_note_user(); $all_notes = USIN_Note::get_all($user_id); $res['notes'] = $all_notes; } } $res['success'] = $success; echo json_encode($res); exit; }
public static function wpSetUpBeforeClass($factory) { // Set post times to get a reliable order. $now = time(); for ($i = 0; $i <= 22; $i++) { $post_date = date('Y-m-d H:i:s', $now - 10 * $i); self::$posts[$i] = $factory->post->create(array('post_date' => $post_date)); } stick_post(self::$posts[2]); stick_post(self::$posts[14]); stick_post(self::$posts[8]); }
function testBlogPosts() { $pids = $this->factory->post->create_many(7); $pid = $this->factory->post->create(); stick_post($pid); $pid = $this->factory->post->create(); stick_post($pid); $pid = $this->factory->post->create(); stick_post($pid); $posts = Blades_Home::get_blog_posts(); $this->assertEquals(6, count($posts)); }
public static function setUpBeforeClass() { $f = new WP_UnitTest_Factory(); // Set post times to get a reliable order. $now = time(); for ($i = 0; $i <= 22; $i++) { $post_date = date('Y-m-d H:i:s', $now - 10 * $i); self::$posts[$i] = $f->post->create(array('post_date' => $post_date)); } stick_post(self::$posts[2]); stick_post(self::$posts[14]); stick_post(self::$posts[8]); self::commit_transaction(); }
/** * Create new posts based on import information * * Posts marked as having a parent which doesn't exist will become top level items. * Doesn't create a new post if: the post type doesn't exist, the given post ID * is already noted as imported or a post with the same title and date already exists. * Note that new/updated terms, comments and meta are imported for the last of the above. */ function process_posts() { foreach ($this->posts as $post) { if (!post_type_exists($post['post_type'])) { printf(__('Failed to import “%s”: Invalid post type %s', 'radium'), esc_html($post['post_title']), esc_html($post['post_type'])); echo '<br />'; continue; } if (isset($this->processed_posts[$post['post_id']]) && !empty($post['post_id'])) { continue; } if ($post['status'] == 'auto-draft') { continue; } if ('nav_menu_item' == $post['post_type']) { $this->process_menu_item($post); continue; } $post_type_object = get_post_type_object($post['post_type']); $post_exists = post_exists($post['post_title'], '', $post['post_date']); if ($post_exists && get_post_type($post_exists) == $post['post_type']) { printf(__('%s “%s” already exists.', 'radium'), $post_type_object->labels->singular_name, esc_html($post['post_title'])); echo '<br />'; $comment_post_ID = $post_id = $post_exists; } else { $post_parent = (int) $post['post_parent']; if ($post_parent) { // if we already know the parent, map it to the new local ID if (isset($this->processed_posts[$post_parent])) { $post_parent = $this->processed_posts[$post_parent]; // otherwise record the parent for later } else { $this->post_orphans[intval($post['post_id'])] = $post_parent; $post_parent = 0; } } // map the post author $author = sanitize_user($post['post_author'], true); if (isset($this->author_mapping[$author])) { $author = $this->author_mapping[$author]; } else { $author = (int) get_current_user_id(); } $postdata = array('import_id' => $post['post_id'], 'post_author' => $author, 'post_date' => $post['post_date'], 'post_date_gmt' => $post['post_date_gmt'], 'post_content' => $post['post_content'], 'post_excerpt' => $post['post_excerpt'], 'post_title' => $post['post_title'], 'post_status' => $post['status'], 'post_name' => $post['post_name'], 'comment_status' => $post['comment_status'], 'ping_status' => $post['ping_status'], 'guid' => $post['guid'], 'post_parent' => $post_parent, 'menu_order' => $post['menu_order'], 'post_type' => $post['post_type'], 'post_password' => $post['post_password']); if ('attachment' == $postdata['post_type']) { $remote_url = !empty($post['attachment_url']) ? $post['attachment_url'] : $post['guid']; // try to use _wp_attached file for upload folder placement to ensure the same location as the export site // e.g. location is 2003/05/image.jpg but the attachment post_date is 2010/09, see media_handle_upload() $postdata['upload_date'] = $post['post_date']; if (isset($post['postmeta'])) { foreach ($post['postmeta'] as $meta) { if ($meta['key'] == '_wp_attached_file') { if (preg_match('%^[0-9]{4}/[0-9]{2}%', $meta['value'], $matches)) { $postdata['upload_date'] = $matches[0]; } break; } } } $comment_post_ID = $post_id = $this->process_attachment($postdata, $remote_url); } else { $comment_post_ID = $post_id = wp_insert_post($postdata, true); } if (is_wp_error($post_id)) { printf(__('Failed to import %s “%s”', 'radium'), $post_type_object->labels->singular_name, esc_html($post['post_title'])); if (defined('IMPORT_DEBUG') && IMPORT_DEBUG) { echo ': ' . $post_id->get_error_message(); } echo '<br />'; continue; } if ($post['is_sticky'] == 1) { stick_post($post_id); } } // map pre-import ID to local ID $this->processed_posts[intval($post['post_id'])] = (int) $post_id; // add categories, tags and other terms if (!empty($post['terms'])) { $terms_to_set = array(); foreach ($post['terms'] as $term) { // back compat with WXR 1.0 map 'tag' to 'post_tag' $taxonomy = 'tag' == $term['domain'] ? 'post_tag' : $term['domain']; $term_exists = term_exists($term['slug'], $taxonomy); $term_id = is_array($term_exists) ? $term_exists['term_id'] : $term_exists; if (!$term_id) { $t = wp_insert_term($term['name'], $taxonomy, array('slug' => $term['slug'])); if (!is_wp_error($t)) { $term_id = $t['term_id']; } else { printf(__('Failed to import %s %s', 'radium'), esc_html($taxonomy), esc_html($term['name'])); if (defined('IMPORT_DEBUG') && IMPORT_DEBUG) { echo ': ' . $t->get_error_message(); } echo '<br />'; continue; } } $terms_to_set[$taxonomy][] = intval($term_id); } foreach ($terms_to_set as $tax => $ids) { $tt_ids = wp_set_post_terms($post_id, $ids, $tax); } unset($post['terms'], $terms_to_set); } // add/update comments if (!empty($post['comments'])) { $num_comments = 0; $inserted_comments = array(); foreach ($post['comments'] as $comment) { $comment_id = $comment['comment_id']; $newcomments[$comment_id]['comment_post_ID'] = $comment_post_ID; $newcomments[$comment_id]['comment_author'] = $comment['comment_author']; $newcomments[$comment_id]['comment_author_email'] = $comment['comment_author_email']; $newcomments[$comment_id]['comment_author_IP'] = $comment['comment_author_IP']; $newcomments[$comment_id]['comment_author_url'] = $comment['comment_author_url']; $newcomments[$comment_id]['comment_date'] = $comment['comment_date']; $newcomments[$comment_id]['comment_date_gmt'] = $comment['comment_date_gmt']; $newcomments[$comment_id]['comment_content'] = $comment['comment_content']; $newcomments[$comment_id]['comment_approved'] = $comment['comment_approved']; $newcomments[$comment_id]['comment_type'] = $comment['comment_type']; $newcomments[$comment_id]['comment_parent'] = $comment['comment_parent']; $newcomments[$comment_id]['commentmeta'] = isset($comment['commentmeta']) ? $comment['commentmeta'] : array(); if (isset($this->processed_authors[$comment['comment_user_id']])) { $newcomments[$comment_id]['user_id'] = $this->processed_authors[$comment['comment_user_id']]; } } ksort($newcomments); foreach ($newcomments as $key => $comment) { // if this is a new post we can skip the comment_exists() check if (!$post_exists || !comment_exists($comment['comment_author'], $comment['comment_date'])) { if (isset($inserted_comments[$comment['comment_parent']])) { $comment['comment_parent'] = $inserted_comments[$comment['comment_parent']]; } $comment = wp_filter_comment($comment); $inserted_comments[$key] = wp_insert_comment($comment); foreach ($comment['commentmeta'] as $meta) { $value = maybe_unserialize($meta['value']); add_comment_meta($inserted_comments[$key], $meta['key'], $value); } $num_comments++; } } unset($newcomments, $inserted_comments, $post['comments']); } // add/update post meta if (isset($post['postmeta'])) { foreach ($post['postmeta'] as $meta) { $key = apply_filters('import_post_meta_key', $meta['key']); $value = false; if ('_edit_last' == $key) { if (isset($this->processed_authors[intval($meta['value'])])) { $value = $this->processed_authors[intval($meta['value'])]; } else { $key = false; } } if ($key) { // export gets meta straight from the DB so could have a serialized string if (!$value) { $value = maybe_unserialize($meta['value']); } add_post_meta($post_id, $key, $value); do_action('import_post_meta', $post_id, $key, $value); // if the post has a featured image, take note of this in case of remap if ('_thumbnail_id' == $key) { $this->featured_images[$post_id] = (int) $value; } } } } } unset($this->posts); }
/** * Main AJAX callback * * @param object The post fragment object */ function callback($post_data) { if (!property_exists($post_data, 'postID') || !property_exists($post_data, 'isSticky')) { self::die_failure('invalid_message', __('Insufficient information provided.', 'o2')); } $post = get_post(absint($post_data->postID)); if (!$post) { self::die_failure('post_not_found', __('Post not found.', 'o2')); } if (!current_user_can('edit_post', $post->ID)) { self::die_failure('cannot_edit_post_sticky', __('You are not allowed to edit this post sticky.', 'o2')); } if ($post_data->isSticky) { stick_post($post->ID); } else { unstick_post($post->ID); } // Bump the post to make it update in polling o2_Fragment::bump_post($post->ID); $retval = array('isSticky' => is_sticky($post->ID)); self::die_success($retval); }
/** * Process the post data for the bulk editing of posts. * * Updates all bulk edited posts/pages, adding (but not removing) tags and * categories. Skips pages when they would be their own parent or child. * * @since 2.7.0 * * @global wpdb $wpdb WordPress database abstraction object. * * @param array $post_data Optional, the array of post data to process if not provided will use $_POST superglobal. * @return array */ function bulk_edit_posts($post_data = null) { global $wpdb; if (empty($post_data)) { $post_data =& $_POST; } if (isset($post_data['post_type'])) { $ptype = get_post_type_object($post_data['post_type']); } else { $ptype = get_post_type_object('post'); } if (!current_user_can($ptype->cap->edit_posts)) { if ('page' == $ptype->name) { wp_die(__('Sorry, you are not allowed to edit pages.')); } else { wp_die(__('Sorry, you are not allowed to edit posts.')); } } if (-1 == $post_data['_status']) { $post_data['post_status'] = null; unset($post_data['post_status']); } else { $post_data['post_status'] = $post_data['_status']; } unset($post_data['_status']); if (!empty($post_data['post_status'])) { $post_data['post_status'] = sanitize_key($post_data['post_status']); if ('inherit' == $post_data['post_status']) { unset($post_data['post_status']); } } $post_IDs = array_map('intval', (array) $post_data['post']); $reset = array('post_author', 'post_status', 'post_password', 'post_parent', 'page_template', 'comment_status', 'ping_status', 'keep_private', 'tax_input', 'post_category', 'sticky', 'post_format'); foreach ($reset as $field) { if (isset($post_data[$field]) && ('' == $post_data[$field] || -1 == $post_data[$field])) { unset($post_data[$field]); } } if (isset($post_data['post_category'])) { if (is_array($post_data['post_category']) && !empty($post_data['post_category'])) { $new_cats = array_map('absint', $post_data['post_category']); } else { unset($post_data['post_category']); } } $tax_input = array(); if (isset($post_data['tax_input'])) { foreach ($post_data['tax_input'] as $tax_name => $terms) { if (empty($terms)) { continue; } if (is_taxonomy_hierarchical($tax_name)) { $tax_input[$tax_name] = array_map('absint', $terms); } else { $comma = _x(',', 'tag delimiter'); if (',' !== $comma) { $terms = str_replace($comma, ',', $terms); } $tax_input[$tax_name] = explode(',', trim($terms, " \n\t\r\v,")); } } } if (isset($post_data['post_parent']) && ($parent = (int) $post_data['post_parent'])) { $pages = $wpdb->get_results("SELECT ID, post_parent FROM {$wpdb->posts} WHERE post_type = 'page'"); $children = array(); for ($i = 0; $i < 50 && $parent > 0; $i++) { $children[] = $parent; foreach ($pages as $page) { if ($page->ID == $parent) { $parent = $page->post_parent; break; } } } } $updated = $skipped = $locked = array(); $shared_post_data = $post_data; foreach ($post_IDs as $post_ID) { // Start with fresh post data with each iteration. $post_data = $shared_post_data; $post_type_object = get_post_type_object(get_post_type($post_ID)); if (!isset($post_type_object) || isset($children) && in_array($post_ID, $children) || !current_user_can('edit_post', $post_ID)) { $skipped[] = $post_ID; continue; } if (wp_check_post_lock($post_ID)) { $locked[] = $post_ID; continue; } $post = get_post($post_ID); $tax_names = get_object_taxonomies($post); foreach ($tax_names as $tax_name) { $taxonomy_obj = get_taxonomy($tax_name); if (isset($tax_input[$tax_name]) && current_user_can($taxonomy_obj->cap->assign_terms)) { $new_terms = $tax_input[$tax_name]; } else { $new_terms = array(); } if ($taxonomy_obj->hierarchical) { $current_terms = (array) wp_get_object_terms($post_ID, $tax_name, array('fields' => 'ids')); } else { $current_terms = (array) wp_get_object_terms($post_ID, $tax_name, array('fields' => 'names')); } $post_data['tax_input'][$tax_name] = array_merge($current_terms, $new_terms); } if (isset($new_cats) && in_array('category', $tax_names)) { $cats = (array) wp_get_post_categories($post_ID); $post_data['post_category'] = array_unique(array_merge($cats, $new_cats)); unset($post_data['tax_input']['category']); } $post_data['post_type'] = $post->post_type; $post_data['post_mime_type'] = $post->post_mime_type; $post_data['guid'] = $post->guid; foreach (array('comment_status', 'ping_status', 'post_author') as $field) { if (!isset($post_data[$field])) { $post_data[$field] = $post->{$field}; } } $post_data['ID'] = $post_ID; $post_data['post_ID'] = $post_ID; $post_data = _wp_translate_postdata(true, $post_data); if (is_wp_error($post_data)) { $skipped[] = $post_ID; continue; } $updated[] = wp_update_post($post_data); if (isset($post_data['sticky']) && current_user_can($ptype->cap->edit_others_posts)) { if ('sticky' == $post_data['sticky']) { stick_post($post_ID); } else { unstick_post($post_ID); } } if (isset($post_data['post_format'])) { set_post_format($post_ID, $post_data['post_format']); } } return array('updated' => $updated, 'skipped' => $skipped, 'locked' => $locked); }
/** * {@internal Missing Short Description}} * * Updates all bulk edited posts/pages, adding (but not removing) tags and * categories. Skips pages when they would be their own parent or child. * * @since unknown * * @return array */ function bulk_edit_posts($post_data = null) { global $wpdb; if (empty($post_data)) { $post_data =& $_POST; } if (isset($post_data['post_type']) && 'page' == $post_data['post_type']) { if (!current_user_can('edit_pages')) { wp_die(__('You are not allowed to edit pages.')); } } else { if (!current_user_can('edit_posts')) { wp_die(__('You are not allowed to edit posts.')); } } $post_IDs = array_map('intval', (array) $post_data['post']); $reset = array('post_author', 'post_status', 'post_password', 'post_parent', 'page_template', 'comment_status', 'ping_status', 'keep_private', 'tags_input', 'post_category', 'sticky'); foreach ($reset as $field) { if (isset($post_data[$field]) && ('' == $post_data[$field] || -1 == $post_data[$field])) { unset($post_data[$field]); } } if (isset($post_data['post_category'])) { if (is_array($post_data['post_category']) && !empty($post_data['post_category'])) { $new_cats = array_map(absint, $post_data['post_category']); } else { unset($post_data['post_category']); } } if (isset($post_data['tags_input'])) { $new_tags = preg_replace('/\\s*,\\s*/', ',', rtrim(trim($post_data['tags_input']), ' ,')); $new_tags = explode(',', $new_tags); } if (isset($post_data['post_parent']) && ($parent = (int) $post_data['post_parent'])) { $pages = $wpdb->get_results("SELECT ID, post_parent FROM {$wpdb->posts} WHERE post_type = 'page'"); $children = array(); for ($i = 0; $i < 50 && $parent > 0; $i++) { $children[] = $parent; foreach ($pages as $page) { if ($page->ID == $parent) { $parent = $page->post_parent; break; } } } } $updated = $skipped = $locked = array(); foreach ($post_IDs as $post_ID) { if (isset($children) && in_array($post_ID, $children)) { $skipped[] = $post_ID; continue; } if (wp_check_post_lock($post_ID)) { $locked[] = $post_ID; continue; } if (isset($new_cats)) { $cats = (array) wp_get_post_categories($post_ID); $post_data['post_category'] = array_unique(array_merge($cats, $new_cats)); } if (isset($new_tags)) { $tags = wp_get_post_tags($post_ID, array('fields' => 'names')); $post_data['tags_input'] = array_unique(array_merge($tags, $new_tags)); } $post_data['ID'] = $post_ID; $updated[] = wp_update_post($post_data); if (current_user_can('edit_others_posts') && isset($post_data['sticky'])) { if ('sticky' == $post_data['sticky']) { stick_post($post_ID); } else { unstick_post($post_ID); } } } return array('updated' => $updated, 'skipped' => $skipped, 'locked' => $locked); }
/** * function to map the csv file and process it * * @return boolean */ function processDataInWP($data_rows, $ret_array, $session_arr, $currentLimit, $extractedimagelocation, $importinlineimageoption, $sample_inlineimage_url = null) { global $wpdb; $post_id = ''; $new_post = array(); $smack_taxo = array(); $custom_array = array(); $seo_custom_array = array(); $imported_feature_img = array(); $headr_count = $ret_array['h2']; //for ($i = 0; $i < count($data_rows); $i++) { for ($i = 0; $i <= $ret_array['basic_count']; $i++) { if (array_key_exists('coremapping' . $i, $ret_array)) { if ($ret_array['coretextbox' . $i] != '-- Select --' && $ret_array['coremapping' . $i] != '') { $mappedindex = str_replace('textbox', '', $ret_array['coretextbox' . $i]); $new_post[$ret_array['coremapping' . $i]] = $data_rows[$mappedindex]; $custom_array[$ret_array['coremapping' . $i]] = $data_rows[$mappedindex]; } } else { if (array_key_exists('mapping' . $i, $ret_array)) { if ($ret_array['mapping' . $i] != '-- Select --') { if ($ret_array['mapping' . $i] != 'add_custom' . $i) { $strip_CF = strpos($ret_array['mapping' . $i], 'CF: '); $strip_SEO = strpos($ret_array['mapping' . $i], 'SEO: '); if ($strip_CF === 0) { $custom_key = substr($ret_array['mapping' . $i], 4); $custom_array[$custom_key] = $data_rows[$i]; } elseif ($strip_SEO === 0) { $seo_key = substr($ret_array['mapping' . $i], 5); $seo_custom_array[$seo_key] = $data_rows[$i]; } else { $new_post[$ret_array['mapping' . $i]] = $data_rows[$i]; } } else { $new_post[$ret_array['textbox' . $i]] = $data_rows[$i]; $custom_array[$ret_array['textbox' . $i]] = $data_rows[$i]; } } } } } /* for($j = 0; $j< $ret_array['corecustomcount'];j++){ if(array_key_exists('coremapping' . $i,$ret_array)){ echo '<pre>';print_r($ret_array['coretextbox' . $i]);echo '</pre>'; if($ret_array['coretextbox' . $i] != '-- Select --'){ $mappedindex = str_replace('textbox','',$ret_array['coretextbox'.$i]); echo '<pre>';print_r($mappedindex);echo '</pre>';die; //$new_post[$ret_array['coretextbox'.$i]] = $data_rows[]; //$custom_array[$ret_array['coremapping'.$i]] = $data_rows[$i]; } } }*/ for ($inc = 0; $inc < count($data_rows); $inc++) { foreach ($this->keys as $k => $v) { if (array_key_exists($v, $new_post)) { $custom_array[$v] = $new_post[$v]; } } } if (is_array($new_post)) { foreach ($new_post as $ckey => $cval) { $this->postFlag = true; $taxo = get_taxonomies(); foreach ($taxo as $taxokey => $taxovalue) { if ($taxokey != 'category' && $taxokey != 'link_category' && $taxokey != 'post_tag' && $taxokey != 'nav_menu' && $taxokey != 'post_format') { if ($taxokey == $ckey) { $smack_taxo[$ckey] = $new_post[$ckey]; } } } $taxo_check = 0; if (!isset($smack_taxo[$ckey])) { $smack_taxo[$ckey] = null; $taxo_check = 1; } if ($ckey != 'post_category' && $ckey != 'post_tag' && $ckey != 'featured_image' && $ckey != $smack_taxo[$ckey] && $ckey != 'wp_page_template') { if ($taxo_check == 1) { unset($smack_taxo[$ckey]); $taxo_check = 0; } if (array_key_exists($ckey, $custom_array)) { $darray[$ckey] = $new_post[$ckey]; } else { if (array_key_exists($ckey, $smack_taxo)) { $data_array[$ckey] = null; } else { $data_array[$ckey] = $new_post[$ckey]; } } } else { switch ($ckey) { case 'post_tag': $tags[$ckey] = $new_post[$ckey]; break; case 'post_category': $categories[$ckey] = $new_post[$ckey]; break; case 'wp_page_template': $custom_array['_wp_page_template'] = $new_post[$ckey]; break; case 'featured_image': require_once ABSPATH . "wp-includes/pluggable.php"; require_once ABSPATH . 'wp-admin/includes/image.php'; $dir = wp_upload_dir(); $get_media_settings = get_option('uploads_use_yearmonth_folders'); if ($get_media_settings == 1) { $dirname = date('Y') . '/' . date('m'); $full_path = $dir['basedir'] . '/' . $dirname; $baseurl = $dir['baseurl'] . '/' . $dirname; } else { $full_path = $dir['basedir']; $baseurl = $dir['baseurl']; } $f_img = $new_post[$ckey]; $fimg_path = $full_path; $fimg_name = @basename($f_img); $featured_image = $fimg_name; $fimg_name = strtolower(str_replace(' ', '-', $fimg_name)); $fimg_name = preg_replace('/[^a-zA-Z0-9._\\s]/', '', $fimg_name); $fimg_name = urlencode($fimg_name); $parseURL = parse_url($f_img); $path_parts = pathinfo($f_img); if (!isset($path_parts['extension'])) { $fimg_name = $fimg_name . '.jpg'; } //else // $fimg_name = $fimg_name.'.'.$path_parts['extension']; $f_img_slug = ''; $f_img_slug = strtolower(str_replace('', '-', $f_img_slug)); $f_img_slug = preg_replace('/[^a-zA-Z0-9._\\s]/', '', $f_img_slug); $post_slug_value = strtolower($f_img_slug); if (array_key_exists('extension', $path_parts)) { //$fimg_name = wp_unique_filename($fimg_path, $fimg_name, $path_parts['extension']); } $this->get_fimg_from_URL($f_img, $fimg_path, $fimg_name, $post_slug_value, $currentLimit, $this); $filepath = $fimg_path . "/" . $fimg_name; if (@getimagesize($filepath)) { $img = wp_get_image_editor($filepath); /*if (!is_wp_error($img)) { $sizes_array = array( // #1 - resizes to 1024x768 pixel, square-cropped image array('width' => 1024, 'height' => 768, 'crop' => true), // #2 - resizes to 100px max width/height, non-cropped image array('width' => 100, 'height' => 100, 'crop' => false), // #3 - resizes to 100 pixel max height, non-cropped image array('width' => 300, 'height' => 100, 'crop' => false), // #3 - resizes to 624x468 pixel max width, non-cropped image array('width' => 624, 'height' => 468, 'crop' => false) ); $resize = $img->multi_resize($sizes_array); }*/ $file['guid'] = $baseurl . "/" . $fimg_name; $file['post_title'] = $fimg_name; $file['post_content'] = ''; $file['post_status'] = 'attachment'; } else { $file = false; } break; } } } } if ($_SESSION['SMACK_MAPPING_SETTINGS_VALUES']['selectedImporter'] != 'custompost') { $data_array['post_type'] = $_SESSION['SMACK_MAPPING_SETTINGS_VALUES']['selectedImporter']; } else { $data_array['post_type'] = $_SESSION['SMACK_MAPPING_SETTINGS_VALUES']['custompostlist']; } if ($this->titleDupCheck == 'true') { $this->postFlag = $this->duplicateChecks('title', $data_array['post_title'], $data_array['post_type'], $currentLimit, $data_array['post_title']); } if ($this->conDupCheck == 'true' && $this->postFlag) { $this->postFlag = $this->duplicateChecks('content', $data_array['post_content'], $data_array['post_type'], $currentLimit, $data_array['post_title']); } if ($this->titleDupCheck == 'true' && $this->conDupCheck == 'true') { $this->postFlag = $this->duplicateChecks('title && content', $data_array['post_content'], $data_array['post_type'], $currentLimit, $data_array['post_title']); } if ($this->postFlag) { unset($sticky); if (empty($data_array['post_status'])) { $data_array['post_status'] = null; } if ($_SESSION['SMACK_MAPPING_SETTINGS_VALUES']['importallwithps'] != 0) { $data_array['post_status'] = $_SESSION['SMACK_MAPPING_SETTINGS_VALUES']['importallwithps']; } switch ($data_array['post_status']) { case 1: $data_array['post_status'] = 'publish'; $this->detailedLog[$currentLimit]['poststatus'] = "<b>" . __('Status', 'wp-ultimate-csv-importer') . " - </b>" . __('publish', 'wp-ultimate-csv-importer'); break; case 2: $data_array['post_status'] = 'publish'; $sticky = true; $this->detailedLog[$currentLimit]['poststatus'] = "<b>" . __('Status', 'wp-ultimate-csv-importer') . " - </b>" . __('sticky', 'wp-ultimate-csv-importer'); break; case 3: $data_array['post_status'] = 'publish'; $data_array['post_password'] = $_POST['postsPassword']; $this->detailedLog[$currentLimit]['poststatus'] = "<b>" . __('Status', 'wp-ultimate-csv-importer') . " - </b>" . __('protected with password', 'wp-ultimate-csv-importer') . $data_array['post_password']; break; case 4: $data_array['post_status'] = 'private'; $this->detailedLog[$currentLimit]['poststatus'] = "<b>" . __('Status', 'wp-ultimate-csv-importer') . " - </b>" . __('private', 'wp-ultimate-csv-importer'); break; case 5: $data_array['post_status'] = 'draft'; $this->detailedLog[$currentLimit]['poststatus'] = "<b>" . __('Status', 'wp-ultimate-csv-importer') . " - </b>" . __('draft', 'wp-ultimate-csv-importer'); break; case 6: $data_array['post_status'] = 'pending'; $this->detailedLog[$currentLimit]['poststatus'] = "<b>" . __('Status', 'wp-ultimate-csv-importer') . " - </b>" . __('pending', 'wp-ultimate-csv-importer'); break; default: $poststatus = $data_array['post_status'] = strtolower($data_array['post_status']); if ($data_array['post_status'] != 'publish' && $data_array['post_status'] != 'private' && $data_array['post_status'] != 'draft' && $data_array['post_status'] != 'pending' && $data_array['post_status'] != 'sticky') { $stripPSF = strpos($data_array['post_status'], '{'); if ($stripPSF === 0) { $poststatus = substr($data_array['post_status'], 1); $stripPSL = substr($poststatus, -1); if ($stripPSL == '}') { $postpwd = substr($poststatus, 0, -1); $data_array['post_status'] = 'publish'; $data_array['post_password'] = $postpwd; $this->detailedLog[$currentLimit]['poststatus'] = "<b>" . __('Status', 'wp-ultimate-csv-importer') . " - </b>" . __('protected with password', 'wp-ultimate-csv-importer') . $data_array['post_password']; } else { $data_array['post_status'] = 'publish'; $data_array['post_password'] = $poststatus; $this->detailedLog[$currentLimit]['poststatus'] = "<b>" . __('Status', 'wp-ultimate-csv-importer') . " - </b>" . __('protected with password', 'wp-ultimate-csv-importer') . $data_array['post_password']; } } else { $data_array['post_status'] = 'publish'; $this->detailedLog[$currentLimit]['poststatus'] = "<b>" . __('Status', 'wp-ultimate-csv-importer') . " - </b>" . __('publish', 'wp-ultimate-csv-importer'); } } if ($data_array['post_status'] == 'sticky') { $data_array['post_status'] = 'publish'; $sticky = true; $this->detailedLog[$currentLimit]['poststatus'] = "<b>" . __('Status', 'wp-ultimate-csv-importer') . " - </b>" . __('sticky', 'wp-ultimate-csv-importer'); } else { $this->detailedLog[$currentLimit]['poststatus'] = "<b>" . __('Status', 'wp-ultimate-csv-importer') . " - </b>" . $data_array['post_status']; } } // Post Format Options if (isset($data_array['post_format'])) { $post_format = 0; switch ($data_array['post_format']) { case 1: $post_format = 'post-format-aside'; break; case 2: $post_format = 'post-format-image'; break; case 3: $post_format = 'post-format-video'; break; case 4: $post_format = 'post-format-audio'; break; case 5: $post_format = 'post-format-quote'; break; case 6: $post_format = 'post-format-link'; break; case 7: $post_format = 'post-format-gallery'; break; default: if ($data_array['post_format'] == 'post-format-aside') { $post_format = 'post-format-aside'; break; } if ($data_array['post_format'] == 'post-format-image') { $post_format = 'post-format-image'; break; } if ($data_array['post_format'] == 'post-format-video') { $post_format = 'post-format-video'; break; } if ($data_array['post_format'] == 'post-format-audio') { $post_format = 'post-format-audio'; break; } if ($data_array['post_format'] == 'post-format-quote') { $post_format = 'post-format-quote'; break; } if ($data_array['post_format'] == 'post-format-link') { $post_format = 'post-format-link'; break; } if ($data_array['post_format'] == 'post-format-gallery') { $post_format = 'post-format-gallery'; break; } $post_format = 0; } } // Author name/id update if (isset($data_array['post_author'])) { $authorLen = strlen($data_array['post_author']); $postuserid = $data_array['post_author']; $checkpostuserid = intval($data_array['post_author']); $postAuthorLen = strlen($checkpostuserid); $postauthor = array(); if ($authorLen == $postAuthorLen) { $postauthor = $wpdb->get_results("select ID,user_login from {$wpdb->users} where ID = \"{$postuserid}\""); if (empty($postauthor) || !$postauthor[0]->ID) { // If user name are numeric Ex: 1300001 $postauthor = $wpdb->get_results("select ID,user_login from {$wpdb->users} where user_login = \"{$postuserid}\""); } } else { $postauthor = $wpdb->get_results("select ID,user_login from {$wpdb->users} where user_login = \"{$postuserid}\""); } if (empty($postauthor) || !$postauthor[0]->ID) { $data_array['post_author'] = 1; $admindet = $wpdb->get_results("select ID,user_login from {$wpdb->users} where ID = 1"); $this->detailedLog[$currentLimit]['assigned_author'] = "<b>" . __('Author - not found (assigned to', 'wp-ultimate-csv-importer') . " </b>" . $admindet[0]->user_login . ")"; $this->noPostAuthCount++; } else { $data_array['post_author'] = $postauthor[0]->ID; $this->detailedLog[$currentLimit]['assigned_author'] = "<b>" . __('Author', 'wp-ultimate-csv-importer') . " - </b>" . $postauthor[0]->user_login; } } else { $data_array['post_author'] = 1; $admindet = $wpdb->get_results("select ID,user_login from {$wpdb->users} where ID = 1"); $this->detailedLog[$currentLimit]['assigned_author'] = "<b>" . __('Author - not found (assigned to', 'wp-ultimate-csv-importer') . " </b>" . $admindet[0]->user_login . ")"; $this->noPostAuthCount++; } // Date format post $data_array['post_date'] = str_replace('/', '-', $data_array['post_date']); if (!isset($data_array['post_date'])) { $data_array['post_date'] = date('Y-m-d H:i:s'); $this->detailedLog[$currentLimit]['postdate'] = "<b>" . __('Date', 'wp-ultimate-csv-importer') . " - </b>" . $data_array['post_date']; } else { $data_array['post_date'] = date('Y-m-d H:i:s', strtotime($data_array['post_date'])); $this->detailedLog[$currentLimit]['postdate'] = "<b>" . __('Date', 'wp-ultimate-csv-importer') . " - </b>" . $data_array['post_date']; } if (isset($data_array['post_slug'])) { $data_array['post_name'] = $data_array['post_slug']; } //add global password if ($data_array) { if ($ret_array['importallwithps'] == 3) { $data_array['post_password'] = $ret_array['globalpassword_txt']; $this->detailedLog[$currentLimit]['poststatus'] = "<b>" . __('Status', 'wp-ultimate-csv-importer') . " - </b>" . __('protected with password', 'wp-ultimate-csv-importer') . $ret_array['globalpassword_txt']; } } if ($data_array) { if ($this->MultiImages == 'true') { // Inline image import feature by fredrick marks $inlineImagesObj = new WPImporter_inlineImages(); $postid = wp_insert_post($data_array); $post_id = $inlineImagesObj->importwithInlineImages($postid, $currentLimit, $data_array, $this, $importinlineimageoption, $extractedimagelocation, $sample_inlineimage_url); // $inline_shortcode = $inlineImagesObj->capture_all_shortcodes($data_array['post_content']); } else { $post_id = wp_insert_post($data_array); $this->detailedLog[$currentLimit]['post_id'] = "<b>" . __('Created Post_ID', 'wp-ultimate-csv-importer') . " - </b>" . $post_id . " - success"; } } unset($postauthor); if ($post_id) { $uploaded_file_name = $session_arr['uploadedFile']; $real_file_name = $session_arr['uploaded_csv_name']; // $version = $session_arr['currentfileversion']; $action = $data_array['post_type']; /* $version_arr=array(); $version_arr=explode("(",$uploaded_file_name); $version_arr=explode(")",$version_arr[1]); $version=$version_arr[0]; */ $get_imported_feature_image = array(); $get_imported_feature_image = get_option('IMPORTED_FEATURE_IMAGES'); if (is_array($get_imported_feature_image)) { $imported_feature_img = array_merge($get_imported_feature_image, $imported_feature_img); } else { $imported_feature_img = $imported_feature_img; } update_option('IMPORTED_FEATURE_IMAGES', $imported_feature_img); $created_records[$action][] = $post_id; if ($action == 'post') { $imported_as = 'Post'; } if ($action == 'page') { $imported_as = 'Page'; } if ($action != 'post' && $action != 'page') { $imported_as = 'Custom Post'; } $keyword = $action; $this->insPostCount++; if (isset($sticky) && $sticky) { stick_post($post_id); } if (!empty($custom_array)) { foreach ($custom_array as $custom_key => $custom_value) { update_post_meta($post_id, $custom_key, $custom_value); } } // Import post formats added by fredrick marks if (isset($post_format)) { wp_set_object_terms($post_id, $post_format, 'post_format'); } //Import SEO Values if (!empty($seo_custom_array)) { $this->importSEOfields($seo_custom_array, $post_id); } // Create custom taxonomy to post if (!empty($smack_taxo)) { foreach ($smack_taxo as $taxo_key => $taxo_value) { if (!empty($taxo_value)) { $split_line = explode('|', $taxo_value); wp_set_object_terms($post_id, $split_line, $taxo_key); } } } // Create/Add tags to post if (!empty($tags)) { $this->detailedLog[$currentLimit]['tags'] = ""; foreach ($tags as $tag_key => $tag_value) { $this->detailedLog[$currentLimit]['tags'] .= $tag_value . "|"; wp_set_post_tags($post_id, $tag_value); } $this->detailedLog[$currentLimit]['tags'] = "<b>" . __('Tags', 'wp-ultimate-csv-importer') . " - </b>" . substr($this->detailedLog[$currentLimit]['tags'], 0, -1); } // Create/Add category to post if (!empty($categories)) { $this->detailedLog[$currentLimit]['category'] = ""; $assigned_categories = array(); $split_cate = explode('|', $categories['post_category']); foreach ($split_cate as $key => $val) { if (is_numeric($val)) { $split_cate[$key] = 'uncategorized'; $assigned_categories['uncategorized'] = 'uncategorized'; } $assigned_categories[$val] = $val; } foreach ($assigned_categories as $cateKey => $cateVal) { $this->detailedLog[$currentLimit]['category'] .= $cateKey . "|"; } $this->detailedLog[$currentLimit]['category'] = "<b>" . __('Category', 'wp-ultimate-csv-importer') . " - </b>" . substr($this->detailedLog[$currentLimit]['category'], 0, -1); wp_set_object_terms($post_id, $split_cate, 'category'); } // Add featured image if (!empty($file)) { //$wp_filetype = wp_check_filetype(@basename($file ['guid']), null); $wp_upload_dir = wp_upload_dir(); $attachment = array('guid' => $file['guid'], 'post_mime_type' => 'image/jpeg', 'post_title' => preg_replace('/[^a-zA-Z0-9._\\s]/', '', @basename($file['guid'])), 'post_content' => '', 'post_status' => 'inherit'); if ($get_media_settings == 1) { $generate_attachment = $dirname . '/' . $fimg_name; } else { $generate_attachment = $fimg_name; } $uploadedImage = $wp_upload_dir['path'] . '/' . $fimg_name; /*$attach_id = wp_insert_attachment($attachment, $generate_attachment, $post_id); $attach_data = wp_generate_attachment_metadata($attach_id, $uploadedImage); wp_update_attachment_metadata($attach_id, $attach_data);*/ $existing_attachment = array(); $query = $wpdb->get_results("select post_title from {$wpdb->posts} where post_type = 'attachment' and post_mime_type = 'image/jpeg'"); foreach ($query as $key) { $existing_attachment[] = $key->post_title; } if (!in_array($fimg_name, $existing_attachment)) { $attach_id = wp_insert_attachment($attachment, $generate_attachment, $post_id); $attach_data = wp_generate_attachment_metadata($attach_id, $uploadedImage); wp_update_attachment_metadata($attach_id, $attach_data); } else { $query2 = $wpdb->get_results("select ID from {$wpdb->posts} where post_title = '{$fimg_name}' and post_type = 'attachment'"); foreach ($query2 as $key2) { $attach_id = $key2->ID; } } set_post_thumbnail($post_id, $attach_id); } } else { $skippedRecords[] = $_SESSION['SMACK_SKIPPED_RECORDS']; } $this->detailedLog[$currentLimit]['verify_here'] = "<b>Verify Here -</b> <a href='" . get_permalink($post_id) . "' title='" . esc_attr(sprintf(__('View “%s”'), $data_array['post_title'])) . "' rel='permalink' target='_blank'>" . __('Web View', 'wp-ultimate-csv-importer') . "</a> | <a href='" . get_edit_post_link($post_id, true) . "' title='" . esc_attr(__('Edit this item', 'wp-ultimate-csv-importer')) . "' target='_blank'>" . __('Admin View', 'wp-ultimate-csv-importer') . "</a>"; } unset($data_array); }
function test_password_transition_unsticky() { // when transitioning to private status or adding a post password, post should be un-stuck $editor_id = $this->make_user_by_role( 'editor' ); $post_id = $this->factory->post->create( array( 'post_author' => $editor_id ) ); stick_post( $post_id ); $post2 = array( 'post_password' => 'foobar', 'sticky' => false ); $result = $this->myxmlrpcserver->wp_editPost( array( 1, 'editor', 'editor', $post_id, $post2 ) ); $this->assertNotInstanceOf( 'IXR_Error', $result ); $this->assertFalse( is_sticky( $post_id ) ); }
/** * Edit a post. * * @since 1.5.0 * * @param array $args Method parameters. * @return bool True on success. */ function mw_editPost($args) { $this->escape($args); $post_ID = (int) $args[0]; $username = $args[1]; $password = $args[2]; $content_struct = $args[3]; $publish = $args[4]; if (!($user = $this->login($username, $password))) { return $this->error; } do_action('xmlrpc_call', 'metaWeblog.editPost'); $cap = $publish ? 'publish_posts' : 'edit_posts'; $error_message = __('Sorry, you are not allowed to publish posts on this site.'); $post_type = 'post'; $page_template = ''; if (!empty($content_struct['post_type'])) { if ($content_struct['post_type'] == 'page') { $cap = $publish ? 'publish_pages' : 'edit_pages'; $error_message = __('Sorry, you are not allowed to publish pages on this site.'); $post_type = 'page'; if (!empty($content_struct['wp_page_template'])) { $page_template = $content_struct['wp_page_template']; } } elseif ($content_struct['post_type'] == 'post') { // This is the default, no changes needed } else { // No other post_type values are allowed here return new IXR_Error(401, __('Invalid post type.')); } } if (!current_user_can($cap)) { return new IXR_Error(401, $error_message); } $postdata = wp_get_single_post($post_ID, ARRAY_A); // If there is no post data for the give post id, stop // now and return an error. Other wise a new post will be // created (which was the old behavior). if (empty($postdata["ID"])) { return new IXR_Error(404, __("Invalid post ID.")); } $this->escape($postdata); extract($postdata, EXTR_SKIP); // Let WordPress manage slug if none was provided. $post_name = ""; if (isset($content_struct["wp_slug"])) { $post_name = $content_struct["wp_slug"]; } // Only use a password if one was given. if (isset($content_struct["wp_password"])) { $post_password = $content_struct["wp_password"]; } // Only set a post parent if one was given. if (isset($content_struct["wp_page_parent_id"])) { $post_parent = $content_struct["wp_page_parent_id"]; } // Only set the menu_order if it was given. if (isset($content_struct["wp_page_order"])) { $menu_order = $content_struct["wp_page_order"]; } $post_author = $postdata["post_author"]; // Only set the post_author if one is set. if (isset($content_struct["wp_author_id"]) && $user->ID != $content_struct["wp_author_id"]) { switch ($post_type) { case "post": if (!current_user_can("edit_others_posts")) { return new IXR_Error(401, __("You are not allowed to change the post author as this user.")); } break; case "page": if (!current_user_can("edit_others_pages")) { return new IXR_Error(401, __("You are not allowed to change the page author as this user.")); } break; default: return new IXR_Error(401, __("Invalid post type.")); break; } $post_author = $content_struct["wp_author_id"]; } if (isset($content_struct["mt_allow_comments"])) { if (!is_numeric($content_struct["mt_allow_comments"])) { switch ($content_struct["mt_allow_comments"]) { case "closed": $comment_status = "closed"; break; case "open": $comment_status = "open"; break; default: $comment_status = get_option("default_comment_status"); break; } } else { switch ((int) $content_struct["mt_allow_comments"]) { case 0: case 2: $comment_status = "closed"; break; case 1: $comment_status = "open"; break; default: $comment_status = get_option("default_comment_status"); break; } } } if (isset($content_struct["mt_allow_pings"])) { if (!is_numeric($content_struct["mt_allow_pings"])) { switch ($content_struct["mt_allow_pings"]) { case "closed": $ping_status = "closed"; break; case "open": $ping_status = "open"; break; default: $ping_status = get_option("default_ping_status"); break; } } else { switch ((int) $content_struct["mt_allow_pings"]) { case 0: $ping_status = "closed"; break; case 1: $ping_status = "open"; break; default: $ping_status = get_option("default_ping_status"); break; } } } $post_title = $content_struct['title']; $post_content = $content_struct['description']; $catnames = $content_struct['categories']; $post_category = array(); if (is_array($catnames)) { foreach ($catnames as $cat) { $post_category[] = get_cat_ID($cat); } } $post_excerpt = $content_struct['mt_excerpt']; $post_more = $content_struct['mt_text_more']; $post_status = $publish ? 'publish' : 'draft'; if (isset($content_struct["{$post_type}_status"])) { switch ($content_struct["{$post_type}_status"]) { case 'draft': case 'private': case 'publish': $post_status = $content_struct["{$post_type}_status"]; break; case 'pending': // Pending is only valid for posts, not pages. if ($post_type === 'post') { $post_status = $content_struct["{$post_type}_status"]; } break; default: $post_status = $publish ? 'publish' : 'draft'; break; } } $tags_input = $content_struct['mt_keywords']; if ('publish' == $post_status) { if ('page' == $post_type && !current_user_can('publish_pages')) { return new IXR_Error(401, __('Sorry, you do not have the right to publish this page.')); } else { if (!current_user_can('publish_posts')) { return new IXR_Error(401, __('Sorry, you do not have the right to publish this post.')); } } } if ($post_more) { $post_content = $post_content . "<!--more-->" . $post_more; } $to_ping = $content_struct['mt_tb_ping_urls']; if (is_array($to_ping)) { $to_ping = implode(' ', $to_ping); } // Do some timestamp voodoo if (!empty($content_struct['date_created_gmt'])) { $dateCreated = str_replace('Z', '', $content_struct['date_created_gmt']->getIso()) . 'Z'; } elseif (!empty($content_struct['dateCreated'])) { $dateCreated = $content_struct['dateCreated']->getIso(); } if (!empty($dateCreated)) { $post_date = get_date_from_gmt(iso8601_to_datetime($dateCreated)); $post_date_gmt = iso8601_to_datetime($dateCreated, GMT); } else { $post_date = $postdata['post_date']; $post_date_gmt = $postdata['post_date_gmt']; } // We've got all the data -- post it: $newpost = compact('ID', 'post_content', 'post_title', 'post_category', 'post_status', 'post_excerpt', 'comment_status', 'ping_status', 'post_date', 'post_date_gmt', 'to_ping', 'post_name', 'post_password', 'post_parent', 'menu_order', 'post_author', 'tags_input', 'page_template'); $result = wp_update_post($newpost, true); if (is_wp_error($result)) { return new IXR_Error(500, $result->get_error_message()); } if (!$result) { return new IXR_Error(500, __('Sorry, your entry could not be edited. Something wrong happened.')); } // Only posts can be sticky if ($post_type == 'post' && isset($content_struct['sticky'])) { if ($content_struct['sticky'] == true) { stick_post($post_ID); } elseif ($content_struct['sticky'] == false) { unstick_post($post_ID); } } if (isset($content_struct['custom_fields'])) { $this->set_custom_fields($post_ID, $content_struct['custom_fields']); } // Handle enclosures $this->add_enclosure_if_new($post_ID, $content_struct['enclosure']); $this->attach_uploads($ID, $post_content); logIO('O', "(MW) Edited ! ID: {$post_ID}"); return true; }
/** * If the `edit_post()` method is invoked by a user without publish_posts permission, the sticky status of the post * should not be changed. * * @ticket 24153 */ function test_user_without_publish_cannot_affect_sticky_with_edit_post() { // Create a sticky post. $post = $this->factory->post->create_and_get( array( 'post_title' => 'Will be changed', 'post_content' => 'Will be changed', ) ); stick_post( $post->ID ); // Sanity Check. $this->assertTrue( is_sticky( $post->ID ) ); // Create a role with edit_others_posts. add_role( 'grammarian', 'Grammarian', array( 'read' => true, 'edit_posts' => true, 'edit_others_posts' => true, 'edit_published_posts' => true, ) ); $editor_user = $this->factory->user->create( array( 'role' => 'grammarian' ) ); $old_uid = get_current_user_id(); wp_set_current_user( $editor_user ); // Sanity Check. $this->assertFalse( current_user_can( 'publish_posts' ) ); $this->assertTrue( current_user_can( 'edit_others_posts' ) ); $this->assertTrue( current_user_can( 'edit_published_posts' ) ); // Edit the post - The key 'sticky' is intentionally unset. $data = array( 'post_ID' => $post->ID, 'post_title' => 'Updated', 'post_content' => 'Updated', ); edit_post( $data ); // Make sure it's still sticky $saved_post = get_post( $post->ID ); $this->assertTrue( is_sticky( $saved_post->ID ) ); $this->assertEquals( 'Updated', $saved_post->post_title ); $this->assertEquals( 'Updated', $saved_post->post_content ); // Teardown wp_set_current_user( $old_uid ); }
public function pll_save_post($post_id, $post, $translations) { global $wpdb; // prepare properties to synchronize foreach (array('comment_status', 'ping_status', 'menu_order', 'post_date') as $property) { if (in_array($property, $this->options['sync'])) { $postarr[$property] = $post->{$property}; } } if (in_array('post_date', $this->options['sync'])) { $post_arr['post_date_gmt'] = $post->post_date_gmt; } // synchronise terms and metas in translations foreach ($translations as $lang => $tr_id) { if (!$tr_id) { continue; } // synchronize terms and metas $this->copy_post_metas($post_id, $tr_id, $lang, true); // sticky posts if (in_array('sticky_posts', $this->options['sync'])) { isset($_REQUEST['sticky']) ? stick_post($tr_id) : unstick_post($tr_id); } // synchronize comment status, ping status, menu order... if (!empty($postarr)) { $wpdb->update($wpdb->posts, $postarr, array('ID' => $tr_id)); } // FIXME: optimize the 2 db update in 1 // post parent // do not udpate the translation parent if the user set a parent with no translation if (in_array('post_parent', $this->options['sync'])) { $post_parent = ($parent_id = wp_get_post_parent_id($post_id)) ? $this->model->get_translation('post', $parent_id, $lang) : 0; if (!($parent_id && !$post_parent)) { $wpdb->update($wpdb->posts, array('post_parent' => $post_parent), array('ID' => $tr_id)); } } } }
/** * Updates a single post. * * @since 4.7.0 * @access public * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ public function update_item($request) { $id = (int) $request['id']; $post = get_post($id); if (empty($id) || empty($post->ID) || $this->post_type !== $post->post_type) { return new WP_Error('rest_post_invalid_id', __('Invalid post ID.'), array('status' => 404)); } $post = $this->prepare_item_for_database($request); if (is_wp_error($post)) { return $post; } // convert the post object to an array, otherwise wp_update_post will expect non-escaped input. $post_id = wp_update_post(wp_slash((array) $post), true); if (is_wp_error($post_id)) { if ('db_update_error' === $post_id->get_error_code()) { $post_id->add_data(array('status' => 500)); } else { $post_id->add_data(array('status' => 400)); } return $post_id; } $post = get_post($post_id); /* This action is documented in lib/endpoints/class-wp-rest-controller.php */ do_action("rest_insert_{$this->post_type}", $post, $request, false); $schema = $this->get_item_schema(); if (!empty($schema['properties']['format']) && !empty($request['format'])) { set_post_format($post, $request['format']); } if (!empty($schema['properties']['featured_media']) && isset($request['featured_media'])) { $this->handle_featured_media($request['featured_media'], $post_id); } if (!empty($schema['properties']['sticky']) && isset($request['sticky'])) { if (!empty($request['sticky'])) { stick_post($post_id); } else { unstick_post($post_id); } } if (!empty($schema['properties']['template']) && isset($request['template'])) { $this->handle_template($request['template'], $post->ID); } $terms_update = $this->handle_terms($post->ID, $request); if (is_wp_error($terms_update)) { return $terms_update; } if (!empty($schema['properties']['meta']) && isset($request['meta'])) { $meta_update = $this->meta->update_value($request['meta'], $post->ID); if (is_wp_error($meta_update)) { return $meta_update; } } $post = get_post($post_id); $fields_update = $this->update_additional_fields_for_object($post, $request); if (is_wp_error($fields_update)) { return $fields_update; } $request->set_param('context', 'edit'); $response = $this->prepare_item_for_response($post, $request); return rest_ensure_response($response); }
/** * Update an existing post with values provided in $_POST. * * @since 1.5.0 * * @param array $post_data Optional. * @return int Post ID. */ function edit_post($post_data = null) { if (empty($post_data)) { $post_data =& $_POST; } $post_ID = (int) $post_data['post_ID']; $ptype = get_post_type_object($post_data['post_type']); if (!current_user_can($ptype->cap->edit_post, $post_ID)) { if ('page' == $post_data['post_type']) { wp_die(__('You are not allowed to edit this page.')); } else { wp_die(__('You are not allowed to edit this post.')); } } // Autosave shouldn't save too soon after a real save if ('autosave' == $post_data['action']) { $post =& get_post($post_ID); $now = time(); $then = strtotime($post->post_date_gmt . ' +0000'); $delta = AUTOSAVE_INTERVAL / 2; if ($now - $then < $delta) { return $post_ID; } } $post_data = $this->_translate_postdata(true, $post_data); $post_data['post_status'] = 'publish'; if (is_wp_error($post_data)) { wp_die($post_data->get_error_message()); } if ('autosave' != $post_data['action'] && 'auto-draft' == $post_data['post_status']) { $post_data['post_status'] = 'draft'; } if (isset($post_data['visibility'])) { switch ($post_data['visibility']) { case 'public': $post_data['post_password'] = ''; break; case 'password': unset($post_data['sticky']); break; case 'private': $post_data['post_status'] = 'private'; $post_data['post_password'] = ''; unset($post_data['sticky']); break; } } // Post Formats if (current_theme_supports('post-formats') && isset($post_data['post_format'])) { $formats = get_theme_support('post-formats'); if (is_array($formats)) { $formats = $formats[0]; if (in_array($post_data['post_format'], $formats)) { set_post_format($post_ID, $post_data['post_format']); } elseif ('0' == $post_data['post_format']) { set_post_format($post_ID, false); } } } // print_r($post_data); exit(); // Meta Stuff if (isset($post_data['meta']) && $post_data['meta']) { foreach ($post_data['meta'] as $key => $value) { if (!($meta = get_post_meta_by_id($key))) { continue; } if ($meta->post_id != $post_ID) { continue; } update_meta($key, $value['key'], $value['value']); } } if (isset($post_data['deletemeta']) && $post_data['deletemeta']) { foreach ($post_data['deletemeta'] as $key => $value) { if (!($meta = get_post_meta_by_id($key))) { continue; } if ($meta->post_id != $post_ID) { continue; } delete_meta($key); } } // add_meta( $post_ID ); update_post_meta($post_ID, '_edit_last', $GLOBALS['current_user']->ID); wp_update_post($post_data); // Reunite any orphaned attachments with their parent if (!($draft_ids = get_user_option('autosave_draft_ids'))) { $draft_ids = array(); } if ($draft_temp_id = (int) array_search($post_ID, $draft_ids)) { _relocate_children($draft_temp_id, $post_ID); } $this->set_post_lock($post_ID, $GLOBALS['current_user']->ID); if (current_user_can($ptype->cap->edit_others_posts)) { if (!empty($post_data['sticky'])) { stick_post($post_ID); } else { unstick_post($post_ID); } } return $post_ID; }
public function test_update_stick_post_with_password_fails() { wp_set_current_user(self::$editor_id); stick_post(self::$post_id); $request = new WP_REST_Request('PUT', sprintf('/wp/v2/posts/%d', self::$post_id)); $params = $this->set_post_data(array('password' => '123')); $request->set_body_params($params); $response = $this->server->dispatch($request); $this->assertErrorResponse('rest_invalid_field', $response, 400); }
/** * wpsc_insert_product function * * @param unknown * @return unknown */ function wpsc_insert_product($post_data, $wpsc_error = false) { global $wpdb, $user_ID; $adding = false; $update = false; $product_columns = array('name' => '', 'description' => '', 'additional_description' => '', 'price' => null, 'weight' => null, 'weight_unit' => '', 'pnp' => null, 'international_pnp' => null, 'file' => null, 'image' => '0', 'quantity_limited' => '', 'quantity' => null, 'special' => null, 'special_price' => null, 'display_frontpage' => null, 'notax' => null, 'publish' => null, 'active' => null, 'donation' => null, 'no_shipping' => null, 'thumbnail_image' => null, 'thumbnail_state' => null); foreach ($product_columns as $column => $default) { if (!isset($post_data[$column])) { $post_data[$column] = ''; } if ($post_data[$column] !== null) { $update_values[$column] = stripslashes($post_data[$column]); } else { if ($update != true && $default !== null) { $update_values[$column] = stripslashes($default); } } } $product_post_values = array('post_author' => $user_ID, 'post_content' => $post_data['description'], 'post_excerpt' => $post_data['additional_description'], 'post_title' => $post_data['name'], 'post_status' => $post_data['post_status'], 'post_type' => "wpsc-product", 'post_name' => sanitize_title($post_data['name'])); $product_post_values["comment_status"] = "open"; if (isset($sku) && $sku != '') { $product_post_array['guid'] = $sku; } $product_id = wp_insert_post($product_post_values); if (isset($post_data["sticky"])) { stick_post($product_id); } else { unstick_post($product_id); } if ($product_id == 0) { if ($wp_error) { return new WP_Error('db_insert_error', __('Could not insert product into the database', 'wpsc'), $wpdb->last_error); } else { return 0; } } $adding = true; // if we succeed, we can do further editing // and the meta wpsc_update_product_meta($product_id, $post_data['meta']); do_action('wpsc_edit_product', $product_id); return $product_id; }
function save_translation($data) { global $wpdb, $sitepress, $sitepress_settings, $ICL_Pro_Translation; $new_post_id = false; $is_incomplete = false; foreach ($data['fields'] as $field) { $this->_save_translation_field($field['tid'], $field); if (!isset($field['finished']) || !$field['finished']) { $is_incomplete = true; } } //check if translation job still exists $job_count = $wpdb->get_var($wpdb->prepare("SELECT count(1) FROM {$wpdb->prefix}icl_translate_job WHERE job_id=%d", $data['job_id'])); if ($job_count == 0) { wp_redirect(admin_url(sprintf('admin.php?page=%s', WPML_TM_FOLDER . '/menu/translations-queue.php', 'job-cancelled'))); exit; } if (!empty($data['complete']) && !$is_incomplete) { $wpdb->update($wpdb->prefix . 'icl_translate_job', array('translated' => 1), array('job_id' => $data['job_id'])); $rid = $wpdb->get_var($wpdb->prepare("SELECT rid FROM {$wpdb->prefix}icl_translate_job WHERE job_id=%d", $data['job_id'])); $translation_id = $wpdb->get_var($wpdb->prepare("SELECT translation_id FROM {$wpdb->prefix}icl_translation_status WHERE rid=%d", $rid)); $wpdb->update($wpdb->prefix . 'icl_translation_status', array('status' => ICL_TM_COMPLETE, 'needs_update' => 0), array('rid' => $rid)); list($element_id, $trid) = $wpdb->get_row($wpdb->prepare("SELECT element_id, trid FROM {$wpdb->prefix}icl_translations WHERE translation_id=%d", $translation_id), ARRAY_N); $job = $this->get_translation_job($data['job_id'], true); $parts = explode('_', $job->original_doc_id); if ($parts[0] == 'external') { // Translations are saved in the string table for 'external' types $id = array_pop($parts); unset($parts[0]); $type = implode('_', $parts); $type = apply_filters('WPML_get_package_type', $type, $job->original_doc_id); foreach ($job->elements as $field) { if ($field->field_translate) { if (function_exists('icl_st_is_registered_string')) { $string_id = icl_st_is_registered_string($type, $id . '_' . $field->field_type); if (!$string_id) { icl_register_string($type, $id . '_' . $field->field_type, self::decode_field_data($field->field_data, $field->field_format)); $string_id = icl_st_is_registered_string($type, $id . '_' . $field->field_type); } if ($string_id) { icl_add_string_translation($string_id, $job->language_code, self::decode_field_data($field->field_data_translated, $field->field_format), ICL_STRING_TRANSLATION_COMPLETE); } } } } } else { if (!is_null($element_id)) { $postarr['ID'] = $_POST['post_ID'] = $element_id; } foreach ($job->elements as $field) { switch ($field->field_type) { case 'title': $postarr['post_title'] = self::decode_field_data($field->field_data_translated, $field->field_format); break; case 'body': $postarr['post_content'] = self::decode_field_data($field->field_data_translated, $field->field_format); break; case 'excerpt': $postarr['post_excerpt'] = self::decode_field_data($field->field_data_translated, $field->field_format); break; case 'URL': $postarr['post_name'] = self::decode_field_data($field->field_data_translated, $field->field_format); break; default: break; } } $original_post = get_post($job->original_doc_id); $postarr['post_author'] = $original_post->post_author; $postarr['post_type'] = $original_post->post_type; if ($sitepress_settings['sync_comment_status']) { $postarr['comment_status'] = $original_post->comment_status; } if ($sitepress_settings['sync_ping_status']) { $postarr['ping_status'] = $original_post->ping_status; } if ($sitepress_settings['sync_page_ordering']) { $postarr['menu_order'] = $original_post->menu_order; } if ($sitepress_settings['sync_private_flag'] && $original_post->post_status == 'private') { $postarr['post_status'] = 'private'; } if ($sitepress_settings['sync_post_date']) { $postarr['post_date'] = $original_post->post_date; } //set as draft or the same status as original post $postarr['post_status'] = !$sitepress_settings['translated_document_status'] ? 'draft' : $original_post->post_status; if ($original_post->post_parent) { $post_parent_trid = $wpdb->get_var("SELECT trid FROM {$wpdb->prefix}icl_translations\n\t\t\t\t\t\tWHERE element_type='post_{$original_post->post_type}' AND element_id='{$original_post->post_parent}'"); if ($post_parent_trid) { $parent_id = $wpdb->get_var("SELECT element_id FROM {$wpdb->prefix}icl_translations\n\t\t\t\t\t\t\tWHERE element_type='post_{$original_post->post_type}' AND trid='{$post_parent_trid}' AND language_code='{$job->language_code}'"); } } if (isset($parent_id) && $sitepress_settings['sync_page_parent']) { $_POST['post_parent'] = $postarr['post_parent'] = $parent_id; $_POST['parent_id'] = $postarr['parent_id'] = $parent_id; } $_POST['trid'] = $trid; $_POST['lang'] = $job->language_code; $_POST['skip_sitepress_actions'] = true; $postarr = apply_filters('icl_pre_save_pro_translation', $postarr); if (isset($element_id)) { // it's an update so dont change the url $postarr['post_name'] = $wpdb->get_var($wpdb->prepare("SELECT post_name FROM {$wpdb->posts} WHERE ID=%d", $element_id)); } if (isset($element_id)) { // it's an update so dont change post date $existing_post = get_post($element_id); $postarr['post_date'] = $existing_post->post_date; $postarr['post_date_gmt'] = $existing_post->post_date_gmt; } $new_post_id = $this->icl_insert_post($postarr, $job->language_code); icl_cache_clear($postarr['post_type'] . 's_per_language'); // clear post counter per language in cache do_action('icl_pro_translation_saved', $new_post_id, $data['fields']); // Allow identical slugs $post_name = sanitize_title($postarr['post_title']); // for Translated documents options:Page URL = Translate if (isset($data['fields']['URL']['data']) && $data['fields']['URL']['data']) { $post_name = $data['fields']['URL']['data']; } $post_name_rewritten = $wpdb->get_var($wpdb->prepare("SELECT post_name FROM {$wpdb->posts} WHERE ID=%d", $new_post_id)); $post_name_base = $post_name; if ($post_name != $post_name_rewritten || $postarr['post_type'] == 'post' || $postarr['post_type'] == 'page') { $incr = 1; do { $exists = $wpdb->get_var($wpdb->prepare("\n\t\t\t\t\t\t\tSELECT p.ID FROM {$wpdb->posts} p\n\t\t\t\t\t\t\t\tJOIN {$wpdb->prefix}icl_translations t ON t.element_id = p.ID\n\t\t\t\t\t\t\tWHERE p.ID <> %d AND t.language_code = %s AND p.post_name=%s\n\t\t\t\t\t\t", $new_post_id, $job->language_code, $post_name)); if ($exists) { $incr++; } else { break; } $post_name = $post_name_base . '-' . $incr; } while ($exists); $wpdb->update($wpdb->posts, array('post_name' => $post_name), array('ID' => $new_post_id)); } $ICL_Pro_Translation->_content_fix_links_to_translated_content($new_post_id, $job->language_code); // update body translation with the links fixed $new_post_content = $wpdb->get_var($wpdb->prepare("SELECT post_content FROM {$wpdb->posts} WHERE ID=%d", $new_post_id)); foreach ($job->elements as $jel) { if ($jel->field_type == 'body') { $fields_data_translated = $this->encode_field_data($new_post_content, $jel->field_format); break; } } $wpdb->update($wpdb->prefix . 'icl_translate', array('field_data_translated' => $fields_data_translated), array('job_id' => $data['job_id'], 'field_type' => 'body')); // set stickiness //is the original post a sticky post? remove_filter('option_sticky_posts', array($sitepress, 'option_sticky_posts')); // remove filter used to get language relevant stickies. get them all $sticky_posts = get_option('sticky_posts'); $is_original_sticky = $original_post->post_type == 'post' && in_array($original_post->ID, $sticky_posts); if ($is_original_sticky && $sitepress_settings['sync_sticky_flag']) { stick_post($new_post_id); } else { if ($original_post->post_type == 'post' && !is_null($element_id)) { unstick_post($new_post_id); //just in case - if this is an update and the original post stckiness has changed since the post was sent to translation } } //sync plugins texts foreach ((array) $this->settings['custom_fields_translation'] as $cf => $op) { if ($op == 1) { update_post_meta($new_post_id, $cf, get_post_meta($original_post->ID, $cf, true)); } } // set specific custom fields $copied_custom_fields = array('_top_nav_excluded', '_cms_nav_minihome'); foreach ($copied_custom_fields as $ccf) { $val = get_post_meta($original_post->ID, $ccf, true); update_post_meta($new_post_id, $ccf, $val); } // sync _wp_page_template if ($sitepress_settings['sync_page_template']) { $_wp_page_template = get_post_meta($original_post->ID, '_wp_page_template', true); if (!empty($_wp_page_template)) { update_post_meta($new_post_id, '_wp_page_template', $_wp_page_template); } } // sync post format if ($sitepress_settings['sync_post_format']) { $_wp_post_format = get_post_format($original_post->ID); set_post_format($new_post_id, $_wp_post_format); } // set the translated custom fields if we have any. foreach ((array) $this->settings['custom_fields_translation'] as $field_name => $val) { if ($val == 2) { // should be translated // find it in the translation foreach ($job->elements as $name => $eldata) { if ($eldata->field_data == $field_name) { if (preg_match("/field-(.*?)-name/", $eldata->field_type, $match)) { $field_id = $match[1]; foreach ($job->elements as $k => $v) { if ($v->field_type == 'field-' . $field_id) { $field_translation = self::decode_field_data($v->field_data_translated, $v->field_format); } if ($v->field_type == 'field-' . $field_id . '-type') { $field_type = $v->field_data; } } if (isset($field_type) && $field_type == 'custom_field') { $field_translation = str_replace('�A;', "\n", $field_translation); // always decode html entities eg decode & to & $field_translation = html_entity_decode($field_translation); update_post_meta($new_post_id, $field_name, $field_translation); } } } } } } $link = get_edit_post_link($new_post_id); if ($link == '') { // the current user can't edit so just include permalink $link = get_permalink($new_post_id); } if (is_null($element_id)) { $wpdb->update($wpdb->prefix . 'icl_translations', array('element_id' => $new_post_id), array('translation_id' => $translation_id)); $user_message = __('Translation added: ', 'sitepress') . '<a href="' . $link . '">' . $postarr['post_title'] . '</a>.'; } else { $user_message = __('Translation updated: ', 'sitepress') . '<a href="' . $link . '">' . $postarr['post_title'] . '</a>.'; } // synchronize the page parent for translations if ($trid && $sitepress_settings['sync_page_parent']) { $translations = $sitepress->get_element_translations($trid, 'post_' . $postarr['post_type']); foreach ($translations as $target_lang => $target_details) { if ($target_lang != $job->language_code) { if ($target_details->element_id) { $sitepress->fix_translated_parent($new_post_id, $target_details->element_id, $target_lang); } } } } } if (isset($user_message)) { $this->messages[] = array('type' => 'updated', 'text' => $user_message); } if ($this->settings['notification']['completed'] != ICL_TM_NOTIFICATION_NONE) { require_once ICL_PLUGIN_PATH . '/inc/translation-management/tm-notification.class.php'; if ($data['job_id']) { $tn_notification = new TM_Notification(); $tn_notification->work_complete($data['job_id'], !is_null($element_id)); } } self::set_page_url($new_post_id); // redirect to jobs list wp_redirect(admin_url(sprintf('admin.php?page=%s&%s=%d', WPML_TM_FOLDER . '/menu/translations-queue.php', is_null($element_id) ? 'added' : 'updated', is_null($element_id) ? $new_post_id : $element_id))); } else { $this->messages[] = array('type' => 'updated', 'text' => __('Translation (incomplete) saved.', 'sitepress')); } /* * After all previous functionality the terms form the job are assigned to the new post just created or updated. * $overwrite is true by default for now. */ $overwrite = true; WPML_Terms_Translations::save_all_terms_from_job($data['job_id'], $new_post_id, $overwrite); do_action('icl_pro_translation_completed', $new_post_id); }
function write_post($path, $blog_id, $post_id) { $new = $this->api->ends_with($path, '/new'); $args = $this->query_args(); // unhook publicize, it's hooked again later -- without this, skipping services is impossible if (defined('IS_WPCOM') && IS_WPCOM) { remove_action('save_post', array($GLOBALS['publicize_ui']->publicize, 'async_publicize_post'), 100, 2); add_action('rest_api_inserted_post', array($GLOBALS['publicize_ui']->publicize, 'async_publicize_post')); } if ($new) { $input = $this->input(true); if ('revision' === $input['type']) { if (!isset($input['parent'])) { return new WP_Error('invalid_input', 'Invalid request input', 400); } $input['status'] = 'inherit'; // force inherit for revision type $input['slug'] = $input['parent'] . '-autosave-v1'; } elseif (!isset($input['title']) && !isset($input['content']) && !isset($input['excerpt'])) { return new WP_Error('invalid_input', 'Invalid request input', 400); } // default to post if (empty($input['type'])) { $input['type'] = 'post'; } $post_type = get_post_type_object($input['type']); if (!$this->is_post_type_allowed($input['type'])) { return new WP_Error('unknown_post_type', 'Unknown post type', 404); } if (!empty($input['author'])) { $author_id = $this->parse_and_set_author($input['author'], $input['type']); unset($input['author']); if (is_wp_error($author_id)) { return $author_id; } } if ('publish' === $input['status']) { if (!current_user_can($post_type->cap->publish_posts)) { if (current_user_can($post_type->cap->edit_posts)) { $input['status'] = 'pending'; } else { return new WP_Error('unauthorized', 'User cannot publish posts', 403); } } } else { if (!current_user_can($post_type->cap->edit_posts)) { return new WP_Error('unauthorized', 'User cannot edit posts', 403); } } } else { $input = $this->input(false); if (!is_array($input) || !$input) { return new WP_Error('invalid_input', 'Invalid request input', 400); } $post = get_post($post_id); $_post_type = !empty($input['type']) ? $input['type'] : $post->post_type; $post_type = get_post_type_object($_post_type); if (!$post || is_wp_error($post)) { return new WP_Error('unknown_post', 'Unknown post', 404); } if (!current_user_can('edit_post', $post->ID)) { return new WP_Error('unauthorized', 'User cannot edit post', 403); } if (!empty($input['author'])) { $author_id = $this->parse_and_set_author($input['author'], $_post_type); unset($input['author']); if (is_wp_error($author_id)) { return $author_id; } } if (isset($input['status']) && 'publish' === $input['status'] && 'publish' !== $post->post_status && !current_user_can('publish_post', $post->ID)) { $input['status'] = 'pending'; } $last_status = $post->post_status; $new_status = isset($input['status']) ? $input['status'] : $last_status; // Make sure that drafts get the current date when transitioning to publish if not supplied in the post. $date_in_past = strtotime($post->post_date_gmt) < time(); if ('publish' === $new_status && 'draft' === $last_status && !isset($input['date_gmt']) && $date_in_past) { $input['date_gmt'] = gmdate('Y-m-d H:i:s'); } } // If date is set, $this->input will set date_gmt, date still needs to be adjusted for the blog's offset if (isset($input['date_gmt'])) { $gmt_offset = get_option('gmt_offset'); $time_with_offset = strtotime($input['date_gmt']) + $gmt_offset * HOUR_IN_SECONDS; $input['date'] = date('Y-m-d H:i:s', $time_with_offset); } if (!empty($author_id) && get_current_user_id() != $author_id) { if (!current_user_can($post_type->cap->edit_others_posts)) { return new WP_Error('unauthorized', "User is not allowed to publish others' posts.", 403); } elseif (!user_can($author_id, $post_type->cap->edit_posts)) { return new WP_Error('unauthorized', 'Assigned author cannot publish post.', 403); } } if (!is_post_type_hierarchical($post_type->name) && 'revision' !== $post_type->name) { unset($input['parent']); } $tax_input = array(); foreach (array('categories' => 'category', 'tags' => 'post_tag') as $key => $taxonomy) { if (!isset($input[$key])) { continue; } $tax_input[$taxonomy] = array(); $is_hierarchical = is_taxonomy_hierarchical($taxonomy); if (is_array($input[$key])) { $terms = $input[$key]; } else { $terms = explode(',', $input[$key]); } foreach ($terms as $term) { /** * `curl --data 'category[]=123'` should be interpreted as a category ID, * not a category whose name is '123'. * * Consequence: To add a category/tag whose name is '123', the client must * first look up its ID. */ if (ctype_digit($term)) { $term = (int) $term; } $term_info = term_exists($term, $taxonomy); if (!$term_info) { // A term ID that doesn't already exist. Ignore it: we don't know what name to give it. if (is_int($term)) { continue; } // only add a new tag/cat if the user has access to $tax = get_taxonomy($taxonomy); if (!current_user_can($tax->cap->edit_terms)) { continue; } $term_info = wp_insert_term($term, $taxonomy); } if (!is_wp_error($term_info)) { if ($is_hierarchical) { // Categories must be added by ID $tax_input[$taxonomy][] = (int) $term_info['term_id']; } else { // Tags must be added by name if (is_int($term)) { $term = get_term($term, $taxonomy); $tax_input[$taxonomy][] = $term->name; } else { $tax_input[$taxonomy][] = $term; } } } } } if (isset($input['categories']) && empty($tax_input['category']) && 'revision' !== $post_type->name) { $tax_input['category'][] = get_option('default_category'); } unset($input['tags'], $input['categories']); $insert = array(); if (!empty($input['slug'])) { $insert['post_name'] = $input['slug']; unset($input['slug']); } if (isset($input['comments_open'])) { $insert['comment_status'] = true === $input['comments_open'] ? 'open' : 'closed'; } if (isset($input['pings_open'])) { $insert['ping_status'] = true === $input['pings_open'] ? 'open' : 'closed'; } unset($input['comments_open'], $input['pings_open']); if (isset($input['menu_order'])) { $insert['menu_order'] = $input['menu_order']; unset($input['menu_order']); } $publicize = isset($input['publicize']) ? $input['publicize'] : null; unset($input['publicize']); $publicize_custom_message = isset($input['publicize_message']) ? $input['publicize_message'] : null; unset($input['publicize_message']); if (isset($input['featured_image'])) { $featured_image = trim($input['featured_image']); $delete_featured_image = empty($featured_image); unset($input['featured_image']); } $metadata = isset($input['metadata']) ? $input['metadata'] : null; unset($input['metadata']); $likes = isset($input['likes_enabled']) ? $input['likes_enabled'] : null; unset($input['likes_enabled']); $sharing = isset($input['sharing_enabled']) ? $input['sharing_enabled'] : null; unset($input['sharing_enabled']); $sticky = isset($input['sticky']) ? $input['sticky'] : null; unset($input['sticky']); foreach ($input as $key => $value) { $insert["post_{$key}"] = $value; } if (!empty($author_id)) { $insert['post_author'] = absint($author_id); } if (!empty($tax_input)) { $insert['tax_input'] = $tax_input; } $has_media = isset($input['media']) && $input['media'] ? count($input['media']) : false; $has_media_by_url = isset($input['media_urls']) && $input['media_urls'] ? count($input['media_urls']) : false; if ($new) { if (isset($input['content']) && !has_shortcode($input['content'], 'gallery') && ($has_media || $has_media_by_url)) { switch ($has_media + $has_media_by_url) { case 0: // No images - do nothing. break; case 1: // 1 image - make it big $insert['post_content'] = $input['content'] = "[gallery size=full columns=1]\n\n" . $input['content']; break; default: // Several images - 3 column gallery $insert['post_content'] = $input['content'] = "[gallery]\n\n" . $input['content']; break; } } $post_id = wp_insert_post(add_magic_quotes($insert), true); } else { $insert['ID'] = $post->ID; // wp_update_post ignores date unless edit_date is set // See: http://codex.wordpress.org/Function_Reference/wp_update_post#Scheduling_posts // See: https://core.trac.wordpress.org/browser/tags/3.9.2/src/wp-includes/post.php#L3302 if (isset($input['date_gmt']) || isset($input['date'])) { $insert['edit_date'] = true; } $post_id = wp_update_post((object) $insert); } if (!$post_id || is_wp_error($post_id)) { return $post_id; } // make sure this post actually exists and is not an error of some kind (ie, trying to load media in the posts endpoint) $post_check = $this->get_post_by('ID', $post_id, $args['context']); if (is_wp_error($post_check)) { return $post_check; } if ($has_media) { $this->api->trap_wp_die('upload_error'); foreach ($input['media'] as $media_item) { $_FILES['.api.media.item.'] = $media_item; // check for WP_Error if we ever actually need $media_id $media_id = media_handle_upload('.api.media.item.', $post_id); } $this->api->trap_wp_die(null); unset($_FILES['.api.media.item.']); } if ($has_media_by_url) { foreach ($input['media_urls'] as $url) { $this->handle_media_sideload($url, $post_id); } } // Set like status for the post /** This filter is documented in modules/likes.php */ $sitewide_likes_enabled = (bool) apply_filters('wpl_is_enabled_sitewide', !get_option('disabled_likes')); if ($new) { if ($sitewide_likes_enabled) { if (false === $likes) { update_post_meta($post_id, 'switch_like_status', 1); } else { delete_post_meta($post_id, 'switch_like_status'); } } else { if ($likes) { update_post_meta($post_id, 'switch_like_status', 1); } else { delete_post_meta($post_id, 'switch_like_status'); } } } else { if (isset($likes)) { if ($sitewide_likes_enabled) { if (false === $likes) { update_post_meta($post_id, 'switch_like_status', 1); } else { delete_post_meta($post_id, 'switch_like_status'); } } else { if (true === $likes) { update_post_meta($post_id, 'switch_like_status', 1); } else { delete_post_meta($post_id, 'switch_like_status'); } } } } // Set sharing status of the post if ($new) { $sharing_enabled = isset($sharing) ? (bool) $sharing : true; if (false === $sharing_enabled) { update_post_meta($post_id, 'sharing_disabled', 1); } } else { if (isset($sharing) && true === $sharing) { delete_post_meta($post_id, 'sharing_disabled'); } else { if (isset($sharing) && false == $sharing) { update_post_meta($post_id, 'sharing_disabled', 1); } } } if (isset($sticky)) { if (true === $sticky) { stick_post($post_id); } else { unstick_post($post_id); } } // WPCOM Specific (Jetpack's will get bumped elsewhere // Tracks how many posts are published and sets meta // so we can track some other cool stats (like likes & comments on posts published) if (defined('IS_WPCOM') && IS_WPCOM) { if ($new && 'publish' == $input['status'] || !$new && isset($last_status) && 'publish' != $last_status && isset($new_status) && 'publish' == $new_status) { do_action('jetpack_bump_stats_extras', 'api-insights-posts', $this->api->token_details['client_id']); update_post_meta($post_id, '_rest_api_published', 1); update_post_meta($post_id, '_rest_api_client_id', $this->api->token_details['client_id']); } } // We ask the user/dev to pass Publicize services he/she wants activated for the post, but Publicize expects us // to instead flag the ones we don't want to be skipped. proceed with said logic. // any posts coming from Path (client ID 25952) should also not publicize if ($publicize === false || isset($this->api->token_details['client_id']) && 25952 == $this->api->token_details['client_id']) { // No publicize at all, skip all by ID foreach ($GLOBALS['publicize_ui']->publicize->get_services('all') as $name => $service) { delete_post_meta($post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $name); $service_connections = $GLOBALS['publicize_ui']->publicize->get_connections($name); if (!$service_connections) { continue; } foreach ($service_connections as $service_connection) { update_post_meta($post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $service_connection->unique_id, 1); } } } else { if (is_array($publicize) && count($publicize) > 0) { foreach ($GLOBALS['publicize_ui']->publicize->get_services('all') as $name => $service) { /* * We support both indexed and associative arrays: * * indexed are to pass entire services * * associative are to pass specific connections per service * * We do support mixed arrays: mixed integer and string keys (see 3rd example below). * * EG: array( 'twitter', 'facebook') will only publicize to those, ignoring the other available services * Form data: publicize[]=twitter&publicize[]=facebook * EG: array( 'twitter' => '(int) $pub_conn_id_0, (int) $pub_conn_id_3', 'facebook' => (int) $pub_conn_id_7 ) will publicize to two Twitter accounts, and one Facebook connection, of potentially many. * Form data: publicize[twitter]=$pub_conn_id_0,$pub_conn_id_3&publicize[facebook]=$pub_conn_id_7 * EG: array( 'twitter', 'facebook' => '(int) $pub_conn_id_0, (int) $pub_conn_id_3' ) will publicize to all available Twitter accounts, but only 2 of potentially many Facebook connections * Form data: publicize[]=twitter&publicize[facebook]=$pub_conn_id_0,$pub_conn_id_3 */ // Delete any stale SKIP value for the service by name. We'll add it back by ID. delete_post_meta($post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $name); // Get the user's connections $service_connections = $GLOBALS['publicize_ui']->publicize->get_connections($name); // if the user doesn't have any connections for this service, move on if (!$service_connections) { continue; } if (!in_array($name, $publicize) && !array_key_exists($name, $publicize)) { // Skip the whole service by adding each connection ID foreach ($service_connections as $service_connection) { update_post_meta($post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $service_connection->unique_id, 1); } } else { if (!empty($publicize[$name])) { // Seems we're being asked to only push to [a] specific connection[s]. // Explode the list on commas, which will also support a single passed ID $requested_connections = explode(',', preg_replace('/[\\s]*/', '', $publicize[$name])); // Flag the connections we can't match with the requested list to be skipped. foreach ($service_connections as $service_connection) { if (!in_array($service_connection->meta['connection_data']->id, $requested_connections)) { update_post_meta($post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $service_connection->unique_id, 1); } else { delete_post_meta($post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $service_connection->unique_id); } } } else { // delete all SKIP values; it's okay to publish to all connected IDs for this service foreach ($service_connections as $service_connection) { delete_post_meta($post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $service_connection->unique_id); } } } } } } if (!is_null($publicize_custom_message)) { if (empty($publicize_custom_message)) { delete_post_meta($post_id, $GLOBALS['publicize_ui']->publicize->POST_MESS); } else { update_post_meta($post_id, $GLOBALS['publicize_ui']->publicize->POST_MESS, trim($publicize_custom_message)); } } if (!empty($insert['post_format'])) { if ('default' !== strtolower($insert['post_format'])) { set_post_format($post_id, $insert['post_format']); } else { set_post_format($post_id, get_option('default_post_format')); } } if (isset($featured_image)) { $this->parse_and_set_featured_image($post_id, $delete_featured_image, $featured_image); } if (!empty($metadata)) { foreach ((array) $metadata as $meta) { $meta = (object) $meta; $existing_meta_item = new stdClass(); if (empty($meta->operation)) { $meta->operation = 'update'; } if (!empty($meta->value)) { if ('true' == $meta->value) { $meta->value = true; } if ('false' == $meta->value) { $meta->value = false; } } if (!empty($meta->id)) { $meta->id = absint($meta->id); $existing_meta_item = get_metadata_by_mid('post', $meta->id); } $unslashed_meta_key = wp_unslash($meta->key); // should match what the final key will be $meta->key = wp_slash($meta->key); $unslashed_existing_meta_key = wp_unslash($existing_meta_item->meta_key); $existing_meta_item->meta_key = wp_slash($existing_meta_item->meta_key); // make sure that the meta id passed matches the existing meta key if (!empty($meta->id) && !empty($meta->key)) { $meta_by_id = get_metadata_by_mid('post', $meta->id); if ($meta_by_id->meta_key !== $meta->key) { continue; // skip this meta } } switch ($meta->operation) { case 'delete': if (!empty($meta->id) && !empty($existing_meta_item->meta_key) && current_user_can('delete_post_meta', $post_id, $unslashed_existing_meta_key)) { delete_metadata_by_mid('post', $meta->id); } elseif (!empty($meta->key) && !empty($meta->previous_value) && current_user_can('delete_post_meta', $post_id, $unslashed_meta_key)) { delete_post_meta($post_id, $meta->key, $meta->previous_value); } elseif (!empty($meta->key) && current_user_can('delete_post_meta', $post_id, $unslashed_meta_key)) { delete_post_meta($post_id, $meta->key); } break; case 'add': if (!empty($meta->id) || !empty($meta->previous_value)) { continue; } elseif (!empty($meta->key) && !empty($meta->value) && current_user_can('add_post_meta', $post_id, $unslashed_meta_key) || $this->is_metadata_public($meta->key)) { add_post_meta($post_id, $meta->key, $meta->value); } break; case 'update': if (!isset($meta->value)) { continue; } elseif (!empty($meta->id) && !empty($existing_meta_item->meta_key) && (current_user_can('edit_post_meta', $post_id, $unslashed_existing_meta_key) || $this->is_metadata_public($meta->key))) { update_metadata_by_mid('post', $meta->id, $meta->value); } elseif (!empty($meta->key) && !empty($meta->previous_value) && (current_user_can('edit_post_meta', $post_id, $unslashed_meta_key) || $this->is_metadata_public($meta->key))) { update_post_meta($post_id, $meta->key, $meta->value, $meta->previous_value); } elseif (!empty($meta->key) && (current_user_can('edit_post_meta', $post_id, $unslashed_meta_key) || $this->is_metadata_public($meta->key))) { update_post_meta($post_id, $meta->key, $meta->value); } break; } } } /** * Fires when a post is created via the REST API. * * @since 2.3.0 * * @param int $post_id Post ID. * @param array $insert Data used to build the post. * @param string $new New post URL suffix. */ do_action('rest_api_inserted_post', $post_id, $insert, $new); $return = $this->get_post_by('ID', $post_id, $args['context']); if (!$return || is_wp_error($return)) { return $return; } if (isset($input['type']) && 'revision' === $input['type']) { $return['preview_nonce'] = wp_create_nonce('post_preview_' . $input['parent']); } if (isset($sticky)) { // workaround for sticky test occasionally failing, maybe a race condition with stick_post() above $return['sticky'] = true === $sticky; } /** This action is documented in json-endpoints/class.wpcom-json-api-site-settings-endpoint.php */ do_action('wpcom_json_api_objects', 'posts'); return $return; }
/** * Process the post data for the bulk editing of posts. * * Updates all bulk edited posts/pages, adding (but not removing) tags and * categories. Skips pages when they would be their own parent or child. * * @since 2.7.0 * * @param array $post_data Optional, the array of post data to process if not provided will use $_POST superglobal. * @return array */ function bulk_edit_posts($post_data = null) { global $wpdb; if (empty($post_data)) { $post_data =& $_POST; } if (isset($post_data['post_type'])) { $ptype = get_post_type_object($post_data['post_type']); } else { $ptype = get_post_type_object('post'); } if (!current_user_can($ptype->cap->edit_posts)) { if ('page' == $ptype->name) { wp_die(__('You are not allowed to edit pages.')); } else { wp_die(__('You are not allowed to edit posts.')); } } if (-1 == $post_data['_status']) { $post_data['post_status'] = null; unset($post_data['post_status']); } else { $post_data['post_status'] = $post_data['_status']; } unset($post_data['_status']); $post_IDs = array_map('intval', (array) $post_data['post']); $reset = array('post_author', 'post_status', 'post_password', 'post_parent', 'page_template', 'comment_status', 'ping_status', 'keep_private', 'tax_input', 'post_category', 'sticky'); foreach ($reset as $field) { if (isset($post_data[$field]) && ('' == $post_data[$field] || -1 == $post_data[$field])) { unset($post_data[$field]); } } if (isset($post_data['post_category'])) { if (is_array($post_data['post_category']) && !empty($post_data['post_category'])) { $new_cats = array_map('absint', $post_data['post_category']); } else { unset($post_data['post_category']); } } $tax_input = array(); if (isset($post_data['tax_input'])) { foreach ($post_data['tax_input'] as $tax_name => $terms) { if (empty($terms)) { continue; } if (is_taxonomy_hierarchical($tax_name)) { $tax_input[$tax_name] = array_map('absint', $terms); } else { $tax_input[$tax_name] = preg_replace('/\\s*,\\s*/', ',', rtrim(trim($terms), ' ,')); $tax_input[$tax_name] = explode(',', $tax_input[$tax_name]); } } } if (isset($post_data['post_parent']) && ($parent = (int) $post_data['post_parent'])) { $pages = $wpdb->get_results("SELECT ID, post_parent FROM {$wpdb->posts} WHERE post_type = 'page'"); $children = array(); for ($i = 0; $i < 50 && $parent > 0; $i++) { $children[] = $parent; foreach ($pages as $page) { if ($page->ID == $parent) { $parent = $page->post_parent; break; } } } } $updated = $skipped = $locked = array(); foreach ($post_IDs as $post_ID) { $post_type_object = get_post_type_object(get_post_type($post_ID)); if (!isset($post_type_object) || isset($children) && in_array($post_ID, $children) || !current_user_can($post_type_object->cap->edit_post, $post_ID)) { $skipped[] = $post_ID; continue; } if (wp_check_post_lock($post_ID)) { $locked[] = $post_ID; continue; } $tax_names = get_object_taxonomies(get_post($post_ID)); foreach ($tax_names as $tax_name) { $taxonomy_obj = get_taxonomy($tax_name); if (isset($tax_input[$tax_name]) && current_user_can($taxonomy_obj->cap->assign_terms)) { $new_terms = $tax_input[$tax_name]; } else { $new_terms = array(); } if ($taxonomy_obj->hierarchical) { $current_terms = (array) wp_get_object_terms($post_ID, $tax_name, array('fields' => 'ids')); } else { $current_terms = (array) wp_get_object_terms($post_ID, $tax_name, array('fields' => 'names')); } $post_data['tax_input'][$tax_name] = array_merge($current_terms, $new_terms); } if (isset($new_cats) && in_array('category', $tax_names)) { $cats = (array) wp_get_post_categories($post_ID); $post_data['post_category'] = array_unique(array_merge($cats, $new_cats)); unset($post_data['tax_input']['category']); } $post_data['ID'] = $post_ID; $updated[] = wp_update_post($post_data); if (isset($post_data['sticky']) && current_user_can('edit_others_posts')) { if ('sticky' == $post_data['sticky']) { stick_post($post_ID); } else { unstick_post($post_ID); } } } return array('updated' => $updated, 'skipped' => $skipped, 'locked' => $locked); }
/** * Encapsulate the logic for sticking a post * and determining if the user has permission to do so * * @since 4.3.0 * @access private * * @param array $post_data * @param bool $update * @return void|IXR_Error */ private function _toggle_sticky($post_data, $update = false) { $post_type = get_post_type_object($post_data['post_type']); // Private and password-protected posts cannot be stickied. if ('private' === $post_data['post_status'] || !empty($post_data['post_password'])) { // Error if the client tried to stick the post, otherwise, silently unstick. if (!empty($post_data['sticky'])) { return new IXR_Error(401, __('Sorry, you cannot stick a private post.')); } if ($update) { unstick_post($post_data['ID']); } } elseif (isset($post_data['sticky'])) { if (!current_user_can($post_type->cap->edit_others_posts)) { return new IXR_Error(401, __('Sorry, you are not allowed to stick this post.')); } $sticky = wp_validate_boolean($post_data['sticky']); if ($sticky) { stick_post($post_data['ID']); } else { unstick_post($post_data['ID']); } } }
/** * SACK response function for toggling post/page sticky * * @since 2.3.0 * @author scripts@schloebe.de */ function ame_toggle_sticky() { global $wpdb; $postid = intval($_POST['post_id']); $post = get_post($postid); if (is_sticky($postid)) { unstick_post($postid); AdminManagementXtended::fireActions('post', $postid, $post); die("jQuery('#stickyicon" . $postid . "').html('<a href=\"javascript:void(0);\" onclick=\"ame_ajax_set_sticky(" . $postid . ");return false;\"><img src=\"" . AME_PLUGINFULLURL . "img/" . AME_IMGSET . "nosticky.png\" border=\"0\" alt=\"" . __('Stick this post to the front page') . "\" title=\"" . __('Stick this post to the front page') . "\" /></a>');jQuery('#post-" . $postid . " td, #post-" . $postid . " th').animate( { backgroundColor: '#EAF3FA' }, 300).animate( { backgroundColor: '#F9F9F9' }, 300).animate( { backgroundColor: '#EAF3FA' }, 300).animate( { backgroundColor: '#F9F9F9' }, 300);jQuery('#post-" . $postid . "');"); } else { stick_post($postid); AdminManagementXtended::fireActions('post', $postid, $post); die("jQuery('#stickyicon" . $postid . "').html('<a href=\"javascript:void(0);\" onclick=\"ame_ajax_set_sticky(" . $postid . ");return false;\"><img src=\"" . AME_PLUGINFULLURL . "img/" . AME_IMGSET . "sticky.png\" border=\"0\" alt=\"" . __('Stick this post to the front page') . "\" title=\"" . __('Stick this post to the front page') . "\" /></a>');jQuery('#post-" . $postid . " td, #post-" . $postid . " th').animate( { backgroundColor: '#EAF3FA' }, 300).animate( { backgroundColor: '#F9F9F9' }, 300).animate( { backgroundColor: '#EAF3FA' }, 300).animate( { backgroundColor: '#F9F9F9' }, 300);jQuery('#post-" . $postid . "');"); } }
function write_post($path, $blog_id, $post_id) { $new = $this->api->ends_with($path, '/new'); $args = $this->query_args(); // unhook publicize, it's hooked again later -- without this, skipping services is impossible if (defined('IS_WPCOM') && IS_WPCOM) { remove_action('save_post', array($GLOBALS['publicize_ui']->publicize, 'async_publicize_post'), 100, 2); add_action('rest_api_inserted_post', array($GLOBALS['publicize_ui']->publicize, 'async_publicize_post')); } if ($new) { $input = $this->input(true); if ('revision' === $input['type']) { if (!isset($input['parent'])) { return new WP_Error('invalid_input', 'Invalid request input', 400); } $input['status'] = 'inherit'; // force inherit for revision type $input['slug'] = $input['parent'] . '-autosave-v1'; } elseif (!isset($input['title']) && !isset($input['content']) && !isset($input['excerpt'])) { return new WP_Error('invalid_input', 'Invalid request input', 400); } // default to post if (empty($input['type'])) { $input['type'] = 'post'; } $post_type = get_post_type_object($input['type']); if (!$this->is_post_type_allowed($input['type'])) { return new WP_Error('unknown_post_type', 'Unknown post type', 404); } if (!empty($input['author'])) { $author_id = parent::parse_and_set_author($input['author'], $input['type']); unset($input['author']); if (is_wp_error($author_id)) { return $author_id; } } if ('publish' === $input['status']) { if (!current_user_can($post_type->cap->publish_posts)) { if (current_user_can($post_type->cap->edit_posts)) { $input['status'] = 'pending'; } else { return new WP_Error('unauthorized', 'User cannot publish posts', 403); } } } else { if (!current_user_can($post_type->cap->edit_posts)) { return new WP_Error('unauthorized', 'User cannot edit posts', 403); } } } else { $input = $this->input(false); if (!is_array($input) || !$input) { return new WP_Error('invalid_input', 'Invalid request input', 400); } $post = get_post($post_id); $_post_type = !empty($input['type']) ? $input['type'] : $post->post_type; $post_type = get_post_type_object($_post_type); if (!$post || is_wp_error($post)) { return new WP_Error('unknown_post', 'Unknown post', 404); } if (!current_user_can('edit_post', $post->ID)) { return new WP_Error('unauthorized', 'User cannot edit post', 403); } if (!empty($input['author'])) { $author_id = parent::parse_and_set_author($input['author'], $_post_type); unset($input['author']); if (is_wp_error($author_id)) { return $author_id; } } if ('publish' === $input['status'] && 'publish' !== $post->post_status && !current_user_can('publish_post', $post->ID)) { $input['status'] = 'pending'; } $last_status = $post->post_status; $new_status = $input['status']; } // Fix for https://iorequests.wordpress.com/2014/08/13/scheduled-posts-made-in-the/ // See: https://a8c.slack.com/archives/io/p1408047082000273 // If date was set, $this->input will set date_gmt, date still needs to be adjusted for the blog's offset if (isset($input['date_gmt'])) { $gmt_offset = get_option('gmt_offset'); $time_with_offset = strtotime($input['date_gmt']) + $gmt_offset * HOUR_IN_SECONDS; $input['date'] = date('Y-m-d H:i:s', $time_with_offset); } if (!empty($author_id) && get_current_user_id() != $author_id) { if (!current_user_can($post_type->cap->edit_others_posts)) { return new WP_Error('unauthorized', "User is not allowed to publish others' posts.", 403); } elseif (!user_can($author_id, $post_type->cap->edit_posts)) { return new WP_Error('unauthorized', 'Assigned author cannot publish post.', 403); } } if (!is_post_type_hierarchical($post_type->name) && 'revision' !== $post_type->name) { unset($input['parent']); } /* add taxonomies by name */ $tax_input = array(); foreach (array('categories' => 'category', 'tags' => 'post_tag') as $key => $taxonomy) { if (!isset($input[$key])) { continue; } $tax_input[$taxonomy] = array(); $is_hierarchical = is_taxonomy_hierarchical($taxonomy); if (is_array($input[$key])) { $terms = $input[$key]; } else { $terms = explode(',', $input[$key]); } foreach ($terms as $term) { /** * We assume these are names, not IDs, even if they are numeric. * Note: A category named "0" will not work right. * https://core.trac.wordpress.org/ticket/9059 */ $term_info = get_term_by('name', $term, $taxonomy, ARRAY_A); if (!$term_info) { // only add a new tag/cat if the user has access to $tax = get_taxonomy($taxonomy); if (!current_user_can($tax->cap->edit_terms)) { continue; } $term_info = wp_insert_term($term, $taxonomy); } if (!is_wp_error($term_info)) { if ($is_hierarchical) { // Categories must be added by ID $tax_input[$taxonomy][] = (int) $term_info['term_id']; } else { // Tags must be added by name $tax_input[$taxonomy][] = $term; } } } } /* add taxonomies by ID */ foreach (array('categories_by_id' => 'category', 'tags_by_id' => 'post_tag') as $key => $taxonomy) { if (!isset($input[$key])) { continue; } // combine with any previous selections if (!is_array($tax_input[$taxonomy])) { $tax_input[$taxonomy] = array(); } $is_hierarchical = is_taxonomy_hierarchical($taxonomy); if (is_array($input[$key])) { $terms = $input[$key]; } else { $terms = explode(',', $input[$key]); } foreach ($terms as $term) { if (!ctype_digit($term)) { // skip anything that doesn't look like an ID continue; } $term = (int) $term; $term_info = get_term_by('id', $term, $taxonomy, ARRAY_A); if ($term_info && !is_wp_error($term_info)) { if ($is_hierarchical) { // Categories must be added by ID $tax_input[$taxonomy][] = $term; } else { // Tags must be added by name $tax_input[$taxonomy][] = $term_info['name']; } } } } if ((isset($input['categories']) || isset($input['categories_by_id'])) && empty($tax_input['category']) && 'revision' !== $post_type->name) { $tax_input['category'][] = get_option('default_category'); } unset($input['tags'], $input['categories'], $input['tags_by_id'], $input['categories_by_id']); $insert = array(); if (!empty($input['slug'])) { $insert['post_name'] = $input['slug']; unset($input['slug']); } if (isset($input['discussion'])) { $discussion = (array) $input['discussion']; foreach (array('comment', 'ping') as $discussion_type) { $discussion_open = sprintf('%ss_open', $discussion_type); $discussion_status = sprintf('%s_status', $discussion_type); if (isset($discussion[$discussion_open])) { $is_open = WPCOM_JSON_API::is_truthy($discussion[$discussion_open]); $discussion[$discussion_status] = $is_open ? 'open' : 'closed'; } if (in_array($discussion[$discussion_status], array('open', 'closed'))) { $insert[$discussion_status] = $discussion[$discussion_status]; } } } unset($input['discussion']); if (isset($input['menu_order'])) { $insert['menu_order'] = $input['menu_order']; unset($input['menu_order']); } if (isset($input['publicize'])) { $publicize = $input['publicize']; unset($input['publicize']); } if (isset($input['publicize_message'])) { $publicize_custom_message = $input['publicize_message']; unset($input['publicize_message']); } if (isset($input['featured_image'])) { $featured_image = trim($input['featured_image']); $delete_featured_image = empty($featured_image); unset($input['featured_image']); } if (isset($input['metadata'])) { $metadata = $input['metadata']; unset($input['metadata']); } if (isset($input['likes_enabled'])) { $likes = $input['likes_enabled']; unset($input['likes_enabled']); } if (isset($input['sharing_enabled'])) { $sharing = $input['sharing_enabled']; unset($input['sharing_enabled']); } if (isset($input['sticky'])) { $sticky = $input['sticky']; unset($input['sticky']); } foreach ($input as $key => $value) { $insert["post_{$key}"] = $value; } if (!empty($author_id)) { $insert['post_author'] = absint($author_id); } if (!empty($tax_input)) { $insert['tax_input'] = $tax_input; } $has_media = !empty($input['media']) ? count($input['media']) : false; $has_media_by_url = !empty($input['media_urls']) ? count($input['media_urls']) : false; if ($new) { if (false === strpos($input['content'], '[gallery') && ($has_media || $has_media_by_url)) { switch ($has_media + $has_media_by_url) { case 0: // No images - do nothing. break; case 1: // 1 image - make it big $insert['post_content'] = $input['content'] = "[gallery size=full columns=1]\n\n" . $input['content']; break; default: // Several images - 3 column gallery $insert['post_content'] = $input['content'] = "[gallery]\n\n" . $input['content']; break; } } $post_id = wp_insert_post(add_magic_quotes($insert), true); } else { $insert['ID'] = $post->ID; // wp_update_post ignores date unless edit_date is set // See: http://codex.wordpress.org/Function_Reference/wp_update_post#Scheduling_posts // See: https://core.trac.wordpress.org/browser/tags/3.9.2/src/wp-includes/post.php#L3302 if (isset($input['date_gmt']) || isset($input['date'])) { $insert['edit_date'] = true; } $post_id = wp_update_post((object) $insert); } if (!$post_id || is_wp_error($post_id)) { return $post_id; } // make sure this post actually exists and is not an error of some kind (ie, trying to load media in the posts endpoint) $post_check = $this->get_post_by('ID', $post_id, $args['context']); if (is_wp_error($post_check)) { return $post_check; } if ($has_media || $has_media_by_url) { $media_files = !empty($input['media']) ? $input['media'] : array(); $media_urls = !empty($input['media_urls']) ? $input['media_urls'] : array(); $media_attrs = !empty($input['media_attrs']) ? $input['media_attrs'] : array(); $force_parent_id = $post_id; $media_results = $this->handle_media_creation_v1_1($media_files, $media_urls, $media_attrs, $force_parent_id); } // set page template for this post.. if (isset($input['page_template']) && 'page' == $post_type->name) { $page_template = $input['page_template']; $page_templates = wp_get_theme()->get_page_templates(get_post($post_id)); if (empty($page_template) || 'default' == $page_template || isset($page_templates[$page_template])) { update_post_meta($post_id, '_wp_page_template', $page_template); } } // Set like status for the post $sitewide_likes_enabled = (bool) apply_filters('wpl_is_enabled_sitewide', !get_option('disabled_likes')); if ($new) { if ($sitewide_likes_enabled) { if (false === $likes) { update_post_meta($post_id, 'switch_like_status', 1); } else { delete_post_meta($post_id, 'switch_like_status'); } } else { if ($likes) { update_post_meta($post_id, 'switch_like_status', 1); } else { delete_post_meta($post_id, 'switch_like_status'); } } } else { if (isset($likes)) { if ($sitewide_likes_enabled) { if (false === $likes) { update_post_meta($post_id, 'switch_like_status', 1); } else { delete_post_meta($post_id, 'switch_like_status'); } } else { if (true === $likes) { update_post_meta($post_id, 'switch_like_status', 1); } else { delete_post_meta($post_id, 'switch_like_status'); } } } } // Set sharing status of the post if ($new) { $sharing_enabled = isset($sharing) ? (bool) $sharing : true; if (false === $sharing_enabled) { update_post_meta($post_id, 'sharing_disabled', 1); } } else { if (isset($sharing) && true === $sharing) { delete_post_meta($post_id, 'sharing_disabled'); } else { if (isset($sharing) && false == $sharing) { update_post_meta($post_id, 'sharing_disabled', 1); } } } if (true === $sticky) { stick_post($post_id); } else { unstick_post($post_id); } // WPCOM Specific (Jetpack's will get bumped elsewhere // Tracks how many posts are published and sets meta so we can track some other cool stats (like likes & comments on posts published) if ($new && 'publish' == $input['status'] || !$new && isset($last_status) && 'publish' != $last_status && isset($new_status) && 'publish' == $new_status) { if (function_exists('bump_stats_extras')) { bump_stats_extras('api-insights-posts', $this->api->token_details['client_id']); update_post_meta($post_id, '_rest_api_published', 1); update_post_meta($post_id, '_rest_api_client_id', $this->api->token_details['client_id']); } } // We ask the user/dev to pass Publicize services he/she wants activated for the post, but Publicize expects us // to instead flag the ones we don't want to be skipped. proceed with said logic. // any posts coming from Path (client ID 25952) should also not publicize if ($publicize === false || isset($this->api->token_details['client_id']) && 25952 == $this->api->token_details['client_id']) { // No publicize at all, skip all by ID foreach ($GLOBALS['publicize_ui']->publicize->get_services('all') as $name => $service) { delete_post_meta($post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $name); $service_connections = $GLOBALS['publicize_ui']->publicize->get_connections($name); if (!$service_connections) { continue; } foreach ($service_connections as $service_connection) { update_post_meta($post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $service_connection->unique_id, 1); } } } else { if (is_array($publicize) && count($publicize) > 0) { foreach ($GLOBALS['publicize_ui']->publicize->get_services('all') as $name => $service) { /* * We support both indexed and associative arrays: * * indexed are to pass entire services * * associative are to pass specific connections per service * * We do support mixed arrays: mixed integer and string keys (see 3rd example below). * * EG: array( 'twitter', 'facebook') will only publicize to those, ignoring the other available services * Form data: publicize[]=twitter&publicize[]=facebook * EG: array( 'twitter' => '(int) $pub_conn_id_0, (int) $pub_conn_id_3', 'facebook' => (int) $pub_conn_id_7 ) will publicize to two Twitter accounts, and one Facebook connection, of potentially many. * Form data: publicize[twitter]=$pub_conn_id_0,$pub_conn_id_3&publicize[facebook]=$pub_conn_id_7 * EG: array( 'twitter', 'facebook' => '(int) $pub_conn_id_0, (int) $pub_conn_id_3' ) will publicize to all available Twitter accounts, but only 2 of potentially many Facebook connections * Form data: publicize[]=twitter&publicize[facebook]=$pub_conn_id_0,$pub_conn_id_3 */ // Delete any stale SKIP value for the service by name. We'll add it back by ID. delete_post_meta($post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $name); // Get the user's connections $service_connections = $GLOBALS['publicize_ui']->publicize->get_connections($name); // if the user doesn't have any connections for this service, move on if (!$service_connections) { continue; } if (!in_array($name, $publicize) && !array_key_exists($name, $publicize)) { // Skip the whole service by adding each connection ID foreach ($service_connections as $service_connection) { update_post_meta($post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $service_connection->unique_id, 1); } } else { if (!empty($publicize[$name])) { // Seems we're being asked to only push to [a] specific connection[s]. // Explode the list on commas, which will also support a single passed ID $requested_connections = explode(',', preg_replace('/[\\s]*/', '', $publicize[$name])); // Flag the connections we can't match with the requested list to be skipped. foreach ($service_connections as $service_connection) { if (!in_array($service_connection->meta['connection_data']->id, $requested_connections)) { update_post_meta($post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $service_connection->unique_id, 1); } else { delete_post_meta($post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $service_connection->unique_id); } } } else { // delete all SKIP values; it's okay to publish to all connected IDs for this service foreach ($service_connections as $service_connection) { delete_post_meta($post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $service_connection->unique_id); } } } } } } if (!empty($publicize_custom_message)) { update_post_meta($post_id, $GLOBALS['publicize_ui']->publicize->POST_MESS, trim($publicize_custom_message)); } set_post_format($post_id, $insert['post_format']); if (isset($featured_image)) { parent::parse_and_set_featured_image($post_id, $delete_featured_image, $featured_image); } if (!empty($metadata)) { foreach ((array) $metadata as $meta) { $meta = (object) $meta; $existing_meta_item = new stdClass(); if (empty($meta->operation)) { $meta->operation = 'update'; } if (!empty($meta->value)) { if ('true' == $meta->value) { $meta->value = true; } if ('false' == $meta->value) { $meta->value = false; } } if (!empty($meta->id)) { $meta->id = absint($meta->id); $existing_meta_item = get_metadata_by_mid('post', $meta->id); } $unslashed_meta_key = wp_unslash($meta->key); // should match what the final key will be $meta->key = wp_slash($meta->key); $unslashed_existing_meta_key = wp_unslash($existing_meta_item->meta_key); $existing_meta_item->meta_key = wp_slash($existing_meta_item->meta_key); // make sure that the meta id passed matches the existing meta key if (!empty($meta->id) && !empty($meta->key)) { $meta_by_id = get_metadata_by_mid('post', $meta->id); if ($meta_by_id->meta_key !== $meta->key) { continue; // skip this meta } } switch ($meta->operation) { case 'delete': if (!empty($meta->id) && !empty($existing_meta_item->meta_key) && current_user_can('delete_post_meta', $post_id, $unslashed_existing_meta_key)) { delete_metadata_by_mid('post', $meta->id); } elseif (!empty($meta->key) && !empty($meta->previous_value) && current_user_can('delete_post_meta', $post_id, $unslashed_meta_key)) { delete_post_meta($post_id, $meta->key, $meta->previous_value); } elseif (!empty($meta->key) && current_user_can('delete_post_meta', $post_id, $unslashed_meta_key)) { delete_post_meta($post_id, $meta->key); } break; case 'add': if (!empty($meta->id) || !empty($meta->previous_value)) { continue; } elseif (!empty($meta->key) && !empty($meta->value) && current_user_can('add_post_meta', $post_id, $unslashed_meta_key) || $this->is_metadata_public($meta->key)) { add_post_meta($post_id, $meta->key, $meta->value); } break; case 'update': if (!isset($meta->value)) { continue; } elseif (!empty($meta->id) && !empty($existing_meta_item->meta_key) && (current_user_can('edit_post_meta', $post_id, $unslashed_existing_meta_key) || $this->is_metadata_public($meta->key))) { update_metadata_by_mid('post', $meta->id, $meta->value); } elseif (!empty($meta->key) && !empty($meta->previous_value) && (current_user_can('edit_post_meta', $post_id, $unslashed_meta_key) || $this->is_metadata_public($meta->key))) { update_post_meta($post_id, $meta->key, $meta->value, $meta->previous_value); } elseif (!empty($meta->key) && (current_user_can('edit_post_meta', $post_id, $unslashed_meta_key) || $this->is_metadata_public($meta->key))) { update_post_meta($post_id, $meta->key, $meta->value); } break; } } } do_action('rest_api_inserted_post', $post_id, $insert, $new); $return = $this->get_post_by('ID', $post_id, $args['context']); if (!$return || is_wp_error($return)) { return $return; } if (isset($input['type']) && 'revision' === $input['type']) { $return['preview_nonce'] = wp_create_nonce('post_preview_' . $input['parent']); } // workaround for sticky test occasionally failing, maybe a race condition with stick_post() above $return['sticky'] = true === $sticky; if (!empty($media_results['errors'])) { $return['media_errors'] = $media_results['errors']; } do_action('wpcom_json_api_objects', 'posts'); return $return; }
function cp_add_new_listing($advals) { global $wpdb; $new_tags = ''; $ad_length = ''; $attach_id = ''; $the_attachment = ''; // tags are tricky and need to be put into an array before saving the ad if (!empty($advals['tags_input'])) { $new_tags = explode(',', $advals['tags_input']); } // put all the new ad elements into an array // these are the minimum required fields for WP (except tags) $new_ad = array(); $new_ad['post_title'] = appthemes_filter($advals['post_title']); $new_ad['post_content'] = trim($advals['post_content']); $new_ad['post_status'] = 'pending'; // no longer setting final status until after images are set $new_ad['post_author'] = 0; if (!empty($_SESSION['anonym']) && $_SESSION['anonym'] != '') { $new_ad['post_author'] = 0; } else { $new_ad['post_author'] = $advals['user_id']; } $new_ad['post_type'] = APP_POST_TYPE; // make sure the WP sanitize_post function doesn't strip out embed & other html if (get_option('cp_allow_html') == 'yes') { $new_ad['filter'] = true; } //print_r($new_ad).' <- new ad array<br>'; // insert the new ad $post_id = wp_insert_post($new_ad); //set the custom post type categories wp_set_post_terms($post_id, appthemes_filter($advals['cat']), APP_TAX_CAT, false); //set the custom post type tags wp_set_post_terms($post_id, $new_tags, APP_TAX_TAG, false); //$location = get_field('location'); //**************************************EKLEME********************************************** // Google Maps ten Pozisyon Seçilmiþse O pozisyonu kaydeder seçimemiþse adresten bulur if (!empty($_SESSION['kordinat']) && $_SESSION['kordinat'] != '') { $category = get_the_terms($post_id, 'ad_cat'); $address1 = explode('|', $_SESSION['kordinat']); $address2 = explode(',', $address1[1]); cp_add_geocode($post_id, $category[0]->name, $address2[0], $address2[1]); $_SESSION['kordinat'] = ''; } else { $_SESSION['kordinat'] == 'yok'; } //************************************************************************************ // the unique order ID we created becomes the ad confirmation ID // we will use this for payment systems and for activating the ad // later if need be. it needs to start with cp_ otherwise it won't // be loaded in with the ad so let's give it a new name $advals['cp_sys_ad_conf_id'] = $advals['oid']; // get the ad duration and first see if ad packs are being used // if so, get the length of time in days otherwise use the default // prune period defined on the CP settings page if (isset($advals['pack_duration'])) { $ad_length = $advals['pack_duration']; } else { $ad_length = get_option('cp_prun_period'); } // set the ad listing expiration date and put into a session $ad_expire_date = date_i18n('m/d/Y H:i:s', strtotime('+' . $ad_length . ' days')); // don't localize the word 'days' $advals['cp_sys_expire_date'] = $ad_expire_date; $advals['cp_sys_ad_duration'] = $ad_length; // now add all the custom fields into WP post meta fields foreach ($advals as $meta_key => $meta_value) { if (appthemes_str_starts_with($meta_key, 'cp_') && !is_array($advals[$meta_key])) { add_post_meta($post_id, $meta_key, $meta_value, true); } if (appthemes_str_starts_with($meta_key, 'cp_') && is_array($advals[$meta_key])) { foreach ($advals[$meta_key] as $checkbox_value) { add_post_meta($post_id, $meta_key, $checkbox_value); } } } // if they checked the box for a featured ad, then make the post sticky if (isset($advals['featured_ad'])) { stick_post($post_id); } if (isset($advals['attachment'])) { $the_attachment = $advals['attachment']; // associate the already uploaded images to the new ad and create multiple image sizes $attach_id = cp_associate_images($post_id, $the_attachment, true); } // set the thumbnail pic on the WP post //cp_set_ad_thumbnail($post_id, $attach_id); //last step is to publish the ad when its appropriate to publish immediately $final_status = cp_set_post_status($advals); if ($final_status == 'publish') { $final_post = array(); $final_post['ID'] = $post_id; $final_post['post_status'] = $final_status; $update_result = wp_update_post($final_post); } // kick back the post id in case we want to use it return $post_id; }
function process_post($post) { global $wpdb; $post_ID = (int) $this->get_tag($post, 'wp:post_id'); if ($post_ID && !empty($this->post_ids_processed[$post_ID])) { // Processed already return 0; } set_time_limit(60); // There are only ever one of these $post_title = $this->get_tag($post, 'title'); $post_date = $this->get_tag($post, 'wp:post_date'); $post_date_gmt = $this->get_tag($post, 'wp:post_date_gmt'); $comment_status = $this->get_tag($post, 'wp:comment_status'); $ping_status = $this->get_tag($post, 'wp:ping_status'); $post_status = $this->get_tag($post, 'wp:status'); $post_name = $this->get_tag($post, 'wp:post_name'); $post_parent = $this->get_tag($post, 'wp:post_parent'); $menu_order = $this->get_tag($post, 'wp:menu_order'); $post_type = $this->get_tag($post, 'wp:post_type'); $post_password = $this->get_tag($post, 'wp:post_password'); $is_sticky = $this->get_tag($post, 'wp:is_sticky'); $guid = $this->get_tag($post, 'guid'); $post_author = $this->get_tag($post, 'dc:creator'); $post_excerpt = $this->get_tag($post, 'excerpt:encoded'); $post_excerpt = preg_replace_callback('|<(/?[A-Z]+)|', array(&$this, '_normalize_tag'), $post_excerpt); $post_excerpt = str_replace('<br>', '<br />', $post_excerpt); $post_excerpt = str_replace('<hr>', '<hr />', $post_excerpt); $post_content = $this->get_tag($post, 'content:encoded'); $post_content = preg_replace_callback('|<(/?[A-Z]+)|', array(&$this, '_normalize_tag'), $post_content); $post_content = str_replace('<br>', '<br />', $post_content); $post_content = str_replace('<hr>', '<hr />', $post_content); preg_match_all('|<category domain="tag">(.*?)</category>|is', $post, $tags); $tags = $tags[1]; $tag_index = 0; foreach ($tags as $tag) { $tags[$tag_index] = $wpdb->escape(html_entity_decode(str_replace(array('<![CDATA[', ']]>'), '', $tag))); $tag_index++; } preg_match_all('|<category>(.*?)</category>|is', $post, $categories); $categories = $categories[1]; $cat_index = 0; foreach ($categories as $category) { $categories[$cat_index] = $wpdb->escape(html_entity_decode(str_replace(array('<![CDATA[', ']]>'), '', $category))); $cat_index++; } $post_exists = $wpdb->get_row("SELECT ID FROM wp_posts WHERE post_title = '" . $post_title . "' && post_status = 'publish'", 'ARRAY_N'); if ($post_exists) { echo '<li>'; printf(__('Post <em>%s</em> already exists.', 'wordpress-importer'), stripslashes($post_title)); $comment_post_ID = $post_id = $post_exists; } else { // If it has parent, process parent first. $post_parent = (int) $post_parent; if ($post_parent) { // if we already know the parent, map it to the local ID if (isset($this->post_ids_processed[$post_parent])) { $post_parent = $this->post_ids_processed[$post_parent]; // new ID of the parent } else { // record the parent for later $this->orphans[intval($post_ID)] = $post_parent; } } echo '<li>'; $post_author = $this->checkauthor($post_author); //just so that if a post already exists, new users are not created by checkauthor $postdata = compact('post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_excerpt', 'post_title', 'post_status', 'post_name', 'comment_status', 'ping_status', 'guid', 'post_parent', 'menu_order', 'post_type', 'post_password'); $postdata['import_id'] = $post_ID; if ($post_type == 'attachment') { $remote_url = $this->get_tag($post, 'wp:attachment_url'); if (!$remote_url) { $remote_url = $guid; } $comment_post_ID = $post_id = $this->process_attachment($postdata, $remote_url); if (!$post_id or is_wp_error($post_id)) { return $post_id; } } else { printf(__('Importing post <em>%s</em>...', 'wordpress-importer') . "\n", stripslashes($post_title)); $comment_post_ID = $post_id = wp_insert_post($postdata); if ($post_id && $is_sticky == 1) { stick_post($post_id); } } if (is_wp_error($post_id)) { return $post_id; } // Memorize old and new ID. if ($post_id && $post_ID) { $this->post_ids_processed[intval($post_ID)] = intval($post_id); } // Add categories. if (count($categories) > 0) { $post_cats = array(); foreach ($categories as $category) { if ('' == $category) { continue; } $slug = sanitize_term_field('slug', $category, 0, 'category', 'db'); $cat = get_term_by('slug', $slug, 'category'); $cat_ID = 0; if (!empty($cat)) { $cat_ID = $cat->term_id; } if ($cat_ID == 0) { $category = $wpdb->escape($category); $cat_ID = wp_insert_category(array('cat_name' => $category)); if (is_wp_error($cat_ID)) { continue; } } $post_cats[] = $cat_ID; } wp_set_post_categories($post_id, $post_cats); } // Add tags. if (count($tags) > 0) { $post_tags = array(); foreach ($tags as $tag) { if ('' == $tag) { continue; } $slug = sanitize_term_field('slug', $tag, 0, 'post_tag', 'db'); $tag_obj = get_term_by('slug', $slug, 'post_tag'); $tag_id = 0; if (!empty($tag_obj)) { $tag_id = $tag_obj->term_id; } if ($tag_id == 0) { $tag = $wpdb->escape($tag); $tag_id = wp_insert_term($tag, 'post_tag'); if (is_wp_error($tag_id)) { continue; } $tag_id = $tag_id['term_id']; } $post_tags[] = intval($tag_id); } wp_set_post_tags($post_id, $post_tags); } } // Now for comments preg_match_all('|<wp:comment>(.*?)</wp:comment>|is', $post, $comments); $comments = $comments[1]; $num_comments = 0; $inserted_comments = array(); if ($comments) { foreach ($comments as $comment) { $comment_id = $this->get_tag($comment, 'wp:comment_id'); $newcomments[$comment_id]['comment_post_ID'] = $comment_post_ID; $newcomments[$comment_id]['comment_author'] = $this->get_tag($comment, 'wp:comment_author'); $newcomments[$comment_id]['comment_author_email'] = $this->get_tag($comment, 'wp:comment_author_email'); $newcomments[$comment_id]['comment_author_IP'] = $this->get_tag($comment, 'wp:comment_author_IP'); $newcomments[$comment_id]['comment_author_url'] = $this->get_tag($comment, 'wp:comment_author_url'); $newcomments[$comment_id]['comment_date'] = $this->get_tag($comment, 'wp:comment_date'); $newcomments[$comment_id]['comment_date_gmt'] = $this->get_tag($comment, 'wp:comment_date_gmt'); $newcomments[$comment_id]['comment_content'] = $this->get_tag($comment, 'wp:comment_content'); $newcomments[$comment_id]['comment_approved'] = $this->get_tag($comment, 'wp:comment_approved'); $newcomments[$comment_id]['comment_type'] = $this->get_tag($comment, 'wp:comment_type'); $newcomments[$comment_id]['comment_parent'] = $this->get_tag($comment, 'wp:comment_parent'); } // Sort by comment ID, to make sure comment parents exist (if there at all) ksort($newcomments); foreach ($newcomments as $key => $comment) { // if this is a new post we can skip the comment_exists() check if (!$post_exists || !comment_exists($comment['comment_author'], $comment['comment_date'])) { if (isset($inserted_comments[$comment['comment_parent']])) { $comment['comment_parent'] = $inserted_comments[$comment['comment_parent']]; } $comment = wp_filter_comment($comment); $inserted_comments[$key] = wp_insert_comment($comment); $num_comments++; } } } if ($num_comments) { printf(' ' . _n('(%s comment)', '(%s comments)', $num_comments, 'wordpress-importer'), $num_comments); } // Now for post meta preg_match_all('|<wp:postmeta>(.*?)</wp:postmeta>|is', $post, $postmeta); $postmeta = $postmeta[1]; if ($postmeta) { foreach ($postmeta as $p) { $key = $this->get_tag($p, 'wp:meta_key'); $value = $this->get_tag($p, 'wp:meta_value'); $this->process_post_meta($post_id, $key, $value); } } do_action('import_post_added', $post_id); print "</li>\n"; }
function cherry_plugin_import_posts() { $nonce = $_POST['nonce']; if (!wp_verify_nonce($nonce, 'import_ajax-nonce')) { exit('instal_error'); } if (session_id() != "import_xml") { session_name("import_xml"); session_start(); } do_action('cherry_plugin_import_posts'); $_SESSION['url_remap'] = array(); $_SESSION['featured_images'] = array(); $_SESSION['attachment_posts'] = array(); $_SESSION['processed_posts'] = array(); $posts_array = $_SESSION['posts']; $posts_array = apply_filters('wp_import_posts', $posts_array); $attachment_posts = array(); foreach ($posts_array as $post) { $post = apply_filters('wp_import_post_data_raw', $post); if (!post_type_exists($post['post_type'])) { // Failed to import do_action('wp_import_post_exists', $post); continue; } if (isset($_SESSION['processed_posts'][$post['post_id']]) && !empty($post['post_id'])) { continue; } if ($post['status'] == 'auto-draft') { continue; } if ('nav_menu_item' == $post['post_type']) { continue; } //!!!!$post_type_object = get_post_type_object( $post['post_type'] ); $post_exists = post_exists($post['post_title'], '', $post['post_date']); if ($post_exists && get_post_type($post_exists) == $post['post_type']) { // already exists $comment_post_ID = $post_id = $post_exists; } else { $post_parent = (int) $post['post_parent']; if ($post_parent) { // if we already know the parent, map it to the new local ID if (isset($_SESSION['processed_posts'][$post_parent])) { $post_parent = $_SESSION['processed_posts'][$post_parent]; // otherwise record the parent for later } else { $_SESSION['post_orphans'][intval($post['post_id'])] = $post_parent; $post_parent = 0; } } $author = (int) get_current_user_id(); $postdata = array('import_id' => $post['post_id'], 'post_author' => $author, 'post_date' => $post['post_date'], 'post_date_gmt' => $post['post_date_gmt'], 'post_content' => $post['post_content'], 'post_excerpt' => $post['post_excerpt'], 'post_title' => $post['post_title'], 'post_status' => $post['status'], 'post_name' => $post['post_name'], 'comment_status' => $post['comment_status'], 'ping_status' => $post['ping_status'], 'guid' => $post['guid'], 'post_parent' => $post_parent, 'menu_order' => $post['menu_order'], 'post_type' => $post['post_type'], 'post_password' => $post['post_password']); $original_post_ID = $post['post_id']; $postdata = apply_filters('wp_import_post_data_processed', $postdata, $post); if ('attachment' == $postdata['post_type']) { array_push($attachment_posts, $post); } if ('attachment' != $postdata['post_type']) { ini_set('max_execution_time', -1); set_time_limit(0); $comment_post_ID = $post_id = wp_insert_post($postdata, true); do_action('wp_import_insert_post', $post_id, $original_post_ID, $postdata, $post); if (is_wp_error($post_id)) { // Failed to import continue; } if ($post['is_sticky'] == 1) { stick_post($post_id); } // map pre-import ID to local ID $_SESSION['processed_posts'][intval($post['post_id'])] = intval($post_id); if (!isset($post['terms'])) { $post['terms'] = array(); } $post['terms'] = apply_filters('wp_import_post_terms', $post['terms'], $post_id, $post); // add categories, tags and other terms if (!empty($post['terms'])) { $terms_to_set = array(); foreach ($post['terms'] as $term) { // back compat with WXR 1.0 map 'tag' to 'post_tag' $taxonomy = 'tag' == $term['domain'] ? 'post_tag' : $term['domain']; $term_exists = term_exists($term['slug'], $taxonomy); $term_id = is_array($term_exists) ? $term_exists['term_id'] : $term_exists; if (!$term_id) { $t = wp_insert_term($term['name'], $taxonomy, array('slug' => $term['slug'])); if (!is_wp_error($t)) { $term_id = $t['term_id']; do_action('cherry_plugin_import_insert_term', $t, $term, $post_id, $post); } else { // Failed to import do_action('cherry_plugin_import_insert_term_failed', $t, $term, $post_id, $post); continue; } } $terms_to_set[$taxonomy][] = intval($term_id); } foreach ($terms_to_set as $tax => $ids) { $tt_ids = wp_set_post_terms($post_id, $ids, $tax); do_action('wp_import_set_post_terms', $tt_ids, $ids, $tax, $post_id, $post); } unset($post['terms'], $terms_to_set); } if (!isset($post['comments'])) { $post['comments'] = array(); } $post['comments'] = apply_filters('wp_import_post_comments', $post['comments'], $post_id, $post); // add/update comments if (!empty($post['comments'])) { $num_comments = 0; $inserted_comments = array(); foreach ($post['comments'] as $comment) { $comment_id = $comment['comment_id']; $newcomments[$comment_id]['comment_post_ID'] = $comment_post_ID; $newcomments[$comment_id]['comment_author'] = $comment['comment_author']; $newcomments[$comment_id]['comment_author_email'] = $comment['comment_author_email']; $newcomments[$comment_id]['comment_author_IP'] = $comment['comment_author_IP']; $newcomments[$comment_id]['comment_author_url'] = $comment['comment_author_url']; $newcomments[$comment_id]['comment_date'] = $comment['comment_date']; $newcomments[$comment_id]['comment_date_gmt'] = $comment['comment_date_gmt']; $newcomments[$comment_id]['comment_content'] = $comment['comment_content']; $newcomments[$comment_id]['comment_approved'] = $comment['comment_approved']; $newcomments[$comment_id]['comment_type'] = $comment['comment_type']; $newcomments[$comment_id]['comment_parent'] = $comment['comment_parent']; $newcomments[$comment_id]['commentmeta'] = isset($comment['commentmeta']) ? $comment['commentmeta'] : array(); if (isset($processed_authors[$comment['comment_user_id']])) { $newcomments[$comment_id]['user_id'] = $processed_authors[$comment['comment_user_id']]; } } ksort($newcomments); foreach ($newcomments as $key => $comment) { // if this is a new post we can skip the comment_exists() check if (!$post_exists || !comment_exists($comment['comment_author'], $comment['comment_date'])) { if (isset($inserted_comments[$comment['comment_parent']])) { $comment['comment_parent'] = $inserted_comments[$comment['comment_parent']]; } $comment = wp_filter_comment($comment); $inserted_comments[$key] = wp_insert_comment($comment); do_action('cherry_plugin_import_insert_comment', $inserted_comments[$key], $comment, $comment_post_ID, $post); foreach ($comment['commentmeta'] as $meta) { $value = maybe_unserialize($meta['value']); add_comment_meta($inserted_comments[$key], $meta['key'], $value); } $num_comments++; } } unset($newcomments, $inserted_comments, $post['comments']); } if (!isset($post['postmeta'])) { $post['postmeta'] = array(); } $post['postmeta'] = apply_filters('wp_import_post_meta', $post['postmeta'], $post_id, $post); // add/update post meta if (isset($post['postmeta'])) { foreach ($post['postmeta'] as $meta) { $key = apply_filters('import_post_meta_key', $meta['key']); $value = false; if ('_edit_last' == $key) { if (isset($processed_authors[intval($meta['value'])])) { $value = $processed_authors[intval($meta['value'])]; } else { $key = false; } } if ($key) { // export gets meta straight from the DB so could have a serialized string if (!$value) { $value = maybe_unserialize($meta['value']); } ini_set('max_execution_time', -1); set_time_limit(0); add_post_meta($post_id, $key, $value); do_action('cherry_plugin_import_post_meta', $post_id, $key, $value); // if the post has a featured image, take note of this in case of remap if ('_thumbnail_id' == $key) { $_SESSION['featured_images'][$post_id] = (int) $value; } } } } } } } $_SESSION['attachment_posts'] = $attachment_posts; exit('import_menu_item'); }
/** * Edit a post. * * @since 1.5.0 * * @param array $args Method parameters. * @return bool|IXR_Error True on success. */ public function mw_editPost($args) { $this->escape($args); $post_ID = (int) $args[0]; $username = $args[1]; $password = $args[2]; $content_struct = $args[3]; $publish = isset($args[4]) ? $args[4] : 0; if (!($user = $this->login($username, $password))) { return $this->error; } /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */ do_action('xmlrpc_call', 'metaWeblog.editPost'); $postdata = get_post($post_ID, ARRAY_A); // If there is no post data for the give post id, stop // now and return an error. Other wise a new post will be // created (which was the old behavior). if (!$postdata || empty($postdata['ID'])) { return new IXR_Error(404, __('Invalid post ID.')); } if (!current_user_can('edit_post', $post_ID)) { return new IXR_Error(401, __('Sorry, you do not have the right to edit this post.')); } // Use wp.editPost to edit post types other than post and page. if (!in_array($postdata['post_type'], array('post', 'page'))) { return new IXR_Error(401, __('Invalid post type')); } // Thwart attempt to change the post type. if (!empty($content_struct['post_type']) && $content_struct['post_type'] != $postdata['post_type']) { return new IXR_Error(401, __('The post type may not be changed.')); } // Check for a valid post format if one was given if (isset($content_struct['wp_post_format'])) { $content_struct['wp_post_format'] = sanitize_key($content_struct['wp_post_format']); if (!array_key_exists($content_struct['wp_post_format'], get_post_format_strings())) { return new IXR_Error(404, __('Invalid post format')); } } $this->escape($postdata); $ID = $postdata['ID']; $post_content = $postdata['post_content']; $post_title = $postdata['post_title']; $post_excerpt = $postdata['post_excerpt']; $post_password = $postdata['post_password']; $post_parent = $postdata['post_parent']; $post_type = $postdata['post_type']; $menu_order = $postdata['menu_order']; // Let WordPress manage slug if none was provided. $post_name = ""; $post_name = $postdata['post_name']; if (isset($content_struct['wp_slug'])) { $post_name = $content_struct['wp_slug']; } // Only use a password if one was given. if (isset($content_struct['wp_password'])) { $post_password = $content_struct['wp_password']; } // Only set a post parent if one was given. if (isset($content_struct['wp_page_parent_id'])) { $post_parent = $content_struct['wp_page_parent_id']; } // Only set the menu_order if it was given. if (isset($content_struct['wp_page_order'])) { $menu_order = $content_struct['wp_page_order']; } $page_template = null; if (!empty($content_struct['wp_page_template']) && 'page' == $post_type) { $page_template = $content_struct['wp_page_template']; } $post_author = $postdata['post_author']; // Only set the post_author if one is set. if (isset($content_struct['wp_author_id']) && $user->ID != $content_struct['wp_author_id']) { switch ($post_type) { case 'post': if (!current_user_can('edit_others_posts')) { return new IXR_Error(401, __('You are not allowed to change the post author as this user.')); } break; case 'page': if (!current_user_can('edit_others_pages')) { return new IXR_Error(401, __('You are not allowed to change the page author as this user.')); } break; default: return new IXR_Error(401, __('Invalid post type')); break; } $post_author = $content_struct['wp_author_id']; } if (isset($content_struct['mt_allow_comments'])) { if (!is_numeric($content_struct['mt_allow_comments'])) { switch ($content_struct['mt_allow_comments']) { case 'closed': $comment_status = 'closed'; break; case 'open': $comment_status = 'open'; break; default: $comment_status = get_option('default_comment_status'); break; } } else { switch ((int) $content_struct['mt_allow_comments']) { case 0: case 2: $comment_status = 'closed'; break; case 1: $comment_status = 'open'; break; default: $comment_status = get_option('default_comment_status'); break; } } } if (isset($content_struct['mt_allow_pings'])) { if (!is_numeric($content_struct['mt_allow_pings'])) { switch ($content_struct['mt_allow_pings']) { case 'closed': $ping_status = 'closed'; break; case 'open': $ping_status = 'open'; break; default: $ping_status = get_option('default_ping_status'); break; } } else { switch ((int) $content_struct["mt_allow_pings"]) { case 0: $ping_status = 'closed'; break; case 1: $ping_status = 'open'; break; default: $ping_status = get_option('default_ping_status'); break; } } } if (isset($content_struct['title'])) { $post_title = $content_struct['title']; } if (isset($content_struct['description'])) { $post_content = $content_struct['description']; } $post_category = array(); if (isset($content_struct['categories'])) { $catnames = $content_struct['categories']; if (is_array($catnames)) { foreach ($catnames as $cat) { $post_category[] = get_cat_ID($cat); } } } if (isset($content_struct['mt_excerpt'])) { $post_excerpt = $content_struct['mt_excerpt']; } $post_more = isset($content_struct['mt_text_more']) ? $content_struct['mt_text_more'] : null; $post_status = $publish ? 'publish' : 'draft'; if (isset($content_struct["{$post_type}_status"])) { switch ($content_struct["{$post_type}_status"]) { case 'draft': case 'pending': case 'private': case 'publish': $post_status = $content_struct["{$post_type}_status"]; break; default: $post_status = $publish ? 'publish' : 'draft'; break; } } $tags_input = isset($content_struct['mt_keywords']) ? $content_struct['mt_keywords'] : null; if ('publish' == $post_status) { if ('page' == $post_type && !current_user_can('publish_pages')) { return new IXR_Error(401, __('Sorry, you do not have the right to publish this page.')); } else { if (!current_user_can('publish_posts')) { return new IXR_Error(401, __('Sorry, you do not have the right to publish this post.')); } } } if ($post_more) { $post_content = $post_content . "<!--more-->" . $post_more; } $to_ping = null; if (isset($content_struct['mt_tb_ping_urls'])) { $to_ping = $content_struct['mt_tb_ping_urls']; if (is_array($to_ping)) { $to_ping = implode(' ', $to_ping); } } // Do some timestamp voodoo if (!empty($content_struct['date_created_gmt'])) { // We know this is supposed to be GMT, so we're going to slap that Z on there by force $dateCreated = rtrim($content_struct['date_created_gmt']->getIso(), 'Z') . 'Z'; } elseif (!empty($content_struct['dateCreated'])) { $dateCreated = $content_struct['dateCreated']->getIso(); } if (!empty($dateCreated)) { $post_date = get_date_from_gmt(iso8601_to_datetime($dateCreated)); $post_date_gmt = iso8601_to_datetime($dateCreated, 'GMT'); } else { $post_date = $postdata['post_date']; $post_date_gmt = $postdata['post_date_gmt']; } // We've got all the data -- post it: $newpost = compact('ID', 'post_content', 'post_title', 'post_category', 'post_status', 'post_excerpt', 'comment_status', 'ping_status', 'post_date', 'post_date_gmt', 'to_ping', 'post_name', 'post_password', 'post_parent', 'menu_order', 'post_author', 'tags_input', 'page_template'); $result = wp_update_post($newpost, true); if (is_wp_error($result)) { return new IXR_Error(500, $result->get_error_message()); } if (!$result) { return new IXR_Error(500, __('Sorry, your entry could not be edited. Something wrong happened.')); } // Only posts can be sticky if ($post_type == 'post' && isset($content_struct['sticky'])) { if ($content_struct['sticky'] == true) { stick_post($post_ID); } elseif ($content_struct['sticky'] == false) { unstick_post($post_ID); } } if (isset($content_struct['custom_fields'])) { $this->set_custom_fields($post_ID, $content_struct['custom_fields']); } if (isset($content_struct['wp_post_thumbnail'])) { // empty value deletes, non-empty value adds/updates if (empty($content_struct['wp_post_thumbnail'])) { delete_post_thumbnail($post_ID); } else { if (set_post_thumbnail($post_ID, $content_struct['wp_post_thumbnail']) === false) { return new IXR_Error(404, __('Invalid attachment ID.')); } } unset($content_struct['wp_post_thumbnail']); } // Handle enclosures $thisEnclosure = isset($content_struct['enclosure']) ? $content_struct['enclosure'] : null; $this->add_enclosure_if_new($post_ID, $thisEnclosure); $this->attach_uploads($ID, $post_content); // Handle post formats if assigned, validation is handled // earlier in this function if (isset($content_struct['wp_post_format'])) { set_post_format($post_ID, $content_struct['wp_post_format']); } /** * Fires after a post has been successfully updated via the XML-RPC MovableType API. * * @since 3.4.0 * * @param int $post_ID ID of the updated post. * @param array $args An array of arguments to update the post. */ do_action('xmlrpc_call_success_mw_editPost', $post_ID, $args); return true; }
/** * Create new posts based on import information * * Posts marked as having a parent which doesn't exist will become top level items. * Doesn't create a new post if: the post type doesn't exist, the given post ID * is already noted as imported or a post with the same title and date already exists. * Note that new/updated terms, comments and meta are imported for the last of the above. */ protected function process_post($data, $meta, $comments, $terms) { /** * Pre-process post data. * * @param array $data Post data. (Return empty to skip.) * @param array $meta Meta data. * @param array $comments Comments on the post. * @param array $terms Terms on the post. */ $data = apply_filters('wxr_importer.pre_process.post', $data, $meta, $comments, $terms); if (empty($data)) { return false; } $original_id = isset($data['post_id']) ? (int) $data['post_id'] : 0; $parent_id = isset($data['post_parent']) ? (int) $data['post_parent'] : 0; $author_id = isset($data['post_author']) ? (int) $data['post_author'] : 0; // Have we already processed this? if (isset($this->mapping['post'][$original_id])) { return; } $post_type_object = get_post_type_object($data['post_type']); // Is this type even valid? if (!$post_type_object) { $this->logger->warning(sprintf(__('Failed to import "%s": Invalid post type %s', 'wordpress-importer'), $data['post_title'], $data['post_type'])); return false; } $post_exists = $this->post_exists($data); if ($post_exists) { $this->logger->info(sprintf(__('%s "%s" already exists.', 'wordpress-importer'), $post_type_object->labels->singular_name, $data['post_title'])); return false; } // Map the parent post, or mark it as one we need to fix $requires_remapping = false; if ($parent_id) { if (isset($this->mapping['post'][$parent_id])) { $data['post_parent'] = $this->mapping['post'][$parent_id]; } else { $meta[] = array('key' => '_wxr_import_parent', 'value' => $parent_id); $requires_remapping = true; $data['post_parent'] = 0; } } // Map the author, or mark it as one we need to fix $author = sanitize_user($data['post_author'], true); if (empty($author)) { // Missing or invalid author, use default if available. $data['post_author'] = $this->options['default_author']; } elseif (isset($this->mapping['user_slug'][$author])) { $data['post_author'] = $this->mapping['user_slug'][$author]; } else { $meta[] = array('key' => '_wxr_import_user_slug', 'value' => $author); $requires_remapping = true; $data['post_author'] = (int) get_current_user_id(); } // Does the post look like it contains attachment images? if (preg_match(self::REGEX_HAS_ATTACHMENT_REFS, $data['post_content'])) { $meta[] = array('key' => '_wxr_import_has_attachment_refs', 'value' => true); $requires_remapping = true; } // Whitelist to just the keys we allow $postdata = array('import_id' => $data['post_id']); $allowed = array('post_author' => true, 'post_date' => true, 'post_date_gmt' => true, 'post_content' => true, 'post_excerpt' => true, 'post_title' => true, 'post_status' => true, 'post_name' => true, 'comment_status' => true, 'ping_status' => true, 'guid' => true, 'post_parent' => true, 'menu_order' => true, 'post_type' => true, 'post_password' => true); foreach ($data as $key => $value) { if (!isset($allowed[$key])) { continue; } $postdata[$key] = $data[$key]; } $postdata = apply_filters('wp_import_post_data_processed', $postdata, $data); if ('attachment' === $postdata['post_type']) { if (!$this->options['fetch_attachments']) { $this->logger->notice(sprintf(__('Skipping attachment "%s", fetching attachments disabled'), $data['post_title'])); return false; } $remote_url = !empty($data['attachment_url']) ? $data['attachment_url'] : $data['guid']; $post_id = $this->process_attachment($postdata, $meta, $remote_url); } else { $post_id = wp_insert_post($postdata, true); do_action('wp_import_insert_post', $post_id, $original_id, $postdata, $data); } if (is_wp_error($post_id)) { $this->logger->error(sprintf(__('Failed to import "%s" (%s)', 'wordpress-importer'), $data['post_title'], $post_type_object->labels->singular_name)); $this->logger->debug($post_id->get_error_message()); /** * Post processing failed. * * @param WP_Error $post_id Error object. * @param array $data Raw data imported for the post. * @param array $meta Raw meta data, already processed by {@see process_post_meta}. * @param array $comments Raw comment data, already processed by {@see process_comments}. * @param array $terms Raw term data, already processed. */ do_action('wxr_importer.process_failed.post', $post_id, $data, $meta, $comments, $terms); return false; } // Ensure stickiness is handled correctly too if ($data['is_sticky'] == 1) { stick_post($post_id); } // map pre-import ID to local ID $this->mapping['post'][$original_id] = (int) $post_id; if ($requires_remapping) { $this->requires_remapping['post'][$post_id] = true; } $this->mark_post_exists($data, $post_id); $this->logger->info(sprintf(__('Imported "%s" (%s)', 'wordpress-importer'), $data['post_title'], $post_type_object->labels->singular_name)); $this->logger->debug(sprintf(__('Post %d remapped to %d', 'wordpress-importer'), $original_id, $post_id)); // Handle the terms too $terms = apply_filters('wp_import_post_terms', $terms, $post_id, $data); if (!empty($terms)) { $term_ids = array(); foreach ($terms as $term) { $taxonomy = $term['taxonomy']; $key = sha1($taxonomy . ':' . $term['slug']); if (isset($this->mapping['term'][$key])) { $term_ids[$taxonomy][] = $this->mapping['term'][$key]; } else { $meta[] = array('key' => '_wxr_import_term', 'value' => $term); $requires_remapping = true; } } foreach ($term_ids as $tax => $ids) { $tt_ids = wp_set_post_terms($post_id, $ids, $tax); do_action('wp_import_set_post_terms', $tt_ids, $ids, $tax, $post_id, $data); } } $this->process_comments($comments, $post_id, $data); $this->process_post_meta($meta, $post_id, $data); if ('nav_menu_item' === $data['post_type']) { $this->process_menu_item_meta($post_id, $data, $meta); } /** * Post processing completed. * * @param int $post_id New post ID. * @param array $data Raw data imported for the post. * @param array $meta Raw meta data, already processed by {@see process_post_meta}. * @param array $comments Raw comment data, already processed by {@see process_comments}. * @param array $terms Raw term data, already processed. */ do_action('wxr_importer.processed.post', $post_id, $data, $meta, $comments, $terms); }
function save_post_translation($translation_id, $translation) { global $wpdb, $sitepress_settings, $sitepress, $wp_taxonomies, $icl_adjust_id_url_filter_off; $icl_adjust_id_url_filter_off = true; $taxonomies = array_diff(array_keys((array) $wp_taxonomies), array('post_tag', 'category')); $tinfo = $wpdb->get_row($wpdb->prepare("\n SELECT * FROM {$wpdb->prefix}icl_translations tr\n JOIN {$wpdb->prefix}icl_translation_status ts ON ts.translation_id = tr.translation_id\n WHERE tr.translation_id=%d", $translation_id)); $lang_code = $tinfo->language_code; $trid = $tinfo->trid; $original_post_details = $wpdb->get_row("\n SELECT p.post_author, p.post_type, p.post_status, p.comment_status, p.ping_status, p.post_parent, p.menu_order, p.post_date, t.language_code\n FROM {$wpdb->prefix}icl_translations t \n JOIN {$wpdb->posts} p ON t.element_id = p.ID AND CONCAT('post_',p.post_type) = t.element_type\n WHERE trid='{$trid}' AND p.ID = '{$translation['original_id']}'\n "); //is the original post a sticky post? remove_filter('option_sticky_posts', array($sitepress, 'option_sticky_posts')); // remove filter used to get language relevant stickies. get them all $sticky_posts = get_option('sticky_posts'); $is_original_sticky = $original_post_details->post_type == 'post' && in_array($translation['original_id'], $sticky_posts); $this->_content_fix_image_paths_in_body($translation); $this->_content_fix_relative_link_paths_in_body($translation); $this->_content_decode_shortcodes($translation); // deal with tags if (isset($translation['tags'])) { $translated_tags = $translation['tags']; $translated_tag_ids = explode(',', $translation['tag_ids']); foreach ($translated_tags as $k => $v) { $tag_trid = $wpdb->get_var("SELECT trid FROM {$wpdb->prefix}icl_translations WHERE element_id='{$translated_tag_ids[$k]}' AND element_type='tax_post_tag'"); // before adding the new term make sure that another tag with the same name doesn't exist. If it does append @lang // same term name exists in a different language? $term_different_language = $wpdb->get_var("\n SELECT tm.term_id \n FROM {$wpdb->term_taxonomy} tx\n JOIN {$wpdb->terms} tm ON tx.term_id = tm.term_id \n JOIN {$wpdb->prefix}icl_translations tr ON tx.term_taxonomy_id = tr.element_id\n WHERE tm.name='" . $wpdb->escape($v) . "' AND tr.element_type LIKE 'tax\\_%' AND tr.language_code <> '{$lang_code}'\n "); if ($term_different_language) { $v .= ' @' . $lang_code; } //tag exists? (in the current language) $etag = get_term_by('name', htmlspecialchars($v), 'post_tag'); if (!$etag) { $etag = get_term_by('name', htmlspecialchars($v) . ' @' . $lang_code, 'post_tag'); } if (!$etag) { $tmp = wp_insert_term($v, 'post_tag'); if (!is_wp_error($tmp) && isset($tmp['term_taxonomy_id'])) { $wpdb->update($wpdb->prefix . 'icl_translations', array('language_code' => $lang_code, 'trid' => $tag_trid, 'source_language_code' => $original_post_details->language_code), array('element_type' => 'tax_post_tag', 'element_id' => $tmp['term_taxonomy_id'])); } } else { $term_taxonomy_id = $etag->term_taxonomy_id; // check whether we have an orphan translation - the same trid and language but a different element id $__translation_id = $wpdb->get_var("\n SELECT translation_id FROM {$wpdb->prefix}icl_translations \n WHERE trid = '{$tag_trid}' \n AND language_code = '{$lang_code}' \n AND element_id <> '{$term_taxonomy_id}'\n "); if ($__translation_id) { $wpdb->query("DELETE FROM {$wpdb->prefix}icl_translations WHERE translation_id={$__translation_id}"); } $tag_translation_id = $wpdb->get_var("SELECT translation_id FROM {$wpdb->prefix}icl_translations WHERE element_id={$term_taxonomy_id} AND element_type='tax_post_tag'"); if ($tag_translation_id) { $wpdb->update($wpdb->prefix . 'icl_translations', array('language_code' => $lang_code, 'trid' => $tag_trid, 'source_language_code' => $original_post_details->language_code), array('element_type' => 'tax_post_tag', 'translation_id' => $tag_translation_id)); } else { $wpdb->insert($wpdb->prefix . 'icl_translations', array('language_code' => $lang_code, 'trid' => $tag_trid, 'element_type' => 'tax_post_tag', 'element_id' => $term_taxonomy_id, 'source_language_code' => $original_post_details->language_code)); } } } } $original_post_tags = array(); foreach (wp_get_object_terms($translation['original_id'], 'post_tag') as $t) { $original_post_tags[] = $t->term_taxonomy_id; } if ($original_post_tags) { $tag_trids = $wpdb->get_col("SELECT trid FROM {$wpdb->prefix}icl_translations WHERE element_type='tax_post_tag' AND element_id IN (" . join(',', $original_post_tags) . ")"); if (!empty($tag_trids)) { $tag_tr_tts = $wpdb->get_col("SELECT element_id FROM {$wpdb->prefix}icl_translations WHERE element_type='tax_post_tag' AND language_code='{$lang_code}' AND trid IN (" . join(',', $tag_trids) . ")"); } if (!empty($tag_tr_tts)) { $translated_tags = $wpdb->get_col("SELECT t.name FROM {$wpdb->terms} t JOIN {$wpdb->term_taxonomy} tx ON tx.term_id = t.term_id WHERE tx.taxonomy='post_tag' AND tx.term_taxonomy_id IN (" . join(',', $tag_tr_tts) . ")"); } } // deal with categories if (isset($translation['categories'])) { $translated_cats = $translation['categories']; $translated_cats_ids = explode(',', $translation['category_ids']); foreach ($translated_cats as $k => $v) { //$v = trim(str_replace('<p>', '', $v)); $cat_trid = $wpdb->get_var("SELECT trid FROM {$wpdb->prefix}icl_translations WHERE element_id='{$translated_cats_ids[$k]}' AND element_type='tax_category'"); // before adding the new term make sure that another tag with the same name doesn't exist. If it does append @lang // same term name exists in a different language? $term_different_language = $wpdb->get_var("\n SELECT tm.term_id \n FROM {$wpdb->term_taxonomy} tx\n JOIN {$wpdb->terms} tm ON tx.term_id = tm.term_id \n JOIN {$wpdb->prefix}icl_translations tr ON tx.term_taxonomy_id = tr.element_id\n WHERE tm.name='" . $wpdb->escape($v) . "' AND tr.element_type LIKE 'tax\\_%' AND tr.language_code <> '{$lang_code}'\n "); if ($term_different_language) { $v .= ' @' . $lang_code; } //cat exists? $ecat = get_term_by('name', htmlspecialchars($v), 'category'); if (!$ecat) { $ecat = get_term_by('name', htmlspecialchars($v) . ' @' . $lang_code, 'category'); } if (!$ecat) { // get original category parent id $original_category_parent_id = $wpdb->get_var($wpdb->prepare("SELECT parent FROM {$wpdb->term_taxonomy} WHERE term_taxonomy_id=%d", $translated_cats_ids[$k])); if ($original_category_parent_id) { $_op_tax_id = $wpdb->get_var($wpdb->prepare("SELECT term_taxonomy_id FROM {$wpdb->term_taxonomy} WHERE taxonomy='category' AND term_id=%d", $original_category_parent_id)); $_op_trid = $wpdb->get_var($wpdb->prepare("SELECT trid FROM {$wpdb->prefix}icl_translations WHERE element_type='tax_category' AND element_id=%d", $_op_tax_id)); // get id of the translated category parent $_tp_tax_id = $wpdb->get_var($wpdb->prepare("SELECT element_id FROM {$wpdb->prefix}icl_translations WHERE language_code='{$lang_code}' AND trid=%d", $_op_trid)); if ($_tp_tax_id) { $category_parent_id = $wpdb->get_var($wpdb->prepare("SELECT term_id FROM {$wpdb->term_taxonomy} WHERE taxonomy='category' AND term_taxonomy_id=%d", $_tp_tax_id)); } else { $category_parent_id = 0; } } else { $category_parent_id = 0; } $tmp = wp_insert_term($v, 'category', array('parent' => $category_parent_id)); if (!is_wp_error($tmp) && isset($tmp['term_taxonomy_id'])) { $wpdb->update($wpdb->prefix . 'icl_translations', array('language_code' => $lang_code, 'trid' => $cat_trid, 'source_language_code' => $original_post_details->language_code), array('element_type' => 'tax_category', 'element_id' => $tmp['term_taxonomy_id'])); // if this is a parent category, make sure that nesting is correct for all translations $orig_cat_tax_id = $wpdb->get_var($wpdb->prepare("SELECT element_id FROM {$wpdb->prefix}icl_translations WHERE trid=%d AND source_language_code IS NULL", $cat_trid)); $orig_cat_term_id = $wpdb->get_var($wpdb->prepare("SELECT term_id FROM {$wpdb->term_taxonomy} WHERE term_taxonomy_id=%d AND taxonomy='category'", $orig_cat_tax_id)); $orig_cat_children = $wpdb->get_col($wpdb->prepare("SELECT term_id FROM {$wpdb->term_taxonomy} WHERE parent=%d", $orig_cat_term_id)); if (!empty($orig_cat_children)) { foreach ($orig_cat_children as $ch) { $_tr_child = icl_object_id($ch, 'category', false, $lang_code); if ($_tr_child) { $wpdb->update($wpdb->term_taxonomy, array('parent' => $tmp['term_id']), array('taxonomy' => 'category', 'term_id' => $_tr_child)); } } } delete_option('category_children'); } } else { $term_taxonomy_id = $ecat->term_taxonomy_id; // check whether we have an orphan translation - the same trid and language but a different element id $__translation_id = $wpdb->get_var("\n SELECT translation_id FROM {$wpdb->prefix}icl_translations \n WHERE trid = '{$cat_trid}' \n AND language_code = '{$lang_code}' \n AND element_id <> '{$term_taxonomy_id}'\n "); if ($__translation_id) { $wpdb->query("DELETE FROM {$wpdb->prefix}icl_translations WHERE translation_id={$__translation_id}"); } $cat_translation_id = $wpdb->get_var("SELECT translation_id FROM {$wpdb->prefix}icl_translations WHERE element_id={$term_taxonomy_id} AND element_type='tax_category'"); if ($cat_translation_id) { $wpdb->update($wpdb->prefix . 'icl_translations', array('language_code' => $lang_code, 'trid' => $cat_trid, 'source_language_code' => $original_post_details->language_code), array('element_type' => 'tax_category', 'translation_id' => $cat_translation_id)); } else { $wpdb->insert($wpdb->prefix . 'icl_translations', array('language_code' => $lang_code, 'trid' => $cat_trid, 'element_type' => 'tax_category', 'element_id' => $term_taxonomy_id, 'source_language_code' => $original_post_details->language_code)); } } } } $original_post_cats = array(); foreach (wp_get_object_terms($translation['original_id'], 'category') as $t) { $original_post_cats[] = $t->term_taxonomy_id; } if ($original_post_cats) { $cat_trids = $wpdb->get_col("SELECT trid FROM {$wpdb->prefix}icl_translations WHERE element_type='tax_category' AND element_id IN (" . join(',', $original_post_cats) . ")"); if (!empty($cat_trids)) { $cat_tr_tts = $wpdb->get_col("SELECT element_id FROM {$wpdb->prefix}icl_translations WHERE element_type='tax_category' AND language_code='{$lang_code}' AND trid IN (" . join(',', $cat_trids) . ")"); } if (!empty($cat_tr_tts)) { $translated_cats_ids = $wpdb->get_col("SELECT t.term_id FROM {$wpdb->terms} t JOIN {$wpdb->term_taxonomy} tx ON tx.term_id = t.term_id WHERE tx.taxonomy='category' AND tx.term_taxonomy_id IN (" . join(',', $cat_tr_tts) . ")"); } } // deal with custom taxonomies if (!empty($sitepress_settings['taxonomies_sync_option'])) { foreach ($sitepress_settings['taxonomies_sync_option'] as $taxonomy => $value) { if ($value == 1 && isset($translation[$taxonomy])) { $translated_taxs[$taxonomy] = $translation[$taxonomy]; $translated_tax_ids[$taxonomy] = explode(',', $translation[$taxonomy . '_ids']); foreach ($translated_taxs[$taxonomy] as $k => $v) { $tax_trid = $wpdb->get_var("\n SELECT trid FROM {$wpdb->prefix}icl_translations \n WHERE element_id='{$translated_tax_ids[$taxonomy][$k]}' AND element_type='tax_{$taxonomy}'"); // before adding the new term make sure that another tag with the same name doesn't exist. If it does append @lang // same term name exists in a different language? $term_different_language = $wpdb->get_var("\n SELECT tm.term_id \n FROM {$wpdb->term_taxonomy} tx\n JOIN {$wpdb->terms} tm ON tx.term_id = tm.term_id \n JOIN {$wpdb->prefix}icl_translations tr ON tx.term_taxonomy_id = tr.element_id\n WHERE tm.name='" . $wpdb->escape($v) . "' AND tr.element_type LIKE 'tax\\_%' AND tr.language_code <> '{$lang_code}'\n "); if ($term_different_language) { $v .= ' @' . $lang_code; } //tax exists? (in the current language) $etag = get_term_by('name', htmlspecialchars($v), $taxonomy); if (!$etag) { $etag = get_term_by('name', htmlspecialchars($v) . ' @' . $lang_code, $taxonomy); } if (!$etag) { // get original category parent id $original_t_parent_id = $wpdb->get_var($wpdb->prepare("SELECT parent FROM {$wpdb->term_taxonomy} WHERE term_taxonomy_id=%d", $translated_tax_ids[$taxonomy][$k])); if ($original_t_parent_id) { $_op_tax_id = $wpdb->get_var($wpdb->prepare("SELECT term_taxonomy_id FROM {$wpdb->term_taxonomy} WHERE taxonomy='category' AND term_id=%d", $original_t_parent_id)); $_op_trid = $wpdb->get_var($wpdb->prepare("SELECT trid FROM {$wpdb->prefix}icl_translations WHERE element_type='tax_category' AND element_id=%d", $_op_tax_id)); // get id of the translated category parent $_tp_tax_id = $wpdb->get_var($wpdb->prepare("SELECT element_id FROM {$wpdb->prefix}icl_translations WHERE language_code='{$lang_code}' AND trid=%d", $_op_trid)); if ($_tp_tax_id) { $t_parent_id = $wpdb->get_var($wpdb->prepare("SELECT term_id FROM {$wpdb->term_taxonomy} WHERE taxonomy='category' AND term_taxonomy_id=%d", $_tp_tax_id)); } else { $t_parent_id = 0; } } else { $t_parent_id = 0; } $tmp = wp_insert_term($v, $taxonomy); if (!is_wp_error($tmp) && isset($tmp['term_taxonomy_id'])) { $wpdb->update($wpdb->prefix . 'icl_translations', array('language_code' => $lang_code, 'trid' => $tax_trid, 'source_language_code' => $original_post_details->language_code), array('element_type' => 'tax_' . $taxonomy, 'element_id' => $tmp['term_taxonomy_id'])); // if this is a parent category, make sure that nesting is correct for all translations $orig_tax_id = $wpdb->get_var($wpdb->prepare("SELECT element_id FROM {$wpdb->prefix}icl_translations WHERE trid=%d AND source_language_code IS NULL", $tax_trid)); $orig_term_id = $wpdb->get_var($wpdb->prepare("SELECT term_id FROM {$wpdb->term_taxonomy} WHERE term_taxonomy_id=%d AND taxonomy='{$taxonomy}'", $orig_tax_id)); $orig_tax_children = $wpdb->get_col($wpdb->prepare("SELECT term_id FROM {$wpdb->term_taxonomy} WHERE parent=%d", $orig_term_id)); if (!empty($orig_tax_children)) { foreach ($orig_tax_children as $ch) { $_tr_child = icl_object_id($ch, $taxonomy, false, $lang_code); if ($_tr_child) { $wpdb->update($wpdb->term_taxonomy, array('parent' => $tmp['term_id']), array('taxonomy' => $taxonomy, 'term_id' => $_tr_child)); } } } delete_option($taxonomy . '_children'); } } else { $term_taxonomy_id = $etag->term_taxonomy_id; // check whether we have an orphan translation - the same trid and language but a different element id $__translation_id = $wpdb->get_var("\n SELECT translation_id FROM {$wpdb->prefix}icl_translations \n WHERE trid = '{$tax_trid}' \n AND language_code = '{$lang_code}' \n AND element_id <> '{$term_taxonomy_id}'\n "); if ($__translation_id) { $wpdb->query("DELETE FROM {$wpdb->prefix}icl_translations WHERE translation_id={$__translation_id}"); } $tax_translation_id = $wpdb->get_var("\n SELECT translation_id FROM {$wpdb->prefix}icl_translations \n WHERE element_id={$term_taxonomy_id} AND element_type='tax_{$taxonomy}'"); if ($tax_translation_id) { $wpdb->update($wpdb->prefix . 'icl_translations', array('language_code' => $lang_code, 'trid' => $tax_trid, 'source_language_code' => $original_post_details->language_code), array('element_type' => 'tax_' . $taxonomy, 'translation_id' => $tax_translation_id)); } else { $wpdb->insert($wpdb->prefix . 'icl_translations', array('language_code' => $lang_code, 'trid' => $tax_trid, 'element_type' => 'tax_' . $taxonomy, 'element_id' => $term_taxonomy_id, 'source_language_code' => $original_post_details->language_code)); } } } } $oterms = wp_get_object_terms($translation['original_id'], $taxonomy); if (!is_wp_error($oterms)) { foreach ($oterms as $t) { $original_post_taxs[$taxonomy][] = $t->term_taxonomy_id; } } if (!empty($original_post_taxs[$taxonomy])) { $tax_trids = $wpdb->get_col("SELECT trid FROM {$wpdb->prefix}icl_translations \n WHERE element_type='tax_{$taxonomy}' AND element_id IN (" . join(',', $original_post_taxs[$taxonomy]) . ")"); if (!empty($tax_trids)) { $tax_tr_tts = $wpdb->get_col("SELECT element_id FROM {$wpdb->prefix}icl_translations \n WHERE element_type='tax_{$taxonomy}' AND language_code='{$lang_code}' AND trid IN (" . join(',', $tax_trids) . ")"); } if (!empty($tax_tr_tts)) { if ($wp_taxonomies[$taxonomy]->hierarchical) { $translated_tax_ids[$taxonomy] = $wpdb->get_col("SELECT term_id FROM {$wpdb->term_taxonomy} WHERE term_taxonomy_id IN (" . join(',', $tax_tr_tts) . ")"); } else { $translated_taxs[$taxonomy] = $wpdb->get_col("SELECT t.name FROM {$wpdb->terms} t \n JOIN {$wpdb->term_taxonomy} tx ON tx.term_id = t.term_id \n WHERE tx.taxonomy='{$taxonomy}' AND tx.term_taxonomy_id IN (" . join(',', $tax_tr_tts) . ")"); } } } } } // handle the page parent and set it to the translated parent if we have one. if ($original_post_details->post_parent) { $post_parent_trid = $wpdb->get_var("SELECT trid FROM {$wpdb->prefix}icl_translations WHERE element_type='post_{$original_post_details->post_type}' AND element_id='{$original_post_details->post_parent}'"); if ($post_parent_trid) { $parent_id = $wpdb->get_var("SELECT element_id FROM {$wpdb->prefix}icl_translations WHERE element_type='post_{$original_post_details->post_type}' AND trid='{$post_parent_trid}' AND language_code='{$lang_code}'"); } } // determine post id based on trid $post_id = $tinfo->element_id; if ($post_id) { // see if the post really exists - make sure it wasn't deleted while the plugin was if (!$wpdb->get_var("SELECT ID FROM {$wpdb->posts} WHERE ID={$post_id}")) { $is_update = false; $wpdb->query("DELETE FROM {$wpdb->prefix}icl_translations WHERE element_type='post_{$original_post_details->post_type}' AND element_id={$post_id}"); } else { $is_update = true; $postarr['ID'] = $_POST['post_ID'] = $post_id; } } else { $is_update = false; } $postarr['post_title'] = $translation['title']; $postarr['post_content'] = $translation['body']; if (isset($translation['excerpt']) && $translation['excerpt'] != "") { $postarr['post_excerpt'] = $translation['excerpt']; } if (@is_array($translated_tags)) { $postarr['tags_input'] = join(',', (array) $translated_tags); } if (@is_array($translated_taxs)) { foreach ($translated_taxs as $taxonomy => $values) { $postarr['tax_input'][$taxonomy] = join(',', (array) $values); } } if (@is_array($translated_tax_ids)) { $postarr['tax_input'] = $translated_tax_ids; } if (isset($translated_cats_ids)) { $postarr['post_category'] = $translated_cats_ids; } $postarr['post_author'] = $original_post_details->post_author; $postarr['post_type'] = $original_post_details->post_type; if ($sitepress_settings['sync_comment_status']) { $postarr['comment_status'] = $original_post_details->comment_status; } if ($sitepress_settings['sync_ping_status']) { $postarr['ping_status'] = $original_post_details->ping_status; } if ($sitepress_settings['sync_page_ordering']) { $postarr['menu_order'] = $original_post_details->menu_order; } if ($sitepress_settings['sync_private_flag'] && $original_post_details->post_status == 'private') { $postarr['post_status'] = 'private'; } if (!$is_update) { $postarr['post_status'] = !$sitepress_settings['translated_document_status'] ? 'draft' : $original_post_details->post_status; } else { // set post_status to the current post status. $postarr['post_status'] = $wpdb->get_var("SELECT post_status FROM {$wpdb->prefix}posts WHERE ID = " . $post_id); } if ($sitepress_settings['sync_post_date']) { $postarr['post_date'] = $original_post_details->post_date; } if (isset($parent_id) && $sitepress_settings['sync_page_parent']) { $_POST['post_parent'] = $postarr['post_parent'] = $parent_id; $_POST['parent_id'] = $postarr['parent_id'] = $parent_id; } if ($is_update) { $postarr['post_name'] = $wpdb->get_var($wpdb->prepare("SELECT post_name FROM {$wpdb->posts} WHERE ID=%d", $post_id)); } $_POST['trid'] = $trid; $_POST['lang'] = $lang_code; $_POST['skip_sitepress_actions'] = true; global $wp_rewrite; if (!isset($wp_rewrite)) { $wp_rewrite = new WP_Rewrite(); } kses_remove_filters(); $postarr = apply_filters('icl_pre_save_pro_translation', $postarr); $new_post_id = wp_insert_post($postarr); do_action('icl_pro_translation_saved', $new_post_id); // associate custom taxonomies by hand if (!empty($postarr['tax_input'])) { foreach ($postarr['tax_input'] as $taxonomy => $tags) { wp_set_post_terms($new_post_id, $tags, $taxonomy); } } // set stickiness if ($is_original_sticky && $sitepress_settings['sync_sticky_flag']) { stick_post($new_post_id); } else { if ($original_post_details->post_type == 'post' && $is_update) { unstick_post($new_post_id); //just in case - if this is an update and the original post stckiness has changed since the post was sent to translation } } foreach ((array) $sitepress_settings['translation-management']['custom_fields_translation'] as $cf => $op) { if ($op == 1) { update_post_meta($new_post_id, $cf, get_post_meta($translation['original_id'], $cf, true)); } elseif ($op == 2 && isset($translation['field-' . $cf])) { $field_translation = $translation['field-' . $cf]; $field_type = $translation['field-' . $cf . '-type']; if ($field_type == 'custom_field') { $field_translation = str_replace('�A;', "\n", $field_translation); // always decode html entities eg decode & to & $field_translation = html_entity_decode($field_translation); update_post_meta($new_post_id, $cf, $field_translation); } } } // set specific custom fields $copied_custom_fields = array('_top_nav_excluded', '_cms_nav_minihome'); foreach ($copied_custom_fields as $ccf) { $val = get_post_meta($translation['original_id'], $ccf, true); update_post_meta($new_post_id, $ccf, $val); } // sync _wp_page_template if ($sitepress_settings['sync_page_template']) { $_wp_page_template = get_post_meta($translation['original_id'], '_wp_page_template', true); update_post_meta($new_post_id, '_wp_page_template', $_wp_page_template); } if (!$new_post_id) { return false; } if (!$is_update) { $wpdb->update($wpdb->prefix . 'icl_translations', array('element_id' => $new_post_id), array('translation_id' => $translation_id)); } update_post_meta($new_post_id, '_icl_translation', 1); global $iclTranslationManagement; $ts = array('status' => ICL_TM_COMPLETE, 'needs_update' => 0, 'translation_id' => $translation_id); $translator_id = $wpdb->get_var($wpdb->prepare("SELECT translator_id FROM {$wpdb->prefix}icl_translation_status WHERE translation_id=%d", $translation_id)); if (!$translator_id) { foreach ($sitepress_settings['icl_lang_status'] as $lpair) { if ($lpair['from'] == $original_post_details->language_code && $lpair['to'] == $lang_code && isset($lpair['translators'][0]['id'])) { $ts['translator_id'] = $lpair['translators'][0]['id']; break; } } } // update translation status $iclTranslationManagement->update_translation_status($ts); // add new translation job //$translation_package = $iclTranslationManagement->create_translation_package(get_post($translation['original_id'])); //$job_id = $iclTranslationManagement->add_translation_job($tinfo->rid, $tinfo->translator_id, $translation_package); $job_id = $iclTranslationManagement->get_translation_job_id($trid, $lang_code); // save the translation $iclTranslationManagement->mark_job_done($job_id); $parts = explode('_', $translation['original_id']); if ($parts[0] != 'external') { $iclTranslationManagement->save_job_fields_from_post($job_id, get_post($new_post_id)); $this->_content_fix_links_to_translated_content($new_post_id, $lang_code, "post_{$original_post_details->post_type}"); if (function_exists('icl_st_fix_links_in_strings')) { icl_st_fix_links_in_strings($new_post_id); } // Now try to fix links in other translated content that may link to this post. $sql = "SELECT\n tr.element_id\n FROM\n {$wpdb->prefix}icl_translations tr\n JOIN\n {$wpdb->prefix}icl_translation_status ts\n ON\n tr.translation_id = ts.translation_id\n WHERE\n ts.links_fixed = 0 AND tr.element_type = 'post_{$original_post_details->post_type}' AND tr.language_code = '{$lang_code}' AND tr.element_id IS NOT NULL"; $needs_fixing = $wpdb->get_results($sql); foreach ($needs_fixing as $id) { if ($id->element_id != $new_post_id) { // fix all except the new_post_id. We have already done this. $this->_content_fix_links_to_translated_content($id->element_id, $lang_code, "post_{$original_post_details->post_type}"); } } // if this is a parent page then make sure it's children point to this. $this->fix_translated_children($translation['original_id'], $new_post_id, $lang_code); } return true; }
/** * Helper method for {@see create_post} and {@see edit_post}, containing shared logic. * * * @param array $data Post data to insert. * * @return int|WP_Error */ protected function insert_post(array $data) { $post = array(); $update = !empty($data['ID']); if ($update) { $current_post = get_post(absint($data['ID'])); if (!$current_post) { return new WP_Error('json_post_invalid_id', __('Invalid post ID.'), array('status' => 400)); } $post['ID'] = absint($data['ID']); } else { // Defaults $post['post_author'] = 0; $post['post_password'] = ''; $post['post_excerpt'] = ''; $post['post_content'] = ''; $post['post_title'] = ''; } // Post type if (!empty($data['type'])) { // Changing post type $post_type = get_post_type_object($data['type']); if (!$post_type) { return new WP_Error('json_invalid_post_type', __('Invalid post type'), array('status' => 400)); } $post['post_type'] = $data['type']; } elseif ($update) { // Updating post, use existing post type $current_post = get_post($data['ID']); if (!$current_post) { return new WP_Error('json_post_invalid_id', __('Invalid post ID.'), array('status' => 400)); } $post_type = get_post_type_object($current_post->post_type); $post['post_type'] = $current_post->post_type; } else { // Creating new post, use default type $post['post_type'] = apply_filters('json_insert_default_post_type', 'post'); $post_type = get_post_type_object($post['post_type']); if (!$post_type) { return new WP_Error('json_invalid_post_type', __('Invalid post type'), array('status' => 400)); } } // Permissions check if ($update) { if (!json_check_post_permission($post, 'edit')) { return new WP_Error('json_cannot_edit', __('Sorry, you are not allowed to edit this post.'), array('status' => 401)); } if ($post_type->name != get_post_type($data['ID'])) { return new WP_Error('json_cannot_change_post_type', __('The post type may not be changed.'), array('status' => 400)); } } else { if (!json_check_post_permission($post, 'create')) { return new WP_Error('json_cannot_create', __('Sorry, you are not allowed to post on this site.'), array('status' => 403)); } } // Post status if (!empty($data['status'])) { $post['post_status'] = $data['status']; switch ($post['post_status']) { case 'draft': case 'pending': break; case 'private': if (!json_check_post_permission($post, 'publish_posts')) { return new WP_Error('json_cannot_create_private', __('Sorry, you are not allowed to create private posts in this post type'), array('status' => 403)); } break; case 'publish': case 'future': if (!json_check_post_permission($post, 'publish_posts')) { return new WP_Error('json_cannot_publish', __('Sorry, you are not allowed to publish posts in this post type'), array('status' => 403)); } break; default: if (!get_post_status_object($post['post_status'])) { $post['post_status'] = 'draft'; } break; } } // Post title if (!empty($data['title'])) { $post['post_title'] = $data['title']; } // Post date if (!empty($data['date'])) { $date_data = json_get_date_with_gmt($data['date']); if (!empty($date_data)) { list($post['post_date'], $post['post_date_gmt']) = $date_data; } } elseif (!empty($data['date_gmt'])) { $date_data = json_get_date_with_gmt($data['date_gmt'], true); if (!empty($date_data)) { list($post['post_date'], $post['post_date_gmt']) = $date_data; } } // Post slug if (!empty($data['name'])) { $post['post_name'] = $data['name']; } // Author if (!empty($data['author'])) { // Allow passing an author object if (is_object($data['author'])) { if (empty($data['author']->ID)) { return new WP_Error('json_invalid_author', __('Invalid author object.'), array('status' => 400)); } $data['author'] = (int) $data['author']->ID; } else { $data['author'] = (int) $data['author']; } // Only check edit others' posts if we are another user if ($data['author'] !== get_current_user_id()) { if (!json_check_post_permission($post, 'edit_others_posts')) { return new WP_Error('json_cannot_edit_others', __('You are not allowed to edit posts as this user.'), array('status' => 401)); } $author = get_userdata($data['author']); if (!$author) { return new WP_Error('json_invalid_author', __('Invalid author ID.'), array('status' => 400)); } } $post['post_author'] = $data['author']; } // Post password if (!empty($data['password'])) { $post['post_password'] = $data['password']; if (!json_check_post_permission($post, 'publish_posts')) { return new WP_Error('json_cannot_create_passworded', __('Sorry, you are not allowed to create password protected posts in this post type'), array('status' => 401)); } } // Content and excerpt if (!empty($data['content_raw'])) { $post['post_content'] = $data['content_raw']; } if (!empty($data['excerpt_raw'])) { $post['post_excerpt'] = $data['excerpt_raw']; } // Parent if (!empty($data['parent'])) { $parent = get_post($data['parent']); if (empty($parent)) { return new WP_Error('json_post_invalid_id', __('Invalid post parent ID.'), array('status' => 400)); } $post['post_parent'] = $parent->ID; } // Menu order if (!empty($data['menu_order'])) { $post['menu_order'] = $data['menu_order']; } // Comment status if (!empty($data['comment_status'])) { $post['comment_status'] = $data['comment_status']; } // Ping status if (!empty($data['ping_status'])) { $post['ping_status'] = $data['ping_status']; } // Post format if (!empty($data['post_format'])) { $formats = get_post_format_slugs(); if (!in_array($data['post_format'], $formats)) { return new WP_Error('json_invalid_post_format', __('Invalid post format.'), array('status' => 400)); } $post['post_format'] = $data['post_format']; } // Pre-insert hook $can_insert = apply_filters('json_pre_insert_post', true, $post, $data, $update); if (is_wp_error($can_insert)) { return $can_insert; } // Post meta // TODO: implement this $post_ID = $update ? wp_update_post($post, true) : wp_insert_post($post, true); if (is_wp_error($post_ID)) { return $post_ID; } // If this is a new post, add the post ID to $post if (!$update) { $post['ID'] = $post_ID; } // Post meta if (!empty($data['post_meta'])) { $result = $this->handle_post_meta_action($post_ID, $data); if (is_wp_error($result)) { return $result; } } // Sticky if (isset($data['sticky'])) { if ($data['sticky']) { stick_post($post_ID); } else { unstick_post($post_ID); } } do_action('json_insert_post', $post, $data, $update); return $post_ID; }