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;
 }
/**
 * Unstick Posts
 *
 * @access public
 * @since 1.0
 * @return void
 */
function pw_esp_unstick($title = '', $post_id = 0)
{
    if (pw_esp_is_expired($post_id)) {
        // Post is expired so unstick
        unstick_post($post_id);
    }
    return $title;
}
Exemple #3
0
function unsticky_unstick()
{
    $args = array('post__in' => get_option('sticky_posts'));
    $stickyQuery = get_posts($args);
    error_log($stickyQuery);
    foreach ($stickyQuery as $id) {
        $timeToUnstick = get_post_meta($id, '_unsticky_time', true);
        error_log(print_r($timeToUnstick));
        if ($timeToUnstick < time()) {
            unstick_post($id);
        }
    }
}
/**
 * Trashes or deletes a post or page.
 *
 * When the post and page is permanently deleted, everything that is tied to it is deleted also.
 * This includes comments, post meta fields, and terms associated with the post.
 *
 * The post or page is moved to trash instead of permanently deleted unless trash is
 * disabled, item is already in the trash, or $force_delete is true.
 *
 * @since 1.0.0
 * @uses do_action() on 'delete_post' before deletion unless post type is 'attachment'.
 * @uses do_action() on 'deleted_post' after deletion unless post type is 'attachment'.
 * @uses wp_delete_attachment() if post type is 'attachment'.
 * @uses wp_trash_post() if item should be trashed.
 *
 * @param int $postid Post ID.
 * @param bool $force_delete Whether to bypass trash and force deletion. Defaults to false.
 * @return mixed False on failure
 */
function wp_delete_post($postid = 0, $force_delete = false)
{
    global $wpdb, $wp_rewrite;
    if (!($post = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$wpdb->posts} WHERE ID = %d", $postid)))) {
        return $post;
    }
    if (!$force_delete && ($post->post_type == 'post' || $post->post_type == 'page') && get_post_status($postid) != 'trash' && EMPTY_TRASH_DAYS) {
        return wp_trash_post($postid);
    }
    if ($post->post_type == 'attachment') {
        return wp_delete_attachment($postid, $force_delete);
    }
    do_action('delete_post', $postid);
    delete_post_meta($postid, '_wp_trash_meta_status');
    delete_post_meta($postid, '_wp_trash_meta_time');
    wp_delete_object_term_relationships($postid, get_object_taxonomies($post->post_type));
    $parent_data = array('post_parent' => $post->post_parent);
    $parent_where = array('post_parent' => $postid);
    if ('page' == $post->post_type) {
        // if the page is defined in option page_on_front or post_for_posts,
        // adjust the corresponding options
        if (get_option('page_on_front') == $postid) {
            update_option('show_on_front', 'posts');
            delete_option('page_on_front');
        }
        if (get_option('page_for_posts') == $postid) {
            delete_option('page_for_posts');
        }
        // Point children of this page to its parent, also clean the cache of affected children
        $children_query = $wpdb->prepare("SELECT * FROM {$wpdb->posts} WHERE post_parent = %d AND post_type='page'", $postid);
        $children = $wpdb->get_results($children_query);
        $wpdb->update($wpdb->posts, $parent_data, $parent_where + array('post_type' => 'page'));
    } else {
        unstick_post($postid);
    }
    // Do raw query.  wp_get_post_revisions() is filtered
    $revision_ids = $wpdb->get_col($wpdb->prepare("SELECT ID FROM {$wpdb->posts} WHERE post_parent = %d AND post_type = 'revision'", $postid));
    // Use wp_delete_post (via wp_delete_post_revision) again.  Ensures any meta/misplaced data gets cleaned up.
    foreach ($revision_ids as $revision_id) {
        wp_delete_post_revision($revision_id);
    }
    // Point all attachments to this post up one level
    $wpdb->update($wpdb->posts, $parent_data, $parent_where + array('post_type' => 'attachment'));
    $comment_ids = $wpdb->get_col($wpdb->prepare("SELECT comment_ID FROM {$wpdb->comments} WHERE comment_post_ID = %d", $postid));
    if (!empty($comment_ids)) {
        do_action('delete_comment', $comment_ids);
        foreach ($comment_ids as $comment_id) {
            wp_delete_comment($comment_id, true);
        }
        do_action('deleted_comment', $comment_ids);
    }
    $post_meta_ids = $wpdb->get_col($wpdb->prepare("SELECT meta_id FROM {$wpdb->postmeta} WHERE post_id = %d ", $postid));
    if (!empty($post_meta_ids)) {
        do_action('delete_postmeta', $post_meta_ids);
        $in_post_meta_ids = "'" . implode("', '", $post_meta_ids) . "'";
        $wpdb->query("DELETE FROM {$wpdb->postmeta} WHERE meta_id IN({$in_post_meta_ids})");
        do_action('deleted_postmeta', $post_meta_ids);
    }
    do_action('delete_post', $postid);
    $wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->posts} WHERE ID = %d", $postid));
    do_action('deleted_post', $postid);
    if ('page' == $post->post_type) {
        clean_page_cache($postid);
        foreach ((array) $children as $child) {
            clean_page_cache($child->ID);
        }
        $wp_rewrite->flush_rules(false);
    } else {
        clean_post_cache($postid);
    }
    wp_clear_scheduled_hook('publish_future_post', array($postid));
    do_action('deleted_post', $postid);
    return $post;
}
Exemple #5
0
 /**
  * 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);
 }
Exemple #6
0
/**
 * 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);
}
 /**
  * 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']);
         }
     }
 }
/**
	* 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 cp_add_new_listing($advals, $renew_id = false)
{
    global $wpdb, $cp_options;
    $new_tags = '';
    $ad_length = '';
    $attach_id = '';
    $the_attachment = '';
    // check to see if html is allowed
    if (!$cp_options->allow_html) {
        $post_content = appthemes_filter($advals['post_content']);
    } else {
        $post_content = wp_kses_post($advals['post_content']);
    }
    // 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($post_content);
    $new_ad['post_status'] = 'pending';
    // no longer setting final status until after images are set
    $new_ad['post_author'] = $advals['user_id'];
    $new_ad['post_type'] = APP_POST_TYPE;
    if ($renew_id) {
        $new_ad['ID'] = $renew_id;
        $new_ad['post_date'] = current_time('mysql');
        $new_ad['post_date_gmt'] = current_time('mysql', 1);
        $post_id = wp_update_post($new_ad);
    } else {
        // 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);
    // 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 = $cp_options->prun_period;
    }
    // set the ad listing expiration date and put into a session
    $ad_expire_date = appthemes_mysql_date(current_time('mysql'), $ad_length);
    $advals['cp_sys_expire_date'] = $ad_expire_date;
    $advals['cp_sys_ad_duration'] = $ad_length;
    // if renew ad - delete all old post meta and unmark ad as featured
    if ($renew_id) {
        unstick_post($renew_id);
        $custom_field_keys = get_post_custom_keys($renew_id);
        foreach ($custom_field_keys as $custom_key) {
            delete_post_meta($renew_id, $custom_key);
        }
    }
    // 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, wp_kses_post($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, wp_kses_post($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);
    }
    if (isset($advals['app_attach_id'])) {
        $attachments = $advals['app_attach_id'];
        $titles = isset($advals['app_attach_title']) ? $advals['app_attach_title'] : array();
        // associate the already uploaded images to the new ad and update titles
        $attach_id = appthemes_plupload_associate_images($post_id, $attachments, $titles, 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);
    }
    cp_action_add_new_listing($post_id);
    // kick back the post id in case we want to use it
    return $post_id;
}
 /**
  * Update a single post.
  *
  * @param WP_REST_Request $request Full details about the request.
  * @return WP_Error|WP_REST_Response
  */
 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', __('Post id is invalid.'), array('status' => 400));
     }
     $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((array) $post, true);
     if (is_wp_error($post_id)) {
         if (in_array($post_id->get_error_code(), array('db_update_error'))) {
             $post_id->add_data(array('status' => 500));
         } else {
             $post_id->add_data(array('status' => 400));
         }
         return $post_id;
     }
     $schema = $this->get_item_schema();
     if (!empty($schema['properties']['format']) && !empty($request['format'])) {
         set_post_format($post, $request['format']);
     }
     if (!empty($schema['properties']['featured_image']) && isset($request['featured_image'])) {
         $this->handle_featured_image($request['featured_image'], $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);
     }
     $this->update_additional_fields_for_object(get_post($post_id), $request);
     /**
      * @TODO: Enable rest_insert_post() action after.
      * Media Controller has been migrated to new style.
      *
      * do_action( 'rest_insert_post', $post, $request );
      */
     /* This action is documented in lib/endpoints/class-wp-rest-controller.php */
     do_action('rest_insert_post', $post, $request, false);
     return $this->get_item(array('id' => $post_id, 'context' => 'edit'));
 }
 public function save_post($post_id)
 {
     if (!$this->role_at_least($this->get_site_option('role_broadcast'))) {
         return;
     }
     $allowed_post_status = array('publish');
     if ($this->role_at_least($this->get_site_option('role_broadcast_as_draft'))) {
         $allowed_post_status[] = 'draft';
     }
     if ($this->role_at_least($this->get_site_option('role_broadcast_scheduled_posts'))) {
         $allowed_post_status[] = 'future';
     }
     $post = get_post($post_id, 'ARRAY_A');
     if (!in_array($post['post_status'], $allowed_post_status)) {
         return;
     }
     if (!isset($_POST['broadcast'])) {
         // Site admin is never forced to do anything.
         if (is_super_admin()) {
             return;
         }
         // Ignore this post. It's being force broadcast.
         if (isset($_POST['broadcast_force'])) {
             return;
         }
         if ($this->get_site_option('always_use_required_list') == true) {
             $_POST['broadcast_force'] = true;
         } else {
             return;
         }
     }
     $post_type = $_POST['post_type'];
     $post_type_object = get_post_type_object($post_type);
     $post_type_supports_thumbnails = post_type_supports($post_type, 'thumbnail');
     $post_type_supports_custom_fields = post_type_supports($post_type, 'custom-fields');
     $post_type_is_hierarchical = $post_type_object->hierarchical;
     // Create new post data from the original stuff.
     $newPost = $post;
     foreach (array('ID', 'guid', 'menu_order', 'comment_count', 'post_parent') as $key) {
         unset($newPost[$key]);
     }
     if (isset($_POST['broadcast']['groups']['666'])) {
         $blogs = array_keys($_POST['broadcast']['groups']['666']);
     } else {
         $blogs = array();
     }
     // Now to add and remove blogs.
     $blogs = array_flip($blogs);
     // Remove the blog we're currently working on. No point in broadcasting to ourselves.
     global $blog_id;
     unset($blogs[$blog_id]);
     $user_id = $this->user_id();
     // Convenience.
     // Remove blacklisted
     foreach ($blogs as $blogID => $ignore) {
         if (!$this->is_blog_user_writable($user_id, $blogID)) {
             unset($blogs[$blogID]);
         }
     }
     // Add required blogs.
     if ($this->get_site_option('always_use_required_list')) {
         $requiredBlogs = $this->get_required_blogs();
         foreach ($requiredBlogs as $requiredBlog => $ignore) {
             $blogs[$requiredBlog] = $requiredBlog;
         }
     }
     $blogs = array_keys($blogs);
     // Now to add and remove blogs: done
     // Do we actually need to to anything?
     if (count($blogs) < 1) {
         return;
     }
     $link = $this->role_at_least($this->get_site_option('role_link')) && isset($_POST['broadcast']['link']);
     if ($link) {
         // Prepare the broadcast data for linked children.
         $broadcast_data = $this->get_post_broadcast_data($blog_id, $post_id);
         // Does this post type have parent support, so that we can link to a parent?
         if ($post_type_is_hierarchical && $_POST['post_parent'] > 0) {
             $post_id_parent = $_POST['post_parent'];
             $parent_broadcast_data = $this->get_post_broadcast_data($blog_id, $post_id_parent);
         }
     }
     $taxonomies = $this->role_at_least($this->get_site_option('role_taxonomies')) && isset($_POST['broadcast']['taxonomies']);
     $taxonomies_create = $this->role_at_least($this->get_site_option('role_taxonomies_create')) && isset($_POST['broadcast']['taxonomies_create']);
     if ($taxonomies) {
         $source_blog_taxonomies = get_object_taxonomies(array('object_type' => $post_type), 'array');
         $source_post_taxonomies = array();
         foreach ($source_blog_taxonomies as $source_blog_taxonomy => $ignore) {
             $source_post_taxonomies[$source_blog_taxonomy] = get_the_terms($post_id, $source_blog_taxonomy);
             if ($source_post_taxonomies[$source_blog_taxonomy] === false) {
                 unset($source_post_taxonomies[$source_blog_taxonomy]);
             }
         }
     }
     require_once 'AttachmentData.php';
     $upload_dir = wp_upload_dir();
     // We need to find out where the files are on disk for this blog.
     $attachment_data = array();
     $attached_files =& get_children('post_parent=' . $post_id . '&post_type=attachment');
     $has_attached_files = count($attached_files) > 0;
     if ($has_attached_files) {
         foreach ($attached_files as $attached_file) {
             $attachment_data[$attached_file->ID] = AttachmentData::from_attachment_id($attached_file->ID, $upload_dir);
         }
     }
     $custom_fields = $this->role_at_least($this->get_site_option('role_custom_fields')) && isset($_POST['broadcast']['custom_fields']) && ($post_type_supports_custom_fields || $post_type_supports_thumbnails);
     if ($custom_fields) {
         $post_custom_fields = get_post_custom($post_id);
         $has_thumbnail = isset($post_custom_fields['_thumbnail_id']);
         if ($has_thumbnail) {
             $thumbnail_id = $post_custom_fields['_thumbnail_id'][0];
             unset($post_custom_fields['_thumbnail_id']);
             // There is a new thumbnail id for each blog.
             $attachment_data['thumbnail'] = AttachmentData::from_attachment_id($thumbnail_id, $upload_dir);
             // Now that we know what the attachment id the thumbnail has, we must remove it from the attached files to avoid duplicates.
             unset($attachment_data[$thumbnail_id]);
         }
         // Remove all the _internal custom fields.
         $post_custom_fields = $this->keep_valid_custom_fields($post_custom_fields);
     }
     // Sticky isn't a tag, cat or custom_field.
     $post_is_sticky = @($_POST['sticky'] == 'sticky');
     // And now save the user's last settings.
     $this->save_last_used_settings($user_id, $_POST['broadcast']);
     $this->broadcasting = $_POST['broadcast'];
     $to_broadcasted_blogs = array();
     // Array of blog names that we're broadcasting to.
     // To prevent recursion
     unset($_POST['broadcast']);
     $original_blog = $blog_id;
     foreach ($blogs as $blogID) {
         // Another safety check. Goes with the safety dance.
         if (!$this->is_blog_user_writable($user_id, $blogID)) {
             continue;
         }
         switch_to_blog($blogID);
         // Post parent
         if ($link && isset($parent_broadcast_data)) {
             if ($parent_broadcast_data->has_linked_child_on_this_blog()) {
                 $linked_parent = $parent_broadcast_data->get_linked_child_on_this_blog();
                 $newPost['post_parent'] = $linked_parent;
             }
         }
         // Insert new? Or update? Depends on whether the parent post was linked before or is newly linked?
         $need_to_insert_post = true;
         if ($link) {
             if ($broadcast_data->has_linked_child_on_this_blog()) {
                 $child_post_id = $broadcast_data->get_linked_child_on_this_blog();
                 // Does this child post still exist?
                 $child_post = get_post($child_post_id);
                 if ($child_post !== null) {
                     $temp_post_data = $newPost;
                     $temp_post_data['ID'] = $child_post_id;
                     $new_post_id = wp_update_post($temp_post_data);
                     $need_to_insert_post = false;
                 }
             }
         }
         if ($need_to_insert_post) {
             $new_post_id = wp_insert_post($newPost);
             if ($link) {
                 $broadcast_data->add_linked_child($blogID, $new_post_id);
             }
         }
         if ($taxonomies) {
             foreach ($source_post_taxonomies as $source_post_taxonomy => $source_post_terms) {
                 // If we're updating a linked post, remove all the taxonomies and start from the top.
                 if ($link) {
                     if ($broadcast_data->has_linked_child_on_this_blog()) {
                         wp_set_object_terms($new_post_id, array(), $source_post_taxonomy);
                     }
                 }
                 // Get a list of cats that the target blog has.
                 $target_blog_terms = $this->get_current_blog_taxonomy_terms($source_post_taxonomy);
                 // Go through the original post's terms and compare each slug with the slug of the target terms.
                 $taxonomies_to_add_to = array();
                 $have_created_taxonomies = false;
                 foreach ($source_post_terms as $source_post_term) {
                     $found = false;
                     $source_slug = $source_post_term->slug;
                     foreach ($target_blog_terms as $target_blog_term) {
                         if ($target_blog_term['slug'] == $source_slug) {
                             $found = true;
                             $taxonomies_to_add_to[$target_blog_term['term_id']] = intval($target_blog_term['term_id']);
                             break;
                         }
                     }
                     // Should we create the taxonomy if it doesn't exist?
                     if (!$found && $taxonomies_create) {
                         $new_taxonomy = wp_insert_term($source_post_term->name, $source_post_taxonomy, array('slug' => $source_post_term->slug, 'description' => $source_post_term->description));
                         $taxonomies_to_add_to[] = $source_post_term->slug;
                         $have_created_taxonomies = true;
                     }
                 }
                 if ($taxonomies_create) {
                     $this->sync_terms($source_post_taxonomy, $original_blog, $blogID);
                 }
                 if (count($taxonomies_to_add_to) > 0) {
                     wp_set_object_terms($new_post_id, $taxonomies_to_add_to, $source_post_taxonomy);
                 }
             }
         }
         /**
         	Remove the current attachments.
         */
         $attachments_to_remove =& get_children('post_parent=' . $new_post_id . '&post_type=attachment');
         foreach ($attachments_to_remove as $attachment_to_remove) {
             wp_delete_attachment($attachment_to_remove->ID);
         }
         foreach ($attachment_data as $key => $attached_file) {
             if ($key != 'thumbnail') {
                 $this->copy_attachment($attached_file, $new_post_id);
             }
         }
         if ($custom_fields) {
             // Remove all old custom fields.
             $old_custom_fields = get_post_custom($new_post_id);
             foreach ($old_custom_fields as $key => $value) {
                 // This post has a featured image! Remove it from disk!
                 if ($key == '_thumbnail_id') {
                     $thumbnail_post = $value[0];
                     wp_delete_post($thumbnail_post);
                 }
                 delete_post_meta($new_post_id, $key);
             }
             foreach ($post_custom_fields as $meta_key => $meta_value) {
                 if (is_array($meta_value)) {
                     foreach ($meta_value as $single_meta_value) {
                         $single_meta_value = maybe_unserialize($single_meta_value);
                         add_post_meta($new_post_id, $meta_key, $single_meta_value);
                     }
                 } else {
                     $meta_value = maybe_unserialize($meta_value);
                     add_post_meta($new_post_id, $meta_key, $meta_value);
                 }
             }
             // Attached files are custom fields... but special custom fields. Therefore they need special treatment. Like retards. Retarded files.
             if ($has_thumbnail) {
                 $new_attachment_id = $this->copy_attachment($attachment_data['thumbnail'], $new_post_id);
                 if ($new_attachment_id !== false) {
                     update_post_meta($new_post_id, '_thumbnail_id', $new_attachment_id);
                 }
             }
         }
         // Sticky behaviour
         $child_post_is_sticky = is_sticky($new_post_id);
         if ($post_is_sticky && !$child_post_is_sticky) {
             stick_post($new_post_id);
         }
         if (!$post_is_sticky && $child_post_is_sticky) {
             unstick_post($new_post_id);
         }
         if ($link) {
             $new_post_broadcast_data = $this->get_post_broadcast_data($blog_id, $new_post_id);
             $new_post_broadcast_data->set_linked_parent($original_blog, $post_id);
             $this->set_post_broadcast_data($blogID, $new_post_id, $new_post_broadcast_data);
         }
         $to_broadcasted_blogs[] = '<a href="' . get_permalink($new_post_id) . '">' . get_bloginfo('name') . '</a>';
         restore_current_blog();
     }
     // Finished broadcasting.
     $this->broadcasting = false;
     $post_url_and_name = '<a href="' . get_permalink($post_id) . '">' . $post['post_title'] . '</a>';
     do_action('threewp_activity_monitor_new_activity', array('activity_id' => '3broadcast_broadcasted', 'activity_strings' => array('' => '%user_display_name_with_link% has broadcasted ' . $post_url_and_name . ' to: ' . implode(', ', $to_broadcasted_blogs))));
     // Save the post broadcast data.
     if ($link) {
         $this->set_post_broadcast_data($blog_id, $post_id, $broadcast_data);
     }
 }
 function save_post_translation($translation_id, $translation)
 {
     global $wpdb, $sitepress_settings, $sitepress, $icl_adjust_id_url_filter_off;
     $icl_adjust_id_url_filter_off = true;
     $translation_info = $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 = $translation_info->language_code;
     $trid = $translation_info->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?
     $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);
     // 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($wpdb->prepare("\tSELECT trid\n\t\t\t\t\t\tFROM {$wpdb->prefix}icl_translations\n\t\t\t\t\t\tWHERE element_type= %s AND element_id = %d ", 'post_' . $original_post_details->post_type, $original_post_details->post_parent));
         if ($post_parent_trid) {
             $parent_id = $wpdb->get_var($wpdb->prepare("SELECT element_id\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t FROM {$wpdb->prefix}icl_translations\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t WHERE element_type = %s\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  AND trid = %d\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  AND language_code = %s ", 'post_' . $original_post_details->post_type, $post_parent_trid, $lang_code));
         }
     }
     // determine post id based on trid
     $post_id = $translation_info->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($wpdb->prepare("SELECT ID FROM {$wpdb->posts} WHERE ID = %d ", $post_id))) {
             $is_update = false;
             $q = "DELETE FROM {$wpdb->prefix}icl_translations WHERE element_type=%s AND element_id=%d";
             $q_prepared = $wpdb->prepare($q, array('post_' . $original_post_details->post_type, $post_id));
             $wpdb->query($q_prepared);
         } else {
             $is_update = true;
             $postarr['ID'] = $_POST['post_ID'] = $post_id;
         }
     } else {
         $is_update = false;
     }
     $postarr['post_title'] = $translation['title'];
     if ($sitepress_settings['translated_document_page_url'] == 'translate' && isset($translation['URL'])) {
         $postarr['post_name'] = $translation['URL'];
     }
     $postarr['post_content'] = $translation['body'];
     if (isset($translation['excerpt']) && $translation['excerpt'] != "") {
         $postarr['post_excerpt'] = $translation['excerpt'];
     }
     if (isset($translated_taxonomies) && is_array($translated_taxonomies)) {
         foreach ($translated_taxonomies as $taxonomy => $values) {
             $postarr['tax_input'][$taxonomy] = join(',', (array) $values);
         }
     }
     $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($wpdb->prepare("SELECT post_status\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t FROM {$wpdb->prefix}posts\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t WHERE ID = %d ", $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);
     // 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) {
             $sitepress->_sync_custom_field($translation['original_id'], $new_post_id, $cf);
         } 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('&#0A;', "\n", $field_translation);
                 // always decode html entities  eg decode &amp; 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);
     }
     // sync post format
     if ($sitepress_settings['sync_post_format']) {
         $_wp_post_format = get_post_format($translation['original_id']);
         set_post_format($new_post_id, $_wp_post_format);
     }
     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);
     TranslationManagement::set_page_url($new_post_id);
     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) {
         $lang_status = TranslationProxy_Translator::get_language_pairs();
         foreach ($lang_status as $languages_pair) {
             if ($languages_pair['from'] == $original_post_details->language_code && $languages_pair['to'] == $lang_code && isset($languages_pair['translators'][0]['id'])) {
                 $ts['translator_id'] = $languages_pair['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($translation_info->rid, $translation_info->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}");
         // 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 = %s AND tr.language_code = %s AND tr.element_id IS NOT NULL";
         $sql_prepared = $wpdb->prepare($sql, array('post_' . $original_post_details->post_type, $lang_code));
         $needs_fixing = $wpdb->get_results($sql_prepared);
         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);
     }
     WPML_Translation_Job_Terms::save_terms_from_job($job_id, $lang_code);
     do_action('icl_pro_translation_completed', $new_post_id);
     return true;
 }
 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
     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 ('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'];
     }
     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']);
     }
     $categories = null;
     $tags = null;
     if (!empty($input['categories'])) {
         if (is_array($input['categories'])) {
             $_categories = $input['categories'];
         } else {
             foreach (explode(',', $input['categories']) as $category) {
                 $_categories[] = $category;
             }
         }
         foreach ($_categories as $category) {
             if (!($category_info = term_exists($category, 'category'))) {
                 if (is_int($category)) {
                     continue;
                 }
                 $category_info = wp_insert_term($category, 'category');
             }
             if (!is_wp_error($category_info)) {
                 $categories[] = (int) $category_info['term_id'];
             }
         }
     }
     if (!empty($input['tags'])) {
         if (is_array($input['tags'])) {
             $tags = $input['tags'];
         } else {
             foreach (explode(',', $input['tags']) as $tag) {
                 $tags[] = $tag;
             }
         }
         $tags_string = implode(',', $tags);
     }
     unset($input['tags'], $input['categories']);
     $insert = array();
     if (!empty($input['slug'])) {
         $insert['post_name'] = $input['slug'];
         unset($input['slug']);
     }
     if (true === $input['comments_open']) {
         $insert['comment_status'] = 'open';
     } else {
         if (false === $input['comments_open']) {
             $insert['comment_status'] = 'closed';
         }
     }
     if (true === $input['pings_open']) {
         $insert['ping_status'] = 'open';
     } else {
         if (false === $input['pings_open']) {
             $insert['ping_status'] = 'closed';
         }
     }
     unset($input['comments_open'], $input['pings_open']);
     $publicize = $input['publicize'];
     $publicize_custom_message = $input['publicize_message'];
     unset($input['publicize'], $input['publicize_message']);
     if (isset($input['featured_image'])) {
         $featured_image = trim($input['featured_image']);
         $delete_featured_image = empty($featured_image);
         $featured_image = $input['featured_image'];
         unset($input['featured_image']);
     }
     $metadata = $input['metadata'];
     unset($input['metadata']);
     $likes = $input['likes_enabled'];
     $sharing = $input['sharing_enabled'];
     $gplus = $input['gplusauthorship_enabled'];
     unset($input['likes_enabled']);
     unset($input['sharing_enabled']);
     unset($input['gplusauthorship_enabled']);
     $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($tags)) {
         $insert["tax_input"]["post_tag"] = $tags;
     }
     if (!empty($categories)) {
         $insert["tax_input"]["category"] = $categories;
     }
     $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 (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;
         $post_id = wp_update_post((object) $insert);
     }
     if (!$post_id || is_wp_error($post_id)) {
         return $post_id;
     }
     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
     $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 Google+ authorship status for the post
     if ($new) {
         $gplus_enabled = isset($gplus) ? (bool) $gplus : true;
         if (false === $gplus_enabled) {
             update_post_meta($post_id, 'gplus_authorship_disabled', 1);
         }
     } else {
         if (isset($gplus) && true === $gplus) {
             delete_post_meta($post_id, 'gplus_authorship_disabled');
         } else {
             if (isset($gplus) && false == $gplus) {
                 update_post_meta($post_id, 'gplus_authorship_disabled', 1);
             }
         }
     }
     // 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 || 25952 == $this->api->token_details['client_id']) {
         // No publicize at all, skipp all by full service
         foreach ($GLOBALS['publicize_ui']->publicize->get_services('all') as $name => $service) {
             update_post_meta($post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $name, 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
                  */
                 if (!in_array($name, $publicize) && !array_key_exists($name, $publicize)) {
                     // Skip the whole service
                     update_post_meta($post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $name, 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]));
                         // Get the user's connections and flag the ones we can't match with the requested list to be skipped.
                         $service_connections = $GLOBALS['publicize_ui']->publicize->get_connections($name);
                         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);
                             }
                         }
                     }
                 }
             }
         }
     }
     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 (!empty($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);
             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 ('revision' === $input['type']) {
         $return['preview_nonce'] = wp_create_nonce('post_preview_' . $input['parent']);
     }
     do_action('wpcom_json_api_objects', 'posts');
     return $return;
 }
 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_id = $wpdb->get_var($wpdb->prepare("SELECT count(1) FROM {$wpdb->prefix}icl_translate_job WHERE job_id=%d", $data['job_id']));
     if ($job_id == 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);
             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;
                     case 'tags':
                         $tags = self::decode_field_data($field->field_data_translated, $field->field_format);
                         $original_tags = self::decode_field_data($field->field_data, $field->field_format);
                         // create tags that don't exist
                         foreach ($tags as $k => $t) {
                             $thetag = $sitepress->get_term_by_name_and_lang($t, 'post_tag', $job->language_code);
                             $tags[$k] = $t;
                             // Save $t as we may have added @.lang to it
                             if (empty($thetag)) {
                                 $the_original_tag = $sitepress->get_term_by_name_and_lang($original_tags[$k], 'post_tag', $job->source_language_code);
                                 $tmp = self::icl_insert_term($t, 'post_tag', array(), $job->language_code);
                                 if (!is_wp_error($tmp) && isset($tmp['term_taxonomy_id'])) {
                                     $sitepress->set_term_translation($the_original_tag, $tmp['term_taxonomy_id'], 'post_tag', $job->language_code, $job->source_language_code);
                                 }
                             }
                         }
                         $postarr['tags_input'] = join(',', $tags);
                         $postarr['tax_input']['post_tag'] = $tags;
                         break;
                     case 'categories':
                         $cats = self::decode_field_data($field->field_data_translated, $field->field_format);
                         $original_cats = self::decode_field_data($field->field_data, $field->field_format);
                         $missing_parents = array();
                         $cat_ids = array();
                         foreach ($cats as $k => $c) {
                             $parent_missing = false;
                             $thecat = $sitepress->get_term_by_name_and_lang($c, 'category', $job->language_code);
                             $cat_id = 0;
                             if (empty($thecat)) {
                                 $the_original_cat = $sitepress->get_term_by_name_and_lang($original_cats[$k], 'category', $job->source_language_code);
                                 if ($the_original_cat) {
                                     $original_parent_id = $wpdb->get_var("SELECT parent FROM {$wpdb->term_taxonomy} WHERE term_taxonomy_id=" . $the_original_cat->term_taxonomy_id);
                                 } else {
                                     $original_parent_id = false;
                                 }
                                 if ($original_parent_id) {
                                     $translated_parent_id = icl_object_id($original_parent_id, 'category', false, $job->language_code);
                                     if (!$translated_parent_id) {
                                         // The parent is missing. Possibly because we haven't created a translation of it yet
                                         $parent_missing = true;
                                     }
                                 } else {
                                     $translated_parent_id = 0;
                                 }
                                 $tmp = self::icl_insert_term($c, 'category', array('parent' => $translated_parent_id), $job->language_code);
                                 if (!is_wp_error($tmp) && isset($tmp['term_taxonomy_id'])) {
                                     $sitepress->set_term_translation($the_original_cat, $tmp['term_taxonomy_id'], 'category', $job->language_code, $job->source_language_code);
                                     $cat_id = $tmp['term_id'];
                                 }
                             } else {
                                 $cat_id = $thecat->term_id;
                             }
                             if ($cat_id) {
                                 $cat_ids[] = $cat_id;
                             }
                             if ($parent_missing && isset($original_parent_id)) {
                                 $missing_parents[$cat_id] = $original_parent_id;
                             }
                         }
                         // Double check missing parents as they might be available now.
                         foreach ($missing_parents as $cat_id => $original_parent_id) {
                             $translated_parent_id = icl_object_id($original_parent_id, 'category', false, $job->language_code);
                             $cat_trid = $sitepress->get_element_trid($cat_id, 'tax_category');
                             $buf_post = isset($_POST) ? $_POST : array();
                             $_POST['icl_trid'] = $cat_trid;
                             $_POST['icl_translation_of'] = $wpdb->get_var($wpdb->prepare("SELECT element_id FROM {$wpdb->prefix}icl_translations WHERE element_type='tax_category' AND trid=%d AND source_language_code IS NULL", $cat_trid));
                             $_POST['icl_tax_category_language'] = $job->language_code;
                             wp_update_term($cat_id, 'category', array('parent' => $translated_parent_id));
                             $_POST = $buf_post;
                             $cat_tax_id = $wpdb->get_var($wpdb->prepare("SELECT term_taxonomy_id FROM {$wpdb->term_taxonomy} WHERE term_id=%d AND taxonomy='category'", $cat_id));
                             $wpdb->update($wpdb->prefix . 'icl_translations', array('language_code' => $job->language_code, 'trid' => $cat_trid, 'source_language_code' => $job->source_language_code), array('element_type' => 'tax_category', 'element_id' => $cat_tax_id));
                             $sitepress->update_terms_relationship_cache(array($translated_parent_id, $cat_id), 'category');
                         }
                         $postarr['post_category'] = $cat_ids;
                         if ($cat_ids) {
                             $sitepress->update_terms_relationship_cache($missing_parents, 'category');
                             $sitepress->update_terms_relationship_cache($cat_ids, 'category');
                         }
                         break;
                     default:
                         if (in_array($field->field_type, $sitepress->get_translatable_taxonomies(false, $job->original_post_type))) {
                             $taxs = self::decode_field_data($field->field_data_translated, $field->field_format);
                             $missing_parents = array();
                             $original_taxs = self::decode_field_data($field->field_data, $field->field_format);
                             $taxonomy = $field->field_type;
                             $taxonomy_obj = get_taxonomy($taxonomy);
                             // array = hierarchical, string = non-hierarchical.
                             if ($taxonomy_obj->hierarchical) {
                                 $missing_parents = array();
                             }
                             $alltaxs = $tax_ids = array();
                             foreach ($taxs as $k => $c) {
                                 $the_original_tax_parent = false;
                                 $parent_missing = false;
                                 if ($taxonomy_obj->hierarchical) {
                                     $parent_missing = false;
                                 }
                                 $thetax = $sitepress->get_term_by_name_and_lang($c, $taxonomy, $job->language_code);
                                 $taxs[$k] = $c;
                                 // Save $c as we may have added @.lang to it
                                 if (empty($thetax)) {
                                     $the_original_tax = $sitepress->get_term_by_name_and_lang($original_taxs[$k], $taxonomy, $job->source_language_code);
                                     if ($taxonomy_obj->hierarchical && $the_original_tax) {
                                         $the_original_tax_parent = $wpdb->get_var("SELECT parent FROM {$wpdb->term_taxonomy} WHERE term_taxonomy_id=" . $the_original_tax->term_taxonomy_id);
                                     }
                                     if ($the_original_tax_parent) {
                                         $translated_parent_id = icl_object_id($the_original_tax_parent, $taxonomy, false, $job->language_code);
                                         if (!$translated_parent_id) {
                                             // The parent is missing. Possibly because we haven't created a translation of it yet
                                             $parent_missing = true;
                                         }
                                     } else {
                                         $translated_parent_id = 0;
                                     }
                                     $tmp = self::icl_insert_term($c, $taxonomy, array('parent' => $translated_parent_id), $job->language_code);
                                     if (isset($tmp['term_taxonomy_id'])) {
                                         $sitepress->set_term_translation($the_original_tax, $tmp['term_taxonomy_id'], $taxonomy, $job->language_code, $job->source_language_code);
                                     }
                                     $tax_id = $tmp['term_id'];
                                 } else {
                                     $tax_id = $thetax->term_id;
                                 }
                                 if ($taxonomy_obj->hierarchical && $parent_missing) {
                                     $missing_parents[$tax_id] = $the_original_tax_parent;
                                 }
                                 $tax_ids[] = $tax_id;
                                 $alltaxs[] = $c;
                             }
                             // Double check missing parents as they might be available now.
                             foreach ($missing_parents as $tax_id => $the_original_tax_parent) {
                                 $translated_parent_id = icl_object_id($the_original_tax_parent, $taxonomy, false, $job->language_code);
                                 $tax_trid = $sitepress->get_element_trid($tax_id, 'tax_' . $taxonomy);
                                 $buf_post = isset($_POST) ? $_POST : array();
                                 $_POST['icl_trid'] = $tax_trid;
                                 $_POST['icl_translation_of'] = $wpdb->get_var($wpdb->prepare("SELECT element_id FROM {$wpdb->prefix}icl_translations WHERE element_type=%s AND trid=%d AND source_language_code IS NULL", 'tax_' . $taxonomy, $tax_trid));
                                 $_POST['icl_tax_' . $taxonomy . '_language'] = $job->language_code;
                                 wp_update_term($tax_id, $taxonomy, array('parent' => $translated_parent_id));
                                 $_POST = $buf_post;
                                 $tax_tax_id = $wpdb->get_var($wpdb->prepare("SELECT term_taxonomy_id FROM {$wpdb->term_taxonomy} WHERE term_id=%d AND taxonomy=%s", $tax_id, $taxonomy));
                                 $wpdb->update($wpdb->prefix . 'icl_translations', array('language_code' => $job->language_code, 'trid' => $tax_trid, 'source_language_code' => $job->source_language_code), array('element_type' => 'tax_' . $taxonomy, 'element_id' => $tax_tax_id));
                                 $sitepress->update_terms_relationship_cache(array($translated_parent_id, $tax_id), $taxonomy);
                             }
                             if ($taxonomy_obj->hierarchical) {
                                 $postarr['tax_input'][$taxonomy] = $tax_ids;
                             } else {
                                 $postarr['tax_input'][$taxonomy] = $taxs;
                             }
                         }
                 }
             }
             $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                        WHERE 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                            WHERE 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
             // set taxonomies for users with limited caps
             if (!current_user_can('manage-categories') && !empty($postarr['tax_input'])) {
                 foreach ($postarr['tax_input'] as $taxonomy => $terms) {
                     wp_set_post_terms($new_post_id, $terms, $taxonomy, FALSE);
                     // true to append to existing tags | false to replace existing tags
                 }
             }
             do_action('icl_pro_translation_saved', $new_post_id, $data['fields']);
             // Allow identical slugs
             $post_name = sanitize_title($postarr['post_title']);
             $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) {
                 $incr = 1;
                 do {
                     $exists = $wpdb->get_var($wpdb->prepare("\n                            SELECT p.ID FROM {$wpdb->posts} p\n                                JOIN {$wpdb->prefix}icl_translations t ON t.element_id = p.ID AND t.element_type=%s\n                            WHERE p.ID <> %d AND t.language_code = %s AND p.post_name=%s\n                        ", 'post_' . $postarr['post_type'], $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('&#0A;', "\n", $field_translation);
                                     // always decode html entities  eg decode &amp; 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'));
     }
     do_action('icl_pro_translation_completed', $new_post_id);
 }
 function save_translation($data)
 {
     global $wpdb, $sitepress, $ICL_Pro_Translation;
     $new_post_id = false;
     $is_incomplete = false;
     $job = null;
     $original_post = null;
     $element_type_prefix = null;
     if (isset($data['job_id'])) {
         $job = $this->get_translation_job($data['job_id'], true);
         $element_type_prefix = $this->get_element_type_prefix_from_job($job);
         $original_post = $this->get_post($job->original_doc_id, $element_type_prefix);
     }
     $data_to_validate = array('original_post' => $original_post, 'type_prefix' => $element_type_prefix, 'data' => $data, 'is_external' => $this->is_external_type($element_type_prefix));
     $is_valid = true;
     $validation_default_results = array('is_valid' => $is_valid, 'messages' => array());
     if (!$job || !$original_post || !$element_type_prefix) {
         $is_valid = false;
         if (!$job) {
             $validation_default_results['messages'][] = _('Job ID is missing', 'sitepress');
         }
         if (!$original_post) {
             $validation_default_results['messages'][] = _('The original post cannot be retrieved', 'sitepress');
         }
         if (!$element_type_prefix) {
             $validation_default_results['messages'][] = _('The type of the post cannot be retrieved', 'sitepress');
         }
     }
     $validation_default_results['is_valid'] = $is_valid;
     $validation_results = apply_filters('wpml_translation_validation_data', $validation_default_results, $data_to_validate);
     $validation_results = array_merge($validation_results, $validation_default_results);
     if (!$is_valid && $validation_results['is_valid']) {
         $validation_results['is_valid'] = $is_valid;
     }
     if (isset($validation_results['is_valid']) && !$validation_results['is_valid']) {
         if (isset($validation_results['messages'])) {
             $messages = (array) $validation_results['messages'];
             if ($messages) {
                 foreach ($messages as $message) {
                     $this->messages[] = array('type' => 'error', 'text' => $message);
                 }
             } else {
                 $this->messages[] = array('type' => 'error', 'text' => __('Submitted data is not valid.', 'sitepress'));
             }
         }
         do_action('wpml_translation_validation_failed', $validation_results, $data_to_validate);
     } else {
         foreach ($data['fields'] as $fieldname => $field) {
             if (substr($fieldname, 0, 6) === 'field-') {
                 $field = apply_filters('wpml_tm_save_translation_cf', $field, $fieldname, $data);
             }
             $this->_save_translation_field($field['tid'], $field);
             if (!isset($field['finished']) || !$field['finished']) {
                 $is_incomplete = true;
             }
         }
         $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));
         if (($is_incomplete === true || empty($data['complete'])) && empty($data['resign'])) {
             $status_update = array('translation_id' => $translation_id, 'status' => ICL_TM_IN_PROGRESS);
             $this->update_translation_status($status_update);
             $wpdb->update($wpdb->prefix . 'icl_translate_job', array('translated' => 0), array('job_id' => $data['job_id']));
         }
         //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) {
             if (defined('XMLRPC_REQUEST') || defined('DOING_AJAX')) {
                 return;
             } else {
                 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']));
             $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);
             if ($this->is_external_type($element_type_prefix)) {
                 // Translations are saved in the string table for 'external' types
                 $element_type_prefix = apply_filters('wpml_get_package_type_prefix', $element_type_prefix, $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($element_type_prefix, $field->field_type);
                             if (!$string_id) {
                                 icl_register_string($element_type_prefix, $field->field_type, self::decode_field_data($field->field_data, $field->field_format));
                                 $string_id = icl_st_is_registered_string($element_type_prefix, $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_TM_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;
                     }
                 }
                 $postarr['post_author'] = $original_post->post_author;
                 $postarr['post_type'] = $original_post->post_type;
                 if ($sitepress->get_setting('sync_comment_status')) {
                     $postarr['comment_status'] = $original_post->comment_status;
                 }
                 if ($sitepress->get_setting('sync_ping_status')) {
                     $postarr['ping_status'] = $original_post->ping_status;
                 }
                 if ($sitepress->get_setting('sync_page_ordering')) {
                     $postarr['menu_order'] = $original_post->menu_order;
                 }
                 if ($sitepress->get_setting('sync_private_flag') && $original_post->post_status == 'private') {
                     $postarr['post_status'] = 'private';
                 }
                 if ($sitepress->get_setting('sync_post_date')) {
                     $postarr['post_date'] = $original_post->post_date;
                 }
                 //set as draft or the same status as original post
                 $postarr['post_status'] = !$sitepress->get_setting('translated_document_status') ? 'draft' : $original_post->post_status;
                 if ($original_post->post_parent) {
                     $post_parent_trid = $wpdb->get_var($wpdb->prepare("\tSELECT trid\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tFROM {$wpdb->prefix}icl_translations\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE element_type LIKE 'post%%'\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tAND element_id=%d", $original_post->post_parent));
                     if ($post_parent_trid) {
                         $parent_id = $wpdb->get_var($wpdb->prepare("\tSELECT element_id\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tFROM {$wpdb->prefix}icl_translations\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE element_type LIKE 'post%%' AND trid=%d AND language_code=%s", $post_parent_trid, $job->language_code));
                     }
                 }
                 if (isset($parent_id) && $sitepress->get_setting('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);
                 // it's an update and user do not want to translate urls so do not change the url
                 if (isset($element_id) && $sitepress->get_setting('translated_document_page_url') !== 'translate') {
                     $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
                 // set taxonomies for users with limited caps
                 if (!current_user_can('manage-categories') && !empty($postarr['tax_input'])) {
                     foreach ($postarr['tax_input'] as $taxonomy => $terms) {
                         wp_set_post_terms($new_post_id, $terms, $taxonomy, false);
                         // true to append to existing tags | false to replace existing tags
                     }
                 }
                 do_action('icl_pro_translation_saved', $new_post_id, $data['fields']);
                 if ($ICL_Pro_Translation) {
                     /** @var WPML_Pro_Translation $ICL_Pro_Translation */
                     $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;
                     }
                 }
                 if (isset($fields_data_translated)) {
                     $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?
                 $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->get_setting('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->get_setting('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->get_setting('sync_post_format')) {
                     $_wp_post_format = get_post_format($original_post->ID);
                     set_post_format($new_post_id, $_wp_post_format);
                 }
                 $package_helper = new WPML_Element_Translation_Package();
                 $package_helper->save_job_custom_fields($job, $new_post_id, (array) $this->settings['custom_fields_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->delete($wpdb->prefix . 'icl_translations', array('element_id' => $new_post_id, 'element_type' => 'post_' . $postarr['post_type']));
                     $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>.';
                 }
             }
             if (isset($user_message)) {
                 $this->add_message(array('type' => 'updated', 'text' => $user_message));
             }
             if ($this->settings['notification']['completed'] != ICL_TM_NOTIFICATION_NONE && $data['job_id']) {
                 do_action('wpml_tm_complete_job_notification', $data['job_id'], !is_null($element_id));
             }
             self::set_page_url($new_post_id);
             if (isset($job) && isset($job->language_code) && isset($job->source_language_code)) {
                 WPML_Translation_Job_Terms::save_terms_from_job($data['job_id'], $job->language_code);
                 $term_helper = wpml_get_term_translation_util();
                 $term_helper->sync_terms($original_post->ID, $job->language_code);
             }
             // Set the posts mime type correctly.
             if (isset($original_post) && isset($original_post->ID) && $original_post->post_type == 'attachment') {
                 $attached_file = get_post_meta($original_post->ID, '_wp_attached_file', false);
                 update_post_meta($new_post_id, '_wp_attached_file', array_pop($attached_file));
                 $mime_type = get_post_mime_type($original_post->ID);
                 if ($mime_type) {
                     $wpdb->update($wpdb->posts, array('post_mime_type' => $mime_type), array('ID' => $new_post_id));
                 }
             }
             do_action('icl_pro_translation_completed', $new_post_id);
             if (defined('XMLRPC_REQUEST') || defined('DOING_AJAX') || isset($_POST['xliff_upload'])) {
                 return;
             } else {
                 $action_type = is_null($element_id) ? 'added' : 'updated';
                 $element_id = is_null($element_id) ? $new_post_id : $element_id;
                 wp_redirect(admin_url(sprintf('admin.php?page=%s&%s=%d&element_type=%s', WPML_TM_FOLDER . '/menu/translations-queue.php', $action_type, $element_id, $element_type_prefix)));
                 exit;
             }
         } else {
             $this->messages[] = array('type' => 'updated', 'text' => __('Translation (incomplete) saved.', 'sitepress'));
         }
     }
 }
/**
 * 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 . "');");
    }
}
 /**
  * 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;
 }
Exemple #18
0
/**
 * Removes a post, attachment, or page.
 *
 * When the post and page goes, everything that is tied to it is deleted also.
 * This includes comments, post meta fields, and terms associated with the post.
 *
 * @since 1.0.0
 * @uses do_action() Calls 'deleted_post' hook on post ID.
 *
 * @param int $postid Post ID.
 * @return mixed
 */
function wp_delete_post($postid = 0)
{
    global $wpdb, $wp_rewrite;
    if (!($post = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$wpdb->posts} WHERE ID = %d", $postid)))) {
        return $post;
    }
    if ('attachment' == $post->post_type) {
        return wp_delete_attachment($postid);
    }
    do_action('delete_post', $postid);
    /** @todo delete for pluggable post taxonomies too */
    wp_delete_object_term_relationships($postid, array('category', 'post_tag'));
    $parent_data = array('post_parent' => $post->post_parent);
    $parent_where = array('post_parent' => $postid);
    if ('page' == $post->post_type) {
        // if the page is defined in option page_on_front or post_for_posts,
        // adjust the corresponding options
        if (get_option('page_on_front') == $postid) {
            update_option('show_on_front', 'posts');
            delete_option('page_on_front');
        }
        if (get_option('page_for_posts') == $postid) {
            delete_option('page_for_posts');
        }
        // Point children of this page to its parent, also clean the cache of affected children
        $children_query = $wpdb->prepare("SELECT * FROM {$wpdb->posts} WHERE post_parent = %d AND post_type='page'", $postid);
        $children = $wpdb->get_results($children_query);
        $wpdb->update($wpdb->posts, $parent_data, $parent_where + array('post_type' => 'page'));
    } else {
        unstick_post($postid);
    }
    // Do raw query.  wp_get_post_revisions() is filtered
    $revision_ids = $wpdb->get_col($wpdb->prepare("SELECT ID FROM {$wpdb->posts} WHERE post_parent = %d AND post_type = 'revision'", $postid));
    // Use wp_delete_post (via wp_delete_post_revision) again.  Ensures any meta/misplaced data gets cleaned up.
    foreach ($revision_ids as $revision_id) {
        wp_delete_post_revision($revision_id);
    }
    // Point all attachments to this post up one level
    $wpdb->update($wpdb->posts, $parent_data, $parent_where + array('post_type' => 'attachment'));
    $wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->posts} WHERE ID = %d", $postid));
    $wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->comments} WHERE comment_post_ID = %d", $postid));
    $wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->postmeta} WHERE post_id = %d", $postid));
    if ('page' == $post->post_type) {
        clean_page_cache($postid);
        foreach ((array) $children as $child) {
            clean_page_cache($child->ID);
        }
        $wp_rewrite->flush_rules();
    } else {
        clean_post_cache($postid);
    }
    do_action('deleted_post', $postid);
    return $post;
}
 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;
 }
 /**
  * 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;
 }
Exemple #21
0
/**
 * {@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);
}
 /**
  * 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);
 }
 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;
 }
Exemple #24
0
 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));
             }
         }
     }
 }
Exemple #25
0
/**
 * Reset the page_on_front, show_on_front, and page_for_post settings when
 * a linked page is deleted or trashed.
 *
 * Also ensures the post is no longer sticky.
 *
 * @since 3.7.0
 * @access private
 *
 * @param int $post_id Post ID.
 */
function _reset_front_page_settings_for_post($post_id)
{
    $post = get_post($post_id);
    if ('page' == $post->post_type) {
        /*
         * If the page is defined in option page_on_front or post_for_posts,
         * adjust the corresponding options.
         */
        if (get_option('page_on_front') == $post->ID) {
            update_option('show_on_front', 'posts');
            update_option('page_on_front', 0);
        }
        if (get_option('page_for_posts') == $post->ID) {
            delete_option('page_for_posts', 0);
        }
    }
    unstick_post($post->ID);
}
Exemple #26
0
 /**
  * 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;
 }
 /**
  * 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;
 }
 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('&#0A;', "\n", $field_translation);
                                     // always decode html entities  eg decode &amp; 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 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('&#0A;', "\n", $field_translation);
                 // always decode html entities  eg decode &amp; 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;
 }
Exemple #30
0
/**
 * 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);
}