Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
23.38% covered (danger)
23.38%
141 / 603
0.00% covered (danger)
0.00%
0 / 5
CRAP
0.00% covered (danger)
0.00%
0 / 1
WPCOM_JSON_API_Update_Post_v1_2_Endpoint
30.92% covered (danger)
30.92%
141 / 456
0.00% covered (danger)
0.00%
0 / 5
20194.37
0.00% covered (danger)
0.00%
0 / 1
 write_post
30.24% covered (danger)
30.24%
124 / 410
0.00% covered (danger)
0.00%
0 / 1
18979.86
 should_load_theme_functions
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
12
 dtp_fb_allowed_metadata
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 dtp_fb_preprocess_post
0.00% covered (danger)
0.00%
0 / 18
0.00% covered (danger)
0.00%
0 / 1
20
 post_exists
77.27% covered (warning)
77.27%
17 / 22
0.00% covered (danger)
0.00%
0 / 1
3.11
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
12if ( ! defined( 'ABSPATH' ) ) {
13    exit( 0 );
14}
15
16new 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`). Unprotected meta keys can be changed by users who can edit the post. Protected meta keys (those starting with an underscore) can be changed only when the user can edit that key, which requires an <code>auth_callback</code> registered with <code>register_meta()</code> or an <code>auth_post_meta_{$meta_key}</code> filter. Keys allowed by the <code>rest_api_allowed_public_metadata</code> filter can also be added or updated.',
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
95new 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`). Users who can edit the post get its unprotected meta keys. Protected meta keys (those starting with an underscore) are returned only when the user can edit that key, which requires an <code>auth_callback</code> registered with <code>register_meta()</code> or an <code>auth_post_meta_{$meta_key}</code> filter. Keys allowed by the <code>rest_api_allowed_public_metadata</code> filter, plus <code>_thumbnail_id</code> and keys starting with <code>geo_</code> or <code>_wpas_</code>, are returned to anyone who can read the post. Most keys starting with <code>_jetpack_</code>, and all keys starting with <code>_elasticsearch_</code>, are never returned.',
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
172use 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 */
180class 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        // A JSON boolean false is cast to array( false ) by the (array|bool) input type.
589        $skip_publicize = false === $publicize || array( false ) === $publicize;
590
591        $block_publicize_flag = $skip_publicize && ! ( defined( 'IS_WPCOM' ) && IS_WPCOM );
592
593        /**
594         * On Jetpack sites, Sync flags the post for sharing on publish, before the skip meta below exists.
595         * WordPress.com unhooks sharing from save_post above instead.
596         *
597         * @return false
598         */
599        $block_publicize = static function () {
600            return false;
601        };
602        if ( $block_publicize_flag ) {
603            add_filter( 'publicize_should_publicize_published_post', $block_publicize, PHP_INT_MAX );
604        }
605
606        if ( $new ) {
607            if ( isset( $input['content'] ) && ! has_shortcode( $input['content'], 'gallery' ) && ( $has_media || $has_media_by_url ) ) {
608                switch ( ( $has_media + $has_media_by_url ) ) {
609                    case 0:
610                        // No images - do nothing.
611                        break;
612                    case 1:
613                        // 1 image - make it big.
614                        $input['content']       = sprintf(
615                            "[gallery size=full ids='%s' columns=1]\n\n",
616                            $media_id_string
617                        ) . $input['content'];
618                        $insert['post_content'] = $input['content'];
619                        break;
620                    default:
621                        // Several images - 3 column gallery.
622                        $input['content']       = sprintf(
623                            "[gallery ids='%s']\n\n",
624                            $media_id_string
625                        ) . $input['content'];
626                        $insert['post_content'] = $input['content'];
627                        break;
628                }
629            }
630
631            $insert['post_date'] ??= '';
632
633            if ( $is_dtp_fb_post ) {
634                $insert = $this->dtp_fb_preprocess_post( $insert, $metadata );
635            }
636
637            $post_id = $this->post_exists( $insert['post_title'], $insert['post_content'], $insert['post_date'], $post_type->name );
638            if ( 0 === $post_id ) {
639                $post_id = wp_insert_post( add_magic_quotes( $insert ), true );
640            }
641        } else {
642            // @phan-suppress-next-line PhanPossiblyUndeclaredVariable -- $post is set and validated several blocks earlier if $new (only set once) is falsy.
643            $insert['ID'] = $post->ID;
644
645            // wp_update_post ignores date unless edit_date is set
646            // See: https://codex.wordpress.org/Function_Reference/wp_update_post#Scheduling_posts
647            // See: https://core.trac.wordpress.org/browser/tags/3.9.2/src/wp-includes/post.php#L3302 .
648            if ( isset( $input['date_gmt'] ) || isset( $input['date'] ) ) {
649                $insert['edit_date'] = true;
650            }
651
652            // this two-step process ensures any changes submitted along with status=trash get saved before trashing.
653            if ( isset( $input['status'] ) && 'trash' === $input['status'] ) {
654                // if we insert it with status='trash', it will get double-trashed, so insert it as a draft first.
655                unset( $insert['status'] );
656                $post_id = wp_update_post( (object) $insert );
657                // now call wp_trash_post so post_meta gets set and any filters get called.
658                wp_trash_post( $post_id );
659            } else {
660                $post_id = wp_update_post( (object) $insert );
661            }
662        }
663
664        if ( $block_publicize_flag ) {
665            remove_filter( 'publicize_should_publicize_published_post', $block_publicize, PHP_INT_MAX );
666        }
667
668        if ( ! $post_id || is_wp_error( $post_id ) ) {
669            return $post_id;
670        }
671
672        // make sure this post actually exists and is not an error of some kind (ie, trying to load media in the posts endpoint).
673        $post_check = $this->get_post_by( 'ID', $post_id, $args['context'] );
674        if ( is_wp_error( $post_check ) ) {
675            return $post_check;
676        }
677
678        if ( $media_id_string ) {
679            // Yes - this is really how wp-admin does it.
680            $wpdb->query(
681                $wpdb->prepare(
682                    "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.
683                    $post_id
684                )
685            );
686            foreach ( $media_results['media_ids'] as $media_id ) {
687                clean_attachment_cache( $media_id );
688            }
689            clean_post_cache( $post_id );
690        }
691
692        // set page template for this post.
693        if ( isset( $input['page_template'] ) && 'page' === $post_type->name ) {
694            $page_template  = $input['page_template'];
695            $page_templates = wp_get_theme()->get_page_templates( get_post( $post_id ) );
696            if ( empty( $page_template ) || 'default' === $page_template || isset( $page_templates[ $page_template ] ) ) {
697                update_post_meta( $post_id, '_wp_page_template', $page_template );
698            }
699        }
700
701        // Set like status for the post.
702        /** This filter is documented in modules/likes.php */
703        $sitewide_likes_enabled = (bool) apply_filters( 'wpl_is_enabled_sitewide', ! get_option( 'disabled_likes' ) );
704        if ( $new ) {
705            if ( $sitewide_likes_enabled ) {
706                if ( false === $likes ) {
707                    update_post_meta( $post_id, 'switch_like_status', 0 );
708                } else {
709                    delete_post_meta( $post_id, 'switch_like_status' );
710                }
711            } elseif ( $likes ) {
712                update_post_meta( $post_id, 'switch_like_status', 1 );
713            } else {
714                delete_post_meta( $post_id, 'switch_like_status' );
715            }
716        } elseif ( isset( $likes ) ) {
717            if ( $sitewide_likes_enabled ) {
718                if ( false === $likes ) {
719                    update_post_meta( $post_id, 'switch_like_status', 0 );
720                } else {
721                    delete_post_meta( $post_id, 'switch_like_status' );
722                }
723            } elseif ( true === $likes ) {
724                update_post_meta( $post_id, 'switch_like_status', 1 );
725            } else {
726                delete_post_meta( $post_id, 'switch_like_status' );
727            }
728        }
729
730        // Set sharing status of the post.
731        if ( $new ) {
732            $sharing_enabled = isset( $sharing ) ? (bool) $sharing : true;
733            if ( ! $sharing_enabled ) {
734                update_post_meta( $post_id, 'sharing_disabled', 1 );
735            }
736        } elseif ( isset( $sharing ) && true === $sharing ) {
737            delete_post_meta( $post_id, 'sharing_disabled' );
738        } elseif ( isset( $sharing ) && false == $sharing ) { // phpcs:ignore Universal.Operators.StrictComparisons.LooseEqual
739            update_post_meta( $post_id, 'sharing_disabled', 1 );
740        }
741
742        if ( isset( $sticky ) ) {
743            if ( true === $sticky ) {
744                stick_post( $post_id );
745            } else {
746                unstick_post( $post_id );
747            }
748        }
749
750        // WPCOM Specific (Jetpack's will get bumped elsewhere
751        // Tracks how many posts are published and sets meta
752        // so we can track some other cool stats (like likes & comments on posts published).
753        if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
754            if (
755                ( $new && 'publish' === $input['status'] )
756                || (
757                    ! $new && isset( $last_status )
758                    && 'publish' !== $last_status
759                    && isset( $new_status )
760                    && 'publish' === $new_status
761                )
762            ) {
763                /** This action is documented in modules/widgets/social-media-icons.php */
764                do_action( 'jetpack_bump_stats_extras', 'api-insights-posts', $this->api->token_details['client_id'] );
765                update_post_meta( $post_id, '_rest_api_published', 1 );
766                update_post_meta( $post_id, '_rest_api_client_id', $this->api->token_details['client_id'] );
767            }
768        }
769
770        // We ask the user/dev to pass Publicize services he/she wants activated for the post, but Publicize expects us
771        // to instead flag the ones we don't want to be skipped. proceed with said logic.
772        if ( $skip_publicize ) {
773            // No publicize at all, skip all by ID.
774            foreach ( $GLOBALS['publicize_ui']->publicize->get_services( 'all' ) as $name => $service ) {
775                delete_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $name );
776                $service_connections = $GLOBALS['publicize_ui']->publicize->get_connections( $name );
777                if ( ! $service_connections ) {
778                    continue;
779                }
780                foreach ( $service_connections as $service_connection ) {
781                    update_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $GLOBALS['publicize_ui']->publicize->get_connection_unique_id( $service_connection ), 1 );
782                }
783            }
784        } elseif ( is_array( $publicize ) && ( count( $publicize ) > 0 ) ) {
785            foreach ( $GLOBALS['publicize_ui']->publicize->get_services( 'all' ) as $name => $service ) {
786                /*
787                 * We support both indexed and associative arrays:
788                 * * indexed are to pass entire services
789                 * * associative are to pass specific connections per service
790                 *
791                 * We do support mixed arrays: mixed integer and string keys (see 3rd example below).
792                 *
793                 * EG: array( 'linkedin', 'facebook') will only publicize to those, ignoring the other available services
794                 *      Form data: publicize[]=linkedin&publicize[]=facebook
795                 * 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.
796                 *      Form data: publicize[linkedin]=$pub_conn_id_0,$pub_conn_id_3&publicize[facebook]=$pub_conn_id_7
797                 * 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
798                 *      Form data: publicize[]=linkedin&publicize[facebook]=$pub_conn_id_0,$pub_conn_id_3
799                 */
800
801                // Delete any stale SKIP value for the service by name. We'll add it back by ID.
802                delete_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $name );
803
804                // Get the user's connections.
805                $service_connections = $GLOBALS['publicize_ui']->publicize->get_connections( $name );
806
807                // if the user doesn't have any connections for this service, move on.
808                if ( ! $service_connections ) {
809                    continue;
810                }
811
812                if ( ! in_array( $name, $publicize, true ) && ! array_key_exists( $name, $publicize ) ) {
813                    // Skip the whole service by adding each connection ID.
814                    foreach ( $service_connections as $service_connection ) {
815                        update_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $GLOBALS['publicize_ui']->publicize->get_connection_unique_id( $service_connection ), 1 );
816                    }
817                } elseif ( ! empty( $publicize[ $name ] ) ) {
818                    // Seems we're being asked to only push to [a] specific connection[s].
819                    // Explode the list on commas, which will also support a single passed ID.
820                    $requested_connections = explode( ',', ( preg_replace( '/[\s]*/', '', $publicize[ $name ] ) ) );
821
822                    // Flag the connections we can't match with the requested list to be skipped.
823                    foreach ( $service_connections as $service_connection ) {
824                        if ( ! in_array( (string) $GLOBALS['publicize_ui']->publicize->get_connection_id( $service_connection ), $requested_connections, true ) ) {
825                            update_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $GLOBALS['publicize_ui']->publicize->get_connection_unique_id( $service_connection ), 1 );
826                        } else {
827                            delete_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $GLOBALS['publicize_ui']->publicize->get_connection_unique_id( $service_connection ) );
828                        }
829                    }
830                } else {
831                    // delete all SKIP values; it's okay to publish to all connected IDs for this service.
832                    foreach ( $service_connections as $service_connection ) {
833                        delete_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $GLOBALS['publicize_ui']->publicize->get_connection_unique_id( $service_connection ) );
834                    }
835                }
836            }
837        }
838
839        if ( $publicize_custom_message !== null ) {
840            if ( empty( $publicize_custom_message ) ) {
841                delete_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_MESS );
842            } else {
843                update_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_MESS, trim( $publicize_custom_message ) );
844            }
845        }
846
847        if ( ! empty( $insert['post_format'] ) ) {
848            if ( 'default' !== strtolower( $insert['post_format'] ) ) {
849                set_post_format( $post_id, $insert['post_format'] );
850            } else {
851                set_post_format( $post_id, get_option( 'default_post_format' ) );
852            }
853        }
854
855        if ( isset( $featured_image ) ) {
856            parent::parse_and_set_featured_image( $post_id, $delete_featured_image, $featured_image );
857        }
858
859        if ( ! empty( $metadata ) ) {
860            foreach ( (array) $metadata as $meta ) {
861
862                $meta = (object) $meta;
863
864                if (
865                    in_array( $meta->key, Jetpack_SEO_Posts::POST_META_KEYS_ARRAY, true ) &&
866                    ! Jetpack_SEO_Utils::is_enabled_jetpack_seo()
867                ) {
868                    return new WP_Error( 'unauthorized', __( 'SEO tools are not enabled for this site.', 'jetpack' ), 403 );
869                }
870
871                $existing_meta_item = new stdClass();
872
873                if ( empty( $meta->operation ) ) {
874                    $meta->operation = 'update';
875                }
876
877                if ( ! empty( $meta->value ) ) {
878                    if ( 'true' == $meta->value ) { // phpcs:ignore Universal.Operators.StrictComparisons.LooseEqual
879                        $meta->value = true;
880                    }
881                    if ( 'false' == $meta->value ) { // phpcs:ignore Universal.Operators.StrictComparisons.LooseEqual
882                        $meta->value = false;
883                    }
884                }
885
886                if ( ! empty( $meta->id ) ) {
887                    $meta->id           = absint( $meta->id );
888                    $existing_meta_item = get_metadata_by_mid( 'post', $meta->id );
889                    if ( $post_id !== (int) $existing_meta_item->post_id ) {
890                        // Only allow updates for metadata on this post.
891                        continue;
892                    }
893                }
894
895                $unslashed_meta_key           = wp_unslash( $meta->key ); // should match what the final key will be.
896                $meta->key                    = wp_slash( $meta->key );
897                $unslashed_existing_meta_key  = isset( $existing_meta_item->meta_key ) ? wp_unslash( $existing_meta_item->meta_key ) : '';
898                $existing_meta_item->meta_key = isset( $existing_meta_item->meta_key ) ? wp_slash( $existing_meta_item->meta_key ) : '';
899
900                // make sure that the meta id passed matches the existing meta key.
901                if ( ! empty( $meta->id ) && ! empty( $meta->key ) ) {
902                    $meta_by_id = get_metadata_by_mid( 'post', $meta->id );
903                    if ( $meta_by_id->meta_key !== $meta->key ) {
904                        continue; // skip this meta.
905                    }
906                }
907
908                switch ( $meta->operation ) {
909                    case 'delete':
910                        if ( ! empty( $meta->id ) && ! empty( $existing_meta_item->meta_key ) && current_user_can( 'delete_post_meta', $post_id, $unslashed_existing_meta_key ) ) {
911                            delete_metadata_by_mid( 'post', $meta->id );
912                        } elseif ( ! empty( $meta->key ) && ! empty( $meta->previous_value ) && current_user_can( 'delete_post_meta', $post_id, $unslashed_meta_key ) ) {
913                            delete_post_meta( $post_id, $meta->key, $meta->previous_value );
914                        } elseif ( ! empty( $meta->key ) && current_user_can( 'delete_post_meta', $post_id, $unslashed_meta_key ) ) {
915                            delete_post_meta( $post_id, $meta->key );
916                        }
917
918                        break;
919                    case 'add':
920                        if ( ! empty( $meta->id ) || ! empty( $meta->previous_value ) ) {
921                            break;
922                        } 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 ) ) {
923                            add_post_meta( $post_id, $meta->key, $meta->value );
924                        }
925
926                        break;
927                    case 'update':
928                        if ( ! isset( $meta->value ) ) {
929                            break;
930                        } 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 ) ) ) {
931                            update_metadata_by_mid( 'post', $meta->id, $meta->value );
932                        } 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 ) ) ) {
933                            update_post_meta( $post_id, $meta->key, $meta->value, $meta->previous_value );
934                        } elseif ( ! empty( $meta->key ) && ( current_user_can( 'edit_post_meta', $post_id, $unslashed_meta_key ) || WPCOM_JSON_API_Metadata::is_public( $meta->key ) ) ) {
935                            update_post_meta( $post_id, $meta->key, $meta->value );
936                        }
937
938                        break;
939                }
940            }
941        }
942
943        /** This action is documented in json-endpoints/class.wpcom-json-api-update-post-endpoint.php */
944        do_action( 'rest_api_inserted_post', $post_id, $insert, $new );
945
946        $return = $this->get_post_by( 'ID', $post_id, $args['context'] );
947        if ( ! $return || is_wp_error( $return ) ) {
948            return $return;
949        }
950
951        if ( isset( $input['type'] ) && 'revision' === $input['type'] ) {
952            $return['preview_nonce'] = wp_create_nonce( 'post_preview_' . $input['parent'] );
953        }
954
955        if ( isset( $sticky ) ) {
956            // workaround for sticky test occasionally failing, maybe a race condition with stick_post() above.
957            $return['sticky'] = ( true === $sticky );
958        }
959
960        if ( ! empty( $media_results['errors'] ) ) {
961            /*
962             * Depending on whether the errors array keys are sequential or not
963             * json_encode would transform this into either an array or an object
964             * see https://www.php.net/manual/en/function.json-encode.php#example-3967
965             * We use array_values to always return an array
966             */
967            $return['media_errors'] = array_values( $media_results['errors'] );
968        }
969
970        if ( 'publish' !== $return['status'] && isset( $input['title'] ) ) {
971            $sal_site             = $this->get_sal_post_by( 'ID', $post_id, $args['context'] );
972            $return['other_URLs'] = (object) $sal_site->get_permalink_suggestions( $input['title'] );
973        }
974
975        /** This action is documented in json-endpoints/class.wpcom-json-api-site-settings-endpoint.php */
976        do_action( 'wpcom_json_api_objects', 'posts' );
977
978        return $return;
979    }
980
981    /**
982     * Determine if a theme's functions.php file should be loaded.
983     *
984     * @param int $post_id Post ID.
985     *
986     * @return bool
987     */
988    protected function should_load_theme_functions( $post_id = null ) {
989        if ( empty( $post_id ) ) {
990            $input = $this->input( true );
991            $type  = $input['type'] ?? null;
992        } else {
993            $type = get_post_type( $post_id );
994        }
995
996        return ! empty( $type ) && ! in_array( $type, array( 'post', 'revision' ), true );
997    }
998
999    /**
1000     * Filter for rest_api_allowed_public_metadata.
1001     * Adds FB's DTP specific metadata.
1002     *
1003     * @param array $keys Array of metadata that is accessible by the REST API.
1004     *
1005     * @return array
1006     */
1007    public function dtp_fb_allowed_metadata( $keys ) {
1008        return array_merge( $keys, array( '_dtp_fb', '_dtp_fb_geo_points', '_dtp_fb_post_link' ) );
1009    }
1010
1011    /**
1012     * Pre-process FB DTP posts before inserting.
1013     * Here we can improve the DTP content for the following issues:
1014     * - Render the map block based on provided coordinates in metadata
1015     * - [TODO] Improve the title
1016     *
1017     * @param array $post Post to be inserted.
1018     * @param array $metadata Metadata for the post.
1019     *
1020     * @return mixed
1021     */
1022    private function dtp_fb_preprocess_post( $post, $metadata ) {
1023        $geo_points_metadata = wp_filter_object_list( $metadata, array( 'key' => '_dtp_fb_geo_points' ), 'and', 'value' );
1024        if ( ! empty( $geo_points_metadata ) ) {
1025            $fb_points  = reset( $geo_points_metadata );
1026            $geo_points = array();
1027
1028            // Prepare Geo Points so that they match the format expected by the map block.
1029            foreach ( $fb_points as $fb_point ) {
1030                $geo_points[] = array(
1031                    'coordinates' => array(
1032                        'longitude' => $fb_point['longitude'],
1033                        'latitude'  => $fb_point['latitude'],
1034                    ),
1035                    'title'       => $fb_point['name'],
1036                );
1037            }
1038            if ( ! function_exists( 'map_block_from_geo_points' ) ) {
1039                require_once JETPACK__PLUGIN_DIR . 'extensions/blocks/map/map.php';
1040            }
1041            $map_block = map_block_from_geo_points( $geo_points );
1042
1043            $post['post_content'] = $map_block . $post['post_content'];
1044        }
1045
1046        $post['post_format'] = 'aside';
1047
1048        return $post;
1049    }
1050
1051    /**
1052     * Determines if a post exists based on title, content, date, and type,
1053     * But excluding IDs in gallery shortcodes.
1054     * This will prevent duplication of posts created through the API.
1055     *
1056     * @param string $title   Post title.
1057     * @param string $content Post content.
1058     * @param string $post_date    Post date.
1059     * @param string $type    Optional post type.
1060     * @return int Post ID if post exists, 0 otherwise.
1061     */
1062    private function post_exists( $title, $content, $post_date, $type = '' ) {
1063        $date = date_create( $post_date );
1064
1065        $posts = get_posts(
1066            array(
1067                'year'             => date_format( $date, 'Y' ),
1068                'monthnum'         => date_format( $date, 'n' ),
1069                'day'              => date_format( $date, 'j' ),
1070                'hour'             => date_format( $date, 'G' ),
1071                'minute'           => date_format( $date, 'i' ),
1072                'second'           => date_format( $date, 's' ),
1073                'post_type'        => $type,
1074                'title'            => $title,
1075                'numberposts'      => -1,
1076                'suppress_filters' => false,
1077            )
1078        );
1079
1080        foreach ( $posts as $post ) {
1081            $gallery_ids_pattern = "/(\[gallery[^\]]*)(\sids='[\d,]+')([^\]]*\])/";
1082
1083            $post->post_content = preg_replace( $gallery_ids_pattern, '$1$3', $post->post_content );
1084            $content            = preg_replace( $gallery_ids_pattern, '$1$3', $content );
1085
1086            if ( $content === $post->post_content ) {
1087                return $post->ID;
1088            }
1089        }
1090
1091        return 0;
1092    }
1093}