web serviceMDL-12886 refactor servers into object + add Zend_soap and Zend_xmlrpc server

This commit is contained in:
jerome 2009-02-11 06:57:30 +00:00
parent 625b51d4e0
commit 06e7fadc43
79 changed files with 10475 additions and 211 deletions

View file

@ -306,6 +306,11 @@ class Zend_Http_Client
foreach ($config as $k => $v)
$this->config[strtolower($k)] = $v;
// Pass configuration options to the adapter if it exists
if ($this->adapter instanceof Zend_Http_Client_Adapter_Interface) {
$this->adapter->setConfig($config);
}
return $this;
}
@ -932,11 +937,11 @@ class Zend_Http_Client
// Set the Accept-encoding header if not set - depending on whether
// zlib is available or not.
if (! isset($this->headers['accept-encoding'])) {
if (function_exists('gzinflate')) {
$headers[] = 'Accept-encoding: gzip, deflate';
} else {
$headers[] = 'Accept-encoding: identity';
}
if (function_exists('gzinflate')) {
$headers[] = 'Accept-encoding: gzip, deflate';
} else {
$headers[] = 'Accept-encoding: identity';
}
}
// Set the Content-Type header
@ -967,7 +972,7 @@ class Zend_Http_Client
// Add all other user defined headers
foreach ($this->headers as $header) {
list($name, $value) = $header;
list($name, $value) = $header;
if (is_array($value))
$value = implode(', ', $value);

View file

@ -0,0 +1,33 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Http
* @subpackage Client_Adapter_Exception
* @version $Id$
* @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
require_once 'Zend/Http/Client/Exception.php';
/**
* @category Zend
* @package Zend_Http
* @subpackage Client_Adapter
* @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Http_Client_Adapter_Exception extends Zend_Http_Client_Exception
{}

View file

@ -0,0 +1,269 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Http
* @subpackage Client_Adapter
* @version $Id$
* @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
require_once 'Zend/Uri/Http.php';
require_once 'Zend/Http/Client.php';
require_once 'Zend/Http/Client/Adapter/Socket.php';
/**
* HTTP Proxy-supporting Zend_Http_Client adapter class, based on the default
* socket based adapter.
*
* Should be used if proxy HTTP access is required. If no proxy is set, will
* fall back to Zend_Http_Client_Adapter_Socket behavior. Just like the
* default Socket adapter, this adapter does not require any special extensions
* installed.
*
* @category Zend
* @package Zend_Http
* @subpackage Client_Adapter
* @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Http_Client_Adapter_Proxy extends Zend_Http_Client_Adapter_Socket
{
/**
* Parameters array
*
* @var array
*/
protected $config = array(
'ssltransport' => 'ssl',
'proxy_host' => '',
'proxy_port' => 8080,
'proxy_user' => '',
'proxy_pass' => '',
'proxy_auth' => Zend_Http_Client::AUTH_BASIC,
'persistent' => false
);
/**
* Whether HTTPS CONNECT was already negotiated with the proxy or not
*
* @var boolean
*/
protected $negotiated = false;
/**
* Connect to the remote server
*
* Will try to connect to the proxy server. If no proxy was set, will
* fall back to the target server (behave like regular Socket adapter)
*
* @param string $host
* @param int $port
* @param boolean $secure
* @param int $timeout
*/
public function connect($host, $port = 80, $secure = false)
{
// If no proxy is set, fall back to Socket adapter
if (! $this->config['proxy_host']) return parent::connect($host, $port, $secure);
// Go through a proxy - the connection is actually to the proxy server
$host = $this->config['proxy_host'];
$port = $this->config['proxy_port'];
// If we are connected to the wrong proxy, disconnect first
if (($this->connected_to[0] != $host || $this->connected_to[1] != $port)) {
if (is_resource($this->socket)) $this->close();
}
// Now, if we are not connected, connect
if (! is_resource($this->socket) || ! $this->config['keepalive']) {
$this->socket = @fsockopen($host, $port, $errno, $errstr, (int) $this->config['timeout']);
if (! $this->socket) {
$this->close();
require_once 'Zend/Http/Client/Adapter/Exception.php';
throw new Zend_Http_Client_Adapter_Exception(
'Unable to Connect to proxy server ' . $host . ':' . $port . '. Error #' . $errno . ': ' . $errstr);
}
// Set the stream timeout
if (!stream_set_timeout($this->socket, (int) $this->config['timeout'])) {
require_once 'Zend/Http/Client/Adapter/Exception.php';
throw new Zend_Http_Client_Adapter_Exception('Unable to set the connection timeout');
}
// Update connected_to
$this->connected_to = array($host, $port);
}
}
/**
* Send request to the proxy server
*
* @param string $method
* @param Zend_Uri_Http $uri
* @param string $http_ver
* @param array $headers
* @param string $body
* @return string Request as string
*/
public function write($method, $uri, $http_ver = '1.1', $headers = array(), $body = '')
{
// If no proxy is set, fall back to default Socket adapter
if (! $this->config['proxy_host']) return parent::write($method, $uri, $http_ver, $headers, $body);
// Make sure we're properly connected
if (! $this->socket) {
require_once 'Zend/Http/Client/Adapter/Exception.php';
throw new Zend_Http_Client_Adapter_Exception("Trying to write but we are not connected");
}
$host = $this->config['proxy_host'];
$port = $this->config['proxy_port'];
if ($this->connected_to[0] != $host || $this->connected_to[1] != $port) {
require_once 'Zend/Http/Client/Adapter/Exception.php';
throw new Zend_Http_Client_Adapter_Exception("Trying to write but we are connected to the wrong proxy server");
}
// Add Proxy-Authorization header
if ($this->config['proxy_user'] && ! isset($headers['proxy-authorization'])) {
$headers['proxy-authorization'] = Zend_Http_Client::encodeAuthHeader(
$this->config['proxy_user'], $this->config['proxy_pass'], $this->config['proxy_auth']
);
}
// if we are proxying HTTPS, preform CONNECT handshake with the proxy
if ($uri->getScheme() == 'https' && (! $this->negotiated)) {
$this->connectHandshake($uri->getHost(), $uri->getPort(), $http_ver, $headers);
$this->negotiated = true;
}
// Save request method for later
$this->method = $method;
// Build request headers
$request = "{$method} {$uri->__toString()} HTTP/{$http_ver}\r\n";
// Add all headers to the request string
foreach ($headers as $k => $v) {
if (is_string($k)) $v = "$k: $v";
$request .= "$v\r\n";
}
// Add the request body
$request .= "\r\n" . $body;
// Send the request
if (! @fwrite($this->socket, $request)) {
require_once 'Zend/Http/Client/Adapter/Exception.php';
throw new Zend_Http_Client_Adapter_Exception("Error writing request to proxy server");
}
return $request;
}
/**
* Preform handshaking with HTTPS proxy using CONNECT method
*
* @param string $host
* @param integer $port
* @param string $http_ver
* @param array $headers
*/
protected function connectHandshake($host, $port = 443, $http_ver = '1.1', array &$headers = array())
{
$request = "CONNECT $host:$port HTTP/$http_ver\r\n" .
"Host: " . $this->config['proxy_host'] . "\r\n";
// Add the user-agent header
if (isset($this->config['useragent'])) {
$request .= "User-agent: " . $this->config['useragent'] . "\r\n";
}
// If the proxy-authorization header is set, send it to proxy but remove
// it from headers sent to target host
if (isset($headers['proxy-authorization'])) {
$request .= "Proxy-authorization: " . $headers['proxy-authorization'] . "\r\n";
unset($headers['proxy-authorization']);
}
$request .= "\r\n";
// Send the request
if (! @fwrite($this->socket, $request)) {
require_once 'Zend/Http/Client/Adapter/Exception.php';
throw new Zend_Http_Client_Adapter_Exception("Error writing request to proxy server");
}
// Read response headers only
$response = '';
$gotStatus = false;
while ($line = @fgets($this->socket)) {
$gotStatus = $gotStatus || (strpos($line, 'HTTP') !== false);
if ($gotStatus) {
$response .= $line;
if (!chop($line)) break;
}
}
// Check that the response from the proxy is 200
if (Zend_Http_Response::extractCode($response) != 200) {
require_once 'Zend/Http/Client/Adapter/Exception.php';
throw new Zend_Http_Client_Adapter_Exception("Unable to connect to HTTPS proxy. Server response: " . $response);
}
// If all is good, switch socket to secure mode. We have to fall back
// through the different modes
$modes = array(
STREAM_CRYPTO_METHOD_TLS_CLIENT,
STREAM_CRYPTO_METHOD_SSLv3_CLIENT,
STREAM_CRYPTO_METHOD_SSLv23_CLIENT,
STREAM_CRYPTO_METHOD_SSLv2_CLIENT
);
$success = false;
foreach($modes as $mode) {
$success = stream_socket_enable_crypto($this->socket, true, $mode);
if ($success) break;
}
if (! $success) {
require_once 'Zend/Http/Client/Adapter/Exception.php';
throw new Zend_Http_Client_Adapter_Exception("Unable to connect to" .
" HTTPS server through proxy: could not negotiate secure connection.");
}
}
/**
* Close the connection to the server
*
*/
public function close()
{
parent::close();
$this->negotiated = false;
}
/**
* Destructor: make sure the socket is disconnected
*
*/
public function __destruct()
{
if ($this->socket) $this->close();
}
}

View file

@ -0,0 +1,193 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Http
* @subpackage Client_Adapter
* @version $Id$
* @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
require_once 'Zend/Uri/Http.php';
require_once 'Zend/Http/Response.php';
require_once 'Zend/Http/Client/Adapter/Interface.php';
/**
* A testing-purposes adapter.
*
* Should be used to test all components that rely on Zend_Http_Client,
* without actually performing an HTTP request. You should instantiate this
* object manually, and then set it as the client's adapter. Then, you can
* set the expected response using the setResponse() method.
*
* @category Zend
* @package Zend_Http
* @subpackage Client_Adapter
* @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Http_Client_Adapter_Test implements Zend_Http_Client_Adapter_Interface
{
/**
* Parameters array
*
* @var array
*/
protected $config = array();
/**
* Buffer of responses to be returned by the read() method. Can be
* set using setResponse() and addResponse().
*
* @var array
*/
protected $responses = array("HTTP/1.1 400 Bad Request\r\n\r\n");
/**
* Current position in the response buffer
*
* @var integer
*/
protected $responseIndex = 0;
/**
* Adapter constructor, currently empty. Config is set using setConfig()
*
*/
public function __construct()
{ }
/**
* Set the configuration array for the adapter
*
* @param array $config
*/
public function setConfig($config = array())
{
if (! is_array($config)) {
require_once 'Zend/Http/Client/Adapter/Exception.php';
throw new Zend_Http_Client_Adapter_Exception(
'$config expects an array, ' . gettype($config) . ' recieved.');
}
foreach ($config as $k => $v) {
$this->config[strtolower($k)] = $v;
}
}
/**
* Connect to the remote server
*
* @param string $host
* @param int $port
* @param boolean $secure
* @param int $timeout
*/
public function connect($host, $port = 80, $secure = false)
{ }
/**
* Send request to the remote server
*
* @param string $method
* @param Zend_Uri_Http $uri
* @param string $http_ver
* @param array $headers
* @param string $body
* @return string Request as string
*/
public function write($method, $uri, $http_ver = '1.1', $headers = array(), $body = '')
{
$host = $uri->getHost();
$host = (strtolower($uri->getScheme()) == 'https' ? 'sslv2://' . $host : $host);
// Build request headers
$path = $uri->getPath();
if ($uri->getQuery()) $path .= '?' . $uri->getQuery();
$request = "{$method} {$path} HTTP/{$http_ver}\r\n";
foreach ($headers as $k => $v) {
if (is_string($k)) $v = ucfirst($k) . ": $v";
$request .= "$v\r\n";
}
// Add the request body
$request .= "\r\n" . $body;
// Do nothing - just return the request as string
return $request;
}
/**
* Return the response set in $this->setResponse()
*
* @return string
*/
public function read()
{
if ($this->responseIndex >= count($this->responses)) {
$this->responseIndex = 0;
}
return $this->responses[$this->responseIndex++];
}
/**
* Close the connection (dummy)
*
*/
public function close()
{ }
/**
* Set the HTTP response(s) to be returned by this adapter
*
* @param Zend_Http_Response|array|string $response
*/
public function setResponse($response)
{
if ($response instanceof Zend_Http_Response) {
$response = $response->asString();
}
$this->responses = (array)$response;
$this->responseIndex = 0;
}
/**
* Add another response to the response buffer.
*
* @param string $response
*/
public function addResponse($response)
{
$this->responses[] = $response;
}
/**
* Sets the position of the response buffer. Selects which
* response will be returned on the next call to read().
*
* @param integer $index
*/
public function setResponseIndex($index)
{
if ($index < 0 || $index >= count($this->responses)) {
require_once 'Zend/Http/Client/Adapter/Exception.php';
throw new Zend_Http_Client_Adapter_Exception(
'Index out of range of response buffer size');
}
$this->responseIndex = $index;
}
}

View file

@ -0,0 +1,327 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Http
* @subpackage Cookie
* @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com/)
* @version $Id$
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
require_once 'Zend/Uri/Http.php';
/**
* Zend_Http_Cookie is a class describing an HTTP cookie and all it's parameters.
*
* Zend_Http_Cookie is a class describing an HTTP cookie and all it's parameters. The
* class also enables validating whether the cookie should be sent to the server in
* a specified scenario according to the request URI, the expiry time and whether
* session cookies should be used or not. Generally speaking cookies should be
* contained in a Cookiejar object, or instantiated manually and added to an HTTP
* request.
*
* See http://wp.netscape.com/newsref/std/cookie_spec.html for some specs.
*
* @category Zend
* @package Zend_Http
* @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com/)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Http_Cookie
{
/**
* Cookie name
*
* @var string
*/
protected $name;
/**
* Cookie value
*
* @var string
*/
protected $value;
/**
* Cookie expiry date
*
* @var int
*/
protected $expires;
/**
* Cookie domain
*
* @var string
*/
protected $domain;
/**
* Cookie path
*
* @var string
*/
protected $path;
/**
* Whether the cookie is secure or not
*
* @var boolean
*/
protected $secure;
/**
* Cookie object constructor
*
* @todo Add validation of each one of the parameters (legal domain, etc.)
*
* @param string $name
* @param string $value
* @param int $expires
* @param string $domain
* @param string $path
* @param bool $secure
*/
public function __construct($name, $value, $domain, $expires = null, $path = null, $secure = false)
{
if (preg_match("/[=,; \t\r\n\013\014]/", $name)) {
require_once 'Zend/Http/Exception.php';
throw new Zend_Http_Exception("Cookie name cannot contain these characters: =,; \\t\\r\\n\\013\\014 ({$name})");
}
if (! $this->name = (string) $name) {
require_once 'Zend/Http/Exception.php';
throw new Zend_Http_Exception('Cookies must have a name');
}
if (! $this->domain = (string) $domain) {
require_once 'Zend/Http/Exception.php';
throw new Zend_Http_Exception('Cookies must have a domain');
}
$this->value = (string) $value;
$this->expires = ($expires === null ? null : (int) $expires);
$this->path = ($path ? $path : '/');
$this->secure = $secure;
}
/**
* Get Cookie name
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Get cookie value
*
* @return string
*/
public function getValue()
{
return $this->value;
}
/**
* Get cookie domain
*
* @return string
*/
public function getDomain()
{
return $this->domain;
}
/**
* Get the cookie path
*
* @return string
*/
public function getPath()
{
return $this->path;
}
/**
* Get the expiry time of the cookie, or null if no expiry time is set
*
* @return int|null
*/
public function getExpiryTime()
{
return $this->expires;
}
/**
* Check whether the cookie should only be sent over secure connections
*
* @return boolean
*/
public function isSecure()
{
return $this->secure;
}
/**
* Check whether the cookie has expired
*
* Always returns false if the cookie is a session cookie (has no expiry time)
*
* @param int $now Timestamp to consider as "now"
* @return boolean
*/
public function isExpired($now = null)
{
if ($now === null) $now = time();
if (is_int($this->expires) && $this->expires < $now) {
return true;
} else {
return false;
}
}
/**
* Check whether the cookie is a session cookie (has no expiry time set)
*
* @return boolean
*/
public function isSessionCookie()
{
return ($this->expires === null);
}
/**
* Checks whether the cookie should be sent or not in a specific scenario
*
* @param string|Zend_Uri_Http $uri URI to check against (secure, domain, path)
* @param boolean $matchSessionCookies Whether to send session cookies
* @param int $now Override the current time when checking for expiry time
* @return boolean
*/
public function match($uri, $matchSessionCookies = true, $now = null)
{
if (is_string ($uri)) {
$uri = Zend_Uri_Http::factory($uri);
}
// Make sure we have a valid Zend_Uri_Http object
if (! ($uri->valid() && ($uri->getScheme() == 'http' || $uri->getScheme() =='https'))) {
require_once 'Zend/Http/Exception.php';
throw new Zend_Http_Exception('Passed URI is not a valid HTTP or HTTPS URI');
}
// Check that the cookie is secure (if required) and not expired
if ($this->secure && $uri->getScheme() != 'https') return false;
if ($this->isExpired($now)) return false;
if ($this->isSessionCookie() && ! $matchSessionCookies) return false;
// Validate domain and path
// Domain is validated using tail match, while path is validated using head match
$domain_preg = preg_quote($this->getDomain(), "/");
if (! preg_match("/{$domain_preg}$/", $uri->getHost())) return false;
$path_preg = preg_quote($this->getPath(), "/");
if (! preg_match("/^{$path_preg}/", $uri->getPath())) return false;
// If we didn't die until now, return true.
return true;
}
/**
* Get the cookie as a string, suitable for sending as a "Cookie" header in an
* HTTP request
*
* @return string
*/
public function __toString()
{
return $this->name . '=' . urlencode($this->value) . ';';
}
/**
* Generate a new Cookie object from a cookie string
* (for example the value of the Set-Cookie HTTP header)
*
* @param string $cookieStr
* @param Zend_Uri_Http|string $ref_uri Reference URI for default values (domain, path)
* @return Zend_Http_Cookie A new Zend_Http_Cookie object or false on failure.
*/
public static function fromString($cookieStr, $ref_uri = null)
{
// Set default values
if (is_string($ref_uri)) {
$ref_uri = Zend_Uri_Http::factory($ref_uri);
}
$name = '';
$value = '';
$domain = '';
$path = '';
$expires = null;
$secure = false;
$parts = explode(';', $cookieStr);
// If first part does not include '=', fail
if (strpos($parts[0], '=') === false) return false;
// Get the name and value of the cookie
list($name, $value) = explode('=', trim(array_shift($parts)), 2);
$name = trim($name);
$value = urldecode(trim($value));
// Set default domain and path
if ($ref_uri instanceof Zend_Uri_Http) {
$domain = $ref_uri->getHost();
$path = $ref_uri->getPath();
$path = substr($path, 0, strrpos($path, '/'));
}
// Set other cookie parameters
foreach ($parts as $part) {
$part = trim($part);
if (strtolower($part) == 'secure') {
$secure = true;
continue;
}
$keyValue = explode('=', $part, 2);
if (count($keyValue) == 2) {
list($k, $v) = $keyValue;
switch (strtolower($k)) {
case 'expires':
$expires = strtotime($v);
break;
case 'path':
$path = $v;
break;
case 'domain':
$domain = $v;
break;
default:
break;
}
}
}
if ($name !== '') {
return new Zend_Http_Cookie($name, $value, $domain, $expires, $path, $secure);
} else {
return false;
}
}
}

View file

@ -0,0 +1,350 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Http
* @subpackage CookieJar
* @version $Id$
* @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com/)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
require_once "Zend/Uri.php";
require_once "Zend/Http/Cookie.php";
require_once "Zend/Http/Response.php";
/**
* A Zend_Http_CookieJar object is designed to contain and maintain HTTP cookies, and should
* be used along with Zend_Http_Client in order to manage cookies across HTTP requests and
* responses.
*
* The class contains an array of Zend_Http_Cookie objects. Cookies can be added to the jar
* automatically from a request or manually. Then, the jar can find and return the cookies
* needed for a specific HTTP request.
*
* A special parameter can be passed to all methods of this class that return cookies: Cookies
* can be returned either in their native form (as Zend_Http_Cookie objects) or as strings -
* the later is suitable for sending as the value of the "Cookie" header in an HTTP request.
* You can also choose, when returning more than one cookie, whether to get an array of strings
* (by passing Zend_Http_CookieJar::COOKIE_STRING_ARRAY) or one unified string for all cookies
* (by passing Zend_Http_CookieJar::COOKIE_STRING_CONCAT).
*
* @link http://wp.netscape.com/newsref/std/cookie_spec.html for some specs.
*
* @category Zend
* @package Zend_Http
* @subpackage CookieJar
* @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com/)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Http_CookieJar
{
/**
* Return cookie(s) as a Zend_Http_Cookie object
*
*/
const COOKIE_OBJECT = 0;
/**
* Return cookie(s) as a string (suitable for sending in an HTTP request)
*
*/
const COOKIE_STRING_ARRAY = 1;
/**
* Return all cookies as one long string (suitable for sending in an HTTP request)
*
*/
const COOKIE_STRING_CONCAT = 2;
/**
* Array storing cookies
*
* Cookies are stored according to domain and path:
* $cookies
* + www.mydomain.com
* + /
* - cookie1
* - cookie2
* + /somepath
* - othercookie
* + www.otherdomain.net
* + /
* - alsocookie
*
* @var array
*/
protected $cookies = array();
/**
* Construct a new CookieJar object
*
*/
public function __construct()
{ }
/**
* Add a cookie to the jar. Cookie should be passed either as a Zend_Http_Cookie object
* or as a string - in which case an object is created from the string.
*
* @param Zend_Http_Cookie|string $cookie
* @param Zend_Uri_Http|string $ref_uri Optional reference URI (for domain, path, secure)
*/
public function addCookie($cookie, $ref_uri = null)
{
if (is_string($cookie)) {
$cookie = Zend_Http_Cookie::fromString($cookie, $ref_uri);
}
if ($cookie instanceof Zend_Http_Cookie) {
$domain = $cookie->getDomain();
$path = $cookie->getPath();
if (! isset($this->cookies[$domain])) $this->cookies[$domain] = array();
if (! isset($this->cookies[$domain][$path])) $this->cookies[$domain][$path] = array();
$this->cookies[$domain][$path][$cookie->getName()] = $cookie;
} else {
require_once 'Zend/Http/Exception.php';
throw new Zend_Http_Exception('Supplient argument is not a valid cookie string or object');
}
}
/**
* Parse an HTTP response, adding all the cookies set in that response
* to the cookie jar.
*
* @param Zend_Http_Response $response
* @param Zend_Uri_Http|string $ref_uri Requested URI
*/
public function addCookiesFromResponse($response, $ref_uri)
{
if (! $response instanceof Zend_Http_Response) {
require_once 'Zend/Http/Exception.php';
throw new Zend_Http_Exception('$response is expected to be a Response object, ' .
gettype($response) . ' was passed');
}
$cookie_hdrs = $response->getHeader('Set-Cookie');
if (is_array($cookie_hdrs)) {
foreach ($cookie_hdrs as $cookie) {
$this->addCookie($cookie, $ref_uri);
}
} elseif (is_string($cookie_hdrs)) {
$this->addCookie($cookie_hdrs, $ref_uri);
}
}
/**
* Get all cookies in the cookie jar as an array
*
* @param int $ret_as Whether to return cookies as objects of Zend_Http_Cookie or as strings
* @return array|string
*/
public function getAllCookies($ret_as = self::COOKIE_OBJECT)
{
$cookies = $this->_flattenCookiesArray($this->cookies, $ret_as);
return $cookies;
}
/**
* Return an array of all cookies matching a specific request according to the request URI,
* whether session cookies should be sent or not, and the time to consider as "now" when
* checking cookie expiry time.
*
* @param string|Zend_Uri_Http $uri URI to check against (secure, domain, path)
* @param boolean $matchSessionCookies Whether to send session cookies
* @param int $ret_as Whether to return cookies as objects of Zend_Http_Cookie or as strings
* @param int $now Override the current time when checking for expiry time
* @return array|string
*/
public function getMatchingCookies($uri, $matchSessionCookies = true,
$ret_as = self::COOKIE_OBJECT, $now = null)
{
if (is_string($uri)) $uri = Zend_Uri::factory($uri);
if (! $uri instanceof Zend_Uri_Http) {
require_once 'Zend/Http/Exception.php';
throw new Zend_Http_Exception("Invalid URI string or object passed");
}
// Set path
$path = $uri->getPath();
$path = substr($path, 0, strrpos($path, '/'));
if (! $path) $path = '/';
// First, reduce the array of cookies to only those matching domain and path
$cookies = $this->_matchDomain($uri->getHost());
$cookies = $this->_matchPath($cookies, $path);
$cookies = $this->_flattenCookiesArray($cookies, self::COOKIE_OBJECT);
// Next, run Cookie->match on all cookies to check secure, time and session mathcing
$ret = array();
foreach ($cookies as $cookie)
if ($cookie->match($uri, $matchSessionCookies, $now))
$ret[] = $cookie;
// Now, use self::_flattenCookiesArray again - only to convert to the return format ;)
$ret = $this->_flattenCookiesArray($ret, $ret_as);
return $ret;
}
/**
* Get a specific cookie according to a URI and name
*
* @param Zend_Uri_Http|string $uri The uri (domain and path) to match
* @param string $cookie_name The cookie's name
* @param int $ret_as Whether to return cookies as objects of Zend_Http_Cookie or as strings
* @return Zend_Http_Cookie|string
*/
public function getCookie($uri, $cookie_name, $ret_as = self::COOKIE_OBJECT)
{
if (is_string($uri)) {
$uri = Zend_Uri::factory($uri);
}
if (! $uri instanceof Zend_Uri_Http) {
require_once 'Zend/Http/Exception.php';
throw new Zend_Http_Exception('Invalid URI specified');
}
// Get correct cookie path
$path = $uri->getPath();
$path = substr($path, 0, strrpos($path, '/'));
if (! $path) $path = '/';
if (isset($this->cookies[$uri->getHost()][$path][$cookie_name])) {
$cookie = $this->cookies[$uri->getHost()][$path][$cookie_name];
switch ($ret_as) {
case self::COOKIE_OBJECT:
return $cookie;
break;
case self::COOKIE_STRING_ARRAY:
case self::COOKIE_STRING_CONCAT:
return $cookie->__toString();
break;
default:
require_once 'Zend/Http/Exception.php';
throw new Zend_Http_Exception("Invalid value passed for \$ret_as: {$ret_as}");
break;
}
} else {
return false;
}
}
/**
* Helper function to recursivly flatten an array. Shoud be used when exporting the
* cookies array (or parts of it)
*
* @param Zend_Http_Cookie|array $ptr
* @param int $ret_as What value to return
* @return array|string
*/
protected function _flattenCookiesArray($ptr, $ret_as = self::COOKIE_OBJECT) {
if (is_array($ptr)) {
$ret = ($ret_as == self::COOKIE_STRING_CONCAT ? '' : array());
foreach ($ptr as $item) {
if ($ret_as == self::COOKIE_STRING_CONCAT) {
$ret .= $this->_flattenCookiesArray($item, $ret_as);
} else {
$ret = array_merge($ret, $this->_flattenCookiesArray($item, $ret_as));
}
}
return $ret;
} elseif ($ptr instanceof Zend_Http_Cookie) {
switch ($ret_as) {
case self::COOKIE_STRING_ARRAY:
return array($ptr->__toString());
break;
case self::COOKIE_STRING_CONCAT:
return $ptr->__toString();
break;
case self::COOKIE_OBJECT:
default:
return array($ptr);
break;
}
}
return null;
}
/**
* Return a subset of the cookies array matching a specific domain
*
* Returned array is actually an array of pointers to items in the $this->cookies array.
*
* @param string $domain
* @return array
*/
protected function _matchDomain($domain) {
$ret = array();
foreach (array_keys($this->cookies) as $cdom) {
$regex = "/" . preg_quote($cdom, "/") . "$/i";
if (preg_match($regex, $domain)) $ret[$cdom] = &$this->cookies[$cdom];
}
return $ret;
}
/**
* Return a subset of a domain-matching cookies that also match a specified path
*
* Returned array is actually an array of pointers to items in the $passed array.
*
* @param array $dom_array
* @param string $path
* @return array
*/
protected function _matchPath($domains, $path) {
$ret = array();
if (substr($path, -1) != '/') $path .= '/';
foreach ($domains as $dom => $paths_array) {
foreach (array_keys($paths_array) as $cpath) {
$regex = "|^" . preg_quote($cpath, "|") . "|i";
if (preg_match($regex, $path)) {
if (! isset($ret[$dom])) $ret[$dom] = array();
$ret[$dom][$cpath] = &$paths_array[$cpath];
}
}
}
return $ret;
}
/**
* Create a new CookieJar object and automatically load into it all the
* cookies set in an Http_Response object. If $uri is set, it will be
* considered as the requested URI for setting default domain and path
* of the cookie.
*
* @param Zend_Http_Response $response HTTP Response object
* @param Zend_Uri_Http|string $uri The requested URI
* @return Zend_Http_CookieJar
* @todo Add the $uri functionality.
*/
public static function fromResponse(Zend_Http_Response $response, $ref_uri)
{
$jar = new self();
$jar->addCookiesFromResponse($response, $ref_uri);
return $jar;
}
}

View file

@ -162,7 +162,7 @@ class Zend_Http_Response
if (! is_array($headers)) {
require_once 'Zend/Http/Exception.php';
throw new Zend_Http_Exception('No valid headers were passed');
}
}
foreach ($headers as $name => $value) {
if (is_int($name))
@ -536,10 +536,9 @@ class Zend_Http_Response
{
$parts = preg_split('|(?:\r?\n){2}|m', $response_str, 2);
if (isset($parts[1])) {
return $parts[1];
} else {
return '';
return $parts[1];
}
return '';
}
/**
@ -603,7 +602,7 @@ class Zend_Http_Response
'body: perhaps the zlib extension is not loaded?');
}
return gzuncompress($body);
return gzuncompress($body);
}
/**