class.wpcom-json-api-update-post-endpoint.php 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921
  1. <?php
  2. new WPCOM_JSON_API_Update_Post_Endpoint( array(
  3. 'description' => 'Create a post.',
  4. 'group' => 'posts',
  5. 'stat' => 'posts:new',
  6. 'new_version' => '1.2',
  7. 'max_version' => '1',
  8. 'method' => 'POST',
  9. 'path' => '/sites/%s/posts/new',
  10. 'path_labels' => array(
  11. '$site' => '(int|string) Site ID or domain',
  12. ),
  13. 'request_format' => array(
  14. // explicitly document all input
  15. 'date' => "(ISO 8601 datetime) The post's creation time.",
  16. 'title' => '(HTML) The post title.',
  17. 'content' => '(HTML) The post content.',
  18. 'excerpt' => '(HTML) An optional post excerpt.',
  19. 'slug' => '(string) The name (slug) for the post, used in URLs.',
  20. 'author' => '(string) The username or ID for the user to assign the post to.',
  21. 'publicize' => '(array|bool) True or false if the post be publicized to external services. An array of services if we only want to publicize to a select few. Defaults to true.',
  22. 'publicize_message' => '(string) Custom message to be publicized to external services.',
  23. 'status' => array(
  24. 'publish' => 'Publish the post.',
  25. 'private' => 'Privately publish the post.',
  26. 'draft' => 'Save the post as a draft.',
  27. 'pending' => 'Mark the post as pending editorial approval.',
  28. 'auto-draft' => 'Save a placeholder for a newly created post, with no content.',
  29. ),
  30. 'sticky' => array(
  31. 'false' => 'Post is not marked as sticky.',
  32. 'true' => 'Stick the post to the front page.',
  33. ),
  34. 'password' => '(string) The plaintext password protecting the post, or, more likely, the empty string if the post is not password protected.',
  35. 'parent' => "(int) The post ID of the new post's parent.",
  36. '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.",
  37. 'categories' => "(array|string) Comma-separated list or array of categories (name or id)",
  38. 'tags' => "(array|string) Comma-separated list or array of tags (name or id)",
  39. 'format' => array_merge( array( 'default' => 'Use default post format' ), get_post_format_strings() ),
  40. '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.",
  41. '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. <br /><br /><strong>Example</strong>:<br />" .
  42. "<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>",
  43. 'media_urls' => "(array) An array of URLs for images to attach to a post. Sideloads the media in for a post.",
  44. '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.",
  45. 'comments_open' => "(bool) Should the post be open to comments? Defaults to the blog's preference.",
  46. 'pings_open' => "(bool) Should the post be open to comments? Defaults to the blog's preference.",
  47. 'likes_enabled' => "(bool) Should the post be open to likes? Defaults to the blog's preference.",
  48. 'sharing_enabled' => "(bool) Should sharing buttons show on this post? Defaults to true.",
  49. 'menu_order' => "(int) (Pages Only) the order pages should appear in. Use 0 to maintain alphabetical order.",
  50. ),
  51. 'example_request' => 'https://public-api.wordpress.com/rest/v1/sites/82974409/posts/new/',
  52. 'example_request_data' => array(
  53. 'headers' => array(
  54. 'authorization' => 'Bearer YOUR_API_TOKEN'
  55. ),
  56. 'body' => array(
  57. 'title' => 'Hello World',
  58. 'content' => 'Hello. I am a test post. I was created by the API',
  59. 'tags' => 'tests',
  60. 'categories' => 'API'
  61. )
  62. )
  63. ) );
  64. new WPCOM_JSON_API_Update_Post_Endpoint( array(
  65. 'description' => 'Edit a post.',
  66. 'group' => 'posts',
  67. 'stat' => 'posts:1:POST',
  68. 'new_version' => '1.2',
  69. 'max_version' => '1',
  70. 'method' => 'POST',
  71. 'path' => '/sites/%s/posts/%d',
  72. 'path_labels' => array(
  73. '$site' => '(int|string) Site ID or domain',
  74. '$post_ID' => '(int) The post ID',
  75. ),
  76. 'request_format' => array(
  77. 'date' => "(ISO 8601 datetime) The post's creation time.",
  78. 'title' => '(HTML) The post title.',
  79. 'content' => '(HTML) The post content.',
  80. 'excerpt' => '(HTML) An optional post excerpt.',
  81. 'slug' => '(string) The name (slug) for the post, used in URLs.',
  82. 'author' => '(string) The username or ID for the user to assign the post to.',
  83. 'publicize' => '(array|bool) True or false if the post be publicized to external services. An array of services if we only want to publicize to a select few. Defaults to true.',
  84. 'publicize_message' => '(string) Custom message to be publicized to external services.',
  85. 'status' => array(
  86. 'publish' => 'Publish the post.',
  87. 'private' => 'Privately publish the post.',
  88. 'draft' => 'Save the post as a draft.',
  89. 'pending' => 'Mark the post as pending editorial approval.',
  90. 'trash' => 'Set the post as trashed.',
  91. ),
  92. 'sticky' => array(
  93. 'false' => 'Post is not marked as sticky.',
  94. 'true' => 'Stick the post to the front page.',
  95. ),
  96. 'password' => '(string) The plaintext password protecting the post, or, more likely, the empty string if the post is not password protected.',
  97. 'parent' => "(int) The post ID of the new post's parent.",
  98. 'categories' => "(array|string) Comma-separated list or array of categories (name or id)",
  99. 'tags' => "(array|string) Comma-separated list or array of tags (name or id)",
  100. 'format' => array_merge( array( 'default' => 'Use default post format' ), get_post_format_strings() ),
  101. 'comments_open' => '(bool) Should the post be open to comments?',
  102. 'pings_open' => '(bool) Should the post be open to comments?',
  103. 'likes_enabled' => "(bool) Should the post be open to likes?",
  104. 'menu_order' => "(int) (Pages Only) the order pages should appear in. Use 0 to maintain alphabetical order.",
  105. 'sharing_enabled' => "(bool) Should sharing buttons show on this post?",
  106. '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.",
  107. '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 />" .
  108. "<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>",
  109. 'media_urls' => "(array) An array of URLs for images to attach to a post. Sideloads the media in for a post.",
  110. '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.",
  111. ),
  112. 'example_request' => 'https://public-api.wordpress.com/rest/v1/sites/82974409/posts/881',
  113. 'example_request_data' => array(
  114. 'headers' => array(
  115. 'authorization' => 'Bearer YOUR_API_TOKEN'
  116. ),
  117. 'body' => array(
  118. 'title' => 'Hello World (Again)',
  119. 'content' => 'Hello. I am an edited post. I was edited by the API',
  120. 'tags' => 'tests',
  121. 'categories' => 'API'
  122. )
  123. )
  124. ) );
  125. new WPCOM_JSON_API_Update_Post_Endpoint( array(
  126. '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.',
  127. 'group' => 'posts',
  128. 'stat' => 'posts:1:delete',
  129. 'new_version' => '1.1',
  130. 'max_version' => '1',
  131. 'method' => 'POST',
  132. 'path' => '/sites/%s/posts/%d/delete',
  133. 'path_labels' => array(
  134. '$site' => '(int|string) Site ID or domain',
  135. '$post_ID' => '(int) The post ID',
  136. ),
  137. 'example_request' => 'https://public-api.wordpress.com/rest/v1/sites/82974409/posts/$post_ID/delete/',
  138. 'example_request_data' => array(
  139. 'headers' => array(
  140. 'authorization' => 'Bearer YOUR_API_TOKEN'
  141. )
  142. )
  143. ) );
  144. new WPCOM_JSON_API_Update_Post_Endpoint( array(
  145. 'description' => 'Restore a post or page from the trash to its previous status.',
  146. 'group' => 'posts',
  147. 'stat' => 'posts:1:restore',
  148. 'method' => 'POST',
  149. 'new_version' => '1.1',
  150. 'max_version' => '1',
  151. 'path' => '/sites/%s/posts/%d/restore',
  152. 'path_labels' => array(
  153. '$site' => '(int|string) Site ID or domain',
  154. '$post_ID' => '(int) The post ID',
  155. ),
  156. 'example_request' => 'https://public-api.wordpress.com/rest/v1/sites/82974409/posts/$post_ID/restore/',
  157. 'example_request_data' => array(
  158. 'headers' => array(
  159. 'authorization' => 'Bearer YOUR_API_TOKEN'
  160. )
  161. )
  162. ) );
  163. class WPCOM_JSON_API_Update_Post_Endpoint extends WPCOM_JSON_API_Post_Endpoint {
  164. function __construct( $args ) {
  165. parent::__construct( $args );
  166. if ( $this->api->ends_with( $this->path, '/delete' ) ) {
  167. $this->post_object_format['status']['deleted'] = 'The post has been deleted permanently.';
  168. }
  169. }
  170. // /sites/%s/posts/new -> $blog_id
  171. // /sites/%s/posts/%d -> $blog_id, $post_id
  172. // /sites/%s/posts/%d/delete -> $blog_id, $post_id
  173. // /sites/%s/posts/%d/restore -> $blog_id, $post_id
  174. function callback( $path = '', $blog_id = 0, $post_id = 0 ) {
  175. $blog_id = $this->api->switch_to_blog_and_validate_user( $this->api->get_blog_id( $blog_id ) );
  176. if ( is_wp_error( $blog_id ) ) {
  177. return $blog_id;
  178. }
  179. if ( $this->api->ends_with( $path, '/delete' ) ) {
  180. return $this->delete_post( $path, $blog_id, $post_id );
  181. } elseif ( $this->api->ends_with( $path, '/restore' ) ) {
  182. return $this->restore_post( $path, $blog_id, $post_id );
  183. } else {
  184. return $this->write_post( $path, $blog_id, $post_id );
  185. }
  186. }
  187. // /sites/%s/posts/new -> $blog_id
  188. // /sites/%s/posts/%d -> $blog_id, $post_id
  189. function write_post( $path, $blog_id, $post_id ) {
  190. $new = $this->api->ends_with( $path, '/new' );
  191. $args = $this->query_args();
  192. // unhook publicize, it's hooked again later -- without this, skipping services is impossible
  193. if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
  194. remove_action( 'save_post', array( $GLOBALS['publicize_ui']->publicize, 'async_publicize_post' ), 100, 2 );
  195. add_action( 'rest_api_inserted_post', array( $GLOBALS['publicize_ui']->publicize, 'async_publicize_post' ) );
  196. }
  197. if ( $new ) {
  198. $input = $this->input( true );
  199. if ( 'revision' === $input['type'] ) {
  200. if ( ! isset( $input['parent'] ) ) {
  201. return new WP_Error( 'invalid_input', 'Invalid request input', 400 );
  202. }
  203. $input['status'] = 'inherit'; // force inherit for revision type
  204. $input['slug'] = $input['parent'] . '-autosave-v1';
  205. }
  206. elseif ( !isset( $input['title'] ) && !isset( $input['content'] ) && !isset( $input['excerpt'] ) ) {
  207. return new WP_Error( 'invalid_input', 'Invalid request input', 400 );
  208. }
  209. // default to post
  210. if ( empty( $input['type'] ) )
  211. $input['type'] = 'post';
  212. $post_type = get_post_type_object( $input['type'] );
  213. if ( ! $this->is_post_type_allowed( $input['type'] ) ) {
  214. return new WP_Error( 'unknown_post_type', 'Unknown post type', 404 );
  215. }
  216. if ( ! empty( $input['author'] ) ) {
  217. $author_id = $this->parse_and_set_author( $input['author'], $input['type'] );
  218. unset( $input['author'] );
  219. if ( is_wp_error( $author_id ) )
  220. return $author_id;
  221. }
  222. if ( 'publish' === $input['status'] ) {
  223. if ( ! current_user_can( $post_type->cap->publish_posts ) ) {
  224. if ( current_user_can( $post_type->cap->edit_posts ) ) {
  225. $input['status'] = 'pending';
  226. } else {
  227. return new WP_Error( 'unauthorized', 'User cannot publish posts', 403 );
  228. }
  229. }
  230. } else {
  231. if ( !current_user_can( $post_type->cap->edit_posts ) ) {
  232. return new WP_Error( 'unauthorized', 'User cannot edit posts', 403 );
  233. }
  234. }
  235. } else {
  236. $input = $this->input( false );
  237. if ( !is_array( $input ) || !$input ) {
  238. return new WP_Error( 'invalid_input', 'Invalid request input', 400 );
  239. }
  240. if ( isset( $input['status'] ) && 'trash' === $input['status'] && ! current_user_can( 'delete_post', $post_id ) ) {
  241. return new WP_Error( 'unauthorized', 'User cannot delete post', 403 );
  242. }
  243. $post = get_post( $post_id );
  244. $_post_type = ( ! empty( $input['type'] ) ) ? $input['type'] : $post->post_type;
  245. $post_type = get_post_type_object( $_post_type );
  246. if ( !$post || is_wp_error( $post ) ) {
  247. return new WP_Error( 'unknown_post', 'Unknown post', 404 );
  248. }
  249. if ( !current_user_can( 'edit_post', $post->ID ) ) {
  250. return new WP_Error( 'unauthorized', 'User cannot edit post', 403 );
  251. }
  252. if ( ! empty( $input['author'] ) ) {
  253. $author_id = $this->parse_and_set_author( $input['author'], $_post_type );
  254. unset( $input['author'] );
  255. if ( is_wp_error( $author_id ) )
  256. return $author_id;
  257. }
  258. if ( ( isset( $input['status'] ) && 'publish' === $input['status'] ) && 'publish' !== $post->post_status && !current_user_can( 'publish_post', $post->ID ) ) {
  259. $input['status'] = 'pending';
  260. }
  261. $last_status = $post->post_status;
  262. $new_status = isset( $input['status'] ) ? $input['status'] : $last_status;
  263. // Make sure that drafts get the current date when transitioning to publish if not supplied in the post.
  264. $date_in_past = ( strtotime($post->post_date_gmt) < time() );
  265. if ( 'publish' === $new_status && 'draft' === $last_status && ! isset( $input['date_gmt'] ) && $date_in_past ) {
  266. $input['date_gmt'] = gmdate( 'Y-m-d H:i:s' );
  267. }
  268. }
  269. if ( function_exists( 'wpcom_switch_to_locale' ) ) {
  270. // fixes calypso-pre-oss #12476: respect blog locale when creating the post slug
  271. wpcom_switch_to_locale( get_blog_lang_code( $blog_id ) );
  272. }
  273. // If date was set, $this->input will set date_gmt, date still needs to be adjusted for the blog's offset
  274. if ( isset( $input['date_gmt'] ) ) {
  275. $gmt_offset = get_option( 'gmt_offset' );
  276. $time_with_offset = strtotime( $input['date_gmt'] ) + $gmt_offset * HOUR_IN_SECONDS;
  277. $input['date'] = date( 'Y-m-d H:i:s', $time_with_offset );
  278. }
  279. if ( ! empty( $author_id ) && get_current_user_id() != $author_id ) {
  280. if ( ! current_user_can( $post_type->cap->edit_others_posts ) ) {
  281. return new WP_Error( 'unauthorized', "User is not allowed to publish others' posts.", 403 );
  282. } elseif ( ! user_can( $author_id, $post_type->cap->edit_posts ) ) {
  283. return new WP_Error( 'unauthorized', 'Assigned author cannot publish post.', 403 );
  284. }
  285. }
  286. if ( !is_post_type_hierarchical( $post_type->name ) && 'revision' !== $post_type->name ) {
  287. unset( $input['parent'] );
  288. }
  289. $tax_input = array();
  290. foreach ( array( 'categories' => 'category', 'tags' => 'post_tag' ) as $key => $taxonomy ) {
  291. if ( ! isset( $input[ $key ] ) ) {
  292. continue;
  293. }
  294. $tax_input[ $taxonomy ] = array();
  295. $is_hierarchical = is_taxonomy_hierarchical( $taxonomy );
  296. if ( is_array( $input[$key] ) ) {
  297. $terms = $input[$key];
  298. } else {
  299. $terms = explode( ',', $input[$key] );
  300. }
  301. foreach ( $terms as $term ) {
  302. /**
  303. * `curl --data 'category[]=123'` should be interpreted as a category ID,
  304. * not a category whose name is '123'.
  305. *
  306. * Consequence: To add a category/tag whose name is '123', the client must
  307. * first look up its ID.
  308. */
  309. $term = (string) $term; // ctype_digit compat
  310. if ( ctype_digit( $term ) ) {
  311. $term = (int) $term;
  312. }
  313. $term_info = term_exists( $term, $taxonomy );
  314. if ( ! $term_info ) {
  315. // A term ID that doesn't already exist. Ignore it: we don't know what name to give it.
  316. if ( is_int( $term ) ){
  317. continue;
  318. }
  319. // only add a new tag/cat if the user has access to
  320. $tax = get_taxonomy( $taxonomy );
  321. // see https://core.trac.wordpress.org/ticket/26409
  322. if ( 'category' === $taxonomy && ! current_user_can( $tax->cap->edit_terms ) ) {
  323. continue;
  324. } else if ( ! current_user_can( $tax->cap->assign_terms ) ) {
  325. continue;
  326. }
  327. $term_info = wp_insert_term( $term, $taxonomy );
  328. }
  329. if ( ! is_wp_error( $term_info ) ) {
  330. if ( $is_hierarchical ) {
  331. // Categories must be added by ID
  332. $tax_input[$taxonomy][] = (int) $term_info['term_id'];
  333. } else {
  334. // Tags must be added by name
  335. if ( is_int( $term ) ) {
  336. $term = get_term( $term, $taxonomy );
  337. $tax_input[$taxonomy][] = $term->name;
  338. } else {
  339. $tax_input[$taxonomy][] = $term;
  340. }
  341. }
  342. }
  343. }
  344. }
  345. if ( isset( $input['categories'] ) && empty( $tax_input['category'] ) && 'revision' !== $post_type->name ) {
  346. $tax_input['category'][] = get_option( 'default_category' );
  347. }
  348. unset( $input['tags'], $input['categories'] );
  349. $insert = array();
  350. if ( !empty( $input['slug'] ) ) {
  351. $insert['post_name'] = $input['slug'];
  352. unset( $input['slug'] );
  353. }
  354. if ( isset( $input['comments_open'] ) ) {
  355. $insert['comment_status'] = ( true === $input['comments_open'] ) ? 'open' : 'closed';
  356. }
  357. if ( isset( $input['pings_open'] ) ) {
  358. $insert['ping_status'] = ( true === $input['pings_open'] ) ? 'open' : 'closed';
  359. }
  360. unset( $input['comments_open'], $input['pings_open'] );
  361. if ( isset( $input['menu_order'] ) ) {
  362. $insert['menu_order'] = $input['menu_order'];
  363. unset( $input['menu_order'] );
  364. }
  365. $publicize = isset( $input['publicize'] ) ? $input['publicize'] : null;
  366. unset( $input['publicize'] );
  367. $publicize_custom_message = isset( $input['publicize_message'] ) ? $input['publicize_message'] : null;
  368. unset( $input['publicize_message'] );
  369. if ( isset( $input['featured_image'] ) ) {
  370. $featured_image = trim( $input['featured_image'] );
  371. $delete_featured_image = empty( $featured_image );
  372. unset( $input['featured_image'] );
  373. }
  374. $metadata = isset( $input['metadata'] ) ? $input['metadata'] : null;
  375. unset( $input['metadata'] );
  376. $likes = isset( $input['likes_enabled'] ) ? $input['likes_enabled'] : null;
  377. unset( $input['likes_enabled'] );
  378. $sharing = isset( $input['sharing_enabled'] ) ? $input['sharing_enabled'] : null;
  379. unset( $input['sharing_enabled'] );
  380. $sticky = isset( $input['sticky'] ) ? $input['sticky'] : null;
  381. unset( $input['sticky'] );
  382. foreach ( $input as $key => $value ) {
  383. $insert["post_$key"] = $value;
  384. }
  385. if ( ! empty( $author_id ) ) {
  386. $insert['post_author'] = absint( $author_id );
  387. }
  388. if ( ! empty( $tax_input ) ) {
  389. $insert['tax_input'] = $tax_input;
  390. }
  391. $has_media = isset( $input['media'] ) && $input['media'] ? count( $input['media'] ) : false;
  392. $has_media_by_url = isset( $input['media_urls'] ) && $input['media_urls'] ? count( $input['media_urls'] ) : false;
  393. if ( $new ) {
  394. if ( isset( $input['content'] ) && ! has_shortcode( $input['content'], 'gallery' ) && ( $has_media || $has_media_by_url ) ) {
  395. switch ( ( $has_media + $has_media_by_url ) ) {
  396. case 0 :
  397. // No images - do nothing.
  398. break;
  399. case 1 :
  400. // 1 image - make it big
  401. $insert['post_content'] = $input['content'] = "[gallery size=full columns=1]\n\n" . $input['content'];
  402. break;
  403. default :
  404. // Several images - 3 column gallery
  405. $insert['post_content'] = $input['content'] = "[gallery]\n\n" . $input['content'];
  406. break;
  407. }
  408. }
  409. $post_id = wp_insert_post( add_magic_quotes( $insert ), true );
  410. } else {
  411. $insert['ID'] = $post->ID;
  412. // wp_update_post ignores date unless edit_date is set
  413. // See: http://codex.wordpress.org/Function_Reference/wp_update_post#Scheduling_posts
  414. // See: https://core.trac.wordpress.org/browser/tags/3.9.2/src/wp-includes/post.php#L3302
  415. if ( isset( $input['date_gmt'] ) || isset( $input['date'] ) ) {
  416. $insert['edit_date'] = true;
  417. }
  418. // this two-step process ensures any changes submitted along with status=trash get saved before trashing
  419. if ( isset( $input['status'] ) && 'trash' === $input['status'] ) {
  420. // if we insert it with status='trash', it will get double-trashed, so insert it as a draft first
  421. unset( $insert['status'] );
  422. $post_id = wp_update_post( (object) $insert );
  423. // now call wp_trash_post so post_meta gets set and any filters get called
  424. wp_trash_post( $post_id );
  425. } else {
  426. $post_id = wp_update_post( (object) $insert );
  427. }
  428. }
  429. if ( !$post_id || is_wp_error( $post_id ) ) {
  430. return $post_id;
  431. }
  432. // make sure this post actually exists and is not an error of some kind (ie, trying to load media in the posts endpoint)
  433. $post_check = $this->get_post_by( 'ID', $post_id, $args['context'] );
  434. if ( is_wp_error( $post_check ) ) {
  435. return $post_check;
  436. }
  437. if ( $has_media ) {
  438. $this->api->trap_wp_die( 'upload_error' );
  439. foreach ( $input['media'] as $media_item ) {
  440. $_FILES['.api.media.item.'] = $media_item;
  441. // check for WP_Error if we ever actually need $media_id
  442. $media_id = media_handle_upload( '.api.media.item.', $post_id );
  443. }
  444. $this->api->trap_wp_die( null );
  445. unset( $_FILES['.api.media.item.'] );
  446. }
  447. if ( $has_media_by_url ) {
  448. foreach ( $input['media_urls'] as $url ) {
  449. $this->handle_media_sideload( $url, $post_id );
  450. }
  451. }
  452. // Set like status for the post
  453. /** This filter is documented in modules/likes.php */
  454. $sitewide_likes_enabled = (bool) apply_filters( 'wpl_is_enabled_sitewide', ! get_option( 'disabled_likes' ) );
  455. if ( $new ) {
  456. if ( $sitewide_likes_enabled ) {
  457. if ( false === $likes ) {
  458. update_post_meta( $post_id, 'switch_like_status', 1 );
  459. } else {
  460. delete_post_meta( $post_id, 'switch_like_status' );
  461. }
  462. } else {
  463. if ( $likes ) {
  464. update_post_meta( $post_id, 'switch_like_status', 1 );
  465. } else {
  466. delete_post_meta( $post_id, 'switch_like_status' );
  467. }
  468. }
  469. } else {
  470. if ( isset( $likes ) ) {
  471. if ( $sitewide_likes_enabled ) {
  472. if ( false === $likes ) {
  473. update_post_meta( $post_id, 'switch_like_status', 1 );
  474. } else {
  475. delete_post_meta( $post_id, 'switch_like_status' );
  476. }
  477. } else {
  478. if ( true === $likes ) {
  479. update_post_meta( $post_id, 'switch_like_status', 1 );
  480. } else {
  481. delete_post_meta( $post_id, 'switch_like_status' );
  482. }
  483. }
  484. }
  485. }
  486. // Set sharing status of the post
  487. if ( $new ) {
  488. $sharing_enabled = isset( $sharing ) ? (bool) $sharing : true;
  489. if ( false === $sharing_enabled ) {
  490. update_post_meta( $post_id, 'sharing_disabled', 1 );
  491. }
  492. }
  493. else {
  494. if ( isset( $sharing ) && true === $sharing ) {
  495. delete_post_meta( $post_id, 'sharing_disabled' );
  496. } else if ( isset( $sharing ) && false == $sharing ) {
  497. update_post_meta( $post_id, 'sharing_disabled', 1 );
  498. }
  499. }
  500. if ( isset( $sticky ) ) {
  501. if ( true === $sticky ) {
  502. stick_post( $post_id );
  503. } else {
  504. unstick_post( $post_id );
  505. }
  506. }
  507. // WPCOM Specific (Jetpack's will get bumped elsewhere
  508. // Tracks how many posts are published and sets meta
  509. // so we can track some other cool stats (like likes & comments on posts published)
  510. if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
  511. if (
  512. ( $new && 'publish' == $input['status'] )
  513. || (
  514. ! $new && isset( $last_status )
  515. && 'publish' != $last_status
  516. && isset( $new_status )
  517. && 'publish' == $new_status
  518. )
  519. ) {
  520. /** This action is documented in modules/widgets/social-media-icons.php */
  521. do_action( 'jetpack_bump_stats_extras', 'api-insights-posts', $this->api->token_details['client_id'] );
  522. update_post_meta( $post_id, '_rest_api_published', 1 );
  523. update_post_meta( $post_id, '_rest_api_client_id', $this->api->token_details['client_id'] );
  524. }
  525. }
  526. // We ask the user/dev to pass Publicize services he/she wants activated for the post, but Publicize expects us
  527. // to instead flag the ones we don't want to be skipped. proceed with said logic.
  528. // any posts coming from Path (client ID 25952) should also not publicize
  529. if ( $publicize === false || ( isset( $this->api->token_details['client_id'] ) && 25952 == $this->api->token_details['client_id'] ) ) {
  530. // No publicize at all, skip all by ID
  531. foreach ( $GLOBALS['publicize_ui']->publicize->get_services( 'all' ) as $name => $service ) {
  532. delete_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $name );
  533. $service_connections = $GLOBALS['publicize_ui']->publicize->get_connections( $name );
  534. if ( ! $service_connections ) {
  535. continue;
  536. }
  537. foreach ( $service_connections as $service_connection ) {
  538. update_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $service_connection->unique_id, 1 );
  539. }
  540. }
  541. } else if ( is_array( $publicize ) && ( count ( $publicize ) > 0 ) ) {
  542. foreach ( $GLOBALS['publicize_ui']->publicize->get_services( 'all' ) as $name => $service ) {
  543. /*
  544. * We support both indexed and associative arrays:
  545. * * indexed are to pass entire services
  546. * * associative are to pass specific connections per service
  547. *
  548. * We do support mixed arrays: mixed integer and string keys (see 3rd example below).
  549. *
  550. * EG: array( 'twitter', 'facebook') will only publicize to those, ignoring the other available services
  551. * Form data: publicize[]=twitter&publicize[]=facebook
  552. * 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.
  553. * Form data: publicize[twitter]=$pub_conn_id_0,$pub_conn_id_3&publicize[facebook]=$pub_conn_id_7
  554. * 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
  555. * Form data: publicize[]=twitter&publicize[facebook]=$pub_conn_id_0,$pub_conn_id_3
  556. */
  557. // Delete any stale SKIP value for the service by name. We'll add it back by ID.
  558. delete_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $name );
  559. // Get the user's connections
  560. $service_connections = $GLOBALS['publicize_ui']->publicize->get_connections( $name );
  561. // if the user doesn't have any connections for this service, move on
  562. if ( ! $service_connections ) {
  563. continue;
  564. }
  565. if ( !in_array( $name, $publicize ) && !array_key_exists( $name, $publicize ) ) {
  566. // Skip the whole service by adding each connection ID
  567. foreach ( $service_connections as $service_connection ) {
  568. update_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $service_connection->unique_id, 1 );
  569. }
  570. } else if ( !empty( $publicize[ $name ] ) ) {
  571. // Seems we're being asked to only push to [a] specific connection[s].
  572. // Explode the list on commas, which will also support a single passed ID
  573. $requested_connections = explode( ',', ( preg_replace( '/[\s]*/', '', $publicize[ $name ] ) ) );
  574. // Flag the connections we can't match with the requested list to be skipped.
  575. foreach ( $service_connections as $service_connection ) {
  576. if ( !in_array( $service_connection->meta['connection_data']->id, $requested_connections ) ) {
  577. update_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $service_connection->unique_id, 1 );
  578. } else {
  579. delete_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $service_connection->unique_id );
  580. }
  581. }
  582. } else {
  583. // delete all SKIP values; it's okay to publish to all connected IDs for this service
  584. foreach ( $service_connections as $service_connection ) {
  585. delete_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $service_connection->unique_id );
  586. }
  587. }
  588. }
  589. }
  590. if ( ! is_null( $publicize_custom_message ) ) {
  591. if ( empty( $publicize_custom_message ) ) {
  592. delete_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_MESS );
  593. } else {
  594. update_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_MESS, trim( $publicize_custom_message ) );
  595. }
  596. }
  597. if ( ! empty( $insert['post_format'] ) ) {
  598. if ( 'default' !== strtolower( $insert['post_format'] ) ) {
  599. set_post_format( $post_id, $insert['post_format'] );
  600. }
  601. else {
  602. set_post_format( $post_id, get_option( 'default_post_format' ) );
  603. }
  604. }
  605. if ( isset( $featured_image ) ) {
  606. $this->parse_and_set_featured_image( $post_id, $delete_featured_image, $featured_image );
  607. }
  608. if ( ! empty( $metadata ) ) {
  609. foreach ( (array) $metadata as $meta ) {
  610. $meta = (object) $meta;
  611. // Custom meta description can only be set on sites that have a business subscription.
  612. if ( Jetpack_SEO_Posts::DESCRIPTION_META_KEY == $meta->key && ! Jetpack_SEO_Utils::is_enabled_jetpack_seo() ) {
  613. return new WP_Error( 'unauthorized', __( 'SEO tools are not enabled for this site.', 'jetpack' ), 403 );
  614. }
  615. $existing_meta_item = new stdClass;
  616. if ( empty( $meta->operation ) )
  617. $meta->operation = 'update';
  618. if ( ! empty( $meta->value ) ) {
  619. if ( 'true' == $meta->value )
  620. $meta->value = true;
  621. if ( 'false' == $meta->value )
  622. $meta->value = false;
  623. }
  624. if ( ! empty( $meta->id ) ) {
  625. $meta->id = absint( $meta->id );
  626. $existing_meta_item = get_metadata_by_mid( 'post', $meta->id );
  627. if ( $post_id !== (int) $existing_meta_item->post_id ) {
  628. // Only allow updates for metadata on this post
  629. continue;
  630. }
  631. }
  632. $unslashed_meta_key = wp_unslash( $meta->key ); // should match what the final key will be
  633. $meta->key = wp_slash( $meta->key );
  634. $unslashed_existing_meta_key = wp_unslash( $existing_meta_item->meta_key );
  635. $existing_meta_item->meta_key = wp_slash( $existing_meta_item->meta_key );
  636. // make sure that the meta id passed matches the existing meta key
  637. if ( ! empty( $meta->id ) && ! empty( $meta->key ) ) {
  638. $meta_by_id = get_metadata_by_mid( 'post', $meta->id );
  639. if ( $meta_by_id->meta_key !== $meta->key ) {
  640. continue; // skip this meta
  641. }
  642. }
  643. switch ( $meta->operation ) {
  644. case 'delete':
  645. if ( ! empty( $meta->id ) && ! empty( $existing_meta_item->meta_key ) && current_user_can( 'delete_post_meta', $post_id, $unslashed_existing_meta_key ) ) {
  646. delete_metadata_by_mid( 'post', $meta->id );
  647. } elseif ( ! empty( $meta->key ) && ! empty( $meta->previous_value ) && current_user_can( 'delete_post_meta', $post_id, $unslashed_meta_key ) ) {
  648. delete_post_meta( $post_id, $meta->key, $meta->previous_value );
  649. } elseif ( ! empty( $meta->key ) && current_user_can( 'delete_post_meta', $post_id, $unslashed_meta_key ) ) {
  650. delete_post_meta( $post_id, $meta->key );
  651. }
  652. break;
  653. case 'add':
  654. if ( ! empty( $meta->id ) || ! empty( $meta->previous_value ) ) {
  655. continue;
  656. } 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 ) ) {
  657. add_post_meta( $post_id, $meta->key, $meta->value );
  658. }
  659. break;
  660. case 'update':
  661. if ( ! isset( $meta->value ) ) {
  662. continue;
  663. } 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 ) ) ) {
  664. update_metadata_by_mid( 'post', $meta->id, $meta->value );
  665. } 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 ) ) ) {
  666. update_post_meta( $post_id, $meta->key,$meta->value, $meta->previous_value );
  667. } elseif ( ! empty( $meta->key ) && ( current_user_can( 'edit_post_meta', $post_id, $unslashed_meta_key ) || WPCOM_JSON_API_Metadata::is_public( $meta->key ) ) ) {
  668. update_post_meta( $post_id, $meta->key, $meta->value );
  669. }
  670. break;
  671. }
  672. }
  673. }
  674. /**
  675. * Fires when a post is created via the REST API.
  676. *
  677. * @module json-api
  678. *
  679. * @since 2.3.0
  680. *
  681. * @param int $post_id Post ID.
  682. * @param array $insert Data used to build the post.
  683. * @param string $new New post URL suffix.
  684. */
  685. do_action( 'rest_api_inserted_post', $post_id, $insert, $new );
  686. $return = $this->get_post_by( 'ID', $post_id, $args['context'] );
  687. if ( !$return || is_wp_error( $return ) ) {
  688. return $return;
  689. }
  690. if ( isset( $input['type'] ) && 'revision' === $input['type'] ) {
  691. $return['preview_nonce'] = wp_create_nonce( 'post_preview_' . $input['parent'] );
  692. }
  693. if ( isset( $sticky ) ) {
  694. // workaround for sticky test occasionally failing, maybe a race condition with stick_post() above
  695. $return['sticky'] = ( true === $sticky );
  696. }
  697. /** This action is documented in json-endpoints/class.wpcom-json-api-site-settings-endpoint.php */
  698. do_action( 'wpcom_json_api_objects', 'posts' );
  699. return $return;
  700. }
  701. // /sites/%s/posts/%d/delete -> $blog_id, $post_id
  702. function delete_post( $path, $blog_id, $post_id ) {
  703. $post = get_post( $post_id );
  704. if ( !$post || is_wp_error( $post ) ) {
  705. return new WP_Error( 'unknown_post', 'Unknown post', 404 );
  706. }
  707. if ( ! $this->is_post_type_allowed( $post->post_type ) ) {
  708. return new WP_Error( 'unknown_post_type', 'Unknown post type', 404 );
  709. }
  710. if ( !current_user_can( 'delete_post', $post->ID ) ) {
  711. return new WP_Error( 'unauthorized', 'User cannot delete posts', 403 );
  712. }
  713. $args = $this->query_args();
  714. $return = $this->get_post_by( 'ID', $post->ID, $args['context'] );
  715. if ( !$return || is_wp_error( $return ) ) {
  716. return $return;
  717. }
  718. /** This action is documented in json-endpoints/class.wpcom-json-api-site-settings-endpoint.php */
  719. do_action( 'wpcom_json_api_objects', 'posts' );
  720. // we need to call wp_trash_post so that untrash will work correctly for all post types
  721. if ( 'trash' === $post->post_status )
  722. wp_delete_post( $post->ID );
  723. else
  724. wp_trash_post( $post->ID );
  725. $status = get_post_status( $post->ID );
  726. if ( false === $status ) {
  727. $return['status'] = 'deleted';
  728. return $return;
  729. }
  730. return $this->get_post_by( 'ID', $post->ID, $args['context'] );
  731. }
  732. // /sites/%s/posts/%d/restore -> $blog_id, $post_id
  733. function restore_post( $path, $blog_id, $post_id ) {
  734. $args = $this->query_args();
  735. $post = get_post( $post_id );
  736. if ( !$post || is_wp_error( $post ) ) {
  737. return new WP_Error( 'unknown_post', 'Unknown post', 404 );
  738. }
  739. if ( !current_user_can( 'delete_post', $post->ID ) ) {
  740. return new WP_Error( 'unauthorized', 'User cannot restore trashed posts', 403 );
  741. }
  742. /** This action is documented in json-endpoints/class.wpcom-json-api-site-settings-endpoint.php */
  743. do_action( 'wpcom_json_api_objects', 'posts' );
  744. wp_untrash_post( $post->ID );
  745. return $this->get_post_by( 'ID', $post->ID, $args['context'] );
  746. }
  747. private function parse_and_set_featured_image( $post_id, $delete_featured_image, $featured_image ) {
  748. if ( $delete_featured_image ) {
  749. delete_post_thumbnail( $post_id );
  750. return;
  751. }
  752. $featured_image = (string) $featured_image;
  753. // if we got a post ID, we can just set it as the thumbnail
  754. if ( ctype_digit( $featured_image ) && 'attachment' == get_post_type( $featured_image ) ) {
  755. set_post_thumbnail( $post_id, $featured_image );
  756. return $featured_image;
  757. }
  758. $featured_image_id = $this->handle_media_sideload( $featured_image, $post_id, 'image' );
  759. if ( empty( $featured_image_id ) || ! is_int( $featured_image_id ) )
  760. return false;
  761. set_post_thumbnail( $post_id, $featured_image_id );
  762. return $featured_image_id;
  763. }
  764. private function parse_and_set_author( $author = null, $post_type = 'post' ) {
  765. if ( empty( $author ) || ! post_type_supports( $post_type, 'author' ) )
  766. return get_current_user_id();
  767. $author = (string) $author;
  768. if ( ctype_digit( $author ) ) {
  769. $_user = get_user_by( 'id', $author );
  770. if ( ! $_user || is_wp_error( $_user ) )
  771. return new WP_Error( 'invalid_author', 'Invalid author provided' );
  772. return $_user->ID;
  773. }
  774. $_user = get_user_by( 'login', $author );
  775. if ( ! $_user || is_wp_error( $_user ) )
  776. return new WP_Error( 'invalid_author', 'Invalid author provided' );
  777. return $_user->ID;
  778. }
  779. }