Completed
Push — update/debugger-for-wp52-site-... ( d73c7a )
by
unknown
15:48 queued 08:59
created

Jetpack_Cxn_Test_Base::run_tests()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

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