Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
88.04% covered (warning)
88.04%
81 / 92
75.00% covered (warning)
75.00%
6 / 8
CRAP
0.00% covered (danger)
0.00%
0 / 1
Site_Health
88.04% covered (warning)
88.04%
81 / 92
75.00% covered (warning)
75.00%
6 / 8
20.68
0.00% covered (danger)
0.00%
0 / 1
 init
100.00% covered (success)
100.00%
6 / 6
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
 get_default_test_labels
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
1
 get_default_test_label
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
2
 make_site_health_callback
85.00% covered (warning)
85.00%
34 / 40
0.00% covered (danger)
0.00%
0 / 1
7.17
 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 the connection with WordPress Site Health.
12 *
13 * Registers the connection health tests on the Status tab, unless an old Jetpack plugin registers its own,
14 * and adds the Jetpack Connection section to the Info tab.
15 *
16 * @since 8.5.0
17 */
18class Site_Health {
19
20    /**
21     * Whether the class has been initialized.
22     *
23     * @var bool
24     */
25    private static $initialized = false;
26
27    /**
28     * Initialize Site Health integration.
29     *
30     * Should be called once, typically from the package's actions.php via a plugins_loaded hook.
31     *
32     * @since 8.5.0
33     */
34    public static function init() {
35        if ( self::$initialized ) {
36            return;
37        }
38        self::$initialized = true;
39
40        add_action( 'admin_init', array( __CLASS__, 'maybe_register_site_health' ), 1 );
41
42        add_filter( 'debug_information', array( Debug_Data::class, 'add_section' ) );
43
44        // Deliberately hooked to the cron-only `jetpack_heartbeat` action (end of
45        // Heartbeat::cron_exec()) and not `jetpack_heartbeat_stats_array`, which
46        // also fires in synchronous request contexts (XML-RPC, REST, WP-CLI) where
47        // a remote test would be slow and an amplification vector.
48        add_action( 'jetpack_heartbeat', array( __CLASS__, 'do_daily_connection_check' ) );
49    }
50
51    /**
52     * Runs the WP.com connection test once a day on the heartbeat cron.
53     *
54     * The test result itself is discarded: the point is the test's side effects,
55     * which keep the Error_Handler state for failures that WP.com cannot report
56     * through a request of its own (the site blocking WP.com requests; the site's
57     * SSL certificate failing verification) fresh — reported while the condition
58     * persists, cleared once it resolves. Without this, the errors would only
59     * update on Site Health page visits and Core's weekly Site Health cron, and
60     * would expire (ERROR_LIFE_TIME) while still unresolved.
61     *
62     * @since 8.10.0
63     */
64    public static function do_daily_connection_check() {
65        if ( ! ( new Manager() )->is_connected() ) {
66            return;
67        }
68
69        ( new Connection_Health_Tests() )->run_test( 'test__wpcom_connection_test' );
70    }
71
72    /**
73     * Conditionally register Site Health hooks.
74     *
75     * Checks whether the legacy Jetpack debugger has already registered its
76     * Site Health hooks. If so, we defer to avoid duplicate tests.
77     *
78     * @since 8.5.0
79     */
80    public static function maybe_register_site_health() {
81        // Defer to the old Jetpack plugin's debugger if it has already registered
82        // its Site Health filter. Old Jetpack versions add this filter during plugin
83        // loading, so by admin_init it is already present.
84        if ( has_filter( 'site_status_tests', 'jetpack_debugger_site_status_tests' ) ) {
85            return;
86        }
87
88        add_filter( 'site_status_tests', array( __CLASS__, 'register_site_health_tests' ) );
89        add_action( 'wp_ajax_health-check-jetpack-connection-health', array( __CLASS__, 'ajax_local_testing_suite' ) );
90    }
91
92    /**
93     * Register connection tests with WordPress Site Health.
94     *
95     * @since 8.5.0
96     *
97     * @param array $core_tests Array of tests from Core's Site Health.
98     *
99     * @return array Modified array of tests.
100     */
101    public static function register_site_health_tests( $core_tests ) {
102        $cxn_tests = new Connection_Health_Tests();
103        $tests     = $cxn_tests->list_tests( 'direct' );
104
105        foreach ( $tests as $test ) {
106            $core_tests['direct'][ $test['name'] ] = array(
107                'label' => __( 'Jetpack: ', 'jetpack-connection' ) . $test['name'],
108                'test'  => self::make_site_health_callback( $test, $cxn_tests ),
109            );
110        }
111
112        $core_tests['async']['jetpack_connection_test_suite'] = array(
113            'label' => __( 'Jetpack Connection Tests', 'jetpack-connection' ),
114            'test'  => 'jetpack-connection-health',
115        );
116
117        return $core_tests;
118    }
119
120    /**
121     * Human-readable headings for the built-in connection tests.
122     *
123     * Used when a test result carries no label of its own, so Site Health does not
124     * derive a title from the method name (e.g. "Wpcom Connection Test").
125     *
126     * A heading here has to read sensibly for a pass, a fail, and a skip alike, so
127     * these name what was tested rather than stating an outcome. Results that want
128     * to state an outcome set their own label, which takes precedence.
129     *
130     * @since 9.4.0
131     *
132     * @return array Map of test name => label.
133     */
134    private static function get_default_test_labels() {
135        return array(
136            'test__blog_token_if_exists'           => __( 'Site Token', 'jetpack-connection' ),
137            'test__check_if_connected'             => __( 'WordPress.com Connection', 'jetpack-connection' ),
138            'test__master_user_exists_on_site'     => __( 'Connection Owner', 'jetpack-connection' ),
139            'test__master_user_can_manage_options' => __( 'Connection Owner Permissions', 'jetpack-connection' ),
140            'test__identity_crisis'                => __( 'Site Address', 'jetpack-connection' ),
141            'test__connection_token_health'        => __( 'Connection Tokens', 'jetpack-connection' ),
142            'test__wpcom_connection_test'          => __( 'Requests from WordPress.com', 'jetpack-connection' ),
143            // Only registered when the jetpack_debugger_run_self_test filter returns true.
144            'test__wpcom_self_test'                => __( 'Site XML-RPC Endpoint', 'jetpack-connection' ),
145            'test__server_port_value'              => __( 'Server Port', 'jetpack-connection' ),
146            'test__xml_parser_available'           => __( 'PHP XML Support', 'jetpack-connection' ),
147        );
148    }
149
150    /**
151     * Get the heading for a test whose result carries no label of its own.
152     *
153     * Falls back to deriving a title from the method name, which is the last resort
154     * for tests other plugins register through the jetpack_connection_tests_loaded
155     * action and which therefore cannot appear in the map.
156     *
157     * @since 9.4.0
158     *
159     * @param string $test_name Test name, e.g. "test__blog_token_if_exists".
160     *
161     * @return string The heading to display.
162     */
163    private static function get_default_test_label( $test_name ) {
164        $labels = self::get_default_test_labels();
165
166        if ( isset( $labels[ $test_name ] ) ) {
167            return $labels[ $test_name ];
168        }
169
170        return ucwords(
171            str_replace(
172                '_',
173                ' ',
174                str_replace( 'test__', '', $test_name )
175            )
176        );
177    }
178
179    /**
180     * Create a closure for a Site Health direct test.
181     *
182     * @since 8.5.0
183     *
184     * @param array                   $test      Test definition array.
185     * @param Connection_Health_Tests $cxn_tests Test suite instance.
186     *
187     * @return callable The Site Health test callback.
188     */
189    private static function make_site_health_callback( $test, $cxn_tests ) {
190        $default_label = self::get_default_test_label( $test['name'] );
191
192        return function () use ( $test, $cxn_tests, $default_label ) {
193            $results = $cxn_tests->run_test( $test['name'] );
194            if ( is_wp_error( $results ) ) {
195                return;
196            }
197
198            $label = $results['label'] ? $results['label'] : $default_label;
199
200            if ( $results['long_description'] ) {
201                $description = $results['long_description'];
202            } elseif ( $results['short_description'] ) {
203                $description = sprintf(
204                    '<p>%s</p>',
205                    $results['short_description']
206                );
207            } else {
208                $description = sprintf(
209                    '<p>%s</p>',
210                    __( 'This test successfully passed!', 'jetpack-connection' )
211                );
212            }
213
214            $badge_label = $cxn_tests->get_site_health_badge_label();
215
216            $return = array(
217                'label'       => $label,
218                'status'      => 'good',
219                'badge'       => array(
220                    'label' => $badge_label,
221                    'color' => 'green',
222                ),
223                'description' => $description,
224                'actions'     => '',
225                'test'        => 'jetpack_' . $test['name'],
226            );
227
228            if ( false === $results['pass'] ) {
229                $return['status'] = $results['severity'];
230                if ( ! empty( $results['action'] ) ) {
231                    $return['actions'] = sprintf(
232                        '<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>',
233                        esc_url( $results['action'] ),
234                        $results['action_label'],
235                        /* translators: accessibility text */
236                        __( '(opens in a new tab)', 'jetpack-connection' )
237                    );
238                }
239            }
240
241            return $return;
242        };
243    }
244
245    /**
246     * AJAX handler for async Site Health tests.
247     *
248     * @since 8.5.0
249     */
250    public static function ajax_local_testing_suite() {
251        check_ajax_referer( 'health-check-site-status' );
252        if ( ! current_user_can( 'manage_options' ) ) {
253            // @phan-suppress-next-line PhanTypeMismatchArgumentProbablyReal
254            wp_send_json_error( null, null, JSON_UNESCAPED_SLASHES );
255        }
256        $tests = new Connection_Health_Tests();
257        // @phan-suppress-next-line PhanTypeMismatchArgumentProbablyReal
258        wp_send_json_success( $tests->output_results_for_core_async_site_health(), null, JSON_UNESCAPED_SLASHES );
259    }
260}