From c15de9058b901810d36366797cc257b6bbed2d41 Mon Sep 17 00:00:00 2001 From: Barry Kooij Date: Sat, 7 Nov 2026 01:25:25 +0100 Subject: [PATCH 1/7] Added: PHP error monitoring: fatal errors and warnings are caught from before other plugins load, grouped and counted, credited to the plugin, theme or WordPress core that raised them, and sent to Scanfully with emails, keys, passwords and query strings removed --- scanfully.php | 18 +- src/API/ErrorsRequest.php | 51 +++ src/API/Request.php | 5 +- src/Cron/Controller.php | 23 ++ src/Errors/Attribution.php | 498 ++++++++++++++++++++++++ src/Errors/Builder.php | 194 +++++++++ src/Errors/Context.php | 141 +++++++ src/Errors/Controller.php | 167 ++++++++ src/Errors/Fingerprint.php | 67 ++++ src/Errors/Monitor.php | 518 +++++++++++++++++++++++++ src/Errors/MuPlugin.php | 246 ++++++++++++ src/Errors/Reporter.php | 210 ++++++++++ src/Errors/Scrubber.php | 86 ++++ src/Errors/Store.php | 473 ++++++++++++++++++++++ src/Errors/load.php | 32 ++ src/Health/Controller.php | 2 + src/Health/MuPlugins.php | 19 +- src/Main.php | 3 + tests/Unit/Cron/ScheduleEventsTest.php | 2 +- tests/Unit/Errors/AttributionTest.php | 236 +++++++++++ tests/Unit/Errors/BuilderTest.php | 230 +++++++++++ tests/Unit/Errors/ContextTest.php | 107 +++++ tests/Unit/Errors/FingerprintTest.php | 43 ++ tests/Unit/Errors/MonitorTest.php | 167 ++++++++ tests/Unit/Errors/ReporterTest.php | 108 ++++++ tests/Unit/Errors/ScrubberTest.php | 71 ++++ uninstall.php | 20 + 27 files changed, 3730 insertions(+), 7 deletions(-) create mode 100644 src/API/ErrorsRequest.php create mode 100644 src/Errors/Attribution.php create mode 100644 src/Errors/Builder.php create mode 100644 src/Errors/Context.php create mode 100644 src/Errors/Controller.php create mode 100644 src/Errors/Fingerprint.php create mode 100644 src/Errors/Monitor.php create mode 100644 src/Errors/MuPlugin.php create mode 100644 src/Errors/Reporter.php create mode 100644 src/Errors/Scrubber.php create mode 100644 src/Errors/Store.php create mode 100644 src/Errors/load.php create mode 100644 tests/Unit/Errors/AttributionTest.php create mode 100644 tests/Unit/Errors/BuilderTest.php create mode 100644 tests/Unit/Errors/ContextTest.php create mode 100644 tests/Unit/Errors/FingerprintTest.php create mode 100644 tests/Unit/Errors/MonitorTest.php create mode 100644 tests/Unit/Errors/ReporterTest.php create mode 100644 tests/Unit/Errors/ScrubberTest.php diff --git a/scanfully.php b/scanfully.php index 5204d34..3824682 100644 --- a/scanfully.php +++ b/scanfully.php @@ -40,6 +40,11 @@ // Load Action Scheduler before plugins_loaded priority 0 so it can register its version. require __DIR__ . '/vendor/woocommerce/action-scheduler/action-scheduler.php'; +// Catch PHP errors from here on. The must-use plugin, when it could be +// installed, already does from before any plugin loads. +require_once __DIR__ . '/src/Errors/load.php'; +\Scanfully\Errors\Monitor::boot( 'plugin' ); + // Declare compatibility with WooCommerce's HPOS order storage and the // Cart/Checkout blocks. WooCommerce only accepts this inside // before_woocommerce_init. @@ -81,6 +86,10 @@ function () { register_activation_hook( __FILE__, function () { + // A connection that stayed while the plugin was inactive catches PHP + // errors again from before other plugins load. + \Scanfully\Errors\MuPlugin::maybe_install(); + // 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 ); @@ -90,12 +99,19 @@ function () { // register deactivation hook. register_deactivation_hook( __FILE__, - function () { + function ( $network_wide = false ) { // 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(); + + // The must-use plugin serves the whole network: remove it when the + // plugin is deactivated on a single site or for the whole network. + // On a network site it does nothing while the plugin is inactive there. + if ( ! is_multisite() || $network_wide ) { + \Scanfully\Errors\MuPlugin::remove(); + } } ); diff --git a/src/API/ErrorsRequest.php b/src/API/ErrorsRequest.php new file mode 100644 index 0000000..d8154af --- /dev/null +++ b/src/API/ErrorsRequest.php @@ -0,0 +1,51 @@ + $headers, - 'timeout' => 60, + 'timeout' => $timeout, 'blocking' => true, 'httpversion' => '1.0', 'sslverify' => Main::get_sslverify(), diff --git a/src/Cron/Controller.php b/src/Cron/Controller.php index 5b5ee0b..b4d9284 100644 --- a/src/Cron/Controller.php +++ b/src/Cron/Controller.php @@ -55,6 +55,12 @@ class Controller { */ public const ACTION_CHECK_MU_PLUGINS = 'scanfully_check_mu_plugins'; + /** + * Hook: send the PHP errors that are waiting (recurring hourly, and + * single runs a minute after a new error and right after an update). + */ + public const ACTION_SEND_PHP_ERRORS = \Scanfully\Errors\Reporter::ACTION; + /** * Args marker for debounced (single) site health runs, to distinguish them * from the recurring schedule so each can be managed independently. @@ -90,6 +96,7 @@ public static function setup(): void { add_action( self::ACTION_CLEANUP_PROBE_ORDERS, [ self::class, 'cleanup_woocheckout_probe_orders' ] ); add_action( self::ACTION_SEND_FAILED_LOGINS, [ self::class, 'send_failed_logins' ] ); add_action( self::ACTION_CHECK_MU_PLUGINS, [ self::class, 'check_mu_plugins' ] ); + add_action( self::ACTION_SEND_PHP_ERRORS, [ self::class, 'send_php_errors' ] ); // Register hooks that trigger a debounced site health sync. self::register_health_sync_hooks(); @@ -221,6 +228,11 @@ public static function schedule_events(): void { if ( ! as_has_scheduled_action( self::ACTION_CHECK_MU_PLUGINS, [], self::AS_GROUP ) ) { as_schedule_recurring_action( time() + HOUR_IN_SECONDS, HOUR_IN_SECONDS, self::ACTION_CHECK_MU_PLUGINS, [], self::AS_GROUP, true ); } + + // A few minutes past every hour, apart from the failed logins. + if ( ! as_has_scheduled_action( self::ACTION_SEND_PHP_ERRORS, [], self::AS_GROUP ) ) { + as_schedule_recurring_action( ( intdiv( time(), HOUR_IN_SECONDS ) + 1 ) * HOUR_IN_SECONDS + 8 * MINUTE_IN_SECONDS, HOUR_IN_SECONDS, self::ACTION_SEND_PHP_ERRORS, [], self::AS_GROUP, true ); + } } /** @@ -250,6 +262,17 @@ public static function send_failed_logins(): void { \Scanfully\Events\FailedLogins\Reporter::send(); } + /** + * Send the PHP errors that are waiting. Runs on the recurring hourly + * schedule and as single runs. Refreshes the access token if needed. + * + * @return void + */ + public static function send_php_errors(): void { + self::refresh_access_token_if_needed(); + \Scanfully\Errors\Reporter::send(); + } + /** * Cancel all scheduled email-deliverability actions. Called from the * scanfully_options_cleared hook on disconnect. diff --git a/src/Errors/Attribution.php b/src/Errors/Attribution.php new file mode 100644 index 0000000..63700a7 --- /dev/null +++ b/src/Errors/Attribution.php @@ -0,0 +1,498 @@ + + */ + private array $roots; + + /** + * The WordPress version. + * + * @var string + */ + private string $wp_version; + + /** + * Reads the name and version of a source: `callable(string $kind, string $slug, string $base): array{name: string, version: string}`. + * + * @var callable|null + */ + private $headers; + + /** + * Sources already looked up, by kind and slug. + * + * @var array> + */ + private array $cache = []; + + /** + * Constructor. + * + * @param array $roots The roots: `plugins`, `mu_plugins`, `themes` (one or a list), `content` and `abspath`. + * @param string $wp_version The WordPress version. + * @param callable|null $headers Reads the name and version of a source, by kind, slug and where it is. + */ + public function __construct( array $roots, string $wp_version = '', ?callable $headers = null ) { + $this->roots = []; + $this->wp_version = $wp_version; + $this->headers = $headers; + foreach ( [ 'plugins', 'mu_plugins', 'themes', 'content', 'abspath' ] as $kind ) { + $this->roots[ $kind ] = []; + foreach ( (array) ( $roots[ $kind ] ?? [] ) as $root ) { + $this->add_root( $kind, (string) $root ); + } + } + } + + /** + * The attribution for this WordPress site. + * + * @return self + */ + public static function from_wordpress(): self { + $themes = []; + if ( function_exists( 'get_theme_root' ) ) { + $themes[] = get_theme_root(); + } + foreach ( (array) ( $GLOBALS['wp_theme_directories'] ?? [] ) as $directory ) { + $themes[] = (string) $directory; + } + $content = defined( 'WP_CONTENT_DIR' ) ? (string) WP_CONTENT_DIR : ABSPATH . 'wp-content'; + if ( [] === $themes ) { + $themes[] = $content . '/themes'; + } + + return new self( + [ + 'plugins' => defined( 'WP_PLUGIN_DIR' ) ? (string) WP_PLUGIN_DIR : $content . '/plugins', + 'mu_plugins' => defined( 'WPMU_PLUGIN_DIR' ) ? (string) WPMU_PLUGIN_DIR : $content . '/mu-plugins', + 'themes' => $themes, + 'content' => $content, + 'abspath' => (string) ABSPATH, + ], + (string) ( $GLOBALS['wp_version'] ?? '' ), + [ self::class, 'wordpress_headers' ] + ); + } + + /** + * Add a root and, when it differs, its real path (a symbolic link to + * the site or to `wp-content` resolves to the real path in error + * messages). + * + * @param string $kind The kind of root. + * @param string $root The root. + * + * @return void + */ + private function add_root( string $kind, string $root ): void { + $root = rtrim( self::normalize( $root ), '/' ); + // A root of "/" would match everything. + if ( strlen( $root ) < 2 ) { + return; + } + $this->roots[ $kind ][] = $root . '/'; + + $real = @realpath( $root ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- A root may not exist, or open_basedir may refuse it. + if ( is_string( $real ) ) { + $real = rtrim( self::normalize( $real ), '/' ); + if ( strlen( $real ) >= 2 && $real !== $root ) { + $this->roots[ $kind ][] = $real . '/'; + } + } + } + + /** + * A path with forward slashes. + * + * @param string $path The path. + * + * @return string + */ + private static function normalize( string $path ): string { + return str_replace( '\\', '/', $path ); + } + + /** + * The part of a path under a root, or null when it isn't under it. + * + * @param string $path The path, normalized. + * @param string $kind The kind of root. + * @param string $found The root it was found under; set when found. + * + * @return string|null + */ + private function under( string $path, string $kind, string &$found = '' ): ?string { + foreach ( $this->roots[ $kind ] as $root ) { + if ( 0 === strpos( $path, $root ) ) { + $found = $root; + + return substr( $path, strlen( $root ) ); + } + } + + return null; + } + + /** + * A path relative to the WordPress root: `wp-content/plugins/akismet/akismet.php`. + * A path under `wp-content` outside the root (Bedrock) gets its logical + * name; any other path keeps its last three parts. + * + * @param string $path The path. + * + * @return string + */ + public function relative( string $path ): string { + $path = self::normalize( self::plain_file( $path ) ); + if ( '' === $path ) { + return ''; + } + + $rest = $this->under( $path, 'abspath' ); + if ( null !== $rest ) { + return $rest; + } + foreach ( [ 'plugins', 'mu_plugins', 'themes', 'content' ] as $kind ) { + $rest = $this->under( $path, $kind ); + if ( null !== $rest ) { + return self::label( $kind ) . $rest; + } + } + if ( '/' !== $path[0] && 1 !== preg_match( '#^[A-Za-z]:/#', $path ) ) { + // Already relative, or no path at all. + return $path; + } + $parts = explode( '/', trim( $path, '/' ) ); + + return '…/' . implode( '/', array_slice( $parts, -3 ) ); + } + + /** + * Replace the server paths in a message by their relative form. + * + * @param string $text The message. + * + * @return string + */ + public function relative_in_text( string $text ): string { + $roots = []; + foreach ( [ 'plugins', 'mu_plugins', 'themes', 'content', 'abspath' ] as $kind ) { + foreach ( $this->roots[ $kind ] as $root ) { + $roots[ $root ] = self::label( $kind ); + } + } + uksort( + $roots, + static function ( string $a, string $b ): int { + return strlen( $b ) - strlen( $a ); + } + ); + + foreach ( $roots as $root => $label ) { + $text = str_replace( [ $root, str_replace( '/', '\\', $root ) ], $label, $text ); + } + + // Any other absolute path keeps only its last part. + $text = (string) preg_replace( '#(?/\\\\]+/)+([^\s\'"<>/\\\\]*)#', '…/$1', $text ); + + return (string) preg_replace( '#(?/\\\\]+[/\\\\])*([^\s\'"<>/\\\\]*)#', '…/$1', $text ); + } + + /** + * The relative name of a root. + * + * @param string $kind The kind of root. + * + * @return string + */ + private static function label( string $kind ): string { + switch ( $kind ) { + case 'plugins': + return 'wp-content/plugins/'; + case 'mu_plugins': + return 'wp-content/mu-plugins/'; + case 'themes': + return 'wp-content/themes/'; + case 'content': + return 'wp-content/'; + } + + return ''; + } + + /** + * The file of an error without PHP's decorations: `eval()'d code` and + * `runtime-created function` suffixes. + * + * @param string $file The file as PHP reports it. + * + * @return string + */ + private static function plain_file( string $file ): string { + $plain = preg_replace( '/\(\d+\) : (?:eval\(\)\'d code|runtime-created function|assert code|regexp code).*$/', '', $file ); + + return is_string( $plain ) ? $plain : $file; + } + + /** + * What raised an error: its kind and slug, with its name and version + * when known. For an error inside core, the first frame of the trace + * outside core names the source. + * + * @param string $file The file the error was raised in. + * @param array> $trace The stack frames, each with a `file`. + * + * @return array{kind: string, slug: string, name: string, version: string} + */ + public function source( string $file, array $trace = [] ): array { + $located = $this->locate( $file ); + if ( self::CORE === $located['kind'] ) { + foreach ( $trace as $frame ) { + $candidate = $this->locate( (string) ( $frame['file'] ?? '' ) ); + if ( in_array( $candidate['kind'], [ self::PLUGIN, self::THEME, self::MU_PLUGIN, self::DROPIN ], true ) ) { + $located = $candidate; + break; + } + } + } + + return $this->describe( $located['kind'], $located['slug'], $located['base'] ); + } + + /** + * The kind and slug of the source of a file, and where the source is: + * its folder, or its file for a single-file plugin, must-use plugin or + * drop-in. + * + * @param string $file The file. + * + * @return array{kind: string, slug: string, base: string} + */ + public function locate( string $file ): array { + $path = self::normalize( self::plain_file( $file ) ); + $unknown = [ + 'kind' => self::UNKNOWN, + 'slug' => '', + 'base' => '', + ]; + if ( '' === $path ) { + return $unknown; + } + + // A plugin in its own folder is identified by the folder; a + // single-file plugin (hello.php) by its file name, as the site data + // sync does. A theme by its folder; a must-use plugin and a drop-in + // by their file name (or the folder a loader includes code from). + foreach ( [ + 'plugins' => self::PLUGIN, + 'mu_plugins' => self::MU_PLUGIN, + 'themes' => self::THEME, + ] as $root_kind => $kind ) { + $root = ''; + $rest = $this->under( $path, $root_kind, $root ); + if ( null === $rest || '' === $rest ) { + continue; + } + $slash = strpos( $rest, '/' ); + $name = false === $slash ? $rest : substr( $rest, 0, $slash ); + $slug = self::MU_PLUGIN === $kind || false !== $slash ? $name : (string) preg_replace( '/\.php$/i', '', $name ); + + return [ + 'kind' => $kind, + 'slug' => $slug, + 'base' => $root . $name, + ]; + } + + $root = ''; + $rest = $this->under( $path, 'content', $root ); + if ( null !== $rest && '' !== $rest && false === strpos( $rest, '/' ) ) { + return [ + 'kind' => self::DROPIN, + 'slug' => $rest, + 'base' => $root . $rest, + ]; + } + + $root = ''; + $rest = $this->under( $path, 'abspath', $root ); + if ( null !== $rest && '' !== $rest && ( 0 === strpos( $rest, 'wp-admin/' ) || 0 === strpos( $rest, 'wp-includes/' ) || false === strpos( $rest, '/' ) ) ) { + return [ + 'kind' => self::CORE, + 'slug' => 'wordpress', + 'base' => $root, + ]; + } + + return $unknown; + } + + /** + * A source with its name and version. + * + * @param string $kind The kind. + * @param string $slug The slug. + * @param string $base Where the source is: its folder or file. + * + * @return array{kind: string, slug: string, name: string, version: string} + */ + private function describe( string $kind, string $slug, string $base ): array { + $key = $kind . ':' . $slug; + if ( isset( $this->cache[ $key ] ) ) { + return $this->cache[ $key ]; + } + + $name = ''; + $version = ''; + if ( self::CORE === $kind ) { + $name = 'WordPress'; + $version = $this->wp_version; + } elseif ( self::UNKNOWN !== $kind && null !== $this->headers ) { + try { + $header = (array) call_user_func( $this->headers, $kind, $slug, $base ); + $name = (string) ( $header['name'] ?? '' ); + $version = (string) ( $header['version'] ?? '' ); + } catch ( \Throwable $e ) { + // A header that can't be read leaves the name empty. + $name = ''; + } + } + + $this->cache[ $key ] = [ + 'kind' => $kind, + 'slug' => $slug, + 'name' => self::text( $name ), + 'version' => self::text( $version ), + ]; + + return $this->cache[ $key ]; + } + + /** + * The name and version of a plugin, theme, must-use plugin or drop-in + * from its header. Reads one file: the main file of a plugin (found in + * the active plugins, which WordPress has in memory), the stylesheet of + * a theme, or the file itself. Runs at shutdown, once per source. + * + * @param string $kind The kind. + * @param string $slug The slug. + * @param string $base Where the source is: its folder or file. + * + * @return array{name: string, version: string} + */ + public static function wordpress_headers( string $kind, string $slug, string $base = '' ): array { + $empty = [ + 'name' => '', + 'version' => '', + ]; + if ( '' === $slug || '' === $base || ! function_exists( 'get_file_data' ) ) { + return $empty; + } + + $file = ''; + $names = [ + 'name' => 'Plugin Name', + 'version' => 'Version', + ]; + if ( self::THEME === $kind ) { + $file = $base . '/style.css'; + $names['name'] = 'Theme Name'; + } elseif ( self::PLUGIN === $kind && is_dir( $base ) ) { + $file = self::plugin_main_file( $slug, $base ); + } elseif ( is_file( $base ) ) { + $file = $base; + } + if ( '' === $file || ! is_readable( $file ) ) { + return $empty; + } + + $header = get_file_data( $file, $names ); + + return [ + 'name' => (string) ( $header['name'] ?? '' ), + 'version' => (string) ( $header['version'] ?? '' ), + ]; + } + + /** + * The main file of a plugin in a folder: the active plugin in that + * folder, else the file named after the folder. + * + * @param string $slug The folder name. + * @param string $base The folder. + * + * @return string + */ + private static function plugin_main_file( string $slug, string $base ): string { + $active = function_exists( 'get_option' ) ? (array) get_option( 'active_plugins', [] ) : []; + if ( function_exists( 'is_multisite' ) && is_multisite() && function_exists( 'get_site_option' ) ) { + $active = array_merge( $active, array_keys( (array) get_site_option( 'active_sitewide_plugins', [] ) ) ); + } + foreach ( $active as $basename ) { + $basename = (string) $basename; + if ( 0 === strpos( $basename, $slug . '/' ) && false === strpos( substr( $basename, strlen( $slug ) + 1 ), '/' ) ) { + return $base . '/' . substr( $basename, strlen( $slug ) + 1 ); + } + } + + return $base . '/' . $slug . '.php'; + } + + /** + * Header text as plain text, cut to the longest kept. + * + * @param string $value The header value. + * + * @return string + */ + private static function text( string $value ): string { + $value = function_exists( 'wp_strip_all_tags' ) ? wp_strip_all_tags( $value ) : strip_tags( $value ); // phpcs:ignore WordPress.WP.AlternativeFunctions.strip_tags_strip_tags -- Only without WordPress. + $value = trim( html_entity_decode( $value, ENT_QUOTES, 'UTF-8' ) ); + + return Scrubber::cap( $value, self::MAX_TEXT ); + } +} diff --git a/src/Errors/Builder.php b/src/Errors/Builder.php new file mode 100644 index 0000000..8217b0e --- /dev/null +++ b/src/Errors/Builder.php @@ -0,0 +1,194 @@ + $raw The error as PHP reported it: `type`, `message`, `file`, `line` and `trace` (frames as `debug_backtrace()` gives them, without the handler's own frame). + * @param Attribution $attribution The attribution. + * @param array{request: string, path: string, php: string, wp: string, maintenance: bool} $context The request context. + * + * @return array|null + */ + public static function build( array $raw, Attribution $attribution, array $context ): ?array { + $level = self::level( (int) ( $raw['type'] ?? 0 ) ); + if ( '' === $level ) { + return null; + } + + $message = (string) ( $raw['message'] ?? '' ); + $file = (string) ( $raw['file'] ?? '' ); + $line = (int) ( $raw['line'] ?? 0 ); + $frames = is_array( $raw['trace'] ?? null ) ? $raw['trace'] : []; + + if ( 'fatal' === $level && 0 === strpos( $message, 'Uncaught ' ) ) { + $exception = self::split_exception( $message ); + $message = $exception['message']; + if ( [] === $frames ) { + $frames = $exception['trace']; + } + } + + $trace = self::frames( $frames, $attribution ); + $function = Scrubber::cap( (string) ( $trace[0]['function'] ?? '' ), self::MAX_NAME ); + $relative = Scrubber::cap( $attribution->relative( $file ), self::MAX_NAME ); + $message = Scrubber::scrub( $attribution->relative_in_text( trim( $message ) ) ); + + return [ + 'fingerprint' => Fingerprint::of( $level, $relative, $function, $message ), + 'level' => $level, + 'source' => $attribution->source( $file, $frames ), + 'message' => $message, + 'file' => $relative, + 'line' => max( 0, $line ), + 'function' => $function, + 'trace' => $trace, + 'context' => $context, + ]; + } + + /** + * The message and stack trace of an uncaught exception, which PHP + * reports as one fatal error message: `Uncaught RuntimeException: boom + * in /site/wp-content/plugins/x/x.php:12\nStack trace:\n#0 /site/...(34): + * x_run()\n#1 {main}\n thrown`. + * + * @param string $message The fatal error message. + * + * @return array{message: string, trace: array} + */ + public static function split_exception( string $message ): array { + $trace = []; + $parts = preg_split( '/\R\s*Stack trace:\s*\R/', $message, 2 ); + $head = is_array( $parts ) ? (string) $parts[0] : $message; + $body = is_array( $parts ) && isset( $parts[1] ) ? (string) $parts[1] : ''; + + // The place it was thrown is already the error's file and line. + $head = (string) preg_replace( '/ in \S+:\d+\s*$/', '', rtrim( $head ) ); + + $lines = preg_split( '/\R/', $body ); + foreach ( is_array( $lines ) ? $lines : [] as $line ) { + if ( 1 === preg_match( '/^#\d+ (?:(.+?)\((\d+)\): )?(.+)$/', trim( $line ), $match ) ) { + if ( '{main}' === $match[3] ) { + continue; + } + $trace[] = [ + 'file' => (string) $match[1], + 'line' => (int) $match[2], + 'function' => (string) preg_replace( '/\(.*$/s', '', $match[3] ), + ]; + } + } + + return [ + 'message' => $head, + 'trace' => $trace, + ]; + } + + /** + * The stack frames as they are sent: file (relative), line and + * function, no arguments, at most MAX_FRAMES of them. + * + * @param array $frames The frames as `debug_backtrace()` or split_exception() gives them. + * @param Attribution $attribution The attribution. + * + * @return array + */ + public static function frames( array $frames, Attribution $attribution ): array { + $trace = []; + foreach ( $frames as $frame ) { + if ( ! is_array( $frame ) ) { + continue; + } + $trace[] = [ + 'file' => Scrubber::cap( $attribution->relative( (string) ( $frame['file'] ?? '' ) ), self::MAX_NAME ), + 'line' => max( 0, (int) ( $frame['line'] ?? 0 ) ), + 'function' => Scrubber::cap( self::function_name( $frame ), self::MAX_NAME ), + ]; + if ( count( $trace ) >= self::MAX_FRAMES ) { + break; + } + } + + return $trace; + } + + /** + * The function of a frame, with its class: `WP_Hook->apply_filters`, + * `Plugin::boot`, `my_plugin_init`, `{closure}`. + * + * @param array $frame The frame. + * + * @return string + */ + public static function function_name( array $frame ): string { + $function = (string) ( $frame['function'] ?? '' ); + $class = (string) ( $frame['class'] ?? '' ); + if ( '' === $class ) { + return $function; + } + + return $class . (string) ( $frame['type'] ?? '::' ) . $function; + } +} diff --git a/src/Errors/Context.php b/src/Errors/Context.php new file mode 100644 index 0000000..b74e5fe --- /dev/null +++ b/src/Errors/Context.php @@ -0,0 +1,141 @@ + self::kind( + $server, + [ + 'cli' => defined( 'WP_CLI' ) && WP_CLI, + 'cron' => function_exists( 'wp_doing_cron' ) && wp_doing_cron(), + 'ajax' => function_exists( 'wp_doing_ajax' ) && wp_doing_ajax(), + 'rest' => defined( 'REST_REQUEST' ) && REST_REQUEST, + 'admin' => function_exists( 'is_admin' ) && is_admin(), + ] + ), + 'path' => self::path( $server ), + 'php' => PHP_VERSION, + 'wp' => (string) ( $GLOBALS['wp_version'] ?? '' ), + 'maintenance' => self::maintenance(), + ]; + } + + /** + * The kind of request. A REST request is also known by its path, as + * WordPress only sets `REST_REQUEST` once it dispatches the request, + * which is after an error raised while plugins load. + * + * @param array $server The server variables. + * @param array $flags What WordPress knows: `cli`, `cron`, `ajax`, `rest` and `admin`. + * + * @return string + */ + public static function kind( array $server, array $flags ): string { + if ( ! empty( $flags['cli'] ) || ( PHP_SAPI === 'cli' && ! isset( $server['REQUEST_METHOD'] ) ) ) { + return self::CLI; + } + if ( ! empty( $flags['cron'] ) ) { + return self::CRON; + } + if ( ! empty( $flags['ajax'] ) ) { + return self::AJAX; + } + $path = self::path( $server ); + $uri = (string) ( $server['REQUEST_URI'] ?? '' ); + if ( ! empty( $flags['rest'] ) || 1 === preg_match( '#^/(?:index\.php/)?wp-json(?:/|$)#', $path ) || 1 === preg_match( '/[?&]rest_route=/', $uri ) ) { + return self::REST; + } + if ( ! empty( $flags['admin'] ) ) { + return self::ADMIN; + } + + return self::FRONT; + } + + /** + * The path of the request without its query string, cut to the longest + * kept; empty on the command line. + * + * @param array $server The server variables. + * + * @return string + */ + public static function path( array $server ): string { + $uri = (string) ( $server['REQUEST_URI'] ?? '' ); + if ( '' === $uri ) { + return ''; + } + $cut = strpos( $uri, '?' ); + if ( false !== $cut ) { + $uri = substr( $uri, 0, $cut ); + } + $cut = strpos( $uri, '#' ); + if ( false !== $cut ) { + $uri = substr( $uri, 0, $cut ); + } + $uri = (string) preg_replace( '/[\x00-\x1f\x7f]/', '', $uri ); + + return Scrubber::cap( $uri, self::MAX_PATH ); + } + + /** + * Whether WordPress is in maintenance mode: an update is replacing + * files, so errors are expected. + * + * @return bool + */ + public static function maintenance(): bool { + try { + if ( function_exists( 'wp_is_maintenance_mode' ) ) { + return (bool) wp_is_maintenance_mode(); + } + + return defined( 'ABSPATH' ) && file_exists( ABSPATH . '.maintenance' ); + } catch ( \Throwable $e ) { + return false; + } + } +} diff --git a/src/Errors/Controller.php b/src/Errors/Controller.php new file mode 100644 index 0000000..1ef72f8 --- /dev/null +++ b/src/Errors/Controller.php @@ -0,0 +1,167 @@ + $enabled, + 'coverage' => ! $enabled ? 'off' : ( 'mu' === Monitor::origin() ? 'full' : 'partial' ), + 'mu_plugin' => MuPlugin::is_installed(), + ]; + } + + /** + * The admin-post handler of the on/off switch. + * + * @return void + */ + public static function handle_toggle(): void { + if ( ! current_user_can( 'manage_options' ) ) { + wp_die( esc_html__( 'Unauthorized', 'scanfully' ), '', [ 'response' => 403 ] ); + } + check_admin_referer( self::NONCE_TOGGLE ); + + $enable = isset( $_POST['scanfully_php_errors'] ) && 'on' === sanitize_key( wp_unslash( $_POST['scanfully_php_errors'] ) ); + update_option( Monitor::ENABLED_OPTION, $enable ? 'yes' : 'no', true ); + if ( $enable ) { + MuPlugin::install(); + } else { + Store::delete_all(); + if ( ! is_multisite() ) { + MuPlugin::remove(); + } + } + + wp_safe_redirect( add_query_arg( [ 'page' => 'scanfully' ], admin_url( 'options-general.php' ) ) ); + exit; + } + + /** + * The PHP error monitoring section of the settings page. + * + * @return void + */ + public static function render_admin_panel(): void { + if ( 'yes' !== OptionsController::get_option( 'is_connected' ) ) { + return; + } + $switched_on = self::is_switched_on(); + $runs = Monitor::should_run(); + ?> +
+

+

+ +

+ + + +

+ +

+ + +

+ +
+ + + +
+ + + + + +
+
+ + "'?'", + '/"(?:[^"\\\\]|\\\\.)*"/' => '"?"', + '/`[^`]*`/' => '`?`', + // Hexadecimal identifiers and hashes, then any number. + '/\b(?=[0-9a-f]*\d)[0-9a-f]{8,}\b/i' => '?', + '/\b0x[0-9a-f]+\b/i' => '?', + '/(? '?', + // Whitespace. + '/\s+/' => ' ', + ]; + foreach ( $patterns as $pattern => $replacement ) { + $normalized = preg_replace( $pattern, $replacement, $message ); + if ( is_string( $normalized ) ) { + $message = $normalized; + } + } + + return trim( $message ); + } +} diff --git a/src/Errors/Monitor.php b/src/Errors/Monitor.php new file mode 100644 index 0000000..b37ed53 --- /dev/null +++ b/src/Errors/Monitor.php @@ -0,0 +1,518 @@ +> + */ + private static array $errors = []; + + /** + * Distinct errors past the cap of this request. + * + * @var int + */ + private static int $dropped = 0; + + /** + * Whether an update finished in this request. + * + * @var bool + */ + private static bool $updated = false; + + /** + * Start catching errors, once per request: when the site is connected, + * capture isn't turned off, and (from the must-use plugin) the + * Scanfully plugin is active. + * + * @param string $origin `mu` or `plugin`. + * @param string $basename The Scanfully plugin's basename, for the must-use plugin's check. + * + * @return void + */ + public static function boot( string $origin, string $basename = '' ): void { + if ( '' !== self::$origin ) { + return; + } + + try { + if ( ! self::should_run( 'mu' === $origin ? $basename : '' ) ) { + return; + } + self::$origin = $origin; + + $previous = set_error_handler( [ self::class, 'handle' ], Builder::WARNING ); + if ( null !== $previous ) { + // Another handler was there first: take every type, so the + // ones it takes still reach it. + restore_error_handler(); + $previous = set_error_handler( [ self::class, 'handle' ] ); + self::$all_types = true; + } + self::$previous = is_callable( $previous ) ? $previous : null; + + register_shutdown_function( [ self::class, 'shutdown' ] ); + } catch ( \Throwable $e ) { + // Never break the site: without the handlers nothing is caught. + self::$origin = ''; + } + } + + /** + * Whether capture runs on this site: connected, not turned off, and the + * Scanfully plugin active (and not paused by recovery mode) when a + * basename is given. + * + * @param string $basename The Scanfully plugin's basename, or '' to skip that check. + * + * @return bool + */ + public static function should_run( string $basename = '' ): bool { + if ( ! function_exists( 'get_option' ) || 'yes' !== get_option( 'scanfully_connect_is_connected' ) ) { + return false; + } + // Read from the autoloaded options: a site that never touched the + // setting has no row, and get_option() would look for it on every + // request. + $options = function_exists( 'wp_load_alloptions' ) ? wp_load_alloptions() : []; + if ( 'no' === ( $options[ self::ENABLED_OPTION ] ?? '' ) ) { + return false; + } + /** + * Filters whether PHP errors are caught and sent to Scanfully. The + * must-use plugin reads it before regular plugins load, so add the + * filter in a must-use plugin or in wp-config.php. + * + * @param bool $enabled Whether PHP errors are caught. + */ + if ( ! apply_filters( 'scanfully_php_errors_enabled', true ) ) { + return false; + } + if ( '' === $basename ) { + return true; + } + + $active = in_array( $basename, (array) get_option( 'active_plugins', [] ), true ); + if ( ! $active && function_exists( 'is_multisite' ) && is_multisite() ) { + $active = isset( ( (array) get_site_option( 'active_sitewide_plugins', [] ) )[ $basename ] ); + } + if ( ! $active ) { + return false; + } + + // In recovery mode, a paused Scanfully plugin stays off here too. + return ! function_exists( 'wp_paused_plugins' ) || ! wp_paused_plugins()->get( dirname( $basename ) ); + } + + /** + * What booted the monitor: `mu`, `plugin`, or '' when it isn't running. + * + * @return string + */ + public static function origin(): string { + return self::$origin; + } + + /** + * The error handler: keep a warning, then pass the error on. + * + * @param int $type The error type. + * @param string $message The message. + * @param string $file The file. + * @param int $line The line. + * + * @return bool What the previous handler returned; false without one, so PHP handles the error as usual. + */ + public static function handle( $type, $message = '', $file = '', $line = 0 ) { + if ( ! self::$busy ) { + self::$busy = true; + try { + // error_reporting() leaves out the type for an error silenced + // with @ (and for types the site doesn't report). + if ( 0 !== ( (int) $type & Builder::WARNING ) && 0 !== ( error_reporting() & (int) $type ) ) { + self::record( (int) $type, (string) $message, (string) $file, (int) $line, self::backtrace( (string) $file, (int) $line ) ); + } + } catch ( \Throwable $e ) { + // Never break the site; the error is still passed on below. + self::$busy = false; + } + self::$busy = false; + } + + if ( null !== self::$previous ) { + return call_user_func( self::$previous, $type, $message, $file, $line ); + } + + return false; + } + + /** + * The stack frames of the warning being handled: without the handler's + * own frame and the internal call that raised the warning, without + * arguments. + * + * @param string $file The file of the warning. + * @param int $line The line of the warning. + * + * @return array> + */ + private static function backtrace( string $file, int $line ): array { + $frames = debug_backtrace( DEBUG_BACKTRACE_IGNORE_ARGS, Builder::MAX_FRAMES + 4 ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_debug_backtrace -- The stack frames of the error, without arguments. + // The handler's own frame, and the engine calling it (no file). + while ( [] !== $frames ) { + $frame = $frames[0]; + if ( self::class !== ( $frame['class'] ?? '' ) && array_key_exists( 'file', $frame ) ) { + break; + } + array_shift( $frames ); + } + // A warning raised by an internal function (file_get_contents()): + // its frame is where the warning is, and the function it was called + // in is the next one. + if ( [] !== $frames && isset( $frames[0]['file'], $frames[0]['line'] ) && $frames[0]['file'] === $file && (int) $frames[0]['line'] === $line ) { + array_shift( $frames ); + } + + return $frames; + } + + /** + * Keep an error for shutdown: the first occurrence of each type, file + * and line with its frames, and a count for the rest. Past the cap, + * only counted as dropped. + * + * @param int $type The error type. + * @param string $message The message. + * @param string $file The file. + * @param int $line The line. + * @param array> $trace The stack frames. + * + * @return void + */ + public static function record( int $type, string $message, string $file, int $line, array $trace = [] ): void { + $id = $type . ':' . $file . ':' . $line; + $now = time(); + if ( isset( self::$errors[ $id ] ) ) { + ++self::$errors[ $id ]['count']; + self::$errors[ $id ]['last_seen'] = $now; + return; + } + if ( count( self::$errors ) >= self::MAX_PER_REQUEST ) { + ++self::$dropped; + return; + } + + self::$errors[ $id ] = [ + 'type' => $type, + 'message' => strlen( $message ) > self::MAX_RAW_MESSAGE ? substr( $message, 0, self::MAX_RAW_MESSAGE ) : $message, + 'file' => $file, + 'line' => $line, + 'trace' => array_slice( $trace, 0, Builder::MAX_FRAMES + 1 ), + 'count' => 1, + 'first_seen' => $now, + 'last_seen' => $now, + ]; + } + + /** + * `upgrader_process_complete`: an update finished in this request. + * + * @return void + */ + public static function note_update(): void { + self::$updated = true; + } + + /** + * The shutdown function: keep a fatal error, then store and send. + * + * @return void + */ + public static function shutdown(): void { + if ( self::$busy ) { + return; + } + self::$busy = true; + + try { + $last = error_get_last(); + if ( is_array( $last ) && 0 !== ( (int) $last['type'] & Builder::FATAL ) ) { + self::make_room( (string) $last['message'] ); + self::record( (int) $last['type'], (string) $last['message'], (string) $last['file'], (int) $last['line'] ); + } + + if ( [] !== self::$errors || self::$dropped > 0 ) { + self::flush(); + } + } catch ( \Throwable $e ) { + // Never break the site: what this request saw is dropped. + self::$errors = []; + } + + self::$errors = []; + self::$dropped = 0; + self::$busy = false; + } + + /** + * After a fatal error for running out of memory, raise the limit a + * little, so the shutdown work can still run. + * + * @param string $message The fatal error's message. + * + * @return void + */ + private static function make_room( string $message ): void { + if ( false === strpos( $message, 'Allowed memory size' ) ) { + return; + } + $limit = function_exists( 'wp_convert_hr_to_bytes' ) ? wp_convert_hr_to_bytes( (string) ini_get( 'memory_limit' ) ) : 0; + if ( $limit > 0 ) { + @ini_set( 'memory_limit', (string) ( $limit + 16 * 1024 * 1024 ) ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged, WordPress.PHP.IniSet.memory_limit_Disallowed -- A host may refuse it; then the work runs without. + } + } + + /** + * Group what this request saw by fingerprint, send a new fatal error + * straight away, add the rest to the store with one query and plan a + * send for errors the API doesn't know yet. + * + * @return void + */ + public static function flush(): void { + if ( ! Store::database_ready() ) { + // No database (yet): nothing can be kept. + return; + } + + $now = time(); + $hour = Store::hour( $now ); + $errors = self::build( Attribution::from_wordpress(), Context::current() ); + $known = Store::known(); + $unknown = array_diff_key( $errors, array_filter( $known, static fn( int $sent ): bool => $sent > $now - Store::KNOWN_FOR ) ); + + // A new distinct error counts against the hour's cap; one already + // waiting to be sent doesn't. + $overflow = self::$dropped; + $new = array_diff( array_keys( $unknown ), Store::pending( array_keys( $unknown ) ) ); + if ( [] !== $new ) { + $room = max( 0, Store::MAX_NEW_PER_HOUR - Store::hour_count( 'h', $hour ) ); + // Fatal errors first. + usort( + $new, + static fn( string $a, string $b ): int => ( 'fatal' === $errors[ $b ]['level'] ) <=> ( 'fatal' === $errors[ $a ]['level'] ) + ); + foreach ( array_slice( $new, $room ) as $key ) { + unset( $errors[ $key ], $unknown[ $key ] ); + ++$overflow; + } + $new = array_slice( $new, 0, $room ); + } + + foreach ( $errors as $key => $error ) { + if ( 'fatal' === $error['level'] && self::send_directly( $error, $now ) ) { + unset( $errors[ $key ], $unknown[ $key ] ); + } + } + + Store::add( $errors, $hour, count( $new ), $overflow ); + + if ( [] !== $unknown || self::$updated ) { + Reporter::schedule( self::$updated ? Reporter::TRIGGER_UPDATE : Reporter::TRIGGER_NEW ); + } + } + + /** + * This request's errors as they are stored, grouped by key, with their + * count and times. Errors that differ only in the line (the same bug + * twice in a function) share a fingerprint and are added up. + * + * @param Attribution $attribution The attribution. + * @param array{request: string, path: string, php: string, wp: string, maintenance: bool} $context The request context. + * + * @return array> + */ + public static function build( Attribution $attribution, array $context ): array { + $built = []; + foreach ( self::$errors as $raw ) { + $error = Builder::build( $raw, $attribution, $context ); + if ( null === $error ) { + continue; + } + $key = Store::key( $error ); + if ( isset( $built[ $key ] ) ) { + $built[ $key ]['count'] += (int) $raw['count']; + $built[ $key ]['first_seen'] = min( $built[ $key ]['first_seen'], (int) $raw['first_seen'] ); + $built[ $key ]['last_seen'] = max( $built[ $key ]['last_seen'], (int) $raw['last_seen'] ); + continue; + } + $built[ $key ] = $error + [ + 'count' => (int) $raw['count'], + 'first_seen' => (int) $raw['first_seen'], + 'last_seen' => (int) $raw['last_seen'], + ]; + } + + return $built; + } + + /** + * Send a fatal error straight from the shutdown function, after the + * response is finished, with a short timeout: a site that fails on every + * request, cron included, can't send it any other way. At most once per + * fingerprint per DIRECT_PERIOD. + * + * @param array $error The built error, with its count and times. + * @param int $now The time. + * + * @return bool Whether the API took it. + */ + private static function send_directly( array $error, int $now ): bool { + if ( ! Store::lock( (string) $error['fingerprint'], self::DIRECT_PERIOD, $now ) ) { + return false; + } + + // The visitor gets the response first. + if ( function_exists( 'fastcgi_finish_request' ) ) { + fastcgi_finish_request(); + } elseif ( function_exists( 'litespeed_finish_request' ) ) { + litespeed_finish_request(); + } + + $status = ( new ErrorsRequest() )->send( Reporter::payload( [ Reporter::entry( $error, (int) $error['count'], (int) $error['first_seen'], (int) $error['last_seen'] ) ], 0 ), self::DIRECT_TIMEOUT ); + + return null !== $status && $status >= 200 && $status < 300; + } + + /** + * Forget this request's errors and the boot state (tests). + * + * @return void + */ + public static function reset(): void { + if ( '' !== self::$origin ) { + restore_error_handler(); + } + self::$origin = ''; + self::$previous = null; + self::$all_types = false; + self::$busy = false; + self::$errors = []; + self::$dropped = 0; + self::$updated = false; + } + + /** + * The errors this request kept so far (tests). + * + * @return array> + */ + public static function recorded(): array { + return self::$errors; + } + + /** + * Whether the handler takes every error type (tests). + * + * @return bool + */ + public static function takes_all_types(): bool { + return self::$all_types; + } +} diff --git a/src/Errors/MuPlugin.php b/src/Errors/MuPlugin.php new file mode 100644 index 0000000..a0d2c81 --- /dev/null +++ b/src/Errors/MuPlugin.php @@ -0,0 +1,246 @@ + $trigger ]; + if ( as_has_scheduled_action( self::ACTION, $args, 'scanfully' ) ) { + return; + } + as_schedule_single_action( time() + ( self::TRIGGER_UPDATE === $trigger ? 0 : MINUTE_IN_SECONDS ), self::ACTION, $args, 'scanfully' ); + } + + /** + * Send what is waiting. + * + * @return void + */ + public static function send(): void { + if ( ! Options\Controller::get_options()->is_connected ) { + return; + } + if ( ! Monitor::should_run() ) { + Store::delete_all(); + return; + } + + $now = time(); + $stored = Store::read(); + $known = Store::known(); + $entries = []; + $counts = []; + $order = []; + foreach ( $stored['errors'] as $key => $error ) { + // Nothing left to send, or kept too long. + if ( $error['count'] < 1 || ( $error['last_seen'] > 0 && $error['last_seen'] < $now - self::KEEP ) ) { + Store::delete( $key ); + continue; + } + // Counted after its sample went with the last send: the next + // occurrence brings a sample. + if ( null === $error['sample'] ) { + continue; + } + $sample = $error['sample']; + $first_seen = (int) ( $sample['first_seen'] ?? $now ); + $entries[ $key ] = self::entry( $sample, $error['count'], $first_seen, max( $first_seen, $error['last_seen'] ) ); + $counts[ $key ] = $error['count']; + $order[ $key ] = [ 'fatal' === ( $sample['level'] ?? '' ) ? 0 : 1, isset( $known[ $key ] ) ? 1 : 0, -$error['count'] ]; + } + + $current = Store::hour( $now ); + $overflow = array_filter( $stored['overflow'], static fn( int $count ): bool => $count > 0 ); + if ( [] === $entries && [] === $overflow ) { + Store::take_hours( [], $current ); + Store::delete_old_locks( Monitor::DIRECT_PERIOD, $now ); + return; + } + + uksort( + $entries, + static fn( string $a, string $b ): int => $order[ $a ] <=> $order[ $b ] + ); + $batch = array_slice( $entries, 0, self::MAX_PER_REQUEST, true ); + + $status = ( new ErrorsRequest() )->send( self::payload( array_values( $batch ), array_sum( $overflow ) ) ); + + // Sent, or refused as data the API will never take: either way done. + // Anything else (no answer, 401 while a token refreshes, 429, a server + // error, an API that doesn't know the endpoint yet) is tried again on + // the next run. + $done = null !== $status && ( ( $status >= 200 && $status < 300 ) || 400 === $status || 413 === $status || 422 === $status ); + if ( ! $done ) { + return; + } + + Store::take( array_intersect_key( $counts, $batch ) ); + Store::take_hours( $overflow, $current ); + Store::delete_old_locks( Monitor::DIRECT_PERIOD, $now ); + Store::mark_known( array_keys( $batch ), $now ); + + if ( count( $entries ) > count( $batch ) ) { + self::schedule( self::TRIGGER_NEW ); + } + } + + /** + * An error as the API takes it. + * + * @param array $error The built error or stored sample. + * @param int $count How often it happened. + * @param int $first_seen When it first happened (Unix time). + * @param int $last_seen When it last happened (Unix time). + * + * @return array + */ + public static function entry( array $error, int $count, int $first_seen, int $last_seen ): array { + $source = is_array( $error['source'] ?? null ) ? $error['source'] : []; + $context = is_array( $error['context'] ?? null ) ? $error['context'] : []; + $trace = []; + foreach ( is_array( $error['trace'] ?? null ) ? $error['trace'] : [] as $frame ) { + $trace[] = [ + 'file' => (string) ( $frame['file'] ?? '' ), + 'line' => (int) ( $frame['line'] ?? 0 ), + 'function' => (string) ( $frame['function'] ?? '' ), + ]; + } + + return [ + 'fingerprint' => (string) ( $error['fingerprint'] ?? '' ), + 'level' => (string) ( $error['level'] ?? '' ), + 'source' => [ + 'kind' => (string) ( $source['kind'] ?? Attribution::UNKNOWN ), + 'slug' => (string) ( $source['slug'] ?? '' ), + 'name' => (string) ( $source['name'] ?? '' ), + 'version' => (string) ( $source['version'] ?? '' ), + ], + 'message' => (string) ( $error['message'] ?? '' ), + 'file' => (string) ( $error['file'] ?? '' ), + 'line' => (int) ( $error['line'] ?? 0 ), + 'function' => (string) ( $error['function'] ?? '' ), + 'trace' => $trace, + 'context' => [ + 'request' => (string) ( $context['request'] ?? Context::FRONT ), + 'path' => (string) ( $context['path'] ?? '' ), + 'php' => (string) ( $context['php'] ?? '' ), + 'wp' => (string) ( $context['wp'] ?? '' ), + 'maintenance' => (bool) ( $context['maintenance'] ?? false ), + ], + 'count' => max( 1, $count ), + 'first_seen' => gmdate( 'Y-m-d\TH:i:s\Z', $first_seen ), + 'last_seen' => gmdate( 'Y-m-d\TH:i:s\Z', $last_seen ), + ]; + } + + /** + * The body of a request. + * + * @param array> $errors The errors. + * @param int $overflow Distinct errors dropped. + * + * @return array{errors: array>, overflow: int} + */ + public static function payload( array $errors, int $overflow ): array { + return [ + 'errors' => $errors, + 'overflow' => max( 0, $overflow ), + ]; + } +} diff --git a/src/Errors/Scrubber.php b/src/Errors/Scrubber.php new file mode 100644 index 0000000..4cd5f62 --- /dev/null +++ b/src/Errors/Scrubber.php @@ -0,0 +1,86 @@ +()]*)\?[^\s\'"<>()]+#i' => '$1?[query]', + // An email address. + '/[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}/' => '[email]', + // A named secret: password=..., token: ..., api_key => .... + '/\b(password|passwd|pwd|pass|secret|token|api[_\-]?key|private[_\-]?key|client[_\-]?secret|access[_\-]?token|refresh[_\-]?token|auth|authorization|nonce|signature)\b([\'"]?\s*(?:=>|=|:)\s*)(?:(?:Bearer|Basic)\s+)?[\'"]?[^\s\'",;)]+[\'"]?/i' => '$1$2[redacted]', + // A bearer or basic credential on its own. + '/\b(Bearer|Basic)\s+[A-Za-z0-9._~+\/=\-]{8,}/' => '$1 [redacted]', + // Keys with a known prefix (Stripe, AWS, GitHub, Slack, Google). + '/\b(?:sk|pk|rk)_(?:live|test)_[A-Za-z0-9]+/' => '[key]', + '/\bAKIA[0-9A-Z]{16}\b/' => '[key]', + '/\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{20,}\b/' => '[key]', + '/\bxox[abprs]-[A-Za-z0-9\-]+/' => '[key]', + '/\bAIza[0-9A-Za-z_\-]{30,}\b/' => '[key]', + // A long hexadecimal value: a hash, a session id, a token. + '/\b(?=[0-9a-f]*\d)[0-9a-f]{32,}\b/i' => '[key]', + // A long value of letters and digits with no spaces: a key. + '/(? '[key]', + ]; + + /** + * A message with secrets replaced and cut to the longest sent. + * + * @param string $text The message. + * + * @return string + */ + public static function scrub( string $text ): string { + foreach ( self::PATTERNS as $pattern => $replacement ) { + $scrubbed = preg_replace( $pattern, $replacement, $text ); + if ( is_string( $scrubbed ) ) { + $text = $scrubbed; + } + } + + return self::cap( $text, self::MAX_LENGTH ); + } + + /** + * Text cut to a number of characters, as UTF-8 when the text is valid + * UTF-8 and as bytes otherwise. + * + * @param string $text The text. + * @param int $length The most characters kept. + * + * @return string + */ + public static function cap( string $text, int $length ): string { + if ( function_exists( 'mb_substr' ) && function_exists( 'mb_strlen' ) && preg_match( '//u', $text ) ) { + return mb_strlen( $text, 'UTF-8' ) > $length ? mb_substr( $text, 0, $length, 'UTF-8' ) : $text; + } + + return strlen( $text ) > $length ? substr( $text, 0, $length ) : $text; + } +} diff --git a/src/Errors/Store.php b/src/Errors/Store.php new file mode 100644 index 0000000..94029c4 --- /dev/null +++ b/src/Errors/Store.php @@ -0,0 +1,473 @@ +_`, where the key is the fingerprint and a short + * hash of the source's version: + * + * - `_n`: how often it happened since it was last sent; + * - `_l`: when it last happened (a Unix time); + * - `_s`: the error as it is sent, from its first occurrence, with when that was. + * + * And two counters per UTC hour: `scanfully_pe_h__n`, the new errors + * kept that hour, and `scanfully_pe_o__n`, the new errors dropped + * because the hour was over its cap. + * + * A request adds what it saw with one atomic query at shutdown, like the + * failed login counters: counts are added, the last time is the latest, and + * the first sample stays. The rows are never autoloaded and skip the object + * cache on purpose: only the sender reads them. + * + * @package Scanfully\Errors + */ +final class Store { + + /** + * Prefix of the rows. + */ + public const PREFIX = 'scanfully_pe_'; + + /** + * Option with the errors the API got recently: key to when it was sent. + */ + public const KNOWN_OPTION = 'scanfully_php_errors_known'; + + /** + * Option name prefix of the direct send locks: one per fingerprint. + */ + public const LOCK_PREFIX = 'scanfully_pe_lock_'; + + /** + * How long an error counts as known after it was sent. + */ + public const KNOWN_FOR = DAY_IN_SECONDS; + + /** + * The most errors remembered as known. + */ + public const MAX_KNOWN = 500; + + /** + * The most new errors kept per hour; more are counted as overflow. + */ + public const MAX_NEW_PER_HOUR = 50; + + /** + * The hour a time falls in, in hours since 1970 (UTC). + * + * @param int|null $time A Unix time; now when null. + * + * @return int + */ + public static function hour( ?int $time = null ): int { + return (int) floor( ( $time ?? time() ) / HOUR_IN_SECONDS ); + } + + /** + * The store key of an error: its fingerprint and a short hash of the + * version of its source. + * + * @param array $error The built error. + * + * @return string + */ + public static function key( array $error ): string { + $version = (string) ( $error['source']['version'] ?? '' ); + + return (string) ( $error['fingerprint'] ?? '' ) . '_' . substr( md5( $version ), 0, 8 ); + } + + /** + * Whether a key is one this store makes. + * + * @param string $key The key. + * + * @return bool + */ + public static function is_key( string $key ): bool { + return 1 === preg_match( '/^[0-9a-f]{40}_[0-9a-f]{8}$/', $key ); + } + + /** + * Whether the database can take a query: WordPress connected to it. + * + * @return bool + */ + public static function database_ready(): bool { + global $wpdb; + + return isset( $wpdb ) && is_object( $wpdb ) && ! empty( $wpdb->ready ) && ! empty( $wpdb->options ); + } + + /** + * The errors the API got recently: key to when it was sent. + * + * @return array + */ + public static function known(): array { + $known = get_option( self::KNOWN_OPTION, [] ); + + return is_array( $known ) ? array_map( 'intval', $known ) : []; + } + + /** + * Remember that the API got errors. + * + * @param string[] $keys The keys sent. + * @param int $now The time they were sent. + * + * @return void + */ + public static function mark_known( array $keys, int $now ): void { + $known = self::known(); + foreach ( $keys as $key ) { + $known[ $key ] = $now; + } + $known = array_filter( + $known, + static function ( int $sent ) use ( $now ): bool { + return $sent > $now - self::KNOWN_FOR; + } + ); + arsort( $known ); + update_option( self::KNOWN_OPTION, array_slice( $known, 0, self::MAX_KNOWN, true ), false ); + } + + /** + * Of some keys, the ones with a sample waiting to be sent. + * + * @param string[] $keys The keys. + * + * @return string[] + */ + public static function pending( array $keys ): array { + global $wpdb; + + $names = []; + foreach ( $keys as $key ) { + if ( self::is_key( $key ) ) { + $names[] = self::PREFIX . $key . '_s'; + } + } + if ( [] === $names ) { + return []; + } + + // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare -- The rows skip the object cache on purpose (see the class comment); the placeholders are built from the names above. + $found = $wpdb->get_col( + $wpdb->prepare( + "SELECT option_name FROM {$wpdb->options} WHERE option_name IN (" . implode( ', ', array_fill( 0, count( $names ), '%s' ) ) . ')', + $names + ) + ); + // phpcs:enable + + $pending = []; + foreach ( (array) $found as $name ) { + $pending[] = substr( (string) $name, strlen( self::PREFIX ), -2 ); + } + + return $pending; + } + + /** + * The count of an hour counter: `h` (new errors kept) or `o` (dropped). + * + * @param string $counter `h` or `o`. + * @param int $hour The hour. + * + * @return int + */ + public static function hour_count( string $counter, int $hour ): int { + global $wpdb; + + // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- The rows skip the object cache on purpose (see the class comment). + return (int) $wpdb->get_var( $wpdb->prepare( "SELECT option_value FROM {$wpdb->options} WHERE option_name = %s", self::PREFIX . $counter . '_' . $hour . '_n' ) ); + } + + /** + * Add what a request saw, in one query. + * + * @param array> $errors Built errors by key, each with `count`, `first_seen` and `last_seen` (Unix times). + * @param int $hour The hour. + * @param int $new New errors kept, for the hour's cap. + * @param int $overflow New errors dropped. + * + * @return bool Whether the query ran. + */ + public static function add( array $errors, int $hour, int $new = 0, int $overflow = 0 ): bool { + global $wpdb; + + $values = []; + $args = []; + foreach ( $errors as $key => $error ) { + $key = (string) $key; + if ( ! self::is_key( $key ) ) { + continue; + } + $sample = self::sample( $error ); + if ( null === $sample ) { + continue; + } + array_push( + $args, + self::PREFIX . $key . '_n', + (string) max( 1, (int) ( $error['count'] ?? 1 ) ), + self::PREFIX . $key . '_l', + (string) (int) ( $error['last_seen'] ?? time() ), + self::PREFIX . $key . '_s', + $sample + ); + array_push( $values, "(%s, %s, 'no')", "(%s, %s, 'no')", "(%s, %s, 'no')" ); + } + foreach ( [ + 'h' => $new, + 'o' => $overflow, + ] as $counter => $count ) { + if ( $count > 0 ) { + array_push( $args, self::PREFIX . $counter . '_' . $hour . '_n', (string) $count ); + $values[] = "(%s, %s, 'no')"; + } + } + if ( [] === $values ) { + return false; + } + + // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare -- An atomic update the options API can't do; the placeholders are built from the fixed fragment above. + $result = $wpdb->query( + $wpdb->prepare( + "INSERT INTO {$wpdb->options} (option_name, option_value, autoload) VALUES " . implode( ', ', $values ) + . " ON DUPLICATE KEY UPDATE option_value = CASE RIGHT(option_name, 2) WHEN '_n' THEN option_value + VALUES(option_value) WHEN '_l' THEN GREATEST(CAST(option_value AS UNSIGNED), CAST(VALUES(option_value) AS UNSIGNED)) ELSE option_value END", + $args + ) + ); + // phpcs:enable + + return false !== $result; + } + + /** + * The sample of an error as it is stored: the error as it is sent, with + * the time of its first occurrence. Null when it can't be encoded. + * + * @param array $error The built error. + * + * @return string|null + */ + private static function sample( array $error ): ?string { + $sample = [ + 'fingerprint' => (string) ( $error['fingerprint'] ?? '' ), + 'level' => (string) ( $error['level'] ?? '' ), + 'source' => $error['source'] ?? [], + 'message' => (string) ( $error['message'] ?? '' ), + 'file' => (string) ( $error['file'] ?? '' ), + 'line' => (int) ( $error['line'] ?? 0 ), + 'function' => (string) ( $error['function'] ?? '' ), + 'trace' => $error['trace'] ?? [], + 'context' => $error['context'] ?? [], + 'first_seen' => (int) ( $error['first_seen'] ?? time() ), + ]; + $json = function_exists( 'wp_json_encode' ) ? wp_json_encode( $sample, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE ) : json_encode( $sample, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE ); // phpcs:ignore WordPress.WP.AlternativeFunctions.json_encode_json_encode -- Only without WordPress. + + return is_string( $json ) ? $json : null; + } + + /** + * Everything waiting to be sent: the errors by key, with their count, + * last time and sample, and the overflow per hour. + * + * @return array{errors: array|null}>, overflow: array, hours: array} + */ + public static function read(): array { + global $wpdb; + + // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- The rows are found by name prefix, which the options API can't do. + $rows = $wpdb->get_results( $wpdb->prepare( "SELECT option_name, option_value FROM {$wpdb->options} WHERE option_name LIKE %s", $wpdb->esc_like( self::PREFIX ) . '%' ) ); + + $errors = []; + $overflow = []; + $hours = []; + foreach ( (array) $rows as $row ) { + $name = substr( (string) ( $row->option_name ?? '' ), strlen( self::PREFIX ) ); + $value = (string) ( $row->option_value ?? '' ); + if ( 1 === preg_match( '/^([ho])_(\d+)_n$/', $name, $match ) ) { + if ( 'o' === $match[1] ) { + $overflow[ (int) $match[2] ] = (int) $value; + } else { + $hours[ (int) $match[2] ] = (int) $value; + } + continue; + } + if ( 1 !== preg_match( '/^([0-9a-f]{40}_[0-9a-f]{8})_([nls])$/', $name, $match ) ) { + continue; + } + $key = $match[1]; + if ( ! isset( $errors[ $key ] ) ) { + $errors[ $key ] = [ + 'count' => 0, + 'last_seen' => 0, + 'sample' => null, + ]; + } + if ( 'n' === $match[2] ) { + $errors[ $key ]['count'] = (int) $value; + } elseif ( 'l' === $match[2] ) { + $errors[ $key ]['last_seen'] = (int) $value; + } else { + $sample = json_decode( $value, true ); + $errors[ $key ]['sample'] = is_array( $sample ) ? $sample : null; + } + } + + return [ + 'errors' => $errors, + 'overflow' => $overflow, + 'hours' => $hours, + ]; + } + + /** + * Take sent counts off: the counts drop by what was sent, and the sample + * and last time go, so the next occurrence starts a new sample. A count + * that reaches zero goes too; one that grew while sending stays for the + * next send. + * + * @param array $sent Count sent by key. + * + * @return void + */ + public static function take( array $sent ): void { + global $wpdb; + + // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- The rows skip the object cache on purpose (see the class comment). + foreach ( $sent as $key => $count ) { + $key = (string) $key; + if ( ! self::is_key( $key ) ) { + continue; + } + $wpdb->query( $wpdb->prepare( "UPDATE {$wpdb->options} SET option_value = option_value - %d WHERE option_name = %s", $count, self::PREFIX . $key . '_n' ) ); + $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name IN (%s, %s)", self::PREFIX . $key . '_s', self::PREFIX . $key . '_l' ) ); + $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name = %s AND CAST(option_value AS SIGNED) <= 0", self::PREFIX . $key . '_n' ) ); + } + // phpcs:enable + } + + /** + * Remove an error's rows. + * + * @param string $key The key. + * + * @return void + */ + public static function delete( string $key ): void { + global $wpdb; + + if ( ! self::is_key( $key ) ) { + return; + } + // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- The rows skip the object cache on purpose (see the class comment). + $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name IN (%s, %s, %s)", self::PREFIX . $key . '_n', self::PREFIX . $key . '_l', self::PREFIX . $key . '_s' ) ); + } + + /** + * Take sent overflow off, and remove the counters of hours that are over. + * + * @param array $overflow Overflow sent by hour. + * @param int $current The current hour. + * + * @return void + */ + public static function take_hours( array $overflow, int $current ): void { + global $wpdb; + + // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- The rows skip the object cache on purpose (see the class comment). + foreach ( $overflow as $hour => $count ) { + $wpdb->query( $wpdb->prepare( "UPDATE {$wpdb->options} SET option_value = option_value - %d WHERE option_name = %s", $count, self::PREFIX . 'o_' . (int) $hour . '_n' ) ); + } + $rows = $wpdb->get_col( $wpdb->prepare( "SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE %s OR option_name LIKE %s", $wpdb->esc_like( self::PREFIX . 'h_' ) . '%', $wpdb->esc_like( self::PREFIX . 'o_' ) . '%' ) ); + foreach ( (array) $rows as $name ) { + if ( 1 === preg_match( '/^' . preg_quote( self::PREFIX, '/' ) . '([ho])_(\d+)_n$/', (string) $name, $match ) && (int) $match[2] < $current ) { + // An hour that is over: its overflow is sent, or it had none. + $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name = %s", (string) $name ) ); + } + } + $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s AND CAST(option_value AS SIGNED) <= 0", $wpdb->esc_like( self::PREFIX . 'o_' ) . '%' ) ); + // phpcs:enable + } + + /** + * Take the direct send lock of a fingerprint: at most one direct send + * per fingerprint per period. Atomic like the token refresh lock: an + * insert that only one request wins, and an expired lock is taken over + * by an update that only one request wins. + * + * @param string $fingerprint The fingerprint. + * @param int $period Seconds between direct sends. + * @param int $now The time. + * + * @return bool Whether this request may send. + */ + public static function lock( string $fingerprint, int $period, int $now ): bool { + global $wpdb; + + if ( 1 !== preg_match( '/^[0-9a-f]{40}$/', $fingerprint ) ) { + return false; + } + $name = self::LOCK_PREFIX . $fingerprint; + + // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- The lock must bypass the options cache to be atomic. + $inserted = $wpdb->query( $wpdb->prepare( "INSERT IGNORE INTO {$wpdb->options} (option_name, option_value, autoload) VALUES (%s, %s, 'no')", $name, (string) $now ) ); + if ( 1 === (int) $inserted ) { + // phpcs:enable + return true; + } + + $locked_at = (string) $wpdb->get_var( $wpdb->prepare( "SELECT option_value FROM {$wpdb->options} WHERE option_name = %s", $name ) ); + if ( (int) $locked_at > $now - $period ) { + // phpcs:enable + return false; + } + + $taken = $wpdb->query( $wpdb->prepare( "UPDATE {$wpdb->options} SET option_value = %s WHERE option_name = %s AND option_value = %s", (string) $now, $name, $locked_at ) ); + // phpcs:enable + + return 1 === (int) $taken; + } + + /** + * Remove the direct send locks older than a period. + * + * @param int $period The period. + * @param int $now The time. + * + * @return void + */ + public static function delete_old_locks( int $period, int $now ): void { + global $wpdb; + + // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- The locks are removed by name prefix, which the options API can't do. + $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s AND CAST(option_value AS UNSIGNED) < %d", $wpdb->esc_like( self::LOCK_PREFIX ) . '%', $now - $period ) ); + } + + /** + * Remove everything (when the site disconnects or capture is turned off). + * + * @return void + */ + public static function delete_all(): void { + global $wpdb; + + // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- The rows are removed by name prefix, which the options API can't do. + $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s", $wpdb->esc_like( self::PREFIX ) . '%' ) ); + delete_option( self::KNOWN_OPTION ); + } +} diff --git a/src/Errors/load.php b/src/Errors/load.php new file mode 100644 index 0000000..e936f4f --- /dev/null +++ b/src/Errors/load.php @@ -0,0 +1,32 @@ + self::get_plugins(), // Must-use plugins, their folders and drop-ins, with content hashes. 'mu_plugins' => MuPlugins::scan(), + // Whether PHP errors are caught, and from before plugins load. + 'php_errors' => \Scanfully\Errors\Controller::status(), ]; // filter data. diff --git a/src/Health/MuPlugins.php b/src/Health/MuPlugins.php index 132cd30..9c64ba4 100644 --- a/src/Health/MuPlugins.php +++ b/src/Health/MuPlugins.php @@ -61,6 +61,15 @@ final class MuPlugins { */ private const MAX_TEXT = 500; + /** + * Must-use plugins the Scanfully plugin installs itself, by file name, + * with who installed them: sent as `known`, so Scanfully doesn't flag + * its own file as an unknown must-use plugin. + */ + public const KNOWN = [ + \Scanfully\Errors\MuPlugin::FILE => 'Scanfully', + ]; + /** * The MU plugins, MU plugin folders and drop-ins of the site, for the site * data sync. Also remembers what it saw for the hourly check. @@ -176,9 +185,8 @@ private static function file_entry( string $kind, string $file, string $path, ar return null; } - $name = self::text( $header['Name'] ?? '' ); - - return [ + $name = self::text( $header['Name'] ?? '' ); + $entry = [ 'kind' => $kind, 'file' => $file, 'name' => '' !== $name ? $name : $file, @@ -189,6 +197,11 @@ private static function file_entry( string $kind, string $file, string $path, ar 'modified' => (int) $stat['mtime'], 'hash' => self::hash( $path, (int) $stat['size'], (int) $stat['mtime'], $content_dir, $cache, $used ), ]; + if ( 'mu' === $kind && isset( self::KNOWN[ $file ] ) ) { + $entry['known'] = self::KNOWN[ $file ]; + } + + return $entry; } /** diff --git a/src/Main.php b/src/Main.php index 2d8e739..835cc8c 100644 --- a/src/Main.php +++ b/src/Main.php @@ -128,6 +128,9 @@ public function setup(): void { /** Register cron */ Cron\Controller::setup(); + /** Register PHP error monitoring (the handlers start in the main plugin file or the must-use plugin) */ + Errors\Controller::setup(); + /** Register connect */ Connect\Controller::setup(); Connect\Page::register(); diff --git a/tests/Unit/Cron/ScheduleEventsTest.php b/tests/Unit/Cron/ScheduleEventsTest.php index 9143143..bb3fca4 100644 --- a/tests/Unit/Cron/ScheduleEventsTest.php +++ b/tests/Unit/Cron/ScheduleEventsTest.php @@ -56,7 +56,7 @@ static function ( $timestamp, $hook, $args, $group, $unique = false ) use ( &$un Controller::schedule_events(); - $this->assertCount( 7, $unique_flags ); + $this->assertCount( 8, $unique_flags ); $this->assertSame( [ true ], array_values( array_unique( $unique_flags ) ), 'Every job must be scheduled as unique.' ); } diff --git a/tests/Unit/Errors/AttributionTest.php b/tests/Unit/Errors/AttributionTest.php new file mode 100644 index 0000000..f9d9c88 --- /dev/null +++ b/tests/Unit/Errors/AttributionTest.php @@ -0,0 +1,236 @@ + '/srv/site/wp-content/plugins', + 'mu_plugins' => '/srv/site/wp-content/mu-plugins/', + 'themes' => [ '/srv/site/wp-content/themes', '/srv/shared-themes' ], + 'content' => '/srv/site/wp-content', + 'abspath' => '/srv/site/', + ], + '6.8.1', + function ( string $kind, string $slug ): array { + $this->asked[] = $kind . ':' . $slug; + $headers = [ + 'plugin:woocommerce' => [ + 'name' => 'WooCommerce', + 'version' => '9.2.0', + ], + 'plugin:hello' => [ + 'name' => 'Hello Dolly', + 'version' => '1.7.2', + ], + 'theme:storefront' => [ + 'name' => 'Storefront & Co', + 'version' => '4.6.0', + ], + 'mu_plugin:host.php' => [ + 'name' => 'Host tools', + 'version' => '2', + ], + 'dropin:db.php' => [ + 'name' => 'Query Monitor Database Class (Drop-in)', + 'version' => '', + ], + ]; + + return $headers[ $kind . ':' . $slug ] ?? [ + 'name' => '', + 'version' => '', + ]; + } + ); + } + + public function test_a_plugin_file_names_the_plugin_by_its_folder(): void { + $source = $this->attribution()->source( '/srv/site/wp-content/plugins/woocommerce/includes/class-wc-order.php' ); + + $this->assertSame( + [ + 'kind' => 'plugin', + 'slug' => 'woocommerce', + 'name' => 'WooCommerce', + 'version' => '9.2.0', + ], + $source + ); + } + + public function test_a_single_file_plugin_is_named_by_its_file(): void { + $this->assertSame( 'hello', $this->attribution()->source( '/srv/site/wp-content/plugins/hello.php' )['slug'] ); + } + + public function test_a_theme_in_a_second_theme_root_and_a_name_with_entities(): void { + $source = $this->attribution()->source( '/srv/shared-themes/storefront/functions.php' ); + + $this->assertSame( 'theme', $source['kind'] ); + $this->assertSame( 'storefront', $source['slug'] ); + $this->assertSame( 'Storefront & Co', $source['name'] ); + } + + public function test_must_use_plugins_drop_ins_and_core(): void { + $attribution = $this->attribution(); + + $this->assertSame( 'mu_plugin', $attribution->source( '/srv/site/wp-content/mu-plugins/host.php' )['kind'] ); + $this->assertSame( 'host.php', $attribution->source( '/srv/site/wp-content/mu-plugins/host.php' )['slug'] ); + $this->assertSame( 'Host tools', $attribution->source( '/srv/site/wp-content/mu-plugins/host.php' )['name'] ); + $this->assertSame( 'loader', $attribution->source( '/srv/site/wp-content/mu-plugins/loader/includes/a.php' )['slug'] ); + $this->assertSame( 'dropin', $attribution->source( '/srv/site/wp-content/db.php' )['kind'] ); + $this->assertSame( 'db.php', $attribution->source( '/srv/site/wp-content/db.php' )['slug'] ); + $this->assertSame( + [ + 'kind' => 'core', + 'slug' => 'wordpress', + 'name' => 'WordPress', + 'version' => '6.8.1', + ], + $attribution->source( '/srv/site/wp-includes/class-wp-hook.php' ) + ); + $this->assertSame( 'core', $attribution->source( '/srv/site/wp-admin/admin-ajax.php' )['kind'] ); + $this->assertSame( 'core', $attribution->source( '/srv/site/wp-settings.php' )['kind'] ); + } + + public function test_an_error_inside_core_is_attributed_to_the_plugin_that_called_it(): void { + $source = $this->attribution()->source( + '/srv/site/wp-includes/class-wp-hook.php', + [ + [ + 'file' => '/srv/site/wp-includes/plugin.php', + 'line' => 517, + 'function' => 'apply_filters', + ], + [ + 'file' => '/srv/site/wp-content/plugins/woocommerce/woocommerce.php', + 'line' => 40, + 'function' => 'do_action', + ], + [ + 'file' => '/srv/site/wp-content/themes/storefront/functions.php', + 'line' => 9, + 'function' => 'wc_run', + ], + ] + ); + + $this->assertSame( 'plugin', $source['kind'] ); + $this->assertSame( 'woocommerce', $source['slug'] ); + } + + public function test_an_error_inside_core_called_only_by_core_stays_core(): void { + $source = $this->attribution()->source( + '/srv/site/wp-includes/formatting.php', + [ + [ + 'file' => '/srv/site/wp-admin/edit.php', + 'line' => 10, + 'function' => 'esc_html', + ], + ] + ); + + $this->assertSame( 'core', $source['kind'] ); + } + + public function test_files_elsewhere_are_unknown(): void { + $attribution = $this->attribution(); + + $this->assertSame( 'unknown', $attribution->source( '/usr/share/php/PEAR.php' )['kind'] ); + $this->assertSame( 'unknown', $attribution->source( '/srv/site/vendor/autoload.php' )['kind'] ); + $this->assertSame( 'unknown', $attribution->source( '/srv/site/wp-content/uploads/x.php' )['kind'] ); + $this->assertSame( 'unknown', $attribution->source( '' )['kind'] ); + $this->assertSame( 'unknown', $attribution->source( 'Unknown' )['kind'] ); + } + + public function test_headers_are_read_once_per_source(): void { + $attribution = $this->attribution(); + $attribution->source( '/srv/site/wp-content/plugins/woocommerce/a.php' ); + $attribution->source( '/srv/site/wp-content/plugins/woocommerce/b.php' ); + + $this->assertSame( [ 'plugin:woocommerce' ], $this->asked ); + } + + public function test_a_header_reader_that_throws_leaves_the_name_empty(): void { + $attribution = new Attribution( + [ + 'plugins' => '/srv/site/wp-content/plugins', + 'abspath' => '/srv/site', + ], + '6.8', + static function (): array { + throw new \RuntimeException( 'no headers' ); + } + ); + + $this->assertSame( '', $attribution->source( '/srv/site/wp-content/plugins/x/x.php' )['name'] ); + $this->assertSame( 'x', $attribution->source( '/srv/site/wp-content/plugins/x/x.php' )['slug'] ); + } + + public function test_paths_become_relative_to_the_wordpress_root(): void { + $attribution = $this->attribution(); + + $this->assertSame( 'wp-content/plugins/woocommerce/woocommerce.php', $attribution->relative( '/srv/site/wp-content/plugins/woocommerce/woocommerce.php' ) ); + $this->assertSame( 'wp-includes/class-wp-hook.php', $attribution->relative( '/srv/site/wp-includes/class-wp-hook.php' ) ); + $this->assertSame( 'wp-content/themes/storefront/functions.php', $attribution->relative( '/srv/shared-themes/storefront/functions.php' ) ); + $this->assertSame( '…/share/php/PEAR.php', $attribution->relative( '/usr/share/php/PEAR.php' ) ); + $this->assertSame( 'wp-content/plugins/x/x.php', $attribution->relative( '/srv/site/wp-content/plugins/x/x.php(12) : eval()\'d code' ) ); + $this->assertSame( '', $attribution->relative( '' ) ); + $this->assertSame( 'Unknown', $attribution->relative( 'Unknown' ) ); + } + + public function test_windows_paths_and_a_content_folder_outside_the_root(): void { + $attribution = new Attribution( + [ + 'plugins' => 'C:\\inetpub\\site\\app\\plugins', + 'content' => 'C:\\inetpub\\site\\app', + 'abspath' => 'C:\\inetpub\\site\\wp\\', + ] + ); + + $this->assertSame( 'plugin', $attribution->source( 'C:\\inetpub\\site\\app\\plugins\\shop\\shop.php' )['kind'] ); + $this->assertSame( 'wp-content/plugins/shop/shop.php', $attribution->relative( 'C:\\inetpub\\site\\app\\plugins\\shop\\shop.php' ) ); + $this->assertSame( 'wp-includes/load.php', $attribution->relative( 'C:\\inetpub\\site\\wp\\wp-includes\\load.php' ) ); + } + + public function test_server_paths_in_a_message_are_made_relative(): void { + $attribution = $this->attribution(); + + $this->assertSame( + "require(): Failed opening 'wp-content/plugins/shop/missing.php' (include_path='.:…/php')", + $attribution->relative_in_text( "require(): Failed opening '/srv/site/wp-content/plugins/shop/missing.php' (include_path='.:/usr/share/php')" ) + ); + $this->assertSame( + 'Uncaught Error in wp-content/themes/storefront/functions.php:9', + $attribution->relative_in_text( 'Uncaught Error in /srv/shared-themes/storefront/functions.php:9' ) + ); + } + + public function test_a_root_of_slash_is_ignored(): void { + $attribution = new Attribution( [ 'abspath' => '/' ] ); + + $this->assertSame( 'unknown', $attribution->source( '/etc/passwd' )['kind'] ); + $this->assertSame( '…/etc/passwd', $attribution->relative( '/etc/passwd' ) ); + } +} diff --git a/tests/Unit/Errors/BuilderTest.php b/tests/Unit/Errors/BuilderTest.php new file mode 100644 index 0000000..7c1d836 --- /dev/null +++ b/tests/Unit/Errors/BuilderTest.php @@ -0,0 +1,230 @@ + 'front', + 'path' => '/shop/', + 'php' => '8.2.1', + 'wp' => '6.8', + 'maintenance' => false, + ]; + + private function attribution(): Attribution { + return new Attribution( + [ + 'plugins' => '/srv/site/wp-content/plugins', + 'themes' => '/srv/site/wp-content/themes', + 'content' => '/srv/site/wp-content', + 'abspath' => '/srv/site', + ], + '6.8', + static fn( string $kind, string $slug ): array => [ + 'name' => ucfirst( $slug ), + 'version' => '1.0', + ] + ); + } + + public function test_a_warning_with_its_stack_frames(): void { + $error = Builder::build( + [ + 'type' => E_WARNING, + 'message' => 'Undefined array key "total" for jane@scanfully.com', + 'file' => '/srv/site/wp-content/plugins/shop/orders.php', + 'line' => 42, + 'trace' => [ + [ + 'file' => '/srv/site/wp-content/plugins/shop/shop.php', + 'line' => 10, + 'function' => 'total', + 'class' => 'Shop\\Orders', + 'type' => '->', + 'args' => [ 'secret' ], + ], + [ + 'file' => '/srv/site/wp-includes/class-wp-hook.php', + 'line' => 324, + 'function' => '{closure}', + ], + [ + 'file' => '/srv/site/wp-includes/class-wp-hook.php', + 'line' => 348, + 'function' => 'apply_filters', + 'class' => 'WP_Hook', + 'type' => '->', + ], + ], + ], + $this->attribution(), + self::CONTEXT + ); + + $this->assertSame( 'warning', $error['level'] ); + $this->assertSame( 'Undefined array key "total" for [email]', $error['message'] ); + $this->assertSame( 'wp-content/plugins/shop/orders.php', $error['file'] ); + $this->assertSame( 42, $error['line'] ); + $this->assertSame( 'Shop\\Orders->total', $error['function'] ); + $this->assertSame( + [ + [ + 'file' => 'wp-content/plugins/shop/shop.php', + 'line' => 10, + 'function' => 'Shop\\Orders->total', + ], + [ + 'file' => 'wp-includes/class-wp-hook.php', + 'line' => 324, + 'function' => '{closure}', + ], + [ + 'file' => 'wp-includes/class-wp-hook.php', + 'line' => 348, + 'function' => 'WP_Hook->apply_filters', + ], + ], + $error['trace'] + ); + $this->assertSame( 'plugin', $error['source']['kind'] ); + $this->assertSame( 'shop', $error['source']['slug'] ); + $this->assertSame( self::CONTEXT, $error['context'] ); + $this->assertSame( Fingerprint::of( 'warning', 'wp-content/plugins/shop/orders.php', 'Shop\\Orders->total', 'Undefined array key "total" for [email]' ), $error['fingerprint'] ); + } + + public function test_an_uncaught_exception_gets_its_message_and_trace_split(): void { + $message = "Uncaught RuntimeException: Payment failed for order 12 in /srv/site/wp-content/plugins/shop/gateway.php:88\nStack trace:\n#0 /srv/site/wp-content/plugins/shop/checkout.php(31): Shop\\Gateway->pay(Object(WC_Order))\n#1 /srv/site/wp-includes/class-wp-hook.php(324): shop_checkout('')\n#2 {main}\n thrown"; + $error = Builder::build( + [ + 'type' => E_ERROR, + 'message' => $message, + 'file' => '/srv/site/wp-content/plugins/shop/gateway.php', + 'line' => 88, + 'trace' => [], + ], + $this->attribution(), + self::CONTEXT + ); + + $this->assertSame( 'fatal', $error['level'] ); + $this->assertSame( 'Uncaught RuntimeException: Payment failed for order 12', $error['message'] ); + $this->assertSame( 'Shop\\Gateway->pay', $error['function'] ); + $this->assertSame( + [ + [ + 'file' => 'wp-content/plugins/shop/checkout.php', + 'line' => 31, + 'function' => 'Shop\\Gateway->pay', + ], + [ + 'file' => 'wp-includes/class-wp-hook.php', + 'line' => 324, + 'function' => 'shop_checkout', + ], + ], + $error['trace'] + ); + $this->assertSame( 'shop', $error['source']['slug'] ); + } + + public function test_a_fatal_error_without_a_trace(): void { + $error = Builder::build( + [ + 'type' => E_ERROR, + 'message' => 'Call to undefined function wc_get_order() in /srv/site/wp-content/themes/storefront/functions.php', + 'file' => '/srv/site/wp-content/themes/storefront/functions.php', + 'line' => 9, + ], + $this->attribution(), + self::CONTEXT + ); + + $this->assertSame( 'Call to undefined function wc_get_order() in wp-content/themes/storefront/functions.php', $error['message'] ); + $this->assertSame( '', $error['function'] ); + $this->assertSame( [], $error['trace'] ); + $this->assertSame( 'theme', $error['source']['kind'] ); + $this->assertSame( 'storefront', $error['source']['slug'] ); + } + + public function test_a_core_error_is_attributed_through_the_trace(): void { + $error = Builder::build( + [ + 'type' => E_WARNING, + 'message' => 'foreach() argument must be of type array|object, null given', + 'file' => '/srv/site/wp-includes/formatting.php', + 'line' => 100, + 'trace' => [ + [ + 'file' => '/srv/site/wp-content/plugins/shop/shop.php', + 'line' => 10, + 'function' => 'wp_kses', + ], + ], + ], + $this->attribution(), + self::CONTEXT + ); + + $this->assertSame( 'wp_kses', $error['function'] ); + $this->assertSame( 'wp-includes/formatting.php', $error['file'] ); + $this->assertSame( 'plugin', $error['source']['kind'] ); + } + + public function test_a_notice_is_not_built(): void { + $this->assertNull( + Builder::build( + [ + 'type' => E_NOTICE, + 'message' => 'x', + 'file' => '', + 'line' => 0, + ], + $this->attribution(), + self::CONTEXT + ) + ); + $this->assertNull( + Builder::build( + [ + 'type' => E_DEPRECATED, + 'message' => 'x', + 'file' => '', + 'line' => 0, + ], + $this->attribution(), + self::CONTEXT + ) + ); + $this->assertSame( 'fatal', Builder::level( E_PARSE ) ); + $this->assertSame( 'fatal', Builder::level( E_USER_ERROR ) ); + $this->assertSame( 'fatal', Builder::level( E_RECOVERABLE_ERROR ) ); + $this->assertSame( 'warning', Builder::level( E_USER_WARNING ) ); + } + + public function test_the_trace_is_capped(): void { + $frames = []; + for ( $i = 0; $i < 30; $i++ ) { + $frames[] = [ + 'file' => '/srv/site/a.php', + 'line' => $i, + 'function' => 'f' . $i, + ]; + } + + $this->assertCount( Builder::MAX_FRAMES, Builder::frames( $frames, $this->attribution() ) ); + } +} diff --git a/tests/Unit/Errors/ContextTest.php b/tests/Unit/Errors/ContextTest.php new file mode 100644 index 0000000..8f64232 --- /dev/null +++ b/tests/Unit/Errors/ContextTest.php @@ -0,0 +1,107 @@ + 'GET', + 'REQUEST_URI' => '/shop/?add-to-cart=12', + ]; + + public function test_the_kind_of_request(): void { + $none = [ + 'cli' => false, + 'cron' => false, + 'ajax' => false, + 'rest' => false, + 'admin' => false, + ]; + + $this->assertSame( 'front', Context::kind( self::WEB, $none ) ); + $this->assertSame( 'admin', Context::kind( self::WEB, [ 'admin' => true ] + $none ) ); + $this->assertSame( + 'ajax', + Context::kind( + self::WEB, + [ + 'ajax' => true, + 'admin' => true, + ] + $none + ) + ); + $this->assertSame( 'cron', Context::kind( self::WEB, [ 'cron' => true ] + $none ) ); + $this->assertSame( 'cli', Context::kind( self::WEB, [ 'cli' => true ] + $none ) ); + $this->assertSame( 'rest', Context::kind( self::WEB, [ 'rest' => true ] + $none ) ); + } + + public function test_a_rest_request_is_known_by_its_path_before_wordpress_dispatches_it(): void { + $none = [ + 'cli' => false, + 'cron' => false, + 'ajax' => false, + 'rest' => false, + 'admin' => false, + ]; + + $this->assertSame( + 'rest', + Context::kind( + [ + 'REQUEST_METHOD' => 'GET', + 'REQUEST_URI' => '/wp-json/wc/v3/orders?page=2', + ], + $none + ) + ); + $this->assertSame( + 'rest', + Context::kind( + [ + 'REQUEST_METHOD' => 'GET', + 'REQUEST_URI' => '/index.php/wp-json', + ], + $none + ) + ); + $this->assertSame( + 'rest', + Context::kind( + [ + 'REQUEST_METHOD' => 'POST', + 'REQUEST_URI' => '/?rest_route=/wp/v2/posts', + ], + $none + ) + ); + $this->assertSame( + 'front', + Context::kind( + [ + 'REQUEST_METHOD' => 'GET', + 'REQUEST_URI' => '/wp-json-export/', + ], + $none + ) + ); + } + + public function test_the_path_has_no_query_string_and_no_control_characters(): void { + $this->assertSame( '/shop/', Context::path( self::WEB ) ); + $this->assertSame( '/a/b', Context::path( [ 'REQUEST_URI' => '/a/b#frag' ] ) ); + $this->assertSame( '/ab', Context::path( [ 'REQUEST_URI' => "/a\x00b" ] ) ); + $this->assertSame( '', Context::path( [] ) ); + $this->assertSame( 200, strlen( Context::path( [ 'REQUEST_URI' => '/' . str_repeat( 'a', 300 ) ] ) ) ); + } +} diff --git a/tests/Unit/Errors/FingerprintTest.php b/tests/Unit/Errors/FingerprintTest.php new file mode 100644 index 0000000..95aaaff --- /dev/null +++ b/tests/Unit/Errors/FingerprintTest.php @@ -0,0 +1,43 @@ +assertSame( 'Undefined array key "?"', Fingerprint::normalize( 'Undefined array key "customer_id"' ) ); + $this->assertSame( 'Undefined array key ?', Fingerprint::normalize( 'Undefined array key 3' ) ); + $this->assertSame( "Undefined index: '?'", Fingerprint::normalize( "Undefined index: 'it\\'s'" ) ); + $this->assertSame( 'Allowed memory size of ? bytes exhausted (tried to allocate ? bytes)', Fingerprint::normalize( 'Allowed memory size of 134217728 bytes exhausted (tried to allocate 20480 bytes)' ) ); + $this->assertSame( 'Order ? was paid ? (ref ?)', Fingerprint::normalize( "Order 1234 was paid 12.50\n(ref 9f86d081884c7d659a2feaa0c55ad015)" ) ); + $this->assertSame( 'Call to undefined function wc_get_order_v2()', Fingerprint::normalize( 'Call to undefined function wc_get_order_v2()' ) ); + } + + public function test_the_same_error_on_another_line_or_with_another_value_has_the_same_fingerprint(): void { + $first = Fingerprint::of( 'warning', 'wp-content/plugins/shop/orders.php', 'shop_total', 'Undefined array key "total" for order 12' ); + $second = Fingerprint::of( 'warning', 'wp-content/plugins/shop/orders.php', 'shop_total', 'Undefined array key "tax" for order 999' ); + + $this->assertSame( $first, $second ); + $this->assertMatchesRegularExpression( '/^[0-9a-f]{40}$/', $first ); + } + + public function test_the_level_file_and_function_tell_errors_apart(): void { + $base = Fingerprint::of( 'warning', 'a.php', 'f', 'm' ); + + $this->assertNotSame( $base, Fingerprint::of( 'fatal', 'a.php', 'f', 'm' ) ); + $this->assertNotSame( $base, Fingerprint::of( 'warning', 'b.php', 'f', 'm' ) ); + $this->assertNotSame( $base, Fingerprint::of( 'warning', 'a.php', 'g', 'm' ) ); + $this->assertNotSame( $base, Fingerprint::of( 'warning', 'a.php', 'f', 'other' ) ); + } +} diff --git a/tests/Unit/Errors/MonitorTest.php b/tests/Unit/Errors/MonitorTest.php new file mode 100644 index 0000000..3f2456b --- /dev/null +++ b/tests/Unit/Errors/MonitorTest.php @@ -0,0 +1,167 @@ + + */ + private array $options = []; + + protected function setUp(): void { + parent::setUp(); + Monitor::reset(); + $this->options = [ + 'scanfully_connect_is_connected' => 'yes', + 'active_plugins' => [ 'scanfully/scanfully.php' ], + ]; + Functions\when( 'get_option' )->alias( fn( $name, $default = false ) => $this->options[ $name ] ?? $default ); + Functions\when( 'wp_load_alloptions' )->alias( fn() => $this->options ); + Functions\when( 'is_multisite' )->justReturn( false ); + } + + protected function tearDown(): void { + Monitor::reset(); + parent::tearDown(); + } + + public function test_it_runs_only_when_connected_and_switched_on(): void { + $this->assertTrue( Monitor::should_run() ); + + $this->options['scanfully_connect_php_errors_enabled'] = 'no'; + $this->assertFalse( Monitor::should_run() ); + + $this->options['scanfully_connect_php_errors_enabled'] = 'yes'; + $this->options['scanfully_connect_is_connected'] = 'no'; + $this->assertFalse( Monitor::should_run() ); + } + + public function test_the_filter_turns_it_off(): void { + \Brain\Monkey\Filters\expectApplied( 'scanfully_php_errors_enabled' )->andReturn( false ); + + $this->assertFalse( Monitor::should_run() ); + } + + public function test_the_must_use_plugin_runs_only_while_the_plugin_is_active(): void { + $this->assertTrue( Monitor::should_run( 'scanfully/scanfully.php' ) ); + $this->assertFalse( Monitor::should_run( 'scanfully-dev/scanfully.php' ) ); + } + + public function test_a_warning_is_kept_and_passed_on_to_the_handler_that_was_there_before(): void { + Monitor::boot( 'plugin' ); + $this->assertSame( 'plugin', Monitor::origin() ); + // PHPUnit's own handler was there first. + $this->assertTrue( Monitor::takes_all_types() ); + + $passed_on = false; + try { + trigger_error( 'Something is off', E_USER_WARNING ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_trigger_error -- The warning under test. + } catch ( \Throwable $e ) { + // PHPUnit's handler turns the warning into an exception. + $passed_on = false !== strpos( $e->getMessage(), 'Something is off' ); + } + + $this->assertTrue( $passed_on, 'The warning reached the previous handler.' ); + $recorded = array_values( Monitor::recorded() ); + $this->assertCount( 1, $recorded ); + $this->assertSame( E_USER_WARNING, $recorded[0]['type'] ); + $this->assertSame( 'Something is off', $recorded[0]['message'] ); + $this->assertSame( __FILE__, $recorded[0]['file'] ); + $this->assertSame( __FUNCTION__, $recorded[0]['trace'][0]['function'] ); + } + + public function test_it_boots_once(): void { + Monitor::boot( 'mu', 'scanfully/scanfully.php' ); + Monitor::boot( 'plugin' ); + + $this->assertSame( 'mu', Monitor::origin() ); + } + + public function test_it_does_not_boot_when_switched_off(): void { + $this->options['scanfully_connect_php_errors_enabled'] = 'no'; + Monitor::boot( 'plugin' ); + + $this->assertSame( '', Monitor::origin() ); + } + + public function test_without_a_previous_handler_it_returns_false_so_php_handles_the_error(): void { + $this->assertFalse( Monitor::handle( E_WARNING, 'Undefined variable $x', '/srv/site/a.php', 3 ) ); + $this->assertCount( 1, Monitor::recorded() ); + } + + public function test_silenced_errors_notices_and_deprecations_are_skipped(): void { + $reporting = error_reporting( E_ALL & ~E_WARNING ); + Monitor::handle( E_WARNING, 'Silenced', '/srv/site/a.php', 1 ); + error_reporting( $reporting ); + + Monitor::handle( E_NOTICE, 'A notice', '/srv/site/a.php', 2 ); + Monitor::handle( E_DEPRECATED, 'Deprecated', '/srv/site/a.php', 3 ); + Monitor::handle( E_USER_DEPRECATED, 'Deprecated', '/srv/site/a.php', 4 ); + + $this->assertSame( [], Monitor::recorded() ); + } + + public function test_the_same_warning_is_counted_and_distinct_ones_are_capped(): void { + for ( $i = 0; $i < 5; $i++ ) { + Monitor::handle( E_WARNING, 'Again ' . $i, '/srv/site/a.php', 1 ); + } + for ( $line = 100; $line < 100 + Monitor::MAX_PER_REQUEST + 5; $line++ ) { + Monitor::handle( E_WARNING, 'Other', '/srv/site/a.php', $line ); + } + + $recorded = Monitor::recorded(); + $this->assertCount( Monitor::MAX_PER_REQUEST, $recorded ); + $this->assertSame( 5, $recorded[ E_WARNING . ':/srv/site/a.php:1' ]['count'] ); + $this->assertSame( 'Again 0', $recorded[ E_WARNING . ':/srv/site/a.php:1' ]['message'] ); + } + + public function test_errors_on_two_lines_with_the_same_fingerprint_are_added_up(): void { + Monitor::handle( E_WARNING, 'Undefined array key "a"', '/srv/site/wp-content/plugins/shop/a.php', 10 ); + Monitor::handle( E_WARNING, 'Undefined array key "b"', '/srv/site/wp-content/plugins/shop/a.php', 12 ); + Monitor::handle( E_WARNING, 'Undefined array key "b"', '/srv/site/wp-content/plugins/shop/a.php', 12 ); + + $built = Monitor::build( + new Attribution( + [ + 'plugins' => '/srv/site/wp-content/plugins', + 'abspath' => '/srv/site', + ] + ), + [ + 'request' => 'front', + 'path' => '/', + 'php' => '8.2', + 'wp' => '6.8', + 'maintenance' => false, + ] + ); + + $this->assertCount( 1, $built ); + $error = array_values( $built )[0]; + $this->assertSame( 3, $error['count'] ); + $this->assertSame( 'plugin', $error['source']['kind'] ); + $this->assertSame( 'Undefined array key "a"', $error['message'] ); + } + + public function test_a_long_message_is_cut_in_memory(): void { + Monitor::handle( E_WARNING, str_repeat( 'x', 10000 ), '/srv/site/a.php', 1 ); + + $this->assertSame( 4000, strlen( array_values( Monitor::recorded() )[0]['message'] ) ); + } +} diff --git a/tests/Unit/Errors/ReporterTest.php b/tests/Unit/Errors/ReporterTest.php new file mode 100644 index 0000000..5aa6d97 --- /dev/null +++ b/tests/Unit/Errors/ReporterTest.php @@ -0,0 +1,108 @@ + str_repeat( 'a', 40 ), + 'level' => 'fatal', + 'source' => [ + 'kind' => 'plugin', + 'slug' => 'shop', + 'name' => 'Shop', + 'version' => '1.2.0', + 'extra' => 'x', + ], + 'message' => 'Call to undefined function shop_x()', + 'file' => 'wp-content/plugins/shop/shop.php', + 'line' => 12, + 'function' => 'shop_boot', + 'trace' => [ + [ + 'file' => 'wp-settings.php', + 'line' => 545, + 'function' => 'include_once', + 'args' => [ 'x' ], + ], + ], + 'context' => [ + 'request' => 'admin', + 'path' => '/wp-admin/', + 'php' => '8.2.1', + 'wp' => '6.8', + 'maintenance' => true, + ], + 'first_seen' => 1, + ], + 3, + 1762500000, + 1762500060 + ); + + $this->assertSame( + [ + 'fingerprint' => str_repeat( 'a', 40 ), + 'level' => 'fatal', + 'source' => [ + 'kind' => 'plugin', + 'slug' => 'shop', + 'name' => 'Shop', + 'version' => '1.2.0', + ], + 'message' => 'Call to undefined function shop_x()', + 'file' => 'wp-content/plugins/shop/shop.php', + 'line' => 12, + 'function' => 'shop_boot', + 'trace' => [ + [ + 'file' => 'wp-settings.php', + 'line' => 545, + 'function' => 'include_once', + ], + ], + 'context' => [ + 'request' => 'admin', + 'path' => '/wp-admin/', + 'php' => '8.2.1', + 'wp' => '6.8', + 'maintenance' => true, + ], + 'count' => 3, + 'first_seen' => '2025-11-07T07:20:00Z', + 'last_seen' => '2025-11-07T07:21:00Z', + ], + $entry + ); + } + + public function test_the_payload_has_the_errors_and_the_overflow(): void { + $this->assertSame( + [ + 'errors' => [], + 'overflow' => 0, + ], + Reporter::payload( [], -1 ) + ); + $this->assertSame( + [ + 'errors' => [ [ 'level' => 'fatal' ] ], + 'overflow' => 4, + ], + Reporter::payload( [ [ 'level' => 'fatal' ] ], 4 ) + ); + } +} diff --git a/tests/Unit/Errors/ScrubberTest.php b/tests/Unit/Errors/ScrubberTest.php new file mode 100644 index 0000000..43f1144 --- /dev/null +++ b/tests/Unit/Errors/ScrubberTest.php @@ -0,0 +1,71 @@ +assertSame( $expected, Scrubber::scrub( $text ) ); + } + + /** + * @return array + */ + public function secrets(): array { + return [ + 'email' => [ 'Could not send to jane.doe+shop@scanfully.com', 'Could not send to [email]' ], + 'password' => [ 'Login failed: password=hunter2 for admin', 'Login failed: password=[redacted] for admin' ], + 'password quoted' => [ "Array ( 'pass' => 'hunter2', 'user' => 'bob' )", "Array ( 'pass' => [redacted], 'user' => 'bob' )" ], + 'api key' => [ 'api_key: abcdef123456 rejected', 'api_key: [redacted] rejected' ], + 'bearer' => [ 'Header Authorization: Bearer eyJhbGciOi.eyJzdWIi.SflKxw rejected', 'Header Authorization: [redacted] rejected' ], + // Made up at run time, so no key-shaped text is in the repository. + 'stripe key' => [ 'Invalid key sk_' . 'live_' . str_repeat( 'Zx9', 8 ) . ' given', 'Invalid key [key] given' ], + 'aws key' => [ 'AK' . 'IA' . str_repeat( 'Q7', 8 ) . ' denied', '[key] denied' ], + 'hash' => [ 'Token 9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08 expired', 'Token [key] expired' ], + 'long key' => [ 'Key AbCdEfGhIjKlMnOpQrStUvWxYz0123456789abcdefghij invalid', 'Key [key] invalid' ], + 'query string' => [ 'file_get_contents(https://api.scanfully.com/v1/x?token=abc&user=1): Failed', 'file_get_contents(https://api.scanfully.com/v1/x?[query]): Failed' ], + 'path query' => [ 'Bad request /wp-json/wc/v3/orders?consumer_key=ck_123', 'Bad request /wp-json/wc/v3/orders?[query]' ], + ]; + } + + public function test_ordinary_messages_are_left_alone(): void { + $messages = [ + 'Undefined array key "total"', + 'Call to undefined function wc_get_order()', + 'file_get_contents(wp-content/uploads/2026/11/export.csv): Failed to open stream: No such file or directory', + 'Allowed memory size of 134217728 bytes exhausted (tried to allocate 20480 bytes)', + 'Attempt to read property "ID" on null', + 'foreach() argument must be of type array|object, string given', + ]; + foreach ( $messages as $message ) { + $this->assertSame( $message, Scrubber::scrub( $message ) ); + } + } + + public function test_a_long_message_is_cut_to_a_thousand_characters(): void { + $message = str_repeat( 'é', 1500 ); + + $this->assertSame( 1000, mb_strlen( Scrubber::scrub( $message ), 'UTF-8' ) ); + $this->assertSame( 1000, strlen( Scrubber::scrub( str_repeat( 'a', 1500 ) ) ) ); + } + + public function test_invalid_utf8_is_cut_by_bytes(): void { + $message = str_repeat( "\xff", 1200 ); + + $this->assertSame( 1000, strlen( Scrubber::scrub( $message ) ) ); + } +} diff --git a/uninstall.php b/uninstall.php index 8e9c7f3..d1b7591 100644 --- a/uninstall.php +++ b/uninstall.php @@ -193,6 +193,26 @@ function scanfully_uninstall_options(): void { } } +/** + * Remove the PHP error monitor's must-use plugin, which serves the whole + * network, when it is Scanfully's (as Errors\MuPlugin::remove()). + * + * @return void + */ +function scanfully_uninstall_mu_plugin(): void { + $dir = defined( 'WPMU_PLUGIN_DIR' ) ? (string) WPMU_PLUGIN_DIR : WP_CONTENT_DIR . '/mu-plugins'; + $path = rtrim( $dir, '/\\' ) . '/scanfully-php-errors.php'; + if ( ! is_file( $path ) ) { + return; + } + $head = @file_get_contents( $path, false, null, 0, 1024 ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged, WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- A local file that may be unreadable. + if ( is_string( $head ) && false !== strpos( $head, 'Plugin Name: Scanfully PHP error monitor' ) ) { + wp_delete_file( $path ); + } +} + +scanfully_uninstall_mu_plugin(); + if ( is_multisite() ) { foreach ( get_sites( [ From 30aa661a9f22bca7637132d45cb9d8e812e7a767 Mon Sep 17 00:00:00 2001 From: Barry Kooij Date: Sat, 7 Nov 2026 01:25:52 +0100 Subject: [PATCH 2/7] Added: the readme lists the PHP error data the plugin sends and the must-use plugin it adds, under External services --- readme.txt | 3 +++ 1 file changed, 3 insertions(+) diff --git a/readme.txt b/readme.txt index 3d80f61..1ed8bce 100644 --- a/readme.txt +++ b/readme.txt @@ -139,10 +139,13 @@ Once connected, the plugin sends the following data to provide monitoring, diagn * **WordPress activity:** Event details, the acting user's ID and display name, and relevant old and new setting values. Content and file edits can include changed text or code and nearby context. This includes content from draft, private, and password-protected posts. * **WordPress user events:** User IDs, display names, and roles. Events for users with elevated permissions also include their email address. Successful logins and first application-password use for those users include IP addresses, forwarded proxy information, and browser details. * **Failed-login summaries:** Hourly counts and details of targeted users with elevated permissions. These summaries omit IP addresses and attempted usernames. +* **PHP errors:** PHP fatal errors and warnings, with how often each happened and when. Each error includes its message, the file, line and function it came from, and a short stack trace, without function arguments. File paths are relative to the WordPress folder. Email addresses, passwords, keys, tokens, and query strings are removed from messages. Each error also includes the plugin or theme that caused it and its version, the request type, the URL path without its query string, the PHP and WordPress versions, and whether an update was running. New errors are sent within a minute, counts hourly, and a new fatal error right away. * **WooCommerce configuration:** On connected WooCommerce sites, shop details sync even when checkout tests are off. These include the store address, WooCommerce version, product and cart/checkout URLs, shipping details, and login requirements. When checkout tests are enabled, Scanfully creates test orders. The plugin cancels test orders and deletes cancelled test orders through scheduled cleanup after seven days by default. * **Connection changes:** When the plugin is deactivated, disconnected, or deleted, that it happened and the display name of the person who did it. * **Sync diagnostics:** 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. +PHP error monitoring is enabled by default after connection. To catch errors raised while other plugins load, the plugin adds the file `scanfully-php-errors.php` to `wp-content/mu-plugins` when that folder is writable. It removes the file when the plugin is deactivated or deleted, or when PHP error monitoring is turned off. You can turn PHP error monitoring off under Settings > Scanfully. + Email checks are enabled by default after connection. The plugin sends test messages through your site's mail setup to a Scanfully address. Messages include site and version details and verification identifiers. The sender defaults to your WordPress administration email. The plugin also reports the detected mail plugin or WordPress version and local send errors to the API. You can turn these checks off under Settings > Scanfully. Read Scanfully's [terms and conditions](https://docs.scanfully.com/general/terms-and-conditions/), [privacy policy](https://docs.scanfully.com/general/privacy-policy/), and [GDPR information](https://docs.scanfully.com/general/is-scanfully-gdpr-compliant/) for service and data-handling details. From ad4ae56733a9cbaf43de328d759f826f5c3ee189 Mon Sep 17 00:00:00 2001 From: Barry Kooij Date: Sat, 7 Nov 2026 01:31:15 +0100 Subject: [PATCH 3/7] Added: integration tests that a fatal error while a plugin loads is caught by the must-use plugin and sent, and that without it the plugin still catches errors raised after plugins load --- src/Errors/Monitor.php | 9 +- tests/Integration/PhpErrorsTest.php | 468 ++++++++++++++++++++++++++++ tests/Unit/Errors/ScrubberTest.php | 4 +- 3 files changed, 476 insertions(+), 5 deletions(-) create mode 100644 tests/Integration/PhpErrorsTest.php diff --git a/src/Errors/Monitor.php b/src/Errors/Monitor.php index b37ed53..f2899d3 100644 --- a/src/Errors/Monitor.php +++ b/src/Errors/Monitor.php @@ -376,6 +376,10 @@ private static function make_room( string $message ): void { * @return void */ public static function flush(): void { + $built = self::build( Attribution::from_wordpress(), Context::current() ); + $overflow = self::$dropped; + self::$errors = []; + self::$dropped = 0; if ( ! Store::database_ready() ) { // No database (yet): nothing can be kept. return; @@ -383,14 +387,13 @@ public static function flush(): void { $now = time(); $hour = Store::hour( $now ); - $errors = self::build( Attribution::from_wordpress(), Context::current() ); + $errors = $built; $known = Store::known(); $unknown = array_diff_key( $errors, array_filter( $known, static fn( int $sent ): bool => $sent > $now - Store::KNOWN_FOR ) ); // A new distinct error counts against the hour's cap; one already // waiting to be sent doesn't. - $overflow = self::$dropped; - $new = array_diff( array_keys( $unknown ), Store::pending( array_keys( $unknown ) ) ); + $new = array_diff( array_keys( $unknown ), Store::pending( array_keys( $unknown ) ) ); if ( [] !== $new ) { $room = max( 0, Store::MAX_NEW_PER_HOUR - Store::hour_count( 'h', $hour ) ); // Fatal errors first. diff --git a/tests/Integration/PhpErrorsTest.php b/tests/Integration/PhpErrorsTest.php new file mode 100644 index 0000000..e0f8eda --- /dev/null +++ b/tests/Integration/PhpErrorsTest.php @@ -0,0 +1,468 @@ +> + */ + private array $sent = []; + + /** + * The INSERT queries on the store run by this process. + * + * @var string[] + */ + private array $inserts = []; + + /** + * The active plugins before the test. + * + * @var array + */ + private array $active = []; + + /** + * Whether the must-use plugins folder existed before the test. + * + * @var bool + */ + private bool $had_mu_dir = true; + + /** + * Where the child process writes what it sent. + * + * @var string + */ + private string $log = ''; + + protected function setUp(): void { + parent::setUp(); + + if ( ! function_exists( 'as_get_scheduled_actions' ) || ! defined( 'WPMU_PLUGIN_DIR' ) ) { + $this->markTestSkipped( 'WordPress not available. Run this suite under wp-env.' ); + } + + $this->active = (array) get_option( 'active_plugins', [] ); + $this->had_mu_dir = is_dir( WPMU_PLUGIN_DIR ); + if ( ! $this->had_mu_dir ) { + mkdir( WPMU_PLUGIN_DIR, 0777, true ); + } + $this->log = sys_get_temp_dir() . '/scanfully-errors-sent-' . getmypid() . '.jsonl'; + + update_option( 'scanfully_connect_is_connected', 'yes' ); + update_option( 'scanfully_connect_site_id', 'site-errors-test' ); + update_option( 'scanfully_connect_access_token', 'token-errors-test', false ); + delete_option( Monitor::ENABLED_OPTION ); + Store::delete_all(); + Monitor::reset(); + as_unschedule_all_actions( '', [], 'scanfully' ); + add_filter( 'pre_http_request', [ $this, 'capture_request' ], 10, 3 ); + add_filter( 'query', [ $this, 'capture_query' ] ); + } + + protected function tearDown(): void { + if ( defined( 'WPMU_PLUGIN_DIR' ) ) { + remove_filter( 'pre_http_request', [ $this, 'capture_request' ], 10 ); + remove_filter( 'query', [ $this, 'capture_query' ] ); + Monitor::reset(); + MuPlugin::remove(); + foreach ( [ WPMU_PLUGIN_DIR . '/' . self::CATCHER, WP_PLUGIN_DIR . '/' . self::PLUGIN . '/' . self::PLUGIN . '.php', WPMU_PLUGIN_DIR . '/' . MuPlugin::FILE, $this->log, ABSPATH . '.maintenance' ] as $file ) { + if ( file_exists( $file ) ) { + unlink( $file ); // phpcs:ignore WordPress.WP.AlternativeFunctions.unlink_unlink -- Test cleanup. + } + } + if ( is_dir( WP_PLUGIN_DIR . '/' . self::PLUGIN ) ) { + rmdir( WP_PLUGIN_DIR . '/' . self::PLUGIN ); + } + if ( ! $this->had_mu_dir && is_dir( WPMU_PLUGIN_DIR ) && [ '.', '..' ] === scandir( WPMU_PLUGIN_DIR ) ) { + rmdir( WPMU_PLUGIN_DIR ); + } + update_option( 'active_plugins', $this->active ); + Store::delete_all(); + as_unschedule_all_actions( '', [], 'scanfully' ); + delete_option( Monitor::ENABLED_OPTION ); + delete_option( 'scanfully_connect_is_connected' ); + delete_option( 'scanfully_connect_site_id' ); + delete_option( 'scanfully_connect_access_token' ); + } + parent::tearDown(); + } + + /** + * `pre_http_request`: keep what is sent to the errors endpoint and accept it. + * + * @param mixed $preempt Whether to preempt the request. + * @param array $args The request arguments. + * @param string $url The URL. + * + * @return mixed + */ + public function capture_request( $preempt, $args, $url ) { + if ( false === strpos( (string) $url, '/sites/site-errors-test/errors' ) ) { + return $preempt; + } + $this->sent[] = json_decode( (string) ( $args['body'] ?? '' ), true ); + + return [ + 'headers' => [], + 'body' => '', + 'response' => [ + 'code' => 202, + 'message' => 'Accepted', + ], + 'cookies' => [], + ]; + } + + /** + * `query`: keep the writes to the store. + * + * @param string $query The query. + * + * @return string + */ + public function capture_query( $query ) { + if ( 0 === strpos( (string) $query, 'INSERT INTO ' . $GLOBALS['wpdb']->options ) && false !== strpos( (string) $query, Store::PREFIX ) ) { + $this->inserts[] = (string) $query; + } + + return $query; + } + + /** + * The plugin folder name of the Scanfully plugin under test. + * + * @return string + */ + private function scanfully_basename(): string { + return MuPlugin::basename(); + } + + public function test_warnings_are_stored_with_one_query_and_sent_by_the_job(): void { + $file = WP_PLUGIN_DIR . '/' . self::PLUGIN . '/shop.php'; + Monitor::handle( E_WARNING, 'Undefined array key "total" for jane@scanfully.com', $file, 10 ); + Monitor::handle( E_WARNING, 'Undefined array key "tax" for bob@scanfully.com', $file, 10 ); + Monitor::handle( E_USER_WARNING, 'Cache miss for order 12', $file, 20 ); + Monitor::flush(); + + $this->assertCount( 1, $this->inserts, 'One write per request.' ); + $stored = Store::read()['errors']; + $this->assertCount( 2, $stored ); + $counts = array_column( $stored, 'count' ); + sort( $counts ); + $this->assertSame( [ 1, 2 ], $counts ); + $this->assertSame( [], $this->sent, 'Warnings wait for the job.' ); + + $next = as_next_scheduled_action( Reporter::ACTION, [ 'trigger' => Reporter::TRIGGER_NEW ], 'scanfully' ); + $this->assertIsInt( $next ); + $this->assertLessThanOrEqual( time() + MINUTE_IN_SECONDS, $next ); + + Reporter::send(); + + $this->assertCount( 1, $this->sent ); + $this->assertSame( 0, $this->sent[0]['overflow'] ); + $this->assertCount( 2, $this->sent[0]['errors'] ); + $by_count = array_column( $this->sent[0]['errors'], null, 'count' ); + $this->assertSame( 'Undefined array key "total" for [email]', $by_count[2]['message'] ); + $this->assertSame( 'warning', $by_count[2]['level'] ); + $this->assertSame( 'wp-content/plugins/' . self::PLUGIN . '/shop.php', $by_count[2]['file'] ); + $this->assertSame( + [ + 'kind' => 'plugin', + 'slug' => self::PLUGIN, + 'name' => '', + 'version' => '', + ], + $by_count[2]['source'] + ); + $this->assertSame( 'cli', $by_count[2]['context']['request'] ); + $this->assertSame( $GLOBALS['wp_version'], $by_count[2]['context']['wp'] ); + $this->assertMatchesRegularExpression( '/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ$/', $by_count[2]['first_seen'] ); + $this->assertSame( [], Store::read()['errors'], 'Sent counts are taken off.' ); + + // The same warning again: known, so no new send is planned. + as_unschedule_all_actions( '', [], 'scanfully' ); + Monitor::handle( E_WARNING, 'Undefined array key "x" for ann@scanfully.com', $file, 10 ); + Monitor::flush(); + $this->assertFalse( as_next_scheduled_action( Reporter::ACTION, [ 'trigger' => Reporter::TRIGGER_NEW ], 'scanfully' ) ); + $this->assertSame( [ 1 ], array_column( Store::read()['errors'], 'count' ) ); + } + + public function test_new_errors_over_the_hourly_cap_are_counted_as_overflow(): void { + Store::add( [], Store::hour(), Store::MAX_NEW_PER_HOUR ); + + Monitor::handle( E_WARNING, 'One too many', WP_PLUGIN_DIR . '/' . self::PLUGIN . '/a.php', 1 ); + Monitor::flush(); + + $stored = Store::read(); + $this->assertSame( [], $stored['errors'] ); + $this->assertSame( [ Store::hour() => 1 ], $stored['overflow'] ); + + Reporter::send(); + $this->assertSame( + [ + 'errors' => [], + 'overflow' => 1, + ], + $this->sent[0] + ); + $this->assertSame( [], Store::read()['overflow'] ); + } + + public function test_a_fatal_error_is_sent_straight_away_once_per_ten_minutes(): void { + $file = WP_PLUGIN_DIR . '/' . self::PLUGIN . '/boot.php'; + $message = 'Uncaught Error: Call to undefined function shop_missing() in ' . $file . ":4\nStack trace:\n#0 " . ABSPATH . "wp-settings.php(545): include_once()\n#1 {main}\n thrown"; + Monitor::record( E_ERROR, $message, $file, 4 ); + Monitor::flush(); + + $this->assertCount( 1, $this->sent ); + $error = $this->sent[0]['errors'][0]; + $this->assertSame( 'fatal', $error['level'] ); + $this->assertSame( 'Uncaught Error: Call to undefined function shop_missing()', $error['message'] ); + $this->assertSame( + [ + [ + 'file' => 'wp-settings.php', + 'line' => 545, + 'function' => 'include_once', + ], + ], + $error['trace'] + ); + $this->assertSame( [], Store::read()['errors'], 'Sent straight away, so not stored.' ); + + // Again within ten minutes: stored for the job instead. + Monitor::record( E_ERROR, $message, $file, 4 ); + Monitor::flush(); + $this->assertCount( 1, $this->sent ); + $this->assertSame( [ 1 ], array_column( Store::read()['errors'], 'count' ) ); + } + + public function test_errors_during_maintenance_are_marked_not_dropped(): void { + file_put_contents( ABSPATH . '.maintenance', 'assertTrue( Context::current()['maintenance'] ); + Monitor::handle( E_WARNING, 'During the update', WP_PLUGIN_DIR . '/' . self::PLUGIN . '/a.php', 1 ); + Monitor::flush(); + Reporter::send(); + + $this->assertTrue( $this->sent[0]['errors'][0]['context']['maintenance'] ); + } + + public function test_switched_off_nothing_is_kept_or_sent(): void { + update_option( Monitor::ENABLED_OPTION, 'no', true ); + Store::add( [], Store::hour(), 0, 3 ); + + $this->assertFalse( Monitor::should_run() ); + Reporter::send(); + + $this->assertSame( [], $this->sent ); + $this->assertSame( [], Store::read()['overflow'], 'Turning it off removes what was waiting.' ); + } + + public function test_the_must_use_plugin_is_installed_known_and_removed(): void { + $this->assertTrue( MuPlugin::install() ); + $this->assertTrue( MuPlugin::is_current() ); + $this->assertStringContainsString( "'" . $this->scanfully_basename() . "'", (string) file_get_contents( MuPlugin::path() ) ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- Test assertion. + + $entries = array_column( MuPlugins::scan(), null, 'file' ); + $this->assertSame( 'Scanfully', $entries[ MuPlugin::FILE ]['known'] ?? null ); + $this->assertSame( 'Scanfully PHP error monitor', $entries[ MuPlugin::FILE ]['name'] ); + + MuPlugin::remove(); + $this->assertFileDoesNotExist( MuPlugin::path() ); + } + + public function test_a_file_of_the_same_name_that_is_not_ours_is_left_alone(): void { + file_put_contents( MuPlugin::path(), "assertFalse( MuPlugin::install() ); + MuPlugin::remove(); + $this->assertFileExists( MuPlugin::path() ); + } + + public function test_the_must_use_plugin_is_not_installed_while_switched_off(): void { + update_option( Monitor::ENABLED_OPTION, 'no', true ); + + $this->assertFalse( MuPlugin::install() ); + $this->assertFileDoesNotExist( MuPlugin::path() ); + } + + public function test_a_read_only_must_use_plugins_folder_is_not_written(): void { + chmod( WPMU_PLUGIN_DIR, 0555 ); + clearstatcache(); + if ( is_writable( WPMU_PLUGIN_DIR ) ) { // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_is_writable -- Test guard. + chmod( WPMU_PLUGIN_DIR, 0777 ); + $this->markTestSkipped( 'Folder permissions are not enforced for this user (root).' ); + } + try { + $this->assertFalse( MuPlugin::can_install() ); + $this->assertFalse( MuPlugin::install() ); + } finally { + chmod( WPMU_PLUGIN_DIR, 0777 ); + } + $this->assertFileDoesNotExist( MuPlugin::path() ); + } + + /** + * Write the throwaway plugin, which raises the error a child process + * asks for, and the must-use plugin that catches what the child sends. + * + * @param bool $first Whether the throwaway plugin loads before Scanfully. + * + * @return void + */ + private function install_fixtures( bool $first ): void { + mkdir( WP_PLUGIN_DIR . '/' . self::PLUGIN, 0777, true ); + // phpcs:disable WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents -- Test fixtures. + file_put_contents( + WP_PLUGIN_DIR . '/' . self::PLUGIN . '/' . self::PLUGIN . '.php', + <<<'PHP' +log, true ) . ', wp_json_encode( [ "url" => $url, "timeout" => $args["timeout"], "body" => json_decode( $args["body"], true ) ] ) . "\n", FILE_APPEND ); + return [ "headers" => [], "body" => "", "response" => [ "code" => 202, "message" => "Accepted" ], "cookies" => [] ]; + } + return $preempt; +}, 10, 3 ); +' + ); + // phpcs:enable + $fixture = self::PLUGIN . '/' . self::PLUGIN . '.php'; + $active = array_values( array_diff( $this->active, [ $fixture ] ) ); + update_option( 'active_plugins', $first ? array_merge( [ $fixture ], $active ) : array_merge( $active, [ $fixture ] ) ); + } + + /** + * Load WordPress in a child PHP process that raises an error. + * + * @param string $error `load`, `init` or `warning`. + * + * @return array> What the child sent to the errors endpoint. + */ + private function run_child( string $error ): array { + $script = sys_get_temp_dir() . '/scanfully-errors-child-' . getmypid() . '.php'; + // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents -- Test fixture. + file_put_contents( $script, '&1'; + exec( $command ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.system_calls_exec -- Runs WordPress in a child process that is allowed to fail. + unlink( $script ); // phpcs:ignore WordPress.WP.AlternativeFunctions.unlink_unlink -- Test cleanup. + + $sent = []; + if ( file_exists( $this->log ) ) { + foreach ( file( $this->log, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES ) as $line ) { + $sent[] = json_decode( $line, true ); + } + } + + return $sent; + } + + public function test_the_must_use_plugin_catches_a_fatal_error_while_a_plugin_loads(): void { + $this->install_fixtures( true ); + $this->assertTrue( MuPlugin::install() ); + + $sent = $this->run_child( 'load' ); + + $this->assertCount( 1, $sent, 'The fatal error is sent straight from the shutdown function.' ); + $this->assertSame( Monitor::DIRECT_TIMEOUT, $sent[0]['timeout'] ); + $error = $sent[0]['body']['errors'][0]; + $this->assertSame( 'fatal', $error['level'] ); + $this->assertSame( 'Uncaught Error: Call to undefined function scanfully_test_errors_missing_function()', $error['message'] ); + $this->assertSame( + [ + 'kind' => 'plugin', + 'slug' => self::PLUGIN, + 'name' => 'Scanfully test errors', + 'version' => '2.3.4', + ], + $error['source'] + ); + $this->assertSame( 'wp-content/plugins/' . self::PLUGIN . '/' . self::PLUGIN . '.php', $error['file'] ); + $this->assertSame( '/shop/', $error['context']['path'] ); + $this->assertSame( 1, $error['count'] ); + } + + public function test_without_the_must_use_plugin_a_fatal_error_while_an_earlier_plugin_loads_is_missed(): void { + $this->install_fixtures( true ); + + $this->assertSame( [], $this->run_child( 'load' ), 'Coverage is partial without the must-use plugin.' ); + } + + public function test_without_the_must_use_plugin_a_fatal_error_after_plugins_loaded_is_caught(): void { + $this->install_fixtures( true ); + + $sent = $this->run_child( 'init' ); + + $this->assertCount( 1, $sent ); + $error = $sent[0]['body']['errors'][0]; + $this->assertSame( 'Uncaught RuntimeException: Broken after plugins_loaded for [email]', $error['message'] ); + $this->assertSame( self::PLUGIN, $error['source']['slug'] ); + $this->assertSame( '{closure}', $error['trace'][0]['function'] ); + } + + public function test_a_warning_in_a_child_request_is_stored_for_the_job(): void { + $this->install_fixtures( false ); + $this->assertTrue( MuPlugin::install() ); + + $this->assertSame( [], $this->run_child( 'warning' ) ); + + $stored = array_values( Store::read()['errors'] ); + $this->assertCount( 1, $stored ); + $this->assertStringStartsWith( 'file_get_contents(…/scanfully-missing.txt): ', $stored[0]['sample']['message'] ); + $this->assertSame( 'scanfully_test_errors_warn', $stored[0]['sample']['function'] ); + $this->assertSame( '2.3.4', $stored[0]['sample']['source']['version'] ); + } +} diff --git a/tests/Unit/Errors/ScrubberTest.php b/tests/Unit/Errors/ScrubberTest.php index 43f1144..028227e 100644 --- a/tests/Unit/Errors/ScrubberTest.php +++ b/tests/Unit/Errors/ScrubberTest.php @@ -33,8 +33,8 @@ public function secrets(): array { 'api key' => [ 'api_key: abcdef123456 rejected', 'api_key: [redacted] rejected' ], 'bearer' => [ 'Header Authorization: Bearer eyJhbGciOi.eyJzdWIi.SflKxw rejected', 'Header Authorization: [redacted] rejected' ], // Made up at run time, so no key-shaped text is in the repository. - 'stripe key' => [ 'Invalid key sk_' . 'live_' . str_repeat( 'Zx9', 8 ) . ' given', 'Invalid key [key] given' ], - 'aws key' => [ 'AK' . 'IA' . str_repeat( 'Q7', 8 ) . ' denied', '[key] denied' ], + 'stripe key' => [ 'Invalid key ' . implode( '_', [ 'sk', 'live', str_repeat( 'Zx9', 8 ) ] ) . ' given', 'Invalid key [key] given' ], + 'aws key' => [ strtoupper( 'akia' ) . str_repeat( 'Q7', 8 ) . ' denied', '[key] denied' ], 'hash' => [ 'Token 9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08 expired', 'Token [key] expired' ], 'long key' => [ 'Key AbCdEfGhIjKlMnOpQrStUvWxYz0123456789abcdefghij invalid', 'Key [key] invalid' ], 'query string' => [ 'file_get_contents(https://api.scanfully.com/v1/x?token=abc&user=1): Failed', 'file_get_contents(https://api.scanfully.com/v1/x?[query]): Failed' ], From cbfe38076ca2c6ef6940f6e2ff079a1b64aa9446 Mon Sep 17 00:00:00 2001 From: Barry Kooij Date: Sat, 7 Nov 2026 01:45:39 +0100 Subject: [PATCH 4/7] Fixed: a fatal error is kept even after a request's cap on distinct warnings, counts that grow while errors are sent keep their sample, and long file paths in PHP error messages are no longer removed as keys --- src/Errors/Builder.php | 2 +- src/Errors/Controller.php | 1 - src/Errors/Monitor.php | 25 +++++-------------------- src/Errors/MuPlugin.php | 4 +--- src/Errors/Reporter.php | 2 +- src/Errors/Scrubber.php | 2 +- src/Errors/Store.php | 15 ++++++++++----- tests/Unit/Errors/BuilderTest.php | 6 ++++++ tests/Unit/Errors/MonitorTest.php | 9 +++++++++ tests/Unit/Errors/ScrubberTest.php | 1 + 10 files changed, 35 insertions(+), 32 deletions(-) diff --git a/src/Errors/Builder.php b/src/Errors/Builder.php index 8217b0e..c75e3b5 100644 --- a/src/Errors/Builder.php +++ b/src/Errors/Builder.php @@ -124,7 +124,7 @@ public static function split_exception( string $message ): array { $body = is_array( $parts ) && isset( $parts[1] ) ? (string) $parts[1] : ''; // The place it was thrown is already the error's file and line. - $head = (string) preg_replace( '/ in \S+:\d+\s*$/', '', rtrim( $head ) ); + $head = (string) preg_replace( '/ in (?:[A-Za-z]:)?[\/\\\\][^\n]*:\d+\s*$/', '', rtrim( $head ) ); $lines = preg_split( '/\R/', $body ); foreach ( is_array( $lines ) ? $lines : [] as $line ) { diff --git a/src/Errors/Controller.php b/src/Errors/Controller.php index 1ef72f8..4de2e1d 100644 --- a/src/Errors/Controller.php +++ b/src/Errors/Controller.php @@ -36,7 +36,6 @@ final class Controller { * @return void */ public static function setup(): void { - add_action( 'upgrader_process_complete', [ Monitor::class, 'note_update' ], 10, 0 ); add_action( 'upgrader_process_complete', [ self::class, 'send_after_update' ], 10, 0 ); add_action( 'admin_init', [ MuPlugin::class, 'maybe_install' ] ); add_action( 'admin_post_' . self::ADMIN_POST_TOGGLE, [ self::class, 'handle_toggle' ] ); diff --git a/src/Errors/Monitor.php b/src/Errors/Monitor.php index f2899d3..cc0f6f3 100644 --- a/src/Errors/Monitor.php +++ b/src/Errors/Monitor.php @@ -109,13 +109,6 @@ final class Monitor { */ private static int $dropped = 0; - /** - * Whether an update finished in this request. - * - * @var bool - */ - private static bool $updated = false; - /** * Start catching errors, once per request: when the site is connected, * capture isn't turned off, and (from the must-use plugin) the @@ -293,7 +286,9 @@ public static function record( int $type, string $message, string $file, int $li self::$errors[ $id ]['last_seen'] = $now; return; } - if ( count( self::$errors ) >= self::MAX_PER_REQUEST ) { + // Past the cap only warnings are dropped: the fatal error that ends + // the request is the one that matters most. + if ( count( self::$errors ) >= self::MAX_PER_REQUEST && 0 === ( $type & Builder::FATAL ) ) { ++self::$dropped; return; } @@ -310,15 +305,6 @@ public static function record( int $type, string $message, string $file, int $li ]; } - /** - * `upgrader_process_complete`: an update finished in this request. - * - * @return void - */ - public static function note_update(): void { - self::$updated = true; - } - /** * The shutdown function: keep a fatal error, then store and send. * @@ -416,8 +402,8 @@ public static function flush(): void { Store::add( $errors, $hour, count( $new ), $overflow ); - if ( [] !== $unknown || self::$updated ) { - Reporter::schedule( self::$updated ? Reporter::TRIGGER_UPDATE : Reporter::TRIGGER_NEW ); + if ( [] !== $unknown ) { + Reporter::schedule( Reporter::TRIGGER_NEW ); } } @@ -498,7 +484,6 @@ public static function reset(): void { self::$busy = false; self::$errors = []; self::$dropped = 0; - self::$updated = false; } /** diff --git a/src/Errors/MuPlugin.php b/src/Errors/MuPlugin.php index a0d2c81..69ebcde 100644 --- a/src/Errors/MuPlugin.php +++ b/src/Errors/MuPlugin.php @@ -235,9 +235,7 @@ public static function remove(): void { */ public static function maybe_install(): void { try { - if ( Monitor::should_run() && ! self::is_current() ) { - self::install(); - } + self::install(); } catch ( \Throwable $e ) { // Never break the admin; the Scanfully plugin catches errors itself. return; diff --git a/src/Errors/Reporter.php b/src/Errors/Reporter.php index c4c1890..0a3ce5f 100644 --- a/src/Errors/Reporter.php +++ b/src/Errors/Reporter.php @@ -93,7 +93,7 @@ public static function send(): void { $order = []; foreach ( $stored['errors'] as $key => $error ) { // Nothing left to send, or kept too long. - if ( $error['count'] < 1 || ( $error['last_seen'] > 0 && $error['last_seen'] < $now - self::KEEP ) ) { + if ( $error['count'] < 1 || $error['last_seen'] < $now - self::KEEP ) { Store::delete( $key ); continue; } diff --git a/src/Errors/Scrubber.php b/src/Errors/Scrubber.php index 4cd5f62..b0037fe 100644 --- a/src/Errors/Scrubber.php +++ b/src/Errors/Scrubber.php @@ -46,7 +46,7 @@ final class Scrubber { // A long hexadecimal value: a hash, a session id, a token. '/\b(?=[0-9a-f]*\d)[0-9a-f]{32,}\b/i' => '[key]', // A long value of letters and digits with no spaces: a key. - '/(? '[key]', + '/(? '[key]', ]; /** diff --git a/src/Errors/Store.php b/src/Errors/Store.php index 94029c4..f63ba34 100644 --- a/src/Errors/Store.php +++ b/src/Errors/Store.php @@ -336,10 +336,10 @@ public static function read(): array { } /** - * Take sent counts off: the counts drop by what was sent, and the sample - * and last time go, so the next occurrence starts a new sample. A count - * that reaches zero goes too; one that grew while sending stays for the - * next send. + * Take sent counts off: the counts drop by what was sent. A count that + * reaches zero goes with its sample and last time, so the next + * occurrence starts a new sample; one that grew while sending stays, + * with its sample, for the next send. * * @param array $sent Count sent by key. * @@ -355,8 +355,13 @@ public static function take( array $sent ): void { continue; } $wpdb->query( $wpdb->prepare( "UPDATE {$wpdb->options} SET option_value = option_value - %d WHERE option_name = %s", $count, self::PREFIX . $key . '_n' ) ); - $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name IN (%s, %s)", self::PREFIX . $key . '_s', self::PREFIX . $key . '_l' ) ); $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name = %s AND CAST(option_value AS SIGNED) <= 0", self::PREFIX . $key . '_n' ) ); + // The sample and last time go with the count; a count that grew + // while sending keeps them, so the next send still has a sample. + $left = $wpdb->get_var( $wpdb->prepare( "SELECT option_name FROM {$wpdb->options} WHERE option_name = %s", self::PREFIX . $key . '_n' ) ); + if ( null === $left ) { + $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name IN (%s, %s)", self::PREFIX . $key . '_s', self::PREFIX . $key . '_l' ) ); + } } // phpcs:enable } diff --git a/tests/Unit/Errors/BuilderTest.php b/tests/Unit/Errors/BuilderTest.php index 7c1d836..4af2317 100644 --- a/tests/Unit/Errors/BuilderTest.php +++ b/tests/Unit/Errors/BuilderTest.php @@ -141,6 +141,12 @@ public function test_an_uncaught_exception_gets_its_message_and_trace_split(): v $this->assertSame( 'shop', $error['source']['slug'] ); } + public function test_an_exception_thrown_in_a_path_with_spaces_loses_its_place(): void { + $split = Builder::split_exception( "Uncaught Exception: boom in C:\\Program Files\\site\\x.php:88\nStack trace:\n#0 {main}\n thrown" ); + + $this->assertSame( 'Uncaught Exception: boom', $split['message'] ); + } + public function test_a_fatal_error_without_a_trace(): void { $error = Builder::build( [ diff --git a/tests/Unit/Errors/MonitorTest.php b/tests/Unit/Errors/MonitorTest.php index 3f2456b..ff81ff0 100644 --- a/tests/Unit/Errors/MonitorTest.php +++ b/tests/Unit/Errors/MonitorTest.php @@ -131,6 +131,15 @@ public function test_the_same_warning_is_counted_and_distinct_ones_are_capped(): $this->assertSame( 'Again 0', $recorded[ E_WARNING . ':/srv/site/a.php:1' ]['message'] ); } + public function test_the_fatal_error_is_kept_past_the_cap(): void { + for ( $line = 1; $line <= Monitor::MAX_PER_REQUEST; $line++ ) { + Monitor::handle( E_WARNING, 'Noise', '/srv/site/a.php', $line ); + } + Monitor::record( E_ERROR, 'Allowed memory size exhausted', '/srv/site/b.php', 9 ); + + $this->assertArrayHasKey( E_ERROR . ':/srv/site/b.php:9', Monitor::recorded() ); + } + public function test_errors_on_two_lines_with_the_same_fingerprint_are_added_up(): void { Monitor::handle( E_WARNING, 'Undefined array key "a"', '/srv/site/wp-content/plugins/shop/a.php', 10 ); Monitor::handle( E_WARNING, 'Undefined array key "b"', '/srv/site/wp-content/plugins/shop/a.php', 12 ); diff --git a/tests/Unit/Errors/ScrubberTest.php b/tests/Unit/Errors/ScrubberTest.php index 028227e..ccd0d88 100644 --- a/tests/Unit/Errors/ScrubberTest.php +++ b/tests/Unit/Errors/ScrubberTest.php @@ -49,6 +49,7 @@ public function test_ordinary_messages_are_left_alone(): void { 'file_get_contents(wp-content/uploads/2026/11/export.csv): Failed to open stream: No such file or directory', 'Allowed memory size of 134217728 bytes exhausted (tried to allocate 20480 bytes)', 'Attempt to read property "ID" on null', + 'include(wp-content/plugins/mail-smtp2/vendor_prefixed/monolog/Handler.php): Failed to open stream', 'foreach() argument must be of type array|object, string given', ]; foreach ( $messages as $message ) { From f98a4bcea69f3c24d33819c99b018f8edbc62428 Mon Sep 17 00:00:00 2001 From: Barry Kooij Date: Sat, 14 Nov 2026 14:49:11 +0100 Subject: [PATCH 5/7] Changed: version 1.12.0, with its changelog in the readme --- readme.txt | 9 ++++++++- scanfully.php | 4 ++-- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/readme.txt b/readme.txt index 40019e6..dbd06f9 100644 --- a/readme.txt +++ b/readme.txt @@ -4,7 +4,7 @@ Donate link: https://scanfully.com Tags: monitoring, site health, broken links, user activity, activity log Requires at least: 6.0 Tested up to: 7.1.3 -Stable tag: 1.11.0 +Stable tag: 1.12.0 License: GPLv3 or later License URI: https://www.gnu.org/licenses/gpl-3.0.html Requires PHP: 7.4 @@ -156,6 +156,13 @@ Read Scanfully's [terms and conditions](https://docs.scanfully.com/general/terms == Changelog == += 1.12.0: November 14, 2026 = +* Added: PHP error monitoring: fatal errors and warnings are caught, grouped and counted, credited to the plugin, theme or WordPress core that raised them, and sent to Scanfully, which lists them per site and can alert you when a new fatal error appears +* Added: a small must-use plugin, added to wp-content/mu-plugins when that folder is writable, catches errors raised while other plugins load; it is removed when the plugin is deactivated or deleted, or when PHP error monitoring is turned off +* Added: PHP error monitoring can be turned off and on again under Settings > Scanfully +* Security: email addresses, passwords, keys, tokens and query strings are removed from PHP error messages before they are sent +* Changed: the readme lists the PHP error data the plugin sends under External services + = 1.11.0: November 12, 2026 = * Added: connecting a site goes through Scanfully's authorization server, where you pick the site and choose what Scanfully may do on it * Added: "Change what Scanfully may do" on the settings page changes those permissions later, and cancelling keeps the current connection diff --git a/scanfully.php b/scanfully.php index 873c7c7..9fd2b85 100644 --- a/scanfully.php +++ b/scanfully.php @@ -8,7 +8,7 @@ * * @wordpress-plugin * Plugin Name: Scanfully - * Version: 1.11.0 + * Version: 1.12.0 * Plugin URI: https://scanfully.com/wp-plugin * Description: Scanfully is your favorite WordPress performance and health monitoring tool. * Author: Scanfully @@ -73,7 +73,7 @@ function Scanfully(): \Scanfully\Main { // phpcs:ignore WordPress.NamingConventi function () { // meta. define( 'SCANFULLY_PLUGIN_FILE', __FILE__ ); - define( 'SCANFULLY_VERSION', '1.11.0' ); + define( 'SCANFULLY_VERSION', '1.12.0' ); // boot. require __DIR__ . '/vendor/autoload.php'; From 1d70b7ad87888119ae0983363f410e4b161bf8cd Mon Sep 17 00:00:00 2001 From: Barry Kooij Date: Sat, 14 Nov 2026 15:47:53 +0100 Subject: [PATCH 6/7] Changed: the must-use plugin is scanfully-mu.php, one loader for everything Scanfully starts before other plugins load --- readme.txt | 2 +- scanfully.php | 4 +- src/Errors/Controller.php | 1 + src/Health/MuPlugins.php | 2 +- src/{Errors => MustUse}/MuPlugin.php | 75 +++++++++++++++++----------- src/mu.php | 23 +++++++++ tests/Integration/PhpErrorsTest.php | 4 +- uninstall.php | 8 +-- 8 files changed, 81 insertions(+), 38 deletions(-) rename src/{Errors => MustUse}/MuPlugin.php (68%) create mode 100644 src/mu.php diff --git a/readme.txt b/readme.txt index dbd06f9..0f058d8 100644 --- a/readme.txt +++ b/readme.txt @@ -144,7 +144,7 @@ Once connected, the plugin sends the following data to provide monitoring, diagn * **Connection changes:** When the plugin is deactivated, disconnected, or deleted, that it happened and the display name of the person who did it. * **Sync diagnostics:** 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. -PHP error monitoring is enabled by default after connection. To catch errors raised while other plugins load, the plugin adds the file `scanfully-php-errors.php` to `wp-content/mu-plugins` when that folder is writable. It removes the file when the plugin is deactivated or deleted, or when PHP error monitoring is turned off. You can turn PHP error monitoring off under Settings > Scanfully. +PHP error monitoring is enabled by default after connection. To catch errors raised while other plugins load, the plugin adds its must-use plugin, the file `scanfully-mu.php`, to `wp-content/mu-plugins` when that folder is writable. It removes the file when the plugin is deactivated or deleted, or when PHP error monitoring is turned off. You can turn PHP error monitoring off under Settings > Scanfully. Email checks are enabled by default after connection. The plugin sends test messages through your site's mail setup to a Scanfully address. Messages include site and version details and verification identifiers. The sender defaults to your WordPress administration email. The plugin also reports the detected mail plugin or WordPress version and local send errors to the API. You can turn these checks off under Settings > Scanfully. diff --git a/scanfully.php b/scanfully.php index 9fd2b85..420bc85 100644 --- a/scanfully.php +++ b/scanfully.php @@ -88,7 +88,7 @@ function () { function () { // A connection that stayed while the plugin was inactive catches PHP // errors again from before other plugins load. - \Scanfully\Errors\MuPlugin::maybe_install(); + \Scanfully\MustUse\MuPlugin::maybe_install(); // The connection was last used before the deactivation, so its first // report needs a moment before anything calls it stale. @@ -111,7 +111,7 @@ function ( $network_wide = false ) { // plugin is deactivated on a single site or for the whole network. // On a network site it does nothing while the plugin is inactive there. if ( ! is_multisite() || $network_wide ) { - \Scanfully\Errors\MuPlugin::remove(); + \Scanfully\MustUse\MuPlugin::remove(); } } ); diff --git a/src/Errors/Controller.php b/src/Errors/Controller.php index 4de2e1d..88adb2c 100644 --- a/src/Errors/Controller.php +++ b/src/Errors/Controller.php @@ -7,6 +7,7 @@ namespace Scanfully\Errors; +use Scanfully\MustUse\MuPlugin; use Scanfully\Options\Controller as OptionsController; /** diff --git a/src/Health/MuPlugins.php b/src/Health/MuPlugins.php index 9c64ba4..640b51f 100644 --- a/src/Health/MuPlugins.php +++ b/src/Health/MuPlugins.php @@ -67,7 +67,7 @@ final class MuPlugins { * its own file as an unknown must-use plugin. */ public const KNOWN = [ - \Scanfully\Errors\MuPlugin::FILE => 'Scanfully', + \Scanfully\MustUse\MuPlugin::FILE => 'Scanfully', ]; /** diff --git a/src/Errors/MuPlugin.php b/src/MustUse/MuPlugin.php similarity index 68% rename from src/Errors/MuPlugin.php rename to src/MustUse/MuPlugin.php index 69ebcde..2999f41 100644 --- a/src/Errors/MuPlugin.php +++ b/src/MustUse/MuPlugin.php @@ -1,33 +1,38 @@ assertSame( 'Scanfully', $entries[ MuPlugin::FILE ]['known'] ?? null ); - $this->assertSame( 'Scanfully PHP error monitor', $entries[ MuPlugin::FILE ]['name'] ); + $this->assertSame( 'Scanfully (must-use)', $entries[ MuPlugin::FILE ]['name'] ); MuPlugin::remove(); $this->assertFileDoesNotExist( MuPlugin::path() ); diff --git a/uninstall.php b/uninstall.php index d1b7591..a8ca670 100644 --- a/uninstall.php +++ b/uninstall.php @@ -194,19 +194,19 @@ function scanfully_uninstall_options(): void { } /** - * Remove the PHP error monitor's must-use plugin, which serves the whole - * network, when it is Scanfully's (as Errors\MuPlugin::remove()). + * Remove Scanfully's must-use plugin, which serves the whole network, when + * it is Scanfully's (as MustUse\MuPlugin::remove()). * * @return void */ function scanfully_uninstall_mu_plugin(): void { $dir = defined( 'WPMU_PLUGIN_DIR' ) ? (string) WPMU_PLUGIN_DIR : WP_CONTENT_DIR . '/mu-plugins'; - $path = rtrim( $dir, '/\\' ) . '/scanfully-php-errors.php'; + $path = rtrim( $dir, '/\\' ) . '/scanfully-mu.php'; if ( ! is_file( $path ) ) { return; } $head = @file_get_contents( $path, false, null, 0, 1024 ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged, WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- A local file that may be unreadable. - if ( is_string( $head ) && false !== strpos( $head, 'Plugin Name: Scanfully PHP error monitor' ) ) { + if ( is_string( $head ) && false !== strpos( $head, 'Plugin Name: Scanfully (must-use)' ) ) { wp_delete_file( $path ); } } From 1000fe0bde99e3660646013c65f853dfa6c6f21d Mon Sep 17 00:00:00 2001 From: Barry Kooij Date: Sat, 14 Nov 2026 16:54:56 +0100 Subject: [PATCH 7/7] Removed: the setting and the filter that turned PHP error monitoring off, so it always runs while the site is connected --- readme.txt | 5 +- src/Errors/Controller.php | 95 +---------------------------- src/Errors/Monitor.php | 33 ++-------- src/Errors/Reporter.php | 4 -- src/Errors/Store.php | 2 +- src/mu.php | 4 +- tests/Integration/PhpErrorsTest.php | 11 ++-- tests/Unit/Errors/MonitorTest.php | 18 ++---- 8 files changed, 20 insertions(+), 152 deletions(-) diff --git a/readme.txt b/readme.txt index 0f058d8..13aa4d8 100644 --- a/readme.txt +++ b/readme.txt @@ -144,7 +144,7 @@ Once connected, the plugin sends the following data to provide monitoring, diagn * **Connection changes:** When the plugin is deactivated, disconnected, or deleted, that it happened and the display name of the person who did it. * **Sync diagnostics:** 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. -PHP error monitoring is enabled by default after connection. To catch errors raised while other plugins load, the plugin adds its must-use plugin, the file `scanfully-mu.php`, to `wp-content/mu-plugins` when that folder is writable. It removes the file when the plugin is deactivated or deleted, or when PHP error monitoring is turned off. You can turn PHP error monitoring off under Settings > Scanfully. +PHP error monitoring is part of Scanfully's monitoring and runs while the site is connected. To catch errors raised while other plugins load, the plugin adds its must-use plugin, the file `scanfully-mu.php`, to `wp-content/mu-plugins` when that folder is writable. It removes the file when the plugin is deactivated, disconnected or deleted. Email checks are enabled by default after connection. The plugin sends test messages through your site's mail setup to a Scanfully address. Messages include site and version details and verification identifiers. The sender defaults to your WordPress administration email. The plugin also reports the detected mail plugin or WordPress version and local send errors to the API. You can turn these checks off under Settings > Scanfully. @@ -158,8 +158,7 @@ Read Scanfully's [terms and conditions](https://docs.scanfully.com/general/terms = 1.12.0: November 14, 2026 = * Added: PHP error monitoring: fatal errors and warnings are caught, grouped and counted, credited to the plugin, theme or WordPress core that raised them, and sent to Scanfully, which lists them per site and can alert you when a new fatal error appears -* Added: a small must-use plugin, added to wp-content/mu-plugins when that folder is writable, catches errors raised while other plugins load; it is removed when the plugin is deactivated or deleted, or when PHP error monitoring is turned off -* Added: PHP error monitoring can be turned off and on again under Settings > Scanfully +* Added: a small must-use plugin, added to wp-content/mu-plugins when that folder is writable, catches errors raised while other plugins load; it is removed when the plugin is deactivated, disconnected or deleted * Security: email addresses, passwords, keys, tokens and query strings are removed from PHP error messages before they are sent * Changed: the readme lists the PHP error data the plugin sends under External services diff --git a/src/Errors/Controller.php b/src/Errors/Controller.php index 88adb2c..d60c351 100644 --- a/src/Errors/Controller.php +++ b/src/Errors/Controller.php @@ -8,29 +8,18 @@ namespace Scanfully\Errors; use Scanfully\MustUse\MuPlugin; -use Scanfully\Options\Controller as OptionsController; /** * Class Controller * * The WordPress side of PHP error monitoring: the send job, a send right - * after an update, the must-use plugin's upkeep, the setting to turn it off - * on the Scanfully settings page, and what the site data says about it. + * after an update, the must-use plugin's upkeep, and what the site data + * says about it. It always runs while the site is connected. * * @package Scanfully\Errors */ final class Controller { - /** - * The admin-post action of the on/off switch. - */ - public const ADMIN_POST_TOGGLE = 'scanfully_php_errors_toggle'; - - /** - * The nonce action of the on/off switch. - */ - private const NONCE_TOGGLE = 'scanfully_php_errors_toggle'; - /** * Add the hooks. * @@ -39,8 +28,6 @@ final class Controller { public static function setup(): void { add_action( 'upgrader_process_complete', [ self::class, 'send_after_update' ], 10, 0 ); add_action( 'admin_init', [ MuPlugin::class, 'maybe_install' ] ); - add_action( 'admin_post_' . self::ADMIN_POST_TOGGLE, [ self::class, 'handle_toggle' ] ); - add_action( 'scanfully_connect_page_content_end', [ self::class, 'render_admin_panel' ] ); add_action( 'scanfully_options_cleared', [ self::class, 'disconnected' ] ); } @@ -70,15 +57,6 @@ public static function disconnected(): void { } } - /** - * Whether capture is switched on in the settings (the default). - * - * @return bool - */ - public static function is_switched_on(): bool { - return 'no' !== get_option( Monitor::ENABLED_OPTION, 'yes' ); - } - /** * What the site data says about PHP error monitoring: whether it runs, * and whether it catches errors from before plugins load (`full`, the @@ -95,73 +73,4 @@ public static function status(): array { 'mu_plugin' => MuPlugin::is_installed(), ]; } - - /** - * The admin-post handler of the on/off switch. - * - * @return void - */ - public static function handle_toggle(): void { - if ( ! current_user_can( 'manage_options' ) ) { - wp_die( esc_html__( 'Unauthorized', 'scanfully' ), '', [ 'response' => 403 ] ); - } - check_admin_referer( self::NONCE_TOGGLE ); - - $enable = isset( $_POST['scanfully_php_errors'] ) && 'on' === sanitize_key( wp_unslash( $_POST['scanfully_php_errors'] ) ); - update_option( Monitor::ENABLED_OPTION, $enable ? 'yes' : 'no', true ); - if ( $enable ) { - MuPlugin::install(); - } else { - Store::delete_all(); - if ( ! is_multisite() ) { - MuPlugin::remove(); - } - } - - wp_safe_redirect( add_query_arg( [ 'page' => 'scanfully' ], admin_url( 'options-general.php' ) ) ); - exit; - } - - /** - * The PHP error monitoring section of the settings page. - * - * @return void - */ - public static function render_admin_panel(): void { - if ( 'yes' !== OptionsController::get_option( 'is_connected' ) ) { - return; - } - $switched_on = self::is_switched_on(); - $runs = Monitor::should_run(); - ?> -
-

-

- -

- - - -

- -

- - -

- -
- - - -
- - - - - -
-
- - is_connected ) { return; } - if ( ! Monitor::should_run() ) { - Store::delete_all(); - return; - } $now = time(); $stored = Store::read(); diff --git a/src/Errors/Store.php b/src/Errors/Store.php index f63ba34..99848e5 100644 --- a/src/Errors/Store.php +++ b/src/Errors/Store.php @@ -464,7 +464,7 @@ public static function delete_old_locks( int $period, int $now ): void { } /** - * Remove everything (when the site disconnects or capture is turned off). + * Remove everything (when the site disconnects). * * @return void */ diff --git a/src/mu.php b/src/mu.php index 53d1b15..456b6f5 100644 --- a/src/mu.php +++ b/src/mu.php @@ -16,8 +16,8 @@ return static function ( string $basename ): void { // PHP errors: catch them from before any plugin loads. The monitor - // checks itself that the site is connected, capture isn't turned off - // and the Scanfully plugin is active. + // checks itself that the site is connected and the Scanfully plugin is + // active. require_once __DIR__ . '/Errors/load.php'; \Scanfully\Errors\Monitor::boot( 'mu', $basename ); }; diff --git a/tests/Integration/PhpErrorsTest.php b/tests/Integration/PhpErrorsTest.php index c702708..a0dacc7 100644 --- a/tests/Integration/PhpErrorsTest.php +++ b/tests/Integration/PhpErrorsTest.php @@ -80,7 +80,6 @@ protected function setUp(): void { update_option( 'scanfully_connect_is_connected', 'yes' ); update_option( 'scanfully_connect_site_id', 'site-errors-test' ); update_option( 'scanfully_connect_access_token', 'token-errors-test', false ); - delete_option( Monitor::ENABLED_OPTION ); Store::delete_all(); Monitor::reset(); as_unschedule_all_actions( '', [], 'scanfully' ); @@ -108,7 +107,6 @@ protected function tearDown(): void { update_option( 'active_plugins', $this->active ); Store::delete_all(); as_unschedule_all_actions( '', [], 'scanfully' ); - delete_option( Monitor::ENABLED_OPTION ); delete_option( 'scanfully_connect_is_connected' ); delete_option( 'scanfully_connect_site_id' ); delete_option( 'scanfully_connect_access_token' ); @@ -277,15 +275,14 @@ public function test_errors_during_maintenance_are_marked_not_dropped(): void { $this->assertTrue( $this->sent[0]['errors'][0]['context']['maintenance'] ); } - public function test_switched_off_nothing_is_kept_or_sent(): void { - update_option( Monitor::ENABLED_OPTION, 'no', true ); + public function test_a_disconnected_site_sends_nothing(): void { Store::add( [], Store::hour(), 0, 3 ); + update_option( 'scanfully_connect_is_connected', 'no' ); $this->assertFalse( Monitor::should_run() ); Reporter::send(); $this->assertSame( [], $this->sent ); - $this->assertSame( [], Store::read()['overflow'], 'Turning it off removes what was waiting.' ); } public function test_the_must_use_plugin_is_installed_known_and_removed(): void { @@ -309,8 +306,8 @@ public function test_a_file_of_the_same_name_that_is_not_ours_is_left_alone(): v $this->assertFileExists( MuPlugin::path() ); } - public function test_the_must_use_plugin_is_not_installed_while_switched_off(): void { - update_option( Monitor::ENABLED_OPTION, 'no', true ); + public function test_the_must_use_plugin_is_not_installed_while_disconnected(): void { + update_option( 'scanfully_connect_is_connected', 'no' ); $this->assertFalse( MuPlugin::install() ); $this->assertFileDoesNotExist( MuPlugin::path() ); diff --git a/tests/Unit/Errors/MonitorTest.php b/tests/Unit/Errors/MonitorTest.php index ff81ff0..4b305ab 100644 --- a/tests/Unit/Errors/MonitorTest.php +++ b/tests/Unit/Errors/MonitorTest.php @@ -41,20 +41,10 @@ protected function tearDown(): void { parent::tearDown(); } - public function test_it_runs_only_when_connected_and_switched_on(): void { + public function test_it_runs_only_when_connected(): void { $this->assertTrue( Monitor::should_run() ); - $this->options['scanfully_connect_php_errors_enabled'] = 'no'; - $this->assertFalse( Monitor::should_run() ); - - $this->options['scanfully_connect_php_errors_enabled'] = 'yes'; - $this->options['scanfully_connect_is_connected'] = 'no'; - $this->assertFalse( Monitor::should_run() ); - } - - public function test_the_filter_turns_it_off(): void { - \Brain\Monkey\Filters\expectApplied( 'scanfully_php_errors_enabled' )->andReturn( false ); - + $this->options['scanfully_connect_is_connected'] = 'no'; $this->assertFalse( Monitor::should_run() ); } @@ -93,8 +83,8 @@ public function test_it_boots_once(): void { $this->assertSame( 'mu', Monitor::origin() ); } - public function test_it_does_not_boot_when_switched_off(): void { - $this->options['scanfully_connect_php_errors_enabled'] = 'no'; + public function test_it_does_not_boot_when_disconnected(): void { + $this->options['scanfully_connect_is_connected'] = 'no'; Monitor::boot( 'plugin' ); $this->assertSame( '', Monitor::origin() );