e unscheduling the event. * @param string $hook Action hook, the execution of which will be unscheduled. * @param array $args Arguments to pass to the hook's callback function. * @param bool $wp_error Whether to return a WP_Error on failure. */ $pre = apply_filters( 'pre_clear_scheduled_hook', null, $hook, $args, $wp_error ); if ( null !== $pre ) { if ( $wp_error && false === $pre ) { return new WP_Error( 'pre_clear_scheduled_hook_false', __( 'A plugin prevented the hook from being cleared.' ) ); } if ( ! $wp_error && is_wp_error( $pre ) ) { return false; } return $pre; } /* * This logic duplicates wp_next_scheduled(). * It's required due to a scenario where wp_unschedule_event() fails due to update_option() failing, * and, wp_next_scheduled() returns the same schedule in an infinite loop. */ $crons = _get_cron_array(); if ( empty( $crons ) ) { return 0; } $results = array(); $key = md5( serialize( $args ) ); foreach ( $crons as $timestamp => $cron ) { if ( isset( $cron[ $hook ][ $key ] ) ) { $results[] = wp_unschedule_event( $timestamp, $hook, $args, true ); } } $errors = array_filter( $results, 'is_wp_error' ); $error = new WP_Error(); if ( $errors ) { if ( $wp_error ) { array_walk( $errors, array( $error, 'merge_from' ) ); return $error; } return false; } return count( $results ); } /** * Unschedules all events attached to the hook. * * Can be useful for plugins when deactivating to clean up the cron queue. * * Warning: This function may return Boolean FALSE, but may also return a non-Boolean * value which evaluates to FALSE. For information about casting to booleans see the * {@link https://www.php.net/manual/en/language.types.boolean.php PHP documentation}. Use * the `===` operator for testing the return value of this function. * * @since 4.9.0 * @since 5.1.0 Return value added to indicate success or failure. * @since 5.7.0 The `$wp_error` parameter was added. * * @param string $hook Action hook, the execution of which will be unscheduled. * @param bool $wp_error Optional. Whether to return a WP_Error on failure. Default false. * @return int|false|WP_Error On success an integer indicating number of events unscheduled (0 indicates no * events were registered on the hook), false or WP_Error if unscheduling fails. */ function wp_unschedule_hook( $hook, $wp_error = false ) { /** * Filter to preflight or hijack clearing all events attached to the hook. * * Returning a non-null value will short-circuit the normal unscheduling * process, causing the function to return the filtered value instead. * * For plugins replacing wp-cron, return the number of events successfully * unscheduled (zero if no events were registered with the hook) or false * if unscheduling one or more events fails. * * @since 5.1.0 * @since 5.7.0 The `$wp_error` parameter was added, and a `WP_Error` object can now be returned. * * @param null|int|false|WP_Error $pre Value to return instead. Default null to continue unscheduling the hook. * @param string $hook Action hook, the execution of which will be unscheduled. * @param bool $wp_error Whether to return a WP_Error on failure. */ $pre = apply_filters( 'pre_unschedule_hook', null, $hook, $wp_error ); if ( null !== $pre ) { if ( $wp_error && false === $pre ) { return new WP_Error( 'pre_unschedule_hook_false', __( 'A plugin prevented the hook from being cleared.' ) ); } if ( ! $wp_error && is_wp_error( $pre ) ) { return false; } return $pre; } $crons = _get_cron_array(); if ( empty( $crons ) ) { return 0; } $results = array(); foreach ( $crons as $timestamp => $args ) { if ( ! empty( $crons[ $timestamp ][ $hook ] ) ) { $results[] = count( $crons[ $timestamp ][ $hook ] ); } unset( $crons[ $timestamp ][ $hook ] ); if ( empty( $crons[ $timestamp ] ) ) { unset( $crons[ $timestamp ] ); } } /* * If the results are empty (zero events to unschedule), no attempt * to update the cron array is required. */ if ( empty( $results ) ) { return 0; } $set = _set_cron_array( $crons, $wp_error ); if ( true === $set ) { return array_sum( $results ); } return $set; } /** * Retrieves a scheduled event. * * Retrieves the full event object for a given event, if no timestamp is specified the next * scheduled event is returned. * * @since 5.1.0 * * @param string $hook Action hook of the event. * @param array $args Optional. Array containing each separate argument to pass to the hook's callback function. * Although not passed to a callback, these arguments are used to uniquely identify the * event, so they should be the same as those used when originally scheduling the event. * Default empty array. * @param int|null $timestamp Optional. Unix timestamp (UTC) of the event. If not specified, the next scheduled event * is returned. Default null. * @return object|false { * The event object. False if the event does not exist. * * @type string $hook Action hook to execute when the event is run. * @type int $timestamp Unix timestamp (UTC) for when to next run the event. * @type string|false $schedule How often the event should subsequently recur. * @type array $args Array containing each separate argument to pass to the hook's callback function. * @type int $interval Optional. The interval time in seconds for the schedule. Only present for recurring events. * } */ function wp_get_scheduled_event( $hook, $args = array(), $timestamp = null ) { /** * Filter to preflight or hijack retrieving a scheduled event. * * Returning a non-null value will short-circuit the normal process, * returning the filtered value instead. * * Return false if the event does not exist, otherwise an event object * should be returned. * * @since 5.1.0 * * @param null|false|object $pre Value to return instead. Default null to continue retrieving the event. * @param string $hook Action hook of the event. * @param array $args Array containing each separate argument to pass to the hook's callback function. * Although not passed to a callback, these arguments are used to uniquely identify * the event. * @param int|null $timestamp Unix timestamp (UTC) of the event. Null to retrieve next scheduled event. */ $pre = apply_filters( 'pre_get_scheduled_event', null, $hook, $args, $timestamp ); if ( null !== $pre ) { return $pre; } if ( null !== $timestamp && ! is_numeric( $timestamp ) ) { return false; } $crons = _get_cron_array(); if ( empty( $crons ) ) { return false; } $key = md5( serialize( $args ) ); if ( ! $timestamp ) { // Get next event. $next = false; foreach ( $crons as $timestamp => $cron ) { if ( isset( $cron[ $hook ][ $key ] ) ) { $next = $timestamp; break; } } if ( ! $next ) { return false; } $timestamp = $next; } elseif ( ! isset( $crons[ $timestamp ][ $hook ][ $key ] ) ) { return false; } $event = (object) array( 'hook' => $hook, 'timestamp' => $timestamp, 'schedule' => $crons[ $timestamp ][ $hook ][ $key ]['schedule'], 'args' => $args, ); if ( isset( $crons[ $timestamp ][ $hook ][ $key ]['interval'] ) ) { $event->interval = $crons[ $timestamp ][ $hook ][ $key ]['interval']; } return $event; } /** * Retrieves the next timestamp for an event. * * @since 2.1.0 * * @param string $hook Action hook of the event. * @param array $args Optional. Array containing each separate argument to pass to the hook's callback function. * Although not passed to a callback, these arguments are used to uniquely identify the * event, so they should be the same as those used when originally scheduling the event. * Default empty array. * @return int|false The Unix timestamp of the next time the event will occur. False if the event doesn't exist. */ function wp_next_scheduled( $hook, $args = array() ) { $next_event = wp_get_scheduled_event( $hook, $args ); if ( ! $next_event ) { return false; } return $next_event->timestamp; } /** * Sends a request to run cron through HTTP request that doesn't halt page loading. * * @since 2.1.0 * @since 5.1.0 Return values added. * * @param int $gmt_time Optional. Unix timestamp (UTC). Default 0 (current time is used). * @return bool True if spawned, false if no events spawned. */ function spawn_cron( $gmt_time = 0 ) { if ( ! $gmt_time ) { $gmt_time = microtime( true ); } if ( defined( 'DOING_CRON' ) || isset( $_GET['doing_wp_cron'] ) ) { return false; } /* * Get the cron lock, which is a Unix timestamp of when the last cron was spawned * and has not finished running. * * Multiple processes on multiple web servers can run this code concurrently, * this lock attempts to make spawning as atomic as possible. */ $lock = get_transient( 'doing_cron' ); if ( $lock > $gmt_time + 10 * MINUTE_IN_SECONDS ) { $lock = 0; } // Don't run if another process is currently running it or more than once every 60 sec. if ( $lock + WP_CRON_LOCK_TIMEOUT > $gmt_time ) { return false; } // Sanity check. $crons = wp_get_ready_cron_jobs(); if ( empty( $crons ) ) { return false; } $keys = array_keys( $crons ); if ( isset( $keys[0] ) && $keys[0] > $gmt_time ) { return false; } if ( defined( 'ALTERNATE_WP_CRON' ) && ALTERNATE_WP_CRON ) { if ( 'GET' !== $_SERVER['REQUEST_METHOD'] || defined( 'DOING_AJAX' ) || defined( 'XMLRPC_REQUEST' ) ) { return false; } $doing_wp_cron = sprintf( '%.22F', $gmt_time ); set_transient( 'doing_cron', $doing_wp_cron ); ob_start(); wp_redirect( add_query_arg( 'doing_wp_cron', $doing_wp_cron, wp_unslash( $_SERVER['REQUEST_URI'] ) ) ); echo ' '; // Flush any buffers and send the headers. wp_ob_end_flush_all(); flush(); require_once ABSPATH . 'wp-cron.php'; return true; } // Set the cron lock with the current unix timestamp, when the cron is being spawned. $doing_wp_cron = sprintf( '%.22F', $gmt_time ); set_transient( 'doing_cron', $doing_wp_cron ); /** * Filters the cron request arguments. * * @since 3.5.0 * @since 4.5.0 The `$doing_wp_cron` parameter was added. * * @param array $cron_request_array { * An array of cron request URL arguments. * * @type string $url The cron request URL. * @type int $key The 22 digit GMT microtime. * @type array $args { * An array of cron request arguments. * * @type int $timeout The request timeout in seconds. Default .01 seconds. * @type bool $blocking Whether to set blocking for the request. Default false. * @type bool $sslverify Whether SSL should be verified for the request. Default false. * } * } * @param string $doing_wp_cron The unix timestamp of the cron lock. */ $cron_request = apply_filters( 'cron_request', array( 'url' => add_query_arg( 'doing_wp_cron', $doing_wp_cron, site_url( 'wp-cron.php' ) ), 'key' => $doing_wp_cron, 'args' => array( 'timeout' => 0.01, 'blocking' => false, /** This filter is documented in wp-includes/class-wp-http-streams.php */ 'sslverify' => apply_filters( 'https_local_ssl_verify', false ), ), ), $doing_wp_cron ); $result = wp_remote_post( $cron_request['url'], $cron_request['args'] ); return ! is_wp_error( $result ); } /** * Registers _wp_cron() to run on the {@see 'wp_loaded'} action. * * If the {@see 'wp_loaded'} action has already fired, this function calls * _wp_cron() directly. * * Warning: This function may return Boolean FALSE, but may also return a non-Boolean * value which evaluates to FALSE. For information about casting to booleans see the * {@link https://www.php.net/manual/en/language.types.boolean.php PHP documentation}. Use * the `===` operator for testing the return value of this function. * * @since 2.1.0 * @since 5.1.0 Return value added to indicate success or failure. * @since 5.7.0 Functionality moved to _wp_cron() to which this becomes a wrapper. * * @return bool|int|void On success an integer indicating number of events spawned (0 indicates no * events needed to be spawned), false if spawning fails for one or more events or * void if the function registered _wp_cron() to run on the action. */ function wp_cron() { if ( did_action( 'wp_loaded' ) ) { return _wp_cron(); } add_action( 'wp_loaded', '_wp_cron', 20 ); } /** * Runs scheduled callbacks or spawns cron for all scheduled events. * * Warning: This function may return Boolean FALSE, but may also return a non-Boolean * value which evaluates to FALSE. For information about casting to booleans see the * {@link https://www.php.net/manual/en/language.types.boolean.php PHP documentation}. Use * the `===` operator for testing the return value of this function. * * @since 5.7.0 * @access private * * @return int|false On success an integer indicating number of events spawned (0 indicates no * events needed to be spawned), false if spawning fails for one or more events. */ function _wp_cron() { // Prevent infinite loops caused by lack of wp-cron.php. if ( str_contains( $_SERVER['REQUEST_URI'], '/wp-cron.php' ) || ( defined( 'DISABLE_WP_CRON' ) && DISABLE_WP_CRON ) ) { return 0; } $crons = wp_get_ready_cron_jobs(); if ( empty( $crons ) ) { return 0; } $gmt_time = microtime( true ); $keys = array_keys( $crons ); if ( isset( $keys[0] ) && $keys[0] > $gmt_time ) { return 0; } $schedules = wp_get_schedules(); $results = array(); foreach ( $crons as $timestamp => $cronhooks ) { if ( $timestamp > $gmt_time ) { break; } foreach ( (array) $cronhooks as $hook => $args ) { if ( isset( $schedules[ $hook ]['callback'] ) && ! call_user_func( $schedules[ $hook ]['callback'] ) ) { continue; } $results[] = spawn_cron( $gmt_time ); break 2; } } if ( in_array( false, $results, true ) ) { return false; } return count( $results ); } /** * Retrieves supported event recurrence schedules. * * The default supported recurrences are 'hourly', 'twicedaily', 'daily', and 'weekly'. * A plugin may add more by hooking into the {@see 'cron_schedules'} filter. * The filter accepts an array of arrays. The outer array has a key that is the name * of the schedule, for example 'monthly'. The value is an array with two keys, * one is 'interval' and the other is 'display'. * * The 'interval' is a number in seconds of when the cron job should run. * So for 'hourly' the time is `HOUR_IN_SECONDS` (60 * 60 or 3600). For 'monthly', * the value would be `MONTH_IN_SECONDS` (30 * 24 * 60 * 60 or 2592000). * * The 'display' is the description. For the 'monthly' key, the 'display' * would be `__( 'Once Monthly' )`. * * For your plugin, you will be passed an array. You can easily add your * schedule by doing the following. * * // Filter parameter variable name is 'array'. * $array['monthly'] = array( * 'interval' => MONTH_IN_SECONDS, * 'display' => __( 'Once Monthly' ) * ); * * @since 2.1.0 * @since 5.4.0 The 'weekly' schedule was added. * * @return array { * The array of cron schedules keyed by the schedule name. * * @type array ...$0 { * Cron schedule information. * * @type int $interval The schedule interval in seconds. * @type string $display The schedule display name. * } * } */ function wp_get_schedules() { $schedules = array( 'hourly' => array( 'interval' => HOUR_IN_SECONDS, 'display' => __( 'Once Hourly' ), ), 'twicedaily' => array( 'interval' => 12 * HOUR_IN_SECONDS, 'display' => __( 'Twice Daily' ), ), 'daily' => array( 'interval' => DAY_IN_SECONDS, 'display' => __( 'Once Daily' ), ), 'weekly' => array( 'interval' => WEEK_IN_SECONDS, 'display' => __( 'Once Weekly' ), ), ); /** * Filters the non-default cron schedules. * * @since 2.1.0 * * @param array $new_schedules { * An array of non-default cron schedules keyed by the schedule name. Default empty array. * * @type array ...$0 { * Cron schedule information. * * @type int $interval The schedule interval in seconds. * @type string $display The schedule display name. * } * } */ return array_merge( apply_filters( 'cron_schedules', array() ), $schedules ); } /** * Retrieves the name of the recurrence schedule for an event. * * @see wp_get_schedules() for available schedules. * * @since 2.1.0 * @since 5.1.0 {@see 'get_schedule'} filter added. * * @param string $hook Action hook to identify the event. * @param array $args Optional. Arguments passed to the event's callback function. * Default empty array. * @return string|false Schedule name on success, false if no schedule. */ function wp_get_schedule( $hook, $args = array() ) { $schedule = false; $event = wp_get_scheduled_event( $hook, $args ); if ( $event ) { $schedule = $event->schedule; } /** * Filters the schedule name for a hook. * * @since 5.1.0 * * @param string|false $schedule Schedule for the hook. False if not found. * @param string $hook Action hook to execute when cron is run. * @param array $args Arguments to pass to the hook's callback function. */ return apply_filters( 'get_schedule', $schedule, $hook, $args ); } /** * Retrieves cron jobs ready to be run. * * Returns the results of _get_cron_array() limited to events ready to be run, * ie, with a timestamp in the past. * * @since 5.1.0 * * @return array[] Array of cron job arrays ready to be run. */ function wp_get_ready_cron_jobs() { /** * Filter to preflight or hijack retrieving ready cron jobs. * * Returning an array will short-circuit the normal retrieval of ready * cron jobs, causing the function to return the filtered value instead. * * @since 5.1.0 * * @param null|array[] $pre Array of ready cron tasks to return instead. Default null * to continue using results from _get_cron_array(). */ $pre = apply_filters( 'pre_get_ready_cron_jobs', null ); if ( null !== $pre ) { return $pre; } $crons = _get_cron_array(); $gmt_time = microtime( true ); $results = array(); foreach ( $crons as $timestamp => $cronhooks ) { if ( $timestamp > $gmt_time ) { break; } $results[ $timestamp ] = $cronhooks; } return $results; } // // Private functions. // /** * Retrieves cron info array option. * * @since 2.1.0 * @since 6.1.0 Return type modified to consistently return an array. * @access private * * @return array[] Array of cron events. */ function _get_cron_array() { $cron = get_option( 'cron' ); if ( ! is_array( $cron ) ) { return array(); } if ( ! isset( $cron['version'] ) ) { $cron = _upgrade_cron_array( $cron ); } unset( $cron['version'] ); return $cron; } /** * Updates the cron option with the new cron array. * * @since 2.1.0 * @since 5.1.0 Return value modified to outcome of update_option(). * @since 5.7.0 The `$wp_error` parameter was added. * * @access private * * @param array[] $cron Array of cron info arrays from _get_cron_array(). * @param bool $wp_error Optional. Whether to return a WP_Error on failure. Default false. * @return bool|WP_Error True if cron array updated. False or WP_Error on failure. */ function _set_cron_array( $cron, $wp_error = false ) { if ( ! is_array( $cron ) ) { $cron = array(); } $cron['version'] = 2; $result = update_option( 'cron', $cron ); if ( $wp_error && ! $result ) { return new WP_Error( 'could_not_set', __( 'The cron event list could not be saved.' ) ); } return $result; } /** * Upgrades a cron info array. * * This function upgrades the cron info array to version 2. * * @since 2.1.0 * @access private * * @param array $cron Cron info array from _get_cron_array(). * @return array An upgraded cron info array. */ function _upgrade_cron_array( $cron ) { if ( isset( $cron['version'] ) && 2 == $cron['version'] ) { return $cron; } $new_cron = array(); foreach ( (array) $cron as $timestamp => $hooks ) { foreach ( (array) $hooks as $hook => $args ) { $key = md5( serialize( $args['args'] ) ); $new_cron[ $timestamp ][ $hook ][ $key ] = $args; } } $new_cron['version'] = 2; update_option( 'cron', $new_cron ); return $new_cron; } request['id'] = get_current_user_id(); return $this->update_item( $request ); } /** * Checks if a given request has access delete a user. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has access to delete the item, WP_Error object otherwise. */ public function delete_item_permissions_check( $request ) { $user = $this->get_user( $request['id'] ); if ( is_wp_error( $user ) ) { return $user; } if ( ! current_user_can( 'delete_user', $user->ID ) ) { return new WP_Error( 'rest_user_cannot_delete', __( 'Sorry, you are not allowed to delete this user.' ), array( 'status' => rest_authorization_required_code() ) ); } return true; } /** * Deletes a single user. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ public function delete_item( $request ) { // We don't support delete requests in multisite. if ( is_multisite() ) { return new WP_Error( 'rest_cannot_delete', __( 'The user cannot be deleted.' ), array( 'status' => 501 ) ); } $user = $this->get_user( $request['id'] ); if ( is_wp_error( $user ) ) { return $user; } $id = $user->ID; $reassign = false === $request['reassign'] ? null : absint( $request['reassign'] ); $force = isset( $request['force'] ) ? (bool) $request['force'] : false; // We don't support trashing for users. if ( ! $force ) { return new WP_Error( 'rest_trash_not_supported', /* translators: %s: force=true */ sprintf( __( "Users do not support trashing. Set '%s' to delete." ), 'force=true' ), array( 'status' => 501 ) ); } if ( ! empty( $reassign ) ) { if ( $reassign === $id || ! get_userdata( $reassign ) ) { return new WP_Error( 'rest_user_invalid_reassign', __( 'Invalid user ID for reassignment.' ), array( 'status' => 400 ) ); } } $request->set_param( 'context', 'edit' ); $previous = $this->prepare_item_for_response( $user, $request ); // Include user admin functions to get access to wp_delete_user(). require_once ABSPATH . 'wp-admin/includes/user.php'; $result = wp_delete_user( $id, $reassign ); if ( ! $result ) { return new WP_Error( 'rest_cannot_delete', __( 'The user cannot be deleted.' ), array( 'status' => 500 ) ); } $response = new WP_REST_Response(); $response->set_data( array( 'deleted' => true, 'previous' => $previous->get_data(), ) ); /** * Fires immediately after a user is deleted via the REST API. * * @since 4.7.0 * * @param WP_User $user The user data. * @param WP_REST_Response $response The response returned from the API. * @param WP_REST_Request $request The request sent to the API. */ do_action( 'rest_delete_user', $user, $response, $request ); return $response; } /** * Checks if a given request has access to delete the current user. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has access to delete the item, WP_Error object otherwise. */ public function delete_current_item_permissions_check( $request ) { $request['id'] = get_current_user_id(); return $this->delete_item_permissions_check( $request ); } /** * Deletes the current user. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ public function delete_current_item( $request ) { $request['id'] = get_current_user_id(); return $this->delete_item( $request ); } /** * Prepares a single user output for response. * * @since 4.7.0 * @since 5.9.0 Renamed `$user` to `$item` to match parent class for PHP 8 named parameter support. * * @param WP_User $item User object. * @param WP_REST_Request $request Request object. * @return WP_REST_Response Response object. */ public function prepare_item_for_response( $item, $request ) { // Restores the more descriptive, specific name for use within this method. $user = $item; $data = array(); $fields = $this->get_fields_for_response( $request ); if ( in_array( 'id', $fields, true ) ) { $data['id'] = $user->ID; } if ( in_array( 'username', $fields, true ) ) { $data['username'] = $user->user_login; } if ( in_array( 'name', $fields, true ) ) { $data['name'] = $user->display_name; } if ( in_array( 'first_name', $fields, true ) ) { $data['first_name'] = $user->first_name; } if ( in_array( 'last_name', $fields, true ) ) { $data['last_name'] = $user->last_name; } if ( in_array( 'email', $fields, true ) ) { $data['email'] = $user->user_email; } if ( in_array( 'url', $fields, true ) ) { $data['url'] = $user->user_url; } if ( in_array( 'description', $fields, true ) ) { $data['description'] = $user->description; } if ( in_array( 'link', $fields, true ) ) { $data['link'] = get_author_posts_url( $user->ID, $user->user_nicename ); } if ( in_array( 'locale', $fields, true ) ) { $data['locale'] = get_user_locale( $user ); } if ( in_array( 'nickname', $fields, true ) ) { $data['nickname'] = $user->nickname; } if ( in_array( 'slug', $fields, true ) ) { $data['slug'] = $user->user_nicename; } if ( in_array( 'roles', $fields, true ) ) { // Defensively call array_values() to ensure an array is returned. $data['roles'] = array_values( $user->roles ); } if ( in_array( 'registered_date', $fields, true ) ) { $data['registered_date'] = gmdate( 'c', strtotime( $user->user_registered ) ); } if ( in_array( 'capabilities', $fields, true ) ) { $data['capabilities'] = (object) $user->allcaps; } if ( in_array( 'extra_capabilities', $fields, true ) ) { $data['extra_capabilities'] = (object) $user->caps; } if ( in_array( 'avatar_urls', $fields, true ) ) { $data['avatar_urls'] = rest_get_avatar_urls( $user ); } if ( in_array( 'meta', $fields, true ) ) { $data['meta'] = $this->meta->get_value( $user->ID, $request ); } $context = ! empty( $request['context'] ) ? $request['context'] : 'embed'; $data = $this->add_additional_fields_to_object( $data, $request ); $data = $this->filter_response_by_context( $data, $context ); // Wrap the data in a response object. $response = rest_ensure_response( $data ); if ( rest_is_field_included( '_links', $fields ) || rest_is_field_included( '_embedded', $fields ) ) { $response->add_links( $this->prepare_links( $user ) ); } /** * Filters user data returned from the REST API. * * @since 4.7.0 * * @param WP_REST_Response $response The response object. * @param WP_User $user User object used to create response. * @param WP_REST_Request $request Request object. */ return apply_filters( 'rest_prepare_user', $response, $user, $request ); } /** * Prepares links for the user request. * * @since 4.7.0 * * @param WP_User $user User object. * @return array Links for the given user. */ protected function prepare_links( $user ) { $links = array( 'self' => array( 'href' => rest_url( sprintf( '%s/%s/%d', $this->namespace, $this->rest_base, $user->ID ) ), ), 'collection' => array( 'href' => rest_url( sprintf( '%s/%s', $this->namespace, $this->rest_base ) ), ), ); return $links; } /** * Prepares a single user for creation or update. * * @since 4.7.0 * * @param WP_REST_Request $request Request object. * @return object User object. */ protected function prepare_item_for_database( $request ) { $prepared_user = new stdClass(); $schema = $this->get_item_schema(); // Required arguments. if ( isset( $request['email'] ) && ! empty( $schema['properties']['email'] ) ) { $prepared_user->user_email = $request['email']; } if ( isset( $request['username'] ) && ! empty( $schema['properties']['username'] ) ) { $prepared_user->user_login = $request['username']; } if ( isset( $request['password'] ) && ! empty( $schema['properties']['password'] ) ) { $prepared_user->user_pass = $request['password']; } // Optional arguments. if ( isset( $request['id'] ) ) { $prepared_user->ID = absint( $request['id'] ); } if ( isset( $request['name'] ) && ! empty( $schema['properties']['name'] ) ) { $prepared_user->display_name = $request['name']; } if ( isset( $request['first_name'] ) && ! empty( $schema['properties']['first_name'] ) ) { $prepared_user->first_name = $request['first_name']; } if ( isset( $request['last_name'] ) && ! empty( $schema['properties']['last_name'] ) ) { $prepared_user->last_name = $request['last_name']; } if ( isset( $request['nickname'] ) && ! empty( $schema['properties']['nickname'] ) ) { $prepared_user->nickname = $request['nickname']; } if ( isset( $request['slug'] ) && ! empty( $schema['properties']['slug'] ) ) { $prepared_user->user_nicename = $request['slug']; } if ( isset( $request['description'] ) && ! empty( $schema['properties']['description'] ) ) { $prepared_user->description = $request['description']; } if ( isset( $request['url'] ) && ! empty( $schema['properties']['url'] ) ) { $prepared_user->user_url = $request['url']; } if ( isset( $request['locale'] ) && ! empty( $schema['properties']['locale'] ) ) { $prepared_user->locale = $request['locale']; } // Setting roles will be handled outside of this function. if ( isset( $request['roles'] ) ) { $prepared_user->role = false; } /** * Filters user data before insertion via the REST API. * * @since 4.7.0 * * @param object $prepared_user User object. * @param WP_REST_Request $request Request object. */ return apply_filters( 'rest_pre_insert_user', $prepared_user, $request ); } /** * Determines if the current user is allowed to make the desired roles change. * * @since 4.7.0 * * @global WP_Roles $wp_roles WordPress role management object. * * @param int $user_id User ID. * @param array $roles New user roles. * @return true|WP_Error True if the current user is allowed to make the role change, * otherwise a WP_Error object. */ protected function check_role_update( $user_id, $roles ) { global $wp_roles; foreach ( $roles as $role ) { if ( ! isset( $wp_roles->role_objects[ $role ] ) ) { return new WP_Error( 'rest_user_invalid_role', /* translators: %s: Role key. */ sprintf( __( 'The role %s does not exist.' ), $role ), array( 'status' => 400 ) ); } $potential_role = $wp_roles->role_objects[ $role ]; /* * Don't let anyone with 'edit_users' (admins) edit their own role to something without it. * Multisite super admins can freely edit their blog roles -- they possess all caps. */ if ( ! ( is_multisite() && current_user_can( 'manage_sites' ) ) && get_current_user_id() === $user_id && ! $potential_role->has_cap( 'edit_users' ) ) { return new WP_Error( 'rest_user_invalid_role', __( 'Sorry, you are not allowed to give users that role.' ), array( 'status' => rest_authorization_required_code() ) ); } // Include user admin functions to get access to get_editable_roles(). require_once ABSPATH . 'wp-admin/includes/user.php'; // The new role must be editable by the logged-in user. $editable_roles = get_editable_roles(); if ( empty( $editable_roles[ $role ] ) ) { return new WP_Error( 'rest_user_invalid_role', __( 'Sorry, you are not allowed to give users that role.' ), array( 'status' => 403 ) ); } } return true; } /** * Check a username for the REST API. * * Performs a couple of checks like edit_user() in wp-admin/includes/user.php. * * @since 4.7.0 * * @param string $value The username submitted in the request. * @param WP_REST_Request $request Full details about the request. * @param string $param The parameter name. * @return string|WP_Error The sanitized username, if valid, otherwise an error. */ public function check_username( $value, $request, $param ) { $username = (string) $value; if ( ! validate_username( $username ) ) { return new WP_Error( 'rest_user_invalid_username', __( 'This username is invalid because it uses illegal characters. Please enter a valid username.' ), array( 'status' => 400 ) ); } /** This filter is documented in wp-includes/user.php */ $illegal_logins = (array) apply_filters( 'illegal_user_logins', array() ); if ( in_array( strtolower( $username ), array_map( 'strtolower', $illegal_logins ), true ) ) { return new WP_Error( 'rest_user_invalid_username', __( 'Sorry, that username is not allowed.' ), array( 'status' => 400 ) ); } return $username; } /** * Check a user password for the REST API. * * Performs a couple of checks like edit_user() in wp-admin/includes/user.php. * * @since 4.7.0 * * @param string $value The password submitted in the request. * @param WP_REST_Request $request Full details about the request. * @param string $param The parameter name. * @return string|WP_Error The sanitized password, if valid, otherwise an error. */ public function check_user_password( $value, $request, $param ) { $password = (string) $value; if ( empty( $password ) ) { return new WP_Error( 'rest_user_invalid_password', __( 'Passwords cannot be empty.' ), array( 'status' => 400 ) ); } if ( str_contains( $password, '\\' ) ) { return new WP_Error( 'rest_user_invalid_password', sprintf( /* translators: %s: The '\' character. */ __( 'Passwords cannot contain the "%s" character.' ), '\\' ), array( 'status' => 400 ) ); } return $password; } /** * Retrieves the user's schema, conforming to JSON Schema. * * @since 4.7.0 * * @return array Item schema data. */ public function get_item_schema() { if ( $this->schema ) { return $this->add_additional_fields_schema( $this->schema ); } $schema = array( '$schema' => 'http://json-schema.org/draft-04/schema#', 'title' => 'user', 'type' => 'object', 'properties' => array( 'id' => array( 'description' => __( 'Unique identifier for the user.' ), 'type' => 'integer', 'context' => array( 'embed', 'view', 'edit' ), 'readonly' => true, ), 'username' => array( 'description' => __( 'Login name for the user.' ), 'type' => 'string', 'context' => array( 'edit' ), 'required' => true, 'arg_options' => array( 'sanitize_callback' => array( $this, 'check_username' ), ), ), 'name' => array( 'description' => __( 'Display name for the user.' ), 'type' => 'string', 'context' => array( 'embed', 'view', 'edit' ), 'arg_options' => array( 'sanitize_callback' => 'sanitize_text_field', ), ), 'first_name' => array( 'description' => __( 'First name for the user.' ), 'type' => 'string', 'context' => array( 'edit' ), 'arg_options' => array( 'sanitize_callback' => 'sanitize_text_field', ), ), 'last_name' => array( 'description' => __( 'Last name for the user.' ), 'type' => 'string', 'context' => array( 'edit' ), 'arg_options' => array( 'sanitize_callback' => 'sanitize_text_field', ), ), 'email' => array( 'description' => __( 'The email address for the user.' ), 'type' => 'string', 'format' => 'email', 'context' => array( 'edit' ), 'required' => true, ), 'url' => array( 'description' => __( 'URL of the user.' ), 'type' => 'string', 'format' => 'uri', 'context' => array( 'embed', 'view', 'edit' ), ), 'description' => array( 'description' => __( 'Description of the user.' ), 'type' => 'string', 'context' => array( 'embed', 'view', 'edit' ), ), 'link' => array( 'description' => __( 'Author URL of the user.' ), 'type' => 'string', 'format' => 'uri', 'context' => array( 'embed', 'view', 'edit' ), 'readonly' => true, ), 'locale' => array( 'description' => __( 'Locale for the user.' ), 'type' => 'string', 'enum' => array_merge( array( '', 'en_US' ), get_available_languages() ), 'context' => array( 'edit' ), ), 'nickname' => array( 'description' => __( 'The nickname for the user.' ), 'type' => 'string', 'context' => array( 'edit' ), 'arg_options' => array( 'sanitize_callback' => 'sanitize_text_field', ), ), 'slug' => array( 'description' => __( 'An alphanumeric identifier for the user.' ), 'type' => 'string', 'context' => array( 'embed', 'view', 'edit' ), 'arg_options' => array( 'sanitize_callback' => array( $this, 'sanitize_slug' ), ), ), 'registered_date' => array( 'description' => __( 'Registration date for the user.' ), 'type' => 'string', 'format' => 'date-time', 'context' => array( 'edit' ), 'readonly' => true, ), 'roles' => array( 'description' => __( 'Roles assigned to the user.' ), 'type' => 'array', 'items' => array( 'type' => 'string', ), 'context' => array( 'edit' ), ), 'password' => array( 'description' => __( 'Password for the user (never included).' ), 'type' => 'string', 'context' => array(), // Password is never displayed. 'required' => true, 'arg_options' => array( 'sanitize_callback' => array( $this, 'check_user_password' ), ), ), 'capabilities' => array( 'description' => __( 'All capabilities assigned to the user.' ), 'type' => 'object', 'context' => array( 'edit' ), 'readonly' => true, ), 'extra_capabilities' => array( 'description' => __( 'Any extra capabilities assigned to the user.' ), 'type' => 'object', 'context' => array( 'edit' ), 'readonly' => true, ), ), ); if ( get_option( 'show_avatars' ) ) { $avatar_properties = array(); $avatar_sizes = rest_get_avatar_sizes(); foreach ( $avatar_sizes as $size ) { $avatar_properties[ $size ] = array( /* translators: %d: Avatar image size in pixels. */ 'description' => sprintf( __( 'Avatar URL with image size of %d pixels.' ), $size ), 'type' => 'string', 'format' => 'uri', 'context' => array( 'embed', 'view', 'edit' ), ); } $schema['properties']['avatar_urls'] = array( 'description' => __( 'Avatar URLs for the user.' ), 'type' => 'object', 'context' => array( 'embed', 'view', 'edit' ), 'readonly' => true, 'properties' => $avatar_properties, ); } $schema['properties']['meta'] = $this->meta->get_field_schema(); $this->schema = $schema; return $this->add_additional_fields_schema( $this->schema ); } /** * Retrieves the query params for collections. * * @since 4.7.0 * * @return array Collection parameters. */ public function get_collection_params() { $query_params = parent::get_collection_params(); $query_params['context']['default'] = 'view'; $query_params['exclude'] = array( 'description' => __( 'Ensure result set excludes specific IDs.' ), 'type' => 'array', 'items' => array( 'type' => 'integer', ), 'default' => array(), ); $query_params['include'] = array( 'description' => __( 'Limit result set to specific IDs.' ), 'type' => 'array', 'items' => array( 'type' => 'integer', ), 'default' => array(), ); $query_params['offset'] = array( 'description' => __( 'Offset the result set by a specific number of items.' ), 'type' => 'integer', ); $query_params['order'] = array( 'default' => 'asc', 'description' => __( 'Order sort attribute ascending or descending.' ), 'enum' => array( 'asc', 'desc' ), 'type' => 'string', ); $query_params['orderby'] = array( 'default' => 'name', 'description' => __( 'Sort collection by user attribute.' ), 'enum' => array( 'id', 'include', 'name', 'registered_date', 'slug', 'include_slugs', 'email', 'url', ), 'type' => 'string', ); $query_params['slug'] = array( 'description' => __( 'Limit result set to users with one or more specific slugs.' ), 'type' => 'array', 'items' => array( 'type' => 'string', ), ); $query_params['roles'] = array( 'description' => __( 'Limit result set to users matching at least one specific role provided. Accepts csv list or single role.' ), 'type' => 'array', 'items' => array( 'type' => 'string', ), ); $query_params['capabilities'] = array( 'description' => __( 'Limit result set to users matching at least one specific capability provided. Accepts csv list or single capability.' ), 'type' => 'array', 'items' => array( 'type' => 'string', ), ); $query_params['who'] = array( 'description' => __( 'Limit result set to users who are considered authors.' ), 'type' => 'string', 'enum' => array( 'authors', ), ); $query_params['has_published_posts'] = array( 'description' => __( 'Limit result set to users who have published posts.' ), 'type' => array( 'boolean', 'array' ), 'items' => array( 'type' => 'string', 'enum' => get_post_types( array( 'show_in_rest' => true ), 'names' ), ), ); /** * Filters REST API collection parameters for the users controller. * * This filter registers the collection parameter, but does not map the * collection parameter to an internal WP_User_Query parameter. Use the * `rest_user_query` filter to set WP_User_Query arguments. * * @since 4.7.0 * * @param array $query_params JSON Schema-formatted collection parameters. */ return apply_filters( 'rest_user_collection_params', $query_params ); } }