Completed
Push — fix/obnoxious-wording ( 3823e3...b19a82 )
by
unknown
53:14 queued 44:25
created

class.jetpack-signature.php (4 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
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...
4
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...
5
6
class Jetpack_Signature {
7
	public $token;
8
	public $secret;
9
10
	function __construct( $access_token, $time_diff = 0 ) {
11
		$secret = explode( '.', $access_token );
12
		if ( 2 != count( $secret ) )
13
			return;
14
15
		$this->token  = $secret[0];
16
		$this->secret = $secret[1];
17
		$this->time_diff = $time_diff;
0 ignored issues
show
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...
18
	}
19
20
	function sign_current_request( $override = array() ) {
21
		if ( isset( $override['scheme'] ) ) {
22
			$scheme = $override['scheme'];
23
			if ( !in_array( $scheme, array( 'http', 'https' ) ) ) {
24
				return new Jetpack_Error( 'invalid_sheme', 'Invalid URL scheme' );
25
			}
26
		} else {
27
			if ( is_ssl() ) {
28
				$scheme = 'https';
29
			} else {
30
				$scheme = 'http';
31
			}
32
		}
33
34
		if ( is_ssl() ) {
35
			$port = JETPACK_SIGNATURE__HTTPS_PORT == $_SERVER['SERVER_PORT'] ? '' : $_SERVER['SERVER_PORT'];
36
		} else {
37
			$port = JETPACK_SIGNATURE__HTTP_PORT  == $_SERVER['SERVER_PORT'] ? '' : $_SERVER['SERVER_PORT'];
38
		}
39
40
		$url = "{$scheme}://{$_SERVER['HTTP_HOST']}:{$port}" . stripslashes( $_SERVER['REQUEST_URI'] );
41
42
		if ( array_key_exists( 'body', $override ) && !is_null( $override['body'] ) ) {
43
			$body = $override['body'];
44
		} else if ( 'POST' == strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
45
			$body = isset( $GLOBALS['HTTP_RAW_POST_DATA'] ) ? $GLOBALS['HTTP_RAW_POST_DATA'] : null;
46
		} else {
47
			$body = null;
48
		}
49
50
		$a = array();
51
		foreach ( array( 'token', 'timestamp', 'nonce', 'body-hash' ) as $parameter ) {
52
			if ( isset( $override[$parameter] ) ) {
53
				$a[$parameter] = $override[$parameter];
54
			} else {
55
				$a[$parameter] = isset( $_GET[$parameter] ) ? stripslashes( $_GET[$parameter] ) : '';
56
			}
57
		}
58
59
		$method = isset( $override['method'] ) ? $override['method'] : $_SERVER['REQUEST_METHOD'];
60
		return $this->sign_request( $a['token'], $a['timestamp'], $a['nonce'], $a['body-hash'], $method, $url, $body, true );
61
	}
62
63
	// body_hash v. body-hash is annoying.  Refactor to accept an array?
64
	function sign_request( $token = '', $timestamp = 0, $nonce = '', $body_hash = '', $method = '', $url = '', $body = null, $verify_body_hash = true ) {
65
		if ( !$this->secret ) {
66
			return new Jetpack_Error( 'invalid_secret', 'Invalid secret' );
67
		}
68
69
		if ( !$this->token ) {
70
			return new Jetpack_Error( 'invalid_token', 'Invalid token' );
71
		}
72
73
		list( $token ) = explode( '.', $token );
74
75
		if ( 0 !== strpos( $token, "$this->token:" ) ) {
76
			return new Jetpack_Error( 'token_mismatch', 'Incorrect token' );
77
		}
78
79
		$required_parameters = array( 'token', 'timestamp', 'nonce', 'method', 'url' );
80 View Code Duplication
		if ( !is_null( $body ) ) {
81
			$required_parameters[] = 'body_hash';
82
			if ( !is_string( $body ) ) {
83
				return new Jetpack_Error( 'invalid_body', 'Body is malformed.' );
84
			}
85
		}
86
87
		foreach ( $required_parameters as $required ) {
88 View Code Duplication
			if ( !is_scalar( $$required ) ) {
89
				return new Jetpack_Error( 'invalid_signature', sprintf( 'The required "%s" parameter is malformed.', str_replace( '_', '-', $required ) ) );
90
			}
91
92 View Code Duplication
			if ( !strlen( $$required ) ) {
93
				return new Jetpack_Error( 'invalid_signature', sprintf( 'The required "%s" parameter is missing.', str_replace( '_', '-', $required ) ) );
94
			}
95
		}
96
97
		if ( is_null( $body ) ) {
98
			if ( $body_hash ) {
99
				return new Jetpack_Error( 'invalid_body_hash', 'The body hash does not match.' );
100
			}
101
		} else {
102
			if ( $verify_body_hash && jetpack_sha1_base64( $body ) !== $body_hash ) {
103
				return new Jetpack_Error( 'invalid_body_hash', 'The body hash does not match.' );
104
			}
105
		}
106
107
		$parsed = parse_url( $url );
108
		if ( !isset( $parsed['host'] ) ) {
109
			return new Jetpack_Error( 'invalid_signature', sprintf( 'The required "%s" parameter is malformed.', 'url' ) );
110
		}
111
112
		if ( !empty( $parsed['port'] ) ) {
113
			$port = $parsed['port'];
114
		} else {
115
			if ( 'http' == $parsed['scheme'] ) {
116
				$port = 80;
117
			} else if ( 'https' == $parsed['scheme'] ) {
118
				$port = 443;
119
			} else {
120
				return new Jetpack_Error( 'unknown_scheme_port', "The scheme's port is unknown" );
121
			}
122
		}
123
124
		if ( !ctype_digit( "$timestamp" ) || 10 < strlen( $timestamp ) ) { // If Jetpack is around in 275 years, you can blame mdawaffe for the bug.
125
			return new Jetpack_Error( 'invalid_signature', sprintf( 'The required "%s" parameter is malformed.', 'timestamp' ) );
126
		}
127
128
		$local_time = $timestamp - $this->time_diff;
129
		if ( $local_time < time() - 600 || $local_time > time() + 300 ) {
130
			return new Jetpack_Error( 'invalid_signature', 'The timestamp is too old.' );
131
		}
132
133
		if ( 12 < strlen( $nonce ) || preg_match( '/[^a-zA-Z0-9]/', $nonce ) ) {
134
			return new Jetpack_Error( 'invalid_signature', sprintf( 'The required "%s" parameter is malformed.', 'nonce' ) );
135
		}
136
137
		$normalized_request_pieces = array(
138
			$token,
139
			$timestamp,
140
			$nonce,
141
			$body_hash,
142
			strtoupper( $method ),
143
			strtolower( $parsed['host'] ),
144
			$port,
145
			$parsed['path'],
146
			// Normalized Query String
147
		);
148
149
		$normalized_request_pieces = array_merge( $normalized_request_pieces, $this->normalized_query_parameters( isset( $parsed['query'] ) ? $parsed['query'] : '' ) );
150
151
		$normalized_request_string = join( "\n", $normalized_request_pieces ) . "\n";
152
153
		return base64_encode( hash_hmac( 'sha1', $normalized_request_string, $this->secret, true ) );
154
	}
155
156
	function normalized_query_parameters( $query_string ) {
157
		parse_str( $query_string, $array );
158
		if ( get_magic_quotes_gpc() )
159
			$array = stripslashes_deep( $array );
160
161
		unset( $array['signature'] );
162
163
		$names  = array_keys( $array );
164
		$values = array_values( $array );
165
166
		$names  = array_map( array( $this, 'encode_3986' ), $names  );
167
		$values = array_map( array( $this, 'encode_3986' ), $values );
168
169
		$pairs  = array_map( array( $this, 'join_with_equal_sign' ), $names, $values );
0 ignored issues
show
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...
170
171
		sort( $pairs );
172
173
		return $pairs;
174
	}
175
176
	function encode_3986( $string ) {
177
		$string = rawurlencode( $string );
178
		return str_replace( '%7E', '~', $string ); // prior to PHP 5.3, rawurlencode was RFC 1738
179
	}
180
181
	function join_with_equal_sign( $name, $value ) {
182
		return "{$name}={$value}";
183
	}
184
}
185
186
function jetpack_sha1_base64( $text ) {
187
	return base64_encode( sha1( $text, true ) );
188
}
189