mirror of
https://github.com/brmlab/brmbiolab_sklad.git
synced 2025-10-29 22:44:01 +01:00
Initial commit
This commit is contained in:
commit
3b93da31de
1004 changed files with 265840 additions and 0 deletions
1026
lib/Cake/Network/CakeRequest.php
Normal file
1026
lib/Cake/Network/CakeRequest.php
Normal file
File diff suppressed because it is too large
Load diff
1513
lib/Cake/Network/CakeResponse.php
Normal file
1513
lib/Cake/Network/CakeResponse.php
Normal file
File diff suppressed because it is too large
Load diff
389
lib/Cake/Network/CakeSocket.php
Normal file
389
lib/Cake/Network/CakeSocket.php
Normal file
|
|
@ -0,0 +1,389 @@
|
|||
<?php
|
||||
/**
|
||||
* CakePHP Socket connection class.
|
||||
*
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @package Cake.Network
|
||||
* @since CakePHP(tm) v 1.2.0
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
|
||||
App::uses('Validation', 'Utility');
|
||||
|
||||
/**
|
||||
* CakePHP 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 bool
|
||||
*/
|
||||
public $connected = false;
|
||||
|
||||
/**
|
||||
* This variable contains an array with the last error number (num) and string (str)
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public $lastError = array();
|
||||
|
||||
/**
|
||||
* True if the socket stream is encrypted after a CakeSocket::enableCrypto() call
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
public $encrypted = false;
|
||||
|
||||
/**
|
||||
* Contains all the encryption methods available
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $_encryptMethods = array(
|
||||
// @codingStandardsIgnoreStart
|
||||
'sslv2_client' => STREAM_CRYPTO_METHOD_SSLv2_CLIENT,
|
||||
'sslv3_client' => STREAM_CRYPTO_METHOD_SSLv3_CLIENT,
|
||||
'sslv23_client' => STREAM_CRYPTO_METHOD_SSLv23_CLIENT,
|
||||
'tls_client' => STREAM_CRYPTO_METHOD_TLS_CLIENT,
|
||||
'sslv2_server' => STREAM_CRYPTO_METHOD_SSLv2_SERVER,
|
||||
'sslv3_server' => STREAM_CRYPTO_METHOD_SSLv3_SERVER,
|
||||
'sslv23_server' => STREAM_CRYPTO_METHOD_SSLv23_SERVER,
|
||||
'tls_server' => STREAM_CRYPTO_METHOD_TLS_SERVER
|
||||
// @codingStandardsIgnoreEnd
|
||||
);
|
||||
|
||||
/**
|
||||
* Used to capture connection warnings which can happen when there are
|
||||
* SSL errors for example.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $_connectionErrors = array();
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @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 bool Success
|
||||
* @throws SocketException
|
||||
*/
|
||||
public function connect() {
|
||||
if ($this->connection) {
|
||||
$this->disconnect();
|
||||
}
|
||||
|
||||
$scheme = null;
|
||||
if (isset($this->config['request']['uri']) && $this->config['request']['uri']['scheme'] === 'https') {
|
||||
$scheme = 'ssl://';
|
||||
}
|
||||
|
||||
if (!empty($this->config['context'])) {
|
||||
$context = stream_context_create($this->config['context']);
|
||||
} else {
|
||||
$context = stream_context_create();
|
||||
}
|
||||
|
||||
$connectAs = STREAM_CLIENT_CONNECT;
|
||||
if ($this->config['persistent']) {
|
||||
$connectAs |= STREAM_CLIENT_PERSISTENT;
|
||||
}
|
||||
|
||||
set_error_handler(array($this, '_connectionErrorHandler'));
|
||||
$this->connection = stream_socket_client(
|
||||
$scheme . $this->config['host'] . ':' . $this->config['port'],
|
||||
$errNum,
|
||||
$errStr,
|
||||
$this->config['timeout'],
|
||||
$connectAs,
|
||||
$context
|
||||
);
|
||||
restore_error_handler();
|
||||
|
||||
if (!empty($errNum) || !empty($errStr)) {
|
||||
$this->setLastError($errNum, $errStr);
|
||||
throw new SocketException($errStr, $errNum);
|
||||
}
|
||||
|
||||
if (!$this->connection && $this->_connectionErrors) {
|
||||
$message = implode("\n", $this->_connectionErrors);
|
||||
throw new SocketException($message, E_WARNING);
|
||||
}
|
||||
|
||||
$this->connected = is_resource($this->connection);
|
||||
if ($this->connected) {
|
||||
stream_set_timeout($this->connection, $this->config['timeout']);
|
||||
}
|
||||
return $this->connected;
|
||||
}
|
||||
|
||||
/**
|
||||
* socket_stream_client() does not populate errNum, or $errStr when there are
|
||||
* connection errors, as in the case of SSL verification failure.
|
||||
*
|
||||
* Instead we need to handle those errors manually.
|
||||
*
|
||||
* @param int $code Code.
|
||||
* @param string $message Message.
|
||||
* @return void
|
||||
*/
|
||||
protected function _connectionErrorHandler($code, $message) {
|
||||
$this->_connectionErrors[] = $message;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the connection context.
|
||||
*
|
||||
* @return null|array Null when there is no connection, an array when there is.
|
||||
*/
|
||||
public function context() {
|
||||
if (!$this->connection) {
|
||||
return;
|
||||
}
|
||||
return stream_context_get_options($this->connection);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 int $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 bool 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 int $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 bool 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 bool 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;
|
||||
}
|
||||
|
||||
/**
|
||||
* Encrypts current stream socket, using one of the defined encryption methods
|
||||
*
|
||||
* @param string $type can be one of 'ssl2', 'ssl3', 'ssl23' or 'tls'
|
||||
* @param string $clientOrServer can be one of 'client', 'server'. Default is 'client'
|
||||
* @param bool $enable enable or disable encryption. Default is true (enable)
|
||||
* @return bool True on success
|
||||
* @throws InvalidArgumentException When an invalid encryption scheme is chosen.
|
||||
* @throws SocketException When attempting to enable SSL/TLS fails
|
||||
* @see stream_socket_enable_crypto
|
||||
*/
|
||||
public function enableCrypto($type, $clientOrServer = 'client', $enable = true) {
|
||||
if (!array_key_exists($type . '_' . $clientOrServer, $this->_encryptMethods)) {
|
||||
throw new InvalidArgumentException(__d('cake_dev', 'Invalid encryption scheme chosen'));
|
||||
}
|
||||
$enableCryptoResult = false;
|
||||
try {
|
||||
$enableCryptoResult = stream_socket_enable_crypto($this->connection, $enable, $this->_encryptMethods[$type . '_' . $clientOrServer]);
|
||||
} catch (Exception $e) {
|
||||
$this->setLastError(null, $e->getMessage());
|
||||
throw new SocketException($e->getMessage());
|
||||
}
|
||||
if ($enableCryptoResult === true) {
|
||||
$this->encrypted = $enable;
|
||||
return true;
|
||||
}
|
||||
$errorMessage = __d('cake_dev', 'Unable to perform enableCrypto operation on CakeSocket');
|
||||
$this->setLastError(null, $errorMessage);
|
||||
throw new SocketException($errorMessage);
|
||||
}
|
||||
|
||||
}
|
||||
75
lib/Cake/Network/Email/AbstractTransport.php
Normal file
75
lib/Cake/Network/Email/AbstractTransport.php
Normal file
|
|
@ -0,0 +1,75 @@
|
|||
<?php
|
||||
/**
|
||||
* Abstract send email
|
||||
*
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @package Cake.Network.Email
|
||||
* @since CakePHP(tm) v 2.0.0
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
|
||||
/**
|
||||
* Abstract transport for sending email
|
||||
*
|
||||
* @package Cake.Network.Email
|
||||
*/
|
||||
abstract class AbstractTransport {
|
||||
|
||||
/**
|
||||
* Configurations
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $_config = array();
|
||||
|
||||
/**
|
||||
* Send mail
|
||||
*
|
||||
* @param CakeEmail $email CakeEmail instance.
|
||||
* @return array
|
||||
*/
|
||||
abstract public function send(CakeEmail $email);
|
||||
|
||||
/**
|
||||
* Set the config
|
||||
*
|
||||
* @param array $config Configuration options.
|
||||
* @return array Returns configs
|
||||
*/
|
||||
public function config($config = null) {
|
||||
if (is_array($config)) {
|
||||
$this->_config = $config + $this->_config;
|
||||
}
|
||||
return $this->_config;
|
||||
}
|
||||
|
||||
/**
|
||||
* Help to convert headers in string
|
||||
*
|
||||
* @param array $headers Headers in format key => value
|
||||
* @param string $eol End of line string.
|
||||
* @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;
|
||||
}
|
||||
|
||||
}
|
||||
1726
lib/Cake/Network/Email/CakeEmail.php
Normal file
1726
lib/Cake/Network/Email/CakeEmail.php
Normal file
File diff suppressed because it is too large
Load diff
40
lib/Cake/Network/Email/DebugTransport.php
Normal file
40
lib/Cake/Network/Email/DebugTransport.php
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
<?php
|
||||
/**
|
||||
* Emulates the email sending process for testing purposes
|
||||
*
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @package Cake.Network.Email
|
||||
* @since CakePHP(tm) v 2.0.0
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
|
||||
/**
|
||||
* 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);
|
||||
}
|
||||
|
||||
}
|
||||
82
lib/Cake/Network/Email/MailTransport.php
Normal file
82
lib/Cake/Network/Email/MailTransport.php
Normal file
|
|
@ -0,0 +1,82 @@
|
|||
<?php
|
||||
/**
|
||||
* Send mail using mail() function
|
||||
*
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @package Cake.Network.Email
|
||||
* @since CakePHP(tm) v 2.0.0
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
|
||||
/**
|
||||
* 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']);
|
||||
foreach ($headers as $key => $header) {
|
||||
$headers[$key] = str_replace(array("\r", "\n"), '', $header);
|
||||
}
|
||||
$headers = $this->_headersToString($headers, $eol);
|
||||
$subject = str_replace(array("\r", "\n"), '', $email->subject());
|
||||
$to = str_replace(array("\r", "\n"), '', $to);
|
||||
|
||||
$message = implode($eol, $email->message());
|
||||
|
||||
$params = isset($this->_config['additionalParameters']) ? $this->_config['additionalParameters'] : null;
|
||||
$this->_mail($to, $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)) {
|
||||
$error = error_get_last();
|
||||
$msg = 'Could not send email: ' . isset($error['message']) ? $error['message'] : 'unknown';
|
||||
throw new SocketException($msg);
|
||||
}
|
||||
} elseif (!@mail($to, $subject, $message, $headers, $params)) {
|
||||
$error = error_get_last();
|
||||
$msg = 'Could not send email: ' . isset($error['message']) ? $error['message'] : 'unknown';
|
||||
//@codingStandardsIgnoreEnd
|
||||
throw new SocketException($msg);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
373
lib/Cake/Network/Email/SmtpTransport.php
Normal file
373
lib/Cake/Network/Email/SmtpTransport.php
Normal file
|
|
@ -0,0 +1,373 @@
|
|||
<?php
|
||||
/**
|
||||
* Send mail using SMTP protocol
|
||||
*
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @package Cake.Network.Email
|
||||
* @since CakePHP(tm) v 2.0.0
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
|
||||
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;
|
||||
|
||||
/**
|
||||
* The response of the last sent SMTP command.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $_lastResponse = array();
|
||||
|
||||
/**
|
||||
* Returns the response of the last sent SMTP command.
|
||||
*
|
||||
* A response consists of one or more lines containing a response
|
||||
* code and an optional response message text:
|
||||
* {{{
|
||||
* array(
|
||||
* array(
|
||||
* 'code' => '250',
|
||||
* 'message' => 'mail.example.com'
|
||||
* ),
|
||||
* array(
|
||||
* 'code' => '250',
|
||||
* 'message' => 'PIPELINING'
|
||||
* ),
|
||||
* array(
|
||||
* 'code' => '250',
|
||||
* 'message' => '8BITMIME'
|
||||
* ),
|
||||
* // etc...
|
||||
* )
|
||||
* }}}
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getLastResponse() {
|
||||
return $this->_lastResponse;
|
||||
}
|
||||
|
||||
/**
|
||||
* Send mail
|
||||
*
|
||||
* @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 Configuration options.
|
||||
* @return array Returns configs
|
||||
*/
|
||||
public function config($config = null) {
|
||||
if ($config === null) {
|
||||
return $this->_config;
|
||||
}
|
||||
$default = array(
|
||||
'host' => 'localhost',
|
||||
'port' => 25,
|
||||
'timeout' => 30,
|
||||
'username' => null,
|
||||
'password' => null,
|
||||
'client' => null,
|
||||
'tls' => false
|
||||
);
|
||||
$this->_config = array_merge($default, $this->_config, $config);
|
||||
return $this->_config;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses and stores the reponse lines in `'code' => 'message'` format.
|
||||
*
|
||||
* @param array $responseLines Response lines to parse.
|
||||
* @return void
|
||||
*/
|
||||
protected function _bufferResponseLines(array $responseLines) {
|
||||
$response = array();
|
||||
foreach ($responseLines as $responseLine) {
|
||||
if (preg_match('/^(\d{3})(?:[ -]+(.*))?$/', $responseLine, $match)) {
|
||||
$response[] = array(
|
||||
'code' => $match[1],
|
||||
'message' => isset($match[2]) ? $match[2] : null
|
||||
);
|
||||
}
|
||||
}
|
||||
$this->_lastResponse = array_merge($this->_lastResponse, $response);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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');
|
||||
if ($this->_config['tls']) {
|
||||
$this->_smtpSend("STARTTLS", '220');
|
||||
$this->_socket->enableCrypto('tls');
|
||||
$this->_smtpSend("EHLO {$host}", '250');
|
||||
}
|
||||
} catch (SocketException $e) {
|
||||
if ($this->_config['tls']) {
|
||||
throw new SocketException(__d('cake_dev', 'SMTP server did not accept the connection or trying to connect to non TLS SMTP server using TLS.'));
|
||||
}
|
||||
try {
|
||||
$this->_smtpSend("HELO {$host}", '250');
|
||||
} catch (SocketException $e2) {
|
||||
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 == '504') {
|
||||
throw new SocketException(__d('cake_dev', 'SMTP authentication method not allowed, check if SMTP server requires TLS'));
|
||||
} elseif ($authRequired != '503') {
|
||||
throw new SocketException(__d('cake_dev', 'SMTP does not require authentication.'));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepares the `MAIL FROM` SMTP command.
|
||||
*
|
||||
* @param string $email The email address to send with the command.
|
||||
* @return string
|
||||
*/
|
||||
protected function _prepareFromCmd($email) {
|
||||
return 'MAIL FROM:<' . $email . '>';
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepares the `RCPT TO` SMTP command.
|
||||
*
|
||||
* @param string $email The email address to send with the command.
|
||||
* @return string
|
||||
*/
|
||||
protected function _prepareRcptCmd($email) {
|
||||
return 'RCPT TO:<' . $email . '>';
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepares the `from` email address.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
protected function _prepareFromAddress() {
|
||||
$from = $this->_cakeEmail->returnPath();
|
||||
if (empty($from)) {
|
||||
$from = $this->_cakeEmail->from();
|
||||
}
|
||||
return $from;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepares the recipient email addresses.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
protected function _prepareRecipientAddresses() {
|
||||
$to = $this->_cakeEmail->to();
|
||||
$cc = $this->_cakeEmail->cc();
|
||||
$bcc = $this->_cakeEmail->bcc();
|
||||
return array_merge(array_keys($to), array_keys($cc), array_keys($bcc));
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepares the message headers.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
protected function _prepareMessageHeaders() {
|
||||
return $this->_cakeEmail->getHeaders(array('from', 'sender', 'replyTo', 'readReceipt', 'to', 'cc', 'subject'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepares the message body.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function _prepareMessage() {
|
||||
$lines = $this->_cakeEmail->message();
|
||||
$messages = array();
|
||||
foreach ($lines as $line) {
|
||||
if ((!empty($line)) && ($line[0] === '.')) {
|
||||
$messages[] = '.' . $line;
|
||||
} else {
|
||||
$messages[] = $line;
|
||||
}
|
||||
}
|
||||
return implode("\r\n", $messages);
|
||||
}
|
||||
|
||||
/**
|
||||
* Send emails
|
||||
*
|
||||
* @return void
|
||||
* @throws SocketException
|
||||
*/
|
||||
protected function _sendRcpt() {
|
||||
$from = $this->_prepareFromAddress();
|
||||
$this->_smtpSend($this->_prepareFromCmd(key($from)));
|
||||
|
||||
$emails = $this->_prepareRecipientAddresses();
|
||||
foreach ($emails as $email) {
|
||||
$this->_smtpSend($this->_prepareRcptCmd($email));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Send Data
|
||||
*
|
||||
* @return void
|
||||
* @throws SocketException
|
||||
*/
|
||||
protected function _sendData() {
|
||||
$this->_smtpSend('DATA', '354');
|
||||
|
||||
$headers = $this->_headersToString($this->_prepareMessageHeaders());
|
||||
$message = $this->_prepareMessage();
|
||||
|
||||
$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|bool $checkCode code to check for in server response, false to skip
|
||||
* @return void
|
||||
* @throws SocketException
|
||||
*/
|
||||
protected function _smtpSend($data, $checkCode = '250') {
|
||||
$this->_lastResponse = array();
|
||||
|
||||
if ($data !== null) {
|
||||
$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);
|
||||
|
||||
$this->_bufferResponseLines($responseLines);
|
||||
|
||||
if (preg_match('/^(' . $checkCode . ')(.)/', $response, $code)) {
|
||||
if ($code[2] === '-') {
|
||||
continue;
|
||||
}
|
||||
return $code[1];
|
||||
}
|
||||
throw new SocketException(__d('cake_dev', 'SMTP Error: %s', $response));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
65
lib/Cake/Network/Http/BasicAuthentication.php
Normal file
65
lib/Cake/Network/Http/BasicAuthentication.php
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
<?php
|
||||
/**
|
||||
* Basic authentication
|
||||
*
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @package Cake.Network.Http
|
||||
* @since CakePHP(tm) v 2.0.0
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
|
||||
/**
|
||||
* Basic authentication
|
||||
*
|
||||
* @package Cake.Network.Http
|
||||
*/
|
||||
class BasicAuthentication {
|
||||
|
||||
/**
|
||||
* Authentication
|
||||
*
|
||||
* @param HttpSocket $http Http socket instance.
|
||||
* @param array &$authInfo Authentication info.
|
||||
* @return void
|
||||
* @see http://www.ietf.org/rfc/rfc2617.txt
|
||||
*/
|
||||
public static function authentication(HttpSocket $http, &$authInfo) {
|
||||
if (isset($authInfo['user'], $authInfo['pass'])) {
|
||||
$http->request['header']['Authorization'] = self::_generateHeader($authInfo['user'], $authInfo['pass']);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Proxy Authentication
|
||||
*
|
||||
* @param HttpSocket $http Http socket instance.
|
||||
* @param array &$proxyInfo Proxy info.
|
||||
* @return void
|
||||
* @see http://www.ietf.org/rfc/rfc2617.txt
|
||||
*/
|
||||
public static function proxyAuthentication(HttpSocket $http, &$proxyInfo) {
|
||||
if (isset($proxyInfo['user'], $proxyInfo['pass'])) {
|
||||
$http->request['header']['Proxy-Authorization'] = self::_generateHeader($proxyInfo['user'], $proxyInfo['pass']);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate basic [proxy] authentication header
|
||||
*
|
||||
* @param string $user Username.
|
||||
* @param string $pass Password.
|
||||
* @return string
|
||||
*/
|
||||
protected static function _generateHeader($user, $pass) {
|
||||
return 'Basic ' . base64_encode($user . ':' . $pass);
|
||||
}
|
||||
|
||||
}
|
||||
104
lib/Cake/Network/Http/DigestAuthentication.php
Normal file
104
lib/Cake/Network/Http/DigestAuthentication.php
Normal file
|
|
@ -0,0 +1,104 @@
|
|||
<?php
|
||||
/**
|
||||
* Digest authentication
|
||||
*
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @package Cake.Network.Http
|
||||
* @since CakePHP(tm) v 2.0.0
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
|
||||
/**
|
||||
* Digest authentication
|
||||
*
|
||||
* @package Cake.Network.Http
|
||||
*/
|
||||
class DigestAuthentication {
|
||||
|
||||
/**
|
||||
* Authentication
|
||||
*
|
||||
* @param HttpSocket $http Http socket instance.
|
||||
* @param array &$authInfo Authentication info.
|
||||
* @return void
|
||||
* @link http://www.ietf.org/rfc/rfc2617.txt
|
||||
*/
|
||||
public static function authentication(HttpSocket $http, &$authInfo) {
|
||||
if (isset($authInfo['user'], $authInfo['pass'])) {
|
||||
if (!isset($authInfo['realm']) && !self::_getServerInformation($http, $authInfo)) {
|
||||
return;
|
||||
}
|
||||
$http->request['header']['Authorization'] = self::_generateHeader($http, $authInfo);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve information about the authentication
|
||||
*
|
||||
* @param HttpSocket $http Http socket instance.
|
||||
* @param array &$authInfo Authentication info.
|
||||
* @return bool
|
||||
*/
|
||||
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 Http socket instance.
|
||||
* @param array &$authInfo Authentication info.
|
||||
* @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;
|
||||
}
|
||||
|
||||
}
|
||||
35
lib/Cake/Network/Http/HttpResponse.php
Normal file
35
lib/Cake/Network/Http/HttpResponse.php
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
<?php
|
||||
/**
|
||||
* HTTP Response from HttpSocket.
|
||||
*
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @since CakePHP(tm) v 2.0.0
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
|
||||
App::uses('HttpSocketResponse', 'Network/Http');
|
||||
|
||||
if (class_exists('HttpResponse')) {
|
||||
trigger_error(__d(
|
||||
'cake_dev',
|
||||
"HttpResponse is deprecated due to naming conflicts. Use HttpSocketResponse instead."
|
||||
), E_USER_ERROR);
|
||||
}
|
||||
|
||||
/**
|
||||
* HTTP Response from HttpSocket.
|
||||
*
|
||||
* @package Cake.Network.Http
|
||||
* @deprecated This class is deprecated as it has naming conflicts with pecl/http
|
||||
*/
|
||||
class HttpResponse extends HttpSocketResponse {
|
||||
|
||||
}
|
||||
1032
lib/Cake/Network/Http/HttpSocket.php
Normal file
1032
lib/Cake/Network/Http/HttpSocket.php
Normal file
File diff suppressed because it is too large
Load diff
446
lib/Cake/Network/Http/HttpSocketResponse.php
Normal file
446
lib/Cake/Network/Http/HttpSocketResponse.php
Normal file
|
|
@ -0,0 +1,446 @@
|
|||
<?php
|
||||
/**
|
||||
* HTTP Response from HttpSocket.
|
||||
*
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @since CakePHP(tm) v 2.0.0
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
|
||||
/**
|
||||
* HTTP Response from HttpSocket.
|
||||
*
|
||||
* @package Cake.Network.Http
|
||||
*/
|
||||
class HttpSocketResponse implements ArrayAccess {
|
||||
|
||||
/**
|
||||
* Body content
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $body = '';
|
||||
|
||||
/**
|
||||
* Headers
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public $headers = array();
|
||||
|
||||
/**
|
||||
* Cookies
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public $cookies = array();
|
||||
|
||||
/**
|
||||
* HTTP version
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $httpVersion = 'HTTP/1.1';
|
||||
|
||||
/**
|
||||
* Response code
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
public $code = 0;
|
||||
|
||||
/**
|
||||
* Reason phrase
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $reasonPhrase = '';
|
||||
|
||||
/**
|
||||
* Pure raw content
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $raw = '';
|
||||
|
||||
/**
|
||||
* Context data in the response.
|
||||
* Contains SSL certificates for example.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public $context = array();
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param string $message Message to parse.
|
||||
*/
|
||||
public function __construct($message = null) {
|
||||
if ($message !== null) {
|
||||
$this->parseResponse($message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Body content
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function body() {
|
||||
return (string)$this->body;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get header in case insensitive
|
||||
*
|
||||
* @param string $name Header name.
|
||||
* @param array $headers Headers to format.
|
||||
* @return mixed String if header exists or null
|
||||
*/
|
||||
public function getHeader($name, $headers = null) {
|
||||
if (!is_array($headers)) {
|
||||
$headers =& $this->headers;
|
||||
}
|
||||
if (isset($headers[$name])) {
|
||||
return $headers[$name];
|
||||
}
|
||||
foreach ($headers as $key => $value) {
|
||||
if (strcasecmp($key, $name) === 0) {
|
||||
return $value;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* If return is 200 (OK)
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function isOk() {
|
||||
return in_array($this->code, array(200, 201, 202, 203, 204, 205, 206));
|
||||
}
|
||||
|
||||
/**
|
||||
* If return is a valid 3xx (Redirection)
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function isRedirect() {
|
||||
return in_array($this->code, array(301, 302, 303, 307)) && $this->getHeader('Location') !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses the given message and breaks it down in parts.
|
||||
*
|
||||
* @param string $message Message to parse
|
||||
* @return void
|
||||
* @throws SocketException
|
||||
*/
|
||||
public function parseResponse($message) {
|
||||
if (!is_string($message)) {
|
||||
throw new SocketException(__d('cake_dev', 'Invalid response.'));
|
||||
}
|
||||
|
||||
if (!preg_match("/^(.+\r\n)(.*)(?<=\r\n)\r\n/Us", $message, $match)) {
|
||||
throw new SocketException(__d('cake_dev', 'Invalid HTTP response.'));
|
||||
}
|
||||
|
||||
list(, $statusLine, $header) = $match;
|
||||
$this->raw = $message;
|
||||
$this->body = (string)substr($message, strlen($match[0]));
|
||||
|
||||
if (preg_match("/(.+) ([0-9]{3})(?:\s+(\w.+))?\s*\r\n/DU", $statusLine, $match)) {
|
||||
$this->httpVersion = $match[1];
|
||||
$this->code = $match[2];
|
||||
if (isset($match[3])) {
|
||||
$this->reasonPhrase = $match[3];
|
||||
}
|
||||
}
|
||||
|
||||
$this->headers = $this->_parseHeader($header);
|
||||
$transferEncoding = $this->getHeader('Transfer-Encoding');
|
||||
$decoded = $this->_decodeBody($this->body, $transferEncoding);
|
||||
$this->body = $decoded['body'];
|
||||
|
||||
if (!empty($decoded['header'])) {
|
||||
$this->headers = $this->_parseHeader($this->_buildHeader($this->headers) . $this->_buildHeader($decoded['header']));
|
||||
}
|
||||
|
||||
if (!empty($this->headers)) {
|
||||
$this->cookies = $this->parseCookies($this->headers);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generic function to decode a $body with a given $encoding. Returns either an array with the keys
|
||||
* 'body' and 'header' or false on failure.
|
||||
*
|
||||
* @param string $body A string containing the body to decode.
|
||||
* @param string|bool $encoding Can be false in case no encoding is being used, or a string representing the encoding.
|
||||
* @return mixed Array of response headers and body or false.
|
||||
*/
|
||||
protected function _decodeBody($body, $encoding = 'chunked') {
|
||||
if (!is_string($body)) {
|
||||
return false;
|
||||
}
|
||||
if (empty($encoding)) {
|
||||
return array('body' => $body, 'header' => false);
|
||||
}
|
||||
$decodeMethod = '_decode' . Inflector::camelize(str_replace('-', '_', $encoding)) . 'Body';
|
||||
|
||||
if (!is_callable(array(&$this, $decodeMethod))) {
|
||||
return array('body' => $body, 'header' => false);
|
||||
}
|
||||
return $this->{$decodeMethod}($body);
|
||||
}
|
||||
|
||||
/**
|
||||
* Decodes a chunked message $body and returns either an array with the keys 'body' and 'header' or false as
|
||||
* a result.
|
||||
*
|
||||
* @param string $body A string containing the chunked body to decode.
|
||||
* @return mixed Array of response headers and body or false.
|
||||
* @throws SocketException
|
||||
*/
|
||||
protected function _decodeChunkedBody($body) {
|
||||
if (!is_string($body)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$decodedBody = null;
|
||||
$chunkLength = null;
|
||||
|
||||
while ($chunkLength !== 0) {
|
||||
if (!preg_match('/^([0-9a-f]+) *(?:;(.+)=(.+))?(?:\r\n|\n)/iU', $body, $match)) {
|
||||
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 Characters to unescape.
|
||||
* @return string Unescaped token
|
||||
*/
|
||||
protected function _unescapeToken($token, $chars = null) {
|
||||
$regex = '/"([' . implode('', $this->_tokenEscapeChars(true, $chars)) . '])"/';
|
||||
$token = preg_replace($regex, '\\1', $token);
|
||||
return $token;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets escape chars according to RFC 2616 (HTTP 1.1 specs).
|
||||
*
|
||||
* @param bool $hex True to get them as HEX values, false otherwise.
|
||||
* @param array $chars Characters to uescape.
|
||||
* @return array Escape chars
|
||||
*/
|
||||
protected function _tokenEscapeChars($hex = true, $chars = null) {
|
||||
if (!empty($chars)) {
|
||||
$escape = $chars;
|
||||
} else {
|
||||
$escape = array('"', "(", ")", "<", ">", "@", ",", ";", ":", "\\", "/", "[", "]", "?", "=", "{", "}", " ");
|
||||
for ($i = 0; $i <= 31; $i++) {
|
||||
$escape[] = chr($i);
|
||||
}
|
||||
$escape[] = chr(127);
|
||||
}
|
||||
|
||||
if (!$hex) {
|
||||
return $escape;
|
||||
}
|
||||
foreach ($escape as $key => $char) {
|
||||
$escape[$key] = '\\x' . str_pad(dechex(ord($char)), 2, '0', STR_PAD_LEFT);
|
||||
}
|
||||
return $escape;
|
||||
}
|
||||
|
||||
/**
|
||||
* ArrayAccess - Offset Exists
|
||||
*
|
||||
* @param string $offset Offset to check.
|
||||
* @return bool
|
||||
*/
|
||||
public function offsetExists($offset) {
|
||||
return in_array($offset, array('raw', 'status', 'header', 'body', 'cookies'));
|
||||
}
|
||||
|
||||
/**
|
||||
* ArrayAccess - Offset Get
|
||||
*
|
||||
* @param string $offset Offset to get.
|
||||
* @return mixed
|
||||
*/
|
||||
public function offsetGet($offset) {
|
||||
switch ($offset) {
|
||||
case 'raw':
|
||||
$firstLineLength = strpos($this->raw, "\r\n") + 2;
|
||||
if ($this->raw[$firstLineLength] === "\r") {
|
||||
$header = null;
|
||||
} else {
|
||||
$header = substr($this->raw, $firstLineLength, strpos($this->raw, "\r\n\r\n") - $firstLineLength) . "\r\n";
|
||||
}
|
||||
return array(
|
||||
'status-line' => $this->httpVersion . ' ' . $this->code . ' ' . $this->reasonPhrase . "\r\n",
|
||||
'header' => $header,
|
||||
'body' => $this->body,
|
||||
'response' => $this->raw
|
||||
);
|
||||
case 'status':
|
||||
return array(
|
||||
'http-version' => $this->httpVersion,
|
||||
'code' => $this->code,
|
||||
'reason-phrase' => $this->reasonPhrase
|
||||
);
|
||||
case 'header':
|
||||
return $this->headers;
|
||||
case 'body':
|
||||
return $this->body;
|
||||
case 'cookies':
|
||||
return $this->cookies;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* ArrayAccess - Offset Set
|
||||
*
|
||||
* @param string $offset Offset to set.
|
||||
* @param mixed $value Value.
|
||||
* @return void
|
||||
*/
|
||||
public function offsetSet($offset, $value) {
|
||||
}
|
||||
|
||||
/**
|
||||
* ArrayAccess - Offset Unset
|
||||
*
|
||||
* @param string $offset Offset to unset.
|
||||
* @return void
|
||||
*/
|
||||
public function offsetUnset($offset) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Instance as string
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function __toString() {
|
||||
return $this->body();
|
||||
}
|
||||
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue