Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
69.66% covered (warning)
69.66%
287 / 412
52.17% covered (warning)
52.17%
12 / 23
CRAP
0.00% covered (danger)
0.00%
0 / 1
Connection_Health_Tests
69.66% covered (warning)
69.66%
287 / 412
52.17% covered (warning)
52.17%
12 / 23
433.75
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
4
 test__blog_token_if_exists
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
3
 test__check_if_connected
100.00% covered (success)
100.00%
30 / 30
100.00% covered (success)
100.00%
1 / 1
4
 test__master_user_exists_on_site
100.00% covered (success)
100.00%
22 / 22
100.00% covered (success)
100.00%
1 / 1
4
 test__master_user_can_manage_options
71.43% covered (warning)
71.43%
15 / 21
0.00% covered (danger)
0.00%
0 / 1
4.37
 test__outbound_http
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
3
 test__outbound_https
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
3
 test__identity_crisis
82.35% covered (warning)
82.35%
28 / 34
0.00% covered (danger)
0.00%
0 / 1
10.55
 check_identity_crisis
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
30
 test__connection_token_health
75.00% covered (warning)
75.00%
9 / 12
0.00% covered (danger)
0.00%
0 / 1
7.77
 check_blog_token_health
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
6
 check_tokens_health
0.00% covered (danger)
0.00%
0 / 17
0.00% covered (danger)
0.00%
0 / 1
42
 test__wpcom_connection_test
32.73% covered (danger)
32.73%
18 / 55
0.00% covered (danger)
0.00%
0 / 1
40.45
 evaluate_wpcom_connection_result
100.00% covered (success)
100.00%
27 / 27
100.00% covered (success)
100.00%
1 / 1
11
 report_connection_state_error
95.00% covered (success)
95.00%
19 / 20
0.00% covered (danger)
0.00%
0 / 1
2
 clear_blocked_request_error
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 clear_ssl_verification_error
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 blocked_request_failing_test
100.00% covered (success)
100.00%
16 / 16
100.00% covered (success)
100.00%
1 / 1
2
 ssl_verification_failing_test
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 connection_state_failing_test
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
1
 test__server_port_value
89.47% covered (warning)
89.47%
34 / 38
0.00% covered (danger)
0.00%
0 / 1
11.14
 test__xml_parser_available
25.00% covered (danger)
25.00%
3 / 12
0.00% covered (danger)
0.00%
0 / 1
3.69
 last__wpcom_self_test
0.00% covered (danger)
0.00%
0 / 32
0.00% covered (danger)
0.00%
0 / 1
90
1<?php
2/**
3 * Collection of health tests for the Jetpack Connection.
4 *
5 * @package automattic/jetpack-connection
6 */
7
8namespace Automattic\Jetpack\Connection;
9
10use Automattic\Jetpack\Constants;
11use Automattic\Jetpack\Identity_Crisis;
12use Automattic\Jetpack\Redirect;
13use Automattic\Jetpack\Status;
14use Jetpack_Options;
15
16/**
17 * Class Connection_Health_Tests contains all connection-specific health tests.
18 *
19 * @since 8.5.0
20 */
21class Connection_Health_Tests extends Connection_Health_Test_Base {
22
23    /**
24     * Connection_Health_Tests constructor.
25     */
26    public function __construct() {
27        parent::__construct();
28
29        $methods = get_class_methods( static::class );
30
31        foreach ( $methods as $method ) {
32            if ( ! str_contains( $method, 'test__' ) ) {
33                continue;
34            }
35            $this->add_test( array( $this, $method ), $method, 'direct' );
36        }
37
38        /**
39         * Fires after loading default connection health tests.
40         *
41         * Allows other packages or plugins to register additional tests.
42         *
43         * @since 7.1.0
44         * @since 8.3.0 Passes the test suite instance.
45         * @since 8.5.0 Moved from Jetpack_Cxn_Tests to Connection_Health_Tests.
46         *
47         * @param Connection_Health_Tests $this The Connection_Health_Tests instance.
48         */
49        do_action( 'jetpack_connection_tests_loaded', $this );
50
51        /**
52         * Determines if the WP.com testing suite should be included.
53         *
54         * @since 7.1.0
55         * @since 8.1.0 Default false.
56         *
57         * @param bool $run_test To run the WP.com testing suite. Default false.
58         */
59        if ( apply_filters( 'jetpack_debugger_run_self_test', false ) ) {
60            $this->add_test( array( $this, 'last__wpcom_self_test' ), 'test__wpcom_self_test', 'direct' );
61        }
62    }
63
64    /**
65     * The test verifies the blog token exists.
66     *
67     * @return array
68     */
69    protected function test__blog_token_if_exists() {
70        $name = 'test__blog_token_if_exists';
71
72        if ( ! $this->helper_is_connected() ) {
73            return self::skipped_test(
74                array(
75                    'name'              => $name,
76                    'short_description' => __( 'Your site is not connected to WordPress.com. No site token to check.', 'jetpack-connection' ),
77                )
78            );
79        }
80        $blog_token = $this->helper_get_blog_token();
81
82        if ( $blog_token ) {
83            return self::passing_test( array( 'name' => $name ) );
84        }
85
86        return self::connection_failing_test( $name, __( 'The site token used to authenticate with WordPress.com is missing.', 'jetpack-connection' ) );
87    }
88
89    /**
90     * Test if Jetpack is connected.
91     *
92     * @return array
93     */
94    protected function test__check_if_connected() {
95        $name = 'test__check_if_connected';
96
97        if ( ! $this->helper_get_blog_token() ) {
98            return self::skipped_test(
99                array(
100                    'name'              => $name,
101                    'short_description' => __( 'The site token used to authenticate with WordPress.com is missing.', 'jetpack-connection' ),
102                )
103            );
104        }
105
106        if ( $this->helper_is_connected() ) {
107            return self::passing_test(
108                array(
109                    'name'             => $name,
110                    'label'            => __( 'Your site is connected to WordPress.com', 'jetpack-connection' ),
111                    'long_description' => sprintf(
112                        '<p>%1$s</p>' .
113                        '<p><span class="dashicons pass"><span class="screen-reader-text">%2$s</span></span> %3$s</p>',
114                        self::helper_get_healthy_connection_text(),
115                        /* translators: Screen reader text indicating a test has passed */
116                        __( 'Passed', 'jetpack-connection' ),
117                        __( 'Your site is connected to WordPress.com.', 'jetpack-connection' )
118                    ),
119                )
120            );
121        } elseif ( ( new Status() )->is_offline_mode() ) {
122            return self::skipped_test(
123                array(
124                    'name'              => $name,
125                    'short_description' => __( 'Your site is in Offline Mode.', 'jetpack-connection' ),
126                )
127            );
128        }
129
130        return self::connection_failing_test( $name, __( 'Your site is not connected to WordPress.com', 'jetpack-connection' ) );
131    }
132
133    /**
134     * Test that the connection owner still exists on this site.
135     *
136     * @return array
137     */
138    protected function test__master_user_exists_on_site() {
139        $name = 'test__master_user_exists_on_site';
140
141        if ( ! $this->helper_is_connected() ) {
142            return self::skipped_test(
143                array(
144                    'name'              => $name,
145                    'short_description' => __( 'Your site is not connected to WordPress.com. No connection owner to check.', 'jetpack-connection' ),
146                )
147            );
148        }
149        if ( ! ( new Manager() )->get_connection_owner_id() ) {
150            return self::skipped_test(
151                array(
152                    'name'              => $name,
153                    'short_description' => __( 'The site is connected to WordPress.com without a user. No connection owner to check.', 'jetpack-connection' ),
154                )
155            );
156        }
157        $local_user = $this->helper_retrieve_connection_owner();
158
159        if ( $local_user->exists() ) {
160            return self::passing_test( array( 'name' => $name ) );
161        }
162
163        return self::connection_failing_test(
164            $name,
165            __( 'The user who set up the Jetpack Connection no longer exists on this site.', 'jetpack-connection' )
166        );
167    }
168
169    /**
170     * Test that the connection owner has the manage options capability (e.g. is an admin).
171     *
172     * @return array
173     */
174    protected function test__master_user_can_manage_options() {
175        $name = 'test__master_user_can_manage_options';
176
177        if ( ! $this->helper_is_connected() ) {
178            return self::skipped_test(
179                array(
180                    'name'              => $name,
181                    'short_description' => __( 'Your site is not connected to WordPress.com.', 'jetpack-connection' ),
182                )
183            );
184        }
185        if ( ! ( new Manager() )->get_connection_owner_id() ) {
186            return self::skipped_test(
187                array(
188                    'name'              => $name,
189                    'short_description' => __( 'The site is connected to WordPress.com without a user. No connection owner to check.', 'jetpack-connection' ),
190                )
191            );
192        }
193        $owner_user = $this->helper_retrieve_connection_owner();
194
195        if ( user_can( $owner_user, 'manage_options' ) ) {
196            return self::passing_test( array( 'name' => $name ) );
197        }
198
199        /* translators: a WordPress username */
200        $connection_error = sprintf( __( 'The user (%s) who set up the Jetpack Connection is not an administrator.', 'jetpack-connection' ), $owner_user->user_login );
201        /* translators: a WordPress username */
202        $recommendation = sprintf( __( 'We recommend either upgrading the user (%s) or reconnecting your site to WordPress.com.', 'jetpack-connection' ), $owner_user->user_login );
203
204        return self::connection_failing_test( $name, $connection_error, $recommendation );
205    }
206
207    /**
208     * Test that the server is able to send an outbound HTTP communication.
209     *
210     * @return array
211     */
212    protected function test__outbound_http() {
213        $name     = 'test__outbound_http';
214        $api_base = Constants::get_constant( 'JETPACK__API_BASE' );
215        if ( ! $api_base ) {
216            $api_base = Utils::DEFAULT_JETPACK__API_BASE;
217        }
218        $request = wp_remote_get( preg_replace( '/^https:/', 'http:', $api_base ) . 'test/1/' );
219        $code    = wp_remote_retrieve_response_code( $request );
220
221        if ( 200 === (int) $code ) {
222            return self::passing_test( array( 'name' => $name ) );
223        }
224
225        return self::failing_test(
226            array(
227                'name'              => $name,
228                'short_description' => $this->helper_enable_outbound_requests( 'HTTP' ),
229            )
230        );
231    }
232
233    /**
234     * Test that the server is able to send an outbound HTTPS communication.
235     *
236     * @return array
237     */
238    protected function test__outbound_https() {
239        $name     = 'test__outbound_https';
240        $api_base = Constants::get_constant( 'JETPACK__API_BASE' );
241        if ( ! $api_base ) {
242            $api_base = Utils::DEFAULT_JETPACK__API_BASE;
243        }
244        $request = wp_remote_get( preg_replace( '/^http:/', 'https:', $api_base ) . 'test/1/' );
245        $code    = wp_remote_retrieve_response_code( $request );
246
247        if ( 200 === (int) $code ) {
248            return self::passing_test( array( 'name' => $name ) );
249        }
250
251        return self::failing_test(
252            array(
253                'name'              => $name,
254                'short_description' => $this->helper_enable_outbound_requests( 'HTTPS' ),
255            )
256        );
257    }
258
259    /**
260     * Check for an Identity Crisis.
261     *
262     * @return array
263     */
264    protected function test__identity_crisis() {
265        $name = 'test__identity_crisis';
266
267        if ( ! $this->helper_is_connected() ) {
268            return self::skipped_test(
269                array(
270                    'name'              => $name,
271                    'short_description' => __( 'Your site is not connected to WordPress.com.', 'jetpack-connection' ),
272                )
273            );
274        }
275
276        $identity_crisis = $this->check_identity_crisis();
277
278        if ( ! $identity_crisis ) {
279            return self::passing_test( array( 'name' => $name ) );
280        }
281
282        $messages = array();
283
284        if ( isset( $identity_crisis['home'] ) && isset( $identity_crisis['wpcom_home'] ) && $identity_crisis['home'] !== $identity_crisis['wpcom_home'] ) {
285            $messages[] = sprintf(
286                /* translators: Two URLs. The first is the locally-recorded value, the second is the value as recorded on WP.com. */
287                __( 'Your home URL is set as `%1$s`, but your Jetpack Connection lists it as `%2$s`.', 'jetpack-connection' ),
288                $identity_crisis['home'],
289                $identity_crisis['wpcom_home']
290            );
291        }
292
293        if ( isset( $identity_crisis['siteurl'] ) && isset( $identity_crisis['wpcom_siteurl'] ) && $identity_crisis['siteurl'] !== $identity_crisis['wpcom_siteurl'] ) {
294            $messages[] = sprintf(
295                /* translators: Two URLs. The first is the locally-recorded value, the second is the value as recorded on WP.com. */
296                __( 'Your site URL is set as `%1$s`, but your Jetpack Connection lists it as `%2$s`.', 'jetpack-connection' ),
297                $identity_crisis['siteurl'],
298                $identity_crisis['wpcom_siteurl']
299            );
300        }
301
302        if ( empty( $messages ) ) {
303            $messages[] = __( 'A URL mismatch was detected between your site and WordPress.com.', 'jetpack-connection' );
304        }
305
306        return self::failing_test(
307            array(
308                'name'              => $name,
309                'short_description' => implode( ' ', $messages ),
310                'action_label'      => $this->helper_get_support_text(),
311                'action'            => $this->helper_get_support_url(),
312            )
313        );
314    }
315
316    /**
317     * Check for Identity Crisis using connection package classes.
318     *
319     * @return array|false False if no IDC, array with crisis details otherwise.
320     */
321    protected function check_identity_crisis() {
322        if ( ! ( new Manager() )->is_connected() || ( new Status() )->is_offline_mode() ) {
323            return false;
324        }
325
326        if ( ! class_exists( 'Automattic\Jetpack\Identity_Crisis' ) || ! Identity_Crisis::validate_sync_error_idc_option() ) {
327            return false;
328        }
329
330        return Jetpack_Options::get_option( 'sync_error_idc' );
331    }
332
333    /**
334     * Tests the health of the connection tokens.
335     *
336     * @return array
337     */
338    protected function test__connection_token_health() {
339        $name    = 'test__connection_token_health';
340        $m       = new Manager();
341        $user_id = get_current_user_id();
342
343        // Check if there's a connected logged in user.
344        if ( $user_id && ! $m->is_user_connected( $user_id ) ) {
345            $user_id = false;
346        }
347
348        // If no logged in user to check, let's see if there's a connection owner set.
349        if ( ! $user_id ) {
350            $user_id = Jetpack_Options::get_option( 'master_user' );
351            if ( $user_id && ! $m->is_user_connected( $user_id ) ) {
352                return self::connection_failing_test( $name, __( 'Missing token for the connection owner.', 'jetpack-connection' ) );
353            }
354        }
355
356        if ( $user_id ) {
357            return $this->check_tokens_health( $user_id );
358        }
359
360        return $this->check_blog_token_health();
361    }
362
363    /**
364     * Tests blog token against WP.com's check-token-health endpoint.
365     *
366     * @return array
367     */
368    protected function check_blog_token_health() {
369        $name  = 'test__connection_token_health';
370        $valid = ( new Tokens() )->validate_blog_token();
371
372        if ( ! $valid ) {
373            return self::connection_failing_test( $name, __( 'The site token used to authenticate with WordPress.com could not be validated.', 'jetpack-connection' ) );
374        }
375
376        return self::passing_test( array( 'name' => $name ) );
377    }
378
379    /**
380     * Tests blog and user tokens against WP.com's check-token-health endpoint.
381     *
382     * @param int $user_id The user ID to check the tokens for.
383     *
384     * @return array
385     */
386    protected function check_tokens_health( $user_id ) {
387        $name             = 'test__connection_token_health';
388        $validated_tokens = ( new Tokens() )->validate( $user_id );
389
390        if ( ! is_array( $validated_tokens ) || count( array_diff_key( array_flip( array( 'blog_token', 'user_token' ) ), $validated_tokens ) ) ) {
391            return self::skipped_test(
392                array(
393                    'name'              => $name,
394                    'short_description' => __( 'Token health check failed to validate tokens.', 'jetpack-connection' ),
395                )
396            );
397        }
398
399        $invalid_tokens_exist = false;
400        foreach ( $validated_tokens as $validated_token ) {
401            if ( ! $validated_token['is_healthy'] ) {
402                $invalid_tokens_exist = true;
403                break;
404            }
405        }
406
407        if ( ! $invalid_tokens_exist ) {
408            return self::passing_test( array( 'name' => $name ) );
409        }
410
411        return self::connection_failing_test( $name, __( 'Invalid Jetpack Connection tokens.', 'jetpack-connection' ) );
412    }
413
414    /**
415     * Tests connection status against WP.com's test-connection endpoint.
416     *
417     * @return array
418     */
419    protected function test__wpcom_connection_test() {
420        $name = 'test__wpcom_connection_test';
421
422        $status      = new Status();
423        $skip_reason = '';
424
425        if ( $status->is_offline_mode() ) {
426            $skip_reason = __( 'Your site is in Offline Mode, so this test was skipped.', 'jetpack-connection' );
427        } elseif ( $status->in_safe_mode() ) {
428            $skip_reason = __( 'Your site is in Safe Mode, so this test was skipped.', 'jetpack-connection' );
429        } elseif ( ! ( new Manager() )->is_connected() ) {
430            $skip_reason = __( 'Your site is not communicating with WordPress.com, so this test was skipped.', 'jetpack-connection' );
431        } elseif ( ! $this->pass ) {
432            $skip_reason = __( 'A previous connection health test failed, so this test was skipped.', 'jetpack-connection' );
433        }
434
435        if ( $skip_reason ) {
436            return self::skipped_test(
437                array(
438                    'name'              => $name,
439                    'short_description' => $skip_reason,
440                )
441            );
442        }
443
444        add_filter( 'http_request_timeout', array( static::class, 'increase_timeout' ) );
445        $response = Client::wpcom_json_api_request_as_blog(
446            sprintf( '/jetpack-blogs/%d/test-connection', Jetpack_Options::get_option( 'id' ) ),
447            Client::WPCOM_JSON_API_VERSION
448        );
449        remove_filter( 'http_request_timeout', array( static::class, 'increase_timeout' ) );
450
451        if ( is_wp_error( $response ) ) {
452            if ( str_contains( $response->get_error_message(), 'cURL error 28' ) ) {
453                return self::skipped_test(
454                    array(
455                        'name'              => $name,
456                        'short_description' => self::helper_get_timeout_text(),
457                    )
458                );
459            }
460
461            /* translators: %1$s is the error code, %2$s is the error message */
462            $message = sprintf( __( 'Connection test failed (#%1$s: %2$s)', 'jetpack-connection' ), $response->get_error_code(), $response->get_error_message() );
463            return self::connection_failing_test( $name, $message );
464        }
465
466        $body = wp_remote_retrieve_body( $response );
467        if ( ! $body ) {
468            return self::failing_test(
469                array(
470                    'name'              => $name,
471                    'short_description' => sprintf(
472                        /* translators: %s is the HTTP status code returned by WordPress.com. */
473                        __( 'Connection test failed: WordPress.com returned an empty response (status code: %s).', 'jetpack-connection' ),
474                        wp_remote_retrieve_response_code( $response )
475                    ),
476                    'action_label'      => $this->helper_get_support_text(),
477                    'action'            => $this->helper_get_support_url(),
478                )
479            );
480        }
481
482        if ( 404 === wp_remote_retrieve_response_code( $response ) ) {
483            return self::skipped_test(
484                array(
485                    'name'              => $name,
486                    'short_description' => __( 'The WordPress.com API returned a 404 error.', 'jetpack-connection' ),
487                )
488            );
489        }
490
491        return $this->evaluate_wpcom_connection_result( $name, json_decode( $body ), wp_remote_retrieve_response_code( $response ) );
492    }
493
494    /**
495     * Turns a decoded WP.com test-connection response into a test result.
496     *
497     * Split out from test__wpcom_connection_test() so the decision logic can be
498     * exercised without performing a signed remote request.
499     *
500     * Besides producing the Site Health result, this also keeps the Error_Handler
501     * state for `xmlrpc_request_blocked` and `wpcom_ssl_verification_failed` in sync: a
502     * result carrying one of those codes reports the matching error (making it
503     * visible on Error_Handler surfaces such as admin notices and the dashboard),
504     * and a connected result clears both. Runs from every entry point of the test:
505     * Site Health page loads, Core's weekly Site Health cron, and the daily
506     * connection check on the heartbeat cron.
507     *
508     * @param string      $name        The test name.
509     * @param object|null $result      The JSON-decoded response body; null when the body was not valid JSON.
510     * @param int|string  $status_code The HTTP status code of the WP.com response.
511     *
512     * @return array Test results.
513     */
514    public function evaluate_wpcom_connection_result( $name, $result, $status_code ) {
515        if ( ! empty( $result->connected ) ) {
516            $this->clear_blocked_request_error();
517            $this->clear_ssl_verification_error();
518            return self::passing_test( array( 'name' => $name ) );
519        }
520
521        // The site itself rejected WordPress.com's request (firewall, WAF, security
522        // plugin, or server rule). The connection token could be valid, but reconnecting would
523        // be rejected the same way - surface the real cause and don't offer a reconnect.
524        if ( isset( $result->error_code ) && 'xmlrpc_request_blocked' === $result->error_code ) {
525            $site_http_status = (int) ( $result->site_http_status ?? 0 );
526
527            $this->report_connection_state_error(
528                'xmlrpc_request_blocked',
529                'WordPress.com requests to the site are blocked',
530                array( 'site_http_status' => $site_http_status )
531            );
532
533            // A 4xx/5xx from the site means WP.com completed the TLS handshake to get
534            // it, so a lingering SSL-verification error is provably stale.
535            $this->clear_ssl_verification_error();
536
537            return $this->blocked_request_failing_test( $name, $site_http_status );
538        }
539
540        // WP.com could not verify the site's SSL certificate when connecting to it
541        // (expired, self-signed, or incomplete chain). The site itself never sees these
542        // failures â€” the TLS handshake dies before PHP runs â€” so WP.com's response to
543        // this signed request is the only evidence, and reconnecting would be rejected
544        // the same way. A stored blocked error is preserved: a failed handshake proves
545        // nothing about a blockage, and ERROR_LIFE_TIME bounds any staleness.
546        if ( isset( $result->error_code ) && 'wpcom_ssl_verification_failed' === $result->error_code ) {
547            $this->report_connection_state_error( 'wpcom_ssl_verification_failed', 'WordPress.com cannot verify the SSL certificate of the site' );
548
549            return $this->ssl_verification_failing_test( $name );
550        }
551
552        // An explicit `connected` property (falsy here, past the pass branch) proves
553        // WP.com actually ran its test and did not report a blockage or a certificate
554        // failure â€” a definitive other failure, so a lingering blocked or SSL error is
555        // stale and its suppressed-reconnect presentation would be wrong for this
556        // failure. The exception is a result WP.com marked `inconclusive` (a transport
557        // failure it could not classify, e.g. a timeout): that neither confirms nor
558        // disproves a stored error, so preserve it â€” clearing would flap the notice
559        // for a broken site that is also occasionally slow. Malformed bodies and
560        // service-error envelopes (no `connected` property) are likewise preserved.
561        // A wrongly preserved error is bounded by ERROR_LIFE_TIME anyway.
562        if ( is_object( $result ) && property_exists( $result, 'connected' ) && empty( $result->inconclusive ) ) {
563            $this->clear_blocked_request_error();
564            $this->clear_ssl_verification_error();
565        }
566
567        $message = isset( $result->message ) && '' !== $result->message
568            ? $result->message
569            : __( 'Connection test failed.', 'jetpack-connection' );
570
571        $message .= ' ' . sprintf(
572            /* translators: %s is the HTTP status code returned by WordPress.com. */
573            __( '(status code: %s)', 'jetpack-connection' ),
574            $status_code
575        );
576
577        return self::connection_failing_test( $name, $message );
578    }
579
580    /**
581     * Reports a verified `local_state` connection error derived from a WP.com
582     * test-connection result.
583     *
584     * Skipping the WP.com verification round-trip is safe here: the error was
585     * derived from a response WP.com sent to a request this site initiated and
586     * signed, so it is self-evidencing (same trust model as the outgoing flow).
587     * The method_exists guard and the 'local_state' literal (which matches
588     * Error_Handler::ERROR_TYPE_LOCAL_STATE) protect mid-plugin-update requests,
589     * where a stale Error_Handler predating the factory and the constant can
590     * already be loaded: reporting is best-effort and must never fatal.
591     *
592     * @since 9.3.0
593     *
594     * @param string $error_code    The error code, one of Error_Handler::$known_errors.
595     * @param string $error_message The stored error message (display copy is resolved by the Error_Handler).
596     * @param array  $extra_data    Additional error data, merged over the defaults.
597     */
598    private function report_connection_state_error( $error_code, $error_message, array $extra_data = array() ) {
599        if ( ! method_exists( Error_Handler::class, 'build_connection_wp_error' ) ) {
600            return;
601        }
602
603        Error_Handler::get_instance()->report_error(
604            Error_Handler::build_connection_wp_error(
605                $error_code,
606                $error_message,
607                array( 'token' => '' ),
608                'local_state', // Error_Handler::ERROR_TYPE_LOCAL_STATE.
609                '', // Connection-state errors describe the site's environment, not one request, so they have no direction.
610                array_merge(
611                    array(
612                        'user_id' => 0,
613                        // Reconnecting cannot fix a connection-state error, so it carries
614                        // its remedy: no reconnect CTA on any surface.
615                        'action'  => 'none',
616                    ),
617                    $extra_data
618                )
619            ),
620            false,
621            true
622        );
623    }
624
625    /**
626     * Clears a stored `xmlrpc_request_blocked` error, when the loaded Error_Handler supports it.
627     *
628     * During a plugin update, a stale Error_Handler predating `delete_error_by_code()` can
629     * already be in memory while this file is the new version on disk. State sync is
630     * best-effort and must never fatal such a request, so it is skipped in that window.
631     *
632     * @since 8.10.0
633     */
634    private function clear_blocked_request_error() {
635        if ( method_exists( Error_Handler::class, 'delete_error_by_code' ) ) {
636            Error_Handler::get_instance()->delete_error_by_code( 'xmlrpc_request_blocked' );
637        }
638    }
639
640    /**
641     * Clears a stored `wpcom_ssl_verification_failed` error, when the loaded Error_Handler supports it.
642     *
643     * As with clear_blocked_request_error(), state sync is best-effort and skipped when a
644     * stale Error_Handler predating the method is loaded mid-plugin-update.
645     *
646     * @since 9.3.0
647     */
648    private function clear_ssl_verification_error() {
649        if ( method_exists( Error_Handler::class, 'delete_error_by_code' ) ) {
650            Error_Handler::get_instance()->delete_error_by_code( 'wpcom_ssl_verification_failed' );
651        }
652    }
653
654    /**
655     * Builds a failing result for the case where the site is blocking WordPress.com's
656     * connection test (e.g. firewall/WAF/security plugin).
657     *
658     * No reconnect action is offered because the connection token could be valid but
659     * reconnecting would be rejected the same way.
660     *
661     * @param string $name             The test name.
662     * @param int    $site_http_status The HTTP status the site returned, or 0 if unknown.
663     *
664     * @return array Test results.
665     */
666    protected function blocked_request_failing_test( $name, $site_http_status = 0 ) {
667        // Only the first sentence varies with the status code. Keeping the explanation
668        // in its own string means it is written, translated, and edited once.
669        $blocked = $site_http_status
670            ? sprintf(
671                /* translators: %d is the HTTP status code (e.g. 403) the site returned. */
672                __( 'WordPress.com reached your site but the request was blocked (HTTP %d).', 'jetpack-connection' ),
673                $site_http_status
674            )
675            : __( 'WordPress.com reached your site but the request was blocked.', 'jetpack-connection' );
676
677        $connection_error = $blocked . ' ' . __( 'This is usually caused by a security plugin, firewall, or server rule rejecting requests from WordPress.com.', 'jetpack-connection' );
678
679        $recommendation = sprintf(
680            /* translators: %1$s opens a link to Jetpack's IP allowlist documentation, %2$s closes it (it also carries hidden text noting the link opens in a new tab). Place them around the phrase that should be linked. */
681            __( 'Jetpack Connection uses your site\'s xmlrpc.php file to securely communicate with WordPress.com. Ask your host or security provider to %1$sallowlist Jetpack Connection IPs%2$s â€” reconnecting will not resolve this. If you need further help, contact Jetpack support.', 'jetpack-connection' ),
682            '<a href="' . esc_url( Redirect::get_url( 'https://jetpack.com/support/how-to-add-jetpack-ips-allowlist/' ) ) . '" target="_blank" rel="noopener noreferrer">',
683            sprintf(
684                /* translators: accessibility text */
685                '<span class="screen-reader-text"> %s</span></a>',
686                esc_html__( '(opens in a new tab)', 'jetpack-connection' )
687            )
688        );
689
690        return $this->connection_state_failing_test( $name, $connection_error, $recommendation );
691    }
692
693    /**
694     * Builds a failing result for the case where WordPress.com could not verify the
695     * site's SSL certificate when connecting to it.
696     *
697     * No reconnect action is offered because a reconnect would fail certificate
698     * verification the same way.
699     *
700     * @since 9.3.0
701     *
702     * @param string $name The test name.
703     *
704     * @return array Test results.
705     */
706    protected function ssl_verification_failing_test( $name ) {
707        $connection_error = __( 'WordPress.com could not establish a secure connection to your site because your site\'s SSL certificate could not be verified. This is usually caused by an expired or self-signed certificate, or a missing intermediate certificate.', 'jetpack-connection' );
708
709        $recommendation = __( 'Ask your hosting provider to renew your site\'s SSL certificate or complete its certificate chain. Reconnecting will not resolve this. If you need further help, contact Jetpack support.', 'jetpack-connection' );
710
711        return $this->connection_state_failing_test( $name, $connection_error, $recommendation );
712    }
713
714    /**
715     * Builds a failing result for a connection-state failure that reconnecting cannot fix.
716     *
717     * No reconnect action is offered; contacting support is the only CTA.
718     *
719     * @since 9.3.0
720     *
721     * @param string $name             The test name.
722     * @param string $connection_error The connection-specific error copy.
723     * @param string $recommendation   The recommendation for resolving it.
724     *
725     * @return array Test results.
726     */
727    protected function connection_state_failing_test( $name, $connection_error, $recommendation ) {
728        return self::failing_test(
729            array(
730                'name'              => $name,
731                'label'             => __( 'Your site is blocking requests from WordPress.com', 'jetpack-connection' ),
732                'short_description' => $connection_error,
733                'long_description'  => self::helper_get_reconnect_long_description( $connection_error, $recommendation ),
734                'action_label'      => $this->helper_get_support_text(),
735                'action'            => $this->helper_get_support_url(),
736            )
737        );
738    }
739
740    /**
741     * Tests the port number to ensure it is an expected value.
742     *
743     * @return array
744     */
745    protected function test__server_port_value() {
746        $name = 'test__server_port_value';
747
748        if ( ! isset( $_SERVER['HTTP_X_FORWARDED_PORT'] ) && ! isset( $_SERVER['SERVER_PORT'] ) ) {
749            return self::skipped_test(
750                array(
751                    'name'              => $name,
752                    'short_description' => __( 'The server port values are not defined. This is most common when running PHP via a CLI.', 'jetpack-connection' ),
753                )
754            );
755        }
756        $site_port   = wp_parse_url( home_url(), PHP_URL_PORT );
757        $server_port = isset( $_SERVER['HTTP_X_FORWARDED_PORT'] ) ? (int) $_SERVER['HTTP_X_FORWARDED_PORT'] : (int) $_SERVER['SERVER_PORT'];
758        $http_ports  = array( 80 );
759        $https_ports = array( 80, 443 );
760
761        if ( defined( 'JETPACK_SIGNATURE__HTTP_PORT' ) ) {
762            $http_ports[] = JETPACK_SIGNATURE__HTTP_PORT;
763        }
764
765        if ( defined( 'JETPACK_SIGNATURE__HTTPS_PORT' ) ) {
766            $https_ports[] = JETPACK_SIGNATURE__HTTPS_PORT;
767        }
768
769        if ( $site_port ) {
770            return self::skipped_test( array( 'name' => $name ) );
771        }
772
773        if ( is_ssl() && in_array( $server_port, $https_ports, true ) ) {
774            return self::passing_test( array( 'name' => $name ) );
775        } elseif ( in_array( $server_port, $http_ports, true ) ) {
776            return self::passing_test( array( 'name' => $name ) );
777        }
778
779        if ( is_ssl() ) {
780            $needed_constant = 'JETPACK_SIGNATURE__HTTPS_PORT';
781        } else {
782            $needed_constant = 'JETPACK_SIGNATURE__HTTP_PORT';
783        }
784        return self::failing_test(
785            array(
786                'name'              => $name,
787                'short_description' => sprintf(
788                    /* translators: %1$s - a PHP code snippet */
789                    __(
790                        'The server port value is unexpected.
791                    Try adding the following to your wp-config.php file: %1$s',
792                        'jetpack-connection'
793                    ),
794                    "define( '$needed_constant', $server_port )"
795                ),
796            )
797        );
798    }
799
800    /**
801     * Test that PHP's XML library is installed.
802     *
803     * @return array Test results.
804     */
805    protected function test__xml_parser_available() {
806        $name = 'test__xml_parser_available';
807        if ( function_exists( 'xml_parser_create' ) ) {
808            return self::passing_test( array( 'name' => $name ) );
809        }
810
811        return self::failing_test(
812            array(
813                'name'              => $name,
814                'label'             => __( 'PHP XML manipulation libraries are not available.', 'jetpack-connection' ),
815                'short_description' => __( 'Please ask your hosting provider to refer to our server requirements and enable PHP\'s XML module.', 'jetpack-connection' ),
816                'action_label'      => __( 'View our server requirements', 'jetpack-connection' ),
817                'action'            => Redirect::get_url( 'jetpack-support-server-requirements' ),
818            )
819        );
820    }
821
822    /**
823     * Calls to WP.com to run the connection diagnostic testing suite.
824     *
825     * Intentionally added last as it will be skipped if any local failed conditions exist.
826     *
827     * @since 7.1.0
828     *
829     * @return array Test results.
830     */
831    protected function last__wpcom_self_test() {
832        $name = 'test__wpcom_self_test';
833
834        $status = new Status();
835        if ( ! ( new Manager() )->is_connected() || $status->is_offline_mode() || $status->in_safe_mode() || ! $this->pass ) {
836            return self::skipped_test( array( 'name' => $name ) );
837        }
838
839        $self_xml_rpc_url = site_url( 'xmlrpc.php' );
840
841        $api_base = Constants::get_constant( 'JETPACK__API_BASE' );
842        if ( ! $api_base ) {
843            $api_base = Utils::DEFAULT_JETPACK__API_BASE;
844        }
845        $testsite_url = $api_base . 'testsite/1/?url=';
846
847        add_filter( 'http_request_timeout', array( static::class, 'increase_timeout' ), PHP_INT_MAX - 1 );
848
849        $response = wp_remote_get( $testsite_url . $self_xml_rpc_url );
850
851        remove_filter( 'http_request_timeout', array( static::class, 'increase_timeout' ), PHP_INT_MAX - 1 );
852
853        if ( 200 === wp_remote_retrieve_response_code( $response ) ) {
854            return self::passing_test( array( 'name' => $name ) );
855        } elseif ( is_wp_error( $response ) && str_contains( $response->get_error_message(), 'cURL error 28' ) ) {
856            return self::skipped_test(
857                array(
858                    'name'              => $name,
859                    'short_description' => self::helper_get_timeout_text(),
860                )
861            );
862        }
863
864        return self::failing_test(
865            array(
866                'name'              => $name,
867                'short_description' => sprintf(
868                    /* translators: %1$s - A debugging url */
869                    __( 'Jetpack.com detected an error on the WP.com Self Test. Visit the Jetpack Debug page for more info: %1$s, or contact support.', 'jetpack-connection' ),
870                    Redirect::get_url( 'jetpack-support-debug', array( 'query' => 'url=' . rawurlencode( site_url() ) ) )
871                ),
872                'action_label'      => $this->helper_get_support_text(),
873                'action'            => $this->helper_get_support_url(),
874            )
875        );
876    }
877}