<?php\r
/**\r
- * Class representing a HTTP request\r
+ * Class representing a HTTP request message\r
*\r
* PHP version 5\r
*\r
- * LICENSE:\r
+ * LICENSE\r
*\r
- * Copyright (c) 2008, 2009, Alexey Borzov <avb@php.net>\r
- * All rights reserved.\r
+ * This source file is subject to BSD 3-Clause License that is bundled\r
+ * with this package in the file LICENSE and available at the URL\r
+ * https://raw.github.com/pear/HTTP_Request2/trunk/docs/LICENSE\r
*\r
- * Redistribution and use in source and binary forms, with or without\r
- * modification, are permitted provided that the following conditions\r
- * are met:\r
- *\r
- * * Redistributions of source code must retain the above copyright\r
- * notice, this list of conditions and the following disclaimer.\r
- * * Redistributions in binary form must reproduce the above copyright\r
- * notice, this list of conditions and the following disclaimer in the\r
- * documentation and/or other materials provided with the distribution.\r
- * * The names of the authors may not be used to endorse or promote products\r
- * derived from this software without specific prior written permission.\r
- *\r
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS\r
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\r
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\r
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\r
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\r
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\r
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\r
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY\r
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\r
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\r
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r
- *\r
- * @category HTTP\r
- * @package HTTP_Request2\r
- * @author Alexey Borzov <avb@php.net>\r
- * @license http://opensource.org/licenses/bsd-license.php New BSD License\r
- * @version CVS: $Id: Request2.php 278226 2009-04-03 21:32:48Z avb $\r
- * @link http://pear.php.net/package/HTTP_Request2\r
+ * @category HTTP\r
+ * @package HTTP_Request2\r
+ * @author Alexey Borzov <avb@php.net>\r
+ * @copyright 2008-2014 Alexey Borzov <avb@php.net>\r
+ * @license http://opensource.org/licenses/BSD-3-Clause BSD 3-Clause License\r
+ * @link http://pear.php.net/package/HTTP_Request2\r
*/\r
\r
/**\r
\r
/**\r
* Exception class for HTTP_Request2 package\r
- */ \r
+ */\r
require_once 'HTTP/Request2/Exception.php';\r
\r
/**\r
- * Class representing a HTTP request\r
+ * Class representing a HTTP request message\r
*\r
- * @category HTTP\r
- * @package HTTP_Request2\r
- * @author Alexey Borzov <avb@php.net>\r
- * @version Release: 0.4.1\r
- * @link http://tools.ietf.org/html/rfc2616#section-5\r
+ * @category HTTP\r
+ * @package HTTP_Request2\r
+ * @author Alexey Borzov <avb@php.net>\r
+ * @license http://opensource.org/licenses/BSD-3-Clause BSD 3-Clause License\r
+ * @version Release: 2.2.1\r
+ * @link http://pear.php.net/package/HTTP_Request2\r
+ * @link http://tools.ietf.org/html/rfc2616#section-5\r
*/\r
class HTTP_Request2 implements SplSubject\r
{\r
- /**#@+\r
- * Constants for HTTP request methods\r
- *\r
- * @link http://tools.ietf.org/html/rfc2616#section-5.1.1\r
- */\r
+ /**#@+\r
+ * Constants for HTTP request methods\r
+ *\r
+ * @link http://tools.ietf.org/html/rfc2616#section-5.1.1\r
+ */\r
const METHOD_OPTIONS = 'OPTIONS';\r
const METHOD_GET = 'GET';\r
const METHOD_HEAD = 'HEAD';\r
const METHOD_DELETE = 'DELETE';\r
const METHOD_TRACE = 'TRACE';\r
const METHOD_CONNECT = 'CONNECT';\r
- /**#@-*/\r
+ /**#@-*/\r
\r
- /**#@+\r
- * Constants for HTTP authentication schemes \r
- *\r
- * @link http://tools.ietf.org/html/rfc2617\r
- */\r
+ /**#@+\r
+ * Constants for HTTP authentication schemes\r
+ *\r
+ * @link http://tools.ietf.org/html/rfc2617\r
+ */\r
const AUTH_BASIC = 'basic';\r
const AUTH_DIGEST = 'digest';\r
- /**#@-*/\r
+ /**#@-*/\r
\r
- /**\r
- * Regular expression used to check for invalid symbols in RFC 2616 tokens\r
- * @link http://pear.php.net/bugs/bug.php?id=15630\r
- */\r
+ /**\r
+ * Regular expression used to check for invalid symbols in RFC 2616 tokens\r
+ * @link http://pear.php.net/bugs/bug.php?id=15630\r
+ */\r
const REGEXP_INVALID_TOKEN = '![\x00-\x1f\x7f-\xff()<>@,;:\\\\"/\[\]?={}\s]!';\r
\r
- /**\r
- * Regular expression used to check for invalid symbols in cookie strings\r
- * @link http://pear.php.net/bugs/bug.php?id=15630\r
- * @link http://cgi.netscape.com/newsref/std/cookie_spec.html\r
- */\r
+ /**\r
+ * Regular expression used to check for invalid symbols in cookie strings\r
+ * @link http://pear.php.net/bugs/bug.php?id=15630\r
+ * @link http://web.archive.org/web/20080331104521/http://cgi.netscape.com/newsref/std/cookie_spec.html\r
+ */\r
const REGEXP_INVALID_COOKIE = '/[\s,;]/';\r
\r
- /**\r
- * Fileinfo magic database resource\r
- * @var resource\r
- * @see detectMimeType()\r
- */\r
+ /**\r
+ * Fileinfo magic database resource\r
+ * @var resource\r
+ * @see detectMimeType()\r
+ */\r
private static $_fileinfoDb;\r
\r
- /**\r
- * Observers attached to the request (instances of SplObserver)\r
- * @var array\r
- */\r
+ /**\r
+ * Observers attached to the request (instances of SplObserver)\r
+ * @var array\r
+ */\r
protected $observers = array();\r
\r
- /**\r
- * Request URL\r
- * @var Net_URL2\r
- */\r
+ /**\r
+ * Request URL\r
+ * @var Net_URL2\r
+ */\r
protected $url;\r
\r
- /**\r
- * Request method\r
- * @var string\r
- */\r
+ /**\r
+ * Request method\r
+ * @var string\r
+ */\r
protected $method = self::METHOD_GET;\r
\r
- /**\r
- * Authentication data\r
- * @var array\r
- * @see getAuth()\r
- */\r
+ /**\r
+ * Authentication data\r
+ * @var array\r
+ * @see getAuth()\r
+ */\r
protected $auth;\r
\r
- /**\r
- * Request headers\r
- * @var array\r
- */\r
+ /**\r
+ * Request headers\r
+ * @var array\r
+ */\r
protected $headers = array();\r
\r
- /**\r
- * Configuration parameters\r
- * @var array\r
- * @see setConfig()\r
- */\r
+ /**\r
+ * Configuration parameters\r
+ * @var array\r
+ * @see setConfig()\r
+ */\r
protected $config = array(\r
'adapter' => 'HTTP_Request2_Adapter_Socket',\r
'connect_timeout' => 10,\r
'protocol_version' => '1.1',\r
'buffer_size' => 16384,\r
'store_body' => true,\r
+ 'local_ip' => null,\r
\r
'proxy_host' => '',\r
'proxy_port' => '',\r
'proxy_user' => '',\r
'proxy_password' => '',\r
'proxy_auth_scheme' => self::AUTH_BASIC,\r
+ 'proxy_type' => 'http',\r
\r
'ssl_verify_peer' => true,\r
'ssl_verify_host' => true,\r
'ssl_local_cert' => null,\r
'ssl_passphrase' => null,\r
\r
- 'digest_compat_ie' => false\r
+ 'digest_compat_ie' => false,\r
+\r
+ 'follow_redirects' => false,\r
+ 'max_redirects' => 5,\r
+ 'strict_redirects' => false\r
);\r
\r
- /**\r
- * Last event in request / response handling, intended for observers\r
- * @var array\r
- * @see getLastEvent()\r
- */\r
+ /**\r
+ * Last event in request / response handling, intended for observers\r
+ * @var array\r
+ * @see getLastEvent()\r
+ */\r
protected $lastEvent = array(\r
'name' => 'start',\r
'data' => null\r
);\r
\r
- /**\r
- * Request body\r
- * @var string|resource\r
- * @see setBody()\r
- */\r
+ /**\r
+ * Request body\r
+ * @var string|resource\r
+ * @see setBody()\r
+ */\r
protected $body = '';\r
\r
- /**\r
- * Array of POST parameters\r
- * @var array\r
- */\r
+ /**\r
+ * Array of POST parameters\r
+ * @var array\r
+ */\r
protected $postParams = array();\r
\r
- /**\r
- * Array of file uploads (for multipart/form-data POST requests) \r
- * @var array\r
- */\r
+ /**\r
+ * Array of file uploads (for multipart/form-data POST requests)\r
+ * @var array\r
+ */\r
protected $uploads = array();\r
\r
- /**\r
- * Adapter used to perform actual HTTP request\r
- * @var HTTP_Request2_Adapter\r
- */\r
+ /**\r
+ * Adapter used to perform actual HTTP request\r
+ * @var HTTP_Request2_Adapter\r
+ */\r
protected $adapter;\r
\r
+ /**\r
+ * Cookie jar to persist cookies between requests\r
+ * @var HTTP_Request2_CookieJar\r
+ */\r
+ protected $cookieJar = null;\r
\r
- /**\r
- * Constructor. Can set request URL, method and configuration array.\r
- *\r
- * Also sets a default value for User-Agent header. \r
- *\r
- * @param string|Net_Url2 Request URL\r
- * @param string Request method\r
- * @param array Configuration for this Request instance\r
- */\r
- public function __construct($url = null, $method = self::METHOD_GET, array $config = array())\r
- {\r
+ /**\r
+ * Constructor. Can set request URL, method and configuration array.\r
+ *\r
+ * Also sets a default value for User-Agent header.\r
+ *\r
+ * @param string|Net_Url2 $url Request URL\r
+ * @param string $method Request method\r
+ * @param array $config Configuration for this Request instance\r
+ */\r
+ public function __construct(\r
+ $url = null, $method = self::METHOD_GET, array $config = array()\r
+ ) {\r
+ $this->setConfig($config);\r
if (!empty($url)) {\r
$this->setUrl($url);\r
}\r
if (!empty($method)) {\r
$this->setMethod($method);\r
}\r
- $this->setConfig($config);\r
- $this->setHeader('user-agent', 'HTTP_Request2/0.4.1 ' .\r
- '(http://pear.php.net/package/http_request2) ' .\r
- 'PHP/' . phpversion());\r
+ $this->setHeader(\r
+ 'user-agent', 'HTTP_Request2/2.2.1 ' .\r
+ '(http://pear.php.net/package/http_request2) PHP/' . phpversion()\r
+ );\r
}\r
\r
- /**\r
- * Sets the URL for this request\r
- *\r
- * If the URL has userinfo part (username & password) these will be removed\r
- * and converted to auth data. If the URL does not have a path component,\r
- * that will be set to '/'.\r
- *\r
- * @param string|Net_URL2 Request URL\r
- * @return HTTP_Request2\r
- * @throws HTTP_Request2_Exception\r
- */\r
+ /**\r
+ * Sets the URL for this request\r
+ *\r
+ * If the URL has userinfo part (username & password) these will be removed\r
+ * and converted to auth data. If the URL does not have a path component,\r
+ * that will be set to '/'.\r
+ *\r
+ * @param string|Net_URL2 $url Request URL\r
+ *\r
+ * @return HTTP_Request2\r
+ * @throws HTTP_Request2_LogicException\r
+ */\r
public function setUrl($url)\r
{\r
if (is_string($url)) {\r
- $url = new Net_URL2($url);\r
+ $url = new Net_URL2(\r
+ $url, array(Net_URL2::OPTION_USE_BRACKETS => $this->config['use_brackets'])\r
+ );\r
}\r
if (!$url instanceof Net_URL2) {\r
- throw new HTTP_Request2_Exception('Parameter is not a valid HTTP URL');\r
+ throw new HTTP_Request2_LogicException(\r
+ 'Parameter is not a valid HTTP URL',\r
+ HTTP_Request2_Exception::INVALID_ARGUMENT\r
+ );\r
}\r
// URL contains username / password?\r
if ($url->getUserinfo()) {\r
return $this;\r
}\r
\r
- /**\r
- * Returns the request URL\r
- *\r
- * @return Net_URL2\r
- */\r
+ /**\r
+ * Returns the request URL\r
+ *\r
+ * @return Net_URL2\r
+ */\r
public function getUrl()\r
{\r
return $this->url;\r
}\r
\r
- /**\r
- * Sets the request method\r
- *\r
- * @param string\r
- * @return HTTP_Request2\r
- * @throws HTTP_Request2_Exception if the method name is invalid\r
- */\r
+ /**\r
+ * Sets the request method\r
+ *\r
+ * @param string $method one of the methods defined in RFC 2616\r
+ *\r
+ * @return HTTP_Request2\r
+ * @throws HTTP_Request2_LogicException if the method name is invalid\r
+ */\r
public function setMethod($method)\r
{\r
// Method name should be a token: http://tools.ietf.org/html/rfc2616#section-5.1.1\r
if (preg_match(self::REGEXP_INVALID_TOKEN, $method)) {\r
- throw new HTTP_Request2_Exception("Invalid request method '{$method}'");\r
+ throw new HTTP_Request2_LogicException(\r
+ "Invalid request method '{$method}'",\r
+ HTTP_Request2_Exception::INVALID_ARGUMENT\r
+ );\r
}\r
$this->method = $method;\r
\r
return $this;\r
}\r
\r
- /**\r
- * Returns the request method\r
- *\r
- * @return string\r
- */\r
+ /**\r
+ * Returns the request method\r
+ *\r
+ * @return string\r
+ */\r
public function getMethod()\r
{\r
return $this->method;\r
}\r
\r
- /**\r
- * Sets the configuration parameter(s)\r
- *\r
- * The following parameters are available:\r
- * <ul>\r
- * <li> 'adapter' - adapter to use (string)</li>\r
- * <li> 'connect_timeout' - Connection timeout in seconds (integer)</li>\r
- * <li> 'timeout' - Total number of seconds a request can take.\r
- * Use 0 for no limit, should be greater than \r
- * 'connect_timeout' if set (integer)</li>\r
- * <li> 'use_brackets' - Whether to append [] to array variable names (bool)</li>\r
- * <li> 'protocol_version' - HTTP Version to use, '1.0' or '1.1' (string)</li>\r
- * <li> 'buffer_size' - Buffer size to use for reading and writing (int)</li>\r
- * <li> 'store_body' - Whether to store response body in response object.\r
- * Set to false if receiving a huge response and\r
- * using an Observer to save it (boolean)</li>\r
- * <li> 'proxy_host' - Proxy server host (string)</li>\r
- * <li> 'proxy_port' - Proxy server port (integer)</li>\r
- * <li> 'proxy_user' - Proxy auth username (string)</li>\r
- * <li> 'proxy_password' - Proxy auth password (string)</li>\r
- * <li> 'proxy_auth_scheme' - Proxy auth scheme, one of HTTP_Request2::AUTH_* constants (string)</li>\r
- * <li> 'ssl_verify_peer' - Whether to verify peer's SSL certificate (bool)</li>\r
- * <li> 'ssl_verify_host' - Whether to check that Common Name in SSL\r
- * certificate matches host name (bool)</li>\r
- * <li> 'ssl_cafile' - Cerificate Authority file to verify the peer\r
- * with (use with 'ssl_verify_peer') (string)</li>\r
- * <li> 'ssl_capath' - Directory holding multiple Certificate \r
- * Authority files (string)</li>\r
- * <li> 'ssl_local_cert' - Name of a file containing local cerificate (string)</li>\r
- * <li> 'ssl_passphrase' - Passphrase with which local certificate\r
- * was encoded (string)</li>\r
- * <li> 'digest_compat_ie' - Whether to imitate behaviour of MSIE 5 and 6\r
- * in using URL without query string in digest\r
- * authentication (boolean)</li>\r
- * </ul>\r
- *\r
- * @param string|array configuration parameter name or array\r
- * ('parameter name' => 'parameter value')\r
- * @param mixed parameter value if $nameOrConfig is not an array\r
- * @return HTTP_Request2\r
- * @throws HTTP_Request2_Exception If the parameter is unknown\r
- */\r
+ /**\r
+ * Sets the configuration parameter(s)\r
+ *\r
+ * The following parameters are available:\r
+ * <ul>\r
+ * <li> 'adapter' - adapter to use (string)</li>\r
+ * <li> 'connect_timeout' - Connection timeout in seconds (integer)</li>\r
+ * <li> 'timeout' - Total number of seconds a request can take.\r
+ * Use 0 for no limit, should be greater than\r
+ * 'connect_timeout' if set (integer)</li>\r
+ * <li> 'use_brackets' - Whether to append [] to array variable names (bool)</li>\r
+ * <li> 'protocol_version' - HTTP Version to use, '1.0' or '1.1' (string)</li>\r
+ * <li> 'buffer_size' - Buffer size to use for reading and writing (int)</li>\r
+ * <li> 'store_body' - Whether to store response body in response object.\r
+ * Set to false if receiving a huge response and\r
+ * using an Observer to save it (boolean)</li>\r
+ * <li> 'local_ip' - Specifies the IP address that will be used for accessing\r
+ * the network (string)</li>\r
+ * <li> 'proxy_type' - Proxy type, 'http' or 'socks5' (string)</li>\r
+ * <li> 'proxy_host' - Proxy server host (string)</li>\r
+ * <li> 'proxy_port' - Proxy server port (integer)</li>\r
+ * <li> 'proxy_user' - Proxy auth username (string)</li>\r
+ * <li> 'proxy_password' - Proxy auth password (string)</li>\r
+ * <li> 'proxy_auth_scheme' - Proxy auth scheme, one of HTTP_Request2::AUTH_* constants (string)</li>\r
+ * <li> 'proxy' - Shorthand for proxy_* parameters, proxy given as URL,\r
+ * e.g. 'socks5://localhost:1080/' (string)</li>\r
+ * <li> 'ssl_verify_peer' - Whether to verify peer's SSL certificate (bool)</li>\r
+ * <li> 'ssl_verify_host' - Whether to check that Common Name in SSL\r
+ * certificate matches host name (bool)</li>\r
+ * <li> 'ssl_cafile' - Cerificate Authority file to verify the peer\r
+ * with (use with 'ssl_verify_peer') (string)</li>\r
+ * <li> 'ssl_capath' - Directory holding multiple Certificate\r
+ * Authority files (string)</li>\r
+ * <li> 'ssl_local_cert' - Name of a file containing local cerificate (string)</li>\r
+ * <li> 'ssl_passphrase' - Passphrase with which local certificate\r
+ * was encoded (string)</li>\r
+ * <li> 'digest_compat_ie' - Whether to imitate behaviour of MSIE 5 and 6\r
+ * in using URL without query string in digest\r
+ * authentication (boolean)</li>\r
+ * <li> 'follow_redirects' - Whether to automatically follow HTTP Redirects (boolean)</li>\r
+ * <li> 'max_redirects' - Maximum number of redirects to follow (integer)</li>\r
+ * <li> 'strict_redirects' - Whether to keep request method on redirects via status 301 and\r
+ * 302 (true, needed for compatibility with RFC 2616)\r
+ * or switch to GET (false, needed for compatibility with most\r
+ * browsers) (boolean)</li>\r
+ * </ul>\r
+ *\r
+ * @param string|array $nameOrConfig configuration parameter name or array\r
+ * ('parameter name' => 'parameter value')\r
+ * @param mixed $value parameter value if $nameOrConfig is not an array\r
+ *\r
+ * @return HTTP_Request2\r
+ * @throws HTTP_Request2_LogicException If the parameter is unknown\r
+ */\r
public function setConfig($nameOrConfig, $value = null)\r
{\r
if (is_array($nameOrConfig)) {\r
$this->setConfig($name, $value);\r
}\r
\r
+ } elseif ('proxy' == $nameOrConfig) {\r
+ $url = new Net_URL2($value);\r
+ $this->setConfig(array(\r
+ 'proxy_type' => $url->getScheme(),\r
+ 'proxy_host' => $url->getHost(),\r
+ 'proxy_port' => $url->getPort(),\r
+ 'proxy_user' => rawurldecode($url->getUser()),\r
+ 'proxy_password' => rawurldecode($url->getPassword())\r
+ ));\r
+\r
} else {\r
if (!array_key_exists($nameOrConfig, $this->config)) {\r
- throw new HTTP_Request2_Exception(\r
- "Unknown configuration parameter '{$nameOrConfig}'"\r
+ throw new HTTP_Request2_LogicException(\r
+ "Unknown configuration parameter '{$nameOrConfig}'",\r
+ HTTP_Request2_Exception::INVALID_ARGUMENT\r
);\r
}\r
$this->config[$nameOrConfig] = $value;\r
return $this;\r
}\r
\r
- /**\r
- * Returns the value(s) of the configuration parameter(s)\r
- *\r
- * @param string parameter name\r
- * @return mixed value of $name parameter, array of all configuration \r
- * parameters if $name is not given\r
- * @throws HTTP_Request2_Exception If the parameter is unknown\r
- */\r
+ /**\r
+ * Returns the value(s) of the configuration parameter(s)\r
+ *\r
+ * @param string $name parameter name\r
+ *\r
+ * @return mixed value of $name parameter, array of all configuration\r
+ * parameters if $name is not given\r
+ * @throws HTTP_Request2_LogicException If the parameter is unknown\r
+ */\r
public function getConfig($name = null)\r
{\r
if (null === $name) {\r
return $this->config;\r
} elseif (!array_key_exists($name, $this->config)) {\r
- throw new HTTP_Request2_Exception(\r
- "Unknown configuration parameter '{$name}'"\r
+ throw new HTTP_Request2_LogicException(\r
+ "Unknown configuration parameter '{$name}'",\r
+ HTTP_Request2_Exception::INVALID_ARGUMENT\r
);\r
}\r
return $this->config[$name];\r
}\r
\r
- /**\r
- * Sets the autentification data\r
- *\r
- * @param string user name\r
- * @param string password\r
- * @param string authentication scheme\r
- * @return HTTP_Request2\r
- */ \r
+ /**\r
+ * Sets the autentification data\r
+ *\r
+ * @param string $user user name\r
+ * @param string $password password\r
+ * @param string $scheme authentication scheme\r
+ *\r
+ * @return HTTP_Request2\r
+ */\r
public function setAuth($user, $password = '', $scheme = self::AUTH_BASIC)\r
{\r
if (empty($user)) {\r
return $this;\r
}\r
\r
- /**\r
- * Returns the authentication data\r
- *\r
- * The array has the keys 'user', 'password' and 'scheme', where 'scheme'\r
- * is one of the HTTP_Request2::AUTH_* constants.\r
- *\r
- * @return array\r
- */\r
+ /**\r
+ * Returns the authentication data\r
+ *\r
+ * The array has the keys 'user', 'password' and 'scheme', where 'scheme'\r
+ * is one of the HTTP_Request2::AUTH_* constants.\r
+ *\r
+ * @return array\r
+ */\r
public function getAuth()\r
{\r
return $this->auth;\r
}\r
\r
- /**\r
- * Sets request header(s)\r
- *\r
- * The first parameter may be either a full header string 'header: value' or\r
- * header name. In the former case $value parameter is ignored, in the latter \r
- * the header's value will either be set to $value or the header will be\r
- * removed if $value is null. The first parameter can also be an array of\r
- * headers, in that case method will be called recursively.\r
- *\r
- * Note that headers are treated case insensitively as per RFC 2616.\r
- * \r
- * <code>\r
- * $req->setHeader('Foo: Bar'); // sets the value of 'Foo' header to 'Bar'\r
- * $req->setHeader('FoO', 'Baz'); // sets the value of 'Foo' header to 'Baz'\r
- * $req->setHeader(array('foo' => 'Quux')); // sets the value of 'Foo' header to 'Quux'\r
- * $req->setHeader('FOO'); // removes 'Foo' header from request\r
- * </code>\r
- *\r
- * @param string|array header name, header string ('Header: value')\r
- * or an array of headers\r
- * @param string|null header value, header will be removed if null\r
- * @return HTTP_Request2\r
- * @throws HTTP_Request2_Exception\r
- */\r
- public function setHeader($name, $value = null)\r
+ /**\r
+ * Sets request header(s)\r
+ *\r
+ * The first parameter may be either a full header string 'header: value' or\r
+ * header name. In the former case $value parameter is ignored, in the latter\r
+ * the header's value will either be set to $value or the header will be\r
+ * removed if $value is null. The first parameter can also be an array of\r
+ * headers, in that case method will be called recursively.\r
+ *\r
+ * Note that headers are treated case insensitively as per RFC 2616.\r
+ *\r
+ * <code>\r
+ * $req->setHeader('Foo: Bar'); // sets the value of 'Foo' header to 'Bar'\r
+ * $req->setHeader('FoO', 'Baz'); // sets the value of 'Foo' header to 'Baz'\r
+ * $req->setHeader(array('foo' => 'Quux')); // sets the value of 'Foo' header to 'Quux'\r
+ * $req->setHeader('FOO'); // removes 'Foo' header from request\r
+ * </code>\r
+ *\r
+ * @param string|array $name header name, header string ('Header: value')\r
+ * or an array of headers\r
+ * @param string|array|null $value header value if $name is not an array,\r
+ * header will be removed if value is null\r
+ * @param bool $replace whether to replace previous header with the\r
+ * same name or append to its value\r
+ *\r
+ * @return HTTP_Request2\r
+ * @throws HTTP_Request2_LogicException\r
+ */\r
+ public function setHeader($name, $value = null, $replace = true)\r
{\r
if (is_array($name)) {\r
foreach ($name as $k => $v) {\r
if (is_string($k)) {\r
- $this->setHeader($k, $v);\r
+ $this->setHeader($k, $v, $replace);\r
} else {\r
- $this->setHeader($v);\r
+ $this->setHeader($v, null, $replace);\r
}\r
}\r
} else {\r
}\r
// Header name should be a token: http://tools.ietf.org/html/rfc2616#section-4.2\r
if (preg_match(self::REGEXP_INVALID_TOKEN, $name)) {\r
- throw new HTTP_Request2_Exception("Invalid header name '{$name}'");\r
+ throw new HTTP_Request2_LogicException(\r
+ "Invalid header name '{$name}'",\r
+ HTTP_Request2_Exception::INVALID_ARGUMENT\r
+ );\r
}\r
// Header names are case insensitive anyway\r
$name = strtolower($name);\r
if (null === $value) {\r
unset($this->headers[$name]);\r
+\r
} else {\r
- $this->headers[$name] = $value;\r
+ if (is_array($value)) {\r
+ $value = implode(', ', array_map('trim', $value));\r
+ } elseif (is_string($value)) {\r
+ $value = trim($value);\r
+ }\r
+ if (!isset($this->headers[$name]) || $replace) {\r
+ $this->headers[$name] = $value;\r
+ } else {\r
+ $this->headers[$name] .= ', ' . $value;\r
+ }\r
}\r
}\r
- \r
+\r
return $this;\r
}\r
\r
- /**\r
- * Returns the request headers\r
- *\r
- * The array is of the form ('header name' => 'header value'), header names\r
- * are lowercased\r
- *\r
- * @return array\r
- */\r
+ /**\r
+ * Returns the request headers\r
+ *\r
+ * The array is of the form ('header name' => 'header value'), header names\r
+ * are lowercased\r
+ *\r
+ * @return array\r
+ */\r
public function getHeaders()\r
{\r
return $this->headers;\r
}\r
\r
- /**\r
- * Appends a cookie to "Cookie:" header\r
- *\r
- * @param string cookie name\r
- * @param string cookie value\r
- * @return HTTP_Request2\r
- * @throws HTTP_Request2_Exception\r
- */\r
+ /**\r
+ * Adds a cookie to the request\r
+ *\r
+ * If the request does not have a CookieJar object set, this method simply\r
+ * appends a cookie to "Cookie:" header.\r
+ *\r
+ * If a CookieJar object is available, the cookie is stored in that object.\r
+ * Data from request URL will be used for setting its 'domain' and 'path'\r
+ * parameters, 'expires' and 'secure' will be set to null and false,\r
+ * respectively. If you need further control, use CookieJar's methods.\r
+ *\r
+ * @param string $name cookie name\r
+ * @param string $value cookie value\r
+ *\r
+ * @return HTTP_Request2\r
+ * @throws HTTP_Request2_LogicException\r
+ * @see setCookieJar()\r
+ */\r
public function addCookie($name, $value)\r
{\r
- $cookie = $name . '=' . $value;\r
- if (preg_match(self::REGEXP_INVALID_COOKIE, $cookie)) {\r
- throw new HTTP_Request2_Exception("Invalid cookie: '{$cookie}'");\r
+ if (!empty($this->cookieJar)) {\r
+ $this->cookieJar->store(\r
+ array('name' => $name, 'value' => $value), $this->url\r
+ );\r
+\r
+ } else {\r
+ $cookie = $name . '=' . $value;\r
+ if (preg_match(self::REGEXP_INVALID_COOKIE, $cookie)) {\r
+ throw new HTTP_Request2_LogicException(\r
+ "Invalid cookie: '{$cookie}'",\r
+ HTTP_Request2_Exception::INVALID_ARGUMENT\r
+ );\r
+ }\r
+ $cookies = empty($this->headers['cookie'])? '': $this->headers['cookie'] . '; ';\r
+ $this->setHeader('cookie', $cookies . $cookie);\r
}\r
- $cookies = empty($this->headers['cookie'])? '': $this->headers['cookie'] . '; ';\r
- $this->setHeader('cookie', $cookies . $cookie);\r
\r
return $this;\r
}\r
\r
- /**\r
- * Sets the request body\r
- *\r
- * @param string Either a string with the body or filename containing body\r
- * @param bool Whether first parameter is a filename\r
- * @return HTTP_Request2\r
- * @throws HTTP_Request2_Exception\r
- */\r
+ /**\r
+ * Sets the request body\r
+ *\r
+ * If you provide file pointer rather than file name, it should support\r
+ * fstat() and rewind() operations.\r
+ *\r
+ * @param string|resource|HTTP_Request2_MultipartBody $body Either a\r
+ * string with the body or filename containing body or\r
+ * pointer to an open file or object with multipart body data\r
+ * @param bool $isFilename Whether\r
+ * first parameter is a filename\r
+ *\r
+ * @return HTTP_Request2\r
+ * @throws HTTP_Request2_LogicException\r
+ */\r
public function setBody($body, $isFilename = false)\r
{\r
- if (!$isFilename) {\r
- $this->body = (string)$body;\r
- } else {\r
- if (!($fp = @fopen($body, 'rb'))) {\r
- throw new HTTP_Request2_Exception("Cannot open file {$body}");\r
+ if (!$isFilename && !is_resource($body)) {\r
+ if (!$body instanceof HTTP_Request2_MultipartBody) {\r
+ $this->body = (string)$body;\r
+ } else {\r
+ $this->body = $body;\r
}\r
- $this->body = $fp;\r
+ } else {\r
+ $fileData = $this->fopenWrapper($body, empty($this->headers['content-type']));\r
+ $this->body = $fileData['fp'];\r
if (empty($this->headers['content-type'])) {\r
- $this->setHeader('content-type', self::detectMimeType($body));\r
+ $this->setHeader('content-type', $fileData['type']);\r
}\r
}\r
+ $this->postParams = $this->uploads = array();\r
\r
return $this;\r
}\r
\r
- /**\r
- * Returns the request body\r
- *\r
- * @return string|resource|HTTP_Request2_MultipartBody\r
- */\r
+ /**\r
+ * Returns the request body\r
+ *\r
+ * @return string|resource|HTTP_Request2_MultipartBody\r
+ */\r
public function getBody()\r
{\r
- if (self::METHOD_POST == $this->method && \r
- (!empty($this->postParams) || !empty($this->uploads))\r
+ if (self::METHOD_POST == $this->method\r
+ && (!empty($this->postParams) || !empty($this->uploads))\r
) {\r
- if ('application/x-www-form-urlencoded' == $this->headers['content-type']) {\r
+ if (0 === strpos($this->headers['content-type'], 'application/x-www-form-urlencoded')) {\r
$body = http_build_query($this->postParams, '', '&');\r
if (!$this->getConfig('use_brackets')) {\r
$body = preg_replace('/%5B\d+%5D=/', '=', $body);\r
// support RFC 3986 by not encoding '~' symbol (request #15368)\r
return str_replace('%7E', '~', $body);\r
\r
- } elseif ('multipart/form-data' == $this->headers['content-type']) {\r
+ } elseif (0 === strpos($this->headers['content-type'], 'multipart/form-data')) {\r
require_once 'HTTP/Request2/MultipartBody.php';\r
return new HTTP_Request2_MultipartBody(\r
$this->postParams, $this->uploads, $this->getConfig('use_brackets')\r
return $this->body;\r
}\r
\r
- /**\r
- * Adds a file to form-based file upload\r
- *\r
- * Used to emulate file upload via a HTML form. The method also sets\r
- * Content-Type of HTTP request to 'multipart/form-data'.\r
- *\r
- * If you just want to send the contents of a file as the body of HTTP\r
- * request you should use setBody() method.\r
- *\r
- * @param string name of file-upload field\r
- * @param mixed full name of local file\r
- * @param string filename to send in the request \r
- * @param string content-type of file being uploaded\r
- * @return HTTP_Request2\r
- * @throws HTTP_Request2_Exception\r
- */\r
- public function addUpload($fieldName, $filename, $sendFilename = null,\r
- $contentType = null)\r
- {\r
+ /**\r
+ * Adds a file to form-based file upload\r
+ *\r
+ * Used to emulate file upload via a HTML form. The method also sets\r
+ * Content-Type of HTTP request to 'multipart/form-data'.\r
+ *\r
+ * If you just want to send the contents of a file as the body of HTTP\r
+ * request you should use setBody() method.\r
+ *\r
+ * If you provide file pointers rather than file names, they should support\r
+ * fstat() and rewind() operations.\r
+ *\r
+ * @param string $fieldName name of file-upload field\r
+ * @param string|resource|array $filename full name of local file,\r
+ * pointer to open file or an array of files\r
+ * @param string $sendFilename filename to send in the request\r
+ * @param string $contentType content-type of file being uploaded\r
+ *\r
+ * @return HTTP_Request2\r
+ * @throws HTTP_Request2_LogicException\r
+ */\r
+ public function addUpload(\r
+ $fieldName, $filename, $sendFilename = null, $contentType = null\r
+ ) {\r
if (!is_array($filename)) {\r
- if (!($fp = @fopen($filename, 'rb'))) {\r
- throw new HTTP_Request2_Exception("Cannot open file {$filename}");\r
- }\r
+ $fileData = $this->fopenWrapper($filename, empty($contentType));\r
$this->uploads[$fieldName] = array(\r
- 'fp' => $fp,\r
- 'filename' => empty($sendFilename)? basename($filename): $sendFilename,\r
- 'size' => filesize($filename),\r
- 'type' => empty($contentType)? self::detectMimeType($filename): $contentType\r
+ 'fp' => $fileData['fp'],\r
+ 'filename' => !empty($sendFilename)? $sendFilename\r
+ :(is_string($filename)? basename($filename): 'anonymous.blob') ,\r
+ 'size' => $fileData['size'],\r
+ 'type' => empty($contentType)? $fileData['type']: $contentType\r
);\r
} else {\r
$fps = $names = $sizes = $types = array();\r
if (!is_array($f)) {\r
$f = array($f);\r
}\r
- if (!($fp = @fopen($f[0], 'rb'))) {\r
- throw new HTTP_Request2_Exception("Cannot open file {$f[0]}");\r
- }\r
- $fps[] = $fp;\r
- $names[] = empty($f[1])? basename($f[0]): $f[1];\r
- $sizes[] = filesize($f[0]);\r
- $types[] = empty($f[2])? self::detectMimeType($f[0]): $f[2];\r
+ $fileData = $this->fopenWrapper($f[0], empty($f[2]));\r
+ $fps[] = $fileData['fp'];\r
+ $names[] = !empty($f[1])? $f[1]\r
+ :(is_string($f[0])? basename($f[0]): 'anonymous.blob');\r
+ $sizes[] = $fileData['size'];\r
+ $types[] = empty($f[2])? $fileData['type']: $f[2];\r
}\r
$this->uploads[$fieldName] = array(\r
'fp' => $fps, 'filename' => $names, 'size' => $sizes, 'type' => $types\r
);\r
}\r
- if (empty($this->headers['content-type']) ||\r
- 'application/x-www-form-urlencoded' == $this->headers['content-type']\r
+ if (empty($this->headers['content-type'])\r
+ || 'application/x-www-form-urlencoded' == $this->headers['content-type']\r
) {\r
$this->setHeader('content-type', 'multipart/form-data');\r
}\r
return $this;\r
}\r
\r
- /**\r
- * Adds POST parameter(s) to the request.\r
- *\r
- * @param string|array parameter name or array ('name' => 'value')\r
- * @param mixed parameter value (can be an array)\r
- * @return HTTP_Request2\r
- */\r
+ /**\r
+ * Adds POST parameter(s) to the request.\r
+ *\r
+ * @param string|array $name parameter name or array ('name' => 'value')\r
+ * @param mixed $value parameter value (can be an array)\r
+ *\r
+ * @return HTTP_Request2\r
+ */\r
public function addPostParameter($name, $value = null)\r
{\r
if (!is_array($name)) {\r
return $this;\r
}\r
\r
- /**\r
- * Attaches a new observer\r
- *\r
- * @param SplObserver\r
- */\r
+ /**\r
+ * Attaches a new observer\r
+ *\r
+ * @param SplObserver $observer any object implementing SplObserver\r
+ */\r
public function attach(SplObserver $observer)\r
{\r
foreach ($this->observers as $attached) {\r
$this->observers[] = $observer;\r
}\r
\r
- /**\r
- * Detaches an existing observer\r
- *\r
- * @param SplObserver\r
- */\r
+ /**\r
+ * Detaches an existing observer\r
+ *\r
+ * @param SplObserver $observer any object implementing SplObserver\r
+ */\r
public function detach(SplObserver $observer)\r
{\r
foreach ($this->observers as $key => $attached) {\r
}\r
}\r
\r
- /**\r
- * Notifies all observers\r
- */\r
+ /**\r
+ * Notifies all observers\r
+ */\r
public function notify()\r
{\r
foreach ($this->observers as $observer) {\r
}\r
}\r
\r
- /**\r
- * Sets the last event\r
- *\r
- * Adapters should use this method to set the current state of the request\r
- * and notify the observers.\r
- *\r
- * @param string event name\r
- * @param mixed event data\r
- */\r
+ /**\r
+ * Sets the last event\r
+ *\r
+ * Adapters should use this method to set the current state of the request\r
+ * and notify the observers.\r
+ *\r
+ * @param string $name event name\r
+ * @param mixed $data event data\r
+ */\r
public function setLastEvent($name, $data = null)\r
{\r
$this->lastEvent = array(\r
$this->notify();\r
}\r
\r
- /**\r
- * Returns the last event\r
- *\r
- * Observers should use this method to access the last change in request.\r
- * The following event names are possible:\r
- * <ul>\r
- * <li>'connect' - after connection to remote server,\r
- * data is the destination (string)</li>\r
- * <li>'disconnect' - after disconnection from server</li>\r
- * <li>'sentHeaders' - after sending the request headers,\r
- * data is the headers sent (string)</li>\r
- * <li>'sentBodyPart' - after sending a part of the request body, \r
- * data is the length of that part (int)</li>\r
- * <li>'receivedHeaders' - after receiving the response headers,\r
- * data is HTTP_Request2_Response object</li>\r
- * <li>'receivedBodyPart' - after receiving a part of the response\r
- * body, data is that part (string)</li>\r
- * <li>'receivedEncodedBodyPart' - as 'receivedBodyPart', but data is still\r
- * encoded by Content-Encoding</li>\r
- * <li>'receivedBody' - after receiving the complete response\r
- * body, data is HTTP_Request2_Response object</li>\r
- * </ul>\r
- * Different adapters may not send all the event types. Mock adapter does\r
- * not send any events to the observers.\r
- *\r
- * @return array The array has two keys: 'name' and 'data'\r
- */\r
+ /**\r
+ * Returns the last event\r
+ *\r
+ * Observers should use this method to access the last change in request.\r
+ * The following event names are possible:\r
+ * <ul>\r
+ * <li>'connect' - after connection to remote server,\r
+ * data is the destination (string)</li>\r
+ * <li>'disconnect' - after disconnection from server</li>\r
+ * <li>'sentHeaders' - after sending the request headers,\r
+ * data is the headers sent (string)</li>\r
+ * <li>'sentBodyPart' - after sending a part of the request body,\r
+ * data is the length of that part (int)</li>\r
+ * <li>'sentBody' - after sending the whole request body,\r
+ * data is request body length (int)</li>\r
+ * <li>'receivedHeaders' - after receiving the response headers,\r
+ * data is HTTP_Request2_Response object</li>\r
+ * <li>'receivedBodyPart' - after receiving a part of the response\r
+ * body, data is that part (string)</li>\r
+ * <li>'receivedEncodedBodyPart' - as 'receivedBodyPart', but data is still\r
+ * encoded by Content-Encoding</li>\r
+ * <li>'receivedBody' - after receiving the complete response\r
+ * body, data is HTTP_Request2_Response object</li>\r
+ * </ul>\r
+ * Different adapters may not send all the event types. Mock adapter does\r
+ * not send any events to the observers.\r
+ *\r
+ * @return array The array has two keys: 'name' and 'data'\r
+ */\r
public function getLastEvent()\r
{\r
return $this->lastEvent;\r
}\r
\r
- /**\r
- * Sets the adapter used to actually perform the request\r
- *\r
- * You can pass either an instance of a class implementing HTTP_Request2_Adapter\r
- * or a class name. The method will only try to include a file if the class\r
- * name starts with HTTP_Request2_Adapter_, it will also try to prepend this\r
- * prefix to the class name if it doesn't contain any underscores, so that\r
- * <code>\r
- * $request->setAdapter('curl');\r
- * </code>\r
- * will work.\r
- *\r
- * @param string|HTTP_Request2_Adapter\r
- * @return HTTP_Request2\r
- * @throws HTTP_Request2_Exception\r
- */\r
+ /**\r
+ * Sets the adapter used to actually perform the request\r
+ *\r
+ * You can pass either an instance of a class implementing HTTP_Request2_Adapter\r
+ * or a class name. The method will only try to include a file if the class\r
+ * name starts with HTTP_Request2_Adapter_, it will also try to prepend this\r
+ * prefix to the class name if it doesn't contain any underscores, so that\r
+ * <code>\r
+ * $request->setAdapter('curl');\r
+ * </code>\r
+ * will work.\r
+ *\r
+ * @param string|HTTP_Request2_Adapter $adapter Adapter to use\r
+ *\r
+ * @return HTTP_Request2\r
+ * @throws HTTP_Request2_LogicException\r
+ */\r
public function setAdapter($adapter)\r
{\r
if (is_string($adapter)) {\r
if (false === strpos($adapter, '_')) {\r
$adapter = 'HTTP_Request2_Adapter_' . ucfirst($adapter);\r
}\r
- if (preg_match('/^HTTP_Request2_Adapter_([a-zA-Z0-9]+)$/', $adapter)) {\r
+ if (!class_exists($adapter, false)\r
+ && preg_match('/^HTTP_Request2_Adapter_([a-zA-Z0-9]+)$/', $adapter)\r
+ ) {\r
include_once str_replace('_', DIRECTORY_SEPARATOR, $adapter) . '.php';\r
}\r
if (!class_exists($adapter, false)) {\r
- throw new HTTP_Request2_Exception("Class {$adapter} not found");\r
+ throw new HTTP_Request2_LogicException(\r
+ "Class {$adapter} not found",\r
+ HTTP_Request2_Exception::MISSING_VALUE\r
+ );\r
}\r
}\r
$adapter = new $adapter;\r
}\r
if (!$adapter instanceof HTTP_Request2_Adapter) {\r
- throw new HTTP_Request2_Exception('Parameter is not a HTTP request adapter');\r
+ throw new HTTP_Request2_LogicException(\r
+ 'Parameter is not a HTTP request adapter',\r
+ HTTP_Request2_Exception::INVALID_ARGUMENT\r
+ );\r
}\r
$this->adapter = $adapter;\r
\r
return $this;\r
}\r
\r
- /**\r
- * Sends the request and returns the response\r
- *\r
- * @throws HTTP_Request2_Exception\r
- * @return HTTP_Request2_Response\r
- */\r
+ /**\r
+ * Sets the cookie jar\r
+ *\r
+ * A cookie jar is used to maintain cookies across HTTP requests and\r
+ * responses. Cookies from jar will be automatically added to the request\r
+ * headers based on request URL.\r
+ *\r
+ * @param HTTP_Request2_CookieJar|bool $jar Existing CookieJar object, true to\r
+ * create a new one, false to remove\r
+ *\r
+ * @return HTTP_Request2\r
+ * @throws HTTP_Request2_LogicException\r
+ */\r
+ public function setCookieJar($jar = true)\r
+ {\r
+ if (!class_exists('HTTP_Request2_CookieJar', false)) {\r
+ require_once 'HTTP/Request2/CookieJar.php';\r
+ }\r
+\r
+ if ($jar instanceof HTTP_Request2_CookieJar) {\r
+ $this->cookieJar = $jar;\r
+ } elseif (true === $jar) {\r
+ $this->cookieJar = new HTTP_Request2_CookieJar();\r
+ } elseif (!$jar) {\r
+ $this->cookieJar = null;\r
+ } else {\r
+ throw new HTTP_Request2_LogicException(\r
+ 'Invalid parameter passed to setCookieJar()',\r
+ HTTP_Request2_Exception::INVALID_ARGUMENT\r
+ );\r
+ }\r
+\r
+ return $this;\r
+ }\r
+\r
+ /**\r
+ * Returns current CookieJar object or null if none\r
+ *\r
+ * @return HTTP_Request2_CookieJar|null\r
+ */\r
+ public function getCookieJar()\r
+ {\r
+ return $this->cookieJar;\r
+ }\r
+\r
+ /**\r
+ * Sends the request and returns the response\r
+ *\r
+ * @throws HTTP_Request2_Exception\r
+ * @return HTTP_Request2_Response\r
+ */\r
public function send()\r
{\r
// Sanity check for URL\r
- if (!$this->url instanceof Net_URL2) {\r
- throw new HTTP_Request2_Exception('No URL given');\r
- } elseif (!$this->url->isAbsolute()) {\r
- throw new HTTP_Request2_Exception('Absolute URL required');\r
- } elseif (!in_array(strtolower($this->url->getScheme()), array('https', 'http'))) {\r
- throw new HTTP_Request2_Exception('Not a HTTP URL');\r
+ if (!$this->url instanceof Net_URL2\r
+ || !$this->url->isAbsolute()\r
+ || !in_array(strtolower($this->url->getScheme()), array('https', 'http'))\r
+ ) {\r
+ throw new HTTP_Request2_LogicException(\r
+ 'HTTP_Request2 needs an absolute HTTP(S) request URL, '\r
+ . ($this->url instanceof Net_URL2\r
+ ? "'" . $this->url->__toString() . "'" : 'none')\r
+ . ' given',\r
+ HTTP_Request2_Exception::INVALID_ARGUMENT\r
+ );\r
}\r
if (empty($this->adapter)) {\r
$this->setAdapter($this->getConfig('adapter'));\r
}\r
// magic_quotes_runtime may break file uploads and chunked response\r
- // processing; see bug #4543\r
- if ($magicQuotes = ini_get('magic_quotes_runtime')) {\r
- ini_set('magic_quotes_runtime', false);\r
+ // processing; see bug #4543. Don't use ini_get() here; see bug #16440.\r
+ if ($magicQuotes = get_magic_quotes_runtime()) {\r
+ set_magic_quotes_runtime(false);\r
}\r
// force using single byte encoding if mbstring extension overloads\r
// strlen() and substr(); see bug #1781, bug #10605\r
if (extension_loaded('mbstring') && (2 & ini_get('mbstring.func_overload'))) {\r
$oldEncoding = mb_internal_encoding();\r
- mb_internal_encoding('iso-8859-1');\r
+ mb_internal_encoding('8bit');\r
}\r
\r
try {\r
}\r
// cleanup in either case (poor man's "finally" clause)\r
if ($magicQuotes) {\r
- ini_set('magic_quotes_runtime', true);\r
+ set_magic_quotes_runtime(true);\r
}\r
if (!empty($oldEncoding)) {\r
mb_internal_encoding($oldEncoding);\r
return $response;\r
}\r
\r
- /**\r
- * Tries to detect MIME type of a file\r
- *\r
- * The method will try to use fileinfo extension if it is available,\r
- * deprecated mime_content_type() function in the other case. If neither\r
- * works, default 'application/octet-stream' MIME type is returned\r
- *\r
- * @param string filename\r
- * @return string file MIME type\r
- */\r
+ /**\r
+ * Wrapper around fopen()/fstat() used by setBody() and addUpload()\r
+ *\r
+ * @param string|resource $file file name or pointer to open file\r
+ * @param bool $detectType whether to try autodetecting MIME\r
+ * type of file, will only work if $file is a\r
+ * filename, not pointer\r
+ *\r
+ * @return array array('fp' => file pointer, 'size' => file size, 'type' => MIME type)\r
+ * @throws HTTP_Request2_LogicException\r
+ */\r
+ protected function fopenWrapper($file, $detectType = false)\r
+ {\r
+ if (!is_string($file) && !is_resource($file)) {\r
+ throw new HTTP_Request2_LogicException(\r
+ "Filename or file pointer resource expected",\r
+ HTTP_Request2_Exception::INVALID_ARGUMENT\r
+ );\r
+ }\r
+ $fileData = array(\r
+ 'fp' => is_string($file)? null: $file,\r
+ 'type' => 'application/octet-stream',\r
+ 'size' => 0\r
+ );\r
+ if (is_string($file)) {\r
+ if (!($fileData['fp'] = @fopen($file, 'rb'))) {\r
+ $error = error_get_last();\r
+ throw new HTTP_Request2_LogicException(\r
+ $error['message'], HTTP_Request2_Exception::READ_ERROR\r
+ );\r
+ }\r
+ if ($detectType) {\r
+ $fileData['type'] = self::detectMimeType($file);\r
+ }\r
+ }\r
+ if (!($stat = fstat($fileData['fp']))) {\r
+ throw new HTTP_Request2_LogicException(\r
+ "fstat() call failed", HTTP_Request2_Exception::READ_ERROR\r
+ );\r
+ }\r
+ $fileData['size'] = $stat['size'];\r
+\r
+ return $fileData;\r
+ }\r
+\r
+ /**\r
+ * Tries to detect MIME type of a file\r
+ *\r
+ * The method will try to use fileinfo extension if it is available,\r
+ * deprecated mime_content_type() function in the other case. If neither\r
+ * works, default 'application/octet-stream' MIME type is returned\r
+ *\r
+ * @param string $filename file name\r
+ *\r
+ * @return string file MIME type\r
+ */\r
protected static function detectMimeType($filename)\r
{\r
- // finfo extension from PECL available \r
+ // finfo extension from PECL available\r
if (function_exists('finfo_open')) {\r
if (!isset(self::$_fileinfoDb)) {\r
self::$_fileinfoDb = @finfo_open(FILEINFO_MIME);\r
}\r
- if (self::$_fileinfoDb) { \r
+ if (self::$_fileinfoDb) {\r
$info = finfo_file(self::$_fileinfoDb, $filename);\r
}\r
}\r
return empty($info)? 'application/octet-stream': $info;\r
}\r
}\r
-?>
\ No newline at end of file
+?>\r