class.wpcom-json-api-get-autosave-v1-1-endpoint.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. new WPCOM_JSON_API_Get_Autosave_v1_1_Endpoint( array(
  3. 'description' => 'Get the most recent autosave for a post.',
  4. 'group' => '__do_not_document',
  5. 'stat' => 'posts:autosave',
  6. 'min_version' => '1.1',
  7. 'method' => 'GET',
  8. 'path' => '/sites/%s/posts/%d/autosave',
  9. 'path_labels' => array(
  10. '$site' => '(int|string) Site ID or domain',
  11. '$post_ID' => '(int) The post ID',
  12. ),
  13. 'response_format' => array(
  14. 'ID' => '(int) autodraft post ID',
  15. 'post_ID' => '(int) post ID',
  16. 'author_ID' => '(int) author ID',
  17. 'title' => '(HTML) The post title.',
  18. 'content' => '(HTML) The post content.',
  19. 'excerpt' => '(HTML) The post excerpt.',
  20. 'preview_URL' => '(string) preview URL for the post',
  21. 'modified' => '(ISO 8601 datetime) modified time',
  22. ),
  23. 'example_request' => 'https://public-api.wordpress.com/rest/v1.1/sites/82974409/posts/1/autosave',
  24. ) );
  25. class WPCOM_JSON_API_Get_Autosave_v1_1_Endpoint extends WPCOM_JSON_API_Post_v1_1_Endpoint {
  26. function __construct( $args ) {
  27. parent::__construct( $args );
  28. }
  29. // /sites/%s/posts/%d/autosave -> $blog_id, $post_id
  30. function callback( $path = '', $blog_id = 0, $post_id = 0 ) {
  31. $blog_id = $this->api->switch_to_blog_and_validate_user( $this->api->get_blog_id( $blog_id ) );
  32. if ( is_wp_error( $blog_id ) ) {
  33. return $blog_id;
  34. }
  35. $post = get_post( $post_id );
  36. if ( ! $post || is_wp_error( $post ) ) {
  37. return new WP_Error( 'unknown_post', 'Unknown post', 404 );
  38. }
  39. if ( ! current_user_can( 'edit_post', $post->ID ) ) {
  40. return new WP_Error( 'unauthorized', 'User cannot edit post', 403 );
  41. }
  42. $autosave = wp_get_post_autosave( $post->ID );
  43. if ( $autosave ) {
  44. $preview_url = add_query_arg( 'preview', 'true', get_permalink( $post->ID ) );
  45. $nonce = wp_create_nonce( 'post_preview_' . $post->ID );
  46. $preview_url = add_query_arg( array( 'preview_id' => $auto_ID, 'preview_nonce' => $nonce ), $preview_url );
  47. return array(
  48. 'ID' => $autosave->ID,
  49. 'author_ID' => $autosave->post_author,
  50. 'post_ID' => $autosave->post_parent,
  51. 'title' => $autosave->post_title,
  52. 'content' => $autosave->post_content,
  53. 'excerpt' => $autosave->post_excerpt,
  54. 'preview_URL' => $preview_url,
  55. 'modified' => $this->format_date( $autosave->post_modified )
  56. );
  57. } else {
  58. return new WP_Error( 'not_found', 'No autosaves exist for this post', 404 );
  59. }
  60. }
  61. }