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


Generated: Sat Nov 28 01:00:03 2020 Cross-referenced by PHPXref 0.7.1