Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
30.72% covered (danger)
30.72%
180 / 586
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
41.00% covered (danger)
41.00%
180 / 439
0.00% covered (danger)
0.00%
0 / 5
11575.74
0.00% covered (danger)
0.00%
0 / 1
 write_post
41.48% covered (danger)
41.48%
163 / 393
0.00% covered (danger)
0.00%
0 / 1
10281.77
 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        // The (array|bool) input type casts a JSON boolean to array( true ) or array( false ).
513        if ( array( true ) === $publicize || array( false ) === $publicize ) {
514            $publicize = $publicize[0];
515        }
516        unset( $input['publicize'] );
517
518        $publicize_custom_message = $input['publicize_message'] ?? null;
519        unset( $input['publicize_message'] );
520
521        if ( isset( $input['featured_image'] ) ) {
522            $featured_image        = trim( $input['featured_image'] );
523            $delete_featured_image = empty( $featured_image );
524            unset( $input['featured_image'] );
525        }
526
527        $metadata = $input['metadata'] ?? null;
528        unset( $input['metadata'] );
529
530        $likes = $input['likes_enabled'] ?? null;
531        unset( $input['likes_enabled'] );
532
533        $sharing = $input['sharing_enabled'] ?? null;
534        unset( $input['sharing_enabled'] );
535
536        $sticky = $input['sticky'] ?? null;
537        unset( $input['sticky'] );
538
539        foreach ( $input as $key => $value ) {
540            $insert[ "post_$key" ] = $value;
541        }
542
543        if ( ! empty( $author_id ) ) {
544            $insert['post_author'] = absint( $author_id );
545        }
546
547        if ( ! empty( $tax_input ) ) {
548            $insert['tax_input'] = $tax_input;
549        }
550
551        $has_media        = ! empty( $input['media'] ) ? count( $input['media'] ) : false;
552        $has_media_by_url = ! empty( $input['media_urls'] ) ? count( $input['media_urls'] ) : false;
553        $media_files      = array();
554        $media_urls       = array();
555        $media_attrs      = array();
556        $media_id_string  = '';
557
558        if ( $has_media || $has_media_by_url ) {
559            $media_files     = ! empty( $input['media'] ) ? $input['media'] : array();
560            $media_urls      = ! empty( $input['media_urls'] ) ? $input['media_urls'] : array();
561            $media_attrs     = ! empty( $input['media_attrs'] ) ? $input['media_attrs'] : array();
562            $media_results   = $this->handle_media_creation_v1_1( $media_files, $media_urls, $media_attrs );
563            $media_id_string = implode( ',', array_filter( array_map( 'absint', $media_results['media_ids'] ) ) );
564        }
565
566        $is_dtp_fb_post = false;
567        if ( in_array( '_dtp_fb', wp_list_pluck( (array) $metadata, 'key' ), true ) ) {
568            $is_dtp_fb_post = true;
569            add_filter( 'rest_api_allowed_public_metadata', array( $this, 'dtp_fb_allowed_metadata' ) );
570        }
571
572        /**
573         * Log Media details for a Post creation request.
574         * Temporary logging for media data.
575         *
576         * @see p1709028174665519-slack-CDLH4C1UZ
577         *
578         * @since 13.2
579         *
580         * @param bool  $is_dtp_fb_post Is this for a Facebook import?
581         * @param int   $blog_id        Blog ID.
582         * @param array $input          Whole input.
583         * @param array $media_files    File upload data.
584         * @param array $media_urls     URLs to fetch.
585         * @param array $media_attrs    Attributes corresponding to each entry in `$media_files`/`$media_urls`.
586         * @param array $media_results
587         *  - media_ids: IDs created, by index in `$media_files`/`$media_urls`.
588         *  - errors: Errors encountered, by index in `$media_files`/`$media_urls`.
589         */
590        do_action( 'jetpack_dtp_fb_media', $is_dtp_fb_post, $blog_id, $input, $media_files, $media_urls, $media_attrs, $media_results );
591
592        $skip_publicize = false === $publicize;
593
594        $block_publicize_flag = $skip_publicize && ! ( defined( 'IS_WPCOM' ) && IS_WPCOM );
595
596        /**
597         * On Jetpack sites, Sync flags the post for sharing on publish, before the skip meta below exists.
598         * WordPress.com unhooks sharing from save_post above instead.
599         *
600         * @return false
601         */
602        $block_publicize = static function () {
603            return false;
604        };
605        if ( $block_publicize_flag ) {
606            add_filter( 'publicize_should_publicize_published_post', $block_publicize, PHP_INT_MAX );
607        }
608
609        $skip_meta_post_id = 0;
610        $skip_meta_hook    = $this->hook_publicize_skip_meta( $new ? 0 : (int) $post_id, $post_type->name, $publicize, $skip_meta_post_id );
611
612        if ( $new ) {
613            if ( isset( $input['content'] ) && ! has_shortcode( $input['content'], 'gallery' ) && ( $has_media || $has_media_by_url ) ) {
614                switch ( ( $has_media + $has_media_by_url ) ) {
615                    case 0:
616                        // No images - do nothing.
617                        break;
618                    case 1:
619                        // 1 image - make it big.
620                        $input['content']       = sprintf(
621                            "[gallery size=full ids='%s' columns=1]\n\n",
622                            $media_id_string
623                        ) . $input['content'];
624                        $insert['post_content'] = $input['content'];
625                        break;
626                    default:
627                        // Several images - 3 column gallery.
628                        $input['content']       = sprintf(
629                            "[gallery ids='%s']\n\n",
630                            $media_id_string
631                        ) . $input['content'];
632                        $insert['post_content'] = $input['content'];
633                        break;
634                }
635            }
636
637            $insert['post_date'] ??= '';
638
639            if ( $is_dtp_fb_post ) {
640                $insert = $this->dtp_fb_preprocess_post( $insert, $metadata );
641            }
642
643            $post_id = $this->post_exists( $insert['post_title'], $insert['post_content'], $insert['post_date'], $post_type->name );
644            if ( 0 === $post_id ) {
645                $post_id = wp_insert_post( add_magic_quotes( $insert ), true );
646            }
647        } else {
648            // @phan-suppress-next-line PhanPossiblyUndeclaredVariable -- $post is set and validated several blocks earlier if $new (only set once) is falsy.
649            $insert['ID'] = $post->ID;
650
651            // wp_update_post ignores date unless edit_date is set
652            // See: https://codex.wordpress.org/Function_Reference/wp_update_post#Scheduling_posts
653            // See: https://core.trac.wordpress.org/browser/tags/3.9.2/src/wp-includes/post.php#L3302 .
654            if ( isset( $input['date_gmt'] ) || isset( $input['date'] ) ) {
655                $insert['edit_date'] = true;
656            }
657
658            // this two-step process ensures any changes submitted along with status=trash get saved before trashing.
659            if ( isset( $input['status'] ) && 'trash' === $input['status'] ) {
660                // if we insert it with status='trash', it will get double-trashed, so insert it as a draft first.
661                unset( $insert['status'] );
662                $post_id = wp_update_post( (object) $insert );
663                // now call wp_trash_post so post_meta gets set and any filters get called.
664                wp_trash_post( $post_id );
665            } else {
666                $post_id = wp_update_post( (object) $insert );
667            }
668        }
669
670        if ( $block_publicize_flag ) {
671            remove_filter( 'publicize_should_publicize_published_post', $block_publicize, PHP_INT_MAX );
672        }
673
674        if ( $skip_meta_hook ) {
675            remove_action( 'wp_insert_post', $skip_meta_hook, PHP_INT_MAX );
676        }
677
678        if ( ! $post_id || is_wp_error( $post_id ) ) {
679            return $post_id;
680        }
681
682        // make sure this post actually exists and is not an error of some kind (ie, trying to load media in the posts endpoint).
683        $post_check = $this->get_post_by( 'ID', $post_id, $args['context'] );
684        if ( is_wp_error( $post_check ) ) {
685            return $post_check;
686        }
687
688        if ( $media_id_string ) {
689            // Yes - this is really how wp-admin does it.
690            $wpdb->query(
691                $wpdb->prepare(
692                    "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.
693                    $post_id
694                )
695            );
696            foreach ( $media_results['media_ids'] as $media_id ) {
697                clean_attachment_cache( $media_id );
698            }
699            clean_post_cache( $post_id );
700        }
701
702        // set page template for this post.
703        if ( isset( $input['page_template'] ) && 'page' === $post_type->name ) {
704            $page_template  = $input['page_template'];
705            $page_templates = wp_get_theme()->get_page_templates( get_post( $post_id ) );
706            if ( empty( $page_template ) || 'default' === $page_template || isset( $page_templates[ $page_template ] ) ) {
707                update_post_meta( $post_id, '_wp_page_template', $page_template );
708            }
709        }
710
711        // Set like status for the post.
712        /** This filter is documented in modules/likes.php */
713        $sitewide_likes_enabled = (bool) apply_filters( 'wpl_is_enabled_sitewide', ! get_option( 'disabled_likes' ) );
714        if ( $new ) {
715            if ( $sitewide_likes_enabled ) {
716                if ( false === $likes ) {
717                    update_post_meta( $post_id, 'switch_like_status', 0 );
718                } else {
719                    delete_post_meta( $post_id, 'switch_like_status' );
720                }
721            } elseif ( $likes ) {
722                update_post_meta( $post_id, 'switch_like_status', 1 );
723            } else {
724                delete_post_meta( $post_id, 'switch_like_status' );
725            }
726        } elseif ( isset( $likes ) ) {
727            if ( $sitewide_likes_enabled ) {
728                if ( false === $likes ) {
729                    update_post_meta( $post_id, 'switch_like_status', 0 );
730                } else {
731                    delete_post_meta( $post_id, 'switch_like_status' );
732                }
733            } elseif ( true === $likes ) {
734                update_post_meta( $post_id, 'switch_like_status', 1 );
735            } else {
736                delete_post_meta( $post_id, 'switch_like_status' );
737            }
738        }
739
740        // Set sharing status of the post.
741        if ( $new ) {
742            $sharing_enabled = isset( $sharing ) ? (bool) $sharing : true;
743            if ( ! $sharing_enabled ) {
744                update_post_meta( $post_id, 'sharing_disabled', 1 );
745            }
746        } elseif ( isset( $sharing ) && true === $sharing ) {
747            delete_post_meta( $post_id, 'sharing_disabled' );
748        } elseif ( isset( $sharing ) && false == $sharing ) { // phpcs:ignore Universal.Operators.StrictComparisons.LooseEqual
749            update_post_meta( $post_id, 'sharing_disabled', 1 );
750        }
751
752        if ( isset( $sticky ) ) {
753            if ( true === $sticky ) {
754                stick_post( $post_id );
755            } else {
756                unstick_post( $post_id );
757            }
758        }
759
760        // WPCOM Specific (Jetpack's will get bumped elsewhere
761        // Tracks how many posts are published and sets meta
762        // so we can track some other cool stats (like likes & comments on posts published).
763        if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
764            if (
765                ( $new && 'publish' === $input['status'] )
766                || (
767                    ! $new && isset( $last_status )
768                    && 'publish' !== $last_status
769                    && isset( $new_status )
770                    && 'publish' === $new_status
771                )
772            ) {
773                /** This action is documented in modules/widgets/social-media-icons.php */
774                do_action( 'jetpack_bump_stats_extras', 'api-insights-posts', $this->api->token_details['client_id'] );
775                update_post_meta( $post_id, '_rest_api_published', 1 );
776                update_post_meta( $post_id, '_rest_api_client_id', $this->api->token_details['client_id'] );
777            }
778        }
779
780        if ( (int) $post_id !== $skip_meta_post_id ) {
781            $this->update_publicize_skip_meta( $post_id, $publicize );
782        }
783
784        if ( $publicize_custom_message !== null ) {
785            if ( empty( $publicize_custom_message ) ) {
786                delete_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_MESS );
787            } else {
788                update_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_MESS, trim( $publicize_custom_message ) );
789            }
790        }
791
792        if ( ! empty( $insert['post_format'] ) ) {
793            if ( 'default' !== strtolower( $insert['post_format'] ) ) {
794                set_post_format( $post_id, $insert['post_format'] );
795            } else {
796                set_post_format( $post_id, get_option( 'default_post_format' ) );
797            }
798        }
799
800        if ( isset( $featured_image ) ) {
801            parent::parse_and_set_featured_image( $post_id, $delete_featured_image, $featured_image );
802        }
803
804        if ( ! empty( $metadata ) ) {
805            foreach ( (array) $metadata as $meta ) {
806
807                $meta = (object) $meta;
808
809                if (
810                    in_array( $meta->key, Jetpack_SEO_Posts::POST_META_KEYS_ARRAY, true ) &&
811                    ! Jetpack_SEO_Utils::is_enabled_jetpack_seo()
812                ) {
813                    return new WP_Error( 'unauthorized', __( 'SEO tools are not enabled for this site.', 'jetpack' ), 403 );
814                }
815
816                $existing_meta_item = new stdClass();
817
818                if ( empty( $meta->operation ) ) {
819                    $meta->operation = 'update';
820                }
821
822                if ( ! empty( $meta->value ) ) {
823                    if ( 'true' == $meta->value ) { // phpcs:ignore Universal.Operators.StrictComparisons.LooseEqual
824                        $meta->value = true;
825                    }
826                    if ( 'false' == $meta->value ) { // phpcs:ignore Universal.Operators.StrictComparisons.LooseEqual
827                        $meta->value = false;
828                    }
829                }
830
831                if ( ! empty( $meta->id ) ) {
832                    $meta->id           = absint( $meta->id );
833                    $existing_meta_item = get_metadata_by_mid( 'post', $meta->id );
834                    if ( $post_id !== (int) $existing_meta_item->post_id ) {
835                        // Only allow updates for metadata on this post.
836                        continue;
837                    }
838                }
839
840                $unslashed_meta_key           = wp_unslash( $meta->key ); // should match what the final key will be.
841                $meta->key                    = wp_slash( $meta->key );
842                $unslashed_existing_meta_key  = isset( $existing_meta_item->meta_key ) ? wp_unslash( $existing_meta_item->meta_key ) : '';
843                $existing_meta_item->meta_key = isset( $existing_meta_item->meta_key ) ? wp_slash( $existing_meta_item->meta_key ) : '';
844
845                // make sure that the meta id passed matches the existing meta key.
846                if ( ! empty( $meta->id ) && ! empty( $meta->key ) ) {
847                    $meta_by_id = get_metadata_by_mid( 'post', $meta->id );
848                    if ( $meta_by_id->meta_key !== $meta->key ) {
849                        continue; // skip this meta.
850                    }
851                }
852
853                switch ( $meta->operation ) {
854                    case 'delete':
855                        if ( ! empty( $meta->id ) && ! empty( $existing_meta_item->meta_key ) && current_user_can( 'delete_post_meta', $post_id, $unslashed_existing_meta_key ) ) {
856                            delete_metadata_by_mid( 'post', $meta->id );
857                        } elseif ( ! empty( $meta->key ) && ! empty( $meta->previous_value ) && current_user_can( 'delete_post_meta', $post_id, $unslashed_meta_key ) ) {
858                            delete_post_meta( $post_id, $meta->key, $meta->previous_value );
859                        } elseif ( ! empty( $meta->key ) && current_user_can( 'delete_post_meta', $post_id, $unslashed_meta_key ) ) {
860                            delete_post_meta( $post_id, $meta->key );
861                        }
862
863                        break;
864                    case 'add':
865                        if ( ! empty( $meta->id ) || ! empty( $meta->previous_value ) ) {
866                            break;
867                        } 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 ) ) {
868                            add_post_meta( $post_id, $meta->key, $meta->value );
869                        }
870
871                        break;
872                    case 'update':
873                        if ( ! isset( $meta->value ) ) {
874                            break;
875                        } 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 ) ) ) {
876                            update_metadata_by_mid( 'post', $meta->id, $meta->value );
877                        } 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 ) ) ) {
878                            update_post_meta( $post_id, $meta->key, $meta->value, $meta->previous_value );
879                        } elseif ( ! empty( $meta->key ) && ( current_user_can( 'edit_post_meta', $post_id, $unslashed_meta_key ) || WPCOM_JSON_API_Metadata::is_public( $meta->key ) ) ) {
880                            update_post_meta( $post_id, $meta->key, $meta->value );
881                        }
882
883                        break;
884                }
885            }
886        }
887
888        /** This action is documented in json-endpoints/class.wpcom-json-api-update-post-endpoint.php */
889        do_action( 'rest_api_inserted_post', $post_id, $insert, $new );
890
891        $return = $this->get_post_by( 'ID', $post_id, $args['context'] );
892        if ( ! $return || is_wp_error( $return ) ) {
893            return $return;
894        }
895
896        if ( isset( $input['type'] ) && 'revision' === $input['type'] ) {
897            $return['preview_nonce'] = wp_create_nonce( 'post_preview_' . $input['parent'] );
898        }
899
900        if ( isset( $sticky ) ) {
901            // workaround for sticky test occasionally failing, maybe a race condition with stick_post() above.
902            $return['sticky'] = ( true === $sticky );
903        }
904
905        if ( ! empty( $media_results['errors'] ) ) {
906            /*
907             * Depending on whether the errors array keys are sequential or not
908             * json_encode would transform this into either an array or an object
909             * see https://www.php.net/manual/en/function.json-encode.php#example-3967
910             * We use array_values to always return an array
911             */
912            $return['media_errors'] = array_values( $media_results['errors'] );
913        }
914
915        if ( 'publish' !== $return['status'] && isset( $input['title'] ) ) {
916            $sal_site             = $this->get_sal_post_by( 'ID', $post_id, $args['context'] );
917            $return['other_URLs'] = (object) $sal_site->get_permalink_suggestions( $input['title'] );
918        }
919
920        /** This action is documented in json-endpoints/class.wpcom-json-api-site-settings-endpoint.php */
921        do_action( 'wpcom_json_api_objects', 'posts' );
922
923        return $return;
924    }
925
926    /**
927     * Determine if a theme's functions.php file should be loaded.
928     *
929     * @param int $post_id Post ID.
930     *
931     * @return bool
932     */
933    protected function should_load_theme_functions( $post_id = null ) {
934        if ( empty( $post_id ) ) {
935            $input = $this->input( true );
936            $type  = $input['type'] ?? null;
937        } else {
938            $type = get_post_type( $post_id );
939        }
940
941        return ! empty( $type ) && ! in_array( $type, array( 'post', 'revision' ), true );
942    }
943
944    /**
945     * Filter for rest_api_allowed_public_metadata.
946     * Adds FB's DTP specific metadata.
947     *
948     * @param array $keys Array of metadata that is accessible by the REST API.
949     *
950     * @return array
951     */
952    public function dtp_fb_allowed_metadata( $keys ) {
953        return array_merge( $keys, array( '_dtp_fb', '_dtp_fb_geo_points', '_dtp_fb_post_link' ) );
954    }
955
956    /**
957     * Pre-process FB DTP posts before inserting.
958     * Here we can improve the DTP content for the following issues:
959     * - Render the map block based on provided coordinates in metadata
960     * - [TODO] Improve the title
961     *
962     * @param array $post Post to be inserted.
963     * @param array $metadata Metadata for the post.
964     *
965     * @return mixed
966     */
967    private function dtp_fb_preprocess_post( $post, $metadata ) {
968        $geo_points_metadata = wp_filter_object_list( $metadata, array( 'key' => '_dtp_fb_geo_points' ), 'and', 'value' );
969        if ( ! empty( $geo_points_metadata ) ) {
970            $fb_points  = reset( $geo_points_metadata );
971            $geo_points = array();
972
973            // Prepare Geo Points so that they match the format expected by the map block.
974            foreach ( $fb_points as $fb_point ) {
975                $geo_points[] = array(
976                    'coordinates' => array(
977                        'longitude' => $fb_point['longitude'],
978                        'latitude'  => $fb_point['latitude'],
979                    ),
980                    'title'       => $fb_point['name'],
981                );
982            }
983            if ( ! function_exists( 'map_block_from_geo_points' ) ) {
984                require_once JETPACK__PLUGIN_DIR . 'extensions/blocks/map/map.php';
985            }
986            $map_block = map_block_from_geo_points( $geo_points );
987
988            $post['post_content'] = $map_block . $post['post_content'];
989        }
990
991        $post['post_format'] = 'aside';
992
993        return $post;
994    }
995
996    /**
997     * Determines if a post exists based on title, content, date, and type,
998     * But excluding IDs in gallery shortcodes.
999     * This will prevent duplication of posts created through the API.
1000     *
1001     * @param string $title   Post title.
1002     * @param string $content Post content.
1003     * @param string $post_date    Post date.
1004     * @param string $type    Optional post type.
1005     * @return int Post ID if post exists, 0 otherwise.
1006     */
1007    private function post_exists( $title, $content, $post_date, $type = '' ) {
1008        $date = date_create( $post_date );
1009
1010        $posts = get_posts(
1011            array(
1012                'year'             => date_format( $date, 'Y' ),
1013                'monthnum'         => date_format( $date, 'n' ),
1014                'day'              => date_format( $date, 'j' ),
1015                'hour'             => date_format( $date, 'G' ),
1016                'minute'           => date_format( $date, 'i' ),
1017                'second'           => date_format( $date, 's' ),
1018                'post_type'        => $type,
1019                'title'            => $title,
1020                'numberposts'      => -1,
1021                'suppress_filters' => false,
1022            )
1023        );
1024
1025        foreach ( $posts as $post ) {
1026            $gallery_ids_pattern = "/(\[gallery[^\]]*)(\sids='[\d,]+')([^\]]*\])/";
1027
1028            $post->post_content = preg_replace( $gallery_ids_pattern, '$1$3', $post->post_content );
1029            $content            = preg_replace( $gallery_ids_pattern, '$1$3', $content );
1030
1031            if ( $content === $post->post_content ) {
1032                return $post->ID;
1033            }
1034        }
1035
1036        return 0;
1037    }
1038}