Completed
Push — master-stable ( 53f101...a82972 )
by
unknown
86:26 queued 76:28
created

class.wpcom-json-api-update-post-v1-1-endpoint.php (3 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
class WPCOM_JSON_API_Update_Post_v1_1_Endpoint extends WPCOM_JSON_API_Post_v1_1_Endpoint {
3
	function __construct( $args ) {
4
		parent::__construct( $args );
5
		if ( $this->api->ends_with( $this->path, '/delete' ) ) {
6
			$this->post_object_format['status']['deleted'] = 'The post has been deleted permanently.';
7
		}
8
	}
9
10
	// /sites/%s/posts/new       -> $blog_id
11
	// /sites/%s/posts/%d        -> $blog_id, $post_id
12
	// /sites/%s/posts/%d/delete -> $blog_id, $post_id
13
	// /sites/%s/posts/%d/restore -> $blog_id, $post_id
14 View Code Duplication
	function callback( $path = '', $blog_id = 0, $post_id = 0 ) {
15
		$blog_id = $this->api->switch_to_blog_and_validate_user( $this->api->get_blog_id( $blog_id ) );
16
		if ( is_wp_error( $blog_id ) ) {
17
			return $blog_id;
18
		}
19
20
		if ( $this->api->ends_with( $path, '/delete' ) ) {
21
			return $this->delete_post( $path, $blog_id, $post_id );
22
		} elseif ( $this->api->ends_with( $path, '/restore' ) ) {
23
			return $this->restore_post( $path, $blog_id, $post_id );
24
		} else {
25
			return $this->write_post( $path, $blog_id, $post_id );
26
		}
27
	}
28
29
	// /sites/%s/posts/new       -> $blog_id
30
	// /sites/%s/posts/%d        -> $blog_id, $post_id
31
	function write_post( $path, $blog_id, $post_id ) {
32
		global $wpdb;
33
34
		$new  = $this->api->ends_with( $path, '/new' );
35
		$args = $this->query_args();
36
37
		// unhook publicize, it's hooked again later -- without this, skipping services is impossible
38 View Code Duplication
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
39
			remove_action( 'save_post', array( $GLOBALS['publicize_ui']->publicize, 'async_publicize_post' ), 100, 2 );
40
			add_action( 'rest_api_inserted_post', array( $GLOBALS['publicize_ui']->publicize, 'async_publicize_post' ) );
41
42
			if ( $this->should_load_theme_functions( $post_id ) ) {
43
				$this->load_theme_functions();
44
			}
45
		}
46
47
48
		if ( $new ) {
49
			$input = $this->input( true );
50
51
			// 'future' is an alias for 'publish' for now
52
			if ( 'future' === $input['status'] ) {
53
				$input['status'] = 'publish';
54
			}
55
56
			if ( 'revision' === $input['type'] ) {
57
				if ( ! isset( $input['parent'] ) ) {
58
					return new WP_Error( 'invalid_input', 'Invalid request input', 400 );
59
				}
60
				$input['status'] = 'inherit'; // force inherit for revision type
61
				$input['slug'] = $input['parent'] . '-autosave-v1';
62
			}
63
			elseif ( !isset( $input['title'] ) && !isset( $input['content'] ) && !isset( $input['excerpt'] ) ) {
64
				return new WP_Error( 'invalid_input', 'Invalid request input', 400 );
65
			}
66
67
			// default to post
68
			if ( empty( $input['type'] ) )
69
				$input['type'] = 'post';
70
71
			$post_type = get_post_type_object( $input['type'] );
72
73
			if ( ! $this->is_post_type_allowed( $input['type'] ) ) {
74
				return new WP_Error( 'unknown_post_type', 'Unknown post type', 404 );
75
			}
76
77
			if ( ! empty( $input['author'] ) ) {
78
				$author_id = $this->parse_and_set_author( $input['author'], $input['type'] );
79
				unset( $input['author'] );
80
				if ( is_wp_error( $author_id ) )
81
					return $author_id;
82
			}
83
84
			if ( 'publish' === $input['status'] ) {
85
				if ( ! current_user_can( $post_type->cap->publish_posts ) ) {
86
					if ( current_user_can( $post_type->cap->edit_posts ) ) {
87
						$input['status'] = 'pending';
88
					} else {
89
						return new WP_Error( 'unauthorized', 'User cannot publish posts', 403 );
90
					}
91
				}
92
			} else {
93
				if ( !current_user_can( $post_type->cap->edit_posts ) ) {
94
					return new WP_Error( 'unauthorized', 'User cannot edit posts', 403 );
95
				}
96
			}
97 View Code Duplication
		} else {
98
			$input = $this->input( false );
99
100
			if ( !is_array( $input ) || !$input ) {
101
				return new WP_Error( 'invalid_input', 'Invalid request input', 400 );
102
			}
103
104
			if ( isset( $input['status'] ) && 'trash' === $input['status'] && ! current_user_can( 'delete_post', $post_id ) ) {
105
				return new WP_Error( 'unauthorized', 'User cannot delete post', 403 );
106
			}
107
108
			// 'future' is an alias for 'publish' for now
109
			if ( isset( $input['status'] ) && 'future' === $input['status'] ) {
110
				$input['status'] = 'publish';
111
			}
112
113
			$post = get_post( $post_id );
114
			$_post_type = ( ! empty( $input['type'] ) ) ? $input['type'] : $post->post_type;
115
			$post_type = get_post_type_object( $_post_type );
116
			if ( !$post || is_wp_error( $post ) ) {
117
				return new WP_Error( 'unknown_post', 'Unknown post', 404 );
118
			}
119
120
			if ( !current_user_can( 'edit_post', $post->ID ) ) {
121
				return new WP_Error( 'unauthorized', 'User cannot edit post', 403 );
122
			}
123
124
			if ( ! empty( $input['author'] ) ) {
125
				$author_id = $this->parse_and_set_author( $input['author'], $_post_type );
126
				unset( $input['author'] );
127
				if ( is_wp_error( $author_id ) )
128
					return $author_id;
129
			}
130
131
			if ( ( isset( $input['status'] ) && 'publish' === $input['status'] ) && 'publish' !== $post->post_status && !current_user_can( 'publish_post', $post->ID ) ) {
132
				$input['status'] = 'pending';
133
			}
134
			$last_status = $post->post_status;
135
			$new_status = isset( $input['status'] ) ? $input['status'] : $last_status;
136
137
			// Make sure that drafts get the current date when transitioning to publish if not supplied in the post.
138
			$date_in_past = ( strtotime($post->post_date_gmt) < time() );
139
			if ( 'publish' === $new_status && 'draft' === $last_status && ! isset( $input['date_gmt'] ) && $date_in_past ) {
140
				$input['date_gmt'] = gmdate( 'Y-m-d H:i:s' );
141
			}
142
		}
143
144
		if ( function_exists( 'wpcom_switch_to_blog_locale' ) ) {
145
			// fixes calypso-pre-oss #12476: respect blog locale when creating the post slug
146
			wpcom_switch_to_blog_locale( $blog_id );
147
		}
148
149
		// If date was set, $this->input will set date_gmt, date still needs to be adjusted for the blog's offset
150 View Code Duplication
		if ( isset( $input['date_gmt'] ) ) {
151
			$gmt_offset = get_option( 'gmt_offset' );
152
			$time_with_offset = strtotime( $input['date_gmt'] ) + $gmt_offset * HOUR_IN_SECONDS;
153
			$input['date'] = date( 'Y-m-d H:i:s', $time_with_offset );
154
		}
155
156 View Code Duplication
		if ( ! empty( $author_id ) && get_current_user_id() != $author_id ) {
157
			if ( ! current_user_can( $post_type->cap->edit_others_posts ) ) {
158
				return new WP_Error( 'unauthorized', "User is not allowed to publish others' posts.", 403 );
159
			} elseif ( ! user_can( $author_id, $post_type->cap->edit_posts ) ) {
160
				return new WP_Error( 'unauthorized', 'Assigned author cannot publish post.', 403 );
161
			}
162
		}
163
164
		if ( !is_post_type_hierarchical( $post_type->name ) && 'revision' !== $post_type->name ) {
165
			unset( $input['parent'] );
166
		}
167
168
		$input['terms'] = isset( $input['terms'] ) ? (array) $input['terms'] : array();
169
170
		// Convert comma-separated terms to array before attempting to
171
		// merge with hardcoded taxonomies
172
		foreach ( $input['terms'] as $taxonomy => $terms ) {
173 View Code Duplication
			if ( is_string( $terms ) ) {
174
				$input['terms'][ $taxonomy ] = explode( ',', $terms );
175
			} else if ( ! is_array( $terms ) ) {
176
				$input['terms'][ $taxonomy ] = array();
177
			}
178
		}
179
180
		// For each hard-coded taxonomy, merge into terms object
181
		foreach ( array( 'categories' => 'category', 'tags' => 'post_tag' ) as $taxonomy_key => $taxonomy ) {
182
			if ( ! isset( $input[ $taxonomy_key ] ) ) {
183
				continue;
184
			}
185
186
			if ( ! isset( $input['terms'][ $taxonomy ] ) ) {
187
				$input['terms'][ $taxonomy ] = array();
188
			}
189
190
			$terms = $input[ $taxonomy_key ];
191 View Code Duplication
			if ( is_string( $terms ) ) {
192
				$terms = explode( ',', $terms );
193
			} else if ( ! is_array( $terms ) ) {
194
				continue;
195
			}
196
197
			$input['terms'][ $taxonomy ] = array_merge(
198
				$input['terms'][ $taxonomy ],
199
				$terms
200
			);
201
		}
202
203
		$tax_input = array();
204
205
		foreach ( $input['terms'] as $taxonomy => $terms ) {
206
			$tax_input[ $taxonomy ] = array();
207
			$is_hierarchical = is_taxonomy_hierarchical( $taxonomy );
208
209 View Code Duplication
			foreach ( $terms as $term ) {
210
				/**
211
				 * `curl --data 'terms[category][]=123'` should be interpreted as a category ID,
212
				 * not a category whose name is '123'.
213
				 *
214
				 * Consequence: To add a category/tag whose name is '123', the client must
215
				 * first look up its ID.
216
				 */
217
				$term = (string) $term; // ctype_digit compat
218
				if ( ctype_digit( $term ) ) {
219
					$term = (int) $term;
220
				}
221
222
				$term_info = term_exists( $term, $taxonomy );
223
224
				if ( ! $term_info ) {
225
					// A term ID that doesn't already exist. Ignore it: we don't know what name to give it.
226
					if ( is_int( $term ) ){
227
						continue;
228
					}
229
					// only add a new tag/cat if the user has access to
230
					$tax = get_taxonomy( $taxonomy );
231
232
					// see https://core.trac.wordpress.org/ticket/26409
233
					if ( $is_hierarchical && ! current_user_can( $tax->cap->edit_terms ) ) {
234
						continue;
235
					} else if ( ! current_user_can( $tax->cap->assign_terms ) ) {
236
						continue;
237
					}
238
239
					$term_info = wp_insert_term( $term, $taxonomy );
240
				}
241
242
				if ( ! is_wp_error( $term_info ) ) {
243
					if ( $is_hierarchical ) {
244
						// Hierarchical terms must be added by ID
245
						$tax_input[$taxonomy][] = (int) $term_info['term_id'];
246
					} else {
247
						// Non-hierarchical terms must be added by name
248
						if ( is_int( $term ) ) {
249
							$term = get_term( $term, $taxonomy );
250
							$tax_input[$taxonomy][] = $term->name;
251
						} else {
252
							$tax_input[$taxonomy][] = $term;
253
						}
254
					}
255
				}
256
			}
257
		}
258
259 View Code Duplication
		if ( isset( $input['terms']['category'] ) && empty( $tax_input['category'] ) && 'revision' !== $post_type->name ) {
260
			$tax_input['category'][] = get_option( 'default_category' );
261
		}
262
263
		unset( $input['terms'], $input['tags'], $input['categories'] );
264
265
		$insert = array();
266
267 View Code Duplication
		if ( !empty( $input['slug'] ) ) {
268
			$insert['post_name'] = $input['slug'];
269
			unset( $input['slug'] );
270
		}
271
272 View Code Duplication
		if ( isset( $input['discussion'] ) ) {
273
			$discussion = (array) $input['discussion'];
274
			foreach ( array( 'comment', 'ping' ) as $discussion_type ) {
275
				$discussion_open = sprintf( '%ss_open', $discussion_type );
276
				$discussion_status = sprintf( '%s_status', $discussion_type );
277
278
				if ( isset( $discussion[ $discussion_open ] ) ) {
279
					$is_open = WPCOM_JSON_API::is_truthy( $discussion[ $discussion_open ] );
280
 					$discussion[ $discussion_status ] = $is_open ? 'open' : 'closed';
281
				}
282
283
				if ( in_array( $discussion[ $discussion_status ], array( 'open', 'closed' ) ) ) {
284
					$insert[ $discussion_status ] = $discussion[ $discussion_status ];
285
				}
286
			}
287
		}
288
289
		unset( $input['discussion'] );
290
291 View Code Duplication
		if ( isset( $input['menu_order'] ) ) {
292
			$insert['menu_order'] = $input['menu_order'];
293
			unset( $input['menu_order'] );
294
		}
295
296
		$publicize = isset( $input['publicize'] ) ? $input['publicize'] : null;
297
		unset( $input['publicize'] );
298
299
		$publicize_custom_message = isset( $input['publicize_message'] ) ? $input['publicize_message'] : null;
300
		unset( $input['publicize_message'] );
301
302 View Code Duplication
		if ( isset( $input['featured_image'] ) ) {
303
			$featured_image = trim( $input['featured_image'] );
304
			$delete_featured_image = empty( $featured_image );
305
			unset( $input['featured_image'] );
306
		}
307
308
		$metadata = isset( $input['metadata'] ) ? $input['metadata'] : null;
309
		unset( $input['metadata'] );
310
311
		$likes = isset( $input['likes_enabled'] ) ? $input['likes_enabled'] : null;
312
		unset( $input['likes_enabled'] );
313
314
		$sharing = isset( $input['sharing_enabled'] ) ? $input['sharing_enabled'] : null;
315
		unset( $input['sharing_enabled'] );
316
317
		$sticky = isset( $input['sticky'] ) ? $input['sticky'] : null;
318
		unset( $input['sticky'] );
319
320
		foreach ( $input as $key => $value ) {
321
			$insert["post_$key"] = $value;
322
		}
323
324
		if ( ! empty( $author_id ) ) {
325
			$insert['post_author'] = absint( $author_id );
326
		}
327
328
		if ( ! empty( $tax_input ) ) {
329
			$insert['tax_input'] = $tax_input;
330
		}
331
332
		$has_media = ! empty( $input['media'] ) ? count( $input['media'] ) : false;
333
		$has_media_by_url = ! empty( $input['media_urls'] ) ? count( $input['media_urls'] ) : false;
334
335
		$media_id_string = '';
336
		if ( $has_media || $has_media_by_url ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $has_media of type integer|false is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
337
			$media_files = ! empty( $input['media'] ) ? $input['media'] : array();
338
			$media_urls = ! empty( $input['media_urls'] ) ? $input['media_urls'] : array();
339
			$media_attrs = ! empty( $input['media_attrs'] ) ? $input['media_attrs'] : array();
340
			$media_results = $this->handle_media_creation_v1_1( $media_files, $media_urls, $media_attrs );
341
			$media_id_string = join( ',', array_filter( array_map( 'absint', $media_results['media_ids'] ) ) );
342
		}
343
344 View Code Duplication
		if ( $new ) {
345
			if ( isset( $input['content'] ) && ! has_shortcode( $input['content'], 'gallery' ) && ( $has_media || $has_media_by_url ) ) {
346
				switch ( ( $has_media + $has_media_by_url ) ) {
347
				case 0 :
348
					// No images - do nothing.
349
					break;
350
				case 1 :
351
					// 1 image - make it big
352
					$insert['post_content'] = $input['content'] = sprintf(
353
						"[gallery size=full ids='%s' columns=1]\n\n",
354
						$media_id_string
355
					) . $input['content'];
356
					break;
357
				default :
0 ignored issues
show
There must be no space before the colon in a DEFAULT statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in the default statement.

switch ($expr) {
    default : //wrong
        doSomething();
        break;
}

switch ($expr) {
    default: //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
358
					// Several images - 3 column gallery
359
					$insert['post_content'] = $input['content'] = sprintf(
360
						"[gallery ids='%s']\n\n",
361
						$media_id_string
362
					) . $input['content'];
363
					break;
364
				}
365
			}
366
367
			$post_id = wp_insert_post( add_magic_quotes( $insert ), true );
368
		} else {
369
			$insert['ID'] = $post->ID;
370
371
			// wp_update_post ignores date unless edit_date is set
372
			// See: http://codex.wordpress.org/Function_Reference/wp_update_post#Scheduling_posts
373
			// See: https://core.trac.wordpress.org/browser/tags/3.9.2/src/wp-includes/post.php#L3302
374
			if ( isset( $input['date_gmt'] ) || isset( $input['date'] ) ) {
375
				$insert['edit_date'] = true;
376
			}
377
378
			// this two-step process ensures any changes submitted along with status=trash get saved before trashing
379
			if ( isset( $input['status'] ) && 'trash' === $input['status'] ) {
380
				// if we insert it with status='trash', it will get double-trashed, so insert it as a draft first
381
				unset( $insert['status'] );
382
				$post_id = wp_update_post( (object) $insert );
383
				// now call wp_trash_post so post_meta gets set and any filters get called
384
				wp_trash_post( $post_id );
385
			} else {
386
				$post_id = wp_update_post( (object) $insert );
387
			}
388
		}
389
390
391
		if ( !$post_id || is_wp_error( $post_id ) ) {
392
			return $post_id;
393
		}
394
395
		// make sure this post actually exists and is not an error of some kind (ie, trying to load media in the posts endpoint)
396
		$post_check = $this->get_post_by( 'ID', $post_id, $args['context'] );
397
		if ( is_wp_error( $post_check ) ) {
398
			return $post_check;
399
		}
400
401 View Code Duplication
		if ( $media_id_string ) {
402
			// Yes - this is really how wp-admin does it.
403
			$wpdb->query( $wpdb->prepare(
404
				"UPDATE $wpdb->posts SET post_parent = %d WHERE post_type = 'attachment' AND ID IN ( $media_id_string )",
405
				$post_id
406
			) );
407
			foreach ( $media_results['media_ids'] as $media_id ) {
0 ignored issues
show
The variable $media_results does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
408
				clean_attachment_cache( $media_id );
409
			}
410
			clean_post_cache( $post_id );
411
		}
412
413
		// set page template for this post..
414 View Code Duplication
		if ( isset( $input['page_template'] ) && 'page' == $post_type->name ) {
415
			$page_template = $input['page_template'];
416
			$page_templates = wp_get_theme()->get_page_templates( get_post( $post_id ) );
417
			if ( empty( $page_template ) || 'default' == $page_template || isset( $page_templates[ $page_template ] ) ) {
418
				update_post_meta( $post_id, '_wp_page_template', $page_template );
419
			}
420
		}
421
422
		// Set like status for the post
423
		/** This filter is documented in modules/likes.php */
424
		$sitewide_likes_enabled = (bool) apply_filters( 'wpl_is_enabled_sitewide', ! get_option( 'disabled_likes' ) );
425 View Code Duplication
		if ( $new ) {
426
			if ( $sitewide_likes_enabled ) {
427
				if ( false === $likes ) {
428
					update_post_meta( $post_id, 'switch_like_status', 1 );
429
				} else {
430
					delete_post_meta( $post_id, 'switch_like_status' );
431
				}
432
			} else {
433
				if ( $likes ) {
434
					update_post_meta( $post_id, 'switch_like_status', 1 );
435
				} else {
436
					delete_post_meta( $post_id, 'switch_like_status' );
437
				}
438
			}
439
		} else {
440
			if ( isset( $likes ) ) {
441
				if ( $sitewide_likes_enabled ) {
442
					if ( false === $likes ) {
443
						update_post_meta( $post_id, 'switch_like_status', 1 );
444
					} else {
445
						delete_post_meta( $post_id, 'switch_like_status' );
446
					}
447
				} else {
448
					if ( true === $likes ) {
449
						update_post_meta( $post_id, 'switch_like_status', 1 );
450
					} else {
451
						delete_post_meta( $post_id, 'switch_like_status' );
452
					}
453
				}
454
			}
455
		}
456
457
		// Set sharing status of the post
458 View Code Duplication
		if ( $new ) {
459
			$sharing_enabled = isset( $sharing ) ? (bool) $sharing : true;
460
			if ( false === $sharing_enabled ) {
461
				update_post_meta( $post_id, 'sharing_disabled', 1 );
462
			}
463
		}
464
		else {
465
			if ( isset( $sharing ) && true === $sharing ) {
466
				delete_post_meta( $post_id, 'sharing_disabled' );
467
			} else if ( isset( $sharing ) && false == $sharing ) {
468
				update_post_meta( $post_id, 'sharing_disabled', 1 );
469
			}
470
		}
471
472
		if ( isset( $sticky ) ) {
473
			if ( true === $sticky ) {
474
				stick_post( $post_id );
475
			} else {
476
				unstick_post( $post_id );
477
			}
478
		}
479
480
		// WPCOM Specific (Jetpack's will get bumped elsewhere
481
		// Tracks how many posts are published and sets meta
482
		// so we can track some other cool stats (like likes & comments on posts published)
483 View Code Duplication
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
484
			if (
485
				( $new && 'publish' == $input['status'] )
486
				|| (
487
					! $new && isset( $last_status )
488
					&& 'publish' != $last_status
489
					&& isset( $new_status )
490
					&& 'publish' == $new_status
491
				)
492
			) {
493
				/** This action is documented in modules/widgets/social-media-icons.php */
494
				do_action( 'jetpack_bump_stats_extras', 'api-insights-posts', $this->api->token_details['client_id'] );
495
				update_post_meta( $post_id, '_rest_api_published', 1 );
496
				update_post_meta( $post_id, '_rest_api_client_id', $this->api->token_details['client_id'] );
497
			}
498
		}
499
500
501
		// We ask the user/dev to pass Publicize services he/she wants activated for the post, but Publicize expects us
502
		// to instead flag the ones we don't want to be skipped. proceed with said logic.
503
		// any posts coming from Path (client ID 25952) should also not publicize
504 View Code Duplication
		if ( $publicize === false || ( isset( $this->api->token_details['client_id'] ) && 25952 == $this->api->token_details['client_id'] ) ) {
505
			// No publicize at all, skip all by ID
506
			foreach ( $GLOBALS['publicize_ui']->publicize->get_services( 'all' ) as $name => $service ) {
507
				delete_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $name );
508
				$service_connections   = $GLOBALS['publicize_ui']->publicize->get_connections( $name );
509
				if ( ! $service_connections ) {
510
					continue;
511
				}
512
				foreach ( $service_connections as $service_connection ) {
513
					update_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $service_connection->unique_id, 1 );
514
				}
515
			}
516
		} else if ( is_array( $publicize ) && ( count ( $publicize ) > 0 ) ) {
517
			foreach ( $GLOBALS['publicize_ui']->publicize->get_services( 'all' ) as $name => $service ) {
518
				/*
519
				 * We support both indexed and associative arrays:
520
				 * * indexed are to pass entire services
521
				 * * associative are to pass specific connections per service
522
				 *
523
				 * We do support mixed arrays: mixed integer and string keys (see 3rd example below).
524
				 *
525
				 * EG: array( 'twitter', 'facebook') will only publicize to those, ignoring the other available services
526
				 * 		Form data: publicize[]=twitter&publicize[]=facebook
527
				 * 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.
528
				 * 		Form data: publicize[twitter]=$pub_conn_id_0,$pub_conn_id_3&publicize[facebook]=$pub_conn_id_7
529
				 * 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
530
				 * 		Form data: publicize[]=twitter&publicize[facebook]=$pub_conn_id_0,$pub_conn_id_3
531
				 */
532
533
				// Delete any stale SKIP value for the service by name. We'll add it back by ID.
534
				delete_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $name );
535
536
				// Get the user's connections
537
				$service_connections = $GLOBALS['publicize_ui']->publicize->get_connections( $name );
538
539
				// if the user doesn't have any connections for this service, move on
540
				if ( ! $service_connections ) {
541
					continue;
542
				}
543
544
				if ( !in_array( $name, $publicize ) && !array_key_exists( $name, $publicize ) ) {
545
					// Skip the whole service by adding each connection ID
546
					foreach ( $service_connections as $service_connection ) {
547
						update_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $service_connection->unique_id, 1 );
548
					}
549
				} else if ( !empty( $publicize[ $name ] ) ) {
550
					// Seems we're being asked to only push to [a] specific connection[s].
551
					// Explode the list on commas, which will also support a single passed ID
552
					$requested_connections = explode( ',', ( preg_replace( '/[\s]*/', '', $publicize[ $name ] ) ) );
553
554
					// Flag the connections we can't match with the requested list to be skipped.
555
					foreach ( $service_connections as $service_connection ) {
556
						if ( !in_array( $service_connection->meta['connection_data']->id, $requested_connections ) ) {
557
							update_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $service_connection->unique_id, 1 );
558
						} else {
559
							delete_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $service_connection->unique_id );
560
						}
561
					}
562
				} else {
563
					// delete all SKIP values; it's okay to publish to all connected IDs for this service
564
					foreach ( $service_connections as $service_connection ) {
565
						delete_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $service_connection->unique_id );
566
					}
567
				}
568
			}
569
		}
570
571 View Code Duplication
		if ( ! is_null( $publicize_custom_message ) ) {
572
			if ( empty( $publicize_custom_message ) ) {
573
				delete_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_MESS );
574
			} else {
575
				update_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_MESS, trim( $publicize_custom_message ) );
576
			}
577
		}
578
579 View Code Duplication
		if ( ! empty( $insert['post_format'] ) ) {
580
			if ( 'default' !== strtolower( $insert['post_format'] ) ) {
581
				set_post_format( $post_id, $insert['post_format'] );
582
			}
583
			else {
584
				set_post_format( $post_id, get_option( 'default_post_format' ) );
585
			}
586
		}
587
588
		if ( isset( $featured_image ) ) {
589
			$this->parse_and_set_featured_image( $post_id, $delete_featured_image, $featured_image );
590
		}
591
592 View Code Duplication
		if ( ! empty( $metadata ) ) {
593
			foreach ( (array) $metadata as $meta ) {
594
595
				$meta = (object) $meta;
596
597
				// Custom meta description can only be set on sites that have a business subscription.
598
				if ( Jetpack_SEO_Posts::DESCRIPTION_META_KEY == $meta->key && ! Jetpack_SEO_Utils::is_enabled_jetpack_seo() ) {
599
					return new WP_Error( 'unauthorized', __( 'SEO tools are not enabled for this site.', 'jetpack' ), 403 );
600
				}
601
602
				$existing_meta_item = new stdClass;
603
604
				if ( empty( $meta->operation ) )
605
					$meta->operation = 'update';
606
607
				if ( ! empty( $meta->value ) ) {
608
					if ( 'true' == $meta->value )
609
						$meta->value = true;
610
					if ( 'false' == $meta->value )
611
						$meta->value = false;
612
				}
613
614
				if ( ! empty( $meta->id ) ) {
615
					$meta->id = absint( $meta->id );
616
					$existing_meta_item = get_metadata_by_mid( 'post', $meta->id );
617
					if ( $post_id !== (int) $existing_meta_item->post_id ) {
618
						// Only allow updates for metadata on this post
619
						continue;
620
					}
621
				}
622
623
				$unslashed_meta_key = wp_unslash( $meta->key ); // should match what the final key will be
624
				$meta->key = wp_slash( $meta->key );
625
				$unslashed_existing_meta_key = wp_unslash( $existing_meta_item->meta_key );
626
				$existing_meta_item->meta_key = wp_slash( $existing_meta_item->meta_key );
627
628
				// make sure that the meta id passed matches the existing meta key
629
				if ( ! empty( $meta->id ) && ! empty( $meta->key ) ) {
630
					$meta_by_id = get_metadata_by_mid( 'post', $meta->id );
631
					if ( $meta_by_id->meta_key !== $meta->key ) {
632
						continue; // skip this meta
633
					}
634
				}
635
636
				switch ( $meta->operation ) {
637
					case 'delete':
638
639
						if ( ! empty( $meta->id ) && ! empty( $existing_meta_item->meta_key ) && current_user_can( 'delete_post_meta', $post_id, $unslashed_existing_meta_key ) ) {
640
							delete_metadata_by_mid( 'post', $meta->id );
641
						} elseif ( ! empty( $meta->key ) && ! empty( $meta->previous_value ) && current_user_can( 'delete_post_meta', $post_id, $unslashed_meta_key ) ) {
642
							delete_post_meta( $post_id, $meta->key, $meta->previous_value );
643
						} elseif ( ! empty( $meta->key ) && current_user_can( 'delete_post_meta', $post_id, $unslashed_meta_key ) ) {
644
							delete_post_meta( $post_id, $meta->key );
645
						}
646
647
						break;
648
					case 'add':
649
650
						if ( ! empty( $meta->id ) || ! empty( $meta->previous_value ) ) {
651
							continue;
652
						} 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 ) ) {
653
							add_post_meta( $post_id, $meta->key, $meta->value );
654
						}
655
656
						break;
657
					case 'update':
658
659
						if ( ! isset( $meta->value ) ) {
660
							continue;
661
						} 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 ) ) ) {
662
							update_metadata_by_mid( 'post', $meta->id, $meta->value );
663
						} 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 ) ) ) {
664
							update_post_meta( $post_id, $meta->key,$meta->value, $meta->previous_value );
665
						} elseif ( ! empty( $meta->key ) && ( current_user_can( 'edit_post_meta', $post_id, $unslashed_meta_key ) || WPCOM_JSON_API_Metadata::is_public( $meta->key ) ) ) {
666
							update_post_meta( $post_id, $meta->key, $meta->value );
667
						}
668
669
						break;
670
				}
671
672
			}
673
		}
674
675
		/** This action is documented in json-endpoints/class.wpcom-json-api-update-post-endpoint.php */
676
		do_action( 'rest_api_inserted_post', $post_id, $insert, $new );
677
678
		$return = $this->get_post_by( 'ID', $post_id, $args['context'] );
679
		if ( !$return || is_wp_error( $return ) ) {
680
			return $return;
681
		}
682
683 View Code Duplication
		if ( isset( $input['type'] ) && 'revision' === $input['type'] ) {
684
			$return['preview_nonce'] = wp_create_nonce( 'post_preview_' . $input['parent'] );
685
		}
686
687
		if ( isset( $sticky ) ) {
688
			// workaround for sticky test occasionally failing, maybe a race condition with stick_post() above
689
			$return['sticky'] = ( true === $sticky );
690
		}
691
692
		if ( ! empty( $media_results['errors'] ) )
693
			$return['media_errors'] = $media_results['errors'];
694
695
		if ( 'publish' !== $post->post_status ) {
696
			$sal_site = $this->get_sal_post_by( 'ID', $post_id, $args['context'] );
697
			$return['other_URLs'] = (object) $sal_site->get_permalink_suggestions( $input['title'] );
698
		}
699
700
		/** This action is documented in json-endpoints/class.wpcom-json-api-site-settings-endpoint.php */
701
		do_action( 'wpcom_json_api_objects', 'posts' );
702
703
		return $return;
704
	}
705
706
	// /sites/%s/posts/%d/delete -> $blog_id, $post_id
707 View Code Duplication
	function delete_post( $path, $blog_id, $post_id ) {
708
		$post = get_post( $post_id );
709
		if ( !$post || is_wp_error( $post ) ) {
710
			return new WP_Error( 'unknown_post', 'Unknown post', 404 );
711
		}
712
713
		if ( ! $this->is_post_type_allowed( $post->post_type ) ) {
714
			return new WP_Error( 'unknown_post_type', 'Unknown post type', 404 );
715
		}
716
717
		if ( !current_user_can( 'delete_post', $post->ID ) ) {
718
			return new WP_Error( 'unauthorized', 'User cannot delete posts', 403 );
719
		}
720
721
		$args  = $this->query_args();
722
		$return = $this->get_post_by( 'ID', $post->ID, $args['context'] );
723
		if ( !$return || is_wp_error( $return ) ) {
724
			return $return;
725
		}
726
727
		/** This action is documented in json-endpoints/class.wpcom-json-api-site-settings-endpoint.php */
728
		do_action( 'wpcom_json_api_objects', 'posts' );
729
730
		// we need to call wp_trash_post so that untrash will work correctly for all post types
731
		if ( 'trash' === $post->post_status )
732
			wp_delete_post( $post->ID );
733
		else
734
			wp_trash_post( $post->ID );
735
736
		$status = get_post_status( $post->ID );
737
		if ( false === $status ) {
738
			$return['status'] = 'deleted';
739
			return $return;
740
		}
741
742
		return $this->get_post_by( 'ID', $post->ID, $args['context'] );
743
	}
744
745
	// /sites/%s/posts/%d/restore -> $blog_id, $post_id
746 View Code Duplication
	function restore_post( $path, $blog_id, $post_id ) {
747
		$args  = $this->query_args();
748
		$post = get_post( $post_id );
749
750
		if ( !$post || is_wp_error( $post ) ) {
751
			return new WP_Error( 'unknown_post', 'Unknown post', 404 );
752
		}
753
754
		if ( !current_user_can( 'delete_post', $post->ID ) ) {
755
			return new WP_Error( 'unauthorized', 'User cannot restore trashed posts', 403 );
756
		}
757
758
		/** This action is documented in json-endpoints/class.wpcom-json-api-site-settings-endpoint.php */
759
		do_action( 'wpcom_json_api_objects', 'posts' );
760
761
		wp_untrash_post( $post->ID );
762
763
		return $this->get_post_by( 'ID', $post->ID, $args['context'] );
764
	}
765
766 View Code Duplication
	protected function parse_and_set_featured_image( $post_id, $delete_featured_image, $featured_image ) {
767
		if ( $delete_featured_image ) {
768
			delete_post_thumbnail( $post_id );
769
			return;
770
		}
771
772
		$featured_image = (string) $featured_image;
773
774
		// if we got a post ID, we can just set it as the thumbnail
775
		if ( ctype_digit( $featured_image ) && 'attachment' == get_post_type( $featured_image ) ) {
776
			set_post_thumbnail( $post_id, $featured_image );
777
			return $featured_image;
778
		}
779
780
		$featured_image_id = $this->handle_media_sideload( $featured_image, $post_id, 'image' );
781
782
		if ( empty( $featured_image_id ) || ! is_int( $featured_image_id ) )
783
			return false;
784
785
		set_post_thumbnail( $post_id, $featured_image_id );
786
		return $featured_image_id;
787
	}
788
789 View Code Duplication
	protected function parse_and_set_author( $author = null, $post_type = 'post' ) {
790
		if ( empty( $author ) || ! post_type_supports( $post_type, 'author' ) )
791
			return get_current_user_id();
792
793
		$author = (string) $author;
794
		if ( ctype_digit( $author ) ) {
795
			$_user = get_user_by( 'id', $author );
796
			if ( ! $_user || is_wp_error( $_user ) )
797
				return new WP_Error( 'invalid_author', 'Invalid author provided' );
798
799
			return $_user->ID;
800
		}
801
802
		$_user = get_user_by( 'login', $author );
803
		if ( ! $_user || is_wp_error( $_user ) )
804
			return new WP_Error( 'invalid_author', 'Invalid author provided' );
805
806
		return $_user->ID;
807
	}
808
809 View Code Duplication
	protected function should_load_theme_functions( $post_id = null ) {
810
		if ( empty( $post_id ) ) {
811
			$input = $this->input( true );
812
			$type = $input['type'];
813
		} else {
814
			$type = get_post_type( $post_id );
815
		}
816
817
		return ! empty( $type ) && ! in_array( $type, array( 'post', 'revision' ) );
818
	}
819
}
820