コード例 #1
0
ファイル: meta.php プロジェクト: rmccue/wordpress-unit-tests
 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 see_also_page_template()
 {
     $parent_post_id = array_key_exists('parent', $_GET) ? $_GET['parent'] : 0;
     if (array_key_exists('meta', $_GET)) {
         $meta_id = $_GET['meta'];
     } else {
         if (is_page('video')) {
             $meta_id = get_meta_id_by_key($parent_post_id, 'external_video_url');
         }
     }
     if (empty($meta_id)) {
         show_error_message('missing_meta_param', $parent_post_id);
     }
     $external_url_meta = get_metadata_by_mid('post', $meta_id);
     if (!empty($external_url_meta->meta_value)) {
         echo do_shortcode('[iframe src="' . $external_url_meta->meta_value . '" width="100% height="100%]');
     } else {
         show_error_message('missing_url', $parent_post_id);
     }
 }
コード例 #3
0
ファイル: admin-ajax.php プロジェクト: vivekkodira1/wordpress
     $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 = stripslashes($_POST['meta'][$mid]['key']);
     $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();
コード例 #4
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();
 }
コード例 #5
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']);
         }
     }
 }
コード例 #6
0
ファイル: meta.php プロジェクト: boonebgorges/wp
 function test_update_meta()
 {
     // Add a unique post meta item
     $this->assertInternalType('integer', $mid1 = add_post_meta($this->post_id, 'unique_update', 'value', true));
     // Add two non unique post meta item
     $this->assertInternalType('integer', $mid2 = add_post_meta($this->post_id, 'nonunique_update', 'value'));
     $this->assertInternalType('integer', $mid3 = add_post_meta($this->post_id, 'nonunique_update', 'another value'));
     //Check they exist
     $this->assertEquals('value', get_post_meta($this->post_id, 'unique_update', true));
     $this->assertEquals(array('value'), get_post_meta($this->post_id, 'unique_update', false));
     $this->assertEquals('value', get_post_meta($this->post_id, 'nonunique_update', true));
     $this->assertEquals(array('value', 'another value'), get_post_meta($this->post_id, 'nonunique_update', false));
     // Update them
     $this->assertTrue(update_meta($mid1, 'unique_update', 'new'));
     $this->assertTrue(update_meta($mid2, 'nonunique_update', 'new'));
     $this->assertTrue(update_meta($mid3, 'nonunique_update', 'another new'));
     //Check they updated
     $this->assertEquals('new', get_post_meta($this->post_id, 'unique_update', true));
     $this->assertEquals(array('new'), get_post_meta($this->post_id, 'unique_update', false));
     $this->assertEquals('new', get_post_meta($this->post_id, 'nonunique_update', true));
     $this->assertEquals(array('new', 'another new'), get_post_meta($this->post_id, 'nonunique_update', false));
     // Slashed update
     $data = "'quote and \\slash";
     $this->assertTrue(update_meta($mid1, 'unique_update', addslashes($data)));
     $meta = get_metadata_by_mid('post', $mid1);
     $this->assertEquals($data, $meta->meta_value);
 }
 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;
 }
コード例 #8
0
 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;
 }
コード例 #9
0
	function test_edit_custom_fields() {
		$contributor_id = $this->make_user_by_role( 'contributor' );

		$post = array( 'post_title' => 'Post test', 'post_author' => $contributor_id );
		$post_id = wp_insert_post( $post );
		$mid_edit   = add_post_meta( $post_id, 'custom_field_key', '12345678' );
		$mid_delete = add_post_meta( $post_id, 'custom_field_to_delete', '12345678' );

		$new_title = 'Post test (updated)';
		$post2 = array(
			'post_title' => $new_title,
			'custom_fields' =>
				array(
					array( 'id' => $mid_delete ),
					array( 'id' => $mid_edit, 'key' => 'custom_field_key', 'value' => '87654321' ),
					array( 'key' => 'custom_field_to_create', 'value' => '12345678' )
				)
		);

		$result = $this->myxmlrpcserver->wp_editPost( array( 1, 'contributor', 'contributor', $post_id, $post2 ) );
		$this->assertNotInstanceOf( 'IXR_Error', $result );
		$this->assertTrue($result);

		$out = get_post( $post_id );
		$this->assertEquals( $new_title, $out->post_title );

		$edited_object = get_metadata_by_mid( 'post', $mid_edit );
		$this->assertEquals( '87654321', $edited_object->meta_value );
		$this->assertFalse( get_metadata_by_mid( 'post', $mid_delete ) );

		$created_object = get_post_meta( $post_id, 'custom_field_to_create', true );
		$this->assertEquals( $created_object, '12345678' );
	}
 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;
 }
コード例 #11
0
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;
        }
    }
}
コード例 #12
0
 /**
  * Delete meta from an object.
  *
  * @param int $id Object ID
  * @param int $mid Metadata ID
  * @return array|WP_Error Message on success, WP_Error otherwise
  */
 public function delete_meta($id, $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));
     }
     // 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 (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 (!delete_metadata_by_mid($this->type, $mid)) {
         return new WP_Error('json_meta_could_not_delete', __('Could not delete meta.'), array('status' => 500));
     }
     return array('message' => __('Deleted meta'));
 }
コード例 #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
 /**
  * revert File version
  * @author Ohad Raz
  * @since 2.0
  * @access public
  */
 public function ajax_revet_file()
 {
     check_ajax_referer('revert_file');
     $meta = get_metadata_by_mid('file', intval($_GET['mid']));
     if (!$meta) {
         echo json_encode(array('error' => __('Error restoring file version', 'ace')));
         die;
     }
     $meta = $meta->meta_value;
     $m = __('Make sure to save changes if you want the restore to take place.', 'ace');
     echo json_encode(array('version' => stripslashes($meta['version']), 'm' => $m));
     die;
 }
 /**
  * Delete meta from an object.
  *
  * @param WP_REST_Request $request
  * @return WP_REST_Response|WP_Error Message on success, WP_Error otherwise
  */
 public function delete_item($request)
 {
     $parent_id = (int) $request['parent_id'];
     $mid = (int) $request['id'];
     $force = isset($request['force']) ? (bool) $request['force'] : false;
     // We don't support trashing for this type, error out
     if (!$force) {
         return new WP_Error('rest_trash_not_supported', __('Meta does not support trashing.'), array('status' => 501));
     }
     $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}) !== (int) $parent_id) {
         return new WP_Error('rest_meta_' . $this->parent_type . '_mismatch', __('Meta does not belong to this object'), 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 (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 (!delete_metadata_by_mid($this->parent_type, $mid)) {
         return new WP_Error('rest_meta_could_not_delete', __('Could not delete meta.'), array('status' => 500));
     }
     /**
      * Fires after a meta value is deleted via the REST API.
      *
      * @param WP_REST_Request $request The request sent to the API.
      */
     do_action('rest_delete_meta', $request);
     return rest_ensure_response(array('message' => __('Deleted meta')));
 }
コード例 #16
0
 public function test_delete_item_no_trash()
 {
     wp_set_current_user($this->user);
     $this->allow_user_to_manage_multisite();
     $meta_id = add_user_meta($this->user, 'testkey', 'testvalue');
     $request = new WP_REST_Request('DELETE', sprintf('/wp/v2/users/%d/meta/%d', $this->user, $meta_id));
     $response = $this->server->dispatch($request);
     $this->assertErrorResponse('rest_trash_not_supported', $response, 501);
     // Ensure the meta still exists
     $meta = get_metadata_by_mid('user', $meta_id);
     $this->assertNotEmpty($meta);
 }
コード例 #17
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;
 }
コード例 #18
0
 public function test_delete_item_no_trash()
 {
     $post_id = $this->factory->post->create();
     $meta_id = add_post_meta($post_id, 'testkey', 'testvalue');
     $request = new WP_REST_Request('DELETE', sprintf('/wp/v2/posts/%d/meta/%d', $post_id, $meta_id));
     $response = $this->server->dispatch($request);
     $this->assertErrorResponse('rest_trash_not_supported', $response, 501);
     // Ensure the meta still exists
     $meta = get_metadata_by_mid('post', $meta_id);
     $this->assertNotEmpty($meta);
 }
コード例 #19
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)));
 }
コード例 #20
0
 /**
  * Delete meta from a post
  *
  * @param int $id Post ID
  * @param int $mid Metadata ID
  * @return array|WP_Error Message on success, WP_Error otherwise
  */
 public function delete_meta($id, $mid)
 {
     $id = (int) $id;
     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));
     }
     // 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 (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 (!delete_metadata_by_mid('post', $mid)) {
         return new WP_Error('json_meta_could_not_add', __('Could not delete post meta.'), array('status' => 500));
     }
     return array('message' => __('Deleted meta'));
 }
コード例 #21
0
 public function get_meta($id, $mid)
 {
     $id = (int) $id;
     if (empty($id)) {
         $this->set_status(404);
         return array('message' => __('Invalid post ID.'));
     }
     $post = get_post($id, ARRAY_A);
     if (empty($post['ID'])) {
         $this->set_status(404);
         return array('message' => __('Invalid post ID.'));
     }
     /* if ( ! $this->check_edit_permission( $post ) ) {
        return new WP_Error( 'json_cannot_edit', __( 'Sorry, you cannot edit this post' ), array( 'status' => 403 ) );
        } */
     $meta = get_metadata_by_mid('post', $mid);
     if (empty($meta)) {
         $this->set_status(404);
         return array('message' => __('Invalid post ID.'));
     }
     if (absint($meta->post_id) !== $id) {
         $this->set_status(400);
         return array('message' => __('Meta does not belong to this post.'));
     }
     return $this->prepare_meta($id, $meta);
 }
コード例 #22
0
ファイル: meta.php プロジェクト: nuevomediagroup/WordPress
/**
 * Delete meta data by meta ID
 *
 * @since 3.3.0
 *
 * @uses get_metadata_by_mid() Calls get_metadata_by_mid() to fetch the meta key, value
 *		and object_id of the given meta_id.
 *
 * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user)
 * @param int $meta_id ID for a specific meta row
 * @return bool True on successful delete, false on failure.
 */
function delete_metadata_by_mid($meta_type, $meta_id)
{
    global $wpdb;
    // Make sure everything is valid.
    if (!$meta_type) {
        return false;
    }
    if (!($meta_id = absint($meta_id))) {
        return false;
    }
    if (!($table = _get_meta_table($meta_type))) {
        return false;
    }
    // object and id columns
    $column = esc_sql($meta_type . '_id');
    $id_column = 'user' == $meta_type ? 'umeta_id' : 'meta_id';
    // Fetch the meta and go on if it's found.
    if ($meta = get_metadata_by_mid($meta_type, $meta_id)) {
        $object_id = $meta->{$column};
        do_action("delete_{$meta_type}_meta", (array) $meta_id, $object_id, $meta->meta_key, $meta->meta_value);
        if ('post' == $meta_type) {
            do_action('delete_postmeta', $meta_id);
        }
        // Run the query, will return true if deleted, false otherwise
        $result = (bool) $wpdb->query($wpdb->prepare("DELETE FROM {$table} WHERE {$id_column} = %d LIMIT 1;", $meta_id));
        // Clear the caches.
        wp_cache_delete($object_id, $meta_type . '_meta');
        do_action("deleted_{$meta_type}_meta", (array) $meta_id, $object_id, $meta->meta_key, $meta->meta_value);
        if ('post' == $meta_type) {
            do_action('deleted_postmeta', $meta_id);
        }
        return $result;
    }
    // Meta id was not found.
    return false;
}
コード例 #23
0
ファイル: post.php プロジェクト: nicholasgriffintn/WordPress
/**
 * Get post meta data by meta ID.
 *
 * @since 2.1.0
 *
 * @param int $mid
 * @return object|bool
 */
function get_post_meta_by_id($mid)
{
    return get_metadata_by_mid('post', $mid);
}
コード例 #24
0
/**
 * Delete meta data by meta ID
 *
 * @since 3.3.0
 *
 * @uses get_metadata_by_mid() Calls get_metadata_by_mid() to fetch the meta key, value
 *		and object_id of the given meta_id.
 *
 * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user)
 * @param int $meta_id ID for a specific meta row
 * @return bool True on successful delete, false on failure.
 */
function delete_metadata_by_mid($meta_type, $meta_id)
{
    global $wpdb;
    // Make sure everything is valid.
    if (!$meta_type) {
        return false;
    }
    if (!($meta_id = absint($meta_id))) {
        return false;
    }
    if (!($table = _get_meta_table($meta_type))) {
        return false;
    }
    // object and id columns
    $column = sanitize_key($meta_type . '_id');
    $id_column = 'user' == $meta_type ? 'umeta_id' : 'meta_id';
    // Fetch the meta and go on if it's found.
    if ($meta = get_metadata_by_mid($meta_type, $meta_id)) {
        $object_id = $meta->{$column};
        do_action("delete_{$meta_type}_meta", (array) $meta_id, $object_id, $meta->meta_key, $meta->meta_value);
        // Old-style action.
        if ('post' == $meta_type || 'comment' == $meta_type) {
            do_action("delete_{$meta_type}meta", $meta_id);
        }
        // Run the query, will return true if deleted, false otherwise
        $result = (bool) $wpdb->delete($table, array($id_column => $meta_id));
        // Clear the caches.
        wp_cache_delete($object_id, $meta_type . '_meta');
        do_action("deleted_{$meta_type}_meta", (array) $meta_id, $object_id, $meta->meta_key, $meta->meta_value);
        // Old-style action.
        if ('post' == $meta_type || 'comment' == $meta_type) {
            do_action("deleted_{$meta_type}meta", $meta_id);
        }
        return $result;
    }
    // Meta id was not found.
    return false;
}
コード例 #25
0
ファイル: ajax-actions.php プロジェクト: hughnet/WordPress
/**
 * 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();
}
コード例 #26
0
ファイル: MetaData.php プロジェクト: fia3876/iqmas-portal
 public function EventPostMetaUpdating($meta_id, $object_id, $meta_key)
 {
     static $meta_type = 'post';
     $this->old_meta[$meta_id] = (object) array('key' => ($meta = get_metadata_by_mid($meta_type, $meta_id)) ? $meta->meta_key : $meta_key, 'val' => get_metadata($meta_type, $object_id, $meta_key, true));
 }
コード例 #27
0
ファイル: meta.php プロジェクト: fia3876/iqmas-portal
/**
 * Delete meta data by meta ID
 *
 * @since 3.3.0
 *
 * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user)
 * @param int $meta_id ID for a specific meta row
 * @return bool True on successful delete, false on failure.
 */
function delete_metadata_by_mid($meta_type, $meta_id)
{
    global $wpdb;
    // Make sure everything is valid.
    if (!$meta_type || !is_numeric($meta_id)) {
        return false;
    }
    $meta_id = absint($meta_id);
    if (!$meta_id) {
        return false;
    }
    $table = _get_meta_table($meta_type);
    if (!$table) {
        return false;
    }
    // object and id columns
    $column = sanitize_key($meta_type . '_id');
    $id_column = 'user' == $meta_type ? 'umeta_id' : 'meta_id';
    // Fetch the meta and go on if it's found.
    if ($meta = get_metadata_by_mid($meta_type, $meta_id)) {
        $object_id = $meta->{$column};
        /** This action is documented in wp-includes/meta.php */
        do_action("delete_{$meta_type}_meta", (array) $meta_id, $object_id, $meta->meta_key, $meta->meta_value);
        // Old-style action.
        if ('post' == $meta_type || 'comment' == $meta_type) {
            /**
             * Fires immediately before deleting post or comment metadata of a specific type.
             *
             * The dynamic portion of the hook, `$meta_type`, refers to the meta
             * object type (post or comment).
             *
             * @since 3.4.0
             *
             * @param int $meta_id ID of the metadata entry to delete.
             */
            do_action("delete_{$meta_type}meta", $meta_id);
        }
        // Run the query, will return true if deleted, false otherwise
        $result = (bool) $wpdb->delete($table, array($id_column => $meta_id));
        // Clear the caches.
        wp_cache_delete($object_id, $meta_type . '_meta');
        /** This action is documented in wp-includes/meta.php */
        do_action("deleted_{$meta_type}_meta", (array) $meta_id, $object_id, $meta->meta_key, $meta->meta_value);
        // Old-style action.
        if ('post' == $meta_type || 'comment' == $meta_type) {
            /**
             * Fires immediately after deleting post or comment metadata of a specific type.
             *
             * The dynamic portion of the hook, `$meta_type`, refers to the meta
             * object type (post or comment).
             *
             * @since 3.4.0
             *
             * @param int $meta_ids Deleted metadata entry ID.
             */
            do_action("deleted_{$meta_type}meta", $meta_id);
        }
        return $result;
    }
    // Meta id was not found.
    return false;
}
 public function test_delete_item_no_trash()
 {
     wp_set_current_user($this->admin_id);
     $meta_id = add_comment_meta($this->approved_id, 'testkey', 'testvalue');
     $request = new WP_REST_Request('DELETE', sprintf('/wp/v2/comments/%d/meta/%d', $this->approved_id, $meta_id));
     $response = $this->server->dispatch($request);
     $this->assertErrorResponse('rest_trash_not_supported', $response, 501);
     // Ensure the meta still exists
     $meta = get_metadata_by_mid('comment', $meta_id);
     $this->assertNotEmpty($meta);
 }