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

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