Completed
Push — update/site-health-connection ( a2bbd3 )
by
unknown
26:04 queued 19:26
created

Jetpack_Cxn_Test_Base::failing_test()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 29

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
nc 6
nop 7
dl 0
loc 29
rs 8.8337
c 0
b 0
f 0
1
<?php
2
/**
3
 * Base class for Jetpack's debugging tests.
4
 *
5
 * @package Jetpack.
6
 */
7
8
use Automattic\Jetpack\Status;
9
10
/**
11
 * Jetpack Connection Testing
12
 *
13
 * Framework for various "unit tests" against the Jetpack connection.
14
 *
15
 * Individual tests should be added to the class-jetpack-cxn-tests.php file.
16
 *
17
 * @author Brandon Kraft
18
 * @package Jetpack
19
 */
20
21
/**
22
 * "Unit Tests" for the Jetpack connection.
23
 *
24
 * @since 7.1.0
25
 */
26
class Jetpack_Cxn_Test_Base {
27
28
	/**
29
	 * Tests to run on the Jetpack connection.
30
	 *
31
	 * @var array $tests
32
	 */
33
	protected $tests = array();
34
35
	/**
36
	 * Results of the Jetpack connection tests.
37
	 *
38
	 * @var array $results
39
	 */
40
	protected $results = array();
41
42
	/**
43
	 * Status of the testing suite.
44
	 *
45
	 * Used internally to determine if a test should be skipped since the tests are already failing. Assume passing.
46
	 *
47
	 * @var bool $pass
48
	 */
49
	protected $pass = true;
50
51
	/**
52
	 * Jetpack_Cxn_Test constructor.
53
	 */
54
	public function __construct() {
55
		$this->tests   = array();
56
		$this->results = array();
57
	}
58
59
	/**
60
	 * Adds a new test to the Jetpack Connection Testing suite.
61
	 *
62
	 * @since 7.1.0
63
	 * @since 7.3.0 Adds name parameter and returns WP_Error on failure.
64
	 *
65
	 * @param callable $callable Test to add to queue.
66
	 * @param string   $name Unique name for the test.
67
	 * @param string   $type   Optional. Core Site Health type: 'direct' if test can be run during initial load or 'async' if test should run async.
68
	 * @param array    $groups Optional. Testing groups to add test to.
69
	 *
70
	 * @return mixed True if successfully added. WP_Error on failure.
71
	 */
72
	public function add_test( $callable, $name, $type = 'direct', $groups = array( 'default' ) ) {
73
		if ( is_array( $name ) ) {
74
			// Pre-7.3.0 method passed the $groups parameter here.
75
			return new WP_Error( __( 'add_test arguments changed in 7.3.0. Please reference inline documentation.', 'jetpack' ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with __('add_test arguments c...mentation.', 'jetpack').

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
76
		}
77
		if ( array_key_exists( $name, $this->tests ) ) {
78
			return new WP_Error( __( 'Test names must be unique.', 'jetpack' ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with __('Test names must be unique.', 'jetpack').

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
79
		}
80
		if ( ! is_callable( $callable ) ) {
81
			return new WP_Error( __( 'Tests must be valid PHP callables.', 'jetpack' ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with __('Tests must be valid ...callables.', 'jetpack').

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
82
		}
83
84
		$this->tests[ $name ] = array(
85
			'name'  => $name,
86
			'test'  => $callable,
87
			'group' => $groups,
88
			'type'  => $type,
89
		);
90
		return true;
91
	}
92
93
	/**
94
	 * Lists all tests to run.
95
	 *
96
	 * @since 7.3.0
97
	 *
98
	 * @param string $type Optional. Core Site Health type: 'direct' or 'async'. All by default.
99
	 * @param string $group Optional. A specific testing group. All by default.
100
	 *
101
	 * @return array $tests Array of tests with test information.
102
	 */
103
	public function list_tests( $type = 'all', $group = 'all' ) {
104
		if ( ! ( 'all' === $type || 'direct' === $type || 'async' === $type ) ) {
105
			_doing_it_wrong( 'Jetpack_Cxn_Test_Base->list_tests', 'Type must be all, direct, or async', '7.3.0' );
106
		}
107
108
		$tests = array();
109
		foreach ( $this->tests as $name => $value ) {
110
			// Get all valid tests by group staged.
111
			if ( 'all' === $group || $group === $value['group'] ) {
112
				$tests[ $name ] = $value;
113
			}
114
115
			// Next filter out any that do not match the type.
116
			if ( 'all' !== $type && $type !== $value['type'] ) {
117
				unset( $tests[ $name ] );
118
			}
119
		}
120
121
		return $tests;
122
	}
123
124
	/**
125
	 * Run a specific test.
126
	 *
127
	 * @since 7.3.0
128
	 *
129
	 * @param string $name Name of test.
130
	 *
131
	 * @return mixed $result Test result array or WP_Error if invalid name. {
132
	 * @type string $name Test name
133
	 * @type mixed  $pass True if passed, false if failed, 'skipped' if skipped.
134
	 * @type string $message Human-readable test result message.
135
	 * @type string $resolution Human-readable resolution steps.
136
	 * }
137
	 */
138
	public function run_test( $name ) {
139
		if ( array_key_exists( $name, $this->tests ) ) {
140
			return call_user_func( $this->tests[ $name ]['test'] );
141
		}
142
		return new WP_Error( __( 'There is no test by that name: ', 'jetpack' ) . $name );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with __('There is no test by ...: ', 'jetpack') . $name.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
143
	}
144
145
	/**
146
	 * Runs the Jetpack connection suite.
147
	 */
148
	public function run_tests() {
149
		foreach ( $this->tests as $test ) {
150
			$result          = call_user_func( $test['test'] );
151
			$result['group'] = $test['group'];
152
			$result['type']  = $test['type'];
153
			$this->results[] = $result;
154
			if ( false === $result['pass'] ) {
155
				$this->pass = false;
156
			}
157
		}
158
	}
159
160
	/**
161
	 * Returns the full results array.
162
	 *
163
	 * @since 7.1.0
164
	 * @since 7.3.0 Add 'type'
165
	 *
166
	 * @param string $type  Test type, async or direct.
167
	 * @param string $group Testing group whose results we want. Defaults to all tests.
168
	 * @return array Array of test results.
169
	 */
170
	public function raw_results( $type = 'all', $group = 'all' ) {
171
		if ( ! $this->results ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->results of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
172
			$this->run_tests();
173
		}
174
175
		$results = $this->results;
176
177
		if ( 'all' !== $group ) {
178
			foreach ( $results as $test => $result ) {
179
				if ( ! in_array( $group, $result['group'], true ) ) {
180
					unset( $results[ $test ] );
181
				}
182
			}
183
		}
184
185
		if ( 'all' !== $type ) {
186
			foreach ( $results as $test => $result ) {
187
				if ( $type !== $result['type'] ) {
188
					unset( $results[ $test ] );
189
				}
190
			}
191
		}
192
193
		return $results;
194
	}
195
196
	/**
197
	 * Returns the status of the connection suite.
198
	 *
199
	 * @since 7.1.0
200
	 * @since 7.3.0 Add 'type'
201
	 *
202
	 * @param string $type  Test type, async or direct. Optional, direct all tests.
203
	 * @param string $group Testing group to check status of. Optional, default all tests.
204
	 *
205
	 * @return true|array True if all tests pass. Array of failed tests.
206
	 */
207
	public function pass( $type = 'all', $group = 'all' ) {
208
		$results = $this->raw_results( $type, $group );
209
210
		foreach ( $results as $result ) {
211
			// 'pass' could be true, false, or 'skipped'. We only want false.
212
			if ( isset( $result['pass'] ) && false === $result['pass'] ) {
213
				return false;
214
			}
215
		}
216
217
		return true;
218
219
	}
220
221
	/**
222
	 * Return array of failed test messages.
223
	 *
224
	 * @since 7.1.0
225
	 * @since 7.3.0 Add 'type'
226
	 *
227
	 * @param string $type  Test type, direct or async.
228
	 * @param string $group Testing group whose failures we want. Defaults to "all".
229
	 *
230
	 * @return false|array False if no failed tests. Otherwise, array of failed tests.
231
	 */
232
	public function list_fails( $type = 'all', $group = 'all' ) {
233
		$results = $this->raw_results( $type, $group );
234
235
		foreach ( $results as $test => $result ) {
236
			// We do not want tests that passed or ones that are misconfigured (no pass status or no failure message).
237
			if ( ! isset( $result['pass'] ) || false !== $result['pass'] || ! isset( $result['message'] ) ) {
238
				unset( $results[ $test ] );
239
			}
240
		}
241
242
		return $results;
243
	}
244
245
	/**
246
	 * Helper function to return consistent responses for a passing test.
247
	 *
248
	 * @param string      $name Test name.
249
	 * @param string|bool $message Message to show when test passed.
250
	 * @param string|bool $label Label to be used on Site Health card.
251
	 *
252
	 * @return array Test results.
253
	 */
254
	public static function passing_test( $name = 'Unnamed', $message = false, $label = false ) {
255
		if ( ! $message ) {
256
			$message = __( 'Test Passed!', 'jetpack' );
257
		}
258
		return array(
259
			'name'       => $name,
260
			'pass'       => true,
261
			'message'    => $message,
262
			'resolution' => false,
263
			'severity'   => false,
264
			'label'      => $label,
265
		);
266
	}
267
268
	/**
269
	 * Helper function to return consistent responses for a skipped test.
270
	 *
271
	 * @param string $name Test name.
272
	 * @param string $message Reason for skipping the test. Optional.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $message not be false|string?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
273
	 *
274
	 * @return array Test results.
275
	 */
276
	public static function skipped_test( $name = 'Unnamed', $message = false ) {
277
		return array(
278
			'name'       => $name,
279
			'pass'       => 'skipped',
280
			'message'    => $message,
281
			'resolution' => false,
282
			'severity'   => false,
283
		);
284
	}
285
286
	/**
287
	 * Helper function to return consistent responses for a failing test.
288
	 *
289
	 * @since 7.1.0
290
	 * @since 7.3.0 Added $action for resolution action link, $severity for issue severity.
291
	 *
292
	 * @param string $name Test name.
293
	 * @param string $message Message detailing the failure.
294
	 * @param string $resolution Optional. Steps to resolve.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $resolution not be false|string?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
295
	 * @param string $action Optional. URL to direct users to self-resolve.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $action not be false|string?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
296
	 * @param string $severity Optional. "critical" or "recommended" for failure stats. "good" for passing.
297
	 * @param string $label Optional. The label to use instead of the test name.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $label not be false|string?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
298
	 * @param string $action_label Optional. The label for the action url instead of default 'Resolve'.
299
	 *
300
	 * @return array Test results.
301
	 */
302
	public static function failing_test( $name, $message, $resolution = false, $action = false, $severity = 'critical', $label = false, $action_label = 'Resolve' ) {
303
		// Provide standard resolutions steps, but allow pass-through of non-standard ones.
304
		switch ( $resolution ) {
305
			case 'connect_jetpack':
306
				$resolution = false;
307
				break;
308
			case 'cycle_connection':
309
				$resolution = __( 'Please disconnect and reconnect Jetpack.', 'jetpack' ); // @todo: Link.
310
				break;
311
			case 'outbound_requests':
312
				$resolution = __( 'Please ask your hosting provider to confirm your server can make outbound requests to jetpack.com.', 'jetpack' );
313
				break;
314
			case 'support':
315
			case false:
0 ignored issues
show
Bug introduced by
It seems like you are loosely comparing $resolution of type false|string against false; this is ambiguous if the string can be empty. Consider using a strict comparison === instead.
Loading history...
316
				$resolution = __( 'Please contact Jetpack support.', 'jetpack' ); // @todo: Link to support.
317
				break;
318
		}
319
320
		return array(
321
			'name'         => $name,
322
			'pass'         => false,
323
			'message'      => $message,
324
			'resolution'   => $resolution,
325
			'action'       => $action,
326
			'severity'     => $severity,
327
			'label'        => $label,
328
			'action_label' => $action_label,
329
		);
330
	}
331
332
	/**
333
	 * Provide WP_CLI friendly testing results.
334
	 *
335
	 * @since 7.1.0
336
	 * @since 7.3.0 Add 'type'
337
	 *
338
	 * @param string $type  Test type, direct or async.
339
	 * @param string $group Testing group whose results we are outputting. Default all tests.
340
	 */
341
	public function output_results_for_cli( $type = 'all', $group = 'all' ) {
342
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
343
			if ( ( new Status() )->is_development_mode() ) {
344
				WP_CLI::line( __( 'Jetpack is in Development Mode:', 'jetpack' ) );
345
				WP_CLI::line( Jetpack::development_mode_trigger_text() );
346
			}
347
			WP_CLI::line( __( 'TEST RESULTS:', 'jetpack' ) );
348
			foreach ( $this->raw_results( $group ) as $test ) {
349
				if ( true === $test['pass'] ) {
350
					WP_CLI::log( WP_CLI::colorize( '%gPassed:%n  ' . $test['name'] ) );
351
				} elseif ( 'skipped' === $test['pass'] ) {
352
					WP_CLI::log( WP_CLI::colorize( '%ySkipped:%n ' . $test['name'] ) );
353
					if ( $test['message'] ) {
354
						WP_CLI::log( '         ' . $test['message'] ); // Number of spaces to "tab indent" the reason.
355
					}
356
				} else { // Failed.
357
					WP_CLI::log( WP_CLI::colorize( '%rFailed:%n  ' . $test['name'] ) );
358
					WP_CLI::log( '         ' . $test['message'] ); // Number of spaces to "tab indent" the reason.
359
				}
360
			}
361
		}
362
	}
363
364
	/**
365
	 * Output results of failures in format expected by Core's Site Health tool for async tests.
366
	 *
367
	 * Specifically not asking for a testing group since we're opinionated that Site Heath should see all.
368
	 *
369
	 * @since 7.3.0
370
	 *
371
	 * @return array Array of test results
372
	 */
373
	public function output_results_for_core_async_site_health() {
374
		$result = array(
375
			'label'       => __( 'Jetpack passed all async tests.', 'jetpack' ),
376
			'status'      => 'good',
377
			'badge'       => array(
378
				'label' => __( 'Jetpack', 'jetpack' ),
379
				'color' => 'green',
380
			),
381
			'description' => sprintf(
382
				'<p>%s</p>',
383
				__( "Jetpack's async local testing suite passed all tests!", 'jetpack' )
384
			),
385
			'actions'     => '',
386
			'test'        => 'jetpack_debugger_local_testing_suite_core',
387
		);
388
389
		if ( $this->pass() ) {
390
			return $result;
391
		}
392
393
		$fails = $this->list_fails( 'async' );
394
		$error = false;
395
		foreach ( $fails as $fail ) {
0 ignored issues
show
Bug introduced by
The expression $fails of type false|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
396
			if ( ! $error ) {
397
				$error                 = true;
398
				$result['label']       = $fail['message'];
399
				$result['status']      = $fail['severity'];
400
				$result['description'] = sprintf(
401
					'<p>%s</p>',
402
					$fail['resolution']
403
				);
404 View Code Duplication
				if ( ! empty( $fail['action'] ) ) {
405
					$result['actions'] = sprintf(
406
						'<a class="button button-primary" href="%1$s" target="_blank" rel="noopener noreferrer">%2$s <span class="screen-reader-text">%3$s</span><span aria-hidden="true" class="dashicons dashicons-external"></span></a>',
407
						esc_url( $fail['action'] ),
408
						__( 'Resolve', 'jetpack' ),
409
						/* translators: accessibility text */
410
						__( '(opens in a new tab)', 'jetpack' )
411
					);
412
				}
413
			} else {
414
				$result['description'] .= sprintf(
415
					'<p>%s</p>',
416
					__( 'There was another problem:', 'jetpack' )
417
				) . ' ' . $fail['message'] . ': ' . $fail['resolution'];
418
				if ( 'critical' === $fail['severity'] ) { // In case the initial failure is only "recommended".
419
					$result['status'] = 'critical';
420
				}
421
			}
422
		}
423
424
		return $result;
425
426
	}
427
428
	/**
429
	 * Provide single WP Error instance of all failures.
430
	 *
431
	 * @since 7.1.0
432
	 * @since 7.3.0 Add 'type'
433
	 *
434
	 * @param string $type  Test type, direct or async.
435
	 * @param string $group Testing group whose failures we want converted. Default all tests.
436
	 *
437
	 * @return WP_Error|false WP_Error with all failed tests or false if there were no failures.
438
	 */
439
	public function output_fails_as_wp_error( $type = 'all', $group = 'all' ) {
440
		if ( $this->pass( $group ) ) {
441
			return false;
442
		}
443
		$fails = $this->list_fails( $type, $group );
444
		$error = false;
445
446
		foreach ( $fails as $result ) {
0 ignored issues
show
Bug introduced by
The expression $fails of type false|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
447
			$code    = 'failed_' . $result['name'];
448
			$message = $result['message'];
449
			$data    = array(
450
				'resolution' => $result['resolution'],
451
			);
452
			if ( ! $error ) {
453
				$error = new WP_Error( $code, $message, $data );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with $code.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
454
			} else {
455
				$error->add( $code, $message, $data );
0 ignored issues
show
Bug introduced by
The method add() does not seem to exist on object<WP_Error>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
456
			}
457
		}
458
459
		return $error;
460
	}
461
462
	/**
463
	 * Encrypt data for sending to WordPress.com.
464
	 *
465
	 * @todo When PHP minimum is 5.3+, add cipher detection to use an agreed better cipher than RC4. RC4 should be the last resort.
466
	 *
467
	 * @param string $data Data to encrypt with the WP.com Public Key.
468
	 *
469
	 * @return false|array False if functionality not available. Array of encrypted data, encryption key.
470
	 */
471
	public function encrypt_string_for_wpcom( $data ) {
472
		$return = false;
473
		if ( ! function_exists( 'openssl_get_publickey' ) || ! function_exists( 'openssl_seal' ) ) {
474
			return $return;
475
		}
476
477
		$public_key = openssl_get_publickey( JETPACK__DEBUGGER_PUBLIC_KEY );
478
479
		if ( $public_key && openssl_seal( $data, $encrypted_data, $env_key, array( $public_key ) ) ) {
480
			// We are returning base64-encoded values to ensure they're characters we can use in JSON responses without issue.
481
			$return = array(
482
				'data'   => base64_encode( $encrypted_data ), // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
483
				'key'    => base64_encode( $env_key[0] ), // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
484
				'cipher' => 'RC4', // When Jetpack's minimum WP version is at PHP 5.3+, we will add in detecting and using a stronger one.
485
			);
486
		}
487
488
		openssl_free_key( $public_key );
489
490
		return $return;
491
	}
492
}
493