]> git.mxchange.org Git - quix0rs-gnu-social.git/blobdiff - extlib/HTTP/Request2.php
Merge branch '1.0.x' into testing
[quix0rs-gnu-social.git] / extlib / HTTP / Request2.php
index e06bb86bca0ca270915ccb28c269464cae35a822..60beeaf2ef5f88f547b33e04f7c89ef32026714c 100644 (file)
@@ -1,12 +1,12 @@
 <?php\r
 /**\r
- * Class representing a HTTP request\r
+ * Class representing a HTTP request message\r
  *\r
  * PHP version 5\r
  *\r
  * LICENSE:\r
  *\r
- * Copyright (c) 2008, 2009, Alexey Borzov <avb@php.net>\r
+ * Copyright (c) 2008-2011, Alexey Borzov <avb@php.net>\r
  * All rights reserved.\r
  *\r
  * Redistribution and use in source and binary forms, with or without\r
@@ -37,7 +37,7 @@
  * @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
+ * @version    SVN: $Id: Request2.php 308735 2011-02-27 20:31:28Z avb $\r
  * @link       http://pear.php.net/package/HTTP_Request2\r
  */\r
 \r
@@ -48,16 +48,16 @@ require_once 'Net/URL2.php';
 \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
+ * @version    Release: 2.0.0RC1\r
  * @link       http://tools.ietf.org/html/rfc2616#section-5\r
  */\r
 class HTTP_Request2 implements SplSubject\r
@@ -78,7 +78,7 @@ class HTTP_Request2 implements SplSubject
    /**#@-*/\r
 \r
    /**#@+\r
-    * Constants for HTTP authentication schemes \r
+    * Constants for HTTP authentication schemes\r
     *\r
     * @link http://tools.ietf.org/html/rfc2617\r
     */\r
@@ -95,7 +95,7 @@ class HTTP_Request2 implements SplSubject
    /**\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
+    * @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
@@ -164,7 +164,11 @@ class HTTP_Request2 implements SplSubject
         '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
@@ -191,7 +195,7 @@ class HTTP_Request2 implements SplSubject
     protected $postParams = array();\r
 \r
    /**\r
-    * Array of file uploads (for multipart/form-data POST requests) \r
+    * Array of file uploads (for multipart/form-data POST requests)\r
     * @var  array\r
     */\r
     protected $uploads = array();\r
@@ -202,11 +206,16 @@ class HTTP_Request2 implements SplSubject
     */\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
+    * Also sets a default value for User-Agent header.\r
     *\r
     * @param    string|Net_Url2     Request URL\r
     * @param    string              Request method\r
@@ -214,14 +223,14 @@ class HTTP_Request2 implements SplSubject
     */\r
     public function __construct($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
+        $this->setHeader('user-agent', 'HTTP_Request2/2.0.0RC1 ' .\r
                          '(http://pear.php.net/package/http_request2) ' .\r
                          'PHP/' . phpversion());\r
     }\r
@@ -235,15 +244,20 @@ class HTTP_Request2 implements SplSubject
     *\r
     * @param    string|Net_URL2 Request URL\r
     * @return   HTTP_Request2\r
-    * @throws   HTTP_Request2_Exception\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
@@ -275,13 +289,16 @@ class HTTP_Request2 implements SplSubject
     *\r
     * @param    string\r
     * @return   HTTP_Request2\r
-    * @throws   HTTP_Request2_Exception if the method name is invalid\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
@@ -306,7 +323,7 @@ class HTTP_Request2 implements SplSubject
     *   <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
+    *                              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
@@ -324,7 +341,7 @@ class HTTP_Request2 implements SplSubject
     *                              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
+    *   <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
@@ -332,13 +349,19 @@ class HTTP_Request2 implements SplSubject
     *   <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    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
+    * @throws   HTTP_Request2_LogicException If the parameter is unknown\r
     */\r
     public function setConfig($nameOrConfig, $value = null)\r
     {\r
@@ -349,8 +372,9 @@ class HTTP_Request2 implements SplSubject
 \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
@@ -363,17 +387,18 @@ class HTTP_Request2 implements SplSubject
     * 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
+    * @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
+    * @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
@@ -386,7 +411,7 @@ class HTTP_Request2 implements SplSubject
     * @param    string  password\r
     * @param    string  authentication scheme\r
     * @return   HTTP_Request2\r
-    */ \r
+    */\r
     public function setAuth($user, $password = '', $scheme = self::AUTH_BASIC)\r
     {\r
         if (empty($user)) {\r
@@ -419,13 +444,13 @@ class HTTP_Request2 implements SplSubject
     * 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
+    * 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
+    *\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
@@ -435,18 +460,21 @@ class HTTP_Request2 implements SplSubject
     *\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
+    * @param    string|array|null header value if $name is not an array,\r
+    *                           header will be removed if value is null\r
+    * @param    bool            whether to replace previous header with the\r
+    *                           same name or append to its value\r
     * @return   HTTP_Request2\r
-    * @throws   HTTP_Request2_Exception\r
+    * @throws   HTTP_Request2_LogicException\r
     */\r
-    public function setHeader($name, $value = null)\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
@@ -455,17 +483,30 @@ class HTTP_Request2 implements SplSubject
             }\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
@@ -483,21 +524,39 @@ class HTTP_Request2 implements SplSubject
     }\r
 \r
    /**\r
-    * Appends a cookie to "Cookie:" header\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  cookie name\r
     * @param    string  cookie value\r
     * @return   HTTP_Request2\r
-    * @throws   HTTP_Request2_Exception\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(array('name' => $name, 'value' => $value),\r
+                                    $this->url);\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
@@ -505,24 +564,32 @@ class HTTP_Request2 implements SplSubject
    /**\r
     * Sets the request body\r
     *\r
-    * @param    string  Either a string with the body or filename containing body\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  Either a string\r
+    *               with the body or filename containing body or pointer to\r
+    *               an open file or object with multipart body data\r
     * @param    bool    Whether first parameter is a filename\r
     * @return   HTTP_Request2\r
-    * @throws   HTTP_Request2_Exception\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
@@ -534,10 +601,10 @@ class HTTP_Request2 implements SplSubject
     */\r
     public function getBody()\r
     {\r
-        if (self::METHOD_POST == $this->method && \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
@@ -545,7 +612,7 @@ class HTTP_Request2 implements SplSubject
                 // 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
@@ -564,25 +631,28 @@ class HTTP_Request2 implements SplSubject
     * 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  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|resource|array   full name of local file, pointer to\r
+    *               open file or an array of files\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
+    * @throws   HTTP_Request2_LogicException\r
     */\r
     public function addUpload($fieldName, $filename, $sendFilename = null,\r
                               $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
@@ -590,13 +660,12 @@ class HTTP_Request2 implements SplSubject
                 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
@@ -703,8 +772,10 @@ class HTTP_Request2 implements SplSubject
     *   <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
+    *   <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
@@ -738,7 +809,7 @@ class HTTP_Request2 implements SplSubject
     *\r
     * @param    string|HTTP_Request2_Adapter\r
     * @return   HTTP_Request2\r
-    * @throws   HTTP_Request2_Exception\r
+    * @throws   HTTP_Request2_LogicException\r
     */\r
     public function setAdapter($adapter)\r
     {\r
@@ -751,19 +822,67 @@ class HTTP_Request2 implements SplSubject
                     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
+    * 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   Existing CookieJar object, true to\r
+    *                                       create a new one, false to remove\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
@@ -773,20 +892,25 @@ class HTTP_Request2 implements SplSubject
     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
+                   ? 'none' : "'" . $this->url->__toString() . "'")\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
@@ -801,7 +925,7 @@ class HTTP_Request2 implements SplSubject
         }\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
@@ -813,6 +937,53 @@ class HTTP_Request2 implements SplSubject
         return $response;\r
     }\r
 \r
+   /**\r
+    * Wrapper around fopen()/fstat() used by setBody() and addUpload()\r
+    *\r
+    * @param  string|resource file name or pointer to open file\r
+    * @param  bool            whether to try autodetecting MIME type of file,\r
+    *                         will only work if $file is a filename, not pointer\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
+            $track = @ini_set('track_errors', 1);\r
+            if (!($fileData['fp'] = @fopen($file, 'rb'))) {\r
+                $e = new HTTP_Request2_LogicException(\r
+                    $php_errormsg, HTTP_Request2_Exception::READ_ERROR\r
+                );\r
+            }\r
+            @ini_set('track_errors', $track);\r
+            if (isset($e)) {\r
+                throw $e;\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
@@ -825,12 +996,12 @@ class HTTP_Request2 implements SplSubject
     */\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