Completed
Push — add/paid-mention-blocks ( 0a325f...25129a )
by
unknown
08:03
created

Jetpack_Cxn_Test_Base::failing_test()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
nc 5
nop 5
dl 0
loc 24
rs 9.2248
c 0
b 0
f 0
1
<?php
2
use Automattic\Jetpack\Status;
3
4
/**
5
 * Jetpack Connection Testing
6
 *
7
 * Framework for various "unit tests" against the Jetpack connection.
8
 *
9
 * Individual tests should be added to the class-jetpack-cxn-tests.php file.
10
 *
11
 * @author Brandon Kraft
12
 * @package Jetpack
13
 */
14
15
/**
16
 * "Unit Tests" for the Jetpack connection.
17
 *
18
 * @since 7.1.0
19
 */
20
class Jetpack_Cxn_Test_Base {
21
22
	/**
23
	 * Tests to run on the Jetpack connection.
24
	 *
25
	 * @var array $tests
26
	 */
27
	protected $tests = array();
28
29
	/**
30
	 * Results of the Jetpack connection tests.
31
	 *
32
	 * @var array $results
33
	 */
34
	protected $results = array();
35
36
	/**
37
	 * Status of the testing suite.
38
	 *
39
	 * Used internally to determine if a test should be skipped since the tests are already failing. Assume passing.
40
	 *
41
	 * @var bool $pass
42
	 */
43
	protected $pass = true;
44
45
	/**
46
	 * Jetpack_Cxn_Test constructor.
47
	 */
48
	public function __construct() {
49
		$this->tests   = array();
50
		$this->results = array();
51
	}
52
53
	/**
54
	 * Adds a new test to the Jetpack Connection Testing suite.
55
	 *
56
	 * @since 7.1.0
57
	 * @since 7.3.0 Adds name parameter and returns WP_Error on failure.
58
	 *
59
	 * @param callable $callable Test to add to queue.
60
	 * @param string   $name Unique name for the test.
61
	 * @param string   $type   Optional. Core Site Health type: 'direct' if test can be run during initial load or 'async' if test should run async.
62
	 * @param array    $groups Optional. Testing groups to add test to.
63
	 *
64
	 * @return mixed True if successfully added. WP_Error on failure.
65
	 */
66
	public function add_test( $callable, $name, $type = 'direct', $groups = array( 'default' ) ) {
67
		if ( is_array( $name ) ) {
68
			// Pre-7.3.0 method passed the $groups parameter here.
69
			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...
70
		}
71
		if ( array_key_exists( $name, $this->tests ) ) {
72
			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...
73
		}
74
		if ( ! is_callable( $callable ) ) {
75
			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...
76
		}
77
78
		$this->tests[ $name ] = array(
79
			'name'  => $name,
80
			'test'  => $callable,
81
			'group' => $groups,
82
			'type'  => $type,
83
		);
84
		return true;
85
	}
86
87
	/**
88
	 * Lists all tests to run.
89
	 *
90
	 * @since 7.3.0
91
	 *
92
	 * @param string $type Optional. Core Site Health type: 'direct' or 'async'. All by default.
93
	 * @param string $group Optional. A specific testing group. All by default.
94
	 *
95
	 * @return array $tests Array of tests with test information.
96
	 */
97
	public function list_tests( $type = 'all', $group = 'all' ) {
98
		if ( ! ( 'all' === $type || 'direct' === $type || 'async' === $type ) ) {
99
			_doing_it_wrong( 'Jetpack_Cxn_Test_Base->list_tests', 'Type must be all, direct, or async', '7.3.0' );
100
		}
101
102
		$tests = array();
103
		foreach ( $this->tests as $name => $value ) {
104
			// Get all valid tests by group staged.
105
			if ( 'all' === $group || $group === $value['group'] ) {
106
				$tests[ $name ] = $value;
107
			}
108
109
			// Next filter out any that do not match the type.
110
			if ( 'all' !== $type && $type !== $value['type'] ) {
111
				unset( $tests[ $name ] );
112
			}
113
		}
114
115
		return $tests;
116
	}
117
118
	/**
119
	 * Run a specific test.
120
	 *
121
	 * @since 7.3.0
122
	 *
123
	 * @param string $name Name of test.
124
	 *
125
	 * @return mixed $result Test result array or WP_Error if invalid name. {
126
	 * @type string $name Test name
127
	 * @type mixed  $pass True if passed, false if failed, 'skipped' if skipped.
128
	 * @type string $message Human-readable test result message.
129
	 * @type string $resolution Human-readable resolution steps.
130
	 * }
131
	 */
132
	public function run_test( $name ) {
133
		if ( array_key_exists( $name, $this->tests ) ) {
134
			return call_user_func( $this->tests[ $name ]['test'] );
135
		}
136
		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...
137
	}
138
139
	/**
140
	 * Runs the Jetpack connection suite.
141
	 */
142
	public function run_tests() {
143
		foreach ( $this->tests as $test ) {
144
			$result          = call_user_func( $test['test'] );
145
			$result['group'] = $test['group'];
146
			$result['type']  = $test['type'];
147
			$this->results[] = $result;
148
			if ( false === $result['pass'] ) {
149
				$this->pass = false;
150
			}
151
		}
152
	}
153
154
	/**
155
	 * Returns the full results array.
156
	 *
157
	 * @since 7.1.0
158
	 * @since 7.3.0 Add 'type'
159
	 *
160
	 * @param string $type  Test type, async or direct.
161
	 * @param string $group Testing group whose results we want. Defaults to all tests.
162
	 * @return array Array of test results.
163
	 */
164
	public function raw_results( $type = 'all', $group = 'all' ) {
165
		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...
166
			$this->run_tests();
167
		}
168
169
		$results = $this->results;
170
171
		if ( 'all' !== $group ) {
172
			foreach ( $results as $test => $result ) {
173
				if ( ! in_array( $group, $result['group'], true ) ) {
174
					unset( $results[ $test ] );
175
				}
176
			}
177
		}
178
179
		if ( 'all' !== $type ) {
180
			foreach ( $results as $test => $result ) {
181
				if ( $type !== $result['type'] ) {
182
					unset( $results[ $test ] );
183
				}
184
			}
185
		}
186
187
		return $results;
188
	}
189
190
	/**
191
	 * Returns the status of the connection suite.
192
	 *
193
	 * @since 7.1.0
194
	 * @since 7.3.0 Add 'type'
195
	 *
196
	 * @param string $type  Test type, async or direct. Optional, direct all tests.
197
	 * @param string $group Testing group to check status of. Optional, default all tests.
198
	 *
199
	 * @return true|array True if all tests pass. Array of failed tests.
200
	 */
201
	public function pass( $type = 'all', $group = 'all' ) {
202
		$results = $this->raw_results( $type, $group );
203
204
		foreach ( $results as $result ) {
205
			// 'pass' could be true, false, or 'skipped'. We only want false.
206
			if ( isset( $result['pass'] ) && false === $result['pass'] ) {
207
				return false;
208
			}
209
		}
210
211
		return true;
212
213
	}
214
215
	/**
216
	 * Return array of failed test messages.
217
	 *
218
	 * @since 7.1.0
219
	 * @since 7.3.0 Add 'type'
220
	 *
221
	 * @param string $type  Test type, direct or async.
222
	 * @param string $group Testing group whose failures we want. Defaults to "all".
223
	 *
224
	 * @return false|array False if no failed tests. Otherwise, array of failed tests.
225
	 */
226
	public function list_fails( $type = 'all', $group = 'all' ) {
227
		$results = $this->raw_results( $type, $group );
228
229
		foreach ( $results as $test => $result ) {
230
			// We do not want tests that passed or ones that are misconfigured (no pass status or no failure message).
231
			if ( ! isset( $result['pass'] ) || false !== $result['pass'] || ! isset( $result['message'] ) ) {
232
				unset( $results[ $test ] );
233
			}
234
		}
235
236
		return $results;
237
	}
238
239
	/**
240
	 * Helper function to return consistent responses for a passing test.
241
	 *
242
	 * @param string $name Test name.
243
	 *
244
	 * @return array Test results.
245
	 */
246 View Code Duplication
	public static function passing_test( $name = 'Unnamed' ) {
247
		return array(
248
			'name'       => $name,
249
			'pass'       => true,
250
			'message'    => __( 'Test Passed!', 'jetpack' ),
251
			'resolution' => false,
252
			'severity'   => false,
253
		);
254
	}
255
256
	/**
257
	 * Helper function to return consistent responses for a skipped test.
258
	 *
259
	 * @param string $name Test name.
260
	 * @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...
261
	 *
262
	 * @return array Test results.
263
	 */
264 View Code Duplication
	public static function skipped_test( $name = 'Unnamed', $message = false ) {
265
		return array(
266
			'name'       => $name,
267
			'pass'       => 'skipped',
268
			'message'    => $message,
269
			'resolution' => false,
270
			'severity'   => false,
271
		);
272
	}
273
274
	/**
275
	 * Helper function to return consistent responses for a failing test.
276
	 *
277
	 * @since 7.1.0
278
	 * @since 7.3.0 Added $action for resolution action link, $severity for issue severity.
279
	 *
280
	 * @param string $name Test name.
281
	 * @param string $message Message detailing the failure.
282
	 * @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...
283
	 * @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...
284
	 * @param string $severity Optional. "critical" or "recommended" for failure stats. "good" for passing.
285
	 *
286
	 * @return array Test results.
287
	 */
288
	public static function failing_test( $name, $message, $resolution = false, $action = false, $severity = 'critical' ) {
289
		// Provide standard resolutions steps, but allow pass-through of non-standard ones.
290
		switch ( $resolution ) {
291
			case 'cycle_connection':
292
				$resolution = __( 'Please disconnect and reconnect Jetpack.', 'jetpack' ); // @todo: Link.
293
				break;
294
			case 'outbound_requests':
295
				$resolution = __( 'Please ask your hosting provider to confirm your server can make outbound requests to jetpack.com.', 'jetpack' );
296
				break;
297
			case 'support':
298
			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...
299
				$resolution = __( 'Please contact Jetpack support.', 'jetpack' ); // @todo: Link to support.
300
				break;
301
		}
302
303
		return array(
304
			'name'       => $name,
305
			'pass'       => false,
306
			'message'    => $message,
307
			'resolution' => $resolution,
308
			'action'     => $action,
309
			'severity'   => $severity,
310
		);
311
	}
312
313
	/**
314
	 * Provide WP_CLI friendly testing results.
315
	 *
316
	 * @since 7.1.0
317
	 * @since 7.3.0 Add 'type'
318
	 *
319
	 * @param string $type  Test type, direct or async.
320
	 * @param string $group Testing group whose results we are outputting. Default all tests.
321
	 */
322
	public function output_results_for_cli( $type = 'all', $group = 'all' ) {
323
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
324
			if ( ( new Status() )->is_development_mode() ) {
325
				WP_CLI::line( __( 'Jetpack is in Development Mode:', 'jetpack' ) );
326
				WP_CLI::line( Jetpack::development_mode_trigger_text() );
327
			}
328
			WP_CLI::line( __( 'TEST RESULTS:', 'jetpack' ) );
329
			foreach ( $this->raw_results( $group ) as $test ) {
330
				if ( true === $test['pass'] ) {
331
					WP_CLI::log( WP_CLI::colorize( '%gPassed:%n  ' . $test['name'] ) );
332
				} elseif ( 'skipped' === $test['pass'] ) {
333
					WP_CLI::log( WP_CLI::colorize( '%ySkipped:%n ' . $test['name'] ) );
334
					if ( $test['message'] ) {
335
						WP_CLI::log( '         ' . $test['message'] ); // Number of spaces to "tab indent" the reason.
336
					}
337
				} else { // Failed.
338
					WP_CLI::log( WP_CLI::colorize( '%rFailed:%n  ' . $test['name'] ) );
339
					WP_CLI::log( '         ' . $test['message'] ); // Number of spaces to "tab indent" the reason.
340
				}
341
			}
342
		}
343
	}
344
345
	/**
346
	 * Output results of failures in format expected by Core's Site Health tool for async tests.
347
	 *
348
	 * Specifically not asking for a testing group since we're opinionated that Site Heath should see all.
349
	 *
350
	 * @since 7.3.0
351
	 *
352
	 * @return array Array of test results
353
	 */
354
	public function output_results_for_core_async_site_health() {
355
		$result = array(
356
			'label'       => __( 'Jetpack passed all async tests.', 'jetpack' ),
357
			'status'      => 'good',
358
			'badge'       => array(
359
				'label' => __( 'Jetpack', 'jetpack' ),
360
				'color' => 'green',
361
			),
362
			'description' => sprintf(
363
				'<p>%s</p>',
364
				__( "Jetpack's async local testing suite passed all tests!", 'jetpack' )
365
			),
366
			'actions'     => '',
367
			'test'        => 'jetpack_debugger_local_testing_suite_core',
368
		);
369
370
		if ( $this->pass() ) {
371
			return $result;
372
		}
373
374
		$fails = $this->list_fails( 'async' );
375
		$error = false;
376
		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...
377
			if ( ! $error ) {
378
				$error                 = true;
379
				$result['label']       = $fail['message'];
380
				$result['status']      = $fail['severity'];
381
				$result['description'] = sprintf(
382
					'<p>%s</p>',
383
					$fail['resolution']
384
				);
385 View Code Duplication
				if ( ! empty( $fail['action'] ) ) {
386
					$result['actions'] = sprintf(
387
						'<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>',
388
						esc_url( $fail['action'] ),
389
						__( 'Resolve', 'jetpack' ),
390
						/* translators: accessibility text */
391
						__( '(opens in a new tab)', 'jetpack' )
392
					);
393
				}
394
			} else {
395
				$result['description'] .= sprintf(
396
					'<p>%s</p>',
397
					__( 'There was another problem:', 'jetpack' )
398
				) . ' ' . $fail['message'] . ': ' . $fail['resolution'];
399
				if ( 'critical' === $fail['severity'] ) { // In case the initial failure is only "recommended".
400
					$result['status'] = 'critical';
401
				}
402
			}
403
		}
404
405
		return $result;
406
407
	}
408
409
	/**
410
	 * Provide single WP Error instance of all failures.
411
	 *
412
	 * @since 7.1.0
413
	 * @since 7.3.0 Add 'type'
414
	 *
415
	 * @param string $type  Test type, direct or async.
416
	 * @param string $group Testing group whose failures we want converted. Default all tests.
417
	 *
418
	 * @return WP_Error|false WP_Error with all failed tests or false if there were no failures.
419
	 */
420
	public function output_fails_as_wp_error( $type = 'all', $group = 'all' ) {
421
		if ( $this->pass( $group ) ) {
422
			return false;
423
		}
424
		$fails = $this->list_fails( $type, $group );
425
		$error = false;
426
427
		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...
428
			$code    = 'failed_' . $result['name'];
429
			$message = $result['message'];
430
			$data    = array(
431
				'resolution' => $result['resolution'],
432
			);
433
			if ( ! $error ) {
434
				$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...
435
			} else {
436
				$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...
437
			}
438
		}
439
440
		return $error;
441
	}
442
443
	/**
444
	 * Encrypt data for sending to WordPress.com.
445
	 *
446
	 * @todo When PHP minimum is 5.3+, add cipher detection to use an agreed better cipher than RC4. RC4 should be the last resort.
447
	 *
448
	 * @param string $data Data to encrypt with the WP.com Public Key.
449
	 *
450
	 * @return false|array False if functionality not available. Array of encrypted data, encryption key.
451
	 */
452
	public function encrypt_string_for_wpcom( $data ) {
453
		$return = false;
454
		if ( ! function_exists( 'openssl_get_publickey' ) || ! function_exists( 'openssl_seal' ) ) {
455
			return $return;
456
		}
457
458
		$public_key = openssl_get_publickey( JETPACK__DEBUGGER_PUBLIC_KEY );
459
460
		if ( $public_key && openssl_seal( $data, $encrypted_data, $env_key, array( $public_key ) ) ) {
461
			// We are returning base64-encoded values to ensure they're characters we can use in JSON responses without issue.
462
			$return = array(
463
				'data'   => base64_encode( $encrypted_data ), // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
464
				'key'    => base64_encode( $env_key[0] ), // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
465
				'cipher' => 'RC4', // When Jetpack's minimum WP version is at PHP 5.3+, we will add in detecting and using a stronger one.
466
			);
467
		}
468
469
		openssl_free_key( $public_key );
470
471
		return $return;
472
	}
473
}
474