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]);
}

File diff suppressed because it is too large Load diff

View file

@ -1,26 +1,25 @@
<?php
/**
* Cake Socket connection class.
*
* PHP 5
* CakePHP Socket connection class.
*
* 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
* @package Cake.Network
* @since CakePHP(tm) v 1.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('Validation', 'Utility');
/**
* Cake network socket connection class.
* CakePHP network socket connection class.
*
* Core base class for network communication.
*
@ -29,7 +28,7 @@ App::uses('Validation', 'Utility');
class CakeSocket {
/**
* Object description
* CakeSocket description
*
* @var string
*/
@ -41,11 +40,11 @@ class CakeSocket {
* @var array
*/
protected $_baseConfig = array(
'persistent' => false,
'host' => 'localhost',
'protocol' => 'tcp',
'port' => 80,
'timeout' => 30
'persistent' => false,
'host' => 'localhost',
'protocol' => 'tcp',
'port' => 80,
'timeout' => 30
);
/**
@ -65,7 +64,7 @@ class CakeSocket {
/**
* This boolean contains the current state of the CakeSocket class
*
* @var boolean
* @var bool
*/
public $connected = false;
@ -76,6 +75,39 @@ class CakeSocket {
*/
public $lastError = array();
/**
* True if the socket stream is encrypted after a CakeSocket::enableCrypto() call
*
* @var bool
*/
public $encrypted = false;
/**
* Contains all the encryption methods available
*
* @var array
*/
protected $_encryptMethods = array(
// @codingStandardsIgnoreStart
'sslv2_client' => STREAM_CRYPTO_METHOD_SSLv2_CLIENT,
'sslv3_client' => STREAM_CRYPTO_METHOD_SSLv3_CLIENT,
'sslv23_client' => STREAM_CRYPTO_METHOD_SSLv23_CLIENT,
'tls_client' => STREAM_CRYPTO_METHOD_TLS_CLIENT,
'sslv2_server' => STREAM_CRYPTO_METHOD_SSLv2_SERVER,
'sslv3_server' => STREAM_CRYPTO_METHOD_SSLv3_SERVER,
'sslv23_server' => STREAM_CRYPTO_METHOD_SSLv23_SERVER,
'tls_server' => STREAM_CRYPTO_METHOD_TLS_SERVER
// @codingStandardsIgnoreEnd
);
/**
* Used to capture connection warnings which can happen when there are
* SSL errors for example.
*
* @var array
*/
protected $_connectionErrors = array();
/**
* Constructor.
*
@ -84,49 +116,169 @@ class CakeSocket {
*/
public function __construct($config = array()) {
$this->config = array_merge($this->_baseConfig, $config);
if (!is_numeric($this->config['protocol'])) {
$this->config['protocol'] = getprotobyname($this->config['protocol']);
}
}
/**
* Connect the socket to the given host and port.
* Connects the socket to the given host and port.
*
* @return boolean Success
* @return bool Success
* @throws SocketException
*/
public function connect() {
if ($this->connection != null) {
if ($this->connection) {
$this->disconnect();
}
$hasProtocol = strpos($this->config['host'], '://') !== false;
if ($hasProtocol) {
list($this->config['protocol'], $this->config['host']) = explode('://', $this->config['host']);
}
$scheme = null;
if (isset($this->config['request']) && $this->config['request']['uri']['scheme'] == 'https') {
$scheme = 'ssl://';
if (!empty($this->config['protocol'])) {
$scheme = $this->config['protocol'] . '://';
}
if (!empty($this->config['proxy'])) {
$scheme = 'tcp://';
}
//@codingStandardsIgnoreStart
if ($this->config['persistent'] == true) {
$this->connection = @pfsockopen($scheme . $this->config['host'], $this->config['port'], $errNum, $errStr, $this->config['timeout']);
} else {
$this->connection = @fsockopen($scheme . $this->config['host'], $this->config['port'], $errNum, $errStr, $this->config['timeout']);
$host = $this->config['host'];
if (isset($this->config['request']['uri']['host'])) {
$host = $this->config['request']['uri']['host'];
}
//@codingStandardsIgnoreEnd
$this->_setSslContext($host);
if (!empty($this->config['context'])) {
$context = stream_context_create($this->config['context']);
} else {
$context = stream_context_create();
}
$connectAs = STREAM_CLIENT_CONNECT;
if ($this->config['persistent']) {
$connectAs |= STREAM_CLIENT_PERSISTENT;
}
set_error_handler(array($this, '_connectionErrorHandler'));
$this->connection = stream_socket_client(
$scheme . $this->config['host'] . ':' . $this->config['port'],
$errNum,
$errStr,
$this->config['timeout'],
$connectAs,
$context
);
restore_error_handler();
if (!empty($errNum) || !empty($errStr)) {
$this->setLastError($errNum, $errStr);
throw new SocketException($errStr, $errNum);
}
if (!$this->connection && $this->_connectionErrors) {
$message = implode("\n", $this->_connectionErrors);
throw new SocketException($message, E_WARNING);
}
$this->connected = is_resource($this->connection);
if ($this->connected) {
stream_set_timeout($this->connection, $this->config['timeout']);
if (!empty($this->config['request']) &&
$this->config['request']['uri']['scheme'] === 'https' &&
!empty($this->config['proxy'])
) {
$req = array();
$req[] = 'CONNECT ' . $this->config['request']['uri']['host'] . ':' .
$this->config['request']['uri']['port'] . ' HTTP/1.1';
$req[] = 'Host: ' . $this->config['host'];
$req[] = 'User-Agent: php proxy';
if (!empty($this->config['proxyauth'])) {
$req[] = 'Proxy-Authorization: ' . $this->config['proxyauth'];
}
fwrite($this->connection, implode("\r\n", $req) . "\r\n\r\n");
while (!feof($this->connection)) {
$s = rtrim(fgets($this->connection, 4096));
if (preg_match('/^$/', $s)) {
break;
}
}
$this->enableCrypto('tls', 'client');
}
}
return $this->connected;
}
/**
* Get the host name of the current connection.
* Configure the SSL context options.
*
* @param string $host The host name being connected to.
* @return void
*/
protected function _setSslContext($host) {
foreach ($this->config as $key => $value) {
if (substr($key, 0, 4) !== 'ssl_') {
continue;
}
$contextKey = substr($key, 4);
if (empty($this->config['context']['ssl'][$contextKey])) {
$this->config['context']['ssl'][$contextKey] = $value;
}
unset($this->config[$key]);
}
if (version_compare(PHP_VERSION, '5.3.2', '>=')) {
if (!isset($this->config['context']['ssl']['SNI_enabled'])) {
$this->config['context']['ssl']['SNI_enabled'] = true;
}
if (version_compare(PHP_VERSION, '5.6.0', '>=')) {
if (empty($this->config['context']['ssl']['peer_name'])) {
$this->config['context']['ssl']['peer_name'] = $host;
}
} else {
if (empty($this->config['context']['ssl']['SNI_server_name'])) {
$this->config['context']['ssl']['SNI_server_name'] = $host;
}
}
}
if (empty($this->config['context']['ssl']['cafile'])) {
$this->config['context']['ssl']['cafile'] = CAKE . 'Config' . DS . 'cacert.pem';
}
if (!empty($this->config['context']['ssl']['verify_host'])) {
$this->config['context']['ssl']['CN_match'] = $host;
}
unset($this->config['context']['ssl']['verify_host']);
}
/**
* socket_stream_client() does not populate errNum, or $errStr when there are
* connection errors, as in the case of SSL verification failure.
*
* Instead we need to handle those errors manually.
*
* @param int $code Code.
* @param string $message Message.
* @return void
*/
protected function _connectionErrorHandler($code, $message) {
$this->_connectionErrors[] = $message;
}
/**
* Gets the connection context.
*
* @return null|array Null when there is no connection, an array when there is.
*/
public function context() {
if (!$this->connection) {
return null;
}
return stream_context_get_options($this->connection);
}
/**
* Gets the host name of the current connection.
*
* @return string Host name
*/
@ -138,7 +290,7 @@ class CakeSocket {
}
/**
* Get the IP address of the current connection.
* Gets the IP address of the current connection.
*
* @return string IP address
*/
@ -150,7 +302,7 @@ class CakeSocket {
}
/**
* Get all IP addresses associated with the current connection.
* Gets all IP addresses associated with the current connection.
*
* @return array IP addresses
*/
@ -162,9 +314,9 @@ class CakeSocket {
}
/**
* Get the last error as a string.
* Gets the last error as a string.
*
* @return string Last error
* @return string|null Last error
*/
public function lastError() {
if (!empty($this->lastError)) {
@ -174,9 +326,9 @@ class CakeSocket {
}
/**
* Set the last error.
* Sets the last error.
*
* @param integer $errNum Error code
* @param int $errNum Error code
* @param string $errStr Error string
* @return void
*/
@ -185,10 +337,10 @@ class CakeSocket {
}
/**
* Write data to the socket.
* Writes data to the socket.
*
* @param string $data The data to write to the socket
* @return boolean Success
* @return bool Success
*/
public function write($data) {
if (!$this->connected) {
@ -207,10 +359,10 @@ class CakeSocket {
}
/**
* Read data from the socket. Returns false if no data is available or no connection could be
* Reads data from the socket. Returns false if no data is available or no connection could be
* established.
*
* @param integer $length Optional buffer length to read; defaults to 1024
* @param int $length Optional buffer length to read; defaults to 1024
* @return mixed Socket data
*/
public function read($length = 1024) {
@ -233,9 +385,9 @@ class CakeSocket {
}
/**
* Disconnect the socket from the current connection.
* Disconnects the socket from the current connection.
*
* @return boolean Success
* @return bool Success
*/
public function disconnect() {
if (!is_resource($this->connection)) {
@ -252,17 +404,16 @@ class CakeSocket {
/**
* Destructor, used to disconnect from current connection.
*
*/
public function __destruct() {
$this->disconnect();
}
/**
* Resets the state of this Socket instance to it's initial state (before Object::__construct got executed)
* Resets the state of this Socket instance to it's initial state (before CakeObject::__construct got executed)
*
* @param array $state Array with key and values to reset
* @return boolean True on success
* @return bool True on success
*/
public function reset($state = null) {
if (empty($state)) {
@ -279,4 +430,35 @@ class CakeSocket {
return true;
}
/**
* Encrypts current stream socket, using one of the defined encryption methods.
*
* @param string $type Type which can be one of 'sslv2', 'sslv3', 'sslv23' or 'tls'.
* @param string $clientOrServer Can be one of 'client', 'server'. Default is 'client'.
* @param bool $enable Enable or disable encryption. Default is true (enable)
* @return bool True on success
* @throws InvalidArgumentException When an invalid encryption scheme is chosen.
* @throws SocketException When attempting to enable SSL/TLS fails.
* @see stream_socket_enable_crypto
*/
public function enableCrypto($type, $clientOrServer = 'client', $enable = true) {
if (!array_key_exists($type . '_' . $clientOrServer, $this->_encryptMethods)) {
throw new InvalidArgumentException(__d('cake_dev', 'Invalid encryption scheme chosen'));
}
$enableCryptoResult = false;
try {
$enableCryptoResult = stream_socket_enable_crypto($this->connection, $enable,
$this->_encryptMethods[$type . '_' . $clientOrServer]);
} catch (Exception $e) {
$this->setLastError(null, $e->getMessage());
throw new SocketException($e->getMessage());
}
if ($enableCryptoResult === true) {
$this->encrypted = $enable;
return true;
}
$errorMessage = __d('cake_dev', 'Unable to perform enableCrypto operation on CakeSocket');
$this->setLastError(null, $errorMessage);
throw new SocketException($errorMessage);
}
}

View file

@ -2,19 +2,18 @@
/**
* Abstract send email
*
* 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
* @package Cake.Network.Email
* @since CakePHP(tm) v 2.0.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
/**
@ -34,7 +33,7 @@ abstract class AbstractTransport {
/**
* Send mail
*
* @params CakeEmail $email
* @param CakeEmail $email CakeEmail instance.
* @return array
*/
abstract public function send(CakeEmail $email);
@ -42,12 +41,12 @@ abstract class AbstractTransport {
/**
* Set the config
*
* @param array $config
* @param array $config Configuration options.
* @return array Returns configs
*/
public function config($config = null) {
if (is_array($config)) {
$this->_config = $config;
$this->_config = $config + $this->_config;
}
return $this->_config;
}
@ -56,7 +55,7 @@ abstract class AbstractTransport {
* Help to convert headers in string
*
* @param array $headers Headers in format key => value
* @param string $eol
* @param string $eol End of line string.
* @return string
*/
protected function _headersToString($headers, $eol = "\r\n") {

File diff suppressed because it is too large Load diff

View file

@ -2,20 +2,20 @@
/**
* Emulates the email sending process for testing purposes
*
* 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
* @package Cake.Network.Email
* @since CakePHP(tm) v 2.0.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('AbstractTransport', 'Network/Email');
/**
* Debug Transport class, useful for emulate the email sending process and inspect the resulted

View file

@ -2,20 +2,20 @@
/**
* Send mail using mail() function
*
* 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
* @package Cake.Network.Email
* @since CakePHP(tm) v 2.0.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('AbstractTransport', 'Network/Email');
/**
* Send mail using mail() function
@ -39,11 +39,20 @@ class MailTransport extends AbstractTransport {
$headers = $email->getHeaders(array('from', 'sender', 'replyTo', 'readReceipt', 'returnPath', 'to', 'cc', 'bcc'));
$to = $headers['To'];
unset($headers['To']);
foreach ($headers as $key => $header) {
$headers[$key] = str_replace(array("\r", "\n"), '', $header);
}
$headers = $this->_headersToString($headers, $eol);
$subject = str_replace(array("\r", "\n"), '', $email->subject());
$to = str_replace(array("\r", "\n"), '', $to);
$message = implode($eol, $email->message());
$params = isset($this->_config['additionalParameters']) ? $this->_config['additionalParameters'] : null;
$this->_mail($to, $email->subject(), $message, $headers, $params);
$this->_mail($to, $subject, $message, $headers, $params);
$headers .= $eol . 'Subject: ' . $subject;
$headers .= $eol . 'To: ' . $to;
return array('headers' => $headers, 'message' => $message);
}
@ -62,11 +71,15 @@ class MailTransport extends AbstractTransport {
if (ini_get('safe_mode')) {
//@codingStandardsIgnoreStart
if (!@mail($to, $subject, $message, $headers)) {
throw new SocketException(__d('cake_dev', 'Could not send email.'));
$error = error_get_last();
$msg = 'Could not send email: ' . (isset($error['message']) ? $error['message'] : 'unknown');
throw new SocketException($msg);
}
} elseif (!@mail($to, $subject, $message, $headers, $params)) {
$error = error_get_last();
$msg = 'Could not send email: ' . (isset($error['message']) ? $error['message'] : 'unknown');
//@codingStandardsIgnoreEnd
throw new SocketException(__d('cake_dev', 'Could not send email.'));
throw new SocketException($msg);
}
}

View file

@ -2,21 +2,20 @@
/**
* Send mail using SMTP protocol
*
* 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
* @package Cake.Network.Email
* @since CakePHP(tm) v 2.0.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('AbstractTransport', 'Network/Email');
App::uses('CakeSocket', 'Network');
/**
@ -33,13 +32,6 @@ class SmtpTransport extends AbstractTransport {
*/
protected $_socket;
/**
* CakeEmail
*
* @var CakeEmail
*/
protected $_cakeEmail;
/**
* Content of email to return
*
@ -47,6 +39,42 @@ class SmtpTransport extends AbstractTransport {
*/
protected $_content;
/**
* The response of the last sent SMTP command.
*
* @var array
*/
protected $_lastResponse = array();
/**
* Returns the response of the last sent SMTP command.
*
* A response consists of one or more lines containing a response
* code and an optional response message text:
* ```
* array(
* array(
* 'code' => '250',
* 'message' => 'mail.example.com'
* ),
* array(
* 'code' => '250',
* 'message' => 'PIPELINING'
* ),
* array(
* 'code' => '250',
* 'message' => '8BITMIME'
* ),
* // etc...
* )
* ```
*
* @return array
*/
public function getLastResponse() {
return $this->_lastResponse;
}
/**
* Send mail
*
@ -55,12 +83,10 @@ class SmtpTransport extends AbstractTransport {
* @throws SocketException
*/
public function send(CakeEmail $email) {
$this->_cakeEmail = $email;
$this->_connect();
$this->_auth();
$this->_sendRcpt();
$this->_sendData();
$this->_sendRcpt($email);
$this->_sendData($email);
$this->_disconnect();
return $this->_content;
@ -69,19 +95,44 @@ class SmtpTransport extends AbstractTransport {
/**
* Set the configuration
*
* @param array $config
* @return void
* @param array $config Configuration options.
* @return array Returns configs
*/
public function config($config = array()) {
public function config($config = null) {
if ($config === null) {
return $this->_config;
}
$default = array(
'host' => 'localhost',
'port' => 25,
'timeout' => 30,
'username' => null,
'password' => null,
'client' => null
'client' => null,
'tls' => false,
'ssl_allow_self_signed' => false
);
$this->_config = $config + $default;
$this->_config = array_merge($default, $this->_config, $config);
return $this->_config;
}
/**
* Parses and stores the reponse lines in `'code' => 'message'` format.
*
* @param array $responseLines Response lines to parse.
* @return void
*/
protected function _bufferResponseLines(array $responseLines) {
$response = array();
foreach ($responseLines as $responseLine) {
if (preg_match('/^(\d{3})(?:[ -]+(.*))?$/', $responseLine, $match)) {
$response[] = array(
'code' => $match[1],
'message' => isset($match[2]) ? $match[2] : null
);
}
}
$this->_lastResponse = array_merge($this->_lastResponse, $response);
}
/**
@ -107,7 +158,15 @@ class SmtpTransport extends AbstractTransport {
try {
$this->_smtpSend("EHLO {$host}", '250');
if ($this->_config['tls']) {
$this->_smtpSend("STARTTLS", '220');
$this->_socket->enableCrypto('tls');
$this->_smtpSend("EHLO {$host}", '250');
}
} catch (SocketException $e) {
if ($this->_config['tls']) {
throw new SocketException(__d('cake_dev', 'SMTP server did not accept the connection or trying to connect to non TLS SMTP server using TLS.'));
}
try {
$this->_smtpSend("HELO {$host}", '250');
} catch (SocketException $e2) {
@ -124,51 +183,91 @@ class SmtpTransport extends AbstractTransport {
*/
protected function _auth() {
if (isset($this->_config['username']) && isset($this->_config['password'])) {
$authRequired = $this->_smtpSend('AUTH LOGIN', '334|503');
if ($authRequired == '334') {
if (!$this->_smtpSend(base64_encode($this->_config['username']), '334')) {
$replyCode = $this->_smtpSend('AUTH LOGIN', '334|500|502|504');
if ($replyCode == '334') {
try {
$this->_smtpSend(base64_encode($this->_config['username']), '334');
} catch (SocketException $e) {
throw new SocketException(__d('cake_dev', 'SMTP server did not accept the username.'));
}
if (!$this->_smtpSend(base64_encode($this->_config['password']), '235')) {
try {
$this->_smtpSend(base64_encode($this->_config['password']), '235');
} catch (SocketException $e) {
throw new SocketException(__d('cake_dev', 'SMTP server did not accept the password.'));
}
} elseif ($authRequired != '503') {
throw new SocketException(__d('cake_dev', 'SMTP does not require authentication.'));
} elseif ($replyCode == '504') {
throw new SocketException(__d('cake_dev', 'SMTP authentication method not allowed, check if SMTP server requires TLS.'));
} else {
throw new SocketException(__d('cake_dev', 'AUTH command not recognized or not implemented, SMTP server may not require authentication.'));
}
}
}
/**
* Send emails
* Prepares the `MAIL FROM` SMTP command.
*
* @return void
* @throws SocketException
* @param string $email The email address to send with the command.
* @return string
*/
protected function _sendRcpt() {
$from = $this->_cakeEmail->from();
$this->_smtpSend('MAIL FROM:<' . key($from) . '>');
$to = $this->_cakeEmail->to();
$cc = $this->_cakeEmail->cc();
$bcc = $this->_cakeEmail->bcc();
$emails = array_merge(array_keys($to), array_keys($cc), array_keys($bcc));
foreach ($emails as $email) {
$this->_smtpSend('RCPT TO:<' . $email . '>');
}
protected function _prepareFromCmd($email) {
return 'MAIL FROM:<' . $email . '>';
}
/**
* Send Data
* Prepares the `RCPT TO` SMTP command.
*
* @return void
* @throws SocketException
* @param string $email The email address to send with the command.
* @return string
*/
protected function _sendData() {
$this->_smtpSend('DATA', '354');
protected function _prepareRcptCmd($email) {
return 'RCPT TO:<' . $email . '>';
}
$headers = $this->_cakeEmail->getHeaders(array('from', 'sender', 'replyTo', 'readReceipt', 'returnPath', 'to', 'cc', 'subject'));
$headers = $this->_headersToString($headers);
$lines = $this->_cakeEmail->message();
/**
* Prepares the `from` email address.
*
* @param CakeEmail $email CakeEmail
* @return array
*/
protected function _prepareFromAddress(CakeEmail $email) {
$from = $email->returnPath();
if (empty($from)) {
$from = $email->from();
}
return $from;
}
/**
* Prepares the recipient email addresses.
*
* @param CakeEmail $email CakeEmail
* @return array
*/
protected function _prepareRecipientAddresses(CakeEmail $email) {
$to = $email->to();
$cc = $email->cc();
$bcc = $email->bcc();
return array_merge(array_keys($to), array_keys($cc), array_keys($bcc));
}
/**
* Prepares the message headers.
*
* @param CakeEmail $email CakeEmail
* @return array
*/
protected function _prepareMessageHeaders(CakeEmail $email) {
return $email->getHeaders(array('from', 'sender', 'replyTo', 'readReceipt', 'to', 'cc', 'subject'));
}
/**
* Prepares the message body.
*
* @param CakeEmail $email CakeEmail
* @return string
*/
protected function _prepareMessage(CakeEmail $email) {
$lines = $email->message();
$messages = array();
foreach ($lines as $line) {
if ((!empty($line)) && ($line[0] === '.')) {
@ -177,7 +276,39 @@ class SmtpTransport extends AbstractTransport {
$messages[] = $line;
}
}
$message = implode("\r\n", $messages);
return implode("\r\n", $messages);
}
/**
* Send emails
*
* @param CakeEmail $email CakeEmail
* @return void
* @throws SocketException
*/
protected function _sendRcpt(CakeEmail $email) {
$from = $this->_prepareFromAddress($email);
$this->_smtpSend($this->_prepareFromCmd(key($from)));
$emails = $this->_prepareRecipientAddresses($email);
foreach ($emails as $email) {
$this->_smtpSend($this->_prepareRcptCmd($email));
}
}
/**
* Send Data
*
* @param CakeEmail $email CakeEmail
* @return void
* @throws SocketException
*/
protected function _sendData(CakeEmail $email) {
$this->_smtpSend('DATA', '354');
$headers = $this->_headersToString($this->_prepareMessageHeaders($email));
$message = $this->_prepareMessage($email);
$this->_smtpSend($headers . "\r\n\r\n" . $message . "\r\n\r\n\r\n.");
$this->_content = array('headers' => $headers, 'message' => $message);
}
@ -206,13 +337,15 @@ class SmtpTransport extends AbstractTransport {
/**
* Protected method for sending data to SMTP connection
*
* @param string $data data to be sent to SMTP server
* @param string|boolean $checkCode code to check for in server response, false to skip
* @return void
* @param string|null $data Data to be sent to SMTP server
* @param string|bool $checkCode Code to check for in server response, false to skip
* @return string|null The matched code, or null if nothing matched
* @throws SocketException
*/
protected function _smtpSend($data, $checkCode = '250') {
if (!is_null($data)) {
$this->_lastResponse = array();
if ($data !== null) {
$this->_socket->write($data . "\r\n");
}
while ($checkCode !== false) {
@ -227,6 +360,8 @@ class SmtpTransport extends AbstractTransport {
$responseLines = explode("\r\n", rtrim($response, "\r\n"));
$response = end($responseLines);
$this->_bufferResponseLines($responseLines);
if (preg_match('/^(' . $checkCode . ')(.)/', $response, $code)) {
if ($code[2] === '-') {
continue;

View file

@ -2,19 +2,18 @@
/**
* Basic authentication
*
* 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
* @package Cake.Network.Http
* @since CakePHP(tm) v 2.0.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
/**
@ -27,36 +26,36 @@ class BasicAuthentication {
/**
* Authentication
*
* @param HttpSocket $http
* @param array $authInfo
* @param HttpSocket $http Http socket instance.
* @param array &$authInfo Authentication info.
* @return void
* @see http://www.ietf.org/rfc/rfc2617.txt
*/
public static function authentication(HttpSocket $http, &$authInfo) {
if (isset($authInfo['user'], $authInfo['pass'])) {
$http->request['header']['Authorization'] = self::_generateHeader($authInfo['user'], $authInfo['pass']);
$http->request['header']['Authorization'] = static::_generateHeader($authInfo['user'], $authInfo['pass']);
}
}
/**
* Proxy Authentication
*
* @param HttpSocket $http
* @param array $proxyInfo
* @param HttpSocket $http Http socket instance.
* @param array &$proxyInfo Proxy info.
* @return void
* @see http://www.ietf.org/rfc/rfc2617.txt
*/
public static function proxyAuthentication(HttpSocket $http, &$proxyInfo) {
if (isset($proxyInfo['user'], $proxyInfo['pass'])) {
$http->request['header']['Proxy-Authorization'] = self::_generateHeader($proxyInfo['user'], $proxyInfo['pass']);
$http->request['header']['Proxy-Authorization'] = static::_generateHeader($proxyInfo['user'], $proxyInfo['pass']);
}
}
/**
* Generate basic [proxy] authentication header
*
* @param string $user
* @param string $pass
* @param string $user Username.
* @param string $pass Password.
* @return string
*/
protected static function _generateHeader($user, $pass) {

View file

@ -2,19 +2,18 @@
/**
* Digest authentication
*
* 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
* @package Cake.Network.Http
* @since CakePHP(tm) v 2.0.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
/**
@ -27,26 +26,26 @@ class DigestAuthentication {
/**
* Authentication
*
* @param HttpSocket $http
* @param array $authInfo
* @param HttpSocket $http Http socket instance.
* @param array &$authInfo Authentication info.
* @return void
* @link http://www.ietf.org/rfc/rfc2617.txt
*/
public static function authentication(HttpSocket $http, &$authInfo) {
if (isset($authInfo['user'], $authInfo['pass'])) {
if (!isset($authInfo['realm']) && !self::_getServerInformation($http, $authInfo)) {
if (!isset($authInfo['realm']) && !static::_getServerInformation($http, $authInfo)) {
return;
}
$http->request['header']['Authorization'] = self::_generateHeader($http, $authInfo);
$http->request['header']['Authorization'] = static::_generateHeader($http, $authInfo);
}
}
/**
* Retrieve information about the authentication
*
* @param HttpSocket $http
* @param array $authInfo
* @return boolean
* @param HttpSocket $http Http socket instance.
* @param array &$authInfo Authentication info.
* @return bool
*/
protected static function _getServerInformation(HttpSocket $http, &$authInfo) {
$originalRequest = $http->request;
@ -71,8 +70,8 @@ class DigestAuthentication {
/**
* Generate the header Authorization
*
* @param HttpSocket $http
* @param array $authInfo
* @param HttpSocket $http Http socket instance.
* @param array &$authInfo Authentication info.
* @return string
*/
protected static function _generateHeader(HttpSocket $http, &$authInfo) {

View file

@ -2,437 +2,34 @@
/**
* HTTP Response from HttpSocket.
*
* 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
* @package Cake.Network.Http
* @since CakePHP(tm) v 2.0.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('HttpSocketResponse', 'Network/Http');
if (class_exists('HttpResponse')) {
trigger_error(__d(
'cake_dev',
"HttpResponse is deprecated due to naming conflicts. Use HttpSocketResponse instead."
), E_USER_ERROR);
}
/**
* HTTP Response from HttpSocket.
*
* @package Cake.Network.Http
* @deprecated 3.0.0 This class is deprecated as it has naming conflicts with pecl/http
*/
class HttpResponse implements ArrayAccess {
/**
* Body content
*
* @var string
*/
public $body = '';
/**
* Headers
*
* @var array
*/
public $headers = array();
/**
* Cookies
*
* @var array
*/
public $cookies = array();
/**
* HTTP version
*
* @var string
*/
public $httpVersion = 'HTTP/1.1';
/**
* Response code
*
* @var integer
*/
public $code = 0;
/**
* Reason phrase
*
* @var string
*/
public $reasonPhrase = '';
/**
* Pure raw content
*
* @var string
*/
public $raw = '';
/**
* Constructor
*
* @param string $message
*/
public function __construct($message = null) {
if ($message !== null) {
$this->parseResponse($message);
}
}
/**
* Body content
*
* @return string
*/
public function body() {
return (string)$this->body;
}
/**
* Get header in case insensitive
*
* @param string $name Header name
* @param array $headers
* @return mixed String if header exists or null
*/
public function getHeader($name, $headers = null) {
if (!is_array($headers)) {
$headers =& $this->headers;
}
if (isset($headers[$name])) {
return $headers[$name];
}
foreach ($headers as $key => $value) {
if (strcasecmp($key, $name) == 0) {
return $value;
}
}
return null;
}
/**
* If return is 200 (OK)
*
* @return boolean
*/
public function isOk() {
return $this->code == 200;
}
/**
* If return is a valid 3xx (Redirection)
*
* @return boolean
*/
public function isRedirect() {
return in_array($this->code, array(301, 302, 303, 307)) && !is_null($this->getHeader('Location'));
}
/**
* Parses the given message and breaks it down in parts.
*
* @param string $message Message to parse
* @return void
* @throws SocketException
*/
public function parseResponse($message) {
if (!is_string($message)) {
throw new SocketException(__d('cake_dev', 'Invalid response.'));
}
if (!preg_match("/^(.+\r\n)(.*)(?<=\r\n)\r\n/Us", $message, $match)) {
throw new SocketException(__d('cake_dev', 'Invalid HTTP response.'));
}
list(, $statusLine, $header) = $match;
$this->raw = $message;
$this->body = (string)substr($message, strlen($match[0]));
if (preg_match("/(.+) ([0-9]{3}) (.+)\r\n/DU", $statusLine, $match)) {
$this->httpVersion = $match[1];
$this->code = $match[2];
$this->reasonPhrase = $match[3];
}
$this->headers = $this->_parseHeader($header);
$transferEncoding = $this->getHeader('Transfer-Encoding');
$decoded = $this->_decodeBody($this->body, $transferEncoding);
$this->body = $decoded['body'];
if (!empty($decoded['header'])) {
$this->headers = $this->_parseHeader($this->_buildHeader($this->headers) . $this->_buildHeader($decoded['header']));
}
if (!empty($this->headers)) {
$this->cookies = $this->parseCookies($this->headers);
}
}
/**
* Generic function to decode a $body with a given $encoding. Returns either an array with the keys
* 'body' and 'header' or false on failure.
*
* @param string $body A string containing the body to decode.
* @param string|boolean $encoding Can be false in case no encoding is being used, or a string representing the encoding.
* @return mixed Array of response headers and body or false.
*/
protected function _decodeBody($body, $encoding = 'chunked') {
if (!is_string($body)) {
return false;
}
if (empty($encoding)) {
return array('body' => $body, 'header' => false);
}
$decodeMethod = '_decode' . Inflector::camelize(str_replace('-', '_', $encoding)) . 'Body';
if (!is_callable(array(&$this, $decodeMethod))) {
return array('body' => $body, 'header' => false);
}
return $this->{$decodeMethod}($body);
}
/**
* Decodes a chunked message $body and returns either an array with the keys 'body' and 'header' or false as
* a result.
*
* @param string $body A string containing the chunked body to decode.
* @return mixed Array of response headers and body or false.
* @throws SocketException
*/
protected function _decodeChunkedBody($body) {
if (!is_string($body)) {
return false;
}
$decodedBody = null;
$chunkLength = null;
while ($chunkLength !== 0) {
if (!preg_match('/^([0-9a-f]+) *(?:;(.+)=(.+))?(?:\r\n|\n)/iU', $body, $match)) {
throw new SocketException(__d('cake_dev', 'HttpSocket::_decodeChunkedBody - Could not parse malformed chunk.'));
}
$chunkSize = 0;
$hexLength = 0;
$chunkExtensionValue = '';
if (isset($match[0])) {
$chunkSize = $match[0];
}
if (isset($match[1])) {
$hexLength = $match[1];
}
if (isset($match[3])) {
$chunkExtensionValue = $match[3];
}
$body = substr($body, strlen($chunkSize));
$chunkLength = hexdec($hexLength);
$chunk = substr($body, 0, $chunkLength);
$decodedBody .= $chunk;
if ($chunkLength !== 0) {
$body = substr($body, $chunkLength + strlen("\r\n"));
}
}
$entityHeader = false;
if (!empty($body)) {
$entityHeader = $this->_parseHeader($body);
}
return array('body' => $decodedBody, 'header' => $entityHeader);
}
/**
* Parses an array based header.
*
* @param array $header Header as an indexed array (field => value)
* @return array Parsed header
*/
protected function _parseHeader($header) {
if (is_array($header)) {
return $header;
} elseif (!is_string($header)) {
return false;
}
preg_match_all("/(.+):(.+)(?:(?<![\t ])\r\n|\$)/Uis", $header, $matches, PREG_SET_ORDER);
$header = array();
foreach ($matches as $match) {
list(, $field, $value) = $match;
$value = trim($value);
$value = preg_replace("/[\t ]\r\n/", "\r\n", $value);
$field = $this->_unescapeToken($field);
if (!isset($header[$field])) {
$header[$field] = $value;
} else {
$header[$field] = array_merge((array)$header[$field], (array)$value);
}
}
return $header;
}
/**
* Parses cookies in response headers.
*
* @param array $header Header array containing one ore more 'Set-Cookie' headers.
* @return mixed Either false on no cookies, or an array of cookies received.
*/
public function parseCookies($header) {
$cookieHeader = $this->getHeader('Set-Cookie', $header);
if (!$cookieHeader) {
return false;
}
$cookies = array();
foreach ((array)$cookieHeader as $cookie) {
if (strpos($cookie, '";"') !== false) {
$cookie = str_replace('";"', "{__cookie_replace__}", $cookie);
$parts = str_replace("{__cookie_replace__}", '";"', explode(';', $cookie));
} else {
$parts = preg_split('/\;[ \t]*/', $cookie);
}
list($name, $value) = explode('=', array_shift($parts), 2);
$cookies[$name] = compact('value');
foreach ($parts as $part) {
if (strpos($part, '=') !== false) {
list($key, $value) = explode('=', $part);
} else {
$key = $part;
$value = true;
}
$key = strtolower($key);
if (!isset($cookies[$name][$key])) {
$cookies[$name][$key] = $value;
}
}
}
return $cookies;
}
/**
* Unescapes a given $token according to RFC 2616 (HTTP 1.1 specs)
*
* @param string $token Token to unescape
* @param array $chars
* @return string Unescaped token
*/
protected function _unescapeToken($token, $chars = null) {
$regex = '/"([' . implode('', $this->_tokenEscapeChars(true, $chars)) . '])"/';
$token = preg_replace($regex, '\\1', $token);
return $token;
}
/**
* Gets escape chars according to RFC 2616 (HTTP 1.1 specs).
*
* @param boolean $hex true to get them as HEX values, false otherwise
* @param array $chars
* @return array Escape chars
*/
protected function _tokenEscapeChars($hex = true, $chars = null) {
if (!empty($chars)) {
$escape = $chars;
} else {
$escape = array('"', "(", ")", "<", ">", "@", ",", ";", ":", "\\", "/", "[", "]", "?", "=", "{", "}", " ");
for ($i = 0; $i <= 31; $i++) {
$escape[] = chr($i);
}
$escape[] = chr(127);
}
if ($hex == false) {
return $escape;
}
foreach ($escape as $key => $char) {
$escape[$key] = '\\x' . str_pad(dechex(ord($char)), 2, '0', STR_PAD_LEFT);
}
return $escape;
}
/**
* ArrayAccess - Offset Exists
*
* @param string $offset
* @return boolean
*/
public function offsetExists($offset) {
return in_array($offset, array('raw', 'status', 'header', 'body', 'cookies'));
}
/**
* ArrayAccess - Offset Get
*
* @param string $offset
* @return mixed
*/
public function offsetGet($offset) {
switch ($offset) {
case 'raw':
$firstLineLength = strpos($this->raw, "\r\n") + 2;
if ($this->raw[$firstLineLength] === "\r") {
$header = null;
} else {
$header = substr($this->raw, $firstLineLength, strpos($this->raw, "\r\n\r\n") - $firstLineLength) . "\r\n";
}
return array(
'status-line' => $this->httpVersion . ' ' . $this->code . ' ' . $this->reasonPhrase . "\r\n",
'header' => $header,
'body' => $this->body,
'response' => $this->raw
);
case 'status':
return array(
'http-version' => $this->httpVersion,
'code' => $this->code,
'reason-phrase' => $this->reasonPhrase
);
case 'header':
return $this->headers;
case 'body':
return $this->body;
case 'cookies':
return $this->cookies;
}
return null;
}
/**
* ArrayAccess - Offset Set
*
* @param string $offset
* @param mixed $value
* @return void
*/
public function offsetSet($offset, $value) {
}
/**
* ArrayAccess - Offset Unset
*
* @param string $offset
* @return void
*/
public function offsetUnset($offset) {
}
/**
* Instance as string
*
* @return string
*/
public function __toString() {
return $this->body();
}
class HttpResponse extends HttpSocketResponse {
}

View file

@ -2,25 +2,26 @@
/**
* HTTP Socket connection class.
*
* 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
* @package Cake.Network.Http
* @since CakePHP(tm) v 1.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('CakeSocket', 'Network');
App::uses('Router', 'Routing');
App::uses('Hash', 'Utility');
/**
* Cake network socket connection class.
* CakePHP network socket connection class.
*
* Core base class for HTTP network communication. HttpSocket can be used as an
* Object Oriented replacement for cURL in many places.
@ -34,7 +35,7 @@ class HttpSocket extends CakeSocket {
* enforce RFC 2616 (HTTP/1.1 specs).
* will be disabled and additional measures to deal with non-standard responses will be enabled.
*
* @var boolean
* @var bool
*/
public $quirksMode = false;
@ -64,7 +65,7 @@ class HttpSocket extends CakeSocket {
),
'raw' => null,
'redirect' => false,
'cookies' => array()
'cookies' => array(),
);
/**
@ -75,11 +76,11 @@ class HttpSocket extends CakeSocket {
public $response = null;
/**
* Response classname
* Response class name
*
* @var string
*/
public $responseClass = 'HttpResponse';
public $responseClass = 'HttpSocketResponse';
/**
* Configuration settings for the HttpSocket and the requests
@ -92,6 +93,10 @@ class HttpSocket extends CakeSocket {
'protocol' => 'tcp',
'port' => 80,
'timeout' => 30,
'ssl_verify_peer' => true,
'ssl_allow_self_signed' => false,
'ssl_verify_depth' => 5,
'ssl_verify_host' => true,
'request' => array(
'uri' => array(
'scheme' => array('http', 'https'),
@ -99,7 +104,7 @@ class HttpSocket extends CakeSocket {
'port' => array(80, 443)
),
'redirect' => false,
'cookies' => array()
'cookies' => array(),
)
);
@ -127,23 +132,23 @@ class HttpSocket extends CakeSocket {
/**
* Build an HTTP Socket using the specified configuration.
*
* You can use a url string to set the url and use default configurations for
* You can use a URL string to set the URL and use default configurations for
* all other options:
*
* `$http = new HttpSocket('http://cakephp.org/');`
*
* Or use an array to configure multiple options:
*
* {{{
* ```
* $http = new HttpSocket(array(
* 'host' => 'cakephp.org',
* 'timeout' => 20
* ));
* }}}
* ```
*
* See HttpSocket::$config for options that can be used.
*
* @param string|array $config Configuration information, either a string url or an array of options.
* @param string|array $config Configuration information, either a string URL or an array of options.
*/
public function __construct($config = array()) {
if (is_string($config)) {
@ -161,24 +166,24 @@ class HttpSocket extends CakeSocket {
/**
* Set authentication settings.
*
* Accepts two forms of parameters. If all you need is a username + password, as with
* Accepts two forms of parameters. If all you need is a username + password, as with
* Basic authentication you can do the following:
*
* {{{
* ```
* $http->configAuth('Basic', 'mark', 'secret');
* }}}
* ```
*
* If you are using an authentication strategy that requires more inputs, like Digest authentication
* you can call `configAuth()` with an array of user information.
*
* {{{
* ```
* $http->configAuth('Digest', array(
* 'user' => 'mark',
* 'pass' => 'secret',
* 'realm' => 'my-realm',
* 'nonce' => 1235
* ));
* }}}
* ```
*
* To remove any set authentication strategy, call `configAuth()` with no parameters:
*
@ -205,7 +210,7 @@ class HttpSocket extends CakeSocket {
* Set proxy settings
*
* @param string|array $host Proxy host. Can be an array with settings to authentication class
* @param integer $port Port. Default 3128.
* @param int $port Port. Default 3128.
* @param string $method Proxy method (ie, Basic, Digest). If empty, disable proxy authentication
* @param string $user Username if your proxy need authentication
* @param string $pass Password to proxy authentication
@ -226,7 +231,7 @@ class HttpSocket extends CakeSocket {
/**
* Set the resource to receive the request content. This resource must support fwrite.
*
* @param resource|boolean $resource Resource or false to disable the resource use
* @param resource|bool $resource Resource or false to disable the resource use
* @return void
* @throws SocketException
*/
@ -246,7 +251,7 @@ class HttpSocket extends CakeSocket {
* method and provide a more granular interface.
*
* @param string|array $request Either an URI string, or an array defining host/uri
* @return mixed false on error, HttpResponse on success
* @return mixed false on error, HttpSocketResponse on success
* @throws SocketException
*/
public function request($request = array()) {
@ -289,6 +294,7 @@ class HttpSocket extends CakeSocket {
if (isset($host)) {
$this->config['host'] = $host;
}
$this->_setProxy();
$this->request['proxy'] = $this->_proxy;
@ -306,8 +312,7 @@ class HttpSocket extends CakeSocket {
if (isset($this->request['uri']['port'])) {
$port = $this->request['uri']['port'];
}
if (
($scheme === 'http' && $port != 80) ||
if (($scheme === 'http' && $port != 80) ||
($scheme === 'https' && $port != 443) ||
($port != 80 && $port != 443)
) {
@ -318,12 +323,17 @@ class HttpSocket extends CakeSocket {
if (isset($this->request['uri']['user'], $this->request['uri']['pass'])) {
$this->configAuth('Basic', $this->request['uri']['user'], $this->request['uri']['pass']);
} elseif (isset($this->request['auth'], $this->request['auth']['method'], $this->request['auth']['user'], $this->request['auth']['pass'])) {
$this->configAuth($this->request['auth']['method'], $this->request['auth']['user'], $this->request['auth']['pass']);
}
$authHeader = Hash::get($this->request, 'header.Authorization');
if (empty($authHeader)) {
$this->_setAuth();
$this->request['auth'] = $this->_auth;
}
$this->_setAuth();
$this->request['auth'] = $this->_auth;
if (is_array($this->request['body'])) {
$this->request['body'] = http_build_query($this->request['body']);
$this->request['body'] = http_build_query($this->request['body'], '', '&');
}
if (!empty($this->request['body']) && !isset($this->request['header']['Content-Type'])) {
@ -333,6 +343,9 @@ class HttpSocket extends CakeSocket {
if (!empty($this->request['body']) && !isset($this->request['header']['Content-Length'])) {
$this->request['header']['Content-Length'] = strlen($this->request['body']);
}
if (isset($this->request['uri']['scheme']) && $this->request['uri']['scheme'] === 'https' && in_array($this->config['protocol'], array(false, 'tcp'))) {
$this->config['protocol'] = 'ssl';
}
$connectionType = null;
if (isset($this->request['header']['Connection'])) {
@ -359,11 +372,13 @@ class HttpSocket extends CakeSocket {
$this->request['raw'] .= "\r\n";
$this->request['raw'] .= $this->request['body'];
// SSL context is set during the connect() method.
$this->write($this->request['raw']);
$response = null;
$inHeader = true;
while ($data = $this->read()) {
while (($data = $this->read()) !== false) {
if ($this->_contentResource) {
if ($inHeader) {
$response .= $data;
@ -395,6 +410,7 @@ class HttpSocket extends CakeSocket {
throw new SocketException(__d('cake_dev', 'Class %s not found.', $this->responseClass));
}
$this->response = new $responseClass($response);
if (!empty($this->response->cookies)) {
if (!isset($this->config['request']['cookies'][$Host])) {
$this->config['request']['cookies'][$Host] = array();
@ -403,7 +419,8 @@ class HttpSocket extends CakeSocket {
}
if ($this->request['redirect'] && $this->response->isRedirect()) {
$request['uri'] = trim(urldecode($this->response->getHeader('Location')), '=');
$location = trim($this->response->getHeader('Location'), '=');
$request['uri'] = str_replace('%2F', '/', $location);
$request['redirect'] = is_int($this->request['redirect']) ? $this->request['redirect'] - 1 : $this->request['redirect'];
$this->response = $this->request($request);
}
@ -422,12 +439,12 @@ class HttpSocket extends CakeSocket {
*
* You could express the same thing using a uri array and query string parameters:
*
* {{{
* ```
* $response = $http->get(
* array('host' => 'google.com', 'path' => '/search'),
* array('q' => 'cakephp', 'client' => 'safari')
* );
* }}}
* ```
*
* @param string|array $uri URI to request. Either a string uri, or a uri array, see HttpSocket::_parseUri()
* @param array $query Querystring parameters to append to URI
@ -449,20 +466,46 @@ class HttpSocket extends CakeSocket {
return $this->request($request);
}
/**
* Issues a HEAD request to the specified URI, query, and request.
*
* By definition HEAD request are identical to GET request except they return no response body. This means that all
* information and examples relevant to GET also applys to HEAD.
*
* @param string|array $uri URI to request. Either a string URI, or a URI array, see HttpSocket::_parseUri()
* @param array $query Querystring parameters to append to URI
* @param array $request An indexed array with indexes such as 'method' or uri
* @return mixed Result of request, either false on failure or the response to the request.
*/
public function head($uri = null, $query = array(), $request = array()) {
if (!empty($query)) {
$uri = $this->_parseUri($uri, $this->config['request']['uri']);
if (isset($uri['query'])) {
$uri['query'] = array_merge($uri['query'], $query);
} else {
$uri['query'] = $query;
}
$uri = $this->_buildUri($uri);
}
$request = Hash::merge(array('method' => 'HEAD', 'uri' => $uri), $request);
return $this->request($request);
}
/**
* Issues a POST request to the specified URI, query, and request.
*
* `post()` can be used to post simple data arrays to a url:
* `post()` can be used to post simple data arrays to a URL:
*
* {{{
* ```
* $response = $http->post('http://example.com', array(
* 'username' => 'batman',
* 'password' => 'bruce_w4yne'
* ));
* }}}
* ```
*
* @param string|array $uri URI to request. See HttpSocket::_parseUri()
* @param array $data Array of POST data keys and values.
* @param array $data Array of request body data keys and values.
* @param array $request An indexed array with indexes such as 'method' or uri
* @return mixed Result of request, either false on failure or the response to the request.
*/
@ -475,7 +518,7 @@ class HttpSocket extends CakeSocket {
* Issues a PUT request to the specified URI, query, and request.
*
* @param string|array $uri URI to request, See HttpSocket::_parseUri()
* @param array $data Array of PUT data keys and values.
* @param array $data Array of request body data keys and values.
* @param array $request An indexed array with indexes such as 'method' or uri
* @return mixed Result of request
*/
@ -484,11 +527,24 @@ class HttpSocket extends CakeSocket {
return $this->request($request);
}
/**
* Issues a PATCH request to the specified URI, query, and request.
*
* @param string|array $uri URI to request, See HttpSocket::_parseUri()
* @param array $data Array of request body data keys and values.
* @param array $request An indexed array with indexes such as 'method' or uri
* @return mixed Result of request
*/
public function patch($uri = null, $data = array(), $request = array()) {
$request = Hash::merge(array('method' => 'PATCH', 'uri' => $uri, 'body' => $data), $request);
return $this->request($request);
}
/**
* Issues a DELETE request to the specified URI, query, and request.
*
* @param string|array $uri URI to request (see {@link _parseUri()})
* @param array $data Query to append to URI
* @param array $data Array of request body data keys and values.
* @param array $request An indexed array with indexes such as 'method' or uri
* @return mixed Result of request
*/
@ -498,19 +554,19 @@ class HttpSocket extends CakeSocket {
}
/**
* Normalizes urls into a $uriTemplate. If no template is provided
* a default one will be used. Will generate the url using the
* Normalizes URLs into a $uriTemplate. If no template is provided
* a default one will be used. Will generate the URL using the
* current config information.
*
* ### Usage:
*
* After configuring part of the request parameters, you can use url() to generate
* urls.
* URLs.
*
* {{{
* ```
* $http = new HttpSocket('http://www.cakephp.org');
* $url = $http->url('/search?q=bar');
* }}}
* ```
*
* Would return `http://www.cakephp.org/search?q=bar`
*
@ -520,12 +576,12 @@ class HttpSocket extends CakeSocket {
*
* Would return `/search?q=socket`.
*
* @param string|array Either a string or array of url options to create a url with.
* @param string $uriTemplate A template string to use for url formatting.
* @return mixed Either false on failure or a string containing the composed url.
* @param string|array $url Either a string or array of URL options to create a URL with.
* @param string $uriTemplate A template string to use for URL formatting.
* @return mixed Either false on failure or a string containing the composed URL.
*/
public function url($url = null, $uriTemplate = null) {
if (is_null($url)) {
if ($url === null) {
$url = '/';
}
if (is_string($url)) {
@ -537,7 +593,7 @@ class HttpSocket extends CakeSocket {
if (is_array($port)) {
$port = $port[0];
}
if ($url{0} == '/') {
if ($url{0} === '/') {
$url = $this->config['request']['uri']['host'] . ':' . $port . $url;
}
if (!preg_match('/^.+:\/\/|\*|^\//', $url)) {
@ -579,7 +635,7 @@ class HttpSocket extends CakeSocket {
throw new SocketException(__d('cake_dev', 'Unknown authentication method.'));
}
if (!method_exists($authClass, 'authentication')) {
throw new SocketException(sprintf(__d('cake_dev', 'The %s do not support authentication.'), $authClass));
throw new SocketException(__d('cake_dev', 'The %s does not support authentication.', $authClass));
}
call_user_func_array("$authClass::authentication", array($this, &$this->_auth[$method]));
}
@ -596,6 +652,7 @@ class HttpSocket extends CakeSocket {
}
$this->config['host'] = $this->_proxy['host'];
$this->config['port'] = $this->_proxy['port'];
$this->config['proxy'] = true;
if (empty($this->_proxy['method']) || !isset($this->_proxy['user'], $this->_proxy['pass'])) {
return;
@ -608,16 +665,23 @@ class HttpSocket extends CakeSocket {
throw new SocketException(__d('cake_dev', 'Unknown authentication method for proxy.'));
}
if (!method_exists($authClass, 'proxyAuthentication')) {
throw new SocketException(sprintf(__d('cake_dev', 'The %s do not support proxy authentication.'), $authClass));
throw new SocketException(__d('cake_dev', 'The %s does not support proxy authentication.', $authClass));
}
call_user_func_array("$authClass::proxyAuthentication", array($this, &$this->_proxy));
if (!empty($this->request['header']['Proxy-Authorization'])) {
$this->config['proxyauth'] = $this->request['header']['Proxy-Authorization'];
if ($this->request['uri']['scheme'] === 'https') {
$this->request['header'] = Hash::remove($this->request['header'], 'Proxy-Authorization');
}
}
}
/**
* Parses and sets the specified URI into current request configuration.
*
* @param string|array $uri URI, See HttpSocket::_parseUri()
* @return boolean If uri has merged in config
* @return bool If uri has merged in config
*/
protected function _configUri($uri = null) {
if (empty($uri)) {
@ -661,7 +725,7 @@ class HttpSocket extends CakeSocket {
}
$uri['path'] = preg_replace('/^\//', null, $uri['path']);
$uri['query'] = http_build_query($uri['query']);
$uri['query'] = http_build_query($uri['query'], '', '&');
$uri['query'] = rtrim($uri['query'], '=');
$stripIfEmpty = array(
'query' => '?%query',
@ -695,7 +759,7 @@ class HttpSocket extends CakeSocket {
* such as 'scheme', 'port', 'query'.
*
* @param string|array $uri URI to parse
* @param boolean|array $base If true use default URI config, otherwise indexed array to set 'scheme', 'host', 'port', etc.
* @param bool|array $base If true use default URI config, otherwise indexed array to set 'scheme', 'host', 'port', etc.
* @return array Parsed URI
*/
protected function _parseUri($uri = null, $base = array()) {
@ -823,16 +887,15 @@ class HttpSocket extends CakeSocket {
* Builds a request line according to HTTP/1.1 specs. Activate quirks mode to work outside specs.
*
* @param array $request Needs to contain a 'uri' key. Should also contain a 'method' key, otherwise defaults to GET.
* @param string $versionToken The version token to use, defaults to HTTP/1.1
* @return string Request line
* @throws SocketException
*/
protected function _buildRequestLine($request = array(), $versionToken = 'HTTP/1.1') {
protected function _buildRequestLine($request = array()) {
$asteriskMethods = array('OPTIONS');
if (is_string($request)) {
$isValid = preg_match("/(.+) (.+) (.+)\r\n/U", $request, $match);
if (!$this->quirksMode && (!$isValid || ($match[2] == '*' && !in_array($match[3], $asteriskMethods)))) {
if (!$this->quirksMode && (!$isValid || ($match[2] === '*' && !in_array($match[3], $asteriskMethods)))) {
throw new SocketException(__d('cake_dev', 'HttpSocket::_buildRequestLine - Passed an invalid request line string. Activate quirks mode to do this.'));
}
return $request;
@ -842,9 +905,9 @@ class HttpSocket extends CakeSocket {
return false;
}
$request['uri'] = $this->_parseUri($request['uri']);
$request = array_merge(array('method' => 'GET'), $request);
if (!empty($this->_proxy['host'])) {
$request['uri'] = $this->_parseUri($request['uri']);
$request += array('method' => 'GET');
if (!empty($this->_proxy['host']) && $request['uri']['scheme'] !== 'https') {
$request['uri'] = $this->_buildUri($request['uri'], '%scheme://%host:%port/%path?%query');
} else {
$request['uri'] = $this->_buildUri($request['uri'], '/%path?%query');
@ -853,14 +916,15 @@ class HttpSocket extends CakeSocket {
if (!$this->quirksMode && $request['uri'] === '*' && !in_array($request['method'], $asteriskMethods)) {
throw new SocketException(__d('cake_dev', 'HttpSocket::_buildRequestLine - The "*" asterisk character is only allowed for the following methods: %s. Activate quirks mode to work outside of HTTP/1.1 specs.', implode(',', $asteriskMethods)));
}
return $request['method'] . ' ' . $request['uri'] . ' ' . $versionToken . "\r\n";
$version = isset($request['version']) ? $request['version'] : '1.1';
return $request['method'] . ' ' . $request['uri'] . ' HTTP/' . $version . "\r\n";
}
/**
* Builds the header.
*
* @param array $header Header to build
* @param string $mode
* @param string $mode Mode
* @return string Header built from array
*/
protected function _buildHeader($header, $mode = 'standard') {
@ -883,7 +947,7 @@ class HttpSocket extends CakeSocket {
$returnHeader = '';
foreach ($header as $field => $contents) {
if (is_array($contents) && $mode == 'standard') {
if (is_array($contents) && $mode === 'standard') {
$contents = implode(',', $contents);
}
foreach ((array)$contents as $content) {
@ -899,13 +963,21 @@ class HttpSocket extends CakeSocket {
/**
* Builds cookie headers for a request.
*
* Cookies can either be in the format returned in responses, or
* a simple key => value pair.
*
* @param array $cookies Array of cookies to send with the request.
* @return string Cookie header string to be sent with the request.
*/
public function buildCookies($cookies) {
$header = array();
foreach ($cookies as $name => $cookie) {
$header[] = $name . '=' . $this->_escapeToken($cookie['value'], array(';'));
if (is_array($cookie)) {
$value = $this->_escapeToken($cookie['value'], array(';'));
} else {
$value = $this->_escapeToken($cookie, array(';'));
}
$header[] = $name . '=' . $value;
}
return $this->_buildHeader(array('Cookie' => implode('; ', $header)), 'pragmatic');
}
@ -914,7 +986,7 @@ class HttpSocket extends CakeSocket {
* Escapes a given $token according to RFC 2616 (HTTP 1.1 specs)
*
* @param string $token Token to escape
* @param array $chars
* @param array $chars Characters to escape
* @return string Escaped token
*/
protected function _escapeToken($token, $chars = null) {
@ -926,8 +998,8 @@ class HttpSocket extends CakeSocket {
/**
* Gets escape chars according to RFC 2616 (HTTP 1.1 specs).
*
* @param boolean $hex true to get them as HEX values, false otherwise
* @param array $chars
* @param bool $hex true to get them as HEX values, false otherwise
* @param array $chars Characters to escape
* @return array Escape chars
*/
protected function _tokenEscapeChars($hex = true, $chars = null) {
@ -941,7 +1013,7 @@ class HttpSocket extends CakeSocket {
$escape[] = chr(127);
}
if ($hex == false) {
if (!$hex) {
return $escape;
}
foreach ($escape as $key => $char) {
@ -951,11 +1023,11 @@ class HttpSocket extends CakeSocket {
}
/**
* Resets the state of this HttpSocket instance to it's initial state (before Object::__construct got executed) or does
* Resets the state of this HttpSocket instance to it's initial state (before CakeObject::__construct got executed) or does
* the same thing partially for the request and the response property only.
*
* @param boolean $full If set to false only HttpSocket::response and HttpSocket::request are reseted
* @return boolean True on success
* @param bool $full If set to false only HttpSocket::response and HttpSocket::request are reset
* @return bool True on success
*/
public function reset($full = true) {
static $initalState = array();
@ -972,3 +1044,4 @@ class HttpSocket extends CakeSocket {
}
}

View file

@ -0,0 +1,461 @@
<?php
/**
* HTTP Response from HttpSocket.
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.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 (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since CakePHP(tm) v 2.0.0
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
/**
* HTTP Response from HttpSocket.
*
* @package Cake.Network.Http
*/
class HttpSocketResponse implements ArrayAccess {
/**
* Body content
*
* @var string
*/
public $body = '';
/**
* Headers
*
* @var array
*/
public $headers = array();
/**
* Cookies
*
* @var array
*/
public $cookies = array();
/**
* HTTP version
*
* @var string
*/
public $httpVersion = 'HTTP/1.1';
/**
* Response code
*
* @var int
*/
public $code = 0;
/**
* Reason phrase
*
* @var string
*/
public $reasonPhrase = '';
/**
* Pure raw content
*
* @var string
*/
public $raw = '';
/**
* Context data in the response.
* Contains SSL certificates for example.
*
* @var array
*/
public $context = array();
/**
* Constructor
*
* @param string $message Message to parse.
*/
public function __construct($message = null) {
if ($message !== null) {
$this->parseResponse($message);
}
}
/**
* Body content
*
* @return string
*/
public function body() {
return (string)$this->body;
}
/**
* Get header in case insensitive
*
* @param string $name Header name.
* @param array $headers Headers to format.
* @return mixed String if header exists or null
*/
public function getHeader($name, $headers = null) {
if (!is_array($headers)) {
$headers =& $this->headers;
}
if (isset($headers[$name])) {
return $headers[$name];
}
foreach ($headers as $key => $value) {
if (strcasecmp($key, $name) === 0) {
return $value;
}
}
return null;
}
/**
* If return is 200 (OK)
*
* @return bool
*/
public function isOk() {
return in_array($this->code, array(200, 201, 202, 203, 204, 205, 206));
}
/**
* If return is a valid 3xx (Redirection)
*
* @return bool
*/
public function isRedirect() {
return in_array($this->code, array(301, 302, 303, 307)) && $this->getHeader('Location') !== null;
}
/**
* Parses the given message and breaks it down in parts.
*
* @param string $message Message to parse
* @return void
* @throws SocketException
*/
public function parseResponse($message) {
if (!is_string($message)) {
throw new SocketException(__d('cake_dev', 'Invalid response.'));
}
if (!preg_match("/^(.+\r\n)(.*)(?<=\r\n)\r\n/Us", $message, $match)) {
throw new SocketException(__d('cake_dev', 'Invalid HTTP response.'));
}
list(, $statusLine, $header) = $match;
$this->raw = $message;
$this->body = (string)substr($message, strlen($match[0]));
if (preg_match("/(.+) ([0-9]{3})(?:\s+(\w.+))?\s*\r\n/DU", $statusLine, $match)) {
$this->httpVersion = $match[1];
$this->code = $match[2];
if (isset($match[3])) {
$this->reasonPhrase = $match[3];
}
}
$this->headers = $this->_parseHeader($header);
$transferEncoding = $this->getHeader('Transfer-Encoding');
$decoded = $this->_decodeBody($this->body, $transferEncoding);
$this->body = $decoded['body'];
if (!empty($decoded['header'])) {
$this->headers = $this->_parseHeader($this->_buildHeader($this->headers) . $this->_buildHeader($decoded['header']));
}
if (!empty($this->headers)) {
$this->cookies = $this->parseCookies($this->headers);
}
}
/**
* Generic function to decode a $body with a given $encoding. Returns either an array with the keys
* 'body' and 'header' or false on failure.
*
* @param string $body A string containing the body to decode.
* @param string|bool $encoding Can be false in case no encoding is being used, or a string representing the encoding.
* @return mixed Array of response headers and body or false.
*/
protected function _decodeBody($body, $encoding = 'chunked') {
if (!is_string($body)) {
return false;
}
if (empty($encoding)) {
return array('body' => $body, 'header' => false);
}
$decodeMethod = '_decode' . Inflector::camelize(str_replace('-', '_', $encoding)) . 'Body';
if (!is_callable(array(&$this, $decodeMethod))) {
return array('body' => $body, 'header' => false);
}
return $this->{$decodeMethod}($body);
}
/**
* Decodes a chunked message $body and returns either an array with the keys 'body' and 'header' or false as
* a result.
*
* @param string $body A string containing the chunked body to decode.
* @return mixed Array of response headers and body or false.
* @throws SocketException
*/
protected function _decodeChunkedBody($body) {
if (!is_string($body)) {
return false;
}
$decodedBody = null;
$chunkLength = null;
while ($chunkLength !== 0) {
if (!preg_match('/^([0-9a-f]+)[ ]*(?:;(.+)=(.+))?(?:\r\n|\n)/iU', $body, $match)) {
// Handle remaining invalid data as one big chunk.
preg_match('/^(.*?)\r\n/', $body, $invalidMatch);
$length = isset($invalidMatch[1]) ? strlen($invalidMatch[1]) : 0;
$match = array(
0 => '',
1 => dechex($length)
);
}
$chunkSize = 0;
$hexLength = 0;
if (isset($match[0])) {
$chunkSize = $match[0];
}
if (isset($match[1])) {
$hexLength = $match[1];
}
$chunkLength = hexdec($hexLength);
$body = substr($body, strlen($chunkSize));
$decodedBody .= substr($body, 0, $chunkLength);
if ($chunkLength) {
$body = substr($body, $chunkLength + strlen("\r\n"));
}
}
$entityHeader = false;
if (!empty($body)) {
$entityHeader = $this->_parseHeader($body);
}
return array('body' => $decodedBody, 'header' => $entityHeader);
}
/**
* Parses an array based header.
*
* @param array $header Header as an indexed array (field => value)
* @return array Parsed header
*/
protected function _parseHeader($header) {
if (is_array($header)) {
return $header;
} elseif (!is_string($header)) {
return false;
}
preg_match_all("/(.+):(.+)(?:\r\n|\$)/Uis", $header, $matches, PREG_SET_ORDER);
$lines = explode("\r\n", $header);
$header = array();
foreach ($lines as $line) {
if (strlen($line) === 0) {
continue;
}
$continuation = false;
$first = substr($line, 0, 1);
// Multi-line header
if ($first === ' ' || $first === "\t") {
$value .= preg_replace("/\s+/", ' ', $line);
$continuation = true;
} elseif (strpos($line, ':') !== false) {
list($field, $value) = explode(':', $line, 2);
$field = $this->_unescapeToken($field);
}
$value = trim($value);
if (!isset($header[$field]) || $continuation) {
$header[$field] = $value;
} else {
$header[$field] = array_merge((array)$header[$field], (array)$value);
}
}
return $header;
}
/**
* Parses cookies in response headers.
*
* @param array $header Header array containing one ore more 'Set-Cookie' headers.
* @return mixed Either false on no cookies, or an array of cookies received.
*/
public function parseCookies($header) {
$cookieHeader = $this->getHeader('Set-Cookie', $header);
if (!$cookieHeader) {
return false;
}
$cookies = array();
foreach ((array)$cookieHeader as $cookie) {
if (strpos($cookie, '";"') !== false) {
$cookie = str_replace('";"', "{__cookie_replace__}", $cookie);
$parts = str_replace("{__cookie_replace__}", '";"', explode(';', $cookie));
} else {
$parts = preg_split('/\;[ \t]*/', $cookie);
}
$nameParts = explode('=', array_shift($parts), 2);
if (count($nameParts) < 2) {
$nameParts = array('', $nameParts[0]);
}
list($name, $value) = $nameParts;
$cookies[$name] = compact('value');
foreach ($parts as $part) {
if (strpos($part, '=') !== false) {
list($key, $value) = explode('=', $part);
} else {
$key = $part;
$value = true;
}
$key = strtolower($key);
if (!isset($cookies[$name][$key])) {
$cookies[$name][$key] = $value;
}
}
}
return $cookies;
}
/**
* Unescapes a given $token according to RFC 2616 (HTTP 1.1 specs)
*
* @param string $token Token to unescape.
* @param array $chars Characters to unescape.
* @return string Unescaped token
*/
protected function _unescapeToken($token, $chars = null) {
$regex = '/"([' . implode('', $this->_tokenEscapeChars(true, $chars)) . '])"/';
$token = preg_replace($regex, '\\1', $token);
return $token;
}
/**
* Gets escape chars according to RFC 2616 (HTTP 1.1 specs).
*
* @param bool $hex True to get them as HEX values, false otherwise.
* @param array $chars Characters to uescape.
* @return array Escape chars
*/
protected function _tokenEscapeChars($hex = true, $chars = null) {
if (!empty($chars)) {
$escape = $chars;
} else {
$escape = array('"', "(", ")", "<", ">", "@", ",", ";", ":", "\\", "/", "[", "]", "?", "=", "{", "}", " ");
for ($i = 0; $i <= 31; $i++) {
$escape[] = chr($i);
}
$escape[] = chr(127);
}
if (!$hex) {
return $escape;
}
foreach ($escape as $key => $char) {
$escape[$key] = '\\x' . str_pad(dechex(ord($char)), 2, '0', STR_PAD_LEFT);
}
return $escape;
}
/**
* ArrayAccess - Offset Exists
*
* @param string $offset Offset to check.
* @return bool
*/
public function offsetExists($offset) {
return in_array($offset, array('raw', 'status', 'header', 'body', 'cookies'));
}
/**
* ArrayAccess - Offset Get
*
* @param string $offset Offset to get.
* @return mixed
*/
public function offsetGet($offset) {
switch ($offset) {
case 'raw':
$firstLineLength = strpos($this->raw, "\r\n") + 2;
if ($this->raw[$firstLineLength] === "\r") {
$header = null;
} else {
$header = substr($this->raw, $firstLineLength, strpos($this->raw, "\r\n\r\n") - $firstLineLength) . "\r\n";
}
return array(
'status-line' => $this->httpVersion . ' ' . $this->code . ' ' . $this->reasonPhrase . "\r\n",
'header' => $header,
'body' => $this->body,
'response' => $this->raw
);
case 'status':
return array(
'http-version' => $this->httpVersion,
'code' => $this->code,
'reason-phrase' => $this->reasonPhrase
);
case 'header':
return $this->headers;
case 'body':
return $this->body;
case 'cookies':
return $this->cookies;
}
return null;
}
/**
* ArrayAccess - Offset Set
*
* @param string $offset Offset to set.
* @param mixed $value Value.
* @return void
*/
public function offsetSet($offset, $value) {
}
/**
* ArrayAccess - Offset Unset
*
* @param string $offset Offset to unset.
* @return void
*/
public function offsetUnset($offset) {
}
/**
* Instance as string
*
* @return string
*/
public function __toString() {
return $this->body();
}
}