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