[ Index ]

PHP Cross Reference of WordPress

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


Generated: Tue Oct 19 01:00:04 2021 Cross-referenced by PHPXref 0.7.1