Completed
Push — fix/normalize-www-in-site-url-... ( e67e76 )
by
unknown
13:13 queued 02:59
created

Jetpack_Signature::encode_3986()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 1
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
3
// These constants can be set in wp-config.php to ensure sites behind proxies will still work.
4
// Setting these constants, though, is *not* the preferred method. It's better to configure
5
// the proxy to send the X-Forwarded-Port header.
6
defined( 'JETPACK_SIGNATURE__HTTP_PORT'  ) or define( 'JETPACK_SIGNATURE__HTTP_PORT' , 80  );
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
7
defined( 'JETPACK_SIGNATURE__HTTPS_PORT' ) or define( 'JETPACK_SIGNATURE__HTTPS_PORT', 443 );
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
8
defined( 'JETPACK__WPCOM_JSON_API_HOST' )  or define( 'JETPACK__WPCOM_JSON_API_HOST', 'public-api.wordpress.com' );
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
9
10
class Jetpack_Signature {
11
	public $token;
12
	public $secret;
13
14
	function __construct( $access_token, $time_diff = 0 ) {
15
		$secret = explode( '.', $access_token );
16
		if ( 2 != count( $secret ) )
17
			return;
18
19
		$this->token  = $secret[0];
20
		$this->secret = $secret[1];
21
		$this->time_diff = $time_diff;
0 ignored issues
show
Bug introduced by
The property time_diff does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
22
	}
23
24
	function sign_current_request( $override = array() ) {
25
		if ( isset( $override['scheme'] ) ) {
26
			$scheme = $override['scheme'];
27
			if ( !in_array( $scheme, array( 'http', 'https' ) ) ) {
28
				return new Jetpack_Error( 'invalid_sheme', 'Invalid URL scheme' );
29
			}
30
		} else {
31
			if ( is_ssl() ) {
32
				$scheme = 'https';
33
			} else {
34
				$scheme = 'http';
35
			}
36
		}
37
38
		$host_port = isset( $_SERVER['HTTP_X_FORWARDED_PORT'] ) ? $_SERVER['HTTP_X_FORWARDED_PORT'] : $_SERVER['SERVER_PORT'];
39
40
		if ( is_ssl() ) {
41
			// 443: Standard Port
42
			// 80: Assume we're behind a proxy without X-Forwarded-Port. Hardcoding "80" here means most sites
43
			//     with SSL termination proxies (self-served, Cloudflare, etc.) don't need to fiddle with
44
			//     the JETPACK_SIGNATURE__HTTPS_PORT constant. The code also implies we can't talk to a
45
			//     site at https://example.com:80/ (which would be a strange configuration).
46
			// JETPACK_SIGNATURE__HTTPS_PORT: Set this constant in wp-config.php to the backend webserver's port
47
			//                                if the site is behind a proxy running on port 443 without
48
			//                                X-Forwarded-Port and the backend's port is *not* 80. It's better,
49
			//                                though, to configure the proxy to send X-Forwarded-Port.
50
			$port = in_array( $host_port, array( 443, 80, JETPACK_SIGNATURE__HTTPS_PORT ) ) ? '' : $host_port;
51
		} else {
52
			// 80: Standard Port
53
			// JETPACK_SIGNATURE__HTTPS_PORT: Set this constant in wp-config.php to the backend webserver's port
54
			//                                if the site is behind a proxy running on port 80 without
55
			//                                X-Forwarded-Port. It's better, though, to configure the proxy to
56
			//                                send X-Forwarded-Port.
57
			$port = in_array( $host_port, array( 80, JETPACK_SIGNATURE__HTTP_PORT ) ) ? '' : $host_port;
58
		}
59
60
		$url = "{$scheme}://{$_SERVER['HTTP_HOST']}:{$port}" . stripslashes( $_SERVER['REQUEST_URI'] );
61
62
		if ( array_key_exists( 'body', $override ) && !is_null( $override['body'] ) ) {
63
			$body = $override['body'];
64
		} else if ( 'POST' == strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
65
			$body = isset( $GLOBALS['HTTP_RAW_POST_DATA'] ) ? $GLOBALS['HTTP_RAW_POST_DATA'] : null;
66
		} else {
67
			$body = null;
68
		}
69
70
		$a = array();
71
		foreach ( array( 'token', 'timestamp', 'nonce', 'body-hash' ) as $parameter ) {
72
			if ( isset( $override[$parameter] ) ) {
73
				$a[$parameter] = $override[$parameter];
74
			} else {
75
				$a[$parameter] = isset( $_GET[$parameter] ) ? stripslashes( $_GET[$parameter] ) : '';
76
			}
77
		}
78
79
		$method = isset( $override['method'] ) ? $override['method'] : $_SERVER['REQUEST_METHOD'];
80
		return $this->sign_request( $a['token'], $a['timestamp'], $a['nonce'], $a['body-hash'], $method, $url, $body, true );
81
	}
82
83
	// body_hash v. body-hash is annoying.  Refactor to accept an array?
84
	function sign_request( $token = '', $timestamp = 0, $nonce = '', $body_hash = '', $method = '', $url = '', $body = null, $verify_body_hash = true ) {
85
		if ( !$this->secret ) {
86
			return new Jetpack_Error( 'invalid_secret', 'Invalid secret' );
87
		}
88
89
		if ( !$this->token ) {
90
			return new Jetpack_Error( 'invalid_token', 'Invalid token' );
91
		}
92
93
		list( $token ) = explode( '.', $token );
94
95
		if ( 0 !== strpos( $token, "$this->token:" ) ) {
96
			return new Jetpack_Error( 'token_mismatch', 'Incorrect token' );
97
		}
98
99
		$required_parameters = array( 'token', 'timestamp', 'nonce', 'method', 'url' );
100 View Code Duplication
		if ( !is_null( $body ) ) {
101
			$required_parameters[] = 'body_hash';
102
			if ( !is_string( $body ) ) {
103
				return new Jetpack_Error( 'invalid_body', 'Body is malformed.' );
104
			}
105
		}
106
107
		foreach ( $required_parameters as $required ) {
108 View Code Duplication
			if ( !is_scalar( $$required ) ) {
109
				return new Jetpack_Error( 'invalid_signature', sprintf( 'The required "%s" parameter is malformed.', str_replace( '_', '-', $required ) ) );
110
			}
111
112 View Code Duplication
			if ( !strlen( $$required ) ) {
113
				return new Jetpack_Error( 'invalid_signature', sprintf( 'The required "%s" parameter is missing.', str_replace( '_', '-', $required ) ) );
114
			}
115
		}
116
117
		if ( is_null( $body ) ) {
118
			if ( $body_hash ) {
119
				return new Jetpack_Error( 'invalid_body_hash', 'The body hash does not match.' );
120
			}
121
		} else {
122
			if ( $verify_body_hash && jetpack_sha1_base64( $body ) !== $body_hash ) {
123
				return new Jetpack_Error( 'invalid_body_hash', 'The body hash does not match.' );
124
			}
125
		}
126
127
		$parsed = parse_url( $url );
128
		if ( !isset( $parsed['host'] ) ) {
129
			return new Jetpack_Error( 'invalid_signature', sprintf( 'The required "%s" parameter is malformed.', 'url' ) );
130
		}
131
132
		if ( $parsed['host'] === JETPACK__WPCOM_JSON_API_HOST ) {
133
			$parsed['host'] = 'public-api.wordpress.com';
134
		}
135
136
		if ( !empty( $parsed['port'] ) ) {
137
			$port = $parsed['port'];
138
		} else {
139
			if ( 'http' == $parsed['scheme'] ) {
140
				$port = 80;
141
			} else if ( 'https' == $parsed['scheme'] ) {
142
				$port = 443;
143
			} else {
144
				return new Jetpack_Error( 'unknown_scheme_port', "The scheme's port is unknown" );
145
			}
146
		}
147
148
		if ( !ctype_digit( "$timestamp" ) || 10 < strlen( $timestamp ) ) { // If Jetpack is around in 275 years, you can blame mdawaffe for the bug.
149
			return new Jetpack_Error( 'invalid_signature', sprintf( 'The required "%s" parameter is malformed.', 'timestamp' ) );
150
		}
151
152
		$local_time = $timestamp - $this->time_diff;
153
		if ( $local_time < time() - 600 || $local_time > time() + 300 ) {
154
			return new Jetpack_Error( 'invalid_signature', 'The timestamp is too old.' );
155
		}
156
157
		if ( 12 < strlen( $nonce ) || preg_match( '/[^a-zA-Z0-9]/', $nonce ) ) {
158
			return new Jetpack_Error( 'invalid_signature', sprintf( 'The required "%s" parameter is malformed.', 'nonce' ) );
159
		}
160
161
		$normalized_request_pieces = array(
162
			$token,
163
			$timestamp,
164
			$nonce,
165
			$body_hash,
166
			strtoupper( $method ),
167
			strtolower( $parsed['host'] ),
168
			$port,
169
			$parsed['path'],
170
			// Normalized Query String
171
		);
172
173
		$normalized_request_pieces = array_merge( $normalized_request_pieces, $this->normalized_query_parameters( isset( $parsed['query'] ) ? $parsed['query'] : '' ) );
174
175
		$normalized_request_string = join( "\n", $normalized_request_pieces ) . "\n";
176
177
		return base64_encode( hash_hmac( 'sha1', $normalized_request_string, $this->secret, true ) );
178
	}
179
180
	function normalized_query_parameters( $query_string ) {
181
		parse_str( $query_string, $array );
182
		if ( get_magic_quotes_gpc() )
183
			$array = stripslashes_deep( $array );
184
185
		unset( $array['signature'] );
186
187
		$names  = array_keys( $array );
188
		$values = array_values( $array );
189
190
		$names  = array_map( array( $this, 'encode_3986' ), $names  );
191
		$values = array_map( array( $this, 'encode_3986' ), $values );
192
193
		$pairs  = array_map( array( $this, 'join_with_equal_sign' ), $names, $values );
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned correctly; expected 1 space but found 2 spaces

This check looks for improperly formatted assignments.

Every assignment must have exactly one space before and one space after the equals operator.

To illustrate:

$a = "a";
$ab = "ab";
$abc = "abc";

will have no issues, while

$a   = "a";
$ab  = "ab";
$abc = "abc";

will report issues in lines 1 and 2.

Loading history...
194
195
		sort( $pairs );
196
197
		return $pairs;
198
	}
199
200
	function encode_3986( $string ) {
201
		$string = rawurlencode( $string );
0 ignored issues
show
Coding Style introduced by
Consider using a different name than the parameter $string. This often makes code more readable.
Loading history...
202
		return str_replace( '%7E', '~', $string ); // prior to PHP 5.3, rawurlencode was RFC 1738
203
	}
204
205
	function join_with_equal_sign( $name, $value ) {
206
		return "{$name}={$value}";
207
	}
208
}
209
210
function jetpack_sha1_base64( $text ) {
211
	return base64_encode( sha1( $text, true ) );
212
}
213