Completed
Push — fix/normalize-www-in-site-url-... ( e67e76 )
by
unknown
13:13 queued 02:59
created

....wpcom-json-api-autosave-post-v1-1-endpoint.php (1 issue)

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_Autosave_Post_v1_1_Endpoint extends WPCOM_JSON_API_Post_v1_1_Endpoint {
3
	function __construct( $args ) {
4
		parent::__construct( $args );
5
	}
6
7
	// /sites/%s/posts/%d/autosave -> $blog_id, $post_id
8
	function callback( $path = '', $blog_id = 0, $post_id = 0 ) {
9
10
		$blog_id = $this->api->switch_to_blog_and_validate_user( $this->api->get_blog_id( $blog_id ) );
0 ignored issues
show
Consider using a different name than the parameter $blog_id. This often makes code more readable.
Loading history...
11
		if ( is_wp_error( $blog_id ) ) {
12
			return $blog_id;
13
		}
14
15
		$args = $this->query_args();
16
17
		$input = $this->input( false );
18
19
		if ( ! is_array( $input ) || ! $input ) {
20
			return new WP_Error( 'invalid_input', 'Invalid request input', 400 );
21
		}
22
23
		$post = get_post( $post_id );
24
25
		if ( ! $post || is_wp_error( $post ) ) {
26
			return new WP_Error( 'unknown_post', 'Unknown post', 404 );
27
		}
28
29
		if ( ! current_user_can( 'edit_post', $post->ID ) ) {
30
			return new WP_Error( 'unauthorized', 'User cannot edit post', 403 );
31
		}
32
33
		$post_data = array (
34
			'post_ID'      => $post_id,
35
			'post_title'   => $input['title'],
36
			'post_content' => $input['content'],
37
			'post_excerpt' => $input['excerpt'],
38
		);
39
40
		$preview_url = add_query_arg( 'preview', 'true', get_permalink( $post->ID ) );
41
42
		if ( ! wp_check_post_lock( $post->ID ) &&
43
			 get_current_user_id() == $post->post_author &&
44
			 ( 'auto-draft' == $post->post_status || 'draft' == $post->post_status )
45
		) {
46
			// Drafts and auto-drafts are just overwritten by autosave for the same user if the post is not locked
47
			$auto_ID = edit_post( wp_slash( $post_data ) );
48
		} else {
49
			// Non drafts or other users drafts are not overwritten. The autosave is stored in a special post revision for each user.
50
			$auto_ID = wp_create_post_autosave( wp_slash( $post_data ) );
51
			$nonce = wp_create_nonce( 'post_preview_' . $post->ID );
52
			$preview_url = add_query_arg( array( 'preview_id' => $auto_ID, 'preview_nonce' => $nonce ), $preview_url );
53
		}
54
55
		$updated_post = get_post( $auto_ID );
56
57
		if ( $updated_post && $updated_post->ID && $updated_post->post_modified ) {
58
			return array(
59
				'ID'          => $auto_ID,
60
				'post_ID'     => $post->ID,
61
				'modified'    => $this->format_date( $updated_post->post_modified ),
62
				'preview_URL' => $preview_url
63
			);
64
		} else {
65
			return new WP_Error( 'autosave_error', __( 'Autosave encountered an unexpected error', 'jetpack' ), 500 );
66
		}
67
	}
68
}
69