Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
66.94% covered (warning)
66.94%
245 / 366
47.37% covered (danger)
47.37%
9 / 19
CRAP
0.00% covered (danger)
0.00%
0 / 1
Connection_Health_Tests
66.94% covered (warning)
66.94%
245 / 366
47.37% covered (danger)
47.37%
9 / 19
453.15
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
10.53% covered (danger)
10.53%
4 / 38
0.00% covered (danger)
0.00%
0 / 1
67.02
 evaluate_wpcom_connection_result
100.00% covered (success)
100.00%
33 / 33
100.00% covered (success)
100.00%
1 / 1
9
 clear_blocked_request_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
 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                        __( 'A healthy Jetpack Connection allows connected plugins (such as Jetpack and WooCommerce) to provide features like Stats, Site Security, and Payments.', 'jetpack-connection' ),
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        if ( ! ( new Manager() )->is_connected() || $status->is_offline_mode() || $status->in_safe_mode() || ! $this->pass ) {
424            return self::skipped_test( array( 'name' => $name ) );
425        }
426
427        add_filter( 'http_request_timeout', array( static::class, 'increase_timeout' ) );
428        $response = Client::wpcom_json_api_request_as_blog(
429            sprintf( '/jetpack-blogs/%d/test-connection', Jetpack_Options::get_option( 'id' ) ),
430            Client::WPCOM_JSON_API_VERSION
431        );
432        remove_filter( 'http_request_timeout', array( static::class, 'increase_timeout' ) );
433
434        if ( is_wp_error( $response ) ) {
435            if ( str_contains( $response->get_error_message(), 'cURL error 28' ) ) {
436                return self::skipped_test(
437                    array(
438                        'name'              => $name,
439                        'short_description' => self::helper_get_timeout_text(),
440                    )
441                );
442            }
443
444            /* translators: %1$s is the error code, %2$s is the error message */
445            $message = sprintf( __( 'Connection test failed (#%1$s: %2$s)', 'jetpack-connection' ), $response->get_error_code(), $response->get_error_message() );
446            return self::connection_failing_test( $name, $message );
447        }
448
449        $body = wp_remote_retrieve_body( $response );
450        if ( ! $body ) {
451            return self::failing_test(
452                array(
453                    'name'              => $name,
454                    'short_description' => __( 'Connection test failed (empty response body)', 'jetpack-connection' ) . wp_remote_retrieve_response_code( $response ),
455                    'action_label'      => $this->helper_get_support_text(),
456                    'action'            => $this->helper_get_support_url(),
457                )
458            );
459        }
460
461        if ( 404 === wp_remote_retrieve_response_code( $response ) ) {
462            return self::skipped_test(
463                array(
464                    'name'              => $name,
465                    'short_description' => __( 'The WordPress.com API returned a 404 error.', 'jetpack-connection' ),
466                )
467            );
468        }
469
470        return $this->evaluate_wpcom_connection_result( $name, json_decode( $body ), wp_remote_retrieve_response_code( $response ) );
471    }
472
473    /**
474     * Turns a decoded WP.com test-connection response into a test result.
475     *
476     * Split out from test__wpcom_connection_test() so the decision logic can be
477     * exercised without performing a signed remote request.
478     *
479     * Besides producing the Site Health result, this also keeps the Error_Handler
480     * state for `xmlrpc_request_blocked` in sync: a blocked result reports the
481     * error (making it visible on Error_Handler surfaces such as admin notices and
482     * the dashboard), and a connected result clears it. Runs from every entry point
483     * of the test: Site Health page loads, Core's weekly Site Health cron, and the
484     * daily connection check on the heartbeat cron.
485     *
486     * @param string      $name        The test name.
487     * @param object|null $result      The JSON-decoded response body; null when the body was not valid JSON.
488     * @param int|string  $status_code The HTTP status code of the WP.com response.
489     *
490     * @return array Test results.
491     */
492    public function evaluate_wpcom_connection_result( $name, $result, $status_code ) {
493        if ( ! empty( $result->connected ) ) {
494            $this->clear_blocked_request_error();
495            return self::passing_test( array( 'name' => $name ) );
496        }
497
498        // The site itself rejected WordPress.com's request (firewall, WAF, security
499        // plugin, or server rule). The connection token could be valid, but reconnecting would
500        // be rejected the same way - surface the real cause and don't offer a reconnect.
501        if ( isset( $result->error_code ) && 'xmlrpc_request_blocked' === $result->error_code ) {
502            $site_http_status = (int) ( $result->site_http_status ?? 0 );
503
504            // Skipping the WP.com verification round-trip is safe here: the error was
505            // derived from a response WP.com sent to a request this site initiated and
506            // signed, so it is self-evidencing (same trust model as the outgoing flow).
507            // The method_exists guard and the 'local_state' literal (which matches
508            // Error_Handler::ERROR_TYPE_LOCAL_STATE) protect mid-plugin-update requests,
509            // where a stale Error_Handler predating the factory and the constant can
510            // already be loaded: reporting is best-effort and must never fatal.
511            if ( method_exists( Error_Handler::class, 'build_connection_wp_error' ) ) {
512                Error_Handler::get_instance()->report_error(
513                    Error_Handler::build_connection_wp_error(
514                        'xmlrpc_request_blocked',
515                        'WordPress.com requests to the site are blocked',
516                        array( 'token' => '' ),
517                        'local_state', // Error_Handler::ERROR_TYPE_LOCAL_STATE.
518                        '', // The blocked state describes the site's environment, not one request, so it has no direction.
519                        array(
520                            'user_id'          => 0,
521                            'site_http_status' => $site_http_status,
522                            // Reconnecting would be rejected by the same rule that blocks WP.com,
523                            // so the error carries its remedy: no reconnect CTA on any surface.
524                            'action'           => 'none',
525                        )
526                    ),
527                    false,
528                    true
529                );
530            }
531
532            return $this->blocked_request_failing_test( $name, $site_http_status );
533        }
534
535        // An explicit `connected` property (falsy here, past the pass branch) proves
536        // WP.com actually ran its test and did not report a blockage â€” a definitive
537        // non-blocked failure, so a lingering blocked error is stale and its
538        // suppressed-reconnect presentation would be wrong for this failure.
539        // Malformed bodies and service-error envelopes (no `connected` property) are
540        // inconclusive: preserve any existing blocked error, as with timeouts and
541        // 404s. A wrongly preserved error is bounded by ERROR_LIFE_TIME anyway.
542        if ( is_object( $result ) && property_exists( $result, 'connected' ) ) {
543            $this->clear_blocked_request_error();
544        }
545
546        $message = isset( $result->message ) && '' !== $result->message
547            ? $result->message
548            : __( 'Connection test failed.', 'jetpack-connection' );
549
550        $message .= ' ' . sprintf(
551            /* translators: %s is the HTTP status code returned by WordPress.com. */
552            __( '(status code: %s)', 'jetpack-connection' ),
553            $status_code
554        );
555
556        return self::connection_failing_test( $name, $message );
557    }
558
559    /**
560     * Clears a stored `xmlrpc_request_blocked` error, when the loaded Error_Handler supports it.
561     *
562     * During a plugin update, a stale Error_Handler predating `delete_error_by_code()` can
563     * already be in memory while this file is the new version on disk. State sync is
564     * best-effort and must never fatal such a request, so it is skipped in that window.
565     *
566     * @since 8.10.0
567     */
568    private function clear_blocked_request_error() {
569        if ( method_exists( Error_Handler::class, 'delete_error_by_code' ) ) {
570            Error_Handler::get_instance()->delete_error_by_code( 'xmlrpc_request_blocked' );
571        }
572    }
573
574    /**
575     * Builds a failing result for the case where the site is blocking WordPress.com's
576     * connection test (e.g. firewall/WAF/security plugin).
577     *
578     * No reconnect action is offered because the connection token could be valid but
579     * reconnecting would be rejected the same way.
580     *
581     * @param string $name             The test name.
582     * @param int    $site_http_status The HTTP status the site returned, or 0 if unknown.
583     *
584     * @return array Test results.
585     */
586    protected function blocked_request_failing_test( $name, $site_http_status = 0 ) {
587        $connection_error = $site_http_status
588            ? sprintf(
589                /* translators: %d is the HTTP status code (e.g. 403) the site returned. */
590                __( 'WordPress.com reached your site but the request was blocked (HTTP %d). This is usually caused by a firewall, security plugin, or server rule rejecting requests from WordPress.com.', 'jetpack-connection' ),
591                $site_http_status
592            )
593            : __( 'WordPress.com reached your site but the request was blocked. This is usually caused by a firewall, security plugin, or server rule rejecting requests from WordPress.com.', 'jetpack-connection' );
594
595        $recommendation = __( 'Ask your host or security provider to allow requests from WordPress.com to your site\'s xmlrpc.php file. Reconnecting will not resolve this. If you need further help, contact Jetpack support.', 'jetpack-connection' );
596
597        return self::failing_test(
598            array(
599                'name'              => $name,
600                'short_description' => $connection_error,
601                'long_description'  => self::helper_get_reconnect_long_description( $connection_error, $recommendation ),
602                'action_label'      => $this->helper_get_support_text(),
603                'action'            => $this->helper_get_support_url(),
604            )
605        );
606    }
607
608    /**
609     * Tests the port number to ensure it is an expected value.
610     *
611     * @return array
612     */
613    protected function test__server_port_value() {
614        $name = 'test__server_port_value';
615
616        if ( ! isset( $_SERVER['HTTP_X_FORWARDED_PORT'] ) && ! isset( $_SERVER['SERVER_PORT'] ) ) {
617            return self::skipped_test(
618                array(
619                    'name'              => $name,
620                    'short_description' => __( 'The server port values are not defined. This is most common when running PHP via a CLI.', 'jetpack-connection' ),
621                )
622            );
623        }
624        $site_port   = wp_parse_url( home_url(), PHP_URL_PORT );
625        $server_port = isset( $_SERVER['HTTP_X_FORWARDED_PORT'] ) ? (int) $_SERVER['HTTP_X_FORWARDED_PORT'] : (int) $_SERVER['SERVER_PORT'];
626        $http_ports  = array( 80 );
627        $https_ports = array( 80, 443 );
628
629        if ( defined( 'JETPACK_SIGNATURE__HTTP_PORT' ) ) {
630            $http_ports[] = JETPACK_SIGNATURE__HTTP_PORT;
631        }
632
633        if ( defined( 'JETPACK_SIGNATURE__HTTPS_PORT' ) ) {
634            $https_ports[] = JETPACK_SIGNATURE__HTTPS_PORT;
635        }
636
637        if ( $site_port ) {
638            return self::skipped_test( array( 'name' => $name ) );
639        }
640
641        if ( is_ssl() && in_array( $server_port, $https_ports, true ) ) {
642            return self::passing_test( array( 'name' => $name ) );
643        } elseif ( in_array( $server_port, $http_ports, true ) ) {
644            return self::passing_test( array( 'name' => $name ) );
645        }
646
647        if ( is_ssl() ) {
648            $needed_constant = 'JETPACK_SIGNATURE__HTTPS_PORT';
649        } else {
650            $needed_constant = 'JETPACK_SIGNATURE__HTTP_PORT';
651        }
652        return self::failing_test(
653            array(
654                'name'              => $name,
655                'short_description' => sprintf(
656                    /* translators: %1$s - a PHP code snippet */
657                    __(
658                        'The server port value is unexpected.
659                    Try adding the following to your wp-config.php file: %1$s',
660                        'jetpack-connection'
661                    ),
662                    "define( '$needed_constant', $server_port )"
663                ),
664            )
665        );
666    }
667
668    /**
669     * Test that PHP's XML library is installed.
670     *
671     * @return array Test results.
672     */
673    protected function test__xml_parser_available() {
674        $name = 'test__xml_parser_available';
675        if ( function_exists( 'xml_parser_create' ) ) {
676            return self::passing_test( array( 'name' => $name ) );
677        }
678
679        return self::failing_test(
680            array(
681                'name'              => $name,
682                'label'             => __( 'PHP XML manipulation libraries are not available.', 'jetpack-connection' ),
683                'short_description' => __( 'Please ask your hosting provider to refer to our server requirements and enable PHP\'s XML module.', 'jetpack-connection' ),
684                'action_label'      => __( 'View our server requirements', 'jetpack-connection' ),
685                'action'            => Redirect::get_url( 'jetpack-support-server-requirements' ),
686            )
687        );
688    }
689
690    /**
691     * Calls to WP.com to run the connection diagnostic testing suite.
692     *
693     * Intentionally added last as it will be skipped if any local failed conditions exist.
694     *
695     * @since 7.1.0
696     *
697     * @return array Test results.
698     */
699    protected function last__wpcom_self_test() {
700        $name = 'test__wpcom_self_test';
701
702        $status = new Status();
703        if ( ! ( new Manager() )->is_connected() || $status->is_offline_mode() || $status->in_safe_mode() || ! $this->pass ) {
704            return self::skipped_test( array( 'name' => $name ) );
705        }
706
707        $self_xml_rpc_url = site_url( 'xmlrpc.php' );
708
709        $api_base = Constants::get_constant( 'JETPACK__API_BASE' );
710        if ( ! $api_base ) {
711            $api_base = Utils::DEFAULT_JETPACK__API_BASE;
712        }
713        $testsite_url = $api_base . 'testsite/1/?url=';
714
715        add_filter( 'http_request_timeout', array( static::class, 'increase_timeout' ), PHP_INT_MAX - 1 );
716
717        $response = wp_remote_get( $testsite_url . $self_xml_rpc_url );
718
719        remove_filter( 'http_request_timeout', array( static::class, 'increase_timeout' ), PHP_INT_MAX - 1 );
720
721        if ( 200 === wp_remote_retrieve_response_code( $response ) ) {
722            return self::passing_test( array( 'name' => $name ) );
723        } elseif ( is_wp_error( $response ) && str_contains( $response->get_error_message(), 'cURL error 28' ) ) {
724            return self::skipped_test(
725                array(
726                    'name'              => $name,
727                    'short_description' => self::helper_get_timeout_text(),
728                )
729            );
730        }
731
732        return self::failing_test(
733            array(
734                'name'              => $name,
735                'short_description' => sprintf(
736                    /* translators: %1$s - A debugging url */
737                    __( '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' ),
738                    Redirect::get_url( 'jetpack-support-debug', array( 'query' => 'url=' . rawurlencode( site_url() ) ) )
739                ),
740                'action_label'      => $this->helper_get_support_text(),
741                'action'            => $this->helper_get_support_url(),
742            )
743        );
744    }
745}