Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 389
0.00% covered (danger)
0.00%
0 / 28
CRAP
0.00% covered (danger)
0.00%
0 / 1
Jetpack_Cxn_Tests
0.00% covered (danger)
0.00%
0 / 387
0.00% covered (danger)
0.00%
0 / 28
9900
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
20
 helper_retrieve_local_master_user
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 helper_is_jetpack_connected
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
6
 helper_get_blog_token
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 helper_get_support_url
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 helper_get_reconnect_url
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 helper_get_support_text
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 helper_get_reconnect_text
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 helper_get_timeout_text
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 helper_get_reconnect_long_description
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
2
 connection_failing_test
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
12
 helper_enable_outbound_requests
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
2
 increase_timeout
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 test__blog_token_if_exists
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
12
 test__check_if_connected
0.00% covered (danger)
0.00%
0 / 32
0.00% covered (danger)
0.00%
0 / 1
20
 test__master_user_exists_on_site
0.00% covered (danger)
0.00%
0 / 21
0.00% covered (danger)
0.00%
0 / 1
20
 test__master_user_can_manage_options
0.00% covered (danger)
0.00%
0 / 22
0.00% covered (danger)
0.00%
0 / 1
20
 test__xml_parser_available
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
6
 test__outbound_http
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
6
 test__outbound_https
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
6
 test__identity_crisis
0.00% covered (danger)
0.00%
0 / 35
0.00% covered (danger)
0.00%
0 / 1
110
 test__connection_token_health
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
56
 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 / 18
0.00% covered (danger)
0.00%
0 / 1
42
 test__wpcom_connection_test
0.00% covered (danger)
0.00%
0 / 45
0.00% covered (danger)
0.00%
0 / 1
110
 test__server_port_value
0.00% covered (danger)
0.00%
0 / 38
0.00% covered (danger)
0.00%
0 / 1
132
 test__sync_health
0.00% covered (danger)
0.00%
0 / 31
0.00% covered (danger)
0.00%
0 / 1
20
 last__wpcom_self_test
0.00% covered (danger)
0.00%
0 / 30
0.00% covered (danger)
0.00%
0 / 1
72
1<?php
2/**
3 * Collection of tests to run on the Jetpack connection locally.
4 *
5 * @package automattic/jetpack
6 */
7
8use Automattic\Jetpack\Connection\Client;
9use Automattic\Jetpack\Connection\Manager as Connection_Manager;
10use Automattic\Jetpack\Connection\Tokens;
11use Automattic\Jetpack\Redirect;
12use Automattic\Jetpack\Status;
13use Automattic\Jetpack\Sync\Health as Sync_Health;
14use Automattic\Jetpack\Sync\Settings as Sync_Settings;
15
16if ( ! defined( 'ABSPATH' ) ) {
17    exit( 0 );
18}
19
20/**
21 * Class Jetpack_Cxn_Tests contains all of the actual tests.
22 */
23class Jetpack_Cxn_Tests extends Jetpack_Cxn_Test_Base {
24
25    /**
26     * Jetpack_Cxn_Tests constructor.
27     */
28    public function __construct() {
29        parent::__construct();
30
31        $methods = get_class_methods( 'Jetpack_Cxn_Tests' );
32
33        foreach ( $methods as $method ) {
34            if ( ! str_contains( $method, 'test__' ) ) {
35                continue;
36            }
37            $this->add_test( array( $this, $method ), $method, 'direct' );
38        }
39
40        /**
41         * Fires after loading default Jetpack Connection tests.
42         *
43         * @since 7.1.0
44         * @since 8.3.0 Passes the Jetpack_Cxn_Tests instance.
45         */
46        do_action( 'jetpack_connection_tests_loaded', $this );
47
48        /**
49         * Determines if the WP.com testing suite should be included.
50         *
51         * @since 7.1.0
52         * @since 8.1.0 Default false.
53         *
54         * @param bool $run_test To run the WP.com testing suite. Default false.
55         */
56        if ( apply_filters( 'jetpack_debugger_run_self_test', false ) ) {
57            /**
58             * Intentionally added last as it checks for an existing failure state before attempting.
59             * Generally, any failed location condition would result in the WP.com check to fail too, so
60             * we will skip it to avoid confusing error messages.
61             *
62             * Note: This really should be an 'async' test.
63             */
64            $this->add_test( array( $this, 'last__wpcom_self_test' ), 'test__wpcom_self_test', 'direct' );
65        }
66    }
67
68    /**
69     * Helper function to look up the expected master user and return the local WP_User.
70     *
71     * @return WP_User Jetpack's expected master user.
72     */
73    protected function helper_retrieve_local_master_user() {
74        $master_user = Jetpack_Options::get_option( 'master_user' );
75        return new WP_User( $master_user );
76    }
77
78    /**
79     * Is Jetpack even connected and supposed to be talking to WP.com?
80     */
81    protected function helper_is_jetpack_connected() {
82        return Jetpack::is_connection_ready() && ! ( new Status() )->is_offline_mode();
83    }
84
85    /**
86     * Retrieve the `blog_token` if it exists.
87     *
88     * @return object|false
89     */
90    protected function helper_get_blog_token() {
91        return ( new Tokens() )->get_access_token();
92    }
93
94    /**
95     * Returns a support url based on using a development version.
96     */
97    protected function helper_get_support_url() {
98        return Jetpack::is_development_version()
99            ? Redirect::get_url( 'jetpack-contact-support-beta-group' )
100            : Redirect::get_url( 'jetpack-contact-support' );
101    }
102
103    /**
104     * Returns the url to reconnect Jetpack.
105     *
106     * @return string The reconnect url.
107     */
108    protected static function helper_get_reconnect_url() {
109        return admin_url( 'admin.php?page=jetpack#/reconnect' );
110    }
111
112    /**
113     * Gets translated support text.
114     */
115    protected function helper_get_support_text() {
116        return __( 'Please contact Jetpack support.', 'jetpack' );
117    }
118
119    /**
120     * Returns the translated text to reconnect Jetpack.
121     *
122     * @return string The translated reconnect text.
123     */
124    protected static function helper_get_reconnect_text() {
125        return __( 'Reconnect Jetpack now', 'jetpack' );
126    }
127
128    /**
129     * Returns the translated text for failing tests due to timeouts.
130     *
131     * @return string The translated timeout text.
132     */
133    protected static function helper_get_timeout_text() {
134        return __( 'The test timed out which may sometimes indicate a failure or may be a false failure. Please relaunch tests.', 'jetpack' );
135    }
136
137    /**
138     * Gets translated reconnect long description.
139     *
140     * @param string $connection_error The connection specific error.
141     * @param string $recommendation The recommendation for resolving the connection error.
142     *
143     * @return string The translated long description for reconnection recommendations.
144     */
145    protected static function helper_get_reconnect_long_description( $connection_error, $recommendation ) {
146
147        return sprintf(
148            '<p>%1$s</p>' .
149            '<p><span class="dashicons fail"><span class="screen-reader-text">%2$s</span></span> %3$s</p><p><strong>%4$s</strong></p>',
150            __( 'A healthy connection ensures Jetpack essential services are provided to your WordPress site, such as Stats and Site Security.', 'jetpack' ),
151            /* translators: screen reader text indicating a test failed */
152            __( 'Error', 'jetpack' ),
153            $connection_error,
154            $recommendation
155        );
156    }
157
158    /**
159     * Helper function to return consistent responses for a connection failing test.
160     *
161     * @param string $name The raw method name that runs the test. Default unnamed_test.
162     * @param string $connection_error The connection specific error. Default 'Your site is not connected to Jetpack.'.
163     * @param string $recommendation The recommendation for resolving the connection error. Default 'We recommend reconnecting Jetpack.'.
164     *
165     * @return array Test results.
166     */
167    public static function connection_failing_test( $name, $connection_error = '', $recommendation = '' ) {
168        $connection_error = empty( $connection_error ) ? __( 'Your site is not connected to Jetpack.', 'jetpack' ) : $connection_error;
169        $recommendation   = empty( $recommendation ) ? __( 'We recommend reconnecting Jetpack.', 'jetpack' ) : $recommendation;
170
171        $args = array(
172            'name'              => $name,
173            'short_description' => $connection_error,
174            'action'            => self::helper_get_reconnect_url(),
175            'action_label'      => self::helper_get_reconnect_text(),
176            'long_description'  => self::helper_get_reconnect_long_description( $connection_error, $recommendation ),
177        );
178
179        return self::failing_test( $args );
180    }
181
182    /**
183     * Gets translated text to enable outbound requests.
184     *
185     * @param string $protocol Either 'HTTP' or 'HTTPS'.
186     *
187     * @return string The translated text.
188     */
189    protected function helper_enable_outbound_requests( $protocol ) {
190        return sprintf(
191            /* translators: %1$s - request protocol, either http or https */
192            __(
193                'Your server did not successfully connect to the Jetpack server using %1$s
194                Please ask your hosting provider to confirm your server can make outbound requests to jetpack.com.',
195                'jetpack'
196            ),
197            $protocol
198        );
199    }
200
201    /**
202     * Returns 30 for use with a filter.
203     *
204     * To allow time for WP.com to run upstream testing, this function exists to increase the http_request_timeout value
205     * to 30.
206     *
207     * @return int 30
208     */
209    public static function increase_timeout() {
210        return 30; // seconds.
211    }
212
213    /**
214     * The test verifies the blog token exists.
215     *
216     * @return array
217     */
218    protected function test__blog_token_if_exists() {
219        $name = __FUNCTION__;
220
221        if ( ! $this->helper_is_jetpack_connected() ) {
222            return self::skipped_test(
223                array(
224                    'name'              => $name,
225                    'short_description' => __( 'Jetpack is not connected. No blog token to check.', 'jetpack' ),
226                )
227            );
228        }
229        $blog_token = $this->helper_get_blog_token();
230
231        if ( $blog_token ) {
232            $result = self::passing_test( array( 'name' => $name ) );
233        } else {
234            $connection_error = __( 'Blog token is missing.', 'jetpack' );
235
236            $result = self::connection_failing_test( $name, $connection_error );
237        }
238
239        return $result;
240    }
241
242    /**
243     * Test if Jetpack is connected.
244     */
245    protected function test__check_if_connected() {
246        $name = __FUNCTION__;
247
248        if ( ! $this->helper_get_blog_token() ) {
249            return self::skipped_test(
250                array(
251                    'name'              => $name,
252                    'short_description' => __( 'Blog token is missing.', 'jetpack' ),
253                )
254            );
255        }
256
257        if ( $this->helper_is_jetpack_connected() ) {
258            $result = self::passing_test(
259                array(
260                    'name'             => $name,
261                    'label'            => __( 'Your site is connected to Jetpack', 'jetpack' ),
262                    'long_description' => sprintf(
263                        '<p>%1$s</p>' .
264                        '<p><span class="dashicons pass"><span class="screen-reader-text">%2$s</span></span> %3$s</p>',
265                        __( 'A healthy connection ensures Jetpack essential services are provided to your WordPress site, such as Stats and Site Security.', 'jetpack' ),
266                        /* translators: Screen reader text indicating a test has passed */
267                        __( 'Passed', 'jetpack' ),
268                        __( 'Your site is connected to Jetpack.', 'jetpack' )
269                    ),
270                )
271            );
272        } elseif ( ( new Status() )->is_offline_mode() ) {
273            $result = self::skipped_test(
274                array(
275                    'name'              => $name,
276                    'short_description' => __( 'Jetpack is in Offline Mode:', 'jetpack' ) . ' ' . Jetpack::development_mode_trigger_text(),
277                )
278            );
279        } else {
280            $connection_error = __( 'Your site is not connected to Jetpack', 'jetpack' );
281
282            $result = self::connection_failing_test( $name, $connection_error );
283        }
284
285        return $result;
286    }
287
288    /**
289     * Test that the master user still exists on this site.
290     *
291     * @return array Test results.
292     */
293    protected function test__master_user_exists_on_site() {
294        $name = __FUNCTION__;
295        if ( ! $this->helper_is_jetpack_connected() ) {
296            return self::skipped_test(
297                array(
298                    'name'              => $name,
299                    'short_description' => __( 'Jetpack is not connected. No master user to check.', 'jetpack' ),
300                )
301            );
302        }
303        if ( ! ( new Connection_Manager() )->get_connection_owner_id() ) {
304            return self::skipped_test(
305                array(
306                    'name'              => $name,
307                    'short_description' => __( 'Jetpack is running without a connected user. No master user to check.', 'jetpack' ),
308                )
309            );
310        }
311        $local_user = $this->helper_retrieve_local_master_user();
312
313        if ( $local_user->exists() ) {
314            $result = self::passing_test( array( 'name' => $name ) );
315        } else {
316            $connection_error = __( 'The user who set up the Jetpack connection no longer exists on this site.', 'jetpack' );
317
318            $result = self::connection_failing_test( $name, $connection_error );
319        }
320
321        return $result;
322    }
323
324    /**
325     * Test that the master user has the manage options capability (e.g. is an admin).
326     *
327     * Generic calls from WP.com execute on Jetpack as the master user. If it isn't an admin, random things will fail.
328     *
329     * @return array Test results.
330     */
331    protected function test__master_user_can_manage_options() {
332        $name = __FUNCTION__;
333        if ( ! $this->helper_is_jetpack_connected() ) {
334            return self::skipped_test(
335                array(
336                    'name'              => $name,
337                    'short_description' => __( 'Jetpack is not connected.', 'jetpack' ),
338                )
339            );
340        }
341        if ( ! ( new Connection_Manager() )->get_connection_owner_id() ) {
342            return self::skipped_test(
343                array(
344                    'name'              => $name,
345                    'short_description' => __( 'Jetpack is running without a connected user. No master user to check.', 'jetpack' ),
346                )
347            );
348        }
349        $master_user = $this->helper_retrieve_local_master_user();
350
351        if ( user_can( $master_user, 'manage_options' ) ) {
352            $result = self::passing_test( array( 'name' => $name ) );
353        } else {
354            /* translators: a WordPress username */
355            $connection_error = sprintf( __( 'The user (%s) who set up the Jetpack connection is not an administrator.', 'jetpack' ), $master_user->user_login );
356            /* translators: a WordPress username */
357            $recommendation = sprintf( __( 'We recommend either upgrading the user (%s) or reconnecting Jetpack.', 'jetpack' ), $master_user->user_login );
358
359            $result = self::connection_failing_test( $name, $connection_error, $recommendation );
360        }
361
362        return $result;
363    }
364
365    /**
366     * Test that the PHP's XML library is installed.
367     *
368     * While it should be installed by default, increasingly in PHP 7, some OSes require an additional php-xml package.
369     *
370     * @return array Test results.
371     */
372    protected function test__xml_parser_available() {
373        $name = __FUNCTION__;
374        if ( function_exists( 'xml_parser_create' ) ) {
375            $result = self::passing_test( array( 'name' => $name ) );
376        } else {
377            $result = self::failing_test(
378                array(
379                    'name'              => $name,
380                    'label'             => __( 'PHP XML manipulation libraries are not available.', 'jetpack' ),
381                    'short_description' => __( 'Please ask your hosting provider to refer to our server requirements and enable PHP\'s XML module.', 'jetpack' ),
382                    'action_label'      => __( 'View our server requirements', 'jetpack' ),
383                    'action'            => Redirect::get_url( 'jetpack-support-server-requirements' ),
384                )
385            );
386        }
387        return $result;
388    }
389
390    /**
391     * Test that the server is able to send an outbound http communication.
392     *
393     * @return array Test results.
394     */
395    protected function test__outbound_http() {
396        $name    = __FUNCTION__;
397        $request = wp_remote_get( preg_replace( '/^https:/', 'http:', JETPACK__API_BASE ) . 'test/1/' );
398        $code    = wp_remote_retrieve_response_code( $request );
399
400        if ( 200 === (int) $code ) {
401            $result = self::passing_test( array( 'name' => $name ) );
402        } else {
403            $result = self::failing_test(
404                array(
405                    'name'              => $name,
406                    'short_description' => $this->helper_enable_outbound_requests( 'HTTP' ),
407                )
408            );
409        }
410
411        return $result;
412    }
413
414    /**
415     * Test that the server is able to send an outbound https communication.
416     *
417     * @return array Test results.
418     */
419    protected function test__outbound_https() {
420        $name    = __FUNCTION__;
421        $request = wp_remote_get( preg_replace( '/^http:/', 'https:', JETPACK__API_BASE ) . 'test/1/' );
422        $code    = wp_remote_retrieve_response_code( $request );
423
424        if ( 200 === (int) $code ) {
425            $result = self::passing_test( array( 'name' => $name ) );
426        } else {
427            $result = self::failing_test(
428                array(
429                    'name'              => $name,
430                    'short_description' => $this->helper_enable_outbound_requests( 'HTTPS' ),
431                )
432            );
433        }
434
435        return $result;
436    }
437
438    /**
439     * Check for an IDC.
440     *
441     * @return array Test results.
442     */
443    protected function test__identity_crisis() {
444        $name = __FUNCTION__;
445        if ( ! $this->helper_is_jetpack_connected() ) {
446            return self::skipped_test(
447                array(
448                    'name'              => $name,
449                    'short_description' => __( 'Jetpack is not connected.', 'jetpack' ),
450                )
451            );
452        }
453        $identity_crisis = Jetpack::check_identity_crisis();
454
455        if ( ! $identity_crisis ) {
456            $result = self::passing_test( array( 'name' => $name ) );
457        } else {
458            $messages = array();
459
460            // Check each URL pair and add a message for any that mismatch.
461            if ( isset( $identity_crisis['home'] ) && isset( $identity_crisis['wpcom_home'] ) && $identity_crisis['home'] !== $identity_crisis['wpcom_home'] ) {
462                $messages[] = sprintf(
463                    /* translators: Two URLs. The first is the locally-recorded value, the second is the value as recorded on WP.com. */
464                    __( 'Your home URL is set as `%1$s`, but your WordPress.com connection lists it as `%2$s`.', 'jetpack' ),
465                    $identity_crisis['home'],
466                    $identity_crisis['wpcom_home']
467                );
468            }
469
470            if ( isset( $identity_crisis['siteurl'] ) && isset( $identity_crisis['wpcom_siteurl'] ) && $identity_crisis['siteurl'] !== $identity_crisis['wpcom_siteurl'] ) {
471                $messages[] = sprintf(
472                    /* translators: Two URLs. The first is the locally-recorded value, the second is the value as recorded on WP.com. */
473                    __( 'Your site URL is set as `%1$s`, but your WordPress.com connection lists it as `%2$s`.', 'jetpack' ),
474                    $identity_crisis['siteurl'],
475                    $identity_crisis['wpcom_siteurl']
476                );
477            }
478
479            // Fallback if no specific mismatch was detected (shouldn't happen, but be safe).
480            if ( empty( $messages ) ) {
481                $messages[] = __( 'A URL mismatch was detected between your site and WordPress.com.', 'jetpack' );
482            }
483
484            $result = self::failing_test(
485                array(
486                    'name'              => $name,
487                    'short_description' => implode( ' ', $messages ),
488                    'action_label'      => $this->helper_get_support_text(),
489                    'action'            => $this->helper_get_support_url(),
490                )
491            );
492        }
493        return $result;
494    }
495
496    /**
497     * Tests the health of the Connection tokens.
498     *
499     * This will always check the blog token health. It will also check the user token health if
500     * a user is logged in and connected, or if there's a connected owner.
501     *
502     * @since 9.0.0
503     * @since 9.6.0 Checks only blog token if current user not connected or site does not have a connected owner.
504     *
505     * @return array Test results.
506     */
507    protected function test__connection_token_health() {
508        $name    = __FUNCTION__;
509        $m       = new Connection_Manager();
510        $user_id = get_current_user_id();
511
512        // Check if there's a connected logged in user.
513        if ( $user_id && ! $m->is_user_connected( $user_id ) ) {
514                $user_id = false;
515        }
516
517        // If no logged in user to check, let's see if there's a master_user set.
518        if ( ! $user_id ) {
519                $user_id = Jetpack_Options::get_option( 'master_user' );
520            if ( $user_id && ! $m->is_user_connected( $user_id ) ) {
521                return self::connection_failing_test( $name, __( 'Missing token for the connection owner.', 'jetpack' ) );
522            }
523        }
524
525        if ( $user_id ) {
526            return $this->check_tokens_health( $user_id );
527        } else {
528            return $this->check_blog_token_health();
529        }
530    }
531
532    /**
533     * Tests blog and user's token against wp.com's check-token-health endpoint.
534     *
535     * @since 9.6.0
536     *
537     * @return array Test results.
538     */
539    protected function check_blog_token_health() {
540        $name  = 'test__connection_token_health';
541        $valid = ( new Tokens() )->validate_blog_token();
542
543        if ( ! $valid ) {
544            return self::connection_failing_test( $name, __( 'Blog token validation failed.', 'jetpack' ) );
545        } else {
546            return self::passing_test( array( 'name' => $name ) );
547        }
548    }
549
550    /**
551     * Tests blog token against wp.com's check-token-health endpoint.
552     *
553     * @since 9.6.0
554     *
555     * @param int $user_id The user ID to check the tokens for.
556     *
557     * @return array Test results.
558     */
559    protected function check_tokens_health( $user_id ) {
560        $name             = 'test__connection_token_health';
561        $validated_tokens = ( new Tokens() )->validate( $user_id );
562
563        if ( ! is_array( $validated_tokens ) || count( array_diff_key( array_flip( array( 'blog_token', 'user_token' ) ), $validated_tokens ) ) ) {
564            return self::skipped_test(
565                array(
566                    'name'              => $name,
567                    'short_description' => __( 'Token health check failed to validate tokens.', 'jetpack' ),
568                )
569            );
570        }
571
572        $invalid_tokens_exist = false;
573        foreach ( $validated_tokens as $validated_token ) {
574            if ( ! $validated_token['is_healthy'] ) {
575                $invalid_tokens_exist = true;
576                break;
577            }
578        }
579
580        if ( false === $invalid_tokens_exist ) {
581            return self::passing_test( array( 'name' => $name ) );
582        }
583
584        $connection_error = __( 'Invalid Jetpack connection tokens.', 'jetpack' );
585
586        return self::connection_failing_test( $name, $connection_error );
587    }
588
589    /**
590     * Tests connection status against wp.com's test-connection endpoint.
591     *
592     * @todo: Compare with the wpcom_self_test. We only need one of these.
593     *
594     * @return array Test results.
595     */
596    protected function test__wpcom_connection_test() {
597        $name = __FUNCTION__;
598
599        $status = new Status();
600        if ( ! Jetpack::is_connection_ready() || $status->is_offline_mode() || $status->in_safe_mode() || ! $this->pass ) {
601            return self::skipped_test( array( 'name' => $name ) );
602        }
603
604        add_filter( 'http_request_timeout', array( 'Jetpack_Cxn_Tests', 'increase_timeout' ) );
605        $response = Client::wpcom_json_api_request_as_blog(
606            sprintf( '/jetpack-blogs/%d/test-connection', Jetpack_Options::get_option( 'id' ) ),
607            Client::WPCOM_JSON_API_VERSION
608        );
609        remove_filter( 'http_request_timeout', array( 'Jetpack_Cxn_Tests', 'increase_timeout' ) );
610
611        if ( is_wp_error( $response ) ) {
612            if ( str_contains( $response->get_error_message(), 'cURL error 28' ) ) { // Timeout.
613                $result = self::skipped_test(
614                    array(
615                        'name'              => $name,
616                        'short_description' => self::helper_get_timeout_text(),
617                    )
618                );
619            } else {
620                /* translators: %1$s is the error code, %2$s is the error message */
621                $message = sprintf( __( 'Connection test failed (#%1$s: %2$s)', 'jetpack' ), $response->get_error_code(), $response->get_error_message() );
622
623                $result = self::connection_failing_test( $name, $message );
624            }
625
626            return $result;
627        }
628
629        $body = wp_remote_retrieve_body( $response );
630        if ( ! $body ) {
631            return self::failing_test(
632                array(
633                    'name'              => $name,
634                    'short_description' => __( 'Connection test failed (empty response body)', 'jetpack' ) . wp_remote_retrieve_response_code( $response ),
635                    'action_label'      => $this->helper_get_support_text(),
636                    'action'            => $this->helper_get_support_url(),
637                )
638            );
639        }
640
641        if ( 404 === wp_remote_retrieve_response_code( $response ) ) {
642            return self::skipped_test(
643                array(
644                    'name'              => $name,
645                    'short_description' => __( 'The WordPress.com API returned a 404 error.', 'jetpack' ),
646                )
647            );
648        }
649
650        $result       = json_decode( $body );
651        $is_connected = ! empty( $result->connected );
652        $message      = $result->message . ': ' . wp_remote_retrieve_response_code( $response );
653
654        if ( $is_connected ) {
655            $res = self::passing_test( array( 'name' => $name ) );
656        } else {
657            $res = self::connection_failing_test( $name, $message );
658        }
659
660        return $res;
661    }
662
663    /**
664     * Tests the port number to ensure it is an expected value.
665     *
666     * We expect that sites on be on one of:
667     * port 80,
668     * port 443 (https sites only),
669     * the value of JETPACK_SIGNATURE__HTTP_PORT,
670     * unless the site is intentionally on a different port (e.g. example.com:8080 is the site's URL).
671     *
672     * If the value isn't one of those and the site's URL doesn't include a port, then the signature verification will fail.
673     *
674     * This happens most commonly on sites with reverse proxies, so the edge (e.g. Varnish) is running on 80/443, but nginx
675     * or Apache is responding internally on a different port (e.g. 81).
676     *
677     * @return array Test results
678     */
679    protected function test__server_port_value() {
680        $name = __FUNCTION__;
681        if ( ! isset( $_SERVER['HTTP_X_FORWARDED_PORT'] ) && ! isset( $_SERVER['SERVER_PORT'] ) ) {
682            return self::skipped_test(
683                array(
684                    'name'              => $name,
685                    'short_description' => __( 'The server port values are not defined. This is most common when running PHP via a CLI.', 'jetpack' ),
686                )
687            );
688        }
689        $site_port   = wp_parse_url( home_url(), PHP_URL_PORT );
690        $server_port = isset( $_SERVER['HTTP_X_FORWARDED_PORT'] ) ? (int) $_SERVER['HTTP_X_FORWARDED_PORT'] : (int) $_SERVER['SERVER_PORT'];
691        $http_ports  = array( 80 );
692        $https_ports = array( 80, 443 );
693
694        if ( defined( 'JETPACK_SIGNATURE__HTTP_PORT' ) ) {
695            $http_ports[] = JETPACK_SIGNATURE__HTTP_PORT;
696        }
697
698        if ( defined( 'JETPACK_SIGNATURE__HTTPS_PORT' ) ) {
699            $https_ports[] = JETPACK_SIGNATURE__HTTPS_PORT;
700        }
701
702        if ( $site_port ) {
703            return self::skipped_test( array( 'name' => $name ) ); // Not currently testing for this situation.
704        }
705
706        if ( is_ssl() && in_array( $server_port, $https_ports, true ) ) {
707            return self::passing_test( array( 'name' => $name ) );
708        } elseif ( in_array( $server_port, $http_ports, true ) ) {
709            return self::passing_test( array( 'name' => $name ) );
710        } else {
711            if ( is_ssl() ) {
712                $needed_constant = 'JETPACK_SIGNATURE__HTTPS_PORT';
713            } else {
714                $needed_constant = 'JETPACK_SIGNATURE__HTTP_PORT';
715            }
716            return self::failing_test(
717                array(
718                    'name'              => $name,
719                    'short_description' => sprintf(
720                        /* translators: %1$s - a PHP code snippet */
721                        __(
722                            'The server port value is unexpected.
723                        Try adding the following to your wp-config.php file: %1$s',
724                            'jetpack'
725                        ),
726                        "define( '$needed_constant', $server_port )"
727                    ),
728                )
729            );
730        }
731    }
732
733    /**
734     * Sync Health Tests.
735     *
736     * Disabled: Results in a failing test (recommended)
737     * Delayed: Results in failing test (recommended)
738     * Error: Results in failing test (critical)
739     */
740    protected function test__sync_health() {
741
742        $name = __FUNCTION__;
743
744        if ( ! $this->helper_is_jetpack_connected() ) {
745            // If the site is not connected, there is no point in testing Sync health.
746            return self::skipped_test(
747                array(
748                    'name'                => $name,
749                    'show_in_site_health' => false,
750                )
751            );
752        }
753
754        // Sync is disabled.
755        if ( ! Sync_Settings::is_sync_enabled() ) {
756            return self::failing_test(
757                array(
758                    'name'              => $name,
759                    'label'             => __( 'Jetpack Sync has been disabled on your site.', 'jetpack' ),
760                    'severity'          => 'recommended',
761                    'action'            => 'https://github.com/Automattic/jetpack/blob/trunk/projects/packages/sync/src/class-settings.php',
762                    'action_label'      => __( 'See Github for more on Sync Settings', 'jetpack' ),
763                    'short_description' => __( 'Jetpack Sync has been disabled on your site. This could be impacting some of your site’s Jetpack-powered features. Developers may enable / disable syncing using the Sync Settings API.', 'jetpack' ),
764                )
765            );
766        }
767        // Sync has experienced Data Loss.
768        if ( Sync_Health::get_status() === Sync_Health::STATUS_OUT_OF_SYNC ) {
769            return self::failing_test(
770                array(
771                    'name'              => $name,
772                    'label'             => __( 'Jetpack has detected a problem with the communication between your site and WordPress.com', 'jetpack' ),
773                    'severity'          => 'critical',
774                    'action'            => Redirect::get_url( 'jetpack-contact-support' ),
775                    'action_label'      => __( 'Contact Jetpack Support', 'jetpack' ),
776                    'short_description' => __( 'There is a problem with the communication between your site and WordPress.com. This could be impacting some of your site’s Jetpack-powered features. If you continue to see this error, please contact support for assistance.', 'jetpack' ),
777                )
778            );
779
780        }
781
782        return self::passing_test( array( 'name' => $name ) );
783    }
784
785    /**
786     * Calls to WP.com to run the connection diagnostic testing suite.
787     *
788     * Intentionally added last as it will be skipped if any local failed conditions exist.
789     *
790     * @since 7.1.0
791     * @since 7.9.0 Timeout waiting for a WP.com response no longer fails the test. Test is marked skipped instead.
792     *
793     * @return array Test results.
794     */
795    protected function last__wpcom_self_test() {
796        $name = 'test__wpcom_self_test';
797
798        $status = new Status();
799        if ( ! Jetpack::is_connection_ready() || $status->is_offline_mode() || $status->in_safe_mode() || ! $this->pass ) {
800            return self::skipped_test( array( 'name' => $name ) );
801        }
802
803        $self_xml_rpc_url = site_url( 'xmlrpc.php' );
804
805        $testsite_url = JETPACK__API_BASE . 'testsite/1/?url=';
806
807        // Using PHP_INT_MAX - 1 so that there is still a way to override this if needed and since it only impacts this one call.
808        add_filter( 'http_request_timeout', array( 'Jetpack_Cxn_Tests', 'increase_timeout' ), PHP_INT_MAX - 1 );
809
810        $response = wp_remote_get( $testsite_url . $self_xml_rpc_url );
811
812        remove_filter( 'http_request_timeout', array( 'Jetpack_Cxn_Tests', 'increase_timeout' ), PHP_INT_MAX - 1 );
813
814        if ( 200 === wp_remote_retrieve_response_code( $response ) ) {
815            $result = self::passing_test( array( 'name' => $name ) );
816        } elseif ( is_wp_error( $response ) && str_contains( $response->get_error_message(), 'cURL error 28' ) ) { // Timeout.
817            $result = self::skipped_test(
818                array(
819                    'name'              => $name,
820                    'short_description' => self::helper_get_timeout_text(),
821                )
822            );
823        } else {
824            $result = self::failing_test(
825                array(
826                    'name'              => $name,
827                    'short_description' => sprintf(
828                        /* translators: %1$s - A debugging url */
829                        __( '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' ),
830                        Redirect::get_url( 'jetpack-support-debug', array( 'query' => 'url=' . rawurlencode( site_url() ) ) )
831                    ),
832                    'action_label'      => $this->helper_get_support_text(),
833                    'action'            => $this->helper_get_support_url(),
834                )
835            );
836        }
837
838        return $result;
839    }
840}