Completed
Push — fix/nav-unification-menu-open-... ( d629c6...f468b4 )
by
unknown
17:24 queued 09:08
created

class.wpcom-json-api-update-post-v1-2-endpoint.php (2 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
new WPCOM_JSON_API_Update_Post_v1_2_Endpoint( array(
4
	'description' => 'Create a post.',
5
	'group'       => 'posts',
6
	'stat'        => 'posts:new',
7
	'min_version' => '1.2',
8
	'max_version' => '1.2',
9
	'method'      => 'POST',
10
	'path'        => '/sites/%s/posts/new',
11
	'path_labels' => array(
12
		'$site' => '(int|string) Site ID or domain',
13
	),
14
	'query_parameters' => array(
15
		'autosave' => '(bool) True if the post was saved automatically.',
16
	),
17
18
	'request_format' => array(
19
		// explicitly document all input
20
		'date'      => "(ISO 8601 datetime) The post's creation time.",
21
		'title'     => '(HTML) The post title.',
22
		'content'   => '(HTML) The post content.',
23
		'excerpt'   => '(HTML) An optional post excerpt.',
24
		'slug'      => '(string) The name (slug) for the post, used in URLs.',
25
		'author'    => '(string) The username or ID for the user to assign the post to.',
26
		'publicize' => '(array|bool) True or false if the post be publicized to external services. An array of services if we only want to publicize to a select few. Defaults to true.',
27
		'publicize_message' => '(string) Custom message to be publicized to external services.',
28
		'status'    => array(
29
			'publish' => 'Publish the post.',
30
			'private' => 'Privately publish the post.',
31
			'draft'   => 'Save the post as a draft.',
32
			'pending' => 'Mark the post as pending editorial approval.',
33
			'future'  => 'Schedule the post (alias for publish; you must also set a future date).',
34
			'auto-draft' => 'Save a placeholder for a newly created post, with no content.',
35
		),
36
		'sticky'    => array(
37
			'false'   => 'Post is not marked as sticky.',
38
			'true'    => 'Stick the post to the front page.',
39
		),
40
		'password'  => '(string) The plaintext password protecting the post, or, more likely, the empty string if the post is not password protected.',
41
		'parent'    => "(int) The post ID of the new post's parent.",
42
		'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.",
43
		'terms'      => '(object) Mapping of taxonomy to comma-separated list or array of term names',
44
		'categories' => "(array|string) Comma-separated list or array of category names",
45
		'tags'       => "(array|string) Comma-separated list or array of tag names",
46
		'terms_by_id'      => '(object) Mapping of taxonomy to comma-separated list or array of term IDs',
47
		'categories_by_id' => "(array|string) Comma-separated list or array of category IDs",
48
		'tags_by_id'       => "(array|string) Comma-separated list or array of tag IDs",
49
		'format'     => array_merge( array( 'default' => 'Use default post format' ), get_post_format_strings() ),
50
		'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.",
51
		'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 />" .
52
		 				"<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>",
53
		'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.",
54
		'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 />" .
55
		                 "<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>",
56
		'metadata'      => "(array) Array of metadata objects containing the following properties: `key` (metadata key), `id` (meta ID), `previous_value` (if set, the action will only occur for the provided previous value), `value` (the new value to set the meta to), `operation` (the operation to perform: `update` or `add`; defaults to `update`). All unprotected meta keys are available by default for read requests. Both unprotected and protected meta keys are avaiable for authenticated requests with proper capabilities. Protected meta keys can be made available with the <code>rest_api_allowed_public_metadata</code> filter.",
57
		'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`',
58
		'likes_enabled' => "(bool) Should the post be open to likes? Defaults to the blog's preference.",
59
		'sharing_enabled' => "(bool) Should sharing buttons show on this post? Defaults to true.",
60
		'menu_order'    => "(int) (Pages Only) the order pages should appear in. Use 0 to maintain alphabetical order.",
61
		'page_template' => '(string) (Pages Only) The page template this page should use.',
62
	),
63
64
	'example_request'      => 'https://public-api.wordpress.com/rest/v1.2/sites/82974409/posts/new/',
65
66
	'example_request_data' => array(
67
		'headers' => array(
68
			'authorization' => 'Bearer YOUR_API_TOKEN'
69
		),
70
71
		'body' => array(
72
			'title'      => 'Hello World',
73
			'content'    => 'Hello. I am a test post. I was created by the API',
74
			'tags'       => 'tests',
75
			'categories' => 'API'
76
		)
77
	)
78
) );
79
80
new WPCOM_JSON_API_Update_Post_v1_2_Endpoint( array(
81
	'description' => 'Edit a post.',
82
	'group'       => 'posts',
83
	'stat'        => 'posts:1:POST',
84
	'min_version' => '1.2',
85
	'max_version' => '1.2',
86
	'method'      => 'POST',
87
	'path'        => '/sites/%s/posts/%d',
88
	'path_labels' => array(
89
		'$site'    => '(int|string) Site ID or domain',
90
		'$post_ID' => '(int) The post ID',
91
	),
92
	'query_parameters' => array(
93
		'autosave' => '(bool) True if the post was saved automatically.',
94
	),
95
96
	'request_format' => array(
97
		'date'      => "(ISO 8601 datetime) The post's creation time.",
98
		'title'     => '(HTML) The post title.',
99
		'content'   => '(HTML) The post content.',
100
		'excerpt'   => '(HTML) An optional post excerpt.',
101
		'slug'      => '(string) The name (slug) for the post, used in URLs.',
102
		'author'    => '(string) The username or ID for the user to assign the post to.',
103
		'publicize' => '(array|bool) True or false if the post be publicized to external services. An array of services if we only want to publicize to a select few. Defaults to true.',
104
		'publicize_message' => '(string) Custom message to be publicized to external services.',
105
		'status'    => array(
106
			'publish' => 'Publish the post.',
107
			'private' => 'Privately publish the post.',
108
			'draft'   => 'Save the post as a draft.',
109
			'future'  => 'Schedule the post (alias for publish; you must also set a future date).',
110
			'pending' => 'Mark the post as pending editorial approval.',
111
			'trash'   => 'Set the post as trashed.',
112
		),
113
		'sticky'    => array(
114
			'false'   => 'Post is not marked as sticky.',
115
			'true'    => 'Stick the post to the front page.',
116
		),
117
		'password'   => '(string) The plaintext password protecting the post, or, more likely, the empty string if the post is not password protected.',
118
		'parent'     => "(int) The post ID of the new post's parent.",
119
		'terms'      => '(object) Mapping of taxonomy to comma-separated list or array of term names',
120
		'terms_by_id' => '(object) Mapping of taxonomy to comma-separated list or array of term IDs',
121
		'categories' => "(array|string) Comma-separated list or array of category names",
122
		'categories_by_id' => "(array|string) Comma-separated list or array of category IDs",
123
		'tags'       => "(array|string) Comma-separated list or array of tag names",
124
		'tags_by_id'       => "(array|string) Comma-separated list or array of tag IDs",
125
		'format'     => array_merge( array( 'default' => 'Use default post format' ), get_post_format_strings() ),
126
		'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`',
127
		'likes_enabled' => "(bool) Should the post be open to likes?",
128
		'menu_order'    => "(int) (Pages only) the order pages should appear in. Use 0 to maintain alphabetical order.",
129
		'page_template' => '(string) (Pages Only) The page template this page should use.',
130
		'sharing_enabled' => "(bool) Should sharing buttons show on this post?",
131
		'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.",
132
		'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 />" .
133
		 				"<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>",
134
		'media_urls' => "(array) An array of URLs for images to attach to a post. Sideloads the media in for a post.",
135
		'metadata'      => "(array) Array of metadata objects containing the following properties: `key` (metadata key), `id` (meta ID), `previous_value` (if set, the action will only occur for the provided previous value), `value` (the new value to set the meta to), `operation` (the operation to perform: `update` or `add`; defaults to `update`). All unprotected meta keys are available by default for read requests. Both unprotected and protected meta keys are available for authenticated requests with proper capabilities. Protected meta keys can be made available with the <code>rest_api_allowed_public_metadata</code> filter.",
136
	),
137
138
	'example_request'      => 'https://public-api.wordpress.com/rest/v1.2/sites/82974409/posts/881',
139
140
	'example_request_data' => array(
141
		'headers' => array(
142
			'authorization' => 'Bearer YOUR_API_TOKEN'
143
		),
144
145
		'body' => array(
146
			'title'      => 'Hello World (Again)',
147
			'content'    => 'Hello. I am an edited post. I was edited by the API',
148
			'tags'       => 'tests',
149
			'categories' => 'API'
150
		)
151
	)
152
) );
153
154
class WPCOM_JSON_API_Update_Post_v1_2_Endpoint extends WPCOM_JSON_API_Update_Post_v1_1_Endpoint {
155
156
	// /sites/%s/posts/new       -> $blog_id
157
	// /sites/%s/posts/%d        -> $blog_id, $post_id
158
	function write_post( $path, $blog_id, $post_id ) {
159
		global $wpdb;
160
161
		$new  = $this->api->ends_with( $path, '/new' );
162
		$args = $this->query_args();
163
164
		if ( ! empty( $args['autosave'] ) ) {
165
			define( 'DOING_AUTOSAVE', true );
166
		}
167
168
		// unhook publicize, it's hooked again later -- without this, skipping services is impossible
169 View Code Duplication
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
170
			remove_action( 'save_post', array( $GLOBALS['publicize_ui']->publicize, 'async_publicize_post' ), 100, 2 );
0 ignored issues
show
The call to remove_action() has too many arguments starting with 2.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
171
			add_action( 'rest_api_inserted_post', array( $GLOBALS['publicize_ui']->publicize, 'async_publicize_post' ) );
172
173
			if ( $this->should_load_theme_functions( $post_id ) ) {
174
				$this->load_theme_functions();
175
			}
176
		}
177
178
		if ( $new ) {
179
			$input = $this->input( true );
180
181
			// 'future' is an alias for 'publish' for now
182
			if ( isset( $input['status'] ) && 'future' === $input['status'] ) {
183
				$input['status'] = 'publish';
184
			}
185
186 View Code Duplication
			if ( 'revision' === $input['type'] ) {
187
				if ( ! isset( $input['parent'] ) ) {
188
					return new WP_Error( 'invalid_input', 'Invalid request input', 400 );
189
				}
190
				$input['status'] = 'inherit'; // force inherit for revision type
191
				$input['slug'] = $input['parent'] . '-autosave-v1';
192
			}
193
			elseif ( !isset( $input['title'] ) && !isset( $input['content'] ) && !isset( $input['excerpt'] ) ) {
194
				return new WP_Error( 'invalid_input', 'Invalid request input', 400 );
195
			}
196
197
			// default to post
198
			if ( empty( $input['type'] ) )
199
				$input['type'] = 'post';
200
201
			$post_type = get_post_type_object( $input['type'] );
202
203
			if ( ! $this->is_post_type_allowed( $input['type'] ) ) {
204
				return new WP_Error( 'unknown_post_type', 'Unknown post type', 404 );
205
			}
206
207
			if ( ! empty( $input['author'] ) ) {
208
				$author_id = parent::parse_and_set_author( $input['author'], $input['type'] );
209
				unset( $input['author'] );
210
				if ( is_wp_error( $author_id ) )
211
					return $author_id;
212
			}
213
214 View Code Duplication
			if ( 'publish' === $input['status'] ) {
215
				if ( ! current_user_can( $post_type->cap->publish_posts ) ) {
216
					if ( current_user_can( $post_type->cap->edit_posts ) ) {
217
						$input['status'] = 'pending';
218
					} else {
219
						return new WP_Error( 'unauthorized', 'User cannot publish posts', 403 );
220
					}
221
				}
222
			} else {
223
				if ( !current_user_can( $post_type->cap->edit_posts ) ) {
224
					return new WP_Error( 'unauthorized', 'User cannot edit posts', 403 );
225
				}
226
			}
227 View Code Duplication
		} else {
228
			$input = $this->input( false );
229
230
			if ( !is_array( $input ) || !$input ) {
231
				return new WP_Error( 'invalid_input', 'Invalid request input', 400 );
232
			}
233
234
			if ( isset( $input['status'] ) && 'trash' === $input['status'] && ! current_user_can( 'delete_post', $post_id ) ) {
235
				return new WP_Error( 'unauthorized', 'User cannot delete post', 403 );
236
			}
237
238
			// 'future' is an alias for 'publish' for now
239
			if ( isset( $input['status'] ) && 'future' === $input['status'] ) {
240
				$input['status'] = 'publish';
241
			}
242
243
			$post = get_post( $post_id );
244
			$_post_type = ( ! empty( $input['type'] ) ) ? $input['type'] : $post->post_type;
245
			$post_type = get_post_type_object( $_post_type );
246
			if ( !$post || is_wp_error( $post ) ) {
247
				return new WP_Error( 'unknown_post', 'Unknown post', 404 );
248
			}
249
250
			if ( !current_user_can( 'edit_post', $post->ID ) ) {
251
				return new WP_Error( 'unauthorized', 'User cannot edit post', 403 );
252
			}
253
254
			if ( ! empty( $input['author'] ) ) {
255
				$author_id = parent::parse_and_set_author( $input['author'], $_post_type );
256
				unset( $input['author'] );
257
				if ( is_wp_error( $author_id ) )
258
					return $author_id;
259
			}
260
261
			if ( ( isset( $input['status'] ) && 'publish' === $input['status'] ) && 'publish' !== $post->post_status && !current_user_can( 'publish_post', $post->ID ) ) {
262
				$input['status'] = 'pending';
263
			}
264
			$last_status = $post->post_status;
265
			$new_status = isset( $input['status'] ) ? $input['status'] : $last_status;
266
267
			// Make sure that drafts get the current date when transitioning to publish if not supplied in the post.
268
			// Similarly, scheduled posts that are manually published before their scheduled date should have the date reset.
269
			$date_in_past = ( strtotime($post->post_date_gmt) < time() );
270
			$reset_draft_date     = 'publish' === $new_status && 'draft'  === $last_status && ! isset( $input['date_gmt'] ) && $date_in_past;
271
			$reset_scheduled_date = 'publish' === $new_status && 'future' === $last_status && ! isset( $input['date_gmt'] ) && ! $date_in_past;
272
273
			if ( $reset_draft_date || $reset_scheduled_date ) {
274
				$input['date_gmt'] = gmdate( 'Y-m-d H:i:s' );
275
			}
276
277
			// Untrash a post so that the proper hooks get called as well as the comments get untrashed.
278
			if ( $this->should_untrash_post( $last_status, $new_status, $post ) ) {
279
				$input = $this->untrash_post( $post, $input );
280
			}
281
		}
282
283
		if ( function_exists( 'wpcom_switch_to_blog_locale' ) ) {
284
			// fixes calypso-pre-oss #12476: respect blog locale when creating the post slug
285
			wpcom_switch_to_blog_locale( $blog_id );
286
		}
287
288
		 // If date is set, $this->input will set date_gmt, date still needs to be adjusted f
289 View Code Duplication
		if ( isset( $input['date_gmt'] ) ) {
290
			$gmt_offset = get_option( 'gmt_offset' );
291
			$time_with_offset = strtotime( $input['date_gmt'] ) + $gmt_offset * HOUR_IN_SECONDS;
292
			$input['date'] = date( 'Y-m-d H:i:s', $time_with_offset );
293
		}
294
295 View Code Duplication
		if ( ! empty( $author_id ) && get_current_user_id() != $author_id ) {
296
			if ( ! current_user_can( $post_type->cap->edit_others_posts ) ) {
297
				return new WP_Error( 'unauthorized', "User is not allowed to publish others' posts.", 403 );
298
			} elseif ( ! user_can( $author_id, $post_type->cap->edit_posts ) ) {
299
				return new WP_Error( 'unauthorized', 'Assigned author cannot publish post.', 403 );
300
			}
301
		}
302
303
		if ( !is_post_type_hierarchical( $post_type->name ) && 'revision' !== $post_type->name ) {
304
			unset( $input['parent'] );
305
		}
306
307
		foreach ( array( '', '_by_id' ) as $term_key_suffix ) {
308
			$term_input_key = 'terms' . $term_key_suffix;
309
			if ( isset( $input[ $term_input_key ] ) ) {
310
				$input[ $term_input_key ] = (array) $input[ $term_input_key ];
311
			} else {
312
				$input[ $term_input_key ] = array();
313
			}
314
315
			// Convert comma-separated terms to array before attempting to
316
			// merge with hardcoded taxonomies
317
			foreach ( $input[ $term_input_key ] as $taxonomy => $terms ) {
318 View Code Duplication
				if ( is_string( $terms ) ) {
319
					$input[ $term_input_key ][ $taxonomy ] = explode( ',', $terms );
320
				} else if ( ! is_array( $terms ) ) {
321
					$input[ $term_input_key ][ $taxonomy ] = array();
322
				}
323
			}
324
325
			// For each hard-coded taxonomy, merge into terms object
326
			foreach ( array( 'categories' => 'category', 'tags' => 'post_tag' ) as $key_prefix => $taxonomy ) {
327
				$taxonomy_key = $key_prefix . $term_key_suffix;
328
				if ( ! isset( $input[ $taxonomy_key ] ) ) {
329
					continue;
330
				}
331
332
				if ( ! isset( $input[ $term_input_key ][ $taxonomy ] ) ) {
333
					$input[ $term_input_key ][ $taxonomy ] = array();
334
				}
335
336
				$terms = $input[ $taxonomy_key ];
337 View Code Duplication
				if ( is_string( $terms ) ) {
338
					$terms = explode( ',', $terms );
339
				} else if ( ! is_array( $terms ) ) {
340
					continue;
341
				}
342
343
				$input[ $term_input_key ][ $taxonomy ] = array_merge(
344
					$input[ $term_input_key ][ $taxonomy ],
345
					$terms
346
				);
347
			}
348
		}
349
350
		/* add terms by name */
351
		$tax_input = array();
352
		foreach ( $input['terms'] as $taxonomy => $terms ) {
353
			$tax_input[ $taxonomy ] = array();
354
			$is_hierarchical = is_taxonomy_hierarchical( $taxonomy );
355
356
			foreach ( $terms as $term ) {
357
				/**
358
				 * We assume these are names, not IDs, even if they are numeric.
359
				 * Note: A category named "0" will not work right.
360
				 * https://core.trac.wordpress.org/ticket/9059
361
				 */
362
				if ( ! is_string( $term ) ) {
363
					continue;
364
				}
365
366
				$term_info = get_term_by( 'name', $term, $taxonomy, ARRAY_A );
367
368
				if ( ! $term_info ) {
369
					// only add a new tag/cat if the user has access to
370
					$tax = get_taxonomy( $taxonomy );
371
372
					// see https://core.trac.wordpress.org/ticket/26409
373
					if ( $is_hierarchical && ! current_user_can( $tax->cap->edit_terms ) ) {
374
						continue;
375
					} else if ( ! current_user_can( $tax->cap->assign_terms ) ) {
376
						continue;
377
					}
378
379
					$term_info = wp_insert_term( $term, $taxonomy );
380
				}
381
382 View Code Duplication
				if ( ! is_wp_error( $term_info ) ) {
383
					if ( $is_hierarchical ) {
384
						// Hierarchical terms must be added by ID
385
						$tax_input[$taxonomy][] = (int) $term_info['term_id'];
386
					} else {
387
						// Non-hierarchical terms must be added by name
388
						$tax_input[$taxonomy][] = $term;
389
					}
390
				}
391
			}
392
		}
393
394
		/* add terms by ID */
395
		foreach ( $input['terms_by_id'] as $taxonomy => $terms ) {
396
			// combine with any previous selections
397 View Code Duplication
			if ( ! isset( $tax_input[ $taxonomy ] ) || ! is_array( $tax_input[ $taxonomy ] ) ) {
398
				$tax_input[ $taxonomy ] = array();
399
			}
400
401
			$is_hierarchical = is_taxonomy_hierarchical( $taxonomy );
402
403
			foreach ( $terms as $term ) {
404
				$term = (string) $term; // ctype_digit compat
405
				if ( ! ctype_digit( $term ) ) {
406
					// skip anything that doesn't look like an ID
407
					continue;
408
				}
409
				$term = (int) $term;
410
				$term_info = get_term_by( 'id', $term, $taxonomy, ARRAY_A );
411
412 View Code Duplication
				if ( $term_info && ! is_wp_error( $term_info ) ) {
413
					if ( $is_hierarchical ) {
414
						// Categories must be added by ID
415
						$tax_input[$taxonomy][] = $term;
416
					} else {
417
						// Tags must be added by name
418
						$tax_input[$taxonomy][] = $term_info['name'];
419
					}
420
				}
421
			}
422
		}
423
424
		if ( ( isset( $input['terms']['category'] ) || isset( $input['terms_by_id']['category'] ) )
425
				&& empty( $tax_input['category'] ) && 'revision' !== $post_type->name ) {
426
			$tax_input['category'][] = get_option( 'default_category' );
427
		}
428
429
		unset( $input['terms'], $input['tags'], $input['categories'], $input['terms_by_id'], $input['tags_by_id'], $input['categories_by_id'] );
430
431
		$insert = array();
432
433 View Code Duplication
		if ( !empty( $input['slug'] ) ) {
434
			$insert['post_name'] = $input['slug'];
435
			unset( $input['slug'] );
436
		}
437
438 View Code Duplication
		if ( isset( $input['discussion'] ) ) {
439
			$discussion = (array) $input['discussion'];
440
			foreach ( array( 'comment', 'ping' ) as $discussion_type ) {
441
				$discussion_open = sprintf( '%ss_open', $discussion_type );
442
				$discussion_status = sprintf( '%s_status', $discussion_type );
443
444
				if ( isset( $discussion[ $discussion_open ] ) ) {
445
					$is_open = WPCOM_JSON_API::is_truthy( $discussion[ $discussion_open ] );
446
 					$discussion[ $discussion_status ] = $is_open ? 'open' : 'closed';
447
				}
448
449
				if ( in_array( $discussion[ $discussion_status ], array( 'open', 'closed' ) ) ) {
450
					$insert[ $discussion_status ] = $discussion[ $discussion_status ];
451
				}
452
			}
453
		}
454
455
		unset( $input['discussion'] );
456
457 View Code Duplication
		if ( isset( $input['menu_order'] ) ) {
458
			$insert['menu_order'] = $input['menu_order'];
459
			unset( $input['menu_order'] );
460
		}
461
462
		$publicize = isset( $input['publicize'] ) ? $input['publicize'] : null;
463
		unset( $input['publicize'] );
464
465
		$publicize_custom_message = isset( $input['publicize_message'] ) ? $input['publicize_message'] : null;
466
		unset( $input['publicize_message'] );
467
468 View Code Duplication
		if ( isset( $input['featured_image'] ) ) {
469
			$featured_image = trim( $input['featured_image'] );
470
			$delete_featured_image = empty( $featured_image );
471
			unset( $input['featured_image'] );
472
		}
473
474
		$metadata = isset( $input['metadata'] ) ? $input['metadata'] : null;
475
		unset( $input['metadata'] );
476
477
		$likes = isset( $input['likes_enabled'] ) ? $input['likes_enabled'] : null;
478
		unset( $input['likes_enabled'] );
479
480
		$sharing = isset( $input['sharing_enabled'] ) ? $input['sharing_enabled'] : null;
481
		unset( $input['sharing_enabled'] );
482
483
		$sticky = isset( $input['sticky'] ) ? $input['sticky'] : null;
484
		unset( $input['sticky'] );
485
486
		foreach ( $input as $key => $value ) {
487
			$insert["post_$key"] = $value;
488
		}
489
490
		if ( ! empty( $author_id ) ) {
491
			$insert['post_author'] = absint( $author_id );
492
		}
493
494
		if ( ! empty( $tax_input ) ) {
495
			$insert['tax_input'] = $tax_input;
496
		}
497
498
		$has_media = ! empty( $input['media'] ) ? count( $input['media'] ) : false;
499
		$has_media_by_url = ! empty( $input['media_urls'] ) ? count( $input['media_urls'] ) : false;
500
501
		$media_id_string = '';
502 View Code Duplication
		if ( $has_media || $has_media_by_url ) {
503
			$media_files = ! empty( $input['media'] ) ? $input['media'] : array();
504
			$media_urls = ! empty( $input['media_urls'] ) ? $input['media_urls'] : array();
505
			$media_attrs = ! empty( $input['media_attrs'] ) ? $input['media_attrs'] : array();
506
			$media_results = $this->handle_media_creation_v1_1( $media_files, $media_urls, $media_attrs );
507
			$media_id_string = join( ',', array_filter( array_map( 'absint', $media_results['media_ids'] ) ) );
508
		}
509
510 View Code Duplication
		if ( $new ) {
511
			if ( isset( $input['content'] ) && ! has_shortcode( $input['content'], 'gallery' ) && ( $has_media || $has_media_by_url ) ) {
512
				switch ( ( $has_media + $has_media_by_url ) ) {
513
				case 0 :
514
					// No images - do nothing.
515
					break;
516
				case 1 :
517
					// 1 image - make it big
518
					$insert['post_content'] = $input['content'] = sprintf(
519
						"[gallery size=full ids='%s' columns=1]\n\n",
520
						$media_id_string
521
					) . $input['content'];
522
					break;
523
				default :
524
					// Several images - 3 column gallery
525
					$insert['post_content'] = $input['content'] = sprintf(
526
						"[gallery ids='%s']\n\n",
527
						$media_id_string
528
					) . $input['content'];
529
					break;
530
				}
531
			}
532
533
			$post_id = wp_insert_post( add_magic_quotes( $insert ), true );
534
		} else {
535
			$insert['ID'] = $post->ID;
536
537
			// wp_update_post ignores date unless edit_date is set
538
			// See: https://codex.wordpress.org/Function_Reference/wp_update_post#Scheduling_posts
539
			// See: https://core.trac.wordpress.org/browser/tags/3.9.2/src/wp-includes/post.php#L3302
540
			if ( isset( $input['date_gmt'] ) || isset( $input['date'] ) ) {
541
				$insert['edit_date'] = true;
542
			}
543
544
			// this two-step process ensures any changes submitted along with status=trash get saved before trashing
545
			if ( isset( $input['status'] ) && 'trash' === $input['status'] ) {
546
				// if we insert it with status='trash', it will get double-trashed, so insert it as a draft first
547
				unset( $insert['status'] );
548
				$post_id = wp_update_post( (object) $insert );
549
				// now call wp_trash_post so post_meta gets set and any filters get called
550
				wp_trash_post( $post_id );
551
			} else {
552
				$post_id = wp_update_post( (object) $insert );
553
			}
554
		}
555
556
557
		if ( !$post_id || is_wp_error( $post_id ) ) {
558
			return $post_id;
559
		}
560
561
		// make sure this post actually exists and is not an error of some kind (ie, trying to load media in the posts endpoint)
562
		$post_check = $this->get_post_by( 'ID', $post_id, $args['context'] );
563
		if ( is_wp_error( $post_check ) ) {
564
			return $post_check;
565
		}
566
567 View Code Duplication
		if ( $media_id_string ) {
568
			// Yes - this is really how wp-admin does it.
569
			$wpdb->query( $wpdb->prepare(
570
				"UPDATE $wpdb->posts SET post_parent = %d WHERE post_type = 'attachment' AND ID IN ( $media_id_string )",
571
				$post_id
572
			) );
573
			foreach ( $media_results['media_ids'] as $media_id ) {
574
				clean_attachment_cache( $media_id );
575
			}
576
			clean_post_cache( $post_id );
577
		}
578
579
		// set page template for this post..
580 View Code Duplication
		if ( isset( $input['page_template'] ) && 'page' == $post_type->name ) {
581
			$page_template = $input['page_template'];
582
			$page_templates = wp_get_theme()->get_page_templates( get_post( $post_id ) );
583
			if ( empty( $page_template ) || 'default' == $page_template || isset( $page_templates[ $page_template ] ) ) {
584
				update_post_meta( $post_id, '_wp_page_template', $page_template );
585
			}
586
		}
587
588
		// Set like status for the post
589
		/** This filter is documented in modules/likes.php */
590
		$sitewide_likes_enabled = (bool) apply_filters( 'wpl_is_enabled_sitewide', ! get_option( 'disabled_likes' ) );
591 View Code Duplication
		if ( $new ) {
592
			if ( $sitewide_likes_enabled ) {
593
				if ( false === $likes ) {
594
					update_post_meta( $post_id, 'switch_like_status', 0 );
595
				} else {
596
					delete_post_meta( $post_id, 'switch_like_status' );
597
				}
598
			} else {
599
				if ( $likes ) {
600
					update_post_meta( $post_id, 'switch_like_status', 1 );
601
				} else {
602
					delete_post_meta( $post_id, 'switch_like_status' );
603
				}
604
			}
605
		} else {
606
			if ( isset( $likes ) ) {
607
				if ( $sitewide_likes_enabled ) {
608
					if ( false === $likes ) {
609
						update_post_meta( $post_id, 'switch_like_status', 0 );
610
					} else {
611
						delete_post_meta( $post_id, 'switch_like_status' );
612
					}
613
				} else {
614
					if ( true === $likes ) {
615
						update_post_meta( $post_id, 'switch_like_status', 1 );
616
					} else {
617
						delete_post_meta( $post_id, 'switch_like_status' );
618
					}
619
				}
620
			}
621
		}
622
623
		// Set sharing status of the post
624 View Code Duplication
		if ( $new ) {
625
			$sharing_enabled = isset( $sharing ) ? (bool) $sharing : true;
626
			if ( false === $sharing_enabled ) {
627
				update_post_meta( $post_id, 'sharing_disabled', 1 );
628
			}
629
		}
630
		else {
631
			if ( isset( $sharing ) && true === $sharing ) {
632
				delete_post_meta( $post_id, 'sharing_disabled' );
633
			} else if ( isset( $sharing ) && false == $sharing ) {
634
				update_post_meta( $post_id, 'sharing_disabled', 1 );
635
			}
636
		}
637
638
		if ( isset( $sticky ) ) {
639
			if ( true === $sticky ) {
640
				stick_post( $post_id );
641
			} else {
642
				unstick_post( $post_id );
643
			}
644
		}
645
646
		// WPCOM Specific (Jetpack's will get bumped elsewhere
647
		// Tracks how many posts are published and sets meta
648
		// so we can track some other cool stats (like likes & comments on posts published)
649 View Code Duplication
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
650
			if (
651
				( $new && 'publish' == $input['status'] )
652
				|| (
653
					!$new && isset( $last_status )
654
					&& 'publish' != $last_status
655
					&& isset( $new_status )
656
					&& 'publish' == $new_status
657
				)
658
			) {
659
				/** This action is documented in modules/widgets/social-media-icons.php */
660
				do_action( 'jetpack_bump_stats_extras', 'api-insights-posts', $this->api->token_details['client_id'] );
661
				update_post_meta( $post_id, '_rest_api_published', 1 );
662
				update_post_meta( $post_id, '_rest_api_client_id', $this->api->token_details['client_id'] );
663
			}
664
		}
665
666
667
		// We ask the user/dev to pass Publicize services he/she wants activated for the post, but Publicize expects us
668
		// to instead flag the ones we don't want to be skipped. proceed with said logic.
669
		// any posts coming from Path (client ID 25952) should also not publicize
670 View Code Duplication
		if ( $publicize === false || ( isset( $this->api->token_details['client_id'] ) && 25952 == $this->api->token_details['client_id'] ) ) {
671
			// No publicize at all, skip all by ID
672
			foreach ( $GLOBALS['publicize_ui']->publicize->get_services( 'all' ) as $name => $service ) {
673
				delete_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $name );
674
				$service_connections   = $GLOBALS['publicize_ui']->publicize->get_connections( $name );
675
				if ( ! $service_connections ) {
676
					continue;
677
				}
678
				foreach ( $service_connections as $service_connection ) {
679
					update_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $service_connection->unique_id, 1 );
680
				}
681
			}
682
		} else if ( is_array( $publicize ) && ( count ( $publicize ) > 0 ) ) {
683
			foreach ( $GLOBALS['publicize_ui']->publicize->get_services( 'all' ) as $name => $service ) {
684
				/*
685
				 * We support both indexed and associative arrays:
686
				 * * indexed are to pass entire services
687
				 * * associative are to pass specific connections per service
688
				 *
689
				 * We do support mixed arrays: mixed integer and string keys (see 3rd example below).
690
				 *
691
				 * EG: array( 'twitter', 'facebook') will only publicize to those, ignoring the other available services
692
				 * 		Form data: publicize[]=twitter&publicize[]=facebook
693
				 * EG: array( 'twitter' => '(int) $pub_conn_id_0, (int) $pub_conn_id_3', 'facebook' => (int) $pub_conn_id_7 ) will publicize to two Twitter accounts, and one Facebook connection, of potentially many.
694
				 * 		Form data: publicize[twitter]=$pub_conn_id_0,$pub_conn_id_3&publicize[facebook]=$pub_conn_id_7
695
				 * EG: array( 'twitter', 'facebook' => '(int) $pub_conn_id_0, (int) $pub_conn_id_3' ) will publicize to all available Twitter accounts, but only 2 of potentially many Facebook connections
696
				 * 		Form data: publicize[]=twitter&publicize[facebook]=$pub_conn_id_0,$pub_conn_id_3
697
				 */
698
699
				// Delete any stale SKIP value for the service by name. We'll add it back by ID.
700
				delete_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $name );
701
702
				// Get the user's connections
703
				$service_connections = $GLOBALS['publicize_ui']->publicize->get_connections( $name );
704
705
				// if the user doesn't have any connections for this service, move on
706
				if ( ! $service_connections ) {
707
					continue;
708
				}
709
710
				if ( !in_array( $name, $publicize ) && !array_key_exists( $name, $publicize ) ) {
711
					// Skip the whole service by adding each connection ID
712
					foreach ( $service_connections as $service_connection ) {
713
						update_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $service_connection->unique_id, 1 );
714
					}
715
				} else if ( !empty( $publicize[ $name ] ) ) {
716
					// Seems we're being asked to only push to [a] specific connection[s].
717
					// Explode the list on commas, which will also support a single passed ID
718
					$requested_connections = explode( ',', ( preg_replace( '/[\s]*/', '', $publicize[ $name ] ) ) );
719
720
					// Flag the connections we can't match with the requested list to be skipped.
721
					foreach ( $service_connections as $service_connection ) {
722
						if ( !in_array( $service_connection->meta['connection_data']->id, $requested_connections ) ) {
723
							update_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $service_connection->unique_id, 1 );
724
						} else {
725
							delete_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $service_connection->unique_id );
726
						}
727
					}
728
				} else {
729
					// delete all SKIP values; it's okay to publish to all connected IDs for this service
730
					foreach ( $service_connections as $service_connection ) {
731
						delete_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $service_connection->unique_id );
732
					}
733
				}
734
			}
735
		}
736
737 View Code Duplication
		if ( ! is_null( $publicize_custom_message ) ) {
738
			if ( empty( $publicize_custom_message ) ) {
739
				delete_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_MESS );
740
			} else {
741
				update_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_MESS, trim( $publicize_custom_message ) );
742
			}
743
		}
744
745 View Code Duplication
		if ( ! empty( $insert['post_format'] ) ) {
746
			if ( 'default' !== strtolower( $insert['post_format'] ) ) {
747
				set_post_format( $post_id, $insert['post_format'] );
748
			}
749
			else {
750
				set_post_format( $post_id, get_option( 'default_post_format' ) );
751
			}
752
		}
753
754
		if ( isset( $featured_image ) ) {
755
			parent::parse_and_set_featured_image( $post_id, $delete_featured_image, $featured_image );
756
		}
757
758 View Code Duplication
		if ( ! empty( $metadata ) ) {
759
			foreach ( (array) $metadata as $meta ) {
760
761
				$meta = (object) $meta;
762
763
				// Custom meta description can only be set on sites that have a business subscription.
764
				if ( Jetpack_SEO_Posts::DESCRIPTION_META_KEY == $meta->key && ! Jetpack_SEO_Utils::is_enabled_jetpack_seo() ) {
765
					return new WP_Error( 'unauthorized', __( 'SEO tools are not enabled for this site.', 'jetpack' ), 403 );
766
				}
767
768
				$existing_meta_item = new stdClass;
769
770
				if ( empty( $meta->operation ) )
771
					$meta->operation = 'update';
772
773
				if ( ! empty( $meta->value ) ) {
774
					if ( 'true' == $meta->value )
775
						$meta->value = true;
776
					if ( 'false' == $meta->value )
777
						$meta->value = false;
778
				}
779
780
				if ( ! empty( $meta->id ) ) {
781
					$meta->id = absint( $meta->id );
782
					$existing_meta_item = get_metadata_by_mid( 'post', $meta->id );
783
					if ( $post_id !== (int) $existing_meta_item->post_id ) {
784
						// Only allow updates for metadata on this post
785
						continue;
786
					}
787
				}
788
789
				$unslashed_meta_key = wp_unslash( $meta->key ); // should match what the final key will be
790
				$meta->key = wp_slash( $meta->key );
791
				$unslashed_existing_meta_key = isset( $existing_meta_item->meta_key ) ? wp_unslash( $existing_meta_item->meta_key ) : '';
792
				$existing_meta_item->meta_key = wp_slash( $existing_meta_item->meta_key );
793
794
				// make sure that the meta id passed matches the existing meta key
795
				if ( ! empty( $meta->id ) && ! empty( $meta->key ) ) {
796
					$meta_by_id = get_metadata_by_mid( 'post', $meta->id );
797
					if ( $meta_by_id->meta_key !== $meta->key ) {
798
						continue; // skip this meta
799
					}
800
				}
801
802
				switch ( $meta->operation ) {
803
					case 'delete':
804
						if ( ! empty( $meta->id ) && ! empty( $existing_meta_item->meta_key ) && current_user_can( 'delete_post_meta', $post_id, $unslashed_existing_meta_key ) ) {
805
							delete_metadata_by_mid( 'post', $meta->id );
806
						} elseif ( ! empty( $meta->key ) && ! empty( $meta->previous_value ) && current_user_can( 'delete_post_meta', $post_id, $unslashed_meta_key ) ) {
807
							delete_post_meta( $post_id, $meta->key, $meta->previous_value );
808
						} elseif ( ! empty( $meta->key ) && current_user_can( 'delete_post_meta', $post_id, $unslashed_meta_key ) ) {
809
							delete_post_meta( $post_id, $meta->key );
810
						}
811
812
						break;
813
					case 'add':
814
						if ( ! empty( $meta->id ) || ! empty( $meta->previous_value ) ) {
815
							break;
816
						} 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 ) ) {
817
							add_post_meta( $post_id, $meta->key, $meta->value );
818
						}
819
820
						break;
821
					case 'update':
822
						if ( ! isset( $meta->value ) ) {
823
							break;
824
						} 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 ) ) ) {
825
							update_metadata_by_mid( 'post', $meta->id, $meta->value );
826
						} 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 ) ) ) {
827
							update_post_meta( $post_id, $meta->key,$meta->value, $meta->previous_value );
828
						} elseif ( ! empty( $meta->key ) && ( current_user_can( 'edit_post_meta', $post_id, $unslashed_meta_key ) || WPCOM_JSON_API_Metadata::is_public( $meta->key ) ) ) {
829
							update_post_meta( $post_id, $meta->key, $meta->value );
830
						}
831
832
						break;
833
				}
834
			}
835
		}
836
837
		/** This action is documented in json-endpoints/class.wpcom-json-api-update-post-endpoint.php */
838
		do_action( 'rest_api_inserted_post', $post_id, $insert, $new );
839
840
		$return = $this->get_post_by( 'ID', $post_id, $args['context'] );
841
		if ( !$return || is_wp_error( $return ) ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $return of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
842
			return $return;
843
		}
844
845 View Code Duplication
		if ( isset( $input['type'] ) && 'revision' === $input['type'] ) {
846
			$return['preview_nonce'] = wp_create_nonce( 'post_preview_' . $input['parent'] );
847
		}
848
849
		if ( isset( $sticky ) ) {
850
			// workaround for sticky test occasionally failing, maybe a race condition with stick_post() above
851
			$return['sticky'] = ( true === $sticky );
852
		}
853
854
		if ( ! empty( $media_results['errors'] ) )
855
			$return['media_errors'] = $media_results['errors'];
856
857
		if ( 'publish' !== $return['status'] && isset( $input['title'] )) {
858
			$sal_site = $this->get_sal_post_by( 'ID', $post_id, $args['context'] );
859
			$return['other_URLs'] = (object) $sal_site->get_permalink_suggestions( $input['title'] );
860
		}
861
862
		/** This action is documented in json-endpoints/class.wpcom-json-api-site-settings-endpoint.php */
863
		do_action( 'wpcom_json_api_objects', 'posts' );
864
865
		return $return;
866
	}
867
868 View Code Duplication
	protected function should_load_theme_functions( $post_id = null ) {
869
		if ( empty( $post_id ) ) {
870
			$input = $this->input( true );
871
			$type = $input['type'];
872
		} else {
873
			$type = get_post_type( $post_id );
874
		}
875
876
		return ! empty( $type ) && ! in_array( $type, array( 'post', 'revision' ) );
877
	}
878
}
879