Completed
Push — renovate/webpack-cli-3.x ( 961c1b...02322b )
by
unknown
06:55
created

Jetpack_Cxn_Test_Base::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

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