class.wpcom-json-api-update-post-v1-1-endpoint.php 45.9 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName
/**
 * Update post endpoint v1.1
 *
 * Endpoints:
 * Create a post:  /sites/%s/posts/new
 * Update a post:  /sites/%s/posts/%d
 * Delete a post:  /sites/%s/posts/%d/delete
 * Restore a post: /sites/%s/posts/%d/restore
 */

new WPCOM_JSON_API_Update_Post_v1_1_Endpoint(
	array(
		'description'          => 'Create a post.',
		'group'                => 'posts',
		'stat'                 => 'posts:new',
		'new_version'          => '1.2',
		'min_version'          => '1.1',
		'max_version'          => '1.1',
		'method'               => 'POST',
		'path'                 => '/sites/%s/posts/new',
		'path_labels'          => array(
			'$site' => '(int|string) Site ID or domain',
		),

		'request_format'       => array(
			// explicitly document all input.
			'date'              => "(ISO 8601 datetime) The post's creation time.",
			'title'             => '(HTML) The post title.',
			'content'           => '(HTML) The post content.',
			'excerpt'           => '(HTML) An optional post excerpt.',
			'slug'              => '(string) The name (slug) for the post, used in URLs.',
			'author'            => '(string) The username or ID for the user to assign the post to.',
			'publicize'         => '(array|bool) True or false if the post be shared to external services. An array of services if we only want to share to a select few. Defaults to true.',
			'publicize_message' => '(string) Custom message to be shared to external services.',
			'status'            => array(
				'publish'    => 'Publish the post.',
				'private'    => 'Privately publish the post.',
				'draft'      => 'Save the post as a draft.',
				'pending'    => 'Mark the post as pending editorial approval.',
				'future'     => 'Schedule the post (alias for publish; you must also set a future date).',
				'auto-draft' => 'Save a placeholder for a newly created post, with no content.',
			),
			'sticky'            => array(
				'false' => 'Post is not marked as sticky.',
				'true'  => 'Stick the post to the front page.',
			),
			'password'          => '(string) The plaintext password protecting the post, or, more likely, the empty string if the post is not password protected.',
			'parent'            => "(int) The post ID of the new post's parent.",
			'type'              => "(string) The post type. Defaults to 'post'. Post types besides post and page need to be whitelisted using the <code>rest_api_allowed_post_types</code> filter.",
			'terms'             => '(object) Mapping of taxonomy to comma-separated list or array of terms (name or id)',
			'categories'        => '(array|string) Comma-separated list or array of categories (name or id)',
			'tags'              => '(array|string) Comma-separated list or array of tags (name or id)',
			'format'            => array_merge( array( 'default' => 'Use default post format' ), get_post_format_strings() ),
			'featured_image'    => '(string) The post ID of an existing attachment to set as the featured image. Pass an empty string to delete the existing image.',
			'media'             => '(media) An array of files to attach to the post. To upload media, the entire request should be multipart/form-data encoded. Multiple media items will be displayed in a gallery. Accepts  jpg, jpeg, png, gif, pdf, doc, ppt, odt, pptx, docx, pps, ppsx, xls, xlsx, key. Audio and Video may also be available. See <code>allowed_file_types</code> in the options response of the site endpoint. Errors produced by media uploads, if any, will be in `media_errors` in the response. <br /><br /><strong>Example</strong>:<br />' .
							"<code>curl \<br />--form 'title=Image Post' \<br />--form 'media[0]=@/path/to/file.jpg' \<br />--form 'media_attrs[0][caption]=My Great Photo' \<br />-H 'Authorization: BEARER your-token' \<br />'https://public-api.wordpress.com/rest/v1/sites/123/posts/new'</code>",
			'media_urls'        => '(array) An array of URLs for images to attach to a post. Sideloads the media in for a post. Errors produced by media sideloading, if any, will be in `media_errors` in the response.',
			'media_attrs'       => '(array) An array of attributes (`title`, `description` and `caption`) are supported to assign to the media uploaded via the `media` or `media_urls` properties. You must use a numeric index for the keys of `media_attrs` which follow the same sequence as `media` and `media_urls`. <br /><br /><strong>Example</strong>:<br />' .
							"<code>curl \<br />--form 'title=Gallery Post' \<br />--form 'media[]=@/path/to/file1.jpg' \<br />--form 'media_urls[]=http://exapmple.com/file2.jpg' \<br /> \<br />--form 'media_attrs[0][caption]=This will be the caption for file1.jpg' \<br />--form 'media_attrs[1][title]=This will be the title for file2.jpg' \<br />-H 'Authorization: BEARER your-token' \<br />'https://public-api.wordpress.com/rest/v1/sites/123/posts/new'</code>",
			'metadata'          => '(array) Array of metadata objects containing the following properties: `key` (metadata key), `id` (meta ID), `previous_value` (if set, the action will only occur for the provided previous value), `value` (the new value to set the meta to), `operation` (the operation to perform: `update` or `add`; defaults to `update`). All unprotected meta keys are available by default for read requests. Both unprotected and protected meta keys are avaiable for authenticated requests with proper capabilities. Protected meta keys can be made available with the <code>rest_api_allowed_public_metadata</code> filter.',
			'discussion'        => '(object) A hash containing one or more of the following boolean values, which default to the blog\'s discussion preferences: `comments_open`, `pings_open`',
			'likes_enabled'     => "(bool) Should the post be open to likes? Defaults to the blog's preference.",
			'sharing_enabled'   => '(bool) Should sharing buttons show on this post? Defaults to true.',
			'menu_order'        => '(int) (Pages Only) the order pages should appear in. Use 0 to maintain alphabetical order.',
			'page_template'     => '(string) (Pages Only) The page template this page should use.',
		),

		'example_request'      => 'https://public-api.wordpress.com/rest/v1.1/sites/82974409/posts/new/',

		'example_request_data' => array(
			'headers' => array(
				'authorization' => 'Bearer YOUR_API_TOKEN',
			),

			'body'    => array(
				'title'      => 'Hello World',
				'content'    => 'Hello. I am a test post. I was created by the API',
				'tags'       => 'tests',
				'categories' => 'API',
			),
		),
	)
);

new WPCOM_JSON_API_Update_Post_v1_1_Endpoint(
	array(
		'description'          => 'Edit a post.',
		'group'                => 'posts',
		'stat'                 => 'posts:1:POST',
		'new_version'          => '1.2',
		'min_version'          => '1.1',
		'max_version'          => '1.1',
		'method'               => 'POST',
		'path'                 => '/sites/%s/posts/%d',
		'path_labels'          => array(
			'$site'    => '(int|string) Site ID or domain',
			'$post_ID' => '(int) The post ID',
		),

		'request_format'       => array(
			'date'              => "(ISO 8601 datetime) The post's creation time.",
			'title'             => '(HTML) The post title.',
			'content'           => '(HTML) The post content.',
			'excerpt'           => '(HTML) An optional post excerpt.',
			'slug'              => '(string) The name (slug) for the post, used in URLs.',
			'author'            => '(string) The username or ID for the user to assign the post to.',
			'publicize'         => '(array|bool) True or false if the post be shared to external services. An array of services if we only want to share to a select few. Defaults to true.',
			'publicize_message' => '(string) Custom message to be shared to external services.',
			'status'            => array(
				'publish' => 'Publish the post.',
				'private' => 'Privately publish the post.',
				'draft'   => 'Save the post as a draft.',
				'future'  => 'Schedule the post (alias for publish; you must also set a future date).',
				'pending' => 'Mark the post as pending editorial approval.',
				'trash'   => 'Set the post as trashed.',
			),
			'sticky'            => array(
				'false' => 'Post is not marked as sticky.',
				'true'  => 'Stick the post to the front page.',
			),
			'password'          => '(string) The plaintext password protecting the post, or, more likely, the empty string if the post is not password protected.',
			'parent'            => "(int) The post ID of the new post's parent.",
			'terms'             => '(object) Mapping of taxonomy to comma-separated list or array of terms (name or id)',
			'categories'        => '(array|string) Comma-separated list or array of categories (name or id)',
			'tags'              => '(array|string) Comma-separated list or array of tags (name or id)',
			'format'            => array_merge( array( 'default' => 'Use default post format' ), get_post_format_strings() ),
			'discussion'        => '(object) A hash containing one or more of the following boolean values, which default to the blog\'s discussion preferences: `comments_open`, `pings_open`',
			'likes_enabled'     => '(bool) Should the post be open to likes?',
			'menu_order'        => '(int) (Pages only) the order pages should appear in. Use 0 to maintain alphabetical order.',
			'page_template'     => '(string) (Pages Only) The page template this page should use.',
			'sharing_enabled'   => '(bool) Should sharing buttons show on this post?',
			'featured_image'    => '(string) The post ID of an existing attachment to set as the featured image. Pass an empty string to delete the existing image.',
			'media'             => '(media) An array of files to attach to the post. To upload media, the entire request should be multipart/form-data encoded. Multiple media items will be displayed in a gallery. Accepts  jpg, jpeg, png, gif, pdf, doc, ppt, odt, pptx, docx, pps, ppsx, xls, xlsx, key. Audio and Video may also be available. See <code>allowed_file_types</code> in the options resposne of the site endpoint. <br /><br /><strong>Example</strong>:<br />' .
							"<code>curl \<br />--form 'title=Image' \<br />--form 'media[]=@/path/to/file.jpg' \<br />-H 'Authorization: BEARER your-token' \<br />'https://public-api.wordpress.com/rest/v1/sites/123/posts/new'</code>",
			'media_urls'        => '(array) An array of URLs for images to attach to a post. Sideloads the media in for a post.',
			'metadata'          => '(array) Array of metadata objects containing the following properties: `key` (metadata key), `id` (meta ID), `previous_value` (if set, the action will only occur for the provided previous value), `value` (the new value to set the meta to), `operation` (the operation to perform: `update` or `add`; defaults to `update`). All unprotected meta keys are available by default for read requests. Both unprotected and protected meta keys are available for authenticated requests with proper capabilities. Protected meta keys can be made available with the <code>rest_api_allowed_public_metadata</code> filter.',
		),

		'example_request'      => 'https://public-api.wordpress.com/rest/v1.1/sites/82974409/posts/881',

		'example_request_data' => array(
			'headers' => array(
				'authorization' => 'Bearer YOUR_API_TOKEN',
			),

			'body'    => array(
				'title'      => 'Hello World (Again)',
				'content'    => 'Hello. I am an edited post. I was edited by the API',
				'tags'       => 'tests',
				'categories' => 'API',
			),
		),
	)
);

new WPCOM_JSON_API_Update_Post_v1_1_Endpoint(
	array(
		'description'          => 'Delete a post. Note: If the trash is enabled, this request will send the post to the trash. A second request will permanently delete the post.',
		'group'                => 'posts',
		'stat'                 => 'posts:1:delete',
		'min_version'          => '1.1',
		'max_version'          => '1.1',
		'method'               => 'POST',
		'path'                 => '/sites/%s/posts/%d/delete',
		'path_labels'          => array(
			'$site'    => '(int|string) Site ID or domain',
			'$post_ID' => '(int) The post ID',
		),

		'example_request'      => 'https://public-api.wordpress.com/rest/v1.1/sites/82974409/posts/$post_ID/delete/',

		'example_request_data' => array(
			'headers' => array(
				'authorization' => 'Bearer YOUR_API_TOKEN',
			),
		),
	)
);

new WPCOM_JSON_API_Update_Post_v1_1_Endpoint(
	array(
		'description'          => 'Restore a post or page from the trash to its previous status.',
		'group'                => 'posts',
		'stat'                 => 'posts:1:restore',
		'min_version'          => '1.1',
		'max_version'          => '1.1',
		'method'               => 'POST',
		'path'                 => '/sites/%s/posts/%d/restore',
		'path_labels'          => array(
			'$site'    => '(int|string) Site ID or domain',
			'$post_ID' => '(int) The post ID',
		),

		'example_request'      => 'https://public-api.wordpress.com/rest/v1.1/sites/82974409/posts/$post_ID/restore/',

		'example_request_data' => array(
			'headers' => array(
				'authorization' => 'Bearer YOUR_API_TOKEN',
			),
		),
	)
);

// phpcs:disable PEAR.NamingConventions.ValidClassName.Invalid
/**
 * Update post v1.1 endpoint class.
 */
class WPCOM_JSON_API_Update_Post_v1_1_Endpoint extends WPCOM_JSON_API_Post_v1_1_Endpoint {
	/**
	 * WPCOM_JSON_API_Update_Post_v1_1_Endpoint constructor.
	 *
	 * @param array $args Args.
	 */
	public function __construct( $args ) {
		parent::__construct( $args );
		if ( $this->api->ends_with( $this->path, '/delete' ) ) {
			$this->post_object_format['status']['deleted'] = 'The post has been deleted permanently.';
		}
	}

	/**
	 * Update post API v1.1 callback.
	 *
	 * /sites/%s/posts/new        -> $blog_id
	 * /sites/%s/posts/%d         -> $blog_id, $post_id
	 * /sites/%s/posts/%d/delete  -> $blog_id, $post_id
	 * /sites/%s/posts/%d/restore -> $blog_id, $post_id
	 *
	 * @param string $path API path.
	 * @param int    $blog_id Blog ID.
	 * @param int    $post_id Post ID.
	 *
	 * @return array|bool|WP_Error
	 */
	public function callback( $path = '', $blog_id = 0, $post_id = 0 ) {
		$blog_id = $this->api->switch_to_blog_and_validate_user( $this->api->get_blog_id( $blog_id ) );
		if ( is_wp_error( $blog_id ) ) {
			return $blog_id;
		}

		if ( $this->api->ends_with( $path, '/delete' ) ) {
			return $this->delete_post( $path, $blog_id, $post_id );
		} elseif ( $this->api->ends_with( $path, '/restore' ) ) {
			return $this->restore_post( $path, $blog_id, $post_id );
		} else {
			return $this->write_post( $path, $blog_id, $post_id );
		}
	}

	/**
	 * Create or update a post.
	 *
	 * /sites/%s/posts/new -> $blog_id
	 * /sites/%s/posts/%d  -> $blog_id, $post_id
	 *
	 * @param string $path API path.
	 * @param int    $blog_id Blog ID.
	 * @param int    $post_id Post ID.
	 */
	public function write_post( $path, $blog_id, $post_id ) {
		global $wpdb;

		$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 ( $this->should_load_theme_functions( $post_id ) ) {
				$this->load_theme_functions();
			}
		}

		if ( $new ) {
			$input = $this->input( true );

			// 'future' is an alias for 'publish' for now
			if ( 'future' === $input['status'] ) {
				$input['status'] = 'publish';
			}

			// default to post.
			if ( empty( $input['type'] ) ) {
				$input['type'] = 'post';
			}

			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 );
			}

			$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 );
					}
				}
			} elseif ( ! 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 );
			}

			if ( isset( $input['status'] ) && 'trash' === $input['status'] && ! current_user_can( 'delete_post', $post_id ) ) {
				return new WP_Error( 'unauthorized', 'User cannot delete post', 403 );
			}

			// 'future' is an alias for 'publish' for now
			if ( isset( $input['status'] ) && 'future' === $input['status'] ) {
				$input['status'] = 'publish';
			}

			$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.
			// Similarly, scheduled posts that are manually published before their scheduled date should have the date reset.
			$date_in_past         = ( strtotime( $post->post_date_gmt ) < time() );
			$reset_draft_date     = 'publish' === $new_status && 'draft' === $last_status && ! isset( $input['date_gmt'] ) && $date_in_past;
			$reset_scheduled_date = 'publish' === $new_status && 'future' === $last_status && ! isset( $input['date_gmt'] ) && ! $date_in_past;

			if ( $reset_draft_date || $reset_scheduled_date ) {
				$input['date_gmt'] = gmdate( 'Y-m-d H:i:s' );
			}

			// Untrash a post so that the proper hooks get called as well as the comments get untrashed.
			if ( $this->should_untrash_post( $last_status, $new_status, $post ) ) {
				$input = $this->untrash_post( $post, $input );
			}
		}

		if ( function_exists( 'wpcom_switch_to_blog_locale' ) ) {
			// fixes calypso-pre-oss #12476: respect blog locale when creating the post slug.
			wpcom_switch_to_blog_locale( $blog_id );
		}

		// 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']    = gmdate( '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'] );
		}

		$input['terms'] = isset( $input['terms'] ) ? (array) $input['terms'] : array();

		// Convert comma-separated terms to array before attempting to
		// merge with hardcoded taxonomies.
		foreach ( $input['terms'] as $taxonomy => $terms ) {
			if ( is_string( $terms ) ) {
				$input['terms'][ $taxonomy ] = explode( ',', $terms );
			} elseif ( ! is_array( $terms ) ) {
				$input['terms'][ $taxonomy ] = array();
			}
		}

		// For each hard-coded taxonomy, merge into terms object.
		foreach ( array(
			'categories' => 'category',
			'tags'       => 'post_tag',
		) as $taxonomy_key => $taxonomy ) {
			if ( ! isset( $input[ $taxonomy_key ] ) ) {
				continue;
			}

			if ( ! isset( $input['terms'][ $taxonomy ] ) ) {
				$input['terms'][ $taxonomy ] = array();
			}

			$terms = $input[ $taxonomy_key ];
			if ( is_string( $terms ) ) {
				$terms = explode( ',', $terms );
			} elseif ( ! is_array( $terms ) ) {
				continue;
			}

			$input['terms'][ $taxonomy ] = array_merge(
				$input['terms'][ $taxonomy ],
				$terms
			);
		}

		$tax_input = array();

		foreach ( $input['terms'] as $taxonomy => $terms ) {
			$tax_input[ $taxonomy ] = array();
			$is_hierarchical        = is_taxonomy_hierarchical( $taxonomy );

			foreach ( $terms as $term ) {
				/**
				 * `curl --data 'terms[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.
				 */
				$term = (string) $term; // ctype_digit compat.
				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 );

					// see https://core.trac.wordpress.org/ticket/26409 .
					if ( $is_hierarchical && ! current_user_can( $tax->cap->edit_terms ) ) {
						continue;
					} elseif ( ! current_user_can( $tax->cap->assign_terms ) ) {
						continue;
					}

					$term_info = wp_insert_term( $term, $taxonomy );
				}

				if ( ! is_wp_error( $term_info ) ) {
					if ( $is_hierarchical ) {
						// Hierarchical terms must be added by ID.
						$tax_input[ $taxonomy ][] = (int) $term_info['term_id'];
					} elseif ( is_int( $term ) ) { // Non-hierarchical terms must be added by name.
						$term                     = get_term( $term, $taxonomy );
						$tax_input[ $taxonomy ][] = $term->name;
					} else {
						$tax_input[ $taxonomy ][] = $term;
					}
				}
			}
		}

		if ( isset( $input['terms']['category'] ) && empty( $tax_input['category'] ) && 'revision' !== $post_type->name ) {
			$tax_input['category'][] = get_option( 'default_category' );
		}

		unset( $input['terms'], $input['tags'], $input['categories'] );

		$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' ), true ) ) {
					$insert[ $discussion_status ] = $discussion[ $discussion_status ];
				}
			}
		}

		unset( $input['discussion'] );

		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        = ! empty( $input['media'] ) ? count( $input['media'] ) : false;
		$has_media_by_url = ! empty( $input['media_urls'] ) ? count( $input['media_urls'] ) : false;

		$media_id_string = '';
		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();
			$media_results   = $this->handle_media_creation_v1_1( $media_files, $media_urls, $media_attrs );
			$media_id_string = join( ',', array_filter( array_map( 'absint', $media_results['media_ids'] ) ) );
		}

		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
						$input['content']       = sprintf(
							"[gallery size=full ids='%s' columns=1]\n\n",
							$media_id_string
						) . $input['content'];
						$insert['post_content'] = $input['content'];
						break;
					default:
						// Several images - 3 column gallery.
						$input['content']       = sprintf(
							"[gallery ids='%s']\n\n",
							$media_id_string
						) . $input['content'];
						$insert['post_content'] = $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: https://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;
			}

			// this two-step process ensures any changes submitted along with status=trash get saved before trashing.
			if ( isset( $input['status'] ) && 'trash' === $input['status'] ) {
				// if we insert it with status='trash', it will get double-trashed, so insert it as a draft first.
				unset( $insert['status'] );
				$post_id = wp_update_post( (object) $insert );
				// now call wp_trash_post so post_meta gets set and any filters get called.
				wp_trash_post( $post_id );
			} else {
				$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 ( $media_id_string ) {
			// Yes - this is really how wp-admin does it.
			$wpdb->query(
				$wpdb->prepare(
					"UPDATE $wpdb->posts SET post_parent = %d WHERE post_type = 'attachment' AND ID IN ( $media_id_string )", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- IDs are filtered to absint above.
					$post_id
				)
			);
			foreach ( $media_results['media_ids'] as $media_id ) {
				clean_attachment_cache( $media_id );
			}
			clean_post_cache( $post_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.
		/** 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', 0 );
				} else {
					delete_post_meta( $post_id, 'switch_like_status' );
				}
			} elseif ( $likes ) {
				update_post_meta( $post_id, 'switch_like_status', 1 );
			} else {
				delete_post_meta( $post_id, 'switch_like_status' );
			}
		} elseif ( isset( $likes ) ) {
			if ( $sitewide_likes_enabled ) {
				if ( false === $likes ) {
					update_post_meta( $post_id, 'switch_like_status', 0 );
				} else {
					delete_post_meta( $post_id, 'switch_like_status' );
				}
			} elseif ( 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 );
			}
		} elseif ( isset( $sharing ) && true === $sharing ) {
			delete_post_meta( $post_id, 'sharing_disabled' );
		} elseif ( isset( $sharing ) && false == $sharing ) { // phpcs:ignore Universal.Operators.StrictComparisons.LooseEqual
			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
				)
			) {
				/** This action is documented in modules/widgets/social-media-icons.php */
				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 ( false === $publicize || ( isset( $this->api->token_details['client_id'] ) && 25952 === (int) $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 );
				}
			}
		} elseif ( 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, true ) && ! 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 );
					}
				} elseif ( ! 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, true ) ) {
							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 ( $publicize_custom_message !== null ) {
			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;

				if (
					in_array( $meta->key, Jetpack_SEO_Posts::POST_META_KEYS_ARRAY, true ) &&
					! Jetpack_SEO_Utils::is_enabled_jetpack_seo()
				) {
					return new WP_Error( 'unauthorized', __( 'SEO tools are not enabled for this site.', 'jetpack' ), 403 );
				}

				$existing_meta_item = new stdClass();

				if ( empty( $meta->operation ) ) {
					$meta->operation = 'update';
				}

				if ( ! empty( $meta->value ) ) {
					if ( 'true' == $meta->value ) { // phpcs:ignore Universal.Operators.StrictComparisons.LooseEqual
						$meta->value = true;
					}
					if ( 'false' == $meta->value ) { // phpcs:ignore Universal.Operators.StrictComparisons.LooseEqual
						$meta->value = false;
					}
				}

				if ( ! empty( $meta->id ) ) {
					$meta->id           = absint( $meta->id );
					$existing_meta_item = get_metadata_by_mid( 'post', $meta->id );
					if ( $post_id !== (int) $existing_meta_item->post_id ) {
						// Only allow updates for metadata on this post.
						continue;
					}
				}

				$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 ) ) {
							break;
						} elseif ( ! empty( $meta->key ) && ! empty( $meta->value ) && ( current_user_can( 'add_post_meta', $post_id, $unslashed_meta_key ) ) || WPCOM_JSON_API_Metadata::is_public( $meta->key ) ) {
							add_post_meta( $post_id, $meta->key, $meta->value );
						}

						break;
					case 'update':
						if ( ! isset( $meta->value ) ) {
							break;
						} elseif ( ! empty( $meta->id ) && ! empty( $existing_meta_item->meta_key ) && ( current_user_can( 'edit_post_meta', $post_id, $unslashed_existing_meta_key ) || WPCOM_JSON_API_Metadata::is_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 ) || WPCOM_JSON_API_Metadata::is_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 ) || WPCOM_JSON_API_Metadata::is_public( $meta->key ) ) ) {
							update_post_meta( $post_id, $meta->key, $meta->value );
						}

						break;
				}
			}
		}

		/** This action is documented in json-endpoints/class.wpcom-json-api-update-post-endpoint.php */
		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 );
		}

		if ( ! empty( $media_results['errors'] ) ) {
			$return['media_errors'] = $media_results['errors'];
		}

		if ( 'publish' !== $post->post_status ) {
			$sal_site             = $this->get_sal_post_by( 'ID', $post_id, $args['context'] );
			$return['other_URLs'] = (object) $sal_site->get_permalink_suggestions( $input['title'] );
		}

		/** This action is documented in json-endpoints/class.wpcom-json-api-site-settings-endpoint.php */
		do_action( 'wpcom_json_api_objects', 'posts' );

		return $return;
	}

	/**
	 * Delete a post.
	 *
	 * /sites/%s/posts/%d/delete -> $blog_id, $post_id
	 *
	 * @param string $path API path.
	 * @param array  $blog_id Blog ID.
	 * @param array  $post_id Post ID.
	 *
	 * @return array|WP_Error
	 */
	public function delete_post( $path, $blog_id, $post_id ) {
		$post = get_post( $post_id );
		if ( ! $post || is_wp_error( $post ) ) {
			return new WP_Error( 'unknown_post', 'Unknown post', 404 );
		}

		if ( ! $this->is_post_type_allowed( $post->post_type ) ) {
			return new WP_Error( 'unknown_post_type', 'Unknown post type', 404 );
		}

		if ( ! current_user_can( 'delete_post', $post->ID ) ) {
			return new WP_Error( 'unauthorized', 'User cannot delete posts', 403 );
		}

		$args   = $this->query_args();
		$return = $this->get_post_by( 'ID', $post->ID, $args['context'] );
		if ( ! $return || is_wp_error( $return ) ) {
			return $return;
		}

		/** This action is documented in json-endpoints/class.wpcom-json-api-site-settings-endpoint.php */
		do_action( 'wpcom_json_api_objects', 'posts' );

		// we need to call wp_trash_post so that untrash will work correctly for all post types.
		if ( 'trash' === $post->post_status ) {
			wp_delete_post( $post->ID );
		} else {
			wp_trash_post( $post->ID );
		}

		$status = get_post_status( $post->ID );
		if ( false === $status ) {
			$return['status'] = 'deleted';
			return $return;
		}

		return $this->get_post_by( 'ID', $post->ID, $args['context'] );
	}

	/**
	 * Restore a post.
	 *
	 * /sites/%s/posts/%d/restore -> $blog_id, $post_id
	 *
	 * @param string $path API path.
	 * @param int    $blog_id Blog ID.
	 * @param int    $post_id Post ID.
	 *
	 * @return array|WP_Error
	 */
	public function restore_post( $path, $blog_id, $post_id ) {
		$args = $this->query_args();
		$post = get_post( $post_id );

		if ( ! $post || is_wp_error( $post ) ) {
			return new WP_Error( 'unknown_post', 'Unknown post', 404 );
		}

		if ( ! current_user_can( 'delete_post', $post->ID ) ) {
			return new WP_Error( 'unauthorized', 'User cannot restore trashed posts', 403 );
		}

		/** This action is documented in json-endpoints/class.wpcom-json-api-site-settings-endpoint.php */
		do_action( 'wpcom_json_api_objects', 'posts' );

		wp_untrash_post( $post->ID );

		return $this->get_post_by( 'ID', $post->ID, $args['context'] );
	}

	/**
	 * Set or delete a post's featured image.
	 *
	 * @param int  $post_id Post ID.
	 * @param bool $delete_featured_image Whether to delete the featured image.
	 * @param int  $featured_image Thumbnail ID to attach.
	 *
	 * @return null|int|bool
	 */
	protected function parse_and_set_featured_image( $post_id, $delete_featured_image, $featured_image ) {
		if ( $delete_featured_image ) {
			delete_post_thumbnail( $post_id );
			return;
		}

		$featured_image = (string) $featured_image;

		// if we got a post ID, we can just set it as the thumbnail.
		if ( ctype_digit( $featured_image ) && 'attachment' === get_post_type( $featured_image ) ) {
			set_post_thumbnail( $post_id, $featured_image );
			return $featured_image;
		}

		$featured_image_id = $this->handle_media_sideload( $featured_image, $post_id, 'image' );

		if ( empty( $featured_image_id ) || ! is_int( $featured_image_id ) ) {
			return false;
		}

		set_post_thumbnail( $post_id, $featured_image_id );
		return $featured_image_id;
	}

	/**
	 * Get the Author ID for a post.
	 *
	 * @param int|string $author Author ID.
	 * @param string     $post_type Post type.
	 *
	 * @return int|WP_Error
	 */
	protected function parse_and_set_author( $author = null, $post_type = 'post' ) {
		if ( empty( $author ) || ! post_type_supports( $post_type, 'author' ) ) {
			return get_current_user_id();
		}

		$author = (string) $author;
		if ( ctype_digit( $author ) ) {
			$_user = get_user_by( 'id', $author );
			if ( ! $_user || is_wp_error( $_user ) ) {
				return new WP_Error( 'invalid_author', 'Invalid author provided' );
			}

			return $_user->ID;
		}

		$_user = get_user_by( 'login', $author );
		if ( ! $_user || is_wp_error( $_user ) ) {
			return new WP_Error( 'invalid_author', 'Invalid author provided' );
		}

		return $_user->ID;
	}

	/**
	 * Determine if a post can be untrashed.
	 *
	 * @param string  $last_status Last post status.
	 * @param string  $new_status New post status.
	 * @param WP_Post $post Post.
	 *
	 * @return bool
	 */
	protected function should_untrash_post( $last_status, $new_status, $post ) {
		return 'trash' === $last_status && 'trash' !== $new_status && isset( $post->ID );
	}

	/**
	 * Untrash a post.
	 *
	 * @param WP_Post $post Post to untrash.
	 * @param array   $input POST body data.
	 */
	protected function untrash_post( $post, $input ) {
		wp_untrash_post( $post->ID );
		$untrashed_post = get_post( $post->ID );
		// Lets make sure that we use the reverted the slug.
		if ( isset( $untrashed_post->post_name ) && $untrashed_post->post_name . '__trashed' === $input['slug'] ) {
			unset( $input['slug'] );
		}
		return $input;
	}

	/**
	 * Determine if a theme's functions.php file should be loaded.
	 *
	 * @param int $post_id Post ID.
	 *
	 * @return bool
	 */
	protected function should_load_theme_functions( $post_id = null ) {
		if ( empty( $post_id ) ) {
			$input = $this->input( true );
			$type  = $input['type'];
		} else {
			$type = get_post_type( $post_id );
		}

		return ! empty( $type ) && ! in_array( $type, array( 'post', 'revision' ), true );
	}
}