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


Generated: Tue Sep 17 01:00:03 2019 Cross-referenced by PHPXref 0.7.1