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

class.wpcom-json-api-update-post-v1-2-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_2_Endpoint extends WPCOM_JSON_API_Update_Post_v1_1_Endpoint {
3
4
	// /sites/%s/posts/new       -> $blog_id
5
	// /sites/%s/posts/%d        -> $blog_id, $post_id
6
	function write_post( $path, $blog_id, $post_id ) {
7
		global $wpdb;
8
9
		$new  = $this->api->ends_with( $path, '/new' );
10
		$args = $this->query_args();
11
12
		// unhook publicize, it's hooked again later -- without this, skipping services is impossible
13 View Code Duplication
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
14
			remove_action( 'save_post', array( $GLOBALS['publicize_ui']->publicize, 'async_publicize_post' ), 100, 2 );
15
			add_action( 'rest_api_inserted_post', array( $GLOBALS['publicize_ui']->publicize, 'async_publicize_post' ) );
16
17
			if ( $this->should_load_theme_functions( $post_id ) ) {
18
				$this->load_theme_functions();
19
			}
20
		}
21
22
		if ( $new ) {
23
			$input = $this->input( true );
24
25
			// 'future' is an alias for 'publish' for now
26
			if ( isset( $input['status'] ) && 'future' === $input['status'] ) {
27
				$input['status'] = 'publish';
28
			}
29
30
			if ( 'revision' === $input['type'] ) {
31
				if ( ! isset( $input['parent'] ) ) {
32
					return new WP_Error( 'invalid_input', 'Invalid request input', 400 );
33
				}
34
				$input['status'] = 'inherit'; // force inherit for revision type
35
				$input['slug'] = $input['parent'] . '-autosave-v1';
36
			}
37
			elseif ( !isset( $input['title'] ) && !isset( $input['content'] ) && !isset( $input['excerpt'] ) ) {
38
				return new WP_Error( 'invalid_input', 'Invalid request input', 400 );
39
			}
40
41
			// default to post
42
			if ( empty( $input['type'] ) )
43
				$input['type'] = 'post';
44
45
			$post_type = get_post_type_object( $input['type'] );
46
47
			if ( ! $this->is_post_type_allowed( $input['type'] ) ) {
48
				return new WP_Error( 'unknown_post_type', 'Unknown post type', 404 );
49
			}
50
51
			if ( ! empty( $input['author'] ) ) {
52
				$author_id = parent::parse_and_set_author( $input['author'], $input['type'] );
53
				unset( $input['author'] );
54
				if ( is_wp_error( $author_id ) )
55
					return $author_id;
56
			}
57
58
			if ( 'publish' === $input['status'] ) {
59
				if ( ! current_user_can( $post_type->cap->publish_posts ) ) {
60
					if ( current_user_can( $post_type->cap->edit_posts ) ) {
61
						$input['status'] = 'pending';
62
					} else {
63
						return new WP_Error( 'unauthorized', 'User cannot publish posts', 403 );
64
					}
65
				}
66
			} else {
67
				if ( !current_user_can( $post_type->cap->edit_posts ) ) {
68
					return new WP_Error( 'unauthorized', 'User cannot edit posts', 403 );
69
				}
70
			}
71 View Code Duplication
		} else {
72
			$input = $this->input( false );
73
74
			if ( !is_array( $input ) || !$input ) {
75
				return new WP_Error( 'invalid_input', 'Invalid request input', 400 );
76
			}
77
78
			if ( isset( $input['status'] ) && 'trash' === $input['status'] && ! current_user_can( 'delete_post', $post_id ) ) {
79
				return new WP_Error( 'unauthorized', 'User cannot delete post', 403 );
80
			}
81
82
			// 'future' is an alias for 'publish' for now
83
			if ( isset( $input['status'] ) && 'future' === $input['status'] ) {
84
				$input['status'] = 'publish';
85
			}
86
87
			$post = get_post( $post_id );
88
			$_post_type = ( ! empty( $input['type'] ) ) ? $input['type'] : $post->post_type;
89
			$post_type = get_post_type_object( $_post_type );
90
			if ( !$post || is_wp_error( $post ) ) {
91
				return new WP_Error( 'unknown_post', 'Unknown post', 404 );
92
			}
93
94
			if ( !current_user_can( 'edit_post', $post->ID ) ) {
95
				return new WP_Error( 'unauthorized', 'User cannot edit post', 403 );
96
			}
97
98
			if ( ! empty( $input['author'] ) ) {
99
				$author_id = parent::parse_and_set_author( $input['author'], $_post_type );
100
				unset( $input['author'] );
101
				if ( is_wp_error( $author_id ) )
102
					return $author_id;
103
			}
104
105
			if ( ( isset( $input['status'] ) && 'publish' === $input['status'] ) && 'publish' !== $post->post_status && !current_user_can( 'publish_post', $post->ID ) ) {
106
				$input['status'] = 'pending';
107
			}
108
			$last_status = $post->post_status;
109
			$new_status = isset( $input['status'] ) ? $input['status'] : $last_status;
110
111
			// Make sure that drafts get the current date when transitioning to publish if not supplied in the post.
112
			$date_in_past = ( strtotime($post->post_date_gmt) < time() );
113
			if ( 'publish' === $new_status && 'draft' === $last_status && ! isset( $input['date_gmt'] ) && $date_in_past ) {
114
				$input['date_gmt'] = gmdate( 'Y-m-d H:i:s' );
115
			}
116
		}
117
118
		if ( function_exists( 'wpcom_switch_to_blog_locale' ) ) {
119
			// fixes calypso-pre-oss #12476: respect blog locale when creating the post slug
120
			wpcom_switch_to_blog_locale( $blog_id );
121
		}
122
123
		 // If date is set, $this->input will set date_gmt, date still needs to be adjusted f
124 View Code Duplication
		if ( isset( $input['date_gmt'] ) ) {
125
			$gmt_offset = get_option( 'gmt_offset' );
126
			$time_with_offset = strtotime( $input['date_gmt'] ) + $gmt_offset * HOUR_IN_SECONDS;
127
			$input['date'] = date( 'Y-m-d H:i:s', $time_with_offset );
128
		}
129
130 View Code Duplication
		if ( ! empty( $author_id ) && get_current_user_id() != $author_id ) {
131
			if ( ! current_user_can( $post_type->cap->edit_others_posts ) ) {
132
				return new WP_Error( 'unauthorized', "User is not allowed to publish others' posts.", 403 );
133
			} elseif ( ! user_can( $author_id, $post_type->cap->edit_posts ) ) {
134
				return new WP_Error( 'unauthorized', 'Assigned author cannot publish post.', 403 );
135
			}
136
		}
137
138
		if ( !is_post_type_hierarchical( $post_type->name ) && 'revision' !== $post_type->name ) {
139
			unset( $input['parent'] );
140
		}
141
142
		foreach ( array( '', '_by_id' ) as $term_key_suffix ) {
143
			$term_input_key = 'terms' . $term_key_suffix;
144
			if ( isset( $input[ $term_input_key ] ) ) {
145
				$input[ $term_input_key ] = (array) $input[ $term_input_key ];
146
			} else {
147
				$input[ $term_input_key ] = array();
148
			}
149
150
			// Convert comma-separated terms to array before attempting to
151
			// merge with hardcoded taxonomies
152
			foreach ( $input[ $term_input_key ] as $taxonomy => $terms ) {
153 View Code Duplication
				if ( is_string( $terms ) ) {
154
					$input[ $term_input_key ][ $taxonomy ] = explode( ',', $terms );
155
				} else if ( ! is_array( $terms ) ) {
156
					$input[ $term_input_key ][ $taxonomy ] = array();
157
				}
158
			}
159
160
			// For each hard-coded taxonomy, merge into terms object
161
			foreach ( array( 'categories' => 'category', 'tags' => 'post_tag' ) as $key_prefix => $taxonomy ) {
162
				$taxonomy_key = $key_prefix . $term_key_suffix;
163
				if ( ! isset( $input[ $taxonomy_key ] ) ) {
164
					continue;
165
				}
166
167
				if ( ! isset( $input[ $term_input_key ][ $taxonomy ] ) ) {
168
					$input[ $term_input_key ][ $taxonomy ] = array();
169
				}
170
171
				$terms = $input[ $taxonomy_key ];
172 View Code Duplication
				if ( is_string( $terms ) ) {
173
					$terms = explode( ',', $terms );
174
				} else if ( ! is_array( $terms ) ) {
175
					continue;
176
				}
177
178
				$input[ $term_input_key ][ $taxonomy ] = array_merge(
179
					$input[ $term_input_key ][ $taxonomy ],
180
					$terms
181
				);
182
			}
183
		}
184
185
		/* add terms by name */
186
		$tax_input = array();
187
		foreach ( $input['terms'] as $taxonomy => $terms ) {
188
			$tax_input[ $taxonomy ] = array();
189
			$is_hierarchical = is_taxonomy_hierarchical( $taxonomy );
190
191
			foreach ( $terms as $term ) {
192
				/**
193
				 * We assume these are names, not IDs, even if they are numeric.
194
				 * Note: A category named "0" will not work right.
195
				 * https://core.trac.wordpress.org/ticket/9059
196
				 */
197
				if ( ! is_string( $term ) ) {
198
					continue;
199
				}
200
201
				$term_info = get_term_by( 'name', $term, $taxonomy, ARRAY_A );
202
203
				if ( ! $term_info ) {
204
					// only add a new tag/cat if the user has access to
205
					$tax = get_taxonomy( $taxonomy );
206
207
					// see https://core.trac.wordpress.org/ticket/26409
208
					if ( $is_hierarchical && ! current_user_can( $tax->cap->edit_terms ) ) {
209
						continue;
210
					} else if ( ! current_user_can( $tax->cap->assign_terms ) ) {
211
						continue;
212
					}
213
214
					$term_info = wp_insert_term( $term, $taxonomy );
215
				}
216
217 View Code Duplication
				if ( ! is_wp_error( $term_info ) ) {
218
					if ( $is_hierarchical ) {
219
						// Hierarchical terms must be added by ID
220
						$tax_input[$taxonomy][] = (int) $term_info['term_id'];
221
					} else {
222
						// Non-hierarchical terms must be added by name
223
						$tax_input[$taxonomy][] = $term;
224
					}
225
				}
226
			}
227
		}
228
229
		/* add terms by ID */
230
		foreach ( $input['terms_by_id'] as $taxonomy => $terms ) {
231
			// combine with any previous selections
232 View Code Duplication
			if ( ! isset( $tax_input[ $taxonomy ] ) || ! is_array( $tax_input[ $taxonomy ] ) ) {
233
				$tax_input[ $taxonomy ] = array();
234
			}
235
236
			$is_hierarchical = is_taxonomy_hierarchical( $taxonomy );
237
238
			foreach ( $terms as $term ) {
239
				$term = (string) $term; // ctype_digit compat
240
				if ( ! ctype_digit( $term ) ) {
241
					// skip anything that doesn't look like an ID
242
					continue;
243
				}
244
				$term = (int) $term;
245
				$term_info = get_term_by( 'id', $term, $taxonomy, ARRAY_A );
246
247 View Code Duplication
				if ( $term_info && ! is_wp_error( $term_info ) ) {
248
					if ( $is_hierarchical ) {
249
						// Categories must be added by ID
250
						$tax_input[$taxonomy][] = $term;
251
					} else {
252
						// Tags must be added by name
253
						$tax_input[$taxonomy][] = $term_info['name'];
254
					}
255
				}
256
			}
257
		}
258
259
		if ( ( isset( $input['terms']['category'] ) || isset( $input['terms_by_id']['category'] ) )
260
				&& empty( $tax_input['category'] ) && 'revision' !== $post_type->name ) {
261
			$tax_input['category'][] = get_option( 'default_category' );
262
		}
263
264
		unset( $input['terms'], $input['tags'], $input['categories'], $input['terms_by_id'], $input['tags_by_id'], $input['categories_by_id'] );
265
266
		$insert = array();
267
268 View Code Duplication
		if ( !empty( $input['slug'] ) ) {
269
			$insert['post_name'] = $input['slug'];
270
			unset( $input['slug'] );
271
		}
272
273 View Code Duplication
		if ( isset( $input['discussion'] ) ) {
274
			$discussion = (array) $input['discussion'];
275
			foreach ( array( 'comment', 'ping' ) as $discussion_type ) {
276
				$discussion_open = sprintf( '%ss_open', $discussion_type );
277
				$discussion_status = sprintf( '%s_status', $discussion_type );
278
279
				if ( isset( $discussion[ $discussion_open ] ) ) {
280
					$is_open = WPCOM_JSON_API::is_truthy( $discussion[ $discussion_open ] );
281
 					$discussion[ $discussion_status ] = $is_open ? 'open' : 'closed';
282
				}
283
284
				if ( in_array( $discussion[ $discussion_status ], array( 'open', 'closed' ) ) ) {
285
					$insert[ $discussion_status ] = $discussion[ $discussion_status ];
286
				}
287
			}
288
		}
289
290
		unset( $input['discussion'] );
291
292 View Code Duplication
		if ( isset( $input['menu_order'] ) ) {
293
			$insert['menu_order'] = $input['menu_order'];
294
			unset( $input['menu_order'] );
295
		}
296
297
		$publicize = isset( $input['publicize'] ) ? $input['publicize'] : null;
298
		unset( $input['publicize'] );
299
300
		$publicize_custom_message = isset( $input['publicize_message'] ) ? $input['publicize_message'] : null;
301
		unset( $input['publicize_message'] );
302
303 View Code Duplication
		if ( isset( $input['featured_image'] ) ) {
304
			$featured_image = trim( $input['featured_image'] );
305
			$delete_featured_image = empty( $featured_image );
306
			unset( $input['featured_image'] );
307
		}
308
309
		$metadata = isset( $input['metadata'] ) ? $input['metadata'] : null;
310
		unset( $input['metadata'] );
311
312
		$likes = isset( $input['likes_enabled'] ) ? $input['likes_enabled'] : null;
313
		unset( $input['likes_enabled'] );
314
315
		$sharing = isset( $input['sharing_enabled'] ) ? $input['sharing_enabled'] : null;
316
		unset( $input['sharing_enabled'] );
317
318
		$sticky = isset( $input['sticky'] ) ? $input['sticky'] : null;
319
		unset( $input['sticky'] );
320
321
		foreach ( $input as $key => $value ) {
322
			$insert["post_$key"] = $value;
323
		}
324
325
		if ( ! empty( $author_id ) ) {
326
			$insert['post_author'] = absint( $author_id );
327
		}
328
329
		if ( ! empty( $tax_input ) ) {
330
			$insert['tax_input'] = $tax_input;
331
		}
332
333
		$has_media = ! empty( $input['media'] ) ? count( $input['media'] ) : false;
334
		$has_media_by_url = ! empty( $input['media_urls'] ) ? count( $input['media_urls'] ) : false;
335
336
		$media_id_string = '';
337
		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...
338
			$media_files = ! empty( $input['media'] ) ? $input['media'] : array();
339
			$media_urls = ! empty( $input['media_urls'] ) ? $input['media_urls'] : array();
340
			$media_attrs = ! empty( $input['media_attrs'] ) ? $input['media_attrs'] : array();
341
			$media_results = $this->handle_media_creation_v1_1( $media_files, $media_urls, $media_attrs );
342
			$media_id_string = join( ',', array_filter( array_map( 'absint', $media_results['media_ids'] ) ) );
343
		}
344
345 View Code Duplication
		if ( $new ) {
346
			if ( isset( $input['content'] ) && ! has_shortcode( $input['content'], 'gallery' ) && ( $has_media || $has_media_by_url ) ) {
347
				switch ( ( $has_media + $has_media_by_url ) ) {
348
				case 0 :
349
					// No images - do nothing.
350
					break;
351
				case 1 :
352
					// 1 image - make it big
353
					$insert['post_content'] = $input['content'] = sprintf(
354
						"[gallery size=full ids='%s' columns=1]\n\n",
355
						$media_id_string
356
					) . $input['content'];
357
					break;
358
				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...
359
					// Several images - 3 column gallery
360
					$insert['post_content'] = $input['content'] = sprintf(
361
						"[gallery ids='%s']\n\n", 
362
						$media_id_string
363
					) . $input['content'];
364
					break;
365
				}
366
			}
367
368
			$post_id = wp_insert_post( add_magic_quotes( $insert ), true );
369
		} else {
370
			$insert['ID'] = $post->ID;
371
372
			// wp_update_post ignores date unless edit_date is set
373
			// See: http://codex.wordpress.org/Function_Reference/wp_update_post#Scheduling_posts
374
			// See: https://core.trac.wordpress.org/browser/tags/3.9.2/src/wp-includes/post.php#L3302
375
			if ( isset( $input['date_gmt'] ) || isset( $input['date'] ) ) {
376
				$insert['edit_date'] = true;
377
			}
378
379
			// this two-step process ensures any changes submitted along with status=trash get saved before trashing
380
			if ( isset( $input['status'] ) && 'trash' === $input['status'] ) {
381
				// if we insert it with status='trash', it will get double-trashed, so insert it as a draft first
382
				unset( $insert['status'] );
383
				$post_id = wp_update_post( (object) $insert );
384
				// now call wp_trash_post so post_meta gets set and any filters get called
385
				wp_trash_post( $post_id );
386
			} else {
387
				$post_id = wp_update_post( (object) $insert );
388
			}
389
		}
390
391
392
		if ( !$post_id || is_wp_error( $post_id ) ) {
393
			return $post_id;
394
		}
395
396
		// make sure this post actually exists and is not an error of some kind (ie, trying to load media in the posts endpoint)
397
		$post_check = $this->get_post_by( 'ID', $post_id, $args['context'] );
398
		if ( is_wp_error( $post_check ) ) {
399
			return $post_check;
400
		}
401
402 View Code Duplication
		if ( $media_id_string ) {
403
			// Yes - this is really how wp-admin does it.
404
			$wpdb->query( $wpdb->prepare(
405
				"UPDATE $wpdb->posts SET post_parent = %d WHERE post_type = 'attachment' AND ID IN ( $media_id_string )",
406
				$post_id
407
			) );
408
			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...
409
				clean_attachment_cache( $media_id );
410
			}
411
			clean_post_cache( $post_id );
412
		}
413
414
		// set page template for this post..
415 View Code Duplication
		if ( isset( $input['page_template'] ) && 'page' == $post_type->name ) {
416
			$page_template = $input['page_template'];
417
			$page_templates = wp_get_theme()->get_page_templates( get_post( $post_id ) );
418
			if ( empty( $page_template ) || 'default' == $page_template || isset( $page_templates[ $page_template ] ) ) {
419
				update_post_meta( $post_id, '_wp_page_template', $page_template );
420
			}
421
		}
422
423
		// Set like status for the post
424
		/** This filter is documented in modules/likes.php */
425
		$sitewide_likes_enabled = (bool) apply_filters( 'wpl_is_enabled_sitewide', ! get_option( 'disabled_likes' ) );
426 View Code Duplication
		if ( $new ) {
427
			if ( $sitewide_likes_enabled ) {
428
				if ( false === $likes ) {
429
					update_post_meta( $post_id, 'switch_like_status', 1 );
430
				} else {
431
					delete_post_meta( $post_id, 'switch_like_status' );
432
				}
433
			} else {
434
				if ( $likes ) {
435
					update_post_meta( $post_id, 'switch_like_status', 1 );
436
				} else {
437
					delete_post_meta( $post_id, 'switch_like_status' );
438
				}
439
			}
440
		} else {
441
			if ( isset( $likes ) ) {
442
				if ( $sitewide_likes_enabled ) {
443
					if ( false === $likes ) {
444
						update_post_meta( $post_id, 'switch_like_status', 1 );
445
					} else {
446
						delete_post_meta( $post_id, 'switch_like_status' );
447
					}
448
				} else {
449
					if ( true === $likes ) {
450
						update_post_meta( $post_id, 'switch_like_status', 1 );
451
					} else {
452
						delete_post_meta( $post_id, 'switch_like_status' );
453
					}
454
				}
455
			}
456
		}
457
458
		// Set sharing status of the post
459 View Code Duplication
		if ( $new ) {
460
			$sharing_enabled = isset( $sharing ) ? (bool) $sharing : true;
461
			if ( false === $sharing_enabled ) {
462
				update_post_meta( $post_id, 'sharing_disabled', 1 );
463
			}
464
		}
465
		else {
466
			if ( isset( $sharing ) && true === $sharing ) {
467
				delete_post_meta( $post_id, 'sharing_disabled' );
468
			} else if ( isset( $sharing ) && false == $sharing ) {
469
				update_post_meta( $post_id, 'sharing_disabled', 1 );
470
			}
471
		}
472
473
		if ( isset( $sticky ) ) {
474
			if ( true === $sticky ) {
475
				stick_post( $post_id );
476
			} else {
477
				unstick_post( $post_id );
478
			}
479
		}
480
481
		// WPCOM Specific (Jetpack's will get bumped elsewhere
482
		// Tracks how many posts are published and sets meta
483
		// so we can track some other cool stats (like likes & comments on posts published)
484 View Code Duplication
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
485
			if (
486
				( $new && 'publish' == $input['status'] )
487
				|| (
488
					!$new && isset( $last_status )
489
					&& 'publish' != $last_status
490
					&& isset( $new_status )
491
					&& 'publish' == $new_status
492
				)
493
			) {
494
				/** This action is documented in modules/widgets/social-media-icons.php */
495
				do_action( 'jetpack_bump_stats_extras', 'api-insights-posts', $this->api->token_details['client_id'] );
496
				update_post_meta( $post_id, '_rest_api_published', 1 );
497
				update_post_meta( $post_id, '_rest_api_client_id', $this->api->token_details['client_id'] );
498
			}
499
		}
500
501
502
		// We ask the user/dev to pass Publicize services he/she wants activated for the post, but Publicize expects us
503
		// to instead flag the ones we don't want to be skipped. proceed with said logic.
504
		// any posts coming from Path (client ID 25952) should also not publicize
505 View Code Duplication
		if ( $publicize === false || ( isset( $this->api->token_details['client_id'] ) && 25952 == $this->api->token_details['client_id'] ) ) {
506
			// No publicize at all, skip all by ID
507
			foreach ( $GLOBALS['publicize_ui']->publicize->get_services( 'all' ) as $name => $service ) {
508
				delete_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $name );
509
				$service_connections   = $GLOBALS['publicize_ui']->publicize->get_connections( $name );
510
				if ( ! $service_connections ) {
511
					continue;
512
				}
513
				foreach ( $service_connections as $service_connection ) {
514
					update_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $service_connection->unique_id, 1 );
515
				}
516
			}
517
		} else if ( is_array( $publicize ) && ( count ( $publicize ) > 0 ) ) {
518
			foreach ( $GLOBALS['publicize_ui']->publicize->get_services( 'all' ) as $name => $service ) {
519
				/*
520
				 * We support both indexed and associative arrays:
521
				 * * indexed are to pass entire services
522
				 * * associative are to pass specific connections per service
523
				 *
524
				 * We do support mixed arrays: mixed integer and string keys (see 3rd example below).
525
				 *
526
				 * EG: array( 'twitter', 'facebook') will only publicize to those, ignoring the other available services
527
				 * 		Form data: publicize[]=twitter&publicize[]=facebook
528
				 * 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.
529
				 * 		Form data: publicize[twitter]=$pub_conn_id_0,$pub_conn_id_3&publicize[facebook]=$pub_conn_id_7
530
				 * 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
531
				 * 		Form data: publicize[]=twitter&publicize[facebook]=$pub_conn_id_0,$pub_conn_id_3
532
				 */
533
534
				// Delete any stale SKIP value for the service by name. We'll add it back by ID.
535
				delete_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $name );
536
537
				// Get the user's connections
538
				$service_connections = $GLOBALS['publicize_ui']->publicize->get_connections( $name );
539
540
				// if the user doesn't have any connections for this service, move on
541
				if ( ! $service_connections ) {
542
					continue;
543
				}
544
545
				if ( !in_array( $name, $publicize ) && !array_key_exists( $name, $publicize ) ) {
546
					// Skip the whole service by adding each connection ID
547
					foreach ( $service_connections as $service_connection ) {
548
						update_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $service_connection->unique_id, 1 );
549
					}
550
				} else if ( !empty( $publicize[ $name ] ) ) {
551
					// Seems we're being asked to only push to [a] specific connection[s].
552
					// Explode the list on commas, which will also support a single passed ID
553
					$requested_connections = explode( ',', ( preg_replace( '/[\s]*/', '', $publicize[ $name ] ) ) );
554
555
					// Flag the connections we can't match with the requested list to be skipped.
556
					foreach ( $service_connections as $service_connection ) {
557
						if ( !in_array( $service_connection->meta['connection_data']->id, $requested_connections ) ) {
558
							update_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $service_connection->unique_id, 1 );
559
						} else {
560
							delete_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $service_connection->unique_id );
561
						}
562
					}
563
				} else {
564
					// delete all SKIP values; it's okay to publish to all connected IDs for this service
565
					foreach ( $service_connections as $service_connection ) {
566
						delete_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $service_connection->unique_id );
567
					}
568
				}
569
			}
570
		}
571
572 View Code Duplication
		if ( ! is_null( $publicize_custom_message ) ) {
573
			if ( empty( $publicize_custom_message ) ) {
574
				delete_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_MESS );
575
			} else {
576
				update_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_MESS, trim( $publicize_custom_message ) );
577
			}
578
		}
579
580 View Code Duplication
		if ( ! empty( $insert['post_format'] ) ) {
581
			if ( 'default' !== strtolower( $insert['post_format'] ) ) {
582
				set_post_format( $post_id, $insert['post_format'] );
583
			}
584
			else {
585
				set_post_format( $post_id, get_option( 'default_post_format' ) );
586
			}
587
		}
588
589
		if ( isset( $featured_image ) ) {
590
			parent::parse_and_set_featured_image( $post_id, $delete_featured_image, $featured_image );
591
		}
592
593 View Code Duplication
		if ( ! empty( $metadata ) ) {
594
			foreach ( (array) $metadata as $meta ) {
595
596
				$meta = (object) $meta;
597
598
				// Custom meta description can only be set on sites that have a business subscription.
599
				if ( Jetpack_SEO_Posts::DESCRIPTION_META_KEY == $meta->key && ! Jetpack_SEO_Utils::is_enabled_jetpack_seo() ) {
600
					return new WP_Error( 'unauthorized', __( 'SEO tools are not enabled for this site.', 'jetpack' ), 403 );
601
				}
602
603
				$existing_meta_item = new stdClass;
604
605
				if ( empty( $meta->operation ) )
606
					$meta->operation = 'update';
607
608
				if ( ! empty( $meta->value ) ) {
609
					if ( 'true' == $meta->value )
610
						$meta->value = true;
611
					if ( 'false' == $meta->value )
612
						$meta->value = false;
613
				}
614
615
				if ( ! empty( $meta->id ) ) {
616
					$meta->id = absint( $meta->id );
617
					$existing_meta_item = get_metadata_by_mid( 'post', $meta->id );
618
					if ( $post_id !== (int) $existing_meta_item->post_id ) {
619
						// Only allow updates for metadata on this post
620
						continue;
621
					}
622
				}
623
624
				$unslashed_meta_key = wp_unslash( $meta->key ); // should match what the final key will be
625
				$meta->key = wp_slash( $meta->key );
626
				$unslashed_existing_meta_key = wp_unslash( $existing_meta_item->meta_key );
627
				$existing_meta_item->meta_key = wp_slash( $existing_meta_item->meta_key );
628
629
				// make sure that the meta id passed matches the existing meta key
630
				if ( ! empty( $meta->id ) && ! empty( $meta->key ) ) {
631
					$meta_by_id = get_metadata_by_mid( 'post', $meta->id );
632
					if ( $meta_by_id->meta_key !== $meta->key ) {
633
						continue; // skip this meta
634
					}
635
				}
636
637
				switch ( $meta->operation ) {
638
					case 'delete':
639
640
						if ( ! empty( $meta->id ) && ! empty( $existing_meta_item->meta_key ) && current_user_can( 'delete_post_meta', $post_id, $unslashed_existing_meta_key ) ) {
641
							delete_metadata_by_mid( 'post', $meta->id );
642
						} elseif ( ! empty( $meta->key ) && ! empty( $meta->previous_value ) && current_user_can( 'delete_post_meta', $post_id, $unslashed_meta_key ) ) {
643
							delete_post_meta( $post_id, $meta->key, $meta->previous_value );
644
						} elseif ( ! empty( $meta->key ) && current_user_can( 'delete_post_meta', $post_id, $unslashed_meta_key ) ) {
645
							delete_post_meta( $post_id, $meta->key );
646
						}
647
648
						break;
649
					case 'add':
650
651
						if ( ! empty( $meta->id ) || ! empty( $meta->previous_value ) ) {
652
							continue;
653
						} 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 ) ) {
654
							add_post_meta( $post_id, $meta->key, $meta->value );
655
						}
656
657
						break;
658
					case 'update':
659
660
						if ( ! isset( $meta->value ) ) {
661
							continue;
662
						} 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 ) ) ) {
663
							update_metadata_by_mid( 'post', $meta->id, $meta->value );
664
						} 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 ) ) ) {
665
							update_post_meta( $post_id, $meta->key,$meta->value, $meta->previous_value );
666
						} elseif ( ! empty( $meta->key ) && ( current_user_can( 'edit_post_meta', $post_id, $unslashed_meta_key ) || WPCOM_JSON_API_Metadata::is_public( $meta->key ) ) ) {
667
							update_post_meta( $post_id, $meta->key, $meta->value );
668
						}
669
670
						break;
671
				}
672
673
			}
674
		}
675
676
		/** This action is documented in json-endpoints/class.wpcom-json-api-update-post-endpoint.php */
677
		do_action( 'rest_api_inserted_post', $post_id, $insert, $new );
678
679
		$return = $this->get_post_by( 'ID', $post_id, $args['context'] );
680
		if ( !$return || is_wp_error( $return ) ) {
681
			return $return;
682
		}
683
684 View Code Duplication
		if ( isset( $input['type'] ) && 'revision' === $input['type'] ) {
685
			$return['preview_nonce'] = wp_create_nonce( 'post_preview_' . $input['parent'] );
686
		}
687
688
		if ( isset( $sticky ) ) {
689
			// workaround for sticky test occasionally failing, maybe a race condition with stick_post() above
690
			$return['sticky'] = ( true === $sticky );
691
		}
692
693
		if ( ! empty( $media_results['errors'] ) )
694
			$return['media_errors'] = $media_results['errors'];
695
696
		if ( 'publish' !== $return['status'] && isset( $input['title'] )) {
697
			$sal_site = $this->get_sal_post_by( 'ID', $post_id, $args['context'] );
698
			$return['other_URLs'] = (object) $sal_site->get_permalink_suggestions( $input['title'] );
699
		}
700
701
		/** This action is documented in json-endpoints/class.wpcom-json-api-site-settings-endpoint.php */
702
		do_action( 'wpcom_json_api_objects', 'posts' );
703
704
		return $return;
705
	}
706
707 View Code Duplication
	protected function should_load_theme_functions( $post_id = null ) {
708
		if ( empty( $post_id ) ) {
709
			$input = $this->input( true );
710
			$type = $input['type'];
711
		} else {
712
			$type = get_post_type( $post_id );
713
		}
714
715
		return ! empty( $type ) && ! in_array( $type, array( 'post', 'revision' ) );
716
	}
717
}
718