Upgrade CakePHP from 2.2.5 to 2.9.5

This commit is contained in:
Brm Ko 2017-02-26 15:29:44 +01:00
parent 5a580df460
commit 235a541597
793 changed files with 60746 additions and 23753 deletions

View file

@ -2,19 +2,19 @@
/**
* CakeRequest
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('Hash', 'Utility');
/**
@ -30,7 +30,7 @@ App::uses('Hash', 'Utility');
class CakeRequest implements ArrayAccess {
/**
* Array of parameters parsed from the url.
* Array of parameters parsed from the URL.
*
* @var array
*/
@ -43,8 +43,8 @@ class CakeRequest implements ArrayAccess {
);
/**
* Array of POST data. Will contain form data as well as uploaded files.
* Inputs prefixed with 'data' will have the data prefix removed. If there is
* Array of POST data. Will contain form data as well as uploaded files.
* Inputs prefixed with 'data' will have the data prefix removed. If there is
* overlap between an input prefixed with data and one without, the 'data' prefixed
* value will take precedence.
*
@ -60,14 +60,14 @@ class CakeRequest implements ArrayAccess {
public $query = array();
/**
* The url string used for the request.
* The URL string used for the request.
*
* @var string
*/
public $url;
/**
* Base url path.
* Base URL path.
*
* @var string
*/
@ -97,6 +97,7 @@ class CakeRequest implements ArrayAccess {
*/
protected $_detectors = array(
'get' => array('env' => 'REQUEST_METHOD', 'value' => 'GET'),
'patch' => array('env' => 'REQUEST_METHOD', 'value' => 'PATCH'),
'post' => array('env' => 'REQUEST_METHOD', 'value' => 'POST'),
'put' => array('env' => 'REQUEST_METHOD', 'value' => 'PUT'),
'delete' => array('env' => 'REQUEST_METHOD', 'value' => 'DELETE'),
@ -106,16 +107,18 @@ class CakeRequest implements ArrayAccess {
'ajax' => array('env' => 'HTTP_X_REQUESTED_WITH', 'value' => 'XMLHttpRequest'),
'flash' => array('env' => 'HTTP_USER_AGENT', 'pattern' => '/^(Shockwave|Adobe) Flash/'),
'mobile' => array('env' => 'HTTP_USER_AGENT', 'options' => array(
'Android', 'AvantGo', 'BlackBerry', 'DoCoMo', 'Fennec', 'iPod', 'iPhone', 'iPad',
'Android', 'AvantGo', 'BB10', 'BlackBerry', 'DoCoMo', 'Fennec', 'iPod', 'iPhone', 'iPad',
'J2ME', 'MIDP', 'NetFront', 'Nokia', 'Opera Mini', 'Opera Mobi', 'PalmOS', 'PalmSource',
'portalmmm', 'Plucker', 'ReqwirelessWeb', 'SonyEricsson', 'Symbian', 'UP\\.Browser',
'webOS', 'Windows CE', 'Windows Phone OS', 'Xiino'
)),
'requested' => array('param' => 'requested', 'value' => 1)
'requested' => array('param' => 'requested', 'value' => 1),
'json' => array('accept' => array('application/json'), 'param' => 'ext', 'value' => 'json'),
'xml' => array('accept' => array('application/xml', 'text/xml'), 'param' => 'ext', 'value' => 'xml'),
);
/**
* Copy of php://input. Since this stream can only be read once in most SAPI's
* Copy of php://input. Since this stream can only be read once in most SAPI's
* keep a copy of it so users don't need to know about that detail.
*
* @var string
@ -125,15 +128,15 @@ class CakeRequest implements ArrayAccess {
/**
* Constructor
*
* @param string $url Trimmed url string to use. Should not contain the application base path.
* @param boolean $parseEnvironment Set to false to not auto parse the environment. ie. GET, POST and FILES.
* @param string $url Trimmed URL string to use. Should not contain the application base path.
* @param bool $parseEnvironment Set to false to not auto parse the environment. ie. GET, POST and FILES.
*/
public function __construct($url = null, $parseEnvironment = true) {
$this->_base();
if (empty($url)) {
$url = $this->_url();
}
if ($url[0] == '/') {
if ($url[0] === '/') {
$url = substr($url, 1);
}
$this->url = $url;
@ -162,9 +165,8 @@ class CakeRequest implements ArrayAccess {
protected function _processPost() {
if ($_POST) {
$this->data = $_POST;
} elseif (
($this->is('put') || $this->is('delete')) &&
strpos(env('CONTENT_TYPE'), 'application/x-www-form-urlencoded') === 0
} elseif (($this->is('put') || $this->is('delete')) &&
strpos($this->contentType(), 'application/x-www-form-urlencoded') === 0
) {
$data = $this->_readInput();
parse_str($data, $this->data);
@ -172,9 +174,13 @@ class CakeRequest implements ArrayAccess {
if (ini_get('magic_quotes_gpc') === '1') {
$this->data = stripslashes_deep($this->data);
}
$override = null;
if (env('HTTP_X_HTTP_METHOD_OVERRIDE')) {
$this->data['_method'] = env('HTTP_X_HTTP_METHOD_OVERRIDE');
$override = $this->data['_method'];
}
$isArray = is_array($this->data);
if ($isArray && isset($this->data['_method'])) {
if (!empty($_SERVER)) {
@ -182,8 +188,14 @@ class CakeRequest implements ArrayAccess {
} else {
$_ENV['REQUEST_METHOD'] = $this->data['_method'];
}
$override = $this->data['_method'];
unset($this->data['_method']);
}
if ($override && !in_array($override, array('POST', 'PUT', 'PATCH', 'DELETE'))) {
$this->data = array();
}
if ($isArray && isset($this->data['data'])) {
$data = $this->data['data'];
if (count($this->data) <= 1) {
@ -207,9 +219,11 @@ class CakeRequest implements ArrayAccess {
$query = $_GET;
}
unset($query['/' . str_replace('.', '_', urldecode($this->url))]);
$unsetUrl = '/' . str_replace(array('.', ' '), '_', urldecode($this->url));
unset($query[$unsetUrl]);
unset($query[$this->base . $unsetUrl]);
if (strpos($this->url, '?') !== false) {
list(, $querystr) = explode('?', $this->url);
list($this->url, $querystr) = explode('?', $this->url);
parse_str($querystr, $queryArgs);
$query += $queryArgs;
}
@ -220,8 +234,8 @@ class CakeRequest implements ArrayAccess {
}
/**
* Get the request uri. Looks in PATH_INFO first, as this is the exact value we need prepared
* by PHP. Following that, REQUEST_URI, PHP_SELF, HTTP_X_REWRITE_URL and argv are checked in that order.
* Get the request uri. Looks in PATH_INFO first, as this is the exact value we need prepared
* by PHP. Following that, REQUEST_URI, PHP_SELF, HTTP_X_REWRITE_URL and argv are checked in that order.
* Each of these server variables have the base path, and query strings stripped off
*
* @return string URI The CakePHP request path that is being accessed.
@ -232,7 +246,12 @@ class CakeRequest implements ArrayAccess {
} elseif (isset($_SERVER['REQUEST_URI']) && strpos($_SERVER['REQUEST_URI'], '://') === false) {
$uri = $_SERVER['REQUEST_URI'];
} elseif (isset($_SERVER['REQUEST_URI'])) {
$uri = substr($_SERVER['REQUEST_URI'], strlen(FULL_BASE_URL));
$qPosition = strpos($_SERVER['REQUEST_URI'], '?');
if ($qPosition !== false && strpos($_SERVER['REQUEST_URI'], '://') > $qPosition) {
$uri = $_SERVER['REQUEST_URI'];
} else {
$uri = substr($_SERVER['REQUEST_URI'], strlen(Configure::read('App.fullBaseUrl')));
}
} elseif (isset($_SERVER['PHP_SELF']) && isset($_SERVER['SCRIPT_NAME'])) {
$uri = str_replace($_SERVER['SCRIPT_NAME'], '', $_SERVER['PHP_SELF']);
} elseif (isset($_SERVER['HTTP_X_REWRITE_URL'])) {
@ -249,8 +268,15 @@ class CakeRequest implements ArrayAccess {
if (strpos($uri, '?') !== false) {
list($uri) = explode('?', $uri, 2);
}
if (empty($uri) || $uri == '/' || $uri == '//') {
return '/';
if (empty($uri) || $uri === '/' || $uri === '//' || $uri === '/index.php') {
$uri = '/';
}
$endsWithIndex = '/webroot/index.php';
$endsWithLength = strlen($endsWithIndex);
if (strlen($uri) >= $endsWithLength &&
substr($uri, -$endsWithLength) === $endsWithIndex
) {
$uri = '/';
}
return $uri;
}
@ -258,6 +284,10 @@ class CakeRequest implements ArrayAccess {
/**
* Returns a base URL and sets the proper webroot
*
* If CakePHP is called with index.php in the URL even though
* URL Rewriting is activated (and thus not needed) it swallows
* the unnecessary part from $base to prevent issue #3318.
*
* @return string Base URL
*/
protected function _base() {
@ -275,7 +305,13 @@ class CakeRequest implements ArrayAccess {
if (!$baseUrl) {
$base = dirname(env('PHP_SELF'));
// Clean up additional / which cause following code to fail..
$base = preg_replace('#/+#', '/', $base);
$indexPos = strpos($base, '/webroot/index.php');
if ($indexPos !== false) {
$base = substr($base, 0, $indexPos) . '/webroot';
}
if ($webroot === 'webroot' && $webroot === basename($base)) {
$base = dirname($base);
}
@ -286,8 +322,9 @@ class CakeRequest implements ArrayAccess {
if ($base === DS || $base === '.') {
$base = '';
}
$base = implode('/', array_map('rawurlencode', explode('/', $base)));
$this->webroot = $base . '/';
return $this->base = $base;
}
@ -300,7 +337,7 @@ class CakeRequest implements ArrayAccess {
$this->webroot = $base . '/';
$docRoot = env('DOCUMENT_ROOT');
$docRootContainsWebroot = strpos($docRoot, $dir . '/' . $webroot);
$docRootContainsWebroot = strpos($docRoot, $dir . DS . $webroot);
if (!empty($base) || !$docRootContainsWebroot) {
if (strpos($this->webroot, '/' . $dir . '/') === false) {
@ -346,7 +383,7 @@ class CakeRequest implements ArrayAccess {
protected function _processFileData($path, $data, $field) {
foreach ($data as $key => $fields) {
$newPath = $key;
if (!empty($path)) {
if (strlen($path) > 0) {
$newPath = $path . '.' . $key;
}
if (is_array($fields)) {
@ -358,30 +395,33 @@ class CakeRequest implements ArrayAccess {
}
}
/**
* Get the content type used in this request.
*
* @return string
*/
public function contentType() {
$type = env('CONTENT_TYPE');
if ($type) {
return $type;
}
return env('HTTP_CONTENT_TYPE');
}
/**
* Get the IP the client is using, or says they are using.
*
* @param boolean $safe Use safe = false when you think the user might manipulate their HTTP_CLIENT_IP
* header. Setting $safe = false will will also look at HTTP_X_FORWARDED_FOR
* @param bool $safe Use safe = false when you think the user might manipulate their HTTP_CLIENT_IP
* header. Setting $safe = false will also look at HTTP_X_FORWARDED_FOR
* @return string The client IP.
*/
public function clientIp($safe = true) {
if (!$safe && env('HTTP_X_FORWARDED_FOR') != null) {
if (!$safe && env('HTTP_X_FORWARDED_FOR')) {
$ipaddr = preg_replace('/(?:,.*)/', '', env('HTTP_X_FORWARDED_FOR'));
} elseif (!$safe && env('HTTP_CLIENT_IP')) {
$ipaddr = env('HTTP_CLIENT_IP');
} else {
if (env('HTTP_CLIENT_IP') != null) {
$ipaddr = env('HTTP_CLIENT_IP');
} else {
$ipaddr = env('REMOTE_ADDR');
}
}
if (env('HTTP_CLIENTADDRESS') != null) {
$tmpipaddr = env('HTTP_CLIENTADDRESS');
if (!empty($tmpipaddr)) {
$ipaddr = preg_replace('/(?:,.*)/', '', $tmpipaddr);
}
$ipaddr = env('REMOTE_ADDR');
}
return trim($ipaddr);
}
@ -389,24 +429,20 @@ class CakeRequest implements ArrayAccess {
/**
* Returns the referer that referred this request.
*
* @param boolean $local Attempt to return a local address. Local addresses do not contain hostnames.
* @param bool $local Attempt to return a local address. Local addresses do not contain hostnames.
* @return string The referring address for this request.
*/
public function referer($local = false) {
$ref = env('HTTP_REFERER');
$forwarded = env('HTTP_X_FORWARDED_HOST');
if ($forwarded) {
$ref = $forwarded;
}
$base = '';
if (defined('FULL_BASE_URL')) {
$base = FULL_BASE_URL . $this->webroot;
}
$base = Configure::read('App.fullBaseUrl') . $this->webroot;
if (!empty($ref) && !empty($base)) {
if ($local && strpos($ref, $base) === 0) {
$ref = substr($ref, strlen($base));
if ($ref[0] != '/') {
if (empty($ref)) {
$ref = '/';
}
if ($ref[0] !== '/') {
$ref = '/' . $ref;
}
return $ref;
@ -460,19 +496,120 @@ class CakeRequest implements ArrayAccess {
}
/**
* Check whether or not a Request is a certain type. Uses the built in detection rules
* as well as additional rules defined with CakeRequest::addDetector(). Any detector can be called
* Check whether or not a Request is a certain type.
*
* Uses the built in detection rules as well as additional rules
* defined with CakeRequest::addDetector(). Any detector can be called
* as `is($type)` or `is$Type()`.
*
* @param string $type The type of request you want to check.
* @return boolean Whether or not the request is the type you are checking.
* @param string|array $type The type of request you want to check. If an array
* this method will return true if the request matches any type.
* @return bool Whether or not the request is the type you are checking.
*/
public function is($type) {
if (is_array($type)) {
$result = array_map(array($this, 'is'), $type);
return count(array_filter($result)) > 0;
}
$type = strtolower($type);
if (!isset($this->_detectors[$type])) {
return false;
}
$detect = $this->_detectors[$type];
if (isset($detect['env']) && $this->_environmentDetector($detect)) {
return true;
}
if (isset($detect['header']) && $this->_headerDetector($detect)) {
return true;
}
if (isset($detect['accept']) && $this->_acceptHeaderDetector($detect)) {
return true;
}
if (isset($detect['param']) && $this->_paramDetector($detect)) {
return true;
}
if (isset($detect['callback']) && is_callable($detect['callback'])) {
return call_user_func($detect['callback'], $this);
}
return false;
}
/**
* Detects if a URL extension is present.
*
* @param array $detect Detector options array.
* @return bool Whether or not the request is the type you are checking.
*/
protected function _extensionDetector($detect) {
if (is_string($detect['extension'])) {
$detect['extension'] = array($detect['extension']);
}
if (in_array($this->params['ext'], $detect['extension'])) {
return true;
}
return false;
}
/**
* Detects if a specific accept header is present.
*
* @param array $detect Detector options array.
* @return bool Whether or not the request is the type you are checking.
*/
protected function _acceptHeaderDetector($detect) {
$acceptHeaders = explode(',', (string)env('HTTP_ACCEPT'));
foreach ($detect['accept'] as $header) {
if (in_array($header, $acceptHeaders)) {
return true;
}
}
return false;
}
/**
* Detects if a specific header is present.
*
* @param array $detect Detector options array.
* @return bool Whether or not the request is the type you are checking.
*/
protected function _headerDetector($detect) {
foreach ($detect['header'] as $header => $value) {
$header = env('HTTP_' . strtoupper($header));
if (!is_null($header)) {
if (!is_string($value) && !is_bool($value) && is_callable($value)) {
return call_user_func($value, $header);
}
return ($header === $value);
}
}
return false;
}
/**
* Detects if a specific request parameter is present.
*
* @param array $detect Detector options array.
* @return bool Whether or not the request is the type you are checking.
*/
protected function _paramDetector($detect) {
$key = $detect['param'];
if (isset($detect['value'])) {
$value = $detect['value'];
return isset($this->params[$key]) ? $this->params[$key] == $value : false;
}
if (isset($detect['options'])) {
return isset($this->params[$key]) ? in_array($this->params[$key], $detect['options']) : false;
}
return false;
}
/**
* Detects if a specific environment variable is present.
*
* @param array $detect Detector options array.
* @return bool Whether or not the request is the type you are checking.
*/
protected function _environmentDetector($detect) {
if (isset($detect['env'])) {
if (isset($detect['value'])) {
return env($detect['env']) == $detect['value'];
@ -485,17 +622,25 @@ class CakeRequest implements ArrayAccess {
return (bool)preg_match($pattern, env($detect['env']));
}
}
if (isset($detect['param'])) {
$key = $detect['param'];
$value = $detect['value'];
return isset($this->params[$key]) ? $this->params[$key] == $value : false;
}
if (isset($detect['callback']) && is_callable($detect['callback'])) {
return call_user_func($detect['callback'], $this);
}
return false;
}
/**
* Check that a request matches all the given types.
*
* Allows you to test multiple types and union the results.
* See CakeRequest::is() for how to add additional types and the
* built-in types.
*
* @param array $types The types to check.
* @return bool Success.
* @see CakeRequest::is()
*/
public function isAll(array $types) {
$result = array_filter(array_map(array($this, 'is'), $types));
return count($result) === count($types);
}
/**
* Add a new detector to the list of detectors that a request can use.
* There are several different formats and types of detectors that can be set.
@ -515,14 +660,14 @@ class CakeRequest implements ArrayAccess {
*
* ### Option based comparison
*
* Option based comparisons use a list of options to create a regular expression. Subsequent calls
* Option based comparisons use a list of options to create a regular expression. Subsequent calls
* to add an already defined options detector will merge the options.
*
* e.g `addDetector('mobile', array('env' => 'HTTP_USER_AGENT', 'options' => array('Fennec')));`
*
* ### Callback detectors
*
* Callback detectors allow you to provide a 'callback' type to handle the check. The callback will
* Callback detectors allow you to provide a 'callback' type to handle the check. The callback will
* receive the request object as its only parameter.
*
* e.g `addDetector('custom', array('callback' => array('SomeClass', 'somemethod')));`
@ -531,10 +676,16 @@ class CakeRequest implements ArrayAccess {
*
* Allows for custom detectors on the request parameters.
*
* e.g `addDetector('post', array('param' => 'requested', 'value' => 1)`
* e.g `addDetector('requested', array('param' => 'requested', 'value' => 1)`
*
* You can also make parameter detectors that accept multiple values
* using the `options` key. This is useful when you want to check
* if a request parameter is in a list of options.
*
* `addDetector('extension', array('param' => 'ext', 'options' => array('pdf', 'csv'))`
*
* @param string $name The name of the detector.
* @param array $options The options for the detector definition. See above.
* @param array $options The options for the detector definition. See above.
* @return void
*/
public function addDetector($name, $options) {
@ -550,7 +701,7 @@ class CakeRequest implements ArrayAccess {
* This modifies the parameters available through `$request->params`.
*
* @param array $params Array of parameters to merge in
* @return The current object, you can chain this method.
* @return self
*/
public function addParams($params) {
$this->params = array_merge($this->params, (array)$params);
@ -558,11 +709,11 @@ class CakeRequest implements ArrayAccess {
}
/**
* Add paths to the requests' paths vars. This will overwrite any existing paths.
* Add paths to the requests' paths vars. This will overwrite any existing paths.
* Provides an easy way to modify, here, webroot and base.
*
* @param array $paths Array of paths to merge in
* @return CakeRequest the current object, you can chain this method.
* @return self
*/
public function addPaths($paths) {
foreach (array('webroot', 'here', 'base') as $element) {
@ -574,10 +725,10 @@ class CakeRequest implements ArrayAccess {
}
/**
* Get the value of the current requests url. Will include named parameters and querystring arguments.
* Get the value of the current requests URL. Will include named parameters and querystring arguments.
*
* @param boolean $base Include the base path, set to false to trim the base path off.
* @return string the current request url including query string args.
* @param bool $base Include the base path, set to false to trim the base path off.
* @return string the current request URL including query string args.
*/
public function here($base = true) {
$url = $this->here;
@ -597,8 +748,13 @@ class CakeRequest implements ArrayAccess {
* @return mixed Either false on no header being set or the value of the header.
*/
public static function header($name) {
$name = 'HTTP_' . strtoupper(str_replace('-', '_', $name));
if (!empty($_SERVER[$name])) {
$httpName = 'HTTP_' . strtoupper(str_replace('-', '_', $name));
if (isset($_SERVER[$httpName])) {
return $_SERVER[$httpName];
}
// Use the provided value, in some configurations apache will
// pass Authorization with no prefix and in Titlecase.
if (isset($_SERVER[$name])) {
return $_SERVER[$name];
}
return false;
@ -624,16 +780,20 @@ class CakeRequest implements ArrayAccess {
/**
* Get the host that the request was handled on.
*
* @param bool $trustProxy Whether or not to trust the proxy host.
* @return string
*/
public function host() {
public function host($trustProxy = false) {
if ($trustProxy) {
return env('HTTP_X_FORWARDED_HOST');
}
return env('HTTP_HOST');
}
/**
* Get the domain name and include $tldLength segments of the tld.
*
* @param integer $tldLength Number of segments your tld contains. For example: `example.com` contains 1 tld.
* @param int $tldLength Number of segments your tld contains. For example: `example.com` contains 1 tld.
* While `example.co.uk` contains 2.
* @return string Domain name without subdomains.
*/
@ -646,9 +806,9 @@ class CakeRequest implements ArrayAccess {
/**
* Get the subdomains for a host.
*
* @param integer $tldLength Number of segments your tld contains. For example: `example.com` contains 1 tld.
* @param int $tldLength Number of segments your tld contains. For example: `example.com` contains 1 tld.
* While `example.co.uk` contains 2.
* @return array of subdomains.
* @return array An array of subdomains.
*/
public function subdomains($tldLength = 1) {
$segments = explode('.', $this->host());
@ -670,7 +830,7 @@ class CakeRequest implements ArrayAccess {
* This method will order the returned content types by the preference values indicated
* by the client.
*
* @param string $type The content type to check for. Leave null to get all types a client accepts.
* @param string $type The content type to check for. Leave null to get all types a client accepts.
* @return mixed Either an array of all the types the client accepts or a boolean if they accept the
* provided type.
*/
@ -696,17 +856,69 @@ class CakeRequest implements ArrayAccess {
* @return array An array of prefValue => array(content/types)
*/
public function parseAccept() {
return $this->_parseAcceptWithQualifier($this->header('accept'));
}
/**
* Get the languages accepted by the client, or check if a specific language is accepted.
*
* Get the list of accepted languages:
*
* ``` CakeRequest::acceptLanguage(); ```
*
* Check if a specific language is accepted:
*
* ``` CakeRequest::acceptLanguage('es-es'); ```
*
* @param string $language The language to test.
* @return mixed If a $language is provided, a boolean. Otherwise the array of accepted languages.
*/
public static function acceptLanguage($language = null) {
$raw = static::_parseAcceptWithQualifier(static::header('Accept-Language'));
$accept = array();
$header = explode(',', $this->header('accept'));
foreach (array_filter($header) as $value) {
$prefPos = strpos($value, ';');
if ($prefPos !== false) {
$prefValue = substr($value, strpos($value, '=') + 1);
$value = trim(substr($value, 0, $prefPos));
} else {
$prefValue = '1.0';
$value = trim($value);
foreach ($raw as $languages) {
foreach ($languages as &$lang) {
if (strpos($lang, '_')) {
$lang = str_replace('_', '-', $lang);
}
$lang = strtolower($lang);
}
$accept = array_merge($accept, $languages);
}
if ($language === null) {
return $accept;
}
return in_array(strtolower($language), $accept);
}
/**
* Parse Accept* headers with qualifier options.
*
* Only qualifiers will be extracted, any other accept extensions will be
* discarded as they are not frequently used.
*
* @param string $header Header to parse.
* @return array
*/
protected static function _parseAcceptWithQualifier($header) {
$accept = array();
$header = explode(',', $header);
foreach (array_filter($header) as $value) {
$prefValue = '1.0';
$value = trim($value);
$semiPos = strpos($value, ';');
if ($semiPos !== false) {
$params = explode(';', $value);
$value = trim($params[0]);
foreach ($params as $param) {
$qPos = strpos($param, 'q=');
if ($qPos !== false) {
$prefValue = substr($param, $qPos + 2);
}
}
}
if (!isset($accept[$prefValue])) {
$accept[$prefValue] = array();
}
@ -719,35 +931,18 @@ class CakeRequest implements ArrayAccess {
}
/**
* Get the languages accepted by the client, or check if a specific language is accepted.
* Provides a read accessor for `$this->query`. Allows you
* to use a syntax similar to `CakeSession` for reading URL query data.
*
* Get the list of accepted languages:
*
* {{{ CakeRequest::acceptLanguage(); }}}
*
* Check if a specific language is accepted:
*
* {{{ CakeRequest::acceptLanguage('es-es'); }}}
*
* @param string $language The language to test.
* @return If a $language is provided, a boolean. Otherwise the array of accepted languages.
* @param string $name Query string variable name
* @return mixed The value being read
*/
public static function acceptLanguage($language = null) {
$accepts = preg_split('/[;,]/', self::header('Accept-Language'));
foreach ($accepts as &$accept) {
$accept = strtolower($accept);
if (strpos($accept, '_') !== false) {
$accept = str_replace('_', '-', $accept);
}
}
if ($language === null) {
return $accepts;
}
return in_array($language, $accepts);
public function query($name) {
return Hash::get($this->query, $name);
}
/**
* Provides a read/write accessor for `$this->data`. Allows you
* Provides a read/write accessor for `$this->data`. Allows you
* to use a syntax similar to `CakeSession` for reading post data.
*
* ## Reading values.
@ -763,18 +958,37 @@ class CakeRequest implements ArrayAccess {
* You can write to any value, even paths/keys that do not exist, and the arrays
* will be created for you.
*
* @param string $name,... Dot separated name of the value to read/write
* @return mixed Either the value being read, or this so you can chain consecutive writes.
* @param string $name Dot separated name of the value to read/write, one or more args.
* @return mixed|self Either the value being read, or $this so you can chain consecutive writes.
*/
public function data($name) {
$args = func_get_args();
if (count($args) == 2) {
if (count($args) === 2) {
$this->data = Hash::insert($this->data, $name, $args[1]);
return $this;
}
return Hash::get($this->data, $name);
}
/**
* Safely access the values in $this->params.
*
* @param string $name The name of the parameter to get.
* @return mixed The value of the provided parameter. Will
* return false if the parameter doesn't exist or is falsey.
*/
public function param($name) {
$args = func_get_args();
if (count($args) === 2) {
$this->params = Hash::insert($this->params, $name, $args[1]);
return $this;
}
if (!isset($this->params[$name])) {
return Hash::get($this->params, $name, false);
}
return $this->params[$name];
}
/**
* Read data from `php://input`. Useful when interacting with XML or JSON
* request body content.
@ -805,6 +1019,65 @@ class CakeRequest implements ArrayAccess {
return $input;
}
/**
* Modify data originally from `php://input`. Useful for altering json/xml data
* in middleware or DispatcherFilters before it gets to RequestHandlerComponent
*
* @param string $input A string to replace original parsed data from input()
* @return void
*/
public function setInput($input) {
$this->_input = $input;
}
/**
* Allow only certain HTTP request methods. If the request method does not match
* a 405 error will be shown and the required "Allow" response header will be set.
*
* Example:
*
* $this->request->allowMethod('post', 'delete');
* or
* $this->request->allowMethod(array('post', 'delete'));
*
* If the request would be GET, response header "Allow: POST, DELETE" will be set
* and a 405 error will be returned.
*
* @param string|array $methods Allowed HTTP request methods.
* @return bool true
* @throws MethodNotAllowedException
*/
public function allowMethod($methods) {
if (!is_array($methods)) {
$methods = func_get_args();
}
foreach ($methods as $method) {
if ($this->is($method)) {
return true;
}
}
$allowed = strtoupper(implode(', ', $methods));
$e = new MethodNotAllowedException();
$e->responseHeader('Allow', $allowed);
throw $e;
}
/**
* Alias of CakeRequest::allowMethod() for backwards compatibility.
*
* @param string|array $methods Allowed HTTP request methods.
* @return bool true
* @throws MethodNotAllowedException
* @see CakeRequest::allowMethod()
* @deprecated 3.0.0 Since 2.5, use CakeRequest::allowMethod() instead.
*/
public function onlyAllow($methods) {
if (!is_array($methods)) {
$methods = func_get_args();
}
return $this->allowMethod($methods);
}
/**
* Read data from php://input, mocked in tests.
*
@ -830,10 +1103,10 @@ class CakeRequest implements ArrayAccess {
if (isset($this->params[$name])) {
return $this->params[$name];
}
if ($name == 'url') {
if ($name === 'url') {
return $this->query;
}
if ($name == 'data') {
if ($name === 'data') {
return $this->data;
}
return null;
@ -854,9 +1127,12 @@ class CakeRequest implements ArrayAccess {
* Array access isset() implementation
*
* @param string $name thing to check.
* @return boolean
* @return bool
*/
public function offsetExists($name) {
if ($name === 'url' || $name === 'data') {
return true;
}
return isset($this->params[$name]);
}