]> git.mxchange.org Git - quix0rs-gnu-social.git/blobdiff - extlib/HTTP/Request2.php
Rebuilt HTTPClient class as an extension of PEAR HTTP_Request2 package, adding redire...
[quix0rs-gnu-social.git] / extlib / HTTP / Request2.php
diff --git a/extlib/HTTP/Request2.php b/extlib/HTTP/Request2.php
new file mode 100644 (file)
index 0000000..e06bb86
--- /dev/null
@@ -0,0 +1,844 @@
+<?php\r
+/**\r
+ * Class representing a HTTP request\r
+ *\r
+ * PHP version 5\r
+ *\r
+ * LICENSE:\r
+ *\r
+ * Copyright (c) 2008, 2009, Alexey Borzov <avb@php.net>\r
+ * All rights reserved.\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
+ */\r
+\r
+/**\r
+ * A class representing an URL as per RFC 3986.\r
+ */\r
+require_once 'Net/URL2.php';\r
+\r
+/**\r
+ * Exception class for HTTP_Request2 package\r
+ */ \r
+require_once 'HTTP/Request2/Exception.php';\r
+\r
+/**\r
+ * Class representing a HTTP request\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
+ */\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
+    const METHOD_OPTIONS = 'OPTIONS';\r
+    const METHOD_GET     = 'GET';\r
+    const METHOD_HEAD    = 'HEAD';\r
+    const METHOD_POST    = 'POST';\r
+    const METHOD_PUT     = 'PUT';\r
+    const METHOD_DELETE  = 'DELETE';\r
+    const METHOD_TRACE   = 'TRACE';\r
+    const METHOD_CONNECT = 'CONNECT';\r
+   /**#@-*/\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
+    * 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
+    const REGEXP_INVALID_COOKIE = '/[\s,;]/';\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
+    protected $observers = array();\r
+\r
+   /**\r
+    * Request URL\r
+    * @var  Net_URL2\r
+    */\r
+    protected $url;\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
+    protected $auth;\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
+    protected $config = array(\r
+        'adapter'           => 'HTTP_Request2_Adapter_Socket',\r
+        'connect_timeout'   => 10,\r
+        'timeout'           => 0,\r
+        'use_brackets'      => true,\r
+        'protocol_version'  => '1.1',\r
+        'buffer_size'       => 16384,\r
+        'store_body'        => true,\r
+\r
+        'proxy_host'        => '',\r
+        'proxy_port'        => '',\r
+        'proxy_user'        => '',\r
+        'proxy_password'    => '',\r
+        'proxy_auth_scheme' => self::AUTH_BASIC,\r
+\r
+        'ssl_verify_peer'   => true,\r
+        'ssl_verify_host'   => true,\r
+        'ssl_cafile'        => null,\r
+        'ssl_capath'        => null,\r
+        'ssl_local_cert'    => null,\r
+        'ssl_passphrase'    => null,\r
+\r
+        'digest_compat_ie'  => false\r
+    );\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
+    protected $body = '';\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
+    protected $uploads = array();\r
+\r
+   /**\r
+    * Adapter used to perform actual HTTP request\r
+    * @var  HTTP_Request2_Adapter\r
+    */\r
+    protected $adapter;\r
+\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
+        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
+    }\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
+    public function setUrl($url)\r
+    {\r
+        if (is_string($url)) {\r
+            $url = new Net_URL2($url);\r
+        }\r
+        if (!$url instanceof Net_URL2) {\r
+            throw new HTTP_Request2_Exception('Parameter is not a valid HTTP URL');\r
+        }\r
+        // URL contains username / password?\r
+        if ($url->getUserinfo()) {\r
+            $username = $url->getUser();\r
+            $password = $url->getPassword();\r
+            $this->setAuth(rawurldecode($username), $password? rawurldecode($password): '');\r
+            $url->setUserinfo('');\r
+        }\r
+        if ('' == $url->getPath()) {\r
+            $url->setPath('/');\r
+        }\r
+        $this->url = $url;\r
+\r
+        return $this;\r
+    }\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
+    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
+        }\r
+        $this->method = $method;\r
+\r
+        return $this;\r
+    }\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
+    public function setConfig($nameOrConfig, $value = null)\r
+    {\r
+        if (is_array($nameOrConfig)) {\r
+            foreach ($nameOrConfig as $name => $value) {\r
+                $this->setConfig($name, $value);\r
+            }\r
+\r
+        } else {\r
+            if (!array_key_exists($nameOrConfig, $this->config)) {\r
+                throw new HTTP_Request2_Exception(\r
+                    "Unknown configuration parameter '{$nameOrConfig}'"\r
+                );\r
+            }\r
+            $this->config[$nameOrConfig] = $value;\r
+        }\r
+\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
+    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
+            );\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
+    public function setAuth($user, $password = '', $scheme = self::AUTH_BASIC)\r
+    {\r
+        if (empty($user)) {\r
+            $this->auth = null;\r
+        } else {\r
+            $this->auth = array(\r
+                'user'     => (string)$user,\r
+                'password' => (string)$password,\r
+                'scheme'   => $scheme\r
+            );\r
+        }\r
+\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
+    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
+        if (is_array($name)) {\r
+            foreach ($name as $k => $v) {\r
+                if (is_string($k)) {\r
+                    $this->setHeader($k, $v);\r
+                } else {\r
+                    $this->setHeader($v);\r
+                }\r
+            }\r
+        } else {\r
+            if (null === $value && strpos($name, ':')) {\r
+                list($name, $value) = array_map('trim', explode(':', $name, 2));\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
+            }\r
+            // Header names are case insensitive anyway\r
+            $name = strtolower($name);\r
+            if (null === $value) {\r
+                unset($this->headers[$name]);\r
+            } else {\r
+                $this->headers[$name] = $value;\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
+    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
+    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
+        }\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
+    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
+            }\r
+            $this->body = $fp;\r
+            if (empty($this->headers['content-type'])) {\r
+                $this->setHeader('content-type', self::detectMimeType($body));\r
+            }\r
+        }\r
+\r
+        return $this;\r
+    }\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
+        ) {\r
+            if ('application/x-www-form-urlencoded' == $this->headers['content-type']) {\r
+                $body = http_build_query($this->postParams, '', '&');\r
+                if (!$this->getConfig('use_brackets')) {\r
+                    $body = preg_replace('/%5B\d+%5D=/', '=', $body);\r
+                }\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
+                require_once 'HTTP/Request2/MultipartBody.php';\r
+                return new HTTP_Request2_MultipartBody(\r
+                    $this->postParams, $this->uploads, $this->getConfig('use_brackets')\r
+                );\r
+            }\r
+        }\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
+        if (!is_array($filename)) {\r
+            if (!($fp = @fopen($filename, 'rb'))) {\r
+                throw new HTTP_Request2_Exception("Cannot open file {$filename}");\r
+            }\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
+            );\r
+        } else {\r
+            $fps = $names = $sizes = $types = array();\r
+            foreach ($filename as $f) {\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
+            }\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
+        ) {\r
+            $this->setHeader('content-type', 'multipart/form-data');\r
+        }\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
+    public function addPostParameter($name, $value = null)\r
+    {\r
+        if (!is_array($name)) {\r
+            $this->postParams[$name] = $value;\r
+        } else {\r
+            foreach ($name as $k => $v) {\r
+                $this->addPostParameter($k, $v);\r
+            }\r
+        }\r
+        if (empty($this->headers['content-type'])) {\r
+            $this->setHeader('content-type', 'application/x-www-form-urlencoded');\r
+        }\r
+\r
+        return $this;\r
+    }\r
+\r
+   /**\r
+    * Attaches a new observer\r
+    *\r
+    * @param    SplObserver\r
+    */\r
+    public function attach(SplObserver $observer)\r
+    {\r
+        foreach ($this->observers as $attached) {\r
+            if ($attached === $observer) {\r
+                return;\r
+            }\r
+        }\r
+        $this->observers[] = $observer;\r
+    }\r
+\r
+   /**\r
+    * Detaches an existing observer\r
+    *\r
+    * @param    SplObserver\r
+    */\r
+    public function detach(SplObserver $observer)\r
+    {\r
+        foreach ($this->observers as $key => $attached) {\r
+            if ($attached === $observer) {\r
+                unset($this->observers[$key]);\r
+                return;\r
+            }\r
+        }\r
+    }\r
+\r
+   /**\r
+    * Notifies all observers\r
+    */\r
+    public function notify()\r
+    {\r
+        foreach ($this->observers as $observer) {\r
+            $observer->update($this);\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
+    public function setLastEvent($name, $data = null)\r
+    {\r
+        $this->lastEvent = array(\r
+            'name' => $name,\r
+            'data' => $data\r
+        );\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
+    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
+    public function setAdapter($adapter)\r
+    {\r
+        if (is_string($adapter)) {\r
+            if (!class_exists($adapter, false)) {\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
+                    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
+                }\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
+        }\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
+    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
+        }\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
+        }\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
+        }\r
+\r
+        try {\r
+            $response = $this->adapter->sendRequest($this);\r
+        } catch (Exception $e) {\r
+        }\r
+        // cleanup in either case (poor man's "finally" clause)\r
+        if ($magicQuotes) {\r
+            ini_set('magic_quotes_runtime', true);\r
+        }\r
+        if (!empty($oldEncoding)) {\r
+            mb_internal_encoding($oldEncoding);\r
+        }\r
+        // rethrow the exception\r
+        if (!empty($e)) {\r
+            throw $e;\r
+        }\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
+    protected static function detectMimeType($filename)\r
+    {\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
+                $info = finfo_file(self::$_fileinfoDb, $filename);\r
+            }\r
+        }\r
+        // (deprecated) mime_content_type function available\r
+        if (empty($info) && function_exists('mime_content_type')) {\r
+            return mime_content_type($filename);\r
+        }\r
+        return empty($info)? 'application/octet-stream': $info;\r
+    }\r
+}\r
+?>
\ No newline at end of file