[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

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              if ( $template = get_page_template_slug( $post->ID ) ) {
1583                  $data['template'] = $template;
1584              } else {
1585                  $data['template'] = '';
1586              }
1587          }
1588  
1589          if ( in_array( 'format', $fields, true ) ) {
1590              $data['format'] = get_post_format( $post->ID );
1591  
1592              // Fill in blank post format.
1593              if ( empty( $data['format'] ) ) {
1594                  $data['format'] = 'standard';
1595              }
1596          }
1597  
1598          if ( in_array( 'meta', $fields, true ) ) {
1599              $data['meta'] = $this->meta->get_value( $post->ID, $request );
1600          }
1601  
1602          $taxonomies = wp_list_filter( get_object_taxonomies( $this->post_type, 'objects' ), array( 'show_in_rest' => true ) );
1603  
1604          foreach ( $taxonomies as $taxonomy ) {
1605              $base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name;
1606  
1607              if ( in_array( $base, $fields, true ) ) {
1608                  $terms         = get_the_terms( $post, $taxonomy->name );
1609                  $data[ $base ] = $terms ? array_values( wp_list_pluck( $terms, 'term_id' ) ) : array();
1610              }
1611          }
1612  
1613          $post_type_obj = get_post_type_object( $post->post_type );
1614          if ( is_post_type_viewable( $post_type_obj ) && $post_type_obj->public ) {
1615  
1616              if ( ! function_exists( 'get_sample_permalink' ) ) {
1617                  require_once  ABSPATH . 'wp-admin/includes/post.php';
1618              }
1619  
1620              $sample_permalink = get_sample_permalink( $post->ID, $post->post_title, '' );
1621  
1622              if ( in_array( 'permalink_template', $fields, true ) ) {
1623                  $data['permalink_template'] = $sample_permalink[0];
1624              }
1625              if ( in_array( 'generated_slug', $fields, true ) ) {
1626                  $data['generated_slug'] = $sample_permalink[1];
1627              }
1628          }
1629  
1630          $context = ! empty( $request['context'] ) ? $request['context'] : 'view';
1631          $data    = $this->add_additional_fields_to_object( $data, $request );
1632          $data    = $this->filter_response_by_context( $data, $context );
1633  
1634          // Wrap the data in a response object.
1635          $response = rest_ensure_response( $data );
1636  
1637          $links = $this->prepare_links( $post );
1638          $response->add_links( $links );
1639  
1640          if ( ! empty( $links['self']['href'] ) ) {
1641              $actions = $this->get_available_actions( $post, $request );
1642  
1643              $self = $links['self']['href'];
1644  
1645              foreach ( $actions as $rel ) {
1646                  $response->add_link( $rel, $self );
1647              }
1648          }
1649  
1650          /**
1651           * Filters the post data for a response.
1652           *
1653           * The dynamic portion of the hook name, `$this->post_type`, refers to the post type slug.
1654           *
1655           * @since 4.7.0
1656           *
1657           * @param WP_REST_Response $response The response object.
1658           * @param WP_Post          $post     Post object.
1659           * @param WP_REST_Request  $request  Request object.
1660           */
1661          return apply_filters( "rest_prepare_{$this->post_type}", $response, $post, $request );
1662      }
1663  
1664      /**
1665       * Overwrites the default protected title format.
1666       *
1667       * By default, WordPress will show password protected posts with a title of
1668       * "Protected: %s", as the REST API communicates the protected status of a post
1669       * in a machine readable format, we remove the "Protected: " prefix.
1670       *
1671       * @since 4.7.0
1672       *
1673       * @return string Protected title format.
1674       */
1675  	public function protected_title_format() {
1676          return '%s';
1677      }
1678  
1679      /**
1680       * Prepares links for the request.
1681       *
1682       * @since 4.7.0
1683       *
1684       * @param WP_Post $post Post object.
1685       * @return array Links for the given post.
1686       */
1687  	protected function prepare_links( $post ) {
1688          $base = sprintf( '%s/%s', $this->namespace, $this->rest_base );
1689  
1690          // Entity meta.
1691          $links = array(
1692              'self'       => array(
1693                  'href' => rest_url( trailingslashit( $base ) . $post->ID ),
1694              ),
1695              'collection' => array(
1696                  'href' => rest_url( $base ),
1697              ),
1698              'about'      => array(
1699                  'href' => rest_url( 'wp/v2/types/' . $this->post_type ),
1700              ),
1701          );
1702  
1703          if ( ( in_array( $post->post_type, array( 'post', 'page' ), true ) || post_type_supports( $post->post_type, 'author' ) )
1704              && ! empty( $post->post_author ) ) {
1705              $links['author'] = array(
1706                  'href'       => rest_url( 'wp/v2/users/' . $post->post_author ),
1707                  'embeddable' => true,
1708              );
1709          }
1710  
1711          if ( in_array( $post->post_type, array( 'post', 'page' ), true ) || post_type_supports( $post->post_type, 'comments' ) ) {
1712              $replies_url = rest_url( 'wp/v2/comments' );
1713              $replies_url = add_query_arg( 'post', $post->ID, $replies_url );
1714  
1715              $links['replies'] = array(
1716                  'href'       => $replies_url,
1717                  'embeddable' => true,
1718              );
1719          }
1720  
1721          if ( in_array( $post->post_type, array( 'post', 'page' ), true ) || post_type_supports( $post->post_type, 'revisions' ) ) {
1722              $revisions       = wp_get_post_revisions( $post->ID, array( 'fields' => 'ids' ) );
1723              $revisions_count = count( $revisions );
1724  
1725              $links['version-history'] = array(
1726                  'href'  => rest_url( trailingslashit( $base ) . $post->ID . '/revisions' ),
1727                  'count' => $revisions_count,
1728              );
1729  
1730              if ( $revisions_count > 0 ) {
1731                  $last_revision = array_shift( $revisions );
1732  
1733                  $links['predecessor-version'] = array(
1734                      'href' => rest_url( trailingslashit( $base ) . $post->ID . '/revisions/' . $last_revision ),
1735                      'id'   => $last_revision,
1736                  );
1737              }
1738          }
1739  
1740          $post_type_obj = get_post_type_object( $post->post_type );
1741  
1742          if ( $post_type_obj->hierarchical && ! empty( $post->post_parent ) ) {
1743              $links['up'] = array(
1744                  'href'       => rest_url( trailingslashit( $base ) . (int) $post->post_parent ),
1745                  'embeddable' => true,
1746              );
1747          }
1748  
1749          // If we have a featured media, add that.
1750          if ( $featured_media = get_post_thumbnail_id( $post->ID ) ) {
1751              $image_url = rest_url( 'wp/v2/media/' . $featured_media );
1752  
1753              $links['https://api.w.org/featuredmedia'] = array(
1754                  'href'       => $image_url,
1755                  'embeddable' => true,
1756              );
1757          }
1758  
1759          if ( ! in_array( $post->post_type, array( 'attachment', 'nav_menu_item', 'revision' ), true ) ) {
1760              $attachments_url = rest_url( 'wp/v2/media' );
1761              $attachments_url = add_query_arg( 'parent', $post->ID, $attachments_url );
1762  
1763              $links['https://api.w.org/attachment'] = array(
1764                  'href' => $attachments_url,
1765              );
1766          }
1767  
1768          $taxonomies = get_object_taxonomies( $post->post_type );
1769  
1770          if ( ! empty( $taxonomies ) ) {
1771              $links['https://api.w.org/term'] = array();
1772  
1773              foreach ( $taxonomies as $tax ) {
1774                  $taxonomy_obj = get_taxonomy( $tax );
1775  
1776                  // Skip taxonomies that are not public.
1777                  if ( empty( $taxonomy_obj->show_in_rest ) ) {
1778                      continue;
1779                  }
1780  
1781                  $tax_base = ! empty( $taxonomy_obj->rest_base ) ? $taxonomy_obj->rest_base : $tax;
1782  
1783                  $terms_url = add_query_arg(
1784                      'post',
1785                      $post->ID,
1786                      rest_url( 'wp/v2/' . $tax_base )
1787                  );
1788  
1789                  $links['https://api.w.org/term'][] = array(
1790                      'href'       => $terms_url,
1791                      'taxonomy'   => $tax,
1792                      'embeddable' => true,
1793                  );
1794              }
1795          }
1796  
1797          return $links;
1798      }
1799  
1800      /**
1801       * Get the link relations available for the post and current user.
1802       *
1803       * @since 4.9.8
1804       *
1805       * @param WP_Post $post Post object.
1806       * @param WP_REST_Request Request object.
1807       *
1808       * @return array List of link relations.
1809       */
1810  	protected function get_available_actions( $post, $request ) {
1811  
1812          if ( 'edit' !== $request['context'] ) {
1813              return array();
1814          }
1815  
1816          $rels = array();
1817  
1818          $post_type = get_post_type_object( $post->post_type );
1819  
1820          if ( 'attachment' !== $this->post_type && current_user_can( $post_type->cap->publish_posts ) ) {
1821              $rels[] = 'https://api.w.org/action-publish';
1822          }
1823  
1824          if ( current_user_can( 'unfiltered_html' ) ) {
1825              $rels[] = 'https://api.w.org/action-unfiltered-html';
1826          }
1827  
1828          if ( 'post' === $post_type->name ) {
1829              if ( current_user_can( $post_type->cap->edit_others_posts ) && current_user_can( $post_type->cap->publish_posts ) ) {
1830                  $rels[] = 'https://api.w.org/action-sticky';
1831              }
1832          }
1833  
1834          if ( post_type_supports( $post_type->name, 'author' ) ) {
1835              if ( current_user_can( $post_type->cap->edit_others_posts ) ) {
1836                  $rels[] = 'https://api.w.org/action-assign-author';
1837              }
1838          }
1839  
1840          $taxonomies = wp_list_filter( get_object_taxonomies( $this->post_type, 'objects' ), array( 'show_in_rest' => true ) );
1841  
1842          foreach ( $taxonomies as $tax ) {
1843              $tax_base   = ! empty( $tax->rest_base ) ? $tax->rest_base : $tax->name;
1844              $create_cap = is_taxonomy_hierarchical( $tax->name ) ? $tax->cap->edit_terms : $tax->cap->assign_terms;
1845  
1846              if ( current_user_can( $create_cap ) ) {
1847                  $rels[] = 'https://api.w.org/action-create-' . $tax_base;
1848              }
1849  
1850              if ( current_user_can( $tax->cap->assign_terms ) ) {
1851                  $rels[] = 'https://api.w.org/action-assign-' . $tax_base;
1852              }
1853          }
1854  
1855          return $rels;
1856      }
1857  
1858      /**
1859       * Retrieves the post's schema, conforming to JSON Schema.
1860       *
1861       * @since 4.7.0
1862       *
1863       * @return array Item schema data.
1864       */
1865  	public function get_item_schema() {
1866  
1867          $schema = array(
1868              '$schema'    => 'http://json-schema.org/draft-04/schema#',
1869              'title'      => $this->post_type,
1870              'type'       => 'object',
1871              // Base properties for every Post.
1872              'properties' => array(
1873                  'date'         => array(
1874                      'description' => __( "The date the object was published, in the site's timezone." ),
1875                      'type'        => 'string',
1876                      'format'      => 'date-time',
1877                      'context'     => array( 'view', 'edit', 'embed' ),
1878                  ),
1879                  'date_gmt'     => array(
1880                      'description' => __( 'The date the object was published, as GMT.' ),
1881                      'type'        => 'string',
1882                      'format'      => 'date-time',
1883                      'context'     => array( 'view', 'edit' ),
1884                  ),
1885                  'guid'         => array(
1886                      'description' => __( 'The globally unique identifier for the object.' ),
1887                      'type'        => 'object',
1888                      'context'     => array( 'view', 'edit' ),
1889                      'readonly'    => true,
1890                      'properties'  => array(
1891                          'raw'      => array(
1892                              'description' => __( 'GUID for the object, as it exists in the database.' ),
1893                              'type'        => 'string',
1894                              'context'     => array( 'edit' ),
1895                              'readonly'    => true,
1896                          ),
1897                          'rendered' => array(
1898                              'description' => __( 'GUID for the object, transformed for display.' ),
1899                              'type'        => 'string',
1900                              'context'     => array( 'view', 'edit' ),
1901                              'readonly'    => true,
1902                          ),
1903                      ),
1904                  ),
1905                  'id'           => array(
1906                      'description' => __( 'Unique identifier for the object.' ),
1907                      'type'        => 'integer',
1908                      'context'     => array( 'view', 'edit', 'embed' ),
1909                      'readonly'    => true,
1910                  ),
1911                  'link'         => array(
1912                      'description' => __( 'URL to the object.' ),
1913                      'type'        => 'string',
1914                      'format'      => 'uri',
1915                      'context'     => array( 'view', 'edit', 'embed' ),
1916                      'readonly'    => true,
1917                  ),
1918                  'modified'     => array(
1919                      'description' => __( "The date the object was last modified, in the site's timezone." ),
1920                      'type'        => 'string',
1921                      'format'      => 'date-time',
1922                      'context'     => array( 'view', 'edit' ),
1923                      'readonly'    => true,
1924                  ),
1925                  'modified_gmt' => array(
1926                      'description' => __( 'The date the object was last modified, as GMT.' ),
1927                      'type'        => 'string',
1928                      'format'      => 'date-time',
1929                      'context'     => array( 'view', 'edit' ),
1930                      'readonly'    => true,
1931                  ),
1932                  'slug'         => array(
1933                      'description' => __( 'An alphanumeric identifier for the object unique to its type.' ),
1934                      'type'        => 'string',
1935                      'context'     => array( 'view', 'edit', 'embed' ),
1936                      'arg_options' => array(
1937                          'sanitize_callback' => array( $this, 'sanitize_slug' ),
1938                      ),
1939                  ),
1940                  'status'       => array(
1941                      'description' => __( 'A named status for the object.' ),
1942                      'type'        => 'string',
1943                      'enum'        => array_keys( get_post_stati( array( 'internal' => false ) ) ),
1944                      'context'     => array( 'view', 'edit' ),
1945                  ),
1946                  'type'         => array(
1947                      'description' => __( 'Type of Post for the object.' ),
1948                      'type'        => 'string',
1949                      'context'     => array( 'view', 'edit', 'embed' ),
1950                      'readonly'    => true,
1951                  ),
1952                  'password'     => array(
1953                      'description' => __( 'A password to protect access to the content and excerpt.' ),
1954                      'type'        => 'string',
1955                      'context'     => array( 'edit' ),
1956                  ),
1957              ),
1958          );
1959  
1960          $post_type_obj = get_post_type_object( $this->post_type );
1961          if ( is_post_type_viewable( $post_type_obj ) && $post_type_obj->public ) {
1962              $schema['properties']['permalink_template'] = array(
1963                  'description' => __( 'Permalink template for the object.' ),
1964                  'type'        => 'string',
1965                  'context'     => array( 'edit' ),
1966                  'readonly'    => true,
1967              );
1968  
1969              $schema['properties']['generated_slug'] = array(
1970                  'description' => __( 'Slug automatically generated from the object title.' ),
1971                  'type'        => 'string',
1972                  'context'     => array( 'edit' ),
1973                  'readonly'    => true,
1974              );
1975          }
1976  
1977          if ( $post_type_obj->hierarchical ) {
1978              $schema['properties']['parent'] = array(
1979                  'description' => __( 'The ID for the parent of the object.' ),
1980                  'type'        => 'integer',
1981                  'context'     => array( 'view', 'edit' ),
1982              );
1983          }
1984  
1985          $post_type_attributes = array(
1986              'title',
1987              'editor',
1988              'author',
1989              'excerpt',
1990              'thumbnail',
1991              'comments',
1992              'revisions',
1993              'page-attributes',
1994              'post-formats',
1995              'custom-fields',
1996          );
1997          $fixed_schemas        = array(
1998              'post'       => array(
1999                  'title',
2000                  'editor',
2001                  'author',
2002                  'excerpt',
2003                  'thumbnail',
2004                  'comments',
2005                  'revisions',
2006                  'post-formats',
2007                  'custom-fields',
2008              ),
2009              'page'       => array(
2010                  'title',
2011                  'editor',
2012                  'author',
2013                  'excerpt',
2014                  'thumbnail',
2015                  'comments',
2016                  'revisions',
2017                  'page-attributes',
2018                  'custom-fields',
2019              ),
2020              'attachment' => array(
2021                  'title',
2022                  'author',
2023                  'comments',
2024                  'revisions',
2025                  'custom-fields',
2026              ),
2027          );
2028          foreach ( $post_type_attributes as $attribute ) {
2029              if ( isset( $fixed_schemas[ $this->post_type ] ) && ! in_array( $attribute, $fixed_schemas[ $this->post_type ], true ) ) {
2030                  continue;
2031              } elseif ( ! isset( $fixed_schemas[ $this->post_type ] ) && ! post_type_supports( $this->post_type, $attribute ) ) {
2032                  continue;
2033              }
2034  
2035              switch ( $attribute ) {
2036  
2037                  case 'title':
2038                      $schema['properties']['title'] = array(
2039                          'description' => __( 'The title for the object.' ),
2040                          'type'        => 'object',
2041                          'context'     => array( 'view', 'edit', 'embed' ),
2042                          'arg_options' => array(
2043                              'sanitize_callback' => null, // Note: sanitization implemented in self::prepare_item_for_database()
2044                              'validate_callback' => null, // Note: validation implemented in self::prepare_item_for_database()
2045                          ),
2046                          'properties'  => array(
2047                              'raw'      => array(
2048                                  'description' => __( 'Title for the object, as it exists in the database.' ),
2049                                  'type'        => 'string',
2050                                  'context'     => array( 'edit' ),
2051                              ),
2052                              'rendered' => array(
2053                                  'description' => __( 'HTML title for the object, transformed for display.' ),
2054                                  'type'        => 'string',
2055                                  'context'     => array( 'view', 'edit', 'embed' ),
2056                                  'readonly'    => true,
2057                              ),
2058                          ),
2059                      );
2060                      break;
2061  
2062                  case 'editor':
2063                      $schema['properties']['content'] = array(
2064                          'description' => __( 'The content for the object.' ),
2065                          'type'        => 'object',
2066                          'context'     => array( 'view', 'edit' ),
2067                          'arg_options' => array(
2068                              'sanitize_callback' => null, // Note: sanitization implemented in self::prepare_item_for_database()
2069                              'validate_callback' => null, // Note: validation implemented in self::prepare_item_for_database()
2070                          ),
2071                          'properties'  => array(
2072                              'raw'           => array(
2073                                  'description' => __( 'Content for the object, as it exists in the database.' ),
2074                                  'type'        => 'string',
2075                                  'context'     => array( 'edit' ),
2076                              ),
2077                              'rendered'      => array(
2078                                  'description' => __( 'HTML content for the object, transformed for display.' ),
2079                                  'type'        => 'string',
2080                                  'context'     => array( 'view', 'edit' ),
2081                                  'readonly'    => true,
2082                              ),
2083                              'block_version' => array(
2084                                  'description' => __( 'Version of the content block format used by the object.' ),
2085                                  'type'        => 'integer',
2086                                  'context'     => array( 'edit' ),
2087                                  'readonly'    => true,
2088                              ),
2089                              'protected'     => array(
2090                                  'description' => __( 'Whether the content is protected with a password.' ),
2091                                  'type'        => 'boolean',
2092                                  'context'     => array( 'view', 'edit', 'embed' ),
2093                                  'readonly'    => true,
2094                              ),
2095                          ),
2096                      );
2097                      break;
2098  
2099                  case 'author':
2100                      $schema['properties']['author'] = array(
2101                          'description' => __( 'The ID for the author of the object.' ),
2102                          'type'        => 'integer',
2103                          'context'     => array( 'view', 'edit', 'embed' ),
2104                      );
2105                      break;
2106  
2107                  case 'excerpt':
2108                      $schema['properties']['excerpt'] = array(
2109                          'description' => __( 'The excerpt for the object.' ),
2110                          'type'        => 'object',
2111                          'context'     => array( 'view', 'edit', 'embed' ),
2112                          'arg_options' => array(
2113                              'sanitize_callback' => null, // Note: sanitization implemented in self::prepare_item_for_database()
2114                              'validate_callback' => null, // Note: validation implemented in self::prepare_item_for_database()
2115                          ),
2116                          'properties'  => array(
2117                              'raw'       => array(
2118                                  'description' => __( 'Excerpt for the object, as it exists in the database.' ),
2119                                  'type'        => 'string',
2120                                  'context'     => array( 'edit' ),
2121                              ),
2122                              'rendered'  => array(
2123                                  'description' => __( 'HTML excerpt for the object, transformed for display.' ),
2124                                  'type'        => 'string',
2125                                  'context'     => array( 'view', 'edit', 'embed' ),
2126                                  'readonly'    => true,
2127                              ),
2128                              'protected' => array(
2129                                  'description' => __( 'Whether the excerpt is protected with a password.' ),
2130                                  'type'        => 'boolean',
2131                                  'context'     => array( 'view', 'edit', 'embed' ),
2132                                  'readonly'    => true,
2133                              ),
2134                          ),
2135                      );
2136                      break;
2137  
2138                  case 'thumbnail':
2139                      $schema['properties']['featured_media'] = array(
2140                          'description' => __( 'The ID of the featured media for the object.' ),
2141                          'type'        => 'integer',
2142                          'context'     => array( 'view', 'edit', 'embed' ),
2143                      );
2144                      break;
2145  
2146                  case 'comments':
2147                      $schema['properties']['comment_status'] = array(
2148                          'description' => __( 'Whether or not comments are open on the object.' ),
2149                          'type'        => 'string',
2150                          'enum'        => array( 'open', 'closed' ),
2151                          'context'     => array( 'view', 'edit' ),
2152                      );
2153                      $schema['properties']['ping_status']    = array(
2154                          'description' => __( 'Whether or not the object can be pinged.' ),
2155                          'type'        => 'string',
2156                          'enum'        => array( 'open', 'closed' ),
2157                          'context'     => array( 'view', 'edit' ),
2158                      );
2159                      break;
2160  
2161                  case 'page-attributes':
2162                      $schema['properties']['menu_order'] = array(
2163                          'description' => __( 'The order of the object in relation to other object of its type.' ),
2164                          'type'        => 'integer',
2165                          'context'     => array( 'view', 'edit' ),
2166                      );
2167                      break;
2168  
2169                  case 'post-formats':
2170                      // Get the native post formats and remove the array keys.
2171                      $formats = array_values( get_post_format_slugs() );
2172  
2173                      $schema['properties']['format'] = array(
2174                          'description' => __( 'The format for the object.' ),
2175                          'type'        => 'string',
2176                          'enum'        => $formats,
2177                          'context'     => array( 'view', 'edit' ),
2178                      );
2179                      break;
2180  
2181                  case 'custom-fields':
2182                      $schema['properties']['meta'] = $this->meta->get_field_schema();
2183                      break;
2184  
2185              }
2186          }
2187  
2188          if ( 'post' === $this->post_type ) {
2189              $schema['properties']['sticky'] = array(
2190                  'description' => __( 'Whether or not the object should be treated as sticky.' ),
2191                  'type'        => 'boolean',
2192                  'context'     => array( 'view', 'edit' ),
2193              );
2194          }
2195  
2196          $schema['properties']['template'] = array(
2197              'description' => __( 'The theme file to use to display the object.' ),
2198              'type'        => 'string',
2199              'context'     => array( 'view', 'edit' ),
2200              'arg_options' => array(
2201                  'validate_callback' => array( $this, 'check_template' ),
2202              ),
2203          );
2204  
2205          $taxonomies = wp_list_filter( get_object_taxonomies( $this->post_type, 'objects' ), array( 'show_in_rest' => true ) );
2206          foreach ( $taxonomies as $taxonomy ) {
2207              $base                          = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name;
2208              $schema['properties'][ $base ] = array(
2209                  /* translators: %s: taxonomy name */
2210                  'description' => sprintf( __( 'The terms assigned to the object in the %s taxonomy.' ), $taxonomy->name ),
2211                  'type'        => 'array',
2212                  'items'       => array(
2213                      'type' => 'integer',
2214                  ),
2215                  'context'     => array( 'view', 'edit' ),
2216              );
2217          }
2218  
2219          $schema_links = $this->get_schema_links();
2220  
2221          if ( $schema_links ) {
2222              $schema['links'] = $schema_links;
2223          }
2224  
2225          return $this->add_additional_fields_schema( $schema );
2226      }
2227  
2228      /**
2229       * Retrieve Link Description Objects that should be added to the Schema for the posts collection.
2230       *
2231       * @since 4.9.8
2232       *
2233       * @return array
2234       */
2235  	protected function get_schema_links() {
2236  
2237          $href = rest_url( "{$this->namespace}/{$this->rest_base}/{id}" );
2238  
2239          $links = array();
2240  
2241          if ( 'attachment' !== $this->post_type ) {
2242              $links[] = array(
2243                  'rel'          => 'https://api.w.org/action-publish',
2244                  'title'        => __( 'The current user can publish this post.' ),
2245                  'href'         => $href,
2246                  'targetSchema' => array(
2247                      'type'       => 'object',
2248                      'properties' => array(
2249                          'status' => array(
2250                              'type' => 'string',
2251                              'enum' => array( 'publish', 'future' ),
2252                          ),
2253                      ),
2254                  ),
2255              );
2256          }
2257  
2258          $links[] = array(
2259              'rel'          => 'https://api.w.org/action-unfiltered-html',
2260              'title'        => __( 'The current user can post unfiltered HTML markup and JavaScript.' ),
2261              'href'         => $href,
2262              'targetSchema' => array(
2263                  'type'       => 'object',
2264                  'properties' => array(
2265                      'content' => array(
2266                          'raw' => array(
2267                              'type' => 'string',
2268                          ),
2269                      ),
2270                  ),
2271              ),
2272          );
2273  
2274          if ( 'post' === $this->post_type ) {
2275              $links[] = array(
2276                  'rel'          => 'https://api.w.org/action-sticky',
2277                  'title'        => __( 'The current user can sticky this post.' ),
2278                  'href'         => $href,
2279                  'targetSchema' => array(
2280                      'type'       => 'object',
2281                      'properties' => array(
2282                          'sticky' => array(
2283                              'type' => 'boolean',
2284                          ),
2285                      ),
2286                  ),
2287              );
2288          }
2289  
2290          if ( post_type_supports( $this->post_type, 'author' ) ) {
2291              $links[] = array(
2292                  'rel'          => 'https://api.w.org/action-assign-author',
2293                  'title'        => __( 'The current user can change the author on this post.' ),
2294                  'href'         => $href,
2295                  'targetSchema' => array(
2296                      'type'       => 'object',
2297                      'properties' => array(
2298                          'author' => array(
2299                              'type' => 'integer',
2300                          ),
2301                      ),
2302                  ),
2303              );
2304          }
2305  
2306          $taxonomies = wp_list_filter( get_object_taxonomies( $this->post_type, 'objects' ), array( 'show_in_rest' => true ) );
2307  
2308          foreach ( $taxonomies as $tax ) {
2309              $tax_base = ! empty( $tax->rest_base ) ? $tax->rest_base : $tax->name;
2310  
2311              /* translators: %s: taxonomy name */
2312              $assign_title = sprintf( __( 'The current user can assign terms in the %s taxonomy.' ), $tax->name );
2313              /* translators: %s: taxonomy name */
2314              $create_title = sprintf( __( 'The current user can create terms in the %s taxonomy.' ), $tax->name );
2315  
2316              $links[] = array(
2317                  'rel'          => 'https://api.w.org/action-assign-' . $tax_base,
2318                  'title'        => $assign_title,
2319                  'href'         => $href,
2320                  'targetSchema' => array(
2321                      'type'       => 'object',
2322                      'properties' => array(
2323                          $tax_base => array(
2324                              'type'  => 'array',
2325                              'items' => array(
2326                                  'type' => 'integer',
2327                              ),
2328                          ),
2329                      ),
2330                  ),
2331              );
2332  
2333              $links[] = array(
2334                  'rel'          => 'https://api.w.org/action-create-' . $tax_base,
2335                  'title'        => $create_title,
2336                  'href'         => $href,
2337                  'targetSchema' => array(
2338                      'type'       => 'object',
2339                      'properties' => array(
2340                          $tax_base => array(
2341                              'type'  => 'array',
2342                              'items' => array(
2343                                  'type' => 'integer',
2344                              ),
2345                          ),
2346                      ),
2347                  ),
2348              );
2349          }
2350  
2351          return $links;
2352      }
2353  
2354      /**
2355       * Retrieves the query params for the posts collection.
2356       *
2357       * @since 4.7.0
2358       *
2359       * @return array Collection parameters.
2360       */
2361  	public function get_collection_params() {
2362          $query_params = parent::get_collection_params();
2363  
2364          $query_params['context']['default'] = 'view';
2365  
2366          $query_params['after'] = array(
2367              'description' => __( 'Limit response to posts published after a given ISO8601 compliant date.' ),
2368              'type'        => 'string',
2369              'format'      => 'date-time',
2370          );
2371  
2372          if ( post_type_supports( $this->post_type, 'author' ) ) {
2373              $query_params['author']         = array(
2374                  'description' => __( 'Limit result set to posts assigned to specific authors.' ),
2375                  'type'        => 'array',
2376                  'items'       => array(
2377                      'type' => 'integer',
2378                  ),
2379                  'default'     => array(),
2380              );
2381              $query_params['author_exclude'] = array(
2382                  'description' => __( 'Ensure result set excludes posts assigned to specific authors.' ),
2383                  'type'        => 'array',
2384                  'items'       => array(
2385                      'type' => 'integer',
2386                  ),
2387                  'default'     => array(),
2388              );
2389          }
2390  
2391          $query_params['before'] = array(
2392              'description' => __( 'Limit response to posts published before a given ISO8601 compliant date.' ),
2393              'type'        => 'string',
2394              'format'      => 'date-time',
2395          );
2396  
2397          $query_params['exclude'] = array(
2398              'description' => __( 'Ensure result set excludes specific IDs.' ),
2399              'type'        => 'array',
2400              'items'       => array(
2401                  'type' => 'integer',
2402              ),
2403              'default'     => array(),
2404          );
2405  
2406          $query_params['include'] = array(
2407              'description' => __( 'Limit result set to specific IDs.' ),
2408              'type'        => 'array',
2409              'items'       => array(
2410                  'type' => 'integer',
2411              ),
2412              'default'     => array(),
2413          );
2414  
2415          if ( 'page' === $this->post_type || post_type_supports( $this->post_type, 'page-attributes' ) ) {
2416              $query_params['menu_order'] = array(
2417                  'description' => __( 'Limit result set to posts with a specific menu_order value.' ),
2418                  'type'        => 'integer',
2419              );
2420          }
2421  
2422          $query_params['offset'] = array(
2423              'description' => __( 'Offset the result set by a specific number of items.' ),
2424              'type'        => 'integer',
2425          );
2426  
2427          $query_params['order'] = array(
2428              'description' => __( 'Order sort attribute ascending or descending.' ),
2429              'type'        => 'string',
2430              'default'     => 'desc',
2431              'enum'        => array( 'asc', 'desc' ),
2432          );
2433  
2434          $query_params['orderby'] = array(
2435              'description' => __( 'Sort collection by object attribute.' ),
2436              'type'        => 'string',
2437              'default'     => 'date',
2438              'enum'        => array(
2439                  'author',
2440                  'date',
2441                  'id',
2442                  'include',
2443                  'modified',
2444                  'parent',
2445                  'relevance',
2446                  'slug',
2447                  'include_slugs',
2448                  'title',
2449              ),
2450          );
2451  
2452          if ( 'page' === $this->post_type || post_type_supports( $this->post_type, 'page-attributes' ) ) {
2453              $query_params['orderby']['enum'][] = 'menu_order';
2454          }
2455  
2456          $post_type = get_post_type_object( $this->post_type );
2457  
2458          if ( $post_type->hierarchical || 'attachment' === $this->post_type ) {
2459              $query_params['parent']         = array(
2460                  'description' => __( 'Limit result set to items with particular parent IDs.' ),
2461                  'type'        => 'array',
2462                  'items'       => array(
2463                      'type' => 'integer',
2464                  ),
2465                  'default'     => array(),
2466              );
2467              $query_params['parent_exclude'] = array(
2468                  'description' => __( 'Limit result set to all items except those of a particular parent ID.' ),
2469                  'type'        => 'array',
2470                  'items'       => array(
2471                      'type' => 'integer',
2472                  ),
2473                  'default'     => array(),
2474              );
2475          }
2476  
2477          $query_params['slug'] = array(
2478              'description'       => __( 'Limit result set to posts with one or more specific slugs.' ),
2479              'type'              => 'array',
2480              'items'             => array(
2481                  'type' => 'string',
2482              ),
2483              'sanitize_callback' => 'wp_parse_slug_list',
2484          );
2485  
2486          $query_params['status'] = array(
2487              'default'           => 'publish',
2488              'description'       => __( 'Limit result set to posts assigned one or more statuses.' ),
2489              'type'              => 'array',
2490              'items'             => array(
2491                  'enum' => array_merge( array_keys( get_post_stati() ), array( 'any' ) ),
2492                  'type' => 'string',
2493              ),
2494              'sanitize_callback' => array( $this, 'sanitize_post_statuses' ),
2495          );
2496  
2497          $taxonomies = wp_list_filter( get_object_taxonomies( $this->post_type, 'objects' ), array( 'show_in_rest' => true ) );
2498  
2499          foreach ( $taxonomies as $taxonomy ) {
2500              $base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name;
2501  
2502              $query_params[ $base ] = array(
2503                  /* translators: %s: taxonomy name */
2504                  'description' => sprintf( __( 'Limit result set to all items that have the specified term assigned in the %s taxonomy.' ), $base ),
2505                  'type'        => 'array',
2506                  'items'       => array(
2507                      'type' => 'integer',
2508                  ),
2509                  'default'     => array(),
2510              );
2511  
2512              $query_params[ $base . '_exclude' ] = array(
2513                  /* translators: %s: taxonomy name */
2514                  'description' => sprintf( __( 'Limit result set to all items except those 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  
2523          if ( 'post' === $this->post_type ) {
2524              $query_params['sticky'] = array(
2525                  'description' => __( 'Limit result set to items that are sticky.' ),
2526                  'type'        => 'boolean',
2527              );
2528          }
2529  
2530          /**
2531           * Filter collection parameters for the posts controller.
2532           *
2533           * The dynamic part of the filter `$this->post_type` refers to the post
2534           * type slug for the controller.
2535           *
2536           * This filter registers the collection parameter, but does not map the
2537           * collection parameter to an internal WP_Query parameter. Use the
2538           * `rest_{$this->post_type}_query` filter to set WP_Query parameters.
2539           *
2540           * @since 4.7.0
2541           *
2542           * @param array        $query_params JSON Schema-formatted collection parameters.
2543           * @param WP_Post_Type $post_type    Post type object.
2544           */
2545          return apply_filters( "rest_{$this->post_type}_collection_params", $query_params, $post_type );
2546      }
2547  
2548      /**
2549       * Sanitizes and validates the list of post statuses, including whether the
2550       * user can query private statuses.
2551       *
2552       * @since 4.7.0
2553       *
2554       * @param  string|array    $statuses  One or more post statuses.
2555       * @param  WP_REST_Request $request   Full details about the request.
2556       * @param  string          $parameter Additional parameter to pass to validation.
2557       * @return array|WP_Error A list of valid statuses, otherwise WP_Error object.
2558       */
2559  	public function sanitize_post_statuses( $statuses, $request, $parameter ) {
2560          $statuses = wp_parse_slug_list( $statuses );
2561  
2562          // The default status is different in WP_REST_Attachments_Controller
2563          $attributes     = $request->get_attributes();
2564          $default_status = $attributes['args']['status']['default'];
2565  
2566          foreach ( $statuses as $status ) {
2567              if ( $status === $default_status ) {
2568                  continue;
2569              }
2570  
2571              $post_type_obj = get_post_type_object( $this->post_type );
2572  
2573              if ( current_user_can( $post_type_obj->cap->edit_posts ) || 'private' === $status && current_user_can( $post_type_obj->cap->read_private_posts ) ) {
2574                  $result = rest_validate_request_arg( $status, $request, $parameter );
2575                  if ( is_wp_error( $result ) ) {
2576                      return $result;
2577                  }
2578              } else {
2579                  return new WP_Error( 'rest_forbidden_status', __( 'Status is forbidden.' ), array( 'status' => rest_authorization_required_code() ) );
2580              }
2581          }
2582  
2583          return $statuses;
2584      }
2585  }


Generated: Mon Jun 17 08:20:02 2019 Cross-referenced by PHPXref 0.7