WP_REST_Server::READABLE, 'callback' => array( $this, 'get_scan' ), 'permission_callback' => array( $this, 'can_view' ), ), array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'start_scan' ), 'permission_callback' => array( $this, 'can_manage' ), ), ) ); register_rest_route( self::NAMESPACE_V1, '/site-health', array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'site_health' ), 'permission_callback' => array( $this, 'can_view_site_health' ), ) ); } /** * @return bool */ public function can_view_site_health() { return current_user_can( 'view_site_health_checks' ); } /** * Site Health async test: can this site reach Consiva? * * @return WP_REST_Response */ public function site_health() { return new WP_REST_Response( SiteHealthTests::test_reachable(), 200 ); } /** * Starting a scan is a settings action (ยง9.1). * * @return bool */ public function can_manage() { return Capabilities::can_configure(); } /** * Reading scan progress is part of the read-only screens. * * @return bool */ public function can_view() { return Capabilities::can_view(); } /** * GET /scan: progress of the current scan (polled by assets/scan.js). * * @return WP_REST_Response|WP_Error */ public function get_scan() { return self::respond( ScanProgress::current() ); } /** * POST /scan: "Scan again". * * @return WP_REST_Response|WP_Error */ public function start_scan() { return self::respond( ScanProgress::start() ); } /** * @param array|WP_Error $result View or error. * @return WP_REST_Response|WP_Error */ private static function respond( $result ) { if ( ! is_wp_error( $result ) ) { return new WP_REST_Response( $result, 200 ); } $data = $result->get_error_data(); $upstream = is_array( $data ) && isset( $data['status'] ) ? (int) $data['status'] : 0; return new WP_Error( $result->get_error_code(), $result->get_error_message(), array( // 502: Consiva (not this site) failed. The upstream status is passed along for the script. 'status' => TokenStore::is_connected() ? 502 : 409, 'upstream' => $upstream, 'request_id' => is_array( $data ) && isset( $data['request_id'] ) ? (string) $data['request_id'] : '', // The connection was dropped (e.g. a rejected refresh): the page should reload into Connect. 'reconnect' => ! TokenStore::is_connected(), // Plan limits and rate limits will not fix themselves by polling faster. 'retryable' => ! in_array( $upstream, array( 401, 403, 404, 422 ), true ), ) ); } }