예제 #1
0
 function test_update_metadata_by_mid()
 {
     // Setup
     $meta = get_metadata_by_mid('user', $this->meta_id);
     // Update the meta value
     $this->assertTrue(update_metadata_by_mid('user', $this->meta_id, 'meta_new_value'));
     $meta = get_metadata_by_mid('user', $this->meta_id);
     $this->assertEquals('meta_new_value', $meta->meta_value);
     // Update the meta value
     $this->assertTrue(update_metadata_by_mid('user', $this->meta_id, 'meta_new_value', 'meta_new_key'));
     $meta = get_metadata_by_mid('user', $this->meta_id);
     $this->assertEquals('meta_new_key', $meta->meta_key);
     // Update the key and value
     $this->assertTrue(update_metadata_by_mid('user', $this->meta_id, 'meta_value', 'meta_key'));
     $meta = get_metadata_by_mid('user', $this->meta_id);
     $this->assertEquals('meta_key', $meta->meta_key);
     $this->assertEquals('meta_value', $meta->meta_value);
     // Update the value that has to be serialized
     $this->assertTrue(update_metadata_by_mid('user', $this->meta_id, array('first', 'second')));
     $meta = get_metadata_by_mid('user', $this->meta_id);
     $this->assertEquals(array('first', 'second'), $meta->meta_value);
     // Let's try some invalid meta data
     $this->assertFalse(update_metadata_by_mid('user', 0, 'meta_value'));
     $this->assertFalse(update_metadata_by_mid('user', $this->meta_id, 'meta_value', array('invalid', 'key')));
     // Let's see if caches get cleared after updates.
     $meta = get_metadata_by_mid('user', $this->meta_id);
     $first = get_user_meta($meta->user_id, $meta->meta_key);
     $this->assertTrue(update_metadata_by_mid('user', $this->meta_id, 'other_meta_value'));
     $second = get_user_meta($meta->user_id, $meta->meta_key);
     $this->assertFalse($first === $second);
 }
예제 #2
0
 function write_post($path, $blog_id, $post_id)
 {
     $new = $this->api->ends_with($path, '/new');
     $args = $this->query_args();
     if ($new) {
         $input = $this->input(true);
         if (!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 ('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);
         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 ('publish' === $input['status'] && 'publish' !== $post->post_status && !current_user_can('publish_post', $post->ID)) {
             $input['status'] = 'pending';
         }
         $post_type = get_post_type_object($post->post_type);
     }
     if (!is_post_type_hierarchical($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']);
     $metadata = $input['metadata'];
     unset($input['metadata']);
     foreach ($input as $key => $value) {
         $insert["post_{$key}"] = $value;
     }
     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;
     if ($new) {
         if (false === strpos($input['content'], '[gallery') && $has_media) {
             switch ($has_media) {
                 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);
         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.']);
         }
     } else {
         $insert['ID'] = $post->ID;
         $post_id = wp_update_post((object) $insert);
     }
     if (!$post_id || is_wp_error($post_id)) {
         return $post_id;
     }
     if ($publicize === false) {
         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) {
                 if (!in_array($name, $publicize)) {
                     update_post_meta($post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $name, 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($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)) {
                         add_post_meta($post_id, $meta->key, $meta->value);
                     }
                     break;
                 case 'update':
                     if (empty($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)) {
                         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)) {
                         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)) {
                         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;
     }
     do_action('wpcom_json_api_objects', 'posts');
     return $return;
 }
 /**
  * Add meta to an object.
  *
  * @param WP_REST_Request $request
  * @return WP_REST_Response|WP_Error
  */
 public function update_item($request)
 {
     $parent_id = (int) $request['parent_id'];
     $mid = (int) $request['id'];
     $parent_column = $this->get_parent_column();
     $current = get_metadata_by_mid($this->parent_type, $mid);
     if (empty($current)) {
         return new WP_Error('rest_meta_invalid_id', __('Invalid meta id.'), array('status' => 404));
     }
     if (absint($current->{$parent_column}) !== $parent_id) {
         return new WP_Error('rest_meta_' . $this->parent_type . '_mismatch', __('Meta does not belong to this object'), array('status' => 400));
     }
     if (!isset($request['key']) && !isset($request['value'])) {
         return new WP_Error('rest_meta_data_invalid', __('Invalid meta parameters.'), array('status' => 400));
     }
     if (isset($request['key'])) {
         $key = $request['key'];
     } else {
         $key = $current->meta_key;
     }
     if (isset($request['value'])) {
         $value = $request['value'];
     } else {
         $value = $current->meta_value;
     }
     if (!$key) {
         return new WP_Error('rest_meta_invalid_key', __('Invalid meta key.'), array('status' => 400));
     }
     // for now let's not allow updating of arrays, objects or serialized values.
     if (!$this->is_valid_meta_data($current->meta_value)) {
         $code = $this->parent_type === 'post' ? 'rest_post_invalid_action' : 'rest_meta_invalid_action';
         return new WP_Error($code, __('Invalid existing meta data for action.'), array('status' => 400));
     }
     if (!$this->is_valid_meta_data($value)) {
         $code = $this->parent_type === 'post' ? 'rest_post_invalid_action' : 'rest_meta_invalid_action';
         return new WP_Error($code, __('Invalid provided meta data for action.'), array('status' => 400));
     }
     if (is_protected_meta($current->meta_key)) {
         return new WP_Error('rest_meta_protected', sprintf(__('%s is marked as a protected field.'), $current->meta_key), array('status' => 403));
     }
     if (is_protected_meta($key)) {
         return new WP_Error('rest_meta_protected', sprintf(__('%s is marked as a protected field.'), $key), array('status' => 403));
     }
     // update_metadata_by_mid will return false if these are equal, so check
     // first and pass through
     if ((string) $value === $current->meta_value && (string) $key === $current->meta_key) {
         return $this->get_item($request);
     }
     if (!update_metadata_by_mid($this->parent_type, $mid, $value, $key)) {
         return new WP_Error('rest_meta_could_not_update', __('Could not update meta.'), array('status' => 500));
     }
     $request = new WP_REST_Request('GET');
     $request->set_query_params(array('context' => 'edit', 'parent_id' => $parent_id, 'id' => $mid));
     $response = $this->get_item($request);
     /**
      * Fires after meta is added to an object or updated via the REST API.
      *
      * @param array           $value    The inserted meta data.
      * @param WP_REST_Request $request  The request sent to the API.
      * @param bool            $creating True when adding meta, false when updating.
      */
     do_action('rest_insert_meta', $value, $request, false);
     return rest_ensure_response($response);
 }
예제 #4
0
         $value = stripslashes($_POST['meta'][$mid]['value']);
         if ('' == trim($key)) {
             die(__('Please provide a custom field name.'));
         }
         if ('' == trim($value)) {
             die(__('Please provide a custom field value.'));
         }
         if (!($meta = get_metadata_by_mid('post', $mid))) {
             die('0');
         }
         // if meta doesn't exist
         if (is_protected_meta($meta->meta_key, 'post') || is_protected_meta($key, 'post') || !current_user_can('edit_post_meta', $meta->post_id, $meta->meta_key) || !current_user_can('edit_post_meta', $meta->post_id, $key)) {
             die('-1');
         }
         if ($meta->meta_value != $value || $meta->meta_key != $key) {
             if (!($u = update_metadata_by_mid('post', $mid, $value, $key))) {
                 die('0');
             }
             // We know meta exists; we also know it's unchanged (or DB error, in which case there are bigger problems).
         }
         $x = new WP_Ajax_Response(array('what' => 'meta', 'id' => $mid, 'old_id' => $mid, 'data' => _list_meta_row(array('meta_key' => $key, 'meta_value' => $value, 'meta_id' => $mid), $c), 'position' => 0, 'supplemental' => array('postid' => $meta->post_id)));
     }
     $x->send();
     break;
 case 'add-user':
     check_ajax_referer($action);
     if (!current_user_can('create_users')) {
         die('-1');
     }
     if (!($user_id = add_user())) {
         die('0');
예제 #5
0
파일: drop-it.php 프로젝트: foo123/drop-it
 /**
  * Update a drop
  *
  * @todo delegate to Drop classes
  * @param [type]  $payload [description]
  * @return [type]          [description]
  */
 function update_drop($payload)
 {
     $drop = Drop_It_Drop::payload($payload);
     update_metadata_by_mid('post', $payload->drop_id, $drop, $meta_key = false);
 }
예제 #6
0
/**
 * Ajax handler for adding meta.
 *
 * @since 3.1.0
 */
function wp_ajax_add_meta()
{
    check_ajax_referer('add-meta', '_ajax_nonce-add-meta');
    $c = 0;
    $pid = (int) $_POST['post_id'];
    $post = get_post($pid);
    if (isset($_POST['metakeyselect']) || isset($_POST['metakeyinput'])) {
        if (!current_user_can('edit_post', $pid)) {
            wp_die(-1);
        }
        if (isset($_POST['metakeyselect']) && '#NONE#' == $_POST['metakeyselect'] && empty($_POST['metakeyinput'])) {
            wp_die(1);
        }
        // If the post is an autodraft, save the post as a draft and then attempt to save the meta.
        if ($post->post_status == 'auto-draft') {
            $post_data = array();
            $post_data['action'] = 'draft';
            // Warning fix
            $post_data['post_ID'] = $pid;
            $post_data['post_type'] = $post->post_type;
            $post_data['post_status'] = 'draft';
            $now = current_time('timestamp', 1);
            $post_data['post_title'] = sprintf(__('Draft created on %1$s at %2$s'), date(get_option('date_format'), $now), date(get_option('time_format'), $now));
            $pid = edit_post($post_data);
            if ($pid) {
                if (is_wp_error($pid)) {
                    $x = new WP_Ajax_Response(array('what' => 'meta', 'data' => $pid));
                    $x->send();
                }
                if (!($mid = add_meta($pid))) {
                    wp_die(__('Please provide a custom field value.'));
                }
            } else {
                wp_die(0);
            }
        } elseif (!($mid = add_meta($pid))) {
            wp_die(__('Please provide a custom field value.'));
        }
        $meta = get_metadata_by_mid('post', $mid);
        $pid = (int) $meta->post_id;
        $meta = get_object_vars($meta);
        $x = new WP_Ajax_Response(array('what' => 'meta', 'id' => $mid, 'data' => _list_meta_row($meta, $c), 'position' => 1, 'supplemental' => array('postid' => $pid)));
    } else {
        // Update?
        $mid = (int) key($_POST['meta']);
        $key = wp_unslash($_POST['meta'][$mid]['key']);
        $value = wp_unslash($_POST['meta'][$mid]['value']);
        if ('' == trim($key)) {
            wp_die(__('Please provide a custom field name.'));
        }
        if ('' == trim($value)) {
            wp_die(__('Please provide a custom field value.'));
        }
        if (!($meta = get_metadata_by_mid('post', $mid))) {
            wp_die(0);
        }
        // if meta doesn't exist
        if (is_protected_meta($meta->meta_key, 'post') || is_protected_meta($key, 'post') || !current_user_can('edit_post_meta', $meta->post_id, $meta->meta_key) || !current_user_can('edit_post_meta', $meta->post_id, $key)) {
            wp_die(-1);
        }
        if ($meta->meta_value != $value || $meta->meta_key != $key) {
            if (!($u = update_metadata_by_mid('post', $mid, $value, $key))) {
                wp_die(0);
            }
            // We know meta exists; we also know it's unchanged (or DB error, in which case there are bigger problems).
        }
        $x = new WP_Ajax_Response(array('what' => 'meta', 'id' => $mid, 'old_id' => $mid, 'data' => _list_meta_row(array('meta_key' => $key, 'meta_value' => $value, 'meta_id' => $mid), $c), 'position' => 0, 'supplemental' => array('postid' => $meta->post_id)));
    }
    $x->send();
}
예제 #7
0
/**
 * Update post meta data by meta ID.
 *
 * @since 1.2.0
 *
 * @param int    $meta_id
 * @param string $meta_key Expect Slashed
 * @param string $meta_value Expect Slashed
 * @return bool
 */
function update_meta($meta_id, $meta_key, $meta_value)
{
    $meta_key = wp_unslash($meta_key);
    $meta_value = wp_unslash($meta_value);
    return update_metadata_by_mid('post', $meta_id, $meta_value, $meta_key);
}
예제 #8
0
/**
 * {@internal Missing Short Description}}
 *
 * @since 1.2.0
 *
 * @param unknown_type $meta_id
 * @param unknown_type $meta_key Expect Slashed
 * @param unknown_type $meta_value Expect Slashed
 * @return unknown
 */
function update_meta($meta_id, $meta_key, $meta_value)
{
    $meta_key = stripslashes($meta_key);
    $meta_value = stripslashes_deep($meta_value);
    return update_metadata_by_mid('post', $meta_id, $meta_value, $meta_key);
}
 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 powerpress_admin_migrate_request()
{
    if (!empty($_GET['migrate_step'])) {
        switch ($_GET['migrate_step']) {
            case 1:
                $GLOBALS['powerpress_migrate_stats'] = powerpress_admin_extension_counts();
                break;
        }
    }
    if (!empty($_POST['migrate_action'])) {
        check_admin_referer('powerpress-migrate-media');
        switch ($_POST['migrate_action']) {
            case 'queue_episodes':
                if (!empty($_POST['Migrate'])) {
                    powerpress_admin_queue_files($_POST['Migrate']);
                    // Else error message handled in functoin called above
                }
                break;
            case 'update_episodes':
                // <input type="hidden" name="migrate_action" value="update_episodes" />
                $MigrateResultsPrevious = get_option('powerpress_migrate_results');
                $add_option = false;
                if ($MigrateResultsPrevious == false) {
                    $add_option = true;
                }
                unset($MigrateResultsPrevious);
                // Free up the memory
                //$URLs = powerpress_admin_migrate_get_migrated_by_status('completed');
                $URLs = powerpress_admin_migrate_get_migrated_by_status('all');
                if (!empty($URLs)) {
                    $URLs['updated_timestamp'] = current_time('timestamp');
                    if ($add_option) {
                        add_option('powerpress_migrate_results', $URLs, '', 'no');
                    } else {
                        update_option('powerpress_migrate_results', $URLs);
                    }
                    if (!empty($URLs['results'])) {
                        $update_option = true;
                        $CompletedResults = get_option('powerpress_migrate_completed');
                        if ($CompletedResults == false) {
                            $update_option = false;
                        }
                        if (empty($CompletedResults['completed_count'])) {
                            $CompletedResults['completed_count'] = 0;
                        }
                        if (empty($CompletedResults['error_count'])) {
                            $CompletedResults['error_count'] = 0;
                        }
                        if (empty($GLOBALS['g_powerprss_verify_failed_count'])) {
                            $GLOBALS['g_powerprss_verify_failed_count'] = 0;
                        }
                        if (empty($GLOBALS['g_powerpress_already_migrated'])) {
                            $GLOBALS['g_powerpress_already_migrated'] = 0;
                        }
                        if (empty($GLOBALS['g_powerpress_total_files_found'])) {
                            $GLOBALS['g_powerpress_total_files_found'] = 0;
                        }
                        if (empty($GLOBALS['g_powerpress_update_errors'])) {
                            $GLOBALS['g_powerpress_update_errors'] = 0;
                        }
                        $QueuedEpisodes = get_option('powerpress_migrate_queued');
                        // Array of key meta_id => URL value pairs
                        $FoundCount = 0;
                        if (!empty($QueuedEpisodes)) {
                            while (list($index, $row) = each($URLs['results'])) {
                                if ($row['status'] != 'completed') {
                                    // Not migrated
                                    continue;
                                }
                                $source_url = $row['source_url'];
                                $new_url = $row['new_url'];
                                $found = array_keys($QueuedEpisodes, $source_url);
                                if (empty($found)) {
                                    continue;
                                    // Nothing found here
                                }
                                $FoundCount++;
                                $GLOBALS['g_powerpress_total_files_found']++;
                                while (list($null, $meta_id) = each($found)) {
                                    // Get the post meta
                                    $meta_object = get_metadata_by_mid('post', $meta_id);
                                    if (!is_object($meta_object)) {
                                        continue;
                                    }
                                    // Weird
                                    $meta_data = $meta_object->meta_value;
                                    $parts = explode("\n", $meta_data, 2);
                                    $other_meta_data = false;
                                    if (count($parts) == 2) {
                                        list($current_url, $other_meta_data) = $parts;
                                    } else {
                                        $current_url = trim($meta_data);
                                    }
                                    $current_url = trim($current_url);
                                    // We already migrated this one, or it was modified anyway
                                    if ($source_url != $current_url) {
                                        //echo "$source_url != $current_url ";
                                        $GLOBALS['g_powerpress_already_migrated']++;
                                        continue;
                                    }
                                    // Verify the URL:
                                    if (!empty($_POST['PowerPressVerifyURLs'])) {
                                        $verified = powerpress_admin_verify_url($new_url);
                                        if (!empty($verified['error'])) {
                                            // TODO: Handle the error here...
                                            $GLOBALS['g_powerprss_verify_failed_count']++;
                                            continue;
                                        }
                                    }
                                    $new_meta_data = $new_url;
                                    if ($other_meta_data) {
                                        $new_meta_data .= "\n" . $other_meta_data;
                                    }
                                    // save the new URL
                                    if (update_metadata_by_mid('post', $meta_id, $new_meta_data)) {
                                        $CompletedResults['completed_count']++;
                                        $CompletedResults['results'][$meta_id] = $new_url;
                                    } else {
                                        $CompletedResults['error_count']++;
                                        $GLOBALS['g_powerpress_update_errors']++;
                                    }
                                }
                            }
                            if ($CompletedResults['completed_count'] > 0) {
                                if ($update_option) {
                                    update_option('powerpress_migrate_completed', $CompletedResults);
                                } else {
                                    add_option('powerpress_migrate_completed', $CompletedResults, '', 'no');
                                }
                                // Make sure we are not preloading
                                powerpress_page_message_add_notice(sprintf(__('Episodes updated successfully.', 'powerpress')));
                                return;
                            }
                            powerpress_page_message_add_notice(sprintf(__('No Episodes updated. Please see results.', 'powerpress')));
                            return;
                        }
                    } else {
                        powerpress_page_message_add_notice(sprintf(__('No episodes updated.', 'powerpress')));
                    }
                }
                break;
        }
    }
    if (!empty($_GET['migrate_action'])) {
        check_admin_referer('powerpress-migrate-media');
        switch ($_GET['migrate_action']) {
            case 'reset_migrate_media':
                delete_option('powerpress_migrate_completed');
                delete_option('powerpress_migrate_queued');
                delete_option('powerpress_migrate_status');
                delete_option('powerpress_migrate_results');
                powerpress_page_message_add_notice(sprintf(__('Media migration reset successfully.', 'powerpress')));
                break;
        }
    }
}
 /**
  * Add meta to an object.
  *
  * @param int $id Object ID
  * @param array $data {
  *     @type string|null $key Meta key
  *     @type string|null $key Meta value
  * }
  * @return bool|WP_Error
  */
 public function update_meta($id, $mid, $data)
 {
     $id = (int) $id;
     $mid = (int) $mid;
     $check = $this->check_object($id);
     if (is_wp_error($check)) {
         return $check;
     }
     $parent_column = $this->get_parent_column();
     $current = get_metadata_by_mid($this->type, $mid);
     if (empty($current)) {
         return new WP_Error('json_meta_invalid_id', __('Invalid meta ID.'), array('status' => 404));
     }
     if (absint($current->{$parent_column}) !== $id) {
         return new WP_Error('json_meta_' . $this->type . '_mismatch', __('Meta does not belong to this object'), array('status' => 400));
     }
     if (!array_key_exists('key', $data)) {
         $data['key'] = $current->meta_key;
     }
     if (!array_key_exists('value', $data)) {
         $data['value'] = $current->meta_value;
     }
     if (empty($data['key'])) {
         return new WP_Error('json_meta_invalid_key', __('Invalid meta key.'), array('status' => 400));
     }
     // for now let's not allow updating of arrays, objects or serialized values.
     if (!$this->is_valid_meta_data($current->meta_value)) {
         $code = $this->type === 'post' ? 'json_post_invalid_action' : 'json_meta_invalid_action';
         return new WP_Error($code, __('Invalid existing meta data for action.'), array('status' => 400));
     }
     if (!$this->is_valid_meta_data($data['value'])) {
         $code = $this->type === 'post' ? 'json_post_invalid_action' : 'json_meta_invalid_action';
         return new WP_Error($code, __('Invalid provided meta data for action.'), array('status' => 400));
     }
     if (is_protected_meta($current->meta_key)) {
         return new WP_Error('json_meta_protected', sprintf(__('%s is marked as a protected field.'), $current->meta_key), array('status' => 403));
     }
     if (is_protected_meta($data['key'])) {
         return new WP_Error('json_meta_protected', sprintf(__('%s is marked as a protected field.'), $data['key']), array('status' => 403));
     }
     // update_metadata_by_mid will return false if these are equal, so check
     // first and pass through
     if ($data['value'] === $current->meta_value && $data['key'] === $current->meta_key) {
         return $this->get_meta($id, $mid);
     }
     $key = wp_slash($data['key']);
     $value = wp_slash($data['value']);
     if (!update_metadata_by_mid($this->type, $mid, $value, $key)) {
         return new WP_Error('json_meta_could_not_update', __('Could not update meta.'), array('status' => 500));
     }
     return $this->get_meta($id, $mid);
 }
예제 #12
0
 /**
  * Update Meta Data in the database.
  * @since 2.6.0
  */
 protected function save_meta_data()
 {
     foreach ($this->_meta_data as $array_key => $meta) {
         if (is_null($meta->value)) {
             if (!empty($meta->id)) {
                 delete_metadata_by_mid($this->_meta_type, $meta->id);
             }
         } elseif (empty($meta->id)) {
             $new_meta_id = add_metadata($this->_meta_type, $this->get_id(), $meta->key, $meta->value, false);
             $this->_meta_data[$array_key]->id = $new_meta_id;
         } else {
             update_metadata_by_mid($this->_meta_type, $meta->id, $meta->value, $meta->key);
         }
     }
     if (!empty($this->_cache_group)) {
         WC_Cache_Helper::incr_cache_prefix($this->_cache_group);
     }
     $this->read_meta_data();
 }
예제 #13
0
 /**
  * @ticket 37746
  */
 function test_string_point_zero_meta_id()
 {
     $meta_id = add_metadata('user', $this->author->ID, 'meta_key', 'meta_value_2');
     $string_mid = "{$meta_id}.0";
     $this->assertTrue(floor($string_mid) == $string_mid);
     $this->assertNotEquals(false, get_metadata_by_mid('user', $string_mid));
     $this->assertNotEquals(false, update_metadata_by_mid('user', $string_mid, 'meta_new_value_2'));
     $this->assertNotEquals(false, delete_metadata_by_mid('user', $string_mid));
 }
예제 #14
0
 /**
  * save
  * Save the form data, excludes widgets and settings api fields.
  *
  * @return bool Whether or not data was saved.
  *
  * @access public
  * @static
  * @since 1.0
  */
 public static function save()
 {
     global $wpdb, $wp_post_types, $wp_taxonomies;
     $check = piklist_validate::check();
     // Get our field data after its been sanitized and validated
     if (!isset($_REQUEST[piklist::$prefix]['fields']) || isset($_REQUEST[piklist::$prefix]['filter']) || !$check['valid'] || $check['type'] != 'POST') {
         self::$form_submission = $check['fields_data'];
         return false;
     }
     $fields_data = $check['fields_data'];
     // Handle normal file uploads
     foreach ($fields_data as $scope => &$fields) {
         if (in_array($scope, array('post_meta', 'term_meta', 'user_meta', 'comment_meta'))) {
             $meta_type = substr($scope, 0, strpos($scope, '_'));
             foreach ($fields as &$field) {
                 if (!$field['display'] && array_key_exists(piklist::$prefix . $scope, $_FILES) && array_key_exists($field['field'], $_FILES[piklist::$prefix . $scope]['name'])) {
                     $paths = piklist::array_paths($_FILES[piklist::$prefix . $scope]['name'][$field['field']]);
                     if (!empty($paths)) {
                         if (strstr($paths[0], ':')) {
                             foreach ($paths as $path) {
                                 $files_path = explode(':', $path);
                                 unset($files_path[count($files_path) - 1]);
                                 $files_path = array_merge(array(piklist::$prefix . $scope, 'name'), explode(':', $field['field'] . ':' . implode(':', $files_path)));
                                 $field_name = explode(':', $path);
                                 $field_name = $field_name[1];
                                 $options = $field['options'];
                                 foreach ($field['fields'] as $_field) {
                                     if ($_field['field'] == $field_name) {
                                         $options = $_field['options'];
                                         break;
                                     }
                                 }
                                 $storage = array();
                                 $storage_type = isset($field['options']['save']) && $field['options']['save'] == 'url';
                                 $upload = self::save_upload($files_path, $storage, $storage_type);
                                 if ($upload) {
                                     piklist::array_path_set($field['request_value'], explode(':', $path), current($upload));
                                 }
                             }
                         } else {
                             $path = array_merge(array(piklist::$prefix . $scope, 'name'), array($field['field']));
                             $storage = is_array($field['request_value']) ? array_filter($field['request_value']) : $field['request_value'];
                             $storage_type = isset($field['options']['save']) && $field['options']['save'] == 'url';
                             $upload = self::save_upload($path, $storage, $storage_type);
                             if ($upload) {
                                 $field['request_value'] = $upload;
                             }
                         }
                     }
                 }
             }
         }
     }
     $object_ids = array();
     // Save field data
     foreach ($fields_data as $scope => &$fields) {
         if (in_array($scope, array('post', 'user', 'comment'))) {
             $objects = array();
             foreach ($fields as &$field) {
                 $values = is_array($field['request_value']) ? $field['request_value'] : array($field['request_value']);
                 foreach ($values as $index => $value) {
                     if (is_array($field['object_id'])) {
                         $id = isset($field['object_id'][$index]) ? $field['object_id'][$index] : 'insert-' . $index;
                     } else {
                         $id = isset($field['object_id']) ? $field['object_id'] : 'insert-' . $index;
                     }
                     if (isset($field['object_id'][$id]) && !isset($objects[$field['object_id'][$id]])) {
                         $objects[$id] = array();
                     }
                     if (isset($field['object_id'][$index]) || $field['object_id']) {
                         $objects[$id][$scope == 'comment' ? $field['relate'] ? 'comment_ID' : 'comment_post_ID' : 'ID'] = $id;
                     }
                     if ($field['request_value'] && !$field['display']) {
                         $field_name = strrpos($field['field'], ':') > 0 ? substr($field['field'], strrpos($field['field'], ':') + 1) : $field['field'];
                         $objects[$id][$field_name] = $value;
                     }
                 }
             }
             foreach ($fields as &$field) {
                 if ($field['relate']) {
                     $_object_ids = is_array($field['object_id']) ? $field['object_id'] : array($field['object_id']);
                     foreach ($_object_ids as $_object_id) {
                         if (!isset($objects[$_object_id])) {
                             if (!isset($field['relate']['remove'])) {
                                 $field['relate']['remove'] = array();
                             }
                             array_push($field['relate']['remove'], $_object_id);
                         }
                     }
                 }
             }
             foreach ($objects as $id => $object) {
                 $result_id = self::save_object($scope, $object);
                 if (strstr($id, 'insert-')) {
                     foreach ($fields as &$field) {
                         if ($field['object_id']) {
                             $field['object_id'] = is_array($field['object_id']) ? $field['object_id'] : array($field['object_id']);
                             array_push($field['object_id'], $result_id);
                         } else {
                             $field['object_id'] = $result_id;
                         }
                     }
                 }
                 if (!isset($object_ids[$scope])) {
                     $object_ids[$scope] = $result_id;
                 }
             }
         } elseif (in_array($scope, array('post_meta', 'term_meta', 'user_meta', 'comment_meta'))) {
             $meta_type = substr($scope, 0, strpos($scope, '_'));
             $meta = piklist_meta::get_meta_properties($meta_type);
             foreach ($fields as &$field) {
                 $field['object_id'] = $field['object_id'] ? $field['object_id'] : $object_ids[$meta_type];
                 if ($field['object_id'] && !$field['display'] && !strstr($field['field'], ':')) {
                     $save_as = is_string($field['save_as']) ? $field['save_as'] : $field['field'];
                     $grouped = in_array($field['type'], self::$field_list_types['multiple_value']);
                     $current_meta_ids = $wpdb->get_col($wpdb->prepare("SELECT {$meta->id} FROM {$meta->table} WHERE {$meta->object_id} = %d AND meta_key = %s", $field['object_id'], $save_as));
                     if ($grouped) {
                         $current_group_meta_ids = $wpdb->get_col($wpdb->prepare("SELECT {$meta->id} FROM {$meta->table} WHERE {$meta->object_id} = %d AND meta_key = %s", $field['object_id'], '_' . piklist::$prefix . $save_as));
                     }
                     if (is_array($field['request_value']) && $field['type'] != 'group') {
                         foreach ($field['request_value'] as $values) {
                             if (is_array($values)) {
                                 $meta_ids = array();
                                 foreach ($values as $value) {
                                     if (!empty($current_meta_ids)) {
                                         $meta_id = array_shift($current_meta_ids);
                                         update_metadata_by_mid($meta_type, $meta_id, $value);
                                     } else {
                                         $meta_id = add_metadata($meta_type, $field['object_id'], $save_as, $value);
                                     }
                                     if ($meta_id) {
                                         array_push($meta_ids, $meta_id);
                                     }
                                 }
                                 if ($grouped) {
                                     if (!empty($current_group_meta_ids)) {
                                         $group_meta_id = array_shift($current_group_meta_ids);
                                         update_metadata_by_mid($meta_type, $group_meta_id, $meta_ids);
                                     } else {
                                         add_metadata($meta_type, $field['object_id'], '_' . piklist::$prefix . $save_as, $meta_ids);
                                     }
                                 }
                             } else {
                                 if (is_array($values) && count($values) == 1) {
                                     $values = current($values);
                                 }
                                 if (!empty($current_meta_ids)) {
                                     $meta_id = array_shift($current_meta_ids);
                                     update_metadata_by_mid($meta_type, $meta_id, $values);
                                 } else {
                                     add_metadata($meta_type, $field['object_id'], $save_as, $values);
                                 }
                             }
                         }
                         if (!empty($current_group_meta_ids)) {
                             foreach ($current_group_meta_ids as $current_group_meta_id) {
                                 delete_metadata_by_mid($meta_type, $current_group_meta_id);
                             }
                         }
                     } else {
                         if (!empty($current_meta_ids)) {
                             if (is_numeric($field['index_force'])) {
                                 if (isset($current_meta_ids[$field['index_force']])) {
                                     $meta_id = $current_meta_ids[$field['index_force']];
                                     update_metadata_by_mid($meta_type, $meta_id, $field['request_value']);
                                 } else {
                                     add_metadata($meta_type, $field['object_id'], $save_as, $field['request_value']);
                                 }
                                 $current_meta_ids = array();
                             } else {
                                 $meta_id = array_shift($current_meta_ids);
                             }
                             if (isset($meta_id)) {
                                 update_metadata_by_mid($meta_type, $meta_id, $field['request_value']);
                             }
                         } else {
                             add_metadata($meta_type, $field['object_id'], $save_as, $field['request_value']);
                         }
                     }
                     if (!empty($current_meta_ids)) {
                         foreach ($current_meta_ids as $current_meta_id) {
                             delete_metadata_by_mid($meta_type, $current_meta_id);
                         }
                     }
                 }
             }
         } elseif ($scope == 'taxonomy') {
             $taxonomies = array();
             $append = array();
             $ids = array();
             foreach ($fields as &$field) {
                 if (!$field['display']) {
                     $taxonomy = is_string($field['save_as']) ? $field['save_as'] : $field['field'];
                     $append[$taxonomy] = isset($field['options']['append']) && is_bool($field['options']['append']) ? $field['options']['append'] : false;
                     if (!isset($taxonomies[$taxonomy])) {
                         $taxonomies[$taxonomy] = array();
                         $field['object_id'] = $field['object_id'] ? $field['object_id'] : $object_ids[$wp_taxonomies[$taxonomy]->object_type[0]];
                         $ids[$taxonomy] = $field['object_id'];
                     }
                     if ($field['request_value']) {
                         $request_value = is_array($field['request_value']) ? $field['request_value'] : array($field['request_value']);
                         foreach ($request_value as $terms) {
                             if (!empty($terms)) {
                                 $terms = !is_array($terms) ? array($terms) : $terms;
                                 foreach ($terms as $term) {
                                     if (!in_array($term, $taxonomies[$taxonomy])) {
                                         array_push($taxonomies[$taxonomy], is_numeric($term) ? (int) $term : $term);
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
             foreach ($taxonomies as $taxonomy => $terms) {
                 if (isset($wp_taxonomies[$taxonomy]->object_type[0])) {
                     switch ($wp_taxonomies[$taxonomy]->object_type[0]) {
                         case 'user':
                             if (current_user_can('edit_user', $field['object_id']) && current_user_can($wp_taxonomies[$taxonomy]->cap->assign_terms)) {
                                 $id = $ids[$taxonomy];
                             }
                             break;
                         default:
                             $id = $ids[$taxonomy];
                             break;
                     }
                 }
                 if (isset($id)) {
                     wp_set_object_terms($id, $terms, $taxonomy, $append[$taxonomy]);
                     clean_object_term_cache($id, $taxonomy);
                 }
             }
         } elseif ($scope == 'option') {
             foreach ($fields as &$field) {
                 if ($field['field'] && !stristr($field['field'], ':')) {
                     $value = $field['request_value'];
                     if (is_array($value) && piklist::is_flat($value) && count($value) == 1) {
                         $value = current($value);
                     }
                     if (!isset($field['options']['type'])) {
                         $auto_load = isset($field['options']['auto_load']) ? $field['options']['auto_load'] : null;
                         update_option($field['field'], $value, $auto_load);
                     } elseif ($field['options']['type'] == 'blog' && $field['object_id']) {
                         $deprecated = isset($field['options']['deprecated']) ? $field['options']['deprecated'] : null;
                         update_blog_option($field['object_id'], $field['field'], $value, $deprecated);
                     } elseif ($field['options']['type'] == 'user' && $field['object_id']) {
                         $global = isset($field['options']['global']) ? $field['options']['global'] : false;
                         update_user_option($field['object_id'], $field['field'], $value, $global);
                     } elseif ($field['options']['type'] == 'site') {
                         update_site_option($field['field'], $value);
                     }
                 }
             }
         }
         /**
          * piklist_save_field
          * Fires after fields have been saved
          *
          * @param $type Field type.
          *
          * @since 1.0
          */
         do_action('piklist_save_field', $scope, $fields);
         /**
          * piklist_save_field-{$scope}
          * Fires after fields have been saved and is scope specific
          *
          * @param $type Field type.
          *
          * @since 1.0
          */
         do_action("piklist_save_field-{$scope}", $fields);
     }
     self::$form_submission = $fields_data;
     self::relate();
     return true;
 }
예제 #15
0
파일: meta.php 프로젝트: boonebgorges/wp
 /**
  * @ticket 28315
  */
 function test_non_numeric_meta_id()
 {
     $this->assertFalse(get_metadata_by_mid('user', array(1)));
     $this->assertFalse(update_metadata_by_mid('user', array(1), 'meta_new_value'));
     $this->assertFalse(delete_metadata_by_mid('user', array(1)));
 }
 /**
  * Update meta.
  *
  * @since  2.7.0
  * @param  WC_Data
  * @param  stdClass (containing ->id, ->key and ->value)
  */
 public function update_meta(&$object, $meta)
 {
     update_metadata_by_mid($this->meta_type, $meta->id, $meta->value, $meta->key);
 }
 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;
 }
예제 #18
0
 /**
  * Add meta to a post
  *
  * @param int $id Post ID
  * @param array $data {
  *     @type string|null $key Meta key
  *     @type string|null $key Meta value
  * }
  * @return bool|WP_Error
  */
 public function update_meta($id, $mid, $data)
 {
     $id = (int) $id;
     $mid = (int) $mid;
     if (empty($id)) {
         return new WP_Error('json_post_invalid_id', __('Invalid post ID.'), array('status' => 404));
     }
     $post = get_post($id, ARRAY_A);
     if (empty($post['ID'])) {
         return new WP_Error('json_post_invalid_id', __('Invalid post ID.'), array('status' => 404));
     }
     if (!$this->check_edit_permission($post)) {
         return new WP_Error('json_cannot_edit', __('Sorry, you cannot edit this post'), array('status' => 403));
     }
     $current = get_metadata_by_mid('post', $mid);
     if (empty($current)) {
         return new WP_Error('json_meta_invalid_id', __('Invalid meta ID.'), array('status' => 404));
     }
     if (absint($current->post_id) !== $id) {
         return new WP_Error('json_meta_post_mismatch', __('Meta does not belong to this post'), array('status' => 400));
     }
     if (!array_key_exists('key', $data)) {
         $data['key'] = $current->meta_key;
     }
     if (!array_key_exists('value', $data)) {
         $data['value'] = $current->meta_value;
     }
     if (empty($data['key'])) {
         return new WP_Error('json_meta_invalid_key', __('Invalid meta key.'), array('status' => 400));
     }
     // for now let's not allow updating of arrays, objects or serialized values.
     if (!$this->is_valid_meta_data($current->meta_value)) {
         return new WP_Error('json_post_invalid_action', __('Invalid existing meta data for action.'), array('status' => 400));
     }
     if (!$this->is_valid_meta_data($data['value'])) {
         return new WP_Error('json_post_invalid_action', __('Invalid provided meta data for action.'), array('status' => 400));
     }
     if (is_protected_meta($current->meta_key)) {
         return new WP_Error('json_meta_protected', sprintf(__('%s is marked as a protected field.'), $current->meta_key), array('status' => 403));
     }
     if (is_protected_meta($data['key'])) {
         return new WP_Error('json_meta_protected', sprintf(__('%s is marked as a protected field.'), $data['key']), array('status' => 403));
     }
     // update_metadata_by_mid will return false if these are equal, so check
     // first and pass through
     if ($data['value'] === $current->meta_value && $data['key'] === $current->meta_key) {
         return $this->get_meta($id, $mid);
     }
     $key = wp_slash($data['key']);
     $value = wp_slash($data['value']);
     if (!update_metadata_by_mid('post', $mid, $value, $key)) {
         return new WP_Error('json_meta_could_not_update', __('Could not update post meta.'), array('status' => 500));
     }
     return $this->get_meta($id, $mid);
 }
 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;
 }
예제 #20
0
 /**
  * Update Meta Data in the database.
  * @since 2.6.0
  */
 protected function save_meta_data()
 {
     global $wpdb;
     $db_info = $this->_get_db_info();
     $all_meta_ids = array_map('absint', $wpdb->get_col($wpdb->prepare("\n\t\t\tSELECT " . $db_info['meta_id_field'] . " FROM " . $db_info['table'] . "\n\t\t\tWHERE " . $db_info['object_id_field'] . " = %d", $this->get_id()) . "\n\t\t\tAND meta_key NOT IN ('" . implode("','", array_map('esc_sql', $this->get_internal_meta_keys())) . "')\n\t\t\tAND meta_key NOT LIKE 'wp\\_%%';\n\t\t"));
     $set_meta_ids = array();
     foreach ($this->_meta_data as $array_key => $meta) {
         if (empty($meta->id)) {
             $new_meta_id = add_metadata($this->_meta_type, $this->get_id(), $meta->key, $meta->value, false);
             $set_meta_ids[] = $new_meta_id;
             $this->_meta_data[$array_key]->id = $new_meta_id;
         } else {
             update_metadata_by_mid($this->_meta_type, $meta->id, $meta->value, $meta->key);
             $set_meta_ids[] = absint($meta->id);
         }
     }
     // Delete no longer set meta data
     $delete_meta_ids = array_diff($all_meta_ids, $set_meta_ids);
     foreach ($delete_meta_ids as $meta_id) {
         delete_metadata_by_mid($this->_meta_type, $meta_id);
     }
     if (!empty($this->_cache_group)) {
         WC_Cache_Helper::incr_cache_prefix($this->_cache_group);
     }
     $this->read_meta_data();
 }
예제 #21
0
 /**
  * General clean-up of the saved meta values
  * - Remove potentially lingering old meta keys
  * - Remove all default and invalid values
  *
  * @static
  * @return void
  */
 public static function clean_up()
 {
     global $wpdb;
     /**
      * Clean up '_yoast_wpseo_meta-robots'
      *
      * Retrieve all '_yoast_wpseo_meta-robots' meta values and convert if no new values found
      * @internal Query is pretty well optimized this way
      *
      * @todo [JRF => Yoast] find out all possible values which the old '_yoast_wpseo_meta-robots' could contain
      * to convert the data correctly
      */
     $query = $wpdb->prepare("\r\n\t\t\t\tSELECT `a`.*\r\n\t\t\t\tFROM {$wpdb->postmeta} AS a\r\n\t\t\t\tWHERE `a`.`meta_key` = %s\r\n\t\t\t\t\tAND NOT\tEXISTS (\r\n\t\t\t\t\t\tSELECT DISTINCT `post_id` , count( `meta_id` ) AS count\r\n\t\t\t\t\t\tFROM {$wpdb->postmeta} AS b\r\n\t\t\t\t\t\tWHERE `a`.`post_id` = `b`.`post_id`\r\n\t\t\t\t\t\t\tAND ( `meta_key` = %s\r\n\t\t\t\t\t\t\tOR `meta_key` = %s )\r\n\t\t\t\t\t\tGROUP BY `post_id`\r\n\t\t\t\t\t)\r\n\t\t\t\t;", self::$meta_prefix . 'meta-robots', self::$meta_prefix . 'meta-robots-noindex', self::$meta_prefix . 'meta-robots-nofollow');
     $oldies = $wpdb->get_results($query);
     if (is_array($oldies) && $oldies !== array()) {
         foreach ($oldies as $old) {
             $old_values = explode(',', $old->meta_value);
             foreach ($old_values as $value) {
                 if ($value === 'noindex') {
                     update_post_meta($old->post_id, self::$meta_prefix . 'meta-robots-noindex', 1);
                 } elseif ($value === 'nofollow') {
                     update_post_meta($old->post_id, self::$meta_prefix . 'meta-robots-nofollow', 1);
                 }
             }
         }
     }
     unset($query, $oldies, $old, $old_values, $value);
     // Delete old keys
     delete_post_meta_by_key(self::$meta_prefix . 'meta-robots');
     /**
      * Remove all default values and (most) invalid option values
      * Invalid option values for the multiselect (meta-robots-adv) field will be dealt with seperately
      *
      * @internal some of the defaults have changed in v1.5, but as the defaults will be removed and
      * new defaults will now automatically be passed when no data found, this update is automatic
      * (as long as we remove the old values which we do in the below routine)
      *
      * @internal unfortunately we can't use the normal delete_meta() with key/value combination as ''
      * (empty string) values will be ignored and would result in all metas with that key being deleted,
      * not just the empty fields.
      * Still, the below implementation is largely based on the delete_meta() function
      */
     $query = array();
     foreach (self::$meta_fields as $subset => $field_group) {
         foreach ($field_group as $key => $field_def) {
             if ($field_def['type'] === 'snippetpreview' || !isset($field_def['default_value'])) {
                 continue;
             }
             if ($key === 'meta-robots-adv') {
                 $query[] = $wpdb->prepare("( meta_key = %s AND ( meta_value = 'none' OR meta_value = '-' ) )", self::$meta_prefix . $key);
             } elseif (isset($field_def['options']) && is_array($field_def['options']) && $field_def['options'] !== array()) {
                 $valid = $field_def['options'];
                 // remove the default value from the valid options
                 unset($valid[$field_def['default_value']]);
                 $valid = array_keys($valid);
                 $query[] = $wpdb->prepare("( meta_key = %s AND meta_value NOT IN ( '" . implode("','", esc_sql($valid)) . "' ) )", self::$meta_prefix . $key);
                 unset($valid);
             } elseif (is_string($field_def['default_value']) && $field_def['default_value'] !== '') {
                 $query[] = $wpdb->prepare('( meta_key = %s AND meta_value = %s )', self::$meta_prefix . $key, $field_def['default_value']);
             } else {
                 $query[] = $wpdb->prepare("( meta_key = %s AND meta_value = '' )", self::$meta_prefix . $key);
             }
         }
     }
     unset($subset, $field_group, $key, $field_def, $where_or_or);
     $query = "SELECT meta_id FROM {$wpdb->postmeta} WHERE " . implode(' OR ', $query) . ';';
     $meta_ids = $wpdb->get_col($query);
     if (is_array($meta_ids) && $meta_ids !== array()) {
         // wp native action
         do_action('delete_post_meta', $meta_ids, null, null, null);
         $query = "DELETE FROM {$wpdb->postmeta} WHERE meta_id IN( " . implode(',', $meta_ids) . ' )';
         $count = $wpdb->query($query);
         if ($count) {
             foreach ($meta_ids as $object_id) {
                 wp_cache_delete($object_id, 'post_meta');
             }
             // wp native action
             do_action('deleted_post_meta', $meta_ids, null, null, null);
         }
     }
     unset($query, $meta_ids, $count, $object_id);
     /**
      * Deal with the multiselect (meta-robots-adv) field
      *
      * Removes invalid option combinations, such as 'none,noarchive'
      *
      * Default values have already been removed, so we should have a small result set and
      * (hopefully) even smaller set of invalid results.
      */
     $query = $wpdb->prepare("SELECT meta_id, meta_value FROM {$wpdb->postmeta} WHERE meta_key = %s", self::$meta_prefix . 'meta-robots-adv');
     $oldies = $wpdb->get_results($query);
     if (is_array($oldies) && $oldies !== array()) {
         foreach ($oldies as $old) {
             $clean = self::validate_meta_robots_adv($old->meta_value);
             if ($clean !== $old->meta_value) {
                 if ($clean !== self::$meta_fields['advanced']['meta-robots-adv']['default_value']) {
                     update_metadata_by_mid('post', $old->meta_id, $clean);
                 } else {
                     delete_metadata_by_mid('post', $old->meta_id);
                 }
             }
         }
     }
     unset($query, $oldies, $old, $clean);
     do_action('wpseo_meta_clean_up');
 }
예제 #22
0
 /**
  * Upgrade book metadata.
  */
 function upgradeBook()
 {
     $book_structure = Book::getBookStructure();
     foreach ($book_structure['__order'] as $post_id => $_) {
         $meta = get_post_meta($post_id);
         $compare = $this->getDeprecatedComparisonTable(get_post_type($post_id));
         foreach ($meta as $meta_key => $meta_value) {
             $new_meta_key = @$compare[$meta_key];
             if ($new_meta_key) {
                 $meta_id = $this->getMidByKey($post_id, $meta_key);
                 if ($meta_id) {
                     if (isset($this->upgradeCheckboxes[$meta_key])) {
                         $meta_value = 'on';
                     } elseif (is_array($meta_value)) {
                         $meta_value = array_values($meta_value);
                         $meta_value = array_pop($meta_value);
                     }
                     // Updating [$meta_key] to [$new_meta_key]
                     update_metadata_by_mid('post', $meta_id, $meta_value, $new_meta_key);
                 }
             }
         }
     }
 }
예제 #23
0
 /**
  * Set custom fields for post.
  *
  * @since 2.5.0
  *
  * @param int $post_id Post ID.
  * @param array $fields Custom fields.
  */
 public function set_custom_fields($post_id, $fields)
 {
     $post_id = (int) $post_id;
     foreach ((array) $fields as $meta) {
         if (isset($meta['id'])) {
             $meta['id'] = (int) $meta['id'];
             $pmeta = get_metadata_by_mid('post', $meta['id']);
             if (isset($meta['key'])) {
                 $meta['key'] = wp_unslash($meta['key']);
                 if ($meta['key'] !== $pmeta->meta_key) {
                     continue;
                 }
                 $meta['value'] = wp_unslash($meta['value']);
                 if (current_user_can('edit_post_meta', $post_id, $meta['key'])) {
                     update_metadata_by_mid('post', $meta['id'], $meta['value']);
                 }
             } elseif (current_user_can('delete_post_meta', $post_id, $pmeta->meta_key)) {
                 delete_metadata_by_mid('post', $meta['id']);
             }
         } elseif (current_user_can('add_post_meta', $post_id, wp_unslash($meta['key']))) {
             add_post_meta($post_id, $meta['key'], $meta['value']);
         }
     }
 }
예제 #24
0
파일: meta.php 프로젝트: 082net/bbpresskr
 static function ajax_add_bbpmeta()
 {
     check_ajax_referer('add-bbpmeta', '_ajax_nonce-add-bbpmeta');
     $c = 0;
     $pid = (int) $_POST['post_id'];
     $post = get_post($pid);
     if (isset($_POST['bbpmeta_key'])) {
         if (!current_user_can('edit_post', $pid)) {
             wp_die(-1);
         }
         if (empty($_POST['bbpmeta_key'])) {
             wp_die(1);
         }
         if ($post->post_status == 'auto-draft') {
             $save_POST = $_POST;
             // Backup $_POST
             $_POST = array();
             // Make it empty for edit_post()
             $_POST['action'] = 'draft';
             // Warning fix
             $_POST['post_ID'] = $pid;
             $_POST['post_type'] = $post->post_type;
             $_POST['post_status'] = 'draft';
             $now = current_time('timestamp', 1);
             $_POST['post_title'] = sprintf(__('Draft created on %1$s at %2$s'), date(get_option('date_format'), $now), date(get_option('time_format'), $now));
             if ($pid = edit_post()) {
                 if (is_wp_error($pid)) {
                     $x = new WP_Ajax_Response(array('what' => 'bbpmeta', 'data' => $pid));
                     $x->send();
                 }
                 $_POST = $save_POST;
                 // Now we can restore original $_POST again
                 if (!($mid = self::add_meta($pid))) {
                     wp_die(__('Please provide a valid key and value set.', 'bbpresskr'));
                 } elseif (!is_numeric($mid)) {
                     wp_die($mid);
                 }
             } else {
                 wp_die(0);
             }
         } elseif (!($mid = self::add_meta($pid))) {
             wp_die(__('Please provide a valid key and value set.', 'bbpresskr'));
         } elseif (!is_numeric($mid)) {
             wp_die($mid);
         }
         $meta = get_metadata_by_mid('post', $mid);
         $pid = (int) $meta->post_id;
         $meta = $meta->meta_value;
         $x = new WP_Ajax_Response(array('what' => 'meta', 'id' => $mid, 'data' => self::_list_meta_row(array_merge($meta, array('meta_id' => $mid)), $c), 'position' => 1, 'supplemental' => array('postid' => $pid)));
     } else {
         // Update?
         $mid = (int) key($_POST['bbpmeta']);
         $new = array_map('wp_unslash', $_POST['bbpmeta'][$mid]);
         foreach (array('list') as $what) {
             $new[$what] = isset($new[$what]);
         }
         extract($new, EXTR_SKIP);
         // var_dump( $_POST['bbpmeta'], $key, $label);
         if (true !== ($validate = self::validate_meta($new))) {
             wp_die($validate);
         }
         if (!($meta = get_metadata_by_mid('post', $mid))) {
             wp_die(0);
         }
         // if meta doesn't exist
         if (is_protected_meta($meta->meta_key, 'post') || is_protected_meta($key, 'post') || !current_user_can('edit_post_meta', $meta->post_id, $meta->meta_key) || !current_user_can('edit_post_meta', $meta->post_id, $key)) {
             wp_die(-1);
         }
         $meta_value = maybe_unserialize($meta->meta_value);
         if ($meta_value != $new) {
             if ($meta_value['key'] != $new['key']) {
                 $current = \bbPressKR\Meta::meta_params($pid);
                 foreach ($current as $param) {
                     if ($param['key'] == $new['key']) {
                         wp_die('Provided key is already in use.', 'bbpresskr');
                     }
                 }
             }
             if (!($u = update_metadata_by_mid('post', $mid, $new))) {
                 wp_die(0);
             }
             // We know meta exists; we also know it's unchanged (or DB error, in which case there are bigger problems).
         }
         $x = new WP_Ajax_Response(array('what' => 'meta', 'id' => $mid, 'old_id' => $mid, 'data' => self::_list_meta_row(array_merge($new, array('meta_id' => $mid)), $c), 'position' => 0, 'supplemental' => array('postid' => $meta->post_id)));
     }
     $x->send();
 }