Completed
Push — update/activity-log-links ( 92fe50...3b9362 )
by
unknown
12:21
created

jetpack-server-sandbox.php ➔ jetpack_server_sandbox()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
nc 4
nop 2
dl 0
loc 16
rs 9.4222
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * This feature is only useful for Automattic developers.
5
 * It configures Jetpack to talk to staging/sandbox servers
6
 * on WordPress.com instead of production servers.
7
 */
8
9
/**
10
 * @param string $sandbox Sandbox domain
11
 * @param string $url URL of request about to be made
12
 * @param array  $headers Headers of request about to be made
13
 * @return array [ 'url' => new URL, 'host' => new Host ]
14
 */
15
function jetpack_server_sandbox_request_parameters( $sandbox, $url, $headers ) {
16
	$host = '';
17
18
	$url_host = parse_url( $url, PHP_URL_HOST );
19
20
	switch ( $url_host ) {
21
	case 'public-api.wordpress.com' :
22
	case 'jetpack.wordpress.com' :
23
	case 'dashboard.wordpress.com' :
24
		$host = isset( $headers['Host'] ) ? $headers['Host'] : $url_host;
25
		$url = preg_replace(
26
			'@^(https?://)' . preg_quote( $url_host, '@' ) . '(?=[/?#].*|$)@',
27
			'\\1' . $sandbox,
28
			$url,
29
			1
30
		);
31
	}
32
33
	return compact( 'url', 'host' );
34
}
35
36
/**
37
 * Modifies parameters of request in order to send the request to the
38
 * server specified by `JETPACK__SANDBOX_DOMAIN`.
39
 *
40
 * Attached to the `requests-requests.before_request` filter.
41
 * @param string &$url URL of request about to be made
42
 * @param array  &$headers Headers of request about to be made
43
 * @return void
44
 */
45
function jetpack_server_sandbox( &$url, &$headers ) {
46
	if ( ! JETPACK__SANDBOX_DOMAIN ) {
47
		return;
48
	}
49
50
	$original_url = $url;
51
52
	$request_parameters = jetpack_server_sandbox_request_parameters( JETPACK__SANDBOX_DOMAIN, $url, $headers );
53
	$url = $request_parameters['url'];
54
	if ( $request_parameters['host'] ) {
55
		$headers['Host'] = $request_parameters['host'];
56
		if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
57
			error_log( sprintf( "SANDBOXING via '%s': '%s'", JETPACK__SANDBOX_DOMAIN, $original_url ) );
58
		}
59
	}
60
}
61
62
add_action( 'requests-requests.before_request', 'jetpack_server_sandbox', 10, 2 );
63