diff --git a/src/js/_enqueues/admin/site-health.js b/src/js/_enqueues/admin/site-health.js index 8d8c40c70c3e9..063aac481b257 100644 --- a/src/js/_enqueues/admin/site-health.js +++ b/src/js/_enqueues/admin/site-health.js @@ -107,6 +107,19 @@ jQuery( function( $ ) { return false; } + /* + * Only these statuses have a section on the screen and are accepted by the + * server-side cache. Any other status would make the whole cache update fail. + */ + if ( -1 === [ 'good', 'recommended', 'critical' ].indexOf( issue.status ) ) { + return false; + } + + // A blank identifier would cause the server to reject the entire cache update. + if ( 'string' !== typeof issue.test || '' === issue.test.trim() ) { + return false; + } + // Loop over expected data and match the data types. for ( key in minimumExpected ) { value = minimumExpected[ key ]; @@ -160,10 +173,14 @@ jQuery( function( $ ) { count = SiteHealth.site_status.issues[ issue.status ]; - // If no test name is supplied, append a placeholder for markup references. - if ( typeof issue.test === 'undefined' ) { - issue.test = issue.status + count; - } + /* + * Collect the test name and status so they can be cached server-side. These + * include the asynchronous tests that only run in the browser. Labels are left + * out on purpose, as they are translated and the cache is shared across locales. + */ + SiteHealth.site_status.results[ issue.test ] = { + status: issue.status + }; if ( 'critical' === issue.status ) { heading = sprintf( @@ -254,12 +271,14 @@ jQuery( function( $ ) { } if ( isStatusTab ) { + // One request avoids competing counts-only and results-only updates to the shared cache. $.post( ajaxurl, { 'action': 'health-check-site-status-result', '_wpnonce': SiteHealth.nonce.site_status_result, - 'counts': SiteHealth.site_status.issues + 'counts': SiteHealth.site_status.issues, + 'results': JSON.stringify( SiteHealth.site_status.results ) } ); diff --git a/src/wp-admin/includes/ajax-actions.php b/src/wp-admin/includes/ajax-actions.php index 076549b218b82..5d87ac2d04182 100644 --- a/src/wp-admin/includes/ajax-actions.php +++ b/src/wp-admin/includes/ajax-actions.php @@ -5448,7 +5448,14 @@ function wp_ajax_health_check_loopback_requests() { /** * Handles site health check to update the result status via AJAX. * + * Counts and compact per-test results are saved together. Counts-only requests + * remain supported for compatibility, and results-only requests preserve stored counts. + * Core readers calculate counts from valid, unexpired per-test results when available; + * the stored counts remain for consumers that read the transient directly. + * * @since 5.2.0 + * @since 7.3.0 The submitted counts are validated, and optional per-test statuses + * and timestamps extend the existing transient. */ function wp_ajax_health_check_site_status_result() { check_ajax_referer( 'health-check-site-status-result' ); @@ -5457,7 +5464,41 @@ function wp_ajax_health_check_site_status_result() { wp_send_json_error(); } - set_transient( 'health-check-site-status-result', wp_json_encode( $_POST['counts'] ) ); + if ( ! class_exists( 'WP_Site_Health' ) ) { + require_once ABSPATH . 'wp-admin/includes/class-wp-site-health.php'; + } + + $counts = null; + $results = null; + + if ( isset( $_POST['counts'] ) ) { + if ( ! is_array( $_POST['counts'] ) ) { + wp_send_json_error(); + } + $counts = wp_unslash( $_POST['counts'] ); + } + + if ( isset( $_POST['results'] ) ) { + if ( ! is_string( $_POST['results'] ) ) { + wp_send_json_error(); + } + $results = json_decode( wp_unslash( $_POST['results'] ), true ); + if ( ! is_array( $results ) ) { + wp_send_json_error(); + } + } + + if ( null !== $results ) { + $saved = WP_Site_Health::update_site_status_detail( $results, $counts ); + } elseif ( null !== $counts ) { + $saved = WP_Site_Health::set_site_status_counts( $counts ); + } else { + wp_send_json_error(); + } + + if ( is_wp_error( $saved ) ) { + wp_send_json_error( $saved ); + } wp_send_json_success(); } diff --git a/src/wp-admin/includes/class-wp-site-health.php b/src/wp-admin/includes/class-wp-site-health.php index b9ce4f472834f..7e4c4c3f5e6a5 100644 --- a/src/wp-admin/includes/class-wp-site-health.php +++ b/src/wp-admin/includes/class-wp-site-health.php @@ -7,9 +7,28 @@ * @since 5.2.0 */ - require_once __DIR__ . '/secrets-site-health.php'; +/** + * @phpstan-type Test_Status_Counts array{ + * good: non-negative-int, + * recommended: non-negative-int, + * critical: non-negative-int, + * } + * @phpstan-type Stored_Test_Result array{ + * status: 'good'|'recommended'|'critical', + * timestamp: non-negative-int, + * } + * @phpstan-type Stored_Test_Results array{ + * results: array, + * timestamp: non-negative-int, + * } + * @phpstan-type Site_Status_Detail array{ + * results: array, + * counts: Test_Status_Counts, + * timestamp: non-negative-int, + * } + */ #[AllowDynamicProperties] class WP_Site_Health { private static $instance = null; @@ -32,6 +51,75 @@ class WP_Site_Health { private $timeout_missed_cron = null; private $timeout_late_cron = null; + private const VALID_STATUS_VALUES = array( 'good', 'recommended', 'critical' ); + + /* + * Maximum number of detailed results kept in the autoloaded transient. Core + * registers about 30 tests. This limits growth in the number of entries, but + * does not impose a byte-size limit: the payload also depends on the length + * of test identifiers. + */ + private const MAX_STORED_RESULTS = 500; + + private const STATUS_COUNTS_SCHEMA = array( + 'type' => 'object', + 'properties' => array( + 'good' => array( + 'type' => 'integer', + 'minimum' => 0, + ), + 'recommended' => array( + 'type' => 'integer', + 'minimum' => 0, + ), + 'critical' => array( + 'type' => 'integer', + 'minimum' => 0, + ), + ), + ); + + private const STORED_STATUS_SCHEMA = array( + 'type' => 'object', + 'properties' => array( + 'results' => array( + 'type' => 'object', + 'additionalProperties' => array( + 'type' => 'object', + 'properties' => array( + 'status' => array( + 'type' => 'string', + 'enum' => self::VALID_STATUS_VALUES, + ), + 'timestamp' => array( + 'type' => 'integer', + 'minimum' => 1, + ), + ), + 'required' => array( 'status', 'timestamp' ), + 'additionalProperties' => false, + ), + ), + 'timestamp' => array( + 'type' => 'integer', + 'minimum' => 1, + ), + ), + 'required' => array( 'results', 'timestamp' ), + ); + + /** + * Transient name for the cached Site Health counts and verified test results. + * + * The top-level counts describe the latest run, including unavailable tests, + * and remain stored for consumers that read the transient directly. Core readers derive counts from + * the compact, locale-independent results, which retain each test's latest verified + * status. This transient remains autoloaded for the admin menu and Dashboard. + * + * @since 7.3.0 + */ + const STATUS_RESULT_TRANSIENT = 'health-check-site-status-result'; + /** * WP_Site_Health constructor. * @@ -77,7 +165,7 @@ public function show_site_health_tab( $tab ) { * * @since 5.4.0 * - * @return WP_Site_Health|null + * @return WP_Site_Health */ public static function get_instance() { self::$instance ??= new WP_Site_Health(); @@ -103,24 +191,13 @@ public function enqueue_scripts() { 'site_status_result' => wp_create_nonce( 'health-check-site-status-result' ), ), 'site_status' => array( - 'direct' => array(), - 'async' => array(), - 'issues' => array( - 'good' => 0, - 'recommended' => 0, - 'critical' => 0, - ), + 'direct' => array(), + 'async' => array(), + 'issues' => self::get_site_status_counts(), + 'results' => new stdClass(), ), ); - $issue_counts = get_transient( 'health-check-site-status-result' ); - - if ( false !== $issue_counts ) { - $issue_counts = json_decode( $issue_counts ); - - $health_check_js_variables['site_status']['issues'] = $issue_counts; - } - if ( 'site-health' === $screen->id && ( ! isset( $_GET['tab'] ) || empty( $_GET['tab'] ) ) ) { $tests = WP_Site_Health::get_tests(); @@ -2848,6 +2925,22 @@ public function get_test_opcode_cache(): array { * @since 5.6.0 Added support for `has_rest` and `permissions`. * * @return array The list of tests to run. + * + * @phpstan-return array{ + * direct: array, + * async: array, + * }>, + * } */ public static function get_tests() { $tests = array( @@ -3350,6 +3443,8 @@ public function maybe_create_scheduled_event() { * Runs the scheduled event to check and update the latest site health status for the website. * * @since 5.4.0 + * @since 7.3.0 Compact verified test results are saved with the counts in the same + * transient via WP_Site_Health::update_site_status_detail(). */ public function wp_cron_scheduled_check() { // Bootstrap wp-admin, as WP_Cron doesn't do this for us. @@ -3357,13 +3452,8 @@ public function wp_cron_scheduled_check() { $tests = WP_Site_Health::get_tests(); - $results = array(); - - $site_status = array( - 'good' => 0, - 'recommended' => 0, - 'critical' => 0, - ); + $results = array(); + $unavailable_tests = array(); // Don't run https test on development environments. if ( $this->is_development_environment() ) { @@ -3392,7 +3482,7 @@ public function wp_cron_scheduled_check() { } } - foreach ( $tests['async'] as $test ) { + foreach ( $tests['async'] as $test_name => $test ) { if ( ! empty( $test['skip_cron'] ) ) { continue; } @@ -3404,57 +3494,368 @@ public function wp_cron_scheduled_check() { continue; } - if ( is_string( $test['test'] ) ) { - // Check if this test has a REST API endpoint. - if ( isset( $test['has_rest'] ) && $test['has_rest'] ) { - $result_fetch = wp_remote_get( - $test['test'], - array( - 'body' => array( - '_wpnonce' => wp_create_nonce( 'wp_rest' ), - ), - ) - ); - } else { - $result_fetch = wp_remote_post( - admin_url( 'admin-ajax.php' ), - array( - 'body' => array( - 'action' => $test['test'], - '_wpnonce' => wp_create_nonce( 'health-check-site-status' ), - ), - ) - ); - } + // Check if this test has a REST API endpoint. + if ( isset( $test['has_rest'] ) && $test['has_rest'] ) { + $result_fetch = wp_remote_get( + $test['test'], + array( + 'body' => array( + '_wpnonce' => wp_create_nonce( 'wp_rest' ), + ), + ) + ); + } else { + $result_fetch = wp_remote_post( + admin_url( 'admin-ajax.php' ), + array( + 'body' => array( + 'action' => $test['test'], + '_wpnonce' => wp_create_nonce( 'health-check-site-status' ), + ), + ) + ); + } - if ( ! is_wp_error( $result_fetch ) && 200 === wp_remote_retrieve_response_code( $result_fetch ) ) { - $result = json_decode( wp_remote_retrieve_body( $result_fetch ), true ); - } else { - $result = false; - } + if ( ! is_wp_error( $result_fetch ) && 200 === wp_remote_retrieve_response_code( $result_fetch ) ) { + $result = json_decode( wp_remote_retrieve_body( $result_fetch ), true ); + } else { + $result = false; + } - if ( is_array( $result ) ) { - $results[] = $result; - } else { - $results[] = array( - 'status' => 'recommended', - 'label' => __( 'A test is unavailable' ), - ); + if ( is_array( $result ) ) { + $results[] = $result; + } else { + // Include the test identifier so the unavailable result is counted consistently. + $unavailable_tests[ $test_name ] = true; + $results[] = array( + 'test' => $test_name, + 'status' => 'recommended', + 'label' => __( 'A test is unavailable' ), + ); + } + } + + $counts = self::normalize_status_counts( array() ); + $results_to_store = array(); + foreach ( $results as $result ) { + // Filters may return unexpected values, so require the fields used by counts and details. + if ( ! is_array( $result ) ) { + continue; + } + + $test = $result['test'] ?? null; + $status = $result['status'] ?? null; + if ( + ! is_string( $test ) + || '' === sanitize_text_field( $test ) + || ! in_array( $status, self::VALID_STATUS_VALUES, true ) + ) { + continue; + } + + ++$counts[ $status ]; + if ( ! isset( $unavailable_tests[ $test ] ) ) { + $results_to_store[ $test ] = array( 'status' => $status ); + } + } + + /* + * An unavailable test affects this run's counts but must not replace a + * previously verified result, so only verified results are merged into details. + */ + self::update_site_status_detail( $results_to_store, $counts ); + } + + /** + * Calculates Site Health status counts from unexpired cached results. + * + * Stored aggregate counts are only used for caches without valid detailed results, + * including legacy counts-only values. An empty or fully expired set of valid + * detailed results returns zero counts instead of falling back to stored counts. + * The fallback preserves compatibility; it does not imply that stored counts + * are newer or more accurate than the detailed results. + * + * @since 7.3.0 + * + * @return array Aggregate counts. Each value is `0` when no result has been cached. + * @phpstan-return Test_Status_Counts + */ + public static function get_site_status_counts(): array { + $counts = self::read_site_status_cache(); + $detail = self::normalize_site_status_detail( $counts ); + if ( $detail['timestamp'] > 0 ) { + return self::count_site_status_results( $detail['results'] ); + } + + if ( is_wp_error( rest_validate_value_from_schema( $counts, self::STATUS_COUNTS_SCHEMA ) ) ) { + $counts = array(); + } + + return self::normalize_status_counts( $counts ); + } + + /** + * Caches the aggregate Site Health status counts. + * + * Preserves unexpired verified results and their collection timestamps. + * These stored counts are retained for backward compatibility; readers derive + * counts from valid detailed results when available. + * + * @since 7.3.0 + * + * @param mixed[] $counts Aggregate counts. + * @return true|WP_Error True when the counts were saved, or WP_Error on failure. + */ + public static function set_site_status_counts( array $counts ) { + $validity = rest_validate_value_from_schema( $counts, self::STATUS_COUNTS_SCHEMA ); + if ( is_wp_error( $validity ) ) { + return $validity; + } + + return self::save_site_status_cache( + array_merge( self::normalize_status_counts( $counts ), self::normalize_site_status_detail( self::read_site_status_cache() ) ) + ); + } + + /** + * Returns the cached detailed Site Health test results. + * + * The `counts` are derived from the cached `results`, so the two are always + * internally consistent. WP_Site_Health::get_site_status_counts() uses the same + * calculation when valid detailed results are available, falling back to stored + * counts only for caches without valid details, including legacy counts-only values. + * Results older than a month are excluded even when no writer has refreshed + * the autoloaded transient. + * + * @since 7.3.0 + * + * @return array The cached results as a map keyed by test name, aggregate counts derived + * from those same results, and the time of the most recent update. `results` + * is empty and all counts are `0` when no unexpired results remain. The + * timestamp records the last detail update, or `0` if none is available. + * @phpstan-return Site_Status_Detail + */ + public static function get_site_status_detail(): array { + $cached = self::normalize_site_status_detail( self::read_site_status_cache() ); + + return array( + 'results' => $cached['results'], + 'counts' => self::count_site_status_results( $cached['results'] ), + 'timestamp' => $cached['timestamp'], + ); + } + + /** + * Updates the detailed Site Health results cache. + * + * Results are normalized and sanitized, then stored keyed by test name with a + * per-result timestamp. Entries that have not been refreshed within a month are + * dropped, for example when the plugin that registered a test has been deactivated. + * At most 500 results are kept. When there are more, critical results are kept + * first, then recommended, then good, and the newest results within each status. + * Optional latest-run counts are validated and saved in the same write for + * consumers that read the transient directly. When omitted, the stored counts + * are preserved. Core readers calculate counts from the retained, unexpired + * results instead, so expiry and the storage limit also affect those counts. + * + * @since 7.3.0 + * + * @param array $results Map of raw Site Health test result arrays, + * keyed by test name. + * @param mixed[]|null $counts Optional latest-run counts to save with the results. + * @return true|WP_Error True on success, WP_Error on failure. + */ + public static function update_site_status_detail( array $results, ?array $counts = null ) { + if ( null !== $counts ) { + $validity = rest_validate_value_from_schema( $counts, self::STATUS_COUNTS_SCHEMA ); + if ( is_wp_error( $validity ) ) { + return $validity; + } + } + + $now = time(); + + $stored = self::read_site_status_cache(); + $cached = self::normalize_site_status_detail( $stored ); + if ( null === $counts ) { + $counts = is_wp_error( rest_validate_value_from_schema( $stored, self::STATUS_COUNTS_SCHEMA ) ) ? array() : $stored; + } + + foreach ( $results as $test => $result ) { + $test = sanitize_text_field( $test ); + if ( '' === $test ) { + return new WP_Error( 'invalid_test', __( 'The Site Health test identifier is invalid.' ) ); + } + + if ( is_array( $result ) ) { + $result['timestamp'] = $now; + } + + $validity = rest_validate_value_from_schema( $result, self::STORED_STATUS_SCHEMA['properties']['results']['additionalProperties'] ); + if ( is_wp_error( $validity ) ) { + return $validity; + } + /** @var Stored_Test_Result $result */ + + $cached['results'][ $test ] = $result; + } + + /* + * Keep the autoloaded transient small. When over the limit, drop the least useful + * results first: good before recommended before critical, and older before newer. + * The original order breaks ties, so the outcome does not depend on the sort algorithm. + */ + if ( count( $cached['results'] ) > self::MAX_STORED_RESULTS ) { + $unsorted = $cached['results']; + $priority = array_flip( array( 'critical', 'recommended', 'good' ) ); + $position = array_flip( array_keys( $unsorted ) ); + uksort( + $cached['results'], + static function ( $a, $b ) use ( $unsorted, $priority, $position ) { + $status_order = $priority[ $unsorted[ $a ]['status'] ] <=> $priority[ $unsorted[ $b ]['status'] ]; + if ( 0 !== $status_order ) { + return $status_order; + } + + $newest_first = $unsorted[ $b ]['timestamp'] <=> $unsorted[ $a ]['timestamp']; + if ( 0 !== $newest_first ) { + return $newest_first; + } + + return $position[ $a ] <=> $position[ $b ]; } + ); + $cached['results'] = array_slice( $cached['results'], 0, self::MAX_STORED_RESULTS, true ); + } + + return self::save_site_status_cache( + array_merge( + self::normalize_status_counts( $counts ), + array( + 'results' => $cached['results'], + 'timestamp' => $now, + ) + ) + ); + } + + /** + * Saves the counts and compact results together in the autoloaded transient. + * + * @since 7.3.0 + * + * @param array $status Combined counts and detailed results. + * @return true|WP_Error True on success, WP_Error on failure. + */ + private static function save_site_status_cache( array $status ) { + $stored_value = wp_json_encode( $status ); + + // An unchanged option also returns false, so only read back after a failed write. + if ( ! set_transient( self::STATUS_RESULT_TRANSIENT, $stored_value ) && + get_transient( self::STATUS_RESULT_TRANSIENT ) !== $stored_value + ) { + return new WP_Error( 'set_transient_error', __( 'The Site Health status could not be saved.' ) ); + } + return true; + } + + /** + * Reads and decodes the shared Site Health cache. + * + * @since 7.3.0 + * + * @return mixed[] The decoded cache, or an empty array when unavailable. + */ + private static function read_site_status_cache(): array { + $cached = get_transient( self::STATUS_RESULT_TRANSIENT ); + if ( is_string( $cached ) ) { + $cached = json_decode( $cached, true ); + } + + return is_array( $cached ) ? $cached : array(); + } + + /** + * Validates detailed results and excludes expired entries from a cache snapshot. + * + * @since 7.3.0 + * + * @param mixed[] $cached The decoded cache. + * @return array The unexpired results and the last detail-update timestamp. + * @phpstan-return Stored_Test_Results + */ + private static function normalize_site_status_detail( array $cached ): array { + // The schema validation accepts an empty string as an empty object, so check the type too. + if ( + is_wp_error( rest_validate_value_from_schema( $cached, self::STORED_STATUS_SCHEMA ) ) + || ! is_array( $cached['results'] ) + ) { + $cached = array( + 'results' => array(), + 'timestamp' => 0, + ); + } + + /** @var Stored_Test_Results $cached */ + $expires_before = time() - MONTH_IN_SECONDS; + foreach ( $cached['results'] as $test => $result ) { + if ( $result['timestamp'] < $expires_before ) { + unset( $cached['results'][ $test ] ); } } + return array( + 'results' => $cached['results'], + 'timestamp' => $cached['timestamp'], + ); + } + + /** + * Normalizes a set of aggregate status counts to integers. + * + * @since 7.3.0 + * + * @param mixed[] $counts Raw counts that may be missing keys or hold non-integer values. + * @return array The good, recommended, and critical counts. + * @phpstan-return Test_Status_Counts + */ + private static function normalize_status_counts( array $counts ): array { + return array( + 'good' => max( 0, (int) ( $counts['good'] ?? 0 ) ), + 'recommended' => max( 0, (int) ( $counts['recommended'] ?? 0 ) ), + 'critical' => max( 0, (int) ( $counts['critical'] ?? 0 ) ), + ); + } + + /** + * Counts a set of Site Health results by status. + * + * @since 7.3.0 + * + * @param array $results Result arrays, each with a status. + * @return array Aggregate counts, one bucket per status. A status other than `recommended` or `critical` counts as `good`. + * @phpstan-return Test_Status_Counts + */ + private static function count_site_status_results( array $results ): array { + $counts = array( + 'good' => 0, + 'recommended' => 0, + 'critical' => 0, + ); + foreach ( $results as $result ) { - if ( 'critical' === $result['status'] ) { - ++$site_status['critical']; - } elseif ( 'recommended' === $result['status'] ) { - ++$site_status['recommended']; + $status = $result['status']; + + if ( 'critical' === $status ) { + ++$counts['critical']; + } elseif ( 'recommended' === $status ) { + ++$counts['recommended']; } else { - ++$site_status['good']; + ++$counts['good']; } } - set_transient( 'health-check-site-status-result', wp_json_encode( $site_status ) ); + return $counts; } /** diff --git a/src/wp-admin/includes/dashboard.php b/src/wp-admin/includes/dashboard.php index 3e0d28d7f85f1..b5bdee537d505 100644 --- a/src/wp-admin/includes/dashboard.php +++ b/src/wp-admin/includes/dashboard.php @@ -2214,22 +2214,12 @@ function dashboard_php_nag_class( $classes ) { * @since 5.4.0 */ function wp_dashboard_site_health() { - $get_issues = get_transient( 'health-check-site-status-result' ); - - $issue_counts = array(); - - if ( false !== $get_issues ) { - $issue_counts = json_decode( $get_issues, true ); - } - - if ( ! is_array( $issue_counts ) || ! $issue_counts ) { - $issue_counts = array( - 'good' => 0, - 'recommended' => 0, - 'critical' => 0, - ); + if ( ! class_exists( 'WP_Site_Health' ) ) { + require_once ABSPATH . 'wp-admin/includes/class-wp-site-health.php'; } + $issue_counts = WP_Site_Health::get_site_status_counts(); + $has_results = array_sum( $issue_counts ) > 0; $issues_total = $issue_counts['recommended'] + $issue_counts['critical']; ?>
@@ -2241,7 +2231,7 @@ function wp_dashboard_site_health() {
- + @@ -2250,7 +2240,7 @@ function wp_dashboard_site_health() {
- +

- 0 && false !== $get_issues ) : ?> + 0 && $has_results ) : ?>

0, - 'recommended' => 0, - 'critical' => 0, - ); + if ( ! class_exists( 'WP_Site_Health' ) ) { + require_once ABSPATH . 'wp-admin/includes/class-wp-site-health.php'; } + $issue_counts = WP_Site_Health::get_site_status_counts(); $site_health_count = sprintf( '%s', diff --git a/tests/phpunit/tests/admin/wpSiteHealth.php b/tests/phpunit/tests/admin/wpSiteHealth.php index e325c917b50ff..25abb83dc6b26 100644 --- a/tests/phpunit/tests/admin/wpSiteHealth.php +++ b/tests/phpunit/tests/admin/wpSiteHealth.php @@ -513,7 +513,6 @@ static function () { ); } - /** * @group ms-required * @ticket 56040 @@ -742,4 +741,699 @@ public function test_get_test_theme_version_with_no_installed_themes() { $this->assertSame( 'good', $result['status'] ); $this->assertStringContainsString( 'Your site does not have any installed themes.', $result['description'] ); } + + /** + * Registers a controlled set of direct Site Health tests via `site_status_tests`. + * + * @param array $direct Map of result arrays to return, keyed by test name. + * @return Closure The filter callback, so the caller can remove it. + */ + private function use_fake_site_status_tests( array $direct ): Closure { + $tests = array( + 'direct' => array(), + 'async' => array(), + ); + + foreach ( $direct as $name => $result ) { + $tests['direct'][ $name ] = array( + 'label' => $name, + 'test' => static function () use ( $result ) { + return $result; + }, + ); + } + + $filter = static function () use ( $tests ) { + return $tests; + }; + + add_filter( 'site_status_tests', $filter ); + + return $filter; + } + + /** + * Seeds the detailed Site Health results cache. + * + * @param array $results Map of result arrays keyed by test name. + * @param int $time Timestamp to store for the cache and each result. + */ + private function seed_site_status_detail( array $results, int $time ): void { + foreach ( $results as $test => $result ) { + $results[ $test ]['timestamp'] = $time; + } + + set_transient( + WP_Site_Health::STATUS_RESULT_TRANSIENT, + wp_json_encode( + array( + 'results' => $results, + 'timestamp' => $time, + ) + ) + ); + } + + /** + * The scheduled check extends the autoloaded counts transient with compact results. + * + * @ticket 65232 + * + * @covers ::wp_cron_scheduled_check + * @covers ::get_site_status_detail + * @covers ::update_site_status_detail + */ + public function test_scheduled_check_stores_counts_and_detail_together(): void { + $filter = $this->use_fake_site_status_tests( + array( + 'fake_critical' => array( + 'test' => 'fake_critical', + 'label' => 'Critical label', + 'status' => 'critical', + 'badge' => array( + 'label' => 'Security', + 'color' => 'red', + ), + 'description' => '

Critical description.

', + 'actions' => '', + ), + 'fake_recommended' => array( + 'test' => 'fake_recommended', + 'label' => 'Recommended label', + 'status' => 'recommended', + 'description' => '

Recommended description.

', + ), + 'fake_good' => array( + 'test' => 'fake_good', + 'label' => 'Good label', + 'status' => 'good', + 'description' => '

Good description.

', + ), + ) + ); + + delete_transient( WP_Site_Health::STATUS_RESULT_TRANSIENT ); + + $before = time(); + $this->instance->wp_cron_scheduled_check(); + $after = time(); + + remove_filter( 'site_status_tests', $filter ); + + $transient = get_transient( WP_Site_Health::STATUS_RESULT_TRANSIENT ); + $this->assertIsString( $transient ); + $stored = json_decode( $transient, true ); + $this->assertSameSets( + array( 'good', 'recommended', 'critical', 'results', 'timestamp' ), + array_keys( $stored ) + ); + $this->assertSame( 1, $stored['good'] ); + $this->assertSame( 1, $stored['recommended'] ); + $this->assertSame( 1, $stored['critical'] ); + + // The detailed cache holds every result, including the passing one. + $detail = WP_Site_Health::get_site_status_detail(); + + $results_by_test = $detail['results']; + + $this->assertSame( + array( 'fake_critical', 'fake_recommended', 'fake_good' ), + array_keys( $results_by_test ) + ); + + // Only locale-independent fields are stored: the test name, status, and timestamp. + $this->assertSameSets( + array( 'status', 'timestamp' ), + array_keys( $results_by_test['fake_critical'] ), + 'No translated or HTML fields should be cached.' + ); + $this->assertSame( 'critical', $results_by_test['fake_critical']['status'] ); + + // Each result carries its own collection timestamp. + $this->assertGreaterThanOrEqual( $before, $results_by_test['fake_critical']['timestamp'] ); + $this->assertLessThanOrEqual( $after, $results_by_test['fake_critical']['timestamp'] ); + + // The detail cache exposes counts derived from its own results. + $this->assertSame( + array( + 'good' => 1, + 'recommended' => 1, + 'critical' => 1, + ), + $detail['counts'], + 'Detail counts should be derived from the cached detail results.' + ); + } + + /** + * The shared transient has no expiration, so the database stores it as an autoloaded option. + * + * @ticket 65232 + * + * @covers ::update_site_status_detail + */ + public function test_status_cache_is_autoloaded_without_expiration(): void { + if ( wp_using_ext_object_cache() ) { + $this->markTestSkipped( 'This test requires that an external object cache is not in use.' ); + } + + $this->assertTrue( + WP_Site_Health::update_site_status_detail( + array( 'fake_good' => array( 'status' => 'good' ) ), + array( + 'good' => 1, + 'recommended' => 0, + 'critical' => 0, + ) + ) + ); + $this->assertArrayHasKey( '_transient_' . WP_Site_Health::STATUS_RESULT_TRANSIENT, wp_load_alloptions() ); + $this->assertFalse( get_option( '_transient_timeout_' . WP_Site_Health::STATUS_RESULT_TRANSIENT ) ); + } + + /** + * Only valid results are cached. The scheduled check ignores invalid results + * returned by the result filter, while direct updates return a validation error. + * + * @ticket 65232 + * + * @covers ::wp_cron_scheduled_check + * @covers ::update_site_status_detail + */ + public function test_only_valid_results_are_cached(): void { + $invalid_results = array( + 'non_array_result' => new WP_Error( 'invalid_result' ), + 'missing_test' => array( 'status' => 'good' ), + 'empty_test' => array( + 'test' => '', + 'status' => 'good', + ), + 'invalid_test' => array( + 'test' => array(), + 'status' => 'good', + ), + 'missing_status' => array( 'test' => 'missing_status' ), + 'invalid_status' => array( + 'test' => 'invalid_status', + 'status' => 'invalid', + ), + ); + $test_results = array(); + foreach ( array_merge( array_keys( $invalid_results ), array( 'valid_result' ) ) as $test ) { + $test_results[ $test ] = array( + 'test' => $test, + 'status' => 'good', + ); + } + + $tests_filter = $this->use_fake_site_status_tests( $test_results ); + $result_filter = static function ( $result ) use ( $invalid_results ) { + if ( is_array( $result ) && isset( $invalid_results[ $result['test'] ] ) ) { + return $invalid_results[ $result['test'] ]; + } + + return $result; + }; + add_filter( 'site_status_test_result', $result_filter ); + + delete_transient( WP_Site_Health::STATUS_RESULT_TRANSIENT ); + + try { + $this->instance->wp_cron_scheduled_check(); + } finally { + remove_filter( 'site_status_test_result', $result_filter ); + remove_filter( 'site_status_tests', $tests_filter ); + } + + $detail = WP_Site_Health::get_site_status_detail(); + $this->assertSame( array( 'valid_result' ), array_keys( $detail['results'] ) ); + $this->assertSame( + array( + 'good' => 1, + 'recommended' => 0, + 'critical' => 0, + ), + $detail['counts'] + ); + $this->assertSame( $detail['counts'], WP_Site_Health::get_site_status_counts() ); + + $result = WP_Site_Health::update_site_status_detail( + array( + '' => array( + 'status' => 'good', + ), + ) + ); + + $this->assertWPError( $result ); + $this->assertSame( 'invalid_test', $result->get_error_code() ); + $this->assertNotSame( '', $result->get_error_message() ); + $this->assertSame( array( 'valid_result' ), array_keys( WP_Site_Health::get_site_status_detail()['results'] ) ); + } + + /** + * An unavailable asynchronous test is counted but does not replace a previously + * verified detailed result. + * + * @ticket 65232 + * + * @covers ::wp_cron_scheduled_check + */ + public function test_scheduled_check_preserves_verified_result_when_async_test_is_unavailable(): void { + $cached_at = time() - 2 * WEEK_IN_SECONDS; + $this->seed_site_status_detail( + array( + 'my_async' => array( + 'status' => 'good', + ), + ), + $cached_at + ); + + // Force the asynchronous remote request to fail so the fallback path runs. + $http = static function () { + return new WP_Error( 'unavailable', 'Service unavailable.' ); + }; + add_filter( 'pre_http_request', $http ); + + $filter = static function () { + return array( + 'direct' => array(), + 'async' => array( + 'my_async' => array( + 'label' => 'My async test', + 'test' => 'https://example.invalid/site-health', + 'has_rest' => true, + ), + ), + ); + }; + add_filter( 'site_status_tests', $filter ); + + $this->instance->wp_cron_scheduled_check(); + + remove_filter( 'site_status_tests', $filter ); + remove_filter( 'pre_http_request', $http ); + + $detail = WP_Site_Health::get_site_status_detail(); + $results_by_id = $detail['results']; + + $this->assertArrayHasKey( 'my_async', $results_by_id ); + $this->assertSame( 'good', $results_by_id['my_async']['status'] ); + $this->assertSame( $cached_at, $results_by_id['my_async']['timestamp'] ); + $this->assertSame( 0, WP_Site_Health::get_site_status_counts()['recommended'] ); + $this->assertSame( $detail['counts'], WP_Site_Health::get_site_status_counts() ); + $stored = json_decode( get_transient( WP_Site_Health::STATUS_RESULT_TRANSIENT ), true ); + $this->assertSame( 1, $stored['recommended'], 'Unavailable tests remain in the stored counts for compatibility.' ); + } + + /** + * The scheduled check overwrites an existing result when it collects a newer verified result. + * + * @ticket 65232 + * + * @covers ::wp_cron_scheduled_check + * @covers ::update_site_status_detail + */ + public function test_scheduled_check_stores_freshest_verified_result(): void { + $this->seed_site_status_detail( + array( + 'fake_async' => array( + 'status' => 'good', + ), + ), + time() + ); + + $filter = $this->use_fake_site_status_tests( + array( + 'fake_async' => array( + 'test' => 'fake_async', + 'status' => 'critical', + ), + ) + ); + + $this->instance->wp_cron_scheduled_check(); + + remove_filter( 'site_status_tests', $filter ); + + $detail = WP_Site_Health::get_site_status_detail(); + $this->assertCount( 1, $detail['results'] ); + $this->assertSame( 'critical', array_first( $detail['results'] )['status'] ); + } + + /** + * The detail accessor distinguishes a valid empty cache from a missing or malformed cache. + * + * @ticket 65232 + * + * @covers ::get_site_status_detail + * @covers ::get_site_status_counts + * @covers ::update_site_status_detail + */ + public function test_get_site_status_detail_distinguishes_empty_from_missing_or_malformed_cache(): void { + delete_transient( WP_Site_Health::STATUS_RESULT_TRANSIENT ); + $this->assertSame( + array( + 'good' => 0, + 'recommended' => 0, + 'critical' => 0, + ), + WP_Site_Health::get_site_status_counts() + ); + + $detail = WP_Site_Health::get_site_status_detail(); + $this->assertSame( array(), $detail['results'] ); + $this->assertSame( 0, $detail['timestamp'] ); + + $before = time(); + $this->assertTrue( WP_Site_Health::update_site_status_detail( array() ) ); + $after = time(); + + $detail = WP_Site_Health::get_site_status_detail(); + $this->assertSame( array(), $detail['results'] ); + $this->assertGreaterThanOrEqual( $before, $detail['timestamp'] ); + $this->assertLessThanOrEqual( $after, $detail['timestamp'] ); + $this->assertIsString( get_transient( WP_Site_Health::STATUS_RESULT_TRANSIENT ) ); + + $now = time(); + set_transient( + WP_Site_Health::STATUS_RESULT_TRANSIENT, + wp_json_encode( + array( + 'results' => array( + 'missing_timestamp' => array( 'status' => 'good' ), + ), + 'timestamp' => $now, + ) + ) + ); + + $detail = WP_Site_Health::get_site_status_detail(); + $this->assertSame( array(), $detail['results'] ); + $this->assertSame( 0, $detail['timestamp'] ); + + // The schema validation accepts an empty string as an object, but it must not reach the reader. + set_transient( + WP_Site_Health::STATUS_RESULT_TRANSIENT, + wp_json_encode( + array( + 'results' => '', + 'timestamp' => $now, + ) + ) + ); + + $detail = WP_Site_Health::get_site_status_detail(); + $this->assertSame( array(), $detail['results'] ); + $this->assertSame( 0, $detail['timestamp'] ); + + set_transient( + WP_Site_Health::STATUS_RESULT_TRANSIENT, + wp_json_encode( + array( + 'results' => array( + 'missing_cache_timestamp' => array( + 'status' => 'good', + 'timestamp' => $now, + ), + ), + ), + ) + ); + + $detail = WP_Site_Health::get_site_status_detail(); + $this->assertSame( array(), $detail['results'] ); + $this->assertSame( 0, $detail['timestamp'] ); + } + + /** + * An empty detailed cache must not revive stored counts. + * + * @ticket 65232 + * @covers ::get_site_status_counts + */ + public function test_empty_details_override_stored_counts(): void { + $this->assertTrue( + WP_Site_Health::update_site_status_detail( + array(), + array( + 'good' => 5, + 'recommended' => 2, + 'critical' => 1, + ) + ) + ); + $this->assertSame( + array( + 'good' => 0, + 'recommended' => 0, + 'critical' => 0, + ), + WP_Site_Health::get_site_status_counts() + ); + } + + /** + * The Dashboard counts verified results and treats expired results as unavailable. + * + * @ticket 65232 + * @covers ::get_site_status_counts + * @covers ::get_site_status_detail + * @covers \wp_dashboard_site_health + */ + public function test_dashboard_uses_unexpired_result_counts(): void { + require_once ABSPATH . 'wp-admin/includes/dashboard.php'; + + $this->assertTrue( + WP_Site_Health::update_site_status_detail( + array( 'verified' => array( 'status' => 'critical' ) ), + array( + 'good' => 5, + 'recommended' => 0, + 'critical' => 0, + ) + ) + ); + $output = get_echo( 'wp_dashboard_site_health' ); + $this->assertStringContainsString( 'Your site has a critical issue', $output ); + $this->assertStringNotContainsString( 'Great job!', $output ); + + $stored = json_decode( get_transient( WP_Site_Health::STATUS_RESULT_TRANSIENT ), true ); + $stored['results']['verified']['timestamp'] = time() - MONTH_IN_SECONDS - 10; + set_transient( WP_Site_Health::STATUS_RESULT_TRANSIENT, wp_json_encode( $stored ) ); + + $output = get_echo( 'wp_dashboard_site_health' ); + $this->assertStringContainsString( 'No information yet', $output ); + $this->assertStringNotContainsString( 'Great job!', $output ); + } + + /** + * Old counts remain stored for compatibility, but readers count detailed results once available. + * + * @ticket 65232 + * @covers ::update_site_status_detail + * @covers ::set_site_status_counts + * @covers ::get_site_status_counts + */ + public function test_extending_legacy_counts_switches_readers_to_detailed_results(): void { + $counts = array( + 'good' => 9, + 'recommended' => 2, + 'critical' => 1, + ); + set_transient( WP_Site_Health::STATUS_RESULT_TRANSIENT, wp_json_encode( $counts ) ); + $this->assertSame( $counts, WP_Site_Health::get_site_status_counts() ); + $this->assertSame( 0, WP_Site_Health::get_site_status_detail()['timestamp'] ); + + $reads_before = did_filter( 'pre_transient_' . WP_Site_Health::STATUS_RESULT_TRANSIENT ); + $this->assertTrue( WP_Site_Health::update_site_status_detail( array( 'verified' => array( 'status' => 'good' ) ) ) ); + $this->assertSame( 1, did_filter( 'pre_transient_' . WP_Site_Health::STATUS_RESULT_TRANSIENT ) - $reads_before, 'A results-only update should read the shared cache once.' ); + $this->assertSame( + array( + 'good' => 1, + 'recommended' => 0, + 'critical' => 0, + ), + WP_Site_Health::get_site_status_counts() + ); + $detail = WP_Site_Health::get_site_status_detail(); + + $counts['critical'] = 3; + $this->assertTrue( WP_Site_Health::set_site_status_counts( $counts ) ); + $this->assertSame( $detail, WP_Site_Health::get_site_status_detail() ); + $this->assertSame( + array( + 'good' => 1, + 'recommended' => 0, + 'critical' => 0, + ), + WP_Site_Health::get_site_status_counts() + ); + $stored = json_decode( get_transient( WP_Site_Health::STATUS_RESULT_TRANSIENT ), true ); + $this->assertSame( $counts, array_intersect_key( $stored, $counts ) ); + } + + /** + * Counts exclude expired results even without a scheduled update. + * + * @ticket 65232 + * @covers ::get_site_status_detail + * @covers ::update_site_status_detail + * @covers ::set_site_status_counts + */ + public function test_reading_expired_details_recalculates_counts(): void { + $counts = array( + 'good' => 4, + 'recommended' => 1, + 'critical' => 0, + ); + $old = time() - MONTH_IN_SECONDS - 10; + $status = array_merge( + $counts, + array( + 'results' => array( + 'old' => array( + 'status' => 'critical', + 'timestamp' => $old, + ), + 'new' => array( + 'status' => 'good', + 'timestamp' => time(), + ), + ), + 'timestamp' => time(), + ) + ); + set_transient( WP_Site_Health::STATUS_RESULT_TRANSIENT, wp_json_encode( $status ) ); + $detail = WP_Site_Health::get_site_status_detail(); + $this->assertSame( array( 'new' ), array_keys( $detail['results'] ) ); + $this->assertSame( 1, $detail['counts']['good'] ); + $this->assertSame( 0, $detail['counts']['critical'] ); + $this->assertSame( $detail['counts'], WP_Site_Health::get_site_status_counts() ); + + $this->assertTrue( WP_Site_Health::update_site_status_detail( array() ) ); + $stored = json_decode( get_transient( WP_Site_Health::STATUS_RESULT_TRANSIENT ), true ); + $this->assertSame( array( 'new' ), array_keys( $stored['results'] ), 'A detail update must persist pruning, even with no new results.' ); + + $status['results']['new']['timestamp'] = $old; + $status['timestamp'] = $old; + set_transient( WP_Site_Health::STATUS_RESULT_TRANSIENT, wp_json_encode( $status ) ); + $this->assertSame( array(), WP_Site_Health::get_site_status_detail()['results'] ); + $this->assertSame( $old, WP_Site_Health::get_site_status_detail()['timestamp'] ); + $this->assertSame( + array( + 'good' => 0, + 'recommended' => 0, + 'critical' => 0, + ), + WP_Site_Health::get_site_status_counts() + ); + + // A counts-only update must prune expired details without refreshing their age. + $this->assertTrue( WP_Site_Health::set_site_status_counts( $counts ) ); + $stored = json_decode( get_transient( WP_Site_Health::STATUS_RESULT_TRANSIENT ), true ); + $this->assertSame( array(), $stored['results'] ); + $this->assertSame( $old, $stored['timestamp'] ); + } + + /** + * When over the limit, the least useful results are dropped first. + * + * Critical results are kept before recommended ones, and recommended before good. + * Within each status, newer results are kept before older ones. + * + * @ticket 65232 + * @covers ::update_site_status_detail + */ + public function test_update_site_status_detail_limits_stored_results(): void { + $cached = array(); + for ( $i = 0; $i < 500; $i++ ) { + $cached[ "cached_$i" ] = array( + 'status' => 0 === $i ? 'critical' : 'good', + 'timestamp' => time() - 1000 + $i, + ); + } + set_transient( + WP_Site_Health::STATUS_RESULT_TRANSIENT, + wp_json_encode( + array( + 'results' => $cached, + 'timestamp' => time(), + ) + ) + ); + + $this->assertTrue( + WP_Site_Health::update_site_status_detail( + array( + 'cached_2' => array( 'status' => 'recommended' ), + 'submitted' => array( 'status' => 'recommended' ), + ) + ) + ); + $results = WP_Site_Health::get_site_status_detail()['results']; + $this->assertCount( 500, $results ); + $this->assertArrayHasKey( 'cached_0', $results, 'An old critical result must be kept.' ); + $this->assertArrayNotHasKey( 'cached_1', $results, 'The oldest good result must be dropped.' ); + $this->assertSame( 'recommended', $results['cached_2']['status'] ); + $this->assertArrayHasKey( 'submitted', $results ); + $this->assertSame( + array( + 'good' => 497, + 'recommended' => 2, + 'critical' => 1, + ), + WP_Site_Health::get_site_status_counts() + ); + + $submitted = array(); + for ( $i = 0; $i < 500; $i++ ) { + $submitted[ "submitted_$i" ] = array( 'status' => 'good' ); + } + $submitted['submitted_critical'] = array( 'status' => 'critical' ); + $this->assertTrue( WP_Site_Health::update_site_status_detail( $submitted ) ); + + $expected = array_merge( + array( 'submitted_critical', 'cached_0', 'cached_2', 'submitted' ), + array_slice( array_keys( $submitted ), 0, 496 ) + ); + $this->assertSame( $expected, array_keys( WP_Site_Health::get_site_status_detail()['results'] ) ); + } + + /** + * An unchanged cache is a success, but a failed write must still report an error. + * + * @ticket 65232 + * @covers ::set_site_status_counts + */ + public function test_cache_write_failure_returns_error(): void { + if ( wp_using_ext_object_cache() ) { + $this->markTestSkipped( 'This test requires that an external object cache is not in use.' ); + } + + $counts = array( + 'good' => 1, + 'recommended' => 0, + 'critical' => 0, + ); + $this->assertTrue( WP_Site_Health::set_site_status_counts( $counts ) ); + $this->assertTrue( WP_Site_Health::set_site_status_counts( $counts ) ); + $before = get_transient( WP_Site_Health::STATUS_RESULT_TRANSIENT ); + $prevent_write = static function ( $value, $old_value ) { + return $old_value; + }; + $filter = 'pre_update_option__transient_' . WP_Site_Health::STATUS_RESULT_TRANSIENT; + add_filter( $filter, $prevent_write, 10, 2 ); + $counts['good'] = 2; + try { + $result = WP_Site_Health::set_site_status_counts( $counts ); + } finally { + remove_filter( $filter, $prevent_write ); + } + $this->assertWPError( $result ); + $this->assertSame( 'set_transient_error', $result->get_error_code() ); + $this->assertSame( $before, get_transient( WP_Site_Health::STATUS_RESULT_TRANSIENT ) ); + } } diff --git a/tests/phpunit/tests/ajax/wpAjaxHealthCheckSiteStatusResult.php b/tests/phpunit/tests/ajax/wpAjaxHealthCheckSiteStatusResult.php new file mode 100644 index 0000000000000..b63d9664801b5 --- /dev/null +++ b/tests/phpunit/tests/ajax/wpAjaxHealthCheckSiteStatusResult.php @@ -0,0 +1,267 @@ +super_admin_user_id ) { + revoke_super_admin( $this->super_admin_user_id ); + $this->super_admin_user_id = 0; + } + + parent::tear_down(); + } + + /** + * Sets the current user to one that can view Site Health checks. + */ + private function set_user_with_site_health_capability(): void { + $this->_setRole( 'administrator' ); + + if ( is_multisite() ) { + $this->super_admin_user_id = get_current_user_id(); + grant_super_admin( $this->super_admin_user_id ); + } + } + + /** + * Dispatches the Ajax request and returns the decoded JSON response. + * + * @return array{ success: bool, ... } The decoded response. + */ + private function dispatch_result_request(): array { + $this->_last_response = ''; + + try { + $this->_handleAjax( self::ACTION ); + } catch ( WPAjaxDieContinueException $e ) { + unset( $e ); + } + + $response = json_decode( $this->_last_response, true ); + assert( is_array( $response ) ); + return $response; + } + + /** + * The request stores both parts in one write, without deriving latest-run counts from details. + * + * @ticket 65232 + */ + public function test_posting_counts_and_results_caches_them_together(): void { + delete_transient( WP_Site_Health::STATUS_RESULT_TRANSIENT ); + $this->set_user_with_site_health_capability(); + $_POST['_wpnonce'] = wp_create_nonce( self::ACTION ); + $_POST['counts'] = array( + 'good' => 5, + 'recommended' => 1, + 'critical' => 2, + ); + $_POST['results'] = wp_slash( wp_json_encode( array( 'a' => array( 'status' => 'critical' ) ) ) ); + + $writes_before = did_action( 'set_transient_' . WP_Site_Health::STATUS_RESULT_TRANSIENT ); + $this->assertTrue( $this->dispatch_result_request()['success'] ); + $this->assertSame( 1, did_action( 'set_transient_' . WP_Site_Health::STATUS_RESULT_TRANSIENT ) - $writes_before ); + $stored = json_decode( get_transient( WP_Site_Health::STATUS_RESULT_TRANSIENT ), true ); + $this->assertSame( $_POST['counts'], array_intersect_key( $stored, $_POST['counts'] ) ); + $this->assertSame( WP_Site_Health::get_site_status_detail()['counts'], WP_Site_Health::get_site_status_counts() ); + $detail = WP_Site_Health::get_site_status_detail(); + $this->assertSame( array( 'a' ), array_keys( $detail['results'] ) ); + $this->assertSame( 'critical', $detail['results']['a']['status'] ); + $this->assertSame( + array( + 'good' => 0, + 'recommended' => 0, + 'critical' => 1, + ), + $detail['counts'] + ); + } + + /** + * Posting only the results updates the detailed cache without changing the latest-run counts. + * + * @ticket 65232 + */ + public function test_posting_results_only_updates_calculated_counts(): void { + delete_transient( WP_Site_Health::STATUS_RESULT_TRANSIENT ); + + $this->set_user_with_site_health_capability(); + $_POST['_wpnonce'] = wp_create_nonce( self::ACTION ); + $_POST['results'] = wp_slash( wp_json_encode( array( 'a' => array( 'status' => 'critical' ) ) ) ); + + $response = $this->dispatch_result_request(); + + $this->assertTrue( $response['success'] ); + + // The detailed cache is updated. + $results = WP_Site_Health::get_site_status_detail()['results']; + $this->assertSame( array( 'a' ), array_keys( $results ) ); + + // Readers calculate counts from the posted results. + $this->assertSame( + array( + 'good' => 0, + 'recommended' => 0, + 'critical' => 1, + ), + WP_Site_Health::get_site_status_counts() + ); + } + + /** + * Posting only counts refreshes the counts and leaves verified results intact. + * + * @ticket 65232 + */ + public function test_posting_counts_only_leaves_detail_intact(): void { + WP_Site_Health::update_site_status_detail( array( 'seeded' => array( 'status' => 'good' ) ) ); + $detail = WP_Site_Health::get_site_status_detail(); + + $this->set_user_with_site_health_capability(); + $_POST['_wpnonce'] = wp_create_nonce( self::ACTION ); + $_POST['counts'] = array( + 'good' => 3, + 'recommended' => 0, + 'critical' => 0, + ); + + $response = $this->dispatch_result_request(); + + $this->assertTrue( $response['success'] ); + + $this->assertSame( + array( + 'good' => 1, + 'recommended' => 0, + 'critical' => 0, + ), + WP_Site_Health::get_site_status_counts() + ); + + $this->assertSame( $detail, WP_Site_Health::get_site_status_detail(), 'Verified results and timestamps should be untouched.' ); + } + + /** + * Users without the capability cannot write to the cache. + * + * @ticket 65232 + */ + public function test_user_without_capability_cannot_write_cache(): void { + delete_transient( WP_Site_Health::STATUS_RESULT_TRANSIENT ); + + $this->_setRole( 'subscriber' ); + $_POST['_wpnonce'] = wp_create_nonce( self::ACTION ); + $_POST['counts'] = array( + 'good' => 1, + 'recommended' => 1, + 'critical' => 1, + ); + $_POST['results'] = wp_slash( wp_json_encode( array( 'a' => array( 'status' => 'critical' ) ) ) ); + + $response = $this->dispatch_result_request(); + + $this->assertFalse( $response['success'] ); + $this->assertFalse( get_transient( WP_Site_Health::STATUS_RESULT_TRANSIENT ) ); + } + + /** + * Invalid requests must not partially overwrite the shared cache. + * + * @ticket 65232 + * @dataProvider data_invalid_cache_requests + * + * @param array $request Submitted fields, excluding the nonce. + * @param string|null $error_code Expected validation error code, if provided. + */ + public function test_invalid_request_preserves_existing_cache( array $request, ?string $error_code ): void { + $this->set_user_with_site_health_capability(); + WP_Site_Health::update_site_status_detail( + array( 'existing' => array( 'status' => 'good' ) ), + array( + 'good' => 1, + 'recommended' => 0, + 'critical' => 0, + ) + ); + $before = get_transient( WP_Site_Health::STATUS_RESULT_TRANSIENT ); + $_POST = wp_slash( $request ); + $_POST['_wpnonce'] = wp_create_nonce( self::ACTION ); + $response = $this->dispatch_result_request(); + $this->assertFalse( $response['success'] ); + if ( null !== $error_code ) { + $this->assertSame( $error_code, $response['data'][0]['code'] ); + } + $this->assertSame( $before, get_transient( WP_Site_Health::STATUS_RESULT_TRANSIENT ) ); + } + + /** + * @return array Named invalid requests and their expected error codes. + */ + public static function data_invalid_cache_requests(): array { + return array( + 'no fields' => array( array(), null ), + 'invalid counts with valid results' => array( + array( + 'counts' => array( 'good' => -1 ), + 'results' => '{"new":{"status":"critical"}}', + ), + 'rest_out_of_bounds', + ), + 'valid counts with malformed JSON' => array( + array( + 'counts' => array( 'good' => 2 ), + 'results' => '{invalid json', + ), + null, + ), + 'valid counts with invalid status' => array( + array( + 'counts' => array( 'good' => 2 ), + 'results' => '{"new":{"status":"invalid"}}', + ), + 'rest_not_in_enum', + ), + ); + } +} diff --git a/tests/qunit/index.html b/tests/qunit/index.html index f9033a776151c..fff6a71cfd6d0 100644 --- a/tests/qunit/index.html +++ b/tests/qunit/index.html @@ -89,9 +89,11 @@
+ + @@ -134,6 +136,46 @@ + + @@ -186,6 +228,7 @@ + diff --git a/tests/qunit/wp-admin/js/site-health.js b/tests/qunit/wp-admin/js/site-health.js new file mode 100644 index 0000000000000..2208166d17026 --- /dev/null +++ b/tests/qunit/wp-admin/js/site-health.js @@ -0,0 +1,24 @@ +/* global SiteHealth */ + +QUnit.module( 'Site Health', function() { + QUnit.test( 'updates state only for valid direct tests', function( assert ) { + assert.deepEqual( + SiteHealth.site_status.results, + { + direct_test: { + status: 'good' + } + }, + 'The test results contain locale-independent data and exclude missing, empty, and whitespace-only identifiers.' + ); + assert.deepEqual( + SiteHealth.site_status.issues, + { + critical: 0, + good: 1, + recommended: 0 + }, + 'The issue counts reflect the test results.' + ); + } ); +} );