* @param string[] $caps Array of the user's capabilities. */ $allowed = apply_filters( "auth_{$object_type}_meta_{$meta_key}", $allowed, $meta_key, $object_id, $user_id, $cap, $caps ); } if ( ! empty( $object_subtype ) ) { /** * Filters whether the user is allowed to edit meta for specific object types/subtypes. * * Return true to have the mapped meta caps from `edit_{$object_type}` apply. * * The dynamic portion of the hook name, `$object_type` refers to the object type being filtered. * The dynamic portion of the hook name, `$object_subtype` refers to the object subtype being filtered. * The dynamic portion of the hook name, `$meta_key`, refers to the meta key passed to map_meta_cap(). * * @since 4.6.0 As `auth_post_{$post_type}_meta_{$meta_key}`. * @since 4.7.0 Renamed from `auth_post_{$post_type}_meta_{$meta_key}` to * `auth_{$object_type}_{$object_subtype}_meta_{$meta_key}`. * @deprecated 4.9.8 Use {@see 'auth_{$object_type}_meta_{$meta_key}_for_{$object_subtype}'} instead. * * @param bool $allowed Whether the user can add the object meta. Default false. * @param string $meta_key The meta key. * @param int $object_id Object ID. * @param int $user_id User ID. * @param string $cap Capability name. * @param string[] $caps Array of the user's capabilities. */ $allowed = apply_filters_deprecated( "auth_{$object_type}_{$object_subtype}_meta_{$meta_key}", array( $allowed, $meta_key, $object_id, $user_id, $cap, $caps ), '4.9.8', "auth_{$object_type}_meta_{$meta_key}_for_{$object_subtype}" ); } if ( ! $allowed ) { $caps[] = $cap; } } break; case 'edit_comment': if ( ! isset( $args[0] ) ) { /* translators: %s: Capability name. */ $message = __( 'When checking for the %s capability, you must always check it against a specific comment.' ); _doing_it_wrong( __FUNCTION__, sprintf( $message, '' . $cap . '' ), '6.1.0' ); $caps[] = 'do_not_allow'; break; } $comment = get_comment( $args[0] ); if ( ! $comment ) { $caps[] = 'do_not_allow'; break; } $post = get_post( $comment->comment_post_ID ); /* * If the post doesn't exist, we have an orphaned comment. * Fall back to the edit_posts capability, instead. */ if ( $post ) { $caps = map_meta_cap( 'edit_post', $user_id, $post->ID ); } else { $caps = map_meta_cap( 'edit_posts', $user_id ); } break; case 'unfiltered_upload': if ( defined( 'ALLOW_UNFILTERED_UPLOADS' ) && ALLOW_UNFILTERED_UPLOADS && ( ! is_multisite() || is_super_admin( $user_id ) ) ) { $caps[] = $cap; } else { $caps[] = 'do_not_allow'; } break; case 'edit_css': case 'unfiltered_html': // Disallow unfiltered_html for all users, even admins and super admins. if ( defined( 'DISALLOW_UNFILTERED_HTML' ) && DISALLOW_UNFILTERED_HTML ) { $caps[] = 'do_not_allow'; } elseif ( is_multisite() && ! is_super_admin( $user_id ) ) { $caps[] = 'do_not_allow'; } else { $caps[] = 'unfiltered_html'; } break; case 'edit_files': case 'edit_plugins': case 'edit_themes': // Disallow the file editors. if ( defined( 'DISALLOW_FILE_EDIT' ) && DISALLOW_FILE_EDIT ) { $caps[] = 'do_not_allow'; } elseif ( ! wp_is_file_mod_allowed( 'capability_edit_themes' ) ) { $caps[] = 'do_not_allow'; } elseif ( is_multisite() && ! is_super_admin( $user_id ) ) { $caps[] = 'do_not_allow'; } else { $caps[] = $cap; } break; case 'update_plugins': case 'delete_plugins': case 'install_plugins': case 'upload_plugins': case 'update_themes': case 'delete_themes': case 'install_themes': case 'upload_themes': case 'update_core': /* * Disallow anything that creates, deletes, or updates core, plugin, or theme files. * Files in uploads are excepted. */ if ( ! wp_is_file_mod_allowed( 'capability_update_core' ) ) { $caps[] = 'do_not_allow'; } elseif ( is_multisite() && ! is_super_admin( $user_id ) ) { $caps[] = 'do_not_allow'; } elseif ( 'upload_themes' === $cap ) { $caps[] = 'install_themes'; } elseif ( 'upload_plugins' === $cap ) { $caps[] = 'install_plugins'; } else { $caps[] = $cap; } break; case 'install_languages': case 'update_languages': if ( ! wp_is_file_mod_allowed( 'can_install_language_pack' ) ) { $caps[] = 'do_not_allow'; } elseif ( is_multisite() && ! is_super_admin( $user_id ) ) { $caps[] = 'do_not_allow'; } else { $caps[] = 'install_languages'; } break; case 'activate_plugins': case 'deactivate_plugins': case 'activate_plugin': case 'deactivate_plugin': $caps[] = 'activate_plugins'; if ( is_multisite() ) { // update_, install_, and delete_ are handled above with is_super_admin(). $menu_perms = get_site_option( 'menu_items', array() ); if ( empty( $menu_perms['plugins'] ) ) { $caps[] = 'manage_network_plugins'; } } break; case 'resume_plugin': $caps[] = 'resume_plugins'; break; case 'resume_theme': $caps[] = 'resume_themes'; break; case 'delete_user': case 'delete_users': // If multisite only super admins can delete users. if ( is_multisite() && ! is_super_admin( $user_id ) ) { $caps[] = 'do_not_allow'; } else { $caps[] = 'delete_users'; // delete_user maps to delete_users. } break; case 'create_users': if ( ! is_multisite() ) { $caps[] = $cap; } elseif ( is_super_admin( $user_id ) || get_site_option( 'add_new_users' ) ) { $caps[] = $cap; } else { $caps[] = 'do_not_allow'; } break; case 'manage_links': if ( get_option( 'link_manager_enabled' ) ) { $caps[] = $cap; } else { $caps[] = 'do_not_allow'; } break; case 'customize': $caps[] = 'edit_theme_options'; break; case 'delete_site': if ( is_multisite() ) { $caps[] = 'manage_options'; } else { $caps[] = 'do_not_allow'; } break; case 'edit_term': case 'delete_term': case 'assign_term': if ( ! isset( $args[0] ) ) { /* translators: %s: Capability name. */ $message = __( 'When checking for the %s capability, you must always check it against a specific term.' ); _doing_it_wrong( __FUNCTION__, sprintf( $message, '' . $cap . '' ), '6.1.0' ); $caps[] = 'do_not_allow'; break; } $term_id = (int) $args[0]; $term = get_term( $term_id ); if ( ! $term || is_wp_error( $term ) ) { $caps[] = 'do_not_allow'; break; } $tax = get_taxonomy( $term->taxonomy ); if ( ! $tax ) { $caps[] = 'do_not_allow'; break; } if ( 'delete_term' === $cap && ( get_option( 'default_' . $term->taxonomy ) == $term->term_id || get_option( 'default_term_' . $term->taxonomy ) == $term->term_id ) ) { $caps[] = 'do_not_allow'; break; } $taxo_cap = $cap . 's'; $caps = map_meta_cap( $tax->cap->$taxo_cap, $user_id, $term_id ); break; case 'manage_post_tags': case 'edit_categories': case 'edit_post_tags': case 'delete_categories': case 'delete_post_tags': $caps[] = 'manage_categories'; break; case 'assign_categories': case 'assign_post_tags': $caps[] = 'edit_posts'; break; case 'create_sites': case 'delete_sites': case 'manage_network': case 'manage_sites': case 'manage_network_users': case 'manage_network_plugins': case 'manage_network_themes': case 'manage_network_options': case 'upgrade_network': $caps[] = $cap; break; case 'setup_network': if ( is_multisite() ) { $caps[] = 'manage_network_options'; } else { $caps[] = 'manage_options'; } break; case 'update_php': if ( is_multisite() && ! is_super_admin( $user_id ) ) { $caps[] = 'do_not_allow'; } else { $caps[] = 'update_core'; } break; case 'update_https': if ( is_multisite() && ! is_super_admin( $user_id ) ) { $caps[] = 'do_not_allow'; } else { $caps[] = 'manage_options'; $caps[] = 'update_core'; } break; case 'export_others_personal_data': case 'erase_others_personal_data': case 'manage_privacy_options': $caps[] = is_multisite() ? 'manage_network' : 'manage_options'; break; case 'create_app_password': case 'list_app_passwords': case 'read_app_password': case 'edit_app_password': case 'delete_app_passwords': case 'delete_app_password': $caps = map_meta_cap( 'edit_user', $user_id, $args[0] ); break; default: // Handle meta capabilities for custom post types. global $post_type_meta_caps; if ( isset( $post_type_meta_caps[ $cap ] ) ) { return map_meta_cap( $post_type_meta_caps[ $cap ], $user_id, ...$args ); } // Block capabilities map to their post equivalent. $block_caps = array( 'edit_blocks', 'edit_others_blocks', 'publish_blocks', 'read_private_blocks', 'delete_blocks', 'delete_private_blocks', 'delete_published_blocks', 'delete_others_blocks', 'edit_private_blocks', 'edit_published_blocks', ); if ( in_array( $cap, $block_caps, true ) ) { $cap = str_replace( '_blocks', '_posts', $cap ); } // If no meta caps match, return the original cap. $caps[] = $cap; } /** * Filters the primitive capabilities required of the given user to satisfy the * capability being checked. * * @since 2.8.0 * * @param string[] $caps Primitive capabilities required of the user. * @param string $cap Capability being checked. * @param int $user_id The user ID. * @param array $args Adds context to the capability check, typically * starting with an object ID. */ return apply_filters( 'map_meta_cap', $caps, $cap, $user_id, $args ); } /** * Returns whether the current user has the specified capability. * * This function also accepts an ID of an object to check against if the capability is a meta capability. Meta * capabilities such as `edit_post` and `edit_user` are capabilities used by the `map_meta_cap()` function to * map to primitive capabilities that a user or role has, such as `edit_posts` and `edit_others_posts`. * * Example usage: * * current_user_can( 'edit_posts' ); * current_user_can( 'edit_post', $post->ID ); * current_user_can( 'edit_post_meta', $post->ID, $meta_key ); * * While checking against particular roles in place of a capability is supported * in part, this practice is discouraged as it may produce unreliable results. * * Note: Will always return true if the current user is a super admin, unless specifically denied. * * @since 2.0.0 * @since 5.3.0 Formalized the existing and already documented `...$args` parameter * by adding it to the function signature. * @since 5.8.0 Converted to wrapper for the user_can() function. * * @see WP_User::has_cap() * @see map_meta_cap() * * @param string $capability Capability name. * @param mixed ...$args Optional further parameters, typically starting with an object ID. * @return bool Whether the current user has the given capability. If `$capability` is a meta cap and `$object_id` is * passed, whether the current user has the given meta capability for the given object. */ function current_user_can( $capability, ...$args ) { return user_can( wp_get_current_user(), $capability, ...$args ); } /** * Returns whether the current user has the specified capability for a given site. * * This function also accepts an ID of an object to check against if the capability is a meta capability. Meta * capabilities such as `edit_post` and `edit_user` are capabilities used by the `map_meta_cap()` function to * map to primitive capabilities that a user or role has, such as `edit_posts` and `edit_others_posts`. * * Example usage: * * current_user_can_for_blog( $blog_id, 'edit_posts' ); * current_user_can_for_blog( $blog_id, 'edit_post', $post->ID ); * current_user_can_for_blog( $blog_id, 'edit_post_meta', $post->ID, $meta_key ); * * @since 3.0.0 * @since 5.3.0 Formalized the existing and already documented `...$args` parameter * by adding it to the function signature. * @since 5.8.0 Wraps current_user_can() after switching to blog. * * @param int $blog_id Site ID. * @param string $capability Capability name. * @param mixed ...$args Optional further parameters, typically starting with an object ID. * @return bool Whether the user has the given capability. */ function current_user_can_for_blog( $blog_id, $capability, ...$args ) { $switched = is_multisite() ? switch_to_blog( $blog_id ) : false; $can = current_user_can( $capability, ...$args ); if ( $switched ) { restore_current_blog(); } return $can; } /** * Returns whether the author of the supplied post has the specified capability. * * This function also accepts an ID of an object to check against if the capability is a meta capability. Meta * capabilities such as `edit_post` and `edit_user` are capabilities used by the `map_meta_cap()` function to * map to primitive capabilities that a user or role has, such as `edit_posts` and `edit_others_posts`. * * Example usage: * * author_can( $post, 'edit_posts' ); * author_can( $post, 'edit_post', $post->ID ); * author_can( $post, 'edit_post_meta', $post->ID, $meta_key ); * * @since 2.9.0 * @since 5.3.0 Formalized the existing and already documented `...$args` parameter * by adding it to the function signature. * * @param int|WP_Post $post Post ID or post object. * @param string $capability Capability name. * @param mixed ...$args Optional further parameters, typically starting with an object ID. * @return bool Whether the post author has the given capability. */ function author_can( $post, $capability, ...$args ) { $post = get_post( $post ); if ( ! $post ) { return false; } $author = get_userdata( $post->post_author ); if ( ! $author ) { return false; } return $author->has_cap( $capability, ...$args ); } /** * Returns whether a particular user has the specified capability. * * This function also accepts an ID of an object to check against if the capability is a meta capability. Meta * capabilities such as `edit_post` and `edit_user` are capabilities used by the `map_meta_cap()` function to * map to primitive capabilities that a user or role has, such as `edit_posts` and `edit_others_posts`. * * Example usage: * * user_can( $user->ID, 'edit_posts' ); * user_can( $user->ID, 'edit_post', $post->ID ); * user_can( $user->ID, 'edit_post_meta', $post->ID, $meta_key ); * * @since 3.1.0 * @since 5.3.0 Formalized the existing and already documented `...$args` parameter * by adding it to the function signature. * * @param int|WP_User $user User ID or object. * @param string $capability Capability name. * @param mixed ...$args Optional further parameters, typically starting with an object ID. * @return bool Whether the user has the given capability. */ function user_can( $user, $capability, ...$args ) { if ( ! is_object( $user ) ) { $user = get_userdata( $user ); } if ( empty( $user ) ) { // User is logged out, create anonymous user object. $user = new WP_User( 0 ); $user->init( new stdClass() ); } return $user->has_cap( $capability, ...$args ); } /** * Retrieves the global WP_Roles instance and instantiates it if necessary. * * @since 4.3.0 * * @global WP_Roles $wp_roles WordPress role management object. * * @return WP_Roles WP_Roles global instance if not already instantiated. */ function wp_roles() { global $wp_roles; if ( ! isset( $wp_roles ) ) { $wp_roles = new WP_Roles(); } return $wp_roles; } /** * Retrieves role object. * * @since 2.0.0 * * @param string $role Role name. * @return WP_Role|null WP_Role object if found, null if the role does not exist. */ function get_role( $role ) { return wp_roles()->get_role( $role ); } /** * Adds a role, if it does not exist. * * @since 2.0.0 * * @param string $role Role name. * @param string $display_name Display name for role. * @param bool[] $capabilities List of capabilities keyed by the capability name, * e.g. array( 'edit_posts' => true, 'delete_posts' => false ). * @return WP_Role|void WP_Role object, if the role is added. */ function add_role( $role, $display_name, $capabilities = array() ) { if ( empty( $role ) ) { return; } return wp_roles()->add_role( $role, $display_name, $capabilities ); } /** * Removes a role, if it exists. * * @since 2.0.0 * * @param string $role Role name. */ function remove_role( $role ) { wp_roles()->remove_role( $role ); } /** * Retrieves a list of super admins. * * @since 3.0.0 * * @global array $super_admins * * @return string[] List of super admin logins. */ function get_super_admins() { global $super_admins; if ( isset( $super_admins ) ) { return $super_admins; } else { return get_site_option( 'site_admins', array( 'admin' ) ); } } /** * Determines whether user is a site admin. * * @since 3.0.0 * * @param int|false $user_id Optional. The ID of a user. Defaults to false, to check the current user. * @return bool Whether the user is a site admin. */ function is_super_admin( $user_id = false ) { if ( ! $user_id ) { $user = wp_get_current_user(); } else { $user = get_userdata( $user_id ); } if ( ! $user || ! $user->exists() ) { return false; } if ( is_multisite() ) { $super_admins = get_super_admins(); if ( is_array( $super_admins ) && in_array( $user->user_login, $super_admins, true ) ) { return true; } } else { if ( $user->has_cap( 'delete_users' ) ) { return true; } } return false; } /** * Grants Super Admin privileges. * * @since 3.0.0 * * @global array $super_admins * * @param int $user_id ID of the user to be granted Super Admin privileges. * @return bool True on success, false on failure. This can fail when the user is * already a super admin or when the `$super_admins` global is defined. */ function grant_super_admin( $user_id ) { // If global super_admins override is defined, there is nothing to do here. if ( isset( $GLOBALS['super_admins'] ) || ! is_multisite() ) { return false; } /** * Fires before the user is granted Super Admin privileges. * * @since 3.0.0 * * @param int $user_id ID of the user that is about to be granted Super Admin privileges. */ do_action( 'grant_super_admin', $user_id ); // Directly fetch site_admins instead of using get_super_admins(). $super_admins = get_site_option( 'site_admins', array( 'admin' ) ); $user = get_userdata( $user_id ); if ( $user && ! in_array( $user->user_login, $super_admins, true ) ) { $super_admins[] = $user->user_login; update_site_option( 'site_admins', $super_admins ); /** * Fires after the user is granted Super Admin privileges. * * @since 3.0.0 * * @param int $user_id ID of the user that was granted Super Admin privileges. */ do_action( 'granted_super_admin', $user_id ); return true; } return false; } /** * Revokes Super Admin privileges. * * @since 3.0.0 * * @global array $super_admins * * @param int $user_id ID of the user Super Admin privileges to be revoked from. * @return bool True on success, false on failure. This can fail when the user's email * is the network admin email or when the `$super_admins` global is defined. */ function revoke_super_admin( $user_id ) { // If global super_admins override is defined, there is nothing to do here. if ( isset( $GLOBALS['super_admins'] ) || ! is_multisite() ) { return false; } /** * Fires before the user's Super Admin privileges are revoked. * * @since 3.0.0 * * @param int $user_id ID of the user Super Admin privileges are being revoked from. */ do_action( 'revoke_super_admin', $user_id ); // Directly fetch site_admins instead of using get_super_admins(). $super_admins = get_site_option( 'site_admins', array( 'admin' ) ); $user = get_userdata( $user_id ); if ( $user && 0 !== strcasecmp( $user->user_email, get_site_option( 'admin_email' ) ) ) { $key = array_search( $user->user_login, $super_admins, true ); if ( false !== $key ) { unset( $super_admins[ $key ] ); update_site_option( 'site_admins', $super_admins ); /** * Fires after the user's Super Admin privileges are revoked. * * @since 3.0.0 * * @param int $user_id ID of the user Super Admin privileges were revoked from. */ do_action( 'revoked_super_admin', $user_id ); return true; } } return false; } /** * Filters the user capabilities to grant the 'install_languages' capability as necessary. * * A user must have at least one out of the 'update_core', 'install_plugins', and * 'install_themes' capabilities to qualify for 'install_languages'. * * @since 4.9.0 * * @param bool[] $allcaps An array of all the user's capabilities. * @return bool[] Filtered array of the user's capabilities. */ function wp_maybe_grant_install_languages_cap( $allcaps ) { if ( ! empty( $allcaps['update_core'] ) || ! empty( $allcaps['install_plugins'] ) || ! empty( $allcaps['install_themes'] ) ) { $allcaps['install_languages'] = true; } return $allcaps; } /** * Filters the user capabilities to grant the 'resume_plugins' and 'resume_themes' capabilities as necessary. * * @since 5.2.0 * * @param bool[] $allcaps An array of all the user's capabilities. * @return bool[] Filtered array of the user's capabilities. */ function wp_maybe_grant_resume_extensions_caps( $allcaps ) { // Even in a multisite, regular administrators should be able to resume plugins. if ( ! empty( $allcaps['activate_plugins'] ) ) { $allcaps['resume_plugins'] = true; } // Even in a multisite, regular administrators should be able to resume themes. if ( ! empty( $allcaps['switch_themes'] ) ) { $allcaps['resume_themes'] = true; } return $allcaps; } /** * Filters the user capabilities to grant the 'view_site_health_checks' capabilities as necessary. * * @since 5.2.2 * * @param bool[] $allcaps An array of all the user's capabilities. * @param string[] $caps Required primitive capabilities for the requested capability. * @param array $args { * Arguments that accompany the requested capability check. * * @type string $0 Requested capability. * @type int $1 Concerned user ID. * @type mixed ...$2 Optional second and further parameters, typically object ID. * } * @param WP_User $user The user object. * @return bool[] Filtered array of the user's capabilities. */ function wp_maybe_grant_site_health_caps( $allcaps, $caps, $args, $user ) { if ( ! empty( $allcaps['install_plugins'] ) && ( ! is_multisite() || is_super_admin( $user->ID ) ) ) { $allcaps['view_site_health_checks'] = true; } return $allcaps; } return; // Dummy gettext calls to get strings in the catalog. /* translators: User role for administrators. */ _x( 'Administrator', 'User role' ); /* translators: User role for editors. */ _x( 'Editor', 'User role' ); /* translators: User role for authors. */ _x( 'Author', 'User role' ); /* translators: User role for contributors. */ _x( 'Contributor', 'User role' ); /* translators: User role for subscribers. */ _x( 'Subscriber', 'User role' ); since 5.6.0 * * @param WP_REST_Request $request The request object. * @param string $route The matched route regex. * @param array $handler The matched route handler. * @param WP_Error|null $response The current error object if any. * @return WP_REST_Response */ protected function respond_to_request( $request, $route, $handler, $response ) { /** * Filters the response before executing any REST API callbacks. * * Allows plugins to perform additional validation after a * request is initialized and matched to a registered route, * but before it is executed. * * Note that this filter will not be called for requests that * fail to authenticate or match to a registered route. * * @since 4.7.0 * * @param WP_REST_Response|WP_HTTP_Response|WP_Error|mixed $response Result to send to the client. * Usually a WP_REST_Response or WP_Error. * @param array $handler Route handler used for the request. * @param WP_REST_Request $request Request used to generate the response. */ $response = apply_filters( 'rest_request_before_callbacks', $response, $handler, $request ); // Check permission specified on the route. if ( ! is_wp_error( $response ) && ! empty( $handler['permission_callback'] ) ) { $permission = call_user_func( $handler['permission_callback'], $request ); if ( is_wp_error( $permission ) ) { $response = $permission; } elseif ( false === $permission || null === $permission ) { $response = new WP_Error( 'rest_forbidden', __( 'Sorry, you are not allowed to do that.' ), array( 'status' => rest_authorization_required_code() ) ); } } if ( ! is_wp_error( $response ) ) { /** * Filters the REST API dispatch request result. * * Allow plugins to override dispatching the request. * * @since 4.4.0 * @since 4.5.0 Added `$route` and `$handler` parameters. * * @param mixed $dispatch_result Dispatch result, will be used if not empty. * @param WP_REST_Request $request Request used to generate the response. * @param string $route Route matched for the request. * @param array $handler Route handler used for the request. */ $dispatch_result = apply_filters( 'rest_dispatch_request', null, $request, $route, $handler ); // Allow plugins to halt the request via this filter. if ( null !== $dispatch_result ) { $response = $dispatch_result; } else { $response = call_user_func( $handler['callback'], $request ); } } /** * Filters the response immediately after executing any REST API * callbacks. * * Allows plugins to perform any needed cleanup, for example, * to undo changes made during the {@see 'rest_request_before_callbacks'} * filter. * * Note that this filter will not be called for requests that * fail to authenticate or match to a registered route. * * Note that an endpoint's `permission_callback` can still be * called after this filter - see `rest_send_allow_header()`. * * @since 4.7.0 * * @param WP_REST_Response|WP_HTTP_Response|WP_Error|mixed $response Result to send to the client. * Usually a WP_REST_Response or WP_Error. * @param array $handler Route handler used for the request. * @param WP_REST_Request $request Request used to generate the response. */ $response = apply_filters( 'rest_request_after_callbacks', $response, $handler, $request ); if ( is_wp_error( $response ) ) { $response = $this->error_to_response( $response ); } else { $response = rest_ensure_response( $response ); } $response->set_matched_route( $route ); $response->set_matched_handler( $handler ); return $response; } /** * Returns if an error occurred during most recent JSON encode/decode. * * Strings to be translated will be in format like * "Encoding error: Maximum stack depth exceeded". * * @since 4.4.0 * * @return false|string Boolean false or string error message. */ protected function get_json_last_error() { $last_error_code = json_last_error(); if ( JSON_ERROR_NONE === $last_error_code || empty( $last_error_code ) ) { return false; } return json_last_error_msg(); } /** * Retrieves the site index. * * This endpoint describes the capabilities of the site. * * @since 4.4.0 * * @param array $request { * Request. * * @type string $context Context. * } * @return WP_REST_Response The API root index data. */ public function get_index( $request ) { // General site data. $available = array( 'name' => get_option( 'blogname' ), 'description' => get_option( 'blogdescription' ), 'url' => get_option( 'siteurl' ), 'home' => home_url(), 'gmt_offset' => get_option( 'gmt_offset' ), 'timezone_string' => get_option( 'timezone_string' ), 'namespaces' => array_keys( $this->namespaces ), 'authentication' => array(), 'routes' => $this->get_data_for_routes( $this->get_routes(), $request['context'] ), ); $response = new WP_REST_Response( $available ); $response->add_link( 'help', 'https://developer.wordpress.org/rest-api/' ); $this->add_active_theme_link_to_index( $response ); $this->add_site_logo_to_index( $response ); $this->add_site_icon_to_index( $response ); /** * Filters the REST API root index data. * * This contains the data describing the API. This includes information * about supported authentication schemes, supported namespaces, routes * available on the API, and a small amount of data about the site. * * @since 4.4.0 * @since 6.0.0 Added `$request` parameter. * * @param WP_REST_Response $response Response data. * @param WP_REST_Request $request Request data. */ return apply_filters( 'rest_index', $response, $request ); } /** * Adds a link to the active theme for users who have proper permissions. * * @since 5.7.0 * * @param WP_REST_Response $response REST API response. */ protected function add_active_theme_link_to_index( WP_REST_Response $response ) { $should_add = current_user_can( 'switch_themes' ) || current_user_can( 'manage_network_themes' ); if ( ! $should_add && current_user_can( 'edit_posts' ) ) { $should_add = true; } if ( ! $should_add ) { foreach ( get_post_types( array( 'show_in_rest' => true ), 'objects' ) as $post_type ) { if ( current_user_can( $post_type->cap->edit_posts ) ) { $should_add = true; break; } } } if ( $should_add ) { $theme = wp_get_theme(); $response->add_link( 'https://api.w.org/active-theme', rest_url( 'wp/v2/themes/' . $theme->get_stylesheet() ) ); } } /** * Exposes the site logo through the WordPress REST API. * * This is used for fetching this information when user has no rights * to update settings. * * @since 5.8.0 * * @param WP_REST_Response $response REST API response. */ protected function add_site_logo_to_index( WP_REST_Response $response ) { $site_logo_id = get_theme_mod( 'custom_logo', 0 ); $this->add_image_to_index( $response, $site_logo_id, 'site_logo' ); } /** * Exposes the site icon through the WordPress REST API. * * This is used for fetching this information when user has no rights * to update settings. * * @since 5.9.0 * * @param WP_REST_Response $response REST API response. */ protected function add_site_icon_to_index( WP_REST_Response $response ) { $site_icon_id = get_option( 'site_icon', 0 ); $this->add_image_to_index( $response, $site_icon_id, 'site_icon' ); $response->data['site_icon_url'] = get_site_icon_url(); } /** * Exposes an image through the WordPress REST API. * This is used for fetching this information when user has no rights * to update settings. * * @since 5.9.0 * * @param WP_REST_Response $response REST API response. * @param int $image_id Image attachment ID. * @param string $type Type of Image. */ protected function add_image_to_index( WP_REST_Response $response, $image_id, $type ) { $response->data[ $type ] = (int) $image_id; if ( $image_id ) { $response->add_link( 'https://api.w.org/featuredmedia', rest_url( rest_get_route_for_post( $image_id ) ), array( 'embeddable' => true, 'type' => $type, ) ); } } /** * Retrieves the index for a namespace. * * @since 4.4.0 * * @param WP_REST_Request $request REST request instance. * @return WP_REST_Response|WP_Error WP_REST_Response instance if the index was found, * WP_Error if the namespace isn't set. */ public function get_namespace_index( $request ) { $namespace = $request['namespace']; if ( ! isset( $this->namespaces[ $namespace ] ) ) { return new WP_Error( 'rest_invalid_namespace', __( 'The specified namespace could not be found.' ), array( 'status' => 404 ) ); } $routes = $this->namespaces[ $namespace ]; $endpoints = array_intersect_key( $this->get_routes(), $routes ); $data = array( 'namespace' => $namespace, 'routes' => $this->get_data_for_routes( $endpoints, $request['context'] ), ); $response = rest_ensure_response( $data ); // Link to the root index. $response->add_link( 'up', rest_url( '/' ) ); /** * Filters the REST API namespace index data. * * This typically is just the route data for the namespace, but you can * add any data you'd like here. * * @since 4.4.0 * * @param WP_REST_Response $response Response data. * @param WP_REST_Request $request Request data. The namespace is passed as the 'namespace' parameter. */ return apply_filters( 'rest_namespace_index', $response, $request ); } /** * Retrieves the publicly-visible data for routes. * * @since 4.4.0 * * @param array $routes Routes to get data for. * @param string $context Optional. Context for data. Accepts 'view' or 'help'. Default 'view'. * @return array[] Route data to expose in indexes, keyed by route. */ public function get_data_for_routes( $routes, $context = 'view' ) { $available = array(); // Find the available routes. foreach ( $routes as $route => $callbacks ) { $data = $this->get_data_for_route( $route, $callbacks, $context ); if ( empty( $data ) ) { continue; } /** * Filters the publicly-visible data for a single REST API route. * * @since 4.4.0 * * @param array $data Publicly-visible data for the route. */ $available[ $route ] = apply_filters( 'rest_endpoints_description', $data ); } /** * Filters the publicly-visible data for REST API routes. * * This data is exposed on indexes and can be used by clients or * developers to investigate the site and find out how to use it. It * acts as a form of self-documentation. * * @since 4.4.0 * * @param array[] $available Route data to expose in indexes, keyed by route. * @param array $routes Internal route data as an associative array. */ return apply_filters( 'rest_route_data', $available, $routes ); } /** * Retrieves publicly-visible data for the route. * * @since 4.4.0 * * @param string $route Route to get data for. * @param array $callbacks Callbacks to convert to data. * @param string $context Optional. Context for the data. Accepts 'view' or 'help'. Default 'view'. * @return array|null Data for the route, or null if no publicly-visible data. */ public function get_data_for_route( $route, $callbacks, $context = 'view' ) { $data = array( 'namespace' => '', 'methods' => array(), 'endpoints' => array(), ); $allow_batch = false; if ( isset( $this->route_options[ $route ] ) ) { $options = $this->route_options[ $route ]; if ( isset( $options['namespace'] ) ) { $data['namespace'] = $options['namespace']; } $allow_batch = isset( $options['allow_batch'] ) ? $options['allow_batch'] : false; if ( isset( $options['schema'] ) && 'help' === $context ) { $data['schema'] = call_user_func( $options['schema'] ); } } $allowed_schema_keywords = array_flip( rest_get_allowed_schema_keywords() ); $route = preg_replace( '#\(\?P<(\w+?)>.*?\)#', '{$1}', $route ); foreach ( $callbacks as $callback ) { // Skip to the next route if any callback is hidden. if ( empty( $callback['show_in_index'] ) ) { continue; } $data['methods'] = array_merge( $data['methods'], array_keys( $callback['methods'] ) ); $endpoint_data = array( 'methods' => array_keys( $callback['methods'] ), ); $callback_batch = isset( $callback['allow_batch'] ) ? $callback['allow_batch'] : $allow_batch; if ( $callback_batch ) { $endpoint_data['allow_batch'] = $callback_batch; } if ( isset( $callback['args'] ) ) { $endpoint_data['args'] = array(); foreach ( $callback['args'] as $key => $opts ) { if ( is_string( $opts ) ) { $opts = array( $opts => 0 ); } elseif ( ! is_array( $opts ) ) { $opts = array(); } $arg_data = array_intersect_key( $opts, $allowed_schema_keywords ); $arg_data['required'] = ! empty( $opts['required'] ); $endpoint_data['args'][ $key ] = $arg_data; } } $data['endpoints'][] = $endpoint_data; // For non-variable routes, generate links. if ( ! str_contains( $route, '{' ) ) { $data['_links'] = array( 'self' => array( array( 'href' => rest_url( $route ), ), ), ); } } if ( empty( $data['methods'] ) ) { // No methods supported, hide the route. return null; } return $data; } /** * Gets the maximum number of requests that can be included in a batch. * * @since 5.6.0 * * @return int The maximum requests. */ protected function get_max_batch_size() { /** * Filters the maximum number of REST API requests that can be included in a batch. * * @since 5.6.0 * * @param int $max_size The maximum size. */ return apply_filters( 'rest_get_max_batch_size', 25 ); } /** * Serves the batch/v1 request. * * @since 5.6.0 * * @param WP_REST_Request $batch_request The batch request object. * @return WP_REST_Response The generated response object. */ public function serve_batch_request_v1( WP_REST_Request $batch_request ) { $requests = array(); foreach ( $batch_request['requests'] as $args ) { $parsed_url = wp_parse_url( $args['path'] ); if ( false === $parsed_url ) { $requests[] = new WP_Error( 'parse_path_failed', __( 'Could not parse the path.' ), array( 'status' => 400 ) ); continue; } $single_request = new WP_REST_Request( isset( $args['method'] ) ? $args['method'] : 'POST', $parsed_url['path'] ); if ( ! empty( $parsed_url['query'] ) ) { $query_args = null; // Satisfy linter. wp_parse_str( $parsed_url['query'], $query_args ); $single_request->set_query_params( $query_args ); } if ( ! empty( $args['body'] ) ) { $single_request->set_body_params( $args['body'] ); } if ( ! empty( $args['headers'] ) ) { $single_request->set_headers( $args['headers'] ); } $requests[] = $single_request; } $matches = array(); $validation = array(); $has_error = false; foreach ( $requests as $single_request ) { $match = $this->match_request_to_handler( $single_request ); $matches[] = $match; $error = null; if ( is_wp_error( $match ) ) { $error = $match; } if ( ! $error ) { list( $route, $handler ) = $match; if ( isset( $handler['allow_batch'] ) ) { $allow_batch = $handler['allow_batch']; } else { $route_options = $this->get_route_options( $route ); $allow_batch = isset( $route_options['allow_batch'] ) ? $route_options['allow_batch'] : false; } if ( ! is_array( $allow_batch ) || empty( $allow_batch['v1'] ) ) { $error = new WP_Error( 'rest_batch_not_allowed', __( 'The requested route does not support batch requests.' ), array( 'status' => 400 ) ); } } if ( ! $error ) { $check_required = $single_request->has_valid_params(); if ( is_wp_error( $check_required ) ) { $error = $check_required; } } if ( ! $error ) { $check_sanitized = $single_request->sanitize_params(); if ( is_wp_error( $check_sanitized ) ) { $error = $check_sanitized; } } if ( $error ) { $has_error = true; $validation[] = $error; } else { $validation[] = true; } } $responses = array(); if ( $has_error && 'require-all-validate' === $batch_request['validation'] ) { foreach ( $validation as $valid ) { if ( is_wp_error( $valid ) ) { $responses[] = $this->envelope_response( $this->error_to_response( $valid ), false )->get_data(); } else { $responses[] = null; } } return new WP_REST_Response( array( 'failed' => 'validation', 'responses' => $responses, ), WP_Http::MULTI_STATUS ); } foreach ( $requests as $i => $single_request ) { $clean_request = clone $single_request; $clean_request->set_url_params( array() ); $clean_request->set_attributes( array() ); $clean_request->set_default_params( array() ); /** This filter is documented in wp-includes/rest-api/class-wp-rest-server.php */ $result = apply_filters( 'rest_pre_dispatch', null, $this, $clean_request ); if ( empty( $result ) ) { $match = $matches[ $i ]; $error = null; if ( is_wp_error( $validation[ $i ] ) ) { $error = $validation[ $i ]; } if ( is_wp_error( $match ) ) { $result = $this->error_to_response( $match ); } else { list( $route, $handler ) = $match; if ( ! $error && ! is_callable( $handler['callback'] ) ) { $error = new WP_Error( 'rest_invalid_handler', __( 'The handler for the route is invalid' ), array( 'status' => 500 ) ); } $result = $this->respond_to_request( $single_request, $route, $handler, $error ); } } /** This filter is documented in wp-includes/rest-api/class-wp-rest-server.php */ $result = apply_filters( 'rest_post_dispatch', rest_ensure_response( $result ), $this, $single_request ); $responses[] = $this->envelope_response( $result, false )->get_data(); } return new WP_REST_Response( array( 'responses' => $responses ), WP_Http::MULTI_STATUS ); } /** * Sends an HTTP status code. * * @since 4.4.0 * * @param int $code HTTP status. */ protected function set_status( $code ) { status_header( $code ); } /** * Sends an HTTP header. * * @since 4.4.0 * * @param string $key Header key. * @param string $value Header value. */ public function send_header( $key, $value ) { /* * Sanitize as per RFC2616 (Section 4.2): * * Any LWS that occurs between field-content MAY be replaced with a * single SP before interpreting the field value or forwarding the * message downstream. */ $value = preg_replace( '/\s+/', ' ', $value ); header( sprintf( '%s: %s', $key, $value ) ); } /** * Sends multiple HTTP headers. * * @since 4.4.0 * * @param array $headers Map of header name to header value. */ public function send_headers( $headers ) { foreach ( $headers as $key => $value ) { $this->send_header( $key, $value ); } } /** * Removes an HTTP header from the current response. * * @since 4.8.0 * * @param string $key Header key. */ public function remove_header( $key ) { header_remove( $key ); } /** * Retrieves the raw request entity (body). * * @since 4.4.0 * * @global string $HTTP_RAW_POST_DATA Raw post data. * * @return string Raw request data. */ public static function get_raw_data() { // phpcs:disable PHPCompatibility.Variables.RemovedPredefinedGlobalVariables.http_raw_post_dataDeprecatedRemoved global $HTTP_RAW_POST_DATA; // $HTTP_RAW_POST_DATA was deprecated in PHP 5.6 and removed in PHP 7.0. if ( ! isset( $HTTP_RAW_POST_DATA ) ) { $HTTP_RAW_POST_DATA = file_get_contents( 'php://input' ); } return $HTTP_RAW_POST_DATA; // phpcs:enable } /** * Extracts headers from a PHP-style $_SERVER array. * * @since 4.4.0 * * @param array $server Associative array similar to `$_SERVER`. * @return array Headers extracted from the input. */ public function get_headers( $server ) { $headers = array(); // CONTENT_* headers are not prefixed with HTTP_. $additional = array( 'CONTENT_LENGTH' => true, 'CONTENT_MD5' => true, 'CONTENT_TYPE' => true, ); foreach ( $server as $key => $value ) { if ( str_starts_with( $key, 'HTTP_' ) ) { $headers[ substr( $key, 5 ) ] = $value; } elseif ( 'REDIRECT_HTTP_AUTHORIZATION' === $key && empty( $server['HTTP_AUTHORIZATION'] ) ) { /* * In some server configurations, the authorization header is passed in this alternate location. * Since it would not be passed in in both places we do not check for both headers and resolve. */ $headers['AUTHORIZATION'] = $value; } elseif ( isset( $additional[ $key ] ) ) { $headers[ $key ] = $value; } } return $headers; } }