Completed
Pull Request — 3.1 (#5200)
by Daniel
12:18
created

ParameterConfirmationToken::checkToken()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 15
rs 9.4285
cc 3
eloc 9
nc 3
nop 1
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
class ParameterConfirmationToken {
14
15
	/**
16
	 * The name of the parameter
17
	 *
18
	 * @var string
19
	 */
20
	protected $parameterName = null;
21
22
	/**
23
	 * The parameter given
24
	 *
25
	 * @var string|null The string value, or null if not provided
26
	 */
27
	protected $parameter = null;
28
29
	/**
30
	 * The validated and checked token for this parameter
31
	 *
32
	 * @var string|null A string value, or null if either not provided or invalid
33
	 */
34
	protected $token = null;
35
36
	protected function pathForToken($token) {
37
		return TEMP_FOLDER.'/token_'.preg_replace('/[^a-z0-9]+/', '', $token);
38
	}
39
40
	/**
41
	 * Generate a new random token and store it
42
	 *
43
	 * @return string Token name
44
	 */
45
	protected function genToken() {
46
		// Generate a new random token (as random as possible)
47
		require_once(dirname(dirname(dirname(__FILE__))).'/security/RandomGenerator.php');
48
		$rg = new RandomGenerator();
49
		$token = $rg->randomToken('md5');
50
51
		// Store a file in the session save path (safer than /tmp, as open_basedir might limit that)
52
		file_put_contents($this->pathForToken($token), $token);
53
54
		return $token;
55
	}
56
57
	/**
58
	 * Validate a token
59
	 *
60
	 * @param string $token
61
	 * @return boolean True if the token is valid
62
	 */
63
	protected function checkToken($token) {
64
		if(!$token) {
65
			return false;
66
		}
67
		
68
		$file = $this->pathForToken($token);
69
		$content = null;
70
71
		if (file_exists($file)) {
72
			$content = file_get_contents($file);
73
			unlink($file);
74
		}
75
76
		return $content == $token;
77
	}
78
79
	/**
80
	 * Create a new ParameterConfirmationToken
81
	 *
82
	 * @param string $parameterName Name of the querystring parameter to check
83
	 */
84
	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...
85
		// Store the parameter name
86
		$this->parameterName = $parameterName;
87
		
88
		// Store the parameter value
89
		$this->parameter = isset($_GET[$parameterName]) ? $_GET[$parameterName] : null;
90
91
		// If the token provided is valid, mark it as such
92
		$token = isset($_GET[$parameterName.'token']) ? $_GET[$parameterName.'token'] : null;
93
		if ($this->checkToken($token)) {
94
			$this->token = $token;
95
		}
96
	}
97
98
	/**
99
	 * Get the name of this token
100
	 * 
101
	 * @return string
102
	 */
103
	public function getName() {
104
		return $this->parameterName;
105
	}
106
107
	/**
108
	 * Is the parameter requested?
109
	 * ?parameter and ?parameter=1 are both considered requested
110
	 * 
111
	 * @return bool
112
	 */
113
	public function parameterProvided() {
114
		return $this->parameter !== null;
115
	}
116
117
	/**
118
	 * Is the necessary token provided for this parameter?
119
	 * A value must be provided for the token
120
	 * 
121
	 * @return bool
122
	 */
123
	public function tokenProvided() {
124
		return !empty($this->token);
125
	}
126
127
	/**
128
	 * Is this parameter requested without a valid token?
129
	 * 
130
	 * @return bool True if the parameter is given without a valid token
131
	 */
132
	public function reloadRequired() {
133
		return $this->parameterProvided() && !$this->tokenProvided();
134
	}
135
136
	/**
137
	 * Suppress the current parameter by unsetting it from $_GET
138
	 */
139
	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...
140
		unset($_GET[$this->parameterName]);
141
	}
142
143
	/**
144
	 * Determine the querystring parameters to include
145
	 *
146
	 * @return array List of querystring parameters with name and token parameters
147
	 */
148
	public function params() {
149
		return array(
150
			$this->parameterName => $this->parameter,
151
			$this->parameterName.'token' => $this->genToken()
152
		);
153
	}
154
155
	/** What to use instead of BASE_URL. Must not contain protocol or host. @var string */
156
	static public $alternateBaseURL = null;
157
158
	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...
159
		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...
160
161
		// Are we http or https? Replicates Director::is_https() without its dependencies/
162
		$proto = 'http';
163
		// See https://en.wikipedia.org/wiki/List_of_HTTP_header_fields
164
		// See https://support.microsoft.com/?kbID=307347
165
		$headerOverride = false;
166
		if(TRUSTED_PROXY) {
167
			$headers = (defined('SS_TRUSTED_PROXY_PROTOCOL_HEADER')) ? array(SS_TRUSTED_PROXY_PROTOCOL_HEADER) : null;
168
			if(!$headers) {
169
				// Backwards compatible defaults
170
				$headers = array('HTTP_X_FORWARDED_PROTO', 'HTTP_X_FORWARDED_PROTOCOL', 'HTTP_FRONT_END_HTTPS');
171
			}
172
			foreach($headers as $header) {
173
				$headerCompareVal = ($header === 'HTTP_FRONT_END_HTTPS' ? 'on' : 'https');
174
				if(!empty($_SERVER[$header]) && strtolower($_SERVER[$header]) == $headerCompareVal) {
175
					$headerOverride = true;
176
					break;
177
				}
178
			}
179
		}
180
181
		if($headerOverride) {
182
			$proto = 'https';
183
		} else if((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off')) {
184
			$proto = 'https';
185
		} else if(isset($_SERVER['SSL'])) {
186
			$proto = 'https';
187
		}
188
189
		$parts = array_filter(array(
190
			// What's our host
191
			$_SERVER['HTTP_HOST'],
192
			// SilverStripe base
193
			self::$alternateBaseURL !== null ? self::$alternateBaseURL : BASE_URL,
194
			// And URL including base script (eg: if it's index.php/page/url/)
195
			(defined('BASE_SCRIPT_URL') ? '/' . BASE_SCRIPT_URL : '') . $url,
196
		));
197
198
		// Join together with protocol into our current absolute URL, avoiding duplicated "/" characters
199
		return "$proto://" . preg_replace('#/{2,}#', '/', implode('/', $parts));
200
	}
201
202
	/**
203
	 * Forces a reload of the request with the token included
204
	 * This method will terminate the script with `die`
205
	 */
206
	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...
207
		$location = $this->currentAbsoluteURL();
208
209
		// What's our GET params (ensuring they include the original parameter + a new token)
210
		$params = array_merge($_GET, $this->params());
211
		unset($params['url']);
212
213
		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...
214
215
		// And redirect
216
		if (headers_sent()) {
217
			echo "
218
<script>location.href='$location';</script>
219
<noscript><meta http-equiv='refresh' content='0; url=$location'></noscript>
220
You are being redirected. If you are not redirected soon, <a href='$location'>click here to continue the flush</a>
221
";
222
		}
223
		else header('location: '.$location, true, 302);
224
		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...
225
	}
226
227
	/**
228
	 * Given a list of token names, suppress all tokens that have not been validated, and 
229
	 * return the non-validated token with the highest priority
230
	 * 
231
	 * @param array $keys List of token keys in ascending priority (low to high)
232
	 * @return ParameterConfirmationToken The token container for the unvalidated $key given with the highest priority
233
	 */
234
	public static function prepare_tokens($keys) {
235
		$target = null;
236
		foreach($keys as $key) {
237
			$token = new ParameterConfirmationToken($key);
238
			// Validate this token
239
			if($token->reloadRequired()) {
240
				$token->suppress();
241
				$target = $token;
242
			}
243
		}
244
		return $target;
245
	}
246
}
247