PluginProbe ʕ •ᴥ•ʔ
Jetpack – WP Security, Backup, Speed, & Growth / 15.9-a.7
Jetpack – WP Security, Backup, Speed, & Growth v15.9-a.7
15.9-a.7 15.9-a.5 15.9-a.3 15.9-a.1 15.8 15.8-beta 15.8-a.7 15.8-a.5 5.2.5 5.3.4 5.4.4 5.5.5 5.6.5 5.7.5 5.8.4 5.9.4 6.0.4 6.1 6.1.1 6.1.2 6.1.3 6.1.4 6.1.5 6.2 6.2.1 6.2.2 6.2.3 6.2.4 6.2.5 6.3 6.3.1 6.3.2 6.3.3 6.3.4 6.3.5 6.3.6 6.3.7 6.4 6.4.1 6.4.2 6.4.3 6.4.4 6.4.5 6.4.6 6.5 6.5.1 6.5.2 6.5.3 6.5.4 6.6 6.6.1 6.6.2 6.6.3 6.6.4 6.6.5 6.7 6.7.1 6.7.2 6.7.3 6.7.4 6.8 6.8.1 6.8.2 6.8.3 6.8.4 6.8.5 6.9 6.9.1 6.9.2 6.9.3 6.9.4 7.0 7.0.1 7.0.2 7.0.3 7.0.4 7.0.5 7.1 7.1.1 7.1.2 7.1.3 7.1.4 7.1.5 7.2 7.2.1 7.2.1.1 7.2.2 7.2.3 7.2.4 7.2.5 7.3 7.3.0.1 7.3.1 7.3.1.1 7.3.2 7.3.3 7.3.4 7.3.5 7.4 7.4.1 7.4.2 7.4.3 7.4.4 7.4.5 7.5 7.5.0.1 7.5.1 7.5.2 7.5.3 7.5.4 7.5.5 7.5.6 7.5.7 7.6 7.6.1 7.6.2 7.6.3 7.6.4 7.7 7.7.1 7.7.2 7.7.3 7.7.4 7.7.5 7.7.6 7.8 7.8.1 7.8.2 7.8.3 7.8.4 7.9 7.9.1 7.9.2 7.9.3 7.9.4 8.0 8.0.1 8.0.2 8.0.3 8.1 8.1.1 8.1.2 8.1.3 8.1.4 8.2 8.2.0.1 8.2.1 8.2.2 8.2.3 8.2.4 8.2.5 8.2.6 8.3 8.3.1 8.3.2 8.3.3 8.4 8.4.1 8.4.2 8.4.3 8.4.4 8.4.5 8.5 8.5.1 8.5.2 8.5.3 8.6 8.6.1 8.6.2 8.6.3 8.6.4 8.7 8.7.0.1 8.7.1 8.7.2 8.7.3 8.7.4 8.8 8.8.1 8.8.2 8.8.3 8.8.4 8.8.5 8.9 8.9.1 8.9.2 8.9.3 8.9.4 9.0 9.0.1 9.0.2 9.0.3 9.0.4 9.0.5 9.1 9.1.1 9.1.2 9.1.3 9.2 9.2.1 9.2.2 9.2.3 9.2.4 9.3 9.3.1 9.3.2 9.3.3 9.3.4 9.3.5 9.4 9.4.1 9.4.2 9.4.3 9.4.4 9.5 9.5.1 9.5.2 9.5.3 9.5.4 9.5.5 9.6 9.6.1 9.6.2 9.6.3 9.6.4 9.7 9.7.1 9.7.2 15.7-beta.2 9.7.3 15.7.1 9.8 15.8-a.1 9.8.1 15.8-a.3 9.8.2 2.0.9 9.8.3 2.1.7 9.9 2.2.10 9.9.1 2.3.10 9.9.2 2.4.7 9.9.3 2.5.5 2.6.6 2.7.5 2.8.5 2.9.6 3.0.6 3.1.5 3.2.5 3.3.6 3.4.6 3.5.6 3.6.4 3.7.5 3.8.5 3.9.10 4.0.7 4.1.4 4.2.5 4.3.5 4.4.5 4.5.3 4.6.3 4.7.4 4.8.5 4.9.3 5.0.3 5.1.4 trunk 10.0 10.0.1 10.0.2 10.1 10.1.1 10.1.2 10.2 10.2.1 10.2.2 10.2.3 10.3 10.3.1 10.3.2 10.4 10.4.1 10.4.2 10.5 10.5.1 10.5.2 10.5.3 10.6 10.6.1 10.6.2 10.7 10.7.1 10.7.2 10.8 10.8.1 10.8.2 10.9 10.9.1 10.9.2 10.9.3 11.0 11.0.1 11.0.2 11.1 11.1.1 11.1.2 11.1.3 11.1.4 11.2 11.2.1 11.2.2 11.3 11.3.1 11.3.2 11.3.3 11.3.4 11.4 11.4.1 11.4.2 11.5 11.5.1 11.5.2 11.5.3 11.6 11.6.1 11.6.2 11.7 11.7.1 11.7.2 11.7.3 11.8 11.8.3 11.8.4 11.8.5 11.8.6 11.9 11.9.1 11.9.2 11.9.3 12.0 12.0.1 12.0.2 12.1 12.1.1 12.1.2 12.2 12.2.1 12.2.2 12.3 12.3.1 12.4 12.4.1 12.5 12.5.1 12.6 12.6.1 12.6.2 12.6.3 12.7 12.7.1 12.7.2 12.8 12.8.1 12.8.2 12.9 12.9.1 12.9.2 12.9.3 12.9.4 13.0 13.0.1 13.1 13.1.1 13.1.2 13.1.3 13.1.4 13.2 13.2.1 13.2.2 13.2.3 13.3 13.3.1 13.3.2 13.4 13.4.1 13.4.2 13.4.3 13.4.4 13.5 13.5.1 13.6 13.6.1 13.7 13.7.1 13.8 13.8.1 13.8.2 13.9 13.9.1 14.0 14.1 14.2 14.2.1 14.3 14.4 14.4.1 14.5 14.6 14.7 14.8 14.9 14.9.1 15.0 15.0.1 15.0.2 15.1 15.1.1 15.2 15.3 15.3.1 15.4 15.5 15.6 15.7 15.7-a.1 15.7-a.3 15.7-a.5 15.7-a.7 15.7-beta
jetpack / json-endpoints / class.wpcom-json-api-update-post-v1-2-endpoint.php
jetpack / json-endpoints Last commit date
jetpack 1 week ago class.wpcom-json-api-add-widget-endpoint.php 6 months ago class.wpcom-json-api-autosave-post-v1-1-endpoint.php 6 months ago class.wpcom-json-api-bulk-delete-post-endpoint.php 6 months ago class.wpcom-json-api-bulk-restore-post-endpoint.php 6 months ago class.wpcom-json-api-bulk-update-comments-endpoint.php 1 week ago class.wpcom-json-api-comment-endpoint.php 6 months ago class.wpcom-json-api-delete-media-endpoint.php 6 months ago class.wpcom-json-api-delete-media-v1-1-endpoint.php 6 months ago class.wpcom-json-api-edit-media-v1-2-endpoint.php 1 week ago class.wpcom-json-api-get-autosave-v1-1-endpoint.php 6 months ago class.wpcom-json-api-get-comment-counts-endpoint.php 6 months ago class.wpcom-json-api-get-comment-endpoint.php 6 months ago class.wpcom-json-api-get-comment-history-endpoint.php 6 months ago class.wpcom-json-api-get-comments-tree-endpoint.php 6 months ago class.wpcom-json-api-get-comments-tree-v1-1-endpoint.php 6 months ago class.wpcom-json-api-get-comments-tree-v1-2-endpoint.php 6 months ago class.wpcom-json-api-get-customcss.php 6 months ago class.wpcom-json-api-get-media-endpoint.php 6 months ago class.wpcom-json-api-get-media-v1-1-endpoint.php 6 months ago class.wpcom-json-api-get-media-v1-2-endpoint.php 6 months ago class.wpcom-json-api-get-post-counts-v1-1-endpoint.php 6 months ago class.wpcom-json-api-get-post-endpoint.php 6 months ago class.wpcom-json-api-get-post-v1-1-endpoint.php 6 months ago class.wpcom-json-api-get-site-endpoint.php 4 weeks ago class.wpcom-json-api-get-site-v1-2-endpoint.php 3 months ago class.wpcom-json-api-get-taxonomies-endpoint.php 1 month ago class.wpcom-json-api-get-taxonomy-endpoint.php 6 months ago class.wpcom-json-api-get-term-endpoint.php 6 months ago class.wpcom-json-api-list-comments-endpoint.php 1 week ago class.wpcom-json-api-list-dropdown-pages-endpoint.php 6 months ago class.wpcom-json-api-list-embeds-endpoint.php 6 months ago class.wpcom-json-api-list-media-endpoint.php 6 months ago class.wpcom-json-api-list-media-v1-1-endpoint.php 1 week ago class.wpcom-json-api-list-media-v1-2-endpoint.php 6 months ago class.wpcom-json-api-list-post-type-taxonomies-endpoint.php 6 months ago class.wpcom-json-api-list-post-types-endpoint.php 6 months ago class.wpcom-json-api-list-posts-endpoint.php 1 week ago class.wpcom-json-api-list-posts-v1-1-endpoint.php 1 week ago class.wpcom-json-api-list-posts-v1-2-endpoint.php 1 week ago class.wpcom-json-api-list-roles-endpoint.php 6 months ago class.wpcom-json-api-list-shortcodes-endpoint.php 6 months ago class.wpcom-json-api-list-terms-endpoint.php 6 months ago class.wpcom-json-api-list-users-endpoint.php 6 months ago class.wpcom-json-api-menus-v1-1-endpoint.php 1 week ago class.wpcom-json-api-post-endpoint.php 6 months ago class.wpcom-json-api-post-v1-1-endpoint.php 1 month ago class.wpcom-json-api-render-embed-endpoint.php 6 months ago class.wpcom-json-api-render-embed-reversal-endpoint.php 6 months ago class.wpcom-json-api-render-endpoint.php 2 weeks ago class.wpcom-json-api-render-shortcode-endpoint.php 6 months ago class.wpcom-json-api-sharing-buttons-endpoint.php 1 week ago class.wpcom-json-api-site-settings-endpoint.php 2 months ago class.wpcom-json-api-site-settings-v1-2-endpoint.php 6 months ago class.wpcom-json-api-site-settings-v1-3-endpoint.php 6 months ago class.wpcom-json-api-site-settings-v1-4-endpoint.php 2 months ago class.wpcom-json-api-site-user-endpoint.php 6 months ago class.wpcom-json-api-taxonomy-endpoint.php 6 months ago class.wpcom-json-api-update-comment-endpoint.php 4 months ago class.wpcom-json-api-update-customcss.php 6 months ago class.wpcom-json-api-update-media-endpoint.php 6 months ago class.wpcom-json-api-update-media-v1-1-endpoint.php 1 week ago class.wpcom-json-api-update-post-endpoint.php 1 week ago class.wpcom-json-api-update-post-v1-1-endpoint.php 1 week ago class.wpcom-json-api-update-post-v1-2-endpoint.php 1 week ago class.wpcom-json-api-update-site-homepage-endpoint.php 6 months ago class.wpcom-json-api-update-site-logo-endpoint.php 6 months ago class.wpcom-json-api-update-taxonomy-endpoint.php 5 months ago class.wpcom-json-api-update-term-endpoint.php 6 months ago class.wpcom-json-api-update-user-endpoint.php 6 months ago class.wpcom-json-api-upload-media-endpoint.php 6 months ago class.wpcom-json-api-upload-media-v1-1-endpoint.php 6 months ago
class.wpcom-json-api-update-post-v1-2-endpoint.php
1073 lines
1 <?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName
2 /**
3 * Update post endpoint v1.2
4 *
5 * Endpoints:
6 * Create a post: /sites/%s/posts/new
7 * Update a post: /sites/%s/posts/%d
8 * Delete a post: /sites/%s/posts/%d/delete
9 * Restore a post: /sites/%s/posts/%d/restore
10 */
11
12 if ( ! defined( 'ABSPATH' ) ) {
13 exit( 0 );
14 }
15
16 new WPCOM_JSON_API_Update_Post_v1_2_Endpoint(
17 array(
18 'description' => 'Create a post.',
19 'group' => 'posts',
20 'stat' => 'posts:new',
21 'min_version' => '1.2',
22 'max_version' => '1.2',
23 'method' => 'POST',
24 'path' => '/sites/%s/posts/new',
25 'path_labels' => array(
26 '$site' => '(int|string) Site ID or domain',
27 ),
28 'query_parameters' => array(
29 'autosave' => '(bool) True if the post was saved automatically.',
30 ),
31
32 'request_format' => array(
33 // explicitly document all input.
34 'date' => "(ISO 8601 datetime) The post's creation time.",
35 'title' => '(HTML) The post title.',
36 'content' => '(HTML) The post content.',
37 'excerpt' => '(HTML) An optional post excerpt.',
38 'slug' => '(string) The name (slug) for the post, used in URLs.',
39 'author' => '(string) The username or ID for the user to assign the post to.',
40 '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.',
41 'publicize_message' => '(string) Custom message to be shared to external services.',
42 'status' => array(
43 'publish' => 'Publish the post.',
44 'private' => 'Privately publish the post.',
45 'draft' => 'Save the post as a draft.',
46 'pending' => 'Mark the post as pending editorial approval.',
47 'future' => 'Schedule the post (alias for publish; you must also set a future date).',
48 'auto-draft' => 'Save a placeholder for a newly created post, with no content.',
49 ),
50 'sticky' => array(
51 'false' => 'Post is not marked as sticky.',
52 'true' => 'Stick the post to the front page.',
53 ),
54 'password' => '(string) The plaintext password protecting the post, or, more likely, the empty string if the post is not password protected.',
55 'parent' => "(int) The post ID of the new post's parent.",
56 '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.",
57 'terms' => '(object) Mapping of taxonomy to comma-separated list or array of term names',
58 'categories' => '(array|string) Comma-separated list or array of category names',
59 'tags' => '(array|string) Comma-separated list or array of tag names',
60 'terms_by_id' => '(object) Mapping of taxonomy to comma-separated list or array of term IDs',
61 'categories_by_id' => '(array|string) Comma-separated list or array of category IDs',
62 'tags_by_id' => '(array|string) Comma-separated list or array of tag IDs',
63 'format' => array_merge( array( 'default' => 'Use default post format' ), get_post_format_strings() ),
64 '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.',
65 '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 />' .
66 "<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>",
67 '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.',
68 '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 />' .
69 "<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>",
70 '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.',
71 '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`',
72 'likes_enabled' => "(bool) Should the post be open to likes? Defaults to the blog's preference.",
73 'sharing_enabled' => '(bool) Should sharing buttons show on this post? Defaults to true.',
74 'menu_order' => '(int) (Pages Only) the order pages should appear in. Use 0 to maintain alphabetical order.',
75 'page_template' => '(string) (Pages Only) The page template this page should use.',
76 ),
77
78 'example_request' => 'https://public-api.wordpress.com/rest/v1.2/sites/82974409/posts/new/',
79
80 'example_request_data' => array(
81 'headers' => array(
82 'authorization' => 'Bearer YOUR_API_TOKEN',
83 ),
84
85 'body' => array(
86 'title' => 'Hello World',
87 'content' => 'Hello. I am a test post. I was created by the API',
88 'tags' => 'tests',
89 'categories' => 'API',
90 ),
91 ),
92 )
93 );
94
95 new WPCOM_JSON_API_Update_Post_v1_2_Endpoint(
96 array(
97 'description' => 'Edit a post.',
98 'group' => 'posts',
99 'stat' => 'posts:1:POST',
100 'min_version' => '1.2',
101 'max_version' => '1.2',
102 'method' => 'POST',
103 'path' => '/sites/%s/posts/%d',
104 'path_labels' => array(
105 '$site' => '(int|string) Site ID or domain',
106 '$post_ID' => '(int) The post ID',
107 ),
108 'query_parameters' => array(
109 'autosave' => '(bool) True if the post was saved automatically.',
110 ),
111
112 'request_format' => array(
113 'date' => "(ISO 8601 datetime) The post's creation time.",
114 'title' => '(HTML) The post title.',
115 'content' => '(HTML) The post content.',
116 'excerpt' => '(HTML) An optional post excerpt.',
117 'slug' => '(string) The name (slug) for the post, used in URLs.',
118 'author' => '(string) The username or ID for the user to assign the post to.',
119 '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.',
120 'publicize_message' => '(string) Custom message to be shared to external services.',
121 'status' => array(
122 'publish' => 'Publish the post.',
123 'private' => 'Privately publish the post.',
124 'draft' => 'Save the post as a draft.',
125 'future' => 'Schedule the post (alias for publish; you must also set a future date).',
126 'pending' => 'Mark the post as pending editorial approval.',
127 'trash' => 'Set the post as trashed.',
128 ),
129 'sticky' => array(
130 'false' => 'Post is not marked as sticky.',
131 'true' => 'Stick the post to the front page.',
132 ),
133 'password' => '(string) The plaintext password protecting the post, or, more likely, the empty string if the post is not password protected.',
134 'parent' => "(int) The post ID of the new post's parent.",
135 'terms' => '(object) Mapping of taxonomy to comma-separated list or array of term names',
136 'terms_by_id' => '(object) Mapping of taxonomy to comma-separated list or array of term IDs',
137 'categories' => '(array|string) Comma-separated list or array of category names',
138 'categories_by_id' => '(array|string) Comma-separated list or array of category IDs',
139 'tags' => '(array|string) Comma-separated list or array of tag names',
140 'tags_by_id' => '(array|string) Comma-separated list or array of tag IDs',
141 'format' => array_merge( array( 'default' => 'Use default post format' ), get_post_format_strings() ),
142 '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`',
143 'likes_enabled' => '(bool) Should the post be open to likes?',
144 'menu_order' => '(int) (Pages only) the order pages should appear in. Use 0 to maintain alphabetical order.',
145 'page_template' => '(string) (Pages Only) The page template this page should use.',
146 'sharing_enabled' => '(bool) Should sharing buttons show on this post?',
147 '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.',
148 '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 />' .
149 "<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>",
150 'media_urls' => '(array) An array of URLs for images to attach to a post. Sideloads the media in for a post.',
151 '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.',
152 'if_not_modified_since' => '(ISO 8601 datetime) If the post has been modified since this time, the post will not be updated.',
153 ),
154
155 'example_request' => 'https://public-api.wordpress.com/rest/v1.2/sites/82974409/posts/881',
156
157 'example_request_data' => array(
158 'headers' => array(
159 'authorization' => 'Bearer YOUR_API_TOKEN',
160 ),
161
162 'body' => array(
163 'title' => 'Hello World (Again)',
164 'content' => 'Hello. I am an edited post. I was edited by the API',
165 'tags' => 'tests',
166 'categories' => 'API',
167 ),
168 ),
169 )
170 );
171
172 use function Automattic\Jetpack\Extensions\Map\map_block_from_geo_points;
173
174 // phpcs:disable PEAR.NamingConventions.ValidClassName.Invalid
175 /**
176 * Update post v1.2 endpoint class.
177 *
178 * @phan-constructor-used-for-side-effects
179 */
180 class WPCOM_JSON_API_Update_Post_v1_2_Endpoint extends WPCOM_JSON_API_Update_Post_v1_1_Endpoint {
181 /**
182 * Create or update a post.
183 *
184 * /sites/%s/posts/new -> $blog_id
185 * /sites/%s/posts/%d -> $blog_id, $post_id
186 *
187 * @param string $path API path.
188 * @param int $blog_id Blog ID.
189 * @param int $post_id Post ID.
190 */
191 public function write_post( $path, $blog_id, $post_id ) {
192 $delete_featured_image = null;
193 $media_results = array();
194 global $wpdb;
195
196 $new = $this->api->ends_with( $path, '/new' );
197 $args = $this->query_args();
198
199 if ( ! empty( $args['autosave'] ) ) {
200 define( 'DOING_AUTOSAVE', true );
201 }
202
203 // unhook publicize, it's hooked again later -- without this, skipping services is impossible.
204 if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
205 remove_action( 'save_post', array( $GLOBALS['publicize_ui']->publicize, 'async_publicize_post' ), 100 );
206
207 if ( $this->should_load_theme_functions( $post_id ) ) {
208 $this->load_theme_functions();
209 }
210 }
211
212 if ( $new ) {
213 $input = $this->input( true );
214
215 // 'future' is an alias for 'publish' for now
216 if ( isset( $input['status'] ) && 'future' === $input['status'] ) {
217 $input['status'] = 'publish';
218 }
219
220 // default to post.
221 if ( empty( $input['type'] ) ) {
222 $input['type'] = 'post';
223 }
224
225 if ( 'revision' === $input['type'] ) {
226 if ( ! isset( $input['parent'] ) ) {
227 return new WP_Error( 'invalid_input', 'Invalid request input', 400 );
228 }
229 $input['status'] = 'inherit'; // force inherit for revision type.
230 $input['slug'] = $input['parent'] . '-autosave-v1';
231 } elseif ( ! isset( $input['title'] ) && ! isset( $input['content'] ) && ! isset( $input['excerpt'] ) ) {
232 return new WP_Error( 'invalid_input', 'Invalid request input', 400 );
233 }
234
235 $post_type = get_post_type_object( $input['type'] );
236
237 if ( ! $this->is_post_type_allowed( $input['type'] ) ) {
238 return new WP_Error( 'unknown_post_type', 'Unknown post type', 404 );
239 }
240
241 if ( ! empty( $input['author'] ) ) {
242 $author_id = parent::parse_and_set_author( $input['author'], $input['type'] );
243 unset( $input['author'] );
244 if ( is_wp_error( $author_id ) ) {
245 return $author_id;
246 }
247 }
248
249 if ( 'publish' === $input['status'] ) {
250 if ( ! current_user_can( $post_type->cap->publish_posts ) ) {
251 if ( current_user_can( $post_type->cap->edit_posts ) ) {
252 $input['status'] = 'pending';
253 } else {
254 return new WP_Error( 'unauthorized', 'User cannot publish posts', 403 );
255 }
256 }
257 } elseif ( ! current_user_can( $post_type->cap->edit_posts ) ) {
258 return new WP_Error( 'unauthorized', 'User cannot edit posts', 403 );
259 }
260 } else {
261 $input = $this->input( false );
262
263 if ( ! is_array( $input ) || ! $input ) {
264 return new WP_Error( 'invalid_input', 'Invalid request input', 400 );
265 }
266
267 $post = get_post( $post_id );
268 if ( ! $post || is_wp_error( $post ) ) {
269 return new WP_Error( 'unknown_post', 'Unknown post', 404 );
270 }
271
272 if ( isset( $input['status'] ) && 'trash' === $input['status'] && ! current_user_can( 'delete_post', $post_id ) ) {
273 return new WP_Error( 'unauthorized', 'User cannot delete post', 403 );
274 }
275
276 // 'future' is an alias for 'publish' for now
277 if ( isset( $input['status'] ) && 'future' === $input['status'] ) {
278 $input['status'] = 'publish';
279 }
280
281 $_post_type = ( ! empty( $input['type'] ) ) ? $input['type'] : $post->post_type;
282 $post_type = get_post_type_object( $_post_type );
283
284 if ( ! current_user_can( 'edit_post', $post->ID ) ) {
285 return new WP_Error( 'unauthorized', 'User cannot edit post', 403 );
286 }
287 // The input `if_not_modified_since` input is the format ISO 8601 datetime and get converted to `if_not_modified_since_gmt` and `if_not_modified_since`
288 if ( ! empty( $input['if_not_modified_since_gmt'] ) ) {
289 if ( mysql2date( 'U', $post->post_modified_gmt ) > mysql2date( 'U', $input['if_not_modified_since_gmt'] ) ) {
290 return new WP_Error( 'old-revision', 'There is a revision of this post that is more recent.', 409 );
291 }
292 }
293
294 if ( ! empty( $input['author'] ) ) {
295 $author_id = parent::parse_and_set_author( $input['author'], $_post_type );
296 unset( $input['author'] );
297 if ( is_wp_error( $author_id ) ) {
298 return $author_id;
299 }
300 }
301
302 if ( ( isset( $input['status'] ) && 'publish' === $input['status'] ) && 'publish' !== $post->post_status && ! current_user_can( 'publish_post', $post->ID ) ) {
303 $input['status'] = 'pending';
304 }
305 $last_status = $post->post_status;
306 $new_status = $input['status'] ?? $last_status;
307
308 // Make sure that drafts get the current date when transitioning to publish if not supplied in the post.
309 // Similarly, scheduled posts that are manually published before their scheduled date should have the date reset.
310 $date_in_past = ( strtotime( $post->post_date_gmt ) < time() );
311 $reset_draft_date = 'publish' === $new_status && 'draft' === $last_status && ! isset( $input['date_gmt'] ) && $date_in_past;
312 $reset_scheduled_date = 'publish' === $new_status && 'future' === $last_status && ! isset( $input['date_gmt'] ) && ! $date_in_past;
313
314 if ( $reset_draft_date || $reset_scheduled_date ) {
315 $input['date_gmt'] = gmdate( 'Y-m-d H:i:s' );
316 }
317
318 // Untrash a post so that the proper hooks get called as well as the comments get untrashed.
319 if ( $this->should_untrash_post( $last_status, $new_status, $post ) ) {
320 $input = $this->untrash_post( $post, $input );
321 }
322 }
323
324 if ( function_exists( 'wpcom_switch_to_blog_locale' ) ) {
325 // fixes calypso-pre-oss #12476: respect blog locale when creating the post slug.
326 wpcom_switch_to_blog_locale( $blog_id );
327 }
328
329 // If date is set, $this->input will set date_gmt, date still needs to be adjusted.
330 if ( isset( $input['date_gmt'] ) ) {
331 $date_gmt_timestamp = strtotime( $input['date_gmt'] );
332 if ( $date_gmt_timestamp ) {
333 $gmt_offset = (int) get_option( 'gmt_offset' );
334 $time_with_offset = $date_gmt_timestamp + $gmt_offset * HOUR_IN_SECONDS;
335 $input['date'] = gmdate( 'Y-m-d H:i:s', $time_with_offset );
336 } else { // Invalid input.
337 unset( $input['date_gmt'] );
338 }
339 }
340
341 if ( ! empty( $author_id ) && get_current_user_id() !== $author_id ) {
342 if ( ! current_user_can( $post_type->cap->edit_others_posts ) ) {
343 return new WP_Error( 'unauthorized', "User is not allowed to publish others' posts.", 403 );
344 } elseif ( ! user_can( $author_id, $post_type->cap->edit_posts ) ) {
345 return new WP_Error( 'unauthorized', 'Assigned author cannot publish post.', 403 );
346 }
347 }
348
349 if ( ! is_post_type_hierarchical( $post_type->name ) && 'revision' !== $post_type->name ) {
350 unset( $input['parent'] );
351 }
352
353 foreach ( array( '', '_by_id' ) as $term_key_suffix ) {
354 $term_input_key = 'terms' . $term_key_suffix;
355 if ( isset( $input[ $term_input_key ] ) ) {
356 $input[ $term_input_key ] = (array) $input[ $term_input_key ];
357 } else {
358 $input[ $term_input_key ] = array();
359 }
360
361 // Convert comma-separated terms to array before attempting to
362 // merge with hardcoded taxonomies.
363 foreach ( $input[ $term_input_key ] as $taxonomy => $terms ) {
364 if ( is_string( $terms ) ) {
365 $input[ $term_input_key ][ $taxonomy ] = explode( ',', $terms );
366 } elseif ( ! is_array( $terms ) ) {
367 $input[ $term_input_key ][ $taxonomy ] = array();
368 }
369 }
370
371 // For each hard-coded taxonomy, merge into terms object.
372 foreach ( array(
373 'categories' => 'category',
374 'tags' => 'post_tag',
375 ) as $key_prefix => $taxonomy ) {
376 $taxonomy_key = $key_prefix . $term_key_suffix;
377 if ( ! isset( $input[ $taxonomy_key ] ) ) {
378 continue;
379 }
380
381 if ( ! isset( $input[ $term_input_key ][ $taxonomy ] ) ) {
382 $input[ $term_input_key ][ $taxonomy ] = array();
383 }
384
385 $terms = $input[ $taxonomy_key ];
386 if ( is_string( $terms ) ) {
387 $terms = explode( ',', $terms );
388 } elseif ( ! is_array( $terms ) ) {
389 continue;
390 }
391
392 $input[ $term_input_key ][ $taxonomy ] = array_merge(
393 $input[ $term_input_key ][ $taxonomy ],
394 $terms
395 );
396 }
397 }
398
399 /* add terms by name */
400 $tax_input = array();
401 foreach ( $input['terms'] as $taxonomy => $terms ) {
402 $tax_input[ $taxonomy ] = array();
403 $is_hierarchical = is_taxonomy_hierarchical( $taxonomy );
404
405 foreach ( $terms as $term ) {
406 /**
407 * We assume these are names, not IDs, even if they are numeric.
408 * Note: A category named "0" will not work right.
409 * https://core.trac.wordpress.org/ticket/9059
410 */
411 if ( ! is_string( $term ) ) {
412 continue;
413 }
414
415 $term_info = get_term_by( 'name', $term, $taxonomy, ARRAY_A );
416
417 if ( ! $term_info ) {
418 // only add a new tag/cat if the user has access to.
419 $tax = get_taxonomy( $taxonomy );
420
421 // see https://core.trac.wordpress.org/ticket/26409 .
422 if ( $is_hierarchical && ! current_user_can( $tax->cap->edit_terms ) ) {
423 continue;
424 } elseif ( ! current_user_can( $tax->cap->assign_terms ) ) {
425 continue;
426 }
427
428 $term_info = wp_insert_term( $term, $taxonomy );
429 }
430
431 if ( ! is_wp_error( $term_info ) ) {
432 if ( $is_hierarchical ) {
433 // Hierarchical terms must be added by ID.
434 $tax_input[ $taxonomy ][] = (int) $term_info['term_id'];
435 } else {
436 // Non-hierarchical terms must be added by name.
437 $tax_input[ $taxonomy ][] = $term;
438 }
439 }
440 }
441 }
442
443 /* add terms by ID */
444 foreach ( $input['terms_by_id'] as $taxonomy => $terms ) {
445 // combine with any previous selections.
446 if ( ! isset( $tax_input[ $taxonomy ] ) || ! is_array( $tax_input[ $taxonomy ] ) ) {
447 $tax_input[ $taxonomy ] = array();
448 }
449
450 $is_hierarchical = is_taxonomy_hierarchical( $taxonomy );
451
452 foreach ( $terms as $term ) {
453 $term = (string) $term; // ctype_digit compat.
454 if ( ! ctype_digit( $term ) ) {
455 // skip anything that doesn't look like an ID.
456 continue;
457 }
458 $term = (int) $term;
459 $term_info = get_term_by( 'id', $term, $taxonomy, ARRAY_A );
460
461 if ( $term_info && ! is_wp_error( $term_info ) ) {
462 if ( $is_hierarchical ) {
463 // Categories must be added by ID.
464 $tax_input[ $taxonomy ][] = $term;
465 } else {
466 // Tags must be added by name.
467 $tax_input[ $taxonomy ][] = $term_info['name'];
468 }
469 }
470 }
471 }
472
473 if ( ( isset( $input['terms']['category'] ) || isset( $input['terms_by_id']['category'] ) )
474 && empty( $tax_input['category'] ) && 'revision' !== $post_type->name ) {
475 $tax_input['category'][] = get_option( 'default_category' );
476 }
477
478 unset( $input['terms'], $input['tags'], $input['categories'], $input['terms_by_id'], $input['tags_by_id'], $input['categories_by_id'] );
479
480 $insert = array();
481
482 if ( ! empty( $input['slug'] ) ) {
483 $insert['post_name'] = $input['slug'];
484 unset( $input['slug'] );
485 }
486
487 if ( isset( $input['discussion'] ) ) {
488 $discussion = (array) $input['discussion'];
489 foreach ( array( 'comment', 'ping' ) as $discussion_type ) {
490 $discussion_open = sprintf( '%ss_open', $discussion_type );
491 $discussion_status = sprintf( '%s_status', $discussion_type );
492
493 if ( isset( $discussion[ $discussion_open ] ) ) {
494 $is_open = WPCOM_JSON_API::is_truthy( $discussion[ $discussion_open ] );
495 $discussion[ $discussion_status ] = $is_open ? 'open' : 'closed';
496 }
497
498 if ( in_array( $discussion[ $discussion_status ], array( 'open', 'closed' ), true ) ) {
499 $insert[ $discussion_status ] = $discussion[ $discussion_status ];
500 }
501 }
502 }
503
504 unset( $input['discussion'] );
505
506 if ( isset( $input['menu_order'] ) ) {
507 $insert['menu_order'] = $input['menu_order'];
508 unset( $input['menu_order'] );
509 }
510
511 $publicize = $input['publicize'] ?? null;
512 unset( $input['publicize'] );
513
514 $publicize_custom_message = $input['publicize_message'] ?? null;
515 unset( $input['publicize_message'] );
516
517 if ( isset( $input['featured_image'] ) ) {
518 $featured_image = trim( $input['featured_image'] );
519 $delete_featured_image = empty( $featured_image );
520 unset( $input['featured_image'] );
521 }
522
523 $metadata = $input['metadata'] ?? null;
524 unset( $input['metadata'] );
525
526 $likes = $input['likes_enabled'] ?? null;
527 unset( $input['likes_enabled'] );
528
529 $sharing = $input['sharing_enabled'] ?? null;
530 unset( $input['sharing_enabled'] );
531
532 $sticky = $input['sticky'] ?? null;
533 unset( $input['sticky'] );
534
535 foreach ( $input as $key => $value ) {
536 $insert[ "post_$key" ] = $value;
537 }
538
539 if ( ! empty( $author_id ) ) {
540 $insert['post_author'] = absint( $author_id );
541 }
542
543 if ( ! empty( $tax_input ) ) {
544 $insert['tax_input'] = $tax_input;
545 }
546
547 $has_media = ! empty( $input['media'] ) ? count( $input['media'] ) : false;
548 $has_media_by_url = ! empty( $input['media_urls'] ) ? count( $input['media_urls'] ) : false;
549 $media_files = array();
550 $media_urls = array();
551 $media_attrs = array();
552 $media_id_string = '';
553
554 if ( $has_media || $has_media_by_url ) {
555 $media_files = ! empty( $input['media'] ) ? $input['media'] : array();
556 $media_urls = ! empty( $input['media_urls'] ) ? $input['media_urls'] : array();
557 $media_attrs = ! empty( $input['media_attrs'] ) ? $input['media_attrs'] : array();
558 $media_results = $this->handle_media_creation_v1_1( $media_files, $media_urls, $media_attrs );
559 $media_id_string = implode( ',', array_filter( array_map( 'absint', $media_results['media_ids'] ) ) );
560 }
561
562 $is_dtp_fb_post = false;
563 if ( in_array( '_dtp_fb', wp_list_pluck( (array) $metadata, 'key' ), true ) ) {
564 $is_dtp_fb_post = true;
565 add_filter( 'rest_api_allowed_public_metadata', array( $this, 'dtp_fb_allowed_metadata' ) );
566 }
567
568 /**
569 * Log Media details for a Post creation request.
570 * Temporary logging for media data.
571 *
572 * @see p1709028174665519-slack-CDLH4C1UZ
573 *
574 * @since 13.2
575 *
576 * @param bool $is_dtp_fb_post Is this for a Facebook import?
577 * @param int $blog_id Blog ID.
578 * @param array $input Whole input.
579 * @param array $media_files File upload data.
580 * @param array $media_urls URLs to fetch.
581 * @param array $media_attrs Attributes corresponding to each entry in `$media_files`/`$media_urls`.
582 * @param array $media_results
583 * - media_ids: IDs created, by index in `$media_files`/`$media_urls`.
584 * - errors: Errors encountered, by index in `$media_files`/`$media_urls`.
585 */
586 do_action( 'jetpack_dtp_fb_media', $is_dtp_fb_post, $blog_id, $input, $media_files, $media_urls, $media_attrs, $media_results );
587
588 if ( $new ) {
589 if ( isset( $input['content'] ) && ! has_shortcode( $input['content'], 'gallery' ) && ( $has_media || $has_media_by_url ) ) {
590 switch ( ( $has_media + $has_media_by_url ) ) {
591 case 0:
592 // No images - do nothing.
593 break;
594 case 1:
595 // 1 image - make it big.
596 $input['content'] = sprintf(
597 "[gallery size=full ids='%s' columns=1]\n\n",
598 $media_id_string
599 ) . $input['content'];
600 $insert['post_content'] = $input['content'];
601 break;
602 default:
603 // Several images - 3 column gallery.
604 $input['content'] = sprintf(
605 "[gallery ids='%s']\n\n",
606 $media_id_string
607 ) . $input['content'];
608 $insert['post_content'] = $input['content'];
609 break;
610 }
611 }
612
613 $insert['post_date'] = $insert['post_date'] ?? '';
614
615 if ( $is_dtp_fb_post ) {
616 $insert = $this->dtp_fb_preprocess_post( $insert, $metadata );
617 }
618
619 $post_id = $this->post_exists( $insert['post_title'], $insert['post_content'], $insert['post_date'], $post_type->name );
620 if ( 0 === $post_id ) {
621 $post_id = wp_insert_post( add_magic_quotes( $insert ), true );
622 }
623 } else {
624 // @phan-suppress-next-line PhanPossiblyUndeclaredVariable -- $post is set and validated several blocks earlier if $new (only set once) is falsy.
625 $insert['ID'] = $post->ID;
626
627 // wp_update_post ignores date unless edit_date is set
628 // See: https://codex.wordpress.org/Function_Reference/wp_update_post#Scheduling_posts
629 // See: https://core.trac.wordpress.org/browser/tags/3.9.2/src/wp-includes/post.php#L3302 .
630 if ( isset( $input['date_gmt'] ) || isset( $input['date'] ) ) {
631 $insert['edit_date'] = true;
632 }
633
634 // this two-step process ensures any changes submitted along with status=trash get saved before trashing.
635 if ( isset( $input['status'] ) && 'trash' === $input['status'] ) {
636 // if we insert it with status='trash', it will get double-trashed, so insert it as a draft first.
637 unset( $insert['status'] );
638 $post_id = wp_update_post( (object) $insert );
639 // now call wp_trash_post so post_meta gets set and any filters get called.
640 wp_trash_post( $post_id );
641 } else {
642 $post_id = wp_update_post( (object) $insert );
643 }
644 }
645
646 if ( ! $post_id || is_wp_error( $post_id ) ) {
647 return $post_id;
648 }
649
650 // make sure this post actually exists and is not an error of some kind (ie, trying to load media in the posts endpoint).
651 $post_check = $this->get_post_by( 'ID', $post_id, $args['context'] );
652 if ( is_wp_error( $post_check ) ) {
653 return $post_check;
654 }
655
656 if ( $media_id_string ) {
657 // Yes - this is really how wp-admin does it.
658 $wpdb->query(
659 $wpdb->prepare(
660 "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.
661 $post_id
662 )
663 );
664 foreach ( $media_results['media_ids'] as $media_id ) {
665 clean_attachment_cache( $media_id );
666 }
667 clean_post_cache( $post_id );
668 }
669
670 // set page template for this post.
671 if ( isset( $input['page_template'] ) && 'page' === $post_type->name ) {
672 $page_template = $input['page_template'];
673 $page_templates = wp_get_theme()->get_page_templates( get_post( $post_id ) );
674 if ( empty( $page_template ) || 'default' === $page_template || isset( $page_templates[ $page_template ] ) ) {
675 update_post_meta( $post_id, '_wp_page_template', $page_template );
676 }
677 }
678
679 // Set like status for the post.
680 /** This filter is documented in modules/likes.php */
681 $sitewide_likes_enabled = (bool) apply_filters( 'wpl_is_enabled_sitewide', ! get_option( 'disabled_likes' ) );
682 if ( $new ) {
683 if ( $sitewide_likes_enabled ) {
684 if ( false === $likes ) {
685 update_post_meta( $post_id, 'switch_like_status', 0 );
686 } else {
687 delete_post_meta( $post_id, 'switch_like_status' );
688 }
689 } elseif ( $likes ) {
690 update_post_meta( $post_id, 'switch_like_status', 1 );
691 } else {
692 delete_post_meta( $post_id, 'switch_like_status' );
693 }
694 } elseif ( isset( $likes ) ) {
695 if ( $sitewide_likes_enabled ) {
696 if ( false === $likes ) {
697 update_post_meta( $post_id, 'switch_like_status', 0 );
698 } else {
699 delete_post_meta( $post_id, 'switch_like_status' );
700 }
701 } elseif ( true === $likes ) {
702 update_post_meta( $post_id, 'switch_like_status', 1 );
703 } else {
704 delete_post_meta( $post_id, 'switch_like_status' );
705 }
706 }
707
708 // Set sharing status of the post.
709 if ( $new ) {
710 $sharing_enabled = isset( $sharing ) ? (bool) $sharing : true;
711 if ( ! $sharing_enabled ) {
712 update_post_meta( $post_id, 'sharing_disabled', 1 );
713 }
714 } elseif ( isset( $sharing ) && true === $sharing ) {
715 delete_post_meta( $post_id, 'sharing_disabled' );
716 } elseif ( isset( $sharing ) && false == $sharing ) { // phpcs:ignore Universal.Operators.StrictComparisons.LooseEqual
717 update_post_meta( $post_id, 'sharing_disabled', 1 );
718 }
719
720 if ( isset( $sticky ) ) {
721 if ( true === $sticky ) {
722 stick_post( $post_id );
723 } else {
724 unstick_post( $post_id );
725 }
726 }
727
728 // WPCOM Specific (Jetpack's will get bumped elsewhere
729 // Tracks how many posts are published and sets meta
730 // so we can track some other cool stats (like likes & comments on posts published).
731 if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
732 if (
733 ( $new && 'publish' === $input['status'] )
734 || (
735 ! $new && isset( $last_status )
736 && 'publish' !== $last_status
737 && isset( $new_status )
738 && 'publish' === $new_status
739 )
740 ) {
741 /** This action is documented in modules/widgets/social-media-icons.php */
742 do_action( 'jetpack_bump_stats_extras', 'api-insights-posts', $this->api->token_details['client_id'] );
743 update_post_meta( $post_id, '_rest_api_published', 1 );
744 update_post_meta( $post_id, '_rest_api_client_id', $this->api->token_details['client_id'] );
745 }
746 }
747
748 // We ask the user/dev to pass Publicize services he/she wants activated for the post, but Publicize expects us
749 // to instead flag the ones we don't want to be skipped. proceed with said logic.
750 // any posts coming from Path (client ID 25952) should also not publicize.
751 if ( false === $publicize || ( isset( $this->api->token_details['client_id'] ) && 25952 === (int) $this->api->token_details['client_id'] ) ) {
752 // No publicize at all, skip all by ID.
753 foreach ( $GLOBALS['publicize_ui']->publicize->get_services( 'all' ) as $name => $service ) {
754 delete_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $name );
755 $service_connections = $GLOBALS['publicize_ui']->publicize->get_connections( $name );
756 if ( ! $service_connections ) {
757 continue;
758 }
759 foreach ( $service_connections as $service_connection ) {
760 update_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $service_connection->unique_id, 1 );
761 }
762 }
763 } elseif ( is_array( $publicize ) && ( count( $publicize ) > 0 ) ) {
764 foreach ( $GLOBALS['publicize_ui']->publicize->get_services( 'all' ) as $name => $service ) {
765 /*
766 * We support both indexed and associative arrays:
767 * * indexed are to pass entire services
768 * * associative are to pass specific connections per service
769 *
770 * We do support mixed arrays: mixed integer and string keys (see 3rd example below).
771 *
772 * EG: array( 'linkedin', 'facebook') will only publicize to those, ignoring the other available services
773 * Form data: publicize[]=linkedin&publicize[]=facebook
774 * EG: array( 'linkedin' => '(int) $pub_conn_id_0, (int) $pub_conn_id_3', 'facebook' => (int) $pub_conn_id_7 ) will publicize to two LinkedIn accounts, and one Facebook connection, of potentially many.
775 * Form data: publicize[linkedin]=$pub_conn_id_0,$pub_conn_id_3&publicize[facebook]=$pub_conn_id_7
776 * EG: array( 'linkedin', 'facebook' => '(int) $pub_conn_id_0, (int) $pub_conn_id_3' ) will publicize to all available LinkedIn accounts, but only 2 of potentially many Facebook connections
777 * Form data: publicize[]=linkedin&publicize[facebook]=$pub_conn_id_0,$pub_conn_id_3
778 */
779
780 // Delete any stale SKIP value for the service by name. We'll add it back by ID.
781 delete_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $name );
782
783 // Get the user's connections.
784 $service_connections = $GLOBALS['publicize_ui']->publicize->get_connections( $name );
785
786 // if the user doesn't have any connections for this service, move on.
787 if ( ! $service_connections ) {
788 continue;
789 }
790
791 if ( ! in_array( $name, $publicize, true ) && ! array_key_exists( $name, $publicize ) ) {
792 // Skip the whole service by adding each connection ID.
793 foreach ( $service_connections as $service_connection ) {
794 update_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $service_connection->unique_id, 1 );
795 }
796 } elseif ( ! empty( $publicize[ $name ] ) ) {
797 // Seems we're being asked to only push to [a] specific connection[s].
798 // Explode the list on commas, which will also support a single passed ID.
799 $requested_connections = explode( ',', ( preg_replace( '/[\s]*/', '', $publicize[ $name ] ) ) );
800
801 // Flag the connections we can't match with the requested list to be skipped.
802 foreach ( $service_connections as $service_connection ) {
803 if ( ! in_array( $service_connection->meta['connection_data']->id, $requested_connections, true ) ) {
804 update_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $service_connection->unique_id, 1 );
805 } else {
806 delete_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $service_connection->unique_id );
807 }
808 }
809 } else {
810 // delete all SKIP values; it's okay to publish to all connected IDs for this service.
811 foreach ( $service_connections as $service_connection ) {
812 delete_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $service_connection->unique_id );
813 }
814 }
815 }
816 }
817
818 if ( $publicize_custom_message !== null ) {
819 if ( empty( $publicize_custom_message ) ) {
820 delete_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_MESS );
821 } else {
822 update_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_MESS, trim( $publicize_custom_message ) );
823 }
824 }
825
826 if ( ! empty( $insert['post_format'] ) ) {
827 if ( 'default' !== strtolower( $insert['post_format'] ) ) {
828 set_post_format( $post_id, $insert['post_format'] );
829 } else {
830 set_post_format( $post_id, get_option( 'default_post_format' ) );
831 }
832 }
833
834 if ( isset( $featured_image ) ) {
835 parent::parse_and_set_featured_image( $post_id, $delete_featured_image, $featured_image );
836 }
837
838 if ( ! empty( $metadata ) ) {
839 foreach ( (array) $metadata as $meta ) {
840
841 $meta = (object) $meta;
842
843 if (
844 in_array( $meta->key, Jetpack_SEO_Posts::POST_META_KEYS_ARRAY, true ) &&
845 ! Jetpack_SEO_Utils::is_enabled_jetpack_seo()
846 ) {
847 return new WP_Error( 'unauthorized', __( 'SEO tools are not enabled for this site.', 'jetpack' ), 403 );
848 }
849
850 $existing_meta_item = new stdClass();
851
852 if ( empty( $meta->operation ) ) {
853 $meta->operation = 'update';
854 }
855
856 if ( ! empty( $meta->value ) ) {
857 if ( 'true' == $meta->value ) { // phpcs:ignore Universal.Operators.StrictComparisons.LooseEqual
858 $meta->value = true;
859 }
860 if ( 'false' == $meta->value ) { // phpcs:ignore Universal.Operators.StrictComparisons.LooseEqual
861 $meta->value = false;
862 }
863 }
864
865 if ( ! empty( $meta->id ) ) {
866 $meta->id = absint( $meta->id );
867 $existing_meta_item = get_metadata_by_mid( 'post', $meta->id );
868 if ( $post_id !== (int) $existing_meta_item->post_id ) {
869 // Only allow updates for metadata on this post.
870 continue;
871 }
872 }
873
874 $unslashed_meta_key = wp_unslash( $meta->key ); // should match what the final key will be.
875 $meta->key = wp_slash( $meta->key );
876 $unslashed_existing_meta_key = isset( $existing_meta_item->meta_key ) ? wp_unslash( $existing_meta_item->meta_key ) : '';
877 $existing_meta_item->meta_key = isset( $existing_meta_item->meta_key ) ? wp_slash( $existing_meta_item->meta_key ) : '';
878
879 // make sure that the meta id passed matches the existing meta key.
880 if ( ! empty( $meta->id ) && ! empty( $meta->key ) ) {
881 $meta_by_id = get_metadata_by_mid( 'post', $meta->id );
882 if ( $meta_by_id->meta_key !== $meta->key ) {
883 continue; // skip this meta.
884 }
885 }
886
887 switch ( $meta->operation ) {
888 case 'delete':
889 if ( ! empty( $meta->id ) && ! empty( $existing_meta_item->meta_key ) && current_user_can( 'delete_post_meta', $post_id, $unslashed_existing_meta_key ) ) {
890 delete_metadata_by_mid( 'post', $meta->id );
891 } elseif ( ! empty( $meta->key ) && ! empty( $meta->previous_value ) && current_user_can( 'delete_post_meta', $post_id, $unslashed_meta_key ) ) {
892 delete_post_meta( $post_id, $meta->key, $meta->previous_value );
893 } elseif ( ! empty( $meta->key ) && current_user_can( 'delete_post_meta', $post_id, $unslashed_meta_key ) ) {
894 delete_post_meta( $post_id, $meta->key );
895 }
896
897 break;
898 case 'add':
899 if ( ! empty( $meta->id ) || ! empty( $meta->previous_value ) ) {
900 break;
901 } 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 ) ) {
902 add_post_meta( $post_id, $meta->key, $meta->value );
903 }
904
905 break;
906 case 'update':
907 if ( ! isset( $meta->value ) ) {
908 break;
909 } 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 ) ) ) {
910 update_metadata_by_mid( 'post', $meta->id, $meta->value );
911 } 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 ) ) ) {
912 update_post_meta( $post_id, $meta->key, $meta->value, $meta->previous_value );
913 } elseif ( ! empty( $meta->key ) && ( current_user_can( 'edit_post_meta', $post_id, $unslashed_meta_key ) || WPCOM_JSON_API_Metadata::is_public( $meta->key ) ) ) {
914 update_post_meta( $post_id, $meta->key, $meta->value );
915 }
916
917 break;
918 }
919 }
920 }
921
922 /** This action is documented in json-endpoints/class.wpcom-json-api-update-post-endpoint.php */
923 do_action( 'rest_api_inserted_post', $post_id, $insert, $new );
924
925 $return = $this->get_post_by( 'ID', $post_id, $args['context'] );
926 if ( ! $return || is_wp_error( $return ) ) {
927 return $return;
928 }
929
930 if ( isset( $input['type'] ) && 'revision' === $input['type'] ) {
931 $return['preview_nonce'] = wp_create_nonce( 'post_preview_' . $input['parent'] );
932 }
933
934 if ( isset( $sticky ) ) {
935 // workaround for sticky test occasionally failing, maybe a race condition with stick_post() above.
936 $return['sticky'] = ( true === $sticky );
937 }
938
939 if ( ! empty( $media_results['errors'] ) ) {
940 /*
941 * Depending on whether the errors array keys are sequential or not
942 * json_encode would transform this into either an array or an object
943 * see https://www.php.net/manual/en/function.json-encode.php#example-3967
944 * We use array_values to always return an array
945 */
946 $return['media_errors'] = array_values( $media_results['errors'] );
947 }
948
949 if ( 'publish' !== $return['status'] && isset( $input['title'] ) ) {
950 $sal_site = $this->get_sal_post_by( 'ID', $post_id, $args['context'] );
951 $return['other_URLs'] = (object) $sal_site->get_permalink_suggestions( $input['title'] );
952 }
953
954 /** This action is documented in json-endpoints/class.wpcom-json-api-site-settings-endpoint.php */
955 do_action( 'wpcom_json_api_objects', 'posts' );
956
957 return $return;
958 }
959
960 /**
961 * Determine if a theme's functions.php file should be loaded.
962 *
963 * @param int $post_id Post ID.
964 *
965 * @return bool
966 */
967 protected function should_load_theme_functions( $post_id = null ) {
968 if ( empty( $post_id ) ) {
969 $input = $this->input( true );
970 $type = $input['type'] ?? null;
971 } else {
972 $type = get_post_type( $post_id );
973 }
974
975 return ! empty( $type ) && ! in_array( $type, array( 'post', 'revision' ), true );
976 }
977
978 /**
979 * Filter for rest_api_allowed_public_metadata.
980 * Adds FB's DTP specific metadata.
981 *
982 * @param array $keys Array of metadata that is accessible by the REST API.
983 *
984 * @return array
985 */
986 public function dtp_fb_allowed_metadata( $keys ) {
987 return array_merge( $keys, array( '_dtp_fb', '_dtp_fb_geo_points', '_dtp_fb_post_link' ) );
988 }
989
990 /**
991 * Pre-process FB DTP posts before inserting.
992 * Here we can improve the DTP content for the following issues:
993 * - Render the map block based on provided coordinates in metadata
994 * - [TODO] Improve the title
995 *
996 * @param array $post Post to be inserted.
997 * @param array $metadata Metadata for the post.
998 *
999 * @return mixed
1000 */
1001 private function dtp_fb_preprocess_post( $post, $metadata ) {
1002 $geo_points_metadata = wp_filter_object_list( $metadata, array( 'key' => '_dtp_fb_geo_points' ), 'and', 'value' );
1003 if ( ! empty( $geo_points_metadata ) ) {
1004 $fb_points = reset( $geo_points_metadata );
1005 $geo_points = array();
1006
1007 // Prepare Geo Points so that they match the format expected by the map block.
1008 foreach ( $fb_points as $fb_point ) {
1009 $geo_points[] = array(
1010 'coordinates' => array(
1011 'longitude' => $fb_point['longitude'],
1012 'latitude' => $fb_point['latitude'],
1013 ),
1014 'title' => $fb_point['name'],
1015 );
1016 }
1017 if ( ! function_exists( 'map_block_from_geo_points' ) ) {
1018 require_once JETPACK__PLUGIN_DIR . 'extensions/blocks/map/map.php';
1019 }
1020 $map_block = map_block_from_geo_points( $geo_points );
1021
1022 $post['post_content'] = $map_block . $post['post_content'];
1023 }
1024
1025 $post['post_format'] = 'aside';
1026
1027 return $post;
1028 }
1029
1030 /**
1031 * Determines if a post exists based on title, content, date, and type,
1032 * But excluding IDs in gallery shortcodes.
1033 * This will prevent duplication of posts created through the API.
1034 *
1035 * @param string $title Post title.
1036 * @param string $content Post content.
1037 * @param string $post_date Post date.
1038 * @param string $type Optional post type.
1039 * @return int Post ID if post exists, 0 otherwise.
1040 */
1041 private function post_exists( $title, $content, $post_date, $type = '' ) {
1042 $date = date_create( $post_date );
1043
1044 $posts = get_posts(
1045 array(
1046 'year' => date_format( $date, 'Y' ),
1047 'monthnum' => date_format( $date, 'n' ),
1048 'day' => date_format( $date, 'j' ),
1049 'hour' => date_format( $date, 'G' ),
1050 'minute' => date_format( $date, 'i' ),
1051 'second' => date_format( $date, 's' ),
1052 'post_type' => $type,
1053 'title' => $title,
1054 'numberposts' => -1,
1055 'suppress_filters' => false,
1056 )
1057 );
1058
1059 foreach ( $posts as $post ) {
1060 $gallery_ids_pattern = "/(\[gallery[^\]]*)(\sids='[\d,]+')([^\]]*\])/";
1061
1062 $post->post_content = preg_replace( $gallery_ids_pattern, '$1$3', $post->post_content );
1063 $content = preg_replace( $gallery_ids_pattern, '$1$3', $content );
1064
1065 if ( $content === $post->post_content ) {
1066 return $post->ID;
1067 }
1068 }
1069
1070 return 0;
1071 }
1072 }
1073