Completed
Push — master-stable ( 3751a6...e73511 )
by
unknown
40:58 queued 32:02
created

WPCOM_JSON_API_Update_Post_Endpoint::callback()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 14
Code Lines 10

Duplication

Lines 14
Ratio 100 %
Metric Value
dl 14
loc 14
rs 9.2
nc 4
cc 4
eloc 10
nop 3
1
<?php
2
class WPCOM_JSON_API_Update_Post_Endpoint extends WPCOM_JSON_API_Post_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
		$new  = $this->api->ends_with( $path, '/new' );
33
		$args = $this->query_args();
34
35
		// unhook publicize, it's hooked again later -- without this, skipping services is impossible
36 View Code Duplication
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
37
			remove_action( 'save_post', array( $GLOBALS['publicize_ui']->publicize, 'async_publicize_post' ), 100, 2 );
38
			add_action( 'rest_api_inserted_post', array( $GLOBALS['publicize_ui']->publicize, 'async_publicize_post' ) );
39
		}
40
41 View Code Duplication
		if ( $new ) {
42
			$input = $this->input( true );
43
44
			if ( 'revision' === $input['type'] ) {
45
				if ( ! isset( $input['parent'] ) ) {
46
					return new WP_Error( 'invalid_input', 'Invalid request input', 400 );
47
				}
48
				$input['status'] = 'inherit'; // force inherit for revision type
49
				$input['slug'] = $input['parent'] . '-autosave-v1';
50
			}
51
			elseif ( !isset( $input['title'] ) && !isset( $input['content'] ) && !isset( $input['excerpt'] ) ) {
52
				return new WP_Error( 'invalid_input', 'Invalid request input', 400 );
53
			}
54
55
			// default to post
56
			if ( empty( $input['type'] ) )
57
				$input['type'] = 'post';
58
59
			$post_type = get_post_type_object( $input['type'] );
60
61
			if ( ! $this->is_post_type_allowed( $input['type'] ) ) {
62
				return new WP_Error( 'unknown_post_type', 'Unknown post type', 404 );
63
			}
64
65
			if ( ! empty( $input['author'] ) ) {
66
				$author_id = $this->parse_and_set_author( $input['author'], $input['type'] );
67
				unset( $input['author'] );
68
				if ( is_wp_error( $author_id ) )
69
					return $author_id;
70
			}
71
72
			if ( 'publish' === $input['status'] ) {
73
				if ( ! current_user_can( $post_type->cap->publish_posts ) ) {
74
					if ( current_user_can( $post_type->cap->edit_posts ) ) {
75
						$input['status'] = 'pending';
76
					} else {
77
						return new WP_Error( 'unauthorized', 'User cannot publish posts', 403 );
78
					}
79
				}
80
			} else {
81
				if ( !current_user_can( $post_type->cap->edit_posts ) ) {
82
					return new WP_Error( 'unauthorized', 'User cannot edit posts', 403 );
83
				}
84
			}
85
		} else {
86
			$input = $this->input( false );
87
88
			if ( !is_array( $input ) || !$input ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $input 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...
89
				return new WP_Error( 'invalid_input', 'Invalid request input', 400 );
90
			}
91
92
			$post = get_post( $post_id );
93
			$_post_type = ( ! empty( $input['type'] ) ) ? $input['type'] : $post->post_type;
94
			$post_type = get_post_type_object( $_post_type );
95
			if ( !$post || is_wp_error( $post ) ) {
96
				return new WP_Error( 'unknown_post', 'Unknown post', 404 );
97
			}
98
99
			if ( !current_user_can( 'edit_post', $post->ID ) ) {
100
				return new WP_Error( 'unauthorized', 'User cannot edit post', 403 );
101
			}
102
103
			if ( ! empty( $input['author'] ) ) {
104
				$author_id = $this->parse_and_set_author( $input['author'], $_post_type );
105
				unset( $input['author'] );
106
				if ( is_wp_error( $author_id ) )
107
					return $author_id;
108
			}
109
110
			if ( ( isset( $input['status'] ) && 'publish' === $input['status'] ) && 'publish' !== $post->post_status && !current_user_can( 'publish_post', $post->ID ) ) {
111
				$input['status'] = 'pending';
112
			}
113
			$last_status = $post->post_status;
114
			$new_status = isset( $input['status'] ) ? $input['status'] : $last_status;
115
116
			// Make sure that drafts get the current date when transitioning to publish if not supplied in the post.
117
			$date_in_past = ( strtotime($post->post_date_gmt) < time() );
118
			if ( 'publish' === $new_status && 'draft' === $last_status && ! isset( $input['date_gmt'] ) && $date_in_past ) {
119
				$input['date_gmt'] = gmdate( 'Y-m-d H:i:s' );
120
			}
121
		}
122
123
		if ( function_exists( 'wpcom_switch_to_locale' ) ) {
124
			// fixes calypso-pre-oss #12476: respect blog locale when creating the post slug
125
			wpcom_switch_to_locale( get_blog_lang_code( $blog_id ) );
126
		}
127
128
		// If date was set, $this->input will set date_gmt, date still needs to be adjusted for the blog's offset
129 View Code Duplication
		if ( isset( $input['date_gmt'] ) ) {
130
			$gmt_offset = get_option( 'gmt_offset' );
131
			$time_with_offset = strtotime( $input['date_gmt'] ) + $gmt_offset * HOUR_IN_SECONDS;
132
			$input['date'] = date( 'Y-m-d H:i:s', $time_with_offset );
133
		}
134
135 View Code Duplication
		if ( ! empty( $author_id ) && get_current_user_id() != $author_id ) {
136
			if ( ! current_user_can( $post_type->cap->edit_others_posts ) ) {
137
				return new WP_Error( 'unauthorized', "User is not allowed to publish others' posts.", 403 );
138
			} elseif ( ! user_can( $author_id, $post_type->cap->edit_posts ) ) {
139
				return new WP_Error( 'unauthorized', 'Assigned author cannot publish post.', 403 );
140
			}
141
		}
142
143
		if ( !is_post_type_hierarchical( $post_type->name ) && 'revision' !== $post_type->name ) {
144
			unset( $input['parent'] );
145
		}
146
147
		$tax_input = array();
148
149 View Code Duplication
		foreach ( array( 'categories' => 'category', 'tags' => 'post_tag' ) as $key => $taxonomy ) {
150
			if ( ! isset( $input[ $key ] ) ) {
151
				continue;
152
			}
153
154
			$tax_input[ $taxonomy ] = array();
155
156
			$is_hierarchical = is_taxonomy_hierarchical( $taxonomy );
157
158
			if ( is_array( $input[$key] ) ) {
159
				$terms = $input[$key];
160
			} else {
161
				$terms = explode( ',', $input[$key] );
162
			}
163
164
			foreach ( $terms as $term ) {
165
				/**
166
				 * `curl --data 'category[]=123'` should be interpreted as a category ID,
167
				 * not a category whose name is '123'.
168
				 *
169
				 * Consequence: To add a category/tag whose name is '123', the client must
170
				 * first look up its ID.
171
				 */
172
				$term = (string) $term; // ctype_digit compat
173
				if ( ctype_digit( $term ) ) {
174
					$term = (int) $term;
175
				}
176
177
				$term_info = term_exists( $term, $taxonomy );
178
179
				if ( ! $term_info ) {
180
					// A term ID that doesn't already exist. Ignore it: we don't know what name to give it.
181
					if ( is_int( $term ) ){
182
						continue;
183
					}
184
					// only add a new tag/cat if the user has access to
185
					$tax = get_taxonomy( $taxonomy );
186
187
					// see https://core.trac.wordpress.org/ticket/26409
188
					if ( 'category' === $taxonomy && ! current_user_can( $tax->cap->edit_terms ) ) {
189
						continue;
190
					} else if ( ! current_user_can( $tax->cap->assign_terms ) ) {
191
						continue;
192
					}
193
194
					$term_info = wp_insert_term( $term, $taxonomy );
195
				}
196
197
				if ( ! is_wp_error( $term_info ) ) {
198
					if ( $is_hierarchical ) {
199
						// Categories must be added by ID
200
						$tax_input[$taxonomy][] = (int) $term_info['term_id'];
201
					} else {
202
						// Tags must be added by name
203
						if ( is_int( $term ) ) {
204
							$term = get_term( $term, $taxonomy );
205
							$tax_input[$taxonomy][] = $term->name;
206
						} else {
207
							$tax_input[$taxonomy][] = $term;
208
						}
209
					}
210
				}
211
			}
212
		}
213
214 View Code Duplication
		if ( isset( $input['categories'] ) && empty( $tax_input['category'] ) && 'revision' !== $post_type->name ) {
215
			$tax_input['category'][] = get_option( 'default_category' );
216
		}
217
218
		unset( $input['tags'], $input['categories'] );
219
220
		$insert = array();
221
222 View Code Duplication
		if ( !empty( $input['slug'] ) ) {
223
			$insert['post_name'] = $input['slug'];
224
			unset( $input['slug'] );
225
		}
226
227
		if ( isset( $input['comments_open'] ) ) {
228
			$insert['comment_status'] = ( true === $input['comments_open'] ) ? 'open' : 'closed';
229
		}
230
231
		if ( isset( $input['pings_open'] ) ) {
232
			$insert['ping_status'] = ( true === $input['pings_open'] ) ? 'open' : 'closed';
233
		}
234
235
		unset( $input['comments_open'], $input['pings_open'] );
236
237 View Code Duplication
		if ( isset( $input['menu_order'] ) ) {
238
			$insert['menu_order'] = $input['menu_order'];
239
			unset( $input['menu_order'] );
240
		}
241
242
		$publicize = isset( $input['publicize'] ) ? $input['publicize'] : null;
243
		unset( $input['publicize'] );
244
245
		$publicize_custom_message = isset( $input['publicize_message'] ) ? $input['publicize_message'] : null;
246
		unset( $input['publicize_message'] );
247
248 View Code Duplication
		if ( isset( $input['featured_image'] ) ) {
249
			$featured_image = trim( $input['featured_image'] );
250
			$delete_featured_image = empty( $featured_image );
251
			unset( $input['featured_image'] );
252
		}
253
254
		$metadata = isset( $input['metadata'] ) ? $input['metadata'] : null;
255
		unset( $input['metadata'] );
256
257
		$likes = isset( $input['likes_enabled'] ) ? $input['likes_enabled'] : null;
258
		unset( $input['likes_enabled'] );
259
260
		$sharing = isset( $input['sharing_enabled'] ) ? $input['sharing_enabled'] : null;
261
		unset( $input['sharing_enabled'] );
262
263
		$sticky = isset( $input['sticky'] ) ? $input['sticky'] : null;
264
		unset( $input['sticky'] );
265
266
		foreach ( $input as $key => $value ) {
267
			$insert["post_$key"] = $value;
268
		}
269
270
		if ( ! empty( $author_id ) ) {
271
			$insert['post_author'] = absint( $author_id );
272
		}
273
274
		if ( ! empty( $tax_input ) ) {
275
			$insert['tax_input'] = $tax_input;
276
		}
277
278
		$has_media = isset( $input['media'] ) && $input['media'] ? count( $input['media'] ) : false;
279
		$has_media_by_url = isset( $input['media_urls'] ) && $input['media_urls'] ? count( $input['media_urls'] ) : false;
280
281 View Code Duplication
		if ( $new ) {
282
283
			if ( isset( $input['content'] ) && ! has_shortcode( $input['content'], 'gallery' ) && ( $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...
Bug Best Practice introduced by
The expression $has_media_by_url 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...
284
				switch ( ( $has_media + $has_media_by_url ) ) {
285
				case 0 :
286
					// No images - do nothing.
287
					break;
288
				case 1 :
289
					// 1 image - make it big
290
					$insert['post_content'] = $input['content'] = "[gallery size=full columns=1]\n\n" . $input['content'];
291
					break;
292
				default :
0 ignored issues
show
Coding Style introduced by
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...
293
					// Several images - 3 column gallery
294
					$insert['post_content'] = $input['content'] = "[gallery]\n\n" . $input['content'];
295
					break;
296
				}
297
			}
298
299
			$post_id = wp_insert_post( add_magic_quotes( $insert ), true );
300
		} else {
301
			$insert['ID'] = $post->ID;
0 ignored issues
show
Bug introduced by
The variable $post 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...
302
303
			// wp_update_post ignores date unless edit_date is set
304
			// See: http://codex.wordpress.org/Function_Reference/wp_update_post#Scheduling_posts
305
			// See: https://core.trac.wordpress.org/browser/tags/3.9.2/src/wp-includes/post.php#L3302
306
			if ( isset( $input['date_gmt'] ) || isset( $input['date'] ) ) {
307
				$insert['edit_date'] = true;
308
			}
309
310
			$post_id = wp_update_post( (object) $insert );
311
312
		}
313
314
		if ( !$post_id || is_wp_error( $post_id ) ) {
315
			return $post_id;
316
		}
317
318
		// make sure this post actually exists and is not an error of some kind (ie, trying to load media in the posts endpoint)
319
		$post_check = $this->get_post_by( 'ID', $post_id, $args['context'] );
320
		if ( is_wp_error( $post_check ) ) {
321
			return $post_check;
322
		}
323
324
		if ( $has_media ) {
325
			$this->api->trap_wp_die( 'upload_error' );
326
			foreach ( $input['media'] as $media_item ) {
327
				$_FILES['.api.media.item.'] = $media_item;
328
				// check for WP_Error if we ever actually need $media_id
329
				$media_id = media_handle_upload( '.api.media.item.', $post_id );
0 ignored issues
show
Unused Code introduced by
$media_id is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
330
			}
331
			$this->api->trap_wp_die( null );
332
333
			unset( $_FILES['.api.media.item.'] );
334
		}
335
336
		if ( $has_media_by_url ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $has_media_by_url 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
			foreach ( $input['media_urls'] as $url ) {
338
				$this->handle_media_sideload( $url, $post_id );
339
			}
340
		}
341
342
		// Set like status for the post
343
		/** This filter is documented in modules/likes.php */
344
		$sitewide_likes_enabled = (bool) apply_filters( 'wpl_is_enabled_sitewide', ! get_option( 'disabled_likes' ) );
345 View Code Duplication
		if ( $new ) {
346
			if ( $sitewide_likes_enabled ) {
347
				if ( false === $likes ) {
348
					update_post_meta( $post_id, 'switch_like_status', 1 );
349
				} else {
350
					delete_post_meta( $post_id, 'switch_like_status' );
351
				}
352
			} else {
353
				if ( $likes ) {
354
					update_post_meta( $post_id, 'switch_like_status', 1 );
355
				} else {
356
					delete_post_meta( $post_id, 'switch_like_status' );
357
				}
358
			}
359
		} else {
360
			if ( isset( $likes ) ) {
361
				if ( $sitewide_likes_enabled ) {
362
					if ( false === $likes ) {
363
						update_post_meta( $post_id, 'switch_like_status', 1 );
364
					} else {
365
						delete_post_meta( $post_id, 'switch_like_status' );
366
					}
367
				} else {
368
					if ( true === $likes ) {
369
						update_post_meta( $post_id, 'switch_like_status', 1 );
370
					} else {
371
						delete_post_meta( $post_id, 'switch_like_status' );
372
					}
373
				}
374
			}
375
		}
376
377
		// Set sharing status of the post
378 View Code Duplication
		if ( $new ) {
379
			$sharing_enabled = isset( $sharing ) ? (bool) $sharing : true;
380
			if ( false === $sharing_enabled ) {
381
				update_post_meta( $post_id, 'sharing_disabled', 1 );
382
			}
383
		}
384
		else {
385
			if ( isset( $sharing ) && true === $sharing ) {
386
				delete_post_meta( $post_id, 'sharing_disabled' );
387
			} else if ( isset( $sharing ) && false == $sharing ) {
388
				update_post_meta( $post_id, 'sharing_disabled', 1 );
389
			}
390
		}
391
392
		if ( isset( $sticky ) ) {
393
			if ( true === $sticky ) {
394
				stick_post( $post_id );
395
			} else {
396
				unstick_post( $post_id );
397
			}
398
		}
399
400
		// WPCOM Specific (Jetpack's will get bumped elsewhere
401
		// Tracks how many posts are published and sets meta
402
		// so we can track some other cool stats (like likes & comments on posts published)
403 View Code Duplication
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
404
			if (
405
				( $new && 'publish' == $input['status'] )
406
				|| (
407
					! $new && isset( $last_status )
408
					&& 'publish' != $last_status
0 ignored issues
show
Bug introduced by
The variable $last_status 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
					&& isset( $new_status )
410
					&& 'publish' == $new_status
0 ignored issues
show
Bug introduced by
The variable $new_status 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...
411
				)
412
			) {
413
				/** This action is documented in modules/widgets/social-media-icons.php */
414
				do_action( 'jetpack_bump_stats_extras', 'api-insights-posts', $this->api->token_details['client_id'] );
415
				update_post_meta( $post_id, '_rest_api_published', 1 );
416
				update_post_meta( $post_id, '_rest_api_client_id', $this->api->token_details['client_id'] );
417
			}
418
		}
419
420
421
		// We ask the user/dev to pass Publicize services he/she wants activated for the post, but Publicize expects us
422
		// to instead flag the ones we don't want to be skipped. proceed with said logic.
423
		// any posts coming from Path (client ID 25952) should also not publicize
424 View Code Duplication
		if ( $publicize === false || ( isset( $this->api->token_details['client_id'] ) && 25952 == $this->api->token_details['client_id'] ) ) {
425
			// No publicize at all, skip all by ID
426
			foreach ( $GLOBALS['publicize_ui']->publicize->get_services( 'all' ) as $name => $service ) {
427
				delete_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $name );
428
				$service_connections   = $GLOBALS['publicize_ui']->publicize->get_connections( $name );
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned correctly; expected 1 space but found 3 spaces

This check looks for improperly formatted assignments.

Every assignment must have exactly one space before and one space after the equals operator.

To illustrate:

$a = "a";
$ab = "ab";
$abc = "abc";

will have no issues, while

$a   = "a";
$ab  = "ab";
$abc = "abc";

will report issues in lines 1 and 2.

Loading history...
429
				if ( ! $service_connections ) {
430
					continue;
431
				}
432
				foreach ( $service_connections as $service_connection ) {
433
					update_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $service_connection->unique_id, 1 );
434
				}
435
			}
436
		} else if ( is_array( $publicize ) && ( count ( $publicize ) > 0 ) ) {
437
			foreach ( $GLOBALS['publicize_ui']->publicize->get_services( 'all' ) as $name => $service ) {
438
				/*
439
				 * We support both indexed and associative arrays:
440
				 * * indexed are to pass entire services
441
				 * * associative are to pass specific connections per service
442
				 *
443
				 * We do support mixed arrays: mixed integer and string keys (see 3rd example below).
444
				 *
445
				 * EG: array( 'twitter', 'facebook') will only publicize to those, ignoring the other available services
446
				 * 		Form data: publicize[]=twitter&publicize[]=facebook
447
				 * 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.
448
				 * 		Form data: publicize[twitter]=$pub_conn_id_0,$pub_conn_id_3&publicize[facebook]=$pub_conn_id_7
449
				 * 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
450
				 * 		Form data: publicize[]=twitter&publicize[facebook]=$pub_conn_id_0,$pub_conn_id_3
451
				 */
452
453
				// Delete any stale SKIP value for the service by name. We'll add it back by ID.
454
				delete_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $name );
455
456
				// Get the user's connections
457
				$service_connections = $GLOBALS['publicize_ui']->publicize->get_connections( $name );
458
459
				// if the user doesn't have any connections for this service, move on
460
				if ( ! $service_connections ) {
461
					continue;
462
				}
463
464
				if ( !in_array( $name, $publicize ) && !array_key_exists( $name, $publicize ) ) {
465
					// Skip the whole service by adding each connection ID
466
					foreach ( $service_connections as $service_connection ) {
467
						update_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $service_connection->unique_id, 1 );
468
					}
469
				} else if ( !empty( $publicize[ $name ] ) ) {
470
					// Seems we're being asked to only push to [a] specific connection[s].
471
					// Explode the list on commas, which will also support a single passed ID
472
					$requested_connections = explode( ',', ( preg_replace( '/[\s]*/', '', $publicize[ $name ] ) ) );
473
					// Flag the connections we can't match with the requested list to be skipped.
474
					foreach ( $service_connections as $service_connection ) {
475
						if ( !in_array( $service_connection->meta['connection_data']->id, $requested_connections ) ) {
476
							update_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $service_connection->unique_id, 1 );
477
						} else {
478
							delete_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $service_connection->unique_id );
479
						}
480
					}
481
				} else {
482
					// delete all SKIP values; it's okay to publish to all connected IDs for this service
483
					foreach ( $service_connections as $service_connection ) {
484
						delete_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $service_connection->unique_id );
485
					}
486
				}
487
			}
488
		}
489
490 View Code Duplication
		if ( ! is_null( $publicize_custom_message ) ) {
491
			if ( empty( $publicize_custom_message ) ) {
492
				delete_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_MESS );
493
			} else {
494
				update_post_meta( $post_id, $GLOBALS['publicize_ui']->publicize->POST_MESS, trim( $publicize_custom_message ) );
495
			}
496
		}
497
498 View Code Duplication
		if ( ! empty( $insert['post_format'] ) ) {
499
			if ( 'default' !== strtolower( $insert['post_format'] ) ) {
500
				set_post_format( $post_id, $insert['post_format'] );
501
			}
502
			else {
503
				set_post_format( $post_id, get_option( 'default_post_format' ) );
504
			}
505
		}
506
507
		if ( isset( $featured_image  ) ) {
508
			$this->parse_and_set_featured_image( $post_id, $delete_featured_image, $featured_image );
0 ignored issues
show
Bug introduced by
The variable $delete_featured_image 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...
509
		}
510
511 View Code Duplication
		if ( ! empty( $metadata ) ) {
512
			foreach ( (array) $metadata as $meta ) {
513
514
				$meta = (object) $meta;
515
516
				$existing_meta_item = new stdClass;
517
518
				if ( empty( $meta->operation ) )
519
					$meta->operation = 'update';
520
521
				if ( ! empty( $meta->value ) ) {
522
					if ( 'true' == $meta->value )
523
						$meta->value = true;
524
					if ( 'false' == $meta->value )
525
						$meta->value = false;
526
				}
527
528
				if ( ! empty( $meta->id ) ) {
529
					$meta->id = absint( $meta->id );
530
					$existing_meta_item = get_metadata_by_mid( 'post', $meta->id );
531
				}
532
533
				$unslashed_meta_key = wp_unslash( $meta->key ); // should match what the final key will be
534
				$meta->key = wp_slash( $meta->key );
535
				$unslashed_existing_meta_key = wp_unslash( $existing_meta_item->meta_key );
536
				$existing_meta_item->meta_key = wp_slash( $existing_meta_item->meta_key );
537
538
				// make sure that the meta id passed matches the existing meta key
539
				if ( ! empty( $meta->id ) && ! empty( $meta->key ) ) {
540
					$meta_by_id = get_metadata_by_mid( 'post', $meta->id );
541
					if ( $meta_by_id->meta_key !== $meta->key ) {
542
						continue; // skip this meta
543
					}
544
				}
545
546
				switch ( $meta->operation ) {
547
					case 'delete':
0 ignored issues
show
Coding Style introduced by
The case body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a case statement must start on the line immediately following the case statement.

switch ($expr) {
case "A":
    doSomething(); //right
    break;
case "B":

    doSomethingElse(); //wrong
    break;

}

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

Loading history...
548
549
						if ( ! empty( $meta->id ) && ! empty( $existing_meta_item->meta_key ) && current_user_can( 'delete_post_meta', $post_id, $unslashed_existing_meta_key ) ) {
550
							delete_metadata_by_mid( 'post', $meta->id );
551
						} elseif ( ! empty( $meta->key ) && ! empty( $meta->previous_value ) && current_user_can( 'delete_post_meta', $post_id, $unslashed_meta_key ) ) {
552
							delete_post_meta( $post_id, $meta->key, $meta->previous_value );
553
						} elseif ( ! empty( $meta->key ) && current_user_can( 'delete_post_meta', $post_id, $unslashed_meta_key ) ) {
554
							delete_post_meta( $post_id, $meta->key );
555
						}
556
557
						break;
558
					case 'add':
0 ignored issues
show
Coding Style introduced by
The case body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a case statement must start on the line immediately following the case statement.

switch ($expr) {
case "A":
    doSomething(); //right
    break;
case "B":

    doSomethingElse(); //wrong
    break;

}

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

Loading history...
559
560
						if ( ! empty( $meta->id ) || ! empty( $meta->previous_value ) ) {
561
							continue;
562
						} elseif ( ! empty( $meta->key ) && ! empty( $meta->value ) && ( current_user_can( 'add_post_meta', $post_id, $unslashed_meta_key ) ) || $this->is_metadata_public( $meta->key ) ) {
563
							add_post_meta( $post_id, $meta->key, $meta->value );
564
						}
565
566
						break;
567
					case 'update':
0 ignored issues
show
Coding Style introduced by
The case body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a case statement must start on the line immediately following the case statement.

switch ($expr) {
case "A":
    doSomething(); //right
    break;
case "B":

    doSomethingElse(); //wrong
    break;

}

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

Loading history...
568
569
						if ( ! isset( $meta->value ) ) {
570
							continue;
571
						} elseif ( ! empty( $meta->id ) && ! empty( $existing_meta_item->meta_key ) && ( current_user_can( 'edit_post_meta', $post_id, $unslashed_existing_meta_key ) || $this->is_metadata_public( $meta->key ) ) ) {
572
							update_metadata_by_mid( 'post', $meta->id, $meta->value );
573
						} elseif ( ! empty( $meta->key ) && ! empty( $meta->previous_value ) && ( current_user_can( 'edit_post_meta', $post_id, $unslashed_meta_key ) || $this->is_metadata_public( $meta->key ) ) ) {
574
							update_post_meta( $post_id, $meta->key,$meta->value, $meta->previous_value );
575
						} elseif ( ! empty( $meta->key ) && ( current_user_can( 'edit_post_meta', $post_id, $unslashed_meta_key ) || $this->is_metadata_public( $meta->key ) ) ) {
576
							update_post_meta( $post_id, $meta->key, $meta->value );
577
						}
578
579
						break;
580
				}
581
582
			}
583
		}
584
585
		/**
586
		 * Fires when a post is created via the REST API.
587
		 *
588
		 * @module json-api
589
		 *
590
		 * @since 2.3.0
591
		 *
592
		 * @param int $post_id Post ID.
593
		 * @param array $insert Data used to build the post.
594
		 * @param string $new New post URL suffix.
595
		 */
596
		do_action( 'rest_api_inserted_post', $post_id, $insert, $new );
597
598
		$return = $this->get_post_by( 'ID', $post_id, $args['context'] );
599
		if ( !$return || is_wp_error( $return ) ) {
600
			return $return;
601
		}
602
603 View Code Duplication
		if ( isset( $input['type'] ) && 'revision' === $input['type'] ) {
604
			$return['preview_nonce'] = wp_create_nonce( 'post_preview_' . $input['parent'] );
605
		}
606
607
		if ( isset( $sticky ) ) {
608
			// workaround for sticky test occasionally failing, maybe a race condition with stick_post() above
609
			$return['sticky'] = ( true === $sticky );
610
		}
611
612
		/** This action is documented in json-endpoints/class.wpcom-json-api-site-settings-endpoint.php */
613
		do_action( 'wpcom_json_api_objects', 'posts' );
614
615
		return $return;
616
	}
617
618
	// /sites/%s/posts/%d/delete -> $blog_id, $post_id
619 View Code Duplication
	function delete_post( $path, $blog_id, $post_id ) {
0 ignored issues
show
Unused Code introduced by
The parameter $path is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $blog_id is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
620
		$post = get_post( $post_id );
621
		if ( !$post || is_wp_error( $post ) ) {
622
			return new WP_Error( 'unknown_post', 'Unknown post', 404 );
623
		}
624
625
		if ( ! $this->is_post_type_allowed( $post->post_type ) ) {
626
			return new WP_Error( 'unknown_post_type', 'Unknown post type', 404 );
627
		}
628
629
		if ( !current_user_can( 'delete_post', $post->ID ) ) {
630
			return new WP_Error( 'unauthorized', 'User cannot delete posts', 403 );
631
		}
632
633
		$args  = $this->query_args();
634
		$return = $this->get_post_by( 'ID', $post->ID, $args['context'] );
635
		if ( !$return || is_wp_error( $return ) ) {
636
			return $return;
637
		}
638
639
		/** This action is documented in json-endpoints/class.wpcom-json-api-site-settings-endpoint.php */
640
		do_action( 'wpcom_json_api_objects', 'posts' );
641
642
		wp_delete_post( $post->ID );
643
644
		$status = get_post_status( $post->ID );
645
		if ( false === $status ) {
646
			$return['status'] = 'deleted';
647
			return $return;
648
		}
649
650
		return $this->get_post_by( 'ID', $post->ID, $args['context'] );
651
	}
652
653
	// /sites/%s/posts/%d/restore -> $blog_id, $post_id
654 View Code Duplication
	function restore_post( $path, $blog_id, $post_id ) {
0 ignored issues
show
Unused Code introduced by
The parameter $path is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $blog_id is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
655
		$args  = $this->query_args();
656
		$post = get_post( $post_id );
657
658
		if ( !$post || is_wp_error( $post ) ) {
659
			return new WP_Error( 'unknown_post', 'Unknown post', 404 );
660
		}
661
662
		if ( !current_user_can( 'delete_post', $post->ID ) ) {
663
			return new WP_Error( 'unauthorized', 'User cannot restore trashed posts', 403 );
664
		}
665
666
		/** This action is documented in json-endpoints/class.wpcom-json-api-site-settings-endpoint.php */
667
		do_action( 'wpcom_json_api_objects', 'posts' );
668
669
		wp_untrash_post( $post->ID );
670
671
		return $this->get_post_by( 'ID', $post->ID, $args['context'] );
672
	}
673
674 View Code Duplication
	private function parse_and_set_featured_image( $post_id, $delete_featured_image, $featured_image ) {
675
		if ( $delete_featured_image ) {
676
			delete_post_thumbnail( $post_id );
677
			return;
678
		}
679
680
		$featured_image = (string) $featured_image;
681
682
		// if we got a post ID, we can just set it as the thumbnail
683
		if ( ctype_digit( $featured_image ) && 'attachment' == get_post_type( $featured_image ) ) {
684
			set_post_thumbnail( $post_id, $featured_image );
685
			return $featured_image;
686
		}
687
688
		$featured_image_id = $this->handle_media_sideload( $featured_image, $post_id );
689
690
		if ( empty( $featured_image_id ) || ! is_int( $featured_image_id ) )
691
			return false;
692
693
		set_post_thumbnail( $post_id, $featured_image_id );
694
		return $featured_image_id;
695
	}
696
697 View Code Duplication
	private function parse_and_set_author( $author = null, $post_type = 'post' ) {
698
		if ( empty( $author ) || ! post_type_supports( $post_type, 'author' ) )
699
			return get_current_user_id();
700
701
		$author = (string) $author;
702
		if ( ctype_digit( $author ) ) {
703
			$_user = get_user_by( 'id', $author );
704
			if ( ! $_user || is_wp_error( $_user ) )
705
				return new WP_Error( 'invalid_author', 'Invalid author provided' );
706
707
			return $_user->ID;
708
		}
709
710
		$_user = get_user_by( 'login', $author );
711
		if ( ! $_user || is_wp_error( $_user ) )
712
			return new WP_Error( 'invalid_author', 'Invalid author provided' );
713
714
		return $_user->ID;
715
	}
716
}
717