[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

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

   1  <?php
   2  /**
   3   * REST API: WP_REST_Posts_Controller class
   4   *
   5   * @package WordPress
   6   * @subpackage REST_API
   7   * @since 4.7.0
   8   */
   9  
  10  /**
  11   * Core class to access posts via the REST API.
  12   *
  13   * @since 4.7.0
  14   *
  15   * @see WP_REST_Controller
  16   */
  17  class WP_REST_Posts_Controller extends WP_REST_Controller {
  18      /**
  19       * Post type.
  20       *
  21       * @since 4.7.0
  22       * @var string
  23       */
  24      protected $post_type;
  25  
  26      /**
  27       * Instance of a post meta fields object.
  28       *
  29       * @since 4.7.0
  30       * @var WP_REST_Post_Meta_Fields
  31       */
  32      protected $meta;
  33  
  34      /**
  35       * Passwordless post access permitted.
  36       *
  37       * @since 5.7.1
  38       * @var int[]
  39       */
  40      protected $password_check_passed = array();
  41  
  42      /**
  43       * Whether the controller supports batching.
  44       *
  45       * @since 5.9.0
  46       * @var array
  47       */
  48      protected $allow_batch = array( 'v1' => true );
  49  
  50      /**
  51       * Constructor.
  52       *
  53       * @since 4.7.0
  54       *
  55       * @param string $post_type Post type.
  56       */
  57  	public function __construct( $post_type ) {
  58          $this->post_type = $post_type;
  59          $obj             = get_post_type_object( $post_type );
  60          $this->rest_base = ! empty( $obj->rest_base ) ? $obj->rest_base : $obj->name;
  61          $this->namespace = ! empty( $obj->rest_namespace ) ? $obj->rest_namespace : 'wp/v2';
  62  
  63          $this->meta = new WP_REST_Post_Meta_Fields( $this->post_type );
  64      }
  65  
  66      /**
  67       * Registers the routes for posts.
  68       *
  69       * @since 4.7.0
  70       *
  71       * @see register_rest_route()
  72       */
  73  	public function register_routes() {
  74  
  75          register_rest_route(
  76              $this->namespace,
  77              '/' . $this->rest_base,
  78              array(
  79                  array(
  80                      'methods'             => WP_REST_Server::READABLE,
  81                      'callback'            => array( $this, 'get_items' ),
  82                      'permission_callback' => array( $this, 'get_items_permissions_check' ),
  83                      'args'                => $this->get_collection_params(),
  84                  ),
  85                  array(
  86                      'methods'             => WP_REST_Server::CREATABLE,
  87                      'callback'            => array( $this, 'create_item' ),
  88                      'permission_callback' => array( $this, 'create_item_permissions_check' ),
  89                      'args'                => $this->get_endpoint_args_for_item_schema( WP_REST_Server::CREATABLE ),
  90                  ),
  91                  'allow_batch' => $this->allow_batch,
  92                  'schema'      => array( $this, 'get_public_item_schema' ),
  93              )
  94          );
  95  
  96          $schema        = $this->get_item_schema();
  97          $get_item_args = array(
  98              'context' => $this->get_context_param( array( 'default' => 'view' ) ),
  99          );
 100          if ( isset( $schema['properties']['excerpt'] ) ) {
 101              $get_item_args['excerpt_length'] = array(
 102                  'description' => __( 'Override the default excerpt length.' ),
 103                  'type'        => 'integer',
 104              );
 105          }
 106          if ( isset( $schema['properties']['password'] ) ) {
 107              $get_item_args['password'] = array(
 108                  'description' => __( 'The password for the post if it is password protected.' ),
 109                  'type'        => 'string',
 110              );
 111          }
 112          register_rest_route(
 113              $this->namespace,
 114              '/' . $this->rest_base . '/(?P<id>[\d]+)',
 115              array(
 116                  'args'        => array(
 117                      'id' => array(
 118                          'description' => __( 'Unique identifier for the post.' ),
 119                          'type'        => 'integer',
 120                      ),
 121                  ),
 122                  array(
 123                      'methods'             => WP_REST_Server::READABLE,
 124                      'callback'            => array( $this, 'get_item' ),
 125                      'permission_callback' => array( $this, 'get_item_permissions_check' ),
 126                      'args'                => $get_item_args,
 127                  ),
 128                  array(
 129                      'methods'             => WP_REST_Server::EDITABLE,
 130                      'callback'            => array( $this, 'update_item' ),
 131                      'permission_callback' => array( $this, 'update_item_permissions_check' ),
 132                      'args'                => $this->get_endpoint_args_for_item_schema( WP_REST_Server::EDITABLE ),
 133                  ),
 134                  array(
 135                      'methods'             => WP_REST_Server::DELETABLE,
 136                      'callback'            => array( $this, 'delete_item' ),
 137                      'permission_callback' => array( $this, 'delete_item_permissions_check' ),
 138                      'args'                => array(
 139                          'force' => array(
 140                              'type'        => 'boolean',
 141                              'default'     => false,
 142                              'description' => __( 'Whether to bypass Trash and force deletion.' ),
 143                          ),
 144                      ),
 145                  ),
 146                  'allow_batch' => $this->allow_batch,
 147                  'schema'      => array( $this, 'get_public_item_schema' ),
 148              )
 149          );
 150      }
 151  
 152      /**
 153       * Checks if a given request has access to read posts.
 154       *
 155       * @since 4.7.0
 156       *
 157       * @param WP_REST_Request $request Full details about the request.
 158       * @return true|WP_Error True if the request has read access, WP_Error object otherwise.
 159       */
 160  	public function get_items_permissions_check( $request ) {
 161  
 162          $post_type = get_post_type_object( $this->post_type );
 163  
 164          if ( 'edit' === $request['context'] && ! current_user_can( $post_type->cap->edit_posts ) ) {
 165              return new WP_Error(
 166                  'rest_forbidden_context',
 167                  __( 'Sorry, you are not allowed to edit posts in this post type.' ),
 168                  array( 'status' => rest_authorization_required_code() )
 169              );
 170          }
 171  
 172          return true;
 173      }
 174  
 175      /**
 176       * Overrides the result of the post password check for REST requested posts.
 177       *
 178       * Allow users to read the content of password protected posts if they have
 179       * previously passed a permission check or if they have the `edit_post` capability
 180       * for the post being checked.
 181       *
 182       * @since 5.7.1
 183       *
 184       * @param bool    $required Whether the post requires a password check.
 185       * @param WP_Post $post     The post been password checked.
 186       * @return bool Result of password check taking in to account REST API considerations.
 187       */
 188  	public function check_password_required( $required, $post ) {
 189          if ( ! $required ) {
 190              return $required;
 191          }
 192  
 193          $post = get_post( $post );
 194  
 195          if ( ! $post ) {
 196              return $required;
 197          }
 198  
 199          if ( ! empty( $this->password_check_passed[ $post->ID ] ) ) {
 200              // Password previously checked and approved.
 201              return false;
 202          }
 203  
 204          return ! current_user_can( 'edit_post', $post->ID );
 205      }
 206  
 207      /**
 208       * Retrieves a collection of posts.
 209       *
 210       * @since 4.7.0
 211       *
 212       * @param WP_REST_Request $request Full details about the request.
 213       * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
 214       */
 215  	public function get_items( $request ) {
 216  
 217          // Ensure a search string is set in case the orderby is set to 'relevance'.
 218          if ( ! empty( $request['orderby'] ) && 'relevance' === $request['orderby'] && empty( $request['search'] ) ) {
 219              return new WP_Error(
 220                  'rest_no_search_term_defined',
 221                  __( 'You need to define a search term to order by relevance.' ),
 222                  array( 'status' => 400 )
 223              );
 224          }
 225  
 226          // Ensure an include parameter is set in case the orderby is set to 'include'.
 227          if ( ! empty( $request['orderby'] ) && 'include' === $request['orderby'] && empty( $request['include'] ) ) {
 228              return new WP_Error(
 229                  'rest_orderby_include_missing_include',
 230                  __( 'You need to define an include parameter to order by include.' ),
 231                  array( 'status' => 400 )
 232              );
 233          }
 234  
 235          // Retrieve the list of registered collection query parameters.
 236          $registered = $this->get_collection_params();
 237          $args       = array();
 238  
 239          /*
 240           * This array defines mappings between public API query parameters whose
 241           * values are accepted as-passed, and their internal WP_Query parameter
 242           * name equivalents (some are the same). Only values which are also
 243           * present in $registered will be set.
 244           */
 245          $parameter_mappings = array(
 246              'author'         => 'author__in',
 247              'author_exclude' => 'author__not_in',
 248              'exclude'        => 'post__not_in',
 249              'include'        => 'post__in',
 250              'menu_order'     => 'menu_order',
 251              'offset'         => 'offset',
 252              'order'          => 'order',
 253              'orderby'        => 'orderby',
 254              'page'           => 'paged',
 255              'parent'         => 'post_parent__in',
 256              'parent_exclude' => 'post_parent__not_in',
 257              'search'         => 's',
 258              'search_columns' => 'search_columns',
 259              'slug'           => 'post_name__in',
 260              'status'         => 'post_status',
 261          );
 262  
 263          /*
 264           * For each known parameter which is both registered and present in the request,
 265           * set the parameter's value on the query $args.
 266           */
 267          foreach ( $parameter_mappings as $api_param => $wp_param ) {
 268              if ( isset( $registered[ $api_param ], $request[ $api_param ] ) ) {
 269                  $args[ $wp_param ] = $request[ $api_param ];
 270              }
 271          }
 272  
 273          // Check for & assign any parameters which require special handling or setting.
 274          $args['date_query'] = array();
 275  
 276          if ( isset( $registered['before'], $request['before'] ) ) {
 277              $args['date_query'][] = array(
 278                  'before' => $request['before'],
 279                  'column' => 'post_date',
 280              );
 281          }
 282  
 283          if ( isset( $registered['modified_before'], $request['modified_before'] ) ) {
 284              $args['date_query'][] = array(
 285                  'before' => $request['modified_before'],
 286                  'column' => 'post_modified',
 287              );
 288          }
 289  
 290          if ( isset( $registered['after'], $request['after'] ) ) {
 291              $args['date_query'][] = array(
 292                  'after'  => $request['after'],
 293                  'column' => 'post_date',
 294              );
 295          }
 296  
 297          if ( isset( $registered['modified_after'], $request['modified_after'] ) ) {
 298              $args['date_query'][] = array(
 299                  'after'  => $request['modified_after'],
 300                  'column' => 'post_modified',
 301              );
 302          }
 303  
 304          // Ensure our per_page parameter overrides any provided posts_per_page filter.
 305          if ( isset( $registered['per_page'] ) ) {
 306              $args['posts_per_page'] = $request['per_page'];
 307          }
 308  
 309          if ( isset( $registered['sticky'], $request['sticky'] ) ) {
 310              $sticky_posts = get_option( 'sticky_posts', array() );
 311              if ( ! is_array( $sticky_posts ) ) {
 312                  $sticky_posts = array();
 313              }
 314              if ( $request['sticky'] ) {
 315                  /*
 316                   * As post__in will be used to only get sticky posts,
 317                   * we have to support the case where post__in was already
 318                   * specified.
 319                   */
 320                  $args['post__in'] = $args['post__in'] ? array_intersect( $sticky_posts, $args['post__in'] ) : $sticky_posts;
 321  
 322                  /*
 323                   * If we intersected, but there are no post IDs in common,
 324                   * WP_Query won't return "no posts" for post__in = array()
 325                   * so we have to fake it a bit.
 326                   */
 327                  if ( ! $args['post__in'] ) {
 328                      $args['post__in'] = array( 0 );
 329                  }
 330              } elseif ( $sticky_posts ) {
 331                  /*
 332                   * As post___not_in will be used to only get posts that
 333                   * are not sticky, we have to support the case where post__not_in
 334                   * was already specified.
 335                   */
 336                  $args['post__not_in'] = array_merge( $args['post__not_in'], $sticky_posts );
 337              }
 338          }
 339  
 340          $args = $this->prepare_tax_query( $args, $request );
 341  
 342          // Force the post_type argument, since it's not a user input variable.
 343          $args['post_type'] = $this->post_type;
 344  
 345          /**
 346           * Filters WP_Query arguments when querying posts via the REST API.
 347           *
 348           * The dynamic portion of the hook name, `$this->post_type`, refers to the post type slug.
 349           *
 350           * Possible hook names include:
 351           *
 352           *  - `rest_post_query`
 353           *  - `rest_page_query`
 354           *  - `rest_attachment_query`
 355           *
 356           * Enables adding extra arguments or setting defaults for a post collection request.
 357           *
 358           * @since 4.7.0
 359           * @since 5.7.0 Moved after the `tax_query` query arg is generated.
 360           *
 361           * @link https://developer.wordpress.org/reference/classes/wp_query/
 362           *
 363           * @param array           $args    Array of arguments for WP_Query.
 364           * @param WP_REST_Request $request The REST API request.
 365           */
 366          $args       = apply_filters( "rest_{$this->post_type}_query", $args, $request );
 367          $query_args = $this->prepare_items_query( $args, $request );
 368  
 369          $posts_query  = new WP_Query();
 370          $query_result = $posts_query->query( $query_args );
 371  
 372          // Allow access to all password protected posts if the context is edit.
 373          if ( 'edit' === $request['context'] ) {
 374              add_filter( 'post_password_required', array( $this, 'check_password_required' ), 10, 2 );
 375          }
 376  
 377          $posts = array();
 378  
 379          update_post_author_caches( $query_result );
 380          update_post_parent_caches( $query_result );
 381  
 382          if ( post_type_supports( $this->post_type, 'thumbnail' ) ) {
 383              update_post_thumbnail_cache( $posts_query );
 384          }
 385  
 386          foreach ( $query_result as $post ) {
 387              if ( ! $this->check_read_permission( $post ) ) {
 388                  continue;
 389              }
 390  
 391              $data    = $this->prepare_item_for_response( $post, $request );
 392              $posts[] = $this->prepare_response_for_collection( $data );
 393          }
 394  
 395          // Reset filter.
 396          if ( 'edit' === $request['context'] ) {
 397              remove_filter( 'post_password_required', array( $this, 'check_password_required' ) );
 398          }
 399  
 400          $page        = (int) $query_args['paged'];
 401          $total_posts = $posts_query->found_posts;
 402  
 403          if ( $total_posts < 1 && $page > 1 ) {
 404              // Out-of-bounds, run the query again without LIMIT for total count.
 405              unset( $query_args['paged'] );
 406  
 407              $count_query = new WP_Query();
 408              $count_query->query( $query_args );
 409              $total_posts = $count_query->found_posts;
 410          }
 411  
 412          $max_pages = (int) ceil( $total_posts / (int) $posts_query->query_vars['posts_per_page'] );
 413  
 414          if ( $page > $max_pages && $total_posts > 0 ) {
 415              return new WP_Error(
 416                  'rest_post_invalid_page_number',
 417                  __( 'The page number requested is larger than the number of pages available.' ),
 418                  array( 'status' => 400 )
 419              );
 420          }
 421  
 422          $response = rest_ensure_response( $posts );
 423  
 424          $response->header( 'X-WP-Total', (int) $total_posts );
 425          $response->header( 'X-WP-TotalPages', (int) $max_pages );
 426  
 427          $request_params = $request->get_query_params();
 428          $collection_url = rest_url( rest_get_route_for_post_type_items( $this->post_type ) );
 429          $base           = add_query_arg( urlencode_deep( $request_params ), $collection_url );
 430  
 431          if ( $page > 1 ) {
 432              $prev_page = $page - 1;
 433  
 434              if ( $prev_page > $max_pages ) {
 435                  $prev_page = $max_pages;
 436              }
 437  
 438              $prev_link = add_query_arg( 'page', $prev_page, $base );
 439              $response->link_header( 'prev', $prev_link );
 440          }
 441          if ( $max_pages > $page ) {
 442              $next_page = $page + 1;
 443              $next_link = add_query_arg( 'page', $next_page, $base );
 444  
 445              $response->link_header( 'next', $next_link );
 446          }
 447  
 448          return $response;
 449      }
 450  
 451      /**
 452       * Gets the post, if the ID is valid.
 453       *
 454       * @since 4.7.2
 455       *
 456       * @param int $id Supplied ID.
 457       * @return WP_Post|WP_Error Post object if ID is valid, WP_Error otherwise.
 458       */
 459  	protected function get_post( $id ) {
 460          $error = new WP_Error(
 461              'rest_post_invalid_id',
 462              __( 'Invalid post ID.' ),
 463              array( 'status' => 404 )
 464          );
 465  
 466          if ( (int) $id <= 0 ) {
 467              return $error;
 468          }
 469  
 470          $post = get_post( (int) $id );
 471          if ( empty( $post ) || empty( $post->ID ) || $this->post_type !== $post->post_type ) {
 472              return $error;
 473          }
 474  
 475          return $post;
 476      }
 477  
 478      /**
 479       * Checks if a given request has access to read a post.
 480       *
 481       * @since 4.7.0
 482       *
 483       * @param WP_REST_Request $request Full details about the request.
 484       * @return bool|WP_Error True if the request has read access for the item, WP_Error object or false otherwise.
 485       */
 486  	public function get_item_permissions_check( $request ) {
 487          $post = $this->get_post( $request['id'] );
 488          if ( is_wp_error( $post ) ) {
 489              return $post;
 490          }
 491  
 492          if ( 'edit' === $request['context'] && $post && ! $this->check_update_permission( $post ) ) {
 493              return new WP_Error(
 494                  'rest_forbidden_context',
 495                  __( 'Sorry, you are not allowed to edit this post.' ),
 496                  array( 'status' => rest_authorization_required_code() )
 497              );
 498          }
 499  
 500          if ( $post && ! empty( $request['password'] ) ) {
 501              // Check post password, and return error if invalid.
 502              if ( ! hash_equals( $post->post_password, $request['password'] ) ) {
 503                  return new WP_Error(
 504                      'rest_post_incorrect_password',
 505                      __( 'Incorrect post password.' ),
 506                      array( 'status' => 403 )
 507                  );
 508              }
 509          }
 510  
 511          // Allow access to all password protected posts if the context is edit.
 512          if ( 'edit' === $request['context'] ) {
 513              add_filter( 'post_password_required', array( $this, 'check_password_required' ), 10, 2 );
 514          }
 515  
 516          if ( $post ) {
 517              return $this->check_read_permission( $post );
 518          }
 519  
 520          return true;
 521      }
 522  
 523      /**
 524       * Checks if the user can access password-protected content.
 525       *
 526       * This method determines whether we need to override the regular password
 527       * check in core with a filter.
 528       *
 529       * @since 4.7.0
 530       *
 531       * @param WP_Post         $post    Post to check against.
 532       * @param WP_REST_Request $request Request data to check.
 533       * @return bool True if the user can access password-protected content, otherwise false.
 534       */
 535  	public function can_access_password_content( $post, $request ) {
 536          if ( empty( $post->post_password ) ) {
 537              // No filter required.
 538              return false;
 539          }
 540  
 541          /*
 542           * Users always gets access to password protected content in the edit
 543           * context if they have the `edit_post` meta capability.
 544           */
 545          if (
 546              'edit' === $request['context'] &&
 547              current_user_can( 'edit_post', $post->ID )
 548          ) {
 549              return true;
 550          }
 551  
 552          // No password, no auth.
 553          if ( empty( $request['password'] ) ) {
 554              return false;
 555          }
 556  
 557          // Double-check the request password.
 558          return hash_equals( $post->post_password, $request['password'] );
 559      }
 560  
 561      /**
 562       * Retrieves a single post.
 563       *
 564       * @since 4.7.0
 565       *
 566       * @param WP_REST_Request $request Full details about the request.
 567       * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
 568       */
 569  	public function get_item( $request ) {
 570          $post = $this->get_post( $request['id'] );
 571          if ( is_wp_error( $post ) ) {
 572              return $post;
 573          }
 574  
 575          $data     = $this->prepare_item_for_response( $post, $request );
 576          $response = rest_ensure_response( $data );
 577  
 578          if ( is_post_type_viewable( get_post_type_object( $post->post_type ) ) ) {
 579              $response->link_header( 'alternate', get_permalink( $post->ID ), array( 'type' => 'text/html' ) );
 580          }
 581  
 582          return $response;
 583      }
 584  
 585      /**
 586       * Checks if a given request has access to create a post.
 587       *
 588       * @since 4.7.0
 589       *
 590       * @param WP_REST_Request $request Full details about the request.
 591       * @return true|WP_Error True if the request has access to create items, WP_Error object otherwise.
 592       */
 593  	public function create_item_permissions_check( $request ) {
 594          if ( ! empty( $request['id'] ) ) {
 595              return new WP_Error(
 596                  'rest_post_exists',
 597                  __( 'Cannot create existing post.' ),
 598                  array( 'status' => 400 )
 599              );
 600          }
 601  
 602          $post_type = get_post_type_object( $this->post_type );
 603  
 604          if ( ! empty( $request['author'] ) && get_current_user_id() !== $request['author'] && ! current_user_can( $post_type->cap->edit_others_posts ) ) {
 605              return new WP_Error(
 606                  'rest_cannot_edit_others',
 607                  __( 'Sorry, you are not allowed to create posts as this user.' ),
 608                  array( 'status' => rest_authorization_required_code() )
 609              );
 610          }
 611  
 612          if ( ! empty( $request['sticky'] ) && ! current_user_can( $post_type->cap->edit_others_posts ) && ! current_user_can( $post_type->cap->publish_posts ) ) {
 613              return new WP_Error(
 614                  'rest_cannot_assign_sticky',
 615                  __( 'Sorry, you are not allowed to make posts sticky.' ),
 616                  array( 'status' => rest_authorization_required_code() )
 617              );
 618          }
 619  
 620          if ( ! current_user_can( $post_type->cap->create_posts ) ) {
 621              return new WP_Error(
 622                  'rest_cannot_create',
 623                  __( 'Sorry, you are not allowed to create posts as this user.' ),
 624                  array( 'status' => rest_authorization_required_code() )
 625              );
 626          }
 627  
 628          if ( ! $this->check_assign_terms_permission( $request ) ) {
 629              return new WP_Error(
 630                  'rest_cannot_assign_term',
 631                  __( 'Sorry, you are not allowed to assign the provided terms.' ),
 632                  array( 'status' => rest_authorization_required_code() )
 633              );
 634          }
 635  
 636          return true;
 637      }
 638  
 639      /**
 640       * Creates a single post.
 641       *
 642       * @since 4.7.0
 643       *
 644       * @param WP_REST_Request $request Full details about the request.
 645       * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
 646       */
 647  	public function create_item( $request ) {
 648          if ( ! empty( $request['id'] ) ) {
 649              return new WP_Error(
 650                  'rest_post_exists',
 651                  __( 'Cannot create existing post.' ),
 652                  array( 'status' => 400 )
 653              );
 654          }
 655  
 656          $prepared_post = $this->prepare_item_for_database( $request );
 657  
 658          if ( is_wp_error( $prepared_post ) ) {
 659              return $prepared_post;
 660          }
 661  
 662          $prepared_post->post_type = $this->post_type;
 663  
 664          if ( ! empty( $prepared_post->post_name )
 665              && ! empty( $prepared_post->post_status )
 666              && in_array( $prepared_post->post_status, array( 'draft', 'pending' ), true )
 667          ) {
 668              /*
 669               * `wp_unique_post_slug()` returns the same slug for 'draft' or 'pending' posts.
 670               *
 671               * To ensure that a unique slug is generated, pass the post data with the 'publish' status.
 672               */
 673              $prepared_post->post_name = wp_unique_post_slug(
 674                  $prepared_post->post_name,
 675                  $prepared_post->id,
 676                  'publish',
 677                  $prepared_post->post_type,
 678                  $prepared_post->post_parent
 679              );
 680          }
 681  
 682          $post_id = wp_insert_post( wp_slash( (array) $prepared_post ), true, false );
 683  
 684          if ( is_wp_error( $post_id ) ) {
 685  
 686              if ( 'db_insert_error' === $post_id->get_error_code() ) {
 687                  $post_id->add_data( array( 'status' => 500 ) );
 688              } else {
 689                  $post_id->add_data( array( 'status' => 400 ) );
 690              }
 691  
 692              return $post_id;
 693          }
 694  
 695          $post = get_post( $post_id );
 696  
 697          /**
 698           * Fires after a single post is created or updated via the REST API.
 699           *
 700           * The dynamic portion of the hook name, `$this->post_type`, refers to the post type slug.
 701           *
 702           * Possible hook names include:
 703           *
 704           *  - `rest_insert_post`
 705           *  - `rest_insert_page`
 706           *  - `rest_insert_attachment`
 707           *
 708           * @since 4.7.0
 709           *
 710           * @param WP_Post         $post     Inserted or updated post object.
 711           * @param WP_REST_Request $request  Request object.
 712           * @param bool            $creating True when creating a post, false when updating.
 713           */
 714          do_action( "rest_insert_{$this->post_type}", $post, $request, true );
 715  
 716          $schema = $this->get_item_schema();
 717  
 718          if ( ! empty( $schema['properties']['sticky'] ) ) {
 719              if ( ! empty( $request['sticky'] ) ) {
 720                  stick_post( $post_id );
 721              } else {
 722                  unstick_post( $post_id );
 723              }
 724          }
 725  
 726          if ( ! empty( $schema['properties']['featured_media'] ) && isset( $request['featured_media'] ) ) {
 727              $this->handle_featured_media( $request['featured_media'], $post_id );
 728          }
 729  
 730          if ( ! empty( $schema['properties']['format'] ) && ! empty( $request['format'] ) ) {
 731              set_post_format( $post, $request['format'] );
 732          }
 733  
 734          if ( ! empty( $schema['properties']['template'] ) && isset( $request['template'] ) ) {
 735              $this->handle_template( $request['template'], $post_id, true );
 736          }
 737  
 738          $terms_update = $this->handle_terms( $post_id, $request );
 739  
 740          if ( is_wp_error( $terms_update ) ) {
 741              return $terms_update;
 742          }
 743  
 744          if ( ! empty( $schema['properties']['meta'] ) && isset( $request['meta'] ) ) {
 745              $meta_update = $this->meta->update_value( $request['meta'], $post_id );
 746  
 747              if ( is_wp_error( $meta_update ) ) {
 748                  return $meta_update;
 749              }
 750          }
 751  
 752          $post          = get_post( $post_id );
 753          $fields_update = $this->update_additional_fields_for_object( $post, $request );
 754  
 755          if ( is_wp_error( $fields_update ) ) {
 756              return $fields_update;
 757          }
 758  
 759          $request->set_param( 'context', 'edit' );
 760  
 761          /**
 762           * Fires after a single post is completely created or updated via the REST API.
 763           *
 764           * The dynamic portion of the hook name, `$this->post_type`, refers to the post type slug.
 765           *
 766           * Possible hook names include:
 767           *
 768           *  - `rest_after_insert_post`
 769           *  - `rest_after_insert_page`
 770           *  - `rest_after_insert_attachment`
 771           *
 772           * @since 5.0.0
 773           *
 774           * @param WP_Post         $post     Inserted or updated post object.
 775           * @param WP_REST_Request $request  Request object.
 776           * @param bool            $creating True when creating a post, false when updating.
 777           */
 778          do_action( "rest_after_insert_{$this->post_type}", $post, $request, true );
 779  
 780          wp_after_insert_post( $post, false, null );
 781  
 782          $response = $this->prepare_item_for_response( $post, $request );
 783          $response = rest_ensure_response( $response );
 784  
 785          $response->set_status( 201 );
 786          $response->header( 'Location', rest_url( rest_get_route_for_post( $post ) ) );
 787  
 788          return $response;
 789      }
 790  
 791      /**
 792       * Checks if a given request has access to update a post.
 793       *
 794       * @since 4.7.0
 795       *
 796       * @param WP_REST_Request $request Full details about the request.
 797       * @return true|WP_Error True if the request has access to update the item, WP_Error object otherwise.
 798       */
 799  	public function update_item_permissions_check( $request ) {
 800          $post = $this->get_post( $request['id'] );
 801          if ( is_wp_error( $post ) ) {
 802              return $post;
 803          }
 804  
 805          $post_type = get_post_type_object( $this->post_type );
 806  
 807          if ( $post && ! $this->check_update_permission( $post ) ) {
 808              return new WP_Error(
 809                  'rest_cannot_edit',
 810                  __( 'Sorry, you are not allowed to edit this post.' ),
 811                  array( 'status' => rest_authorization_required_code() )
 812              );
 813          }
 814  
 815          if ( ! empty( $request['author'] ) && get_current_user_id() !== $request['author'] && ! current_user_can( $post_type->cap->edit_others_posts ) ) {
 816              return new WP_Error(
 817                  'rest_cannot_edit_others',
 818                  __( 'Sorry, you are not allowed to update posts as this user.' ),
 819                  array( 'status' => rest_authorization_required_code() )
 820              );
 821          }
 822  
 823          if ( ! empty( $request['sticky'] ) && ! current_user_can( $post_type->cap->edit_others_posts ) && ! current_user_can( $post_type->cap->publish_posts ) ) {
 824              return new WP_Error(
 825                  'rest_cannot_assign_sticky',
 826                  __( 'Sorry, you are not allowed to make posts sticky.' ),
 827                  array( 'status' => rest_authorization_required_code() )
 828              );
 829          }
 830  
 831          if ( ! $this->check_assign_terms_permission( $request ) ) {
 832              return new WP_Error(
 833                  'rest_cannot_assign_term',
 834                  __( 'Sorry, you are not allowed to assign the provided terms.' ),
 835                  array( 'status' => rest_authorization_required_code() )
 836              );
 837          }
 838  
 839          return true;
 840      }
 841  
 842      /**
 843       * Updates a single post.
 844       *
 845       * @since 4.7.0
 846       *
 847       * @param WP_REST_Request $request Full details about the request.
 848       * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
 849       */
 850  	public function update_item( $request ) {
 851          $valid_check = $this->get_post( $request['id'] );
 852          if ( is_wp_error( $valid_check ) ) {
 853              return $valid_check;
 854          }
 855  
 856          $post_before = get_post( $request['id'] );
 857          $post        = $this->prepare_item_for_database( $request );
 858  
 859          if ( is_wp_error( $post ) ) {
 860              return $post;
 861          }
 862  
 863          if ( ! empty( $post->post_status ) ) {
 864              $post_status = $post->post_status;
 865          } else {
 866              $post_status = $post_before->post_status;
 867          }
 868  
 869          /*
 870           * `wp_unique_post_slug()` returns the same slug for 'draft' or 'pending' posts.
 871           *
 872           * To ensure that a unique slug is generated, pass the post data with the 'publish' status.
 873           */
 874          if ( ! empty( $post->post_name ) && in_array( $post_status, array( 'draft', 'pending' ), true ) ) {
 875              $post_parent     = ! empty( $post->post_parent ) ? $post->post_parent : 0;
 876              $post->post_name = wp_unique_post_slug(
 877                  $post->post_name,
 878                  $post->ID,
 879                  'publish',
 880                  $post->post_type,
 881                  $post_parent
 882              );
 883          }
 884  
 885          // Convert the post object to an array, otherwise wp_update_post() will expect non-escaped input.
 886          $post_id = wp_update_post( wp_slash( (array) $post ), true, false );
 887  
 888          if ( is_wp_error( $post_id ) ) {
 889              if ( 'db_update_error' === $post_id->get_error_code() ) {
 890                  $post_id->add_data( array( 'status' => 500 ) );
 891              } else {
 892                  $post_id->add_data( array( 'status' => 400 ) );
 893              }
 894              return $post_id;
 895          }
 896  
 897          $post = get_post( $post_id );
 898  
 899          /** This action is documented in wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php */
 900          do_action( "rest_insert_{$this->post_type}", $post, $request, false );
 901  
 902          $schema = $this->get_item_schema();
 903  
 904          if ( ! empty( $schema['properties']['format'] ) && ! empty( $request['format'] ) ) {
 905              set_post_format( $post, $request['format'] );
 906          }
 907  
 908          if ( ! empty( $schema['properties']['featured_media'] ) && isset( $request['featured_media'] ) ) {
 909              $this->handle_featured_media( $request['featured_media'], $post_id );
 910          }
 911  
 912          if ( ! empty( $schema['properties']['sticky'] ) && isset( $request['sticky'] ) ) {
 913              if ( ! empty( $request['sticky'] ) ) {
 914                  stick_post( $post_id );
 915              } else {
 916                  unstick_post( $post_id );
 917              }
 918          }
 919  
 920          if ( ! empty( $schema['properties']['template'] ) && isset( $request['template'] ) ) {
 921              $this->handle_template( $request['template'], $post->ID );
 922          }
 923  
 924          $terms_update = $this->handle_terms( $post->ID, $request );
 925  
 926          if ( is_wp_error( $terms_update ) ) {
 927              return $terms_update;
 928          }
 929  
 930          if ( ! empty( $schema['properties']['meta'] ) && isset( $request['meta'] ) ) {
 931              $meta_update = $this->meta->update_value( $request['meta'], $post->ID );
 932  
 933              if ( is_wp_error( $meta_update ) ) {
 934                  return $meta_update;
 935              }
 936          }
 937  
 938          $post          = get_post( $post_id );
 939          $fields_update = $this->update_additional_fields_for_object( $post, $request );
 940  
 941          if ( is_wp_error( $fields_update ) ) {
 942              return $fields_update;
 943          }
 944  
 945          $request->set_param( 'context', 'edit' );
 946  
 947          // Filter is fired in WP_REST_Attachments_Controller subclass.
 948          if ( 'attachment' === $this->post_type ) {
 949              $response = $this->prepare_item_for_response( $post, $request );
 950              return rest_ensure_response( $response );
 951          }
 952  
 953          /** This action is documented in wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php */
 954          do_action( "rest_after_insert_{$this->post_type}", $post, $request, false );
 955  
 956          wp_after_insert_post( $post, true, $post_before );
 957  
 958          $response = $this->prepare_item_for_response( $post, $request );
 959  
 960          return rest_ensure_response( $response );
 961      }
 962  
 963      /**
 964       * Checks if a given request has access to delete a post.
 965       *
 966       * @since 4.7.0
 967       *
 968       * @param WP_REST_Request $request Full details about the request.
 969       * @return true|WP_Error True if the request has access to delete the item, WP_Error object otherwise.
 970       */
 971  	public function delete_item_permissions_check( $request ) {
 972          $post = $this->get_post( $request['id'] );
 973          if ( is_wp_error( $post ) ) {
 974              return $post;
 975          }
 976  
 977          if ( $post && ! $this->check_delete_permission( $post ) ) {
 978              return new WP_Error(
 979                  'rest_cannot_delete',
 980                  __( 'Sorry, you are not allowed to delete this post.' ),
 981                  array( 'status' => rest_authorization_required_code() )
 982              );
 983          }
 984  
 985          return true;
 986      }
 987  
 988      /**
 989       * Deletes a single post.
 990       *
 991       * @since 4.7.0
 992       *
 993       * @param WP_REST_Request $request Full details about the request.
 994       * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
 995       */
 996  	public function delete_item( $request ) {
 997          $post = $this->get_post( $request['id'] );
 998          if ( is_wp_error( $post ) ) {
 999              return $post;
1000          }
1001  
1002          $id    = $post->ID;
1003          $force = (bool) $request['force'];
1004  
1005          $supports_trash = ( EMPTY_TRASH_DAYS > 0 );
1006  
1007          if ( 'attachment' === $post->post_type ) {
1008              $supports_trash = $supports_trash && MEDIA_TRASH;
1009          }
1010  
1011          /**
1012           * Filters whether a post is trashable.
1013           *
1014           * The dynamic portion of the hook name, `$this->post_type`, refers to the post type slug.
1015           *
1016           * Possible hook names include:
1017           *
1018           *  - `rest_post_trashable`
1019           *  - `rest_page_trashable`
1020           *  - `rest_attachment_trashable`
1021           *
1022           * Pass false to disable Trash support for the post.
1023           *
1024           * @since 4.7.0
1025           *
1026           * @param bool    $supports_trash Whether the post type support trashing.
1027           * @param WP_Post $post           The Post object being considered for trashing support.
1028           */
1029          $supports_trash = apply_filters( "rest_{$this->post_type}_trashable", $supports_trash, $post );
1030  
1031          if ( ! $this->check_delete_permission( $post ) ) {
1032              return new WP_Error(
1033                  'rest_user_cannot_delete_post',
1034                  __( 'Sorry, you are not allowed to delete this post.' ),
1035                  array( 'status' => rest_authorization_required_code() )
1036              );
1037          }
1038  
1039          $request->set_param( 'context', 'edit' );
1040  
1041          // If we're forcing, then delete permanently.
1042          if ( $force ) {
1043              $previous = $this->prepare_item_for_response( $post, $request );
1044              $result   = wp_delete_post( $id, true );
1045              $response = new WP_REST_Response();
1046              $response->set_data(
1047                  array(
1048                      'deleted'  => true,
1049                      'previous' => $previous->get_data(),
1050                  )
1051              );
1052          } else {
1053              // If we don't support trashing for this type, error out.
1054              if ( ! $supports_trash ) {
1055                  return new WP_Error(
1056                      'rest_trash_not_supported',
1057                      /* translators: %s: force=true */
1058                      sprintf( __( "The post does not support trashing. Set '%s' to delete." ), 'force=true' ),
1059                      array( 'status' => 501 )
1060                  );
1061              }
1062  
1063              // Otherwise, only trash if we haven't already.
1064              if ( 'trash' === $post->post_status ) {
1065                  return new WP_Error(
1066                      'rest_already_trashed',
1067                      __( 'The post has already been deleted.' ),
1068                      array( 'status' => 410 )
1069                  );
1070              }
1071  
1072              /*
1073               * (Note that internally this falls through to `wp_delete_post()`
1074               * if the Trash is disabled.)
1075               */
1076              $result   = wp_trash_post( $id );
1077              $post     = get_post( $id );
1078              $response = $this->prepare_item_for_response( $post, $request );
1079          }
1080  
1081          if ( ! $result ) {
1082              return new WP_Error(
1083                  'rest_cannot_delete',
1084                  __( 'The post cannot be deleted.' ),
1085                  array( 'status' => 500 )
1086              );
1087          }
1088  
1089          /**
1090           * Fires immediately after a single post is deleted or trashed via the REST API.
1091           *
1092           * They dynamic portion of the hook name, `$this->post_type`, refers to the post type slug.
1093           *
1094           * Possible hook names include:
1095           *
1096           *  - `rest_delete_post`
1097           *  - `rest_delete_page`
1098           *  - `rest_delete_attachment`
1099           *
1100           * @since 4.7.0
1101           *
1102           * @param WP_Post          $post     The deleted or trashed post.
1103           * @param WP_REST_Response $response The response data.
1104           * @param WP_REST_Request  $request  The request sent to the API.
1105           */
1106          do_action( "rest_delete_{$this->post_type}", $post, $response, $request );
1107  
1108          return $response;
1109      }
1110  
1111      /**
1112       * Determines the allowed query_vars for a get_items() response and prepares
1113       * them for WP_Query.
1114       *
1115       * @since 4.7.0
1116       *
1117       * @param array           $prepared_args Optional. Prepared WP_Query arguments. Default empty array.
1118       * @param WP_REST_Request $request       Optional. Full details about the request.
1119       * @return array Items query arguments.
1120       */
1121  	protected function prepare_items_query( $prepared_args = array(), $request = null ) {
1122          $query_args = array();
1123  
1124          foreach ( $prepared_args as $key => $value ) {
1125              /**
1126               * Filters the query_vars used in get_items() for the constructed query.
1127               *
1128               * The dynamic portion of the hook name, `$key`, refers to the query_var key.
1129               *
1130               * @since 4.7.0
1131               *
1132               * @param string $value The query_var value.
1133               */
1134              $query_args[ $key ] = apply_filters( "rest_query_var-{$key}", $value ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
1135          }
1136  
1137          if ( 'post' !== $this->post_type || ! isset( $query_args['ignore_sticky_posts'] ) ) {
1138              $query_args['ignore_sticky_posts'] = true;
1139          }
1140  
1141          // Map to proper WP_Query orderby param.
1142          if ( isset( $query_args['orderby'] ) && isset( $request['orderby'] ) ) {
1143              $orderby_mappings = array(
1144                  'id'            => 'ID',
1145                  'include'       => 'post__in',
1146                  'slug'          => 'post_name',
1147                  'include_slugs' => 'post_name__in',
1148              );
1149  
1150              if ( isset( $orderby_mappings[ $request['orderby'] ] ) ) {
1151                  $query_args['orderby'] = $orderby_mappings[ $request['orderby'] ];
1152              }
1153          }
1154  
1155          return $query_args;
1156      }
1157  
1158      /**
1159       * Checks the post_date_gmt or modified_gmt and prepare any post or
1160       * modified date for single post output.
1161       *
1162       * @since 4.7.0
1163       *
1164       * @param string      $date_gmt GMT publication time.
1165       * @param string|null $date     Optional. Local publication time. Default null.
1166       * @return string|null ISO8601/RFC3339 formatted datetime.
1167       */
1168  	protected function prepare_date_response( $date_gmt, $date = null ) {
1169          // Use the date if passed.
1170          if ( isset( $date ) ) {
1171              return mysql_to_rfc3339( $date );
1172          }
1173  
1174          // Return null if $date_gmt is empty/zeros.
1175          if ( '0000-00-00 00:00:00' === $date_gmt ) {
1176              return null;
1177          }
1178  
1179          // Return the formatted datetime.
1180          return mysql_to_rfc3339( $date_gmt );
1181      }
1182  
1183      /**
1184       * Prepares a single post for create or update.
1185       *
1186       * @since 4.7.0
1187       *
1188       * @param WP_REST_Request $request Request object.
1189       * @return stdClass|WP_Error Post object or WP_Error.
1190       */
1191  	protected function prepare_item_for_database( $request ) {
1192          $prepared_post  = new stdClass();
1193          $current_status = '';
1194  
1195          // Post ID.
1196          if ( isset( $request['id'] ) ) {
1197              $existing_post = $this->get_post( $request['id'] );
1198              if ( is_wp_error( $existing_post ) ) {
1199                  return $existing_post;
1200              }
1201  
1202              $prepared_post->ID = $existing_post->ID;
1203              $current_status    = $existing_post->post_status;
1204          }
1205  
1206          $schema = $this->get_item_schema();
1207  
1208          // Post title.
1209          if ( ! empty( $schema['properties']['title'] ) && isset( $request['title'] ) ) {
1210              if ( is_string( $request['title'] ) ) {
1211                  $prepared_post->post_title = $request['title'];
1212              } elseif ( ! empty( $request['title']['raw'] ) ) {
1213                  $prepared_post->post_title = $request['title']['raw'];
1214              }
1215          }
1216  
1217          // Post content.
1218          if ( ! empty( $schema['properties']['content'] ) && isset( $request['content'] ) ) {
1219              if ( is_string( $request['content'] ) ) {
1220                  $prepared_post->post_content = $request['content'];
1221              } elseif ( isset( $request['content']['raw'] ) ) {
1222                  $prepared_post->post_content = $request['content']['raw'];
1223              }
1224          }
1225  
1226          // Post excerpt.
1227          if ( ! empty( $schema['properties']['excerpt'] ) && isset( $request['excerpt'] ) ) {
1228              if ( is_string( $request['excerpt'] ) ) {
1229                  $prepared_post->post_excerpt = $request['excerpt'];
1230              } elseif ( isset( $request['excerpt']['raw'] ) ) {
1231                  $prepared_post->post_excerpt = $request['excerpt']['raw'];
1232              }
1233          }
1234  
1235          // Post type.
1236          if ( empty( $request['id'] ) ) {
1237              // Creating new post, use default type for the controller.
1238              $prepared_post->post_type = $this->post_type;
1239          } else {
1240              // Updating a post, use previous type.
1241              $prepared_post->post_type = get_post_type( $request['id'] );
1242          }
1243  
1244          $post_type = get_post_type_object( $prepared_post->post_type );
1245  
1246          // Post status.
1247          if (
1248              ! empty( $schema['properties']['status'] ) &&
1249              isset( $request['status'] ) &&
1250              ( ! $current_status || $current_status !== $request['status'] )
1251          ) {
1252              $status = $this->handle_status_param( $request['status'], $post_type );
1253  
1254              if ( is_wp_error( $status ) ) {
1255                  return $status;
1256              }
1257  
1258              $prepared_post->post_status = $status;
1259          }
1260  
1261          // Post date.
1262          if ( ! empty( $schema['properties']['date'] ) && ! empty( $request['date'] ) ) {
1263              $current_date = isset( $prepared_post->ID ) ? get_post( $prepared_post->ID )->post_date : false;
1264              $date_data    = rest_get_date_with_gmt( $request['date'] );
1265  
1266              if ( ! empty( $date_data ) && $current_date !== $date_data[0] ) {
1267                  list( $prepared_post->post_date, $prepared_post->post_date_gmt ) = $date_data;
1268                  $prepared_post->edit_date                                        = true;
1269              }
1270          } elseif ( ! empty( $schema['properties']['date_gmt'] ) && ! empty( $request['date_gmt'] ) ) {
1271              $current_date = isset( $prepared_post->ID ) ? get_post( $prepared_post->ID )->post_date_gmt : false;
1272              $date_data    = rest_get_date_with_gmt( $request['date_gmt'], true );
1273  
1274              if ( ! empty( $date_data ) && $current_date !== $date_data[1] ) {
1275                  list( $prepared_post->post_date, $prepared_post->post_date_gmt ) = $date_data;
1276                  $prepared_post->edit_date                                        = true;
1277              }
1278          }
1279  
1280          /*
1281           * Sending a null date or date_gmt value resets date and date_gmt to their
1282           * default values (`0000-00-00 00:00:00`).
1283           */
1284          if (
1285              ( ! empty( $schema['properties']['date_gmt'] ) && $request->has_param( 'date_gmt' ) && null === $request['date_gmt'] ) ||
1286              ( ! empty( $schema['properties']['date'] ) && $request->has_param( 'date' ) && null === $request['date'] )
1287          ) {
1288              $prepared_post->post_date_gmt = null;
1289              $prepared_post->post_date     = null;
1290          }
1291  
1292          // Post slug.
1293          if ( ! empty( $schema['properties']['slug'] ) && isset( $request['slug'] ) ) {
1294              $prepared_post->post_name = $request['slug'];
1295          }
1296  
1297          // Author.
1298          if ( ! empty( $schema['properties']['author'] ) && ! empty( $request['author'] ) ) {
1299              $post_author = (int) $request['author'];
1300  
1301              if ( get_current_user_id() !== $post_author ) {
1302                  $user_obj = get_userdata( $post_author );
1303  
1304                  if ( ! $user_obj ) {
1305                      return new WP_Error(
1306                          'rest_invalid_author',
1307                          __( 'Invalid author ID.' ),
1308                          array( 'status' => 400 )
1309                      );
1310                  }
1311              }
1312  
1313              $prepared_post->post_author = $post_author;
1314          }
1315  
1316          // Post password.
1317          if ( ! empty( $schema['properties']['password'] ) && isset( $request['password'] ) ) {
1318              $prepared_post->post_password = $request['password'];
1319  
1320              if ( '' !== $request['password'] ) {
1321                  if ( ! empty( $schema['properties']['sticky'] ) && ! empty( $request['sticky'] ) ) {
1322                      return new WP_Error(
1323                          'rest_invalid_field',
1324                          __( 'A post can not be sticky and have a password.' ),
1325                          array( 'status' => 400 )
1326                      );
1327                  }
1328  
1329                  if ( ! empty( $prepared_post->ID ) && is_sticky( $prepared_post->ID ) ) {
1330                      return new WP_Error(
1331                          'rest_invalid_field',
1332                          __( 'A sticky post can not be password protected.' ),
1333                          array( 'status' => 400 )
1334                      );
1335                  }
1336              }
1337          }
1338  
1339          if ( ! empty( $schema['properties']['sticky'] ) && ! empty( $request['sticky'] ) ) {
1340              if ( ! empty( $prepared_post->ID ) && post_password_required( $prepared_post->ID ) ) {
1341                  return new WP_Error(
1342                      'rest_invalid_field',
1343                      __( 'A password protected post can not be set to sticky.' ),
1344                      array( 'status' => 400 )
1345                  );
1346              }
1347          }
1348  
1349          // Parent.
1350          if ( ! empty( $schema['properties']['parent'] ) && isset( $request['parent'] ) ) {
1351              if ( 0 === (int) $request['parent'] ) {
1352                  $prepared_post->post_parent = 0;
1353              } else {
1354                  $parent = get_post( (int) $request['parent'] );
1355  
1356                  if ( empty( $parent ) ) {
1357                      return new WP_Error(
1358                          'rest_post_invalid_id',
1359                          __( 'Invalid post parent ID.' ),
1360                          array( 'status' => 400 )
1361                      );
1362                  }
1363  
1364                  $prepared_post->post_parent = (int) $parent->ID;
1365              }
1366          }
1367  
1368          // Menu order.
1369          if ( ! empty( $schema['properties']['menu_order'] ) && isset( $request['menu_order'] ) ) {
1370              $prepared_post->menu_order = (int) $request['menu_order'];
1371          }
1372  
1373          // Comment status.
1374          if ( ! empty( $schema['properties']['comment_status'] ) && ! empty( $request['comment_status'] ) ) {
1375              $prepared_post->comment_status = $request['comment_status'];
1376          }
1377  
1378          // Ping status.
1379          if ( ! empty( $schema['properties']['ping_status'] ) && ! empty( $request['ping_status'] ) ) {
1380              $prepared_post->ping_status = $request['ping_status'];
1381          }
1382  
1383          if ( ! empty( $schema['properties']['template'] ) ) {
1384              // Force template to null so that it can be handled exclusively by the REST controller.
1385              $prepared_post->page_template = null;
1386          }
1387  
1388          /**
1389           * Filters a post before it is inserted via the REST API.
1390           *
1391           * The dynamic portion of the hook name, `$this->post_type`, refers to the post type slug.
1392           *
1393           * Possible hook names include:
1394           *
1395           *  - `rest_pre_insert_post`
1396           *  - `rest_pre_insert_page`
1397           *  - `rest_pre_insert_attachment`
1398           *
1399           * @since 4.7.0
1400           *
1401           * @param stdClass        $prepared_post An object representing a single post prepared
1402           *                                       for inserting or updating the database.
1403           * @param WP_REST_Request $request       Request object.
1404           */
1405          return apply_filters( "rest_pre_insert_{$this->post_type}", $prepared_post, $request );
1406      }
1407  
1408      /**
1409       * Checks whether the status is valid for the given post.
1410       *
1411       * Allows for sending an update request with the current status, even if that status would not be acceptable.
1412       *
1413       * @since 5.6.0
1414       *
1415       * @param string          $status  The provided status.
1416       * @param WP_REST_Request $request The request object.
1417       * @param string          $param   The parameter name.
1418       * @return true|WP_Error True if the status is valid, or WP_Error if not.
1419       */
1420  	public function check_status( $status, $request, $param ) {
1421          if ( $request['id'] ) {
1422              $post = $this->get_post( $request['id'] );
1423  
1424              if ( ! is_wp_error( $post ) && $post->post_status === $status ) {
1425                  return true;
1426              }
1427          }
1428  
1429          $args = $request->get_attributes()['args'][ $param ];
1430  
1431          return rest_validate_value_from_schema( $status, $args, $param );
1432      }
1433  
1434      /**
1435       * Determines validity and normalizes the given status parameter.
1436       *
1437       * @since 4.7.0
1438       *
1439       * @param string       $post_status Post status.
1440       * @param WP_Post_Type $post_type   Post type.
1441       * @return string|WP_Error Post status or WP_Error if lacking the proper permission.
1442       */
1443  	protected function handle_status_param( $post_status, $post_type ) {
1444  
1445          switch ( $post_status ) {
1446              case 'draft':
1447              case 'pending':
1448                  break;
1449              case 'private':
1450                  if ( ! current_user_can( $post_type->cap->publish_posts ) ) {
1451                      return new WP_Error(
1452                          'rest_cannot_publish',
1453                          __( 'Sorry, you are not allowed to create private posts in this post type.' ),
1454                          array( 'status' => rest_authorization_required_code() )
1455                      );
1456                  }
1457                  break;
1458              case 'publish':
1459              case 'future':
1460                  if ( ! current_user_can( $post_type->cap->publish_posts ) ) {
1461                      return new WP_Error(
1462                          'rest_cannot_publish',
1463                          __( 'Sorry, you are not allowed to publish posts in this post type.' ),
1464                          array( 'status' => rest_authorization_required_code() )
1465                      );
1466                  }
1467                  break;
1468              default:
1469                  if ( ! get_post_status_object( $post_status ) ) {
1470                      $post_status = 'draft';
1471                  }
1472                  break;
1473          }
1474  
1475          return $post_status;
1476      }
1477  
1478      /**
1479       * Determines the featured media based on a request param.
1480       *
1481       * @since 4.7.0
1482       *
1483       * @param int $featured_media Featured Media ID.
1484       * @param int $post_id        Post ID.
1485       * @return bool|WP_Error Whether the post thumbnail was successfully deleted, otherwise WP_Error.
1486       */
1487  	protected function handle_featured_media( $featured_media, $post_id ) {
1488  
1489          $featured_media = (int) $featured_media;
1490          if ( $featured_media ) {
1491              $result = set_post_thumbnail( $post_id, $featured_media );
1492              if ( $result ) {
1493                  return true;
1494              } else {
1495                  return new WP_Error(
1496                      'rest_invalid_featured_media',
1497                      __( 'Invalid featured media ID.' ),
1498                      array( 'status' => 400 )
1499                  );
1500              }
1501          } else {
1502              return delete_post_thumbnail( $post_id );
1503          }
1504      }
1505  
1506      /**
1507       * Checks whether the template is valid for the given post.
1508       *
1509       * @since 4.9.0
1510       *
1511       * @param string          $template Page template filename.
1512       * @param WP_REST_Request $request  Request.
1513       * @return true|WP_Error True if template is still valid or if the same as existing value, or a WP_Error if template not supported.
1514       */
1515  	public function check_template( $template, $request ) {
1516  
1517          if ( ! $template ) {
1518              return true;
1519          }
1520  
1521          if ( $request['id'] ) {
1522              $post             = get_post( $request['id'] );
1523              $current_template = get_page_template_slug( $request['id'] );
1524          } else {
1525              $post             = null;
1526              $current_template = '';
1527          }
1528  
1529          // Always allow for updating a post to the same template, even if that template is no longer supported.
1530          if ( $template === $current_template ) {
1531              return true;
1532          }
1533  
1534          // If this is a create request, get_post() will return null and wp theme will fallback to the passed post type.
1535          $allowed_templates = wp_get_theme()->get_page_templates( $post, $this->post_type );
1536  
1537          if ( isset( $allowed_templates[ $template ] ) ) {
1538              return true;
1539          }
1540  
1541          return new WP_Error(
1542              'rest_invalid_param',
1543              /* translators: 1: Parameter, 2: List of valid values. */
1544              sprintf( __( '%1$s is not one of %2$s.' ), 'template', implode( ', ', array_keys( $allowed_templates ) ) )
1545          );
1546      }
1547  
1548      /**
1549       * Sets the template for a post.
1550       *
1551       * @since 4.7.0
1552       * @since 4.9.0 Added the `$validate` parameter.
1553       *
1554       * @param string $template Page template filename.
1555       * @param int    $post_id  Post ID.
1556       * @param bool   $validate Whether to validate that the template selected is valid.
1557       */
1558  	public function handle_template( $template, $post_id, $validate = false ) {
1559  
1560          if ( $validate && ! array_key_exists( $template, wp_get_theme()->get_page_templates( get_post( $post_id ) ) ) ) {
1561              $template = '';
1562          }
1563  
1564          update_post_meta( $post_id, '_wp_page_template', $template );
1565      }
1566  
1567      /**
1568       * Updates the post's terms from a REST request.
1569       *
1570       * @since 4.7.0
1571       *
1572       * @param int             $post_id The post ID to update the terms form.
1573       * @param WP_REST_Request $request The request object with post and terms data.
1574       * @return null|WP_Error WP_Error on an error assigning any of the terms, otherwise null.
1575       */
1576  	protected function handle_terms( $post_id, $request ) {
1577          $taxonomies = wp_list_filter( get_object_taxonomies( $this->post_type, 'objects' ), array( 'show_in_rest' => true ) );
1578  
1579          foreach ( $taxonomies as $taxonomy ) {
1580              $base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name;
1581  
1582              if ( ! isset( $request[ $base ] ) ) {
1583                  continue;
1584              }
1585  
1586              $result = wp_set_object_terms( $post_id, $request[ $base ], $taxonomy->name );
1587  
1588              if ( is_wp_error( $result ) ) {
1589                  return $result;
1590              }
1591          }
1592      }
1593  
1594      /**
1595       * Checks whether current user can assign all terms sent with the current request.
1596       *
1597       * @since 4.7.0
1598       *
1599       * @param WP_REST_Request $request The request object with post and terms data.
1600       * @return bool Whether the current user can assign the provided terms.
1601       */
1602  	protected function check_assign_terms_permission( $request ) {
1603          $taxonomies = wp_list_filter( get_object_taxonomies( $this->post_type, 'objects' ), array( 'show_in_rest' => true ) );
1604          foreach ( $taxonomies as $taxonomy ) {
1605              $base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name;
1606  
1607              if ( ! isset( $request[ $base ] ) ) {
1608                  continue;
1609              }
1610  
1611              foreach ( (array) $request[ $base ] as $term_id ) {
1612                  // Invalid terms will be rejected later.
1613                  if ( ! get_term( $term_id, $taxonomy->name ) ) {
1614                      continue;
1615                  }
1616  
1617                  if ( ! current_user_can( 'assign_term', (int) $term_id ) ) {
1618                      return false;
1619                  }
1620              }
1621          }
1622  
1623          return true;
1624      }
1625  
1626      /**
1627       * Checks if a given post type can be viewed or managed.
1628       *
1629       * @since 4.7.0
1630       *
1631       * @param WP_Post_Type|string $post_type Post type name or object.
1632       * @return bool Whether the post type is allowed in REST.
1633       */
1634  	protected function check_is_post_type_allowed( $post_type ) {
1635          if ( ! is_object( $post_type ) ) {
1636              $post_type = get_post_type_object( $post_type );
1637          }
1638  
1639          if ( ! empty( $post_type ) && ! empty( $post_type->show_in_rest ) ) {
1640              return true;
1641          }
1642  
1643          return false;
1644      }
1645  
1646      /**
1647       * Checks if a post can be read.
1648       *
1649       * Correctly handles posts with the inherit status.
1650       *
1651       * @since 4.7.0
1652       *
1653       * @param WP_Post $post Post object.
1654       * @return bool Whether the post can be read.
1655       */
1656  	public function check_read_permission( $post ) {
1657          $post_type = get_post_type_object( $post->post_type );
1658          if ( ! $this->check_is_post_type_allowed( $post_type ) ) {
1659              return false;
1660          }
1661  
1662          // Is the post readable?
1663          if ( 'publish' === $post->post_status || current_user_can( 'read_post', $post->ID ) ) {
1664              return true;
1665          }
1666  
1667          $post_status_obj = get_post_status_object( $post->post_status );
1668          if ( $post_status_obj && $post_status_obj->public ) {
1669              return true;
1670          }
1671  
1672          // Can we read the parent if we're inheriting?
1673          if ( 'inherit' === $post->post_status && $post->post_parent > 0 ) {
1674              $parent = get_post( $post->post_parent );
1675              if ( $parent ) {
1676                  return $this->check_read_permission( $parent );
1677              }
1678          }
1679  
1680          /*
1681           * If there isn't a parent, but the status is set to inherit, assume
1682           * it's published (as per get_post_status()).
1683           */
1684          if ( 'inherit' === $post->post_status ) {
1685              return true;
1686          }
1687  
1688          return false;
1689      }
1690  
1691      /**
1692       * Checks if a post can be edited.
1693       *
1694       * @since 4.7.0
1695       *
1696       * @param WP_Post $post Post object.
1697       * @return bool Whether the post can be edited.
1698       */
1699  	protected function check_update_permission( $post ) {
1700          $post_type = get_post_type_object( $post->post_type );
1701  
1702          if ( ! $this->check_is_post_type_allowed( $post_type ) ) {
1703              return false;
1704          }
1705  
1706          return current_user_can( 'edit_post', $post->ID );
1707      }
1708  
1709      /**
1710       * Checks if a post can be created.
1711       *
1712       * @since 4.7.0
1713       *
1714       * @param WP_Post $post Post object.
1715       * @return bool Whether the post can be created.
1716       */
1717  	protected function check_create_permission( $post ) {
1718          $post_type = get_post_type_object( $post->post_type );
1719  
1720          if ( ! $this->check_is_post_type_allowed( $post_type ) ) {
1721              return false;
1722          }
1723  
1724          return current_user_can( $post_type->cap->create_posts );
1725      }
1726  
1727      /**
1728       * Checks if a post can be deleted.
1729       *
1730       * @since 4.7.0
1731       *
1732       * @param WP_Post $post Post object.
1733       * @return bool Whether the post can be deleted.
1734       */
1735  	protected function check_delete_permission( $post ) {
1736          $post_type = get_post_type_object( $post->post_type );
1737  
1738          if ( ! $this->check_is_post_type_allowed( $post_type ) ) {
1739              return false;
1740          }
1741  
1742          return current_user_can( 'delete_post', $post->ID );
1743      }
1744  
1745      /**
1746       * Prepares a single post output for response.
1747       *
1748       * @since 4.7.0
1749       * @since 5.9.0 Renamed `$post` to `$item` to match parent class for PHP 8 named parameter support.
1750       *
1751       * @global WP_Post $post Global post object.
1752       *
1753       * @param WP_Post         $item    Post object.
1754       * @param WP_REST_Request $request Request object.
1755       * @return WP_REST_Response Response object.
1756       */
1757  	public function prepare_item_for_response( $item, $request ) {
1758          // Restores the more descriptive, specific name for use within this method.
1759          $post = $item;
1760  
1761          $GLOBALS['post'] = $post;
1762  
1763          setup_postdata( $post );
1764  
1765          $fields = $this->get_fields_for_response( $request );
1766  
1767          // Base fields for every post.
1768          $data = array();
1769  
1770          if ( rest_is_field_included( 'id', $fields ) ) {
1771              $data['id'] = $post->ID;
1772          }
1773  
1774          if ( rest_is_field_included( 'date', $fields ) ) {
1775              $data['date'] = $this->prepare_date_response( $post->post_date_gmt, $post->post_date );
1776          }
1777  
1778          if ( rest_is_field_included( 'date_gmt', $fields ) ) {
1779              /*
1780               * For drafts, `post_date_gmt` may not be set, indicating that the date
1781               * of the draft should be updated each time it is saved (see #38883).
1782               * In this case, shim the value based on the `post_date` field
1783               * with the site's timezone offset applied.
1784               */
1785              if ( '0000-00-00 00:00:00' === $post->post_date_gmt ) {
1786                  $post_date_gmt = get_gmt_from_date( $post->post_date );
1787              } else {
1788                  $post_date_gmt = $post->post_date_gmt;
1789              }
1790              $data['date_gmt'] = $this->prepare_date_response( $post_date_gmt );
1791          }
1792  
1793          if ( rest_is_field_included( 'guid', $fields ) ) {
1794              $data['guid'] = array(
1795                  /** This filter is documented in wp-includes/post-template.php */
1796                  'rendered' => apply_filters( 'get_the_guid', $post->guid, $post->ID ),
1797                  'raw'      => $post->guid,
1798              );
1799          }
1800  
1801          if ( rest_is_field_included( 'modified', $fields ) ) {
1802              $data['modified'] = $this->prepare_date_response( $post->post_modified_gmt, $post->post_modified );
1803          }
1804  
1805          if ( rest_is_field_included( 'modified_gmt', $fields ) ) {
1806              /*
1807               * For drafts, `post_modified_gmt` may not be set (see `post_date_gmt` comments
1808               * above). In this case, shim the value based on the `post_modified` field
1809               * with the site's timezone offset applied.
1810               */
1811              if ( '0000-00-00 00:00:00' === $post->post_modified_gmt ) {
1812                  $post_modified_gmt = gmdate( 'Y-m-d H:i:s', strtotime( $post->post_modified ) - ( get_option( 'gmt_offset' ) * HOUR_IN_SECONDS ) );
1813              } else {
1814                  $post_modified_gmt = $post->post_modified_gmt;
1815              }
1816              $data['modified_gmt'] = $this->prepare_date_response( $post_modified_gmt );
1817          }
1818  
1819          if ( rest_is_field_included( 'password', $fields ) ) {
1820              $data['password'] = $post->post_password;
1821          }
1822  
1823          if ( rest_is_field_included( 'slug', $fields ) ) {
1824              $data['slug'] = $post->post_name;
1825          }
1826  
1827          if ( rest_is_field_included( 'status', $fields ) ) {
1828              $data['status'] = $post->post_status;
1829          }
1830  
1831          if ( rest_is_field_included( 'type', $fields ) ) {
1832              $data['type'] = $post->post_type;
1833          }
1834  
1835          if ( rest_is_field_included( 'link', $fields ) ) {
1836              $data['link'] = get_permalink( $post->ID );
1837          }
1838  
1839          if ( rest_is_field_included( 'title', $fields ) ) {
1840              $data['title'] = array();
1841          }
1842          if ( rest_is_field_included( 'title.raw', $fields ) ) {
1843              $data['title']['raw'] = $post->post_title;
1844          }
1845          if ( rest_is_field_included( 'title.rendered', $fields ) ) {
1846              add_filter( 'protected_title_format', array( $this, 'protected_title_format' ) );
1847  
1848              $data['title']['rendered'] = get_the_title( $post->ID );
1849  
1850              remove_filter( 'protected_title_format', array( $this, 'protected_title_format' ) );
1851          }
1852  
1853          $has_password_filter = false;
1854  
1855          if ( $this->can_access_password_content( $post, $request ) ) {
1856              $this->password_check_passed[ $post->ID ] = true;
1857              // Allow access to the post, permissions already checked before.
1858              add_filter( 'post_password_required', array( $this, 'check_password_required' ), 10, 2 );
1859  
1860              $has_password_filter = true;
1861          }
1862  
1863          if ( rest_is_field_included( 'content', $fields ) ) {
1864              $data['content'] = array();
1865          }
1866          if ( rest_is_field_included( 'content.raw', $fields ) ) {
1867              $data['content']['raw'] = $post->post_content;
1868          }
1869          if ( rest_is_field_included( 'content.rendered', $fields ) ) {
1870              /** This filter is documented in wp-includes/post-template.php */
1871              $data['content']['rendered'] = post_password_required( $post ) ? '' : apply_filters( 'the_content', $post->post_content );
1872          }
1873          if ( rest_is_field_included( 'content.protected', $fields ) ) {
1874              $data['content']['protected'] = (bool) $post->post_password;
1875          }
1876          if ( rest_is_field_included( 'content.block_version', $fields ) ) {
1877              $data['content']['block_version'] = block_version( $post->post_content );
1878          }
1879  
1880          if ( rest_is_field_included( 'excerpt', $fields ) ) {
1881              if ( isset( $request['excerpt_length'] ) ) {
1882                  $excerpt_length          = $request['excerpt_length'];
1883                  $override_excerpt_length = static function () use ( $excerpt_length ) {
1884                      return $excerpt_length;
1885                  };
1886  
1887                  add_filter(
1888                      'excerpt_length',
1889                      $override_excerpt_length,
1890                      20
1891                  );
1892              }
1893  
1894              /** This filter is documented in wp-includes/post-template.php */
1895              $excerpt = apply_filters( 'get_the_excerpt', $post->post_excerpt, $post );
1896  
1897              /** This filter is documented in wp-includes/post-template.php */
1898              $excerpt = apply_filters( 'the_excerpt', $excerpt );
1899  
1900              $data['excerpt'] = array(
1901                  'raw'       => $post->post_excerpt,
1902                  'rendered'  => post_password_required( $post ) ? '' : $excerpt,
1903                  'protected' => (bool) $post->post_password,
1904              );
1905  
1906              if ( isset( $override_excerpt_length ) ) {
1907                  remove_filter(
1908                      'excerpt_length',
1909                      $override_excerpt_length,
1910                      20
1911                  );
1912              }
1913          }
1914  
1915          if ( $has_password_filter ) {
1916              // Reset filter.
1917              remove_filter( 'post_password_required', array( $this, 'check_password_required' ) );
1918          }
1919  
1920          if ( rest_is_field_included( 'author', $fields ) ) {
1921              $data['author'] = (int) $post->post_author;
1922          }
1923  
1924          if ( rest_is_field_included( 'featured_media', $fields ) ) {
1925              $data['featured_media'] = (int) get_post_thumbnail_id( $post->ID );
1926          }
1927  
1928          if ( rest_is_field_included( 'parent', $fields ) ) {
1929              $data['parent'] = (int) $post->post_parent;
1930          }
1931  
1932          if ( rest_is_field_included( 'menu_order', $fields ) ) {
1933              $data['menu_order'] = (int) $post->menu_order;
1934          }
1935  
1936          if ( rest_is_field_included( 'comment_status', $fields ) ) {
1937              $data['comment_status'] = $post->comment_status;
1938          }
1939  
1940          if ( rest_is_field_included( 'ping_status', $fields ) ) {
1941              $data['ping_status'] = $post->ping_status;
1942          }
1943  
1944          if ( rest_is_field_included( 'sticky', $fields ) ) {
1945              $data['sticky'] = is_sticky( $post->ID );
1946          }
1947  
1948          if ( rest_is_field_included( 'template', $fields ) ) {
1949              $template = get_page_template_slug( $post->ID );
1950              if ( $template ) {
1951                  $data['template'] = $template;
1952              } else {
1953                  $data['template'] = '';
1954              }
1955          }
1956  
1957          if ( rest_is_field_included( 'format', $fields ) ) {
1958              $data['format'] = get_post_format( $post->ID );
1959  
1960              // Fill in blank post format.
1961              if ( empty( $data['format'] ) ) {
1962                  $data['format'] = 'standard';
1963              }
1964          }
1965  
1966          if ( rest_is_field_included( 'meta', $fields ) ) {
1967              $data['meta'] = $this->meta->get_value( $post->ID, $request );
1968          }
1969  
1970          $taxonomies = wp_list_filter( get_object_taxonomies( $this->post_type, 'objects' ), array( 'show_in_rest' => true ) );
1971  
1972          foreach ( $taxonomies as $taxonomy ) {
1973              $base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name;
1974  
1975              if ( rest_is_field_included( $base, $fields ) ) {
1976                  $terms         = get_the_terms( $post, $taxonomy->name );
1977                  $data[ $base ] = $terms ? array_values( wp_list_pluck( $terms, 'term_id' ) ) : array();
1978              }
1979          }
1980  
1981          $post_type_obj = get_post_type_object( $post->post_type );
1982          if ( is_post_type_viewable( $post_type_obj ) && $post_type_obj->public ) {
1983              $permalink_template_requested = rest_is_field_included( 'permalink_template', $fields );
1984              $generated_slug_requested     = rest_is_field_included( 'generated_slug', $fields );
1985  
1986              if ( $permalink_template_requested || $generated_slug_requested ) {
1987                  if ( ! function_exists( 'get_sample_permalink' ) ) {
1988                      require_once  ABSPATH . 'wp-admin/includes/post.php';
1989                  }
1990  
1991                  $sample_permalink = get_sample_permalink( $post->ID, $post->post_title, '' );
1992  
1993                  if ( $permalink_template_requested ) {
1994                      $data['permalink_template'] = $sample_permalink[0];
1995                  }
1996  
1997                  if ( $generated_slug_requested ) {
1998                      $data['generated_slug'] = $sample_permalink[1];
1999                  }
2000              }
2001          }
2002  
2003          $context = ! empty( $request['context'] ) ? $request['context'] : 'view';
2004          $data    = $this->add_additional_fields_to_object( $data, $request );
2005          $data    = $this->filter_response_by_context( $data, $context );
2006  
2007          // Wrap the data in a response object.
2008          $response = rest_ensure_response( $data );
2009  
2010          if ( rest_is_field_included( '_links', $fields ) || rest_is_field_included( '_embedded', $fields ) ) {
2011              $links = $this->prepare_links( $post );
2012              $response->add_links( $links );
2013  
2014              if ( ! empty( $links['self']['href'] ) ) {
2015                  $actions = $this->get_available_actions( $post, $request );
2016  
2017                  $self = $links['self']['href'];
2018  
2019                  foreach ( $actions as $rel ) {
2020                      $response->add_link( $rel, $self );
2021                  }
2022              }
2023          }
2024  
2025          /**
2026           * Filters the post data for a REST API response.
2027           *
2028           * The dynamic portion of the hook name, `$this->post_type`, refers to the post type slug.
2029           *
2030           * Possible hook names include:
2031           *
2032           *  - `rest_prepare_post`
2033           *  - `rest_prepare_page`
2034           *  - `rest_prepare_attachment`
2035           *
2036           * @since 4.7.0
2037           *
2038           * @param WP_REST_Response $response The response object.
2039           * @param WP_Post          $post     Post object.
2040           * @param WP_REST_Request  $request  Request object.
2041           */
2042          return apply_filters( "rest_prepare_{$this->post_type}", $response, $post, $request );
2043      }
2044  
2045      /**
2046       * Overwrites the default protected title format.
2047       *
2048       * By default, WordPress will show password protected posts with a title of
2049       * "Protected: %s", as the REST API communicates the protected status of a post
2050       * in a machine readable format, we remove the "Protected: " prefix.
2051       *
2052       * @since 4.7.0
2053       *
2054       * @return string Protected title format.
2055       */
2056  	public function protected_title_format() {
2057          return '%s';
2058      }
2059  
2060      /**
2061       * Prepares links for the request.
2062       *
2063       * @since 4.7.0
2064       *
2065       * @param WP_Post $post Post object.
2066       * @return array Links for the given post.
2067       */
2068  	protected function prepare_links( $post ) {
2069          // Entity meta.
2070          $links = array(
2071              'self'       => array(
2072                  'href' => rest_url( rest_get_route_for_post( $post->ID ) ),
2073              ),
2074              'collection' => array(
2075                  'href' => rest_url( rest_get_route_for_post_type_items( $this->post_type ) ),
2076              ),
2077              'about'      => array(
2078                  'href' => rest_url( 'wp/v2/types/' . $this->post_type ),
2079              ),
2080          );
2081  
2082          if ( ( in_array( $post->post_type, array( 'post', 'page' ), true ) || post_type_supports( $post->post_type, 'author' ) )
2083              && ! empty( $post->post_author ) ) {
2084              $links['author'] = array(
2085                  'href'       => rest_url( 'wp/v2/users/' . $post->post_author ),
2086                  'embeddable' => true,
2087              );
2088          }
2089  
2090          if ( in_array( $post->post_type, array( 'post', 'page' ), true ) || post_type_supports( $post->post_type, 'comments' ) ) {
2091              $replies_url = rest_url( 'wp/v2/comments' );
2092              $replies_url = add_query_arg( 'post', $post->ID, $replies_url );
2093  
2094              $links['replies'] = array(
2095                  'href'       => $replies_url,
2096                  'embeddable' => true,
2097              );
2098          }
2099  
2100          if ( in_array( $post->post_type, array( 'post', 'page' ), true ) || post_type_supports( $post->post_type, 'revisions' ) ) {
2101              $revisions       = wp_get_latest_revision_id_and_total_count( $post->ID );
2102              $revisions_count = ! is_wp_error( $revisions ) ? $revisions['count'] : 0;
2103              $revisions_base  = sprintf( '/%s/%s/%d/revisions', $this->namespace, $this->rest_base, $post->ID );
2104  
2105              $links['version-history'] = array(
2106                  'href'  => rest_url( $revisions_base ),
2107                  'count' => $revisions_count,
2108              );
2109  
2110              if ( $revisions_count > 0 ) {
2111                  $links['predecessor-version'] = array(
2112                      'href' => rest_url( $revisions_base . '/' . $revisions['latest_id'] ),
2113                      'id'   => $revisions['latest_id'],
2114                  );
2115              }
2116          }
2117  
2118          $post_type_obj = get_post_type_object( $post->post_type );
2119  
2120          if ( $post_type_obj->hierarchical && ! empty( $post->post_parent ) ) {
2121              $links['up'] = array(
2122                  'href'       => rest_url( rest_get_route_for_post( $post->post_parent ) ),
2123                  'embeddable' => true,
2124              );
2125          }
2126  
2127          // If we have a featured media, add that.
2128          $featured_media = get_post_thumbnail_id( $post->ID );
2129          if ( $featured_media ) {
2130              $image_url = rest_url( rest_get_route_for_post( $featured_media ) );
2131  
2132              $links['https://api.w.org/featuredmedia'] = array(
2133                  'href'       => $image_url,
2134                  'embeddable' => true,
2135              );
2136          }
2137  
2138          if ( ! in_array( $post->post_type, array( 'attachment', 'nav_menu_item', 'revision' ), true ) ) {
2139              $attachments_url = rest_url( rest_get_route_for_post_type_items( 'attachment' ) );
2140              $attachments_url = add_query_arg( 'parent', $post->ID, $attachments_url );
2141  
2142              $links['https://api.w.org/attachment'] = array(
2143                  'href' => $attachments_url,
2144              );
2145          }
2146  
2147          $taxonomies = get_object_taxonomies( $post->post_type );
2148  
2149          if ( ! empty( $taxonomies ) ) {
2150              $links['https://api.w.org/term'] = array();
2151  
2152              foreach ( $taxonomies as $tax ) {
2153                  $taxonomy_route = rest_get_route_for_taxonomy_items( $tax );
2154  
2155                  // Skip taxonomies that are not public.
2156                  if ( empty( $taxonomy_route ) ) {
2157                      continue;
2158                  }
2159                  $terms_url = add_query_arg(
2160                      'post',
2161                      $post->ID,
2162                      rest_url( $taxonomy_route )
2163                  );
2164  
2165                  $links['https://api.w.org/term'][] = array(
2166                      'href'       => $terms_url,
2167                      'taxonomy'   => $tax,
2168                      'embeddable' => true,
2169                  );
2170              }
2171          }
2172  
2173          return $links;
2174      }
2175  
2176      /**
2177       * Gets the link relations available for the post and current user.
2178       *
2179       * @since 4.9.8
2180       *
2181       * @param WP_Post         $post    Post object.
2182       * @param WP_REST_Request $request Request object.
2183       * @return array List of link relations.
2184       */
2185  	protected function get_available_actions( $post, $request ) {
2186  
2187          if ( 'edit' !== $request['context'] ) {
2188              return array();
2189          }
2190  
2191          $rels = array();
2192  
2193          $post_type = get_post_type_object( $post->post_type );
2194  
2195          if ( 'attachment' !== $this->post_type && current_user_can( $post_type->cap->publish_posts ) ) {
2196              $rels[] = 'https://api.w.org/action-publish';
2197          }
2198  
2199          if ( current_user_can( 'unfiltered_html' ) ) {
2200              $rels[] = 'https://api.w.org/action-unfiltered-html';
2201          }
2202  
2203          if ( 'post' === $post_type->name ) {
2204              if ( current_user_can( $post_type->cap->edit_others_posts ) && current_user_can( $post_type->cap->publish_posts ) ) {
2205                  $rels[] = 'https://api.w.org/action-sticky';
2206              }
2207          }
2208  
2209          if ( post_type_supports( $post_type->name, 'author' ) ) {
2210              if ( current_user_can( $post_type->cap->edit_others_posts ) ) {
2211                  $rels[] = 'https://api.w.org/action-assign-author';
2212              }
2213          }
2214  
2215          $taxonomies = wp_list_filter( get_object_taxonomies( $this->post_type, 'objects' ), array( 'show_in_rest' => true ) );
2216  
2217          foreach ( $taxonomies as $tax ) {
2218              $tax_base   = ! empty( $tax->rest_base ) ? $tax->rest_base : $tax->name;
2219              $create_cap = is_taxonomy_hierarchical( $tax->name ) ? $tax->cap->edit_terms : $tax->cap->assign_terms;
2220  
2221              if ( current_user_can( $create_cap ) ) {
2222                  $rels[] = 'https://api.w.org/action-create-' . $tax_base;
2223              }
2224  
2225              if ( current_user_can( $tax->cap->assign_terms ) ) {
2226                  $rels[] = 'https://api.w.org/action-assign-' . $tax_base;
2227              }
2228          }
2229  
2230          return $rels;
2231      }
2232  
2233      /**
2234       * Retrieves the post's schema, conforming to JSON Schema.
2235       *
2236       * @since 4.7.0
2237       *
2238       * @return array Item schema data.
2239       */
2240  	public function get_item_schema() {
2241          if ( $this->schema ) {
2242              return $this->add_additional_fields_schema( $this->schema );
2243          }
2244  
2245          $schema = array(
2246              '$schema'    => 'http://json-schema.org/draft-04/schema#',
2247              'title'      => $this->post_type,
2248              'type'       => 'object',
2249              // Base properties for every Post.
2250              'properties' => array(
2251                  'date'         => array(
2252                      'description' => __( "The date the post was published, in the site's timezone." ),
2253                      'type'        => array( 'string', 'null' ),
2254                      'format'      => 'date-time',
2255                      'context'     => array( 'view', 'edit', 'embed' ),
2256                  ),
2257                  'date_gmt'     => array(
2258                      'description' => __( 'The date the post was published, as GMT.' ),
2259                      'type'        => array( 'string', 'null' ),
2260                      'format'      => 'date-time',
2261                      'context'     => array( 'view', 'edit' ),
2262                  ),
2263                  'guid'         => array(
2264                      'description' => __( 'The globally unique identifier for the post.' ),
2265                      'type'        => 'object',
2266                      'context'     => array( 'view', 'edit' ),
2267                      'readonly'    => true,
2268                      'properties'  => array(
2269                          'raw'      => array(
2270                              'description' => __( 'GUID for the post, as it exists in the database.' ),
2271                              'type'        => 'string',
2272                              'context'     => array( 'edit' ),
2273                              'readonly'    => true,
2274                          ),
2275                          'rendered' => array(
2276                              'description' => __( 'GUID for the post, transformed for display.' ),
2277                              'type'        => 'string',
2278                              'context'     => array( 'view', 'edit' ),
2279                              'readonly'    => true,
2280                          ),
2281                      ),
2282                  ),
2283                  'id'           => array(
2284                      'description' => __( 'Unique identifier for the post.' ),
2285                      'type'        => 'integer',
2286                      'context'     => array( 'view', 'edit', 'embed' ),
2287                      'readonly'    => true,
2288                  ),
2289                  'link'         => array(
2290                      'description' => __( 'URL to the post.' ),
2291                      'type'        => 'string',
2292                      'format'      => 'uri',
2293                      'context'     => array( 'view', 'edit', 'embed' ),
2294                      'readonly'    => true,
2295                  ),
2296                  'modified'     => array(
2297                      'description' => __( "The date the post was last modified, in the site's timezone." ),
2298                      'type'        => 'string',
2299                      'format'      => 'date-time',
2300                      'context'     => array( 'view', 'edit' ),
2301                      'readonly'    => true,
2302                  ),
2303                  'modified_gmt' => array(
2304                      'description' => __( 'The date the post was last modified, as GMT.' ),
2305                      'type'        => 'string',
2306                      'format'      => 'date-time',
2307                      'context'     => array( 'view', 'edit' ),
2308                      'readonly'    => true,
2309                  ),
2310                  'slug'         => array(
2311                      'description' => __( 'An alphanumeric identifier for the post unique to its type.' ),
2312                      'type'        => 'string',
2313                      'context'     => array( 'view', 'edit', 'embed' ),
2314                      'arg_options' => array(
2315                          'sanitize_callback' => array( $this, 'sanitize_slug' ),
2316                      ),
2317                  ),
2318                  'status'       => array(
2319                      'description' => __( 'A named status for the post.' ),
2320                      'type'        => 'string',
2321                      'enum'        => array_keys( get_post_stati( array( 'internal' => false ) ) ),
2322                      'context'     => array( 'view', 'edit' ),
2323                      'arg_options' => array(
2324                          'validate_callback' => array( $this, 'check_status' ),
2325                      ),
2326                  ),
2327                  'type'         => array(
2328                      'description' => __( 'Type of post.' ),
2329                      'type'        => 'string',
2330                      'context'     => array( 'view', 'edit', 'embed' ),
2331                      'readonly'    => true,
2332                  ),
2333                  'password'     => array(
2334                      'description' => __( 'A password to protect access to the content and excerpt.' ),
2335                      'type'        => 'string',
2336                      'context'     => array( 'edit' ),
2337                  ),
2338              ),
2339          );
2340  
2341          $post_type_obj = get_post_type_object( $this->post_type );
2342          if ( is_post_type_viewable( $post_type_obj ) && $post_type_obj->public ) {
2343              $schema['properties']['permalink_template'] = array(
2344                  'description' => __( 'Permalink template for the post.' ),
2345                  'type'        => 'string',
2346                  'context'     => array( 'edit' ),
2347                  'readonly'    => true,
2348              );
2349  
2350              $schema['properties']['generated_slug'] = array(
2351                  'description' => __( 'Slug automatically generated from the post title.' ),
2352                  'type'        => 'string',
2353                  'context'     => array( 'edit' ),
2354                  'readonly'    => true,
2355              );
2356          }
2357  
2358          if ( $post_type_obj->hierarchical ) {
2359              $schema['properties']['parent'] = array(
2360                  'description' => __( 'The ID for the parent of the post.' ),
2361                  'type'        => 'integer',
2362                  'context'     => array( 'view', 'edit' ),
2363              );
2364          }
2365  
2366          $post_type_attributes = array(
2367              'title',
2368              'editor',
2369              'author',
2370              'excerpt',
2371              'thumbnail',
2372              'comments',
2373              'revisions',
2374              'page-attributes',
2375              'post-formats',
2376              'custom-fields',
2377          );
2378          $fixed_schemas        = array(
2379              'post'       => array(
2380                  'title',
2381                  'editor',
2382                  'author',
2383                  'excerpt',
2384                  'thumbnail',
2385                  'comments',
2386                  'revisions',
2387                  'post-formats',
2388                  'custom-fields',
2389              ),
2390              'page'       => array(
2391                  'title',
2392                  'editor',
2393                  'author',
2394                  'excerpt',
2395                  'thumbnail',
2396                  'comments',
2397                  'revisions',
2398                  'page-attributes',
2399                  'custom-fields',
2400              ),
2401              'attachment' => array(
2402                  'title',
2403                  'author',
2404                  'comments',
2405                  'revisions',
2406                  'custom-fields',
2407                  'thumbnail',
2408              ),
2409          );
2410  
2411          foreach ( $post_type_attributes as $attribute ) {
2412              if ( isset( $fixed_schemas[ $this->post_type ] ) && ! in_array( $attribute, $fixed_schemas[ $this->post_type ], true ) ) {
2413                  continue;
2414              } elseif ( ! isset( $fixed_schemas[ $this->post_type ] ) && ! post_type_supports( $this->post_type, $attribute ) ) {
2415                  continue;
2416              }
2417  
2418              switch ( $attribute ) {
2419  
2420                  case 'title':
2421                      $schema['properties']['title'] = array(
2422                          'description' => __( 'The title for the post.' ),
2423                          'type'        => 'object',
2424                          'context'     => array( 'view', 'edit', 'embed' ),
2425                          'arg_options' => array(
2426                              'sanitize_callback' => null, // Note: sanitization implemented in self::prepare_item_for_database().
2427                              'validate_callback' => null, // Note: validation implemented in self::prepare_item_for_database().
2428                          ),
2429                          'properties'  => array(
2430                              'raw'      => array(
2431                                  'description' => __( 'Title for the post, as it exists in the database.' ),
2432                                  'type'        => 'string',
2433                                  'context'     => array( 'edit' ),
2434                              ),
2435                              'rendered' => array(
2436                                  'description' => __( 'HTML title for the post, transformed for display.' ),
2437                                  'type'        => 'string',
2438                                  'context'     => array( 'view', 'edit', 'embed' ),
2439                                  'readonly'    => true,
2440                              ),
2441                          ),
2442                      );
2443                      break;
2444  
2445                  case 'editor':
2446                      $schema['properties']['content'] = array(
2447                          'description' => __( 'The content for the post.' ),
2448                          'type'        => 'object',
2449                          'context'     => array( 'view', 'edit' ),
2450                          'arg_options' => array(
2451                              'sanitize_callback' => null, // Note: sanitization implemented in self::prepare_item_for_database().
2452                              'validate_callback' => null, // Note: validation implemented in self::prepare_item_for_database().
2453                          ),
2454                          'properties'  => array(
2455                              'raw'           => array(
2456                                  'description' => __( 'Content for the post, as it exists in the database.' ),
2457                                  'type'        => 'string',
2458                                  'context'     => array( 'edit' ),
2459                              ),
2460                              'rendered'      => array(
2461                                  'description' => __( 'HTML content for the post, transformed for display.' ),
2462                                  'type'        => 'string',
2463                                  'context'     => array( 'view', 'edit' ),
2464                                  'readonly'    => true,
2465                              ),
2466                              'block_version' => array(
2467                                  'description' => __( 'Version of the content block format used by the post.' ),
2468                                  'type'        => 'integer',
2469                                  'context'     => array( 'edit' ),
2470                                  'readonly'    => true,
2471                              ),
2472                              'protected'     => array(
2473                                  'description' => __( 'Whether the content is protected with a password.' ),
2474                                  'type'        => 'boolean',
2475                                  'context'     => array( 'view', 'edit', 'embed' ),
2476                                  'readonly'    => true,
2477                              ),
2478                          ),
2479                      );
2480                      break;
2481  
2482                  case 'author':
2483                      $schema['properties']['author'] = array(
2484                          'description' => __( 'The ID for the author of the post.' ),
2485                          'type'        => 'integer',
2486                          'context'     => array( 'view', 'edit', 'embed' ),
2487                      );
2488                      break;
2489  
2490                  case 'excerpt':
2491                      $schema['properties']['excerpt'] = array(
2492                          'description' => __( 'The excerpt for the post.' ),
2493                          'type'        => 'object',
2494                          'context'     => array( 'view', 'edit', 'embed' ),
2495                          'arg_options' => array(
2496                              'sanitize_callback' => null, // Note: sanitization implemented in self::prepare_item_for_database().
2497                              'validate_callback' => null, // Note: validation implemented in self::prepare_item_for_database().
2498                          ),
2499                          'properties'  => array(
2500                              'raw'       => array(
2501                                  'description' => __( 'Excerpt for the post, as it exists in the database.' ),
2502                                  'type'        => 'string',
2503                                  'context'     => array( 'edit' ),
2504                              ),
2505                              'rendered'  => array(
2506                                  'description' => __( 'HTML excerpt for the post, transformed for display.' ),
2507                                  'type'        => 'string',
2508                                  'context'     => array( 'view', 'edit', 'embed' ),
2509                                  'readonly'    => true,
2510                              ),
2511                              'protected' => array(
2512                                  'description' => __( 'Whether the excerpt is protected with a password.' ),
2513                                  'type'        => 'boolean',
2514                                  'context'     => array( 'view', 'edit', 'embed' ),
2515                                  'readonly'    => true,
2516                              ),
2517                          ),
2518                      );
2519                      break;
2520  
2521                  case 'thumbnail':
2522                      $schema['properties']['featured_media'] = array(
2523                          'description' => __( 'The ID of the featured media for the post.' ),
2524                          'type'        => 'integer',
2525                          'context'     => array( 'view', 'edit', 'embed' ),
2526                      );
2527                      break;
2528  
2529                  case 'comments':
2530                      $schema['properties']['comment_status'] = array(
2531                          'description' => __( 'Whether or not comments are open on the post.' ),
2532                          'type'        => 'string',
2533                          'enum'        => array( 'open', 'closed' ),
2534                          'context'     => array( 'view', 'edit' ),
2535                      );
2536                      $schema['properties']['ping_status']    = array(
2537                          'description' => __( 'Whether or not the post can be pinged.' ),
2538                          'type'        => 'string',
2539                          'enum'        => array( 'open', 'closed' ),
2540                          'context'     => array( 'view', 'edit' ),
2541                      );
2542                      break;
2543  
2544                  case 'page-attributes':
2545                      $schema['properties']['menu_order'] = array(
2546                          'description' => __( 'The order of the post in relation to other posts.' ),
2547                          'type'        => 'integer',
2548                          'context'     => array( 'view', 'edit' ),
2549                      );
2550                      break;
2551  
2552                  case 'post-formats':
2553                      // Get the native post formats and remove the array keys.
2554                      $formats = array_values( get_post_format_slugs() );
2555  
2556                      $schema['properties']['format'] = array(
2557                          'description' => __( 'The format for the post.' ),
2558                          'type'        => 'string',
2559                          'enum'        => $formats,
2560                          'context'     => array( 'view', 'edit' ),
2561                      );
2562                      break;
2563  
2564                  case 'custom-fields':
2565                      $schema['properties']['meta'] = $this->meta->get_field_schema();
2566                      break;
2567  
2568              }
2569          }
2570  
2571          if ( 'post' === $this->post_type ) {
2572              $schema['properties']['sticky'] = array(
2573                  'description' => __( 'Whether or not the post should be treated as sticky.' ),
2574                  'type'        => 'boolean',
2575                  'context'     => array( 'view', 'edit' ),
2576              );
2577          }
2578  
2579          $schema['properties']['template'] = array(
2580              'description' => __( 'The theme file to use to display the post.' ),
2581              'type'        => 'string',
2582              'context'     => array( 'view', 'edit' ),
2583              'arg_options' => array(
2584                  'validate_callback' => array( $this, 'check_template' ),
2585              ),
2586          );
2587  
2588          $taxonomies = wp_list_filter( get_object_taxonomies( $this->post_type, 'objects' ), array( 'show_in_rest' => true ) );
2589  
2590          foreach ( $taxonomies as $taxonomy ) {
2591              $base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name;
2592  
2593              if ( array_key_exists( $base, $schema['properties'] ) ) {
2594                  $taxonomy_field_name_with_conflict = ! empty( $taxonomy->rest_base ) ? 'rest_base' : 'name';
2595                  _doing_it_wrong(
2596                      'register_taxonomy',
2597                      sprintf(
2598                          /* translators: 1: The taxonomy name, 2: The property name, either 'rest_base' or 'name', 3: The conflicting value. */
2599                          __( 'The "%1$s" taxonomy "%2$s" property (%3$s) conflicts with an existing property on the REST API Posts Controller. Specify a custom "rest_base" when registering the taxonomy to avoid this error.' ),
2600                          $taxonomy->name,
2601                          $taxonomy_field_name_with_conflict,
2602                          $base
2603                      ),
2604                      '5.4.0'
2605                  );
2606              }
2607  
2608              $schema['properties'][ $base ] = array(
2609                  /* translators: %s: Taxonomy name. */
2610                  'description' => sprintf( __( 'The terms assigned to the post in the %s taxonomy.' ), $taxonomy->name ),
2611                  'type'        => 'array',
2612                  'items'       => array(
2613                      'type' => 'integer',
2614                  ),
2615                  'context'     => array( 'view', 'edit' ),
2616              );
2617          }
2618  
2619          $schema_links = $this->get_schema_links();
2620  
2621          if ( $schema_links ) {
2622              $schema['links'] = $schema_links;
2623          }
2624  
2625          // Take a snapshot of which fields are in the schema pre-filtering.
2626          $schema_fields = array_keys( $schema['properties'] );
2627  
2628          /**
2629           * Filters the post's schema.
2630           *
2631           * The dynamic portion of the filter, `$this->post_type`, refers to the
2632           * post type slug for the controller.
2633           *
2634           * Possible hook names include:
2635           *
2636           *  - `rest_post_item_schema`
2637           *  - `rest_page_item_schema`
2638           *  - `rest_attachment_item_schema`
2639           *
2640           * @since 5.4.0
2641           *
2642           * @param array $schema Item schema data.
2643           */
2644          $schema = apply_filters( "rest_{$this->post_type}_item_schema", $schema );
2645  
2646          // Emit a _doing_it_wrong warning if user tries to add new properties using this filter.
2647          $new_fields = array_diff( array_keys( $schema['properties'] ), $schema_fields );
2648          if ( count( $new_fields ) > 0 ) {
2649              _doing_it_wrong(
2650                  __METHOD__,
2651                  sprintf(
2652                      /* translators: %s: register_rest_field */
2653                      __( 'Please use %s to add new schema properties.' ),
2654                      'register_rest_field'
2655                  ),
2656                  '5.4.0'
2657              );
2658          }
2659  
2660          $this->schema = $schema;
2661  
2662          return $this->add_additional_fields_schema( $this->schema );
2663      }
2664  
2665      /**
2666       * Retrieves Link Description Objects that should be added to the Schema for the posts collection.
2667       *
2668       * @since 4.9.8
2669       *
2670       * @return array
2671       */
2672  	protected function get_schema_links() {
2673  
2674          $href = rest_url( "{$this->namespace}/{$this->rest_base}/{id}" );
2675  
2676          $links = array();
2677  
2678          if ( 'attachment' !== $this->post_type ) {
2679              $links[] = array(
2680                  'rel'          => 'https://api.w.org/action-publish',
2681                  'title'        => __( 'The current user can publish this post.' ),
2682                  'href'         => $href,
2683                  'targetSchema' => array(
2684                      'type'       => 'object',
2685                      'properties' => array(
2686                          'status' => array(
2687                              'type' => 'string',
2688                              'enum' => array( 'publish', 'future' ),
2689                          ),
2690                      ),
2691                  ),
2692              );
2693          }
2694  
2695          $links[] = array(
2696              'rel'          => 'https://api.w.org/action-unfiltered-html',
2697              'title'        => __( 'The current user can post unfiltered HTML markup and JavaScript.' ),
2698              'href'         => $href,
2699              'targetSchema' => array(
2700                  'type'       => 'object',
2701                  'properties' => array(
2702                      'content' => array(
2703                          'raw' => array(
2704                              'type' => 'string',
2705                          ),
2706                      ),
2707                  ),
2708              ),
2709          );
2710  
2711          if ( 'post' === $this->post_type ) {
2712              $links[] = array(
2713                  'rel'          => 'https://api.w.org/action-sticky',
2714                  'title'        => __( 'The current user can sticky this post.' ),
2715                  'href'         => $href,
2716                  'targetSchema' => array(
2717                      'type'       => 'object',
2718                      'properties' => array(
2719                          'sticky' => array(
2720                              'type' => 'boolean',
2721                          ),
2722                      ),
2723                  ),
2724              );
2725          }
2726  
2727          if ( post_type_supports( $this->post_type, 'author' ) ) {
2728              $links[] = array(
2729                  'rel'          => 'https://api.w.org/action-assign-author',
2730                  'title'        => __( 'The current user can change the author on this post.' ),
2731                  'href'         => $href,
2732                  'targetSchema' => array(
2733                      'type'       => 'object',
2734                      'properties' => array(
2735                          'author' => array(
2736                              'type' => 'integer',
2737                          ),
2738                      ),
2739                  ),
2740              );
2741          }
2742  
2743          $taxonomies = wp_list_filter( get_object_taxonomies( $this->post_type, 'objects' ), array( 'show_in_rest' => true ) );
2744  
2745          foreach ( $taxonomies as $tax ) {
2746              $tax_base = ! empty( $tax->rest_base ) ? $tax->rest_base : $tax->name;
2747  
2748              /* translators: %s: Taxonomy name. */
2749              $assign_title = sprintf( __( 'The current user can assign terms in the %s taxonomy.' ), $tax->name );
2750              /* translators: %s: Taxonomy name. */
2751              $create_title = sprintf( __( 'The current user can create terms in the %s taxonomy.' ), $tax->name );
2752  
2753              $links[] = array(
2754                  'rel'          => 'https://api.w.org/action-assign-' . $tax_base,
2755                  'title'        => $assign_title,
2756                  'href'         => $href,
2757                  'targetSchema' => array(
2758                      'type'       => 'object',
2759                      'properties' => array(
2760                          $tax_base => array(
2761                              'type'  => 'array',
2762                              'items' => array(
2763                                  'type' => 'integer',
2764                              ),
2765                          ),
2766                      ),
2767                  ),
2768              );
2769  
2770              $links[] = array(
2771                  'rel'          => 'https://api.w.org/action-create-' . $tax_base,
2772                  'title'        => $create_title,
2773                  'href'         => $href,
2774                  'targetSchema' => array(
2775                      'type'       => 'object',
2776                      'properties' => array(
2777                          $tax_base => array(
2778                              'type'  => 'array',
2779                              'items' => array(
2780                                  'type' => 'integer',
2781                              ),
2782                          ),
2783                      ),
2784                  ),
2785              );
2786          }
2787  
2788          return $links;
2789      }
2790  
2791      /**
2792       * Retrieves the query params for the posts collection.
2793       *
2794       * @since 4.7.0
2795       * @since 5.4.0 The `tax_relation` query parameter was added.
2796       * @since 5.7.0 The `modified_after` and `modified_before` query parameters were added.
2797       *
2798       * @return array Collection parameters.
2799       */
2800  	public function get_collection_params() {
2801          $query_params = parent::get_collection_params();
2802  
2803          $query_params['context']['default'] = 'view';
2804  
2805          $query_params['after'] = array(
2806              'description' => __( 'Limit response to posts published after a given ISO8601 compliant date.' ),
2807              'type'        => 'string',
2808              'format'      => 'date-time',
2809          );
2810  
2811          $query_params['modified_after'] = array(
2812              'description' => __( 'Limit response to posts modified after a given ISO8601 compliant date.' ),
2813              'type'        => 'string',
2814              'format'      => 'date-time',
2815          );
2816  
2817          if ( post_type_supports( $this->post_type, 'author' ) ) {
2818              $query_params['author']         = array(
2819                  'description' => __( 'Limit result set to posts assigned to specific authors.' ),
2820                  'type'        => 'array',
2821                  'items'       => array(
2822                      'type' => 'integer',
2823                  ),
2824                  'default'     => array(),
2825              );
2826              $query_params['author_exclude'] = array(
2827                  'description' => __( 'Ensure result set excludes posts assigned to specific authors.' ),
2828                  'type'        => 'array',
2829                  'items'       => array(
2830                      'type' => 'integer',
2831                  ),
2832                  'default'     => array(),
2833              );
2834          }
2835  
2836          $query_params['before'] = array(
2837              'description' => __( 'Limit response to posts published before a given ISO8601 compliant date.' ),
2838              'type'        => 'string',
2839              'format'      => 'date-time',
2840          );
2841  
2842          $query_params['modified_before'] = array(
2843              'description' => __( 'Limit response to posts modified before a given ISO8601 compliant date.' ),
2844              'type'        => 'string',
2845              'format'      => 'date-time',
2846          );
2847  
2848          $query_params['exclude'] = array(
2849              'description' => __( 'Ensure result set excludes specific IDs.' ),
2850              'type'        => 'array',
2851              'items'       => array(
2852                  'type' => 'integer',
2853              ),
2854              'default'     => array(),
2855          );
2856  
2857          $query_params['include'] = array(
2858              'description' => __( 'Limit result set to specific IDs.' ),
2859              'type'        => 'array',
2860              'items'       => array(
2861                  'type' => 'integer',
2862              ),
2863              'default'     => array(),
2864          );
2865  
2866          if ( 'page' === $this->post_type || post_type_supports( $this->post_type, 'page-attributes' ) ) {
2867              $query_params['menu_order'] = array(
2868                  'description' => __( 'Limit result set to posts with a specific menu_order value.' ),
2869                  'type'        => 'integer',
2870              );
2871          }
2872  
2873          $query_params['offset'] = array(
2874              'description' => __( 'Offset the result set by a specific number of items.' ),
2875              'type'        => 'integer',
2876          );
2877  
2878          $query_params['order'] = array(
2879              'description' => __( 'Order sort attribute ascending or descending.' ),
2880              'type'        => 'string',
2881              'default'     => 'desc',
2882              'enum'        => array( 'asc', 'desc' ),
2883          );
2884  
2885          $query_params['orderby'] = array(
2886              'description' => __( 'Sort collection by post attribute.' ),
2887              'type'        => 'string',
2888              'default'     => 'date',
2889              'enum'        => array(
2890                  'author',
2891                  'date',
2892                  'id',
2893                  'include',
2894                  'modified',
2895                  'parent',
2896                  'relevance',
2897                  'slug',
2898                  'include_slugs',
2899                  'title',
2900              ),
2901          );
2902  
2903          if ( 'page' === $this->post_type || post_type_supports( $this->post_type, 'page-attributes' ) ) {
2904              $query_params['orderby']['enum'][] = 'menu_order';
2905          }
2906  
2907          $post_type = get_post_type_object( $this->post_type );
2908  
2909          if ( $post_type->hierarchical || 'attachment' === $this->post_type ) {
2910              $query_params['parent']         = array(
2911                  'description' => __( 'Limit result set to items with particular parent IDs.' ),
2912                  'type'        => 'array',
2913                  'items'       => array(
2914                      'type' => 'integer',
2915                  ),
2916                  'default'     => array(),
2917              );
2918              $query_params['parent_exclude'] = array(
2919                  'description' => __( 'Limit result set to all items except those of a particular parent ID.' ),
2920                  'type'        => 'array',
2921                  'items'       => array(
2922                      'type' => 'integer',
2923                  ),
2924                  'default'     => array(),
2925              );
2926          }
2927  
2928          $query_params['search_columns'] = array(
2929              'default'     => array(),
2930              'description' => __( 'Array of column names to be searched.' ),
2931              'type'        => 'array',
2932              'items'       => array(
2933                  'enum' => array( 'post_title', 'post_content', 'post_excerpt' ),
2934                  'type' => 'string',
2935              ),
2936          );
2937  
2938          $query_params['slug'] = array(
2939              'description' => __( 'Limit result set to posts with one or more specific slugs.' ),
2940              'type'        => 'array',
2941              'items'       => array(
2942                  'type' => 'string',
2943              ),
2944          );
2945  
2946          $query_params['status'] = array(
2947              'default'           => 'publish',
2948              'description'       => __( 'Limit result set to posts assigned one or more statuses.' ),
2949              'type'              => 'array',
2950              'items'             => array(
2951                  'enum' => array_merge( array_keys( get_post_stati() ), array( 'any' ) ),
2952                  'type' => 'string',
2953              ),
2954              'sanitize_callback' => array( $this, 'sanitize_post_statuses' ),
2955          );
2956  
2957          $query_params = $this->prepare_taxonomy_limit_schema( $query_params );
2958  
2959          if ( 'post' === $this->post_type ) {
2960              $query_params['sticky'] = array(
2961                  'description' => __( 'Limit result set to items that are sticky.' ),
2962                  'type'        => 'boolean',
2963              );
2964          }
2965  
2966          /**
2967           * Filters collection parameters for the posts controller.
2968           *
2969           * The dynamic part of the filter `$this->post_type` refers to the post
2970           * type slug for the controller.
2971           *
2972           * This filter registers the collection parameter, but does not map the
2973           * collection parameter to an internal WP_Query parameter. Use the
2974           * `rest_{$this->post_type}_query` filter to set WP_Query parameters.
2975           *
2976           * @since 4.7.0
2977           *
2978           * @param array        $query_params JSON Schema-formatted collection parameters.
2979           * @param WP_Post_Type $post_type    Post type object.
2980           */
2981          return apply_filters( "rest_{$this->post_type}_collection_params", $query_params, $post_type );
2982      }
2983  
2984      /**
2985       * Sanitizes and validates the list of post statuses, including whether the
2986       * user can query private statuses.
2987       *
2988       * @since 4.7.0
2989       *
2990       * @param string|array    $statuses  One or more post statuses.
2991       * @param WP_REST_Request $request   Full details about the request.
2992       * @param string          $parameter Additional parameter to pass to validation.
2993       * @return array|WP_Error A list of valid statuses, otherwise WP_Error object.
2994       */
2995  	public function sanitize_post_statuses( $statuses, $request, $parameter ) {
2996          $statuses = wp_parse_slug_list( $statuses );
2997  
2998          // The default status is different in WP_REST_Attachments_Controller.
2999          $attributes     = $request->get_attributes();
3000          $default_status = $attributes['args']['status']['default'];
3001  
3002          foreach ( $statuses as $status ) {
3003              if ( $status === $default_status ) {
3004                  continue;
3005              }
3006  
3007              $post_type_obj = get_post_type_object( $this->post_type );
3008  
3009              if ( current_user_can( $post_type_obj->cap->edit_posts ) || 'private' === $status && current_user_can( $post_type_obj->cap->read_private_posts ) ) {
3010                  $result = rest_validate_request_arg( $status, $request, $parameter );
3011                  if ( is_wp_error( $result ) ) {
3012                      return $result;
3013                  }
3014              } else {
3015                  return new WP_Error(
3016                      'rest_forbidden_status',
3017                      __( 'Status is forbidden.' ),
3018                      array( 'status' => rest_authorization_required_code() )
3019                  );
3020              }
3021          }
3022  
3023          return $statuses;
3024      }
3025  
3026      /**
3027       * Prepares the 'tax_query' for a collection of posts.
3028       *
3029       * @since 5.7.0
3030       *
3031       * @param array           $args    WP_Query arguments.
3032       * @param WP_REST_Request $request Full details about the request.
3033       * @return array Updated query arguments.
3034       */
3035  	private function prepare_tax_query( array $args, WP_REST_Request $request ) {
3036          $relation = $request['tax_relation'];
3037  
3038          if ( $relation ) {
3039              $args['tax_query'] = array( 'relation' => $relation );
3040          }
3041  
3042          $taxonomies = wp_list_filter(
3043              get_object_taxonomies( $this->post_type, 'objects' ),
3044              array( 'show_in_rest' => true )
3045          );
3046  
3047          foreach ( $taxonomies as $taxonomy ) {
3048              $base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name;
3049  
3050              $tax_include = $request[ $base ];
3051              $tax_exclude = $request[ $base . '_exclude' ];
3052  
3053              if ( $tax_include ) {
3054                  $terms            = array();
3055                  $include_children = false;
3056                  $operator         = 'IN';
3057  
3058                  if ( rest_is_array( $tax_include ) ) {
3059                      $terms = $tax_include;
3060                  } elseif ( rest_is_object( $tax_include ) ) {
3061                      $terms            = empty( $tax_include['terms'] ) ? array() : $tax_include['terms'];
3062                      $include_children = ! empty( $tax_include['include_children'] );
3063  
3064                      if ( isset( $tax_include['operator'] ) && 'AND' === $tax_include['operator'] ) {
3065                          $operator = 'AND';
3066                      }
3067                  }
3068  
3069                  if ( $terms ) {
3070                      $args['tax_query'][] = array(
3071                          'taxonomy'         => $taxonomy->name,
3072                          'field'            => 'term_id',
3073                          'terms'            => $terms,
3074                          'include_children' => $include_children,
3075                          'operator'         => $operator,
3076                      );
3077                  }
3078              }
3079  
3080              if ( $tax_exclude ) {
3081                  $terms            = array();
3082                  $include_children = false;
3083  
3084                  if ( rest_is_array( $tax_exclude ) ) {
3085                      $terms = $tax_exclude;
3086                  } elseif ( rest_is_object( $tax_exclude ) ) {
3087                      $terms            = empty( $tax_exclude['terms'] ) ? array() : $tax_exclude['terms'];
3088                      $include_children = ! empty( $tax_exclude['include_children'] );
3089                  }
3090  
3091                  if ( $terms ) {
3092                      $args['tax_query'][] = array(
3093                          'taxonomy'         => $taxonomy->name,
3094                          'field'            => 'term_id',
3095                          'terms'            => $terms,
3096                          'include_children' => $include_children,
3097                          'operator'         => 'NOT IN',
3098                      );
3099                  }
3100              }
3101          }
3102  
3103          return $args;
3104      }
3105  
3106      /**
3107       * Prepares the collection schema for including and excluding items by terms.
3108       *
3109       * @since 5.7.0
3110       *
3111       * @param array $query_params Collection schema.
3112       * @return array Updated schema.
3113       */
3114  	private function prepare_taxonomy_limit_schema( array $query_params ) {
3115          $taxonomies = wp_list_filter( get_object_taxonomies( $this->post_type, 'objects' ), array( 'show_in_rest' => true ) );
3116  
3117          if ( ! $taxonomies ) {
3118              return $query_params;
3119          }
3120  
3121          $query_params['tax_relation'] = array(
3122              'description' => __( 'Limit result set based on relationship between multiple taxonomies.' ),
3123              'type'        => 'string',
3124              'enum'        => array( 'AND', 'OR' ),
3125          );
3126  
3127          $limit_schema = array(
3128              'type'  => array( 'object', 'array' ),
3129              'oneOf' => array(
3130                  array(
3131                      'title'       => __( 'Term ID List' ),
3132                      'description' => __( 'Match terms with the listed IDs.' ),
3133                      'type'        => 'array',
3134                      'items'       => array(
3135                          'type' => 'integer',
3136                      ),
3137                  ),
3138                  array(
3139                      'title'                => __( 'Term ID Taxonomy Query' ),
3140                      'description'          => __( 'Perform an advanced term query.' ),
3141                      'type'                 => 'object',
3142                      'properties'           => array(
3143                          'terms'            => array(
3144                              'description' => __( 'Term IDs.' ),
3145                              'type'        => 'array',
3146                              'items'       => array(
3147                                  'type' => 'integer',
3148                              ),
3149                              'default'     => array(),
3150                          ),
3151                          'include_children' => array(
3152                              'description' => __( 'Whether to include child terms in the terms limiting the result set.' ),
3153                              'type'        => 'boolean',
3154                              'default'     => false,
3155                          ),
3156                      ),
3157                      'additionalProperties' => false,
3158                  ),
3159              ),
3160          );
3161  
3162          $include_schema = array_merge(
3163              array(
3164                  /* translators: %s: Taxonomy name. */
3165                  'description' => __( 'Limit result set to items with specific terms assigned in the %s taxonomy.' ),
3166              ),
3167              $limit_schema
3168          );
3169          // 'operator' is supported only for 'include' queries.
3170          $include_schema['oneOf'][1]['properties']['operator'] = array(
3171              'description' => __( 'Whether items must be assigned all or any of the specified terms.' ),
3172              'type'        => 'string',
3173              'enum'        => array( 'AND', 'OR' ),
3174              'default'     => 'OR',
3175          );
3176  
3177          $exclude_schema = array_merge(
3178              array(
3179                  /* translators: %s: Taxonomy name. */
3180                  'description' => __( 'Limit result set to items except those with specific terms assigned in the %s taxonomy.' ),
3181              ),
3182              $limit_schema
3183          );
3184  
3185          foreach ( $taxonomies as $taxonomy ) {
3186              $base         = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name;
3187              $base_exclude = $base . '_exclude';
3188  
3189              $query_params[ $base ]                = $include_schema;
3190              $query_params[ $base ]['description'] = sprintf( $query_params[ $base ]['description'], $base );
3191  
3192              $query_params[ $base_exclude ]                = $exclude_schema;
3193              $query_params[ $base_exclude ]['description'] = sprintf( $query_params[ $base_exclude ]['description'], $base );
3194  
3195              if ( ! $taxonomy->hierarchical ) {
3196                  unset( $query_params[ $base ]['oneOf'][1]['properties']['include_children'] );
3197                  unset( $query_params[ $base_exclude ]['oneOf'][1]['properties']['include_children'] );
3198              }
3199          }
3200  
3201          return $query_params;
3202      }
3203  }


Generated : Thu May 9 08:20:02 2024 Cross-referenced by PHPXref