From d35e4162b2b051322bc0a46ccd644e52bcdf0b5a Mon Sep 17 00:00:00 2001 From: Barry Kooij Date: Thu, 29 Oct 2026 00:13:49 +0100 Subject: [PATCH 1/4] Added: the plugin tells Scanfully when it is deactivated, disconnected or deleted, and by whom, and its sync answer says its version and how its last requests to Scanfully went, so Scanfully can tell the site's owner why the plugin stopped reporting --- scanfully.php | 5 + src/API/Request.php | 105 ++++++++++++-- src/Connect/Controller.php | 40 +++++- src/Events/Event.php | 5 +- src/Options/Controller.php | 1 + src/Sync/Controller.php | 29 +++- tests/Unit/API/RequestFailureTest.php | 128 ++++++++++++++++++ tests/Unit/API/RequestTlsTest.php | 1 + tests/Unit/Connect/RevokeTokensTest.php | 82 +++++++++-- .../Unit/EmailHealth/FailureHandlingTest.php | 5 +- tests/Unit/EmailHealth/InboundAddressTest.php | 5 +- tests/Unit/EmailHealth/StateCacheTest.php | 5 +- tests/Unit/Sync/ControllerTest.php | 37 ++++- tests/stubs.php | 34 +++++ uninstall.php | 32 ++++- 15 files changed, 482 insertions(+), 32 deletions(-) create mode 100644 tests/Unit/API/RequestFailureTest.php diff --git a/scanfully.php b/scanfully.php index bc4047a..7332faa 100644 --- a/scanfully.php +++ b/scanfully.php @@ -81,6 +81,11 @@ function () { register_deactivation_hook( __FILE__, function () { + // Tell Scanfully first, so the site's owner learns why the plugin + // stopped reporting. + if ( class_exists( '\\Scanfully\\Connect\\Controller' ) ) { + \Scanfully\Connect\Controller::report_deactivated(); + } \Scanfully\Cron\Controller::clear_scheduled_events(); } ); diff --git a/src/API/Request.php b/src/API/Request.php index bcb09fb..aaa8111 100644 --- a/src/API/Request.php +++ b/src/API/Request.php @@ -15,6 +15,19 @@ */ abstract class Request { + /** + * Option holding the plugin's last failed request to Scanfully: when, + * the HTTP status (0 when no answer came) and the error. The sync route + * answers it to the API, so the site's owner learns why the plugin + * stopped reporting. Written only on a failure, never autoloaded. + */ + public const OPTION_LAST_ERROR = 'scanfully_connect_last_request_error'; + + /** + * The longest error text kept. + */ + private const MAX_ERROR_LENGTH = 200; + /** * Send the request to the API. * @@ -53,28 +66,41 @@ public function do_request( string $endpoint, array $data ): ?int { $response = wp_remote_post( $this->get_url( $endpoint ), $request_args ); if ( is_wp_error( $response ) ) { + self::record_failure( 0, self::error_message( $response ) ); return null; } // Only update last_used when we can confirm a successful response. $status = (int) wp_remote_retrieve_response_code( $response ); if ( $status >= 200 && $status < 300 ) { - // A successful request proves the connection works, so clear any - // stale refresh-failure state that would otherwise keep the - // broken-connection notice showing while data is flowing. - \Scanfully\Cron\Controller::clear_refresh_failures(); - try { - $now = new \DateTime(); - $now->setTimezone( new \DateTimeZone( 'UTC' ) ); - OptionController::set_option( 'last_used', $now->format( \Scanfully\Connect\Controller::DATE_FORMAT ) ); - } catch ( \Exception $e ) { - // do nothing for now, just don't break the plugin. - } + self::record_success(); + } else { + self::record_failure( $status, '' ); } return $status; } + /** + * Keep that a request to Scanfully worked: it proves the connection + * works, so any stale refresh-failure state that would keep the + * broken-connection notice showing goes, and last_used says when. The + * sync route answers last_used to the API as the last success, next to + * the last failure, so every kind of request records both. + * + * @return void + */ + private static function record_success(): void { + \Scanfully\Cron\Controller::clear_refresh_failures(); + try { + $now = new \DateTime(); + $now->setTimezone( new \DateTimeZone( 'UTC' ) ); + OptionController::set_option( 'last_used', $now->format( \Scanfully\Connect\Controller::DATE_FORMAT ) ); + } catch ( \Exception $e ) { + // do nothing for now, just don't break the plugin. + } + } + /** * Send the request to the API and return the parsed response. * @@ -164,16 +190,20 @@ public function do_get_request( string $endpoint, array $query = [], int $timeou */ private function process_response( $response ): ?array { if ( is_wp_error( $response ) ) { + self::record_failure( 0, self::error_message( $response ) ); return null; } $status = (int) wp_remote_retrieve_response_code( $response ); $raw_body = wp_remote_retrieve_body( $response ); + if ( $status < 200 || $status >= 300 ) { + self::record_failure( $status, '' ); + } // A successful request proves the connection works, so clear any stale // refresh-failure state that would otherwise keep the broken-connection // notice showing while the plugin is communicating fine. if ( $status >= 200 && $status < 300 ) { - \Scanfully\Cron\Controller::clear_refresh_failures(); + self::record_success(); } $decoded = null; @@ -190,6 +220,57 @@ private function process_response( $response ): ?array { ]; } + /** + * Keep a failed request to Scanfully: an answer with a status outside + * 2xx, or none at all, with the transport's error. + * + * @param int $status The HTTP status; 0 when no answer came. + * @param string $message The error of a request that got no answer. + * + * @return void + */ + private static function record_failure( int $status, string $message ): void { + update_option( + self::OPTION_LAST_ERROR, + [ + 'at' => time(), + 'status' => $status, + 'message' => mb_substr( trim( $message ), 0, self::MAX_ERROR_LENGTH ), + ], + false + ); + } + + /** + * The message of a transport error, or '' when it holds none. + * + * @param mixed $error What is_wp_error() took for an error. + * + * @return string + */ + private static function error_message( $error ): string { + return $error instanceof \WP_Error ? $error->get_error_message() : ''; + } + + /** + * The plugin's last failed request to Scanfully, or null when none + * failed since the site connected. + * + * @return array{at: int, status: int, message: string}|null + */ + public static function last_error(): ?array { + $error = get_option( self::OPTION_LAST_ERROR ); + if ( ! is_array( $error ) || ! isset( $error['at'] ) ) { + return null; + } + + return [ + 'at' => (int) $error['at'], + 'status' => (int) ( $error['status'] ?? 0 ), + 'message' => (string) ( $error['message'] ?? '' ), + ]; + } + /** * Get the auth headers for the request. * diff --git a/src/Connect/Controller.php b/src/Connect/Controller.php index 355a7bb..8ff6c5d 100644 --- a/src/Connect/Controller.php +++ b/src/Connect/Controller.php @@ -427,21 +427,55 @@ public static function refresh_access_token( string $refresh_token, string $site * a database dump) stays valid on the API side until it expires. * * Best effort: a failure never blocks the disconnect, and the timeout is - * short so an unreachable API doesn't hold up the admin. + * short so an unreachable API doesn't hold up the admin. It says the + * site was disconnected, and by whom, so the site's owner learns why the + * plugin stopped reporting. * * @return void */ public static function revoke_tokens(): void { + self::tell_connection( 'revoke', [ 'reason' => 'disconnected' ] ); + } + + /** + * Tell the API that the plugin is being deactivated, and by whom, so the + * site's owner learns why the plugin stopped reporting. Called from the + * deactivation hook, before the jobs are cancelled. The tokens stay: + * activating the plugin again lets it report with them. + * + * @return void + */ + public static function report_deactivated(): void { + self::tell_connection( 'deactivated', [] ); + } + + /** + * Send a request about the connection itself to the API: the revoke or + * the deactivation, with who did it. Best effort with a short timeout: + * it never blocks what the user is doing. + * + * @param string $action The connect route: revoke or deactivated. + * @param array $body What the request says, besides who did it. + * + * @return void + */ + private static function tell_connection( string $action, array $body ): void { $site_id = OptionsController::get_option( 'site_id' ); $access_token = OptionsController::get_option( 'access_token' ); if ( '' === $site_id || '' === $access_token ) { return; } + $body['by'] = \Scanfully\Events\Event::safe_display_name( wp_get_current_user() ); + wp_remote_post( - Main::get_api_url() . '/sites/' . rawurlencode( $site_id ) . '/connect/revoke', + Main::get_api_url() . '/sites/' . rawurlencode( $site_id ) . '/connect/' . $action, [ - 'headers' => [ 'Authorization' => sprintf( 'Bearer %s', $access_token ) ], + 'headers' => [ + 'Authorization' => sprintf( 'Bearer %s', $access_token ), + 'Content-Type' => 'application/json', + ], + 'body' => wp_json_encode( $body ), 'timeout' => 5, 'blocking' => true, 'httpversion' => '1.0', diff --git a/src/Events/Event.php b/src/Events/Event.php index 4f87935..ed56e5a 100644 --- a/src/Events/Event.php +++ b/src/Events/Event.php @@ -107,13 +107,14 @@ protected function get_actor( array $args ): ?object { * A user's display name, safe to send. WordPress defaults the display * name to the login, which is often an email address; an email address * is replaced by the user's first and last name, or left empty, so no - * email address leaves the site. + * email address leaves the site. Public, as the connection's own + * requests name who deactivated or disconnected the plugin the same way. * * @param object $user The user (a WP_User). * * @return string */ - protected static function safe_display_name( object $user ): string { + public static function safe_display_name( object $user ): string { $name = trim( (string) ( $user->display_name ?? '' ) ); if ( ! self::looks_like_email( $name ) ) { return $name; diff --git a/src/Options/Controller.php b/src/Options/Controller.php index d0af3d2..d6f2752 100644 --- a/src/Options/Controller.php +++ b/src/Options/Controller.php @@ -143,6 +143,7 @@ public static function clear() { delete_option( self::$db_prefix . 'expires' ); delete_option( self::$db_prefix . 'last_used' ); delete_option( self::$db_prefix . 'date_connected' ); + delete_option( self::$db_prefix . 'last_request_error' ); // Email deliverability sub-feature: per-site secret + cached state. delete_option( self::$db_prefix . 'email_deliverability_enabled' ); diff --git a/src/Sync/Controller.php b/src/Sync/Controller.php index 7053ff8..d175dac 100644 --- a/src/Sync/Controller.php +++ b/src/Sync/Controller.php @@ -129,7 +129,7 @@ public static function handle_sync(): \WP_REST_Response { if ( $last_run > 0 ) { $retry_after = max( 1, self::RATE_LIMIT_WINDOW - ( time() - $last_run ) ); - $response = new \WP_REST_Response( [ 'status' => 'rate_limited' ], 429 ); + $response = new \WP_REST_Response( array_merge( [ 'status' => 'rate_limited' ], self::diagnostics() ), 429 ); $response->header( 'Retry-After', (string) $retry_after ); return $response; @@ -140,7 +140,32 @@ public static function handle_sync(): \WP_REST_Response { self::schedule_syncs(); self::run_queue_now(); - return new \WP_REST_Response( [ 'status' => 'scheduled' ], 202 ); + return new \WP_REST_Response( array_merge( [ 'status' => 'scheduled' ], self::diagnostics() ), 202 ); + } + + /** + * What the plugin tells the API about itself in the answer: its version, + * when its last request to Scanfully worked and its last one that + * failed. The answer comes from this web request, so it gets through + * when the plugin's scheduled jobs do not run. Only the token holder (the + * API) gets it, and it holds no site data. + * + * @return array + */ + private static function diagnostics(): array { + $last_used = Options\Controller::get_option( 'last_used' ); + $last_error = \Scanfully\API\Request::last_error(); + $used_at = '' === $last_used ? false : strtotime( $last_used . ' UTC' ); + + return [ + 'version' => defined( 'SCANFULLY_VERSION' ) ? SCANFULLY_VERSION : '', + 'last_success_at' => false === $used_at ? null : gmdate( 'c', $used_at ), + 'last_error' => null === $last_error ? null : [ + 'at' => gmdate( 'c', $last_error['at'] ), + 'status' => $last_error['status'], + 'message' => $last_error['message'], + ], + ]; } /** diff --git a/tests/Unit/API/RequestFailureTest.php b/tests/Unit/API/RequestFailureTest.php new file mode 100644 index 0000000..9c9d116 --- /dev/null +++ b/tests/Unit/API/RequestFailureTest.php @@ -0,0 +1,128 @@ + + */ + private array $options = []; + + /** + * What the next request answers: a response array or a WP_Error. + * + * @var mixed + */ + private $answer; + + protected function setUp(): void { + parent::setUp(); + $this->options = []; + $this->answer = [ 'response' => [ 'code' => 200 ] ]; + + Functions\when( 'get_option' )->alias( fn( string $name, $default = false ) => array_key_exists( $name, $this->options ) ? $this->options[ $name ] : $default ); + Functions\when( 'update_option' )->alias( + function ( string $name, $value ) { + $this->options[ $name ] = $value; + return true; + } + ); + Functions\when( 'wp_remote_post' )->alias( fn() => $this->answer ); + Functions\when( 'is_wp_error' )->alias( static fn( $thing ) => $thing instanceof \WP_Error ); + Functions\when( 'wp_remote_retrieve_response_code' )->alias( static fn( $response ) => $response['response']['code'] ); + Functions\when( 'wp_remote_retrieve_body' )->justReturn( '' ); + Functions\when( 'wp_json_encode' )->alias( static fn( $data ) => json_encode( $data ) ); // phpcs:ignore WordPress.WP.AlternativeFunctions.json_encode_json_encode -- WordPress is not loaded in unit tests. + Functions\when( 'delete_transient' )->justReturn( true ); + } + + /** + * A minimal concrete request. + * + * @return Request + */ + private function make_request(): Request { + return new class() extends Request { + /** + * Get the url for the request. + * + * @param string $endpoint The endpoint. + * + * @return string + */ + public function get_url( string $endpoint ): string { + return 'https://api.scanfully.test/' . $endpoint; + } + + /** + * Get the body for the request. + * + * @param array $data The data. + * + * @return array + */ + public function get_body( array $data ): array { + return $data; + } + }; + } + + public function test_a_request_without_an_answer_keeps_its_error(): void { + $this->answer = new \WP_Error( 'http_request_failed', 'cURL error 28: Operation timed out after 60001 milliseconds' ); + + $this->assertNull( $this->make_request()->do_request( 'sites/s1/data', [] ) ); + + $error = Request::last_error(); + $this->assertNotNull( $error ); + $this->assertSame( 0, $error['status'] ); + $this->assertSame( 'cURL error 28: Operation timed out after 60001 milliseconds', $error['message'] ); + $this->assertGreaterThan( 0, $error['at'] ); + } + + public function test_an_error_status_keeps_the_status(): void { + $this->answer = [ 'response' => [ 'code' => 503 ] ]; + + $this->make_request()->do_request_with_response( 'sites/s1/email', [] ); + + $this->assertSame( 503, Request::last_error()['status'] ?? null ); + } + + public function test_a_long_error_is_cut(): void { + $this->answer = new \WP_Error( 'http_request_failed', str_repeat( 'x', 500 ) ); + + $this->make_request()->do_request( 'sites/s1/data', [] ); + + $this->assertSame( 200, strlen( Request::last_error()['message'] ?? '' ) ); + } + + public function test_a_success_keeps_when_and_leaves_the_last_error(): void { + $this->options[ Request::OPTION_LAST_ERROR ] = [ + 'at' => 1000, + 'status' => 503, + 'message' => '', + ]; + + $this->assertSame( 200, $this->make_request()->do_request( 'sites/s1/data', [] ) ); + + $this->assertArrayHasKey( 'scanfully_connect_last_used', $this->options ); + $this->assertSame( 1000, Request::last_error()['at'] ?? null ); + } + + public function test_no_error_before_any_failed(): void { + $this->assertNull( Request::last_error() ); + } +} diff --git a/tests/Unit/API/RequestTlsTest.php b/tests/Unit/API/RequestTlsTest.php index 91ae78c..2123834 100644 --- a/tests/Unit/API/RequestTlsTest.php +++ b/tests/Unit/API/RequestTlsTest.php @@ -41,6 +41,7 @@ protected function setUp(): void { Functions\when( 'is_wp_error' )->alias( static fn( $thing ) => null === $thing ); Functions\when( 'wp_json_encode' )->alias( static fn( $data ) => json_encode( $data ) ); // phpcs:ignore WordPress.WP.AlternativeFunctions.json_encode_json_encode -- WordPress is not loaded in unit tests. Functions\when( 'get_option' )->justReturn( 'token' ); + Functions\when( 'update_option' )->justReturn( true ); Functions\when( 'add_query_arg' )->alias( static fn( $args, $url ) => $url ); } diff --git a/tests/Unit/Connect/RevokeTokensTest.php b/tests/Unit/Connect/RevokeTokensTest.php index 6ea3839..f18192d 100644 --- a/tests/Unit/Connect/RevokeTokensTest.php +++ b/tests/Unit/Connect/RevokeTokensTest.php @@ -13,6 +13,7 @@ /** * @covers \Scanfully\Connect\Controller::revoke_tokens + * @covers \Scanfully\Connect\Controller::report_deactivated */ final class RevokeTokensTest extends TestCase { @@ -23,36 +24,101 @@ final class RevokeTokensTest extends TestCase { */ private array $options = []; + /** + * The signed-in user. + * + * @var object + */ + private object $user; + protected function setUp(): void { parent::setUp(); $this->options = []; + $this->user = (object) [ + 'ID' => 7, + 'display_name' => 'Jane', + 'first_name' => 'Jane', + 'last_name' => 'Doe', + ]; Functions\when( 'get_option' )->alias( fn( string $name ) => array_key_exists( $name, $this->options ) ? $this->options[ $name ] : false ); + Functions\when( 'wp_get_current_user' )->alias( fn() => $this->user ); + Functions\when( 'wp_json_encode' )->alias( static fn( $data ) => json_encode( $data ) ); // phpcs:ignore WordPress.WP.AlternativeFunctions.json_encode_json_encode -- WordPress is not loaded in unit tests. + Functions\when( 'is_email' )->alias( static fn( $value ) => false !== filter_var( $value, FILTER_VALIDATE_EMAIL ) ? $value : false ); } - public function test_it_revokes_the_tokens_of_a_connected_site(): void { - $this->options = [ - 'scanfully_connect_site_id' => 'site-123', - 'scanfully_connect_access_token' => 'access-abc', - ]; - + /** + * Expect one request to a connect route of site-123, with the body. + * + * @param string $route The connect route. + * @param array $body The body it must send. + * + * @return void + */ + private function expect_request( string $route, array $body ): void { Functions\expect( 'wp_remote_post' ) ->once() ->with( - 'https://api.scanfully.com/v1/sites/site-123/connect/revoke', + 'https://api.scanfully.com/v1/sites/site-123/connect/' . $route, \Mockery::on( - static function ( array $args ): bool { + static function ( array $args ) use ( $body ): bool { return 'Bearer access-abc' === $args['headers']['Authorization'] + && 'application/json' === $args['headers']['Content-Type'] + && json_decode( $args['body'], true ) === $body && $args['timeout'] <= 5 && true === $args['sslverify']; } ) ) ->andReturn( [ 'response' => [ 'code' => 204 ] ] ); + } + + public function test_it_revokes_the_tokens_of_a_connected_site(): void { + $this->options = [ + 'scanfully_connect_site_id' => 'site-123', + 'scanfully_connect_access_token' => 'access-abc', + ]; + $this->expect_request( + 'revoke', + [ + 'reason' => 'disconnected', + 'by' => 'Jane', + ] + ); Controller::revoke_tokens(); $this->addToAssertionCount( 1 ); } + public function test_a_deactivation_is_reported_with_who_did_it(): void { + $this->options = [ + 'scanfully_connect_site_id' => 'site-123', + 'scanfully_connect_access_token' => 'access-abc', + ]; + $this->expect_request( 'deactivated', [ 'by' => 'Jane' ] ); + + Controller::report_deactivated(); + $this->addToAssertionCount( 1 ); + } + + public function test_no_email_address_leaves_the_site(): void { + $this->options = [ + 'scanfully_connect_site_id' => 'site-123', + 'scanfully_connect_access_token' => 'access-abc', + ]; + $this->user->display_name = 'jane@scanfully.com'; + $this->expect_request( 'deactivated', [ 'by' => 'Jane Doe' ] ); + + Controller::report_deactivated(); + $this->addToAssertionCount( 1 ); + } + + public function test_a_deactivation_without_a_connection_sends_nothing(): void { + Functions\expect( 'wp_remote_post' )->never(); + + Controller::report_deactivated(); + $this->addToAssertionCount( 1 ); + } + /** * @dataProvider provide_incomplete_connections * diff --git a/tests/Unit/EmailHealth/FailureHandlingTest.php b/tests/Unit/EmailHealth/FailureHandlingTest.php index dca15de..eee2ac3 100644 --- a/tests/Unit/EmailHealth/FailureHandlingTest.php +++ b/tests/Unit/EmailHealth/FailureHandlingTest.php @@ -86,7 +86,10 @@ function ( string $name, $default = false ) { ); Functions\when( 'update_option' )->alias( function ( string $name, $value ) { - $this->options[ self::key( $name ) ] = (string) $value; + // The request's own record of its last failure is not an email health option. + if ( \Scanfully\API\Request::OPTION_LAST_ERROR !== $name ) { + $this->options[ self::key( $name ) ] = (string) $value; + } return true; } ); diff --git a/tests/Unit/EmailHealth/InboundAddressTest.php b/tests/Unit/EmailHealth/InboundAddressTest.php index e5220f0..dd30d2d 100644 --- a/tests/Unit/EmailHealth/InboundAddressTest.php +++ b/tests/Unit/EmailHealth/InboundAddressTest.php @@ -121,7 +121,10 @@ public function test_provisioning_ignores_an_address_outside_scanfully(): void { Functions\when( 'get_option' )->justReturn( 'site-1' ); Functions\when( 'update_option' )->alias( static function ( string $name, $value ) use ( &$saved ) { - $saved[ $name ] = $value; + // When the connection last worked is not stored from the response. + if ( 'scanfully_connect_last_used' !== $name ) { + $saved[ $name ] = $value; + } return true; } ); diff --git a/tests/Unit/EmailHealth/StateCacheTest.php b/tests/Unit/EmailHealth/StateCacheTest.php index f6f87b2..7adfb7d 100644 --- a/tests/Unit/EmailHealth/StateCacheTest.php +++ b/tests/Unit/EmailHealth/StateCacheTest.php @@ -54,7 +54,10 @@ protected function setUp(): void { Functions\when( 'get_option' )->justReturn( 'site-1' ); Functions\when( 'update_option' )->alias( function ( string $name, $value ) { - $this->saved[ $name ] = (string) $value; + // The request's own record of its last failure is not the cache. + if ( \Scanfully\API\Request::OPTION_LAST_ERROR !== $name ) { + $this->saved[ $name ] = (string) $value; + } return true; } ); diff --git a/tests/Unit/Sync/ControllerTest.php b/tests/Unit/Sync/ControllerTest.php index 3e9e22c..cf86b13 100644 --- a/tests/Unit/Sync/ControllerTest.php +++ b/tests/Unit/Sync/ControllerTest.php @@ -23,7 +23,7 @@ final class ControllerTest extends TestCase { /** * Stored options, keyed by option name without prefix. * - * @var array + * @var array */ private array $options = []; @@ -138,6 +138,41 @@ public function test_a_sync_starts_the_queue_runner_now(): void { $this->assertSame( [ 'async-request-runner' ], $GLOBALS['scanfully_test_action_scheduler']['locks'] ); } + public function test_a_sync_answers_how_the_plugin_reaches_scanfully(): void { + $this->options['last_used'] = '2026-10-28 03:00:00'; + $this->options['last_request_error'] = [ + 'at' => 1793181600, + 'status' => 0, + 'message' => 'cURL error 28: Operation timed out', + ]; + + $data = Controller::handle_sync()->get_data(); + + $this->assertSame( 'scheduled', $data['status'] ); + $this->assertSame( SCANFULLY_VERSION, $data['version'] ); + $this->assertSame( '2026-10-28T03:00:00+00:00', $data['last_success_at'] ); + $this->assertSame( + [ + 'at' => '2026-10-28T10:00:00+00:00', + 'status' => 0, + 'message' => 'cURL error 28: Operation timed out', + ], + $data['last_error'] + ); + + // A rate limited sync answers the same. + $data = Controller::handle_sync()->get_data(); + $this->assertSame( 'rate_limited', $data['status'] ); + $this->assertSame( SCANFULLY_VERSION, $data['version'] ); + } + + public function test_a_sync_before_any_request_answers_nulls(): void { + $data = Controller::handle_sync()->get_data(); + + $this->assertNull( $data['last_success_at'] ); + $this->assertNull( $data['last_error'] ); + } + public function test_a_second_sync_within_the_window_is_rate_limited(): void { Controller::handle_sync(); $response = Controller::handle_sync(); diff --git a/tests/stubs.php b/tests/stubs.php index a693500..c4d69c1 100644 --- a/tests/stubs.php +++ b/tests/stubs.php @@ -104,6 +104,40 @@ public function get_header( $key ) { } } + if ( ! class_exists( 'WP_Error' ) ) { + /** + * Stub of WordPress' error, with its message. + */ + class WP_Error { + + /** + * The error message. + * + * @var string + */ + private string $message; + + /** + * Constructor. + * + * @param string $code Error code. + * @param string $message Error message. + */ + public function __construct( $code = '', $message = '' ) { + $this->message = (string) $message; + } + + /** + * Get the error message. + * + * @return string + */ + public function get_error_message() { + return $this->message; + } + } + } + if ( ! class_exists( 'WP_REST_Response' ) ) { /** * Stub of WordPress' REST response. diff --git a/uninstall.php b/uninstall.php index e814976..8e9c7f3 100644 --- a/uninstall.php +++ b/uninstall.php @@ -45,10 +45,21 @@ function scanfully_uninstall_revoke_tokens(): void { $api_url = (string) apply_filters( 'scanfully_api_url', 'https://api.scanfully.com/v1' ); + // Say the plugin was deleted, and by whom, so the site's owner learns why + // it stopped reporting. wp_remote_post( $api_url . '/sites/' . rawurlencode( $site_id ) . '/connect/revoke', [ - 'headers' => [ 'Authorization' => sprintf( 'Bearer %s', $access_token ) ], + 'headers' => [ + 'Authorization' => sprintf( 'Bearer %s', $access_token ), + 'Content-Type' => 'application/json', + ], + 'body' => wp_json_encode( + [ + 'reason' => 'uninstalled', + 'by' => scanfully_uninstall_user_name(), + ] + ), 'timeout' => 5, 'blocking' => true, 'httpversion' => '1.0', @@ -57,6 +68,25 @@ function scanfully_uninstall_revoke_tokens(): void { ); } +/** + * The display name of the user who deletes the plugin, safe to send: as + * Events\Event::safe_display_name(), a name that holds an @ is replaced by + * the user's first and last name, or left empty, so no email address leaves + * the site. + * + * @return string + */ +function scanfully_uninstall_user_name(): string { + $user = wp_get_current_user(); + $name = trim( (string) $user->display_name ); + if ( false === strpos( $name, '@' ) ) { + return $name; + } + $name = trim( $user->first_name . ' ' . $user->last_name ); + + return false === strpos( $name, '@' ) ? $name : ''; +} + /** * Delete the WooCheckout probe user, but only when it is still the account the * plugin created: a `scanfully_probe` login, an @scanfully.invalid email and From cec8c1dcb9d9490ce831f3ac0e20151d75a70071 Mon Sep 17 00:00:00 2001 From: Barry Kooij Date: Fri, 30 Oct 2026 12:57:15 +0100 Subject: [PATCH 2/4] Fixed: a request Scanfully answers with 400 or 429 no longer counts as the plugin failing to reach Scanfully --- src/API/Request.php | 10 ++++++++-- tests/Unit/API/RequestFailureTest.php | 21 +++++++++++++++++++++ 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/src/API/Request.php b/src/API/Request.php index aaa8111..4899eb6 100644 --- a/src/API/Request.php +++ b/src/API/Request.php @@ -221,8 +221,10 @@ private function process_response( $response ): ?array { } /** - * Keep a failed request to Scanfully: an answer with a status outside - * 2xx, or none at all, with the transport's error. + * Keep a failed request to Scanfully: no answer at all, with the + * transport's error, or an answer that says it did not get through. + * Scanfully answering 400 or 429 about one request does not count: the + * connection works, and the API would tell the site's owner it doesn't. * * @param int $status The HTTP status; 0 when no answer came. * @param string $message The error of a request that got no answer. @@ -230,6 +232,10 @@ private function process_response( $response ): ?array { * @return void */ private static function record_failure( int $status, string $message ): void { + if ( $status >= 400 && $status < 500 && ! in_array( $status, [ 401, 403, 407 ], true ) ) { + return; + } + update_option( self::OPTION_LAST_ERROR, [ diff --git a/tests/Unit/API/RequestFailureTest.php b/tests/Unit/API/RequestFailureTest.php index 9c9d116..1931894 100644 --- a/tests/Unit/API/RequestFailureTest.php +++ b/tests/Unit/API/RequestFailureTest.php @@ -101,6 +101,27 @@ public function test_an_error_status_keeps_the_status(): void { $this->assertSame( 503, Request::last_error()['status'] ?? null ); } + public function test_a_refusal_of_the_connection_is_kept(): void { + foreach ( [ 401, 403, 407 ] as $status ) { + $this->answer = [ 'response' => [ 'code' => $status ] ]; + + $this->make_request()->do_request( 'sites/s1/data', [] ); + + $this->assertSame( $status, Request::last_error()['status'] ?? null ); + } + } + + public function test_an_answer_about_one_request_is_not_a_failure_to_reach_scanfully(): void { + foreach ( [ 400, 404, 409, 422, 429 ] as $status ) { + $this->answer = [ 'response' => [ 'code' => $status ] ]; + + $this->make_request()->do_request( 'sites/s1/timeline', [] ); + $this->make_request()->do_request_with_response( 'sites/s1/email', [] ); + + $this->assertNull( Request::last_error(), "status $status" ); + } + } + public function test_a_long_error_is_cut(): void { $this->answer = new \WP_Error( 'http_request_failed', str_repeat( 'x', 500 ) ); From 8eb384fb171927ead0f83c997cec5512653fbd0c Mon Sep 17 00:00:00 2001 From: Barry Kooij Date: Sat, 31 Oct 2026 21:42:13 +0100 Subject: [PATCH 3/4] Fixed: wp-admin no longer asks to reconnect right after activating the plugin, and the first email ping goes about a minute after it --- scanfully.php | 10 ++++++++++ src/Connect/AdminNotice.php | 5 +++++ src/Cron/Controller.php | 7 ++++--- 3 files changed, 19 insertions(+), 3 deletions(-) diff --git a/scanfully.php b/scanfully.php index 7332faa..73b1702 100644 --- a/scanfully.php +++ b/scanfully.php @@ -77,6 +77,16 @@ function () { 20 ); +// register activation hook. +register_activation_hook( + __FILE__, + function () { + // The connection was last used before the deactivation, so its first + // report needs a moment before anything calls it stale. + set_transient( 'scanfully_recently_activated', 1, 5 * MINUTE_IN_SECONDS ); + } +); + // register deactivation hook. register_deactivation_hook( __FILE__, diff --git a/src/Connect/AdminNotice.php b/src/Connect/AdminNotice.php index 384635f..4c0826d 100644 --- a/src/Connect/AdminNotice.php +++ b/src/Connect/AdminNotice.php @@ -74,6 +74,11 @@ private static function is_connection_stale( \Scanfully\Options\Options $options return true; } + // Just activated: it hasn't had the chance to report yet. + if ( get_transient( 'scanfully_recently_activated' ) ) { + return false; + } + $reference_date = $options->last_used; // Fall back to date_connected if last_used is empty. diff --git a/src/Cron/Controller.php b/src/Cron/Controller.php index d5f8c32..78a3574 100644 --- a/src/Cron/Controller.php +++ b/src/Cron/Controller.php @@ -198,10 +198,11 @@ public static function schedule_events(): void { // Email deliverability runs as a self-scheduling single action (each run // arms the next via EmailHealth\Controller::schedule_next_ping) so the // cadence can adapt without the duplicate pending actions a recurring - // action produced. This only bootstraps the chain, or heals it if it stalls. + // action produced. This only bootstraps the chain, or heals it if it stalls, + // so the first ping goes soon: after activating the plugin again, the Email + // page should not wait a whole interval for it. if ( ! as_has_scheduled_action( self::ACTION_EMAIL_DELIVERABILITY_PING, [], self::AS_GROUP ) ) { - $interval = \Scanfully\EmailHealth\Controller::current_interval_seconds(); - as_schedule_single_action( time() + $interval, self::ACTION_EMAIL_DELIVERABILITY_PING, [], self::AS_GROUP, true ); + as_schedule_single_action( time() + MINUTE_IN_SECONDS, self::ACTION_EMAIL_DELIVERABILITY_PING, [], self::AS_GROUP, true ); } if ( ! as_has_scheduled_action( self::ACTION_SYNC_WOOCHECKOUT_CONFIG, [], self::AS_GROUP ) ) { From f1ad6c9d05cd6656b8414ac0d77463c2c5ac751c Mon Sep 17 00:00:00 2001 From: Barry Kooij Date: Mon, 2 Nov 2026 20:35:58 +0100 Subject: [PATCH 4/4] Changed: version 1.10.0, with its changelog in the readme and the new connection data under External services --- readme.txt | 10 +++++++++- scanfully.php | 4 ++-- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/readme.txt b/readme.txt index e12e9d1..8b65e2c 100644 --- a/readme.txt +++ b/readme.txt @@ -4,7 +4,7 @@ Donate link: https://scanfully.com Tags: monitoring, site health, broken links, broken media, activity log Requires at least: 6.0 Tested up to: 7.1.0 -Stable tag: 1.9.1 +Stable tag: 1.10.0 License: GPLv3 or later License URI: http://www.gnu.org/licenses/gpl-3.0.html Requires PHP: 7.4 @@ -216,6 +216,8 @@ Once connected, the plugin sends data to the Scanfully API at api.scanfully.com * For accounts with elevated rights only: their email address with their user events, and the IP address and browser of their logins and of the first use of an application password. * Failed logins as counts per hour, with the accounts with elevated rights that were tried, but without IP addresses or the usernames tried. * When WooCommerce is active: the shop details a test checkout needs, such as the product, shipping method and checkout page, on connect, once a day and when they change. Scanfully only places test orders when WooCommerce checkout monitoring is on for the site, and the plugin cancels and removes them. +* When the plugin is deactivated, disconnected or deleted: that it happened, and the display name of the person who did it. +* When Scanfully asks the plugin to sync: the plugin's version, when its last request to Scanfully succeeded, and the time, status and error message of its last failed request. Email deliverability checks are on by default: the plugin sends test emails to a Scanfully address through your site's own mail setup. You can turn them off under Settings > Scanfully. @@ -226,6 +228,12 @@ Scanfully's [terms and conditions](https://scanfully.com/terms/) and [privacy po == Changelog == += 1.10.0: November 2, 2026 = +* Added: the plugin tells Scanfully when it is deactivated, disconnected or deleted, and by whom, so Scanfully can say why a site stopped reporting +* Added: when Scanfully asks the plugin to sync, the plugin answers with its version and how its last requests to Scanfully went +* Fixed: wp-admin no longer asks to reconnect right after activating the plugin, and the first email ping goes about a minute after it +* Fixed: a request Scanfully answers with 400 or 429 no longer counts as the plugin failing to reach Scanfully + = 1.9.1: October 27, 2026 = * Fixed: the WooCommerce checkout test reported a false failure on shops with Mollie * Fixed: test orders of the WooCommerce checkout test no longer email the shop a cancelled order notice, which WooCommerce 11 started sending, and no other WooCommerce email is sent about a test order diff --git a/scanfully.php b/scanfully.php index 73b1702..5204d34 100644 --- a/scanfully.php +++ b/scanfully.php @@ -8,7 +8,7 @@ * * @wordpress-plugin * Plugin Name: Scanfully - * Version: 1.9.1 + * Version: 1.10.0 * Plugin URI: https://scanfully.com/wp-plugin * Description: Scanfully is your favorite WordPress performance and health monitoring tool. * Author: Scanfully @@ -68,7 +68,7 @@ function Scanfully(): \Scanfully\Main { // phpcs:ignore WordPress.NamingConventi function () { // meta. define( 'SCANFULLY_PLUGIN_FILE', __FILE__ ); - define( 'SCANFULLY_VERSION', '1.9.1' ); + define( 'SCANFULLY_VERSION', '1.10.0' ); // boot. require __DIR__ . '/vendor/autoload.php';