Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 378
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 / 376
0.00% covered (danger)
0.00%
0 / 28
8556
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 / 24
0.00% covered (danger)
0.00%
0 / 1
12
 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            $result = self::failing_test(
459                array(
460                    'name'              => $name,
461                    'short_description' => sprintf(
462                        /* translators: Two URLs. The first is the locally-recorded value, the second is the value as recorded on WP.com. */
463                        __( 'Your url is set as `%1$s`, but your WordPress.com connection lists it as `%2$s`!', 'jetpack' ),
464                        $identity_crisis['home'],
465                        $identity_crisis['wpcom_home']
466                    ),
467                    'action_label'      => $this->helper_get_support_text(),
468                    'action'            => $this->helper_get_support_url(),
469                )
470            );
471        }
472        return $result;
473    }
474
475    /**
476     * Tests the health of the Connection tokens.
477     *
478     * This will always check the blog token health. It will also check the user token health if
479     * a user is logged in and connected, or if there's a connected owner.
480     *
481     * @since 9.0.0
482     * @since 9.6.0 Checks only blog token if current user not connected or site does not have a connected owner.
483     *
484     * @return array Test results.
485     */
486    protected function test__connection_token_health() {
487        $name    = __FUNCTION__;
488        $m       = new Connection_Manager();
489        $user_id = get_current_user_id();
490
491        // Check if there's a connected logged in user.
492        if ( $user_id && ! $m->is_user_connected( $user_id ) ) {
493                $user_id = false;
494        }
495
496        // If no logged in user to check, let's see if there's a master_user set.
497        if ( ! $user_id ) {
498                $user_id = Jetpack_Options::get_option( 'master_user' );
499            if ( $user_id && ! $m->is_user_connected( $user_id ) ) {
500                return self::connection_failing_test( $name, __( 'Missing token for the connection owner.', 'jetpack' ) );
501            }
502        }
503
504        if ( $user_id ) {
505            return $this->check_tokens_health( $user_id );
506        } else {
507            return $this->check_blog_token_health();
508        }
509    }
510
511    /**
512     * Tests blog and user's token against wp.com's check-token-health endpoint.
513     *
514     * @since 9.6.0
515     *
516     * @return array Test results.
517     */
518    protected function check_blog_token_health() {
519        $name  = 'test__connection_token_health';
520        $valid = ( new Tokens() )->validate_blog_token();
521
522        if ( ! $valid ) {
523            return self::connection_failing_test( $name, __( 'Blog token validation failed.', 'jetpack' ) );
524        } else {
525            return self::passing_test( array( 'name' => $name ) );
526        }
527    }
528
529    /**
530     * Tests blog token against wp.com's check-token-health endpoint.
531     *
532     * @since 9.6.0
533     *
534     * @param int $user_id The user ID to check the tokens for.
535     *
536     * @return array Test results.
537     */
538    protected function check_tokens_health( $user_id ) {
539        $name             = 'test__connection_token_health';
540        $validated_tokens = ( new Tokens() )->validate( $user_id );
541
542        if ( ! is_array( $validated_tokens ) || count( array_diff_key( array_flip( array( 'blog_token', 'user_token' ) ), $validated_tokens ) ) ) {
543            return self::skipped_test(
544                array(
545                    'name'              => $name,
546                    'short_description' => __( 'Token health check failed to validate tokens.', 'jetpack' ),
547                )
548            );
549        }
550
551        $invalid_tokens_exist = false;
552        foreach ( $validated_tokens as $validated_token ) {
553            if ( ! $validated_token['is_healthy'] ) {
554                $invalid_tokens_exist = true;
555                break;
556            }
557        }
558
559        if ( false === $invalid_tokens_exist ) {
560            return self::passing_test( array( 'name' => $name ) );
561        }
562
563        $connection_error = __( 'Invalid Jetpack connection tokens.', 'jetpack' );
564
565        return self::connection_failing_test( $name, $connection_error );
566    }
567
568    /**
569     * Tests connection status against wp.com's test-connection endpoint.
570     *
571     * @todo: Compare with the wpcom_self_test. We only need one of these.
572     *
573     * @return array Test results.
574     */
575    protected function test__wpcom_connection_test() {
576        $name = __FUNCTION__;
577
578        $status = new Status();
579        if ( ! Jetpack::is_connection_ready() || $status->is_offline_mode() || $status->in_safe_mode() || ! $this->pass ) {
580            return self::skipped_test( array( 'name' => $name ) );
581        }
582
583        add_filter( 'http_request_timeout', array( 'Jetpack_Cxn_Tests', 'increase_timeout' ) );
584        $response = Client::wpcom_json_api_request_as_blog(
585            sprintf( '/jetpack-blogs/%d/test-connection', Jetpack_Options::get_option( 'id' ) ),
586            Client::WPCOM_JSON_API_VERSION
587        );
588        remove_filter( 'http_request_timeout', array( 'Jetpack_Cxn_Tests', 'increase_timeout' ) );
589
590        if ( is_wp_error( $response ) ) {
591            if ( str_contains( $response->get_error_message(), 'cURL error 28' ) ) { // Timeout.
592                $result = self::skipped_test(
593                    array(
594                        'name'              => $name,
595                        'short_description' => self::helper_get_timeout_text(),
596                    )
597                );
598            } else {
599                /* translators: %1$s is the error code, %2$s is the error message */
600                $message = sprintf( __( 'Connection test failed (#%1$s: %2$s)', 'jetpack' ), $response->get_error_code(), $response->get_error_message() );
601
602                $result = self::connection_failing_test( $name, $message );
603            }
604
605            return $result;
606        }
607
608        $body = wp_remote_retrieve_body( $response );
609        if ( ! $body ) {
610            return self::failing_test(
611                array(
612                    'name'              => $name,
613                    'short_description' => __( 'Connection test failed (empty response body)', 'jetpack' ) . wp_remote_retrieve_response_code( $response ),
614                    'action_label'      => $this->helper_get_support_text(),
615                    'action'            => $this->helper_get_support_url(),
616                )
617            );
618        }
619
620        if ( 404 === wp_remote_retrieve_response_code( $response ) ) {
621            return self::skipped_test(
622                array(
623                    'name'              => $name,
624                    'short_description' => __( 'The WordPress.com API returned a 404 error.', 'jetpack' ),
625                )
626            );
627        }
628
629        $result       = json_decode( $body );
630        $is_connected = ! empty( $result->connected );
631        $message      = $result->message . ': ' . wp_remote_retrieve_response_code( $response );
632
633        if ( $is_connected ) {
634            $res = self::passing_test( array( 'name' => $name ) );
635        } else {
636            $res = self::connection_failing_test( $name, $message );
637        }
638
639        return $res;
640    }
641
642    /**
643     * Tests the port number to ensure it is an expected value.
644     *
645     * We expect that sites on be on one of:
646     * port 80,
647     * port 443 (https sites only),
648     * the value of JETPACK_SIGNATURE__HTTP_PORT,
649     * unless the site is intentionally on a different port (e.g. example.com:8080 is the site's URL).
650     *
651     * If the value isn't one of those and the site's URL doesn't include a port, then the signature verification will fail.
652     *
653     * This happens most commonly on sites with reverse proxies, so the edge (e.g. Varnish) is running on 80/443, but nginx
654     * or Apache is responding internally on a different port (e.g. 81).
655     *
656     * @return array Test results
657     */
658    protected function test__server_port_value() {
659        $name = __FUNCTION__;
660        if ( ! isset( $_SERVER['HTTP_X_FORWARDED_PORT'] ) && ! isset( $_SERVER['SERVER_PORT'] ) ) {
661            return self::skipped_test(
662                array(
663                    'name'              => $name,
664                    'short_description' => __( 'The server port values are not defined. This is most common when running PHP via a CLI.', 'jetpack' ),
665                )
666            );
667        }
668        $site_port   = wp_parse_url( home_url(), PHP_URL_PORT );
669        $server_port = isset( $_SERVER['HTTP_X_FORWARDED_PORT'] ) ? (int) $_SERVER['HTTP_X_FORWARDED_PORT'] : (int) $_SERVER['SERVER_PORT'];
670        $http_ports  = array( 80 );
671        $https_ports = array( 80, 443 );
672
673        if ( defined( 'JETPACK_SIGNATURE__HTTP_PORT' ) ) {
674            $http_ports[] = JETPACK_SIGNATURE__HTTP_PORT;
675        }
676
677        if ( defined( 'JETPACK_SIGNATURE__HTTPS_PORT' ) ) {
678            $https_ports[] = JETPACK_SIGNATURE__HTTPS_PORT;
679        }
680
681        if ( $site_port ) {
682            return self::skipped_test( array( 'name' => $name ) ); // Not currently testing for this situation.
683        }
684
685        if ( is_ssl() && in_array( $server_port, $https_ports, true ) ) {
686            return self::passing_test( array( 'name' => $name ) );
687        } elseif ( in_array( $server_port, $http_ports, true ) ) {
688            return self::passing_test( array( 'name' => $name ) );
689        } else {
690            if ( is_ssl() ) {
691                $needed_constant = 'JETPACK_SIGNATURE__HTTPS_PORT';
692            } else {
693                $needed_constant = 'JETPACK_SIGNATURE__HTTP_PORT';
694            }
695            return self::failing_test(
696                array(
697                    'name'              => $name,
698                    'short_description' => sprintf(
699                        /* translators: %1$s - a PHP code snippet */
700                        __(
701                            'The server port value is unexpected.
702                        Try adding the following to your wp-config.php file: %1$s',
703                            'jetpack'
704                        ),
705                        "define( '$needed_constant', $server_port )"
706                    ),
707                )
708            );
709        }
710    }
711
712    /**
713     * Sync Health Tests.
714     *
715     * Disabled: Results in a failing test (recommended)
716     * Delayed: Results in failing test (recommended)
717     * Error: Results in failing test (critical)
718     */
719    protected function test__sync_health() {
720
721        $name = __FUNCTION__;
722
723        if ( ! $this->helper_is_jetpack_connected() ) {
724            // If the site is not connected, there is no point in testing Sync health.
725            return self::skipped_test(
726                array(
727                    'name'                => $name,
728                    'show_in_site_health' => false,
729                )
730            );
731        }
732
733        // Sync is disabled.
734        if ( ! Sync_Settings::is_sync_enabled() ) {
735            return self::failing_test(
736                array(
737                    'name'              => $name,
738                    'label'             => __( 'Jetpack Sync has been disabled on your site.', 'jetpack' ),
739                    'severity'          => 'recommended',
740                    'action'            => 'https://github.com/Automattic/jetpack/blob/trunk/projects/packages/sync/src/class-settings.php',
741                    'action_label'      => __( 'See Github for more on Sync Settings', 'jetpack' ),
742                    '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' ),
743                )
744            );
745        }
746        // Sync has experienced Data Loss.
747        if ( Sync_Health::get_status() === Sync_Health::STATUS_OUT_OF_SYNC ) {
748            return self::failing_test(
749                array(
750                    'name'              => $name,
751                    'label'             => __( 'Jetpack has detected a problem with the communication between your site and WordPress.com', 'jetpack' ),
752                    'severity'          => 'critical',
753                    'action'            => Redirect::get_url( 'jetpack-contact-support' ),
754                    'action_label'      => __( 'Contact Jetpack Support', 'jetpack' ),
755                    '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' ),
756                )
757            );
758
759        }
760
761        return self::passing_test( array( 'name' => $name ) );
762    }
763
764    /**
765     * Calls to WP.com to run the connection diagnostic testing suite.
766     *
767     * Intentionally added last as it will be skipped if any local failed conditions exist.
768     *
769     * @since 7.1.0
770     * @since 7.9.0 Timeout waiting for a WP.com response no longer fails the test. Test is marked skipped instead.
771     *
772     * @return array Test results.
773     */
774    protected function last__wpcom_self_test() {
775        $name = 'test__wpcom_self_test';
776
777        $status = new Status();
778        if ( ! Jetpack::is_connection_ready() || $status->is_offline_mode() || $status->in_safe_mode() || ! $this->pass ) {
779            return self::skipped_test( array( 'name' => $name ) );
780        }
781
782        $self_xml_rpc_url = site_url( 'xmlrpc.php' );
783
784        $testsite_url = JETPACK__API_BASE . 'testsite/1/?url=';
785
786        // 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.
787        add_filter( 'http_request_timeout', array( 'Jetpack_Cxn_Tests', 'increase_timeout' ), PHP_INT_MAX - 1 );
788
789        $response = wp_remote_get( $testsite_url . $self_xml_rpc_url );
790
791        remove_filter( 'http_request_timeout', array( 'Jetpack_Cxn_Tests', 'increase_timeout' ), PHP_INT_MAX - 1 );
792
793        if ( 200 === wp_remote_retrieve_response_code( $response ) ) {
794            $result = self::passing_test( array( 'name' => $name ) );
795        } elseif ( is_wp_error( $response ) && str_contains( $response->get_error_message(), 'cURL error 28' ) ) { // Timeout.
796            $result = self::skipped_test(
797                array(
798                    'name'              => $name,
799                    'short_description' => self::helper_get_timeout_text(),
800                )
801            );
802        } else {
803            $result = self::failing_test(
804                array(
805                    'name'              => $name,
806                    'short_description' => sprintf(
807                        /* translators: %1$s - A debugging url */
808                        __( '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' ),
809                        Redirect::get_url( 'jetpack-support-debug', array( 'query' => 'url=' . rawurlencode( site_url() ) ) )
810                    ),
811                    'action_label'      => $this->helper_get_support_text(),
812                    'action'            => $this->helper_get_support_url(),
813                )
814            );
815        }
816
817        return $result;
818    }
819}