From a8283a18d36c5557c1ca410c592c9067e8d80fd7 Mon Sep 17 00:00:00 2001 From: Timothy Jacobs Date: Tue, 19 May 2020 00:29:37 -0400 Subject: [PATCH 01/25] First pass at plugins endpoint. Brings tests and endpoint code from tellyworth/wordpress-develop/add/rest-api/block-directory. For some reason it seems like the filesystem isn't available when running tests. --- lib/class-wp-rest-plugins-controller.php | 751 ++++++++++++++++++ lib/load.php | 3 + lib/rest-api.php | 10 + .../class-wp-rest-plugins-controller-test.php | 378 +++++++++ 4 files changed, 1142 insertions(+) create mode 100644 lib/class-wp-rest-plugins-controller.php create mode 100644 phpunit/class-wp-rest-plugins-controller-test.php diff --git a/lib/class-wp-rest-plugins-controller.php b/lib/class-wp-rest-plugins-controller.php new file mode 100644 index 00000000000000..78c3882225b3b0 --- /dev/null +++ b/lib/class-wp-rest-plugins-controller.php @@ -0,0 +1,751 @@ +namespace = '__experimental'; + $this->rest_base = 'plugins'; + } + + /** + * Registers the routes for the plugins controller. + * + * @since 5.5.0 + */ + public function register_routes() { + register_rest_route( + $this->namespace, + '/' . $this->rest_base, + array( + array( + 'methods' => WP_REST_Server::READABLE, + 'callback' => array( $this, 'get_items' ), + 'permission_callback' => array( $this, 'get_items_permissions_check' ), + 'args' => $this->get_collection_params(), + ), + array( + 'methods' => WP_REST_Server::CREATABLE, + 'callback' => array( $this, 'create_item' ), + 'permission_callback' => array( $this, 'create_item_permissions_check' ), + 'args' => array( + 'slug' => array( + 'type' => 'string', + 'required' => true, + 'description' => __( 'WordPress.org plugin directory slug.', 'gutenberg' ), + ), + 'activate' => array( + 'type' => 'boolean', + 'default' => false, + 'description' => __( 'Whether to activate the plugin after installing it.', 'gutenberg' ), + ), + ), + ), + 'schema' => array( $this, 'get_public_item_schema' ), + ) + ); + + register_rest_route( + $this->namespace, + '/' . $this->rest_base . '/(?P' . self::PATTERN . ')', + array( + array( + 'methods' => WP_REST_Server::READABLE, + 'callback' => array( $this, 'get_item' ), + 'permission_callback' => array( $this, 'get_item_permissions_check' ), + ), + array( + 'methods' => WP_REST_Server::EDITABLE, + 'callback' => array( $this, 'update_item' ), + 'permission_callback' => array( $this, 'update_item_permissions_check' ), + 'args' => $this->get_endpoint_args_for_item_schema( WP_REST_Server::EDITABLE ), + ), + array( + 'methods' => WP_REST_Server::DELETABLE, + 'callback' => array( $this, 'delete_item' ), + 'permission_callback' => array( $this, 'delete_item_permissions_check' ), + ), + 'args' => array( + 'context' => $this->get_context_param( array( 'default' => 'view' ) ), + 'plugin' => array( + 'type' => 'string', + 'pattern' => self::PATTERN, + 'validate_callback' => static function ( $file ) { + if ( ! is_string( $file ) || ! preg_match( '/' . self::PATTERN . '/u', $file ) ) { + return false; + } + + $validated = validate_file( plugin_basename( $file ) ); + + return 0 === $validated; + }, + 'sanitize_callback' => static function ( $file ) { + return plugin_basename( sanitize_text_field( $file . '.php' ) ); + }, + ), + ), + 'schema' => array( $this, 'get_public_item_schema' ), + ) + ); + } + + /** + * Checks if a given request has access to get plugins. + * + * @since 5.5.0 + * + * @param WP_REST_Request $request Full details about the request. + * @return true|WP_Error True if the request has read access, WP_Error object otherwise. + */ + public function get_items_permissions_check( $request ) { + if ( ! current_user_can( 'activate_plugins' ) ) { + return new WP_Error( + 'rest_cannot_view_plugins', + __( 'Sorry, you are not allowed to manage plugins for this site.', 'gutenberg' ), + array( 'status' => rest_authorization_required_code() ) + ); + } + + return true; + } + + /** + * Retrieves a collection of plugins. + * + * @since 5.5.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 get_items( $request ) { + require_once ABSPATH . 'wp-admin/includes/plugin.php'; + + $plugins = array(); + + foreach ( get_plugins() as $file => $data ) { + if ( ! $this->check_read_permission( $file ) ) { + continue; + } + + $data['_file'] = $file; + $plugins[] = $this->prepare_response_for_collection( $this->prepare_item_for_response( $data, $request ) ); + } + + return new WP_REST_Response( $plugins ); + } + + /** + * Checks if a given request has access to get a specific plugin. + * + * @since 5.5.0 + * + * @param WP_REST_Request $request Full details about the request. + * @return true|WP_Error True if the request has read access for the item, WP_Error object otherwise. + */ + public function get_item_permissions_check( $request ) { + if ( ! current_user_can( 'activate_plugins' ) ) { + return new WP_Error( + 'rest_cannot_view_plugin', + __( 'Sorry, you are not allowed to manage plugins for this site.', 'gutenberg' ), + array( 'status' => rest_authorization_required_code() ) + ); + } + + if ( ! $this->check_read_permission( $request['plugin'] ) ) { + return new WP_Error( + 'rest_cannot_view_plugin', + __( 'Sorry, you are not allowed to manage this plugin.', 'gutenberg' ), + array( 'status' => rest_authorization_required_code() ) + ); + } + + return true; + } + + /** + * Retrieves one plugin from the site. + * + * @since 5.5.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 get_item( $request ) { + require_once ABSPATH . 'wp-admin/includes/plugin.php'; + + $plugins = get_plugins(); + + if ( ! isset( $plugins[ $request['plugin'] ] ) ) { + return new WP_Error( 'rest_plugin_not_found', __( 'Plugin not found.', 'gutenberg' ), array( 'status' => 404 ) ); + } + + $data = $plugins[ $request['plugin'] ]; + $data['_file'] = $request['plugin']; + + return $this->prepare_item_for_response( $data, $request ); + } + + /** + * Checks if the given plugin can be viewed by the current user. + * + * On multisite, this hides non-active network only plugins if the user does not have permission + * to manage network plugins. + * + * @since 5.5.0 + * + * @param string $plugin The plugin file to check. + * @return bool + */ + protected function check_read_permission( $plugin ) { + if ( ! is_multisite() ) { + return true; + } + + return ! is_network_only_plugin( $plugin ) || is_plugin_active( $plugin ) || current_user_can( 'manage_network_plugins' ); + } + + /** + * Checks if a given request has access to upload plugins. + * + * @since 5.5.0 + * + * @param WP_REST_Request $request Full details about the request. + * @return true|WP_Error True if the request has access to create items, WP_Error object otherwise. + */ + public function create_item_permissions_check( $request ) { + if ( ! current_user_can( 'install_plugins' ) ) { + return new WP_Error( + 'rest_cannot_install_plugin', + __( 'Sorry, you are not allowed to install plugins on this site.', 'gutenberg' ), + array( 'status' => rest_authorization_required_code() ) + ); + } + + if ( + $request['activate'] && + ( ! current_user_can( 'activate_plugins' ) || ! current_user_can( 'activate_plugin', $request['slug'] ) ) + ) { + return new WP_Error( + 'rest_cannot_activate_plugin', + __( 'Sorry, you are not allowed to activate this plugin.', 'gutenberg' ), + array( + 'status' => rest_authorization_required_code(), + ) + ); + } + + return true; + } + + /** + * Uploads a plugin and optionally activates it. + * + * @since 5.5.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 create_item( $request ) { + require_once ABSPATH . 'wp-admin/includes/file.php'; + require_once ABSPATH . 'wp-admin/includes/plugin.php'; + require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php'; + require_once ABSPATH . 'wp-admin/includes/plugin-install.php'; + + $slug = $request['slug']; + + // Verify filesystem is accessible first. + $filesystem_available = $this->is_filesystem_available(); + if ( is_wp_error( $filesystem_available ) ) { + return $filesystem_available; + } + + $api = plugins_api( + 'plugin_information', + array( + 'slug' => $slug, + 'fields' => array( + 'sections' => false, + ), + ) + ); + + if ( is_wp_error( $api ) ) { + if ( false !== strpos( $api->get_error_message(), 'Plugin not found.' ) ) { + $api->add_data( array( 'status' => 404 ) ); + } else { + $api->add_data( array( 'status' => 500 ) ); + } + + return $api; + } + + $skin = new WP_Ajax_Upgrader_Skin(); + $upgrader = new Plugin_Upgrader( $skin ); + + $result = $upgrader->install( $api->download_link ); + + if ( is_wp_error( $result ) ) { + return $result; + } + + // This should be the same as $result above. + if ( is_wp_error( $skin->result ) ) { + return $skin->result; + } + + if ( $skin->get_errors()->has_errors() ) { + return $skin->get_errors(); + } + + if ( is_null( $result ) ) { + global $wp_filesystem; + // Pass through the error from WP_Filesystem if one was raised. + if ( $wp_filesystem instanceof WP_Filesystem_Base && is_wp_error( $wp_filesystem->errors ) && $wp_filesystem->errors->has_errors() ) { + return new WP_Error( 'unable_to_connect_to_filesystem', $wp_filesystem->errors->get_error_message(), array( 'status' => 500 ) ); + } + + return new WP_Error( 'unable_to_connect_to_filesystem', __( 'Unable to connect to the filesystem. Please confirm your credentials.', 'gutenberg' ), array( 'status' => 500 ) ); + } + + $file = $upgrader->plugin_info(); + + if ( $request['activate'] ) { + $activated = activate_plugin( $file ); + + if ( is_wp_error( $activated ) ) { + return $activated; + } + } + + $path = WP_PLUGIN_DIR . '/' . $file; + $data = get_plugin_data( $path, false, false ); + $data['_file'] = $file; + + $response = $this->prepare_item_for_response( $data, $request ); + $response->set_status( 201 ); + $response->header( 'Location', rest_url( $this->namespace . '/' . $this->rest_base . '/' . substr( $file, 0, - 4 ) ) ); + + return $response; + } + + /** + * Checks if a given request has access to update a specific plugin. + * + * @since 5.5.0 + * + * @param WP_REST_Request $request Full details about the request. + * @return true|WP_Error True if the request has access to update the item, WP_Error object otherwise. + */ + public function update_item_permissions_check( $request ) { + require_once ABSPATH . 'wp-admin/includes/plugin.php'; + + if ( ! current_user_can( 'activate_plugins' ) ) { + return new WP_Error( + 'rest_cannot_manage_plugins', + __( 'Sorry, you are not allowed to manage plugins for this site.', 'gutenberg' ), + array( 'status' => rest_authorization_required_code() ) + ); + } + + if ( ! $this->check_read_permission( $request['plugin'] ) ) { + return new WP_Error( + 'rest_cannot_view_plugin', + __( 'Sorry, you are not allowed to manage this plugin.', 'gutenberg' ), + array( 'status' => rest_authorization_required_code() ) + ); + } + + $status = $this->get_plugin_status( $request['plugin'] ); + + if ( $status !== $request['status'] ) { + if ( ( 'network-active' === $status || 'network-active' === $request['status'] ) && ! current_user_can( 'manage_network_plugins' ) ) { + return new WP_Error( + 'rest_cannot_manage_network_plugins', + __( 'Sorry, you do not have permission to manage network plugins.', 'gutenberg' ), + array( 'status' => rest_authorization_required_code() ) + ); + } + + if ( 'active' === $request['status'] && ! current_user_can( 'activate_plugin', $request['plugin'] ) ) { + return new WP_Error( + 'rest_cannot_activate_plugin', + __( 'Sorry, you are not allowed to activate this plugin.', 'gutenberg' ), + array( 'status' => rest_authorization_required_code() ) + ); + } + + if ( 'inactive' === $request['status'] && ! current_user_can( 'deactivate_plugin', $request['plugin'] ) ) { + return new WP_Error( + 'rest_cannot_deactivate_plugin', + __( 'Sorry, you are not allowed to deactivate this plugin.', 'gutenberg' ), + array( 'status' => rest_authorization_required_code() ) + ); + } + } + + return true; + } + + /** + * Updates one plugin. + * + * @since 5.5.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 update_item( $request ) { + require_once ABSPATH . 'wp-admin/includes/plugin.php'; + + $plugins = get_plugins(); + + if ( ! isset( $plugins[ $request['plugin'] ] ) ) { + return new WP_Error( 'rest_plugin_not_found', __( 'Plugin not found.', 'gutenberg' ), array( 'status' => 404 ) ); + } + + $data = $plugins[ $request['plugin'] ]; + $data['_file'] = $request['plugin']; + + $status = $this->get_plugin_status( $request['plugin'] ); + + if ( $request['status'] && $status !== $request['status'] ) { + $handled = $this->handle_plugin_status( $request['plugin'], $request['status'], $status ); + + if ( is_wp_error( $handled ) ) { + return $handled; + } + } + + $this->update_additional_fields_for_object( $data, $request ); + + $request['context'] = 'edit'; + + return $this->prepare_item_for_response( $data, $request ); + } + + /** + * Checks if a given request has access to delete a specific plugin. + * + * @since 5.5.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 ) { + if ( ! current_user_can( 'delete_plugins' ) ) { + return new WP_Error( + 'rest_cannot_manage_plugins', + __( 'Sorry, you are not allowed to delete plugins for this site.', 'gutenberg' ), + array( 'status' => rest_authorization_required_code() ) + ); + } + + if ( ! $this->check_read_permission( $request['plugin'] ) ) { + return new WP_Error( + 'rest_cannot_view_plugin', + __( 'Sorry, you are not allowed to manage this plugin.', 'gutenberg' ), + array( 'status' => rest_authorization_required_code() ) + ); + } + + return true; + } + + /** + * Deletes one plugin from the site. + * + * @since 5.5.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 ) { + require_once ABSPATH . 'wp-admin/includes/file.php'; + require_once ABSPATH . 'wp-admin/includes/plugin.php'; + + $plugins = get_plugins(); + + if ( ! isset( $plugins[ $request['plugin'] ] ) ) { + return new WP_Error( 'rest_plugin_not_found', __( 'Plugin not found.', 'gutenberg' ), array( 'status' => 404 ) ); + } + + if ( is_plugin_active( $request['plugin'] ) ) { + return new WP_Error( + 'rest_cannot_delete_active_plugin', + __( 'Cannot delete an active plugin. Please deactivate it first.', 'gutenberg' ), + array( 'status' => 400 ) + ); + } + + $filesystem_available = $this->is_filesystem_available(); + if ( is_wp_error( $filesystem_available ) ) { + return $filesystem_available; + } + + $deleted = delete_plugins( array( $request['plugin'] ) ); + + if ( is_wp_error( $deleted ) ) { + return $deleted; + } + + return new WP_REST_Response( null, 204 ); + } + + /** + * Prepares the plugin for the REST response. + * + * @since 5.5.0 + * + * @param mixed $item Unmarked up and untranslated plugin data from {@see get_plugin_data()}. + * @param WP_REST_Request $request Request object. + * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. + */ + public function prepare_item_for_response( $item, $request ) { + $item = _get_plugin_data_markup_translate( $item['_file'], $item, false ); + $marked = _get_plugin_data_markup_translate( $item['_file'], $item, true, false ); + + $data = array( + 'plugin' => $item['_file'], + 'status' => $this->get_plugin_status( $item['_file'] ), + 'name' => $item['Name'], + 'plugin_uri' => $item['PluginURI'], + 'author' => $item['Author'], + 'author_uri' => $item['AuthorURI'], + 'description' => array( + 'raw' => $item['Description'], + 'rendered' => $marked['Description'], + ), + 'version' => $item['Version'], + 'network_only' => $item['Network'], + 'requires_wp' => $item['RequiresWP'], + 'requires_php' => $item['RequiresPHP'], + ); + + $data = $this->add_additional_fields_to_object( $data, $request ); + + $response = new WP_REST_Response( $data ); + $response->add_link( 'self', rest_url( $this->namespace . '/' . $this->rest_base . '/' . substr( $item['_file'], 0, - 4 ) ) ); + + return $response; + } + + /** + * Get's the activation status for a plugin. + * + * @since 5.5.0 + * + * @param string $plugin The plugin file to check. + * @return string Either 'network-active', 'active' or 'inactive'. + */ + protected function get_plugin_status( $plugin ) { + if ( is_plugin_active_for_network( $plugin ) ) { + return 'network-active'; + } + + if ( is_plugin_active( $plugin ) ) { + return 'active'; + } + + return 'inactive'; + } + + /** + * Handle updating a plugin's status. + * + * @since 5.5.0 + * + * @param string $plugin The plugin file to update. + * @param string $new_status The plugin's new status. + * @param string $current_status The plugin's current status. + * @return true|WP_Error + */ + protected function handle_plugin_status( $plugin, $new_status, $current_status ) { + if ( 'inactive' === $new_status ) { + deactivate_plugins( $plugin, false, 'network-active' === $current_status ); + + return true; + } + + if ( 'active' === $new_status && 'network-active' === $current_status ) { + return true; + } + + $network_activate = 'network-active' === $new_status; + $activated = activate_plugin( $plugin, '', $network_activate ); + + if ( ! $network_activate && is_network_only_plugin( $plugin ) ) { + return new WP_Error( + 'rest_network_only_plugin', + __( 'Network only plugin must be network activated.', 'gutenberg' ), + array( 'status' => 400 ) + ); + } + + if ( is_wp_error( $activated ) ) { + return $activated; + } + + return true; + } + + /** + * Determine if the endpoints are available. + * + * Only the 'Direct' filesystem transport, and SSH/FTP when credentials are stored are supported at present. + * + * @since 5.5.0 + * + * @return true|WP_Error True if filesystem is available, WP_Error otherwise. + */ + protected function is_filesystem_available() { + $filesystem_method = get_filesystem_method(); + + if ( 'direct' === $filesystem_method ) { + return true; + } + + ob_start(); + $filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() ); + ob_end_clean(); + + if ( $filesystem_credentials_are_stored ) { + return true; + } + + return new WP_Error( 'fs_unavailable', __( 'The filesystem is currently unavailable for managing plugins.' ) ); + } + + /** + * Retrieves the plugin'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 ); + } + + $status = array( 'inactive', 'active' ); + + if ( is_multisite() ) { + $status[] = 'network-active'; + } + + $this->schema = array( + '$schema' => 'http://json-schema.org/draft-04/schema#', + 'title' => 'plugin', + 'type' => 'object', + 'properties' => array( + 'plugin' => array( + 'description' => __( 'The plugin file.', 'gutenberg' ), + 'type' => 'string', + 'pattern' => self::PATTERN, + 'readonly' => true, + 'context' => array( 'view', 'edit', 'embed' ), + ), + 'status' => array( + 'description' => __( 'The plugin activation status.', 'gutenberg' ), + 'type' => 'string', + 'enum' => $status, + 'context' => array( 'view', 'edit', 'embed' ), + ), + 'name' => array( + 'description' => __( 'The plugin name.', 'gutenberg' ), + 'type' => 'string', + 'readonly' => true, + 'context' => array( 'view', 'edit', 'embed' ), + ), + 'plugin_uri' => array( + 'description' => __( 'The plugin\'s website address.', 'gutenberg' ), + 'type' => 'string', + 'format' => 'uri', + 'readonly' => true, + 'context' => array( 'view', 'edit' ), + ), + 'author' => array( + 'description' => __( 'The plugin author.', 'gutenberg' ), + 'type' => 'object', + 'readonly' => true, + 'context' => array( 'view', 'edit' ), + ), + 'author_uri' => array( + 'description' => __( 'Plugin author\'s website address.', 'gutenberg' ), + 'type' => 'string', + 'format' => 'uri', + 'readonly' => true, + 'context' => array( 'view', 'edit' ), + ), + 'description' => array( + 'description' => __( 'The plugin description.', 'gutenberg' ), + 'type' => 'object', + 'readonly' => true, + 'context' => array( 'view', 'edit' ), + 'properties' => array( + 'raw' => array( + 'description' => __( 'The raw plugin description.', 'gutenberg' ), + 'type' => 'string', + ), + 'rendered' => array( + 'description' => __( 'The plugin description formatted for display.', 'gutenberg' ), + 'type' => 'string', + ), + ), + ), + 'version' => array( + 'description' => __( 'The plugin version number.', 'gutenberg' ), + 'type' => 'string', + 'readonly' => true, + 'context' => array( 'view', 'edit' ), + ), + 'network_only' => array( + 'description' => __( 'Whether the plugin can only be activated network-wide.', 'gutenberg' ), + 'type' => 'boolean', + 'readonly' => true, + 'context' => array( 'view', 'edit', 'embed' ), + ), + 'requires_wp' => array( + 'description' => __( 'Minimum required version of WordPress.', 'gutenberg' ), + 'type' => 'string', + 'readonly' => true, + 'context' => array( 'view', 'edit', 'embed' ), + ), + 'requires_php' => array( + 'description' => __( 'Minimum required version of PHP.', 'gutenberg' ), + 'type' => 'string', + 'readonly' => true, + 'context' => array( 'view', 'edit', 'embed' ), + ), + ), + ); + + return $this->add_additional_fields_schema( $this->schema ); + } + + /** + * Retrieves the query params for the collections. + * + * @since 5.5.0 + * + * @return array Query parameters for the collection. + */ + public function get_collection_params() { + return array( + 'context' => $this->get_context_param( array( 'default' => 'view' ) ), + ); + } +} diff --git a/lib/load.php b/lib/load.php index 52899966e73b7e..5c0254b1b0e836 100644 --- a/lib/load.php +++ b/lib/load.php @@ -57,6 +57,9 @@ function gutenberg_is_experiment_enabled( $name ) { if ( ! class_exists( 'WP_REST_Image_Editor_Controller' ) ) { require dirname( __FILE__ ) . '/class-wp-rest-image-editor-controller.php'; } + if ( ! class_exists( 'WP_REST_Pluins_Controller' ) ) { + require_once dirname( __FILE__ ) . '/class-wp-rest-plugins-controller.php'; + } /** * End: Include for phase 2 */ diff --git a/lib/rest-api.php b/lib/rest-api.php index 4f5190e82e00a8..75c3573e8725cd 100644 --- a/lib/rest-api.php +++ b/lib/rest-api.php @@ -154,6 +154,16 @@ function gutenberg_register_rest_customizer_nonces() { } add_action( 'rest_api_init', 'gutenberg_register_rest_customizer_nonces' ); + +/** + * Registers the Plugins REST API routes. + */ +function gutenberg_register_plugins_endpoint() { + $plugins = new WP_REST_Plugins_Controller(); + $plugins->register_routes(); +} +add_action( 'rest_api_init', 'gutenberg_register_plugins_endpoint' ); + /** * Hook in to the nav menu item post type and enable a post type rest endpoint. * diff --git a/phpunit/class-wp-rest-plugins-controller-test.php b/phpunit/class-wp-rest-plugins-controller-test.php new file mode 100644 index 00000000000000..7f2f796f8dd1fb --- /dev/null +++ b/phpunit/class-wp-rest-plugins-controller-test.php @@ -0,0 +1,378 @@ +user->create( + array( + 'role' => 'subscriber', + ) + ); + self::$administrator_id = $factory->user->create( + array( + 'role' => 'administrator', + ) + ); + } + + /** + * Clean up test fixtures. + * + * @since 5.5.0 + */ + public static function wpTearDownAfterClass() { + self::delete_user( self::$subscriber_id ); + self::delete_user( self::$administrator_id ); + } + + public function tearDown() { + parent::tearDown(); + + if ( file_exists( WP_PLUGIN_DIR . '/test-plugin/test-plugin.php' ) ) { + $this->rmdir( WP_PLUGIN_DIR . '/test-plugin' ); + } + } + + public function test_register_routes() { + $routes = rest_get_server()->get_routes(); + $this->assertArrayHasKey( self::BASE, $routes ); + $this->assertArrayHasKey( self::BASE . '/(?P[^.\/]+(?:\/[^.\/]+)?)', $routes ); + } + + public function test_context_param() { + // Collection. + $request = new WP_REST_Request( 'OPTIONS', self::BASE ); + $response = rest_get_server()->dispatch( $request ); + $data = $response->get_data(); + $this->assertEquals( 'view', $data['endpoints'][0]['args']['context']['default'] ); + $this->assertEquals( array( 'view', 'embed', 'edit' ), $data['endpoints'][0]['args']['context']['enum'] ); + // Single. + $request = new WP_REST_Request( 'OPTIONS', self::BASE . '/' . self::PLUGIN ); + $response = rest_get_server()->dispatch( $request ); + $data = $response->get_data(); + $this->assertEquals( 'view', $data['endpoints'][0]['args']['context']['default'] ); + $this->assertEquals( array( 'view', 'embed', 'edit' ), $data['endpoints'][0]['args']['context']['enum'] ); + } + + public function test_get_items() { + $this->create_test_plugin(); + wp_set_current_user( self::$administrator_id ); + + $response = rest_do_request( self::BASE ); + $this->assertEquals( 200, $response->get_status() ); + + $items = wp_list_filter( $response->get_data(), array( 'plugin' => self::PLUGIN_FILE ) ); + + $this->assertCount( 1, $items ); + $this->check_get_plugin_data( array_shift( $items ) ); + } + + public function test_get_items_logged_out() { + $response = rest_do_request( self::BASE ); + $this->assertEquals( 401, $response->get_status() ); + } + + public function test_get_items_insufficient_permissions() { + wp_set_current_user( self::$subscriber_id ); + $response = rest_do_request( self::BASE ); + $this->assertequals( 403, $response->get_status() ); + } + + public function test_get_item() { + $this->create_test_plugin(); + wp_set_current_user( self::$administrator_id ); + + $response = rest_do_request( self::BASE . '/' . self::PLUGIN ); + $this->assertEquals( 200, $response->get_status() ); + $this->check_get_plugin_data( $response->get_data() ); + } + + public function test_get_item_logged_out() { + $response = rest_do_request( self::BASE . '/' . self::PLUGIN ); + $this->assertEquals( 401, $response->get_status() ); + } + + public function test_get_item_insufficient_permissions() { + wp_set_current_user( self::$subscriber_id ); + $response = rest_do_request( self::BASE . '/' . self::PLUGIN ); + $this->assertEquals( 403, $response->get_status() ); + } + + public function test_get_item_invalid_plugin() { + wp_set_current_user( self::$administrator_id ); + $response = rest_do_request( self::BASE . '/' . self::PLUGIN ); + $this->assertEquals( 404, $response->get_status() ); + } + + public function test_create_item() { + if ( isset( get_plugins()['hello-dolly/hello.php'] ) ) { + delete_plugins( array( 'hello-dolly/hello.php' ) ); + } + + wp_set_current_user( self::$administrator_id ); + + $request = new WP_REST_Request( 'POST', self::BASE ); + $request->set_body_params( array( 'slug' => 'hello-dolly' ) ); + + $response = rest_do_request( $request ); + $this->assertNotWPError( $response->as_error() ); + $this->assertEquals( 201, $response->get_status() ); + $this->assertEquals( 'Hello Dolly', $response->get_data()['name'] ); + } + + public function test_create_item_logged_out() { + $request = new WP_REST_Request( 'POST', self::BASE ); + $request->set_body_params( array( 'slug' => 'hello-dolly' ) ); + + $response = rest_do_request( $request ); + $this->assertEquals( 401, $response->get_status() ); + } + + public function test_create_item_insufficient_permissions() { + wp_set_current_user( self::$subscriber_id ); + $request = new WP_REST_Request( 'POST', self::BASE ); + $request->set_body_params( array( 'slug' => 'hello-dolly' ) ); + + $response = rest_do_request( $request ); + $this->assertEquals( 403, $response->get_status() ); + } + + public function test_create_item_wdotorg_unreachable() { + wp_set_current_user( self::$administrator_id ); + + $request = new WP_REST_Request( 'POST', self::BASE ); + $request->set_body_params( array( 'slug' => 'foo' ) ); + + $this->prevent_requests_to_host( 'api.wordpress.org' ); + + $this->expectException( 'PHPUnit_Framework_Error_Warning' ); + $response = rest_do_request( $request ); + $this->assertErrorResponse( 'plugins_api_failed', $response, 500 ); + } + + public function test_create_item_unknown_plugin() { + wp_set_current_user( self::$administrator_id ); + + // This will hit the live API. + $request = new WP_REST_Request( 'POST', self::BASE ); + $request->set_body_params( array( 'slug' => 'alex-says-this-block-definitely-doesnt-exist' ) ); + $response = rest_do_request( $request ); + + // Is this an appropriate status? + $this->assertErrorResponse( 'plugins_api_failed', $response, 404 ); + } + + public function test_update_item() { + $this->create_test_plugin(); + wp_set_current_user( self::$administrator_id ); + + $request = new WP_REST_Request( 'PUT', self::BASE . '/' . self::PLUGIN ); + $response = rest_do_request( $request ); + + $this->assertEquals( 200, $response->get_status() ); + } + + public function test_update_item_logged_out() { + $request = new WP_REST_Request( 'PUT', self::BASE . '/' . self::PLUGIN ); + $response = rest_do_request( $request ); + + $this->assertEquals( 401, $response->get_status() ); + } + + public function test_update_item_insufficient_permissions() { + wp_set_current_user( self::$subscriber_id ); + + $request = new WP_REST_Request( 'PUT', self::BASE . '/' . self::PLUGIN ); + $response = rest_do_request( $request ); + + $this->assertEquals( 403, $response->get_status() ); + } + + public function test_update_item_activate_plugin() { + $this->create_test_plugin(); + wp_set_current_user( self::$administrator_id ); + + $request = new WP_REST_Request( 'PUT', self::BASE . '/' . self::PLUGIN ); + $request->set_body_params( array( 'status' => 'active' ) ); + $response = rest_do_request( $request ); + + $this->assertEquals( 200, $response->get_status() ); + $this->assertTrue( is_plugin_active( self::PLUGIN_FILE ) ); + } + + public function test_update_item_deactivate_plugin() { + $this->create_test_plugin(); + activate_plugin( self::PLUGIN_FILE ); + wp_set_current_user( self::$administrator_id ); + + $request = new WP_REST_Request( 'PUT', self::BASE . '/' . self::PLUGIN ); + $request->set_body_params( array( 'status' => 'inactive' ) ); + $response = rest_do_request( $request ); + + $this->assertEquals( 200, $response->get_status() ); + $this->assertTrue( is_plugin_inactive( self::PLUGIN_FILE ) ); + } + + public function test_delete_item() { + $this->create_test_plugin(); + wp_set_current_user( self::$administrator_id ); + + $request = new WP_REST_Request( 'DELETE', self::BASE . '/' . self::PLUGIN ); + $response = rest_do_request( $request ); + + $this->assertNotWPError( $response->as_error() ); + $this->assertEquals( 204, $response->get_status() ); + $this->assertFileNotExists( WP_PLUGIN_DIR . '/' . self::PLUGIN_FILE ); + } + + public function test_delete_item_logged_out() { + $request = new WP_REST_Request( 'DELETE', self::BASE . '/' . self::PLUGIN ); + $response = rest_do_request( $request ); + + $this->assertEquals( 401, $response->get_status() ); + } + + public function test_delete_item_insufficient_permissions() { + wp_set_current_user( self::$subscriber_id ); + + $request = new WP_REST_Request( 'DELETE', self::BASE . '/' . self::PLUGIN ); + $response = rest_do_request( $request ); + + $this->assertEquals( 403, $response->get_status() ); + } + + public function test_prepare_item() { + $this->create_test_plugin(); + + $item = get_plugins()[ self::PLUGIN_FILE ]; + $item['_file'] = self::PLUGIN_FILE; + + $endpoint = new WP_REST_Plugins_Controller(); + $response = $endpoint->prepare_item_for_response( $item, new WP_REST_Request( 'GET', self::BASE . '/' . self::PLUGIN ) ); + + $this->check_get_plugin_data( $response->get_data() ); + } + + public function test_get_item_schema() { + $request = new WP_REST_Request( 'OPTIONS', self::BASE ); + $response = rest_get_server()->dispatch( $request ); + $data = $response->get_data(); + $properties = $data['schema']['properties']; + + $this->assertCount( 11, $properties ); + $this->assertArrayHasKey( 'plugin', $properties ); + $this->assertArrayHasKey( 'status', $properties ); + $this->assertArrayHasKey( 'name', $properties ); + $this->assertArrayHasKey( 'plugin_uri', $properties ); + $this->assertArrayHasKey( 'description', $properties ); + $this->assertArrayHasKey( 'author', $properties ); + $this->assertArrayHasKey( 'author_uri', $properties ); + $this->assertArrayHasKey( 'version', $properties ); + $this->assertArrayHasKey( 'network_only', $properties ); + $this->assertArrayHasKey( 'requires_wp', $properties ); + $this->assertArrayHasKey( 'requires_php', $properties ); + } + + /** + * Checks the response data. + * + * @since 5.5.0 + * + * @param array $data + */ + protected function check_get_plugin_data( $data ) { + $this->assertEquals( 'test-plugin/test-plugin.php', $data['plugin'] ); + $this->assertEquals( '1.5.4', $data['version'] ); + $this->assertEquals( 'inactive', $data['status'] ); + $this->assertEquals( 'Test Plugin', $data['name'] ); + $this->assertEquals( 'https://wordpress.org/plugins/test-plugin/', $data['plugin_uri'] ); + $this->assertEquals( 'WordPress.org', $data['author'] ); + $this->assertEquals( 'https://wordpress.org/', $data['author_uri'] ); + $this->assertEquals( "My 'Cool' Plugin", $data['description']['raw'] ); + $this->assertEquals( 'My ‘Cool’ Plugin By WordPress.org.', $data['description']['rendered'] ); + $this->assertEquals( false, $data['network_only'] ); + $this->assertEquals( '5.6.0', $data['requires_php'] ); + $this->assertEquals( '5.4.0', $data['requires_wp'] ); + } + + /** + * Creates a test plugin. + * + * @since 5.5.0 + */ + private function create_test_plugin() { + $php = <<<'PHP' + Date: Tue, 19 May 2020 01:22:28 -0400 Subject: [PATCH 02/25] phpcs fixes. Don't check status permissions if not updating it --- lib/class-wp-rest-plugins-controller.php | 15 +++++++++++---- phpunit/class-wp-rest-plugins-controller-test.php | 7 +++---- 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/lib/class-wp-rest-plugins-controller.php b/lib/class-wp-rest-plugins-controller.php index 78c3882225b3b0..83177695e9ccc0 100644 --- a/lib/class-wp-rest-plugins-controller.php +++ b/lib/class-wp-rest-plugins-controller.php @@ -1,12 +1,19 @@ get_plugin_status( $request['plugin'] ); - if ( $status !== $request['status'] ) { + if ( $request['status'] && $status !== $request['status'] ) { if ( ( 'network-active' === $status || 'network-active' === $request['status'] ) && ! current_user_can( 'manage_network_plugins' ) ) { return new WP_Error( 'rest_cannot_manage_network_plugins', @@ -625,7 +632,7 @@ protected function is_filesystem_available() { return true; } - return new WP_Error( 'fs_unavailable', __( 'The filesystem is currently unavailable for managing plugins.' ) ); + return new WP_Error( 'fs_unavailable', __( 'The filesystem is currently unavailable for managing plugins.', 'gutenberg' ) ); } /** diff --git a/phpunit/class-wp-rest-plugins-controller-test.php b/phpunit/class-wp-rest-plugins-controller-test.php index 7f2f796f8dd1fb..d6ddb33ec6328d 100644 --- a/phpunit/class-wp-rest-plugins-controller-test.php +++ b/phpunit/class-wp-rest-plugins-controller-test.php @@ -11,8 +11,8 @@ */ class WP_REST_Plugins_Controller_Test extends WP_Test_REST_Controller_Testcase { - const BASE = '/__experimental/plugins'; - const PLUGIN = 'test-plugin/test-plugin'; + const BASE = '/__experimental/plugins'; + const PLUGIN = 'test-plugin/test-plugin'; const PLUGIN_FILE = self::PLUGIN . '.php'; /** @@ -316,7 +316,7 @@ public function test_get_item_schema() { * * @since 5.5.0 * - * @param array $data + * @param array $data Prepared plugin data. */ protected function check_get_plugin_data( $data ) { $this->assertEquals( 'test-plugin/test-plugin.php', $data['plugin'] ); @@ -360,7 +360,6 @@ private function create_test_plugin() { * Simulate a network failure on outbound http requests to a given hostname. */ private function prevent_requests_to_host( $blocked_host = 'api.wordpress.org' ) { - // apply_filters( 'pre_http_request', false, $parsed_args, $url ); add_filter( 'pre_http_request', static function ( $return, $args, $url ) use ( $blocked_host ) { From 9ecb573219630706e55e5695cf244540e6dcf5af Mon Sep 17 00:00:00 2001 From: Timothy Jacobs Date: Tue, 19 May 2020 11:48:26 -0400 Subject: [PATCH 03/25] Try forcing the filesystem method to direct --- phpunit/class-wp-rest-plugins-controller-test.php | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/phpunit/class-wp-rest-plugins-controller-test.php b/phpunit/class-wp-rest-plugins-controller-test.php index d6ddb33ec6328d..a6b0ff6a1cb55b 100644 --- a/phpunit/class-wp-rest-plugins-controller-test.php +++ b/phpunit/class-wp-rest-plugins-controller-test.php @@ -143,10 +143,16 @@ public function test_get_item_invalid_plugin() { } public function test_create_item() { + if ( ! defined( 'FS_METHOD' ) ) { + define( 'FS_METHOD', 'direct' ); + } + if ( isset( get_plugins()['hello-dolly/hello.php'] ) ) { delete_plugins( array( 'hello-dolly/hello.php' ) ); } + $this->assertEquals( 'direct', get_filesystem_method() ); + wp_set_current_user( self::$administrator_id ); $request = new WP_REST_Request( 'POST', self::BASE ); @@ -252,6 +258,10 @@ public function test_update_item_deactivate_plugin() { } public function test_delete_item() { + if ( ! defined( 'FS_METHOD' ) ) { + define( 'FS_METHOD', 'direct' ); + } + $this->create_test_plugin(); wp_set_current_user( self::$administrator_id ); @@ -352,7 +362,7 @@ private function create_test_plugin() { * Requires at least: 5.4.0 */ PHP; - wp_mkdir_p( WP_PLUGIN_DIR . '/test-plugin' ); + $this->assertTrue( wp_mkdir_p( WP_PLUGIN_DIR . '/test-plugin' ) ); file_put_contents( WP_PLUGIN_DIR . '/test-plugin/test-plugin.php', $php ); } From 471332ac0e3e7750df5bccb8583646e7a6886a51 Mon Sep 17 00:00:00 2001 From: Timothy Jacobs Date: Tue, 19 May 2020 12:10:14 -0400 Subject: [PATCH 04/25] Fix spacing issue --- phpunit/class-wp-rest-plugins-controller-test.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/phpunit/class-wp-rest-plugins-controller-test.php b/phpunit/class-wp-rest-plugins-controller-test.php index a6b0ff6a1cb55b..c40752377f5094 100644 --- a/phpunit/class-wp-rest-plugins-controller-test.php +++ b/phpunit/class-wp-rest-plugins-controller-test.php @@ -261,7 +261,7 @@ public function test_delete_item() { if ( ! defined( 'FS_METHOD' ) ) { define( 'FS_METHOD', 'direct' ); } - + $this->create_test_plugin(); wp_set_current_user( self::$administrator_id ); From 4480a8a0c8a8668bff33bb3db7350c3fcb92e392 Mon Sep 17 00:00:00 2001 From: tellyworth Date: Wed, 20 May 2020 17:22:50 +1000 Subject: [PATCH 05/25] Clean up block directory controller This draws on https://github.com/WordPress/gutenberg/pull/17669 and https://github.com/tellyworth/wordpress-develop/pull/1. It fixes many small issues with the block directory controller, and adds unit tests. --- ...ass-wp-rest-block-directory-controller.php | 455 +++++++++++++----- ...p-rest-block-directory-controller-test.php | 215 +++++++++ 2 files changed, 545 insertions(+), 125 deletions(-) create mode 100644 phpunit/class-wp-rest-block-directory-controller-test.php diff --git a/lib/class-wp-rest-block-directory-controller.php b/lib/class-wp-rest-block-directory-controller.php index abc7a2c6c9ae7a..061fe01519b9d9 100644 --- a/lib/class-wp-rest-block-directory-controller.php +++ b/lib/class-wp-rest-block-directory-controller.php @@ -1,7 +1,7 @@ namespace, '/' . $this->rest_base . '/search', array( - array( - 'methods' => WP_REST_Server::READABLE, - 'callback' => array( $this, 'get_items' ), - 'permission_callback' => array( $this, 'permissions_check' ), + 'methods' => WP_REST_Server::READABLE, + 'callback' => array( $this, 'get_items' ), + 'permission_callback' => array( $this, 'get_items_permissions_check' ), + 'args' => array( + 'term' => array( + 'required' => true, + ), ), - 'schema' => array( $this, 'get_item_schema' ), + 'schema' => array( $this, 'get_item_schema' ), ) ); + register_rest_route( $this->namespace, '/' . $this->rest_base . '/install', array( - array( - 'methods' => WP_REST_Server::CREATABLE, - 'callback' => array( $this, 'install_block' ), - 'permission_callback' => array( $this, 'permissions_check' ), + 'methods' => WP_REST_Server::CREATABLE, + 'callback' => array( $this, 'install_block' ), + 'permission_callback' => array( $this, 'install_items_permissions_check' ), + 'args' => array( + 'slug' => array( + 'required' => true, + ), ), - 'schema' => array( $this, 'get_item_schema' ), + 'schema' => array( $this, 'get_item_schema' ), ) ); + register_rest_route( $this->namespace, '/' . $this->rest_base . '/uninstall', array( - array( - 'methods' => WP_REST_Server::DELETABLE, - 'callback' => array( $this, 'uninstall_block' ), - 'permission_callback' => array( $this, 'permissions_check' ), + 'methods' => WP_REST_Server::DELETABLE, + 'callback' => array( $this, 'uninstall_block' ), + 'permission_callback' => array( $this, 'delete_items_permissions_check' ), + 'args' => array( + 'slug' => array( + 'required' => true, + ), ), - 'schema' => array( $this, 'get_item_schema' ), + 'schema' => array( $this, 'get_item_schema' ), ) ); } @@ -71,9 +82,11 @@ public function register_routes() { * * @since 6.5.0 * + * @param WP_REST_Request $request Full details about the request. * @return WP_Error|bool True if the request has permission, WP_Error object otherwise. + * phpcs:disable VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable */ - public function permissions_check() { + public function get_items_permissions_check( $request ) { if ( ! current_user_can( 'install_plugins' ) || ! current_user_can( 'activate_plugins' ) ) { return new WP_Error( 'rest_user_cannot_view', @@ -83,6 +96,59 @@ public function permissions_check() { return true; } + /* phpcs:enable */ + + /** + * Checks whether a given request has permission to install and activate plugins. + * + * @since 6.5.0 + * + * @param WP_REST_Request $request Full details about the request. + * @return WP_Error|bool True if the request has permission, WP_Error object otherwise. + */ + public function install_items_permissions_check( $request ) { + $plugin = $request->get_param( 'slug' ); + + if ( + ! current_user_can( 'install_plugins' ) || + ! current_user_can( 'activate_plugins' ) || + ! current_user_can( 'activate_plugin', $plugin ) + ) { + return new WP_Error( + 'rest_user_cannot_view', + __( 'Sorry, you are not allowed to install blocks.', 'gutenberg' ), + array( 'status' => rest_authorization_required_code() ) + ); + } + + return true; + } + + /** + * Checks whether a given request has permission to remove/deactivate plugins. + * + * @since 6.5.0 + * + * @param WP_REST_Request $request Full details about the request. + * @return WP_Error|bool True if the request has permission, WP_Error object otherwise. + */ + public function delete_items_permissions_check( $request ) { + $plugin = $request->get_param( 'slug' ); + + if ( + ! current_user_can( 'delete_plugins' ) || + ! current_user_can( 'deactivate_plugins' ) || + ! current_user_can( 'deactivate_plugin', $plugin ) + ) { + return new WP_Error( + 'rest_user_cannot_delete', + __( 'Sorry, you are not allowed to uninstall blocks.', 'gutenberg' ), + array( 'status' => rest_authorization_required_code() ) + ); + } + + return true; + } /** * Installs and activates a plugin @@ -99,65 +165,63 @@ public function install_block( $request ) { include_once( ABSPATH . 'wp-admin/includes/class-wp-upgrader.php' ); include_once( ABSPATH . 'wp-admin/includes/plugin-install.php' ); + $slug = $request->get_param( 'slug' ); + + // Verify filesystem is accessible first. + $filesystem_available = self::is_filesystem_available(); + if ( is_wp_error( $filesystem_available ) ) { + return $filesystem_available; + } + $api = plugins_api( 'plugin_information', array( - 'slug' => $request->get_param( 'slug' ), + 'slug' => $slug, 'fields' => array( 'sections' => false, ), ) ); - // Check if the plugin is already installed. - $installed_plugins = get_plugins( '/' . $api->slug ); - - if ( empty( $installed_plugins ) ) { - - if ( is_wp_error( $api ) ) { - return WP_Error( $api->get_error_code(), $api->get_error_message() ); - } - - $skin = new WP_Ajax_Upgrader_Skin(); - $upgrader = new Plugin_Upgrader( $skin ); - - $filesystem_method = get_filesystem_method(); + if ( is_wp_error( $api ) ) { + $api->add_data( array( 'status' => 500 ) ); + return $api; + } - if ( 'direct' !== $filesystem_method ) { - return WP_Error( null, 'Only direct FS_METHOD is supported.' ); - } + $skin = new WP_Ajax_Upgrader_Skin(); + $upgrader = new Plugin_Upgrader( $skin ); - $result = $upgrader->install( $api->download_link ); + $result = $upgrader->install( $api->download_link ); - if ( is_wp_error( $result ) ) { - return WP_Error( $result->get_error_code(), $result->get_error_message() ); - } + if ( is_wp_error( $result ) ) { + return $result; + } - if ( is_wp_error( $skin->result ) ) { - return WP_Error( $skin->$result->get_error_code(), $skin->$result->get_error_message() ); - } + // This should be the same as $result above. + if ( is_wp_error( $skin->result ) ) { + return $skin->result; + } - if ( $skin->get_errors()->has_errors() ) { - return WP_Error( $skin->$result->get_error_code(), $skin->$result->get_error_messages() ); - } + if ( $skin->get_errors()->has_errors() ) { + return $skin->get_errors(); + } - if ( is_null( $result ) ) { - global $wp_filesystem; - // Pass through the error from WP_Filesystem if one was raised. - if ( $wp_filesystem instanceof WP_Filesystem_Base && is_wp_error( $wp_filesystem->errors ) && $wp_filesystem->errors->has_errors() ) { - return WP_Error( 'unable_to_connect_to_filesystem', esc_html( $wp_filesystem->errors->get_error_message() ) ); - } - return WP_Error( 'unable_to_connect_to_filesystem', __( 'Unable to connect to the filesystem. Please confirm your credentials.', 'gutenberg' ) ); + if ( is_null( $result ) ) { + global $wp_filesystem; + // Pass through the error from WP_Filesystem if one was raised. + if ( $wp_filesystem instanceof WP_Filesystem_Base && is_wp_error( $wp_filesystem->errors ) && $wp_filesystem->errors->has_errors() ) { + return new WP_Error( 'unable_to_connect_to_filesystem', esc_html( $wp_filesystem->errors->get_error_message() ), array( 'status' => 500 ) ); } + return new WP_Error( 'unable_to_connect_to_filesystem', __( 'Unable to connect to the filesystem. Please confirm your credentials.', 'gutenberg' ), array( 'status' => 500 ) ); } - $install_status = install_plugin_install_status( $api ); + // Find the plugin to activate it. + $plugin_files = get_plugins( '/' . $slug ); + $plugin_files = array_keys( $plugin_files ); - $activate_result = activate_plugin( $install_status['file'] ); + $plugin_file = $slug . '/' . reset( $plugin_files ); - if ( is_wp_error( $activate_result ) ) { - return WP_Error( $activate_result->get_error_code(), $activate_result->get_error_message() ); - } + activate_plugin( $plugin_file ); return rest_ensure_response( array( 'success' => true ) ); } @@ -177,32 +241,33 @@ public function uninstall_block( $request ) { include_once( ABSPATH . 'wp-admin/includes/class-wp-upgrader.php' ); include_once( ABSPATH . 'wp-admin/includes/plugin-install.php' ); - $api = plugins_api( - 'plugin_information', - array( - 'slug' => $request->get_param( 'slug' ), - 'fields' => array( - 'sections' => false, - ), - ) - ); + $slug = trim( $request->get_param( 'slug' ) ); - if ( is_wp_error( $api ) ) { - return WP_Error( $api->get_error_code(), $api->get_error_message() ); + if ( ! $slug ) { + return new WP_Error( 'slug_not_provided', 'Valid slug not provided.', array( 'status' => 400 ) ); } - $install_status = install_plugin_install_status( $api ); + // Verify filesystem is accessible first. + $filesystem_available = self::is_filesystem_available(); + if ( is_wp_error( $filesystem_available ) ) { + return $filesystem_available; + } - $deactivate_result = deactivate_plugins( $install_status['file'] ); + $plugin_files = get_plugins( '/' . $slug ); - if ( is_wp_error( $deactivate_result ) ) { - return WP_Error( $deactivate_result->get_error_code(), $deactivate_result->get_error_message() ); + if ( ! $plugin_files ) { + return new WP_Error( 'block_not_found', 'Valid slug not provided.', array( 'status' => 400 ) ); } - $delete_result = delete_plugins( array( $install_status['file'] ) ); + $plugin_files = array_keys( $plugin_files ); + $plugin_file = $slug . '/' . reset( $plugin_files ); + + deactivate_plugins( $plugin_file ); + + $delete_result = delete_plugins( array( $plugin_file ) ); if ( is_wp_error( $delete_result ) ) { - return WP_Error( $delete_result->get_error_code(), $delete_result->get_error_message() ); + return $delete_result; } return rest_ensure_response( true ); @@ -218,95 +283,235 @@ public function uninstall_block( $request ) { */ public function get_items( $request ) { - $search_string = $request->get_param( 'term' ); + $search_string = trim( $request->get_param( 'term' ) ); if ( empty( $search_string ) ) { return rest_ensure_response( array() ); } - include( ABSPATH . WPINC . '/version.php' ); + require_once ABSPATH . 'wp-admin/includes/plugin-install.php'; + require_once ABSPATH . 'wp-admin/includes/plugin.php'; - $url = 'http://api.wordpress.org/plugins/info/1.2/'; - $url = add_query_arg( + $response = plugins_api( + 'query_plugins', array( - 'action' => 'query_plugins', - 'request[block]' => $search_string, - 'request[wp_version]' => '5.3', - 'request[per_page]' => '3', - ), - $url + 'block' => $search_string, + 'per_page' => 3, + ) ); - $ssl = wp_http_supports( array( 'ssl' ) ); - if ( $ssl ) { - $url = set_url_scheme( $url, 'https' ); + + if ( is_wp_error( $response ) ) { + $response->add_data( array( 'status' => 500 ) ); + return $response; } - global $wp_version; - $http_args = array( - 'timeout' => 15, - 'user-agent' => 'WordPress/' . $wp_version . '; ' . home_url( '/' ), - ); + $result = array(); - $request = wp_remote_get( $url, $http_args ); - $response = json_decode( wp_remote_retrieve_body( $request ), true ); + foreach ( $response->plugins as $plugin ) { + $installed_plugins = get_plugins( '/' . $plugin['slug'] ); - if ( ! function_exists( 'get_plugins' ) ) { - require_once ABSPATH . 'wp-admin/includes/plugin.php'; + // Only show uninstalled blocks. + if ( empty( $installed_plugins ) ) { + $data = $this->prepare_item_for_response( $plugin, $request ); + $result[] = $this->prepare_response_for_collection( $data ); + } } - $result = array(); + return rest_ensure_response( $result ); + } + + /** + * Determine if the endpoints are available. + * + * Only the 'Direct' filesystem transport, and SSH/FTP when credentials are stored are supported at present. + * + * @since 6.5.0 + * + * @return bool|WP_Error True if filesystem is available, WP_Error otherwise. + */ + private static function is_filesystem_available() { + $filesystem_method = get_filesystem_method(); - foreach ( $response['plugins'] as $plugin ) { - $result[] = self::parse_block_metadata( $plugin ); + if ( 'direct' === $filesystem_method ) { + return true; } - return rest_ensure_response( $result ); + ob_start(); + $filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() ); + ob_end_clean(); + + if ( $filesystem_credentials_are_stored ) { + return true; + } + + return new WP_Error( 'fs_unavailable', __( 'The filesystem is currently unavailable for installing blocks.' ) ); } /** - * Parse block metadata for a block + * Parse block metadata for a block, and prepare it for an API repsonse. * * @since 6.5.0 * * @param WP_Object $plugin The plugin metadata. + * @param WP_REST_Request $request Request object. * @return WP_Error|WP_REST_Response Response object on success, or WP_Error object on failure. */ - private static function parse_block_metadata( $plugin ) { - $block = new stdClass(); + public function prepare_item_for_response( $plugin, $request ) { // There might be multiple blocks in a plugin. Only the first block is mapped. $block_data = reset( $plugin['blocks'] ); - $block->name = $block_data['name']; - $block->title = $block_data['title']; - // Plugin's description, not description in block.json. - $block->description = wp_trim_words( wp_strip_all_tags( $plugin['description'] ), 30, '...' ); + // A data array containing the properties we'll return. + $block = array( + 'name' => $block_data['name'], + 'title' => ( $block_data['title'] ? $block_data['title'] : $plugin['name'] ), + 'description' => wp_trim_words( $plugin['description'], 30, '...' ), + 'id' => $plugin['slug'], + 'rating' => $plugin['rating'] / 20, + 'rating_count' => intval( $plugin['num_ratings'] ), + 'active_installs' => intval( $plugin['active_installs'] ), + 'author_block_rating' => $plugin['author_block_rating'] / 20, + 'author_block_count' => intval( $plugin['author_block_count'] ), + 'author' => wp_strip_all_tags( $plugin['author'] ), + 'icon' => ( isset( $plugin['icons']['1x'] ) ? $plugin['icons']['1x'] : 'block-default' ), + 'assets' => array(), + 'humanized_updated' => sprintf( + /* translators: %s: Human-readable time difference. */ + __( '%s ago' ), + human_time_diff( strtotime( $plugin['last_updated'] ), current_time( 'timestamp' ) ) + ), + ); - $block->id = $plugin['slug']; - $block->rating = $plugin['rating'] / 20; - $block->rating_count = $plugin['num_ratings']; - $block->active_installs = $plugin['active_installs']; - $block->author_block_rating = $plugin['author_block_rating'] / 20; - $block->author_block_count = (int) $plugin['author_block_count']; + foreach ( $plugin['block_assets'] as $asset ) { + // TODO: Return from API, not client-set. + $block[ 'assets' ][] = 'https://plugins.svn.wordpress.org/' . $plugin['slug'] . $asset; + } - // Plugin's author, not author in block.json. - $block->author = wp_strip_all_tags( $plugin['author'] ); + $response = new WP_REST_Response( $block ); - // Plugin's icons or icon in block.json. - $block->icon = isset( $plugin['icons']['1x'] ) ? $plugin['icons']['1x'] : 'block-default'; + return $response; + } - $block->assets = array(); + /** + * Retrieves the theme's schema, conforming to JSON Schema. + * + * @since 5.5.0 + * + * @return array Item schema data. + */ + public function get_item_schema() { + $this->schema = array( + '$schema' => 'http://json-schema.org/draft-04/schema#', + 'title' => 'block-directory-item', + 'type' => 'object', + 'properties' => array( + 'name' => array( + 'description' => __( "The block name, in namespace/block-name format." ), + 'type' => 'string', + 'context' => array( 'view' ), + ), + 'title' => array( + 'description' => __( "The block title, in human readable format." ), + 'type' => 'string', + 'context' => array( 'view' ), + ), + 'description' => array( + 'description' => __( "A short description of the block, in human readable format." ), + 'type' => 'string', + 'context' => array( 'view' ), + ), + 'id' => array( + 'description' => __( "The block slug." ), + 'type' => 'string', + 'context' => array( 'view' ), + ), + 'rating' => array( + 'description' => __( "The star rating of the block." ), + 'type' => 'integer', + 'context' => array( 'view' ), + ), + 'rating_count' => array( + 'description' => __( "The number of ratings." ), + 'type' => 'integer', + 'context' => array( 'view' ), + ), + 'active_installs' => array( + 'description' => __( "The number sites that have activated this block." ), + 'type' => 'string', + 'context' => array( 'view' ), + ), + 'author_block_rating' => array( + 'description' => __( "The average rating of blocks published by the same author." ), + 'type' => 'integer', + 'context' => array( 'view' ), + ), + 'author_block_count' => array( + 'description' => __( "The number of blocks published by the same author." ), + 'type' => 'integer', + 'context' => array( 'view' ), + ), + 'author' => array( + 'description' => __( "The WordPress.org username of the block author." ), + 'type' => 'string', + 'context' => array( 'view' ), + ), + 'icon' => array( + 'description' => __( "The block icon." ), + 'type' => 'string', + 'format' => 'uri', + 'context' => array( 'view' ), + ), + 'humanized_updated' => array( + 'description' => __( "The date when the block was last updated, in fuzzy human readable format." ), + 'type' => 'string', + 'context' => array( 'view' ), + ), + 'assets' => array( + 'description' => __( 'An object representing the block CSS and JavaScript assets.' ), + 'type' => 'array', + 'context' => array( 'view' ), + 'readonly' => true, + 'items' => array( + 'type' => 'string', + 'format' => 'uri', + ), - foreach ( $plugin['block_assets'] as $asset ) { - $block->assets[] = 'https://plugins.svn.wordpress.org/' . $plugin['slug'] . $asset; - } + ), + + ), + ); + + return $this->schema; + } - $block->humanized_updated = sprintf( - /* translators: %s: Human-readable time difference. */ - __( '%s ago', 'gutenberg' ), - human_time_diff( strtotime( $plugin['last_updated'] ), time() ) + + /** + * Retrieves the search params for the blocks collection. + * + * @since 5.5.0 + * + * @return array Collection parameters. + */ + public function get_collection_params() { + $query_params = parent::get_collection_params(); + + $query_params['term'] = array( + 'description' => __( 'Limit result set to blocks matching the search term.' ), + 'type' => 'array', + 'term' => array( + 'type' => 'string', + ), + 'required' => true, ); - return $block; + /** + * Filter collection parameters for the block directory controller. + * + * @since 5.0.0 + * + * @param array $query_params JSON Schema-formatted collection parameters. + */ + return apply_filters( 'rest_block_directory_collection_params', $query_params ); } + } diff --git a/phpunit/class-wp-rest-block-directory-controller-test.php b/phpunit/class-wp-rest-block-directory-controller-test.php new file mode 100644 index 00000000000000..9f4ffd49c9d7ff --- /dev/null +++ b/phpunit/class-wp-rest-block-directory-controller-test.php @@ -0,0 +1,215 @@ +user->create( + array( + 'role' => 'administrator', + ) + ); + + // Ensure routes are registered regardless of the `gutenberg-block-directory` experimental setting. + // This should be removed when `gutenberg_register_rest_block_directory()` is unconditional. + add_filter( 'rest_api_init', function() { + $block_directory_controller = new WP_REST_Block_Directory_Controller(); + $block_directory_controller->register_routes(); + } ); + } + + public static function wpTearDownAfterClass() { + self::delete_user( self::$admin_id ); + } + + public function test_register_routes() { + $routes = rest_get_server()->get_routes(); + + $this->assertArrayHasKey( '/__experimental/block-directory/search', $routes ); + $this->assertArrayHasKey( '/__experimental/block-directory/install', $routes ); + $this->assertArrayHasKey( '/__experimental/block-directory/uninstall', $routes ); + } + + /** + * Tests that an error is returned if the block plugin slug is not provided + */ + function test_should_throw_no_slug_error() { + wp_set_current_user( self::$admin_id ); + + $request = new WP_REST_Request( 'POST', '/__experimental/block-directory/install', [] ); + $result = rest_do_request( $request ); + + $this->assertErrorResponse( 'rest_missing_callback_param', $result, 400 ); + } + + /** + * Tests that the search endpoint does not return an error + */ + function test_simple_search() { + wp_set_current_user( self::$admin_id ); + + $request = new WP_REST_Request( 'GET', '/__experimental/block-directory/search' ); + $request->set_query_params( array( 'term' => 'foo' ) ); + + $result = rest_do_request( $request ); + $this->assertNotWPError( $result ); + $this->assertEquals( 200, $result->status ); + } + + /** + * Simulate a network failure on outbound http requests to a given hostname. + */ + function prevent_requests_to_host( $blocked_host = 'api.wordpress.org' ) { + // apply_filters( 'pre_http_request', false, $parsed_args, $url ); + add_filter( 'pre_http_request', function( $return, $args, $url ) use ( $blocked_host ) { + if ( @parse_url( $url, PHP_URL_HOST ) === $blocked_host ) { + return new WP_Error( 'plugins_api_failed', "An expected error occurred connecting to $blocked_host because of a unit test", "cURL error 7: Failed to connect to $blocked_host port 80: Connection refused" ); + + } + return $return; + }, 10, 3 ); + } + + /** + * Tests that the search endpoint returns WP_Error when the server is unreachable. + */ + function test_search_unreachable() { + wp_set_current_user( self::$admin_id ); + + $request = new WP_REST_Request( 'GET', '/__experimental/block-directory/search' ); + $request->set_query_params( array( 'term' => 'foo' ) ); + + $this->prevent_requests_to_host( 'api.wordpress.org' ); + + $this->expectException('PHPUnit_Framework_Error_Warning'); + $response = rest_do_request( $request ); + $this->assertErrorResponse( 'plugins_api_failed', $response, 500 ); + } + + /** + * Tests that the install endpoint returns WP_Error when the server is unreachable. + */ + function test_install_unreachable() { + wp_set_current_user( self::$admin_id ); + + $request = new WP_REST_Request( 'POST', '/__experimental/block-directory/install' ); + $request->set_query_params( array( 'slug' => 'foo' ) ); + + $this->prevent_requests_to_host( 'api.wordpress.org' ); + + $this->expectException('PHPUnit_Framework_Error_Warning'); + $response = rest_do_request( $request ); + $this->assertErrorResponse( 'plugins_api_failed', $response, 500 ); + } + + /** + * Should fail with a permission error if requesting user is not logged in. + */ + function test_simple_search_no_perms() { + $request = new WP_REST_Request( 'GET', '/__experimental/block-directory/search' ); + $request->set_query_params( array( 'term' => 'foo' ) ); + $response = rest_do_request( $request ); + $data = $response->get_data(); + + $this->assertEquals( $data['code'], 'rest_user_cannot_view' ); + } + + /** + * Make sure a search with the right permissions returns something. + */ + function test_simple_search_with_perms() { + wp_set_current_user( self::$admin_id ); + + // This will hit the live API. We're searching for `block` which should definitely return at least one result. + $request = new WP_REST_Request( 'GET', '/__experimental/block-directory/search' ); + $request->set_query_params( array( 'term' => 'block' ) ); + $response = rest_do_request( $request ); + $data = $response->get_data(); + + $this->assertEquals( 200, $response->status ); + // At least one result + $this->assertGreaterThanOrEqual( 1, count( $data ) ); + // Each result should be an object with important attributes set + foreach ( $data as $plugin ) { + $this->assertArrayHasKey( 'name', $plugin ); + $this->assertArrayHasKey( 'title', $plugin ); + $this->assertArrayHasKey( 'id', $plugin ); + $this->assertArrayHasKey( 'author_block_rating', $plugin ); + $this->assertArrayHasKey( 'assets', $plugin ); + $this->assertArrayHasKey( 'humanized_updated', $plugin ); + } + } + + /** + * A search with zero results should return a 200 response. + */ + function test_simple_search_no_results() { + wp_set_current_user( self::$admin_id ); + + $request = new WP_REST_Request( 'GET', '/__experimental/block-directory/search' ); + $request->set_query_params( array( 'term' => '0c4549ee68f24eaaed46a49dc983ecde' ) ); + $response = rest_do_request( $request ); + $data = $response->get_data(); + + // Should produce a 200 status with an empty array. + $this->assertEquals( 200, $response->status ); + $this->assertEquals( array(), $data ); + } + + /** + * Should fail with a permission error if requesting user is not logged in. + */ + function test_simple_install_no_perms() { + $request = new WP_REST_Request( 'POST', '/__experimental/block-directory/install' ); + $request->set_query_params( array( 'slug' => 'foo' ) ); + $response = rest_do_request( $request ); + $data = $response->get_data(); + + $this->assertEquals( $data['code'], 'rest_user_cannot_view' ); + } + + /** + * Make sure an install with permissions correctly handles an unknown slug. + */ + function test_simple_install_with_perms_bad_slug() { + wp_set_current_user( self::$admin_id ); + + // This will hit the live API. + $request = new WP_REST_Request( 'POST', '/__experimental/block-directory/install' ); + $request->set_query_params( array( 'slug' => 'alex-says-this-block-definitely-doesnt-exist' ) ); + $response = rest_do_request( $request ); + + // Is this an appropriate status? + $this->assertErrorResponse( 'plugins_api_failed', $response, 500 ); + } + + /** + * Make sure the search schema is available and correct. + */ + function test_search_schema() { + wp_set_current_user( self::$admin_id ); + + $request = new WP_REST_Request( 'OPTIONS', '/__experimental/block-directory/search' ); + $request->set_query_params( array( 'term' => 'foo' ) ); + $response = rest_do_request( $request ); + $data = $response->get_data(); + + // Check endpoints + $this->assertEquals( [ 'GET' ], $data['endpoints'][0]['methods'] ); + $this->assertEquals( [ 'term' => [ 'required' => true ] ], $data['endpoints'][0]['args'] ); + + // Check schema + $this->assertEquals( [ + 'description' => __( "The block name, in namespace/block-name format." ), + 'type' => [ 'string' ], + 'context' => [ 'view' ], + ], $data['schema']['properties']['name'] ); + // TODO: ..etc.. + } + +} From 2221a1d55ce6cfcf3a661c2b4eea5aedea2f77f4 Mon Sep 17 00:00:00 2001 From: Timothy Jacobs Date: Wed, 20 May 2020 22:53:48 -0400 Subject: [PATCH 06/25] Refactors block directory controller to make inner requests to the plugins controller --- ...ass-wp-rest-block-directory-controller.php | 470 ++++++++---------- 1 file changed, 203 insertions(+), 267 deletions(-) diff --git a/lib/class-wp-rest-block-directory-controller.php b/lib/class-wp-rest-block-directory-controller.php index 061fe01519b9d9..270cad894af2d4 100644 --- a/lib/class-wp-rest-block-directory-controller.php +++ b/lib/class-wp-rest-block-directory-controller.php @@ -4,15 +4,15 @@ * Block Directory REST API: WP_REST_Block_Directory_Controller class * * @package gutenberg - * @since 6.5.0 + * @since 5.5.0 */ /** * Controller which provides REST endpoint for the blocks. * - * @since 6.5.0 + * @since 5.5.0 * - * @see WP_REST_Controller + * @see WP_REST_Controller */ class WP_REST_Block_Directory_Controller extends WP_REST_Controller { @@ -35,12 +35,8 @@ public function register_routes() { 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'get_items' ), 'permission_callback' => array( $this, 'get_items_permissions_check' ), - 'args' => array( - 'term' => array( - 'required' => true, - ), - ), - 'schema' => array( $this, 'get_item_schema' ), + 'args' => $this->get_collection_params(), + 'schema' => array( $this, 'get_public_item_schema' ), ) ); @@ -49,14 +45,13 @@ public function register_routes() { '/' . $this->rest_base . '/install', array( 'methods' => WP_REST_Server::CREATABLE, - 'callback' => array( $this, 'install_block' ), - 'permission_callback' => array( $this, 'install_items_permissions_check' ), + 'callback' => array( $this, 'create_item' ), + 'permission_callback' => array( $this, 'create_item_permissions_check' ), 'args' => array( 'slug' => array( 'required' => true, ), ), - 'schema' => array( $this, 'get_item_schema' ), ) ); @@ -65,14 +60,13 @@ public function register_routes() { '/' . $this->rest_base . '/uninstall', array( 'methods' => WP_REST_Server::DELETABLE, - 'callback' => array( $this, 'uninstall_block' ), - 'permission_callback' => array( $this, 'delete_items_permissions_check' ), + 'callback' => array( $this, 'delete_item' ), + 'permission_callback' => array( $this, 'delete_item_permissions_check' ), 'args' => array( 'slug' => array( 'required' => true, ), ), - 'schema' => array( $this, 'get_item_schema' ), ) ); } @@ -80,13 +74,12 @@ public function register_routes() { /** * Checks whether a given request has permission to install and activate plugins. * - * @since 6.5.0 + * @since 5.5.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_Error|bool True if the request has permission, WP_Error object otherwise. - * phpcs:disable VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable */ - public function get_items_permissions_check( $request ) { + public function get_items_permissions_check( $request ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable if ( ! current_user_can( 'install_plugins' ) || ! current_user_can( 'activate_plugins' ) ) { return new WP_Error( 'rest_user_cannot_view', @@ -96,53 +89,61 @@ public function get_items_permissions_check( $request ) { return true; } - /* phpcs:enable */ /** - * Checks whether a given request has permission to install and activate plugins. + * Search and retrieve blocks metadata * - * @since 6.5.0 + * @since 5.5.0 * * @param WP_REST_Request $request Full details about the request. - * @return WP_Error|bool True if the request has permission, WP_Error object otherwise. + * @return WP_Error|WP_REST_Response Response object on success, or WP_Error object on failure. */ - public function install_items_permissions_check( $request ) { - $plugin = $request->get_param( 'slug' ); - - if ( - ! current_user_can( 'install_plugins' ) || - ! current_user_can( 'activate_plugins' ) || - ! current_user_can( 'activate_plugin', $plugin ) - ) { - return new WP_Error( - 'rest_user_cannot_view', - __( 'Sorry, you are not allowed to install blocks.', 'gutenberg' ), - array( 'status' => rest_authorization_required_code() ) - ); + public function get_items( $request ) { + require_once ABSPATH . 'wp-admin/includes/plugin-install.php'; + require_once ABSPATH . 'wp-admin/includes/plugin.php'; + + $response = plugins_api( + 'query_plugins', + array( + 'block' => $request['term'], + 'per_page' => $request['per_page'], + 'page' => $request['page'], + ) + ); + + if ( is_wp_error( $response ) ) { + $response->add_data( array( 'status' => 500 ) ); + + return $response; } - return true; + $result = array(); + + foreach ( $response->plugins as $plugin ) { + if ( $this->find_plugin_for_slug( $plugin['slug'] ) ) { + continue; + } + + $data = $this->prepare_item_for_response( $plugin, $request ); + $result[] = $this->prepare_response_for_collection( $data ); + } + + return rest_ensure_response( $result ); } /** - * Checks whether a given request has permission to remove/deactivate plugins. + * Checks whether a given request has permission to install and activate plugins. * - * @since 6.5.0 + * @since 5.5.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_Error|bool True if the request has permission, WP_Error object otherwise. */ - public function delete_items_permissions_check( $request ) { - $plugin = $request->get_param( 'slug' ); - - if ( - ! current_user_can( 'delete_plugins' ) || - ! current_user_can( 'deactivate_plugins' ) || - ! current_user_can( 'deactivate_plugin', $plugin ) - ) { + public function create_item_permissions_check( $request ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable + if ( ! current_user_can( 'install_plugins' ) || ! current_user_can( 'activate_plugins' ) ) { return new WP_Error( - 'rest_user_cannot_delete', - __( 'Sorry, you are not allowed to uninstall blocks.', 'gutenberg' ), + 'rest_user_cannot_view', + __( 'Sorry, you are not allowed to install blocks.', 'gutenberg' ), array( 'status' => rest_authorization_required_code() ) ); } @@ -153,93 +154,53 @@ public function delete_items_permissions_check( $request ) { /** * Installs and activates a plugin * - * @since 6.5.0 + * @since 5.5.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_Error|WP_REST_Response Response object on success, or WP_Error object on failure. */ - public function install_block( $request ) { - - include_once( ABSPATH . 'wp-admin/includes/file.php' ); - include_once( ABSPATH . 'wp-admin/includes/plugin.php' ); - include_once( ABSPATH . 'wp-admin/includes/class-wp-upgrader.php' ); - include_once( ABSPATH . 'wp-admin/includes/plugin-install.php' ); - - $slug = $request->get_param( 'slug' ); - - // Verify filesystem is accessible first. - $filesystem_available = self::is_filesystem_available(); - if ( is_wp_error( $filesystem_available ) ) { - return $filesystem_available; - } - - $api = plugins_api( - 'plugin_information', + public function create_item( $request ) { + $inner_request = new WP_REST_Request( 'POST', '/__experimental/plugins' ); + $inner_request->set_body_params( array( - 'slug' => $slug, - 'fields' => array( - 'sections' => false, - ), + 'slug' => $request['slug'], + 'activate' => true, ) ); - if ( is_wp_error( $api ) ) { - $api->add_data( array( 'status' => 500 ) ); - return $api; - } - - $skin = new WP_Ajax_Upgrader_Skin(); - $upgrader = new Plugin_Upgrader( $skin ); - - $result = $upgrader->install( $api->download_link ); - - if ( is_wp_error( $result ) ) { - return $result; - } - - // This should be the same as $result above. - if ( is_wp_error( $skin->result ) ) { - return $skin->result; - } - - if ( $skin->get_errors()->has_errors() ) { - return $skin->get_errors(); - } + return rest_do_request( $inner_request ); + } - if ( is_null( $result ) ) { - global $wp_filesystem; - // Pass through the error from WP_Filesystem if one was raised. - if ( $wp_filesystem instanceof WP_Filesystem_Base && is_wp_error( $wp_filesystem->errors ) && $wp_filesystem->errors->has_errors() ) { - return new WP_Error( 'unable_to_connect_to_filesystem', esc_html( $wp_filesystem->errors->get_error_message() ), array( 'status' => 500 ) ); - } - return new WP_Error( 'unable_to_connect_to_filesystem', __( 'Unable to connect to the filesystem. Please confirm your credentials.', 'gutenberg' ), array( 'status' => 500 ) ); + /** + * Checks whether a given request has permission to remove/deactivate plugins. + * + * @since 5.5.0 + * + * @param WP_REST_Request $request Full details about the request. + * @return WP_Error|bool True if the request has permission, WP_Error object otherwise. + */ + public function delete_item_permissions_check( $request ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable + if ( ! current_user_can( 'delete_plugins' ) || ! current_user_can( 'deactivate_plugins' ) ) { + return new WP_Error( + 'rest_user_cannot_delete', + __( 'Sorry, you are not allowed to uninstall blocks.', 'gutenberg' ), + array( 'status' => rest_authorization_required_code() ) + ); } - // Find the plugin to activate it. - $plugin_files = get_plugins( '/' . $slug ); - $plugin_files = array_keys( $plugin_files ); - - $plugin_file = $slug . '/' . reset( $plugin_files ); - - activate_plugin( $plugin_file ); - - return rest_ensure_response( array( 'success' => true ) ); + return true; } /** * Deactivates and deletes a plugin * - * @since 6.5.0 + * @since 5.5.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_Error|WP_REST_Response Response object on success, or WP_Error object on failure. */ - public function uninstall_block( $request ) { - - include_once( ABSPATH . 'wp-admin/includes/file.php' ); - include_once( ABSPATH . 'wp-admin/includes/plugin.php' ); - include_once( ABSPATH . 'wp-admin/includes/class-wp-upgrader.php' ); - include_once( ABSPATH . 'wp-admin/includes/plugin-install.php' ); + public function delete_item( $request ) { + require_once ABSPATH . 'wp-admin/includes/plugin.php'; $slug = trim( $request->get_param( 'slug' ) ); @@ -247,149 +208,117 @@ public function uninstall_block( $request ) { return new WP_Error( 'slug_not_provided', 'Valid slug not provided.', array( 'status' => 400 ) ); } - // Verify filesystem is accessible first. - $filesystem_available = self::is_filesystem_available(); - if ( is_wp_error( $filesystem_available ) ) { - return $filesystem_available; - } + $plugin_file = $this->find_plugin_for_slug( $slug ); - $plugin_files = get_plugins( '/' . $slug ); - - if ( ! $plugin_files ) { + if ( ! $plugin_file ) { return new WP_Error( 'block_not_found', 'Valid slug not provided.', array( 'status' => 400 ) ); } - $plugin_files = array_keys( $plugin_files ); - $plugin_file = $slug . '/' . reset( $plugin_files ); - - deactivate_plugins( $plugin_file ); + $route = '/__experimental/plugins/' . substr( $plugin_file, 0, - 4 ); + $deactivate = new WP_REST_Request( 'PUT', $route ); + $deactivate->set_body_params( array( 'status' => 'inactive' ) ); - $delete_result = delete_plugins( array( $plugin_file ) ); + $deactivated = rest_do_request( $deactivate ); - if ( is_wp_error( $delete_result ) ) { - return $delete_result; + if ( $deactivated->is_error() ) { + return $deactivated->as_error(); } - return rest_ensure_response( true ); + return rest_do_request( new WP_REST_Request( 'DELETE', $route ) ); } /** - * Search and retrieve blocks metadata + * Parse block metadata for a block, and prepare it for an API repsonse. * - * @since 6.5.0 + * @since 5.5.0 * - * @param WP_REST_Request $request Full details about the request. + * @param array $plugin The plugin metadata. + * @param WP_REST_Request $request Request object. * @return WP_Error|WP_REST_Response Response object on success, or WP_Error object on failure. */ - public function get_items( $request ) { - - $search_string = trim( $request->get_param( 'term' ) ); - - if ( empty( $search_string ) ) { - return rest_ensure_response( array() ); - } - - require_once ABSPATH . 'wp-admin/includes/plugin-install.php'; - require_once ABSPATH . 'wp-admin/includes/plugin.php'; + public function prepare_item_for_response( $plugin, $request ) { + // There might be multiple blocks in a plugin. Only the first block is mapped. + $block_data = reset( $plugin['blocks'] ); - $response = plugins_api( - 'query_plugins', - array( - 'block' => $search_string, - 'per_page' => 3, - ) + // A data array containing the properties we'll return. + $block = array( + 'name' => $block_data['name'], + 'title' => ( $block_data['title'] ? $block_data['title'] : $plugin['name'] ), + 'description' => wp_trim_words( $plugin['description'], 30, '...' ), + 'id' => $plugin['slug'], + 'rating' => $plugin['rating'] / 20, + 'rating_count' => intval( $plugin['num_ratings'] ), + 'active_installs' => intval( $plugin['active_installs'] ), + 'author_block_rating' => $plugin['author_block_rating'] / 20, + 'author_block_count' => intval( $plugin['author_block_count'] ), + 'author' => wp_strip_all_tags( $plugin['author'] ), + 'icon' => ( isset( $plugin['icons']['1x'] ) ? $plugin['icons']['1x'] : 'block-default' ), + 'assets' => array(), + 'humanized_updated' => sprintf( + /* translators: %s: Human-readable time difference. */ + __( '%s ago', 'gutenberg' ), + human_time_diff( strtotime( $plugin['last_updated'] ), current_time( 'timestamp' ) ) + ), ); - if ( is_wp_error( $response ) ) { - $response->add_data( array( 'status' => 500 ) ); - return $response; + foreach ( $plugin['block_assets'] as $asset ) { + // TODO: Return from API, not client-set. + $block['assets'][] = 'https://plugins.svn.wordpress.org/' . $plugin['slug'] . $asset; } - $result = array(); - - foreach ( $response->plugins as $plugin ) { - $installed_plugins = get_plugins( '/' . $plugin['slug'] ); + $this->add_additional_fields_to_object( $block, $request ); - // Only show uninstalled blocks. - if ( empty( $installed_plugins ) ) { - $data = $this->prepare_item_for_response( $plugin, $request ); - $result[] = $this->prepare_response_for_collection( $data ); - } - } + $response = new WP_REST_Response( $block ); + $response->add_links( $this->prepare_links( $plugin ) ); - return rest_ensure_response( $result ); + return $response; } /** - * Determine if the endpoints are available. + * Generates a list of links to include in the response for the plugin. * - * Only the 'Direct' filesystem transport, and SSH/FTP when credentials are stored are supported at present. + * @since 5.5.0 * - * @since 6.5.0 + * @param array $plugin * - * @return bool|WP_Error True if filesystem is available, WP_Error otherwise. + * @return array */ - private static function is_filesystem_available() { - $filesystem_method = get_filesystem_method(); - - if ( 'direct' === $filesystem_method ) { - return true; - } + protected function prepare_links( $plugin ) { + $links = array(); - ob_start(); - $filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() ); - ob_end_clean(); + $plugin_file = $this->find_plugin_for_slug( $plugin['slug'] ); - if ( $filesystem_credentials_are_stored ) { - return true; + if ( $plugin_file ) { + $links['https://api.w.org/plugin'] = array( + 'href' => rest_url( '__experimental/plugins/' . substr( $plugin_file, 0, - 4 ) ), + 'embeddable' => true, + ); } - return new WP_Error( 'fs_unavailable', __( 'The filesystem is currently unavailable for installing blocks.' ) ); + return $links; } /** - * Parse block metadata for a block, and prepare it for an API repsonse. + * Finds an installed plugin for the given slug. * - * @since 6.5.0 + * @since 5.5.0 * - * @param WP_Object $plugin The plugin metadata. - * @param WP_REST_Request $request Request object. - * @return WP_Error|WP_REST_Response Response object on success, or WP_Error object on failure. + * @param string $slug The WordPress.org directory slug for a plugin. + * + * @return string The plugin file found matching it. */ - public function prepare_item_for_response( $plugin, $request ) { - - // There might be multiple blocks in a plugin. Only the first block is mapped. - $block_data = reset( $plugin['blocks'] ); + protected function find_plugin_for_slug( $slug ) { + require_once ABSPATH . 'wp-admin/includes/plugin.php'; - // A data array containing the properties we'll return. - $block = array( - 'name' => $block_data['name'], - 'title' => ( $block_data['title'] ? $block_data['title'] : $plugin['name'] ), - 'description' => wp_trim_words( $plugin['description'], 30, '...' ), - 'id' => $plugin['slug'], - 'rating' => $plugin['rating'] / 20, - 'rating_count' => intval( $plugin['num_ratings'] ), - 'active_installs' => intval( $plugin['active_installs'] ), - 'author_block_rating' => $plugin['author_block_rating'] / 20, - 'author_block_count' => intval( $plugin['author_block_count'] ), - 'author' => wp_strip_all_tags( $plugin['author'] ), - 'icon' => ( isset( $plugin['icons']['1x'] ) ? $plugin['icons']['1x'] : 'block-default' ), - 'assets' => array(), - 'humanized_updated' => sprintf( - /* translators: %s: Human-readable time difference. */ - __( '%s ago' ), - human_time_diff( strtotime( $plugin['last_updated'] ), current_time( 'timestamp' ) ) - ), - ); + $plugin_files = get_plugins( '/' . $slug ); - foreach ( $plugin['block_assets'] as $asset ) { - // TODO: Return from API, not client-set. - $block[ 'assets' ][] = 'https://plugins.svn.wordpress.org/' . $plugin['slug'] . $asset; + if ( ! $plugin_files ) { + return ''; } - $response = new WP_REST_Response( $block ); + $plugin_files = array_keys( $plugin_files ); - return $response; + return $slug . '/' . reset( $plugin_files ); } /** @@ -400,80 +329,84 @@ public function prepare_item_for_response( $plugin, $request ) { * @return array Item schema data. */ public function get_item_schema() { + if ( $this->schema ) { + return $this->add_additional_fields_schema( $this->schema ); + } + $this->schema = array( '$schema' => 'http://json-schema.org/draft-04/schema#', 'title' => 'block-directory-item', 'type' => 'object', 'properties' => array( 'name' => array( - 'description' => __( "The block name, in namespace/block-name format." ), - 'type' => 'string', - 'context' => array( 'view' ), + 'description' => __( 'The block name, in namespace/block-name format.', 'gutenberg' ), + 'type' => 'string', + 'context' => array( 'view' ), ), 'title' => array( - 'description' => __( "The block title, in human readable format." ), - 'type' => 'string', - 'context' => array( 'view' ), + 'description' => __( 'The block title, in human readable format.', 'gutenberg' ), + 'type' => 'string', + 'context' => array( 'view' ), ), 'description' => array( - 'description' => __( "A short description of the block, in human readable format." ), - 'type' => 'string', - 'context' => array( 'view' ), + 'description' => __( 'A short description of the block, in human readable format.', 'gutenberg' ), + 'type' => 'string', + 'context' => array( 'view' ), ), 'id' => array( - 'description' => __( "The block slug." ), - 'type' => 'string', - 'context' => array( 'view' ), + 'description' => __( 'The block slug.', 'gutenberg' ), + 'type' => 'string', + 'context' => array( 'view' ), ), 'rating' => array( - 'description' => __( "The star rating of the block." ), - 'type' => 'integer', - 'context' => array( 'view' ), + 'description' => __( 'The star rating of the block.', 'gutenberg' ), + 'type' => 'integer', + 'context' => array( 'view' ), ), 'rating_count' => array( - 'description' => __( "The number of ratings." ), - 'type' => 'integer', - 'context' => array( 'view' ), + 'description' => __( 'The number of ratings.', 'gutenberg' ), + 'type' => 'integer', + 'context' => array( 'view' ), ), 'active_installs' => array( - 'description' => __( "The number sites that have activated this block." ), - 'type' => 'string', - 'context' => array( 'view' ), + 'description' => __( 'The number sites that have activated this block.', 'gutenberg' ), + 'type' => 'string', + 'context' => array( 'view' ), ), 'author_block_rating' => array( - 'description' => __( "The average rating of blocks published by the same author." ), - 'type' => 'integer', - 'context' => array( 'view' ), + 'description' => __( 'The average rating of blocks published by the same author.', 'gutenberg' ), + 'type' => 'integer', + 'context' => array( 'view' ), ), 'author_block_count' => array( - 'description' => __( "The number of blocks published by the same author." ), - 'type' => 'integer', - 'context' => array( 'view' ), + 'description' => __( 'The number of blocks published by the same author.', 'gutenberg' ), + 'type' => 'integer', + 'context' => array( 'view' ), ), 'author' => array( - 'description' => __( "The WordPress.org username of the block author." ), - 'type' => 'string', - 'context' => array( 'view' ), + 'description' => __( 'The WordPress.org username of the block author.', 'gutenberg' ), + 'type' => 'string', + 'context' => array( 'view' ), ), - 'icon' => array( - 'description' => __( "The block icon." ), - 'type' => 'string', - 'format' => 'uri', - 'context' => array( 'view' ), + 'icon' => array( + 'description' => __( 'The block icon.', 'gutenberg' ), + 'type' => 'string', + 'format' => 'uri', + 'context' => array( 'view' ), ), 'humanized_updated' => array( - 'description' => __( "The date when the block was last updated, in fuzzy human readable format." ), - 'type' => 'string', - 'context' => array( 'view' ), + 'description' => __( 'The date when the block was last updated, in fuzzy human readable format.', 'gutenberg' ), + 'type' => 'string', + 'context' => array( 'view' ), ), 'assets' => array( - 'description' => __( 'An object representing the block CSS and JavaScript assets.' ), - 'type' => 'array', - 'context' => array( 'view' ), - 'readonly' => true, - 'items' => array( - 'type' => 'string', - 'format' => 'uri', + 'description' => __( 'An object representing the block CSS and JavaScript assets.', 'gutenberg' ), + 'type' => 'array', + 'context' => array( 'view' ), + 'readonly' => true, + 'items' => array( + 'type' => 'string', + 'format' => 'uri', ), ), @@ -481,10 +414,9 @@ public function get_item_schema() { ), ); - return $this->schema; + return $this->add_additional_fields_schema( $this->schema ); } - /** * Retrieves the search params for the blocks collection. * @@ -495,23 +427,27 @@ public function get_item_schema() { public function get_collection_params() { $query_params = parent::get_collection_params(); + $query_params['per_page']['default'] = 3; + $query_params['term'] = array( - 'description' => __( 'Limit result set to blocks matching the search term.' ), - 'type' => 'array', - 'term' => array( + 'description' => __( 'Limit result set to blocks matching the search term.', 'gutenberg' ), + 'type' => 'array', + 'term' => array( 'type' => 'string', ), - 'required' => true, + 'required' => true, + 'minLength' => 1, ); + unset( $query_params['search'] ); + /** * Filter collection parameters for the block directory controller. * - * @since 5.0.0 + * @since 5.5.0 * * @param array $query_params JSON Schema-formatted collection parameters. */ return apply_filters( 'rest_block_directory_collection_params', $query_params ); } - } From 1af90c55836d2fe7441c7c412d7f6ce75ab68386 Mon Sep 17 00:00:00 2001 From: Timothy Jacobs Date: Wed, 20 May 2020 23:03:43 -0400 Subject: [PATCH 07/25] Fix permission check for activating a plugin on install. Add more links. --- lib/class-wp-rest-block-directory-controller.php | 6 +++++- lib/class-wp-rest-plugins-controller.php | 15 +++++++++++---- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/lib/class-wp-rest-block-directory-controller.php b/lib/class-wp-rest-block-directory-controller.php index 270cad894af2d4..7c727030a79aef 100644 --- a/lib/class-wp-rest-block-directory-controller.php +++ b/lib/class-wp-rest-block-directory-controller.php @@ -284,7 +284,11 @@ public function prepare_item_for_response( $plugin, $request ) { * @return array */ protected function prepare_links( $plugin ) { - $links = array(); + $links = array( + 'https://api.w.org/install-plugin' => array( + 'href' => add_query_arg( 'slug', urlencode( $plugin['slug'] ), rest_url( '__experimental/plugins' ) ), + ), + ); $plugin_file = $this->find_plugin_for_slug( $plugin['slug'] ); diff --git a/lib/class-wp-rest-plugins-controller.php b/lib/class-wp-rest-plugins-controller.php index 83177695e9ccc0..b8a9738ea08d18 100644 --- a/lib/class-wp-rest-plugins-controller.php +++ b/lib/class-wp-rest-plugins-controller.php @@ -241,10 +241,7 @@ public function create_item_permissions_check( $request ) { ); } - if ( - $request['activate'] && - ( ! current_user_can( 'activate_plugins' ) || ! current_user_can( 'activate_plugin', $request['slug'] ) ) - ) { + if ( $request['activate'] && ! current_user_can( 'activate_plugins' ) ) { return new WP_Error( 'rest_cannot_activate_plugin', __( 'Sorry, you are not allowed to activate this plugin.', 'gutenberg' ), @@ -330,6 +327,16 @@ public function create_item( $request ) { $file = $upgrader->plugin_info(); if ( $request['activate'] ) { + if ( ! current_user_can( 'activate_plugin', $file ) ) { + return new WP_Error( + 'rest_cannot_activate_plugin', + __( 'Sorry, you are not allowed to activate this plugin. The plugin has been installed.', 'gutenberg' ), + array( + 'status' => rest_authorization_required_code(), + ) + ); + } + $activated = activate_plugin( $file ); if ( is_wp_error( $activated ) ) { From 1cca9d242840b07fe7c2055390730f3140b45724 Mon Sep 17 00:00:00 2001 From: Timothy Jacobs Date: Sat, 23 May 2020 15:15:58 -0400 Subject: [PATCH 08/25] Check if the block plugin is already installed. Applies 562e84e to the refactored block directory controller. --- lib/class-wp-rest-block-directory-controller.php | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/lib/class-wp-rest-block-directory-controller.php b/lib/class-wp-rest-block-directory-controller.php index 7c727030a79aef..88ae7d3e4d5b69 100644 --- a/lib/class-wp-rest-block-directory-controller.php +++ b/lib/class-wp-rest-block-directory-controller.php @@ -160,6 +160,17 @@ public function create_item_permissions_check( $request ) { // phpcs:ignore Vari * @return WP_Error|WP_REST_Response Response object on success, or WP_Error object on failure. */ public function create_item( $request ) { + require_once ABSPATH . 'wp-admin/includes/plugin.php'; + + $existing = $this->find_plugin_for_slug( $request['slug'] ); + + if ( $existing ) { + $activate = new WP_REST_Request( 'PUT', '/__experimental/plugins/' . substr( $existing, 0, - 4 ) ); + $activate->set_body_params( array( 'status' => 'active' ) ); + + return rest_do_request( $activate ); + } + $inner_request = new WP_REST_Request( 'POST', '/__experimental/plugins' ); $inner_request->set_body_params( array( From 269253c26bfb0437af2fbd0f79804fe7f7792fc5 Mon Sep 17 00:00:00 2001 From: Timothy Jacobs Date: Sat, 23 May 2020 15:41:23 -0400 Subject: [PATCH 09/25] Skip tests on fs errors. --- ...ass-wp-rest-block-directory-controller.php | 5 +- ...p-rest-block-directory-controller-test.php | 150 +++++++++--------- .../class-wp-rest-plugins-controller-test.php | 32 +++- 3 files changed, 108 insertions(+), 79 deletions(-) diff --git a/lib/class-wp-rest-block-directory-controller.php b/lib/class-wp-rest-block-directory-controller.php index 88ae7d3e4d5b69..f92ee8a48c7c6b 100644 --- a/lib/class-wp-rest-block-directory-controller.php +++ b/lib/class-wp-rest-block-directory-controller.php @@ -265,10 +265,11 @@ public function prepare_item_for_response( $plugin, $request ) { 'author' => wp_strip_all_tags( $plugin['author'] ), 'icon' => ( isset( $plugin['icons']['1x'] ) ? $plugin['icons']['1x'] : 'block-default' ), 'assets' => array(), + 'last_updated' => $plugin['last_updated'], 'humanized_updated' => sprintf( /* translators: %s: Human-readable time difference. */ __( '%s ago', 'gutenberg' ), - human_time_diff( strtotime( $plugin['last_updated'] ), current_time( 'timestamp' ) ) + human_time_diff( strtotime( $plugin['last_updated'] ) ) ), ); @@ -290,7 +291,7 @@ public function prepare_item_for_response( $plugin, $request ) { * * @since 5.5.0 * - * @param array $plugin + * @param array $plugin The plugin data from WordPress.org. * * @return array */ diff --git a/phpunit/class-wp-rest-block-directory-controller-test.php b/phpunit/class-wp-rest-block-directory-controller-test.php index 9f4ffd49c9d7ff..2031bb5f3bb0fe 100644 --- a/phpunit/class-wp-rest-block-directory-controller-test.php +++ b/phpunit/class-wp-rest-block-directory-controller-test.php @@ -1,4 +1,5 @@ user->create( + self::$admin_id = $factory->user->create( array( - 'role' => 'administrator', + 'role' => 'administrator', ) ); // Ensure routes are registered regardless of the `gutenberg-block-directory` experimental setting. // This should be removed when `gutenberg_register_rest_block_directory()` is unconditional. - add_filter( 'rest_api_init', function() { + add_filter( 'rest_api_init', function () { $block_directory_controller = new WP_REST_Block_Directory_Controller(); $block_directory_controller->register_routes(); } ); @@ -38,11 +39,11 @@ public function test_register_routes() { /** * Tests that an error is returned if the block plugin slug is not provided */ - function test_should_throw_no_slug_error() { + public function test_should_throw_no_slug_error() { wp_set_current_user( self::$admin_id ); $request = new WP_REST_Request( 'POST', '/__experimental/block-directory/install', [] ); - $result = rest_do_request( $request ); + $result = rest_do_request( $request ); $this->assertErrorResponse( 'rest_missing_callback_param', $result, 400 ); } @@ -50,7 +51,7 @@ function test_should_throw_no_slug_error() { /** * Tests that the search endpoint does not return an error */ - function test_simple_search() { + public function test_simple_search() { wp_set_current_user( self::$admin_id ); $request = new WP_REST_Request( 'GET', '/__experimental/block-directory/search' ); @@ -61,24 +62,10 @@ function test_simple_search() { $this->assertEquals( 200, $result->status ); } - /** - * Simulate a network failure on outbound http requests to a given hostname. - */ - function prevent_requests_to_host( $blocked_host = 'api.wordpress.org' ) { - // apply_filters( 'pre_http_request', false, $parsed_args, $url ); - add_filter( 'pre_http_request', function( $return, $args, $url ) use ( $blocked_host ) { - if ( @parse_url( $url, PHP_URL_HOST ) === $blocked_host ) { - return new WP_Error( 'plugins_api_failed', "An expected error occurred connecting to $blocked_host because of a unit test", "cURL error 7: Failed to connect to $blocked_host port 80: Connection refused" ); - - } - return $return; - }, 10, 3 ); - } - /** * Tests that the search endpoint returns WP_Error when the server is unreachable. */ - function test_search_unreachable() { + public function test_search_unreachable() { wp_set_current_user( self::$admin_id ); $request = new WP_REST_Request( 'GET', '/__experimental/block-directory/search' ); @@ -86,23 +73,7 @@ function test_search_unreachable() { $this->prevent_requests_to_host( 'api.wordpress.org' ); - $this->expectException('PHPUnit_Framework_Error_Warning'); - $response = rest_do_request( $request ); - $this->assertErrorResponse( 'plugins_api_failed', $response, 500 ); - } - - /** - * Tests that the install endpoint returns WP_Error when the server is unreachable. - */ - function test_install_unreachable() { - wp_set_current_user( self::$admin_id ); - - $request = new WP_REST_Request( 'POST', '/__experimental/block-directory/install' ); - $request->set_query_params( array( 'slug' => 'foo' ) ); - - $this->prevent_requests_to_host( 'api.wordpress.org' ); - - $this->expectException('PHPUnit_Framework_Error_Warning'); + $this->expectException( 'PHPUnit_Framework_Error_Warning' ); $response = rest_do_request( $request ); $this->assertErrorResponse( 'plugins_api_failed', $response, 500 ); } @@ -110,8 +81,8 @@ function test_install_unreachable() { /** * Should fail with a permission error if requesting user is not logged in. */ - function test_simple_search_no_perms() { - $request = new WP_REST_Request( 'GET', '/__experimental/block-directory/search' ); + public function test_simple_search_no_perms() { + $request = new WP_REST_Request( 'GET', '/__experimental/block-directory/search' ); $request->set_query_params( array( 'term' => 'foo' ) ); $response = rest_do_request( $request ); $data = $response->get_data(); @@ -122,11 +93,11 @@ function test_simple_search_no_perms() { /** * Make sure a search with the right permissions returns something. */ - function test_simple_search_with_perms() { + public function test_simple_search_with_perms() { wp_set_current_user( self::$admin_id ); // This will hit the live API. We're searching for `block` which should definitely return at least one result. - $request = new WP_REST_Request( 'GET', '/__experimental/block-directory/search' ); + $request = new WP_REST_Request( 'GET', '/__experimental/block-directory/search' ); $request->set_query_params( array( 'term' => 'block' ) ); $response = rest_do_request( $request ); $data = $response->get_data(); @@ -148,10 +119,10 @@ function test_simple_search_with_perms() { /** * A search with zero results should return a 200 response. */ - function test_simple_search_no_results() { + public function test_simple_search_no_results() { wp_set_current_user( self::$admin_id ); - $request = new WP_REST_Request( 'GET', '/__experimental/block-directory/search' ); + $request = new WP_REST_Request( 'GET', '/__experimental/block-directory/search' ); $request->set_query_params( array( 'term' => '0c4549ee68f24eaaed46a49dc983ecde' ) ); $response = rest_do_request( $request ); $data = $response->get_data(); @@ -161,45 +132,18 @@ function test_simple_search_no_results() { $this->assertEquals( array(), $data ); } - /** - * Should fail with a permission error if requesting user is not logged in. - */ - function test_simple_install_no_perms() { - $request = new WP_REST_Request( 'POST', '/__experimental/block-directory/install' ); - $request->set_query_params( array( 'slug' => 'foo' ) ); - $response = rest_do_request( $request ); - $data = $response->get_data(); - - $this->assertEquals( $data['code'], 'rest_user_cannot_view' ); - } - - /** - * Make sure an install with permissions correctly handles an unknown slug. - */ - function test_simple_install_with_perms_bad_slug() { - wp_set_current_user( self::$admin_id ); - - // This will hit the live API. - $request = new WP_REST_Request( 'POST', '/__experimental/block-directory/install' ); - $request->set_query_params( array( 'slug' => 'alex-says-this-block-definitely-doesnt-exist' ) ); - $response = rest_do_request( $request ); - - // Is this an appropriate status? - $this->assertErrorResponse( 'plugins_api_failed', $response, 500 ); - } - /** * Make sure the search schema is available and correct. */ - function test_search_schema() { + public function test_search_schema() { wp_set_current_user( self::$admin_id ); - $request = new WP_REST_Request( 'OPTIONS', '/__experimental/block-directory/search' ); + $request = new WP_REST_Request( 'OPTIONS', '/__experimental/block-directory/search' ); $request->set_query_params( array( 'term' => 'foo' ) ); $response = rest_do_request( $request ); $data = $response->get_data(); - // Check endpoints + // Check endpoints $this->assertEquals( [ 'GET' ], $data['endpoints'][0]['methods'] ); $this->assertEquals( [ 'term' => [ 'required' => true ] ], $data['endpoints'][0]['args'] ); @@ -212,4 +156,62 @@ function test_search_schema() { // TODO: ..etc.. } + public function test_install_item() { + if ( ! defined( 'FS_METHOD' ) ) { + define( 'FS_METHOD', 'direct' ); + } + + if ( isset( get_plugins()['hello-dolly/hello.php'] ) ) { + delete_plugins( array( 'hello-dolly/hello.php' ) ); + } + + wp_set_current_user( self::$admin_id ); + + $request = new WP_REST_Request( 'POST', '/__experimental/block-directory/install' ); + $request->set_body_params( array( 'slug' => 'hello-dolly' ) ); + + $response = rest_do_request( $request ); + $this->skip_on_filesystem_error( $response ); + $this->assertNotWPError( $response->as_error() ); + $this->assertEquals( 201, $response->get_status() ); + $this->assertEquals( 'Hello Dolly', $response->get_data()['name'] ); + } + + /** + * Skips the test if the response is an error due to the filesystem being unavailable. + * + * @since 5.5.0 + * + * @param WP_REST_Response $response The response object to inspect. + */ + protected function skip_on_filesystem_error( WP_REST_Response $response ) { + if ( ! $response->is_error() ) { + return; + } + + if ( 'fs_unavailable' === $response->as_error()->get_error_code() ) { + $this->markTestSkipped( 'Filesystem is unavailable.' ); + } + } + + /** + * Simulate a network failure on outbound http requests to a given hostname. + * + * @param string $blocked_host The host to block connections to. + */ + private function prevent_requests_to_host( $blocked_host = 'api.wordpress.org' ) { + add_filter( + 'pre_http_request', + static function ( $return, $args, $url ) use ( $blocked_host ) { + if ( @parse_url( $url, PHP_URL_HOST ) === $blocked_host ) { + return new WP_Error( 'plugins_api_failed', "An expected error occurred connecting to $blocked_host because of a unit test", "cURL error 7: Failed to connect to $blocked_host port 80: Connection refused" ); + + } + + return $return; + }, + 10, + 3 + ); + } } diff --git a/phpunit/class-wp-rest-plugins-controller-test.php b/phpunit/class-wp-rest-plugins-controller-test.php index c40752377f5094..47f9e69b55e69f 100644 --- a/phpunit/class-wp-rest-plugins-controller-test.php +++ b/phpunit/class-wp-rest-plugins-controller-test.php @@ -151,14 +151,13 @@ public function test_create_item() { delete_plugins( array( 'hello-dolly/hello.php' ) ); } - $this->assertEquals( 'direct', get_filesystem_method() ); - wp_set_current_user( self::$administrator_id ); $request = new WP_REST_Request( 'POST', self::BASE ); $request->set_body_params( array( 'slug' => 'hello-dolly' ) ); $response = rest_do_request( $request ); + $this->skip_on_filesystem_error( $response ); $this->assertNotWPError( $response->as_error() ); $this->assertEquals( 201, $response->get_status() ); $this->assertEquals( 'Hello Dolly', $response->get_data()['name'] ); @@ -191,6 +190,7 @@ public function test_create_item_wdotorg_unreachable() { $this->expectException( 'PHPUnit_Framework_Error_Warning' ); $response = rest_do_request( $request ); + $this->skip_on_filesystem_error( $response ); $this->assertErrorResponse( 'plugins_api_failed', $response, 500 ); } @@ -202,6 +202,7 @@ public function test_create_item_unknown_plugin() { $request->set_body_params( array( 'slug' => 'alex-says-this-block-definitely-doesnt-exist' ) ); $response = rest_do_request( $request ); + $this->skip_on_filesystem_error( $response ); // Is this an appropriate status? $this->assertErrorResponse( 'plugins_api_failed', $response, 404 ); } @@ -268,6 +269,7 @@ public function test_delete_item() { $request = new WP_REST_Request( 'DELETE', self::BASE . '/' . self::PLUGIN ); $response = rest_do_request( $request ); + $this->skip_on_filesystem_error( $response ); $this->assertNotWPError( $response->as_error() ); $this->assertEquals( 204, $response->get_status() ); $this->assertFileNotExists( WP_PLUGIN_DIR . '/' . self::PLUGIN_FILE ); @@ -343,6 +345,23 @@ protected function check_get_plugin_data( $data ) { $this->assertEquals( '5.4.0', $data['requires_wp'] ); } + /** + * Skips the test if the response is an error due to the filesystem being unavailable. + * + * @since 5.5.0 + * + * @param WP_REST_Response $response The response object to inspect. + */ + protected function skip_on_filesystem_error( WP_REST_Response $response ) { + if ( ! $response->is_error() ) { + return; + } + + if ( 'fs_unavailable' === $response->as_error()->get_error_code() ) { + $this->markTestSkipped( 'Filesystem is unavailable.' ); + } + } + /** * Creates a test plugin. * @@ -362,12 +381,19 @@ private function create_test_plugin() { * Requires at least: 5.4.0 */ PHP; - $this->assertTrue( wp_mkdir_p( WP_PLUGIN_DIR . '/test-plugin' ) ); + $created = wp_mkdir_p( WP_PLUGIN_DIR . '/test-plugin' ); + + if ( false === $created ) { + $this->markTestAsSkipped(); + } + file_put_contents( WP_PLUGIN_DIR . '/test-plugin/test-plugin.php', $php ); } /** * Simulate a network failure on outbound http requests to a given hostname. + * + * @param string $blocked_host The host to block connections to. */ private function prevent_requests_to_host( $blocked_host = 'api.wordpress.org' ) { add_filter( From 3ee82a05928fb2938afdc16d0e52ce00ede054e3 Mon Sep 17 00:00:00 2001 From: Timothy Jacobs Date: Sat, 23 May 2020 15:49:33 -0400 Subject: [PATCH 10/25] Fix PHPCS --- phpunit/class-wp-rest-plugins-controller-test.php | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/phpunit/class-wp-rest-plugins-controller-test.php b/phpunit/class-wp-rest-plugins-controller-test.php index 47f9e69b55e69f..0520e4ded4c537 100644 --- a/phpunit/class-wp-rest-plugins-controller-test.php +++ b/phpunit/class-wp-rest-plugins-controller-test.php @@ -381,9 +381,7 @@ private function create_test_plugin() { * Requires at least: 5.4.0 */ PHP; - $created = wp_mkdir_p( WP_PLUGIN_DIR . '/test-plugin' ); - - if ( false === $created ) { + if ( false === wp_mkdir_p( WP_PLUGIN_DIR . '/test-plugin' ) ) { $this->markTestAsSkipped(); } From 5999ff1800501eb6ea7e16a3cca21ceae2b92f39 Mon Sep 17 00:00:00 2001 From: Timothy Jacobs Date: Sat, 23 May 2020 17:35:12 -0400 Subject: [PATCH 11/25] Refactors directory tests to use the controller base class. This also enables experiments in the phpunit bootstrap. --- ...ass-wp-rest-block-directory-controller.php | 37 ++-- lib/load.php | 2 +- lib/rest-api.php | 4 + phpunit/bootstrap.php | 7 + ...p-rest-block-directory-controller-test.php | 165 +++++++++--------- .../class-wp-rest-plugins-controller-test.php | 6 +- 6 files changed, 117 insertions(+), 104 deletions(-) diff --git a/lib/class-wp-rest-block-directory-controller.php b/lib/class-wp-rest-block-directory-controller.php index f92ee8a48c7c6b..27f893676bce8f 100644 --- a/lib/class-wp-rest-block-directory-controller.php +++ b/lib/class-wp-rest-block-directory-controller.php @@ -3,8 +3,8 @@ * Start: Include for phase 2 * Block Directory REST API: WP_REST_Block_Directory_Controller class * - * @package gutenberg * @since 5.5.0 + * @package gutenberg */ /** @@ -32,11 +32,13 @@ public function register_routes() { $this->namespace, '/' . $this->rest_base . '/search', array( - 'methods' => WP_REST_Server::READABLE, - 'callback' => array( $this, 'get_items' ), - 'permission_callback' => array( $this, 'get_items_permissions_check' ), - 'args' => $this->get_collection_params(), - 'schema' => array( $this, 'get_public_item_schema' ), + array( + 'methods' => WP_REST_Server::READABLE, + 'callback' => array( $this, 'get_items' ), + 'permission_callback' => array( $this, 'get_items_permissions_check' ), + 'args' => $this->get_collection_params(), + ), + 'schema' => array( $this, 'get_public_item_schema' ), ) ); @@ -77,13 +79,14 @@ public function register_routes() { * @since 5.5.0 * * @param WP_REST_Request $request Full details about the request. + * * @return WP_Error|bool True if the request has permission, WP_Error object otherwise. */ public function get_items_permissions_check( $request ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable if ( ! current_user_can( 'install_plugins' ) || ! current_user_can( 'activate_plugins' ) ) { return new WP_Error( - 'rest_user_cannot_view', - __( 'Sorry, you are not allowed to install blocks.', 'gutenberg' ) + 'rest_block_directory_cannot_view', + __( 'Sorry, you are not allowed to browse the block directory.', 'gutenberg' ) ); } @@ -96,6 +99,7 @@ public function get_items_permissions_check( $request ) { // phpcs:ignore Variab * @since 5.5.0 * * @param WP_REST_Request $request Full details about the request. + * * @return WP_Error|WP_REST_Response Response object on success, or WP_Error object on failure. */ public function get_items( $request ) { @@ -137,12 +141,13 @@ public function get_items( $request ) { * @since 5.5.0 * * @param WP_REST_Request $request Full details about the request. + * * @return WP_Error|bool True if the request has permission, WP_Error object otherwise. */ public function create_item_permissions_check( $request ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable if ( ! current_user_can( 'install_plugins' ) || ! current_user_can( 'activate_plugins' ) ) { return new WP_Error( - 'rest_user_cannot_view', + 'rest_block_directory_cannot_create', __( 'Sorry, you are not allowed to install blocks.', 'gutenberg' ), array( 'status' => rest_authorization_required_code() ) ); @@ -157,6 +162,7 @@ public function create_item_permissions_check( $request ) { // phpcs:ignore Vari * @since 5.5.0 * * @param WP_REST_Request $request Full details about the request. + * * @return WP_Error|WP_REST_Response Response object on success, or WP_Error object on failure. */ public function create_item( $request ) { @@ -188,12 +194,13 @@ public function create_item( $request ) { * @since 5.5.0 * * @param WP_REST_Request $request Full details about the request. + * * @return WP_Error|bool True if the request has permission, WP_Error object otherwise. */ public function delete_item_permissions_check( $request ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable if ( ! current_user_can( 'delete_plugins' ) || ! current_user_can( 'deactivate_plugins' ) ) { return new WP_Error( - 'rest_user_cannot_delete', + 'rest_block_directory_cannot_delete', __( 'Sorry, you are not allowed to uninstall blocks.', 'gutenberg' ), array( 'status' => rest_authorization_required_code() ) ); @@ -208,6 +215,7 @@ public function delete_item_permissions_check( $request ) { // phpcs:ignore Vari * @since 5.5.0 * * @param WP_REST_Request $request Full details about the request. + * * @return WP_Error|WP_REST_Response Response object on success, or WP_Error object on failure. */ public function delete_item( $request ) { @@ -245,6 +253,7 @@ public function delete_item( $request ) { * * @param array $plugin The plugin metadata. * @param WP_REST_Request $request Request object. + * * @return WP_Error|WP_REST_Response Response object on success, or WP_Error object on failure. */ public function prepare_item_for_response( $plugin, $request ) { @@ -267,7 +276,7 @@ public function prepare_item_for_response( $plugin, $request ) { 'assets' => array(), 'last_updated' => $plugin['last_updated'], 'humanized_updated' => sprintf( - /* translators: %s: Human-readable time difference. */ + /* translators: %s: Human-readable time difference. */ __( '%s ago', 'gutenberg' ), human_time_diff( strtotime( $plugin['last_updated'] ) ) ), @@ -443,14 +452,12 @@ public function get_item_schema() { public function get_collection_params() { $query_params = parent::get_collection_params(); + $query_params['context']['default'] = 'view'; $query_params['per_page']['default'] = 3; $query_params['term'] = array( 'description' => __( 'Limit result set to blocks matching the search term.', 'gutenberg' ), - 'type' => 'array', - 'term' => array( - 'type' => 'string', - ), + 'type' => 'string', 'required' => true, 'minLength' => 1, ); diff --git a/lib/load.php b/lib/load.php index 5c0254b1b0e836..3e908e727afe1b 100644 --- a/lib/load.php +++ b/lib/load.php @@ -57,7 +57,7 @@ function gutenberg_is_experiment_enabled( $name ) { if ( ! class_exists( 'WP_REST_Image_Editor_Controller' ) ) { require dirname( __FILE__ ) . '/class-wp-rest-image-editor-controller.php'; } - if ( ! class_exists( 'WP_REST_Pluins_Controller' ) ) { + if ( ! class_exists( 'WP_REST_Plugins_Controller' ) ) { require_once dirname( __FILE__ ) . '/class-wp-rest-plugins-controller.php'; } /** diff --git a/lib/rest-api.php b/lib/rest-api.php index 75c3573e8725cd..0f05798de87d01 100644 --- a/lib/rest-api.php +++ b/lib/rest-api.php @@ -159,6 +159,10 @@ function gutenberg_register_rest_customizer_nonces() { * Registers the Plugins REST API routes. */ function gutenberg_register_plugins_endpoint() { + if ( ! gutenberg_is_experiment_enabled( 'gutenberg-block-directory' ) ) { + return; + } + $plugins = new WP_REST_Plugins_Controller(); $plugins->register_routes(); } diff --git a/phpunit/bootstrap.php b/phpunit/bootstrap.php index 30cb39dad4fdde..2811d0df32e961 100644 --- a/phpunit/bootstrap.php +++ b/phpunit/bootstrap.php @@ -70,6 +70,13 @@ function fail_if_died( $message ) { } tests_add_filter( 'wp_die_handler', 'fail_if_died' ); +function _enable_gutenberg_experiments() { + return array( + 'gutenberg-block-directory' => '1', + ); +} +tests_add_filter( 'pre_option_gutenberg-experiments', '_enable_gutenberg_experiments' ); + // Start up the WP testing environment. require $_tests_dir . '/includes/bootstrap.php'; diff --git a/phpunit/class-wp-rest-block-directory-controller-test.php b/phpunit/class-wp-rest-block-directory-controller-test.php index 2031bb5f3bb0fe..a97e780e8d1fe8 100644 --- a/phpunit/class-wp-rest-block-directory-controller-test.php +++ b/phpunit/class-wp-rest-block-directory-controller-test.php @@ -6,7 +6,7 @@ * @package Gutenberg * phpcs:disable */ -class WP_REST_Block_Directory_Controller_Test extends WP_Test_REST_TestCase { +class WP_REST_Block_Directory_Controller_Test extends WP_Test_REST_Controller_Testcase { protected static $admin_id; public static function wpSetUpBeforeClass( $factory ) { @@ -15,13 +15,6 @@ public static function wpSetUpBeforeClass( $factory ) { 'role' => 'administrator', ) ); - - // Ensure routes are registered regardless of the `gutenberg-block-directory` experimental setting. - // This should be removed when `gutenberg_register_rest_block_directory()` is unconditional. - add_filter( 'rest_api_init', function () { - $block_directory_controller = new WP_REST_Block_Directory_Controller(); - $block_directory_controller->register_routes(); - } ); } public static function wpTearDownAfterClass() { @@ -36,22 +29,16 @@ public function test_register_routes() { $this->assertArrayHasKey( '/__experimental/block-directory/uninstall', $routes ); } - /** - * Tests that an error is returned if the block plugin slug is not provided - */ - public function test_should_throw_no_slug_error() { - wp_set_current_user( self::$admin_id ); - - $request = new WP_REST_Request( 'POST', '/__experimental/block-directory/install', [] ); - $result = rest_do_request( $request ); - - $this->assertErrorResponse( 'rest_missing_callback_param', $result, 400 ); + public function test_context_param() { + // Collection. + $request = new WP_REST_Request( 'OPTIONS', '/__experimental/block-directory/search' ); + $response = rest_get_server()->dispatch( $request ); + $data = $response->get_data(); + $this->assertEquals( 'view', $data['endpoints'][0]['args']['context']['default'] ); + $this->assertEquals( array( 'view' ), $data['endpoints'][0]['args']['context']['enum'] ); } - /** - * Tests that the search endpoint does not return an error - */ - public function test_simple_search() { + public function test_get_items() { wp_set_current_user( self::$admin_id ); $request = new WP_REST_Request( 'GET', '/__experimental/block-directory/search' ); @@ -62,10 +49,7 @@ public function test_simple_search() { $this->assertEquals( 200, $result->status ); } - /** - * Tests that the search endpoint returns WP_Error when the server is unreachable. - */ - public function test_search_unreachable() { + public function test_get_items_wdotorg_unavailable() { wp_set_current_user( self::$admin_id ); $request = new WP_REST_Request( 'GET', '/__experimental/block-directory/search' ); @@ -78,22 +62,60 @@ public function test_search_unreachable() { $this->assertErrorResponse( 'plugins_api_failed', $response, 500 ); } - /** - * Should fail with a permission error if requesting user is not logged in. - */ - public function test_simple_search_no_perms() { + public function test_get_items_logged_out() { $request = new WP_REST_Request( 'GET', '/__experimental/block-directory/search' ); $request->set_query_params( array( 'term' => 'foo' ) ); $response = rest_do_request( $request ); + $this->assertErrorResponse( 'rest_block_directory_cannot_view', $response ); + } + + public function test_get_items_no_results() { + wp_set_current_user( self::$admin_id ); + + $request = new WP_REST_Request( 'GET', '/__experimental/block-directory/search' ); + $request->set_query_params( array( 'term' => '0c4549ee68f24eaaed46a49dc983ecde' ) ); + $response = rest_do_request( $request ); $data = $response->get_data(); - $this->assertEquals( $data['code'], 'rest_user_cannot_view' ); + // Should produce a 200 status with an empty array. + $this->assertEquals( 200, $response->status ); + $this->assertEquals( array(), $data ); } - /** - * Make sure a search with the right permissions returns something. - */ - public function test_simple_search_with_perms() { + public function test_get_item() { + $this->markTestSkipped( 'Controller does not have get_item route.' ); + } + + public function test_create_item() { + if ( ! defined( 'FS_METHOD' ) ) { + define( 'FS_METHOD', 'direct' ); + } + + if ( isset( get_plugins()['hello-dolly/hello.php'] ) ) { + delete_plugins( array( 'hello-dolly/hello.php' ) ); + } + + wp_set_current_user( self::$admin_id ); + + $request = new WP_REST_Request( 'POST', '/__experimental/block-directory/install' ); + $request->set_body_params( array( 'slug' => 'hello-dolly' ) ); + + $response = rest_do_request( $request ); + $this->skip_on_filesystem_error( $response ); + $this->assertNotWPError( $response->as_error() ); + $this->assertEquals( 201, $response->get_status() ); + $this->assertEquals( 'Hello Dolly', $response->get_data()['name'] ); + } + + public function test_update_item() { + $this->markTestSkipped( 'Controller does not have update_item route.' ); + } + + public function test_delete_item() { + $this->markTestSkipped( 'Covered by Plugins controller tests.' ); + } + + public function test_prepare_item() { wp_set_current_user( self::$admin_id ); // This will hit the live API. We're searching for `block` which should definitely return at least one result. @@ -116,26 +138,7 @@ public function test_simple_search_with_perms() { } } - /** - * A search with zero results should return a 200 response. - */ - public function test_simple_search_no_results() { - wp_set_current_user( self::$admin_id ); - - $request = new WP_REST_Request( 'GET', '/__experimental/block-directory/search' ); - $request->set_query_params( array( 'term' => '0c4549ee68f24eaaed46a49dc983ecde' ) ); - $response = rest_do_request( $request ); - $data = $response->get_data(); - - // Should produce a 200 status with an empty array. - $this->assertEquals( 200, $response->status ); - $this->assertEquals( array(), $data ); - } - - /** - * Make sure the search schema is available and correct. - */ - public function test_search_schema() { + public function test_get_item_schema() { wp_set_current_user( self::$admin_id ); $request = new WP_REST_Request( 'OPTIONS', '/__experimental/block-directory/search' ); @@ -145,36 +148,24 @@ public function test_search_schema() { // Check endpoints $this->assertEquals( [ 'GET' ], $data['endpoints'][0]['methods'] ); - $this->assertEquals( [ 'term' => [ 'required' => true ] ], $data['endpoints'][0]['args'] ); - - // Check schema - $this->assertEquals( [ - 'description' => __( "The block name, in namespace/block-name format." ), - 'type' => [ 'string' ], - 'context' => [ 'view' ], - ], $data['schema']['properties']['name'] ); - // TODO: ..etc.. - } - - public function test_install_item() { - if ( ! defined( 'FS_METHOD' ) ) { - define( 'FS_METHOD', 'direct' ); - } - - if ( isset( get_plugins()['hello-dolly/hello.php'] ) ) { - delete_plugins( array( 'hello-dolly/hello.php' ) ); - } - - wp_set_current_user( self::$admin_id ); - - $request = new WP_REST_Request( 'POST', '/__experimental/block-directory/install' ); - $request->set_body_params( array( 'slug' => 'hello-dolly' ) ); - - $response = rest_do_request( $request ); - $this->skip_on_filesystem_error( $response ); - $this->assertNotWPError( $response->as_error() ); - $this->assertEquals( 201, $response->get_status() ); - $this->assertEquals( 'Hello Dolly', $response->get_data()['name'] ); + $this->assertTrue( $data['endpoints'][0]['args']['term'][ 'required'] ); + + $properties = $data['schema']['properties']; + + $this->assertCount( 13, $properties ); + $this->assertArrayHasKey( 'name', $properties ); + $this->assertArrayHasKey( 'title', $properties ); + $this->assertArrayHasKey( 'description', $properties ); + $this->assertArrayHasKey( 'id', $properties ); + $this->assertArrayHasKey( 'rating', $properties ); + $this->assertArrayHasKey( 'rating_count', $properties ); + $this->assertArrayHasKey( 'active_installs', $properties ); + $this->assertArrayHasKey( 'author_block_rating', $properties ); + $this->assertArrayHasKey( 'author_block_count', $properties ); + $this->assertArrayHasKey( 'author', $properties ); + $this->assertArrayHasKey( 'icon', $properties ); + $this->assertArrayHasKey( 'humanized_updated', $properties ); + $this->assertArrayHasKey( 'assets', $properties ); } /** @@ -189,7 +180,9 @@ protected function skip_on_filesystem_error( WP_REST_Response $response ) { return; } - if ( 'fs_unavailable' === $response->as_error()->get_error_code() ) { + $code = $response->as_error()->get_error_code(); + + if ( 'fs_unavailable' === $code || false !== strpos( $code, 'mkdir_failed' ) ) { $this->markTestSkipped( 'Filesystem is unavailable.' ); } } diff --git a/phpunit/class-wp-rest-plugins-controller-test.php b/phpunit/class-wp-rest-plugins-controller-test.php index 0520e4ded4c537..ac8747ad151aae 100644 --- a/phpunit/class-wp-rest-plugins-controller-test.php +++ b/phpunit/class-wp-rest-plugins-controller-test.php @@ -357,7 +357,9 @@ protected function skip_on_filesystem_error( WP_REST_Response $response ) { return; } - if ( 'fs_unavailable' === $response->as_error()->get_error_code() ) { + $code = $response->as_error()->get_error_code(); + + if ( 'fs_unavailable' === $code || false !== strpos( $code, 'mkdir_failed' ) ) { $this->markTestSkipped( 'Filesystem is unavailable.' ); } } @@ -382,7 +384,7 @@ private function create_test_plugin() { */ PHP; if ( false === wp_mkdir_p( WP_PLUGIN_DIR . '/test-plugin' ) ) { - $this->markTestAsSkipped(); + $this->markTestSkipped( 'Filesystem is unavailable.' ); } file_put_contents( WP_PLUGIN_DIR . '/test-plugin/test-plugin.php', $php ); From 95cbea4c645743693386305258305d20a16e0b12 Mon Sep 17 00:00:00 2001 From: Timothy Jacobs Date: Sat, 23 May 2020 19:27:13 -0400 Subject: [PATCH 12/25] Add some more tests. Fix status handling. --- ...ass-wp-rest-block-directory-controller.php | 4 +- lib/class-wp-rest-plugins-controller.php | 120 ++++---- ...p-rest-block-directory-controller-test.php | 8 +- .../class-wp-rest-plugins-controller-test.php | 268 +++++++++++++++++- 4 files changed, 339 insertions(+), 61 deletions(-) diff --git a/lib/class-wp-rest-block-directory-controller.php b/lib/class-wp-rest-block-directory-controller.php index 27f893676bce8f..a822eeca9c61eb 100644 --- a/lib/class-wp-rest-block-directory-controller.php +++ b/lib/class-wp-rest-block-directory-controller.php @@ -180,8 +180,8 @@ public function create_item( $request ) { $inner_request = new WP_REST_Request( 'POST', '/__experimental/plugins' ); $inner_request->set_body_params( array( - 'slug' => $request['slug'], - 'activate' => true, + 'slug' => $request['slug'], + 'status' => 'active', ) ); diff --git a/lib/class-wp-rest-plugins-controller.php b/lib/class-wp-rest-plugins-controller.php index b8a9738ea08d18..a88ef6ab5d7a5b 100644 --- a/lib/class-wp-rest-plugins-controller.php +++ b/lib/class-wp-rest-plugins-controller.php @@ -3,8 +3,8 @@ * Start: Include for phase 2 * Block Directory REST API: WP_REST_Plugins_Controller class * - * @package gutenberg * @since 6.5.0 + * @package gutenberg */ /** @@ -12,7 +12,7 @@ * * @since 5.5.0 * - * @see WP_REST_Controller + * @see WP_REST_Controller */ class WP_REST_Plugins_Controller extends WP_REST_Controller { @@ -49,15 +49,16 @@ public function register_routes() { 'callback' => array( $this, 'create_item' ), 'permission_callback' => array( $this, 'create_item_permissions_check' ), 'args' => array( - 'slug' => array( + 'slug' => array( 'type' => 'string', 'required' => true, 'description' => __( 'WordPress.org plugin directory slug.', 'gutenberg' ), ), - 'activate' => array( - 'type' => 'boolean', - 'default' => false, - 'description' => __( 'Whether to activate the plugin after installing it.', 'gutenberg' ), + 'status' => array( + 'description' => __( 'The plugin activation status.', 'gutenberg' ), + 'type' => 'string', + 'enum' => is_multisite() ? array( 'inactive', 'active', 'network-active' ) : array( 'inactive', 'active' ), + 'default' => 'inactive', ), ), ), @@ -241,7 +242,7 @@ public function create_item_permissions_check( $request ) { ); } - if ( $request['activate'] && ! current_user_can( 'activate_plugins' ) ) { + if ( 'inactive' !== $request['status'] && ! current_user_can( 'activate_plugins' ) ) { return new WP_Error( 'rest_cannot_activate_plugin', __( 'Sorry, you are not allowed to activate this plugin.', 'gutenberg' ), @@ -326,21 +327,21 @@ public function create_item( $request ) { $file = $upgrader->plugin_info(); - if ( $request['activate'] ) { - if ( ! current_user_can( 'activate_plugin', $file ) ) { - return new WP_Error( - 'rest_cannot_activate_plugin', - __( 'Sorry, you are not allowed to activate this plugin. The plugin has been installed.', 'gutenberg' ), - array( - 'status' => rest_authorization_required_code(), - ) - ); + if ( ! $file ) { + return new WP_Error( 'unable_to_determine_installed_plugin', __( 'Unable to determine what plugin was installed.', 'gutenberg' ), array( 'status' => 500 ) ); + } + + if ( 'inactive' !== $request['status'] ) { + $can_change_status = $this->plugin_status_permission_check( $file, $request['status'], 'inactive' ); + + if ( is_wp_error( $can_change_status ) ) { + return $can_change_status; } - $activated = activate_plugin( $file ); + $changed_status = $this->handle_plugin_status( $file, $request['status'], 'inactive' ); - if ( is_wp_error( $activated ) ) { - return $activated; + if ( is_wp_error( $changed_status ) ) { + return $changed_status; } } @@ -385,28 +386,10 @@ public function update_item_permissions_check( $request ) { $status = $this->get_plugin_status( $request['plugin'] ); if ( $request['status'] && $status !== $request['status'] ) { - if ( ( 'network-active' === $status || 'network-active' === $request['status'] ) && ! current_user_can( 'manage_network_plugins' ) ) { - return new WP_Error( - 'rest_cannot_manage_network_plugins', - __( 'Sorry, you do not have permission to manage network plugins.', 'gutenberg' ), - array( 'status' => rest_authorization_required_code() ) - ); - } + $can_change_status = $this->plugin_status_permission_check( $request['plugin'], $request['status'], $status ); - if ( 'active' === $request['status'] && ! current_user_can( 'activate_plugin', $request['plugin'] ) ) { - return new WP_Error( - 'rest_cannot_activate_plugin', - __( 'Sorry, you are not allowed to activate this plugin.', 'gutenberg' ), - array( 'status' => rest_authorization_required_code() ) - ); - } - - if ( 'inactive' === $request['status'] && ! current_user_can( 'deactivate_plugin', $request['plugin'] ) ) { - return new WP_Error( - 'rest_cannot_deactivate_plugin', - __( 'Sorry, you are not allowed to deactivate this plugin.', 'gutenberg' ), - array( 'status' => rest_authorization_required_code() ) - ); + if ( is_wp_error( $can_change_status ) ) { + return $can_change_status; } } @@ -459,6 +442,14 @@ public function update_item( $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 ) { + if ( ! current_user_can( 'activate_plugins' ) ) { + return new WP_Error( + 'rest_cannot_manage_plugins', + __( 'Sorry, you are not allowed to manage plugins for this site.', 'gutenberg' ), + array( 'status' => rest_authorization_required_code() ) + ); + } + if ( ! current_user_can( 'delete_plugins' ) ) { return new WP_Error( 'rest_cannot_manage_plugins', @@ -576,6 +567,45 @@ protected function get_plugin_status( $plugin ) { return 'inactive'; } + /** + * Handle updating a plugin's status. + * + * @since 5.5.0 + * + * @param string $plugin The plugin file to update. + * @param string $new_status The plugin's new status. + * @param string $current_status The plugin's current status. + * + * @return true|WP_Error + */ + protected function plugin_status_permission_check( $plugin, $new_status, $current_status ) { + if ( ( 'network-active' === $current_status || 'network-active' === $new_status ) && ! current_user_can( 'manage_network_plugins' ) ) { + return new WP_Error( + 'rest_cannot_manage_network_plugins', + __( 'Sorry, you do not have permission to manage network plugins.', 'gutenberg' ), + array( 'status' => rest_authorization_required_code() ) + ); + } + + if ( ( 'active' === $new_status || 'network-active' === $new_status ) && ! current_user_can( 'activate_plugin', $plugin ) ) { + return new WP_Error( + 'rest_cannot_activate_plugin', + __( 'Sorry, you are not allowed to activate this plugin.', 'gutenberg' ), + array( 'status' => rest_authorization_required_code() ) + ); + } + + if ( 'inactive' === $new_status && ! current_user_can( 'deactivate_plugin', $plugin ) ) { + return new WP_Error( + 'rest_cannot_deactivate_plugin', + __( 'Sorry, you are not allowed to deactivate this plugin.', 'gutenberg' ), + array( 'status' => rest_authorization_required_code() ) + ); + } + + return true; + } + /** * Handle updating a plugin's status. * @@ -654,12 +684,6 @@ public function get_item_schema() { return $this->add_additional_fields_schema( $this->schema ); } - $status = array( 'inactive', 'active' ); - - if ( is_multisite() ) { - $status[] = 'network-active'; - } - $this->schema = array( '$schema' => 'http://json-schema.org/draft-04/schema#', 'title' => 'plugin', @@ -675,7 +699,7 @@ public function get_item_schema() { 'status' => array( 'description' => __( 'The plugin activation status.', 'gutenberg' ), 'type' => 'string', - 'enum' => $status, + 'enum' => is_multisite() ? array( 'inactive', 'active', 'network-active' ) : array( 'inactive', 'active' ), 'context' => array( 'view', 'edit', 'embed' ), ), 'name' => array( diff --git a/phpunit/class-wp-rest-block-directory-controller-test.php b/phpunit/class-wp-rest-block-directory-controller-test.php index a97e780e8d1fe8..c8040589a8dbb4 100644 --- a/phpunit/class-wp-rest-block-directory-controller-test.php +++ b/phpunit/class-wp-rest-block-directory-controller-test.php @@ -15,6 +15,10 @@ public static function wpSetUpBeforeClass( $factory ) { 'role' => 'administrator', ) ); + + if ( ! defined( 'FS_METHOD' ) ) { + define( 'FS_METHOD', 'direct' ); + } } public static function wpTearDownAfterClass() { @@ -87,10 +91,6 @@ public function test_get_item() { } public function test_create_item() { - if ( ! defined( 'FS_METHOD' ) ) { - define( 'FS_METHOD', 'direct' ); - } - if ( isset( get_plugins()['hello-dolly/hello.php'] ) ) { delete_plugins( array( 'hello-dolly/hello.php' ) ); } diff --git a/phpunit/class-wp-rest-plugins-controller-test.php b/phpunit/class-wp-rest-plugins-controller-test.php index ac8747ad151aae..c963e0c441e46c 100644 --- a/phpunit/class-wp-rest-plugins-controller-test.php +++ b/phpunit/class-wp-rest-plugins-controller-test.php @@ -51,6 +51,10 @@ public static function wpSetUpBeforeClass( $factory ) { 'role' => 'administrator', ) ); + + if ( ! defined( 'FS_METHOD' ) ) { + define( 'FS_METHOD', 'direct' ); + } } /** @@ -143,10 +147,23 @@ public function test_get_item_invalid_plugin() { } public function test_create_item() { - if ( ! defined( 'FS_METHOD' ) ) { - define( 'FS_METHOD', 'direct' ); + if ( isset( get_plugins()['hello-dolly/hello.php'] ) ) { + delete_plugins( array( 'hello-dolly/hello.php' ) ); } + wp_set_current_user( self::$administrator_id ); + + $request = new WP_REST_Request( 'POST', self::BASE ); + $request->set_body_params( array( 'slug' => 'hello-dolly' ) ); + + $response = rest_do_request( $request ); + $this->skip_on_filesystem_error( $response ); + $this->assertNotWPError( $response->as_error() ); + $this->assertEquals( 201, $response->get_status() ); + $this->assertEquals( 'Hello Dolly', $response->get_data()['name'] ); + } + + public function test_create_item_and_activate() { if ( isset( get_plugins()['hello-dolly/hello.php'] ) ) { delete_plugins( array( 'hello-dolly/hello.php' ) ); } @@ -154,13 +171,92 @@ public function test_create_item() { wp_set_current_user( self::$administrator_id ); $request = new WP_REST_Request( 'POST', self::BASE ); - $request->set_body_params( array( 'slug' => 'hello-dolly' ) ); + $request->set_body_params( + array( + 'slug' => 'hello-dolly', + 'status' => 'active', + ) + ); $response = rest_do_request( $request ); $this->skip_on_filesystem_error( $response ); $this->assertNotWPError( $response->as_error() ); $this->assertEquals( 201, $response->get_status() ); $this->assertEquals( 'Hello Dolly', $response->get_data()['name'] ); + $this->assertTrue( is_plugin_active( 'hello-dolly/hello.php' ) ); + } + + public function test_create_item_and_activate_errors_if_no_permission_to_activate_plugin() { + if ( isset( get_plugins()['hello-dolly/hello.php'] ) ) { + delete_plugins( array( 'hello-dolly/hello.php' ) ); + } + + wp_set_current_user( self::$administrator_id ); + $this->disable_activate_permission( 'hello-dolly/hello.php' ); + + $request = new WP_REST_Request( 'POST', self::BASE ); + $request->set_body_params( + array( + 'slug' => 'hello-dolly', + 'status' => 'active', + ) + ); + + $response = rest_do_request( $request ); + $this->skip_on_filesystem_error( $response ); + $this->assertErrorResponse( 'rest_cannot_activate_plugin', $response ); + $this->assertFalse( is_plugin_active( 'hello-dolly/hello.php' ) ); + } + + /** + * @group ms-excluded + */ + public function test_create_item_and_network_activate_rejected_if_not_multisite() { + if ( isset( get_plugins()['hello-dolly/hello.php'] ) ) { + delete_plugins( array( 'hello-dolly/hello.php' ) ); + } + + wp_set_current_user( self::$administrator_id ); + + $request = new WP_REST_Request( 'POST', self::BASE ); + $request->set_body_params( + array( + 'slug' => 'hello-dolly', + 'status' => 'network-active', + ) + ); + + $response = rest_do_request( $request ); + $this->skip_on_filesystem_error( $response ); + $this->assertErrorResponse( 'rest_invalid_param', $response ); + } + + /** + * @group ms-required + */ + public function test_create_item_and_network_activate() { + $this->markTestSkipped( "Multisite tests don't appear to be working." ); + + if ( isset( get_plugins()['hello-dolly/hello.php'] ) ) { + delete_plugins( array( 'hello-dolly/hello.php' ) ); + } + + wp_set_current_user( self::$administrator_id ); + + $request = new WP_REST_Request( 'POST', self::BASE ); + $request->set_body_params( + array( + 'slug' => 'hello-dolly', + 'status' => 'network-active', + ) + ); + + $response = rest_do_request( $request ); + $this->skip_on_filesystem_error( $response ); + $this->assertNotWPError( $response->as_error() ); + $this->assertEquals( 201, $response->get_status() ); + $this->assertEquals( 'Hello Dolly', $response->get_data()['name'] ); + $this->assertTrue( is_plugin_active_for_network( 'hello-dolly/hello.php' ) ); } public function test_create_item_logged_out() { @@ -245,6 +341,67 @@ public function test_update_item_activate_plugin() { $this->assertTrue( is_plugin_active( self::PLUGIN_FILE ) ); } + public function test_update_item_activate_plugin_fails_if_no_activate_cap() { + $this->create_test_plugin(); + wp_set_current_user( self::$administrator_id ); + $this->disable_activate_permission( self::PLUGIN_FILE ); + + $request = new WP_REST_Request( 'PUT', self::BASE . '/' . self::PLUGIN ); + $request->set_body_params( array( 'status' => 'active' ) ); + $response = rest_do_request( $request ); + + $this->assertErrorResponse( 'rest_cannot_activate_plugin', $response, 403 ); + } + + /** + * @group ms-excluded + */ + public function test_update_item_network_activate_plugin_rejected_if_not_multisite() { + $this->create_test_plugin(); + wp_set_current_user( self::$administrator_id ); + + $request = new WP_REST_Request( 'PUT', self::BASE . '/' . self::PLUGIN ); + $request->set_body_params( array( 'status' => 'network-active' ) ); + $response = rest_do_request( $request ); + + $this->assertErrorResponse( 'rest_invalid_param', $response ); + } + + /** + * @group ms-required + */ + public function test_update_item_network_activate_plugin() { + $this->markTestSkipped( "Multisite tests don't appear to be working." ); + + $this->create_test_plugin(); + wp_set_current_user( self::$administrator_id ); + + $request = new WP_REST_Request( 'PUT', self::BASE . '/' . self::PLUGIN ); + $request->set_body_params( array( 'status' => 'network-active' ) ); + $response = rest_do_request( $request ); + + $this->assertEquals( 200, $response->get_status() ); + $this->assertTrue( is_plugin_active_for_network( self::PLUGIN_FILE ) ); + } + + /** + * @group ms-required + */ + public function test_update_item_network_activate_plugin_that_was_active_on_single_site() { + $this->markTestSkipped( "Multisite tests don't appear to be working." ); + + $this->create_test_plugin(); + activate_plugin( self::PLUGIN_FILE ); + wp_set_current_user( self::$administrator_id ); + + $request = new WP_REST_Request( 'PUT', self::BASE . '/' . self::PLUGIN ); + $request->set_body_params( array( 'status' => 'network-active' ) ); + $response = rest_do_request( $request ); + + $this->assertEquals( 200, $response->get_status() ); + $this->assertTrue( is_plugin_active_for_network( self::PLUGIN_FILE ) ); + } + public function test_update_item_deactivate_plugin() { $this->create_test_plugin(); activate_plugin( self::PLUGIN_FILE ); @@ -258,11 +415,38 @@ public function test_update_item_deactivate_plugin() { $this->assertTrue( is_plugin_inactive( self::PLUGIN_FILE ) ); } - public function test_delete_item() { - if ( ! defined( 'FS_METHOD' ) ) { - define( 'FS_METHOD', 'direct' ); - } + public function test_update_item_deactivate_plugin_fails_if_no_deactivate_cap() { + $this->create_test_plugin(); + activate_plugin( self::PLUGIN_FILE ); + wp_set_current_user( self::$administrator_id ); + $this->disable_deactivate_permission( self::PLUGIN_FILE ); + + $request = new WP_REST_Request( 'PUT', self::BASE . '/' . self::PLUGIN ); + $request->set_body_params( array( 'status' => 'inactive' ) ); + $response = rest_do_request( $request ); + + $this->assertErrorResponse( 'rest_cannot_deactivate_plugin', $response, 403 ); + } + + /** + * @group ms-required + */ + public function test_update_item_deactivate_network_active_plugin() { + $this->markTestSkipped( "Multisite tests don't appear to be working." ); + $this->create_test_plugin(); + activate_plugin( self::PLUGIN_FILE, '', true ); + wp_set_current_user( self::$administrator_id ); + + $request = new WP_REST_Request( 'PUT', self::BASE . '/' . self::PLUGIN ); + $request->set_body_params( array( 'status' => 'inactive' ) ); + $response = rest_do_request( $request ); + + $this->assertEquals( 200, $response->get_status() ); + $this->assertTrue( is_plugin_inactive( self::PLUGIN_FILE ) ); + } + + public function test_delete_item() { $this->create_test_plugin(); wp_set_current_user( self::$administrator_id ); @@ -291,6 +475,18 @@ public function test_delete_item_insufficient_permissions() { $this->assertEquals( 403, $response->get_status() ); } + public function test_delete_item_active_plugin() { + $this->create_test_plugin(); + activate_plugin( self::PLUGIN_FILE ); + wp_set_current_user( self::$administrator_id ); + + $request = new WP_REST_Request( 'DELETE', self::BASE . '/' . self::PLUGIN ); + $response = rest_do_request( $request ); + + $this->skip_on_filesystem_error( $response ); + $this->assertErrorResponse( 'rest_cannot_delete_active_plugin', $response ); + } + public function test_prepare_item() { $this->create_test_plugin(); @@ -303,6 +499,24 @@ public function test_prepare_item() { $this->check_get_plugin_data( $response->get_data() ); } + /** + * @group ms-required + */ + public function test_prepare_item_network_active() { + $this->markTestSkipped( "Multisite tests don't appear to be working." ); + + $this->create_test_plugin(); + activate_plugin( self::PLUGIN_FILE, '', true ); + + $item = get_plugins()[ self::PLUGIN_FILE ]; + $item['_file'] = self::PLUGIN_FILE; + + $endpoint = new WP_REST_Plugins_Controller(); + $response = $endpoint->prepare_item_for_response( $item, new WP_REST_Request( 'GET', self::BASE . '/' . self::PLUGIN ) ); + + $this->assertEquals( 'network-active', $response->get_data()['status'] ); + } + public function test_get_item_schema() { $request = new WP_REST_Request( 'OPTIONS', self::BASE ); $response = rest_get_server()->dispatch( $request ); @@ -364,6 +578,46 @@ protected function skip_on_filesystem_error( WP_REST_Response $response ) { } } + /** + * Disables permission for activating a specific plugin. + * + * @param string $plugin The plugin file to disable. + */ + protected function disable_activate_permission( $plugin ) { + add_filter( + 'map_meta_cap', + static function ( $caps, $cap, $user, $args ) use ( $plugin ) { + if ( 'activate_plugin' === $cap && $plugin === $args[0] ) { + $caps = array( 'do_not_allow' ); + } + + return $caps; + }, + 10, + 4 + ); + } + + /** + * Disables permission for deactivating a specific plugin. + * + * @param string $plugin The plugin file to disable. + */ + protected function disable_deactivate_permission( $plugin ) { + add_filter( + 'map_meta_cap', + static function ( $caps, $cap, $user, $args ) use ( $plugin ) { + if ( 'deactivate_plugin' === $cap && $plugin === $args[0] ) { + $caps = array( 'do_not_allow' ); + } + + return $caps; + }, + 10, + 4 + ); + } + /** * Creates a test plugin. * From 8fc84be3a481253b1adba866c0cef921afb997d7 Mon Sep 17 00:00:00 2001 From: Timothy Jacobs Date: Wed, 3 Jun 2020 22:30:30 -0400 Subject: [PATCH 13/25] Use wp_tests_options instead of manually using a filter. --- phpunit/bootstrap.php | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/phpunit/bootstrap.php b/phpunit/bootstrap.php index 2811d0df32e961..b3f564d120e222 100644 --- a/phpunit/bootstrap.php +++ b/phpunit/bootstrap.php @@ -70,12 +70,11 @@ function fail_if_died( $message ) { } tests_add_filter( 'wp_die_handler', 'fail_if_died' ); -function _enable_gutenberg_experiments() { - return array( +$GLOBALS['wp_tests_options'] = array( + 'gutenberg-experiments' => array( 'gutenberg-block-directory' => '1', - ); -} -tests_add_filter( 'pre_option_gutenberg-experiments', '_enable_gutenberg_experiments' ); + ), +); // Start up the WP testing environment. require $_tests_dir . '/includes/bootstrap.php'; From 633b5d487d72cc0e038376e3195dd31c0caec930 Mon Sep 17 00:00:00 2001 From: Timothy Jacobs Date: Thu, 4 Jun 2020 01:07:55 -0400 Subject: [PATCH 14/25] Fix multisite tests. --- ...ass-wp-rest-block-directory-controller.php | 3 +- lib/class-wp-rest-plugins-controller.php | 105 ++++++++++++------ package.json | 4 +- phpunit.xml.dist | 6 + ...p-rest-block-directory-controller-test.php | 6 +- .../class-wp-rest-plugins-controller-test.php | 14 +-- phpunit/multisite.xml | 19 ++++ 7 files changed, 107 insertions(+), 50 deletions(-) create mode 100644 phpunit/multisite.xml diff --git a/lib/class-wp-rest-block-directory-controller.php b/lib/class-wp-rest-block-directory-controller.php index a822eeca9c61eb..7ffa52a1fd767e 100644 --- a/lib/class-wp-rest-block-directory-controller.php +++ b/lib/class-wp-rest-block-directory-controller.php @@ -86,7 +86,8 @@ public function get_items_permissions_check( $request ) { // phpcs:ignore Variab if ( ! current_user_can( 'install_plugins' ) || ! current_user_can( 'activate_plugins' ) ) { return new WP_Error( 'rest_block_directory_cannot_view', - __( 'Sorry, you are not allowed to browse the block directory.', 'gutenberg' ) + __( 'Sorry, you are not allowed to browse the block directory.', 'gutenberg' ), + array( 'status' => rest_authorization_required_code() ) ); } diff --git a/lib/class-wp-rest-plugins-controller.php b/lib/class-wp-rest-plugins-controller.php index a88ef6ab5d7a5b..570611c4908790 100644 --- a/lib/class-wp-rest-plugins-controller.php +++ b/lib/class-wp-rest-plugins-controller.php @@ -144,7 +144,7 @@ public function get_items( $request ) { $plugins = array(); foreach ( get_plugins() as $file => $data ) { - if ( ! $this->check_read_permission( $file ) ) { + if ( is_wp_error( $this->check_read_permission( $file ) ) ) { continue; } @@ -172,12 +172,10 @@ public function get_item_permissions_check( $request ) { ); } - if ( ! $this->check_read_permission( $request['plugin'] ) ) { - return new WP_Error( - 'rest_cannot_view_plugin', - __( 'Sorry, you are not allowed to manage this plugin.', 'gutenberg' ), - array( 'status' => rest_authorization_required_code() ) - ); + $can_read = $this->check_read_permission( $request['plugin'] ); + + if ( is_wp_error( $can_read ) ) { + return $can_read; } return true; @@ -194,15 +192,12 @@ public function get_item_permissions_check( $request ) { public function get_item( $request ) { require_once ABSPATH . 'wp-admin/includes/plugin.php'; - $plugins = get_plugins(); + $data = $this->get_plugin_data( $request['plugin'] ); - if ( ! isset( $plugins[ $request['plugin'] ] ) ) { - return new WP_Error( 'rest_plugin_not_found', __( 'Plugin not found.', 'gutenberg' ), array( 'status' => 404 ) ); + if ( is_wp_error( $data ) ) { + return $data; } - $data = $plugins[ $request['plugin'] ]; - $data['_file'] = $request['plugin']; - return $this->prepare_item_for_response( $data, $request ); } @@ -215,14 +210,26 @@ public function get_item( $request ) { * @since 5.5.0 * * @param string $plugin The plugin file to check. - * @return bool + * @return true|WP_Error True if can read, a WP_Error instance otherwise. */ protected function check_read_permission( $plugin ) { + if ( ! $this->is_plugin_installed( $plugin ) ) { + return new WP_Error( 'rest_plugin_not_found', __( 'Plugin not found.', 'gutenberg' ), array( 'status' => 404 ) ); + } + if ( ! is_multisite() ) { return true; } - return ! is_network_only_plugin( $plugin ) || is_plugin_active( $plugin ) || current_user_can( 'manage_network_plugins' ); + if ( ! is_network_only_plugin( $plugin ) || is_plugin_active( $plugin ) || current_user_can( 'manage_network_plugins' ) ) { + return true; + } + + return new WP_Error( + 'rest_cannot_view_plugin', + __( 'Sorry, you are not allowed to manage this plugin.', 'gutenberg' ), + array( 'status' => rest_authorization_required_code() ) + ); } /** @@ -375,12 +382,10 @@ public function update_item_permissions_check( $request ) { ); } - if ( ! $this->check_read_permission( $request['plugin'] ) ) { - return new WP_Error( - 'rest_cannot_view_plugin', - __( 'Sorry, you are not allowed to manage this plugin.', 'gutenberg' ), - array( 'status' => rest_authorization_required_code() ) - ); + $can_read = $this->check_read_permission( $request['plugin'] ); + + if ( is_wp_error( $can_read ) ) { + return $can_read; } $status = $this->get_plugin_status( $request['plugin'] ); @@ -407,15 +412,12 @@ public function update_item_permissions_check( $request ) { public function update_item( $request ) { require_once ABSPATH . 'wp-admin/includes/plugin.php'; - $plugins = get_plugins(); + $data = $this->get_plugin_data( $request['plugin'] ); - if ( ! isset( $plugins[ $request['plugin'] ] ) ) { - return new WP_Error( 'rest_plugin_not_found', __( 'Plugin not found.', 'gutenberg' ), array( 'status' => 404 ) ); + if ( is_wp_error( $data ) ) { + return $data; } - $data = $plugins[ $request['plugin'] ]; - $data['_file'] = $request['plugin']; - $status = $this->get_plugin_status( $request['plugin'] ); if ( $request['status'] && $status !== $request['status'] ) { @@ -458,12 +460,10 @@ public function delete_item_permissions_check( $request ) { ); } - if ( ! $this->check_read_permission( $request['plugin'] ) ) { - return new WP_Error( - 'rest_cannot_view_plugin', - __( 'Sorry, you are not allowed to manage this plugin.', 'gutenberg' ), - array( 'status' => rest_authorization_required_code() ) - ); + $can_read = $this->check_read_permission( $request['plugin'] ); + + if ( is_wp_error( $can_read ) ) { + return $can_read; } return true; @@ -481,10 +481,10 @@ public function delete_item( $request ) { require_once ABSPATH . 'wp-admin/includes/file.php'; require_once ABSPATH . 'wp-admin/includes/plugin.php'; - $plugins = get_plugins(); + $data = $this->get_plugin_data( $request['plugin'] ); - if ( ! isset( $plugins[ $request['plugin'] ] ) ) { - return new WP_Error( 'rest_plugin_not_found', __( 'Plugin not found.', 'gutenberg' ), array( 'status' => 404 ) ); + if ( is_wp_error( $data ) ) { + return $data; } if ( is_plugin_active( $request['plugin'] ) ) { @@ -547,6 +547,27 @@ public function prepare_item_for_response( $item, $request ) { return $response; } + /** + * Gets the plugin header data for a plugin. + * + * @since 5.5.0 + * + * @param string $plugin The plugin file to get data for. + * @return array|WP_Error The plugin data, or a WP_Error if the plugin is not installed. + */ + protected function get_plugin_data( $plugin ) { + $plugins = get_plugins(); + + if ( ! isset( $plugins[ $plugin ] ) ) { + return new WP_Error( 'rest_plugin_not_found', __( 'Plugin not found.', 'gutenberg' ), array( 'status' => 404 ) ); + } + + $data = $plugins[ $plugin ]; + $data['_file'] = $plugin; + + return $data; + } + /** * Get's the activation status for a plugin. * @@ -645,6 +666,18 @@ protected function handle_plugin_status( $plugin, $new_status, $current_status ) return true; } + /** + * Checks if the plugin is installed. + * + * @since 5.5.0 + * + * @param string $plugin The plugin file. + * @return bool + */ + protected function is_plugin_installed( $plugin ) { + return file_exists( WP_PLUGIN_DIR . '/' . $plugin ); + } + /** * Determine if the endpoints are available. * diff --git a/package.json b/package.json index 2f2a08748da50d..ea7248d5de5911 100644 --- a/package.json +++ b/package.json @@ -236,8 +236,8 @@ "test-unit:debug": "wp-scripts --inspect-brk test-unit-js --runInBand --no-cache --verbose --config test/unit/jest.config.js ", "test-unit:update": "npm run test-unit -- --updateSnapshot", "test-unit:watch": "npm run test-unit -- --watch", - "test-unit-php": "wp-env run phpunit 'phpunit -c /var/www/html/wp-content/plugins/gutenberg/phpunit.xml.dist'", - "test-unit-php-multisite": "wp-env run phpunit 'WP_MULTISITE=1 phpunit -c /var/www/html/wp-content/plugins/gutenberg/phpunit.xml.dist'", + "test-unit-php": "wp-env run phpunit 'phpunit -c /var/www/html/wp-content/plugins/gutenberg/phpunit.xml.dist --verbose'", + "test-unit-php-multisite": "wp-env run phpunit 'WP_MULTISITE=1 phpunit -c /var/www/html/wp-content/plugins/gutenberg/phpunit/multisite.xml --verbose'", "test-unit:native": "cd test/native/ && cross-env NODE_ENV=test jest --config ./jest.config.js", "test-unit:native:debug": "cd test/native/ && node --inspect-brk ../../node_modules/.bin/jest --runInBand --verbose --config ./jest.config.js", "prestorybook:build": "npm run build:packages", diff --git a/phpunit.xml.dist b/phpunit.xml.dist index e799a44754caf4..8f8a43aedd69bf 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -11,4 +11,10 @@ ./phpunit/ + + + ms-files + ms-required + + diff --git a/phpunit/class-wp-rest-block-directory-controller-test.php b/phpunit/class-wp-rest-block-directory-controller-test.php index c8040589a8dbb4..1675fac5fa35c6 100644 --- a/phpunit/class-wp-rest-block-directory-controller-test.php +++ b/phpunit/class-wp-rest-block-directory-controller-test.php @@ -16,6 +16,10 @@ public static function wpSetUpBeforeClass( $factory ) { ) ); + if ( is_multisite() ) { + grant_super_admin( self::$admin_id ); + } + if ( ! defined( 'FS_METHOD' ) ) { define( 'FS_METHOD', 'direct' ); } @@ -49,7 +53,7 @@ public function test_get_items() { $request->set_query_params( array( 'term' => 'foo' ) ); $result = rest_do_request( $request ); - $this->assertNotWPError( $result ); + $this->assertNotWPError( $result->as_error() ); $this->assertEquals( 200, $result->status ); } diff --git a/phpunit/class-wp-rest-plugins-controller-test.php b/phpunit/class-wp-rest-plugins-controller-test.php index c963e0c441e46c..0e1460cbe63657 100644 --- a/phpunit/class-wp-rest-plugins-controller-test.php +++ b/phpunit/class-wp-rest-plugins-controller-test.php @@ -52,6 +52,10 @@ public static function wpSetUpBeforeClass( $factory ) { ) ); + if ( is_multisite() ) { + grant_super_admin( self::$administrator_id ); + } + if ( ! defined( 'FS_METHOD' ) ) { define( 'FS_METHOD', 'direct' ); } @@ -235,8 +239,6 @@ public function test_create_item_and_network_activate_rejected_if_not_multisite( * @group ms-required */ public function test_create_item_and_network_activate() { - $this->markTestSkipped( "Multisite tests don't appear to be working." ); - if ( isset( get_plugins()['hello-dolly/hello.php'] ) ) { delete_plugins( array( 'hello-dolly/hello.php' ) ); } @@ -371,8 +373,6 @@ public function test_update_item_network_activate_plugin_rejected_if_not_multisi * @group ms-required */ public function test_update_item_network_activate_plugin() { - $this->markTestSkipped( "Multisite tests don't appear to be working." ); - $this->create_test_plugin(); wp_set_current_user( self::$administrator_id ); @@ -388,8 +388,6 @@ public function test_update_item_network_activate_plugin() { * @group ms-required */ public function test_update_item_network_activate_plugin_that_was_active_on_single_site() { - $this->markTestSkipped( "Multisite tests don't appear to be working." ); - $this->create_test_plugin(); activate_plugin( self::PLUGIN_FILE ); wp_set_current_user( self::$administrator_id ); @@ -432,8 +430,6 @@ public function test_update_item_deactivate_plugin_fails_if_no_deactivate_cap() * @group ms-required */ public function test_update_item_deactivate_network_active_plugin() { - $this->markTestSkipped( "Multisite tests don't appear to be working." ); - $this->create_test_plugin(); activate_plugin( self::PLUGIN_FILE, '', true ); wp_set_current_user( self::$administrator_id ); @@ -503,8 +499,6 @@ public function test_prepare_item() { * @group ms-required */ public function test_prepare_item_network_active() { - $this->markTestSkipped( "Multisite tests don't appear to be working." ); - $this->create_test_plugin(); activate_plugin( self::PLUGIN_FILE, '', true ); diff --git a/phpunit/multisite.xml b/phpunit/multisite.xml new file mode 100644 index 00000000000000..168d4cb9e1136f --- /dev/null +++ b/phpunit/multisite.xml @@ -0,0 +1,19 @@ + + + + ./ + + + + + ms-excluded + + + From 9e21b2d27bfb6f7b8e7fa76c065b5c26ff23bbd5 Mon Sep 17 00:00:00 2001 From: Timothy Jacobs Date: Thu, 4 Jun 2020 01:45:58 -0400 Subject: [PATCH 15/25] Add a bunch more multisite test. --- lib/class-wp-rest-plugins-controller.php | 4 +- phpunit.xml.dist | 1 - .../class-wp-rest-plugins-controller-test.php | 291 ++++++++++++++++-- 3 files changed, 259 insertions(+), 37 deletions(-) diff --git a/lib/class-wp-rest-plugins-controller.php b/lib/class-wp-rest-plugins-controller.php index 570611c4908790..2f167c4e7e44d6 100644 --- a/lib/class-wp-rest-plugins-controller.php +++ b/lib/class-wp-rest-plugins-controller.php @@ -252,7 +252,7 @@ public function create_item_permissions_check( $request ) { if ( 'inactive' !== $request['status'] && ! current_user_can( 'activate_plugins' ) ) { return new WP_Error( 'rest_cannot_activate_plugin', - __( 'Sorry, you are not allowed to activate this plugin.', 'gutenberg' ), + __( 'Sorry, you are not allowed to activate plugins.', 'gutenberg' ), array( 'status' => rest_authorization_required_code(), ) @@ -651,7 +651,7 @@ protected function handle_plugin_status( $plugin, $new_status, $current_status ) $network_activate = 'network-active' === $new_status; $activated = activate_plugin( $plugin, '', $network_activate ); - if ( ! $network_activate && is_network_only_plugin( $plugin ) ) { + if ( ! $network_activate && is_network_only_plugin( $plugin ) && is_multisite() ) { return new WP_Error( 'rest_network_only_plugin', __( 'Network only plugin must be network activated.', 'gutenberg' ), diff --git a/phpunit.xml.dist b/phpunit.xml.dist index 8f8a43aedd69bf..75b7e4bfeb52e1 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -13,7 +13,6 @@ - ms-files ms-required diff --git a/phpunit/class-wp-rest-plugins-controller-test.php b/phpunit/class-wp-rest-plugins-controller-test.php index 0e1460cbe63657..9554e4b9c38f1d 100644 --- a/phpunit/class-wp-rest-plugins-controller-test.php +++ b/phpunit/class-wp-rest-plugins-controller-test.php @@ -11,8 +11,8 @@ */ class WP_REST_Plugins_Controller_Test extends WP_Test_REST_Controller_Testcase { - const BASE = '/__experimental/plugins'; - const PLUGIN = 'test-plugin/test-plugin'; + const BASE = '/__experimental/plugins'; + const PLUGIN = 'test-plugin/test-plugin'; const PLUGIN_FILE = self::PLUGIN . '.php'; /** @@ -20,18 +20,27 @@ class WP_REST_Plugins_Controller_Test extends WP_Test_REST_Controller_Testcase { * * @since 5.5.0 * - * @var int $subscriber_id + * @var int */ private static $subscriber_id; /** - * Administrator user ID. + * Super administrator user ID. * * @since 5.5.0 * - * @var int $administrator_id + * @var int */ - private static $administrator_id; + private static $super_admin; + + /** + * Administrator user id. + * + * @since 5.5.0 + * + * @var int + */ + private static $admin; /** * Set up class test fixtures. @@ -41,19 +50,24 @@ class WP_REST_Plugins_Controller_Test extends WP_Test_REST_Controller_Testcase { * @param WP_UnitTest_Factory $factory WordPress unit test factory. */ public static function wpSetUpBeforeClass( $factory ) { - self::$subscriber_id = $factory->user->create( + self::$subscriber_id = $factory->user->create( array( 'role' => 'subscriber', ) ); - self::$administrator_id = $factory->user->create( + self::$super_admin = $factory->user->create( + array( + 'role' => 'administrator', + ) + ); + self::$admin = $factory->user->create( array( 'role' => 'administrator', ) ); if ( is_multisite() ) { - grant_super_admin( self::$administrator_id ); + grant_super_admin( self::$super_admin ); } if ( ! defined( 'FS_METHOD' ) ) { @@ -68,7 +82,7 @@ public static function wpSetUpBeforeClass( $factory ) { */ public static function wpTearDownAfterClass() { self::delete_user( self::$subscriber_id ); - self::delete_user( self::$administrator_id ); + self::delete_user( self::$super_admin ); } public function tearDown() { @@ -102,7 +116,7 @@ public function test_context_param() { public function test_get_items() { $this->create_test_plugin(); - wp_set_current_user( self::$administrator_id ); + wp_set_current_user( self::$super_admin ); $response = rest_do_request( self::BASE ); $this->assertEquals( 200, $response->get_status() ); @@ -124,9 +138,34 @@ public function test_get_items_insufficient_permissions() { $this->assertequals( 403, $response->get_status() ); } + /** + * @group ms-required + */ + public function test_cannot_get_items_if_plugins_menu_not_available() { + $this->create_test_plugin(); + wp_set_current_user( self::$admin ); + + $request = new WP_REST_Request( 'GET', self::BASE ); + $response = rest_do_request( $request ); + + $this->assertErrorResponse( 'rest_cannot_view_plugins', $response->as_error(), 403 ); + } + + /** + * @group ms-required + */ + public function test_get_items_if_plugins_menu_available() { + $this->create_test_plugin(); + $this->enable_plugins_menu_item(); + wp_set_current_user( self::$admin ); + + $response = rest_do_request( self::BASE ); + $this->assertEquals( 200, $response->get_status() ); + } + public function test_get_item() { $this->create_test_plugin(); - wp_set_current_user( self::$administrator_id ); + wp_set_current_user( self::$super_admin ); $response = rest_do_request( self::BASE . '/' . self::PLUGIN ); $this->assertEquals( 200, $response->get_status() ); @@ -144,8 +183,33 @@ public function test_get_item_insufficient_permissions() { $this->assertEquals( 403, $response->get_status() ); } + /** + * @group ms-required + */ + public function test_cannot_get_item_if_plugins_menu_not_available() { + $this->create_test_plugin(); + wp_set_current_user( self::$admin ); + + $request = new WP_REST_Request( 'GET', self::BASE . '/' . self::PLUGIN ); + $response = rest_do_request( $request ); + + $this->assertErrorResponse( 'rest_cannot_view_plugin', $response->as_error(), 403 ); + } + + /** + * @group ms-required + */ + public function test_get_item_if_plugins_menu_available() { + $this->create_test_plugin(); + $this->enable_plugins_menu_item(); + wp_set_current_user( self::$admin ); + + $response = rest_do_request( self::BASE . '/' . self::PLUGIN ); + $this->assertEquals( 200, $response->get_status() ); + } + public function test_get_item_invalid_plugin() { - wp_set_current_user( self::$administrator_id ); + wp_set_current_user( self::$super_admin ); $response = rest_do_request( self::BASE . '/' . self::PLUGIN ); $this->assertEquals( 404, $response->get_status() ); } @@ -155,7 +219,7 @@ public function test_create_item() { delete_plugins( array( 'hello-dolly/hello.php' ) ); } - wp_set_current_user( self::$administrator_id ); + wp_set_current_user( self::$super_admin ); $request = new WP_REST_Request( 'POST', self::BASE ); $request->set_body_params( array( 'slug' => 'hello-dolly' ) ); @@ -172,7 +236,7 @@ public function test_create_item_and_activate() { delete_plugins( array( 'hello-dolly/hello.php' ) ); } - wp_set_current_user( self::$administrator_id ); + wp_set_current_user( self::$super_admin ); $request = new WP_REST_Request( 'POST', self::BASE ); $request->set_body_params( @@ -195,7 +259,7 @@ public function test_create_item_and_activate_errors_if_no_permission_to_activat delete_plugins( array( 'hello-dolly/hello.php' ) ); } - wp_set_current_user( self::$administrator_id ); + wp_set_current_user( self::$super_admin ); $this->disable_activate_permission( 'hello-dolly/hello.php' ); $request = new WP_REST_Request( 'POST', self::BASE ); @@ -220,7 +284,7 @@ public function test_create_item_and_network_activate_rejected_if_not_multisite( delete_plugins( array( 'hello-dolly/hello.php' ) ); } - wp_set_current_user( self::$administrator_id ); + wp_set_current_user( self::$super_admin ); $request = new WP_REST_Request( 'POST', self::BASE ); $request->set_body_params( @@ -243,7 +307,7 @@ public function test_create_item_and_network_activate() { delete_plugins( array( 'hello-dolly/hello.php' ) ); } - wp_set_current_user( self::$administrator_id ); + wp_set_current_user( self::$super_admin ); $request = new WP_REST_Request( 'POST', self::BASE ); $request->set_body_params( @@ -278,8 +342,22 @@ public function test_create_item_insufficient_permissions() { $this->assertEquals( 403, $response->get_status() ); } + /** + * @group ms-required + */ + public function test_cannot_create_item_if_not_super_admin() { + $this->create_test_plugin(); + wp_set_current_user( self::$admin ); + + $request = new WP_REST_Request( 'POST', self::BASE ); + $request->set_body_params( array( 'slug' => 'hello-dolly' ) ); + $response = rest_do_request( $request ); + + $this->assertErrorResponse( 'rest_cannot_install_plugin', $response->as_error(), 403 ); + } + public function test_create_item_wdotorg_unreachable() { - wp_set_current_user( self::$administrator_id ); + wp_set_current_user( self::$super_admin ); $request = new WP_REST_Request( 'POST', self::BASE ); $request->set_body_params( array( 'slug' => 'foo' ) ); @@ -293,7 +371,7 @@ public function test_create_item_wdotorg_unreachable() { } public function test_create_item_unknown_plugin() { - wp_set_current_user( self::$administrator_id ); + wp_set_current_user( self::$super_admin ); // This will hit the live API. $request = new WP_REST_Request( 'POST', self::BASE ); @@ -307,7 +385,7 @@ public function test_create_item_unknown_plugin() { public function test_update_item() { $this->create_test_plugin(); - wp_set_current_user( self::$administrator_id ); + wp_set_current_user( self::$super_admin ); $request = new WP_REST_Request( 'PUT', self::BASE . '/' . self::PLUGIN ); $response = rest_do_request( $request ); @@ -331,9 +409,22 @@ public function test_update_item_insufficient_permissions() { $this->assertEquals( 403, $response->get_status() ); } + /** + * @group ms-required + */ + public function test_cannot_update_item_if_plugins_menu_not_available() { + $this->create_test_plugin(); + wp_set_current_user( self::$admin ); + + $request = new WP_REST_Request( 'PUT', self::BASE . '/' . self::PLUGIN ); + $response = rest_do_request( $request ); + + $this->assertErrorResponse( 'rest_cannot_manage_plugins', $response->as_error(), 403 ); + } + public function test_update_item_activate_plugin() { $this->create_test_plugin(); - wp_set_current_user( self::$administrator_id ); + wp_set_current_user( self::$super_admin ); $request = new WP_REST_Request( 'PUT', self::BASE . '/' . self::PLUGIN ); $request->set_body_params( array( 'status' => 'active' ) ); @@ -345,7 +436,7 @@ public function test_update_item_activate_plugin() { public function test_update_item_activate_plugin_fails_if_no_activate_cap() { $this->create_test_plugin(); - wp_set_current_user( self::$administrator_id ); + wp_set_current_user( self::$super_admin ); $this->disable_activate_permission( self::PLUGIN_FILE ); $request = new WP_REST_Request( 'PUT', self::BASE . '/' . self::PLUGIN ); @@ -360,7 +451,7 @@ public function test_update_item_activate_plugin_fails_if_no_activate_cap() { */ public function test_update_item_network_activate_plugin_rejected_if_not_multisite() { $this->create_test_plugin(); - wp_set_current_user( self::$administrator_id ); + wp_set_current_user( self::$super_admin ); $request = new WP_REST_Request( 'PUT', self::BASE . '/' . self::PLUGIN ); $request->set_body_params( array( 'status' => 'network-active' ) ); @@ -374,7 +465,7 @@ public function test_update_item_network_activate_plugin_rejected_if_not_multisi */ public function test_update_item_network_activate_plugin() { $this->create_test_plugin(); - wp_set_current_user( self::$administrator_id ); + wp_set_current_user( self::$super_admin ); $request = new WP_REST_Request( 'PUT', self::BASE . '/' . self::PLUGIN ); $request->set_body_params( array( 'status' => 'network-active' ) ); @@ -390,7 +481,36 @@ public function test_update_item_network_activate_plugin() { public function test_update_item_network_activate_plugin_that_was_active_on_single_site() { $this->create_test_plugin(); activate_plugin( self::PLUGIN_FILE ); - wp_set_current_user( self::$administrator_id ); + wp_set_current_user( self::$super_admin ); + + $request = new WP_REST_Request( 'PUT', self::BASE . '/' . self::PLUGIN ); + $request->set_body_params( array( 'status' => 'network-active' ) ); + $response = rest_do_request( $request ); + + $this->assertEquals( 200, $response->get_status() ); + $this->assertTrue( is_plugin_active_for_network( self::PLUGIN_FILE ) ); + } + + /** + * @group ms-required + */ + public function test_update_item_activate_network_only_plugin() { + $this->create_test_plugin( true ); + wp_set_current_user( self::$super_admin ); + + $request = new WP_REST_Request( 'PUT', self::BASE . '/' . self::PLUGIN ); + $request->set_body_params( array( 'status' => 'active' ) ); + $response = rest_do_request( $request ); + + $this->assertErrorResponse( 'rest_network_only_plugin', $response, 400 ); + } + + /** + * @group ms-required + */ + public function test_update_item_network_activate_network_only_plugin() { + $this->create_test_plugin( true ); + wp_set_current_user( self::$super_admin ); $request = new WP_REST_Request( 'PUT', self::BASE . '/' . self::PLUGIN ); $request->set_body_params( array( 'status' => 'network-active' ) ); @@ -400,10 +520,57 @@ public function test_update_item_network_activate_plugin_that_was_active_on_sing $this->assertTrue( is_plugin_active_for_network( self::PLUGIN_FILE ) ); } + /** + * @group ms-excluded + */ + public function test_update_item_activate_network_only_plugin_on_non_multisite() { + $this->create_test_plugin( true ); + wp_set_current_user( self::$super_admin ); + + $request = new WP_REST_Request( 'PUT', self::BASE . '/' . self::PLUGIN ); + $request->set_body_params( array( 'status' => 'active' ) ); + $response = rest_do_request( $request ); + + $this->assertEquals( 200, $response->get_status() ); + $this->assertTrue( is_plugin_active( self::PLUGIN_FILE ) ); + } + + /** + * @group ms-required + */ + public function test_update_item_activate_plugin_for_site_if_menu_item_available() { + $this->create_test_plugin(); + $this->enable_plugins_menu_item(); + wp_set_current_user( self::$admin ); + + $request = new WP_REST_Request( 'PUT', self::BASE . '/' . self::PLUGIN ); + $request->set_body_params( array( 'status' => 'active' ) ); + $response = rest_do_request( $request ); + + $this->assertNotWPError( $response->as_error() ); + $this->assertEquals( 200, $response->get_status() ); + $this->assertTrue( is_plugin_active( self::PLUGIN_FILE ) ); + } + + /** + * @group ms-required + */ + public function test_update_item_network_activate_plugin_for_site_if_menu_item_available() { + $this->create_test_plugin(); + $this->enable_plugins_menu_item(); + wp_set_current_user( self::$admin ); + + $request = new WP_REST_Request( 'PUT', self::BASE . '/' . self::PLUGIN ); + $request->set_body_params( array( 'status' => 'network-active' ) ); + $response = rest_do_request( $request ); + + $this->assertErrorResponse( 'rest_cannot_manage_network_plugins', $response, 403 ); + } + public function test_update_item_deactivate_plugin() { $this->create_test_plugin(); activate_plugin( self::PLUGIN_FILE ); - wp_set_current_user( self::$administrator_id ); + wp_set_current_user( self::$super_admin ); $request = new WP_REST_Request( 'PUT', self::BASE . '/' . self::PLUGIN ); $request->set_body_params( array( 'status' => 'inactive' ) ); @@ -416,7 +583,7 @@ public function test_update_item_deactivate_plugin() { public function test_update_item_deactivate_plugin_fails_if_no_deactivate_cap() { $this->create_test_plugin(); activate_plugin( self::PLUGIN_FILE ); - wp_set_current_user( self::$administrator_id ); + wp_set_current_user( self::$super_admin ); $this->disable_deactivate_permission( self::PLUGIN_FILE ); $request = new WP_REST_Request( 'PUT', self::BASE . '/' . self::PLUGIN ); @@ -432,7 +599,7 @@ public function test_update_item_deactivate_plugin_fails_if_no_deactivate_cap() public function test_update_item_deactivate_network_active_plugin() { $this->create_test_plugin(); activate_plugin( self::PLUGIN_FILE, '', true ); - wp_set_current_user( self::$administrator_id ); + wp_set_current_user( self::$super_admin ); $request = new WP_REST_Request( 'PUT', self::BASE . '/' . self::PLUGIN ); $request->set_body_params( array( 'status' => 'inactive' ) ); @@ -442,9 +609,25 @@ public function test_update_item_deactivate_network_active_plugin() { $this->assertTrue( is_plugin_inactive( self::PLUGIN_FILE ) ); } + /** + * @group ms-required + */ + public function test_update_item_deactivate_network_active_plugin_if_not_super_admin() { + $this->enable_plugins_menu_item(); + $this->create_test_plugin(); + activate_plugin( self::PLUGIN_FILE, '', true ); + wp_set_current_user( self::$admin ); + + $request = new WP_REST_Request( 'PUT', self::BASE . '/' . self::PLUGIN ); + $request->set_body_params( array( 'status' => 'inactive' ) ); + $response = rest_do_request( $request ); + + $this->assertErrorResponse( 'rest_cannot_manage_network_plugins', $response, 403 ); + } + public function test_delete_item() { $this->create_test_plugin(); - wp_set_current_user( self::$administrator_id ); + wp_set_current_user( self::$super_admin ); $request = new WP_REST_Request( 'DELETE', self::BASE . '/' . self::PLUGIN ); $response = rest_do_request( $request ); @@ -471,10 +654,35 @@ public function test_delete_item_insufficient_permissions() { $this->assertEquals( 403, $response->get_status() ); } + /** + * @group ms-required + */ + public function test_cannot_delete_item_if_plugins_menu_not_available() { + wp_set_current_user( self::$admin ); + + $request = new WP_REST_Request( 'DELETE', self::BASE . '/' . self::PLUGIN ); + $response = rest_do_request( $request ); + + $this->assertErrorResponse( 'rest_cannot_manage_plugins', $response->as_error(), 403 ); + } + + /** + * @group ms-required + */ + public function test_cannot_delete_item_if_plugins_menu_is_available() { + wp_set_current_user( self::$admin ); + $this->enable_plugins_menu_item(); + + $request = new WP_REST_Request( 'DELETE', self::BASE . '/' . self::PLUGIN ); + $response = rest_do_request( $request ); + + $this->assertErrorResponse( 'rest_cannot_manage_plugins', $response->as_error(), 403 ); + } + public function test_delete_item_active_plugin() { $this->create_test_plugin(); activate_plugin( self::PLUGIN_FILE ); - wp_set_current_user( self::$administrator_id ); + wp_set_current_user( self::$super_admin ); $request = new WP_REST_Request( 'DELETE', self::BASE . '/' . self::PLUGIN ); $response = rest_do_request( $request ); @@ -612,13 +820,28 @@ static function ( $caps, $cap, $user, $args ) use ( $plugin ) { ); } + /** + * Enables the "plugins" as an available menu item. + * + * @since 5.5.0 + */ + protected function enable_plugins_menu_item() { + $menu_perms = get_site_option( 'menu_items', array() ); + $menu_perms['plugins'] = true; + update_site_option( 'menu_items', $menu_perms ); + } + /** * Creates a test plugin. * * @since 5.5.0 + * + * @param bool $network_only Whether to make this a network only plugin. */ - private function create_test_plugin() { - $php = <<<'PHP' + private function create_test_plugin( $network_only = false ) { + $network = $network_only ? PHP_EOL . ' * Network: true' . PHP_EOL : ''; + + $php = << Date: Thu, 4 Jun 2020 02:04:34 -0400 Subject: [PATCH 16/25] Fix PHPCS --- phpunit/class-wp-rest-plugins-controller-test.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/phpunit/class-wp-rest-plugins-controller-test.php b/phpunit/class-wp-rest-plugins-controller-test.php index 9554e4b9c38f1d..564e0671f06092 100644 --- a/phpunit/class-wp-rest-plugins-controller-test.php +++ b/phpunit/class-wp-rest-plugins-controller-test.php @@ -11,8 +11,8 @@ */ class WP_REST_Plugins_Controller_Test extends WP_Test_REST_Controller_Testcase { - const BASE = '/__experimental/plugins'; - const PLUGIN = 'test-plugin/test-plugin'; + const BASE = '/__experimental/plugins'; + const PLUGIN = 'test-plugin/test-plugin'; const PLUGIN_FILE = self::PLUGIN . '.php'; /** From 0d44167abef519aceb992be0f696a1b89f467da4 Mon Sep 17 00:00:00 2001 From: Timothy Jacobs Date: Thu, 4 Jun 2020 09:49:19 -0400 Subject: [PATCH 17/25] Wrap specific network permission checks in an is_multisite conditional. See https://github.com/WordPress/gutenberg/pull/22454#discussion_r435145356 --- lib/class-wp-rest-plugins-controller.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/class-wp-rest-plugins-controller.php b/lib/class-wp-rest-plugins-controller.php index 2f167c4e7e44d6..abe43baeacaf28 100644 --- a/lib/class-wp-rest-plugins-controller.php +++ b/lib/class-wp-rest-plugins-controller.php @@ -600,7 +600,7 @@ protected function get_plugin_status( $plugin ) { * @return true|WP_Error */ protected function plugin_status_permission_check( $plugin, $new_status, $current_status ) { - if ( ( 'network-active' === $current_status || 'network-active' === $new_status ) && ! current_user_can( 'manage_network_plugins' ) ) { + if ( is_multisite() && ( 'network-active' === $current_status || 'network-active' === $new_status ) && ! current_user_can( 'manage_network_plugins' ) ) { return new WP_Error( 'rest_cannot_manage_network_plugins', __( 'Sorry, you do not have permission to manage network plugins.', 'gutenberg' ), From a4bb8ebdd9a3facb44ee675248cb813bdd98ef8d Mon Sep 17 00:00:00 2001 From: Timothy Jacobs Date: Thu, 4 Jun 2020 09:56:05 -0400 Subject: [PATCH 18/25] Add text_domain to response. See https://github.com/WordPress/gutenberg/pull/22454#discussion_r435144923 --- lib/class-wp-rest-plugins-controller.php | 7 +++++++ phpunit/class-wp-rest-plugins-controller-test.php | 5 ++++- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/lib/class-wp-rest-plugins-controller.php b/lib/class-wp-rest-plugins-controller.php index abe43baeacaf28..ceaa39b127b71b 100644 --- a/lib/class-wp-rest-plugins-controller.php +++ b/lib/class-wp-rest-plugins-controller.php @@ -537,6 +537,7 @@ public function prepare_item_for_response( $item, $request ) { 'network_only' => $item['Network'], 'requires_wp' => $item['RequiresWP'], 'requires_php' => $item['RequiresPHP'], + 'text_domain' => $item['TextDomain'], ); $data = $this->add_additional_fields_to_object( $data, $request ); @@ -801,6 +802,12 @@ public function get_item_schema() { 'readonly' => true, 'context' => array( 'view', 'edit', 'embed' ), ), + 'text_domain' => array( + 'description' => __( 'The plugin\'s text domain.', 'gutenberg' ), + 'type' => 'string', + 'readonly' => true, + 'context' => array( 'view', 'edit' ), + ), ), ); diff --git a/phpunit/class-wp-rest-plugins-controller-test.php b/phpunit/class-wp-rest-plugins-controller-test.php index 564e0671f06092..d76a6c0f00885c 100644 --- a/phpunit/class-wp-rest-plugins-controller-test.php +++ b/phpunit/class-wp-rest-plugins-controller-test.php @@ -725,7 +725,7 @@ public function test_get_item_schema() { $data = $response->get_data(); $properties = $data['schema']['properties']; - $this->assertCount( 11, $properties ); + $this->assertCount( 12, $properties ); $this->assertArrayHasKey( 'plugin', $properties ); $this->assertArrayHasKey( 'status', $properties ); $this->assertArrayHasKey( 'name', $properties ); @@ -737,6 +737,7 @@ public function test_get_item_schema() { $this->assertArrayHasKey( 'network_only', $properties ); $this->assertArrayHasKey( 'requires_wp', $properties ); $this->assertArrayHasKey( 'requires_php', $properties ); + $this->assertArrayHasKey( 'text_domain', $properties ); } /** @@ -759,6 +760,7 @@ protected function check_get_plugin_data( $data ) { $this->assertEquals( false, $data['network_only'] ); $this->assertEquals( '5.6.0', $data['requires_php'] ); $this->assertEquals( '5.4.0', $data['requires_wp'] ); + $this->assertEquals( 'test-plugin', $data['text_domain'] ); } /** @@ -850,6 +852,7 @@ private function create_test_plugin( $network_only = false ) { * Version: 1.5.4 * Author: WordPress.org * Author URI: https://wordpress.org/ + * Text Domain: test-plugin * Requires PHP: 5.6.0 * Requires at least: 5.4.0{$network} */ From 11821296c16d120bb1dde8f11c50365a03c1ba29 Mon Sep 17 00:00:00 2001 From: Timothy Jacobs Date: Thu, 4 Jun 2020 10:10:26 -0400 Subject: [PATCH 19/25] Add more network only plugin tests. --- .../class-wp-rest-plugins-controller-test.php | 68 ++++++++++++++++++- 1 file changed, 65 insertions(+), 3 deletions(-) diff --git a/phpunit/class-wp-rest-plugins-controller-test.php b/phpunit/class-wp-rest-plugins-controller-test.php index d76a6c0f00885c..464be39ca051f8 100644 --- a/phpunit/class-wp-rest-plugins-controller-test.php +++ b/phpunit/class-wp-rest-plugins-controller-test.php @@ -163,6 +163,52 @@ public function test_get_items_if_plugins_menu_available() { $this->assertEquals( 200, $response->get_status() ); } + /** + * @group ms-required + */ + public function test_get_items_excludes_network_only_plugin_if_not_active() { + $this->create_test_plugin( true ); + $this->enable_plugins_menu_item(); + wp_set_current_user( self::$admin ); + + $response = rest_do_request( self::BASE ); + $this->assertEquals( 200, $response->get_status() ); + + $items = wp_list_filter( $response->get_data(), array( 'plugin' => self::PLUGIN_FILE ) ); + $this->assertCount( 0, $items ); + } + + /** + * @group ms-excluded + */ + public function test_get_items_does_not_exclude_network_only_plugin_if_not_active_on_single_site() { + $this->create_test_plugin( true ); + wp_set_current_user( self::$admin ); + + $response = rest_do_request( self::BASE ); + $this->assertEquals( 200, $response->get_status() ); + + $items = wp_list_filter( $response->get_data(), array( 'plugin' => self::PLUGIN_FILE ) ); + $this->assertCount( 1, $items ); + $this->check_get_plugin_data( array_shift( $items ), true ); + } + + /** + * @group ms-required + */ + public function test_get_items_does_not_exclude_network_only_plugin_if_not_active_but_has_network_caps() { + $this->create_test_plugin( true ); + $this->enable_plugins_menu_item(); + wp_set_current_user( self::$super_admin ); + + $response = rest_do_request( self::BASE ); + $this->assertEquals( 200, $response->get_status() ); + + $items = wp_list_filter( $response->get_data(), array( 'plugin' => self::PLUGIN_FILE ) ); + $this->assertCount( 1, $items ); + $this->check_get_plugin_data( array_shift( $items ), true ); + } + public function test_get_item() { $this->create_test_plugin(); wp_set_current_user( self::$super_admin ); @@ -719,6 +765,21 @@ public function test_prepare_item_network_active() { $this->assertEquals( 'network-active', $response->get_data()['status'] ); } + /** + * @group ms-required + */ + public function test_prepare_item_network_only() { + $this->create_test_plugin( true ); + + $item = get_plugins()[ self::PLUGIN_FILE ]; + $item['_file'] = self::PLUGIN_FILE; + + $endpoint = new WP_REST_Plugins_Controller(); + $response = $endpoint->prepare_item_for_response( $item, new WP_REST_Request( 'GET', self::BASE . '/' . self::PLUGIN ) ); + + $this->check_get_plugin_data( $response->get_data(), true ); + } + public function test_get_item_schema() { $request = new WP_REST_Request( 'OPTIONS', self::BASE ); $response = rest_get_server()->dispatch( $request ); @@ -745,9 +806,10 @@ public function test_get_item_schema() { * * @since 5.5.0 * - * @param array $data Prepared plugin data. + * @param array $data Prepared plugin data. + * @param bool $network_only Whether the plugin is network only. */ - protected function check_get_plugin_data( $data ) { + protected function check_get_plugin_data( $data, $network_only = false ) { $this->assertEquals( 'test-plugin/test-plugin.php', $data['plugin'] ); $this->assertEquals( '1.5.4', $data['version'] ); $this->assertEquals( 'inactive', $data['status'] ); @@ -757,7 +819,7 @@ protected function check_get_plugin_data( $data ) { $this->assertEquals( 'https://wordpress.org/', $data['author_uri'] ); $this->assertEquals( "My 'Cool' Plugin", $data['description']['raw'] ); $this->assertEquals( 'My ‘Cool’ Plugin By WordPress.org.', $data['description']['rendered'] ); - $this->assertEquals( false, $data['network_only'] ); + $this->assertEquals( $network_only, $data['network_only'] ); $this->assertEquals( '5.6.0', $data['requires_php'] ); $this->assertEquals( '5.4.0', $data['requires_wp'] ); $this->assertEquals( 'test-plugin', $data['text_domain'] ); From b39f30b886663a6b4c32cb25743085c33674570c Mon Sep 17 00:00:00 2001 From: Timothy Jacobs Date: Tue, 9 Jun 2020 22:05:18 -0400 Subject: [PATCH 20/25] Follow core pattern for DELETE responses. https://github.com/WordPress/gutenberg/pull/22454#discussion_r437730053 --- lib/class-wp-rest-plugins-controller.php | 10 ++++++++-- phpunit/class-wp-rest-plugins-controller-test.php | 4 +++- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/lib/class-wp-rest-plugins-controller.php b/lib/class-wp-rest-plugins-controller.php index ceaa39b127b71b..c73edbe462a9a1 100644 --- a/lib/class-wp-rest-plugins-controller.php +++ b/lib/class-wp-rest-plugins-controller.php @@ -500,13 +500,19 @@ public function delete_item( $request ) { return $filesystem_available; } - $deleted = delete_plugins( array( $request['plugin'] ) ); + $prepared = $this->prepare_item_for_response( $data, $request ); + $deleted = delete_plugins( array( $request['plugin'] ) ); if ( is_wp_error( $deleted ) ) { return $deleted; } - return new WP_REST_Response( null, 204 ); + return new WP_REST_Response( + array( + 'deleted' => true, + 'previous' => $prepared->get_data(), + ) + ); } /** diff --git a/phpunit/class-wp-rest-plugins-controller-test.php b/phpunit/class-wp-rest-plugins-controller-test.php index 464be39ca051f8..d26542e4ee38d0 100644 --- a/phpunit/class-wp-rest-plugins-controller-test.php +++ b/phpunit/class-wp-rest-plugins-controller-test.php @@ -680,7 +680,9 @@ public function test_delete_item() { $this->skip_on_filesystem_error( $response ); $this->assertNotWPError( $response->as_error() ); - $this->assertEquals( 204, $response->get_status() ); + $this->assertEquals( 200, $response->get_status() ); + $this->assertTrue( $response->get_data()['deleted'] ); + $this->assertEquals( 'test-plugin/test-plugin.php', $response->get_data()['previous']['plugin'] ); $this->assertFileNotExists( WP_PLUGIN_DIR . '/' . self::PLUGIN_FILE ); } From 3737daf82ecd3080793507c7f19a194248763793 Mon Sep 17 00:00:00 2001 From: Timothy Jacobs Date: Tue, 9 Jun 2020 22:29:11 -0400 Subject: [PATCH 21/25] Introduce prepare_links method for generating links. Use sprintf for route building. https://github.com/WordPress/gutenberg/pull/22454#discussion_r437730885 https://github.com/WordPress/gutenberg/pull/22454#discussion_r437731286 https://github.com/WordPress/gutenberg/pull/22454#discussion_r437727852 --- lib/class-wp-rest-plugins-controller.php | 20 +++++++++++++++++-- .../class-wp-rest-plugins-controller-test.php | 3 +++ 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/lib/class-wp-rest-plugins-controller.php b/lib/class-wp-rest-plugins-controller.php index c73edbe462a9a1..0385731c1b24d8 100644 --- a/lib/class-wp-rest-plugins-controller.php +++ b/lib/class-wp-rest-plugins-controller.php @@ -358,7 +358,7 @@ public function create_item( $request ) { $response = $this->prepare_item_for_response( $data, $request ); $response->set_status( 201 ); - $response->header( 'Location', rest_url( $this->namespace . '/' . $this->rest_base . '/' . substr( $file, 0, - 4 ) ) ); + $response->header( 'Location', rest_url( sprintf( '%s/%s/%s', $this->namespace, $this->rest_base, substr( $file, 0, - 4 ) ) ) ); return $response; } @@ -549,11 +549,27 @@ public function prepare_item_for_response( $item, $request ) { $data = $this->add_additional_fields_to_object( $data, $request ); $response = new WP_REST_Response( $data ); - $response->add_link( 'self', rest_url( $this->namespace . '/' . $this->rest_base . '/' . substr( $item['_file'], 0, - 4 ) ) ); + $response->add_links( $this->prepare_links( $item ) ); return $response; } + /** + * Prepares links for the request. + * + * @since 5.5.0 + * + * @param array $item The plugin item. + * @return array[] + */ + protected function prepare_links( $item ) { + return array( + 'self' => array( + 'href' => rest_url( sprintf( '%s/%s/%s', $this->namespace, $this->rest_base, substr( $item['_file'], 0, - 4 ) ) ), + ), + ); + } + /** * Gets the plugin header data for a plugin. * diff --git a/phpunit/class-wp-rest-plugins-controller-test.php b/phpunit/class-wp-rest-plugins-controller-test.php index d26542e4ee38d0..1f8e6c78acaec9 100644 --- a/phpunit/class-wp-rest-plugins-controller-test.php +++ b/phpunit/class-wp-rest-plugins-controller-test.php @@ -749,6 +749,9 @@ public function test_prepare_item() { $response = $endpoint->prepare_item_for_response( $item, new WP_REST_Request( 'GET', self::BASE . '/' . self::PLUGIN ) ); $this->check_get_plugin_data( $response->get_data() ); + $links = $response->get_links(); + $this->assertArrayHasKey( 'self', $links ); + $this->assertEquals( rest_url( self::BASE . '/' . self::PLUGIN ), $links['self'][0]['href'] ); } /** From f525a35b306e65af874d41076ce2ab29525e0c96 Mon Sep 17 00:00:00 2001 From: Timothy Jacobs Date: Tue, 9 Jun 2020 22:42:27 -0400 Subject: [PATCH 22/25] Improve argument sanitization & validation. Introduces a pattern to validate the .org plugin slug, and moves specific callbacks to a dedicated method instead of an inline closure. https://github.com/WordPress/gutenberg/pull/22454#discussion_r437721278 https://github.com/WordPress/gutenberg/pull/22454#discussion_r437721827 https://github.com/WordPress/gutenberg/pull/22454#discussion_r437721999 --- lib/class-wp-rest-plugins-controller.php | 43 +++++++++++++++++------- 1 file changed, 31 insertions(+), 12 deletions(-) diff --git a/lib/class-wp-rest-plugins-controller.php b/lib/class-wp-rest-plugins-controller.php index 0385731c1b24d8..54eb775c10c4ea 100644 --- a/lib/class-wp-rest-plugins-controller.php +++ b/lib/class-wp-rest-plugins-controller.php @@ -53,6 +53,7 @@ public function register_routes() { 'type' => 'string', 'required' => true, 'description' => __( 'WordPress.org plugin directory slug.', 'gutenberg' ), + 'pattern' => '[\w\-]+', ), 'status' => array( 'description' => __( 'The plugin activation status.', 'gutenberg' ), @@ -91,18 +92,8 @@ public function register_routes() { 'plugin' => array( 'type' => 'string', 'pattern' => self::PATTERN, - 'validate_callback' => static function ( $file ) { - if ( ! is_string( $file ) || ! preg_match( '/' . self::PATTERN . '/u', $file ) ) { - return false; - } - - $validated = validate_file( plugin_basename( $file ) ); - - return 0 === $validated; - }, - 'sanitize_callback' => static function ( $file ) { - return plugin_basename( sanitize_text_field( $file . '.php' ) ); - }, + 'validate_callback' => array( $this, 'validate_plugin_param' ), + 'sanitize_callback' => array( $this, 'sanitize_plugin_param' ), ), ), 'schema' => array( $this, 'get_public_item_schema' ), @@ -689,6 +680,34 @@ protected function handle_plugin_status( $plugin, $new_status, $current_status ) return true; } + /** + * Checks that the "plugin" parameter is a valid path. + * + * @since 5.5.0 + * + * @param string $file The plugin file parameter. + * @return bool + */ + public function validate_plugin_param( $file ) { + if ( ! is_string( $file ) || ! preg_match( '/' . self::PATTERN . '/u', $file ) ) { + return false; + } + + $validated = validate_file( plugin_basename( $file ) ); + + return 0 === $validated; + } + + /** + * Sanitizes the "plugin" parameter to be a proper plugin file with ".php" appended. + * + * @param string $file The plugin file parameter. + * @return string + */ + public function sanitize_plugin_param( $file ) { + return plugin_basename( sanitize_text_field( $file . '.php' ) ); + } + /** * Checks if the plugin is installed. * From 98deefe1ab235897594ea03a3cc1b3765ca3025b Mon Sep 17 00:00:00 2001 From: Timothy Jacobs Date: Tue, 9 Jun 2020 23:02:46 -0400 Subject: [PATCH 23/25] Explicitly add a 500 status code when returning a passed-through error. Fix ordering issue of network only plugin activation check. https://github.com/WordPress/gutenberg/pull/22454#discussion_r437739668 https://github.com/WordPress/gutenberg/pull/22454#discussion_r437739714 https://github.com/WordPress/gutenberg/pull/22454#discussion_r437741613 --- lib/class-wp-rest-plugins-controller.php | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/lib/class-wp-rest-plugins-controller.php b/lib/class-wp-rest-plugins-controller.php index 54eb775c10c4ea..365126e9d90145 100644 --- a/lib/class-wp-rest-plugins-controller.php +++ b/lib/class-wp-rest-plugins-controller.php @@ -301,16 +301,23 @@ public function create_item( $request ) { $result = $upgrader->install( $api->download_link ); if ( is_wp_error( $result ) ) { + $result->add_data( array( 'status' => 500 ) ); + return $result; } // This should be the same as $result above. if ( is_wp_error( $skin->result ) ) { + $skin->result->add_data( array( 'status' => 500 ) ); + return $skin->result; } if ( $skin->get_errors()->has_errors() ) { - return $skin->get_errors(); + $error = $skin->get_errors(); + $error->add_data( array( 'status' => 500 ) ); + + return $error; } if ( is_null( $result ) ) { @@ -495,6 +502,8 @@ public function delete_item( $request ) { $deleted = delete_plugins( array( $request['plugin'] ) ); if ( is_wp_error( $deleted ) ) { + $deleted->add_data( array( 'status' => 500 ) ); + return $deleted; } @@ -663,9 +672,8 @@ protected function handle_plugin_status( $plugin, $new_status, $current_status ) } $network_activate = 'network-active' === $new_status; - $activated = activate_plugin( $plugin, '', $network_activate ); - if ( ! $network_activate && is_network_only_plugin( $plugin ) && is_multisite() ) { + if ( is_multisite() && ! $network_activate && is_network_only_plugin( $plugin ) ) { return new WP_Error( 'rest_network_only_plugin', __( 'Network only plugin must be network activated.', 'gutenberg' ), @@ -673,7 +681,11 @@ protected function handle_plugin_status( $plugin, $new_status, $current_status ) ); } + $activated = activate_plugin( $plugin, '', $network_activate ); + if ( is_wp_error( $activated ) ) { + $activated->add_data( array( 'status' => 500 ) ); + return $activated; } @@ -744,7 +756,7 @@ protected function is_filesystem_available() { return true; } - return new WP_Error( 'fs_unavailable', __( 'The filesystem is currently unavailable for managing plugins.', 'gutenberg' ) ); + return new WP_Error( 'fs_unavailable', __( 'The filesystem is currently unavailable for managing plugins.', 'gutenberg' ), array( 'status' => 500 ) ); } /** From 09a21d044b836618a394c7b1df0fcd34df95f460 Mon Sep 17 00:00:00 2001 From: Timothy Jacobs Date: Tue, 9 Jun 2020 23:07:48 -0400 Subject: [PATCH 24/25] Add "rest_prepare_plugin" filter. https://github.com/WordPress/gutenberg/pull/22454#discussion_r437741088 --- lib/class-wp-rest-plugins-controller.php | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/lib/class-wp-rest-plugins-controller.php b/lib/class-wp-rest-plugins-controller.php index 365126e9d90145..42a4c4f517baec 100644 --- a/lib/class-wp-rest-plugins-controller.php +++ b/lib/class-wp-rest-plugins-controller.php @@ -551,7 +551,16 @@ public function prepare_item_for_response( $item, $request ) { $response = new WP_REST_Response( $data ); $response->add_links( $this->prepare_links( $item ) ); - return $response; + /** + * Filters the plugin data for a response. + * + * @since 5.5.0 + * + * @param WP_REST_Response $response The response object. + * @param array $item The plugin item from {@see get_plugin_data()}. + * @param WP_REST_Request $request The request object. + */ + return apply_filters( 'rest_prepare_plugin', $response, $item, $request ); } /** From 3d1a7d6829d20e801926957c6e613786942e6ad1 Mon Sep 17 00:00:00 2001 From: Timothy Jacobs Date: Tue, 9 Jun 2020 23:46:16 -0400 Subject: [PATCH 25/25] Add "status" and "search" parameters. https://github.com/WordPress/gutenberg/pull/22454#discussion_r437720111 --- lib/class-wp-rest-plugins-controller.php | 65 +++++++++++++++++-- .../class-wp-rest-plugins-controller-test.php | 61 +++++++++++++++++ 2 files changed, 122 insertions(+), 4 deletions(-) diff --git a/lib/class-wp-rest-plugins-controller.php b/lib/class-wp-rest-plugins-controller.php index 42a4c4f517baec..492c03a50644fe 100644 --- a/lib/class-wp-rest-plugins-controller.php +++ b/lib/class-wp-rest-plugins-controller.php @@ -140,7 +140,12 @@ public function get_items( $request ) { } $data['_file'] = $file; - $plugins[] = $this->prepare_response_for_collection( $this->prepare_item_for_response( $data, $request ) ); + + if ( ! $this->does_plugin_match_request( $request, $data ) ) { + continue; + } + + $plugins[] = $this->prepare_response_for_collection( $this->prepare_item_for_response( $data, $request ) ); } return new WP_REST_Response( $plugins ); @@ -558,7 +563,7 @@ public function prepare_item_for_response( $item, $request ) { * * @param WP_REST_Response $response The response object. * @param array $item The plugin item from {@see get_plugin_data()}. - * @param WP_REST_Request $request The request object. + * @param WP_REST_Request $request The request object. */ return apply_filters( 'rest_prepare_plugin', $response, $item, $request ); } @@ -722,6 +727,8 @@ public function validate_plugin_param( $file ) { /** * Sanitizes the "plugin" parameter to be a proper plugin file with ".php" appended. * + * @since 5.5.0 + * * @param string $file The plugin file parameter. * @return string */ @@ -729,6 +736,43 @@ public function sanitize_plugin_param( $file ) { return plugin_basename( sanitize_text_field( $file . '.php' ) ); } + /** + * Checks if the plugin matches the requested parameters. + * + * @since 5.5.0 + * + * @param WP_REST_Request $request The request to require the plugin matches against. + * @param array $item The plugin item. + * + * @return bool + */ + protected function does_plugin_match_request( $request, $item ) { + $search = $request['search']; + + if ( $search ) { + $matched_search = false; + + foreach ( $item as $field ) { + if ( is_string( $field ) && false !== strpos( strip_tags( $field ), $search ) ) { + $matched_search = true; + break; + } + } + + if ( ! $matched_search ) { + return false; + } + } + + $status = $request['status']; + + if ( $status && ! in_array( $this->get_plugin_status( $item['_file'] ), $status, true ) ) { + return false; + } + + return true; + } + /** * Checks if the plugin is installed. * @@ -884,8 +928,21 @@ public function get_item_schema() { * @return array Query parameters for the collection. */ public function get_collection_params() { - return array( - 'context' => $this->get_context_param( array( 'default' => 'view' ) ), + $query_params = parent::get_collection_params(); + + $query_params['context']['default'] = 'view'; + + $query_params['status'] = array( + 'description' => __( 'Limits results to plugins with the given status.', 'gutenberg' ), + 'type' => 'array', + 'items' => array( + 'type' => 'string', + 'enum' => is_multisite() ? array( 'inactive', 'active', 'network-active' ) : array( 'inactive', 'active' ), + ), ); + + unset( $query_params['page'], $query_params['per_page'] ); + + return $query_params; } } diff --git a/phpunit/class-wp-rest-plugins-controller-test.php b/phpunit/class-wp-rest-plugins-controller-test.php index 1f8e6c78acaec9..f0d3dbeb5064fa 100644 --- a/phpunit/class-wp-rest-plugins-controller-test.php +++ b/phpunit/class-wp-rest-plugins-controller-test.php @@ -127,6 +127,67 @@ public function test_get_items() { $this->check_get_plugin_data( array_shift( $items ) ); } + public function test_get_items_search() { + $this->create_test_plugin(); + wp_set_current_user( self::$super_admin ); + + $request = new WP_REST_Request( 'GET', self::BASE ); + $request->set_query_params( array( 'search' => 'testeroni' ) ); + $response = rest_do_request( $request ); + $this->assertCount( 0, $response->get_data() ); + + $request = new WP_REST_Request( 'GET', self::BASE ); + $request->set_query_params( array( 'search' => 'Cool' ) ); + $response = rest_do_request( $request ); + $this->assertCount( 1, wp_list_filter( $response->get_data(), array( 'plugin' => self::PLUGIN_FILE ) ) ); + } + + public function test_get_items_status() { + $this->create_test_plugin(); + wp_set_current_user( self::$super_admin ); + + $request = new WP_REST_Request( 'GET', self::BASE ); + $request->set_query_params( array( 'status' => 'inactive' ) ); + $response = rest_do_request( $request ); + $this->assertCount( 1, wp_list_filter( $response->get_data(), array( 'plugin' => self::PLUGIN_FILE ) ) ); + + $request = new WP_REST_Request( 'GET', self::BASE ); + $request->set_query_params( array( 'status' => 'active' ) ); + $response = rest_do_request( $request ); + $this->assertCount( 0, wp_list_filter( $response->get_data(), array( 'plugin' => self::PLUGIN_FILE ) ) ); + } + + public function test_get_items_status_multiple() { + $this->create_test_plugin(); + wp_set_current_user( self::$super_admin ); + + $request = new WP_REST_Request( 'GET', self::BASE ); + $request->set_query_params( array( 'status' => array( 'inactive', 'active' ) ) ); + $response = rest_do_request( $request ); + + $this->assertGreaterThan( 1, count( wp_list_filter( $response->get_data(), array( 'plugin' => self::PLUGIN_FILE ), 'NOT' ) ) ); + $this->assertCount( 1, wp_list_filter( $response->get_data(), array( 'plugin' => self::PLUGIN_FILE ) ) ); + } + + /** + * @group ms-required + */ + public function test_get_items_status_network_active() { + $this->create_test_plugin(); + wp_set_current_user( self::$super_admin ); + + $request = new WP_REST_Request( 'GET', self::BASE ); + $request->set_query_params( array( 'status' => 'network-active' ) ); + $response = rest_do_request( $request ); + $this->assertCount( 0, wp_list_filter( $response->get_data(), array( 'plugin' => self::PLUGIN_FILE ) ) ); + + activate_plugin( self::PLUGIN_FILE, '', true ); + $request = new WP_REST_Request( 'GET', self::BASE ); + $request->set_query_params( array( 'status' => 'network-active' ) ); + $response = rest_do_request( $request ); + $this->assertCount( 1, wp_list_filter( $response->get_data(), array( 'plugin' => self::PLUGIN_FILE ) ) ); + } + public function test_get_items_logged_out() { $response = rest_do_request( self::BASE ); $this->assertEquals( 401, $response->get_status() );