/
Request.php
547 lines (496 loc) · 17.4 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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
<?php
/**
* Lithium: the most rad php framework
*
* @copyright Copyright 2011, Union of RAD (http://union-of-rad.org)
* @license http://opensource.org/licenses/bsd-license.php The BSD License
*/
namespace lithium\action;
use lithium\util\Set;
use lithium\util\Validator;
/**
* A `Request` object is passed into the `Dispatcher`, and is responsible for identifying and
* storing all the information about an HTTP request made to an application, including status,
* headers, and any GET, POST or PUT data, as well as any data returned from the
* `Router`, after the `Request` object has been matched against a `Route`. Includes a property
* accessor method (`__get()`) which allows any parameters returned from routing to be accessed as
* properties of the `Request` object.
*
* @see lithium\action\Dispatcher
* @see lithium\action\Controller
* @see lithium\net\http\Router
* @see lithium\net\http\Route
* @see lithium\action\Request::__get()
*/
class Request extends \lithium\net\http\Request {
/**
* Current url of request.
*
* @var string
*/
public $url = null;
/**
* Params for request.
*
* @var array
*/
public $params = array();
/**
* Route parameters that should persist when generating URLs in this request context.
*
* @var array
*/
public $persist = array();
/**
* POST data.
*
* @var data
*/
public $data = array();
/**
* GET data.
*
* @var string
*/
public $query = array();
/**
* Base path.
*
* @var string
*/
protected $_base = null;
/**
* Holds the environment variables for the request. Retrieved with env().
*
* @var array
* @see lithium\action\Request::env()
*/
protected $_env = array();
/**
* Classes used by `Request`.
*
* @var array
*/
protected $_classes = array('media' => 'lithium\net\http\Media');
/**
* If POST / PUT data is coming from an input stream (rather than `$_POST`), this specified
* where to read it from.
*
* @var stream
*/
protected $_stream = null;
/**
* Options used to detect request type.
*
* @see lithium\action\Request::detect()
* @var array
*/
protected $_detectors = array(
'mobile' => array('HTTP_USER_AGENT', null),
'ajax' => array('HTTP_X_REQUESTED_WITH', 'XMLHttpRequest'),
'flash' => array('HTTP_USER_AGENT', 'Shockwave Flash'),
'ssl' => 'HTTPS',
'get' => array('REQUEST_METHOD', 'GET'),
'post' => array('REQUEST_METHOD', 'POST'),
'put' => array('REQUEST_METHOD', 'PUT'),
'delete' => array('REQUEST_METHOD', 'DELETE'),
'head' => array('REQUEST_METHOD', 'HEAD'),
'options' => array('REQUEST_METHOD', 'OPTIONS')
);
/**
* Auto configuration properties.
*
* @var array
*/
protected $_autoConfig = array(
'classes' => 'merge', 'env', 'detectors' => 'merge', 'base', 'type', 'stream'
);
/**
* Contains an array of content-types, sorted by quality (the priority which the browser
* requests each type).
*
* @var array
*/
protected $_acceptContent = array();
/**
* Pulls request data from superglobals.
*
* @return void
*/
protected function _init() {
parent::_init();
$mobile = array(
'iPhone', 'MIDP', 'AvantGo', 'BlackBerry', 'J2ME', 'Opera Mini', 'DoCoMo', 'NetFront',
'Nokia', 'PalmOS', 'PalmSource', 'portalmmm', 'Plucker', 'ReqwirelessWeb', 'iPod',
'SonyEricsson', 'Symbian', 'UP\.Browser', 'Windows CE', 'Xiino', 'Android'
);
if (!empty($this->_config['detectors']['mobile'][1])) {
$mobile = array_merge($mobile, (array) $this->_config['detectors']['mobile'][1]);
}
$this->_detectors['mobile'][1] = $mobile;
$this->_env += (array) $_SERVER + (array) $_ENV + array('REQUEST_METHOD' => 'GET');
$envs = array('isapi' => 'IIS', 'cgi' => 'CGI', 'cgi-fcgi' => 'CGI');
$this->_env['PLATFORM'] = isset($envs[PHP_SAPI]) ? $envs[PHP_SAPI] : null;
$this->_base = isset($this->_base) ? $this->_base : $this->_base();
$this->url = '/';
if (isset($this->_config['url'])) {
$this->url = rtrim($this->_config['url'], '/');
} elseif (!empty($_GET['url']) ) {
$this->url = rtrim($_GET['url'], '/');
unset($_GET['url']);
}
if (!empty($this->_config['query'])) {
$this->query = $this->_config['query'];
}
if (isset($_GET)) {
$this->query += $_GET;
}
if (!empty($this->_config['data'])) {
$this->data = $this->_config['data'];
} elseif (isset($_POST)) {
$this->data += $_POST;
}
if (isset($this->data['_method'])) {
$this->_env['HTTP_X_HTTP_METHOD_OVERRIDE'] = strtoupper($this->data['_method']);
unset($this->data['_method']);
}
if (!empty($this->_env['HTTP_X_HTTP_METHOD_OVERRIDE'])) {
$this->_env['REQUEST_METHOD'] = $this->_env['HTTP_X_HTTP_METHOD_OVERRIDE'];
}
$method = strtoupper($this->_env['REQUEST_METHOD']);
if (($method == 'POST' || $method == 'PUT') && !$this->data) {
if (($type = $this->type()) && $type !== 'html') {
$this->_stream = $this->_stream ?: fopen('php://input', 'r');
$media = $this->_classes['media'];
$this->data = (array) $media::decode($type, stream_get_contents($this->_stream));
fclose($this->_stream);
}
}
if (isset($_FILES) && $_FILES) {
$result = array();
$normalize = function($key, $value) use ($result, &$normalize){
foreach ($value as $param => $content) {
foreach ($content as $num => $val) {
if (is_numeric($num)) {
$result[$key][$num][$param] = $val;
continue;
}
if (is_array($val)) {
foreach ($val as $next => $one) {
$result[$key][$num][$next][$param] = $one;
}
continue;
}
$result[$key][$num][$param] = $val;
}
}
return $result;
};
foreach ($_FILES as $key => $value) {
if (isset($value['name'])) {
if (is_string($value['name'])) {
$result[$key] = $value;
continue;
}
if (is_array($value['name'])) {
$result += $normalize($key, $value);
}
}
}
$this->data = Set::merge((array) $this->data, $result);
}
}
/**
* Allows request parameters to be accessed as object properties, i.e. `$this->request->action`
* instead of `$this->request->params['action']`.
*
* @see lithium\action\Request::$params
* @param string $name The property name/parameter key to return.
* @return mixed Returns the value of `$params[$name]` if it is set, otherwise returns null.
*/
public function __get($name) {
if (isset($this->params[$name])) {
return $this->params[$name];
}
}
/**
* Allows request parameters to be checked using short-hand notation. See the `__get()` method
* for more details.
*
* @see lithium\action\Request::__get()
* @param string $name The name of the request parameter to check.
* @return boolean Returns true if the key in `$name` is set in the `$params` array, otherwise
* `false`.
*/
public function __isset($name) {
return isset($this->params[$name]);
}
/**
* Queries PHP's environment settings, and provides an abstraction for standardizing expected
* environment values across varying platforms, as well as specify custom environment flags.
*
* @param string $key The environment variable required.
* @return string The requested variables value.
* @todo Refactor to lazy-load environment settings
*/
public function env($key) {
if (strtolower($key) == 'base') {
return $this->_base;
}
if ($key == 'SCRIPT_NAME' && !isset($this->_env['SCRIPT_NAME'])) {
if ($this->_env['PLATFORM'] == 'CGI' || isset($this->_env['SCRIPT_URL'])) {
$key = 'SCRIPT_URL';
}
}
$val = array_key_exists($key, $this->_env) ? $this->_env[$key] : getenv($key);
$this->_env[$key] = $val;
if ($key == 'REMOTE_ADDR' && $val == $this->env('SERVER_ADDR')) {
$val = ($addr = $this->env('HTTP_PC_REMOTE_ADDR')) ? $addr : $val;
}
if ($val !== null && $val !== false && $key !== 'HTTPS') {
return $val;
}
switch ($key) {
case 'HTTPS':
if (isset($this->_env['SCRIPT_URI'])) {
return (strpos($this->_env['SCRIPT_URI'], 'https://') === 0);
}
if (isset($this->_env['HTTPS'])) {
return (!empty($this->_env['HTTPS']) && $this->_env['HTTPS'] !== 'off');
}
return false;
case 'SCRIPT_FILENAME':
if ($this->_env['PLATFORM'] == 'IIS') {
return str_replace('\\\\', '\\', $this->env('PATH_TRANSLATED'));
}
return $this->env('DOCUMENT_ROOT') . $this->env('PHP_SELF');
case 'DOCUMENT_ROOT':
$fileName = $this->env('SCRIPT_FILENAME');
$offset = (!strpos($this->env('SCRIPT_NAME'), '.php')) ? 4 : 0;
$offset = strlen($fileName) - (strlen($this->env('SCRIPT_NAME')) + $offset);
return substr($fileName, 0, $offset);
case 'PHP_SELF':
return str_replace('\\', '/', str_replace(
$this->env('DOCUMENT_ROOT'), '', $this->env('SCRIPT_FILENAME')
));
case 'CGI':
case 'CGI_MODE':
return ($this->_env['PLATFORM'] == 'CGI');
case 'HTTP_BASE':
return preg_replace('/^([^.])*/i', null, $this->_env['HTTP_HOST']);
}
}
/**
* Returns information about the type of content that the client is requesting.
*
* @see lithium\net\http\Media::negotiate()
* @param $type mixed If not specified, returns the media type name that the client prefers,
* using content negotiation. If a media type name (string) is passed, returns
* `true` or `false`, indicating whether or not that type is accepted by the client
* at all. If `true`, returns the raw content types from the `Accept` header,
* parsed into an array and sorted by client preference.
* @return string Returns a simple type name if the type is registered (i.e. `'json'`), or
* a fully-qualified content-type if not (i.e. `'image/jpeg'`), or a boolean or array,
* depending on the value of `$type`.
*/
public function accepts($type = null) {
if ($type === true) {
return $this->_parseAccept();
}
if (!$type && isset($this->params['type'])) {
return $this->params['type'];
}
$media = $this->_classes['media'];
return $media::negotiate($this) ?: 'html';
}
protected function _parseAccept() {
if ($this->_acceptContent) {
return $this->_acceptContent;
}
$accept = $this->env('HTTP_ACCEPT');
$accept = (preg_match('/[a-z,-]/i', $accept)) ? explode(',', $accept) : array('text/html');
foreach (array_reverse($accept) as $i => $type) {
unset($accept[$i]);
list($type, $q) = (explode(';q=', $type, 2) + array($type, 1.0 + $i / 100));
$accept[$type] = ($type == '*/*') ? 0.1 : floatval($q);
}
arsort($accept, SORT_NUMERIC);
if (isset($accept['application/xhtml+xml']) && $accept['application/xhtml+xml'] >= 1) {
unset($accept['application/xml']);
}
$media = $this->_classes['media'];
if (isset($this->params['type']) && ($handler = $media::type($this->params['type']))) {
if (isset($handler['content'])) {
$type = (array) $handler['content'];
$accept = array(current($type) => 1) + $accept;
}
}
return $this->_acceptContent = array_keys($accept);
}
/**
* This method allows easy extraction of any request data using a prefixed key syntax. By
* passing keys in the form of `'prefix:key'`, it is possible to query different information of
* various different types, including GET and POST data, and server environment variables. The
* full list of prefixes is as follows:
*
* - `'data'`: Retrieves values from POST data.
* - `'params'`: Retrieves query parameters returned from the routing system.
* - `'query'`: Retrieves values from GET data.
* - `'env'`: Retrieves values from the server or environment, such as `'env:https'`, or custom
* environment values, like `'env:base'`. See the `env()` method for more info.
* - `'http'`: Retrieves header values (i.e. `'http:accept'`), or the HTTP request method (i.e.
* `'http:method'`).
*
* This method is used in several different places in the framework in order to provide the
* ability to act conditionally on different aspects of the request. See `Media::type()` (the
* section on content negotiation) and the routing system for more information.
*
* _Note_: All keys should be _lower-cased_, even when getting HTTP headers.
* @see lithium\action\Request::env()
* @see lithium\net\http\Media::type()
* @see lithium\net\http\Router
* @param string $key A prefixed key indiciating what part of the request data the requested
* value should come from, and the name of the value to retrieve, in lower case.
* @return string Returns the value of a GET, POST, routing or environment variable, or an
* HTTP header or method name.
*/
public function get($key) {
list($var, $key) = explode(':', $key);
switch (true) {
case in_array($var, array('params', 'data', 'query')):
return isset($this->{$var}[$key]) ? $this->{$var}[$key] : null;
case ($var === 'env'):
return $this->env(strtoupper($key));
case ($var === 'http' && $key === 'method'):
return $this->env('REQUEST_METHOD');
case ($var === 'http'):
return $this->env('HTTP_' . strtoupper($key));
}
}
/**
* Detects properties of the request and returns a boolean response.
*
* @see lithium\action\Request::detect()
* @todo Remove $content and refer to Media class instead
* @param string $flag
* @return boolean
*/
public function is($flag) {
$media = $this->_classes['media'];
if (!isset($this->_detectors[$flag])) {
if (!in_array($flag, $media::types())) {
return false;
}
return $this->type() == $flag;
}
$detector = $this->_detectors[$flag];
if (!is_array($detector) && is_callable($detector)) {
return $detector($this);
}
if (!is_array($detector)) {
return (boolean) $this->env($detector);
}
list($key, $check) = $detector + array('', '');
if (is_array($check)) {
$check = '/' . join('|', $check) . '/i';
}
if (Validator::isRegex($check)) {
return (boolean) preg_match($check, $this->env($key));
}
return ($this->env($key) == $check);
}
/**
* Sets/Gets the content type. If `'type'` is null, the method will attempt to determine the
* type first, from the params, then from the environment setting
*
* @param string $type a full content type i.e. `'application/json'` or simple name `'json'`
* @return string A simple content type name, i.e. `'html'`, `'xml'`, `'json'`, etc., depending
* on the content type of the request.
*/
public function type($type = null) {
if ($type === null) {
$type = $this->type ?: $this->env('CONTENT_TYPE');
}
return parent::type($type);
}
/**
* Creates a _detector_ used with `Request::is()`. A detector is a boolean check that is
* created to determine something about a request.
*
* A detector check can be either an exact string match or a regular expression match against a
* header or environment variable. A detector check can also be a closure that accepts the
* `Request` object instance as a parameter.
*
* For example, to detect whether a request is from an iPhone, you can do the following:
* {{{ embed:lithium\tests\cases\action\RequestTest::testDetect(11-12) }}}
*
* @see lithium\action\Request::is()
* @param string $flag The name of the detector check. Used in subsequent calls to
* `Request::is()`.
* @param mixed $detector Detectors can be specified in four different ways:
* - The name of an HTTP header or environment variable. If a string, calling the
* detector will check that the header or environment variable exists and is set
* to a non-empty value.
* - A two-element array containing a header/environment variable name, and a value
* to match against. The second element of the array must be an exact match to
* the header or variable value.
* - A two-element array containing a header/environment variable name, and a
* regular expression that matches against the value, as in the example above.
* - A closure which accepts an instance of the `Request` object and returns a
* boolean value.
* @return void
*/
public function detect($flag, $detector = null) {
if (is_array($flag)) {
$this->_detectors = $flag + $this->_detectors;
} else {
$this->_detectors[$flag] = $detector;
}
}
/**
* Gets the referring URL of this request.
*
* @param string $default Default URL to use if HTTP_REFERER cannot be read from headers.
* @param boolean $local If true, restrict referring URLs to local server.
* @return string Referring URL.
*/
public function referer($default = null, $local = false) {
if ($ref = $this->env('HTTP_REFERER')) {
if (!$local) {
return $ref;
}
if (strpos($ref, '://') == false) {
return $ref;
}
}
return ($default != null) ? $default : '/';
}
/**
* Overrides `lithium\net\http\Request::to()` to provide the correct options for generating
* URLs. For information about this method, see the parent implementation.
*
* @see lithium\net\http\Request::to()
* @param string $format The format to convert to.
* @param array $options Override options.
* @return mixed The return value type depends on `$format`.
*/
public function to($format, array $options = array()) {
$defaults = array(
'scheme' => $this->env('HTTPS') ? 'https' : 'http',
'host' => $this->env('HTTP_HOST'),
'path' => $this->_base . $this->url,
'query' => $this->query
);
$options += $defaults;
return parent::to($format, $options);
}
/**
* @todo Replace string directory names with configuration.
* @return void
*/
protected function _base() {
$base = str_replace('\\', '/', dirname($this->env('PHP_SELF')));
return rtrim(str_replace(array("/app/webroot", '/webroot'), '', $base), '/');
}
}
?>