mirror of
https://github.com/brmlab/brmsklad.git
synced 2025-10-29 23:33:58 +01:00
Backup of current cakephp version
This commit is contained in:
parent
b8f82da6f8
commit
5a580df460
925 changed files with 238041 additions and 1 deletions
873
lib/Cake/Network/CakeRequest.php
Normal file
873
lib/Cake/Network/CakeRequest.php
Normal file
|
|
@ -0,0 +1,873 @@
|
|||
<?php
|
||||
/**
|
||||
* CakeRequest
|
||||
*
|
||||
* PHP 5
|
||||
*
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright 2005-2012, 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)
|
||||
*/
|
||||
App::uses('Hash', 'Utility');
|
||||
|
||||
/**
|
||||
* A class that helps wrap Request information and particulars about a single request.
|
||||
* Provides methods commonly used to introspect on the request headers and request body.
|
||||
*
|
||||
* Has both an Array and Object interface. You can access framework parameters using indexes:
|
||||
*
|
||||
* `$request['controller']` or `$request->controller`.
|
||||
*
|
||||
* @package Cake.Network
|
||||
*/
|
||||
class CakeRequest implements ArrayAccess {
|
||||
|
||||
/**
|
||||
* Array of parameters parsed from the url.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public $params = array(
|
||||
'plugin' => null,
|
||||
'controller' => null,
|
||||
'action' => null,
|
||||
'named' => array(),
|
||||
'pass' => array(),
|
||||
);
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public $data = array();
|
||||
|
||||
/**
|
||||
* Array of querystring arguments
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public $query = array();
|
||||
|
||||
/**
|
||||
* The url string used for the request.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $url;
|
||||
|
||||
/**
|
||||
* Base url path.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $base = false;
|
||||
|
||||
/**
|
||||
* webroot path segment for the request.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $webroot = '/';
|
||||
|
||||
/**
|
||||
* The full address to the current request
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $here = null;
|
||||
|
||||
/**
|
||||
* The built in detectors used with `is()` can be modified with `addDetector()`.
|
||||
*
|
||||
* There are several ways to specify a detector, see CakeRequest::addDetector() for the
|
||||
* various formats and ways to define detectors.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $_detectors = array(
|
||||
'get' => array('env' => 'REQUEST_METHOD', 'value' => 'GET'),
|
||||
'post' => array('env' => 'REQUEST_METHOD', 'value' => 'POST'),
|
||||
'put' => array('env' => 'REQUEST_METHOD', 'value' => 'PUT'),
|
||||
'delete' => array('env' => 'REQUEST_METHOD', 'value' => 'DELETE'),
|
||||
'head' => array('env' => 'REQUEST_METHOD', 'value' => 'HEAD'),
|
||||
'options' => array('env' => 'REQUEST_METHOD', 'value' => 'OPTIONS'),
|
||||
'ssl' => array('env' => 'HTTPS', 'value' => 1),
|
||||
'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',
|
||||
'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)
|
||||
);
|
||||
|
||||
/**
|
||||
* 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
|
||||
*/
|
||||
protected $_input = '';
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
public function __construct($url = null, $parseEnvironment = true) {
|
||||
$this->_base();
|
||||
if (empty($url)) {
|
||||
$url = $this->_url();
|
||||
}
|
||||
if ($url[0] == '/') {
|
||||
$url = substr($url, 1);
|
||||
}
|
||||
$this->url = $url;
|
||||
|
||||
if ($parseEnvironment) {
|
||||
$this->_processPost();
|
||||
$this->_processGet();
|
||||
$this->_processFiles();
|
||||
}
|
||||
$this->here = $this->base . '/' . $this->url;
|
||||
}
|
||||
|
||||
/**
|
||||
* process the post data and set what is there into the object.
|
||||
* processed data is available at `$this->data`
|
||||
*
|
||||
* Will merge POST vars prefixed with `data`, and ones without
|
||||
* into a single array. Variables prefixed with `data` will overwrite those without.
|
||||
*
|
||||
* If you have mixed POST values be careful not to make any top level keys numeric
|
||||
* containing arrays. Hash::merge() is used to merge data, and it has possibly
|
||||
* unexpected behavior in this situation.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
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
|
||||
) {
|
||||
$data = $this->_readInput();
|
||||
parse_str($data, $this->data);
|
||||
}
|
||||
if (ini_get('magic_quotes_gpc') === '1') {
|
||||
$this->data = stripslashes_deep($this->data);
|
||||
}
|
||||
if (env('HTTP_X_HTTP_METHOD_OVERRIDE')) {
|
||||
$this->data['_method'] = env('HTTP_X_HTTP_METHOD_OVERRIDE');
|
||||
}
|
||||
$isArray = is_array($this->data);
|
||||
if ($isArray && isset($this->data['_method'])) {
|
||||
if (!empty($_SERVER)) {
|
||||
$_SERVER['REQUEST_METHOD'] = $this->data['_method'];
|
||||
} else {
|
||||
$_ENV['REQUEST_METHOD'] = $this->data['_method'];
|
||||
}
|
||||
unset($this->data['_method']);
|
||||
}
|
||||
if ($isArray && isset($this->data['data'])) {
|
||||
$data = $this->data['data'];
|
||||
if (count($this->data) <= 1) {
|
||||
$this->data = $data;
|
||||
} else {
|
||||
unset($this->data['data']);
|
||||
$this->data = Hash::merge($this->data, $data);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Process the GET parameters and move things into the object.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function _processGet() {
|
||||
if (ini_get('magic_quotes_gpc') === '1') {
|
||||
$query = stripslashes_deep($_GET);
|
||||
} else {
|
||||
$query = $_GET;
|
||||
}
|
||||
|
||||
unset($query['/' . str_replace('.', '_', urldecode($this->url))]);
|
||||
if (strpos($this->url, '?') !== false) {
|
||||
list(, $querystr) = explode('?', $this->url);
|
||||
parse_str($querystr, $queryArgs);
|
||||
$query += $queryArgs;
|
||||
}
|
||||
if (isset($this->params['url'])) {
|
||||
$query = array_merge($this->params['url'], $query);
|
||||
}
|
||||
$this->query = $query;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
protected function _url() {
|
||||
if (!empty($_SERVER['PATH_INFO'])) {
|
||||
return $_SERVER['PATH_INFO'];
|
||||
} 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));
|
||||
} 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'])) {
|
||||
$uri = $_SERVER['HTTP_X_REWRITE_URL'];
|
||||
} elseif ($var = env('argv')) {
|
||||
$uri = $var[0];
|
||||
}
|
||||
|
||||
$base = $this->base;
|
||||
|
||||
if (strlen($base) > 0 && strpos($uri, $base) === 0) {
|
||||
$uri = substr($uri, strlen($base));
|
||||
}
|
||||
if (strpos($uri, '?') !== false) {
|
||||
list($uri) = explode('?', $uri, 2);
|
||||
}
|
||||
if (empty($uri) || $uri == '/' || $uri == '//') {
|
||||
return '/';
|
||||
}
|
||||
return $uri;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a base URL and sets the proper webroot
|
||||
*
|
||||
* @return string Base URL
|
||||
*/
|
||||
protected function _base() {
|
||||
$dir = $webroot = null;
|
||||
$config = Configure::read('App');
|
||||
extract($config);
|
||||
|
||||
if (!isset($base)) {
|
||||
$base = $this->base;
|
||||
}
|
||||
if ($base !== false) {
|
||||
$this->webroot = $base . '/';
|
||||
return $this->base = $base;
|
||||
}
|
||||
|
||||
if (!$baseUrl) {
|
||||
$base = dirname(env('PHP_SELF'));
|
||||
|
||||
if ($webroot === 'webroot' && $webroot === basename($base)) {
|
||||
$base = dirname($base);
|
||||
}
|
||||
if ($dir === 'app' && $dir === basename($base)) {
|
||||
$base = dirname($base);
|
||||
}
|
||||
|
||||
if ($base === DS || $base === '.') {
|
||||
$base = '';
|
||||
}
|
||||
|
||||
$this->webroot = $base . '/';
|
||||
return $this->base = $base;
|
||||
}
|
||||
|
||||
$file = '/' . basename($baseUrl);
|
||||
$base = dirname($baseUrl);
|
||||
|
||||
if ($base === DS || $base === '.') {
|
||||
$base = '';
|
||||
}
|
||||
$this->webroot = $base . '/';
|
||||
|
||||
$docRoot = env('DOCUMENT_ROOT');
|
||||
$docRootContainsWebroot = strpos($docRoot, $dir . '/' . $webroot);
|
||||
|
||||
if (!empty($base) || !$docRootContainsWebroot) {
|
||||
if (strpos($this->webroot, '/' . $dir . '/') === false) {
|
||||
$this->webroot .= $dir . '/';
|
||||
}
|
||||
if (strpos($this->webroot, '/' . $webroot . '/') === false) {
|
||||
$this->webroot .= $webroot . '/';
|
||||
}
|
||||
}
|
||||
return $this->base = $base . $file;
|
||||
}
|
||||
|
||||
/**
|
||||
* Process $_FILES and move things into the object.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function _processFiles() {
|
||||
if (isset($_FILES) && is_array($_FILES)) {
|
||||
foreach ($_FILES as $name => $data) {
|
||||
if ($name !== 'data') {
|
||||
$this->params['form'][$name] = $data;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (isset($_FILES['data'])) {
|
||||
foreach ($_FILES['data'] as $key => $data) {
|
||||
$this->_processFileData('', $data, $key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Recursively walks the FILES array restructuring the data
|
||||
* into something sane and useable.
|
||||
*
|
||||
* @param string $path The dot separated path to insert $data into.
|
||||
* @param array $data The data to traverse/insert.
|
||||
* @param string $field The terminal field name, which is the top level key in $_FILES.
|
||||
* @return void
|
||||
*/
|
||||
protected function _processFileData($path, $data, $field) {
|
||||
foreach ($data as $key => $fields) {
|
||||
$newPath = $key;
|
||||
if (!empty($path)) {
|
||||
$newPath = $path . '.' . $key;
|
||||
}
|
||||
if (is_array($fields)) {
|
||||
$this->_processFileData($newPath, $fields, $field);
|
||||
} else {
|
||||
$newPath .= '.' . $field;
|
||||
$this->data = Hash::insert($this->data, $newPath, $fields);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
* @return string The client IP.
|
||||
*/
|
||||
public function clientIp($safe = true) {
|
||||
if (!$safe && env('HTTP_X_FORWARDED_FOR') != null) {
|
||||
$ipaddr = preg_replace('/(?:,.*)/', '', env('HTTP_X_FORWARDED_FOR'));
|
||||
} 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);
|
||||
}
|
||||
}
|
||||
return trim($ipaddr);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the referer that referred this request.
|
||||
*
|
||||
* @param boolean $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;
|
||||
}
|
||||
if (!empty($ref) && !empty($base)) {
|
||||
if ($local && strpos($ref, $base) === 0) {
|
||||
$ref = substr($ref, strlen($base));
|
||||
if ($ref[0] != '/') {
|
||||
$ref = '/' . $ref;
|
||||
}
|
||||
return $ref;
|
||||
} elseif (!$local) {
|
||||
return $ref;
|
||||
}
|
||||
}
|
||||
return '/';
|
||||
}
|
||||
|
||||
/**
|
||||
* Missing method handler, handles wrapping older style isAjax() type methods
|
||||
*
|
||||
* @param string $name The method called
|
||||
* @param array $params Array of parameters for the method call
|
||||
* @return mixed
|
||||
* @throws CakeException when an invalid method is called.
|
||||
*/
|
||||
public function __call($name, $params) {
|
||||
if (strpos($name, 'is') === 0) {
|
||||
$type = strtolower(substr($name, 2));
|
||||
return $this->is($type);
|
||||
}
|
||||
throw new CakeException(__d('cake_dev', 'Method %s does not exist', $name));
|
||||
}
|
||||
|
||||
/**
|
||||
* Magic get method allows access to parsed routing parameters directly on the object.
|
||||
*
|
||||
* Allows access to `$this->params['controller']` via `$this->controller`
|
||||
*
|
||||
* @param string $name The property being accessed.
|
||||
* @return mixed Either the value of the parameter or null.
|
||||
*/
|
||||
public function __get($name) {
|
||||
if (isset($this->params[$name])) {
|
||||
return $this->params[$name];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Magic isset method allows isset/empty checks
|
||||
* on routing parameters.
|
||||
*
|
||||
* @param string $name The property being accessed.
|
||||
* @return bool Existence
|
||||
*/
|
||||
public function __isset($name) {
|
||||
return isset($this->params[$name]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
public function is($type) {
|
||||
$type = strtolower($type);
|
||||
if (!isset($this->_detectors[$type])) {
|
||||
return false;
|
||||
}
|
||||
$detect = $this->_detectors[$type];
|
||||
if (isset($detect['env'])) {
|
||||
if (isset($detect['value'])) {
|
||||
return env($detect['env']) == $detect['value'];
|
||||
}
|
||||
if (isset($detect['pattern'])) {
|
||||
return (bool)preg_match($detect['pattern'], env($detect['env']));
|
||||
}
|
||||
if (isset($detect['options'])) {
|
||||
$pattern = '/' . implode('|', $detect['options']) . '/i';
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*
|
||||
* ### Environment value comparison
|
||||
*
|
||||
* An environment value comparison, compares a value fetched from `env()` to a known value
|
||||
* the environment value is equality checked against the provided value.
|
||||
*
|
||||
* e.g `addDetector('post', array('env' => 'REQUEST_METHOD', 'value' => 'POST'))`
|
||||
*
|
||||
* ### Pattern value comparison
|
||||
*
|
||||
* Pattern value comparison allows you to compare a value fetched from `env()` to a regular expression.
|
||||
*
|
||||
* e.g `addDetector('iphone', array('env' => 'HTTP_USER_AGENT', 'pattern' => '/iPhone/i'));`
|
||||
*
|
||||
* ### Option based comparison
|
||||
*
|
||||
* 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
|
||||
* receive the request object as its only parameter.
|
||||
*
|
||||
* e.g `addDetector('custom', array('callback' => array('SomeClass', 'somemethod')));`
|
||||
*
|
||||
* ### Request parameter detectors
|
||||
*
|
||||
* Allows for custom detectors on the request parameters.
|
||||
*
|
||||
* e.g `addDetector('post', array('param' => 'requested', 'value' => 1)`
|
||||
*
|
||||
* @param string $name The name of the detector.
|
||||
* @param array $options The options for the detector definition. See above.
|
||||
* @return void
|
||||
*/
|
||||
public function addDetector($name, $options) {
|
||||
$name = strtolower($name);
|
||||
if (isset($this->_detectors[$name]) && isset($options['options'])) {
|
||||
$options = Hash::merge($this->_detectors[$name], $options);
|
||||
}
|
||||
$this->_detectors[$name] = $options;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add parameters to the request's parsed parameter set. This will overwrite any existing parameters.
|
||||
* 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.
|
||||
*/
|
||||
public function addParams($params) {
|
||||
$this->params = array_merge($this->params, (array)$params);
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
public function addPaths($paths) {
|
||||
foreach (array('webroot', 'here', 'base') as $element) {
|
||||
if (isset($paths[$element])) {
|
||||
$this->{$element} = $paths[$element];
|
||||
}
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
public function here($base = true) {
|
||||
$url = $this->here;
|
||||
if (!empty($this->query)) {
|
||||
$url .= '?' . http_build_query($this->query, null, '&');
|
||||
}
|
||||
if (!$base) {
|
||||
$url = preg_replace('/^' . preg_quote($this->base, '/') . '/', '', $url, 1);
|
||||
}
|
||||
return $url;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read an HTTP header from the Request information.
|
||||
*
|
||||
* @param string $name Name of the header you want.
|
||||
* @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])) {
|
||||
return $_SERVER[$name];
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the HTTP method used for this request.
|
||||
* There are a few ways to specify a method.
|
||||
*
|
||||
* - If your client supports it you can use native HTTP methods.
|
||||
* - You can set the HTTP-X-Method-Override header.
|
||||
* - You can submit an input with the name `_method`
|
||||
*
|
||||
* Any of these 3 approaches can be used to set the HTTP method used
|
||||
* by CakePHP internally, and will effect the result of this method.
|
||||
*
|
||||
* @return string The name of the HTTP method used.
|
||||
*/
|
||||
public function method() {
|
||||
return env('REQUEST_METHOD');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the host that the request was handled on.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function 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.
|
||||
* While `example.co.uk` contains 2.
|
||||
* @return string Domain name without subdomains.
|
||||
*/
|
||||
public function domain($tldLength = 1) {
|
||||
$segments = explode('.', $this->host());
|
||||
$domain = array_slice($segments, -1 * ($tldLength + 1));
|
||||
return implode('.', $domain);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the subdomains for a host.
|
||||
*
|
||||
* @param integer $tldLength Number of segments your tld contains. For example: `example.com` contains 1 tld.
|
||||
* While `example.co.uk` contains 2.
|
||||
* @return array of subdomains.
|
||||
*/
|
||||
public function subdomains($tldLength = 1) {
|
||||
$segments = explode('.', $this->host());
|
||||
return array_slice($segments, 0, -1 * ($tldLength + 1));
|
||||
}
|
||||
|
||||
/**
|
||||
* Find out which content types the client accepts or check if they accept a
|
||||
* particular type of content.
|
||||
*
|
||||
* #### Get all types:
|
||||
*
|
||||
* `$this->request->accepts();`
|
||||
*
|
||||
* #### Check for a single type:
|
||||
*
|
||||
* `$this->request->accepts('application/json');`
|
||||
*
|
||||
* 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.
|
||||
* @return mixed Either an array of all the types the client accepts or a boolean if they accept the
|
||||
* provided type.
|
||||
*/
|
||||
public function accepts($type = null) {
|
||||
$raw = $this->parseAccept();
|
||||
$accept = array();
|
||||
foreach ($raw as $types) {
|
||||
$accept = array_merge($accept, $types);
|
||||
}
|
||||
if ($type === null) {
|
||||
return $accept;
|
||||
}
|
||||
return in_array($type, $accept);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse the HTTP_ACCEPT header and return a sorted array with content types
|
||||
* as the keys, and pref values as the values.
|
||||
*
|
||||
* Generally you want to use CakeRequest::accept() to get a simple list
|
||||
* of the accepted content types.
|
||||
*
|
||||
* @return array An array of prefValue => array(content/types)
|
||||
*/
|
||||
public function parseAccept() {
|
||||
$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);
|
||||
}
|
||||
if (!isset($accept[$prefValue])) {
|
||||
$accept[$prefValue] = array();
|
||||
}
|
||||
if ($prefValue) {
|
||||
$accept[$prefValue][] = $value;
|
||||
}
|
||||
}
|
||||
krsort($accept);
|
||||
return $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 If a $language is provided, a boolean. Otherwise the array of accepted languages.
|
||||
*/
|
||||
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);
|
||||
}
|
||||
|
||||
/**
|
||||
* Provides a read/write accessor for `$this->data`. Allows you
|
||||
* to use a syntax similar to `CakeSession` for reading post data.
|
||||
*
|
||||
* ## Reading values.
|
||||
*
|
||||
* `$request->data('Post.title');`
|
||||
*
|
||||
* When reading values you will get `null` for keys/values that do not exist.
|
||||
*
|
||||
* ## Writing values
|
||||
*
|
||||
* `$request->data('Post.title', 'New post!');`
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
public function data($name) {
|
||||
$args = func_get_args();
|
||||
if (count($args) == 2) {
|
||||
$this->data = Hash::insert($this->data, $name, $args[1]);
|
||||
return $this;
|
||||
}
|
||||
return Hash::get($this->data, $name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Read data from `php://input`. Useful when interacting with XML or JSON
|
||||
* request body content.
|
||||
*
|
||||
* Getting input with a decoding function:
|
||||
*
|
||||
* `$this->request->input('json_decode');`
|
||||
*
|
||||
* Getting input using a decoding function, and additional params:
|
||||
*
|
||||
* `$this->request->input('Xml::build', array('return' => 'DOMDocument'));`
|
||||
*
|
||||
* Any additional parameters are applied to the callback in the order they are given.
|
||||
*
|
||||
* @param string $callback A decoding callback that will convert the string data to another
|
||||
* representation. Leave empty to access the raw input data. You can also
|
||||
* supply additional parameters for the decoding callback using var args, see above.
|
||||
* @return The decoded/processed request data.
|
||||
*/
|
||||
public function input($callback = null) {
|
||||
$input = $this->_readInput();
|
||||
$args = func_get_args();
|
||||
if (!empty($args)) {
|
||||
$callback = array_shift($args);
|
||||
array_unshift($args, $input);
|
||||
return call_user_func_array($callback, $args);
|
||||
}
|
||||
return $input;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read data from php://input, mocked in tests.
|
||||
*
|
||||
* @return string contents of php://input
|
||||
*/
|
||||
protected function _readInput() {
|
||||
if (empty($this->_input)) {
|
||||
$fh = fopen('php://input', 'r');
|
||||
$content = stream_get_contents($fh);
|
||||
fclose($fh);
|
||||
$this->_input = $content;
|
||||
}
|
||||
return $this->_input;
|
||||
}
|
||||
|
||||
/**
|
||||
* Array access read implementation
|
||||
*
|
||||
* @param string $name Name of the key being accessed.
|
||||
* @return mixed
|
||||
*/
|
||||
public function offsetGet($name) {
|
||||
if (isset($this->params[$name])) {
|
||||
return $this->params[$name];
|
||||
}
|
||||
if ($name == 'url') {
|
||||
return $this->query;
|
||||
}
|
||||
if ($name == 'data') {
|
||||
return $this->data;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Array access write implementation
|
||||
*
|
||||
* @param string $name Name of the key being written
|
||||
* @param mixed $value The value being written.
|
||||
* @return void
|
||||
*/
|
||||
public function offsetSet($name, $value) {
|
||||
$this->params[$name] = $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Array access isset() implementation
|
||||
*
|
||||
* @param string $name thing to check.
|
||||
* @return boolean
|
||||
*/
|
||||
public function offsetExists($name) {
|
||||
return isset($this->params[$name]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Array access unset() implementation
|
||||
*
|
||||
* @param string $name Name to unset.
|
||||
* @return void
|
||||
*/
|
||||
public function offsetUnset($name) {
|
||||
unset($this->params[$name]);
|
||||
}
|
||||
|
||||
}
|
||||
1159
lib/Cake/Network/CakeResponse.php
Normal file
1159
lib/Cake/Network/CakeResponse.php
Normal file
File diff suppressed because it is too large
Load diff
282
lib/Cake/Network/CakeSocket.php
Normal file
282
lib/Cake/Network/CakeSocket.php
Normal file
|
|
@ -0,0 +1,282 @@
|
|||
<?php
|
||||
/**
|
||||
* Cake Socket connection class.
|
||||
*
|
||||
* PHP 5
|
||||
*
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright 2005-2012, 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)
|
||||
*/
|
||||
|
||||
App::uses('Validation', 'Utility');
|
||||
|
||||
/**
|
||||
* Cake network socket connection class.
|
||||
*
|
||||
* Core base class for network communication.
|
||||
*
|
||||
* @package Cake.Network
|
||||
*/
|
||||
class CakeSocket {
|
||||
|
||||
/**
|
||||
* Object description
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $description = 'Remote DataSource Network Socket Interface';
|
||||
|
||||
/**
|
||||
* Base configuration settings for the socket connection
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $_baseConfig = array(
|
||||
'persistent' => false,
|
||||
'host' => 'localhost',
|
||||
'protocol' => 'tcp',
|
||||
'port' => 80,
|
||||
'timeout' => 30
|
||||
);
|
||||
|
||||
/**
|
||||
* Configuration settings for the socket connection
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public $config = array();
|
||||
|
||||
/**
|
||||
* Reference to socket connection resource
|
||||
*
|
||||
* @var resource
|
||||
*/
|
||||
public $connection = null;
|
||||
|
||||
/**
|
||||
* This boolean contains the current state of the CakeSocket class
|
||||
*
|
||||
* @var boolean
|
||||
*/
|
||||
public $connected = false;
|
||||
|
||||
/**
|
||||
* This variable contains an array with the last error number (num) and string (str)
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public $lastError = array();
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param array $config Socket configuration, which will be merged with the base configuration
|
||||
* @see CakeSocket::$_baseConfig
|
||||
*/
|
||||
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.
|
||||
*
|
||||
* @return boolean Success
|
||||
* @throws SocketException
|
||||
*/
|
||||
public function connect() {
|
||||
if ($this->connection != null) {
|
||||
$this->disconnect();
|
||||
}
|
||||
|
||||
$scheme = null;
|
||||
if (isset($this->config['request']) && $this->config['request']['uri']['scheme'] == 'https') {
|
||||
$scheme = 'ssl://';
|
||||
}
|
||||
|
||||
//@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']);
|
||||
}
|
||||
//@codingStandardsIgnoreEnd
|
||||
|
||||
if (!empty($errNum) || !empty($errStr)) {
|
||||
$this->setLastError($errNum, $errStr);
|
||||
throw new SocketException($errStr, $errNum);
|
||||
}
|
||||
|
||||
$this->connected = is_resource($this->connection);
|
||||
if ($this->connected) {
|
||||
stream_set_timeout($this->connection, $this->config['timeout']);
|
||||
}
|
||||
return $this->connected;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the host name of the current connection.
|
||||
*
|
||||
* @return string Host name
|
||||
*/
|
||||
public function host() {
|
||||
if (Validation::ip($this->config['host'])) {
|
||||
return gethostbyaddr($this->config['host']);
|
||||
}
|
||||
return gethostbyaddr($this->address());
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the IP address of the current connection.
|
||||
*
|
||||
* @return string IP address
|
||||
*/
|
||||
public function address() {
|
||||
if (Validation::ip($this->config['host'])) {
|
||||
return $this->config['host'];
|
||||
}
|
||||
return gethostbyname($this->config['host']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all IP addresses associated with the current connection.
|
||||
*
|
||||
* @return array IP addresses
|
||||
*/
|
||||
public function addresses() {
|
||||
if (Validation::ip($this->config['host'])) {
|
||||
return array($this->config['host']);
|
||||
}
|
||||
return gethostbynamel($this->config['host']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the last error as a string.
|
||||
*
|
||||
* @return string Last error
|
||||
*/
|
||||
public function lastError() {
|
||||
if (!empty($this->lastError)) {
|
||||
return $this->lastError['num'] . ': ' . $this->lastError['str'];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the last error.
|
||||
*
|
||||
* @param integer $errNum Error code
|
||||
* @param string $errStr Error string
|
||||
* @return void
|
||||
*/
|
||||
public function setLastError($errNum, $errStr) {
|
||||
$this->lastError = array('num' => $errNum, 'str' => $errStr);
|
||||
}
|
||||
|
||||
/**
|
||||
* Write data to the socket.
|
||||
*
|
||||
* @param string $data The data to write to the socket
|
||||
* @return boolean Success
|
||||
*/
|
||||
public function write($data) {
|
||||
if (!$this->connected) {
|
||||
if (!$this->connect()) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
$totalBytes = strlen($data);
|
||||
for ($written = 0, $rv = 0; $written < $totalBytes; $written += $rv) {
|
||||
$rv = fwrite($this->connection, substr($data, $written));
|
||||
if ($rv === false || $rv === 0) {
|
||||
return $written;
|
||||
}
|
||||
}
|
||||
return $written;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read 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
|
||||
* @return mixed Socket data
|
||||
*/
|
||||
public function read($length = 1024) {
|
||||
if (!$this->connected) {
|
||||
if (!$this->connect()) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (!feof($this->connection)) {
|
||||
$buffer = fread($this->connection, $length);
|
||||
$info = stream_get_meta_data($this->connection);
|
||||
if ($info['timed_out']) {
|
||||
$this->setLastError(E_WARNING, __d('cake_dev', 'Connection timed out'));
|
||||
return false;
|
||||
}
|
||||
return $buffer;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Disconnect the socket from the current connection.
|
||||
*
|
||||
* @return boolean Success
|
||||
*/
|
||||
public function disconnect() {
|
||||
if (!is_resource($this->connection)) {
|
||||
$this->connected = false;
|
||||
return true;
|
||||
}
|
||||
$this->connected = !fclose($this->connection);
|
||||
|
||||
if (!$this->connected) {
|
||||
$this->connection = null;
|
||||
}
|
||||
return !$this->connected;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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)
|
||||
*
|
||||
* @param array $state Array with key and values to reset
|
||||
* @return boolean True on success
|
||||
*/
|
||||
public function reset($state = null) {
|
||||
if (empty($state)) {
|
||||
static $initalState = array();
|
||||
if (empty($initalState)) {
|
||||
$initalState = get_class_vars(__CLASS__);
|
||||
}
|
||||
$state = $initalState;
|
||||
}
|
||||
|
||||
foreach ($state as $property => $value) {
|
||||
$this->{$property} = $value;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
76
lib/Cake/Network/Email/AbstractTransport.php
Normal file
76
lib/Cake/Network/Email/AbstractTransport.php
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
<?php
|
||||
/**
|
||||
* Abstract send email
|
||||
*
|
||||
* PHP 5
|
||||
*
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright 2005-2012, 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)
|
||||
*/
|
||||
|
||||
/**
|
||||
* Abstract transport for sending email
|
||||
*
|
||||
* @package Cake.Network.Email
|
||||
*/
|
||||
abstract class AbstractTransport {
|
||||
|
||||
/**
|
||||
* Configurations
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $_config = array();
|
||||
|
||||
/**
|
||||
* Send mail
|
||||
*
|
||||
* @params CakeEmail $email
|
||||
* @return array
|
||||
*/
|
||||
abstract public function send(CakeEmail $email);
|
||||
|
||||
/**
|
||||
* Set the config
|
||||
*
|
||||
* @param array $config
|
||||
* @return array Returns configs
|
||||
*/
|
||||
public function config($config = null) {
|
||||
if (is_array($config)) {
|
||||
$this->_config = $config;
|
||||
}
|
||||
return $this->_config;
|
||||
}
|
||||
|
||||
/**
|
||||
* Help to convert headers in string
|
||||
*
|
||||
* @param array $headers Headers in format key => value
|
||||
* @param string $eol
|
||||
* @return string
|
||||
*/
|
||||
protected function _headersToString($headers, $eol = "\r\n") {
|
||||
$out = '';
|
||||
foreach ($headers as $key => $value) {
|
||||
if ($value === false || $value === null || $value === '') {
|
||||
continue;
|
||||
}
|
||||
$out .= $key . ': ' . $value . $eol;
|
||||
}
|
||||
if (!empty($out)) {
|
||||
$out = substr($out, 0, -1 * strlen($eol));
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
|
||||
}
|
||||
1591
lib/Cake/Network/Email/CakeEmail.php
Normal file
1591
lib/Cake/Network/Email/CakeEmail.php
Normal file
File diff suppressed because it is too large
Load diff
41
lib/Cake/Network/Email/DebugTransport.php
Normal file
41
lib/Cake/Network/Email/DebugTransport.php
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
<?php
|
||||
/**
|
||||
* 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)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright 2005-2012, 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)
|
||||
*/
|
||||
|
||||
/**
|
||||
* Debug Transport class, useful for emulate the email sending process and inspect the resulted
|
||||
* email message before actually send it during development
|
||||
*
|
||||
* @package Cake.Network.Email
|
||||
*/
|
||||
class DebugTransport extends AbstractTransport {
|
||||
|
||||
/**
|
||||
* Send mail
|
||||
*
|
||||
* @param CakeEmail $email CakeEmail
|
||||
* @return array
|
||||
*/
|
||||
public function send(CakeEmail $email) {
|
||||
$headers = $email->getHeaders(array('from', 'sender', 'replyTo', 'readReceipt', 'returnPath', 'to', 'cc', 'subject'));
|
||||
$headers = $this->_headersToString($headers);
|
||||
$message = implode("\r\n", (array)$email->message());
|
||||
return array('headers' => $headers, 'message' => $message);
|
||||
}
|
||||
|
||||
}
|
||||
73
lib/Cake/Network/Email/MailTransport.php
Normal file
73
lib/Cake/Network/Email/MailTransport.php
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
<?php
|
||||
/**
|
||||
* 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)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright 2005-2012, 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)
|
||||
*/
|
||||
|
||||
/**
|
||||
* Send mail using mail() function
|
||||
*
|
||||
* @package Cake.Network.Email
|
||||
*/
|
||||
class MailTransport extends AbstractTransport {
|
||||
|
||||
/**
|
||||
* Send mail
|
||||
*
|
||||
* @param CakeEmail $email CakeEmail
|
||||
* @return array
|
||||
* @throws SocketException When mail cannot be sent.
|
||||
*/
|
||||
public function send(CakeEmail $email) {
|
||||
$eol = PHP_EOL;
|
||||
if (isset($this->_config['eol'])) {
|
||||
$eol = $this->_config['eol'];
|
||||
}
|
||||
$headers = $email->getHeaders(array('from', 'sender', 'replyTo', 'readReceipt', 'returnPath', 'to', 'cc', 'bcc'));
|
||||
$to = $headers['To'];
|
||||
unset($headers['To']);
|
||||
$headers = $this->_headersToString($headers, $eol);
|
||||
$message = implode($eol, $email->message());
|
||||
|
||||
$params = isset($this->_config['additionalParameters']) ? $this->_config['additionalParameters'] : null;
|
||||
$this->_mail($to, $email->subject(), $message, $headers, $params);
|
||||
return array('headers' => $headers, 'message' => $message);
|
||||
}
|
||||
|
||||
/**
|
||||
* Wraps internal function mail() and throws exception instead of errors if anything goes wrong
|
||||
*
|
||||
* @param string $to email's recipient
|
||||
* @param string $subject email's subject
|
||||
* @param string $message email's body
|
||||
* @param string $headers email's custom headers
|
||||
* @param string $params additional params for sending email, will be ignored when in safe_mode
|
||||
* @throws SocketException if mail could not be sent
|
||||
* @return void
|
||||
*/
|
||||
protected function _mail($to, $subject, $message, $headers, $params = null) {
|
||||
if (ini_get('safe_mode')) {
|
||||
//@codingStandardsIgnoreStart
|
||||
if (!@mail($to, $subject, $message, $headers)) {
|
||||
throw new SocketException(__d('cake_dev', 'Could not send email.'));
|
||||
}
|
||||
} elseif (!@mail($to, $subject, $message, $headers, $params)) {
|
||||
//@codingStandardsIgnoreEnd
|
||||
throw new SocketException(__d('cake_dev', 'Could not send email.'));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
240
lib/Cake/Network/Email/SmtpTransport.php
Normal file
240
lib/Cake/Network/Email/SmtpTransport.php
Normal file
|
|
@ -0,0 +1,240 @@
|
|||
<?php
|
||||
/**
|
||||
* 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)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright 2005-2012, 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)
|
||||
*/
|
||||
|
||||
App::uses('CakeSocket', 'Network');
|
||||
|
||||
/**
|
||||
* Send mail using SMTP protocol
|
||||
*
|
||||
* @package Cake.Network.Email
|
||||
*/
|
||||
class SmtpTransport extends AbstractTransport {
|
||||
|
||||
/**
|
||||
* Socket to SMTP server
|
||||
*
|
||||
* @var CakeSocket
|
||||
*/
|
||||
protected $_socket;
|
||||
|
||||
/**
|
||||
* CakeEmail
|
||||
*
|
||||
* @var CakeEmail
|
||||
*/
|
||||
protected $_cakeEmail;
|
||||
|
||||
/**
|
||||
* Content of email to return
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $_content;
|
||||
|
||||
/**
|
||||
* Send mail
|
||||
*
|
||||
* @param CakeEmail $email CakeEmail
|
||||
* @return array
|
||||
* @throws SocketException
|
||||
*/
|
||||
public function send(CakeEmail $email) {
|
||||
$this->_cakeEmail = $email;
|
||||
|
||||
$this->_connect();
|
||||
$this->_auth();
|
||||
$this->_sendRcpt();
|
||||
$this->_sendData();
|
||||
$this->_disconnect();
|
||||
|
||||
return $this->_content;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the configuration
|
||||
*
|
||||
* @param array $config
|
||||
* @return void
|
||||
*/
|
||||
public function config($config = array()) {
|
||||
$default = array(
|
||||
'host' => 'localhost',
|
||||
'port' => 25,
|
||||
'timeout' => 30,
|
||||
'username' => null,
|
||||
'password' => null,
|
||||
'client' => null
|
||||
);
|
||||
$this->_config = $config + $default;
|
||||
}
|
||||
|
||||
/**
|
||||
* Connect to SMTP Server
|
||||
*
|
||||
* @return void
|
||||
* @throws SocketException
|
||||
*/
|
||||
protected function _connect() {
|
||||
$this->_generateSocket();
|
||||
if (!$this->_socket->connect()) {
|
||||
throw new SocketException(__d('cake_dev', 'Unable to connect to SMTP server.'));
|
||||
}
|
||||
$this->_smtpSend(null, '220');
|
||||
|
||||
if (isset($this->_config['client'])) {
|
||||
$host = $this->_config['client'];
|
||||
} elseif ($httpHost = env('HTTP_HOST')) {
|
||||
list($host) = explode(':', $httpHost);
|
||||
} else {
|
||||
$host = 'localhost';
|
||||
}
|
||||
|
||||
try {
|
||||
$this->_smtpSend("EHLO {$host}", '250');
|
||||
} catch (SocketException $e) {
|
||||
try {
|
||||
$this->_smtpSend("HELO {$host}", '250');
|
||||
} catch (SocketException $e2) {
|
||||
throw new SocketException(__d('cake_dev', 'SMTP server did not accept the connection.'));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Send authentication
|
||||
*
|
||||
* @return void
|
||||
* @throws SocketException
|
||||
*/
|
||||
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')) {
|
||||
throw new SocketException(__d('cake_dev', 'SMTP server did not accept the username.'));
|
||||
}
|
||||
if (!$this->_smtpSend(base64_encode($this->_config['password']), '235')) {
|
||||
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.'));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Send emails
|
||||
*
|
||||
* @return void
|
||||
* @throws SocketException
|
||||
*/
|
||||
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 . '>');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Send Data
|
||||
*
|
||||
* @return void
|
||||
* @throws SocketException
|
||||
*/
|
||||
protected function _sendData() {
|
||||
$this->_smtpSend('DATA', '354');
|
||||
|
||||
$headers = $this->_cakeEmail->getHeaders(array('from', 'sender', 'replyTo', 'readReceipt', 'returnPath', 'to', 'cc', 'subject'));
|
||||
$headers = $this->_headersToString($headers);
|
||||
$lines = $this->_cakeEmail->message();
|
||||
$messages = array();
|
||||
foreach ($lines as $line) {
|
||||
if ((!empty($line)) && ($line[0] === '.')) {
|
||||
$messages[] = '.' . $line;
|
||||
} else {
|
||||
$messages[] = $line;
|
||||
}
|
||||
}
|
||||
$message = implode("\r\n", $messages);
|
||||
$this->_smtpSend($headers . "\r\n\r\n" . $message . "\r\n\r\n\r\n.");
|
||||
$this->_content = array('headers' => $headers, 'message' => $message);
|
||||
}
|
||||
|
||||
/**
|
||||
* Disconnect
|
||||
*
|
||||
* @return void
|
||||
* @throws SocketException
|
||||
*/
|
||||
protected function _disconnect() {
|
||||
$this->_smtpSend('QUIT', false);
|
||||
$this->_socket->disconnect();
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method to generate socket
|
||||
*
|
||||
* @return void
|
||||
* @throws SocketException
|
||||
*/
|
||||
protected function _generateSocket() {
|
||||
$this->_socket = new CakeSocket($this->_config);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
* @throws SocketException
|
||||
*/
|
||||
protected function _smtpSend($data, $checkCode = '250') {
|
||||
if (!is_null($data)) {
|
||||
$this->_socket->write($data . "\r\n");
|
||||
}
|
||||
while ($checkCode !== false) {
|
||||
$response = '';
|
||||
$startTime = time();
|
||||
while (substr($response, -2) !== "\r\n" && ((time() - $startTime) < $this->_config['timeout'])) {
|
||||
$response .= $this->_socket->read();
|
||||
}
|
||||
if (substr($response, -2) !== "\r\n") {
|
||||
throw new SocketException(__d('cake_dev', 'SMTP timeout.'));
|
||||
}
|
||||
$responseLines = explode("\r\n", rtrim($response, "\r\n"));
|
||||
$response = end($responseLines);
|
||||
|
||||
if (preg_match('/^(' . $checkCode . ')(.)/', $response, $code)) {
|
||||
if ($code[2] === '-') {
|
||||
continue;
|
||||
}
|
||||
return $code[1];
|
||||
}
|
||||
throw new SocketException(__d('cake_dev', 'SMTP Error: %s', $response));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
66
lib/Cake/Network/Http/BasicAuthentication.php
Normal file
66
lib/Cake/Network/Http/BasicAuthentication.php
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
<?php
|
||||
/**
|
||||
* Basic authentication
|
||||
*
|
||||
* PHP 5
|
||||
*
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright 2005-2012, 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)
|
||||
*/
|
||||
|
||||
/**
|
||||
* Basic authentication
|
||||
*
|
||||
* @package Cake.Network.Http
|
||||
*/
|
||||
class BasicAuthentication {
|
||||
|
||||
/**
|
||||
* Authentication
|
||||
*
|
||||
* @param HttpSocket $http
|
||||
* @param array $authInfo
|
||||
* @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']);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Proxy Authentication
|
||||
*
|
||||
* @param HttpSocket $http
|
||||
* @param array $proxyInfo
|
||||
* @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']);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate basic [proxy] authentication header
|
||||
*
|
||||
* @param string $user
|
||||
* @param string $pass
|
||||
* @return string
|
||||
*/
|
||||
protected static function _generateHeader($user, $pass) {
|
||||
return 'Basic ' . base64_encode($user . ':' . $pass);
|
||||
}
|
||||
|
||||
}
|
||||
105
lib/Cake/Network/Http/DigestAuthentication.php
Normal file
105
lib/Cake/Network/Http/DigestAuthentication.php
Normal file
|
|
@ -0,0 +1,105 @@
|
|||
<?php
|
||||
/**
|
||||
* Digest authentication
|
||||
*
|
||||
* PHP 5
|
||||
*
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright 2005-2012, 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)
|
||||
*/
|
||||
|
||||
/**
|
||||
* Digest authentication
|
||||
*
|
||||
* @package Cake.Network.Http
|
||||
*/
|
||||
class DigestAuthentication {
|
||||
|
||||
/**
|
||||
* Authentication
|
||||
*
|
||||
* @param HttpSocket $http
|
||||
* @param array $authInfo
|
||||
* @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)) {
|
||||
return;
|
||||
}
|
||||
$http->request['header']['Authorization'] = self::_generateHeader($http, $authInfo);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve information about the authentication
|
||||
*
|
||||
* @param HttpSocket $http
|
||||
* @param array $authInfo
|
||||
* @return boolean
|
||||
*/
|
||||
protected static function _getServerInformation(HttpSocket $http, &$authInfo) {
|
||||
$originalRequest = $http->request;
|
||||
$http->configAuth(false);
|
||||
$http->request($http->request);
|
||||
$http->request = $originalRequest;
|
||||
$http->configAuth('Digest', $authInfo);
|
||||
|
||||
if (empty($http->response['header']['WWW-Authenticate'])) {
|
||||
return false;
|
||||
}
|
||||
preg_match_all('@(\w+)=(?:(?:")([^"]+)"|([^\s,$]+))@', $http->response['header']['WWW-Authenticate'], $matches, PREG_SET_ORDER);
|
||||
foreach ($matches as $match) {
|
||||
$authInfo[$match[1]] = $match[2];
|
||||
}
|
||||
if (!empty($authInfo['qop']) && empty($authInfo['nc'])) {
|
||||
$authInfo['nc'] = 1;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate the header Authorization
|
||||
*
|
||||
* @param HttpSocket $http
|
||||
* @param array $authInfo
|
||||
* @return string
|
||||
*/
|
||||
protected static function _generateHeader(HttpSocket $http, &$authInfo) {
|
||||
$a1 = md5($authInfo['user'] . ':' . $authInfo['realm'] . ':' . $authInfo['pass']);
|
||||
$a2 = md5($http->request['method'] . ':' . $http->request['uri']['path']);
|
||||
|
||||
if (empty($authInfo['qop'])) {
|
||||
$response = md5($a1 . ':' . $authInfo['nonce'] . ':' . $a2);
|
||||
} else {
|
||||
$authInfo['cnonce'] = uniqid();
|
||||
$nc = sprintf('%08x', $authInfo['nc']++);
|
||||
$response = md5($a1 . ':' . $authInfo['nonce'] . ':' . $nc . ':' . $authInfo['cnonce'] . ':auth:' . $a2);
|
||||
}
|
||||
|
||||
$authHeader = 'Digest ';
|
||||
$authHeader .= 'username="' . str_replace(array('\\', '"'), array('\\\\', '\\"'), $authInfo['user']) . '", ';
|
||||
$authHeader .= 'realm="' . $authInfo['realm'] . '", ';
|
||||
$authHeader .= 'nonce="' . $authInfo['nonce'] . '", ';
|
||||
$authHeader .= 'uri="' . $http->request['uri']['path'] . '", ';
|
||||
$authHeader .= 'response="' . $response . '"';
|
||||
if (!empty($authInfo['opaque'])) {
|
||||
$authHeader .= ', opaque="' . $authInfo['opaque'] . '"';
|
||||
}
|
||||
if (!empty($authInfo['qop'])) {
|
||||
$authHeader .= ', qop="auth", nc=' . $nc . ', cnonce="' . $authInfo['cnonce'] . '"';
|
||||
}
|
||||
return $authHeader;
|
||||
}
|
||||
|
||||
}
|
||||
438
lib/Cake/Network/Http/HttpResponse.php
Normal file
438
lib/Cake/Network/Http/HttpResponse.php
Normal file
|
|
@ -0,0 +1,438 @@
|
|||
<?php
|
||||
/**
|
||||
* HTTP Response from HttpSocket.
|
||||
*
|
||||
* PHP 5
|
||||
*
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright 2005-2012, 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)
|
||||
*/
|
||||
|
||||
/**
|
||||
* HTTP Response from HttpSocket.
|
||||
*
|
||||
* @package Cake.Network.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();
|
||||
}
|
||||
|
||||
}
|
||||
974
lib/Cake/Network/Http/HttpSocket.php
Normal file
974
lib/Cake/Network/Http/HttpSocket.php
Normal file
|
|
@ -0,0 +1,974 @@
|
|||
<?php
|
||||
/**
|
||||
* HTTP Socket connection class.
|
||||
*
|
||||
* PHP 5
|
||||
*
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright 2005-2012, 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)
|
||||
*/
|
||||
App::uses('CakeSocket', 'Network');
|
||||
App::uses('Router', 'Routing');
|
||||
|
||||
/**
|
||||
* Cake 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.
|
||||
*
|
||||
* @package Cake.Network.Http
|
||||
*/
|
||||
class HttpSocket extends CakeSocket {
|
||||
|
||||
/**
|
||||
* When one activates the $quirksMode by setting it to true, all checks meant to
|
||||
* enforce RFC 2616 (HTTP/1.1 specs).
|
||||
* will be disabled and additional measures to deal with non-standard responses will be enabled.
|
||||
*
|
||||
* @var boolean
|
||||
*/
|
||||
public $quirksMode = false;
|
||||
|
||||
/**
|
||||
* Contain information about the last request (read only)
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public $request = array(
|
||||
'method' => 'GET',
|
||||
'uri' => array(
|
||||
'scheme' => 'http',
|
||||
'host' => null,
|
||||
'port' => 80,
|
||||
'user' => null,
|
||||
'pass' => null,
|
||||
'path' => null,
|
||||
'query' => null,
|
||||
'fragment' => null
|
||||
),
|
||||
'version' => '1.1',
|
||||
'body' => '',
|
||||
'line' => null,
|
||||
'header' => array(
|
||||
'Connection' => 'close',
|
||||
'User-Agent' => 'CakePHP'
|
||||
),
|
||||
'raw' => null,
|
||||
'redirect' => false,
|
||||
'cookies' => array()
|
||||
);
|
||||
|
||||
/**
|
||||
* Contain information about the last response (read only)
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public $response = null;
|
||||
|
||||
/**
|
||||
* Response classname
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $responseClass = 'HttpResponse';
|
||||
|
||||
/**
|
||||
* Configuration settings for the HttpSocket and the requests
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public $config = array(
|
||||
'persistent' => false,
|
||||
'host' => 'localhost',
|
||||
'protocol' => 'tcp',
|
||||
'port' => 80,
|
||||
'timeout' => 30,
|
||||
'request' => array(
|
||||
'uri' => array(
|
||||
'scheme' => array('http', 'https'),
|
||||
'host' => 'localhost',
|
||||
'port' => array(80, 443)
|
||||
),
|
||||
'redirect' => false,
|
||||
'cookies' => array()
|
||||
)
|
||||
);
|
||||
|
||||
/**
|
||||
* Authentication settings
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $_auth = array();
|
||||
|
||||
/**
|
||||
* Proxy settings
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $_proxy = array();
|
||||
|
||||
/**
|
||||
* Resource to receive the content of request
|
||||
*
|
||||
* @var mixed
|
||||
*/
|
||||
protected $_contentResource = null;
|
||||
|
||||
/**
|
||||
* Build an HTTP Socket using the specified configuration.
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
public function __construct($config = array()) {
|
||||
if (is_string($config)) {
|
||||
$this->_configUri($config);
|
||||
} elseif (is_array($config)) {
|
||||
if (isset($config['request']['uri']) && is_string($config['request']['uri'])) {
|
||||
$this->_configUri($config['request']['uri']);
|
||||
unset($config['request']['uri']);
|
||||
}
|
||||
$this->config = Hash::merge($this->config, $config);
|
||||
}
|
||||
parent::__construct($this->config);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set authentication settings.
|
||||
*
|
||||
* 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:
|
||||
*
|
||||
* `$http->configAuth();`
|
||||
*
|
||||
* @param string $method Authentication method (ie. Basic, Digest). If empty, disable authentication
|
||||
* @param string|array $user Username for authentication. Can be an array with settings to authentication class
|
||||
* @param string $pass Password for authentication
|
||||
* @return void
|
||||
*/
|
||||
public function configAuth($method, $user = null, $pass = null) {
|
||||
if (empty($method)) {
|
||||
$this->_auth = array();
|
||||
return;
|
||||
}
|
||||
if (is_array($user)) {
|
||||
$this->_auth = array($method => $user);
|
||||
return;
|
||||
}
|
||||
$this->_auth = array($method => compact('user', 'pass'));
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 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
|
||||
* @return void
|
||||
*/
|
||||
public function configProxy($host, $port = 3128, $method = null, $user = null, $pass = null) {
|
||||
if (empty($host)) {
|
||||
$this->_proxy = array();
|
||||
return;
|
||||
}
|
||||
if (is_array($host)) {
|
||||
$this->_proxy = $host + array('host' => null);
|
||||
return;
|
||||
}
|
||||
$this->_proxy = compact('host', 'port', 'method', 'user', 'pass');
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
* @return void
|
||||
* @throws SocketException
|
||||
*/
|
||||
public function setContentResource($resource) {
|
||||
if ($resource === false) {
|
||||
$this->_contentResource = null;
|
||||
return;
|
||||
}
|
||||
if (!is_resource($resource)) {
|
||||
throw new SocketException(__d('cake_dev', 'Invalid resource.'));
|
||||
}
|
||||
$this->_contentResource = $resource;
|
||||
}
|
||||
|
||||
/**
|
||||
* Issue the specified request. HttpSocket::get() and HttpSocket::post() wrap this
|
||||
* 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
|
||||
* @throws SocketException
|
||||
*/
|
||||
public function request($request = array()) {
|
||||
$this->reset(false);
|
||||
|
||||
if (is_string($request)) {
|
||||
$request = array('uri' => $request);
|
||||
} elseif (!is_array($request)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!isset($request['uri'])) {
|
||||
$request['uri'] = null;
|
||||
}
|
||||
$uri = $this->_parseUri($request['uri']);
|
||||
if (!isset($uri['host'])) {
|
||||
$host = $this->config['host'];
|
||||
}
|
||||
if (isset($request['host'])) {
|
||||
$host = $request['host'];
|
||||
unset($request['host']);
|
||||
}
|
||||
$request['uri'] = $this->url($request['uri']);
|
||||
$request['uri'] = $this->_parseUri($request['uri'], true);
|
||||
$this->request = Hash::merge($this->request, array_diff_key($this->config['request'], array('cookies' => true)), $request);
|
||||
|
||||
$this->_configUri($this->request['uri']);
|
||||
|
||||
$Host = $this->request['uri']['host'];
|
||||
if (!empty($this->config['request']['cookies'][$Host])) {
|
||||
if (!isset($this->request['cookies'])) {
|
||||
$this->request['cookies'] = array();
|
||||
}
|
||||
if (!isset($request['cookies'])) {
|
||||
$request['cookies'] = array();
|
||||
}
|
||||
$this->request['cookies'] = array_merge($this->request['cookies'], $this->config['request']['cookies'][$Host], $request['cookies']);
|
||||
}
|
||||
|
||||
if (isset($host)) {
|
||||
$this->config['host'] = $host;
|
||||
}
|
||||
$this->_setProxy();
|
||||
$this->request['proxy'] = $this->_proxy;
|
||||
|
||||
$cookies = null;
|
||||
|
||||
if (is_array($this->request['header'])) {
|
||||
if (!empty($this->request['cookies'])) {
|
||||
$cookies = $this->buildCookies($this->request['cookies']);
|
||||
}
|
||||
$scheme = '';
|
||||
$port = 0;
|
||||
if (isset($this->request['uri']['scheme'])) {
|
||||
$scheme = $this->request['uri']['scheme'];
|
||||
}
|
||||
if (isset($this->request['uri']['port'])) {
|
||||
$port = $this->request['uri']['port'];
|
||||
}
|
||||
if (
|
||||
($scheme === 'http' && $port != 80) ||
|
||||
($scheme === 'https' && $port != 443) ||
|
||||
($port != 80 && $port != 443)
|
||||
) {
|
||||
$Host .= ':' . $port;
|
||||
}
|
||||
$this->request['header'] = array_merge(compact('Host'), $this->request['header']);
|
||||
}
|
||||
|
||||
if (isset($this->request['uri']['user'], $this->request['uri']['pass'])) {
|
||||
$this->configAuth('Basic', $this->request['uri']['user'], $this->request['uri']['pass']);
|
||||
}
|
||||
$this->_setAuth();
|
||||
$this->request['auth'] = $this->_auth;
|
||||
|
||||
if (is_array($this->request['body'])) {
|
||||
$this->request['body'] = http_build_query($this->request['body']);
|
||||
}
|
||||
|
||||
if (!empty($this->request['body']) && !isset($this->request['header']['Content-Type'])) {
|
||||
$this->request['header']['Content-Type'] = 'application/x-www-form-urlencoded';
|
||||
}
|
||||
|
||||
if (!empty($this->request['body']) && !isset($this->request['header']['Content-Length'])) {
|
||||
$this->request['header']['Content-Length'] = strlen($this->request['body']);
|
||||
}
|
||||
|
||||
$connectionType = null;
|
||||
if (isset($this->request['header']['Connection'])) {
|
||||
$connectionType = $this->request['header']['Connection'];
|
||||
}
|
||||
$this->request['header'] = $this->_buildHeader($this->request['header']) . $cookies;
|
||||
|
||||
if (empty($this->request['line'])) {
|
||||
$this->request['line'] = $this->_buildRequestLine($this->request);
|
||||
}
|
||||
|
||||
if ($this->quirksMode === false && $this->request['line'] === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->request['raw'] = '';
|
||||
if ($this->request['line'] !== false) {
|
||||
$this->request['raw'] = $this->request['line'];
|
||||
}
|
||||
|
||||
if ($this->request['header'] !== false) {
|
||||
$this->request['raw'] .= $this->request['header'];
|
||||
}
|
||||
|
||||
$this->request['raw'] .= "\r\n";
|
||||
$this->request['raw'] .= $this->request['body'];
|
||||
$this->write($this->request['raw']);
|
||||
|
||||
$response = null;
|
||||
$inHeader = true;
|
||||
while ($data = $this->read()) {
|
||||
if ($this->_contentResource) {
|
||||
if ($inHeader) {
|
||||
$response .= $data;
|
||||
$pos = strpos($response, "\r\n\r\n");
|
||||
if ($pos !== false) {
|
||||
$pos += 4;
|
||||
$data = substr($response, $pos);
|
||||
fwrite($this->_contentResource, $data);
|
||||
|
||||
$response = substr($response, 0, $pos);
|
||||
$inHeader = false;
|
||||
}
|
||||
} else {
|
||||
fwrite($this->_contentResource, $data);
|
||||
fflush($this->_contentResource);
|
||||
}
|
||||
} else {
|
||||
$response .= $data;
|
||||
}
|
||||
}
|
||||
|
||||
if ($connectionType === 'close') {
|
||||
$this->disconnect();
|
||||
}
|
||||
|
||||
list($plugin, $responseClass) = pluginSplit($this->responseClass, true);
|
||||
App::uses($responseClass, $plugin . 'Network/Http');
|
||||
if (!class_exists($responseClass)) {
|
||||
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();
|
||||
}
|
||||
$this->config['request']['cookies'][$Host] = array_merge($this->config['request']['cookies'][$Host], $this->response->cookies);
|
||||
}
|
||||
|
||||
if ($this->request['redirect'] && $this->response->isRedirect()) {
|
||||
$request['uri'] = trim(urldecode($this->response->getHeader('Location')), '=');
|
||||
$request['redirect'] = is_int($this->request['redirect']) ? $this->request['redirect'] - 1 : $this->request['redirect'];
|
||||
$this->response = $this->request($request);
|
||||
}
|
||||
|
||||
return $this->response;
|
||||
}
|
||||
|
||||
/**
|
||||
* Issues a GET request to the specified URI, query, and request.
|
||||
*
|
||||
* Using a string uri and an array of query string parameters:
|
||||
*
|
||||
* `$response = $http->get('http://google.com/search', array('q' => 'cakephp', 'client' => 'safari'));`
|
||||
*
|
||||
* Would do a GET request to `http://google.com/search?q=cakephp&client=safari`
|
||||
*
|
||||
* 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
|
||||
* @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 get($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' => 'GET', '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:
|
||||
*
|
||||
* {{{
|
||||
* $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 $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 post($uri = null, $data = array(), $request = array()) {
|
||||
$request = Hash::merge(array('method' => 'POST', 'uri' => $uri, 'body' => $data), $request);
|
||||
return $this->request($request);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 $request An indexed array with indexes such as 'method' or uri
|
||||
* @return mixed Result of request
|
||||
*/
|
||||
public function put($uri = null, $data = array(), $request = array()) {
|
||||
$request = Hash::merge(array('method' => 'PUT', '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 $request An indexed array with indexes such as 'method' or uri
|
||||
* @return mixed Result of request
|
||||
*/
|
||||
public function delete($uri = null, $data = array(), $request = array()) {
|
||||
$request = Hash::merge(array('method' => 'DELETE', 'uri' => $uri, 'body' => $data), $request);
|
||||
return $this->request($request);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*
|
||||
* {{{
|
||||
* $http = new HttpSocket('http://www.cakephp.org');
|
||||
* $url = $http->url('/search?q=bar');
|
||||
* }}}
|
||||
*
|
||||
* Would return `http://www.cakephp.org/search?q=bar`
|
||||
*
|
||||
* url() can also be used with custom templates:
|
||||
*
|
||||
* `$url = $http->url('http://www.cakephp/search?q=socket', '/%path?%query');`
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
public function url($url = null, $uriTemplate = null) {
|
||||
if (is_null($url)) {
|
||||
$url = '/';
|
||||
}
|
||||
if (is_string($url)) {
|
||||
$scheme = $this->config['request']['uri']['scheme'];
|
||||
if (is_array($scheme)) {
|
||||
$scheme = $scheme[0];
|
||||
}
|
||||
$port = $this->config['request']['uri']['port'];
|
||||
if (is_array($port)) {
|
||||
$port = $port[0];
|
||||
}
|
||||
if ($url{0} == '/') {
|
||||
$url = $this->config['request']['uri']['host'] . ':' . $port . $url;
|
||||
}
|
||||
if (!preg_match('/^.+:\/\/|\*|^\//', $url)) {
|
||||
$url = $scheme . '://' . $url;
|
||||
}
|
||||
} elseif (!is_array($url) && !empty($url)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$base = array_merge($this->config['request']['uri'], array('scheme' => array('http', 'https'), 'port' => array(80, 443)));
|
||||
$url = $this->_parseUri($url, $base);
|
||||
|
||||
if (empty($url)) {
|
||||
$url = $this->config['request']['uri'];
|
||||
}
|
||||
|
||||
if (!empty($uriTemplate)) {
|
||||
return $this->_buildUri($url, $uriTemplate);
|
||||
}
|
||||
return $this->_buildUri($url);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set authentication in request
|
||||
*
|
||||
* @return void
|
||||
* @throws SocketException
|
||||
*/
|
||||
protected function _setAuth() {
|
||||
if (empty($this->_auth)) {
|
||||
return;
|
||||
}
|
||||
$method = key($this->_auth);
|
||||
list($plugin, $authClass) = pluginSplit($method, true);
|
||||
$authClass = Inflector::camelize($authClass) . 'Authentication';
|
||||
App::uses($authClass, $plugin . 'Network/Http');
|
||||
|
||||
if (!class_exists($authClass)) {
|
||||
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));
|
||||
}
|
||||
call_user_func_array("$authClass::authentication", array($this, &$this->_auth[$method]));
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the proxy configuration and authentication
|
||||
*
|
||||
* @return void
|
||||
* @throws SocketException
|
||||
*/
|
||||
protected function _setProxy() {
|
||||
if (empty($this->_proxy) || !isset($this->_proxy['host'], $this->_proxy['port'])) {
|
||||
return;
|
||||
}
|
||||
$this->config['host'] = $this->_proxy['host'];
|
||||
$this->config['port'] = $this->_proxy['port'];
|
||||
|
||||
if (empty($this->_proxy['method']) || !isset($this->_proxy['user'], $this->_proxy['pass'])) {
|
||||
return;
|
||||
}
|
||||
list($plugin, $authClass) = pluginSplit($this->_proxy['method'], true);
|
||||
$authClass = Inflector::camelize($authClass) . 'Authentication';
|
||||
App::uses($authClass, $plugin . 'Network/Http');
|
||||
|
||||
if (!class_exists($authClass)) {
|
||||
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));
|
||||
}
|
||||
call_user_func_array("$authClass::proxyAuthentication", array($this, &$this->_proxy));
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
*/
|
||||
protected function _configUri($uri = null) {
|
||||
if (empty($uri)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (is_array($uri)) {
|
||||
$uri = $this->_parseUri($uri);
|
||||
} else {
|
||||
$uri = $this->_parseUri($uri, true);
|
||||
}
|
||||
|
||||
if (!isset($uri['host'])) {
|
||||
return false;
|
||||
}
|
||||
$config = array(
|
||||
'request' => array(
|
||||
'uri' => array_intersect_key($uri, $this->config['request']['uri'])
|
||||
)
|
||||
);
|
||||
$this->config = Hash::merge($this->config, $config);
|
||||
$this->config = Hash::merge($this->config, array_intersect_key($this->config['request']['uri'], $this->config));
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Takes a $uri array and turns it into a fully qualified URL string
|
||||
*
|
||||
* @param string|array $uri Either A $uri array, or a request string. Will use $this->config if left empty.
|
||||
* @param string $uriTemplate The Uri template/format to use.
|
||||
* @return mixed A fully qualified URL formatted according to $uriTemplate, or false on failure
|
||||
*/
|
||||
protected function _buildUri($uri = array(), $uriTemplate = '%scheme://%user:%pass@%host:%port/%path?%query#%fragment') {
|
||||
if (is_string($uri)) {
|
||||
$uri = array('host' => $uri);
|
||||
}
|
||||
$uri = $this->_parseUri($uri, true);
|
||||
|
||||
if (!is_array($uri) || empty($uri)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$uri['path'] = preg_replace('/^\//', null, $uri['path']);
|
||||
$uri['query'] = http_build_query($uri['query']);
|
||||
$uri['query'] = rtrim($uri['query'], '=');
|
||||
$stripIfEmpty = array(
|
||||
'query' => '?%query',
|
||||
'fragment' => '#%fragment',
|
||||
'user' => '%user:%pass@',
|
||||
'host' => '%host:%port/'
|
||||
);
|
||||
|
||||
foreach ($stripIfEmpty as $key => $strip) {
|
||||
if (empty($uri[$key])) {
|
||||
$uriTemplate = str_replace($strip, null, $uriTemplate);
|
||||
}
|
||||
}
|
||||
|
||||
$defaultPorts = array('http' => 80, 'https' => 443);
|
||||
if (array_key_exists($uri['scheme'], $defaultPorts) && $defaultPorts[$uri['scheme']] == $uri['port']) {
|
||||
$uriTemplate = str_replace(':%port', null, $uriTemplate);
|
||||
}
|
||||
foreach ($uri as $property => $value) {
|
||||
$uriTemplate = str_replace('%' . $property, $value, $uriTemplate);
|
||||
}
|
||||
|
||||
if ($uriTemplate === '/*') {
|
||||
$uriTemplate = '*';
|
||||
}
|
||||
return $uriTemplate;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses the given URI and breaks it down into pieces as an indexed array with elements
|
||||
* 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.
|
||||
* @return array Parsed URI
|
||||
*/
|
||||
protected function _parseUri($uri = null, $base = array()) {
|
||||
$uriBase = array(
|
||||
'scheme' => array('http', 'https'),
|
||||
'host' => null,
|
||||
'port' => array(80, 443),
|
||||
'user' => null,
|
||||
'pass' => null,
|
||||
'path' => '/',
|
||||
'query' => null,
|
||||
'fragment' => null
|
||||
);
|
||||
|
||||
if (is_string($uri)) {
|
||||
$uri = parse_url($uri);
|
||||
}
|
||||
if (!is_array($uri) || empty($uri)) {
|
||||
return false;
|
||||
}
|
||||
if ($base === true) {
|
||||
$base = $uriBase;
|
||||
}
|
||||
|
||||
if (isset($base['port'], $base['scheme']) && is_array($base['port']) && is_array($base['scheme'])) {
|
||||
if (isset($uri['scheme']) && !isset($uri['port'])) {
|
||||
$base['port'] = $base['port'][array_search($uri['scheme'], $base['scheme'])];
|
||||
} elseif (isset($uri['port']) && !isset($uri['scheme'])) {
|
||||
$base['scheme'] = $base['scheme'][array_search($uri['port'], $base['port'])];
|
||||
}
|
||||
}
|
||||
|
||||
if (is_array($base) && !empty($base)) {
|
||||
$uri = array_merge($base, $uri);
|
||||
}
|
||||
|
||||
if (isset($uri['scheme']) && is_array($uri['scheme'])) {
|
||||
$uri['scheme'] = array_shift($uri['scheme']);
|
||||
}
|
||||
if (isset($uri['port']) && is_array($uri['port'])) {
|
||||
$uri['port'] = array_shift($uri['port']);
|
||||
}
|
||||
|
||||
if (array_key_exists('query', $uri)) {
|
||||
$uri['query'] = $this->_parseQuery($uri['query']);
|
||||
}
|
||||
|
||||
if (!array_intersect_key($uriBase, $uri)) {
|
||||
return false;
|
||||
}
|
||||
return $uri;
|
||||
}
|
||||
|
||||
/**
|
||||
* This function can be thought of as a reverse to PHP5's http_build_query(). It takes a given query string and turns it into an array and
|
||||
* supports nesting by using the php bracket syntax. So this means you can parse queries like:
|
||||
*
|
||||
* - ?key[subKey]=value
|
||||
* - ?key[]=value1&key[]=value2
|
||||
*
|
||||
* A leading '?' mark in $query is optional and does not effect the outcome of this function.
|
||||
* For the complete capabilities of this implementation take a look at HttpSocketTest::testparseQuery()
|
||||
*
|
||||
* @param string|array $query A query string to parse into an array or an array to return directly "as is"
|
||||
* @return array The $query parsed into a possibly multi-level array. If an empty $query is
|
||||
* given, an empty array is returned.
|
||||
*/
|
||||
protected function _parseQuery($query) {
|
||||
if (is_array($query)) {
|
||||
return $query;
|
||||
}
|
||||
|
||||
$parsedQuery = array();
|
||||
|
||||
if (is_string($query) && !empty($query)) {
|
||||
$query = preg_replace('/^\?/', '', $query);
|
||||
$items = explode('&', $query);
|
||||
|
||||
foreach ($items as $item) {
|
||||
if (strpos($item, '=') !== false) {
|
||||
list($key, $value) = explode('=', $item, 2);
|
||||
} else {
|
||||
$key = $item;
|
||||
$value = null;
|
||||
}
|
||||
|
||||
$key = urldecode($key);
|
||||
$value = urldecode($value);
|
||||
|
||||
if (preg_match_all('/\[([^\[\]]*)\]/iUs', $key, $matches)) {
|
||||
$subKeys = $matches[1];
|
||||
$rootKey = substr($key, 0, strpos($key, '['));
|
||||
if (!empty($rootKey)) {
|
||||
array_unshift($subKeys, $rootKey);
|
||||
}
|
||||
$queryNode =& $parsedQuery;
|
||||
|
||||
foreach ($subKeys as $subKey) {
|
||||
if (!is_array($queryNode)) {
|
||||
$queryNode = array();
|
||||
}
|
||||
|
||||
if ($subKey === '') {
|
||||
$queryNode[] = array();
|
||||
end($queryNode);
|
||||
$subKey = key($queryNode);
|
||||
}
|
||||
$queryNode =& $queryNode[$subKey];
|
||||
}
|
||||
$queryNode = $value;
|
||||
continue;
|
||||
}
|
||||
if (!isset($parsedQuery[$key])) {
|
||||
$parsedQuery[$key] = $value;
|
||||
} else {
|
||||
$parsedQuery[$key] = (array)$parsedQuery[$key];
|
||||
$parsedQuery[$key][] = $value;
|
||||
}
|
||||
}
|
||||
}
|
||||
return $parsedQuery;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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') {
|
||||
$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)))) {
|
||||
throw new SocketException(__d('cake_dev', 'HttpSocket::_buildRequestLine - Passed an invalid request line string. Activate quirks mode to do this.'));
|
||||
}
|
||||
return $request;
|
||||
} elseif (!is_array($request)) {
|
||||
return false;
|
||||
} elseif (!array_key_exists('uri', $request)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$request['uri'] = $this->_parseUri($request['uri']);
|
||||
$request = array_merge(array('method' => 'GET'), $request);
|
||||
if (!empty($this->_proxy['host'])) {
|
||||
$request['uri'] = $this->_buildUri($request['uri'], '%scheme://%host:%port/%path?%query');
|
||||
} else {
|
||||
$request['uri'] = $this->_buildUri($request['uri'], '/%path?%query');
|
||||
}
|
||||
|
||||
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";
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the header.
|
||||
*
|
||||
* @param array $header Header to build
|
||||
* @param string $mode
|
||||
* @return string Header built from array
|
||||
*/
|
||||
protected function _buildHeader($header, $mode = 'standard') {
|
||||
if (is_string($header)) {
|
||||
return $header;
|
||||
} elseif (!is_array($header)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$fieldsInHeader = array();
|
||||
foreach ($header as $key => $value) {
|
||||
$lowKey = strtolower($key);
|
||||
if (array_key_exists($lowKey, $fieldsInHeader)) {
|
||||
$header[$fieldsInHeader[$lowKey]] = $value;
|
||||
unset($header[$key]);
|
||||
} else {
|
||||
$fieldsInHeader[$lowKey] = $key;
|
||||
}
|
||||
}
|
||||
|
||||
$returnHeader = '';
|
||||
foreach ($header as $field => $contents) {
|
||||
if (is_array($contents) && $mode == 'standard') {
|
||||
$contents = implode(',', $contents);
|
||||
}
|
||||
foreach ((array)$contents as $content) {
|
||||
$contents = preg_replace("/\r\n(?![\t ])/", "\r\n ", $content);
|
||||
$field = $this->_escapeToken($field);
|
||||
|
||||
$returnHeader .= $field . ': ' . $contents . "\r\n";
|
||||
}
|
||||
}
|
||||
return $returnHeader;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds cookie headers for a request.
|
||||
*
|
||||
* @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(';'));
|
||||
}
|
||||
return $this->_buildHeader(array('Cookie' => implode('; ', $header)), 'pragmatic');
|
||||
}
|
||||
|
||||
/**
|
||||
* Escapes a given $token according to RFC 2616 (HTTP 1.1 specs)
|
||||
*
|
||||
* @param string $token Token to escape
|
||||
* @param array $chars
|
||||
* @return string Escaped token
|
||||
*/
|
||||
protected function _escapeToken($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;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resets the state of this HttpSocket instance to it's initial state (before Object::__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
|
||||
*/
|
||||
public function reset($full = true) {
|
||||
static $initalState = array();
|
||||
if (empty($initalState)) {
|
||||
$initalState = get_class_vars(__CLASS__);
|
||||
}
|
||||
if (!$full) {
|
||||
$this->request = $initalState['request'];
|
||||
$this->response = $initalState['response'];
|
||||
return true;
|
||||
}
|
||||
parent::reset($initalState);
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue