Completed
Branch master (86dc85)
by
unknown
23:45
created

WebRequest::overrideRequestId()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 3
rs 10
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
/**
3
 * Deal with importing all those nasty globals and things
4
 *
5
 * Copyright © 2003 Brion Vibber <[email protected]>
6
 * https://www.mediawiki.org/
7
 *
8
 * This program is free software; you can redistribute it and/or modify
9
 * it under the terms of the GNU General Public License as published by
10
 * the Free Software Foundation; either version 2 of the License, or
11
 * (at your option) any later version.
12
 *
13
 * This program is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16
 * GNU General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU General Public License along
19
 * with this program; if not, write to the Free Software Foundation, Inc.,
20
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21
 * http://www.gnu.org/copyleft/gpl.html
22
 *
23
 * @file
24
 */
25
26
use MediaWiki\Session\Session;
27
use MediaWiki\Session\SessionId;
28
use MediaWiki\Session\SessionManager;
29
30
/**
31
 * The WebRequest class encapsulates getting at data passed in the
32
 * URL or via a POSTed form stripping illegal input characters and
33
 * normalizing Unicode sequences.
34
 *
35
 * @ingroup HTTP
36
 */
37
class WebRequest {
38
	protected $data, $headers = [];
0 ignored issues
show
Coding Style introduced by
It is generally advisable to only define one property per statement.

Only declaring a single property per statement allows you to later on add doc comments more easily.

It is also recommended by PSR2, so it is a common style that many people expect.

Loading history...
39
40
	/**
41
	 * Flag to make WebRequest::getHeader return an array of values.
42
	 * @since 1.26
43
	 */
44
	const GETHEADER_LIST = 1;
45
46
	/**
47
	 * The unique request ID.
48
	 * @var string
49
	 */
50
	private static $reqId;
51
52
	/**
53
	 * Lazy-init response object
54
	 * @var WebResponse
55
	 */
56
	private $response;
57
58
	/**
59
	 * Cached client IP address
60
	 * @var string
61
	 */
62
	private $ip;
63
64
	/**
65
	 * The timestamp of the start of the request, with microsecond precision.
66
	 * @var float
67
	 */
68
	protected $requestTime;
69
70
	/**
71
	 * Cached URL protocol
72
	 * @var string
73
	 */
74
	protected $protocol;
75
76
	/**
77
	 * @var SessionId|null Session ID to use for this
78
	 *  request. We can't save the session directly due to reference cycles not
79
	 *  working too well (slow GC in Zend and never collected in HHVM).
80
	 */
81
	protected $sessionId = null;
82
83
	public function __construct() {
0 ignored issues
show
Coding Style introduced by
__construct 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...
Coding Style introduced by
__construct uses the super-global variable $_POST 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...
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...
84
		$this->requestTime = isset( $_SERVER['REQUEST_TIME_FLOAT'] )
85
			? $_SERVER['REQUEST_TIME_FLOAT'] : microtime( true );
86
87
		// POST overrides GET data
88
		// We don't use $_REQUEST here to avoid interference from cookies...
89
		$this->data = $_POST + $_GET;
90
	}
91
92
	/**
93
	 * Extract relevant query arguments from the http request uri's path
94
	 * to be merged with the normal php provided query arguments.
95
	 * Tries to use the REQUEST_URI data if available and parses it
96
	 * according to the wiki's configuration looking for any known pattern.
97
	 *
98
	 * If the REQUEST_URI is not provided we'll fall back on the PATH_INFO
99
	 * provided by the server if any and use that to set a 'title' parameter.
100
	 *
101
	 * @param string $want If this is not 'all', then the function
102
	 * will return an empty array if it determines that the URL is
103
	 * inside a rewrite path.
104
	 *
105
	 * @return array Any query arguments found in path matches.
106
	 */
107
	public static function getPathInfo( $want = 'all' ) {
0 ignored issues
show
Coding Style introduced by
getPathInfo 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...
108
		global $wgUsePathInfo;
109
		// PATH_INFO is mangled due to http://bugs.php.net/bug.php?id=31892
110
		// And also by Apache 2.x, double slashes are converted to single slashes.
111
		// So we will use REQUEST_URI if possible.
112
		$matches = [];
113
		if ( !empty( $_SERVER['REQUEST_URI'] ) ) {
114
			// Slurp out the path portion to examine...
115
			$url = $_SERVER['REQUEST_URI'];
116
			if ( !preg_match( '!^https?://!', $url ) ) {
117
				$url = 'http://unused' . $url;
118
			}
119
			MediaWiki\suppressWarnings();
120
			$a = parse_url( $url );
121
			MediaWiki\restoreWarnings();
122
			if ( $a ) {
123
				$path = isset( $a['path'] ) ? $a['path'] : '';
124
125
				global $wgScript;
126
				if ( $path == $wgScript && $want !== 'all' ) {
127
					// Script inside a rewrite path?
128
					// Abort to keep from breaking...
129
					return $matches;
130
				}
131
132
				$router = new PathRouter;
133
134
				// Raw PATH_INFO style
135
				$router->add( "$wgScript/$1" );
136
137
				if ( isset( $_SERVER['SCRIPT_NAME'] )
138
					&& preg_match( '/\.php5?/', $_SERVER['SCRIPT_NAME'] )
139
				) {
140
					# Check for SCRIPT_NAME, we handle index.php explicitly
141
					# But we do have some other .php files such as img_auth.php
142
					# Don't let root article paths clober the parsing for them
143
					$router->add( $_SERVER['SCRIPT_NAME'] . "/$1" );
144
				}
145
146
				global $wgArticlePath;
147
				if ( $wgArticlePath ) {
148
					$router->add( $wgArticlePath );
149
				}
150
151
				global $wgActionPaths;
152
				if ( $wgActionPaths ) {
153
					$router->add( $wgActionPaths, [ 'action' => '$key' ] );
154
				}
155
156
				global $wgVariantArticlePath, $wgContLang;
157
				if ( $wgVariantArticlePath ) {
158
					$router->add( $wgVariantArticlePath,
159
						[ 'variant' => '$2' ],
160
						[ '$2' => $wgContLang->getVariants() ]
161
					);
162
				}
163
164
				Hooks::run( 'WebRequestPathInfoRouter', [ $router ] );
165
166
				$matches = $router->parse( $path );
167
			}
168
		} elseif ( $wgUsePathInfo ) {
169
			if ( isset( $_SERVER['ORIG_PATH_INFO'] ) && $_SERVER['ORIG_PATH_INFO'] != '' ) {
170
				// Mangled PATH_INFO
171
				// http://bugs.php.net/bug.php?id=31892
172
				// Also reported when ini_get('cgi.fix_pathinfo')==false
173
				$matches['title'] = substr( $_SERVER['ORIG_PATH_INFO'], 1 );
174
175
			} elseif ( isset( $_SERVER['PATH_INFO'] ) && $_SERVER['PATH_INFO'] != '' ) {
176
				// Regular old PATH_INFO yay
177
				$matches['title'] = substr( $_SERVER['PATH_INFO'], 1 );
178
			}
179
		}
180
181
		return $matches;
182
	}
183
184
	/**
185
	 * Work out an appropriate URL prefix containing scheme and host, based on
186
	 * information detected from $_SERVER
187
	 *
188
	 * @return string
189
	 */
190
	public static function detectServer() {
0 ignored issues
show
Coding Style introduced by
detectServer 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...
191
		global $wgAssumeProxiesUseDefaultProtocolPorts;
192
193
		$proto = self::detectProtocol();
194
		$stdPort = $proto === 'https' ? 443 : 80;
195
196
		$varNames = [ 'HTTP_HOST', 'SERVER_NAME', 'HOSTNAME', 'SERVER_ADDR' ];
197
		$host = 'localhost';
198
		$port = $stdPort;
199
		foreach ( $varNames as $varName ) {
200
			if ( !isset( $_SERVER[$varName] ) ) {
201
				continue;
202
			}
203
204
			$parts = IP::splitHostAndPort( $_SERVER[$varName] );
205
			if ( !$parts ) {
206
				// Invalid, do not use
207
				continue;
208
			}
209
210
			$host = $parts[0];
211
			if ( $wgAssumeProxiesUseDefaultProtocolPorts && isset( $_SERVER['HTTP_X_FORWARDED_PROTO'] ) ) {
212
				// Bug 70021: Assume that upstream proxy is running on the default
213
				// port based on the protocol. We have no reliable way to determine
214
				// the actual port in use upstream.
215
				$port = $stdPort;
216
			} elseif ( $parts[1] === false ) {
217
				if ( isset( $_SERVER['SERVER_PORT'] ) ) {
218
					$port = $_SERVER['SERVER_PORT'];
219
				} // else leave it as $stdPort
220
			} else {
221
				$port = $parts[1];
222
			}
223
			break;
224
		}
225
226
		return $proto . '://' . IP::combineHostAndPort( $host, $port, $stdPort );
227
	}
228
229
	/**
230
	 * Detect the protocol from $_SERVER.
231
	 * This is for use prior to Setup.php, when no WebRequest object is available.
232
	 * At other times, use the non-static function getProtocol().
233
	 *
234
	 * @return array
235
	 */
236
	public static function detectProtocol() {
0 ignored issues
show
Coding Style introduced by
detectProtocol 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...
237
		if ( ( !empty( $_SERVER['HTTPS'] ) && $_SERVER['HTTPS'] !== 'off' ) ||
238
			( isset( $_SERVER['HTTP_X_FORWARDED_PROTO'] ) &&
239
			$_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https' ) ) {
240
			return 'https';
241
		} else {
242
			return 'http';
243
		}
244
	}
245
246
	/**
247
	 * Get the number of seconds to have elapsed since request start,
248
	 * in fractional seconds, with microsecond resolution.
249
	 *
250
	 * @return float
251
	 * @since 1.25
252
	 */
253
	public function getElapsedTime() {
254
		return microtime( true ) - $this->requestTime;
255
	}
256
257
	/**
258
	 * Get the unique request ID.
259
	 * This is either the value of the UNIQUE_ID envvar (if present) or a
260
	 * randomly-generated 24-character string.
261
	 *
262
	 * @return string
263
	 * @since 1.27
264
	 */
265
	public static function getRequestId() {
0 ignored issues
show
Coding Style introduced by
getRequestId 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...
266
		if ( !self::$reqId ) {
267
			self::$reqId = isset( $_SERVER['UNIQUE_ID'] )
268
				? $_SERVER['UNIQUE_ID'] : wfRandomString( 24 );
269
		}
270
271
		return self::$reqId;
272
	}
273
274
	/**
275
	 * Override the unique request ID. This is for sub-requests, such as jobs,
276
	 * that wish to use the same id but are not part of the same execution context.
277
	 *
278
	 * @param string $id
279
	 * @since 1.27
280
	 */
281
	public static function overrideRequestId( $id ) {
282
		self::$reqId = $id;
283
	}
284
285
	/**
286
	 * Get the current URL protocol (http or https)
287
	 * @return string
288
	 */
289
	public function getProtocol() {
290
		if ( $this->protocol === null ) {
291
			$this->protocol = self::detectProtocol();
292
		}
293
		return $this->protocol;
294
	}
295
296
	/**
297
	 * Check for title, action, and/or variant data in the URL
298
	 * and interpolate it into the GET variables.
299
	 * This should only be run after $wgContLang is available,
300
	 * as we may need the list of language variants to determine
301
	 * available variant URLs.
302
	 */
303
	public function interpolateTitle() {
0 ignored issues
show
Coding Style introduced by
interpolateTitle 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...
Coding Style introduced by
interpolateTitle uses the super-global variable $_REQUEST 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...
304
		// bug 16019: title interpolation on API queries is useless and sometimes harmful
305
		if ( defined( 'MW_API' ) ) {
306
			return;
307
		}
308
309
		$matches = self::getPathInfo( 'title' );
310
		foreach ( $matches as $key => $val ) {
311
			$this->data[$key] = $_GET[$key] = $_REQUEST[$key] = $val;
312
		}
313
	}
314
315
	/**
316
	 * URL rewriting function; tries to extract page title and,
317
	 * optionally, one other fixed parameter value from a URL path.
318
	 *
319
	 * @param string $path The URL path given from the client
320
	 * @param array $bases One or more URLs, optionally with $1 at the end
321
	 * @param string $key If provided, the matching key in $bases will be
322
	 *    passed on as the value of this URL parameter
323
	 * @return array Array of URL variables to interpolate; empty if no match
324
	 */
325
	static function extractTitle( $path, $bases, $key = false ) {
326
		foreach ( (array)$bases as $keyValue => $base ) {
327
			// Find the part after $wgArticlePath
328
			$base = str_replace( '$1', '', $base );
329
			$baseLen = strlen( $base );
330
			if ( substr( $path, 0, $baseLen ) == $base ) {
331
				$raw = substr( $path, $baseLen );
332
				if ( $raw !== '' ) {
333
					$matches = [ 'title' => rawurldecode( $raw ) ];
334
					if ( $key ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $key of type false|string is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
335
						$matches[$key] = $keyValue;
336
					}
337
					return $matches;
338
				}
339
			}
340
		}
341
		return [];
342
	}
343
344
	/**
345
	 * Recursively normalizes UTF-8 strings in the given array.
346
	 *
347
	 * @param string|array $data
348
	 * @return array|string Cleaned-up version of the given
349
	 * @private
350
	 */
351
	function normalizeUnicode( $data ) {
352
		if ( is_array( $data ) ) {
353
			foreach ( $data as $key => $val ) {
354
				$data[$key] = $this->normalizeUnicode( $val );
355
			}
356
		} else {
357
			global $wgContLang;
358
			$data = isset( $wgContLang ) ?
359
				$wgContLang->normalize( $data ) :
360
				UtfNormal\Validator::cleanUp( $data );
361
		}
362
		return $data;
363
	}
364
365
	/**
366
	 * Fetch a value from the given array or return $default if it's not set.
367
	 *
368
	 * @param array $arr
369
	 * @param string $name
370
	 * @param mixed $default
371
	 * @return mixed
372
	 */
373
	private function getGPCVal( $arr, $name, $default ) {
0 ignored issues
show
Coding Style introduced by
getGPCVal 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...
374
		# PHP is so nice to not touch input data, except sometimes:
375
		# http://us2.php.net/variables.external#language.variables.external.dot-in-names
376
		# Work around PHP *feature* to avoid *bugs* elsewhere.
377
		$name = strtr( $name, '.', '_' );
378
		if ( isset( $arr[$name] ) ) {
379
			global $wgContLang;
380
			$data = $arr[$name];
381
			if ( isset( $_GET[$name] ) && !is_array( $data ) ) {
382
				# Check for alternate/legacy character encoding.
383
				if ( isset( $wgContLang ) ) {
384
					$data = $wgContLang->checkTitleEncoding( $data );
385
				}
386
			}
387
			$data = $this->normalizeUnicode( $data );
388
			return $data;
389
		} else {
390
			return $default;
391
		}
392
	}
393
394
	/**
395
	 * Fetch a scalar from the input or return $default if it's not set.
396
	 * Returns a string. Arrays are discarded. Useful for
397
	 * non-freeform text inputs (e.g. predefined internal text keys
398
	 * selected by a drop-down menu). For freeform input, see getText().
399
	 *
400
	 * @param string $name
401
	 * @param string $default Optional default (or null)
402
	 * @return string
403
	 */
404
	public function getVal( $name, $default = null ) {
405
		$val = $this->getGPCVal( $this->data, $name, $default );
406
		if ( is_array( $val ) ) {
407
			$val = $default;
408
		}
409
		if ( is_null( $val ) ) {
410
			return $val;
411
		} else {
412
			return (string)$val;
413
		}
414
	}
415
416
	/**
417
	 * Set an arbitrary value into our get/post data.
418
	 *
419
	 * @param string $key Key name to use
420
	 * @param mixed $value Value to set
421
	 * @return mixed Old value if one was present, null otherwise
422
	 */
423
	public function setVal( $key, $value ) {
424
		$ret = isset( $this->data[$key] ) ? $this->data[$key] : null;
425
		$this->data[$key] = $value;
426
		return $ret;
427
	}
428
429
	/**
430
	 * Unset an arbitrary value from our get/post data.
431
	 *
432
	 * @param string $key Key name to use
433
	 * @return mixed Old value if one was present, null otherwise
434
	 */
435
	public function unsetVal( $key ) {
436 View Code Duplication
		if ( !isset( $this->data[$key] ) ) {
437
			$ret = null;
438
		} else {
439
			$ret = $this->data[$key];
440
			unset( $this->data[$key] );
441
		}
442
		return $ret;
443
	}
444
445
	/**
446
	 * Fetch an array from the input or return $default if it's not set.
447
	 * If source was scalar, will return an array with a single element.
448
	 * If no source and no default, returns null.
449
	 *
450
	 * @param string $name
451
	 * @param array $default Optional default (or null)
452
	 * @return array
453
	 */
454
	public function getArray( $name, $default = null ) {
455
		$val = $this->getGPCVal( $this->data, $name, $default );
456
		if ( is_null( $val ) ) {
457
			return null;
458
		} else {
459
			return (array)$val;
460
		}
461
	}
462
463
	/**
464
	 * Fetch an array of integers, or return $default if it's not set.
465
	 * If source was scalar, will return an array with a single element.
466
	 * If no source and no default, returns null.
467
	 * If an array is returned, contents are guaranteed to be integers.
468
	 *
469
	 * @param string $name
470
	 * @param array $default Option default (or null)
471
	 * @return array Array of ints
472
	 */
473
	public function getIntArray( $name, $default = null ) {
474
		$val = $this->getArray( $name, $default );
475
		if ( is_array( $val ) ) {
476
			$val = array_map( 'intval', $val );
477
		}
478
		return $val;
479
	}
480
481
	/**
482
	 * Fetch an integer value from the input or return $default if not set.
483
	 * Guaranteed to return an integer; non-numeric input will typically
484
	 * return 0.
485
	 *
486
	 * @param string $name
487
	 * @param int $default
488
	 * @return int
489
	 */
490
	public function getInt( $name, $default = 0 ) {
491
		return intval( $this->getVal( $name, $default ) );
492
	}
493
494
	/**
495
	 * Fetch an integer value from the input or return null if empty.
496
	 * Guaranteed to return an integer or null; non-numeric input will
497
	 * typically return null.
498
	 *
499
	 * @param string $name
500
	 * @return int|null
501
	 */
502
	public function getIntOrNull( $name ) {
503
		$val = $this->getVal( $name );
504
		return is_numeric( $val )
505
			? intval( $val )
506
			: null;
507
	}
508
509
	/**
510
	 * Fetch a floating point value from the input or return $default if not set.
511
	 * Guaranteed to return a float; non-numeric input will typically
512
	 * return 0.
513
	 *
514
	 * @since 1.23
515
	 * @param string $name
516
	 * @param float $default
517
	 * @return float
518
	 */
519
	public function getFloat( $name, $default = 0.0 ) {
520
		return floatval( $this->getVal( $name, $default ) );
521
	}
522
523
	/**
524
	 * Fetch a boolean value from the input or return $default if not set.
525
	 * Guaranteed to return true or false, with normal PHP semantics for
526
	 * boolean interpretation of strings.
527
	 *
528
	 * @param string $name
529
	 * @param bool $default
530
	 * @return bool
531
	 */
532
	public function getBool( $name, $default = false ) {
533
		return (bool)$this->getVal( $name, $default );
534
	}
535
536
	/**
537
	 * Fetch a boolean value from the input or return $default if not set.
538
	 * Unlike getBool, the string "false" will result in boolean false, which is
539
	 * useful when interpreting information sent from JavaScript.
540
	 *
541
	 * @param string $name
542
	 * @param bool $default
543
	 * @return bool
544
	 */
545
	public function getFuzzyBool( $name, $default = false ) {
546
		return $this->getBool( $name, $default ) && strcasecmp( $this->getVal( $name ), 'false' ) !== 0;
547
	}
548
549
	/**
550
	 * Return true if the named value is set in the input, whatever that
551
	 * value is (even "0"). Return false if the named value is not set.
552
	 * Example use is checking for the presence of check boxes in forms.
553
	 *
554
	 * @param string $name
555
	 * @return bool
556
	 */
557
	public function getCheck( $name ) {
558
		# Checkboxes and buttons are only present when clicked
559
		# Presence connotes truth, absence false
560
		return $this->getVal( $name, null ) !== null;
561
	}
562
563
	/**
564
	 * Fetch a text string from the given array or return $default if it's not
565
	 * set. Carriage returns are stripped from the text, and with some language
566
	 * modules there is an input transliteration applied. This should generally
567
	 * be used for form "<textarea>" and "<input>" fields. Used for
568
	 * user-supplied freeform text input (for which input transformations may
569
	 * be required - e.g.  Esperanto x-coding).
570
	 *
571
	 * @param string $name
572
	 * @param string $default Optional
573
	 * @return string
574
	 */
575
	public function getText( $name, $default = '' ) {
576
		global $wgContLang;
577
		$val = $this->getVal( $name, $default );
578
		return str_replace( "\r\n", "\n",
579
			$wgContLang->recodeInput( $val ) );
580
	}
581
582
	/**
583
	 * Extracts the given named values into an array.
584
	 * If no arguments are given, returns all input values.
585
	 * No transformation is performed on the values.
586
	 *
587
	 * @return array
588
	 */
589
	public function getValues() {
590
		$names = func_get_args();
591
		if ( count( $names ) == 0 ) {
592
			$names = array_keys( $this->data );
593
		}
594
595
		$retVal = [];
596
		foreach ( $names as $name ) {
597
			$value = $this->getGPCVal( $this->data, $name, null );
598
			if ( !is_null( $value ) ) {
599
				$retVal[$name] = $value;
600
			}
601
		}
602
		return $retVal;
603
	}
604
605
	/**
606
	 * Returns the names of all input values excluding those in $exclude.
607
	 *
608
	 * @param array $exclude
609
	 * @return array
610
	 */
611
	public function getValueNames( $exclude = [] ) {
612
		return array_diff( array_keys( $this->getValues() ), $exclude );
613
	}
614
615
	/**
616
	 * Get the values passed in the query string.
617
	 * No transformation is performed on the values.
618
	 *
619
	 * @return array
620
	 */
621
	public function getQueryValues() {
0 ignored issues
show
Coding Style introduced by
getQueryValues 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...
622
		return $_GET;
623
	}
624
625
	/**
626
	 * Return the contents of the Query with no decoding. Use when you need to
627
	 * know exactly what was sent, e.g. for an OAuth signature over the elements.
628
	 *
629
	 * @return string
630
	 */
631
	public function getRawQueryString() {
0 ignored issues
show
Coding Style introduced by
getRawQueryString 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...
632
		return $_SERVER['QUERY_STRING'];
633
	}
634
635
	/**
636
	 * Return the contents of the POST with no decoding. Use when you need to
637
	 * know exactly what was sent, e.g. for an OAuth signature over the elements.
638
	 *
639
	 * @return string
640
	 */
641
	public function getRawPostString() {
642
		if ( !$this->wasPosted() ) {
643
			return '';
644
		}
645
		return $this->getRawInput();
646
	}
647
648
	/**
649
	 * Return the raw request body, with no processing. Cached since some methods
650
	 * disallow reading the stream more than once. As stated in the php docs, this
651
	 * does not work with enctype="multipart/form-data".
652
	 *
653
	 * @return string
654
	 */
655
	public function getRawInput() {
656
		static $input = null;
657
		if ( $input === null ) {
658
			$input = file_get_contents( 'php://input' );
659
		}
660
		return $input;
661
	}
662
663
	/**
664
	 * Get the HTTP method used for this request.
665
	 *
666
	 * @return string
667
	 */
668
	public function getMethod() {
0 ignored issues
show
Coding Style introduced by
getMethod 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...
669
		return isset( $_SERVER['REQUEST_METHOD'] ) ? $_SERVER['REQUEST_METHOD'] : 'GET';
670
	}
671
672
	/**
673
	 * Returns true if the present request was reached by a POST operation,
674
	 * false otherwise (GET, HEAD, or command-line).
675
	 *
676
	 * Note that values retrieved by the object may come from the
677
	 * GET URL etc even on a POST request.
678
	 *
679
	 * @return bool
680
	 */
681
	public function wasPosted() {
682
		return $this->getMethod() == 'POST';
683
	}
684
685
	/**
686
	 * Return the session for this request
687
	 * @since 1.27
688
	 * @note For performance, keep the session locally if you will be making
689
	 *  much use of it instead of calling this method repeatedly.
690
	 * @return Session
691
	 */
692
	public function getSession() {
693
		if ( $this->sessionId !== null ) {
694
			$session = SessionManager::singleton()->getSessionById( (string)$this->sessionId, true, $this );
695
			if ( $session ) {
696
				return $session;
697
			}
698
		}
699
700
		$session = SessionManager::singleton()->getSessionForRequest( $this );
701
		$this->sessionId = $session->getSessionId();
702
		return $session;
703
	}
704
705
	/**
706
	 * Set the session for this request
707
	 * @since 1.27
708
	 * @private For use by MediaWiki\Session classes only
709
	 * @param SessionId $sessionId
710
	 */
711
	public function setSessionId( SessionId $sessionId ) {
712
		$this->sessionId = $sessionId;
713
	}
714
715
	/**
716
	 * Get the session id for this request, if any
717
	 * @since 1.27
718
	 * @private For use by MediaWiki\Session classes only
719
	 * @return SessionId|null
720
	 */
721
	public function getSessionId() {
722
		return $this->sessionId;
723
	}
724
725
	/**
726
	 * Returns true if the request has a persistent session.
727
	 * This does not necessarily mean that the user is logged in!
728
	 *
729
	 * @deprecated since 1.27, use
730
	 *  \MediaWiki\Session\SessionManager::singleton()->getPersistedSessionId()
731
	 *  instead.
732
	 * @return bool
733
	 */
734
	public function checkSessionCookie() {
735
		global $wgInitialSessionId;
736
		wfDeprecated( __METHOD__, '1.27' );
737
		return $wgInitialSessionId !== null &&
738
			$this->getSession()->getId() === (string)$wgInitialSessionId;
739
	}
740
741
	/**
742
	 * Get a cookie from the $_COOKIE jar
743
	 *
744
	 * @param string $key The name of the cookie
745
	 * @param string $prefix A prefix to use for the cookie name, if not $wgCookiePrefix
746
	 * @param mixed $default What to return if the value isn't found
747
	 * @return mixed Cookie value or $default if the cookie not set
748
	 */
749
	public function getCookie( $key, $prefix = null, $default = null ) {
0 ignored issues
show
Coding Style introduced by
getCookie uses the super-global variable $_COOKIE 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...
750
		if ( $prefix === null ) {
751
			global $wgCookiePrefix;
752
			$prefix = $wgCookiePrefix;
753
		}
754
		return $this->getGPCVal( $_COOKIE, $prefix . $key, $default );
755
	}
756
757
	/**
758
	 * Return the path and query string portion of the main request URI.
759
	 * This will be suitable for use as a relative link in HTML output.
760
	 *
761
	 * @throws MWException
762
	 * @return string
763
	 */
764
	public static function getGlobalRequestURL() {
0 ignored issues
show
Coding Style introduced by
getGlobalRequestURL 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...
765
		if ( isset( $_SERVER['REQUEST_URI'] ) && strlen( $_SERVER['REQUEST_URI'] ) ) {
766
			$base = $_SERVER['REQUEST_URI'];
767
		} elseif ( isset( $_SERVER['HTTP_X_ORIGINAL_URL'] )
768
			&& strlen( $_SERVER['HTTP_X_ORIGINAL_URL'] )
769
		) {
770
			// Probably IIS; doesn't set REQUEST_URI
771
			$base = $_SERVER['HTTP_X_ORIGINAL_URL'];
772
		} elseif ( isset( $_SERVER['SCRIPT_NAME'] ) ) {
773
			$base = $_SERVER['SCRIPT_NAME'];
774
			if ( isset( $_SERVER['QUERY_STRING'] ) && $_SERVER['QUERY_STRING'] != '' ) {
775
				$base .= '?' . $_SERVER['QUERY_STRING'];
776
			}
777
		} else {
778
			// This shouldn't happen!
779
			throw new MWException( "Web server doesn't provide either " .
780
				"REQUEST_URI, HTTP_X_ORIGINAL_URL or SCRIPT_NAME. Report details " .
781
				"of your web server configuration to https://phabricator.wikimedia.org/" );
782
		}
783
		// User-agents should not send a fragment with the URI, but
784
		// if they do, and the web server passes it on to us, we
785
		// need to strip it or we get false-positive redirect loops
786
		// or weird output URLs
787
		$hash = strpos( $base, '#' );
788
		if ( $hash !== false ) {
789
			$base = substr( $base, 0, $hash );
790
		}
791
792
		if ( $base[0] == '/' ) {
793
			// More than one slash will look like it is protocol relative
794
			return preg_replace( '!^/+!', '/', $base );
795
		} else {
796
			// We may get paths with a host prepended; strip it.
797
			return preg_replace( '!^[^:]+://[^/]+/+!', '/', $base );
798
		}
799
	}
800
801
	/**
802
	 * Return the path and query string portion of the request URI.
803
	 * This will be suitable for use as a relative link in HTML output.
804
	 *
805
	 * @throws MWException
806
	 * @return string
807
	 */
808
	public function getRequestURL() {
809
		return self::getGlobalRequestURL();
810
	}
811
812
	/**
813
	 * Return the request URI with the canonical service and hostname, path,
814
	 * and query string. This will be suitable for use as an absolute link
815
	 * in HTML or other output.
816
	 *
817
	 * If $wgServer is protocol-relative, this will return a fully
818
	 * qualified URL with the protocol that was used for this request.
819
	 *
820
	 * @return string
821
	 */
822
	public function getFullRequestURL() {
823
		return wfExpandUrl( $this->getRequestURL(), PROTO_CURRENT );
824
	}
825
826
	/**
827
	 * @param string $key
828
	 * @param string $value
829
	 * @return string
830
	 */
831
	public function appendQueryValue( $key, $value ) {
832
		return $this->appendQueryArray( [ $key => $value ] );
833
	}
834
835
	/**
836
	 * Appends or replaces value of query variables.
837
	 *
838
	 * @param array $array Array of values to replace/add to query
839
	 * @return string
840
	 */
841
	public function appendQueryArray( $array ) {
842
		$newquery = $this->getQueryValues();
843
		unset( $newquery['title'] );
844
		$newquery = array_merge( $newquery, $array );
845
846
		return wfArrayToCgi( $newquery );
847
	}
848
849
	/**
850
	 * Check for limit and offset parameters on the input, and return sensible
851
	 * defaults if not given. The limit must be positive and is capped at 5000.
852
	 * Offset must be positive but is not capped.
853
	 *
854
	 * @param int $deflimit Limit to use if no input and the user hasn't set the option.
855
	 * @param string $optionname To specify an option other than rclimit to pull from.
856
	 * @return int[] First element is limit, second is offset
857
	 */
858
	public function getLimitOffset( $deflimit = 50, $optionname = 'rclimit' ) {
859
		global $wgUser;
860
861
		$limit = $this->getInt( 'limit', 0 );
862
		if ( $limit < 0 ) {
863
			$limit = 0;
864
		}
865
		if ( ( $limit == 0 ) && ( $optionname != '' ) ) {
866
			$limit = $wgUser->getIntOption( $optionname );
867
		}
868
		if ( $limit <= 0 ) {
869
			$limit = $deflimit;
870
		}
871
		if ( $limit > 5000 ) {
872
			$limit = 5000; # We have *some* limits...
873
		}
874
875
		$offset = $this->getInt( 'offset', 0 );
876
		if ( $offset < 0 ) {
877
			$offset = 0;
878
		}
879
880
		return [ $limit, $offset ];
881
	}
882
883
	/**
884
	 * Return the path to the temporary file where PHP has stored the upload.
885
	 *
886
	 * @param string $key
887
	 * @return string|null String or null if no such file.
888
	 */
889
	public function getFileTempname( $key ) {
890
		$file = new WebRequestUpload( $this, $key );
891
		return $file->getTempName();
892
	}
893
894
	/**
895
	 * Return the upload error or 0
896
	 *
897
	 * @param string $key
898
	 * @return int
899
	 */
900
	public function getUploadError( $key ) {
901
		$file = new WebRequestUpload( $this, $key );
902
		return $file->getError();
903
	}
904
905
	/**
906
	 * Return the original filename of the uploaded file, as reported by
907
	 * the submitting user agent. HTML-style character entities are
908
	 * interpreted and normalized to Unicode normalization form C, in part
909
	 * to deal with weird input from Safari with non-ASCII filenames.
910
	 *
911
	 * Other than this the name is not verified for being a safe filename.
912
	 *
913
	 * @param string $key
914
	 * @return string|null String or null if no such file.
915
	 */
916
	public function getFileName( $key ) {
917
		$file = new WebRequestUpload( $this, $key );
918
		return $file->getName();
919
	}
920
921
	/**
922
	 * Return a WebRequestUpload object corresponding to the key
923
	 *
924
	 * @param string $key
925
	 * @return WebRequestUpload
926
	 */
927
	public function getUpload( $key ) {
928
		return new WebRequestUpload( $this, $key );
929
	}
930
931
	/**
932
	 * Return a handle to WebResponse style object, for setting cookies,
933
	 * headers and other stuff, for Request being worked on.
934
	 *
935
	 * @return WebResponse
936
	 */
937
	public function response() {
938
		/* Lazy initialization of response object for this request */
939
		if ( !is_object( $this->response ) ) {
940
			$class = ( $this instanceof FauxRequest ) ? 'FauxResponse' : 'WebResponse';
941
			$this->response = new $class();
942
		}
943
		return $this->response;
944
	}
945
946
	/**
947
	 * Initialise the header list
948
	 */
949
	protected function initHeaders() {
0 ignored issues
show
Coding Style introduced by
initHeaders 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...
950
		if ( count( $this->headers ) ) {
951
			return;
952
		}
953
954
		$apacheHeaders = function_exists( 'apache_request_headers' ) ? apache_request_headers() : false;
955
		if ( $apacheHeaders ) {
956
			foreach ( $apacheHeaders as $tempName => $tempValue ) {
957
				$this->headers[strtoupper( $tempName )] = $tempValue;
958
			}
959
		} else {
960
			foreach ( $_SERVER as $name => $value ) {
961
				if ( substr( $name, 0, 5 ) === 'HTTP_' ) {
962
					$name = str_replace( '_', '-', substr( $name, 5 ) );
963
					$this->headers[$name] = $value;
964
				} elseif ( $name === 'CONTENT_LENGTH' ) {
965
					$this->headers['CONTENT-LENGTH'] = $value;
966
				}
967
			}
968
		}
969
	}
970
971
	/**
972
	 * Get an array containing all request headers
973
	 *
974
	 * @return array Mapping header name to its value
975
	 */
976
	public function getAllHeaders() {
977
		$this->initHeaders();
978
		return $this->headers;
979
	}
980
981
	/**
982
	 * Get a request header, or false if it isn't set.
983
	 *
984
	 * @param string $name Case-insensitive header name
985
	 * @param int $flags Bitwise combination of:
986
	 *   WebRequest::GETHEADER_LIST  Treat the header as a comma-separated list
987
	 *                               of values, as described in RFC 2616 § 4.2.
988
	 *                               (since 1.26).
989
	 * @return string|array|bool False if header is unset; otherwise the
990
	 *  header value(s) as either a string (the default) or an array, if
991
	 *  WebRequest::GETHEADER_LIST flag was set.
992
	 */
993
	public function getHeader( $name, $flags = 0 ) {
994
		$this->initHeaders();
995
		$name = strtoupper( $name );
996
		if ( !isset( $this->headers[$name] ) ) {
997
			return false;
998
		}
999
		$value = $this->headers[$name];
1000
		if ( $flags & self::GETHEADER_LIST ) {
1001
			$value = array_map( 'trim', explode( ',', $value ) );
1002
		}
1003
		return $value;
1004
	}
1005
1006
	/**
1007
	 * Get data from the session
1008
	 *
1009
	 * @note Prefer $this->getSession() instead if making multiple calls.
1010
	 * @param string $key Name of key in the session
1011
	 * @return mixed
1012
	 */
1013
	public function getSessionData( $key ) {
1014
		return $this->getSession()->get( $key );
1015
	}
1016
1017
	/**
1018
	 * Set session data
1019
	 *
1020
	 * @note Prefer $this->getSession() instead if making multiple calls.
1021
	 * @param string $key Name of key in the session
1022
	 * @param mixed $data
1023
	 */
1024
	public function setSessionData( $key, $data ) {
1025
		return $this->getSession()->set( $key, $data );
1026
	}
1027
1028
	/**
1029
	 * Check if Internet Explorer will detect an incorrect cache extension in
1030
	 * PATH_INFO or QUERY_STRING. If the request can't be allowed, show an error
1031
	 * message or redirect to a safer URL. Returns true if the URL is OK, and
1032
	 * false if an error message has been shown and the request should be aborted.
1033
	 *
1034
	 * @param array $extWhitelist
1035
	 * @throws HttpError
1036
	 * @return bool
1037
	 */
1038
	public function checkUrlExtension( $extWhitelist = [] ) {
0 ignored issues
show
Coding Style introduced by
checkUrlExtension 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...
1039
		$extWhitelist[] = 'php';
1040
		if ( IEUrlExtension::areServerVarsBad( $_SERVER, $extWhitelist ) ) {
1041
			if ( !$this->wasPosted() ) {
1042
				$newUrl = IEUrlExtension::fixUrlForIE6(
1043
					$this->getFullRequestURL(), $extWhitelist );
1044
				if ( $newUrl !== false ) {
1045
					$this->doSecurityRedirect( $newUrl );
1046
					return false;
1047
				}
1048
			}
1049
			throw new HttpError( 403,
1050
				'Invalid file extension found in the path info or query string.' );
1051
		}
1052
		return true;
1053
	}
1054
1055
	/**
1056
	 * Attempt to redirect to a URL with a QUERY_STRING that's not dangerous in
1057
	 * IE 6. Returns true if it was successful, false otherwise.
1058
	 *
1059
	 * @param string $url
1060
	 * @return bool
1061
	 */
1062
	protected function doSecurityRedirect( $url ) {
1063
		header( 'Location: ' . $url );
1064
		header( 'Content-Type: text/html' );
1065
		$encUrl = htmlspecialchars( $url );
1066
		echo <<<HTML
1067
<html>
1068
<head>
1069
<title>Security redirect</title>
1070
</head>
1071
<body>
1072
<h1>Security redirect</h1>
1073
<p>
1074
We can't serve non-HTML content from the URL you have requested, because
1075
Internet Explorer would interpret it as an incorrect and potentially dangerous
1076
content type.</p>
1077
<p>Instead, please use <a href="$encUrl">this URL</a>, which is the same as the
1078
URL you have requested, except that "&amp;*" is appended. This prevents Internet
1079
Explorer from seeing a bogus file extension.
1080
</p>
1081
</body>
1082
</html>
1083
HTML;
1084
		echo "\n";
1085
		return true;
1086
	}
1087
1088
	/**
1089
	 * Parse the Accept-Language header sent by the client into an array
1090
	 *
1091
	 * @return array Array( languageCode => q-value ) sorted by q-value in
1092
	 *   descending order then appearing time in the header in ascending order.
1093
	 * May contain the "language" '*', which applies to languages other than those explicitly listed.
1094
	 * This is aligned with rfc2616 section 14.4
1095
	 * Preference for earlier languages appears in rfc3282 as an extension to HTTP/1.1.
1096
	 */
1097
	public function getAcceptLang() {
1098
		// Modified version of code found at
1099
		// http://www.thefutureoftheweb.com/blog/use-accept-language-header
1100
		$acceptLang = $this->getHeader( 'Accept-Language' );
1101
		if ( !$acceptLang ) {
1102
			return [];
1103
		}
1104
1105
		// Return the language codes in lower case
1106
		$acceptLang = strtolower( $acceptLang );
1107
1108
		// Break up string into pieces (languages and q factors)
1109
		$lang_parse = null;
1110
		preg_match_all(
1111
			'/([a-z]{1,8}(-[a-z]{1,8})*|\*)\s*(;\s*q\s*=\s*(1(\.0{0,3})?|0(\.[0-9]{0,3})?)?)?/',
1112
			$acceptLang,
1113
			$lang_parse
1114
		);
1115
1116
		if ( !count( $lang_parse[1] ) ) {
1117
			return [];
1118
		}
1119
1120
		$langcodes = $lang_parse[1];
1121
		$qvalues = $lang_parse[4];
1122
		$indices = range( 0, count( $lang_parse[1] ) - 1 );
1123
1124
		// Set default q factor to 1
1125
		foreach ( $indices as $index ) {
1126
			if ( $qvalues[$index] === '' ) {
1127
				$qvalues[$index] = 1;
1128
			} elseif ( $qvalues[$index] == 0 ) {
1129
				unset( $langcodes[$index], $qvalues[$index], $indices[$index] );
1130
			}
1131
		}
1132
1133
		// Sort list. First by $qvalues, then by order. Reorder $langcodes the same way
1134
		array_multisort( $qvalues, SORT_DESC, SORT_NUMERIC, $indices, $langcodes );
1135
1136
		// Create a list like "en" => 0.8
1137
		$langs = array_combine( $langcodes, $qvalues );
1138
1139
		return $langs;
1140
	}
1141
1142
	/**
1143
	 * Fetch the raw IP from the request
1144
	 *
1145
	 * @since 1.19
1146
	 *
1147
	 * @throws MWException
1148
	 * @return string
1149
	 */
1150
	protected function getRawIP() {
0 ignored issues
show
Coding Style introduced by
getRawIP 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...
1151
		if ( !isset( $_SERVER['REMOTE_ADDR'] ) ) {
1152
			return null;
1153
		}
1154
1155
		if ( is_array( $_SERVER['REMOTE_ADDR'] ) || strpos( $_SERVER['REMOTE_ADDR'], ',' ) !== false ) {
1156
			throw new MWException( __METHOD__
1157
				. " : Could not determine the remote IP address due to multiple values." );
1158
		} else {
1159
			$ipchain = $_SERVER['REMOTE_ADDR'];
1160
		}
1161
1162
		return IP::canonicalize( $ipchain );
1163
	}
1164
1165
	/**
1166
	 * Work out the IP address based on various globals
1167
	 * For trusted proxies, use the XFF client IP (first of the chain)
1168
	 *
1169
	 * @since 1.19
1170
	 *
1171
	 * @throws MWException
1172
	 * @return string
1173
	 */
1174
	public function getIP() {
1175
		global $wgUsePrivateIPs;
1176
1177
		# Return cached result
1178
		if ( $this->ip !== null ) {
1179
			return $this->ip;
1180
		}
1181
1182
		# collect the originating ips
1183
		$ip = $this->getRawIP();
1184
		if ( !$ip ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $ip of type null|string is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
1185
			throw new MWException( 'Unable to determine IP.' );
1186
		}
1187
1188
		# Append XFF
1189
		$forwardedFor = $this->getHeader( 'X-Forwarded-For' );
1190
		if ( $forwardedFor !== false ) {
1191
			$isConfigured = IP::isConfiguredProxy( $ip );
1192
			$ipchain = array_map( 'trim', explode( ',', $forwardedFor ) );
1193
			$ipchain = array_reverse( $ipchain );
1194
			array_unshift( $ipchain, $ip );
1195
1196
			# Step through XFF list and find the last address in the list which is a
1197
			# trusted server. Set $ip to the IP address given by that trusted server,
1198
			# unless the address is not sensible (e.g. private). However, prefer private
1199
			# IP addresses over proxy servers controlled by this site (more sensible).
1200
			# Note that some XFF values might be "unknown" with Squid/Varnish.
1201
			foreach ( $ipchain as $i => $curIP ) {
1202
				$curIP = IP::sanitizeIP( IP::canonicalize( $curIP ) );
1203
				if ( !$curIP || !isset( $ipchain[$i + 1] ) || $ipchain[$i + 1] === 'unknown'
0 ignored issues
show
Bug Best Practice introduced by
The expression $curIP of type null|string is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
1204
					|| !IP::isTrustedProxy( $curIP )
1205
				) {
1206
					break; // IP is not valid/trusted or does not point to anything
1207
				}
1208
				if (
1209
					IP::isPublic( $ipchain[$i + 1] ) ||
1210
					$wgUsePrivateIPs ||
1211
					IP::isConfiguredProxy( $curIP ) // bug 48919; treat IP as sane
1212
				) {
1213
					// Follow the next IP according to the proxy
1214
					$nextIP = IP::canonicalize( $ipchain[$i + 1] );
1215
					if ( !$nextIP && $isConfigured ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $nextIP of type string|null is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
1216
						// We have not yet made it past CDN/proxy servers of this site,
1217
						// so either they are misconfigured or there is some IP spoofing.
1218
						throw new MWException( "Invalid IP given in XFF '$forwardedFor'." );
1219
					}
1220
					$ip = $nextIP;
1221
					// keep traversing the chain
1222
					continue;
1223
				}
1224
				break;
1225
			}
1226
		}
1227
1228
		# Allow extensions to improve our guess
1229
		Hooks::run( 'GetIP', [ &$ip ] );
1230
1231
		if ( !$ip ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $ip of type string|null is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
1232
			throw new MWException( "Unable to determine IP." );
1233
		}
1234
1235
		wfDebug( "IP: $ip\n" );
1236
		$this->ip = $ip;
1237
		return $ip;
1238
	}
1239
1240
	/**
1241
	 * @param string $ip
1242
	 * @return void
1243
	 * @since 1.21
1244
	 */
1245
	public function setIP( $ip ) {
1246
		$this->ip = $ip;
1247
	}
1248
}
1249