Completed
Push — add/rest-api-sandbox-const ( f30538 )
by
unknown
12:18
created

Jetpack_Signature   B

Complexity

Total Complexity 46

Size/Duplication

Total Lines 183
Duplicated Lines 6.56 %

Coupling/Cohesion

Components 1
Dependencies 1
Metric Value
wmc 46
lcom 1
cbo 1
dl 12
loc 183
rs 8.3999

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 9 2
F sign_current_request() 0 42 15
F sign_request() 12 95 25
A normalized_query_parameters() 0 19 2
A encode_3986() 0 4 1
A join_with_equal_sign() 0 3 1

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like Jetpack_Signature often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Jetpack_Signature, and based on these observations, apply Extract Interface, too.

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
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...
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 ( $parsed['host'] === JETPACK__WPCOM_JSON_API_HOST ) {
113
			$parsed['host'] = 'public-api.wordpress.com';
114
		}
115
116
		if ( !empty( $parsed['port'] ) ) {
117
			$port = $parsed['port'];
118
		} else {
119
			if ( 'http' == $parsed['scheme'] ) {
120
				$port = 80;
121
			} else if ( 'https' == $parsed['scheme'] ) {
122
				$port = 443;
123
			} else {
124
				return new Jetpack_Error( 'unknown_scheme_port', "The scheme's port is unknown" );
125
			}
126
		}
127
128
		if ( !ctype_digit( "$timestamp" ) || 10 < strlen( $timestamp ) ) { // If Jetpack is around in 275 years, you can blame mdawaffe for the bug.
129
			return new Jetpack_Error( 'invalid_signature', sprintf( 'The required "%s" parameter is malformed.', 'timestamp' ) );
130
		}
131
132
		$local_time = $timestamp - $this->time_diff;
133
		if ( $local_time < time() - 600 || $local_time > time() + 300 ) {
134
			return new Jetpack_Error( 'invalid_signature', 'The timestamp is too old.' );
135
		}
136
137
		if ( 12 < strlen( $nonce ) || preg_match( '/[^a-zA-Z0-9]/', $nonce ) ) {
138
			return new Jetpack_Error( 'invalid_signature', sprintf( 'The required "%s" parameter is malformed.', 'nonce' ) );
139
		}
140
141
		$normalized_request_pieces = array(
142
			$token,
143
			$timestamp,
144
			$nonce,
145
			$body_hash,
146
			strtoupper( $method ),
147
			strtolower( $parsed['host'] ),
148
			$port,
149
			$parsed['path'],
150
			// Normalized Query String
151
		);
152
153
		$normalized_request_pieces = array_merge( $normalized_request_pieces, $this->normalized_query_parameters( isset( $parsed['query'] ) ? $parsed['query'] : '' ) );
154
155
		$normalized_request_string = join( "\n", $normalized_request_pieces ) . "\n";
156
157
		return base64_encode( hash_hmac( 'sha1', $normalized_request_string, $this->secret, true ) );
158
	}
159
160
	function normalized_query_parameters( $query_string ) {
161
		parse_str( $query_string, $array );
162
		if ( get_magic_quotes_gpc() )
163
			$array = stripslashes_deep( $array );
164
165
		unset( $array['signature'] );
166
167
		$names  = array_keys( $array );
168
		$values = array_values( $array );
169
170
		$names  = array_map( array( $this, 'encode_3986' ), $names  );
171
		$values = array_map( array( $this, 'encode_3986' ), $values );
172
173
		$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...
174
175
		sort( $pairs );
176
177
		return $pairs;
178
	}
179
180
	function encode_3986( $string ) {
181
		$string = rawurlencode( $string );
182
		return str_replace( '%7E', '~', $string ); // prior to PHP 5.3, rawurlencode was RFC 1738
183
	}
184
185
	function join_with_equal_sign( $name, $value ) {
186
		return "{$name}={$value}";
187
	}
188
}
189
190
function jetpack_sha1_base64( $text ) {
191
	return base64_encode( sha1( $text, true ) );
192
}
193