Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
76.32% covered (warning)
76.32%
58 / 76
66.67% covered (warning)
66.67%
4 / 6
CRAP
0.00% covered (danger)
0.00%
0 / 1
Site_Health
76.32% covered (warning)
76.32%
58 / 76
66.67% covered (warning)
66.67%
4 / 6
20.84
0.00% covered (danger)
0.00%
0 / 1
 init
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
 do_daily_connection_check
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 maybe_register_site_health
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 register_site_health_tests
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
2
 make_site_health_callback
72.34% covered (warning)
72.34%
34 / 47
0.00% covered (danger)
0.00%
0 / 1
8.04
 ajax_local_testing_suite
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
6
1<?php
2/**
3 * WordPress Site Health integration for the Jetpack Connection package.
4 *
5 * @package automattic/jetpack-connection
6 */
7
8namespace Automattic\Jetpack\Connection;
9
10/**
11 * Integrates connection health tests into WordPress Site Health.
12 *
13 * This class defers to the Jetpack plugin's own debugger integration when it
14 * is present (old Jetpack versions). When no legacy integration is detected,
15 * it registers the connection health tests directly.
16 *
17 * @since 8.5.0
18 */
19class Site_Health {
20
21    /**
22     * Whether the class has been initialized.
23     *
24     * @var bool
25     */
26    private static $initialized = false;
27
28    /**
29     * Initialize Site Health integration.
30     *
31     * Should be called once, typically from the package's actions.php via a plugins_loaded hook.
32     *
33     * @since 8.5.0
34     */
35    public static function init() {
36        if ( self::$initialized ) {
37            return;
38        }
39        self::$initialized = true;
40
41        add_action( 'admin_init', array( __CLASS__, 'maybe_register_site_health' ), 1 );
42
43        // Deliberately hooked to the cron-only `jetpack_heartbeat` action (end of
44        // Heartbeat::cron_exec()) and not `jetpack_heartbeat_stats_array`, which
45        // also fires in synchronous request contexts (XML-RPC, REST, WP-CLI) where
46        // a remote test would be slow and an amplification vector.
47        add_action( 'jetpack_heartbeat', array( __CLASS__, 'do_daily_connection_check' ) );
48    }
49
50    /**
51     * Runs the WP.com connection test once a day on the heartbeat cron.
52     *
53     * The test result itself is discarded: the point is the test's side effects,
54     * which keep the Error_Handler state for failures that WP.com cannot report
55     * through a request of its own (e.g. the site blocking WP.com requests) fresh —
56     * reported while the condition persists, cleared once it resolves. Without this,
57     * the error would only update on Site Health page visits and Core's weekly
58     * Site Health cron, and would expire (ERROR_LIFE_TIME) while still unresolved.
59     *
60     * @since 8.10.0
61     */
62    public static function do_daily_connection_check() {
63        if ( ! ( new Manager() )->is_connected() ) {
64            return;
65        }
66
67        ( new Connection_Health_Tests() )->run_test( 'test__wpcom_connection_test' );
68    }
69
70    /**
71     * Conditionally register Site Health hooks.
72     *
73     * Checks whether the legacy Jetpack debugger has already registered its
74     * Site Health hooks. If so, we defer to avoid duplicate tests.
75     *
76     * @since 8.5.0
77     */
78    public static function maybe_register_site_health() {
79        // Defer to the old Jetpack plugin's debugger if it has already registered
80        // its Site Health filter. Old Jetpack versions add this filter during plugin
81        // loading, so by admin_init it is already present.
82        if ( has_filter( 'site_status_tests', 'jetpack_debugger_site_status_tests' ) ) {
83            return;
84        }
85
86        add_filter( 'site_status_tests', array( __CLASS__, 'register_site_health_tests' ) );
87        add_action( 'wp_ajax_health-check-jetpack-connection-health', array( __CLASS__, 'ajax_local_testing_suite' ) );
88    }
89
90    /**
91     * Register connection tests with WordPress Site Health.
92     *
93     * @since 8.5.0
94     *
95     * @param array $core_tests Array of tests from Core's Site Health.
96     *
97     * @return array Modified array of tests.
98     */
99    public static function register_site_health_tests( $core_tests ) {
100        $cxn_tests = new Connection_Health_Tests();
101        $tests     = $cxn_tests->list_tests( 'direct' );
102
103        foreach ( $tests as $test ) {
104            $core_tests['direct'][ $test['name'] ] = array(
105                'label' => __( 'Jetpack: ', 'jetpack-connection' ) . $test['name'],
106                'test'  => self::make_site_health_callback( $test, $cxn_tests ),
107            );
108        }
109
110        $core_tests['async']['jetpack_connection_test_suite'] = array(
111            'label' => __( 'Jetpack Connection Tests', 'jetpack-connection' ),
112            'test'  => 'jetpack-connection-health',
113        );
114
115        return $core_tests;
116    }
117
118    /**
119     * Create a closure for a Site Health direct test.
120     *
121     * @since 8.5.0
122     *
123     * @param array                   $test      Test definition array.
124     * @param Connection_Health_Tests $cxn_tests Test suite instance.
125     *
126     * @return callable The Site Health test callback.
127     */
128    private static function make_site_health_callback( $test, $cxn_tests ) {
129        return function () use ( $test, $cxn_tests ) {
130            $results = $cxn_tests->run_test( $test['name'] );
131            if ( is_wp_error( $results ) ) {
132                return;
133            }
134
135            $label = $results['label'] ?
136                $results['label'] :
137                ucwords(
138                    str_replace(
139                        '_',
140                        ' ',
141                        str_replace( 'test__', '', $test['name'] )
142                    )
143                );
144
145            if ( $results['long_description'] ) {
146                $description = $results['long_description'];
147            } elseif ( $results['short_description'] ) {
148                $description = sprintf(
149                    '<p>%s</p>',
150                    $results['short_description']
151                );
152            } else {
153                $description = sprintf(
154                    '<p>%s</p>',
155                    __( 'This test successfully passed!', 'jetpack-connection' )
156                );
157            }
158
159            $badge_label = $cxn_tests->get_site_health_badge_label();
160
161            $return = array(
162                'label'       => $label,
163                'status'      => 'good',
164                'badge'       => array(
165                    'label' => $badge_label,
166                    'color' => 'green',
167                ),
168                'description' => $description,
169                'actions'     => '',
170                'test'        => 'jetpack_' . $test['name'],
171            );
172
173            if ( false === $results['pass'] ) {
174                $return['status'] = $results['severity'];
175                if ( ! empty( $results['action'] ) ) {
176                    $return['actions'] = sprintf(
177                        '<a href="%1$s" target="_blank" rel="noopener noreferrer">%2$s <span class="screen-reader-text">%3$s</span><span aria-hidden="true" class="dashicons dashicons-external"></span></a>',
178                        esc_url( $results['action'] ),
179                        $results['action_label'],
180                        /* translators: accessibility text */
181                        __( '(opens in a new tab)', 'jetpack-connection' )
182                    );
183                }
184            }
185
186            return $return;
187        };
188    }
189
190    /**
191     * AJAX handler for async Site Health tests.
192     *
193     * @since 8.5.0
194     */
195    public static function ajax_local_testing_suite() {
196        check_ajax_referer( 'health-check-site-status' );
197        if ( ! current_user_can( 'manage_options' ) ) {
198            // @phan-suppress-next-line PhanTypeMismatchArgumentProbablyReal
199            wp_send_json_error( null, null, JSON_UNESCAPED_SLASHES );
200        }
201        $tests = new Connection_Health_Tests();
202        // @phan-suppress-next-line PhanTypeMismatchArgumentProbablyReal
203        wp_send_json_success( $tests->output_results_for_core_async_site_health(), null, JSON_UNESCAPED_SLASHES );
204    }
205}