1: <?php
2: /**
3: * CakeRequest
4: *
5: * PHP 5
6: *
7: * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
8: * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
9: *
10: * Licensed under The MIT License
11: * Redistributions of files must retain the above copyright notice.
12: *
13: * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
14: * @link http://cakephp.org CakePHP(tm) Project
15: * @since CakePHP(tm) v 2.0
16: * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
17: */
18:
19: App::uses('Set', 'Utility');
20:
21: /**
22: * A class that helps wrap Request information and particulars about a single request.
23: * Provides methods commonly used to introspect on the request headers and request body.
24: *
25: * Has both an Array and Object interface. You can access framework parameters using indexes:
26: *
27: * `$request['controller']` or `$request->controller`.
28: *
29: * @package Cake.Network
30: */
31: class CakeRequest implements ArrayAccess {
32:
33: /**
34: * Array of parameters parsed from the url.
35: *
36: * @var array
37: */
38: public $params = array(
39: 'plugin' => null,
40: 'controller' => null,
41: 'action' => null,
42: 'named' => array(),
43: 'pass' => array(),
44: );
45:
46: /**
47: * Array of POST data. Will contain form data as well as uploaded files.
48: * Inputs prefixed with 'data' will have the data prefix removed. If there is
49: * overlap between an input prefixed with data and one without, the 'data' prefixed
50: * value will take precedence.
51: *
52: * @var array
53: */
54: public $data = array();
55:
56: /**
57: * Array of querystring arguments
58: *
59: * @var array
60: */
61: public $query = array();
62:
63: /**
64: * The url string used for the request.
65: *
66: * @var string
67: */
68: public $url;
69:
70: /**
71: * Base url path.
72: *
73: * @var string
74: */
75: public $base = false;
76:
77: /**
78: * webroot path segment for the request.
79: *
80: * @var string
81: */
82: public $webroot = '/';
83:
84: /**
85: * The full address to the current request
86: *
87: * @var string
88: */
89: public $here = null;
90:
91: /**
92: * The built in detectors used with `is()` can be modified with `addDetector()`.
93: *
94: * There are several ways to specify a detector, see CakeRequest::addDetector() for the
95: * various formats and ways to define detectors.
96: *
97: * @var array
98: */
99: protected $_detectors = array(
100: 'get' => array('env' => 'REQUEST_METHOD', 'value' => 'GET'),
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', '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: );
117:
118: /**
119: * Copy of php://input. Since this stream can only be read once in most SAPI's
120: * keep a copy of it so users don't need to know about that detail.
121: *
122: * @var string
123: */
124: protected $_input = '';
125:
126: /**
127: * Constructor
128: *
129: * @param string $url Trimmed url string to use. Should not contain the application base path.
130: * @param boolean $parseEnvironment Set to false to not auto parse the environment. ie. GET, POST and FILES.
131: */
132: public function __construct($url = null, $parseEnvironment = true) {
133: $this->_base();
134: if (empty($url)) {
135: $url = $this->_url();
136: }
137: if ($url[0] == '/') {
138: $url = substr($url, 1);
139: }
140: $this->url = $url;
141:
142: if ($parseEnvironment) {
143: $this->_processPost();
144: $this->_processGet();
145: $this->_processFiles();
146: }
147: $this->here = $this->base . '/' . $this->url;
148: }
149:
150: /**
151: * process the post data and set what is there into the object.
152: * processed data is available at `$this->data`
153: *
154: * Will merge POST vars prefixed with `data`, and ones without
155: * into a single array. Variables prefixed with `data` will overwrite those without.
156: *
157: * If you have mixed POST values be careful not to make any top level keys numeric
158: * containing arrays. Set::merge() is used to merge data, and it has possibly
159: * unexpected behavior in this situation.
160: *
161: * @return void
162: */
163: protected function _processPost() {
164: $this->data = $_POST;
165: if (ini_get('magic_quotes_gpc') === '1') {
166: $this->data = stripslashes_deep($this->data);
167: }
168: if (env('HTTP_X_HTTP_METHOD_OVERRIDE')) {
169: $this->data['_method'] = env('HTTP_X_HTTP_METHOD_OVERRIDE');
170: }
171: if (isset($this->data['_method'])) {
172: if (!empty($_SERVER)) {
173: $_SERVER['REQUEST_METHOD'] = $this->data['_method'];
174: } else {
175: $_ENV['REQUEST_METHOD'] = $this->data['_method'];
176: }
177: unset($this->data['_method']);
178: }
179:
180: if (isset($this->data['data'])) {
181: $data = $this->data['data'];
182: if (count($this->data) <= 1) {
183: $this->data = $data;
184: } else {
185: unset($this->data['data']);
186: $this->data = Set::merge($this->data, $data);
187: }
188: }
189: }
190:
191: /**
192: * Process the GET parameters and move things into the object.
193: *
194: * @return void
195: */
196: protected function _processGet() {
197: if (ini_get('magic_quotes_gpc') === '1') {
198: $query = stripslashes_deep($_GET);
199: } else {
200: $query = $_GET;
201: }
202:
203: unset($query['/' . str_replace('.', '_', urldecode($this->url))]);
204: if (strpos($this->url, '?') !== false) {
205: list(, $querystr) = explode('?', $this->url);
206: parse_str($querystr, $queryArgs);
207: $query += $queryArgs;
208: }
209: if (isset($this->params['url'])) {
210: $query = array_merge($this->params['url'], $query);
211: }
212: $this->query = $query;
213: }
214:
215: /**
216: * Get the request uri. Looks in PATH_INFO first, as this is the exact value we need prepared
217: * by PHP. Following that, REQUEST_URI, PHP_SELF, HTTP_X_REWRITE_URL and argv are checked in that order.
218: * Each of these server variables have the base path, and query strings stripped off
219: *
220: * @return string URI The CakePHP request path that is being accessed.
221: */
222: protected function _url() {
223: if (!empty($_SERVER['PATH_INFO'])) {
224: return $_SERVER['PATH_INFO'];
225: } elseif (isset($_SERVER['REQUEST_URI'])) {
226: $uri = $_SERVER['REQUEST_URI'];
227: } elseif (isset($_SERVER['PHP_SELF']) && isset($_SERVER['SCRIPT_NAME'])) {
228: $uri = str_replace($_SERVER['SCRIPT_NAME'], '', $_SERVER['PHP_SELF']);
229: } elseif (isset($_SERVER['HTTP_X_REWRITE_URL'])) {
230: $uri = $_SERVER['HTTP_X_REWRITE_URL'];
231: } elseif ($var = env('argv')) {
232: $uri = $var[0];
233: }
234:
235: $base = $this->base;
236:
237: if (strlen($base) > 0 && strpos($uri, $base) === 0) {
238: $uri = substr($uri, strlen($base));
239: }
240: if (strpos($uri, '?') !== false) {
241: list($uri) = explode('?', $uri, 2);
242: }
243: if (empty($uri) || $uri == '/' || $uri == '//') {
244: return '/';
245: }
246: return $uri;
247: }
248:
249: /**
250: * Returns a base URL and sets the proper webroot
251: *
252: * @return string Base URL
253: */
254: protected function _base() {
255: $dir = $webroot = null;
256: $config = Configure::read('App');
257: extract($config);
258:
259: if (!isset($base)) {
260: $base = $this->base;
261: }
262: if ($base !== false) {
263: $this->webroot = $base . '/';
264: return $this->base = $base;
265: }
266:
267: if (!$baseUrl) {
268: $base = dirname(env('PHP_SELF'));
269:
270: if ($webroot === 'webroot' && $webroot === basename($base)) {
271: $base = dirname($base);
272: }
273: if ($dir === 'app' && $dir === basename($base)) {
274: $base = dirname($base);
275: }
276:
277: if ($base === DS || $base === '.') {
278: $base = '';
279: }
280:
281: $this->webroot = $base . '/';
282: return $this->base = $base;
283: }
284:
285: $file = '/' . basename($baseUrl);
286: $base = dirname($baseUrl);
287:
288: if ($base === DS || $base === '.') {
289: $base = '';
290: }
291: $this->webroot = $base . '/';
292:
293: $docRoot = env('DOCUMENT_ROOT');
294: $docRootContainsWebroot = strpos($docRoot, $dir . '/' . $webroot);
295:
296: if (!empty($base) || !$docRootContainsWebroot) {
297: if (strpos($this->webroot, '/' . $dir . '/') === false) {
298: $this->webroot .= $dir . '/';
299: }
300: if (strpos($this->webroot, '/' . $webroot . '/') === false) {
301: $this->webroot .= $webroot . '/';
302: }
303: }
304: return $this->base = $base . $file;
305: }
306:
307: /**
308: * Process $_FILES and move things into the object.
309: *
310: * @return void
311: */
312: protected function _processFiles() {
313: if (isset($_FILES) && is_array($_FILES)) {
314: foreach ($_FILES as $name => $data) {
315: if ($name != 'data') {
316: $this->params['form'][$name] = $data;
317: }
318: }
319: }
320:
321: if (isset($_FILES['data'])) {
322: foreach ($_FILES['data'] as $key => $data) {
323: $this->_processFileData('', $data, $key);
324: }
325: }
326: }
327:
328: /**
329: * Recursively walks the FILES array restructuring the data
330: * into something sane and useable.
331: *
332: * @param string $path The dot separated path to insert $data into.
333: * @param array $data The data to traverse/insert.
334: * @param string $field The terminal field name, which is the top level key in $_FILES.
335: * @return void
336: */
337: protected function _processFileData($path, $data, $field) {
338: foreach ($data as $key => $fields) {
339: $newPath = $key;
340: if (!empty($path)) {
341: $newPath = $path . '.' . $key;
342: }
343: if (is_array($fields)) {
344: $this->_processFileData($newPath, $fields, $field);
345: } else {
346: $newPath .= '.' . $field;
347: $this->data = Set::insert($this->data, $newPath, $fields);
348: }
349: }
350: }
351:
352: /**
353: * Get the IP the client is using, or says they are using.
354: *
355: * @param boolean $safe Use safe = false when you think the user might manipulate their HTTP_CLIENT_IP
356: * header. Setting $safe = false will will also look at HTTP_X_FORWARDED_FOR
357: * @return string The client IP.
358: */
359: public function clientIp($safe = true) {
360: if (!$safe && env('HTTP_X_FORWARDED_FOR') != null) {
361: $ipaddr = preg_replace('/(?:,.*)/', '', env('HTTP_X_FORWARDED_FOR'));
362: } else {
363: if (env('HTTP_CLIENT_IP') != null) {
364: $ipaddr = env('HTTP_CLIENT_IP');
365: } else {
366: $ipaddr = env('REMOTE_ADDR');
367: }
368: }
369:
370: if (env('HTTP_CLIENTADDRESS') != null) {
371: $tmpipaddr = env('HTTP_CLIENTADDRESS');
372:
373: if (!empty($tmpipaddr)) {
374: $ipaddr = preg_replace('/(?:,.*)/', '', $tmpipaddr);
375: }
376: }
377: return trim($ipaddr);
378: }
379:
380: /**
381: * Returns the referer that referred this request.
382: *
383: * @param boolean $local Attempt to return a local address. Local addresses do not contain hostnames.
384: * @return string The referring address for this request.
385: */
386: public function referer($local = false) {
387: $ref = env('HTTP_REFERER');
388: $forwarded = env('HTTP_X_FORWARDED_HOST');
389: if ($forwarded) {
390: $ref = $forwarded;
391: }
392:
393: $base = '';
394: if (defined('FULL_BASE_URL')) {
395: $base = FULL_BASE_URL . $this->webroot;
396: }
397: if (!empty($ref) && !empty($base)) {
398: if ($local && strpos($ref, $base) === 0) {
399: $ref = substr($ref, strlen($base));
400: if ($ref[0] != '/') {
401: $ref = '/' . $ref;
402: }
403: return $ref;
404: } elseif (!$local) {
405: return $ref;
406: }
407: }
408: return '/';
409: }
410:
411: /**
412: * Missing method handler, handles wrapping older style isAjax() type methods
413: *
414: * @param string $name The method called
415: * @param array $params Array of parameters for the method call
416: * @return mixed
417: * @throws CakeException when an invalid method is called.
418: */
419: public function __call($name, $params) {
420: if (strpos($name, 'is') === 0) {
421: $type = strtolower(substr($name, 2));
422: return $this->is($type);
423: }
424: throw new CakeException(__d('cake_dev', 'Method %s does not exist', $name));
425: }
426:
427: /**
428: * Magic get method allows access to parsed routing parameters directly on the object.
429: *
430: * Allows access to `$this->params['controller']` via `$this->controller`
431: *
432: * @param string $name The property being accessed.
433: * @return mixed Either the value of the parameter or null.
434: */
435: public function __get($name) {
436: if (isset($this->params[$name])) {
437: return $this->params[$name];
438: }
439: return null;
440: }
441:
442: /**
443: * Magic isset method allows isset/empty checks
444: * on routing parameters.
445: *
446: * @param string $name The property being accessed.
447: * @return bool Existence
448: */
449: public function __isset($name) {
450: return isset($this->params[$name]);
451: }
452:
453: /**
454: * Check whether or not a Request is a certain type. Uses the built in detection rules
455: * as well as additional rules defined with CakeRequest::addDetector(). Any detector can be called
456: * as `is($type)` or `is$Type()`.
457: *
458: * @param string $type The type of request you want to check.
459: * @return boolean Whether or not the request is the type you are checking.
460: */
461: public function is($type) {
462: $type = strtolower($type);
463: if (!isset($this->_detectors[$type])) {
464: return false;
465: }
466: $detect = $this->_detectors[$type];
467: if (isset($detect['env'])) {
468: if (isset($detect['value'])) {
469: return env($detect['env']) == $detect['value'];
470: }
471: if (isset($detect['pattern'])) {
472: return (bool)preg_match($detect['pattern'], env($detect['env']));
473: }
474: if (isset($detect['options'])) {
475: $pattern = '/' . implode('|', $detect['options']) . '/i';
476: return (bool)preg_match($pattern, env($detect['env']));
477: }
478: }
479: if (isset($detect['param'])) {
480: $key = $detect['param'];
481: $value = $detect['value'];
482: return isset($this->params[$key]) ? $this->params[$key] == $value : false;
483: }
484: if (isset($detect['callback']) && is_callable($detect['callback'])) {
485: return call_user_func($detect['callback'], $this);
486: }
487: return false;
488: }
489:
490: /**
491: * Add a new detector to the list of detectors that a request can use.
492: * There are several different formats and types of detectors that can be set.
493: *
494: * ### Environment value comparison
495: *
496: * An environment value comparison, compares a value fetched from `env()` to a known value
497: * the environment value is equality checked against the provided value.
498: *
499: * e.g `addDetector('post', array('env' => 'REQUEST_METHOD', 'value' => 'POST'))`
500: *
501: * ### Pattern value comparison
502: *
503: * Pattern value comparison allows you to compare a value fetched from `env()` to a regular expression.
504: *
505: * e.g `addDetector('iphone', array('env' => 'HTTP_USER_AGENT', 'pattern' => '/iPhone/i'));`
506: *
507: * ### Option based comparison
508: *
509: * Option based comparisons use a list of options to create a regular expression. Subsequent calls
510: * to add an already defined options detector will merge the options.
511: *
512: * e.g `addDetector('mobile', array('env' => 'HTTP_USER_AGENT', 'options' => array('Fennec')));`
513: *
514: * ### Callback detectors
515: *
516: * Callback detectors allow you to provide a 'callback' type to handle the check. The callback will
517: * receive the request object as its only parameter.
518: *
519: * e.g `addDetector('custom', array('callback' => array('SomeClass', 'somemethod')));`
520: *
521: * ### Request parameter detectors
522: *
523: * Allows for custom detectors on the request parameters.
524: *
525: * e.g `addDetector('post', array('param' => 'requested', 'value' => 1)`
526: *
527: * @param string $name The name of the detector.
528: * @param array $options The options for the detector definition. See above.
529: * @return void
530: */
531: public function addDetector($name, $options) {
532: $name = strtolower($name);
533: if (isset($this->_detectors[$name]) && isset($options['options'])) {
534: $options = Set::merge($this->_detectors[$name], $options);
535: }
536: $this->_detectors[$name] = $options;
537: }
538:
539: /**
540: * Add parameters to the request's parsed parameter set. This will overwrite any existing parameters.
541: * This modifies the parameters available through `$request->params`.
542: *
543: * @param array $params Array of parameters to merge in
544: * @return The current object, you can chain this method.
545: */
546: public function addParams($params) {
547: $this->params = array_merge($this->params, (array)$params);
548: return $this;
549: }
550:
551: /**
552: * Add paths to the requests' paths vars. This will overwrite any existing paths.
553: * Provides an easy way to modify, here, webroot and base.
554: *
555: * @param array $paths Array of paths to merge in
556: * @return CakeRequest the current object, you can chain this method.
557: */
558: public function addPaths($paths) {
559: foreach (array('webroot', 'here', 'base') as $element) {
560: if (isset($paths[$element])) {
561: $this->{$element} = $paths[$element];
562: }
563: }
564: return $this;
565: }
566:
567: /**
568: * Get the value of the current requests url. Will include named parameters and querystring arguments.
569: *
570: * @param boolean $base Include the base path, set to false to trim the base path off.
571: * @return string the current request url including query string args.
572: */
573: public function here($base = true) {
574: $url = $this->here;
575: if (!empty($this->query)) {
576: $url .= '?' . http_build_query($this->query, null, '&');
577: }
578: if (!$base) {
579: $url = preg_replace('/^' . preg_quote($this->base, '/') . '/', '', $url, 1);
580: }
581: return $url;
582: }
583:
584: /**
585: * Read an HTTP header from the Request information.
586: *
587: * @param string $name Name of the header you want.
588: * @return mixed Either false on no header being set or the value of the header.
589: */
590: public static function header($name) {
591: $name = 'HTTP_' . strtoupper(str_replace('-', '_', $name));
592: if (!empty($_SERVER[$name])) {
593: return $_SERVER[$name];
594: }
595: return false;
596: }
597:
598: /**
599: * Get the HTTP method used for this request.
600: * There are a few ways to specify a method.
601: *
602: * - If your client supports it you can use native HTTP methods.
603: * - You can set the HTTP-X-Method-Override header.
604: * - You can submit an input with the name `_method`
605: *
606: * Any of these 3 approaches can be used to set the HTTP method used
607: * by CakePHP internally, and will effect the result of this method.
608: *
609: * @return string The name of the HTTP method used.
610: */
611: public function method() {
612: return env('REQUEST_METHOD');
613: }
614:
615: /**
616: * Get the host that the request was handled on.
617: *
618: * @return string
619: */
620: public function host() {
621: return env('HTTP_HOST');
622: }
623:
624: /**
625: * Get the domain name and include $tldLength segments of the tld.
626: *
627: * @param integer $tldLength Number of segments your tld contains. For example: `example.com` contains 1 tld.
628: * While `example.co.uk` contains 2.
629: * @return string Domain name without subdomains.
630: */
631: public function domain($tldLength = 1) {
632: $segments = explode('.', $this->host());
633: $domain = array_slice($segments, -1 * ($tldLength + 1));
634: return implode('.', $domain);
635: }
636:
637: /**
638: * Get the subdomains for a host.
639: *
640: * @param integer $tldLength Number of segments your tld contains. For example: `example.com` contains 1 tld.
641: * While `example.co.uk` contains 2.
642: * @return array of subdomains.
643: */
644: public function subdomains($tldLength = 1) {
645: $segments = explode('.', $this->host());
646: return array_slice($segments, 0, -1 * ($tldLength + 1));
647: }
648:
649: /**
650: * Find out which content types the client accepts or check if they accept a
651: * particular type of content.
652: *
653: * #### Get all types:
654: *
655: * `$this->request->accepts();`
656: *
657: * #### Check for a single type:
658: *
659: * `$this->request->accepts('application/json');`
660: *
661: * This method will order the returned content types by the preference values indicated
662: * by the client.
663: *
664: * @param string $type The content type to check for. Leave null to get all types a client accepts.
665: * @return mixed Either an array of all the types the client accepts or a boolean if they accept the
666: * provided type.
667: */
668: public function accepts($type = null) {
669: $raw = $this->parseAccept();
670: $accept = array();
671: foreach ($raw as $value => $types) {
672: $accept = array_merge($accept, $types);
673: }
674: if ($type === null) {
675: return $accept;
676: }
677: return in_array($type, $accept);
678: }
679:
680: /**
681: * Parse the HTTP_ACCEPT header and return a sorted array with content types
682: * as the keys, and pref values as the values.
683: *
684: * Generally you want to use CakeRequest::accept() to get a simple list
685: * of the accepted content types.
686: *
687: * @return array An array of prefValue => array(content/types)
688: */
689: public function parseAccept() {
690: $accept = array();
691: $header = explode(',', $this->header('accept'));
692: foreach (array_filter($header) as $value) {
693: $prefPos = strpos($value, ';');
694: if ($prefPos !== false) {
695: $prefValue = substr($value, strpos($value, '=') + 1);
696: $value = trim(substr($value, 0, $prefPos));
697: } else {
698: $prefValue = '1.0';
699: $value = trim($value);
700: }
701: if (!isset($accept[$prefValue])) {
702: $accept[$prefValue] = array();
703: }
704: if ($prefValue) {
705: $accept[$prefValue][] = $value;
706: }
707: }
708: krsort($accept);
709: return $accept;
710: }
711:
712: /**
713: * Get the languages accepted by the client, or check if a specific language is accepted.
714: *
715: * Get the list of accepted languages:
716: *
717: * {{{ CakeRequest::acceptLanguage(); }}}
718: *
719: * Check if a specific language is accepted:
720: *
721: * {{{ CakeRequest::acceptLanguage('es-es'); }}}
722: *
723: * @param string $language The language to test.
724: * @return If a $language is provided, a boolean. Otherwise the array of accepted languages.
725: */
726: public static function acceptLanguage($language = null) {
727: $accepts = preg_split('/[;,]/', self::header('Accept-Language'));
728: foreach ($accepts as &$accept) {
729: $accept = strtolower($accept);
730: if (strpos($accept, '_') !== false) {
731: $accept = str_replace('_', '-', $accept);
732: }
733: }
734: if ($language === null) {
735: return $accepts;
736: }
737: return in_array($language, $accepts);
738: }
739:
740: /**
741: * Provides a read/write accessor for `$this->data`. Allows you
742: * to use a syntax similar to `CakeSession` for reading post data.
743: *
744: * ## Reading values.
745: *
746: * `$request->data('Post.title');`
747: *
748: * When reading values you will get `null` for keys/values that do not exist.
749: *
750: * ## Writing values
751: *
752: * `$request->data('Post.title', 'New post!');`
753: *
754: * You can write to any value, even paths/keys that do not exist, and the arrays
755: * will be created for you.
756: *
757: * @param string $name,... Dot separated name of the value to read/write
758: * @return mixed Either the value being read, or this so you can chain consecutive writes.
759: */
760: public function data($name) {
761: $args = func_get_args();
762: if (count($args) == 2) {
763: $this->data = Set::insert($this->data, $name, $args[1]);
764: return $this;
765: }
766: return Set::classicExtract($this->data, $name);
767: }
768:
769: /**
770: * Read data from `php://input`. Useful when interacting with XML or JSON
771: * request body content.
772: *
773: * Getting input with a decoding function:
774: *
775: * `$this->request->input('json_decode');`
776: *
777: * Getting input using a decoding function, and additional params:
778: *
779: * `$this->request->input('Xml::build', array('return' => 'DOMDocument'));`
780: *
781: * Any additional parameters are applied to the callback in the order they are given.
782: *
783: * @param string $callback A decoding callback that will convert the string data to another
784: * representation. Leave empty to access the raw input data. You can also
785: * supply additional parameters for the decoding callback using var args, see above.
786: * @return The decoded/processed request data.
787: */
788: public function input($callback = null) {
789: $input = $this->_readInput();
790: $args = func_get_args();
791: if (!empty($args)) {
792: $callback = array_shift($args);
793: array_unshift($args, $input);
794: return call_user_func_array($callback, $args);
795: }
796: return $input;
797: }
798:
799: /**
800: * Read data from php://input, mocked in tests.
801: *
802: * @return string contents of php://input
803: */
804: protected function _readInput() {
805: if (empty($this->_input)) {
806: $fh = fopen('php://input', 'r');
807: $content = stream_get_contents($fh);
808: fclose($fh);
809: $this->_input = $content;
810: }
811: return $this->_input;
812: }
813:
814: /**
815: * Array access read implementation
816: *
817: * @param string $name Name of the key being accessed.
818: * @return mixed
819: */
820: public function offsetGet($name) {
821: if (isset($this->params[$name])) {
822: return $this->params[$name];
823: }
824: if ($name == 'url') {
825: return $this->query;
826: }
827: if ($name == 'data') {
828: return $this->data;
829: }
830: return null;
831: }
832:
833: /**
834: * Array access write implementation
835: *
836: * @param string $name Name of the key being written
837: * @param mixed $value The value being written.
838: * @return void
839: */
840: public function offsetSet($name, $value) {
841: $this->params[$name] = $value;
842: }
843:
844: /**
845: * Array access isset() implementation
846: *
847: * @param string $name thing to check.
848: * @return boolean
849: */
850: public function offsetExists($name) {
851: return isset($this->params[$name]);
852: }
853:
854: /**
855: * Array access unset() implementation
856: *
857: * @param string $name Name to unset.
858: * @return void
859: */
860: public function offsetUnset($name) {
861: unset($this->params[$name]);
862: }
863:
864: }
865: