[ Index ]

PHP Cross Reference of WordPress

title

Body

[close]

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

   1  <?php
   2  /**
   3   * REST API: WP_REST_Users_Controller class
   4   *
   5   * @package WordPress
   6   * @subpackage REST_API
   7   * @since 4.7.0
   8   */
   9  
  10  /**
  11   * Core class used to manage users via the REST API.
  12   *
  13   * @since 4.7.0
  14   *
  15   * @see WP_REST_Controller
  16   */
  17  class WP_REST_Users_Controller extends WP_REST_Controller {
  18  
  19      /**
  20       * Instance of a user meta fields object.
  21       *
  22       * @since 4.7.0
  23       * @var WP_REST_User_Meta_Fields
  24       */
  25      protected $meta;
  26  
  27      /**
  28       * Constructor.
  29       *
  30       * @since 4.7.0
  31       */
  32  	public function __construct() {
  33          $this->namespace = 'wp/v2';
  34          $this->rest_base = 'users';
  35  
  36          $this->meta = new WP_REST_User_Meta_Fields();
  37      }
  38  
  39      /**
  40       * Registers the routes for users.
  41       *
  42       * @since 4.7.0
  43       *
  44       * @see register_rest_route()
  45       */
  46  	public function register_routes() {
  47  
  48          register_rest_route(
  49              $this->namespace,
  50              '/' . $this->rest_base,
  51              array(
  52                  array(
  53                      'methods'             => WP_REST_Server::READABLE,
  54                      'callback'            => array( $this, 'get_items' ),
  55                      'permission_callback' => array( $this, 'get_items_permissions_check' ),
  56                      'args'                => $this->get_collection_params(),
  57                  ),
  58                  array(
  59                      'methods'             => WP_REST_Server::CREATABLE,
  60                      'callback'            => array( $this, 'create_item' ),
  61                      'permission_callback' => array( $this, 'create_item_permissions_check' ),
  62                      'args'                => $this->get_endpoint_args_for_item_schema( WP_REST_Server::CREATABLE ),
  63                  ),
  64                  'schema' => array( $this, 'get_public_item_schema' ),
  65              )
  66          );
  67  
  68          register_rest_route(
  69              $this->namespace,
  70              '/' . $this->rest_base . '/(?P<id>[\d]+)',
  71              array(
  72                  'args'   => array(
  73                      'id' => array(
  74                          'description' => __( 'Unique identifier for the user.' ),
  75                          'type'        => 'integer',
  76                      ),
  77                  ),
  78                  array(
  79                      'methods'             => WP_REST_Server::READABLE,
  80                      'callback'            => array( $this, 'get_item' ),
  81                      'permission_callback' => array( $this, 'get_item_permissions_check' ),
  82                      'args'                => array(
  83                          'context' => $this->get_context_param( array( 'default' => 'view' ) ),
  84                      ),
  85                  ),
  86                  array(
  87                      'methods'             => WP_REST_Server::EDITABLE,
  88                      'callback'            => array( $this, 'update_item' ),
  89                      'permission_callback' => array( $this, 'update_item_permissions_check' ),
  90                      'args'                => $this->get_endpoint_args_for_item_schema( WP_REST_Server::EDITABLE ),
  91                  ),
  92                  array(
  93                      'methods'             => WP_REST_Server::DELETABLE,
  94                      'callback'            => array( $this, 'delete_item' ),
  95                      'permission_callback' => array( $this, 'delete_item_permissions_check' ),
  96                      'args'                => array(
  97                          'force'    => array(
  98                              'type'        => 'boolean',
  99                              'default'     => false,
 100                              'description' => __( 'Required to be true, as users do not support trashing.' ),
 101                          ),
 102                          'reassign' => array(
 103                              'type'              => 'integer',
 104                              'description'       => __( 'Reassign the deleted user\'s posts and links to this user ID.' ),
 105                              'required'          => true,
 106                              'sanitize_callback' => array( $this, 'check_reassign' ),
 107                          ),
 108                      ),
 109                  ),
 110                  'schema' => array( $this, 'get_public_item_schema' ),
 111              )
 112          );
 113  
 114          register_rest_route(
 115              $this->namespace,
 116              '/' . $this->rest_base . '/me',
 117              array(
 118                  array(
 119                      'methods'             => WP_REST_Server::READABLE,
 120                      'permission_callback' => '__return_true',
 121                      'callback'            => array( $this, 'get_current_item' ),
 122                      'args'                => array(
 123                          'context' => $this->get_context_param( array( 'default' => 'view' ) ),
 124                      ),
 125                  ),
 126                  array(
 127                      'methods'             => WP_REST_Server::EDITABLE,
 128                      'callback'            => array( $this, 'update_current_item' ),
 129                      'permission_callback' => array( $this, 'update_current_item_permissions_check' ),
 130                      'args'                => $this->get_endpoint_args_for_item_schema( WP_REST_Server::EDITABLE ),
 131                  ),
 132                  array(
 133                      'methods'             => WP_REST_Server::DELETABLE,
 134                      'callback'            => array( $this, 'delete_current_item' ),
 135                      'permission_callback' => array( $this, 'delete_current_item_permissions_check' ),
 136                      'args'                => array(
 137                          'force'    => array(
 138                              'type'        => 'boolean',
 139                              'default'     => false,
 140                              'description' => __( 'Required to be true, as users do not support trashing.' ),
 141                          ),
 142                          'reassign' => array(
 143                              'type'              => 'integer',
 144                              'description'       => __( 'Reassign the deleted user\'s posts and links to this user ID.' ),
 145                              'required'          => true,
 146                              'sanitize_callback' => array( $this, 'check_reassign' ),
 147                          ),
 148                      ),
 149                  ),
 150                  'schema' => array( $this, 'get_public_item_schema' ),
 151              )
 152          );
 153      }
 154  
 155      /**
 156       * Checks for a valid value for the reassign parameter when deleting users.
 157       *
 158       * The value can be an integer, 'false', false, or ''.
 159       *
 160       * @since 4.7.0
 161       *
 162       * @param int|bool        $value   The value passed to the reassign parameter.
 163       * @param WP_REST_Request $request Full details about the request.
 164       * @param string          $param   The parameter that is being sanitized.
 165       * @return int|bool|WP_Error
 166       */
 167  	public function check_reassign( $value, $request, $param ) {
 168          if ( is_numeric( $value ) ) {
 169              return $value;
 170          }
 171  
 172          if ( empty( $value ) || false === $value || 'false' === $value ) {
 173              return false;
 174          }
 175  
 176          return new WP_Error(
 177              'rest_invalid_param',
 178              __( 'Invalid user parameter(s).' ),
 179              array( 'status' => 400 )
 180          );
 181      }
 182  
 183      /**
 184       * Permissions check for getting all users.
 185       *
 186       * @since 4.7.0
 187       *
 188       * @param WP_REST_Request $request Full details about the request.
 189       * @return true|WP_Error True if the request has read access, otherwise WP_Error object.
 190       */
 191  	public function get_items_permissions_check( $request ) {
 192          // Check if roles is specified in GET request and if user can list users.
 193          if ( ! empty( $request['roles'] ) && ! current_user_can( 'list_users' ) ) {
 194              return new WP_Error(
 195                  'rest_user_cannot_view',
 196                  __( 'Sorry, you are not allowed to filter users by role.' ),
 197                  array( 'status' => rest_authorization_required_code() )
 198              );
 199          }
 200  
 201          // Check if capabilities is specified in GET request and if user can list users.
 202          if ( ! empty( $request['capabilities'] ) && ! current_user_can( 'list_users' ) ) {
 203              return new WP_Error(
 204                  'rest_user_cannot_view',
 205                  __( 'Sorry, you are not allowed to filter users by capability.' ),
 206                  array( 'status' => rest_authorization_required_code() )
 207              );
 208          }
 209  
 210          if ( 'edit' === $request['context'] && ! current_user_can( 'list_users' ) ) {
 211              return new WP_Error(
 212                  'rest_forbidden_context',
 213                  __( 'Sorry, you are not allowed to list users.' ),
 214                  array( 'status' => rest_authorization_required_code() )
 215              );
 216          }
 217  
 218          if ( in_array( $request['orderby'], array( 'email', 'registered_date' ), true ) && ! current_user_can( 'list_users' ) ) {
 219              return new WP_Error(
 220                  'rest_forbidden_orderby',
 221                  __( 'Sorry, you are not allowed to order users by this parameter.' ),
 222                  array( 'status' => rest_authorization_required_code() )
 223              );
 224          }
 225  
 226          if ( 'authors' === $request['who'] ) {
 227              $types = get_post_types( array( 'show_in_rest' => true ), 'objects' );
 228  
 229              foreach ( $types as $type ) {
 230                  if ( post_type_supports( $type->name, 'author' )
 231                      && current_user_can( $type->cap->edit_posts ) ) {
 232                      return true;
 233                  }
 234              }
 235  
 236              return new WP_Error(
 237                  'rest_forbidden_who',
 238                  __( 'Sorry, you are not allowed to query users by this parameter.' ),
 239                  array( 'status' => rest_authorization_required_code() )
 240              );
 241          }
 242  
 243          return true;
 244      }
 245  
 246      /**
 247       * Retrieves all users.
 248       *
 249       * @since 4.7.0
 250       *
 251       * @param WP_REST_Request $request Full details about the request.
 252       * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
 253       */
 254  	public function get_items( $request ) {
 255  
 256          // Retrieve the list of registered collection query parameters.
 257          $registered = $this->get_collection_params();
 258  
 259          /*
 260           * This array defines mappings between public API query parameters whose
 261           * values are accepted as-passed, and their internal WP_Query parameter
 262           * name equivalents (some are the same). Only values which are also
 263           * present in $registered will be set.
 264           */
 265          $parameter_mappings = array(
 266              'exclude'      => 'exclude',
 267              'include'      => 'include',
 268              'order'        => 'order',
 269              'per_page'     => 'number',
 270              'search'       => 'search',
 271              'roles'        => 'role__in',
 272              'capabilities' => 'capability__in',
 273              'slug'         => 'nicename__in',
 274          );
 275  
 276          $prepared_args = array();
 277  
 278          /*
 279           * For each known parameter which is both registered and present in the request,
 280           * set the parameter's value on the query $prepared_args.
 281           */
 282          foreach ( $parameter_mappings as $api_param => $wp_param ) {
 283              if ( isset( $registered[ $api_param ], $request[ $api_param ] ) ) {
 284                  $prepared_args[ $wp_param ] = $request[ $api_param ];
 285              }
 286          }
 287  
 288          if ( isset( $registered['offset'] ) && ! empty( $request['offset'] ) ) {
 289              $prepared_args['offset'] = $request['offset'];
 290          } else {
 291              $prepared_args['offset'] = ( $request['page'] - 1 ) * $prepared_args['number'];
 292          }
 293  
 294          if ( isset( $registered['orderby'] ) ) {
 295              $orderby_possibles        = array(
 296                  'id'              => 'ID',
 297                  'include'         => 'include',
 298                  'name'            => 'display_name',
 299                  'registered_date' => 'registered',
 300                  'slug'            => 'user_nicename',
 301                  'include_slugs'   => 'nicename__in',
 302                  'email'           => 'user_email',
 303                  'url'             => 'user_url',
 304              );
 305              $prepared_args['orderby'] = $orderby_possibles[ $request['orderby'] ];
 306          }
 307  
 308          if ( isset( $registered['who'] ) && ! empty( $request['who'] ) && 'authors' === $request['who'] ) {
 309              $prepared_args['who'] = 'authors';
 310          } elseif ( ! current_user_can( 'list_users' ) ) {
 311              $prepared_args['has_published_posts'] = get_post_types( array( 'show_in_rest' => true ), 'names' );
 312          }
 313  
 314          if ( ! empty( $request['has_published_posts'] ) ) {
 315              $prepared_args['has_published_posts'] = ( true === $request['has_published_posts'] )
 316                  ? get_post_types( array( 'show_in_rest' => true ), 'names' )
 317                  : (array) $request['has_published_posts'];
 318          }
 319  
 320          if ( ! empty( $prepared_args['search'] ) ) {
 321              $prepared_args['search'] = '*' . $prepared_args['search'] . '*';
 322          }
 323          /**
 324           * Filters WP_User_Query arguments when querying users via the REST API.
 325           *
 326           * @link https://developer.wordpress.org/reference/classes/wp_user_query/
 327           *
 328           * @since 4.7.0
 329           *
 330           * @param array           $prepared_args Array of arguments for WP_User_Query.
 331           * @param WP_REST_Request $request       The REST API request.
 332           */
 333          $prepared_args = apply_filters( 'rest_user_query', $prepared_args, $request );
 334  
 335          $query = new WP_User_Query( $prepared_args );
 336  
 337          $users = array();
 338  
 339          foreach ( $query->results as $user ) {
 340              $data    = $this->prepare_item_for_response( $user, $request );
 341              $users[] = $this->prepare_response_for_collection( $data );
 342          }
 343  
 344          $response = rest_ensure_response( $users );
 345  
 346          // Store pagination values for headers then unset for count query.
 347          $per_page = (int) $prepared_args['number'];
 348          $page     = ceil( ( ( (int) $prepared_args['offset'] ) / $per_page ) + 1 );
 349  
 350          $prepared_args['fields'] = 'ID';
 351  
 352          $total_users = $query->get_total();
 353  
 354          if ( $total_users < 1 ) {
 355              // Out-of-bounds, run the query again without LIMIT for total count.
 356              unset( $prepared_args['number'], $prepared_args['offset'] );
 357              $count_query = new WP_User_Query( $prepared_args );
 358              $total_users = $count_query->get_total();
 359          }
 360  
 361          $response->header( 'X-WP-Total', (int) $total_users );
 362  
 363          $max_pages = ceil( $total_users / $per_page );
 364  
 365          $response->header( 'X-WP-TotalPages', (int) $max_pages );
 366  
 367          $base = add_query_arg( urlencode_deep( $request->get_query_params() ), rest_url( sprintf( '%s/%s', $this->namespace, $this->rest_base ) ) );
 368          if ( $page > 1 ) {
 369              $prev_page = $page - 1;
 370  
 371              if ( $prev_page > $max_pages ) {
 372                  $prev_page = $max_pages;
 373              }
 374  
 375              $prev_link = add_query_arg( 'page', $prev_page, $base );
 376              $response->link_header( 'prev', $prev_link );
 377          }
 378          if ( $max_pages > $page ) {
 379              $next_page = $page + 1;
 380              $next_link = add_query_arg( 'page', $next_page, $base );
 381  
 382              $response->link_header( 'next', $next_link );
 383          }
 384  
 385          return $response;
 386      }
 387  
 388      /**
 389       * Get the user, if the ID is valid.
 390       *
 391       * @since 4.7.2
 392       *
 393       * @param int $id Supplied ID.
 394       * @return WP_User|WP_Error True if ID is valid, WP_Error otherwise.
 395       */
 396  	protected function get_user( $id ) {
 397          $error = new WP_Error(
 398              'rest_user_invalid_id',
 399              __( 'Invalid user ID.' ),
 400              array( 'status' => 404 )
 401          );
 402  
 403          if ( (int) $id <= 0 ) {
 404              return $error;
 405          }
 406  
 407          $user = get_userdata( (int) $id );
 408          if ( empty( $user ) || ! $user->exists() ) {
 409              return $error;
 410          }
 411  
 412          if ( is_multisite() && ! is_user_member_of_blog( $user->ID ) ) {
 413              return $error;
 414          }
 415  
 416          return $user;
 417      }
 418  
 419      /**
 420       * Checks if a given request has access to read a user.
 421       *
 422       * @since 4.7.0
 423       *
 424       * @param WP_REST_Request $request Full details about the request.
 425       * @return true|WP_Error True if the request has read access for the item, otherwise WP_Error object.
 426       */
 427  	public function get_item_permissions_check( $request ) {
 428          $user = $this->get_user( $request['id'] );
 429          if ( is_wp_error( $user ) ) {
 430              return $user;
 431          }
 432  
 433          $types = get_post_types( array( 'show_in_rest' => true ), 'names' );
 434  
 435          if ( get_current_user_id() === $user->ID ) {
 436              return true;
 437          }
 438  
 439          if ( 'edit' === $request['context'] && ! current_user_can( 'list_users' ) ) {
 440              return new WP_Error(
 441                  'rest_user_cannot_view',
 442                  __( 'Sorry, you are not allowed to list users.' ),
 443                  array( 'status' => rest_authorization_required_code() )
 444              );
 445          } elseif ( ! count_user_posts( $user->ID, $types ) && ! current_user_can( 'edit_user', $user->ID ) && ! current_user_can( 'list_users' ) ) {
 446              return new WP_Error(
 447                  'rest_user_cannot_view',
 448                  __( 'Sorry, you are not allowed to list users.' ),
 449                  array( 'status' => rest_authorization_required_code() )
 450              );
 451          }
 452  
 453          return true;
 454      }
 455  
 456      /**
 457       * Retrieves a single user.
 458       *
 459       * @since 4.7.0
 460       *
 461       * @param WP_REST_Request $request Full details about the request.
 462       * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
 463       */
 464  	public function get_item( $request ) {
 465          $user = $this->get_user( $request['id'] );
 466          if ( is_wp_error( $user ) ) {
 467              return $user;
 468          }
 469  
 470          $user     = $this->prepare_item_for_response( $user, $request );
 471          $response = rest_ensure_response( $user );
 472  
 473          return $response;
 474      }
 475  
 476      /**
 477       * Retrieves the current user.
 478       *
 479       * @since 4.7.0
 480       *
 481       * @param WP_REST_Request $request Full details about the request.
 482       * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
 483       */
 484  	public function get_current_item( $request ) {
 485          $current_user_id = get_current_user_id();
 486  
 487          if ( empty( $current_user_id ) ) {
 488              return new WP_Error(
 489                  'rest_not_logged_in',
 490                  __( 'You are not currently logged in.' ),
 491                  array( 'status' => 401 )
 492              );
 493          }
 494  
 495          $user     = wp_get_current_user();
 496          $response = $this->prepare_item_for_response( $user, $request );
 497          $response = rest_ensure_response( $response );
 498  
 499          return $response;
 500      }
 501  
 502      /**
 503       * Checks if a given request has access create users.
 504       *
 505       * @since 4.7.0
 506       *
 507       * @param WP_REST_Request $request Full details about the request.
 508       * @return true|WP_Error True if the request has access to create items, WP_Error object otherwise.
 509       */
 510  	public function create_item_permissions_check( $request ) {
 511  
 512          if ( ! current_user_can( 'create_users' ) ) {
 513              return new WP_Error(
 514                  'rest_cannot_create_user',
 515                  __( 'Sorry, you are not allowed to create new users.' ),
 516                  array( 'status' => rest_authorization_required_code() )
 517              );
 518          }
 519  
 520          return true;
 521      }
 522  
 523      /**
 524       * Creates a single user.
 525       *
 526       * @since 4.7.0
 527       *
 528       * @param WP_REST_Request $request Full details about the request.
 529       * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
 530       */
 531  	public function create_item( $request ) {
 532          if ( ! empty( $request['id'] ) ) {
 533              return new WP_Error(
 534                  'rest_user_exists',
 535                  __( 'Cannot create existing user.' ),
 536                  array( 'status' => 400 )
 537              );
 538          }
 539  
 540          $schema = $this->get_item_schema();
 541  
 542          if ( ! empty( $request['roles'] ) && ! empty( $schema['properties']['roles'] ) ) {
 543              $check_permission = $this->check_role_update( $request['id'], $request['roles'] );
 544  
 545              if ( is_wp_error( $check_permission ) ) {
 546                  return $check_permission;
 547              }
 548          }
 549  
 550          $user = $this->prepare_item_for_database( $request );
 551  
 552          if ( is_multisite() ) {
 553              $ret = wpmu_validate_user_signup( $user->user_login, $user->user_email );
 554  
 555              if ( is_wp_error( $ret['errors'] ) && $ret['errors']->has_errors() ) {
 556                  $error = new WP_Error(
 557                      'rest_invalid_param',
 558                      __( 'Invalid user parameter(s).' ),
 559                      array( 'status' => 400 )
 560                  );
 561  
 562                  foreach ( $ret['errors']->errors as $code => $messages ) {
 563                      foreach ( $messages as $message ) {
 564                          $error->add( $code, $message );
 565                      }
 566  
 567                      $error_data = $error->get_error_data( $code );
 568  
 569                      if ( $error_data ) {
 570                          $error->add_data( $error_data, $code );
 571                      }
 572                  }
 573                  return $error;
 574              }
 575          }
 576  
 577          if ( is_multisite() ) {
 578              $user_id = wpmu_create_user( $user->user_login, $user->user_pass, $user->user_email );
 579  
 580              if ( ! $user_id ) {
 581                  return new WP_Error(
 582                      'rest_user_create',
 583                      __( 'Error creating new user.' ),
 584                      array( 'status' => 500 )
 585                  );
 586              }
 587  
 588              $user->ID = $user_id;
 589              $user_id  = wp_update_user( wp_slash( (array) $user ) );
 590  
 591              if ( is_wp_error( $user_id ) ) {
 592                  return $user_id;
 593              }
 594  
 595              $result = add_user_to_blog( get_site()->id, $user_id, '' );
 596              if ( is_wp_error( $result ) ) {
 597                  return $result;
 598              }
 599          } else {
 600              $user_id = wp_insert_user( wp_slash( (array) $user ) );
 601  
 602              if ( is_wp_error( $user_id ) ) {
 603                  return $user_id;
 604              }
 605          }
 606  
 607          $user = get_user_by( 'id', $user_id );
 608  
 609          /**
 610           * Fires immediately after a user is created or updated via the REST API.
 611           *
 612           * @since 4.7.0
 613           *
 614           * @param WP_User         $user     Inserted or updated user object.
 615           * @param WP_REST_Request $request  Request object.
 616           * @param bool            $creating True when creating a user, false when updating.
 617           */
 618          do_action( 'rest_insert_user', $user, $request, true );
 619  
 620          if ( ! empty( $request['roles'] ) && ! empty( $schema['properties']['roles'] ) ) {
 621              array_map( array( $user, 'add_role' ), $request['roles'] );
 622          }
 623  
 624          if ( ! empty( $schema['properties']['meta'] ) && isset( $request['meta'] ) ) {
 625              $meta_update = $this->meta->update_value( $request['meta'], $user_id );
 626  
 627              if ( is_wp_error( $meta_update ) ) {
 628                  return $meta_update;
 629              }
 630          }
 631  
 632          $user          = get_user_by( 'id', $user_id );
 633          $fields_update = $this->update_additional_fields_for_object( $user, $request );
 634  
 635          if ( is_wp_error( $fields_update ) ) {
 636              return $fields_update;
 637          }
 638  
 639          $request->set_param( 'context', 'edit' );
 640  
 641          /**
 642           * Fires after a user is completely created or updated via the REST API.
 643           *
 644           * @since 5.0.0
 645           *
 646           * @param WP_User         $user     Inserted or updated user object.
 647           * @param WP_REST_Request $request  Request object.
 648           * @param bool            $creating True when creating a user, false when updating.
 649           */
 650          do_action( 'rest_after_insert_user', $user, $request, true );
 651  
 652          $response = $this->prepare_item_for_response( $user, $request );
 653          $response = rest_ensure_response( $response );
 654  
 655          $response->set_status( 201 );
 656          $response->header( 'Location', rest_url( sprintf( '%s/%s/%d', $this->namespace, $this->rest_base, $user_id ) ) );
 657  
 658          return $response;
 659      }
 660  
 661      /**
 662       * Checks if a given request has access to update a user.
 663       *
 664       * @since 4.7.0
 665       *
 666       * @param WP_REST_Request $request Full details about the request.
 667       * @return true|WP_Error True if the request has access to update the item, WP_Error object otherwise.
 668       */
 669  	public function update_item_permissions_check( $request ) {
 670          $user = $this->get_user( $request['id'] );
 671          if ( is_wp_error( $user ) ) {
 672              return $user;
 673          }
 674  
 675          if ( ! empty( $request['roles'] ) ) {
 676              if ( ! current_user_can( 'promote_user', $user->ID ) ) {
 677                  return new WP_Error(
 678                      'rest_cannot_edit_roles',
 679                      __( 'Sorry, you are not allowed to edit roles of this user.' ),
 680                      array( 'status' => rest_authorization_required_code() )
 681                  );
 682              }
 683  
 684              $request_params = array_keys( $request->get_params() );
 685              sort( $request_params );
 686              // If only 'id' and 'roles' are specified (we are only trying to
 687              // edit roles), then only the 'promote_user' cap is required.
 688              if ( array( 'id', 'roles' ) === $request_params ) {
 689                  return true;
 690              }
 691          }
 692  
 693          if ( ! current_user_can( 'edit_user', $user->ID ) ) {
 694              return new WP_Error(
 695                  'rest_cannot_edit',
 696                  __( 'Sorry, you are not allowed to edit this user.' ),
 697                  array( 'status' => rest_authorization_required_code() )
 698              );
 699          }
 700  
 701          return true;
 702      }
 703  
 704      /**
 705       * Updates a single user.
 706       *
 707       * @since 4.7.0
 708       *
 709       * @param WP_REST_Request $request Full details about the request.
 710       * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
 711       */
 712  	public function update_item( $request ) {
 713          $user = $this->get_user( $request['id'] );
 714          if ( is_wp_error( $user ) ) {
 715              return $user;
 716          }
 717  
 718          $id = $user->ID;
 719  
 720          if ( ! $user ) {
 721              return new WP_Error(
 722                  'rest_user_invalid_id',
 723                  __( 'Invalid user ID.' ),
 724                  array( 'status' => 404 )
 725              );
 726          }
 727  
 728          $owner_id = email_exists( $request['email'] );
 729  
 730          if ( $owner_id && $owner_id !== $id ) {
 731              return new WP_Error(
 732                  'rest_user_invalid_email',
 733                  __( 'Invalid email address.' ),
 734                  array( 'status' => 400 )
 735              );
 736          }
 737  
 738          if ( ! empty( $request['username'] ) && $request['username'] !== $user->user_login ) {
 739              return new WP_Error(
 740                  'rest_user_invalid_argument',
 741                  __( 'Username is not editable.' ),
 742                  array( 'status' => 400 )
 743              );
 744          }
 745  
 746          if ( ! empty( $request['slug'] ) && $request['slug'] !== $user->user_nicename && get_user_by( 'slug', $request['slug'] ) ) {
 747              return new WP_Error(
 748                  'rest_user_invalid_slug',
 749                  __( 'Invalid slug.' ),
 750                  array( 'status' => 400 )
 751              );
 752          }
 753  
 754          if ( ! empty( $request['roles'] ) ) {
 755              $check_permission = $this->check_role_update( $id, $request['roles'] );
 756  
 757              if ( is_wp_error( $check_permission ) ) {
 758                  return $check_permission;
 759              }
 760          }
 761  
 762          $user = $this->prepare_item_for_database( $request );
 763  
 764          // Ensure we're operating on the same user we already checked.
 765          $user->ID = $id;
 766  
 767          $user_id = wp_update_user( wp_slash( (array) $user ) );
 768  
 769          if ( is_wp_error( $user_id ) ) {
 770              return $user_id;
 771          }
 772  
 773          $user = get_user_by( 'id', $user_id );
 774  
 775          /** This action is documented in wp-includes/rest-api/endpoints/class-wp-rest-users-controller.php */
 776          do_action( 'rest_insert_user', $user, $request, false );
 777  
 778          if ( ! empty( $request['roles'] ) ) {
 779              array_map( array( $user, 'add_role' ), $request['roles'] );
 780          }
 781  
 782          $schema = $this->get_item_schema();
 783  
 784          if ( ! empty( $schema['properties']['meta'] ) && isset( $request['meta'] ) ) {
 785              $meta_update = $this->meta->update_value( $request['meta'], $id );
 786  
 787              if ( is_wp_error( $meta_update ) ) {
 788                  return $meta_update;
 789              }
 790          }
 791  
 792          $user          = get_user_by( 'id', $user_id );
 793          $fields_update = $this->update_additional_fields_for_object( $user, $request );
 794  
 795          if ( is_wp_error( $fields_update ) ) {
 796              return $fields_update;
 797          }
 798  
 799          $request->set_param( 'context', 'edit' );
 800  
 801          /** This action is documented in wp-includes/rest-api/endpoints/class-wp-rest-users-controller.php */
 802          do_action( 'rest_after_insert_user', $user, $request, false );
 803  
 804          $response = $this->prepare_item_for_response( $user, $request );
 805          $response = rest_ensure_response( $response );
 806  
 807          return $response;
 808      }
 809  
 810      /**
 811       * Checks if a given request has access to update the current user.
 812       *
 813       * @since 4.7.0
 814       *
 815       * @param WP_REST_Request $request Full details about the request.
 816       * @return true|WP_Error True if the request has access to update the item, WP_Error object otherwise.
 817       */
 818  	public function update_current_item_permissions_check( $request ) {
 819          $request['id'] = get_current_user_id();
 820  
 821          return $this->update_item_permissions_check( $request );
 822      }
 823  
 824      /**
 825       * Updates the current user.
 826       *
 827       * @since 4.7.0
 828       *
 829       * @param WP_REST_Request $request Full details about the request.
 830       * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
 831       */
 832  	public function update_current_item( $request ) {
 833          $request['id'] = get_current_user_id();
 834  
 835          return $this->update_item( $request );
 836      }
 837  
 838      /**
 839       * Checks if a given request has access delete a user.
 840       *
 841       * @since 4.7.0
 842       *
 843       * @param WP_REST_Request $request Full details about the request.
 844       * @return true|WP_Error True if the request has access to delete the item, WP_Error object otherwise.
 845       */
 846  	public function delete_item_permissions_check( $request ) {
 847          $user = $this->get_user( $request['id'] );
 848          if ( is_wp_error( $user ) ) {
 849              return $user;
 850          }
 851  
 852          if ( ! current_user_can( 'delete_user', $user->ID ) ) {
 853              return new WP_Error(
 854                  'rest_user_cannot_delete',
 855                  __( 'Sorry, you are not allowed to delete this user.' ),
 856                  array( 'status' => rest_authorization_required_code() )
 857              );
 858          }
 859  
 860          return true;
 861      }
 862  
 863      /**
 864       * Deletes a single user.
 865       *
 866       * @since 4.7.0
 867       *
 868       * @param WP_REST_Request $request Full details about the request.
 869       * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
 870       */
 871  	public function delete_item( $request ) {
 872          // We don't support delete requests in multisite.
 873          if ( is_multisite() ) {
 874              return new WP_Error(
 875                  'rest_cannot_delete',
 876                  __( 'The user cannot be deleted.' ),
 877                  array( 'status' => 501 )
 878              );
 879          }
 880  
 881          $user = $this->get_user( $request['id'] );
 882  
 883          if ( is_wp_error( $user ) ) {
 884              return $user;
 885          }
 886  
 887          $id       = $user->ID;
 888          $reassign = false === $request['reassign'] ? null : absint( $request['reassign'] );
 889          $force    = isset( $request['force'] ) ? (bool) $request['force'] : false;
 890  
 891          // We don't support trashing for users.
 892          if ( ! $force ) {
 893              return new WP_Error(
 894                  'rest_trash_not_supported',
 895                  /* translators: %s: force=true */
 896                  sprintf( __( "Users do not support trashing. Set '%s' to delete." ), 'force=true' ),
 897                  array( 'status' => 501 )
 898              );
 899          }
 900  
 901          if ( ! empty( $reassign ) ) {
 902              if ( $reassign === $id || ! get_userdata( $reassign ) ) {
 903                  return new WP_Error(
 904                      'rest_user_invalid_reassign',
 905                      __( 'Invalid user ID for reassignment.' ),
 906                      array( 'status' => 400 )
 907                  );
 908              }
 909          }
 910  
 911          $request->set_param( 'context', 'edit' );
 912  
 913          $previous = $this->prepare_item_for_response( $user, $request );
 914  
 915          // Include user admin functions to get access to wp_delete_user().
 916          require_once ABSPATH . 'wp-admin/includes/user.php';
 917  
 918          $result = wp_delete_user( $id, $reassign );
 919  
 920          if ( ! $result ) {
 921              return new WP_Error(
 922                  'rest_cannot_delete',
 923                  __( 'The user cannot be deleted.' ),
 924                  array( 'status' => 500 )
 925              );
 926          }
 927  
 928          $response = new WP_REST_Response();
 929          $response->set_data(
 930              array(
 931                  'deleted'  => true,
 932                  'previous' => $previous->get_data(),
 933              )
 934          );
 935  
 936          /**
 937           * Fires immediately after a user is deleted via the REST API.
 938           *
 939           * @since 4.7.0
 940           *
 941           * @param WP_User          $user     The user data.
 942           * @param WP_REST_Response $response The response returned from the API.
 943           * @param WP_REST_Request  $request  The request sent to the API.
 944           */
 945          do_action( 'rest_delete_user', $user, $response, $request );
 946  
 947          return $response;
 948      }
 949  
 950      /**
 951       * Checks if a given request has access to delete the current user.
 952       *
 953       * @since 4.7.0
 954       *
 955       * @param WP_REST_Request $request Full details about the request.
 956       * @return true|WP_Error True if the request has access to delete the item, WP_Error object otherwise.
 957       */
 958  	public function delete_current_item_permissions_check( $request ) {
 959          $request['id'] = get_current_user_id();
 960  
 961          return $this->delete_item_permissions_check( $request );
 962      }
 963  
 964      /**
 965       * Deletes the current user.
 966       *
 967       * @since 4.7.0
 968       *
 969       * @param WP_REST_Request $request Full details about the request.
 970       * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
 971       */
 972  	public function delete_current_item( $request ) {
 973          $request['id'] = get_current_user_id();
 974  
 975          return $this->delete_item( $request );
 976      }
 977  
 978      /**
 979       * Prepares a single user output for response.
 980       *
 981       * @since 4.7.0
 982       * @since 5.9.0 Renamed `$user` to `$item` to match parent class for PHP 8 named parameter support.
 983       *
 984       * @param WP_User         $item    User object.
 985       * @param WP_REST_Request $request Request object.
 986       * @return WP_REST_Response Response object.
 987       */
 988  	public function prepare_item_for_response( $item, $request ) {
 989          // Restores the more descriptive, specific name for use within this method.
 990          $user   = $item;
 991          $data   = array();
 992          $fields = $this->get_fields_for_response( $request );
 993  
 994          if ( in_array( 'id', $fields, true ) ) {
 995              $data['id'] = $user->ID;
 996          }
 997  
 998          if ( in_array( 'username', $fields, true ) ) {
 999              $data['username'] = $user->user_login;
1000          }
1001  
1002          if ( in_array( 'name', $fields, true ) ) {
1003              $data['name'] = $user->display_name;
1004          }
1005  
1006          if ( in_array( 'first_name', $fields, true ) ) {
1007              $data['first_name'] = $user->first_name;
1008          }
1009  
1010          if ( in_array( 'last_name', $fields, true ) ) {
1011              $data['last_name'] = $user->last_name;
1012          }
1013  
1014          if ( in_array( 'email', $fields, true ) ) {
1015              $data['email'] = $user->user_email;
1016          }
1017  
1018          if ( in_array( 'url', $fields, true ) ) {
1019              $data['url'] = $user->user_url;
1020          }
1021  
1022          if ( in_array( 'description', $fields, true ) ) {
1023              $data['description'] = $user->description;
1024          }
1025  
1026          if ( in_array( 'link', $fields, true ) ) {
1027              $data['link'] = get_author_posts_url( $user->ID, $user->user_nicename );
1028          }
1029  
1030          if ( in_array( 'locale', $fields, true ) ) {
1031              $data['locale'] = get_user_locale( $user );
1032          }
1033  
1034          if ( in_array( 'nickname', $fields, true ) ) {
1035              $data['nickname'] = $user->nickname;
1036          }
1037  
1038          if ( in_array( 'slug', $fields, true ) ) {
1039              $data['slug'] = $user->user_nicename;
1040          }
1041  
1042          if ( in_array( 'roles', $fields, true ) ) {
1043              // Defensively call array_values() to ensure an array is returned.
1044              $data['roles'] = array_values( $user->roles );
1045          }
1046  
1047          if ( in_array( 'registered_date', $fields, true ) ) {
1048              $data['registered_date'] = gmdate( 'c', strtotime( $user->user_registered ) );
1049          }
1050  
1051          if ( in_array( 'capabilities', $fields, true ) ) {
1052              $data['capabilities'] = (object) $user->allcaps;
1053          }
1054  
1055          if ( in_array( 'extra_capabilities', $fields, true ) ) {
1056              $data['extra_capabilities'] = (object) $user->caps;
1057          }
1058  
1059          if ( in_array( 'avatar_urls', $fields, true ) ) {
1060              $data['avatar_urls'] = rest_get_avatar_urls( $user );
1061          }
1062  
1063          if ( in_array( 'meta', $fields, true ) ) {
1064              $data['meta'] = $this->meta->get_value( $user->ID, $request );
1065          }
1066  
1067          $context = ! empty( $request['context'] ) ? $request['context'] : 'embed';
1068  
1069          $data = $this->add_additional_fields_to_object( $data, $request );
1070          $data = $this->filter_response_by_context( $data, $context );
1071  
1072          // Wrap the data in a response object.
1073          $response = rest_ensure_response( $data );
1074  
1075          $response->add_links( $this->prepare_links( $user ) );
1076  
1077          /**
1078           * Filters user data returned from the REST API.
1079           *
1080           * @since 4.7.0
1081           *
1082           * @param WP_REST_Response $response The response object.
1083           * @param WP_User          $user     User object used to create response.
1084           * @param WP_REST_Request  $request  Request object.
1085           */
1086          return apply_filters( 'rest_prepare_user', $response, $user, $request );
1087      }
1088  
1089      /**
1090       * Prepares links for the user request.
1091       *
1092       * @since 4.7.0
1093       *
1094       * @param WP_User $user User object.
1095       * @return array Links for the given user.
1096       */
1097  	protected function prepare_links( $user ) {
1098          $links = array(
1099              'self'       => array(
1100                  'href' => rest_url( sprintf( '%s/%s/%d', $this->namespace, $this->rest_base, $user->ID ) ),
1101              ),
1102              'collection' => array(
1103                  'href' => rest_url( sprintf( '%s/%s', $this->namespace, $this->rest_base ) ),
1104              ),
1105          );
1106  
1107          return $links;
1108      }
1109  
1110      /**
1111       * Prepares a single user for creation or update.
1112       *
1113       * @since 4.7.0
1114       *
1115       * @param WP_REST_Request $request Request object.
1116       * @return object User object.
1117       */
1118  	protected function prepare_item_for_database( $request ) {
1119          $prepared_user = new stdClass;
1120  
1121          $schema = $this->get_item_schema();
1122  
1123          // Required arguments.
1124          if ( isset( $request['email'] ) && ! empty( $schema['properties']['email'] ) ) {
1125              $prepared_user->user_email = $request['email'];
1126          }
1127  
1128          if ( isset( $request['username'] ) && ! empty( $schema['properties']['username'] ) ) {
1129              $prepared_user->user_login = $request['username'];
1130          }
1131  
1132          if ( isset( $request['password'] ) && ! empty( $schema['properties']['password'] ) ) {
1133              $prepared_user->user_pass = $request['password'];
1134          }
1135  
1136          // Optional arguments.
1137          if ( isset( $request['id'] ) ) {
1138              $prepared_user->ID = absint( $request['id'] );
1139          }
1140  
1141          if ( isset( $request['name'] ) && ! empty( $schema['properties']['name'] ) ) {
1142              $prepared_user->display_name = $request['name'];
1143          }
1144  
1145          if ( isset( $request['first_name'] ) && ! empty( $schema['properties']['first_name'] ) ) {
1146              $prepared_user->first_name = $request['first_name'];
1147          }
1148  
1149          if ( isset( $request['last_name'] ) && ! empty( $schema['properties']['last_name'] ) ) {
1150              $prepared_user->last_name = $request['last_name'];
1151          }
1152  
1153          if ( isset( $request['nickname'] ) && ! empty( $schema['properties']['nickname'] ) ) {
1154              $prepared_user->nickname = $request['nickname'];
1155          }
1156  
1157          if ( isset( $request['slug'] ) && ! empty( $schema['properties']['slug'] ) ) {
1158              $prepared_user->user_nicename = $request['slug'];
1159          }
1160  
1161          if ( isset( $request['description'] ) && ! empty( $schema['properties']['description'] ) ) {
1162              $prepared_user->description = $request['description'];
1163          }
1164  
1165          if ( isset( $request['url'] ) && ! empty( $schema['properties']['url'] ) ) {
1166              $prepared_user->user_url = $request['url'];
1167          }
1168  
1169          if ( isset( $request['locale'] ) && ! empty( $schema['properties']['locale'] ) ) {
1170              $prepared_user->locale = $request['locale'];
1171          }
1172  
1173          // Setting roles will be handled outside of this function.
1174          if ( isset( $request['roles'] ) ) {
1175              $prepared_user->role = false;
1176          }
1177  
1178          /**
1179           * Filters user data before insertion via the REST API.
1180           *
1181           * @since 4.7.0
1182           *
1183           * @param object          $prepared_user User object.
1184           * @param WP_REST_Request $request       Request object.
1185           */
1186          return apply_filters( 'rest_pre_insert_user', $prepared_user, $request );
1187      }
1188  
1189      /**
1190       * Determines if the current user is allowed to make the desired roles change.
1191       *
1192       * @since 4.7.0
1193       *
1194       * @global WP_Roles $wp_roles WordPress role management object.
1195       *
1196       * @param int   $user_id User ID.
1197       * @param array $roles   New user roles.
1198       * @return true|WP_Error True if the current user is allowed to make the role change,
1199       *                       otherwise a WP_Error object.
1200       */
1201  	protected function check_role_update( $user_id, $roles ) {
1202          global $wp_roles;
1203  
1204          foreach ( $roles as $role ) {
1205  
1206              if ( ! isset( $wp_roles->role_objects[ $role ] ) ) {
1207                  return new WP_Error(
1208                      'rest_user_invalid_role',
1209                      /* translators: %s: Role key. */
1210                      sprintf( __( 'The role %s does not exist.' ), $role ),
1211                      array( 'status' => 400 )
1212                  );
1213              }
1214  
1215              $potential_role = $wp_roles->role_objects[ $role ];
1216  
1217              /*
1218               * Don't let anyone with 'edit_users' (admins) edit their own role to something without it.
1219               * Multisite super admins can freely edit their blog roles -- they possess all caps.
1220               */
1221              if ( ! ( is_multisite()
1222                  && current_user_can( 'manage_sites' ) )
1223                  && get_current_user_id() === $user_id
1224                  && ! $potential_role->has_cap( 'edit_users' )
1225              ) {
1226                  return new WP_Error(
1227                      'rest_user_invalid_role',
1228                      __( 'Sorry, you are not allowed to give users that role.' ),
1229                      array( 'status' => rest_authorization_required_code() )
1230                  );
1231              }
1232  
1233              // Include user admin functions to get access to get_editable_roles().
1234              require_once ABSPATH . 'wp-admin/includes/user.php';
1235  
1236              // The new role must be editable by the logged-in user.
1237              $editable_roles = get_editable_roles();
1238  
1239              if ( empty( $editable_roles[ $role ] ) ) {
1240                  return new WP_Error(
1241                      'rest_user_invalid_role',
1242                      __( 'Sorry, you are not allowed to give users that role.' ),
1243                      array( 'status' => 403 )
1244                  );
1245              }
1246          }
1247  
1248          return true;
1249      }
1250  
1251      /**
1252       * Check a username for the REST API.
1253       *
1254       * Performs a couple of checks like edit_user() in wp-admin/includes/user.php.
1255       *
1256       * @since 4.7.0
1257       *
1258       * @param string          $value   The username submitted in the request.
1259       * @param WP_REST_Request $request Full details about the request.
1260       * @param string          $param   The parameter name.
1261       * @return string|WP_Error The sanitized username, if valid, otherwise an error.
1262       */
1263  	public function check_username( $value, $request, $param ) {
1264          $username = (string) $value;
1265  
1266          if ( ! validate_username( $username ) ) {
1267              return new WP_Error(
1268                  'rest_user_invalid_username',
1269                  __( 'This username is invalid because it uses illegal characters. Please enter a valid username.' ),
1270                  array( 'status' => 400 )
1271              );
1272          }
1273  
1274          /** This filter is documented in wp-includes/user.php */
1275          $illegal_logins = (array) apply_filters( 'illegal_user_logins', array() );
1276  
1277          if ( in_array( strtolower( $username ), array_map( 'strtolower', $illegal_logins ), true ) ) {
1278              return new WP_Error(
1279                  'rest_user_invalid_username',
1280                  __( 'Sorry, that username is not allowed.' ),
1281                  array( 'status' => 400 )
1282              );
1283          }
1284  
1285          return $username;
1286      }
1287  
1288      /**
1289       * Check a user password for the REST API.
1290       *
1291       * Performs a couple of checks like edit_user() in wp-admin/includes/user.php.
1292       *
1293       * @since 4.7.0
1294       *
1295       * @param string          $value   The password submitted in the request.
1296       * @param WP_REST_Request $request Full details about the request.
1297       * @param string          $param   The parameter name.
1298       * @return string|WP_Error The sanitized password, if valid, otherwise an error.
1299       */
1300  	public function check_user_password( $value, $request, $param ) {
1301          $password = (string) $value;
1302  
1303          if ( empty( $password ) ) {
1304              return new WP_Error(
1305                  'rest_user_invalid_password',
1306                  __( 'Passwords cannot be empty.' ),
1307                  array( 'status' => 400 )
1308              );
1309          }
1310  
1311          if ( false !== strpos( $password, '\\' ) ) {
1312              return new WP_Error(
1313                  'rest_user_invalid_password',
1314                  sprintf(
1315                      /* translators: %s: The '\' character. */
1316                      __( 'Passwords cannot contain the "%s" character.' ),
1317                      '\\'
1318                  ),
1319                  array( 'status' => 400 )
1320              );
1321          }
1322  
1323          return $password;
1324      }
1325  
1326      /**
1327       * Retrieves the user's schema, conforming to JSON Schema.
1328       *
1329       * @since 4.7.0
1330       *
1331       * @return array Item schema data.
1332       */
1333  	public function get_item_schema() {
1334          if ( $this->schema ) {
1335              return $this->add_additional_fields_schema( $this->schema );
1336          }
1337  
1338          $schema = array(
1339              '$schema'    => 'http://json-schema.org/draft-04/schema#',
1340              'title'      => 'user',
1341              'type'       => 'object',
1342              'properties' => array(
1343                  'id'                 => array(
1344                      'description' => __( 'Unique identifier for the user.' ),
1345                      'type'        => 'integer',
1346                      'context'     => array( 'embed', 'view', 'edit' ),
1347                      'readonly'    => true,
1348                  ),
1349                  'username'           => array(
1350                      'description' => __( 'Login name for the user.' ),
1351                      'type'        => 'string',
1352                      'context'     => array( 'edit' ),
1353                      'required'    => true,
1354                      'arg_options' => array(
1355                          'sanitize_callback' => array( $this, 'check_username' ),
1356                      ),
1357                  ),
1358                  'name'               => array(
1359                      'description' => __( 'Display name for the user.' ),
1360                      'type'        => 'string',
1361                      'context'     => array( 'embed', 'view', 'edit' ),
1362                      'arg_options' => array(
1363                          'sanitize_callback' => 'sanitize_text_field',
1364                      ),
1365                  ),
1366                  'first_name'         => array(
1367                      'description' => __( 'First name for the user.' ),
1368                      'type'        => 'string',
1369                      'context'     => array( 'edit' ),
1370                      'arg_options' => array(
1371                          'sanitize_callback' => 'sanitize_text_field',
1372                      ),
1373                  ),
1374                  'last_name'          => array(
1375                      'description' => __( 'Last name for the user.' ),
1376                      'type'        => 'string',
1377                      'context'     => array( 'edit' ),
1378                      'arg_options' => array(
1379                          'sanitize_callback' => 'sanitize_text_field',
1380                      ),
1381                  ),
1382                  'email'              => array(
1383                      'description' => __( 'The email address for the user.' ),
1384                      'type'        => 'string',
1385                      'format'      => 'email',
1386                      'context'     => array( 'edit' ),
1387                      'required'    => true,
1388                  ),
1389                  'url'                => array(
1390                      'description' => __( 'URL of the user.' ),
1391                      'type'        => 'string',
1392                      'format'      => 'uri',
1393                      'context'     => array( 'embed', 'view', 'edit' ),
1394                  ),
1395                  'description'        => array(
1396                      'description' => __( 'Description of the user.' ),
1397                      'type'        => 'string',
1398                      'context'     => array( 'embed', 'view', 'edit' ),
1399                  ),
1400                  'link'               => array(
1401                      'description' => __( 'Author URL of the user.' ),
1402                      'type'        => 'string',
1403                      'format'      => 'uri',
1404                      'context'     => array( 'embed', 'view', 'edit' ),
1405                      'readonly'    => true,
1406                  ),
1407                  'locale'             => array(
1408                      'description' => __( 'Locale for the user.' ),
1409                      'type'        => 'string',
1410                      'enum'        => array_merge( array( '', 'en_US' ), get_available_languages() ),
1411                      'context'     => array( 'edit' ),
1412                  ),
1413                  'nickname'           => array(
1414                      'description' => __( 'The nickname for the user.' ),
1415                      'type'        => 'string',
1416                      'context'     => array( 'edit' ),
1417                      'arg_options' => array(
1418                          'sanitize_callback' => 'sanitize_text_field',
1419                      ),
1420                  ),
1421                  'slug'               => array(
1422                      'description' => __( 'An alphanumeric identifier for the user.' ),
1423                      'type'        => 'string',
1424                      'context'     => array( 'embed', 'view', 'edit' ),
1425                      'arg_options' => array(
1426                          'sanitize_callback' => array( $this, 'sanitize_slug' ),
1427                      ),
1428                  ),
1429                  'registered_date'    => array(
1430                      'description' => __( 'Registration date for the user.' ),
1431                      'type'        => 'string',
1432                      'format'      => 'date-time',
1433                      'context'     => array( 'edit' ),
1434                      'readonly'    => true,
1435                  ),
1436                  'roles'              => array(
1437                      'description' => __( 'Roles assigned to the user.' ),
1438                      'type'        => 'array',
1439                      'items'       => array(
1440                          'type' => 'string',
1441                      ),
1442                      'context'     => array( 'edit' ),
1443                  ),
1444                  'password'           => array(
1445                      'description' => __( 'Password for the user (never included).' ),
1446                      'type'        => 'string',
1447                      'context'     => array(), // Password is never displayed.
1448                      'required'    => true,
1449                      'arg_options' => array(
1450                          'sanitize_callback' => array( $this, 'check_user_password' ),
1451                      ),
1452                  ),
1453                  'capabilities'       => array(
1454                      'description' => __( 'All capabilities assigned to the user.' ),
1455                      'type'        => 'object',
1456                      'context'     => array( 'edit' ),
1457                      'readonly'    => true,
1458                  ),
1459                  'extra_capabilities' => array(
1460                      'description' => __( 'Any extra capabilities assigned to the user.' ),
1461                      'type'        => 'object',
1462                      'context'     => array( 'edit' ),
1463                      'readonly'    => true,
1464                  ),
1465              ),
1466          );
1467  
1468          if ( get_option( 'show_avatars' ) ) {
1469              $avatar_properties = array();
1470  
1471              $avatar_sizes = rest_get_avatar_sizes();
1472  
1473              foreach ( $avatar_sizes as $size ) {
1474                  $avatar_properties[ $size ] = array(
1475                      /* translators: %d: Avatar image size in pixels. */
1476                      'description' => sprintf( __( 'Avatar URL with image size of %d pixels.' ), $size ),
1477                      'type'        => 'string',
1478                      'format'      => 'uri',
1479                      'context'     => array( 'embed', 'view', 'edit' ),
1480                  );
1481              }
1482  
1483              $schema['properties']['avatar_urls'] = array(
1484                  'description' => __( 'Avatar URLs for the user.' ),
1485                  'type'        => 'object',
1486                  'context'     => array( 'embed', 'view', 'edit' ),
1487                  'readonly'    => true,
1488                  'properties'  => $avatar_properties,
1489              );
1490          }
1491  
1492          $schema['properties']['meta'] = $this->meta->get_field_schema();
1493  
1494          $this->schema = $schema;
1495  
1496          return $this->add_additional_fields_schema( $this->schema );
1497      }
1498  
1499      /**
1500       * Retrieves the query params for collections.
1501       *
1502       * @since 4.7.0
1503       *
1504       * @return array Collection parameters.
1505       */
1506  	public function get_collection_params() {
1507          $query_params = parent::get_collection_params();
1508  
1509          $query_params['context']['default'] = 'view';
1510  
1511          $query_params['exclude'] = array(
1512              'description' => __( 'Ensure result set excludes specific IDs.' ),
1513              'type'        => 'array',
1514              'items'       => array(
1515                  'type' => 'integer',
1516              ),
1517              'default'     => array(),
1518          );
1519  
1520          $query_params['include'] = array(
1521              'description' => __( 'Limit result set to specific IDs.' ),
1522              'type'        => 'array',
1523              'items'       => array(
1524                  'type' => 'integer',
1525              ),
1526              'default'     => array(),
1527          );
1528  
1529          $query_params['offset'] = array(
1530              'description' => __( 'Offset the result set by a specific number of items.' ),
1531              'type'        => 'integer',
1532          );
1533  
1534          $query_params['order'] = array(
1535              'default'     => 'asc',
1536              'description' => __( 'Order sort attribute ascending or descending.' ),
1537              'enum'        => array( 'asc', 'desc' ),
1538              'type'        => 'string',
1539          );
1540  
1541          $query_params['orderby'] = array(
1542              'default'     => 'name',
1543              'description' => __( 'Sort collection by user attribute.' ),
1544              'enum'        => array(
1545                  'id',
1546                  'include',
1547                  'name',
1548                  'registered_date',
1549                  'slug',
1550                  'include_slugs',
1551                  'email',
1552                  'url',
1553              ),
1554              'type'        => 'string',
1555          );
1556  
1557          $query_params['slug'] = array(
1558              'description' => __( 'Limit result set to users with one or more specific slugs.' ),
1559              'type'        => 'array',
1560              'items'       => array(
1561                  'type' => 'string',
1562              ),
1563          );
1564  
1565          $query_params['roles'] = array(
1566              'description' => __( 'Limit result set to users matching at least one specific role provided. Accepts csv list or single role.' ),
1567              'type'        => 'array',
1568              'items'       => array(
1569                  'type' => 'string',
1570              ),
1571          );
1572  
1573          $query_params['capabilities'] = array(
1574              'description' => __( 'Limit result set to users matching at least one specific capability provided. Accepts csv list or single capability.' ),
1575              'type'        => 'array',
1576              'items'       => array(
1577                  'type' => 'string',
1578              ),
1579          );
1580  
1581          $query_params['who'] = array(
1582              'description' => __( 'Limit result set to users who are considered authors.' ),
1583              'type'        => 'string',
1584              'enum'        => array(
1585                  'authors',
1586              ),
1587          );
1588  
1589          $query_params['has_published_posts'] = array(
1590              'description' => __( 'Limit result set to users who have published posts.' ),
1591              'type'        => array( 'boolean', 'array' ),
1592              'items'       => array(
1593                  'type' => 'string',
1594                  'enum' => get_post_types( array( 'show_in_rest' => true ), 'names' ),
1595              ),
1596          );
1597  
1598          /**
1599           * Filters REST API collection parameters for the users controller.
1600           *
1601           * This filter registers the collection parameter, but does not map the
1602           * collection parameter to an internal WP_User_Query parameter.  Use the
1603           * `rest_user_query` filter to set WP_User_Query arguments.
1604           *
1605           * @since 4.7.0
1606           *
1607           * @param array $query_params JSON Schema-formatted collection parameters.
1608           */
1609          return apply_filters( 'rest_user_collection_params', $query_params );
1610      }
1611  }


Generated: Thu May 19 01:00:03 2022 Cross-referenced by PHPXref 0.7.1