/
Request.php
508 lines (424 loc) · 11.6 KB
/
Request.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
<?php
namespace Elgg\Http;
use Elgg\BadRequestException;
use Elgg\Context;
use Elgg\HttpException;
use Elgg\Router\Route;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\Request as SymfonyRequest;
use Elgg\Config;
/**
* Elgg HTTP request.
*
* @internal
*/
class Request extends SymfonyRequest {
const REWRITE_TEST_TOKEN = '__testing_rewrite';
const REWRITE_TEST_OUTPUT = 'success';
/**
* @var Context
*/
protected $context_stack;
/**
* @var Route
*/
protected $route;
/**
* @ var array
*/
protected $request_overrides;
/**
* {@inheritdoc}
*/
public function __construct(
array $query = [],
array $request = [],
array $attributes = [],
array $cookies = [],
array $files = [],
array $server = [],
$content = null
) {
parent::__construct($query, $request, $attributes, $cookies, $files, $server, $content);
$this->initializeContext();
$this->request_overrides = [];
}
/**
* Configure trusted proxy servers to allow access to more client information
*
* @return void
*/
public function initializeTrustedProxyConfiguration(Config $config) {
$trusted_proxies = $config->http_request_trusted_proxy_ips;
if (empty($trusted_proxies)) {
return;
}
$allowed_headers = $config->http_request_trusted_proxy_headers;
if (empty($allowed_headers)) {
$allowed_headers = self::HEADER_X_FORWARDED_ALL;
}
$this->setTrustedProxies($trusted_proxies, $allowed_headers);
}
/**
* Initialize context stack
* @return static
*/
public function initializeContext() {
$context = new Context($this);
$this->context_stack = $context;
return $this;
}
/**
* Returns context stack
* @return Context
*/
public function getContextStack() {
return $this->context_stack;
}
/**
* Sets the route matched for this request by the router
*
* @param Route $route Route
*
* @return static
*/
public function setRoute(Route $route) {
$this->route = $route;
foreach ($route->getMatchedParameters() as $key => $value) {
$this->setParam($key, $value);
}
return $this;
}
/**
* Returns the route matched for this request by the router
* @return Route|null
*/
public function getRoute() {
return $this->route;
}
/**
* Sets an input value that may later be retrieved by get_input
*
* Note: this function does not handle nested arrays (ex: form input of param[m][n])
*
* @param string $key The name of the variable
* @param string|string[] $value The value of the variable
* @param bool $override_request The variable should override request values (default: false)
*
* @return static
*/
public function setParam($key, $value, $override_request = false) {
if ((bool) $override_request) {
$this->request_overrides[$key] = $value;
} else {
$this->request->set($key, $value);
}
return $this;
}
/**
* Get some input from variables passed submitted through GET or POST.
*
* If using any data obtained from get_input() in a web page, please be aware that
* it is a possible vector for a reflected XSS attack. If you are expecting an
* integer, cast it to an int. If it is a string, escape quotes.
*
* Note: this function does not handle nested arrays (ex: form input of param[m][n])
* because of the filtering done in htmlawed from the filter_tags call.
* @todo Is this ^ still true?
*
* @param string $key The variable name we want.
* @param mixed $default A default value for the variable if it is not found.
* @param bool $filter_result If true, then the result is filtered for bad tags.
*
* @return mixed
*/
public function getParam($key, $default = null, $filter_result = true) {
$result = $default;
$values = $this->getParams($filter_result);
$value = elgg_extract($key, $values, $default);
if ($value !== null) {
$result = $value;
}
return $result;
}
/**
* Returns all values parsed from the request
*
* @param bool $filter_result Sanitize input values
*
* @return array
*/
public function getParams($filter_result = true) {
$request_overrides = $this->request_overrides;
$query = $this->query->all();
$attributes = $this->attributes->all();
$post = $this->request->all();
$result = array_merge($post, $attributes, $query, $request_overrides);
if ($filter_result) {
$this->getContextStack()->push('input');
$result = filter_tags($result);
$this->getContextStack()->pop();
}
return $result;
}
/**
* Returns current page URL
*
* @return string
*/
public function getCurrentURL() {
$url = parse_url(elgg_get_site_url());
$page = $url['scheme'] . "://" . $url['host'];
if (isset($url['port']) && $url['port']) {
$page .= ":" . $url['port'];
}
$page = trim($page, "/");
$page .= $this->getRequestUri();
return $page;
}
/**
* Get the Elgg URL segments
*
* @param bool $raw If true, the segments will not be HTML escaped
*
* @return string[]
*/
public function getUrlSegments($raw = false) {
$path = trim($this->getElggPath(), '/');
if (!$raw) {
$path = htmlspecialchars($path, ENT_QUOTES, 'UTF-8');
}
if (!$path) {
return [];
}
return explode('/', $path);
}
/**
* Get a cloned request with new Elgg URL segments
*
* @param string[] $segments URL segments
*
* @return Request
*/
public function setUrlSegments(array $segments) {
$base_path = trim($this->getBasePath(), '/');
$server = $this->server->all();
$server['REQUEST_URI'] = "$base_path/" . implode('/', $segments);
return $this->duplicate(null, null, null, null, null, $server);
}
/**
* Get first Elgg URL segment
*
* @see \Elgg\Http\Request::getUrlSegments()
*
* @return string
*/
public function getFirstUrlSegment() {
$segments = $this->getUrlSegments();
if (!empty($segments)) {
return array_shift($segments);
}
return '';
}
/**
* Get the Request URI minus querystring
*
* @return string
*/
public function getElggPath() {
if (php_sapi_name() === 'cli-server') {
$path = $this->getRequestUri();
} else {
$path = $this->getPathInfo();
}
return preg_replace('~(\?.*)$~', '', $path);
}
/**
* {@inheritdoc}
*/
public function getClientIp() {
$ip = parent::getClientIp();
if ($ip == $this->server->get('REMOTE_ADDR')) {
// try one more
$ip_addresses = $this->server->get('HTTP_X_REAL_IP');
if ($ip_addresses) {
$ip_addresses = explode(',', $ip_addresses);
return array_pop($ip_addresses);
}
}
return $ip;
}
/**
* {@inheritdoc}
*/
public function isXmlHttpRequest() {
return (strtolower($this->headers->get('X-Requested-With')) === 'xmlhttprequest'
|| $this->query->get('X-Requested-With') === 'XMLHttpRequest'
|| $this->request->get('X-Requested-With') === 'XMLHttpRequest');
// GET/POST check is necessary for jQuery.form and other iframe-based "ajax". #8735
}
/**
* Sniff the Elgg site URL with trailing slash
*
* @return string
*/
public function sniffElggUrl() {
$base_url = $this->getBaseUrl();
// baseURL may end with the PHP script
if ('.php' === substr($base_url, -4)) {
$base_url = dirname($base_url);
}
$base_url = str_replace('\\', '/', $base_url);
return rtrim($this->getSchemeAndHttpHost() . $base_url, '/') . '/';
}
/**
* Is the request for checking URL rewriting?
*
* @return bool
*/
public function isRewriteCheck() {
if ($this->getPathInfo() !== ('/' . self::REWRITE_TEST_TOKEN)) {
return false;
}
if (!$this->get(self::REWRITE_TEST_TOKEN)) {
return false;
}
return true;
}
/**
* Is PHP running the CLI server front controller
*
* @return bool
*/
public function isCliServer() {
return php_sapi_name() === 'cli-server';
}
/**
* Is the request pointing to a file that the CLI server can handle?
*
* @param string $root Root directory
*
* @return bool
*/
public function isCliServable($root) {
$file = rtrim($root, '\\/') . $this->getElggPath();
if (!is_file($file)) {
return false;
}
// http://php.net/manual/en/features.commandline.webserver.php
$extensions = ".3gp, .apk, .avi, .bmp, .css, .csv, .doc, .docx, .flac, .gif, .gz, .gzip, .htm, .html, .ics, .jpe, .jpeg, .jpg, .js, .kml, .kmz, .m4a, .mov, .mp3, .mp4, .mpeg, .mpg, .odp, .ods, .odt, .oga, .ogg, .ogv, .pdf, .pdf, .png, .pps, .pptx, .qt, .svg, .swf, .tar, .text, .tif, .txt, .wav, .webm, .wmv, .xls, .xlsx, .xml, .xsl, .xsd, and .zip";
// The CLI server routes ALL requests here (even existing files), so we have to check for these.
$ext = pathinfo($file, PATHINFO_EXTENSION);
if (!$ext) {
return false;
}
$ext = preg_quote($ext, '~');
return (bool) preg_match("~\\.{$ext}[,$]~", $extensions);
}
/**
* Returns an array of uploaded file objects regardless of upload status/errors
*
* @param string $input_name Form input name
*
* @return UploadedFile[]
*/
public function getFiles($input_name) {
$files = $this->files->get($input_name);
if (empty($files)) {
return [];
}
if (!is_array($files)) {
$files = [$files];
}
return $files;
}
/**
* Returns the first file found based on the input name
*
* @param string $input_name Form input name
* @param bool $check_for_validity If there is an uploaded file, is it required to be valid
*
* @return UploadedFile|false
*/
public function getFile($input_name, $check_for_validity = true) {
$files = $this->getFiles($input_name);
if (empty($files)) {
return false;
}
$file = $files[0];
if (empty($file)) {
return false;
}
if ($check_for_validity && !$file->isValid()) {
return false;
}
return $file;
}
/**
* Validate the request
*
* @return void
* @throws HttpException
*/
public function validate() {
$this->validateRequestHostHeader();
$this->validateRequestBodyTruncated();
}
/**
* Validate that the request was made on the correct host
*
* This will prevent malicious requests from being processed
*
* @return void
* @throws BadRequestException
* @since 3.3.25
*/
protected function validateRequestHostHeader() {
$config = _elgg_services()->config;
if (empty($config->wwwroot)) {
return;
}
$config_host = parse_url($config->wwwroot, PHP_URL_HOST);
if ($config_host === $this->getHost()) {
return;
}
throw new BadRequestException(elgg_echo('BadRequestException:invalid_host_header'));
}
/**
* Validate that the request body hasn't been truncated (eg. exceeded POST max size)
*
* @return void
* @throws BadRequestException
* @since 3.0
*/
protected function validateRequestBodyTruncated(): void {
$reported_bytes = $this->server->get('CONTENT_LENGTH');
// Requests with multipart content type
$post_data_count = count($this->request->all());
// Requests with other content types
$content = $this->getContent();
$post_body_length = is_string($content) ? elgg_strlen($content) : 0;
$file_count = count($this->files->all());
$is_valid = function() use ($reported_bytes, $post_data_count, $post_body_length, $file_count) {
if (empty($reported_bytes)) {
// Content length is set for POST requests only
return true;
}
if (empty($post_data_count) && empty($post_body_length) && empty($file_count)) {
// The size of $_POST or uploaded files has exceed the size limit
// and the request body/query has been truncated
// thus the request reported bytes is set, but no postdata is found
return false;
}
return true;
};
if ($is_valid()) {
return;
}
$error_msg = elgg_trigger_plugin_hook('action_gatekeeper:upload_exceeded_msg', 'all', [
'post_size' => $reported_bytes,
'visible_errors' => true,
], elgg_echo('actiongatekeeper:uploadexceeded'));
throw new BadRequestException($error_msg);
}
}