1: <?php
2: /**
3: * CakeRequest
4: *
5: * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
6: * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
7: *
8: * Licensed under The MIT License
9: * For full copyright and license information, please see the LICENSE.txt
10: * Redistributions of files must retain the above copyright notice.
11: *
12: * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
13: * @link http://cakephp.org CakePHP(tm) Project
14: * @since CakePHP(tm) v 2.0
15: * @license http://www.opensource.org/licenses/mit-license.php MIT License
16: */
17:
18: App::uses('Hash', 'Utility');
19:
20: /**
21: * A class that helps wrap Request information and particulars about a single request.
22: * Provides methods commonly used to introspect on the request headers and request body.
23: *
24: * Has both an Array and Object interface. You can access framework parameters using indexes:
25: *
26: * `$request['controller']` or `$request->controller`.
27: *
28: * @package Cake.Network
29: */
30: class CakeRequest implements ArrayAccess {
31:
32: /**
33: * Array of parameters parsed from the URL.
34: *
35: * @var array
36: */
37: public $params = array(
38: 'plugin' => null,
39: 'controller' => null,
40: 'action' => null,
41: 'named' => array(),
42: 'pass' => array(),
43: );
44:
45: /**
46: * Array of POST data. Will contain form data as well as uploaded files.
47: * Inputs prefixed with 'data' will have the data prefix removed. If there is
48: * overlap between an input prefixed with data and one without, the 'data' prefixed
49: * value will take precedence.
50: *
51: * @var array
52: */
53: public $data = array();
54:
55: /**
56: * Array of querystring arguments
57: *
58: * @var array
59: */
60: public $query = array();
61:
62: /**
63: * The URL string used for the request.
64: *
65: * @var string
66: */
67: public $url;
68:
69: /**
70: * Base URL path.
71: *
72: * @var string
73: */
74: public $base = false;
75:
76: /**
77: * webroot path segment for the request.
78: *
79: * @var string
80: */
81: public $webroot = '/';
82:
83: /**
84: * The full address to the current request
85: *
86: * @var string
87: */
88: public $here = null;
89:
90: /**
91: * The built in detectors used with `is()` can be modified with `addDetector()`.
92: *
93: * There are several ways to specify a detector, see CakeRequest::addDetector() for the
94: * various formats and ways to define detectors.
95: *
96: * @var array
97: */
98: protected $_detectors = array(
99: 'get' => array('env' => 'REQUEST_METHOD', 'value' => 'GET'),
100: 'patch' => array('env' => 'REQUEST_METHOD', 'value' => 'PATCH'),
101: 'post' => array('env' => 'REQUEST_METHOD', 'value' => 'POST'),
102: 'put' => array('env' => 'REQUEST_METHOD', 'value' => 'PUT'),
103: 'delete' => array('env' => 'REQUEST_METHOD', 'value' => 'DELETE'),
104: 'head' => array('env' => 'REQUEST_METHOD', 'value' => 'HEAD'),
105: 'options' => array('env' => 'REQUEST_METHOD', 'value' => 'OPTIONS'),
106: 'ssl' => array('env' => 'HTTPS', 'value' => 1),
107: 'ajax' => array('env' => 'HTTP_X_REQUESTED_WITH', 'value' => 'XMLHttpRequest'),
108: 'flash' => array('env' => 'HTTP_USER_AGENT', 'pattern' => '/^(Shockwave|Adobe) Flash/'),
109: 'mobile' => array('env' => 'HTTP_USER_AGENT', 'options' => array(
110: 'Android', 'AvantGo', 'BB10', 'BlackBerry', 'DoCoMo', 'Fennec', 'iPod', 'iPhone', 'iPad',
111: 'J2ME', 'MIDP', 'NetFront', 'Nokia', 'Opera Mini', 'Opera Mobi', 'PalmOS', 'PalmSource',
112: 'portalmmm', 'Plucker', 'ReqwirelessWeb', 'SonyEricsson', 'Symbian', 'UP\\.Browser',
113: 'webOS', 'Windows CE', 'Windows Phone OS', 'Xiino'
114: )),
115: 'requested' => array('param' => 'requested', 'value' => 1),
116: 'json' => array('accept' => array('application/json'), 'param' => 'ext', 'value' => 'json'),
117: 'xml' => array('accept' => array('application/xml', 'text/xml'), 'param' => 'ext', 'value' => 'xml'),
118: );
119:
120: /**
121: * Copy of php://input. Since this stream can only be read once in most SAPI's
122: * keep a copy of it so users don't need to know about that detail.
123: *
124: * @var string
125: */
126: protected $_input = '';
127:
128: /**
129: * Constructor
130: *
131: * @param string $url Trimmed URL string to use. Should not contain the application base path.
132: * @param bool $parseEnvironment Set to false to not auto parse the environment. ie. GET, POST and FILES.
133: */
134: public function __construct($url = null, $parseEnvironment = true) {
135: $this->_base();
136: if (empty($url)) {
137: $url = $this->_url();
138: }
139: if ($url[0] === '/') {
140: $url = substr($url, 1);
141: }
142: $this->url = $url;
143:
144: if ($parseEnvironment) {
145: $this->_processPost();
146: $this->_processGet();
147: $this->_processFiles();
148: }
149: $this->here = $this->base . '/' . $this->url;
150: }
151:
152: /**
153: * process the post data and set what is there into the object.
154: * processed data is available at `$this->data`
155: *
156: * Will merge POST vars prefixed with `data`, and ones without
157: * into a single array. Variables prefixed with `data` will overwrite those without.
158: *
159: * If you have mixed POST values be careful not to make any top level keys numeric
160: * containing arrays. Hash::merge() is used to merge data, and it has possibly
161: * unexpected behavior in this situation.
162: *
163: * @return void
164: */
165: protected function _processPost() {
166: if ($_POST) {
167: $this->data = $_POST;
168: } elseif (($this->is('put') || $this->is('delete')) &&
169: strpos($this->contentType(), 'application/x-www-form-urlencoded') === 0
170: ) {
171: $data = $this->_readInput();
172: parse_str($data, $this->data);
173: }
174: if (ini_get('magic_quotes_gpc') === '1') {
175: $this->data = stripslashes_deep($this->data);
176: }
177:
178: $override = null;
179: if (env('HTTP_X_HTTP_METHOD_OVERRIDE')) {
180: $this->data['_method'] = env('HTTP_X_HTTP_METHOD_OVERRIDE');
181: $override = $this->data['_method'];
182: }
183:
184: $isArray = is_array($this->data);
185: if ($isArray && isset($this->data['_method'])) {
186: if (!empty($_SERVER)) {
187: $_SERVER['REQUEST_METHOD'] = $this->data['_method'];
188: } else {
189: $_ENV['REQUEST_METHOD'] = $this->data['_method'];
190: }
191: $override = $this->data['_method'];
192: unset($this->data['_method']);
193: }
194:
195: if ($override && !in_array($override, array('POST', 'PUT', 'PATCH', 'DELETE'))) {
196: $this->data = array();
197: }
198:
199: if ($isArray && isset($this->data['data'])) {
200: $data = $this->data['data'];
201: if (count($this->data) <= 1) {
202: $this->data = $data;
203: } else {
204: unset($this->data['data']);
205: $this->data = Hash::merge($this->data, $data);
206: }
207: }
208: }
209:
210: /**
211: * Process the GET parameters and move things into the object.
212: *
213: * @return void
214: */
215: protected function _processGet() {
216: if (ini_get('magic_quotes_gpc') === '1') {
217: $query = stripslashes_deep($_GET);
218: } else {
219: $query = $_GET;
220: }
221:
222: $unsetUrl = '/' . str_replace(array('.', ' '), '_', urldecode($this->url));
223: unset($query[$unsetUrl]);
224: unset($query[$this->base . $unsetUrl]);
225: if (strpos($this->url, '?') !== false) {
226: list(, $querystr) = explode('?', $this->url);
227: parse_str($querystr, $queryArgs);
228: $query += $queryArgs;
229: }
230: if (isset($this->params['url'])) {
231: $query = array_merge($this->params['url'], $query);
232: }
233: $this->query = $query;
234: }
235:
236: /**
237: * Get the request uri. Looks in PATH_INFO first, as this is the exact value we need prepared
238: * by PHP. Following that, REQUEST_URI, PHP_SELF, HTTP_X_REWRITE_URL and argv are checked in that order.
239: * Each of these server variables have the base path, and query strings stripped off
240: *
241: * @return string URI The CakePHP request path that is being accessed.
242: */
243: protected function _url() {
244: if (!empty($_SERVER['PATH_INFO'])) {
245: return $_SERVER['PATH_INFO'];
246: } elseif (isset($_SERVER['REQUEST_URI']) && strpos($_SERVER['REQUEST_URI'], '://') === false) {
247: $uri = $_SERVER['REQUEST_URI'];
248: } elseif (isset($_SERVER['REQUEST_URI'])) {
249: $qPosition = strpos($_SERVER['REQUEST_URI'], '?');
250: if ($qPosition !== false && strpos($_SERVER['REQUEST_URI'], '://') > $qPosition) {
251: $uri = $_SERVER['REQUEST_URI'];
252: } else {
253: $uri = substr($_SERVER['REQUEST_URI'], strlen(Configure::read('App.fullBaseUrl')));
254: }
255: } elseif (isset($_SERVER['PHP_SELF']) && isset($_SERVER['SCRIPT_NAME'])) {
256: $uri = str_replace($_SERVER['SCRIPT_NAME'], '', $_SERVER['PHP_SELF']);
257: } elseif (isset($_SERVER['HTTP_X_REWRITE_URL'])) {
258: $uri = $_SERVER['HTTP_X_REWRITE_URL'];
259: } elseif ($var = env('argv')) {
260: $uri = $var[0];
261: }
262:
263: $base = $this->base;
264:
265: if (strlen($base) > 0 && strpos($uri, $base) === 0) {
266: $uri = substr($uri, strlen($base));
267: }
268: if (strpos($uri, '?') !== false) {
269: list($uri) = explode('?', $uri, 2);
270: }
271: if (empty($uri) || $uri === '/' || $uri === '//' || $uri === '/index.php') {
272: $uri = '/';
273: }
274: $endsWithIndex = '/webroot/index.php';
275: $endsWithLength = strlen($endsWithIndex);
276: if (strlen($uri) >= $endsWithLength &&
277: substr($uri, -$endsWithLength) === $endsWithIndex
278: ) {
279: $uri = '/';
280: }
281: return $uri;
282: }
283:
284: /**
285: * Returns a base URL and sets the proper webroot
286: *
287: * If CakePHP is called with index.php in the URL even though
288: * URL Rewriting is activated (and thus not needed) it swallows
289: * the unnecessary part from $base to prevent issue #3318.
290: *
291: * @return string Base URL
292: */
293: protected function _base() {
294: $dir = $webroot = null;
295: $config = Configure::read('App');
296: extract($config);
297:
298: if (!isset($base)) {
299: $base = $this->base;
300: }
301: if ($base !== false) {
302: $this->webroot = $base . '/';
303: return $this->base = $base;
304: }
305:
306: if (!$baseUrl) {
307: $base = dirname(env('PHP_SELF'));
308: // Clean up additional / which cause following code to fail..
309: $base = preg_replace('#/+#', '/', $base);
310:
311: $indexPos = strpos($base, '/webroot/index.php');
312: if ($indexPos !== false) {
313: $base = substr($base, 0, $indexPos) . '/webroot';
314: }
315: if ($webroot === 'webroot' && $webroot === basename($base)) {
316: $base = dirname($base);
317: }
318: if ($dir === 'app' && $dir === basename($base)) {
319: $base = dirname($base);
320: }
321:
322: if ($base === DS || $base === '.') {
323: $base = '';
324: }
325: $base = implode('/', array_map('rawurlencode', explode('/', $base)));
326: $this->webroot = $base . '/';
327:
328: return $this->base = $base;
329: }
330:
331: $file = '/' . basename($baseUrl);
332: $base = dirname($baseUrl);
333:
334: if ($base === DS || $base === '.') {
335: $base = '';
336: }
337: $this->webroot = $base . '/';
338:
339: $docRoot = env('DOCUMENT_ROOT');
340: $docRootContainsWebroot = strpos($docRoot, $dir . DS . $webroot);
341:
342: if (!empty($base) || !$docRootContainsWebroot) {
343: if (strpos($this->webroot, '/' . $dir . '/') === false) {
344: $this->webroot .= $dir . '/';
345: }
346: if (strpos($this->webroot, '/' . $webroot . '/') === false) {
347: $this->webroot .= $webroot . '/';
348: }
349: }
350: return $this->base = $base . $file;
351: }
352:
353: /**
354: * Process $_FILES and move things into the object.
355: *
356: * @return void
357: */
358: protected function _processFiles() {
359: if (isset($_FILES) && is_array($_FILES)) {
360: foreach ($_FILES as $name => $data) {
361: if ($name !== 'data') {
362: $this->params['form'][$name] = $data;
363: }
364: }
365: }
366:
367: if (isset($_FILES['data'])) {
368: foreach ($_FILES['data'] as $key => $data) {
369: $this->_processFileData('', $data, $key);
370: }
371: }
372: }
373:
374: /**
375: * Recursively walks the FILES array restructuring the data
376: * into something sane and useable.
377: *
378: * @param string $path The dot separated path to insert $data into.
379: * @param array $data The data to traverse/insert.
380: * @param string $field The terminal field name, which is the top level key in $_FILES.
381: * @return void
382: */
383: protected function _processFileData($path, $data, $field) {
384: foreach ($data as $key => $fields) {
385: $newPath = $key;
386: if (strlen($path) > 0) {
387: $newPath = $path . '.' . $key;
388: }
389: if (is_array($fields)) {
390: $this->_processFileData($newPath, $fields, $field);
391: } else {
392: $newPath .= '.' . $field;
393: $this->data = Hash::insert($this->data, $newPath, $fields);
394: }
395: }
396: }
397:
398: /**
399: * Get the content type used in this request.
400: *
401: * @return string
402: */
403: public function contentType() {
404: $type = env('CONTENT_TYPE');
405: if ($type) {
406: return $type;
407: }
408: return env('HTTP_CONTENT_TYPE');
409: }
410:
411: /**
412: * Get the IP the client is using, or says they are using.
413: *
414: * @param bool $safe Use safe = false when you think the user might manipulate their HTTP_CLIENT_IP
415: * header. Setting $safe = false will also look at HTTP_X_FORWARDED_FOR
416: * @return string The client IP.
417: */
418: public function clientIp($safe = true) {
419: if (!$safe && env('HTTP_X_FORWARDED_FOR')) {
420: $ipaddr = preg_replace('/(?:,.*)/', '', env('HTTP_X_FORWARDED_FOR'));
421: } elseif (!$safe && env('HTTP_CLIENT_IP')) {
422: $ipaddr = env('HTTP_CLIENT_IP');
423: } else {
424: $ipaddr = env('REMOTE_ADDR');
425: }
426: return trim($ipaddr);
427: }
428:
429: /**
430: * Returns the referer that referred this request.
431: *
432: * @param bool $local Attempt to return a local address. Local addresses do not contain hostnames.
433: * @return string The referring address for this request.
434: */
435: public function referer($local = false) {
436: $ref = env('HTTP_REFERER');
437:
438: $base = Configure::read('App.fullBaseUrl') . $this->webroot;
439: if (!empty($ref) && !empty($base)) {
440: if ($local && strpos($ref, $base) === 0) {
441: $ref = substr($ref, strlen($base));
442: if (empty($ref)) {
443: $ref = '/';
444: }
445: if ($ref[0] !== '/') {
446: $ref = '/' . $ref;
447: }
448: return $ref;
449: } elseif (!$local) {
450: return $ref;
451: }
452: }
453: return '/';
454: }
455:
456: /**
457: * Missing method handler, handles wrapping older style isAjax() type methods
458: *
459: * @param string $name The method called
460: * @param array $params Array of parameters for the method call
461: * @return mixed
462: * @throws CakeException when an invalid method is called.
463: */
464: public function __call($name, $params) {
465: if (strpos($name, 'is') === 0) {
466: $type = strtolower(substr($name, 2));
467: return $this->is($type);
468: }
469: throw new CakeException(__d('cake_dev', 'Method %s does not exist', $name));
470: }
471:
472: /**
473: * Magic get method allows access to parsed routing parameters directly on the object.
474: *
475: * Allows access to `$this->params['controller']` via `$this->controller`
476: *
477: * @param string $name The property being accessed.
478: * @return mixed Either the value of the parameter or null.
479: */
480: public function __get($name) {
481: if (isset($this->params[$name])) {
482: return $this->params[$name];
483: }
484: return null;
485: }
486:
487: /**
488: * Magic isset method allows isset/empty checks
489: * on routing parameters.
490: *
491: * @param string $name The property being accessed.
492: * @return bool Existence
493: */
494: public function __isset($name) {
495: return isset($this->params[$name]);
496: }
497:
498: /**
499: * Check whether or not a Request is a certain type.
500: *
501: * Uses the built in detection rules as well as additional rules
502: * defined with CakeRequest::addDetector(). Any detector can be called
503: * as `is($type)` or `is$Type()`.
504: *
505: * @param string|array $type The type of request you want to check. If an array
506: * this method will return true if the request matches any type.
507: * @return bool Whether or not the request is the type you are checking.
508: */
509: public function is($type) {
510: if (is_array($type)) {
511: $result = array_map(array($this, 'is'), $type);
512: return count(array_filter($result)) > 0;
513: }
514: $type = strtolower($type);
515: if (!isset($this->_detectors[$type])) {
516: return false;
517: }
518: $detect = $this->_detectors[$type];
519: if (isset($detect['env']) && $this->_environmentDetector($detect)) {
520: return true;
521: }
522: if (isset($detect['header']) && $this->_headerDetector($detect)) {
523: return true;
524: }
525: if (isset($detect['accept']) && $this->_acceptHeaderDetector($detect)) {
526: return true;
527: }
528: if (isset($detect['param']) && $this->_paramDetector($detect)) {
529: return true;
530: }
531: if (isset($detect['callback']) && is_callable($detect['callback'])) {
532: return call_user_func($detect['callback'], $this);
533: }
534: return false;
535: }
536:
537: /**
538: * Detects if a URL extension is present.
539: *
540: * @param array $detect Detector options array.
541: * @return bool Whether or not the request is the type you are checking.
542: */
543: protected function _extensionDetector($detect) {
544: if (is_string($detect['extension'])) {
545: $detect['extension'] = array($detect['extension']);
546: }
547: if (in_array($this->params['ext'], $detect['extension'])) {
548: return true;
549: }
550: return false;
551: }
552:
553: /**
554: * Detects if a specific accept header is present.
555: *
556: * @param array $detect Detector options array.
557: * @return bool Whether or not the request is the type you are checking.
558: */
559: protected function _acceptHeaderDetector($detect) {
560: $acceptHeaders = explode(',', (string)env('HTTP_ACCEPT'));
561: foreach ($detect['accept'] as $header) {
562: if (in_array($header, $acceptHeaders)) {
563: return true;
564: }
565: }
566: return false;
567: }
568:
569: /**
570: * Detects if a specific header is present.
571: *
572: * @param array $detect Detector options array.
573: * @return bool Whether or not the request is the type you are checking.
574: */
575: protected function _headerDetector($detect) {
576: foreach ($detect['header'] as $header => $value) {
577: $header = env('HTTP_' . strtoupper($header));
578: if (!is_null($header)) {
579: if (!is_string($value) && !is_bool($value) && is_callable($value)) {
580: return call_user_func($value, $header);
581: }
582: return ($header === $value);
583: }
584: }
585: return false;
586: }
587:
588: /**
589: * Detects if a specific request parameter is present.
590: *
591: * @param array $detect Detector options array.
592: * @return bool Whether or not the request is the type you are checking.
593: */
594: protected function _paramDetector($detect) {
595: $key = $detect['param'];
596: if (isset($detect['value'])) {
597: $value = $detect['value'];
598: return isset($this->params[$key]) ? $this->params[$key] == $value : false;
599: }
600: if (isset($detect['options'])) {
601: return isset($this->params[$key]) ? in_array($this->params[$key], $detect['options']) : false;
602: }
603: return false;
604: }
605:
606: /**
607: * Detects if a specific environment variable is present.
608: *
609: * @param array $detect Detector options array.
610: * @return bool Whether or not the request is the type you are checking.
611: */
612: protected function _environmentDetector($detect) {
613: if (isset($detect['env'])) {
614: if (isset($detect['value'])) {
615: return env($detect['env']) == $detect['value'];
616: }
617: if (isset($detect['pattern'])) {
618: return (bool)preg_match($detect['pattern'], env($detect['env']));
619: }
620: if (isset($detect['options'])) {
621: $pattern = '/' . implode('|', $detect['options']) . '/i';
622: return (bool)preg_match($pattern, env($detect['env']));
623: }
624: }
625: return false;
626: }
627:
628: /**
629: * Check that a request matches all the given types.
630: *
631: * Allows you to test multiple types and union the results.
632: * See CakeRequest::is() for how to add additional types and the
633: * built-in types.
634: *
635: * @param array $types The types to check.
636: * @return bool Success.
637: * @see CakeRequest::is()
638: */
639: public function isAll(array $types) {
640: $result = array_filter(array_map(array($this, 'is'), $types));
641: return count($result) === count($types);
642: }
643:
644: /**
645: * Add a new detector to the list of detectors that a request can use.
646: * There are several different formats and types of detectors that can be set.
647: *
648: * ### Environment value comparison
649: *
650: * An environment value comparison, compares a value fetched from `env()` to a known value
651: * the environment value is equality checked against the provided value.
652: *
653: * e.g `addDetector('post', array('env' => 'REQUEST_METHOD', 'value' => 'POST'))`
654: *
655: * ### Pattern value comparison
656: *
657: * Pattern value comparison allows you to compare a value fetched from `env()` to a regular expression.
658: *
659: * e.g `addDetector('iphone', array('env' => 'HTTP_USER_AGENT', 'pattern' => '/iPhone/i'));`
660: *
661: * ### Option based comparison
662: *
663: * Option based comparisons use a list of options to create a regular expression. Subsequent calls
664: * to add an already defined options detector will merge the options.
665: *
666: * e.g `addDetector('mobile', array('env' => 'HTTP_USER_AGENT', 'options' => array('Fennec')));`
667: *
668: * ### Callback detectors
669: *
670: * Callback detectors allow you to provide a 'callback' type to handle the check. The callback will
671: * receive the request object as its only parameter.
672: *
673: * e.g `addDetector('custom', array('callback' => array('SomeClass', 'somemethod')));`
674: *
675: * ### Request parameter detectors
676: *
677: * Allows for custom detectors on the request parameters.
678: *
679: * e.g `addDetector('requested', array('param' => 'requested', 'value' => 1)`
680: *
681: * You can also make parameter detectors that accept multiple values
682: * using the `options` key. This is useful when you want to check
683: * if a request parameter is in a list of options.
684: *
685: * `addDetector('extension', array('param' => 'ext', 'options' => array('pdf', 'csv'))`
686: *
687: * @param string $name The name of the detector.
688: * @param array $options The options for the detector definition. See above.
689: * @return void
690: */
691: public function addDetector($name, $options) {
692: $name = strtolower($name);
693: if (isset($this->_detectors[$name]) && isset($options['options'])) {
694: $options = Hash::merge($this->_detectors[$name], $options);
695: }
696: $this->_detectors[$name] = $options;
697: }
698:
699: /**
700: * Add parameters to the request's parsed parameter set. This will overwrite any existing parameters.
701: * This modifies the parameters available through `$request->params`.
702: *
703: * @param array $params Array of parameters to merge in
704: * @return self
705: */
706: public function addParams($params) {
707: $this->params = array_merge($this->params, (array)$params);
708: return $this;
709: }
710:
711: /**
712: * Add paths to the requests' paths vars. This will overwrite any existing paths.
713: * Provides an easy way to modify, here, webroot and base.
714: *
715: * @param array $paths Array of paths to merge in
716: * @return self
717: */
718: public function addPaths($paths) {
719: foreach (array('webroot', 'here', 'base') as $element) {
720: if (isset($paths[$element])) {
721: $this->{$element} = $paths[$element];
722: }
723: }
724: return $this;
725: }
726:
727: /**
728: * Get the value of the current requests URL. Will include named parameters and querystring arguments.
729: *
730: * @param bool $base Include the base path, set to false to trim the base path off.
731: * @return string the current request URL including query string args.
732: */
733: public function here($base = true) {
734: $url = $this->here;
735: if (!empty($this->query)) {
736: $url .= '?' . http_build_query($this->query, null, '&');
737: }
738: if (!$base) {
739: $url = preg_replace('/^' . preg_quote($this->base, '/') . '/', '', $url, 1);
740: }
741: return $url;
742: }
743:
744: /**
745: * Read an HTTP header from the Request information.
746: *
747: * @param string $name Name of the header you want.
748: * @return mixed Either false on no header being set or the value of the header.
749: */
750: public static function header($name) {
751: $httpName = 'HTTP_' . strtoupper(str_replace('-', '_', $name));
752: if (isset($_SERVER[$httpName])) {
753: return $_SERVER[$httpName];
754: }
755: // Use the provided value, in some configurations apache will
756: // pass Authorization with no prefix and in Titlecase.
757: if (isset($_SERVER[$name])) {
758: return $_SERVER[$name];
759: }
760: return false;
761: }
762:
763: /**
764: * Get the HTTP method used for this request.
765: * There are a few ways to specify a method.
766: *
767: * - If your client supports it you can use native HTTP methods.
768: * - You can set the HTTP-X-Method-Override header.
769: * - You can submit an input with the name `_method`
770: *
771: * Any of these 3 approaches can be used to set the HTTP method used
772: * by CakePHP internally, and will effect the result of this method.
773: *
774: * @return string The name of the HTTP method used.
775: */
776: public function method() {
777: return env('REQUEST_METHOD');
778: }
779:
780: /**
781: * Get the host that the request was handled on.
782: *
783: * @param bool $trustProxy Whether or not to trust the proxy host.
784: * @return string
785: */
786: public function host($trustProxy = false) {
787: if ($trustProxy) {
788: return env('HTTP_X_FORWARDED_HOST');
789: }
790: return env('HTTP_HOST');
791: }
792:
793: /**
794: * Get the domain name and include $tldLength segments of the tld.
795: *
796: * @param int $tldLength Number of segments your tld contains. For example: `example.com` contains 1 tld.
797: * While `example.co.uk` contains 2.
798: * @return string Domain name without subdomains.
799: */
800: public function domain($tldLength = 1) {
801: $segments = explode('.', $this->host());
802: $domain = array_slice($segments, -1 * ($tldLength + 1));
803: return implode('.', $domain);
804: }
805:
806: /**
807: * Get the subdomains for a host.
808: *
809: * @param int $tldLength Number of segments your tld contains. For example: `example.com` contains 1 tld.
810: * While `example.co.uk` contains 2.
811: * @return array An array of subdomains.
812: */
813: public function subdomains($tldLength = 1) {
814: $segments = explode('.', $this->host());
815: return array_slice($segments, 0, -1 * ($tldLength + 1));
816: }
817:
818: /**
819: * Find out which content types the client accepts or check if they accept a
820: * particular type of content.
821: *
822: * #### Get all types:
823: *
824: * `$this->request->accepts();`
825: *
826: * #### Check for a single type:
827: *
828: * `$this->request->accepts('application/json');`
829: *
830: * This method will order the returned content types by the preference values indicated
831: * by the client.
832: *
833: * @param string $type The content type to check for. Leave null to get all types a client accepts.
834: * @return mixed Either an array of all the types the client accepts or a boolean if they accept the
835: * provided type.
836: */
837: public function accepts($type = null) {
838: $raw = $this->parseAccept();
839: $accept = array();
840: foreach ($raw as $types) {
841: $accept = array_merge($accept, $types);
842: }
843: if ($type === null) {
844: return $accept;
845: }
846: return in_array($type, $accept);
847: }
848:
849: /**
850: * Parse the HTTP_ACCEPT header and return a sorted array with content types
851: * as the keys, and pref values as the values.
852: *
853: * Generally you want to use CakeRequest::accept() to get a simple list
854: * of the accepted content types.
855: *
856: * @return array An array of prefValue => array(content/types)
857: */
858: public function parseAccept() {
859: return $this->_parseAcceptWithQualifier($this->header('accept'));
860: }
861:
862: /**
863: * Get the languages accepted by the client, or check if a specific language is accepted.
864: *
865: * Get the list of accepted languages:
866: *
867: * ``` CakeRequest::acceptLanguage(); ```
868: *
869: * Check if a specific language is accepted:
870: *
871: * ``` CakeRequest::acceptLanguage('es-es'); ```
872: *
873: * @param string $language The language to test.
874: * @return mixed If a $language is provided, a boolean. Otherwise the array of accepted languages.
875: */
876: public static function acceptLanguage($language = null) {
877: $raw = static::_parseAcceptWithQualifier(static::header('Accept-Language'));
878: $accept = array();
879: foreach ($raw as $languages) {
880: foreach ($languages as &$lang) {
881: if (strpos($lang, '_')) {
882: $lang = str_replace('_', '-', $lang);
883: }
884: $lang = strtolower($lang);
885: }
886: $accept = array_merge($accept, $languages);
887: }
888: if ($language === null) {
889: return $accept;
890: }
891: return in_array(strtolower($language), $accept);
892: }
893:
894: /**
895: * Parse Accept* headers with qualifier options.
896: *
897: * Only qualifiers will be extracted, any other accept extensions will be
898: * discarded as they are not frequently used.
899: *
900: * @param string $header Header to parse.
901: * @return array
902: */
903: protected static function _parseAcceptWithQualifier($header) {
904: $accept = array();
905: $header = explode(',', $header);
906: foreach (array_filter($header) as $value) {
907: $prefValue = '1.0';
908: $value = trim($value);
909:
910: $semiPos = strpos($value, ';');
911: if ($semiPos !== false) {
912: $params = explode(';', $value);
913: $value = trim($params[0]);
914: foreach ($params as $param) {
915: $qPos = strpos($param, 'q=');
916: if ($qPos !== false) {
917: $prefValue = substr($param, $qPos + 2);
918: }
919: }
920: }
921:
922: if (!isset($accept[$prefValue])) {
923: $accept[$prefValue] = array();
924: }
925: if ($prefValue) {
926: $accept[$prefValue][] = $value;
927: }
928: }
929: krsort($accept);
930: return $accept;
931: }
932:
933: /**
934: * Provides a read accessor for `$this->query`. Allows you
935: * to use a syntax similar to `CakeSession` for reading URL query data.
936: *
937: * @param string $name Query string variable name
938: * @return mixed The value being read
939: */
940: public function query($name) {
941: return Hash::get($this->query, $name);
942: }
943:
944: /**
945: * Provides a read/write accessor for `$this->data`. Allows you
946: * to use a syntax similar to `CakeSession` for reading post data.
947: *
948: * ## Reading values.
949: *
950: * `$request->data('Post.title');`
951: *
952: * When reading values you will get `null` for keys/values that do not exist.
953: *
954: * ## Writing values
955: *
956: * `$request->data('Post.title', 'New post!');`
957: *
958: * You can write to any value, even paths/keys that do not exist, and the arrays
959: * will be created for you.
960: *
961: * @param string $name Dot separated name of the value to read/write, one or more args.
962: * @return mixed|self Either the value being read, or $this so you can chain consecutive writes.
963: */
964: public function data($name) {
965: $args = func_get_args();
966: if (count($args) === 2) {
967: $this->data = Hash::insert($this->data, $name, $args[1]);
968: return $this;
969: }
970: return Hash::get($this->data, $name);
971: }
972:
973: /**
974: * Safely access the values in $this->params.
975: *
976: * @param string $name The name of the parameter to get.
977: * @return mixed The value of the provided parameter. Will
978: * return false if the parameter doesn't exist or is falsey.
979: */
980: public function param($name) {
981: $args = func_get_args();
982: if (count($args) === 2) {
983: $this->params = Hash::insert($this->params, $name, $args[1]);
984: return $this;
985: }
986: if (!isset($this->params[$name])) {
987: return Hash::get($this->params, $name, false);
988: }
989: return $this->params[$name];
990: }
991:
992: /**
993: * Read data from `php://input`. Useful when interacting with XML or JSON
994: * request body content.
995: *
996: * Getting input with a decoding function:
997: *
998: * `$this->request->input('json_decode');`
999: *
1000: * Getting input using a decoding function, and additional params:
1001: *
1002: * `$this->request->input('Xml::build', array('return' => 'DOMDocument'));`
1003: *
1004: * Any additional parameters are applied to the callback in the order they are given.
1005: *
1006: * @param string $callback A decoding callback that will convert the string data to another
1007: * representation. Leave empty to access the raw input data. You can also
1008: * supply additional parameters for the decoding callback using var args, see above.
1009: * @return The decoded/processed request data.
1010: */
1011: public function input($callback = null) {
1012: $input = $this->_readInput();
1013: $args = func_get_args();
1014: if (!empty($args)) {
1015: $callback = array_shift($args);
1016: array_unshift($args, $input);
1017: return call_user_func_array($callback, $args);
1018: }
1019: return $input;
1020: }
1021:
1022: /**
1023: * Modify data originally from `php://input`. Useful for altering json/xml data
1024: * in middleware or DispatcherFilters before it gets to RequestHandlerComponent
1025: *
1026: * @param string $input A string to replace original parsed data from input()
1027: * @return void
1028: */
1029: public function setInput($input) {
1030: $this->_input = $input;
1031: }
1032:
1033: /**
1034: * Allow only certain HTTP request methods. If the request method does not match
1035: * a 405 error will be shown and the required "Allow" response header will be set.
1036: *
1037: * Example:
1038: *
1039: * $this->request->allowMethod('post', 'delete');
1040: * or
1041: * $this->request->allowMethod(array('post', 'delete'));
1042: *
1043: * If the request would be GET, response header "Allow: POST, DELETE" will be set
1044: * and a 405 error will be returned.
1045: *
1046: * @param string|array $methods Allowed HTTP request methods.
1047: * @return bool true
1048: * @throws MethodNotAllowedException
1049: */
1050: public function allowMethod($methods) {
1051: if (!is_array($methods)) {
1052: $methods = func_get_args();
1053: }
1054: foreach ($methods as $method) {
1055: if ($this->is($method)) {
1056: return true;
1057: }
1058: }
1059: $allowed = strtoupper(implode(', ', $methods));
1060: $e = new MethodNotAllowedException();
1061: $e->responseHeader('Allow', $allowed);
1062: throw $e;
1063: }
1064:
1065: /**
1066: * Alias of CakeRequest::allowMethod() for backwards compatibility.
1067: *
1068: * @param string|array $methods Allowed HTTP request methods.
1069: * @return bool true
1070: * @throws MethodNotAllowedException
1071: * @see CakeRequest::allowMethod()
1072: * @deprecated 3.0.0 Since 2.5, use CakeRequest::allowMethod() instead.
1073: */
1074: public function onlyAllow($methods) {
1075: if (!is_array($methods)) {
1076: $methods = func_get_args();
1077: }
1078: return $this->allowMethod($methods);
1079: }
1080:
1081: /**
1082: * Read data from php://input, mocked in tests.
1083: *
1084: * @return string contents of php://input
1085: */
1086: protected function _readInput() {
1087: if (empty($this->_input)) {
1088: $fh = fopen('php://input', 'r');
1089: $content = stream_get_contents($fh);
1090: fclose($fh);
1091: $this->_input = $content;
1092: }
1093: return $this->_input;
1094: }
1095:
1096: /**
1097: * Array access read implementation
1098: *
1099: * @param string $name Name of the key being accessed.
1100: * @return mixed
1101: */
1102: public function offsetGet($name) {
1103: if (isset($this->params[$name])) {
1104: return $this->params[$name];
1105: }
1106: if ($name === 'url') {
1107: return $this->query;
1108: }
1109: if ($name === 'data') {
1110: return $this->data;
1111: }
1112: return null;
1113: }
1114:
1115: /**
1116: * Array access write implementation
1117: *
1118: * @param string $name Name of the key being written
1119: * @param mixed $value The value being written.
1120: * @return void
1121: */
1122: public function offsetSet($name, $value) {
1123: $this->params[$name] = $value;
1124: }
1125:
1126: /**
1127: * Array access isset() implementation
1128: *
1129: * @param string $name thing to check.
1130: * @return bool
1131: */
1132: public function offsetExists($name) {
1133: if ($name === 'url' || $name === 'data') {
1134: return true;
1135: }
1136: return isset($this->params[$name]);
1137: }
1138:
1139: /**
1140: * Array access unset() implementation
1141: *
1142: * @param string $name Name to unset.
1143: * @return void
1144: */
1145: public function offsetUnset($name) {
1146: unset($this->params[$name]);
1147: }
1148:
1149: }
1150: