class-jetpack-cxn-tests.php 32.5 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984
<?php
/**
 * Collection of tests to run on the Jetpack connection locally.
 *
 * @package automattic/jetpack
 */

use Automattic\Jetpack\Connection\Client;
use Automattic\Jetpack\Connection\Manager as Connection_Manager;
use Automattic\Jetpack\Connection\Tokens;
use Automattic\Jetpack\Redirect;
use Automattic\Jetpack\Status;
use Automattic\Jetpack\Sync\Health as Sync_Health;
use Automattic\Jetpack\Sync\Modules;
use Automattic\Jetpack\Sync\Sender as Sync_Sender;
use Automattic\Jetpack\Sync\Settings as Sync_Settings;

/**
 * Class Jetpack_Cxn_Tests contains all of the actual tests.
 */
class Jetpack_Cxn_Tests extends Jetpack_Cxn_Test_Base {

	/**
	 * Jetpack_Cxn_Tests constructor.
	 */
	public function __construct() {
		parent::__construct();

		$methods = get_class_methods( 'Jetpack_Cxn_Tests' );

		foreach ( $methods as $method ) {
			if ( false === strpos( $method, 'test__' ) ) {
				continue;
			}
			$this->add_test( array( $this, $method ), $method, 'direct' );
		}

		/**
		 * Fires after loading default Jetpack Connection tests.
		 *
		 * @since 7.1.0
		 * @since 8.3.0 Passes the Jetpack_Cxn_Tests instance.
		 */
		do_action( 'jetpack_connection_tests_loaded', $this );

		/**
		 * Determines if the WP.com testing suite should be included.
		 *
		 * @since 7.1.0
		 * @since 8.1.0 Default false.
		 *
		 * @param bool $run_test To run the WP.com testing suite. Default false.
		 */
		if ( apply_filters( 'jetpack_debugger_run_self_test', false ) ) {
			/**
			 * Intentionally added last as it checks for an existing failure state before attempting.
			 * Generally, any failed location condition would result in the WP.com check to fail too, so
			 * we will skip it to avoid confusing error messages.
			 *
			 * Note: This really should be an 'async' test.
			 */
			$this->add_test( array( $this, 'last__wpcom_self_test' ), 'test__wpcom_self_test', 'direct' );
		}
	}

	/**
	 * Helper function to look up the expected master user and return the local WP_User.
	 *
	 * @return WP_User Jetpack's expected master user.
	 */
	protected function helper_retrieve_local_master_user() {
		$master_user = Jetpack_Options::get_option( 'master_user' );
		return new WP_User( $master_user );
	}

	/**
	 * Is Jetpack even connected and supposed to be talking to WP.com?
	 */
	protected function helper_is_jetpack_connected() {
		return Jetpack::is_connection_ready() && ! ( new Status() )->is_offline_mode();
	}

	/**
	 * Retrieve the `blog_token` if it exists.
	 *
	 * @return object|false
	 */
	protected function helper_get_blog_token() {
		return ( new Tokens() )->get_access_token();
	}

	/**
	 * Returns a support url based on using a development version.
	 */
	protected function helper_get_support_url() {
		return Jetpack::is_development_version()
			? Redirect::get_url( 'jetpack-contact-support-beta-group' )
			: Redirect::get_url( 'jetpack-contact-support' );
	}

	/**
	 * Returns the url to reconnect Jetpack.
	 *
	 * @return string The reconnect url.
	 */
	protected static function helper_get_reconnect_url() {
		return admin_url( 'admin.php?page=jetpack#/reconnect' );
	}

	/**
	 * Gets translated support text.
	 */
	protected function helper_get_support_text() {
		return __( 'Please contact Jetpack support.', 'jetpack' );
	}

	/**
	 * Returns the translated text to reconnect Jetpack.
	 *
	 * @return string The translated reconnect text.
	 */
	protected static function helper_get_reconnect_text() {
		return __( 'Reconnect Jetpack now', 'jetpack' );
	}

	/**
	 * Returns the translated text for failing tests due to timeouts.
	 *
	 * @return string The translated timeout text.
	 */
	protected static function helper_get_timeout_text() {
		return __( 'The test timed out which may sometimes indicate a failure or may be a false failure. Please relaunch tests.', 'jetpack' );
	}

	/**
	 * Gets translated reconnect long description.
	 *
	 * @param string $connection_error The connection specific error.
	 * @param string $recommendation The recommendation for resolving the connection error.
	 *
	 * @return string The translated long description for reconnection recommendations.
	 */
	protected static function helper_get_reconnect_long_description( $connection_error, $recommendation ) {

		return sprintf(
			'<p>%1$s</p>' .
			'<p><span class="dashicons fail"><span class="screen-reader-text">%2$s</span></span> %3$s</p><p><strong>%4$s</strong></p>',
			__( 'A healthy connection ensures Jetpack essential services are provided to your WordPress site, such as Stats and Site Security.', 'jetpack' ),
			/* translators: screen reader text indicating a test failed */
			__( 'Error', 'jetpack' ),
			$connection_error,
			$recommendation
		);
	}

	/**
	 * Helper function to return consistent responses for a connection failing test.
	 *
	 * @param string $name The raw method name that runs the test. Default unnamed_test.
	 * @param string $connection_error The connection specific error. Default 'Your site is not connected to Jetpack.'.
	 * @param string $recommendation The recommendation for resolving the connection error. Default 'We recommend reconnecting Jetpack.'.
	 *
	 * @return array Test results.
	 */
	public static function connection_failing_test( $name, $connection_error = '', $recommendation = '' ) {
		$connection_error = empty( $connection_error ) ? __( 'Your site is not connected to Jetpack.', 'jetpack' ) : $connection_error;
		$recommendation   = empty( $recommendation ) ? __( 'We recommend reconnecting Jetpack.', 'jetpack' ) : $recommendation;

		$args = array(
			'name'              => $name,
			'short_description' => $connection_error,
			'action'            => self::helper_get_reconnect_url(),
			'action_label'      => self::helper_get_reconnect_text(),
			'long_description'  => self::helper_get_reconnect_long_description( $connection_error, $recommendation ),
		);

		return self::failing_test( $args );
	}

	/**
	 * Gets translated text to enable outbound requests.
	 *
	 * @param string $protocol Either 'HTTP' or 'HTTPS'.
	 *
	 * @return string The translated text.
	 */
	protected function helper_enable_outbound_requests( $protocol ) {
		return sprintf(
			/* translators: %1$s - request protocol, either http or https */
			__(
				'Your server did not successfully connect to the Jetpack server using %1$s
				Please ask your hosting provider to confirm your server can make outbound requests to jetpack.com.',
				'jetpack'
			),
			$protocol
		);
	}

	/**
	 * Returns 30 for use with a filter.
	 *
	 * To allow time for WP.com to run upstream testing, this function exists to increase the http_request_timeout value
	 * to 30.
	 *
	 * @return int 30
	 */
	public static function increase_timeout() {
		return 30; // seconds.
	}

	/**
	 * The test verifies the blog token exists.
	 *
	 * @return array
	 */
	protected function test__blog_token_if_exists() {
		$name = __FUNCTION__;

		if ( ! $this->helper_is_jetpack_connected() ) {
			return self::skipped_test(
				array(
					'name'              => $name,
					'short_description' => __( 'Jetpack is not connected. No blog token to check.', 'jetpack' ),
				)
			);
		}
		$blog_token = $this->helper_get_blog_token();

		if ( $blog_token ) {
			$result = self::passing_test( array( 'name' => $name ) );
		} else {
			$connection_error = __( 'Blog token is missing.', 'jetpack' );

			$result = self::connection_failing_test( $name, $connection_error );
		}

		return $result;
	}

	/**
	 * Test if Jetpack is connected.
	 */
	protected function test__check_if_connected() {
		$name = __FUNCTION__;

		if ( ! $this->helper_get_blog_token() ) {
			return self::skipped_test(
				array(
					'name'              => $name,
					'short_description' => __( 'Blog token is missing.', 'jetpack' ),
				)
			);
		}

		if ( $this->helper_is_jetpack_connected() ) {
			$result = self::passing_test(
				array(
					'name'             => $name,
					'label'            => __( 'Your site is connected to Jetpack', 'jetpack' ),
					'long_description' => sprintf(
						'<p>%1$s</p>' .
						'<p><span class="dashicons pass"><span class="screen-reader-text">%2$s</span></span> %3$s</p>',
						__( 'A healthy connection ensures Jetpack essential services are provided to your WordPress site, such as Stats and Site Security.', 'jetpack' ),
						/* translators: Screen reader text indicating a test has passed */
						__( 'Passed', 'jetpack' ),
						__( 'Your site is connected to Jetpack.', 'jetpack' )
					),
				)
			);
		} elseif ( ( new Status() )->is_offline_mode() ) {
			$result = self::skipped_test(
				array(
					'name'              => $name,
					'short_description' => __( 'Jetpack is in Offline Mode:', 'jetpack' ) . ' ' . Jetpack::development_mode_trigger_text(),
				)
			);
		} else {
			$connection_error = __( 'Your site is not connected to Jetpack', 'jetpack' );

			$result = self::connection_failing_test( $name, $connection_error );
		}

		return $result;
	}

	/**
	 * Test that the master user still exists on this site.
	 *
	 * @return array Test results.
	 */
	protected function test__master_user_exists_on_site() {
		$name = __FUNCTION__;
		if ( ! $this->helper_is_jetpack_connected() ) {
			return self::skipped_test(
				array(
					'name'              => $name,
					'short_description' => __( 'Jetpack is not connected. No master user to check.', 'jetpack' ),
				)
			);
		}
		if ( ! ( new Connection_Manager() )->get_connection_owner_id() ) {
			return self::skipped_test(
				array(
					'name'              => $name,
					'short_description' => __( 'Jetpack is running without a connected user. No master user to check.', 'jetpack' ),
				)
			);
		}
		$local_user = $this->helper_retrieve_local_master_user();

		if ( $local_user->exists() ) {
			$result = self::passing_test( array( 'name' => $name ) );
		} else {
			$connection_error = __( 'The user who setup the Jetpack connection no longer exists on this site.', 'jetpack' );

			$result = self::connection_failing_test( $name, $connection_error );
		}

		return $result;
	}

	/**
	 * Test that the master user has the manage options capability (e.g. is an admin).
	 *
	 * Generic calls from WP.com execute on Jetpack as the master user. If it isn't an admin, random things will fail.
	 *
	 * @return array Test results.
	 */
	protected function test__master_user_can_manage_options() {
		$name = __FUNCTION__;
		if ( ! $this->helper_is_jetpack_connected() ) {
			return self::skipped_test(
				array(
					'name'              => $name,
					'short_description' => __( 'Jetpack is not connected.', 'jetpack' ),
				)
			);
		}
		if ( ! ( new Connection_Manager() )->get_connection_owner_id() ) {
			return self::skipped_test(
				array(
					'name'              => $name,
					'short_description' => __( 'Jetpack is running without a connected user. No master user to check.', 'jetpack' ),
				)
			);
		}
		$master_user = $this->helper_retrieve_local_master_user();

		if ( user_can( $master_user, 'manage_options' ) ) {
			$result = self::passing_test( array( 'name' => $name ) );
		} else {
			/* translators: a WordPress username */
			$connection_error = sprintf( __( 'The user (%s) who setup the Jetpack connection is not an administrator.', 'jetpack' ), $master_user->user_login );
			/* translators: a WordPress username */
			$recommendation = sprintf( __( 'We recommend either upgrading the user (%s) or reconnecting Jetpack.', 'jetpack' ), $master_user->user_login );

			$result = self::connection_failing_test( $name, $connection_error, $recommendation );
		}

		return $result;
	}

	/**
	 * Test that the PHP's XML library is installed.
	 *
	 * While it should be installed by default, increasingly in PHP 7, some OSes require an additional php-xml package.
	 *
	 * @return array Test results.
	 */
	protected function test__xml_parser_available() {
		$name = __FUNCTION__;
		if ( function_exists( 'xml_parser_create' ) ) {
			$result = self::passing_test( array( 'name' => $name ) );
		} else {
			$result = self::failing_test(
				array(
					'name'              => $name,
					'label'             => __( 'PHP XML manipulation libraries are not available.', 'jetpack' ),
					'short_description' => __( 'Please ask your hosting provider to refer to our server requirements and enable PHP\'s XML module.', 'jetpack' ),
					'action_label'      => __( 'View our server requirements', 'jetpack' ),
					'action'            => Redirect::get_url( 'jetpack-support-server-requirements' ),
				)
			);
		}
		return $result;
	}

	/**
	 * Test that the server is able to send an outbound http communication.
	 *
	 * @return array Test results.
	 */
	protected function test__outbound_http() {
		$name    = __FUNCTION__;
		$request = wp_remote_get( preg_replace( '/^https:/', 'http:', JETPACK__API_BASE ) . 'test/1/' );
		$code    = wp_remote_retrieve_response_code( $request );

		if ( 200 === (int) $code ) {
			$result = self::passing_test( array( 'name' => $name ) );
		} else {
			$result = self::failing_test(
				array(
					'name'              => $name,
					'short_description' => $this->helper_enable_outbound_requests( 'HTTP' ),
				)
			);
		}

		return $result;
	}

	/**
	 * Test that the server is able to send an outbound https communication.
	 *
	 * @return array Test results.
	 */
	protected function test__outbound_https() {
		$name    = __FUNCTION__;
		$request = wp_remote_get( preg_replace( '/^http:/', 'https:', JETPACK__API_BASE ) . 'test/1/' );
		$code    = wp_remote_retrieve_response_code( $request );

		if ( 200 === (int) $code ) {
			$result = self::passing_test( array( 'name' => $name ) );
		} else {
			$result = self::failing_test(
				array(
					'name'              => $name,
					'short_description' => $this->helper_enable_outbound_requests( 'HTTPS' ),
				)
			);
		}

		return $result;
	}

	/**
	 * Check for an IDC.
	 *
	 * @return array Test results.
	 */
	protected function test__identity_crisis() {
		$name = __FUNCTION__;
		if ( ! $this->helper_is_jetpack_connected() ) {
			return self::skipped_test(
				array(
					'name'              => $name,
					'short_description' => __( 'Jetpack is not connected.', 'jetpack' ),
				)
			);
		}
		$identity_crisis = Jetpack::check_identity_crisis();

		if ( ! $identity_crisis ) {
			$result = self::passing_test( array( 'name' => $name ) );
		} else {
			$result = self::failing_test(
				array(
					'name'              => $name,
					'short_description' => sprintf(
						/* translators: Two URLs. The first is the locally-recorded value, the second is the value as recorded on WP.com. */
						__( 'Your url is set as `%1$s`, but your WordPress.com connection lists it as `%2$s`!', 'jetpack' ),
						$identity_crisis['home'],
						$identity_crisis['wpcom_home']
					),
					'action_label'      => $this->helper_get_support_text(),
					'action'            => $this->helper_get_support_url(),
				)
			);
		}
		return $result;
	}

	/**
	 * Tests the health of the Connection tokens.
	 *
	 * This will always check the blog token health. It will also check the user token health if
	 * a user is logged in and connected, or if there's a connected owner.
	 *
	 * @since 9.0.0
	 * @since 9.6.0 Checks only blog token if current user not connected or site does not have a connected owner.
	 *
	 * @return array Test results.
	 */
	protected function test__connection_token_health() {
		$name    = __FUNCTION__;
		$m       = new Connection_Manager();
		$user_id = get_current_user_id();

		// Check if there's a connected logged in user.
		if ( $user_id && ! $m->is_user_connected( $user_id ) ) {
				$user_id = false;
		}

		// If no logged in user to check, let's see if there's a master_user set.
		if ( ! $user_id ) {
				$user_id = Jetpack_Options::get_option( 'master_user' );
			if ( $user_id && ! $m->is_user_connected( $user_id ) ) {
				return self::connection_failing_test( $name, __( 'Missing token for the connection owner.', 'jetpack' ) );
			}
		}

		if ( $user_id ) {
			return $this->check_tokens_health( $user_id );
		} else {
			return $this->check_blog_token_health();
		}
	}

	/**
	 * Tests blog and user's token against wp.com's check-token-health endpoint.
	 *
	 * @since 9.6.0
	 *
	 * @return array Test results.
	 */
	protected function check_blog_token_health() {
		$name  = 'test__connection_token_health';
		$valid = ( new Tokens() )->validate_blog_token();

		if ( ! $valid ) {
			return self::connection_failing_test( $name, __( 'Blog token validation failed.', 'jetpack' ) );
		} else {
			return self::passing_test( array( 'name' => $name ) );
		}
	}

	/**
	 * Tests blog token against wp.com's check-token-health endpoint.
	 *
	 * @since 9.6.0
	 *
	 * @param int $user_id The user ID to check the tokens for.
	 *
	 * @return array Test results.
	 */
	protected function check_tokens_health( $user_id ) {
		$name             = 'test__connection_token_health';
		$validated_tokens = ( new Tokens() )->validate( $user_id );

		if ( ! is_array( $validated_tokens ) || count( array_diff_key( array_flip( array( 'blog_token', 'user_token' ) ), $validated_tokens ) ) ) {
			return self::skipped_test(
				array(
					'name'              => $name,
					'short_description' => __( 'Token health check failed to validate tokens.', 'jetpack' ),
				)
			);
		}

		$invalid_tokens_exist = false;
		foreach ( $validated_tokens as $validated_token ) {
			if ( ! $validated_token['is_healthy'] ) {
				$invalid_tokens_exist = true;
				break;
			}
		}

		if ( false === $invalid_tokens_exist ) {
			return self::passing_test( array( 'name' => $name ) );
		}

		$connection_error = __( 'Invalid Jetpack connection tokens.', 'jetpack' );

		return self::connection_failing_test( $name, $connection_error );
	}

	/**
	 * Tests connection status against wp.com's test-connection endpoint.
	 *
	 * @todo: Compare with the wpcom_self_test. We only need one of these.
	 *
	 * @return array Test results.
	 */
	protected function test__wpcom_connection_test() {
		$name = __FUNCTION__;

		$status = new Status();
		if ( ! Jetpack::is_connection_ready() || $status->is_offline_mode() || $status->is_staging_site() || ! $this->pass ) {
			return self::skipped_test( array( 'name' => $name ) );
		}

		add_filter( 'http_request_timeout', array( 'Jetpack_Cxn_Tests', 'increase_timeout' ) );
		$response = Client::wpcom_json_api_request_as_blog(
			sprintf( '/jetpack-blogs/%d/test-connection', Jetpack_Options::get_option( 'id' ) ),
			Client::WPCOM_JSON_API_VERSION
		);
		remove_filter( 'http_request_timeout', array( 'Jetpack_Cxn_Tests', 'increase_timeout' ) );

		if ( is_wp_error( $response ) ) {
			if ( false !== strpos( $response->get_error_message(), 'cURL error 28' ) ) { // Timeout.
				$result = self::skipped_test(
					array(
						'name'              => $name,
						'short_description' => self::helper_get_timeout_text(),
					)
				);
			} else {
				/* translators: %1$s is the error code, %2$s is the error message */
				$message = sprintf( __( 'Connection test failed (#%1$s: %2$s)', 'jetpack' ), $response->get_error_code(), $response->get_error_message() );

				$result = self::connection_failing_test( $name, $message );
			}

			return $result;
		}

		$body = wp_remote_retrieve_body( $response );
		if ( ! $body ) {
			return self::failing_test(
				array(
					'name'              => $name,
					'short_description' => __( 'Connection test failed (empty response body)', 'jetpack' ) . wp_remote_retrieve_response_code( $response ),
					'action_label'      => $this->helper_get_support_text(),
					'action'            => $this->helper_get_support_url(),
				)
			);
		}

		if ( 404 === wp_remote_retrieve_response_code( $response ) ) {
			return self::skipped_test(
				array(
					'name'              => $name,
					'short_description' => __( 'The WordPress.com API returned a 404 error.', 'jetpack' ),
				)
			);
		}

		$result       = json_decode( $body );
		$is_connected = ! empty( $result->connected );
		$message      = $result->message . ': ' . wp_remote_retrieve_response_code( $response );

		if ( $is_connected ) {
			$res = self::passing_test( array( 'name' => $name ) );
		} else {
			$res = self::connection_failing_test( $name, $message );
		}

		return $res;
	}

	/**
	 * Tests the port number to ensure it is an expected value.
	 *
	 * We expect that sites on be on one of:
	 * port 80,
	 * port 443 (https sites only),
	 * the value of JETPACK_SIGNATURE__HTTP_PORT,
	 * unless the site is intentionally on a different port (e.g. example.com:8080 is the site's URL).
	 *
	 * If the value isn't one of those and the site's URL doesn't include a port, then the signature verification will fail.
	 *
	 * This happens most commonly on sites with reverse proxies, so the edge (e.g. Varnish) is running on 80/443, but nginx
	 * or Apache is responding internally on a different port (e.g. 81).
	 *
	 * @return array Test results
	 */
	protected function test__server_port_value() {
		$name = __FUNCTION__;
		if ( ! isset( $_SERVER['HTTP_X_FORWARDED_PORT'] ) && ! isset( $_SERVER['SERVER_PORT'] ) ) {
			return self::skipped_test(
				array(
					'name'              => $name,
					'short_description' => __( 'The server port values are not defined. This is most common when running PHP via a CLI.', 'jetpack' ),
				)
			);
		}
		$site_port   = wp_parse_url( home_url(), PHP_URL_PORT );
		$server_port = isset( $_SERVER['HTTP_X_FORWARDED_PORT'] ) ? (int) $_SERVER['HTTP_X_FORWARDED_PORT'] : (int) $_SERVER['SERVER_PORT'];
		$http_ports  = array( 80 );
		$https_ports = array( 80, 443 );

		if ( defined( 'JETPACK_SIGNATURE__HTTP_PORT' ) ) {
			$http_ports[] = JETPACK_SIGNATURE__HTTP_PORT;
		}

		if ( defined( 'JETPACK_SIGNATURE__HTTPS_PORT' ) ) {
			$https_ports[] = JETPACK_SIGNATURE__HTTPS_PORT;
		}

		if ( $site_port ) {
			return self::skipped_test( array( 'name' => $name ) ); // Not currently testing for this situation.
		}

		if ( is_ssl() && in_array( $server_port, $https_ports, true ) ) {
			return self::passing_test( array( 'name' => $name ) );
		} elseif ( in_array( $server_port, $http_ports, true ) ) {
			return self::passing_test( array( 'name' => $name ) );
		} else {
			if ( is_ssl() ) {
				$needed_constant = 'JETPACK_SIGNATURE__HTTPS_PORT';
			} else {
				$needed_constant = 'JETPACK_SIGNATURE__HTTP_PORT';
			}
			return self::failing_test(
				array(
					'name'              => $name,
					'short_description' => sprintf(
						/* translators: %1$s - a PHP code snippet */
						__(
							'The server port value is unexpected.
						Try adding the following to your wp-config.php file: %1$s',
							'jetpack'
						),
						"define( '$needed_constant', $server_port )"
					),
				)
			);
		}
	}

	/**
	 * Full Sync Health Test.
	 *
	 * Sync Disabled: Results in a skipped test
	 * Not In Progress : Results in a skipped test
	 * In Progress: Results in skipped test w/ status in CLI
	 */
	protected function test__full_sync_health() {

		$name = __FUNCTION__;

		if ( ! $this->helper_is_jetpack_connected() ) {
			// If the site is not connected, there is no point in testing Sync health.
			return self::skipped_test(
				array(
					'name'                => $name,
					'show_in_site_health' => false,
				)
			);
		}

		// Sync is enabled.
		if ( Sync_Settings::is_sync_enabled() ) {

			// Get Full Sync Progress.
			$full_sync_module = Modules::get_module( 'full-sync' );
			$progress_percent = $full_sync_module ? $full_sync_module->get_sync_progress_percentage() : null;

			// Full Sync in Progress.
			if ( $progress_percent ) {

				return self::informational_test(
					array(
						'name'              => $name,
						'label'             => __( 'Jetpack is performing a full sync of your site', 'jetpack' ),
						'severity'          => 'recommended',
						/* translators: placeholder is a percentage number. */
						'short_description' => sprintf( __( 'Jetpack is performing a full sync of your site. Current Progress: %1$d %%', 'jetpack' ), $progress_percent ),
						'long_description'  => sprintf(
							'<p>%1$s</p><p><span class="dashicons dashicons-update"><span class="screen-reader-text">%2$s</span></span> %3$s</p><div class="jetpack-sync-progress-ui"><div class="jetpack-sync-progress-label"></div><div class="jetpack-sync-progress-bar"></div></div>',
							__( 'The information synced by Jetpack ensures that Jetpack Search, Related Posts and other features are aligned with your site’s current content.', 'jetpack' ), /* translators: screen reader text indicating data is updating. */
							__( 'Updating', 'jetpack' ),
							__( 'Jetpack is currently performing a full sync of your site data.', 'jetpack' )
						),
					)
				);

			} else {

				// no Full Sync in Progress.
				return self::skipped_test(
					array(
						'name'                => $name,
						'show_in_site_health' => false,
					)
				);

			}
		} else {

			// If sync is not enabled no Full Sync can occur.
			return self::skipped_test(
				array(
					'name'                => $name,
					'show_in_site_health' => false,
				)
			);

		}
	}

	/**
	 * Sync Health Tests.
	 *
	 * Disabled: Results in a failing test (recommended)
	 * Delayed: Results in failing test (recommended)
	 * Error: Results in failing test (critical)
	 */
	protected function test__sync_health() {

		$name = __FUNCTION__;

		if ( ! $this->helper_is_jetpack_connected() ) {
			// If the site is not connected, there is no point in testing Sync health.
			return self::skipped_test(
				array(
					'name'                => $name,
					'show_in_site_health' => false,
				)
			);
		}

		// Sync is enabled.
		if ( Sync_Settings::is_sync_enabled() ) {

			if ( Sync_Health::get_status() === Sync_Health::STATUS_OUT_OF_SYNC ) {
				/*
				 * Sync has experienced Data Loss.
				 */
				$description  = '<p>';
				$description .= esc_html__( 'The information synced by Jetpack ensures that Jetpack Search, Related Posts and other features are aligned with your site’s current content.', 'jetpack' );
				$description .= '</p>';
				$description .= '<p>';
				$description .= sprintf(
					'<span class="dashicons fail"><span class="screen-reader-text">%1$s</span></span> ',
					esc_html__( 'Error', 'jetpack' )
				);
				$description .= wp_kses(
					__( 'Jetpack has detected that data is not properly in sync which may be impacting some of your site’s functionality. <strong>Click <a id="full_sync_request_link" href="#">here</a> to start a fix</strong> to align Jetpack with your site data. If you still notice this error after running the fix process, please contact support for additional assistance.', 'jetpack' ),
					array(
						'a'      => array(
							'id'   => array(),
							'href' => array(),
						),
						'strong' => array(),
					)
				);
				$description .= '</p>';

				return self::failing_test(
					array(
						'name'              => $name,
						'label'             => __( 'Jetpack has detected an error syncing your site.', 'jetpack' ),
						'severity'          => 'critical',
						'action'            => Redirect::get_url( 'jetpack-contact-support' ),
						'action_label'      => __( 'Contact Jetpack Support', 'jetpack' ),
						'short_description' => __( 'Jetpack has detected that data is not properly in sync which may be impacting some of your site’s functionality. We recommend performing a fix to align Jetpack with your site data. If you still notice this error after running the fix process, please contact support for additional assistance.', 'jetpack' ),
						'long_description'  => $description,
					)
				);

			} else {
				// Get the Sync Queue.
				$sender     = Sync_Sender::get_instance();
				$sync_queue = $sender->get_sync_queue();

				// lag exceeds 5 minutes.
				if ( $sync_queue->lag() > 5 * MINUTE_IN_SECONDS ) {

					$description  = '<p>';
					$description .= esc_html__( 'The information synced by Jetpack ensures that Jetpack Search, Related Posts and other features are aligned with your site’s current content.', 'jetpack' );
					$description .= '</p>';
					$description .= '<p>';
					$description .= sprintf(
						'<span class="dashicons dashicons-clock" style="color: orange;"><span class="screen-reader-text">%1$s</span></span> ',
						/* translators: name, used to describe a clock icon. */
						esc_html__( 'Clock', 'jetpack' )
					);
					$description .= wp_kses(
						sprintf(
							/* translators: placeholder is a number of minutes. */
							_n(
								'Jetpack has identified a delay while syncing individual content updates. Certain features might be slower than usual, but this is only temporary while sync catches up with recent changes to your site. <strong>We’re seeing a current delay of %1$d minute.</strong>',
								'Jetpack has identified a delay while syncing individual content updates. Certain features might be slower than usual, but this is only temporary while sync catches up with recent changes to your site. <strong>We’re seeing a current delay of %1$d minutes.</strong>',
								(int) ( $sync_queue->lag() / MINUTE_IN_SECONDS ),
								'jetpack'
							),
							number_format_i18n( $sync_queue->lag() / MINUTE_IN_SECONDS )
						),
						array( 'strong' => array() )
					);
					$description .= '</p>';

					return self::informational_test(
						array(
							'name'              => $name,
							'label'             => __( 'Jetpack is experiencing a delay syncing your site.', 'jetpack' ),
							'severity'          => 'recommended',
							'action'            => null,
							'action_label'      => null,
							'short_description' => __( 'Jetpack is experiencing a delay syncing your site.', 'jetpack' ),
							'long_description'  => $description,
						)
					);

				} else {

					// Sync is Healthy.
					return self::passing_test( array( 'name' => $name ) );

				}
			}
		} else {
			/*
			 * Sync is disabled.
			 */

			$description  = '<p>';
			$description .= esc_html__( 'The information synced by Jetpack ensures that Jetpack Search, Related Posts and other features are aligned with your site’s current content.', 'jetpack' );
			$description .= '</p>';
			$description .= '<p>';
			$description .= __( 'Developers may enable / disable syncing using the Sync Settings API.', 'jetpack' );
			$description .= '</p>';
			$description .= '<p>';
			$description .= sprintf(
				'<span class="dashicons fail"><span class="screen-reader-text">%1$s</span></span> ',
				esc_html__( 'Error', 'jetpack' )
			);
			$description .= wp_kses(
				__( 'Jetpack Sync has been disabled on your site. Without it, certain Jetpack features will not work. <strong>We recommend enabling Sync.</strong>', 'jetpack' ),
				array( 'strong' => array() )
			);
			$description .= '</p>';

			return self::failing_test(
				array(
					'name'              => $name,
					'label'             => __( 'Jetpack Sync has been disabled on your site.', 'jetpack' ),
					'severity'          => 'recommended',
					'action'            => 'https://github.com/Automattic/jetpack/blob/trunk/projects/packages/sync/src/class-settings.php',
					'action_label'      => __( 'See Github for more on Sync Settings', 'jetpack' ),
					'short_description' => __( 'Jetpack Sync has been disabled on your site.', 'jetpack' ),
					'long_description'  => $description,
				)
			);

		}
	}

	/**
	 * Calls to WP.com to run the connection diagnostic testing suite.
	 *
	 * Intentionally added last as it will be skipped if any local failed conditions exist.
	 *
	 * @since 7.1.0
	 * @since 7.9.0 Timeout waiting for a WP.com response no longer fails the test. Test is marked skipped instead.
	 *
	 * @return array Test results.
	 */
	protected function last__wpcom_self_test() {
		$name = 'test__wpcom_self_test';

		$status = new Status();
		if ( ! Jetpack::is_connection_ready() || $status->is_offline_mode() || $status->is_staging_site() || ! $this->pass ) {
			return self::skipped_test( array( 'name' => $name ) );
		}

		$self_xml_rpc_url = site_url( 'xmlrpc.php' );

		$testsite_url = JETPACK__API_BASE . 'testsite/1/?url=';

		// 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.
		add_filter( 'http_request_timeout', array( 'Jetpack_Cxn_Tests', 'increase_timeout' ), PHP_INT_MAX - 1 );

		$response = wp_remote_get( $testsite_url . $self_xml_rpc_url );

		remove_filter( 'http_request_timeout', array( 'Jetpack_Cxn_Tests', 'increase_timeout' ), PHP_INT_MAX - 1 );

		if ( 200 === wp_remote_retrieve_response_code( $response ) ) {
			$result = self::passing_test( array( 'name' => $name ) );
		} elseif ( is_wp_error( $response ) && false !== strpos( $response->get_error_message(), 'cURL error 28' ) ) { // Timeout.
			$result = self::skipped_test(
				array(
					'name'              => $name,
					'short_description' => self::helper_get_timeout_text(),
				)
			);
		} else {
			$result = self::failing_test(
				array(
					'name'              => $name,
					'short_description' => sprintf(
						/* translators: %1$s - A debugging url */
						__( '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' ),
						Redirect::get_url( 'jetpack-support-debug', array( 'query' => 'url=' . rawurlencode( site_url() ) ) )
					),
					'action_label'      => $this->helper_get_support_text(),
					'action'            => $this->helper_get_support_url(),
				)
			);
		}

		return $result;
	}
}