[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-includes/rest-api/endpoints/ -> class-wp-rest-revisions-controller.php (source)

   1  <?php
   2  /**
   3   * REST API: WP_REST_Revisions_Controller class
   4   *
   5   * @package WordPress
   6   * @subpackage REST_API
   7   * @since 4.7.0
   8   */
   9  
  10  /**
  11   * Core class used to access revisions via the REST API.
  12   *
  13   * @since 4.7.0
  14   *
  15   * @see WP_REST_Controller
  16   */
  17  class WP_REST_Revisions_Controller extends WP_REST_Controller {
  18  
  19      /**
  20       * Parent post type.
  21       *
  22       * @since 4.7.0
  23       * @var string
  24       */
  25      private $parent_post_type;
  26  
  27      /**
  28       * Instance of a revision meta fields object.
  29       *
  30       * @since 6.4.0
  31       * @since 7.2.0 Now a WP_REST_Revision_Meta_Fields instance, which only exposes revisioned meta keys.
  32       * @var WP_REST_Post_Meta_Fields
  33       */
  34      protected $meta;
  35  
  36      /**
  37       * Parent controller.
  38       *
  39       * @since 4.7.0
  40       * @var WP_REST_Controller
  41       */
  42      private $parent_controller;
  43  
  44      /**
  45       * The base of the parent controller's route.
  46       *
  47       * @since 4.7.0
  48       * @var string
  49       */
  50      private $parent_base;
  51  
  52      /**
  53       * Constructor.
  54       *
  55       * @since 4.7.0
  56       *
  57       * @param string $parent_post_type Post type of the parent.
  58       */
  59  	public function __construct( $parent_post_type ) {
  60          $this->parent_post_type = $parent_post_type;
  61          $post_type_object       = get_post_type_object( $parent_post_type );
  62          $parent_controller      = $post_type_object->get_rest_controller();
  63  
  64          if ( ! $parent_controller ) {
  65              $parent_controller = new WP_REST_Posts_Controller( $parent_post_type );
  66          }
  67  
  68          $this->parent_controller = $parent_controller;
  69          $this->rest_base         = 'revisions';
  70          $this->parent_base       = ! empty( $post_type_object->rest_base ) ? $post_type_object->rest_base : $post_type_object->name;
  71          $this->namespace         = ! empty( $post_type_object->rest_namespace ) ? $post_type_object->rest_namespace : 'wp/v2';
  72          $this->meta              = new WP_REST_Revision_Meta_Fields( $parent_post_type );
  73      }
  74  
  75      /**
  76       * Registers the routes for revisions based on post types supporting revisions.
  77       *
  78       * @since 4.7.0
  79       *
  80       * @see register_rest_route()
  81       */
  82  	public function register_routes() {
  83  
  84          register_rest_route(
  85              $this->namespace,
  86              '/' . $this->parent_base . '/(?P<parent>[\d]+)/' . $this->rest_base,
  87              array(
  88                  'args'   => array(
  89                      'parent' => array(
  90                          'description' => __( 'The ID for the parent of the revision.' ),
  91                          'type'        => 'integer',
  92                      ),
  93                  ),
  94                  array(
  95                      'methods'             => WP_REST_Server::READABLE,
  96                      'callback'            => array( $this, 'get_items' ),
  97                      'permission_callback' => array( $this, 'get_items_permissions_check' ),
  98                      'args'                => $this->get_collection_params(),
  99                  ),
 100                  'schema' => array( $this, 'get_public_item_schema' ),
 101              )
 102          );
 103  
 104          register_rest_route(
 105              $this->namespace,
 106              '/' . $this->parent_base . '/(?P<parent>[\d]+)/' . $this->rest_base . '/(?P<id>[\d]+)',
 107              array(
 108                  'args'   => array(
 109                      'parent' => array(
 110                          'description' => __( 'The ID for the parent of the revision.' ),
 111                          'type'        => 'integer',
 112                      ),
 113                      'id'     => array(
 114                          'description' => __( 'Unique identifier for the revision.' ),
 115                          'type'        => 'integer',
 116                      ),
 117                  ),
 118                  array(
 119                      'methods'             => WP_REST_Server::READABLE,
 120                      'callback'            => array( $this, 'get_item' ),
 121                      'permission_callback' => array( $this, 'get_item_permissions_check' ),
 122                      'args'                => array(
 123                          'context' => $this->get_context_param( array( 'default' => 'view' ) ),
 124                      ),
 125                  ),
 126                  array(
 127                      'methods'             => WP_REST_Server::DELETABLE,
 128                      'callback'            => array( $this, 'delete_item' ),
 129                      'permission_callback' => array( $this, 'delete_item_permissions_check' ),
 130                      'args'                => array(
 131                          'force' => array(
 132                              'type'        => 'boolean',
 133                              'default'     => false,
 134                              'description' => __( 'Required to be true, as revisions do not support trashing.' ),
 135                          ),
 136                      ),
 137                  ),
 138                  'schema' => array( $this, 'get_public_item_schema' ),
 139              )
 140          );
 141      }
 142  
 143      /**
 144       * Get the parent post, if the ID is valid.
 145       *
 146       * @since 4.7.2
 147       *
 148       * @param int $parent_post_id Supplied ID.
 149       * @return WP_Post|WP_Error Post object if ID is valid, WP_Error otherwise.
 150       */
 151  	protected function get_parent( $parent_post_id ) {
 152          $error = new WP_Error(
 153              'rest_post_invalid_parent',
 154              __( 'Invalid post parent ID.' ),
 155              array( 'status' => 404 )
 156          );
 157  
 158          if ( (int) $parent_post_id <= 0 ) {
 159              return $error;
 160          }
 161  
 162          $parent_post = get_post( (int) $parent_post_id );
 163  
 164          if ( empty( $parent_post ) || empty( $parent_post->ID )
 165              || $this->parent_post_type !== $parent_post->post_type
 166          ) {
 167              return $error;
 168          }
 169  
 170          return $parent_post;
 171      }
 172  
 173      /**
 174       * Checks if a given request has access to get revisions.
 175       *
 176       * @since 4.7.0
 177       *
 178       * @param WP_REST_Request $request Full details about the request.
 179       * @return true|WP_Error True if the request has read access, WP_Error object otherwise.
 180       */
 181  	public function get_items_permissions_check( $request ) {
 182          $parent = $this->get_parent( $request['parent'] );
 183          if ( is_wp_error( $parent ) ) {
 184              return $parent;
 185          }
 186  
 187          if ( ! current_user_can( 'edit_post', $parent->ID ) ) {
 188              return new WP_Error(
 189                  'rest_cannot_read',
 190                  __( 'Sorry, you are not allowed to view revisions of this post.' ),
 191                  array( 'status' => rest_authorization_required_code() )
 192              );
 193          }
 194  
 195          return true;
 196      }
 197  
 198      /**
 199       * Get the revision, if the ID is valid.
 200       *
 201       * @since 4.7.2
 202       *
 203       * @param int $id Supplied ID.
 204       * @return WP_Post|WP_Error Revision post object if ID is valid, WP_Error otherwise.
 205       */
 206  	protected function get_revision( $id ) {
 207          $error = new WP_Error(
 208              'rest_post_invalid_id',
 209              __( 'Invalid revision ID.' ),
 210              array( 'status' => 404 )
 211          );
 212  
 213          if ( (int) $id <= 0 ) {
 214              return $error;
 215          }
 216  
 217          $revision = get_post( (int) $id );
 218          if ( empty( $revision ) || empty( $revision->ID ) || 'revision' !== $revision->post_type ) {
 219              return $error;
 220          }
 221  
 222          return $revision;
 223      }
 224  
 225      /**
 226       * Gets a collection of revisions.
 227       *
 228       * @since 4.7.0
 229       *
 230       * @see WP_REST_Posts_Controller::get_items()
 231       *
 232       * @param WP_REST_Request $request Full details about the request.
 233       * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
 234       */
 235  	public function get_items( $request ) {
 236          $parent = $this->get_parent( $request['parent'] );
 237          if ( is_wp_error( $parent ) ) {
 238              return $parent;
 239          }
 240  
 241          // Ensure a search string is set in case the orderby is set to 'relevance'.
 242          if ( ! empty( $request['orderby'] ) && 'relevance' === $request['orderby'] && empty( $request['search'] ) ) {
 243              return new WP_Error(
 244                  'rest_no_search_term_defined',
 245                  __( 'You need to define a search term to order by relevance.' ),
 246                  array( 'status' => 400 )
 247              );
 248          }
 249  
 250          // Ensure an include parameter is set in case the orderby is set to 'include'.
 251          if ( ! empty( $request['orderby'] ) && 'include' === $request['orderby'] && empty( $request['include'] ) ) {
 252              return new WP_Error(
 253                  'rest_orderby_include_missing_include',
 254                  __( 'You need to define an include parameter to order by include.' ),
 255                  array( 'status' => 400 )
 256              );
 257          }
 258  
 259          $is_head_request = $request->is_method( 'HEAD' );
 260  
 261          if ( wp_revisions_enabled( $parent ) ) {
 262              $registered = $this->get_collection_params();
 263              $args       = array(
 264                  'post_parent'      => $parent->ID,
 265                  'post_type'        => 'revision',
 266                  'post_status'      => 'inherit',
 267                  'posts_per_page'   => -1,
 268                  'orderby'          => 'date ID',
 269                  'order'            => 'DESC',
 270                  'suppress_filters' => true,
 271              );
 272  
 273              $parameter_mappings = array(
 274                  'exclude'  => 'post__not_in',
 275                  'include'  => 'post__in',
 276                  'offset'   => 'offset',
 277                  'order'    => 'order',
 278                  'orderby'  => 'orderby',
 279                  'page'     => 'paged',
 280                  'per_page' => 'posts_per_page',
 281                  'search'   => 's',
 282              );
 283  
 284              foreach ( $parameter_mappings as $api_param => $wp_param ) {
 285                  if ( isset( $registered[ $api_param ], $request[ $api_param ] ) ) {
 286                      $args[ $wp_param ] = $request[ $api_param ];
 287                  }
 288              }
 289  
 290              // For backward-compatibility, 'date' needs to resolve to 'date ID'.
 291              if ( 'date' === $args['orderby'] ) {
 292                  $args['orderby'] = 'date ID';
 293              }
 294  
 295              if ( $is_head_request ) {
 296                  // Force the 'fields' argument. For HEAD requests, only post IDs are required to calculate pagination.
 297                  $args['fields'] = 'ids';
 298                  // Disable priming post meta for HEAD requests to improve performance.
 299                  $args['update_post_term_cache'] = false;
 300                  $args['update_post_meta_cache'] = false;
 301              }
 302  
 303              /**
 304               * Filters WP_Query arguments when querying revisions via the REST API.
 305               *
 306               * Serves the same purpose as the {@see 'rest_{$this->post_type}_query'} filter in
 307               * WP_REST_Posts_Controller, but for the standalone WP_REST_Revisions_Controller.
 308               *
 309               * @since 5.0.0
 310               *
 311               * @param array           $args    Array of arguments for WP_Query.
 312               * @param WP_REST_Request $request The REST API request.
 313               */
 314              $args = apply_filters( 'rest_revision_query', $args, $request );
 315              if ( ! is_array( $args ) ) {
 316                  $args = array();
 317              }
 318              $query_args = $this->prepare_items_query( $args, $request );
 319  
 320              $revisions_query = new WP_Query();
 321              $revisions       = $revisions_query->query( $query_args );
 322              $offset          = isset( $query_args['offset'] ) ? (int) $query_args['offset'] : 0;
 323              $page            = isset( $query_args['paged'] ) ? (int) $query_args['paged'] : 0;
 324              $total_revisions = $revisions_query->found_posts;
 325  
 326              if ( $total_revisions < 1 ) {
 327                  // Out-of-bounds, run the query without pagination/offset to get the total count.
 328                  unset( $query_args['paged'], $query_args['offset'] );
 329  
 330                  $count_query                          = new WP_Query();
 331                  $query_args['fields']                 = 'ids';
 332                  $query_args['posts_per_page']         = 1;
 333                  $query_args['update_post_meta_cache'] = false;
 334                  $query_args['update_post_term_cache'] = false;
 335  
 336                  $count_query->query( $query_args );
 337                  $total_revisions = $count_query->found_posts;
 338              }
 339  
 340              if ( $revisions_query->query_vars['posts_per_page'] > 0 ) {
 341                  $max_pages = (int) ceil( $total_revisions / (int) $revisions_query->query_vars['posts_per_page'] );
 342              } else {
 343                  $max_pages = $total_revisions > 0 ? 1 : 0;
 344              }
 345  
 346              if ( $total_revisions > 0 ) {
 347                  if ( $offset >= $total_revisions ) {
 348                      return new WP_Error(
 349                          'rest_revision_invalid_offset_number',
 350                          __( 'The offset number requested is larger than or equal to the number of available revisions.' ),
 351                          array( 'status' => 400 )
 352                      );
 353                  } elseif ( ! $offset && $page > $max_pages ) {
 354                      return new WP_Error(
 355                          'rest_revision_invalid_page_number',
 356                          __( 'The page number requested is larger than the number of pages available.' ),
 357                          array( 'status' => 400 )
 358                      );
 359                  }
 360              }
 361          } else {
 362              $revisions       = array();
 363              $total_revisions = 0;
 364              $max_pages       = 0;
 365              $page            = (int) $request['page'];
 366          }
 367  
 368          if ( ! $is_head_request ) {
 369              $response = array();
 370  
 371              foreach ( $revisions as $revision ) {
 372                  $data       = $this->prepare_item_for_response( $revision, $request );
 373                  $response[] = $this->prepare_response_for_collection( $data );
 374              }
 375  
 376              $response = rest_ensure_response( $response );
 377          } else {
 378              $response = new WP_REST_Response( array() );
 379          }
 380  
 381          $response->header( 'X-WP-Total', (int) $total_revisions );
 382          $response->header( 'X-WP-TotalPages', (int) $max_pages );
 383  
 384          $request_params = $request->get_query_params();
 385          $base_path      = rest_url( sprintf( '%s/%s/%d/%s', $this->namespace, $this->parent_base, $request['parent'], $this->rest_base ) );
 386          $base           = add_query_arg( urlencode_deep( $request_params ), $base_path );
 387  
 388          if ( $page > 1 ) {
 389              $prev_page = $page - 1;
 390  
 391              if ( $prev_page > $max_pages ) {
 392                  $prev_page = $max_pages;
 393              }
 394  
 395              $prev_link = add_query_arg( 'page', $prev_page, $base );
 396              $response->link_header( 'prev', $prev_link );
 397          }
 398          if ( $max_pages > $page ) {
 399              $next_page = $page + 1;
 400              $next_link = add_query_arg( 'page', $next_page, $base );
 401  
 402              $response->link_header( 'next', $next_link );
 403          }
 404  
 405          return $response;
 406      }
 407  
 408      /**
 409       * Checks if a given request has access to get a specific revision.
 410       *
 411       * @since 4.7.0
 412       *
 413       * @param WP_REST_Request $request Full details about the request.
 414       * @return true|WP_Error True if the request has read access for the item, WP_Error object otherwise.
 415       */
 416  	public function get_item_permissions_check( $request ) {
 417          return $this->get_items_permissions_check( $request );
 418      }
 419  
 420      /**
 421       * Retrieves one revision from the collection.
 422       *
 423       * @since 4.7.0
 424       * @since 6.5.0 Added a condition to check that parent id matches revision parent id.
 425       *
 426       * @param WP_REST_Request $request Full details about the request.
 427       * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
 428       */
 429  	public function get_item( $request ) {
 430          $parent = $this->get_parent( $request['parent'] );
 431          if ( is_wp_error( $parent ) ) {
 432              return $parent;
 433          }
 434  
 435          $revision = $this->get_revision( $request['id'] );
 436          if ( is_wp_error( $revision ) ) {
 437              return $revision;
 438          }
 439  
 440          if ( (int) $parent->ID !== (int) $revision->post_parent ) {
 441              return new WP_Error(
 442                  'rest_revision_parent_id_mismatch',
 443                  /* translators: %d: A post id. */
 444                  sprintf( __( 'The revision does not belong to the specified parent with id of "%d"' ), $parent->ID ),
 445                  array( 'status' => 404 )
 446              );
 447          }
 448  
 449          $response = $this->prepare_item_for_response( $revision, $request );
 450          return rest_ensure_response( $response );
 451      }
 452  
 453      /**
 454       * Checks if a given request has access to delete a revision.
 455       *
 456       * @since 4.7.0
 457       *
 458       * @param WP_REST_Request $request Full details about the request.
 459       * @return true|WP_Error True if the request has access to delete the item, WP_Error object otherwise.
 460       */
 461  	public function delete_item_permissions_check( $request ) {
 462          $parent = $this->get_parent( $request['parent'] );
 463          if ( is_wp_error( $parent ) ) {
 464              return $parent;
 465          }
 466  
 467          if ( ! current_user_can( 'delete_post', $parent->ID ) ) {
 468              return new WP_Error(
 469                  'rest_cannot_delete',
 470                  __( 'Sorry, you are not allowed to delete revisions of this post.' ),
 471                  array( 'status' => rest_authorization_required_code() )
 472              );
 473          }
 474  
 475          $revision = $this->get_revision( $request['id'] );
 476          if ( is_wp_error( $revision ) ) {
 477              return $revision;
 478          }
 479  
 480          $response = $this->get_items_permissions_check( $request );
 481          if ( ! $response || is_wp_error( $response ) ) {
 482              return $response;
 483          }
 484  
 485          if ( ! current_user_can( 'delete_post', $revision->ID ) ) {
 486              return new WP_Error(
 487                  'rest_cannot_delete',
 488                  __( 'Sorry, you are not allowed to delete this revision.' ),
 489                  array( 'status' => rest_authorization_required_code() )
 490              );
 491          }
 492  
 493          return true;
 494      }
 495  
 496      /**
 497       * Deletes a single revision.
 498       *
 499       * @since 4.7.0
 500       *
 501       * @param WP_REST_Request $request Full details about the request.
 502       * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
 503       */
 504  	public function delete_item( $request ) {
 505          $revision = $this->get_revision( $request['id'] );
 506          if ( is_wp_error( $revision ) ) {
 507              return $revision;
 508          }
 509  
 510          $force = isset( $request['force'] ) ? (bool) $request['force'] : false;
 511  
 512          // We don't support trashing for revisions.
 513          if ( ! $force ) {
 514              return new WP_Error(
 515                  'rest_trash_not_supported',
 516                  /* translators: %s: force=true */
 517                  sprintf( __( "Revisions do not support trashing. Set '%s' to delete." ), 'force=true' ),
 518                  array( 'status' => 501 )
 519              );
 520          }
 521  
 522          $previous = $this->prepare_item_for_response( $revision, $request );
 523  
 524          $result = wp_delete_post( $request['id'], true );
 525  
 526          /**
 527           * Fires after a revision is deleted via the REST API.
 528           *
 529           * @since 4.7.0
 530           *
 531           * @param WP_Post|false|null $result  The revision object (if it was deleted or moved to the Trash successfully)
 532           *                                    or false or null (failure). If the revision was moved to the Trash, $result represents
 533           *                                    its new state; if it was deleted, $result represents its state before deletion.
 534           * @param WP_REST_Request    $request The request sent to the API.
 535           */
 536          do_action( 'rest_delete_revision', $result, $request );
 537  
 538          if ( ! $result ) {
 539              return new WP_Error(
 540                  'rest_cannot_delete',
 541                  __( 'The post cannot be deleted.' ),
 542                  array( 'status' => 500 )
 543              );
 544          }
 545  
 546          $response = new WP_REST_Response();
 547          $response->set_data(
 548              array(
 549                  'deleted'  => true,
 550                  'previous' => $previous->get_data(),
 551              )
 552          );
 553          return $response;
 554      }
 555  
 556      /**
 557       * Determines the allowed query_vars for a get_items() response and prepares
 558       * them for WP_Query.
 559       *
 560       * @since 5.0.0
 561       *
 562       * @param array           $prepared_args Optional. Prepared WP_Query arguments. Default empty array.
 563       * @param WP_REST_Request $request       Optional. Full details about the request.
 564       * @return array Items query arguments.
 565       */
 566  	protected function prepare_items_query( $prepared_args = array(), $request = null ) {
 567          $query_args = array();
 568          if ( ! is_array( $prepared_args ) ) {
 569              $prepared_args = array();
 570          }
 571  
 572          foreach ( $prepared_args as $key => $value ) {
 573              /** This filter is documented in wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php */
 574              $query_args[ $key ] = apply_filters( "rest_query_var-{$key}", $value ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
 575          }
 576  
 577          // Map to proper WP_Query orderby param.
 578          if ( isset( $query_args['orderby'] ) && isset( $request['orderby'] ) ) {
 579              $orderby_mappings = array(
 580                  'id'            => 'ID',
 581                  'include'       => 'post__in',
 582                  'slug'          => 'post_name',
 583                  'include_slugs' => 'post_name__in',
 584              );
 585  
 586              if ( isset( $orderby_mappings[ $request['orderby'] ] ) ) {
 587                  $query_args['orderby'] = $orderby_mappings[ $request['orderby'] ];
 588              }
 589          }
 590  
 591          return $query_args;
 592      }
 593  
 594      /**
 595       * Prepares the revision for the REST response.
 596       *
 597       * @since 4.7.0
 598       * @since 5.9.0 Renamed `$post` to `$item` to match parent class for PHP 8 named parameter support.
 599       * @since 7.1.0 The global post is now restored to its previous value before returning.
 600       * @since 7.2.0 The `meta` field only includes the meta keys that are revisioned for the parent post type.
 601       *
 602       * @global WP_Post|null $post Global post object.
 603       *
 604       * @param WP_Post         $item    Post revision object.
 605       * @param WP_REST_Request $request Request object.
 606       * @return WP_REST_Response Response object.
 607       */
 608  	public function prepare_item_for_response( $item, $request ) {
 609          /*
 610           * Save the previous global post so it can be restored before returning.
 611           * Preparing the revision sets up the global post and post data, which
 612           * must not leak into the rest of the request (e.g. the autosaves endpoint
 613           * is preloaded in the block editor, where a leaked global post can cause
 614           * the editor to be initialized with the wrong post).
 615           *
 616           * Note that $post is intentionally not declared as a global here. It must
 617           * remain local to this method so that a filter which reassigns the global
 618           * post while the response is being prepared (for example on 'the_content')
 619           * cannot change which post the remaining fields are read from.
 620           */
 621          $previous_post = isset( $GLOBALS['post'] ) && $GLOBALS['post'] instanceof WP_Post ? $GLOBALS['post'] : null;
 622  
 623          // Restores the more descriptive, specific name for use within this method.
 624          $post = $item;
 625  
 626          $GLOBALS['post'] = $post;
 627  
 628          setup_postdata( $post );
 629  
 630          // Don't prepare the response body for HEAD requests.
 631          if ( $request->is_method( 'HEAD' ) ) {
 632              /** This filter is documented in wp-includes/rest-api/endpoints/class-wp-rest-revisions-controller.php */
 633              $response = apply_filters( 'rest_prepare_revision', new WP_REST_Response( array() ), $post, $request );
 634  
 635              $this->restore_post_data( $previous_post );
 636  
 637              return $response;
 638          }
 639  
 640          $fields = $this->get_fields_for_response( $request );
 641          $data   = array();
 642  
 643          if ( in_array( 'author', $fields, true ) ) {
 644              $data['author'] = (int) $post->post_author;
 645          }
 646  
 647          if ( in_array( 'date', $fields, true ) ) {
 648              $data['date'] = $this->prepare_date_response( $post->post_date_gmt, $post->post_date );
 649          }
 650  
 651          if ( in_array( 'date_gmt', $fields, true ) ) {
 652              $data['date_gmt'] = $this->prepare_date_response( $post->post_date_gmt );
 653          }
 654  
 655          if ( in_array( 'id', $fields, true ) ) {
 656              $data['id'] = $post->ID;
 657          }
 658  
 659          if ( in_array( 'modified', $fields, true ) ) {
 660              $data['modified'] = $this->prepare_date_response( $post->post_modified_gmt, $post->post_modified );
 661          }
 662  
 663          if ( in_array( 'modified_gmt', $fields, true ) ) {
 664              $data['modified_gmt'] = $this->prepare_date_response( $post->post_modified_gmt );
 665          }
 666  
 667          if ( in_array( 'parent', $fields, true ) ) {
 668              $data['parent'] = (int) $post->post_parent;
 669          }
 670  
 671          if ( in_array( 'slug', $fields, true ) ) {
 672              $data['slug'] = $post->post_name;
 673          }
 674  
 675          if ( rest_is_field_included( 'guid', $fields ) ) {
 676              $data['guid'] = array();
 677          }
 678          if ( rest_is_field_included( 'guid.rendered', $fields ) ) {
 679              /** This filter is documented in wp-includes/post-template.php */
 680              $data['guid']['rendered'] = apply_filters( 'get_the_guid', $post->guid, $post->ID );
 681          }
 682          if ( rest_is_field_included( 'guid.raw', $fields ) ) {
 683              $data['guid']['raw'] = $post->guid;
 684          }
 685  
 686          if ( rest_is_field_included( 'title', $fields ) ) {
 687              $data['title'] = array();
 688          }
 689          if ( rest_is_field_included( 'title.raw', $fields ) ) {
 690              $data['title']['raw'] = $post->post_title;
 691          }
 692          if ( rest_is_field_included( 'title.rendered', $fields ) ) {
 693              $data['title']['rendered'] = get_the_title( $post->ID );
 694          }
 695  
 696          if ( rest_is_field_included( 'content', $fields ) ) {
 697              $data['content'] = array();
 698          }
 699          if ( rest_is_field_included( 'content.raw', $fields ) ) {
 700              $data['content']['raw'] = $post->post_content;
 701          }
 702          if ( rest_is_field_included( 'content.rendered', $fields ) ) {
 703              /** This filter is documented in wp-includes/post-template.php */
 704              $data['content']['rendered'] = apply_filters( 'the_content', $post->post_content );
 705          }
 706  
 707          if ( rest_is_field_included( 'excerpt', $fields ) ) {
 708              $data['excerpt'] = array();
 709          }
 710          if ( rest_is_field_included( 'excerpt.raw', $fields ) ) {
 711              $data['excerpt']['raw'] = $post->post_excerpt;
 712          }
 713          if ( rest_is_field_included( 'excerpt.rendered', $fields ) ) {
 714              $data['excerpt']['rendered'] = $this->prepare_excerpt_response( $post->post_excerpt, $post );
 715          }
 716  
 717          if ( rest_is_field_included( 'meta', $fields ) ) {
 718              $data['meta'] = $this->meta->get_value( $post->ID, $request );
 719          }
 720  
 721          $context  = ! empty( $request['context'] ) ? $request['context'] : 'view';
 722          $data     = $this->add_additional_fields_to_object( $data, $request );
 723          $data     = $this->filter_response_by_context( $data, $context );
 724          $response = rest_ensure_response( $data );
 725  
 726          if ( ! empty( $data['parent'] ) ) {
 727              $response->add_link( 'parent', rest_url( rest_get_route_for_post( $data['parent'] ) ) );
 728          }
 729  
 730          /**
 731           * Filters a revision returned from the REST API.
 732           *
 733           * Allows modification of the revision right before it is returned.
 734           *
 735           * @since 4.7.0
 736           *
 737           * @param WP_REST_Response $response The response object.
 738           * @param WP_Post          $post     The original revision object.
 739           * @param WP_REST_Request  $request  Request used to generate the response.
 740           */
 741          $response = apply_filters( 'rest_prepare_revision', $response, $post, $request );
 742  
 743          $this->restore_post_data( $previous_post );
 744  
 745          return $response;
 746      }
 747  
 748      /**
 749       * Restores the global post to its previous value after preparing a revision.
 750       *
 751       * Preparing a revision overwrites the global post and post data via
 752       * setup_postdata(). This restores the global post that was in place
 753       * beforehand so the change does not leak into the rest of the request.
 754       *
 755       * Only the global post is guaranteed to be restored. When there was no
 756       * previous global post and the main query has no post either, which is the
 757       * usual state during a REST request, wp_reset_postdata() has nothing to
 758       * restore from, so the remaining globals set by setup_postdata() (such as
 759       * $id, $authordata and $pages) are left describing the revision. Clearing
 760       * those would mean unsetting each one by hand, which is beyond what is
 761       * needed to keep the global post from leaking.
 762       *
 763       * @since 7.1.0
 764       *
 765       * @param WP_Post|null $previous_post The global post to restore, or null if there was none.
 766       */
 767  	private function restore_post_data( ?WP_Post $previous_post ): void {
 768          if ( $previous_post ) {
 769              $GLOBALS['post'] = $previous_post;
 770              setup_postdata( $previous_post );
 771              return;
 772          }
 773  
 774          /*
 775           * There was no global post to restore, so clear the revision's post data.
 776           * This runs before clearing the global post because wp_reset_postdata()
 777           * repopulates it from the main query whenever that query has a post. Note
 778           * that it is a no-op when the main query has no post, in which case only
 779           * the global post below is cleared.
 780           */
 781          wp_reset_postdata();
 782  
 783          /*
 784           * Assigned rather than unset so that any `global $post` binding made before
 785           * this request keeps pointing at the global. Unsetting removes the entry from
 786           * the symbol table, which detaches those bindings, and a later write through
 787           * one of them would no longer be visible to get_post().
 788           */
 789          $GLOBALS['post'] = null;
 790      }
 791  
 792      /**
 793       * Checks the post_date_gmt or modified_gmt and prepare any post or
 794       * modified date for single post output.
 795       *
 796       * @since 4.7.0
 797       *
 798       * @param string      $date_gmt GMT publication time.
 799       * @param string|null $date     Optional. Local publication time. Default null.
 800       * @return string|null ISO8601/RFC3339 formatted datetime, otherwise null.
 801       */
 802  	protected function prepare_date_response( $date_gmt, $date = null ) {
 803          if ( '0000-00-00 00:00:00' === $date_gmt ) {
 804              return null;
 805          }
 806  
 807          if ( isset( $date ) ) {
 808              return mysql_to_rfc3339( $date );
 809          }
 810  
 811          return mysql_to_rfc3339( $date_gmt );
 812      }
 813  
 814      /**
 815       * Retrieves the revision's schema, conforming to JSON Schema.
 816       *
 817       * @since 4.7.0
 818       * @since 7.2.0 The `meta` property only describes the meta keys that are revisioned for the parent post type.
 819       *
 820       * @return array Item schema data.
 821       */
 822  	public function get_item_schema() {
 823          if ( $this->schema ) {
 824              return $this->add_additional_fields_schema( $this->schema );
 825          }
 826  
 827          $schema = array(
 828              '$schema'    => 'http://json-schema.org/draft-04/schema#',
 829              'title'      => "{$this->parent_post_type}-revision",
 830              'type'       => 'object',
 831              // Base properties for every Revision.
 832              'properties' => array(
 833                  'author'       => array(
 834                      'description' => __( 'The ID for the author of the revision.' ),
 835                      'type'        => 'integer',
 836                      'context'     => array( 'view', 'edit', 'embed' ),
 837                  ),
 838                  'date'         => array(
 839                      'description' => __( "The date the revision was published, in the site's timezone." ),
 840                      'type'        => 'string',
 841                      'format'      => 'date-time',
 842                      'context'     => array( 'view', 'edit', 'embed' ),
 843                  ),
 844                  'date_gmt'     => array(
 845                      'description' => __( 'The date the revision was published, as GMT.' ),
 846                      'type'        => 'string',
 847                      'format'      => 'date-time',
 848                      'context'     => array( 'view', 'edit' ),
 849                  ),
 850                  'guid'         => array(
 851                      'description' => __( 'GUID for the revision, as it exists in the database.' ),
 852                      'type'        => 'string',
 853                      'context'     => array( 'view', 'edit' ),
 854                  ),
 855                  'id'           => array(
 856                      'description' => __( 'Unique identifier for the revision.' ),
 857                      'type'        => 'integer',
 858                      'context'     => array( 'view', 'edit', 'embed' ),
 859                  ),
 860                  'modified'     => array(
 861                      'description' => __( "The date the revision was last modified, in the site's timezone." ),
 862                      'type'        => 'string',
 863                      'format'      => 'date-time',
 864                      'context'     => array( 'view', 'edit' ),
 865                  ),
 866                  'modified_gmt' => array(
 867                      'description' => __( 'The date the revision was last modified, as GMT.' ),
 868                      'type'        => 'string',
 869                      'format'      => 'date-time',
 870                      'context'     => array( 'view', 'edit' ),
 871                  ),
 872                  'parent'       => array(
 873                      'description' => __( 'The ID for the parent of the revision.' ),
 874                      'type'        => 'integer',
 875                      'context'     => array( 'view', 'edit', 'embed' ),
 876                  ),
 877                  'slug'         => array(
 878                      'description' => __( 'An alphanumeric identifier for the revision unique to its type.' ),
 879                      'type'        => 'string',
 880                      'context'     => array( 'view', 'edit', 'embed' ),
 881                  ),
 882              ),
 883          );
 884  
 885          $parent_schema = $this->parent_controller->get_item_schema();
 886  
 887          if ( ! empty( $parent_schema['properties']['title'] ) ) {
 888              $schema['properties']['title'] = $parent_schema['properties']['title'];
 889          }
 890  
 891          if ( ! empty( $parent_schema['properties']['content'] ) ) {
 892              $schema['properties']['content'] = $parent_schema['properties']['content'];
 893          }
 894  
 895          if ( ! empty( $parent_schema['properties']['excerpt'] ) ) {
 896              $schema['properties']['excerpt'] = $parent_schema['properties']['excerpt'];
 897          }
 898  
 899          if ( ! empty( $parent_schema['properties']['guid'] ) ) {
 900              $schema['properties']['guid'] = $parent_schema['properties']['guid'];
 901          }
 902  
 903          $schema['properties']['meta'] = $this->meta->get_field_schema();
 904  
 905          $this->schema = $schema;
 906  
 907          return $this->add_additional_fields_schema( $this->schema );
 908      }
 909  
 910      /**
 911       * Retrieves the query params for collections.
 912       *
 913       * @since 4.7.0
 914       *
 915       * @return array Collection parameters.
 916       */
 917  	public function get_collection_params() {
 918          $query_params = parent::get_collection_params();
 919  
 920          $query_params['context']['default'] = 'view';
 921  
 922          unset( $query_params['per_page']['default'] );
 923  
 924          $query_params['exclude'] = array(
 925              'description' => __( 'Ensure result set excludes specific IDs.' ),
 926              'type'        => 'array',
 927              'items'       => array(
 928                  'type' => 'integer',
 929              ),
 930              'default'     => array(),
 931          );
 932  
 933          $query_params['include'] = array(
 934              'description' => __( 'Limit result set to specific IDs.' ),
 935              'type'        => 'array',
 936              'items'       => array(
 937                  'type' => 'integer',
 938              ),
 939              'default'     => array(),
 940          );
 941  
 942          $query_params['offset'] = array(
 943              'description' => __( 'Offset the result set by a specific number of items.' ),
 944              'type'        => 'integer',
 945          );
 946  
 947          $query_params['order'] = array(
 948              'description' => __( 'Order sort attribute ascending or descending.' ),
 949              'type'        => 'string',
 950              'default'     => 'desc',
 951              'enum'        => array( 'asc', 'desc' ),
 952          );
 953  
 954          $query_params['orderby'] = array(
 955              'description' => __( 'Sort collection by object attribute.' ),
 956              'type'        => 'string',
 957              'default'     => 'date',
 958              'enum'        => array(
 959                  'date',
 960                  'id',
 961                  'include',
 962                  'relevance',
 963                  'slug',
 964                  'include_slugs',
 965                  'title',
 966              ),
 967          );
 968  
 969          return $query_params;
 970      }
 971  
 972      /**
 973       * Checks the post excerpt and prepare it for single post output.
 974       *
 975       * @since 4.7.0
 976       *
 977       * @param string  $excerpt The post excerpt.
 978       * @param WP_Post $post    Post revision object.
 979       * @return string Prepared excerpt or empty string.
 980       */
 981  	protected function prepare_excerpt_response( $excerpt, $post ) {
 982  
 983          /** This filter is documented in wp-includes/post-template.php */
 984          $excerpt = apply_filters( 'the_excerpt', $excerpt );
 985  
 986          if ( empty( $excerpt ) ) {
 987              return '';
 988          }
 989  
 990          return $excerpt;
 991      }
 992  }


Generated : Wed Nov 4 08:20:38 2026 Cross-referenced by PHPXref