Completed
Branch master (8ef871)
by
unknown
29:40
created

WebRequest::getRequestURL()   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
dl 0
loc 3
rs 10
c 1
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
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\SessionManager;
27
28
/**
29
 * The WebRequest class encapsulates getting at data passed in the
30
 * URL or via a POSTed form stripping illegal input characters and
31
 * normalizing Unicode sequences.
32
 *
33
 * @ingroup HTTP
34
 */
35
class WebRequest {
36
	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...
37
38
	/**
39
	 * Flag to make WebRequest::getHeader return an array of values.
40
	 * @since 1.26
41
	 */
42
	const GETHEADER_LIST = 1;
43
44
	/**
45
	 * Lazy-init response object
46
	 * @var WebResponse
47
	 */
48
	private $response;
49
50
	/**
51
	 * Cached client IP address
52
	 * @var string
53
	 */
54
	private $ip;
55
56
	/**
57
	 * The timestamp of the start of the request, with microsecond precision.
58
	 * @var float
59
	 */
60
	protected $requestTime;
61
62
	/**
63
	 * Cached URL protocol
64
	 * @var string
65
	 */
66
	protected $protocol;
67
68
	/**
69
	 * @var \\MediaWiki\\Session\\SessionId|null Session ID to use for this
70
	 *  request. We can't save the session directly due to reference cycles not
71
	 *  working too well (slow GC in Zend and never collected in HHVM).
72
	 */
73
	protected $sessionId = null;
74
75
	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...
76
		$this->requestTime = isset( $_SERVER['REQUEST_TIME_FLOAT'] )
77
			? $_SERVER['REQUEST_TIME_FLOAT'] : microtime( true );
78
79
		// POST overrides GET data
80
		// We don't use $_REQUEST here to avoid interference from cookies...
81
		$this->data = $_POST + $_GET;
82
	}
83
84
	/**
85
	 * Extract relevant query arguments from the http request uri's path
86
	 * to be merged with the normal php provided query arguments.
87
	 * Tries to use the REQUEST_URI data if available and parses it
88
	 * according to the wiki's configuration looking for any known pattern.
89
	 *
90
	 * If the REQUEST_URI is not provided we'll fall back on the PATH_INFO
91
	 * provided by the server if any and use that to set a 'title' parameter.
92
	 *
93
	 * @param string $want If this is not 'all', then the function
94
	 * will return an empty array if it determines that the URL is
95
	 * inside a rewrite path.
96
	 *
97
	 * @return array Any query arguments found in path matches.
98
	 */
99
	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...
100
		global $wgUsePathInfo;
101
		// PATH_INFO is mangled due to http://bugs.php.net/bug.php?id=31892
102
		// And also by Apache 2.x, double slashes are converted to single slashes.
103
		// So we will use REQUEST_URI if possible.
104
		$matches = [];
105
		if ( !empty( $_SERVER['REQUEST_URI'] ) ) {
106
			// Slurp out the path portion to examine...
107
			$url = $_SERVER['REQUEST_URI'];
108
			if ( !preg_match( '!^https?://!', $url ) ) {
109
				$url = 'http://unused' . $url;
110
			}
111
			MediaWiki\suppressWarnings();
112
			$a = parse_url( $url );
113
			MediaWiki\restoreWarnings();
114
			if ( $a ) {
115
				$path = isset( $a['path'] ) ? $a['path'] : '';
116
117
				global $wgScript;
118
				if ( $path == $wgScript && $want !== 'all' ) {
119
					// Script inside a rewrite path?
120
					// Abort to keep from breaking...
121
					return $matches;
122
				}
123
124
				$router = new PathRouter;
125
126
				// Raw PATH_INFO style
127
				$router->add( "$wgScript/$1" );
128
129
				if ( isset( $_SERVER['SCRIPT_NAME'] )
130
					&& preg_match( '/\.php5?/', $_SERVER['SCRIPT_NAME'] )
131
				) {
132
					# Check for SCRIPT_NAME, we handle index.php explicitly
133
					# But we do have some other .php files such as img_auth.php
134
					# Don't let root article paths clober the parsing for them
135
					$router->add( $_SERVER['SCRIPT_NAME'] . "/$1" );
136
				}
137
138
				global $wgArticlePath;
139
				if ( $wgArticlePath ) {
140
					$router->add( $wgArticlePath );
141
				}
142
143
				global $wgActionPaths;
144
				if ( $wgActionPaths ) {
145
					$router->add( $wgActionPaths, [ 'action' => '$key' ] );
146
				}
147
148
				global $wgVariantArticlePath, $wgContLang;
149
				if ( $wgVariantArticlePath ) {
150
					$router->add( $wgVariantArticlePath,
151
						[ 'variant' => '$2' ],
152
						[ '$2' => $wgContLang->getVariants() ]
153
					);
154
				}
155
156
				Hooks::run( 'WebRequestPathInfoRouter', [ $router ] );
157
158
				$matches = $router->parse( $path );
159
			}
160
		} elseif ( $wgUsePathInfo ) {
161
			if ( isset( $_SERVER['ORIG_PATH_INFO'] ) && $_SERVER['ORIG_PATH_INFO'] != '' ) {
162
				// Mangled PATH_INFO
163
				// http://bugs.php.net/bug.php?id=31892
164
				// Also reported when ini_get('cgi.fix_pathinfo')==false
165
				$matches['title'] = substr( $_SERVER['ORIG_PATH_INFO'], 1 );
166
167
			} elseif ( isset( $_SERVER['PATH_INFO'] ) && $_SERVER['PATH_INFO'] != '' ) {
168
				// Regular old PATH_INFO yay
169
				$matches['title'] = substr( $_SERVER['PATH_INFO'], 1 );
170
			}
171
		}
172
173
		return $matches;
174
	}
175
176
	/**
177
	 * Work out an appropriate URL prefix containing scheme and host, based on
178
	 * information detected from $_SERVER
179
	 *
180
	 * @return string
181
	 */
182
	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...
183
		global $wgAssumeProxiesUseDefaultProtocolPorts;
184
185
		$proto = self::detectProtocol();
186
		$stdPort = $proto === 'https' ? 443 : 80;
187
188
		$varNames = [ 'HTTP_HOST', 'SERVER_NAME', 'HOSTNAME', 'SERVER_ADDR' ];
189
		$host = 'localhost';
190
		$port = $stdPort;
191
		foreach ( $varNames as $varName ) {
192
			if ( !isset( $_SERVER[$varName] ) ) {
193
				continue;
194
			}
195
196
			$parts = IP::splitHostAndPort( $_SERVER[$varName] );
197
			if ( !$parts ) {
198
				// Invalid, do not use
199
				continue;
200
			}
201
202
			$host = $parts[0];
203
			if ( $wgAssumeProxiesUseDefaultProtocolPorts && isset( $_SERVER['HTTP_X_FORWARDED_PROTO'] ) ) {
204
				// Bug 70021: Assume that upstream proxy is running on the default
205
				// port based on the protocol. We have no reliable way to determine
206
				// the actual port in use upstream.
207
				$port = $stdPort;
208
			} elseif ( $parts[1] === false ) {
209
				if ( isset( $_SERVER['SERVER_PORT'] ) ) {
210
					$port = $_SERVER['SERVER_PORT'];
211
				} // else leave it as $stdPort
212
			} else {
213
				$port = $parts[1];
214
			}
215
			break;
216
		}
217
218
		return $proto . '://' . IP::combineHostAndPort( $host, $port, $stdPort );
219
	}
220
221
	/**
222
	 * Detect the protocol from $_SERVER.
223
	 * This is for use prior to Setup.php, when no WebRequest object is available.
224
	 * At other times, use the non-static function getProtocol().
225
	 *
226
	 * @return array
227
	 */
228
	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...
229
		if ( ( !empty( $_SERVER['HTTPS'] ) && $_SERVER['HTTPS'] !== 'off' ) ||
230
			( isset( $_SERVER['HTTP_X_FORWARDED_PROTO'] ) &&
231
			$_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https' ) ) {
232
			return 'https';
233
		} else {
234
			return 'http';
235
		}
236
	}
237
238
	/**
239
	 * Get the number of seconds to have elapsed since request start,
240
	 * in fractional seconds, with microsecond resolution.
241
	 *
242
	 * @return float
243
	 * @since 1.25
244
	 */
245
	public function getElapsedTime() {
246
		return microtime( true ) - $this->requestTime;
247
	}
248
249
	/**
250
	 * Get the current URL protocol (http or https)
251
	 * @return string
252
	 */
253
	public function getProtocol() {
254
		if ( $this->protocol === null ) {
255
			$this->protocol = self::detectProtocol();
256
		}
257
		return $this->protocol;
258
	}
259
260
	/**
261
	 * Check for title, action, and/or variant data in the URL
262
	 * and interpolate it into the GET variables.
263
	 * This should only be run after $wgContLang is available,
264
	 * as we may need the list of language variants to determine
265
	 * available variant URLs.
266
	 */
267
	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...
268
		// bug 16019: title interpolation on API queries is useless and sometimes harmful
269
		if ( defined( 'MW_API' ) ) {
270
			return;
271
		}
272
273
		$matches = self::getPathInfo( 'title' );
274
		foreach ( $matches as $key => $val ) {
275
			$this->data[$key] = $_GET[$key] = $_REQUEST[$key] = $val;
276
		}
277
	}
278
279
	/**
280
	 * URL rewriting function; tries to extract page title and,
281
	 * optionally, one other fixed parameter value from a URL path.
282
	 *
283
	 * @param string $path The URL path given from the client
284
	 * @param array $bases One or more URLs, optionally with $1 at the end
285
	 * @param string $key If provided, the matching key in $bases will be
286
	 *    passed on as the value of this URL parameter
287
	 * @return array Array of URL variables to interpolate; empty if no match
288
	 */
289
	static function extractTitle( $path, $bases, $key = false ) {
290
		foreach ( (array)$bases as $keyValue => $base ) {
291
			// Find the part after $wgArticlePath
292
			$base = str_replace( '$1', '', $base );
293
			$baseLen = strlen( $base );
294
			if ( substr( $path, 0, $baseLen ) == $base ) {
295
				$raw = substr( $path, $baseLen );
296
				if ( $raw !== '' ) {
297
					$matches = [ 'title' => rawurldecode( $raw ) ];
298
					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...
299
						$matches[$key] = $keyValue;
300
					}
301
					return $matches;
302
				}
303
			}
304
		}
305
		return [];
306
	}
307
308
	/**
309
	 * Recursively normalizes UTF-8 strings in the given array.
310
	 *
311
	 * @param string|array $data
312
	 * @return array|string Cleaned-up version of the given
313
	 * @private
314
	 */
315
	function normalizeUnicode( $data ) {
316
		if ( is_array( $data ) ) {
317
			foreach ( $data as $key => $val ) {
318
				$data[$key] = $this->normalizeUnicode( $val );
319
			}
320
		} else {
321
			global $wgContLang;
322
			$data = isset( $wgContLang ) ?
323
				$wgContLang->normalize( $data ) :
324
				UtfNormal\Validator::cleanUp( $data );
325
		}
326
		return $data;
327
	}
328
329
	/**
330
	 * Fetch a value from the given array or return $default if it's not set.
331
	 *
332
	 * @param array $arr
333
	 * @param string $name
334
	 * @param mixed $default
335
	 * @return mixed
336
	 */
337
	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...
338
		# PHP is so nice to not touch input data, except sometimes:
339
		# http://us2.php.net/variables.external#language.variables.external.dot-in-names
340
		# Work around PHP *feature* to avoid *bugs* elsewhere.
341
		$name = strtr( $name, '.', '_' );
342
		if ( isset( $arr[$name] ) ) {
343
			global $wgContLang;
344
			$data = $arr[$name];
345
			if ( isset( $_GET[$name] ) && !is_array( $data ) ) {
346
				# Check for alternate/legacy character encoding.
347
				if ( isset( $wgContLang ) ) {
348
					$data = $wgContLang->checkTitleEncoding( $data );
349
				}
350
			}
351
			$data = $this->normalizeUnicode( $data );
352
			return $data;
353
		} else {
354
			return $default;
355
		}
356
	}
357
358
	/**
359
	 * Fetch a scalar from the input or return $default if it's not set.
360
	 * Returns a string. Arrays are discarded. Useful for
361
	 * non-freeform text inputs (e.g. predefined internal text keys
362
	 * selected by a drop-down menu). For freeform input, see getText().
363
	 *
364
	 * @param string $name
365
	 * @param string $default Optional default (or null)
366
	 * @return string
367
	 */
368
	public function getVal( $name, $default = null ) {
369
		$val = $this->getGPCVal( $this->data, $name, $default );
370
		if ( is_array( $val ) ) {
371
			$val = $default;
372
		}
373
		if ( is_null( $val ) ) {
374
			return $val;
375
		} else {
376
			return (string)$val;
377
		}
378
	}
379
380
	/**
381
	 * Set an arbitrary value into our get/post data.
382
	 *
383
	 * @param string $key Key name to use
384
	 * @param mixed $value Value to set
385
	 * @return mixed Old value if one was present, null otherwise
386
	 */
387
	public function setVal( $key, $value ) {
388
		$ret = isset( $this->data[$key] ) ? $this->data[$key] : null;
389
		$this->data[$key] = $value;
390
		return $ret;
391
	}
392
393
	/**
394
	 * Unset an arbitrary value from our get/post data.
395
	 *
396
	 * @param string $key Key name to use
397
	 * @return mixed Old value if one was present, null otherwise
398
	 */
399
	public function unsetVal( $key ) {
400 View Code Duplication
		if ( !isset( $this->data[$key] ) ) {
401
			$ret = null;
402
		} else {
403
			$ret = $this->data[$key];
404
			unset( $this->data[$key] );
405
		}
406
		return $ret;
407
	}
408
409
	/**
410
	 * Fetch an array from the input or return $default if it's not set.
411
	 * If source was scalar, will return an array with a single element.
412
	 * If no source and no default, returns null.
413
	 *
414
	 * @param string $name
415
	 * @param array $default Optional default (or null)
416
	 * @return array
417
	 */
418
	public function getArray( $name, $default = null ) {
419
		$val = $this->getGPCVal( $this->data, $name, $default );
420
		if ( is_null( $val ) ) {
421
			return null;
422
		} else {
423
			return (array)$val;
424
		}
425
	}
426
427
	/**
428
	 * Fetch an array of integers, or return $default if it's not set.
429
	 * If source was scalar, will return an array with a single element.
430
	 * If no source and no default, returns null.
431
	 * If an array is returned, contents are guaranteed to be integers.
432
	 *
433
	 * @param string $name
434
	 * @param array $default Option default (or null)
435
	 * @return array Array of ints
436
	 */
437
	public function getIntArray( $name, $default = null ) {
438
		$val = $this->getArray( $name, $default );
439
		if ( is_array( $val ) ) {
440
			$val = array_map( 'intval', $val );
441
		}
442
		return $val;
443
	}
444
445
	/**
446
	 * Fetch an integer value from the input or return $default if not set.
447
	 * Guaranteed to return an integer; non-numeric input will typically
448
	 * return 0.
449
	 *
450
	 * @param string $name
451
	 * @param int $default
452
	 * @return int
453
	 */
454
	public function getInt( $name, $default = 0 ) {
455
		return intval( $this->getVal( $name, $default ) );
456
	}
457
458
	/**
459
	 * Fetch an integer value from the input or return null if empty.
460
	 * Guaranteed to return an integer or null; non-numeric input will
461
	 * typically return null.
462
	 *
463
	 * @param string $name
464
	 * @return int|null
465
	 */
466
	public function getIntOrNull( $name ) {
467
		$val = $this->getVal( $name );
468
		return is_numeric( $val )
469
			? intval( $val )
470
			: null;
471
	}
472
473
	/**
474
	 * Fetch a floating point value from the input or return $default if not set.
475
	 * Guaranteed to return a float; non-numeric input will typically
476
	 * return 0.
477
	 *
478
	 * @since 1.23
479
	 * @param string $name
480
	 * @param float $default
481
	 * @return float
482
	 */
483
	public function getFloat( $name, $default = 0.0 ) {
484
		return floatval( $this->getVal( $name, $default ) );
485
	}
486
487
	/**
488
	 * Fetch a boolean value from the input or return $default if not set.
489
	 * Guaranteed to return true or false, with normal PHP semantics for
490
	 * boolean interpretation of strings.
491
	 *
492
	 * @param string $name
493
	 * @param bool $default
494
	 * @return bool
495
	 */
496
	public function getBool( $name, $default = false ) {
497
		return (bool)$this->getVal( $name, $default );
498
	}
499
500
	/**
501
	 * Fetch a boolean value from the input or return $default if not set.
502
	 * Unlike getBool, the string "false" will result in boolean false, which is
503
	 * useful when interpreting information sent from JavaScript.
504
	 *
505
	 * @param string $name
506
	 * @param bool $default
507
	 * @return bool
508
	 */
509
	public function getFuzzyBool( $name, $default = false ) {
510
		return $this->getBool( $name, $default ) && strcasecmp( $this->getVal( $name ), 'false' ) !== 0;
511
	}
512
513
	/**
514
	 * Return true if the named value is set in the input, whatever that
515
	 * value is (even "0"). Return false if the named value is not set.
516
	 * Example use is checking for the presence of check boxes in forms.
517
	 *
518
	 * @param string $name
519
	 * @return bool
520
	 */
521
	public function getCheck( $name ) {
522
		# Checkboxes and buttons are only present when clicked
523
		# Presence connotes truth, absence false
524
		return $this->getVal( $name, null ) !== null;
525
	}
526
527
	/**
528
	 * Fetch a text string from the given array or return $default if it's not
529
	 * set. Carriage returns are stripped from the text, and with some language
530
	 * modules there is an input transliteration applied. This should generally
531
	 * be used for form "<textarea>" and "<input>" fields. Used for
532
	 * user-supplied freeform text input (for which input transformations may
533
	 * be required - e.g.  Esperanto x-coding).
534
	 *
535
	 * @param string $name
536
	 * @param string $default Optional
537
	 * @return string
538
	 */
539
	public function getText( $name, $default = '' ) {
540
		global $wgContLang;
541
		$val = $this->getVal( $name, $default );
542
		return str_replace( "\r\n", "\n",
543
			$wgContLang->recodeInput( $val ) );
544
	}
545
546
	/**
547
	 * Extracts the given named values into an array.
548
	 * If no arguments are given, returns all input values.
549
	 * No transformation is performed on the values.
550
	 *
551
	 * @return array
552
	 */
553
	public function getValues() {
554
		$names = func_get_args();
555
		if ( count( $names ) == 0 ) {
556
			$names = array_keys( $this->data );
557
		}
558
559
		$retVal = [];
560
		foreach ( $names as $name ) {
561
			$value = $this->getGPCVal( $this->data, $name, null );
562
			if ( !is_null( $value ) ) {
563
				$retVal[$name] = $value;
564
			}
565
		}
566
		return $retVal;
567
	}
568
569
	/**
570
	 * Returns the names of all input values excluding those in $exclude.
571
	 *
572
	 * @param array $exclude
573
	 * @return array
574
	 */
575
	public function getValueNames( $exclude = [] ) {
576
		return array_diff( array_keys( $this->getValues() ), $exclude );
577
	}
578
579
	/**
580
	 * Get the values passed in the query string.
581
	 * No transformation is performed on the values.
582
	 *
583
	 * @return array
584
	 */
585
	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...
586
		return $_GET;
587
	}
588
589
	/**
590
	 * Return the contents of the Query with no decoding. Use when you need to
591
	 * know exactly what was sent, e.g. for an OAuth signature over the elements.
592
	 *
593
	 * @return string
594
	 */
595
	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...
596
		return $_SERVER['QUERY_STRING'];
597
	}
598
599
	/**
600
	 * Return the contents of the POST with no decoding. Use when you need to
601
	 * know exactly what was sent, e.g. for an OAuth signature over the elements.
602
	 *
603
	 * @return string
604
	 */
605
	public function getRawPostString() {
606
		if ( !$this->wasPosted() ) {
607
			return '';
608
		}
609
		return $this->getRawInput();
610
	}
611
612
	/**
613
	 * Return the raw request body, with no processing. Cached since some methods
614
	 * disallow reading the stream more than once. As stated in the php docs, this
615
	 * does not work with enctype="multipart/form-data".
616
	 *
617
	 * @return string
618
	 */
619
	public function getRawInput() {
620
		static $input = null;
621
		if ( $input === null ) {
622
			$input = file_get_contents( 'php://input' );
623
		}
624
		return $input;
625
	}
626
627
	/**
628
	 * Get the HTTP method used for this request.
629
	 *
630
	 * @return string
631
	 */
632
	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...
633
		return isset( $_SERVER['REQUEST_METHOD'] ) ? $_SERVER['REQUEST_METHOD'] : 'GET';
634
	}
635
636
	/**
637
	 * Returns true if the present request was reached by a POST operation,
638
	 * false otherwise (GET, HEAD, or command-line).
639
	 *
640
	 * Note that values retrieved by the object may come from the
641
	 * GET URL etc even on a POST request.
642
	 *
643
	 * @return bool
644
	 */
645
	public function wasPosted() {
646
		return $this->getMethod() == 'POST';
647
	}
648
649
	/**
650
	 * Return the session for this request
651
	 * @since 1.27
652
	 * @note For performance, keep the session locally if you will be making
653
	 *  much use of it instead of calling this method repeatedly.
654
	 * @return MediaWiki\\Session\\Session
0 ignored issues
show
Documentation introduced by
The doc-type MediaWiki\\Session\\Session could not be parsed: Unknown type name "MediaWiki\\Session\\Session" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
655
	 */
656
	public function getSession() {
657
		if ( $this->sessionId !== null ) {
658
			$session = SessionManager::singleton()->getSessionById( (string)$this->sessionId, true, $this );
659
			if ( $session ) {
660
				return $session;
661
			}
662
		}
663
664
		$session = SessionManager::singleton()->getSessionForRequest( $this );
665
		$this->sessionId = $session->getSessionId();
0 ignored issues
show
Documentation Bug introduced by
It seems like $session->getSessionId() of type object<MediaWiki\Session\SessionId> is incompatible with the declared type object<\MediaWiki\\Session\\SessionId>|null of property $sessionId.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
666
		return $session;
667
	}
668
669
	/**
670
	 * Set the session for this request
671
	 * @since 1.27
672
	 * @private For use by MediaWiki\\Session classes only
673
	 * @param MediaWiki\\Session\\SessionId $sessionId
0 ignored issues
show
Documentation introduced by
The doc-type MediaWiki\\Session\\SessionId could not be parsed: Unknown type name "MediaWiki\\Session\\SessionId" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
674
	 */
675
	public function setSessionId( MediaWiki\Session\SessionId $sessionId ) {
676
		$this->sessionId = $sessionId;
0 ignored issues
show
Documentation Bug introduced by
It seems like $sessionId of type object<MediaWiki\Session\SessionId> is incompatible with the declared type object<\MediaWiki\\Session\\SessionId>|null of property $sessionId.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
677
	}
678
679
	/**
680
	 * Get the session id for this request, if any
681
	 * @since 1.27
682
	 * @private For use by MediaWiki\\Session classes only
683
	 * @return MediaWiki\\Session\\SessionId|null
0 ignored issues
show
Documentation introduced by
The doc-type MediaWiki\\Session\\SessionId|null could not be parsed: Unknown type name "MediaWiki\\Session\\SessionId" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
684
	 */
685
	public function getSessionId() {
686
		return $this->sessionId;
687
	}
688
689
	/**
690
	 * Returns true if the request has a persistent session.
691
	 * This does not necessarily mean that the user is logged in!
692
	 *
693
	 * @deprecated since 1.27, use
694
	 *  \\MediaWiki\\Session\\SessionManager::singleton()->getPersistedSessionId()
695
	 *  instead.
696
	 * @return bool
697
	 */
698
	public function checkSessionCookie() {
699
		global $wgInitialSessionId;
700
		wfDeprecated( __METHOD__, '1.27' );
701
		return $wgInitialSessionId !== null &&
702
			$this->getSession()->getId() === (string)$wgInitialSessionId;
703
	}
704
705
	/**
706
	 * Get a cookie from the $_COOKIE jar
707
	 *
708
	 * @param string $key The name of the cookie
709
	 * @param string $prefix A prefix to use for the cookie name, if not $wgCookiePrefix
710
	 * @param mixed $default What to return if the value isn't found
711
	 * @return mixed Cookie value or $default if the cookie not set
712
	 */
713
	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...
714
		if ( $prefix === null ) {
715
			global $wgCookiePrefix;
716
			$prefix = $wgCookiePrefix;
717
		}
718
		return $this->getGPCVal( $_COOKIE, $prefix . $key, $default );
719
	}
720
721
	/**
722
	 * Return the path and query string portion of the main request URI.
723
	 * This will be suitable for use as a relative link in HTML output.
724
	 *
725
	 * @throws MWException
726
	 * @return string
727
	 */
728
	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...
729
		if ( isset( $_SERVER['REQUEST_URI'] ) && strlen( $_SERVER['REQUEST_URI'] ) ) {
730
			$base = $_SERVER['REQUEST_URI'];
731
		} elseif ( isset( $_SERVER['HTTP_X_ORIGINAL_URL'] )
732
			&& strlen( $_SERVER['HTTP_X_ORIGINAL_URL'] )
733
		) {
734
			// Probably IIS; doesn't set REQUEST_URI
735
			$base = $_SERVER['HTTP_X_ORIGINAL_URL'];
736
		} elseif ( isset( $_SERVER['SCRIPT_NAME'] ) ) {
737
			$base = $_SERVER['SCRIPT_NAME'];
738
			if ( isset( $_SERVER['QUERY_STRING'] ) && $_SERVER['QUERY_STRING'] != '' ) {
739
				$base .= '?' . $_SERVER['QUERY_STRING'];
740
			}
741
		} else {
742
			// This shouldn't happen!
743
			throw new MWException( "Web server doesn't provide either " .
744
				"REQUEST_URI, HTTP_X_ORIGINAL_URL or SCRIPT_NAME. Report details " .
745
				"of your web server configuration to https://phabricator.wikimedia.org/" );
746
		}
747
		// User-agents should not send a fragment with the URI, but
748
		// if they do, and the web server passes it on to us, we
749
		// need to strip it or we get false-positive redirect loops
750
		// or weird output URLs
751
		$hash = strpos( $base, '#' );
752
		if ( $hash !== false ) {
753
			$base = substr( $base, 0, $hash );
754
		}
755
756
		if ( $base[0] == '/' ) {
757
			// More than one slash will look like it is protocol relative
758
			return preg_replace( '!^/+!', '/', $base );
759
		} else {
760
			// We may get paths with a host prepended; strip it.
761
			return preg_replace( '!^[^:]+://[^/]+/+!', '/', $base );
762
		}
763
	}
764
765
	/**
766
	 * Return the path and query string portion of the request URI.
767
	 * This will be suitable for use as a relative link in HTML output.
768
	 *
769
	 * @throws MWException
770
	 * @return string
771
	 */
772
	public function getRequestURL() {
773
		return self::getGlobalRequestURL();
774
	}
775
776
	/**
777
	 * Return the request URI with the canonical service and hostname, path,
778
	 * and query string. This will be suitable for use as an absolute link
779
	 * in HTML or other output.
780
	 *
781
	 * If $wgServer is protocol-relative, this will return a fully
782
	 * qualified URL with the protocol that was used for this request.
783
	 *
784
	 * @return string
785
	 */
786
	public function getFullRequestURL() {
787
		return wfExpandUrl( $this->getRequestURL(), PROTO_CURRENT );
788
	}
789
790
	/**
791
	 * @param string $key
792
	 * @param string $value
793
	 * @return string
794
	 */
795
	public function appendQueryValue( $key, $value ) {
796
		return $this->appendQueryArray( [ $key => $value ] );
797
	}
798
799
	/**
800
	 * Appends or replaces value of query variables.
801
	 *
802
	 * @param array $array Array of values to replace/add to query
803
	 * @return string
804
	 */
805
	public function appendQueryArray( $array ) {
806
		$newquery = $this->getQueryValues();
807
		unset( $newquery['title'] );
808
		$newquery = array_merge( $newquery, $array );
809
810
		return wfArrayToCgi( $newquery );
811
	}
812
813
	/**
814
	 * Check for limit and offset parameters on the input, and return sensible
815
	 * defaults if not given. The limit must be positive and is capped at 5000.
816
	 * Offset must be positive but is not capped.
817
	 *
818
	 * @param int $deflimit Limit to use if no input and the user hasn't set the option.
819
	 * @param string $optionname To specify an option other than rclimit to pull from.
820
	 * @return int[] First element is limit, second is offset
821
	 */
822
	public function getLimitOffset( $deflimit = 50, $optionname = 'rclimit' ) {
823
		global $wgUser;
824
825
		$limit = $this->getInt( 'limit', 0 );
826
		if ( $limit < 0 ) {
827
			$limit = 0;
828
		}
829
		if ( ( $limit == 0 ) && ( $optionname != '' ) ) {
830
			$limit = $wgUser->getIntOption( $optionname );
831
		}
832
		if ( $limit <= 0 ) {
833
			$limit = $deflimit;
834
		}
835
		if ( $limit > 5000 ) {
836
			$limit = 5000; # We have *some* limits...
837
		}
838
839
		$offset = $this->getInt( 'offset', 0 );
840
		if ( $offset < 0 ) {
841
			$offset = 0;
842
		}
843
844
		return [ $limit, $offset ];
845
	}
846
847
	/**
848
	 * Return the path to the temporary file where PHP has stored the upload.
849
	 *
850
	 * @param string $key
851
	 * @return string|null String or null if no such file.
852
	 */
853
	public function getFileTempname( $key ) {
854
		$file = new WebRequestUpload( $this, $key );
855
		return $file->getTempName();
856
	}
857
858
	/**
859
	 * Return the upload error or 0
860
	 *
861
	 * @param string $key
862
	 * @return int
863
	 */
864
	public function getUploadError( $key ) {
865
		$file = new WebRequestUpload( $this, $key );
866
		return $file->getError();
867
	}
868
869
	/**
870
	 * Return the original filename of the uploaded file, as reported by
871
	 * the submitting user agent. HTML-style character entities are
872
	 * interpreted and normalized to Unicode normalization form C, in part
873
	 * to deal with weird input from Safari with non-ASCII filenames.
874
	 *
875
	 * Other than this the name is not verified for being a safe filename.
876
	 *
877
	 * @param string $key
878
	 * @return string|null String or null if no such file.
879
	 */
880
	public function getFileName( $key ) {
881
		$file = new WebRequestUpload( $this, $key );
882
		return $file->getName();
883
	}
884
885
	/**
886
	 * Return a WebRequestUpload object corresponding to the key
887
	 *
888
	 * @param string $key
889
	 * @return WebRequestUpload
890
	 */
891
	public function getUpload( $key ) {
892
		return new WebRequestUpload( $this, $key );
893
	}
894
895
	/**
896
	 * Return a handle to WebResponse style object, for setting cookies,
897
	 * headers and other stuff, for Request being worked on.
898
	 *
899
	 * @return WebResponse
900
	 */
901
	public function response() {
902
		/* Lazy initialization of response object for this request */
903
		if ( !is_object( $this->response ) ) {
904
			$class = ( $this instanceof FauxRequest ) ? 'FauxResponse' : 'WebResponse';
905
			$this->response = new $class();
906
		}
907
		return $this->response;
908
	}
909
910
	/**
911
	 * Initialise the header list
912
	 */
913
	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...
914
		if ( count( $this->headers ) ) {
915
			return;
916
		}
917
918
		$apacheHeaders = function_exists( 'apache_request_headers' ) ? apache_request_headers() : false;
919
		if ( $apacheHeaders ) {
920
			foreach ( $apacheHeaders as $tempName => $tempValue ) {
921
				$this->headers[strtoupper( $tempName )] = $tempValue;
922
			}
923
		} else {
924
			foreach ( $_SERVER as $name => $value ) {
925
				if ( substr( $name, 0, 5 ) === 'HTTP_' ) {
926
					$name = str_replace( '_', '-', substr( $name, 5 ) );
927
					$this->headers[$name] = $value;
928
				} elseif ( $name === 'CONTENT_LENGTH' ) {
929
					$this->headers['CONTENT-LENGTH'] = $value;
930
				}
931
			}
932
		}
933
	}
934
935
	/**
936
	 * Get an array containing all request headers
937
	 *
938
	 * @return array Mapping header name to its value
939
	 */
940
	public function getAllHeaders() {
941
		$this->initHeaders();
942
		return $this->headers;
943
	}
944
945
	/**
946
	 * Get a request header, or false if it isn't set.
947
	 *
948
	 * @param string $name Case-insensitive header name
949
	 * @param int $flags Bitwise combination of:
950
	 *   WebRequest::GETHEADER_LIST  Treat the header as a comma-separated list
951
	 *                               of values, as described in RFC 2616 § 4.2.
952
	 *                               (since 1.26).
953
	 * @return string|array|bool False if header is unset; otherwise the
954
	 *  header value(s) as either a string (the default) or an array, if
955
	 *  WebRequest::GETHEADER_LIST flag was set.
956
	 */
957
	public function getHeader( $name, $flags = 0 ) {
958
		$this->initHeaders();
959
		$name = strtoupper( $name );
960
		if ( !isset( $this->headers[$name] ) ) {
961
			return false;
962
		}
963
		$value = $this->headers[$name];
964
		if ( $flags & self::GETHEADER_LIST ) {
965
			$value = array_map( 'trim', explode( ',', $value ) );
966
		}
967
		return $value;
968
	}
969
970
	/**
971
	 * Get data from the session
972
	 *
973
	 * @note Prefer $this->getSession() instead if making multiple calls.
974
	 * @param string $key Name of key in the session
975
	 * @return mixed
976
	 */
977
	public function getSessionData( $key ) {
978
		return $this->getSession()->get( $key );
979
	}
980
981
	/**
982
	 * Set session data
983
	 *
984
	 * @note Prefer $this->getSession() instead if making multiple calls.
985
	 * @param string $key Name of key in the session
986
	 * @param mixed $data
987
	 */
988
	public function setSessionData( $key, $data ) {
989
		return $this->getSession()->set( $key, $data );
990
	}
991
992
	/**
993
	 * Check if Internet Explorer will detect an incorrect cache extension in
994
	 * PATH_INFO or QUERY_STRING. If the request can't be allowed, show an error
995
	 * message or redirect to a safer URL. Returns true if the URL is OK, and
996
	 * false if an error message has been shown and the request should be aborted.
997
	 *
998
	 * @param array $extWhitelist
999
	 * @throws HttpError
1000
	 * @return bool
1001
	 */
1002
	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...
1003
		$extWhitelist[] = 'php';
1004
		if ( IEUrlExtension::areServerVarsBad( $_SERVER, $extWhitelist ) ) {
1005
			if ( !$this->wasPosted() ) {
1006
				$newUrl = IEUrlExtension::fixUrlForIE6(
1007
					$this->getFullRequestURL(), $extWhitelist );
1008
				if ( $newUrl !== false ) {
1009
					$this->doSecurityRedirect( $newUrl );
1010
					return false;
1011
				}
1012
			}
1013
			throw new HttpError( 403,
1014
				'Invalid file extension found in the path info or query string.' );
1015
		}
1016
		return true;
1017
	}
1018
1019
	/**
1020
	 * Attempt to redirect to a URL with a QUERY_STRING that's not dangerous in
1021
	 * IE 6. Returns true if it was successful, false otherwise.
1022
	 *
1023
	 * @param string $url
1024
	 * @return bool
1025
	 */
1026
	protected function doSecurityRedirect( $url ) {
1027
		header( 'Location: ' . $url );
1028
		header( 'Content-Type: text/html' );
1029
		$encUrl = htmlspecialchars( $url );
1030
		echo <<<HTML
1031
<html>
1032
<head>
1033
<title>Security redirect</title>
1034
</head>
1035
<body>
1036
<h1>Security redirect</h1>
1037
<p>
1038
We can't serve non-HTML content from the URL you have requested, because
1039
Internet Explorer would interpret it as an incorrect and potentially dangerous
1040
content type.</p>
1041
<p>Instead, please use <a href="$encUrl">this URL</a>, which is the same as the
1042
URL you have requested, except that "&amp;*" is appended. This prevents Internet
1043
Explorer from seeing a bogus file extension.
1044
</p>
1045
</body>
1046
</html>
1047
HTML;
1048
		echo "\n";
1049
		return true;
1050
	}
1051
1052
	/**
1053
	 * Parse the Accept-Language header sent by the client into an array
1054
	 *
1055
	 * @return array Array( languageCode => q-value ) sorted by q-value in
1056
	 *   descending order then appearing time in the header in ascending order.
1057
	 * May contain the "language" '*', which applies to languages other than those explicitly listed.
1058
	 * This is aligned with rfc2616 section 14.4
1059
	 * Preference for earlier languages appears in rfc3282 as an extension to HTTP/1.1.
1060
	 */
1061
	public function getAcceptLang() {
1062
		// Modified version of code found at
1063
		// http://www.thefutureoftheweb.com/blog/use-accept-language-header
1064
		$acceptLang = $this->getHeader( 'Accept-Language' );
1065
		if ( !$acceptLang ) {
1066
			return [];
1067
		}
1068
1069
		// Return the language codes in lower case
1070
		$acceptLang = strtolower( $acceptLang );
1071
1072
		// Break up string into pieces (languages and q factors)
1073
		$lang_parse = null;
1074
		preg_match_all(
1075
			'/([a-z]{1,8}(-[a-z]{1,8})*|\*)\s*(;\s*q\s*=\s*(1(\.0{0,3})?|0(\.[0-9]{0,3})?)?)?/',
1076
			$acceptLang,
1077
			$lang_parse
1078
		);
1079
1080
		if ( !count( $lang_parse[1] ) ) {
1081
			return [];
1082
		}
1083
1084
		$langcodes = $lang_parse[1];
1085
		$qvalues = $lang_parse[4];
1086
		$indices = range( 0, count( $lang_parse[1] ) - 1 );
1087
1088
		// Set default q factor to 1
1089
		foreach ( $indices as $index ) {
1090
			if ( $qvalues[$index] === '' ) {
1091
				$qvalues[$index] = 1;
1092
			} elseif ( $qvalues[$index] == 0 ) {
1093
				unset( $langcodes[$index], $qvalues[$index], $indices[$index] );
1094
			}
1095
		}
1096
1097
		// Sort list. First by $qvalues, then by order. Reorder $langcodes the same way
1098
		array_multisort( $qvalues, SORT_DESC, SORT_NUMERIC, $indices, $langcodes );
1099
1100
		// Create a list like "en" => 0.8
1101
		$langs = array_combine( $langcodes, $qvalues );
1102
1103
		return $langs;
1104
	}
1105
1106
	/**
1107
	 * Fetch the raw IP from the request
1108
	 *
1109
	 * @since 1.19
1110
	 *
1111
	 * @throws MWException
1112
	 * @return string
1113
	 */
1114
	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...
1115
		if ( !isset( $_SERVER['REMOTE_ADDR'] ) ) {
1116
			return null;
1117
		}
1118
1119
		if ( is_array( $_SERVER['REMOTE_ADDR'] ) || strpos( $_SERVER['REMOTE_ADDR'], ',' ) !== false ) {
1120
			throw new MWException( __METHOD__
1121
				. " : Could not determine the remote IP address due to multiple values." );
1122
		} else {
1123
			$ipchain = $_SERVER['REMOTE_ADDR'];
1124
		}
1125
1126
		return IP::canonicalize( $ipchain );
1127
	}
1128
1129
	/**
1130
	 * Work out the IP address based on various globals
1131
	 * For trusted proxies, use the XFF client IP (first of the chain)
1132
	 *
1133
	 * @since 1.19
1134
	 *
1135
	 * @throws MWException
1136
	 * @return string
1137
	 */
1138
	public function getIP() {
1139
		global $wgUsePrivateIPs;
1140
1141
		# Return cached result
1142
		if ( $this->ip !== null ) {
1143
			return $this->ip;
1144
		}
1145
1146
		# collect the originating ips
1147
		$ip = $this->getRawIP();
1148
		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...
1149
			throw new MWException( 'Unable to determine IP.' );
1150
		}
1151
1152
		# Append XFF
1153
		$forwardedFor = $this->getHeader( 'X-Forwarded-For' );
1154
		if ( $forwardedFor !== false ) {
1155
			$isConfigured = IP::isConfiguredProxy( $ip );
1156
			$ipchain = array_map( 'trim', explode( ',', $forwardedFor ) );
1157
			$ipchain = array_reverse( $ipchain );
1158
			array_unshift( $ipchain, $ip );
1159
1160
			# Step through XFF list and find the last address in the list which is a
1161
			# trusted server. Set $ip to the IP address given by that trusted server,
1162
			# unless the address is not sensible (e.g. private). However, prefer private
1163
			# IP addresses over proxy servers controlled by this site (more sensible).
1164
			# Note that some XFF values might be "unknown" with Squid/Varnish.
1165
			foreach ( $ipchain as $i => $curIP ) {
1166
				$curIP = IP::sanitizeIP( IP::canonicalize( $curIP ) );
1167
				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...
1168
					|| !IP::isTrustedProxy( $curIP )
1169
				) {
1170
					break; // IP is not valid/trusted or does not point to anything
1171
				}
1172
				if (
1173
					IP::isPublic( $ipchain[$i + 1] ) ||
1174
					$wgUsePrivateIPs ||
1175
					IP::isConfiguredProxy( $curIP ) // bug 48919; treat IP as sane
1176
				) {
1177
					// Follow the next IP according to the proxy
1178
					$nextIP = IP::canonicalize( $ipchain[$i + 1] );
1179
					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...
1180
						// We have not yet made it past CDN/proxy servers of this site,
1181
						// so either they are misconfigured or there is some IP spoofing.
1182
						throw new MWException( "Invalid IP given in XFF '$forwardedFor'." );
1183
					}
1184
					$ip = $nextIP;
1185
					// keep traversing the chain
1186
					continue;
1187
				}
1188
				break;
1189
			}
1190
		}
1191
1192
		# Allow extensions to improve our guess
1193
		Hooks::run( 'GetIP', [ &$ip ] );
1194
1195
		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...
1196
			throw new MWException( "Unable to determine IP." );
1197
		}
1198
1199
		wfDebug( "IP: $ip\n" );
1200
		$this->ip = $ip;
1201
		return $ip;
1202
	}
1203
1204
	/**
1205
	 * @param string $ip
1206
	 * @return void
1207
	 * @since 1.21
1208
	 */
1209
	public function setIP( $ip ) {
1210
		$this->ip = $ip;
1211
	}
1212
}
1213