Completed
Push — 3.7 ( 81b2d8...ef0909 )
by
unknown
09:42
created

ParameterConfirmationToken   A

Complexity

Total Complexity 36

Size/Duplication

Total Lines 234
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
dl 0
loc 234
rs 9.52
c 0
b 0
f 0
wmc 36
lcom 1
cbo 1

13 Methods

Rating   Name   Duplication   Size   Complexity  
A pathForToken() 0 3 1
A genToken() 0 11 1
A checkToken() 0 15 3
A __construct() 0 13 4
A getName() 0 3 1
A parameterProvided() 0 3 1
A tokenProvided() 0 3 1
A reloadRequired() 0 3 2
A suppress() 0 3 1
A params() 0 6 1
C currentAbsoluteURL() 0 43 14
A reloadWithToken() 0 20 3
A prepare_tokens() 0 12 3
1
<?php
2
3
/**
4
 * Class ParameterConfirmationToken
5
 *
6
 * When you need to use a dangerous GET parameter that needs to be set before core/Core.php is
7
 * established, this class takes care of allowing some other code of confirming the parameter,
8
 * by generating a one-time-use token & redirecting with that token included in the redirected URL
9
 *
10
 * WARNING: This class is experimental and designed specifically for use pre-startup in main.php
11
 * It will likely be heavily refactored before the release of 3.2
12
 *
13
 * @package framework
14
 * @subpackage misc
15
 */
16
class ParameterConfirmationToken {
17
18
	/**
19
	 * The name of the parameter
20
	 *
21
	 * @var string
22
	 */
23
	protected $parameterName = null;
24
25
	/**
26
	 * The parameter given
27
	 *
28
	 * @var string|null The string value, or null if not provided
29
	 */
30
	protected $parameter = null;
31
32
	/**
33
	 * The validated and checked token for this parameter
34
	 *
35
	 * @var string|null A string value, or null if either not provided or invalid
36
	 */
37
	protected $token = null;
38
39
	protected function pathForToken($token) {
40
		return TEMP_FOLDER.'/token_'.preg_replace('/[^a-z0-9]+/', '', $token);
41
	}
42
43
	/**
44
	 * Generate a new random token and store it
45
	 *
46
	 * @return string Token name
47
	 */
48
	protected function genToken() {
49
		// Generate a new random token (as random as possible)
50
		require_once(dirname(dirname(dirname(__FILE__))).'/security/RandomGenerator.php');
51
		$rg = new RandomGenerator();
52
		$token = $rg->randomToken('md5');
53
54
		// Store a file in the session save path (safer than /tmp, as open_basedir might limit that)
55
		file_put_contents($this->pathForToken($token), $token);
56
57
		return $token;
58
	}
59
60
	/**
61
	 * Validate a token
62
	 *
63
	 * @param string $token
64
	 * @return boolean True if the token is valid
65
	 */
66
	protected function checkToken($token) {
67
		if(!$token) {
68
			return false;
69
		}
70
71
		$file = $this->pathForToken($token);
72
		$content = null;
73
74
		if (file_exists($file)) {
75
			$content = file_get_contents($file);
76
			unlink($file);
77
		}
78
79
		return $content == $token;
80
	}
81
82
	/**
83
	 * Create a new ParameterConfirmationToken
84
	 *
85
	 * @param string $parameterName Name of the querystring parameter to check
86
	 */
87
	public function __construct($parameterName) {
0 ignored issues
show
Coding Style introduced by
__construct uses the super-global variable $_GET which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
88
		// Store the parameter name
89
		$this->parameterName = $parameterName;
90
91
		// Store the parameter value
92
		$this->parameter = isset($_GET[$parameterName]) ? $_GET[$parameterName] : null;
93
94
		// If the token provided is valid, mark it as such
95
		$token = isset($_GET[$parameterName.'token']) ? $_GET[$parameterName.'token'] : null;
96
		if ($this->checkToken($token)) {
97
			$this->token = $token;
98
		}
99
	}
100
101
	/**
102
	 * Get the name of this token
103
	 *
104
	 * @return string
105
	 */
106
	public function getName() {
107
		return $this->parameterName;
108
	}
109
110
	/**
111
	 * Is the parameter requested?
112
	 * ?parameter and ?parameter=1 are both considered requested
113
	 *
114
	 * @return bool
115
	 */
116
	public function parameterProvided() {
117
		return $this->parameter !== null;
118
	}
119
120
	/**
121
	 * Is the necessary token provided for this parameter?
122
	 * A value must be provided for the token
123
	 *
124
	 * @return bool
125
	 */
126
	public function tokenProvided() {
127
		return !empty($this->token);
128
	}
129
130
	/**
131
	 * Is this parameter requested without a valid token?
132
	 *
133
	 * @return bool True if the parameter is given without a valid token
134
	 */
135
	public function reloadRequired() {
136
		return $this->parameterProvided() && !$this->tokenProvided();
137
	}
138
139
	/**
140
	 * Suppress the current parameter by unsetting it from $_GET
141
	 */
142
	public function suppress() {
0 ignored issues
show
Coding Style introduced by
suppress uses the super-global variable $_GET which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
143
		unset($_GET[$this->parameterName]);
144
	}
145
146
	/**
147
	 * Determine the querystring parameters to include
148
	 *
149
	 * @return array List of querystring parameters with name and token parameters
150
	 */
151
	public function params() {
152
		return array(
153
			$this->parameterName => $this->parameter,
154
			$this->parameterName.'token' => $this->genToken()
155
		);
156
	}
157
158
	/** What to use instead of BASE_URL. Must not contain protocol or host. @var string */
159
	static public $alternateBaseURL = null;
160
161
	protected function currentAbsoluteURL() {
0 ignored issues
show
Coding Style introduced by
currentAbsoluteURL uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
162
		global $url;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
163
164
		// Are we http or https? Replicates Director::is_https() without its dependencies/
165
		$proto = 'http';
166
		// See https://en.wikipedia.org/wiki/List_of_HTTP_header_fields
167
		// See https://support.microsoft.com/?kbID=307347
168
		$headerOverride = false;
169
		if(TRUSTED_PROXY) {
170
			$headers = (defined('SS_TRUSTED_PROXY_PROTOCOL_HEADER')) ? array(SS_TRUSTED_PROXY_PROTOCOL_HEADER) : null;
171
			if(!$headers) {
172
				// Backwards compatible defaults
173
				$headers = array('HTTP_X_FORWARDED_PROTO', 'HTTP_X_FORWARDED_PROTOCOL', 'HTTP_FRONT_END_HTTPS');
174
			}
175
			foreach($headers as $header) {
176
				$headerCompareVal = ($header === 'HTTP_FRONT_END_HTTPS' ? 'on' : 'https');
177
				if(!empty($_SERVER[$header]) && strtolower($_SERVER[$header]) == $headerCompareVal) {
178
					$headerOverride = true;
179
					break;
180
				}
181
			}
182
		}
183
184
		if($headerOverride) {
185
			$proto = 'https';
186
		} else if((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off')) {
187
			$proto = 'https';
188
		} else if(isset($_SERVER['SSL'])) {
189
			$proto = 'https';
190
		}
191
192
		$parts = array_filter(array(
193
			// What's our host
194
			$_SERVER['HTTP_HOST'],
195
			// SilverStripe base
196
			self::$alternateBaseURL !== null ? self::$alternateBaseURL : BASE_URL,
197
			// And URL including base script (eg: if it's index.php/page/url/)
198
			(defined('BASE_SCRIPT_URL') ? '/' . BASE_SCRIPT_URL : '') . $url,
199
		));
200
201
		// Join together with protocol into our current absolute URL, avoiding duplicated "/" characters
202
		return "$proto://" . preg_replace('#/{2,}#', '/', implode('/', $parts));
203
	}
204
205
	/**
206
	 * Forces a reload of the request with the token included
207
	 * This method will terminate the script with `die`
208
	 */
209
	public function reloadWithToken() {
0 ignored issues
show
Coding Style introduced by
reloadWithToken uses the super-global variable $_GET which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
210
		$location = $this->currentAbsoluteURL();
211
212
		// What's our GET params (ensuring they include the original parameter + a new token)
213
		$params = array_merge($_GET, $this->params());
214
		unset($params['url']);
215
216
		if ($params) $location .= '?'.http_build_query($params);
0 ignored issues
show
Bug Best Practice introduced by
The expression $params of type array<string,string|null> 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...
217
218
		// And redirect
219
		if (headers_sent()) {
220
			echo "
221
<script>location.href='$location';</script>
222
<noscript><meta http-equiv='refresh' content='0; url=$location'></noscript>
223
You are being redirected. If you are not redirected soon, <a href='$location'>click here to continue the flush</a>
224
";
225
		}
226
		else header('location: '.$location, true, 302);
227
		die;
0 ignored issues
show
Coding Style Compatibility introduced by
The method reloadWithToken() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
228
	}
229
230
	/**
231
	 * Given a list of token names, suppress all tokens that have not been validated, and
232
	 * return the non-validated token with the highest priority
233
	 *
234
	 * @param array $keys List of token keys in ascending priority (low to high)
235
	 * @return ParameterConfirmationToken The token container for the unvalidated $key given with the highest priority
236
	 */
237
	public static function prepare_tokens($keys) {
238
		$target = null;
239
		foreach($keys as $key) {
240
			$token = new ParameterConfirmationToken($key);
241
			// Validate this token
242
			if($token->reloadRequired()) {
243
				$token->suppress();
244
				$target = $token;
245
			}
246
		}
247
		return $target;
248
	}
249
}
250