Keine Beschreibung

class.wpcom-json-api-update-post-v1-2-endpoint.php 42KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994
  1. <?php
  2. new WPCOM_JSON_API_Update_Post_v1_2_Endpoint( array(
  3. 'description' => 'Create a post.',
  4. 'group' => 'posts',
  5. 'stat' => 'posts:new',
  6. 'min_version' => '1.2',
  7. 'max_version' => '1.2',
  8. 'method' => 'POST',
  9. 'path' => '/sites/%s/posts/new',
  10. 'path_labels' => array(
  11. '$site' => '(int|string) Site ID or domain',
  12. ),
  13. 'query_parameters' => array(
  14. 'autosave' => '(bool) True if the post was saved automatically.',
  15. ),
  16. 'request_format' => array(
  17. // explicitly document all input
  18. 'date' => "(ISO 8601 datetime) The post's creation time.",
  19. 'title' => '(HTML) The post title.',
  20. 'content' => '(HTML) The post content.',
  21. 'excerpt' => '(HTML) An optional post excerpt.',
  22. 'slug' => '(string) The name (slug) for the post, used in URLs.',
  23. 'author' => '(string) The username or ID for the user to assign the post to.',
  24. '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.',
  25. 'publicize_message' => '(string) Custom message to be publicized to external services.',
  26. 'status' => array(
  27. 'publish' => 'Publish the post.',
  28. 'private' => 'Privately publish the post.',
  29. 'draft' => 'Save the post as a draft.',
  30. 'pending' => 'Mark the post as pending editorial approval.',
  31. 'future' => 'Schedule the post (alias for publish; you must also set a future date).',
  32. 'auto-draft' => 'Save a placeholder for a newly created post, with no content.',
  33. ),
  34. 'sticky' => array(
  35. 'false' => 'Post is not marked as sticky.',
  36. 'true' => 'Stick the post to the front page.',
  37. ),
  38. 'password' => '(string) The plaintext password protecting the post, or, more likely, the empty string if the post is not password protected.',
  39. 'parent' => "(int) The post ID of the new post's parent.",
  40. '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.",
  41. 'terms' => '(object) Mapping of taxonomy to comma-separated list or array of term names',
  42. 'categories' => "(array|string) Comma-separated list or array of category names",
  43. 'tags' => "(array|string) Comma-separated list or array of tag names",
  44. 'terms_by_id' => '(object) Mapping of taxonomy to comma-separated list or array of term IDs',
  45. 'categories_by_id' => "(array|string) Comma-separated list or array of category IDs",
  46. 'tags_by_id' => "(array|string) Comma-separated list or array of tag IDs",
  47. 'format' => array_merge( array( 'default' => 'Use default post format' ), get_post_format_strings() ),
  48. '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.",
  49. '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 />" .
  50. "<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>",
  51. '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.",
  52. '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 />" .
  53. "<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>",
  54. '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.",
  55. '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`',
  56. 'likes_enabled' => "(bool) Should the post be open to likes? Defaults to the blog's preference.",
  57. 'sharing_enabled' => "(bool) Should sharing buttons show on this post? Defaults to true.",
  58. 'menu_order' => "(int) (Pages Only) the order pages should appear in. Use 0 to maintain alphabetical order.",
  59. 'page_template' => '(string) (Pages Only) The page template this page should use.',
  60. ),
  61. 'example_request' => 'https://public-api.wordpress.com/rest/v1.2/sites/82974409/posts/new/',
  62. 'example_request_data' => array(
  63. 'headers' => array(
  64. 'authorization' => 'Bearer YOUR_API_TOKEN'
  65. ),
  66. 'body' => array(
  67. 'title' => 'Hello World',
  68. 'content' => 'Hello. I am a test post. I was created by the API',
  69. 'tags' => 'tests',
  70. 'categories' => 'API'
  71. )
  72. )
  73. ) );
  74. new WPCOM_JSON_API_Update_Post_v1_2_Endpoint( array(
  75. 'description' => 'Edit a post.',
  76. 'group' => 'posts',
  77. 'stat' => 'posts:1:POST',
  78. 'min_version' => '1.2',
  79. 'max_version' => '1.2',
  80. 'method' => 'POST',
  81. 'path' => '/sites/%s/posts/%d',
  82. 'path_labels' => array(
  83. '$site' => '(int|string) Site ID or domain',
  84. '$post_ID' => '(int) The post ID',
  85. ),
  86. 'query_parameters' => array(
  87. 'autosave' => '(bool) True if the post was saved automatically.',
  88. ),
  89. 'request_format' => array(
  90. 'date' => "(ISO 8601 datetime) The post's creation time.",
  91. 'title' => '(HTML) The post title.',
  92. 'content' => '(HTML) The post content.',
  93. 'excerpt' => '(HTML) An optional post excerpt.',
  94. 'slug' => '(string) The name (slug) for the post, used in URLs.',
  95. 'author' => '(string) The username or ID for the user to assign the post to.',
  96. '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.',
  97. 'publicize_message' => '(string) Custom message to be publicized to external services.',
  98. 'status' => array(
  99. 'publish' => 'Publish the post.',
  100. 'private' => 'Privately publish the post.',
  101. 'draft' => 'Save the post as a draft.',
  102. 'future' => 'Schedule the post (alias for publish; you must also set a future date).',
  103. 'pending' => 'Mark the post as pending editorial approval.',
  104. 'trash' => 'Set the post as trashed.',
  105. ),
  106. 'sticky' => array(
  107. 'false' => 'Post is not marked as sticky.',
  108. 'true' => 'Stick the post to the front page.',
  109. ),
  110. 'password' => '(string) The plaintext password protecting the post, or, more likely, the empty string if the post is not password protected.',
  111. 'parent' => "(int) The post ID of the new post's parent.",
  112. 'terms' => '(object) Mapping of taxonomy to comma-separated list or array of term names',
  113. 'terms_by_id' => '(object) Mapping of taxonomy to comma-separated list or array of term IDs',
  114. 'categories' => "(array|string) Comma-separated list or array of category names",
  115. 'categories_by_id' => "(array|string) Comma-separated list or array of category IDs",
  116. 'tags' => "(array|string) Comma-separated list or array of tag names",
  117. 'tags_by_id' => "(array|string) Comma-separated list or array of tag IDs",
  118. 'format' => array_merge( array( 'default' => 'Use default post format' ), get_post_format_strings() ),
  119. '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`',
  120. 'likes_enabled' => "(bool) Should the post be open to likes?",
  121. 'menu_order' => "(int) (Pages only) the order pages should appear in. Use 0 to maintain alphabetical order.",
  122. 'page_template' => '(string) (Pages Only) The page template this page should use.',
  123. 'sharing_enabled' => "(bool) Should sharing buttons show on this post?",
  124. '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.",
  125. '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 />" .
  126. "<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>",
  127. 'media_urls' => "(array) An array of URLs for images to attach to a post. Sideloads the media in for a post.",
  128. '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.",
  129. ),
  130. 'example_request' => 'https://public-api.wordpress.com/rest/v1.2/sites/82974409/posts/881',
  131. 'example_request_data' => array(
  132. 'headers' => array(
  133. 'authorization' => 'Bearer YOUR_API_TOKEN'
  134. ),
  135. 'body' => array(
  136. 'title' => 'Hello World (Again)',
  137. 'content' => 'Hello. I am an edited post. I was edited by the API',
  138. 'tags' => 'tests',
  139. 'categories' => 'API'
  140. )
  141. )
  142. ) );
  143. use function \Automattic\Jetpack\Extensions\Map\map_block_from_geo_points;
  144. class WPCOM_JSON_API_Update_Post_v1_2_Endpoint extends WPCOM_JSON_API_Update_Post_v1_1_Endpoint {
  145. // /sites/%s/posts/new -> $blog_id
  146. // /sites/%s/posts/%d -> $blog_id, $post_id
  147. function write_post( $path, $blog_id, $post_id ) {
  148. global $wpdb;
  149. $new = $this->api->ends_with( $path, '/new' );
  150. $args = $this->query_args();
  151. if ( ! empty( $args['autosave'] ) ) {
  152. define( 'DOING_AUTOSAVE', true );
  153. }
  154. // unhook publicize, it's hooked again later -- without this, skipping services is impossible
  155. if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
  156. remove_action( 'save_post', array( $GLOBALS['publicize_ui']->publicize, 'async_publicize_post' ), 100, 2 );
  157. add_action( 'rest_api_inserted_post', array( $GLOBALS['publicize_ui']->publicize, 'async_publicize_post' ) );
  158. if ( $this->should_load_theme_functions( $post_id ) ) {
  159. $this->load_theme_functions();
  160. }
  161. }
  162. if ( $new ) {
  163. $input = $this->input( true );
  164. // 'future' is an alias for 'publish' for now
  165. if ( isset( $input['status'] ) && 'future' === $input['status'] ) {
  166. $input['status'] = 'publish';
  167. }
  168. if ( 'revision' === $input['type'] ) {
  169. if ( ! isset( $input['parent'] ) ) {
  170. return new WP_Error( 'invalid_input', 'Invalid request input', 400 );
  171. }
  172. $input['status'] = 'inherit'; // force inherit for revision type
  173. $input['slug'] = $input['parent'] . '-autosave-v1';
  174. }
  175. elseif ( !isset( $input['title'] ) && !isset( $input['content'] ) && !isset( $input['excerpt'] ) ) {
  176. return new WP_Error( 'invalid_input', 'Invalid request input', 400 );
  177. }
  178. // default to post
  179. if ( empty( $input['type'] ) )
  180. $input['type'] = 'post';
  181. $post_type = get_post_type_object( $input['type'] );
  182. if ( ! $this->is_post_type_allowed( $input['type'] ) ) {
  183. return new WP_Error( 'unknown_post_type', 'Unknown post type', 404 );
  184. }
  185. if ( ! empty( $input['author'] ) ) {
  186. $author_id = parent::parse_and_set_author( $input['author'], $input['type'] );
  187. unset( $input['author'] );
  188. if ( is_wp_error( $author_id ) )
  189. return $author_id;
  190. }
  191. if ( 'publish' === $input['status'] ) {
  192. if ( ! current_user_can( $post_type->cap->publish_posts ) ) {
  193. if ( current_user_can( $post_type->cap->edit_posts ) ) {
  194. $input['status'] = 'pending';
  195. } else {
  196. return new WP_Error( 'unauthorized', 'User cannot publish posts', 403 );
  197. }
  198. }
  199. } else {
  200. if ( !current_user_can( $post_type->cap->edit_posts ) ) {
  201. return new WP_Error( 'unauthorized', 'User cannot edit posts', 403 );
  202. }
  203. }
  204. } else {
  205. $input = $this->input( false );
  206. if ( !is_array( $input ) || !$input ) {
  207. return new WP_Error( 'invalid_input', 'Invalid request input', 400 );
  208. }
  209. if ( isset( $input['status'] ) && 'trash' === $input['status'] && ! current_user_can( 'delete_post', $post_id ) ) {
  210. return new WP_Error( 'unauthorized', 'User cannot delete post', 403 );
  211. }
  212. // 'future' is an alias for 'publish' for now
  213. if ( isset( $input['status'] ) && 'future' === $input['status'] ) {
  214. $input['status'] = 'publish';
  215. }
  216. $post = get_post( $post_id );
  217. $_post_type = ( ! empty( $input['type'] ) ) ? $input['type'] : $post->post_type;
  218. $post_type = get_post_type_object( $_post_type );
  219. if ( !$post || is_wp_error( $post ) ) {
  220. return new WP_Error( 'unknown_post', 'Unknown post', 404 );
  221. }
  222. if ( !current_user_can( 'edit_post', $post->ID ) ) {
  223. return new WP_Error( 'unauthorized', 'User cannot edit post', 403 );
  224. }
  225. if ( ! empty( $input['author'] ) ) {
  226. $author_id = parent::parse_and_set_author( $input['author'], $_post_type );
  227. unset( $input['author'] );
  228. if ( is_wp_error( $author_id ) )
  229. return $author_id;
  230. }
  231. if ( ( isset( $input['status'] ) && 'publish' === $input['status'] ) && 'publish' !== $post->post_status && !current_user_can( 'publish_post', $post->ID ) ) {
  232. $input['status'] = 'pending';
  233. }
  234. $last_status = $post->post_status;
  235. $new_status = isset( $input['status'] ) ? $input['status'] : $last_status;
  236. // Make sure that drafts get the current date when transitioning to publish if not supplied in the post.
  237. // Similarly, scheduled posts that are manually published before their scheduled date should have the date reset.
  238. $date_in_past = ( strtotime($post->post_date_gmt) < time() );
  239. $reset_draft_date = 'publish' === $new_status && 'draft' === $last_status && ! isset( $input['date_gmt'] ) && $date_in_past;
  240. $reset_scheduled_date = 'publish' === $new_status && 'future' === $last_status && ! isset( $input['date_gmt'] ) && ! $date_in_past;
  241. if ( $reset_draft_date || $reset_scheduled_date ) {
  242. $input['date_gmt'] = gmdate( 'Y-m-d H:i:s' );
  243. }
  244. // Untrash a post so that the proper hooks get called as well as the comments get untrashed.
  245. if ( $this->should_untrash_post( $last_status, $new_status, $post ) ) {
  246. $input = $this->untrash_post( $post, $input );
  247. }
  248. }
  249. if ( function_exists( 'wpcom_switch_to_blog_locale' ) ) {
  250. // fixes calypso-pre-oss #12476: respect blog locale when creating the post slug
  251. wpcom_switch_to_blog_locale( $blog_id );
  252. }
  253. // If date is set, $this->input will set date_gmt, date still needs to be adjusted f
  254. if ( isset( $input['date_gmt'] ) ) {
  255. $gmt_offset = get_option( 'gmt_offset' );
  256. $time_with_offset = strtotime( $input['date_gmt'] ) + $gmt_offset * HOUR_IN_SECONDS;
  257. $input['date'] = date( 'Y-m-d H:i:s', $time_with_offset );
  258. }
  259. if ( ! empty( $author_id ) && get_current_user_id() != $author_id ) {
  260. if ( ! current_user_can( $post_type->cap->edit_others_posts ) ) {
  261. return new WP_Error( 'unauthorized', "User is not allowed to publish others' posts.", 403 );
  262. } elseif ( ! user_can( $author_id, $post_type->cap->edit_posts ) ) {
  263. return new WP_Error( 'unauthorized', 'Assigned author cannot publish post.', 403 );
  264. }
  265. }
  266. if ( !is_post_type_hierarchical( $post_type->name ) && 'revision' !== $post_type->name ) {
  267. unset( $input['parent'] );
  268. }
  269. foreach ( array( '', '_by_id' ) as $term_key_suffix ) {
  270. $term_input_key = 'terms' . $term_key_suffix;
  271. if ( isset( $input[ $term_input_key ] ) ) {
  272. $input[ $term_input_key ] = (array) $input[ $term_input_key ];
  273. } else {
  274. $input[ $term_input_key ] = array();
  275. }
  276. // Convert comma-separated terms to array before attempting to
  277. // merge with hardcoded taxonomies
  278. foreach ( $input[ $term_input_key ] as $taxonomy => $terms ) {
  279. if ( is_string( $terms ) ) {
  280. $input[ $term_input_key ][ $taxonomy ] = explode( ',', $terms );
  281. } else if ( ! is_array( $terms ) ) {
  282. $input[ $term_input_key ][ $taxonomy ] = array();
  283. }
  284. }
  285. // For each hard-coded taxonomy, merge into terms object
  286. foreach ( array( 'categories' => 'category', 'tags' => 'post_tag' ) as $key_prefix => $taxonomy ) {
  287. $taxonomy_key = $key_prefix . $term_key_suffix;
  288. if ( ! isset( $input[ $taxonomy_key ] ) ) {
  289. continue;
  290. }
  291. if ( ! isset( $input[ $term_input_key ][ $taxonomy ] ) ) {
  292. $input[ $term_input_key ][ $taxonomy ] = array();
  293. }
  294. $terms = $input[ $taxonomy_key ];
  295. if ( is_string( $terms ) ) {
  296. $terms = explode( ',', $terms );
  297. } else if ( ! is_array( $terms ) ) {
  298. continue;
  299. }
  300. $input[ $term_input_key ][ $taxonomy ] = array_merge(
  301. $input[ $term_input_key ][ $taxonomy ],
  302. $terms
  303. );
  304. }
  305. }
  306. /* add terms by name */
  307. $tax_input = array();
  308. foreach ( $input['terms'] as $taxonomy => $terms ) {
  309. $tax_input[ $taxonomy ] = array();
  310. $is_hierarchical = is_taxonomy_hierarchical( $taxonomy );
  311. foreach ( $terms as $term ) {
  312. /**
  313. * We assume these are names, not IDs, even if they are numeric.
  314. * Note: A category named "0" will not work right.
  315. * https://core.trac.wordpress.org/ticket/9059
  316. */
  317. if ( ! is_string( $term ) ) {
  318. continue;
  319. }
  320. $term_info = get_term_by( 'name', $term, $taxonomy, ARRAY_A );
  321. if ( ! $term_info ) {
  322. // only add a new tag/cat if the user has access to
  323. $tax = get_taxonomy( $taxonomy );
  324. // see https://core.trac.wordpress.org/ticket/26409
  325. if ( $is_hierarchical && ! current_user_can( $tax->cap->edit_terms ) ) {
  326. continue;
  327. } else if ( ! current_user_can( $tax->cap->assign_terms ) ) {
  328. continue;
  329. }
  330. $term_info = wp_insert_term( $term, $taxonomy );
  331. }
  332. if ( ! is_wp_error( $term_info ) ) {
  333. if ( $is_hierarchical ) {
  334. // Hierarchical terms must be added by ID
  335. $tax_input[$taxonomy][] = (int) $term_info['term_id'];
  336. } else {
  337. // Non-hierarchical terms must be added by name
  338. $tax_input[$taxonomy][] = $term;
  339. }
  340. }
  341. }
  342. }
  343. /* add terms by ID */
  344. foreach ( $input['terms_by_id'] as $taxonomy => $terms ) {
  345. // combine with any previous selections
  346. if ( ! isset( $tax_input[ $taxonomy ] ) || ! is_array( $tax_input[ $taxonomy ] ) ) {
  347. $tax_input[ $taxonomy ] = array();
  348. }
  349. $is_hierarchical = is_taxonomy_hierarchical( $taxonomy );
  350. foreach ( $terms as $term ) {
  351. $term = (string) $term; // ctype_digit compat
  352. if ( ! ctype_digit( $term ) ) {
  353. // skip anything that doesn't look like an ID
  354. continue;
  355. }
  356. $term = (int) $term;
  357. $term_info = get_term_by( 'id', $term, $taxonomy, ARRAY_A );
  358. if ( $term_info && ! is_wp_error( $term_info ) ) {
  359. if ( $is_hierarchical ) {
  360. // Categories must be added by ID
  361. $tax_input[$taxonomy][] = $term;
  362. } else {
  363. // Tags must be added by name
  364. $tax_input[$taxonomy][] = $term_info['name'];
  365. }
  366. }
  367. }
  368. }
  369. if ( ( isset( $input['terms']['category'] ) || isset( $input['terms_by_id']['category'] ) )
  370. && empty( $tax_input['category'] ) && 'revision' !== $post_type->name ) {
  371. $tax_input['category'][] = get_option( 'default_category' );
  372. }
  373. unset( $input['terms'], $input['tags'], $input['categories'], $input['terms_by_id'], $input['tags_by_id'], $input['categories_by_id'] );
  374. $insert = array();
  375. if ( !empty( $input['slug'] ) ) {
  376. $insert['post_name'] = $input['slug'];
  377. unset( $input['slug'] );
  378. }
  379. if ( isset( $input['discussion'] ) ) {
  380. $discussion = (array) $input['discussion'];
  381. foreach ( array( 'comment', 'ping' ) as $discussion_type ) {
  382. $discussion_open = sprintf( '%ss_open', $discussion_type );
  383. $discussion_status = sprintf( '%s_status', $discussion_type );
  384. if ( isset( $discussion[ $discussion_open ] ) ) {
  385. $is_open = WPCOM_JSON_API::is_truthy( $discussion[ $discussion_open ] );
  386. $discussion[ $discussion_status ] = $is_open ? 'open' : 'closed';
  387. }
  388. if ( in_array( $discussion[ $discussion_status ], array( 'open', 'closed' ) ) ) {
  389. $insert[ $discussion_status ] = $discussion[ $discussion_status ];
  390. }
  391. }
  392. }
  393. unset( $input['discussion'] );
  394. if ( isset( $input['menu_order'] ) ) {
  395. $insert['menu_order'] = $input['menu_order'];
  396. unset( $input['menu_order'] );
  397. }
  398. $publicize = isset( $input['publicize'] ) ? $input['publicize'] : null;
  399. unset( $input['publicize'] );
  400. $publicize_custom_message = isset( $input['publicize_message'] ) ? $input['publicize_message'] : null;
  401. unset( $input['publicize_message'] );
  402. if ( isset( $input['featured_image'] ) ) {
  403. $featured_image = trim( $input['featured_image'] );
  404. $delete_featured_image = empty( $featured_image );
  405. unset( $input['featured_image'] );
  406. }
  407. $metadata = isset( $input['metadata'] ) ? $input['metadata'] : null;
  408. unset( $input['metadata'] );
  409. $likes = isset( $input['likes_enabled'] ) ? $input['likes_enabled'] : null;
  410. unset( $input['likes_enabled'] );
  411. $sharing = isset( $input['sharing_enabled'] ) ? $input['sharing_enabled'] : null;
  412. unset( $input['sharing_enabled'] );
  413. $sticky = isset( $input['sticky'] ) ? $input['sticky'] : null;
  414. unset( $input['sticky'] );
  415. foreach ( $input as $key => $value ) {
  416. $insert["post_$key"] = $value;
  417. }
  418. if ( ! empty( $author_id ) ) {
  419. $insert['post_author'] = absint( $author_id );
  420. }
  421. if ( ! empty( $tax_input ) ) {
  422. $insert['tax_input'] = $tax_input;
  423. }
  424. $has_media = ! empty( $input['media'] ) ? count( $input['media'] ) : false;
  425. $has_media_by_url = ! empty( $input['media_urls'] ) ? count( $input['media_urls'] ) : false;
  426. $media_id_string = '';
  427. if ( $has_media || $has_media_by_url ) {
  428. $media_files = ! empty( $input['media'] ) ? $input['media'] : array();
  429. $media_urls = ! empty( $input['media_urls'] ) ? $input['media_urls'] : array();
  430. $media_attrs = ! empty( $input['media_attrs'] ) ? $input['media_attrs'] : array();
  431. $media_results = $this->handle_media_creation_v1_1( $media_files, $media_urls, $media_attrs );
  432. $media_id_string = join( ',', array_filter( array_map( 'absint', $media_results['media_ids'] ) ) );
  433. }
  434. $is_dtp_fb_post = false;
  435. if ( in_array( '_dtp_fb', wp_list_pluck( (array) $metadata, 'key' ), true ) ) {
  436. $is_dtp_fb_post = true;
  437. add_filter( 'rest_api_allowed_public_metadata', array( $this, 'dtp_fb_allowed_metadata' ) );
  438. }
  439. if ( $new ) {
  440. if ( isset( $input['content'] ) && ! has_shortcode( $input['content'], 'gallery' ) && ( $has_media || $has_media_by_url ) ) {
  441. switch ( ( $has_media + $has_media_by_url ) ) {
  442. case 0 :
  443. // No images - do nothing.
  444. break;
  445. case 1 :
  446. // 1 image - make it big
  447. $insert['post_content'] = $input['content'] = sprintf(
  448. "[gallery size=full ids='%s' columns=1]\n\n",
  449. $media_id_string
  450. ) . $input['content'];
  451. break;
  452. default :
  453. // Several images - 3 column gallery
  454. $insert['post_content'] = $input['content'] = sprintf(
  455. "[gallery ids='%s']\n\n",
  456. $media_id_string
  457. ) . $input['content'];
  458. break;
  459. }
  460. }
  461. $insert['post_date'] = isset( $insert['post_date'] ) ? $insert['post_date'] : '';
  462. if ( $is_dtp_fb_post ) {
  463. $insert = $this->dtp_fb_preprocess_post( $insert, $metadata );
  464. }
  465. $post_id = $this->post_exists( $insert['post_title'], $insert['post_content'], $insert['post_date'], $post_type->name );
  466. if ( 0 === $post_id ) {
  467. $post_id = wp_insert_post( add_magic_quotes( $insert ), true );
  468. }
  469. } else {
  470. $insert['ID'] = $post->ID;
  471. // wp_update_post ignores date unless edit_date is set
  472. // See: https://codex.wordpress.org/Function_Reference/wp_update_post#Scheduling_posts
  473. // See: https://core.trac.wordpress.org/browser/tags/3.9.2/src/wp-includes/post.php#L3302
  474. if ( isset( $input['date_gmt'] ) || isset( $input['date'] ) ) {
  475. $insert['edit_date'] = true;
  476. }
  477. // this two-step process ensures any changes submitted along with status=trash get saved before trashing
  478. if ( isset( $input['status'] ) && 'trash' === $input['status'] ) {
  479. // if we insert it with status='trash', it will get double-trashed, so insert it as a draft first
  480. unset( $insert['status'] );
  481. $post_id = wp_update_post( (object) $insert );
  482. // now call wp_trash_post so post_meta gets set and any filters get called
  483. wp_trash_post( $post_id );
  484. } else {
  485. $post_id = wp_update_post( (object) $insert );
  486. }
  487. }
  488. if ( !$post_id || is_wp_error( $post_id ) ) {
  489. return $post_id;
  490. }
  491. // make sure this post actually exists and is not an error of some kind (ie, trying to load media in the posts endpoint)
  492. $post_check = $this->get_post_by( 'ID', $post_id, $args['context'] );
  493. if ( is_wp_error( $post_check ) ) {
  494. return $post_check;
  495. }
  496. if ( $media_id_string ) {
  497. // Yes - this is really how wp-admin does it.
  498. $wpdb->query( $wpdb->prepare(
  499. "UPDATE $wpdb->posts SET post_parent = %d WHERE post_type = 'attachment' AND ID IN ( $media_id_string )",
  500. $post_id
  501. ) );
  502. foreach ( $media_results['media_ids'] as $media_id ) {
  503. clean_attachment_cache( $media_id );
  504. }
  505. clean_post_cache( $post_id );
  506. }
  507. // set page template for this post..
  508. if ( isset( $input['page_template'] ) && 'page' == $post_type->name ) {
  509. $page_template = $input['page_template'];
  510. $page_templates = wp_get_theme()->get_page_templates( get_post( $post_id ) );
  511. if ( empty( $page_template ) || 'default' == $page_template || isset( $page_templates[ $page_template ] ) ) {
  512. update_post_meta( $post_id, '_wp_page_template', $page_template );
  513. }
  514. }
  515. // Set like status for the post
  516. /** This filter is documented in modules/likes.php */
  517. $sitewide_likes_enabled = (bool) apply_filters( 'wpl_is_enabled_sitewide', ! get_option( 'disabled_likes' ) );
  518. if ( $new ) {
  519. if ( $sitewide_likes_enabled ) {
  520. if ( false === $likes ) {
  521. update_post_meta( $post_id, 'switch_like_status', 0 );
  522. } else {
  523. delete_post_meta( $post_id, 'switch_like_status' );
  524. }
  525. } else {
  526. if ( $likes ) {
  527. update_post_meta( $post_id, 'switch_like_status', 1 );
  528. } else {
  529. delete_post_meta( $post_id, 'switch_like_status' );
  530. }
  531. }
  532. } else {
  533. if ( isset( $likes ) ) {
  534. if ( $sitewide_likes_enabled ) {
  535. if ( false === $likes ) {
  536. update_post_meta( $post_id, 'switch_like_status', 0 );
  537. } else {
  538. delete_post_meta( $post_id, 'switch_like_status' );
  539. }
  540. } else {
  541. if ( true === $likes ) {
  542. update_post_meta( $post_id, 'switch_like_status', 1 );
  543. } else {
  544. delete_post_meta( $post_id, 'switch_like_status' );
  545. }
  546. }
  547. }
  548. }
  549. // Set sharing status of the post
  550. if ( $new ) {
  551. $sharing_enabled = isset( $sharing ) ? (bool) $sharing : true;
  552. if ( false === $sharing_enabled ) {
  553. update_post_meta( $post_id, 'sharing_disabled', 1 );
  554. }
  555. }
  556. else {
  557. if ( isset( $sharing ) && true === $sharing ) {
  558. delete_post_meta( $post_id, 'sharing_disabled' );
  559. } else if ( isset( $sharing ) && false == $sharing ) {
  560. update_post_meta( $post_id, 'sharing_disabled', 1 );
  561. }
  562. }
  563. if ( isset( $sticky ) ) {
  564. if ( true === $sticky ) {
  565. stick_post( $post_id );
  566. } else {
  567. unstick_post( $post_id );
  568. }
  569. }
  570. // WPCOM Specific (Jetpack's will get bumped elsewhere
  571. // Tracks how many posts are published and sets meta
  572. // so we can track some other cool stats (like likes & comments on posts published)
  573. if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
  574. if (
  575. ( $new && 'publish' == $input['status'] )
  576. || (
  577. !$new && isset( $last_status )
  578. && 'publish' != $last_status
  579. && isset( $new_status )
  580. && 'publish' == $new_status
  581. )
  582. ) {
  583. /** This action is documented in modules/widgets/social-media-icons.php */
  584. do_action( 'jetpack_bump_stats_extras', 'api-insights-posts', $this->api->token_details['client_id'] );
  585. update_post_meta( $post_id, '_rest_api_published', 1 );
  586. update_post_meta( $post_id, '_rest_api_client_id', $this->api->token_details['client_id'] );
  587. }
  588. }
  589. // We ask the user/dev to pass Publicize services he/she wants activated for the post, but Publicize expects us
  590. // to instead flag the ones we don't want to be skipped. proceed with said logic.
  591. // any posts coming from Path (client ID 25952) should also not publicize
  592. if ( $publicize === false || ( isset( $this->api->token_details['client_id'] ) && 25952 == $this->api->token_details['client_id'] ) ) {
  593. // No publicize at all, skip all by ID
  594. foreach ( $GLOBALS['publicize_ui']->publicize->get_services( 'all' ) as $name => $service ) {
  595. delete_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $name );
  596. $service_connections = $GLOBALS['publicize_ui']->publicize->get_connections( $name );
  597. if ( ! $service_connections ) {
  598. continue;
  599. }
  600. foreach ( $service_connections as $service_connection ) {
  601. update_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $service_connection->unique_id, 1 );
  602. }
  603. }
  604. } else if ( is_array( $publicize ) && ( count ( $publicize ) > 0 ) ) {
  605. foreach ( $GLOBALS['publicize_ui']->publicize->get_services( 'all' ) as $name => $service ) {
  606. /*
  607. * We support both indexed and associative arrays:
  608. * * indexed are to pass entire services
  609. * * associative are to pass specific connections per service
  610. *
  611. * We do support mixed arrays: mixed integer and string keys (see 3rd example below).
  612. *
  613. * EG: array( 'twitter', 'facebook') will only publicize to those, ignoring the other available services
  614. * Form data: publicize[]=twitter&publicize[]=facebook
  615. * 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.
  616. * Form data: publicize[twitter]=$pub_conn_id_0,$pub_conn_id_3&publicize[facebook]=$pub_conn_id_7
  617. * 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
  618. * Form data: publicize[]=twitter&publicize[facebook]=$pub_conn_id_0,$pub_conn_id_3
  619. */
  620. // Delete any stale SKIP value for the service by name. We'll add it back by ID.
  621. delete_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $name );
  622. // Get the user's connections
  623. $service_connections = $GLOBALS['publicize_ui']->publicize->get_connections( $name );
  624. // if the user doesn't have any connections for this service, move on
  625. if ( ! $service_connections ) {
  626. continue;
  627. }
  628. if ( !in_array( $name, $publicize ) && !array_key_exists( $name, $publicize ) ) {
  629. // Skip the whole service by adding each connection ID
  630. foreach ( $service_connections as $service_connection ) {
  631. update_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $service_connection->unique_id, 1 );
  632. }
  633. } else if ( !empty( $publicize[ $name ] ) ) {
  634. // Seems we're being asked to only push to [a] specific connection[s].
  635. // Explode the list on commas, which will also support a single passed ID
  636. $requested_connections = explode( ',', ( preg_replace( '/[\s]*/', '', $publicize[ $name ] ) ) );
  637. // Flag the connections we can't match with the requested list to be skipped.
  638. foreach ( $service_connections as $service_connection ) {
  639. if ( !in_array( $service_connection->meta['connection_data']->id, $requested_connections ) ) {
  640. update_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $service_connection->unique_id, 1 );
  641. } else {
  642. delete_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $service_connection->unique_id );
  643. }
  644. }
  645. } else {
  646. // delete all SKIP values; it's okay to publish to all connected IDs for this service
  647. foreach ( $service_connections as $service_connection ) {
  648. delete_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $service_connection->unique_id );
  649. }
  650. }
  651. }
  652. }
  653. if ( ! is_null( $publicize_custom_message ) ) {
  654. if ( empty( $publicize_custom_message ) ) {
  655. delete_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_MESS );
  656. } else {
  657. update_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_MESS, trim( $publicize_custom_message ) );
  658. }
  659. }
  660. if ( ! empty( $insert['post_format'] ) ) {
  661. if ( 'default' !== strtolower( $insert['post_format'] ) ) {
  662. set_post_format( $post_id, $insert['post_format'] );
  663. }
  664. else {
  665. set_post_format( $post_id, get_option( 'default_post_format' ) );
  666. }
  667. }
  668. if ( isset( $featured_image ) ) {
  669. parent::parse_and_set_featured_image( $post_id, $delete_featured_image, $featured_image );
  670. }
  671. if ( ! empty( $metadata ) ) {
  672. foreach ( (array) $metadata as $meta ) {
  673. $meta = (object) $meta;
  674. if ( Jetpack_SEO_Posts::DESCRIPTION_META_KEY == $meta->key && ! Jetpack_SEO_Utils::is_enabled_jetpack_seo() ) {
  675. return new WP_Error( 'unauthorized', __( 'SEO tools are not enabled for this site.', 'jetpack' ), 403 );
  676. }
  677. $existing_meta_item = new stdClass;
  678. if ( empty( $meta->operation ) )
  679. $meta->operation = 'update';
  680. if ( ! empty( $meta->value ) ) {
  681. if ( 'true' == $meta->value )
  682. $meta->value = true;
  683. if ( 'false' == $meta->value )
  684. $meta->value = false;
  685. }
  686. if ( ! empty( $meta->id ) ) {
  687. $meta->id = absint( $meta->id );
  688. $existing_meta_item = get_metadata_by_mid( 'post', $meta->id );
  689. if ( $post_id !== (int) $existing_meta_item->post_id ) {
  690. // Only allow updates for metadata on this post
  691. continue;
  692. }
  693. }
  694. $unslashed_meta_key = wp_unslash( $meta->key ); // should match what the final key will be
  695. $meta->key = wp_slash( $meta->key );
  696. $unslashed_existing_meta_key = isset( $existing_meta_item->meta_key ) ? wp_unslash( $existing_meta_item->meta_key ) : '';
  697. $existing_meta_item->meta_key = wp_slash( $existing_meta_item->meta_key );
  698. // make sure that the meta id passed matches the existing meta key
  699. if ( ! empty( $meta->id ) && ! empty( $meta->key ) ) {
  700. $meta_by_id = get_metadata_by_mid( 'post', $meta->id );
  701. if ( $meta_by_id->meta_key !== $meta->key ) {
  702. continue; // skip this meta
  703. }
  704. }
  705. switch ( $meta->operation ) {
  706. case 'delete':
  707. if ( ! empty( $meta->id ) && ! empty( $existing_meta_item->meta_key ) && current_user_can( 'delete_post_meta', $post_id, $unslashed_existing_meta_key ) ) {
  708. delete_metadata_by_mid( 'post', $meta->id );
  709. } elseif ( ! empty( $meta->key ) && ! empty( $meta->previous_value ) && current_user_can( 'delete_post_meta', $post_id, $unslashed_meta_key ) ) {
  710. delete_post_meta( $post_id, $meta->key, $meta->previous_value );
  711. } elseif ( ! empty( $meta->key ) && current_user_can( 'delete_post_meta', $post_id, $unslashed_meta_key ) ) {
  712. delete_post_meta( $post_id, $meta->key );
  713. }
  714. break;
  715. case 'add':
  716. if ( ! empty( $meta->id ) || ! empty( $meta->previous_value ) ) {
  717. break;
  718. } 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 ) ) {
  719. add_post_meta( $post_id, $meta->key, $meta->value );
  720. }
  721. break;
  722. case 'update':
  723. if ( ! isset( $meta->value ) ) {
  724. break;
  725. } 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 ) ) ) {
  726. update_metadata_by_mid( 'post', $meta->id, $meta->value );
  727. } 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 ) ) ) {
  728. update_post_meta( $post_id, $meta->key,$meta->value, $meta->previous_value );
  729. } elseif ( ! empty( $meta->key ) && ( current_user_can( 'edit_post_meta', $post_id, $unslashed_meta_key ) || WPCOM_JSON_API_Metadata::is_public( $meta->key ) ) ) {
  730. update_post_meta( $post_id, $meta->key, $meta->value );
  731. }
  732. break;
  733. }
  734. }
  735. }
  736. /** This action is documented in json-endpoints/class.wpcom-json-api-update-post-endpoint.php */
  737. do_action( 'rest_api_inserted_post', $post_id, $insert, $new );
  738. $return = $this->get_post_by( 'ID', $post_id, $args['context'] );
  739. if ( !$return || is_wp_error( $return ) ) {
  740. return $return;
  741. }
  742. if ( isset( $input['type'] ) && 'revision' === $input['type'] ) {
  743. $return['preview_nonce'] = wp_create_nonce( 'post_preview_' . $input['parent'] );
  744. }
  745. if ( isset( $sticky ) ) {
  746. // workaround for sticky test occasionally failing, maybe a race condition with stick_post() above
  747. $return['sticky'] = ( true === $sticky );
  748. }
  749. if ( ! empty( $media_results['errors'] ) ) {
  750. /*
  751. * Depending on whether the errors array keys are sequential or not
  752. * json_encode would transform this into either an array or an object
  753. * see https://www.php.net/manual/en/function.json-encode.php#example-3967
  754. * We use array_values to always return an array
  755. */
  756. $return['media_errors'] = array_values( $media_results['errors'] );
  757. }
  758. if ( 'publish' !== $return['status'] && isset( $input['title'] )) {
  759. $sal_site = $this->get_sal_post_by( 'ID', $post_id, $args['context'] );
  760. $return['other_URLs'] = (object) $sal_site->get_permalink_suggestions( $input['title'] );
  761. }
  762. /** This action is documented in json-endpoints/class.wpcom-json-api-site-settings-endpoint.php */
  763. do_action( 'wpcom_json_api_objects', 'posts' );
  764. return $return;
  765. }
  766. protected function should_load_theme_functions( $post_id = null ) {
  767. if ( empty( $post_id ) ) {
  768. $input = $this->input( true );
  769. $type = $input['type'];
  770. } else {
  771. $type = get_post_type( $post_id );
  772. }
  773. return ! empty( $type ) && ! in_array( $type, array( 'post', 'revision' ) );
  774. }
  775. /**
  776. * Filter for rest_api_allowed_public_metadata.
  777. * Adds FB's DTP specific metadata.
  778. *
  779. * @param array $keys Array of metadata that is accessible by the REST API.
  780. *
  781. * @return array
  782. */
  783. public function dtp_fb_allowed_metadata( $keys ) {
  784. return array_merge( $keys, array( '_dtp_fb', '_dtp_fb_geo_points', '_dtp_fb_post_link' ) );
  785. }
  786. /**
  787. * Pre-process FB DTP posts before inserting.
  788. * Here we can improve the DTP content for the following issues:
  789. * - Render the map block based on provided coordinates in metadata
  790. * - [TODO] Improve the title
  791. *
  792. * @param array $post Post to be inserted.
  793. * @param array $metadata Metadata for the post.
  794. *
  795. * @return mixed
  796. */
  797. private function dtp_fb_preprocess_post( $post, $metadata ) {
  798. $geo_points_metadata = wp_filter_object_list( $metadata, array( 'key' => '_dtp_fb_geo_points' ), 'and', 'value' );
  799. if ( ! empty( $geo_points_metadata ) ) {
  800. $fb_points = reset( $geo_points_metadata );
  801. $geo_points = array();
  802. // Prepare Geo Points so that they match the format expected by the map block.
  803. foreach ( $fb_points as $fb_point ) {
  804. $geo_points[] = array(
  805. 'coordinates' => array(
  806. 'longitude' => $fb_point['longitude'],
  807. 'latitude' => $fb_point['latitude'],
  808. ),
  809. 'title' => $fb_point['name'],
  810. );
  811. }
  812. $map_block = map_block_from_geo_points( $geo_points );
  813. $post['post_content'] = $map_block . $post['post_content'];
  814. }
  815. $post['post_format'] = 'aside';
  816. return $post;
  817. }
  818. /**
  819. * Determines if a post exists based on title, content, date, and type,
  820. * But excluding IDs in gallery shortcodes.
  821. * This will prevent duplication of posts created through the API.
  822. *
  823. * @param string $title Post title.
  824. * @param string $content Post content.
  825. * @param string $post_date Post date.
  826. * @param string $type Optional post type.
  827. * @return int Post ID if post exists, 0 otherwise.
  828. */
  829. private function post_exists( $title, $content, $post_date, $type = '' ) {
  830. $date = date_create( $post_date );
  831. $posts = get_posts(
  832. array(
  833. 'year' => date_format( $date, 'Y' ),
  834. 'monthnum' => date_format( $date, 'n' ),
  835. 'day' => date_format( $date, 'j' ),
  836. 'hour' => date_format( $date, 'G' ),
  837. 'minute' => date_format( $date, 'i' ),
  838. 'second' => date_format( $date, 's' ),
  839. 'post_type' => $type,
  840. 'title' => $title,
  841. 'numberposts' => -1,
  842. 'suppress_filters' => false,
  843. )
  844. );
  845. foreach ( $posts as $post ) {
  846. $gallery_ids_pattern = "/(\[gallery[^\]]*)(\sids='[\d,]+')([^\]]*\])/";
  847. $post->post_content = preg_replace( $gallery_ids_pattern, '$1$3', $post->post_content );
  848. $content = preg_replace( $gallery_ids_pattern, '$1$3', $content );
  849. if ( $content === $post->post_content ) {
  850. return $post->ID;
  851. }
  852. }
  853. return 0;
  854. }
  855. }