]> git.mxchange.org Git - quix0rs-gnu-social.git/blobdiff - extlib/HTTP/Request2/Adapter/Socket.php
Revert "Rebuilt HTTPClient class as an extension of PEAR HTTP_Request2 package, addin...
[quix0rs-gnu-social.git] / extlib / HTTP / Request2 / Adapter / Socket.php
diff --git a/extlib/HTTP/Request2/Adapter/Socket.php b/extlib/HTTP/Request2/Adapter/Socket.php
deleted file mode 100644 (file)
index ff44d49..0000000
+++ /dev/null
@@ -1,971 +0,0 @@
-<?php\r
-/**\r
- * Socket-based adapter for HTTP_Request2\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: Socket.php 279760 2009-05-03 10:46:42Z avb $\r
- * @link       http://pear.php.net/package/HTTP_Request2\r
- */\r
-\r
-/**\r
- * Base class for HTTP_Request2 adapters\r
- */\r
-require_once 'HTTP/Request2/Adapter.php';\r
-\r
-/**\r
- * Socket-based adapter for HTTP_Request2\r
- *\r
- * This adapter uses only PHP sockets and will work on almost any PHP\r
- * environment. Code is based on original HTTP_Request PEAR package.\r
- *\r
- * @category    HTTP\r
- * @package     HTTP_Request2\r
- * @author      Alexey Borzov <avb@php.net>\r
- * @version     Release: 0.4.1\r
- */\r
-class HTTP_Request2_Adapter_Socket extends HTTP_Request2_Adapter\r
-{\r
-   /**\r
-    * Regular expression for 'token' rule from RFC 2616\r
-    */ \r
-    const REGEXP_TOKEN = '[^\x00-\x1f\x7f-\xff()<>@,;:\\\\"/\[\]?={}\s]+';\r
-\r
-   /**\r
-    * Regular expression for 'quoted-string' rule from RFC 2616\r
-    */\r
-    const REGEXP_QUOTED_STRING = '"(?:\\\\.|[^\\\\"])*"';\r
-\r
-   /**\r
-    * Connected sockets, needed for Keep-Alive support\r
-    * @var  array\r
-    * @see  connect()\r
-    */\r
-    protected static $sockets = array();\r
-\r
-   /**\r
-    * Data for digest authentication scheme\r
-    *\r
-    * The keys for the array are URL prefixes. \r
-    *\r
-    * The values are associative arrays with data (realm, nonce, nonce-count, \r
-    * opaque...) needed for digest authentication. Stored here to prevent making \r
-    * duplicate requests to digest-protected resources after we have already \r
-    * received the challenge.\r
-    *\r
-    * @var  array\r
-    */\r
-    protected static $challenges = array();\r
-\r
-   /**\r
-    * Connected socket\r
-    * @var  resource\r
-    * @see  connect()\r
-    */\r
-    protected $socket;\r
-\r
-   /**\r
-    * Challenge used for server digest authentication\r
-    * @var  array\r
-    */\r
-    protected $serverChallenge;\r
-\r
-   /**\r
-    * Challenge used for proxy digest authentication\r
-    * @var  array\r
-    */\r
-    protected $proxyChallenge;\r
-\r
-   /**\r
-    * Global timeout, exception will be raised if request continues past this time\r
-    * @var  integer\r
-    */\r
-    protected $timeout = null;\r
-\r
-   /**\r
-    * Remaining length of the current chunk, when reading chunked response\r
-    * @var  integer\r
-    * @see  readChunked()\r
-    */ \r
-    protected $chunkLength = 0;\r
-\r
-   /**\r
-    * Sends request to the remote server and returns its response\r
-    *\r
-    * @param    HTTP_Request2\r
-    * @return   HTTP_Request2_Response\r
-    * @throws   HTTP_Request2_Exception\r
-    */\r
-    public function sendRequest(HTTP_Request2 $request)\r
-    {\r
-        $this->request = $request;\r
-        $keepAlive     = $this->connect();\r
-        $headers       = $this->prepareHeaders();\r
-\r
-        // Use global request timeout if given, see feature requests #5735, #8964 \r
-        if ($timeout = $request->getConfig('timeout')) {\r
-            $this->timeout = time() + $timeout;\r
-        } else {\r
-            $this->timeout = null;\r
-        }\r
-\r
-        try {\r
-            if (false === @fwrite($this->socket, $headers, strlen($headers))) {\r
-                throw new HTTP_Request2_Exception('Error writing request');\r
-            }\r
-            // provide request headers to the observer, see request #7633\r
-            $this->request->setLastEvent('sentHeaders', $headers);\r
-            $this->writeBody();\r
-\r
-            if ($this->timeout && time() > $this->timeout) {\r
-                throw new HTTP_Request2_Exception(\r
-                    'Request timed out after ' . \r
-                    $request->getConfig('timeout') . ' second(s)'\r
-                );\r
-            }\r
-\r
-            $response = $this->readResponse();\r
-\r
-            if (!$this->canKeepAlive($keepAlive, $response)) {\r
-                $this->disconnect();\r
-            }\r
-\r
-            if ($this->shouldUseProxyDigestAuth($response)) {\r
-                return $this->sendRequest($request);\r
-            }\r
-            if ($this->shouldUseServerDigestAuth($response)) {\r
-                return $this->sendRequest($request);\r
-            }\r
-            if ($authInfo = $response->getHeader('authentication-info')) {\r
-                $this->updateChallenge($this->serverChallenge, $authInfo);\r
-            }\r
-            if ($proxyInfo = $response->getHeader('proxy-authentication-info')) {\r
-                $this->updateChallenge($this->proxyChallenge, $proxyInfo);\r
-            }\r
-\r
-        } catch (Exception $e) {\r
-            $this->disconnect();\r
-            throw $e;\r
-        }\r
-\r
-        return $response;\r
-    }\r
-\r
-   /**\r
-    * Connects to the remote server\r
-    *\r
-    * @return   bool    whether the connection can be persistent\r
-    * @throws   HTTP_Request2_Exception\r
-    */\r
-    protected function connect()\r
-    {\r
-        $secure  = 0 == strcasecmp($this->request->getUrl()->getScheme(), 'https');\r
-        $tunnel  = HTTP_Request2::METHOD_CONNECT == $this->request->getMethod();\r
-        $headers = $this->request->getHeaders();\r
-        $reqHost = $this->request->getUrl()->getHost();\r
-        if (!($reqPort = $this->request->getUrl()->getPort())) {\r
-            $reqPort = $secure? 443: 80;\r
-        }\r
-\r
-        if ($host = $this->request->getConfig('proxy_host')) {\r
-            if (!($port = $this->request->getConfig('proxy_port'))) {\r
-                throw new HTTP_Request2_Exception('Proxy port not provided');\r
-            }\r
-            $proxy = true;\r
-        } else {\r
-            $host  = $reqHost;\r
-            $port  = $reqPort;\r
-            $proxy = false;\r
-        }\r
-\r
-        if ($tunnel && !$proxy) {\r
-            throw new HTTP_Request2_Exception(\r
-                "Trying to perform CONNECT request without proxy"\r
-            );\r
-        }\r
-        if ($secure && !in_array('ssl', stream_get_transports())) {\r
-            throw new HTTP_Request2_Exception(\r
-                'Need OpenSSL support for https:// requests'\r
-            );\r
-        }\r
-\r
-        // RFC 2068, section 19.7.1: A client MUST NOT send the Keep-Alive\r
-        // connection token to a proxy server...\r
-        if ($proxy && !$secure && \r
-            !empty($headers['connection']) && 'Keep-Alive' == $headers['connection']\r
-        ) {\r
-            $this->request->setHeader('connection');\r
-        }\r
-\r
-        $keepAlive = ('1.1' == $this->request->getConfig('protocol_version') && \r
-                      empty($headers['connection'])) ||\r
-                     (!empty($headers['connection']) &&\r
-                      'Keep-Alive' == $headers['connection']);\r
-        $host = ((!$secure || $proxy)? 'tcp://': 'ssl://') . $host;\r
-\r
-        $options = array();\r
-        if ($secure || $tunnel) {\r
-            foreach ($this->request->getConfig() as $name => $value) {\r
-                if ('ssl_' == substr($name, 0, 4) && null !== $value) {\r
-                    if ('ssl_verify_host' == $name) {\r
-                        if ($value) {\r
-                            $options['CN_match'] = $reqHost;\r
-                        }\r
-                    } else {\r
-                        $options[substr($name, 4)] = $value;\r
-                    }\r
-                }\r
-            }\r
-            ksort($options);\r
-        }\r
-\r
-        // Changing SSL context options after connection is established does *not*\r
-        // work, we need a new connection if options change\r
-        $remote    = $host . ':' . $port;\r
-        $socketKey = $remote . (($secure && $proxy)? "->{$reqHost}:{$reqPort}": '') .\r
-                     (empty($options)? '': ':' . serialize($options));\r
-        unset($this->socket);\r
-\r
-        // We use persistent connections and have a connected socket?\r
-        // Ensure that the socket is still connected, see bug #16149\r
-        if ($keepAlive && !empty(self::$sockets[$socketKey]) &&\r
-            !feof(self::$sockets[$socketKey])\r
-        ) {\r
-            $this->socket =& self::$sockets[$socketKey];\r
-\r
-        } elseif ($secure && $proxy && !$tunnel) {\r
-            $this->establishTunnel();\r
-            $this->request->setLastEvent(\r
-                'connect', "ssl://{$reqHost}:{$reqPort} via {$host}:{$port}"\r
-            );\r
-            self::$sockets[$socketKey] =& $this->socket;\r
-\r
-        } else {\r
-            // Set SSL context options if doing HTTPS request or creating a tunnel\r
-            $context = stream_context_create();\r
-            foreach ($options as $name => $value) {\r
-                if (!stream_context_set_option($context, 'ssl', $name, $value)) {\r
-                    throw new HTTP_Request2_Exception(\r
-                        "Error setting SSL context option '{$name}'"\r
-                    );\r
-                }\r
-            }\r
-            $this->socket = @stream_socket_client(\r
-                $remote, $errno, $errstr,\r
-                $this->request->getConfig('connect_timeout'),\r
-                STREAM_CLIENT_CONNECT, $context\r
-            );\r
-            if (!$this->socket) {\r
-                throw new HTTP_Request2_Exception(\r
-                    "Unable to connect to {$remote}. Error #{$errno}: {$errstr}"\r
-                );\r
-            }\r
-            $this->request->setLastEvent('connect', $remote);\r
-            self::$sockets[$socketKey] =& $this->socket;\r
-        }\r
-        return $keepAlive;\r
-    }\r
-\r
-   /**\r
-    * Establishes a tunnel to a secure remote server via HTTP CONNECT request\r
-    *\r
-    * This method will fail if 'ssl_verify_peer' is enabled. Probably because PHP\r
-    * sees that we are connected to a proxy server (duh!) rather than the server\r
-    * that presents its certificate.\r
-    *\r
-    * @link     http://tools.ietf.org/html/rfc2817#section-5.2\r
-    * @throws   HTTP_Request2_Exception\r
-    */\r
-    protected function establishTunnel()\r
-    {\r
-        $donor   = new self;\r
-        $connect = new HTTP_Request2(\r
-            $this->request->getUrl(), HTTP_Request2::METHOD_CONNECT,\r
-            array_merge($this->request->getConfig(),\r
-                        array('adapter' => $donor))\r
-        );\r
-        $response = $connect->send();\r
-        // Need any successful (2XX) response\r
-        if (200 > $response->getStatus() || 300 <= $response->getStatus()) {\r
-            throw new HTTP_Request2_Exception(\r
-                'Failed to connect via HTTPS proxy. Proxy response: ' .\r
-                $response->getStatus() . ' ' . $response->getReasonPhrase()\r
-            );\r
-        }\r
-        $this->socket = $donor->socket;\r
-\r
-        $modes = array(\r
-            STREAM_CRYPTO_METHOD_TLS_CLIENT, \r
-            STREAM_CRYPTO_METHOD_SSLv3_CLIENT,\r
-            STREAM_CRYPTO_METHOD_SSLv23_CLIENT,\r
-            STREAM_CRYPTO_METHOD_SSLv2_CLIENT \r
-        );\r
-\r
-        foreach ($modes as $mode) {\r
-            if (stream_socket_enable_crypto($this->socket, true, $mode)) {\r
-                return;\r
-            }\r
-        }\r
-        throw new HTTP_Request2_Exception(\r
-            'Failed to enable secure connection when connecting through proxy'\r
-        );\r
-    }\r
-\r
-   /**\r
-    * Checks whether current connection may be reused or should be closed\r
-    *\r
-    * @param    boolean                 whether connection could be persistent \r
-    *                                   in the first place\r
-    * @param    HTTP_Request2_Response  response object to check\r
-    * @return   boolean\r
-    */\r
-    protected function canKeepAlive($requestKeepAlive, HTTP_Request2_Response $response)\r
-    {\r
-        // Do not close socket on successful CONNECT request\r
-        if (HTTP_Request2::METHOD_CONNECT == $this->request->getMethod() &&\r
-            200 <= $response->getStatus() && 300 > $response->getStatus()\r
-        ) {\r
-            return true;\r
-        }\r
-\r
-        $lengthKnown = 'chunked' == strtolower($response->getHeader('transfer-encoding')) ||\r
-                       null !== $response->getHeader('content-length');\r
-        $persistent  = 'keep-alive' == strtolower($response->getHeader('connection')) ||\r
-                       (null === $response->getHeader('connection') &&\r
-                        '1.1' == $response->getVersion());\r
-        return $requestKeepAlive && $lengthKnown && $persistent;\r
-    }\r
-\r
-   /**\r
-    * Disconnects from the remote server\r
-    */\r
-    protected function disconnect()\r
-    {\r
-        if (is_resource($this->socket)) {\r
-            fclose($this->socket);\r
-            $this->socket = null;\r
-            $this->request->setLastEvent('disconnect');\r
-        }\r
-    }\r
-\r
-   /**\r
-    * Checks whether another request should be performed with server digest auth\r
-    *\r
-    * Several conditions should be satisfied for it to return true:\r
-    *   - response status should be 401\r
-    *   - auth credentials should be set in the request object\r
-    *   - response should contain WWW-Authenticate header with digest challenge\r
-    *   - there is either no challenge stored for this URL or new challenge\r
-    *     contains stale=true parameter (in other case we probably just failed \r
-    *     due to invalid username / password)\r
-    *\r
-    * The method stores challenge values in $challenges static property\r
-    *\r
-    * @param    HTTP_Request2_Response  response to check\r
-    * @return   boolean whether another request should be performed\r
-    * @throws   HTTP_Request2_Exception in case of unsupported challenge parameters\r
-    */\r
-    protected function shouldUseServerDigestAuth(HTTP_Request2_Response $response)\r
-    {\r
-        // no sense repeating a request if we don't have credentials\r
-        if (401 != $response->getStatus() || !$this->request->getAuth()) {\r
-            return false;\r
-        }\r
-        if (!$challenge = $this->parseDigestChallenge($response->getHeader('www-authenticate'))) {\r
-            return false;\r
-        }\r
-\r
-        $url    = $this->request->getUrl();\r
-        $scheme = $url->getScheme();\r
-        $host   = $scheme . '://' . $url->getHost();\r
-        if ($port = $url->getPort()) {\r
-            if ((0 == strcasecmp($scheme, 'http') && 80 != $port) ||\r
-                (0 == strcasecmp($scheme, 'https') && 443 != $port)\r
-            ) {\r
-                $host .= ':' . $port;\r
-            }\r
-        }\r
-\r
-        if (!empty($challenge['domain'])) {\r
-            $prefixes = array();\r
-            foreach (preg_split('/\\s+/', $challenge['domain']) as $prefix) {\r
-                // don't bother with different servers\r
-                if ('/' == substr($prefix, 0, 1)) {\r
-                    $prefixes[] = $host . $prefix;\r
-                }\r
-            }\r
-        }\r
-        if (empty($prefixes)) {\r
-            $prefixes = array($host . '/');\r
-        }\r
-\r
-        $ret = true;\r
-        foreach ($prefixes as $prefix) {\r
-            if (!empty(self::$challenges[$prefix]) &&\r
-                (empty($challenge['stale']) || strcasecmp('true', $challenge['stale']))\r
-            ) {\r
-                // probably credentials are invalid\r
-                $ret = false;\r
-            }\r
-            self::$challenges[$prefix] =& $challenge;\r
-        }\r
-        return $ret;\r
-    }\r
-\r
-   /**\r
-    * Checks whether another request should be performed with proxy digest auth\r
-    *\r
-    * Several conditions should be satisfied for it to return true:\r
-    *   - response status should be 407\r
-    *   - proxy auth credentials should be set in the request object\r
-    *   - response should contain Proxy-Authenticate header with digest challenge\r
-    *   - there is either no challenge stored for this proxy or new challenge\r
-    *     contains stale=true parameter (in other case we probably just failed \r
-    *     due to invalid username / password)\r
-    *\r
-    * The method stores challenge values in $challenges static property\r
-    *\r
-    * @param    HTTP_Request2_Response  response to check\r
-    * @return   boolean whether another request should be performed\r
-    * @throws   HTTP_Request2_Exception in case of unsupported challenge parameters\r
-    */\r
-    protected function shouldUseProxyDigestAuth(HTTP_Request2_Response $response)\r
-    {\r
-        if (407 != $response->getStatus() || !$this->request->getConfig('proxy_user')) {\r
-            return false;\r
-        }\r
-        if (!($challenge = $this->parseDigestChallenge($response->getHeader('proxy-authenticate')))) {\r
-            return false;\r
-        }\r
-\r
-        $key = 'proxy://' . $this->request->getConfig('proxy_host') .\r
-               ':' . $this->request->getConfig('proxy_port');\r
-\r
-        if (!empty(self::$challenges[$key]) &&\r
-            (empty($challenge['stale']) || strcasecmp('true', $challenge['stale']))\r
-        ) {\r
-            $ret = false;\r
-        } else {\r
-            $ret = true;\r
-        }\r
-        self::$challenges[$key] = $challenge;\r
-        return $ret;\r
-    }\r
-\r
-   /**\r
-    * Extracts digest method challenge from (WWW|Proxy)-Authenticate header value\r
-    *\r
-    * There is a problem with implementation of RFC 2617: several of the parameters\r
-    * here are defined as quoted-string and thus may contain backslash escaped\r
-    * double quotes (RFC 2616, section 2.2). However, RFC 2617 defines unq(X) as\r
-    * just value of quoted-string X without surrounding quotes, it doesn't speak\r
-    * about removing backslash escaping.\r
-    *\r
-    * Now realm parameter is user-defined and human-readable, strange things\r
-    * happen when it contains quotes:\r
-    *   - Apache allows quotes in realm, but apparently uses realm value without\r
-    *     backslashes for digest computation\r
-    *   - Squid allows (manually escaped) quotes there, but it is impossible to\r
-    *     authorize with either escaped or unescaped quotes used in digest,\r
-    *     probably it can't parse the response (?)\r
-    *   - Both IE and Firefox display realm value with backslashes in \r
-    *     the password popup and apparently use the same value for digest\r
-    *\r
-    * HTTP_Request2 follows IE and Firefox (and hopefully RFC 2617) in\r
-    * quoted-string handling, unfortunately that means failure to authorize \r
-    * sometimes\r
-    *\r
-    * @param    string  value of WWW-Authenticate or Proxy-Authenticate header\r
-    * @return   mixed   associative array with challenge parameters, false if\r
-    *                   no challenge is present in header value\r
-    * @throws   HTTP_Request2_Exception in case of unsupported challenge parameters\r
-    */\r
-    protected function parseDigestChallenge($headerValue)\r
-    {\r
-        $authParam   = '(' . self::REGEXP_TOKEN . ')\\s*=\\s*(' .\r
-                       self::REGEXP_TOKEN . '|' . self::REGEXP_QUOTED_STRING . ')';\r
-        $challenge   = "!(?<=^|\\s|,)Digest ({$authParam}\\s*(,\\s*|$))+!";\r
-        if (!preg_match($challenge, $headerValue, $matches)) {\r
-            return false;\r
-        }\r
-\r
-        preg_match_all('!' . $authParam . '!', $matches[0], $params);\r
-        $paramsAry   = array();\r
-        $knownParams = array('realm', 'domain', 'nonce', 'opaque', 'stale',\r
-                             'algorithm', 'qop');\r
-        for ($i = 0; $i < count($params[0]); $i++) {\r
-            // section 3.2.1: Any unrecognized directive MUST be ignored.\r
-            if (in_array($params[1][$i], $knownParams)) {\r
-                if ('"' == substr($params[2][$i], 0, 1)) {\r
-                    $paramsAry[$params[1][$i]] = substr($params[2][$i], 1, -1);\r
-                } else {\r
-                    $paramsAry[$params[1][$i]] = $params[2][$i];\r
-                }\r
-            }\r
-        }\r
-        // we only support qop=auth\r
-        if (!empty($paramsAry['qop']) && \r
-            !in_array('auth', array_map('trim', explode(',', $paramsAry['qop'])))\r
-        ) {\r
-            throw new HTTP_Request2_Exception(\r
-                "Only 'auth' qop is currently supported in digest authentication, " .\r
-                "server requested '{$paramsAry['qop']}'"\r
-            );\r
-        }\r
-        // we only support algorithm=MD5\r
-        if (!empty($paramsAry['algorithm']) && 'MD5' != $paramsAry['algorithm']) {\r
-            throw new HTTP_Request2_Exception(\r
-                "Only 'MD5' algorithm is currently supported in digest authentication, " .\r
-                "server requested '{$paramsAry['algorithm']}'"\r
-            );\r
-        }\r
-\r
-        return $paramsAry; \r
-    }\r
-\r
-   /**\r
-    * Parses [Proxy-]Authentication-Info header value and updates challenge\r
-    *\r
-    * @param    array   challenge to update\r
-    * @param    string  value of [Proxy-]Authentication-Info header\r
-    * @todo     validate server rspauth response\r
-    */ \r
-    protected function updateChallenge(&$challenge, $headerValue)\r
-    {\r
-        $authParam   = '!(' . self::REGEXP_TOKEN . ')\\s*=\\s*(' .\r
-                       self::REGEXP_TOKEN . '|' . self::REGEXP_QUOTED_STRING . ')!';\r
-        $paramsAry   = array();\r
-\r
-        preg_match_all($authParam, $headerValue, $params);\r
-        for ($i = 0; $i < count($params[0]); $i++) {\r
-            if ('"' == substr($params[2][$i], 0, 1)) {\r
-                $paramsAry[$params[1][$i]] = substr($params[2][$i], 1, -1);\r
-            } else {\r
-                $paramsAry[$params[1][$i]] = $params[2][$i];\r
-            }\r
-        }\r
-        // for now, just update the nonce value\r
-        if (!empty($paramsAry['nextnonce'])) {\r
-            $challenge['nonce'] = $paramsAry['nextnonce'];\r
-            $challenge['nc']    = 1;\r
-        }\r
-    }\r
-\r
-   /**\r
-    * Creates a value for [Proxy-]Authorization header when using digest authentication\r
-    *\r
-    * @param    string  user name\r
-    * @param    string  password\r
-    * @param    string  request URL\r
-    * @param    array   digest challenge parameters\r
-    * @return   string  value of [Proxy-]Authorization request header\r
-    * @link     http://tools.ietf.org/html/rfc2617#section-3.2.2\r
-    */ \r
-    protected function createDigestResponse($user, $password, $url, &$challenge)\r
-    {\r
-        if (false !== ($q = strpos($url, '?')) && \r
-            $this->request->getConfig('digest_compat_ie')\r
-        ) {\r
-            $url = substr($url, 0, $q);\r
-        }\r
-\r
-        $a1 = md5($user . ':' . $challenge['realm'] . ':' . $password);\r
-        $a2 = md5($this->request->getMethod() . ':' . $url);\r
-\r
-        if (empty($challenge['qop'])) {\r
-            $digest = md5($a1 . ':' . $challenge['nonce'] . ':' . $a2);\r
-        } else {\r
-            $challenge['cnonce'] = 'Req2.' . rand();\r
-            if (empty($challenge['nc'])) {\r
-                $challenge['nc'] = 1;\r
-            }\r
-            $nc     = sprintf('%08x', $challenge['nc']++);\r
-            $digest = md5($a1 . ':' . $challenge['nonce'] . ':' . $nc . ':' .\r
-                          $challenge['cnonce'] . ':auth:' . $a2);\r
-        }\r
-        return 'Digest username="' . str_replace(array('\\', '"'), array('\\\\', '\\"'), $user) . '", ' .\r
-               'realm="' . $challenge['realm'] . '", ' .\r
-               'nonce="' . $challenge['nonce'] . '", ' .\r
-               'uri="' . $url . '", ' .\r
-               'response="' . $digest . '"' .\r
-               (!empty($challenge['opaque'])? \r
-                ', opaque="' . $challenge['opaque'] . '"':\r
-                '') .\r
-               (!empty($challenge['qop'])?\r
-                ', qop="auth", nc=' . $nc . ', cnonce="' . $challenge['cnonce'] . '"':\r
-                '');\r
-    }\r
-\r
-   /**\r
-    * Adds 'Authorization' header (if needed) to request headers array\r
-    *\r
-    * @param    array   request headers\r
-    * @param    string  request host (needed for digest authentication)\r
-    * @param    string  request URL (needed for digest authentication)\r
-    * @throws   HTTP_Request2_Exception\r
-    */\r
-    protected function addAuthorizationHeader(&$headers, $requestHost, $requestUrl)\r
-    {\r
-        if (!($auth = $this->request->getAuth())) {\r
-            return;\r
-        }\r
-        switch ($auth['scheme']) {\r
-            case HTTP_Request2::AUTH_BASIC:\r
-                $headers['authorization'] = \r
-                    'Basic ' . base64_encode($auth['user'] . ':' . $auth['password']);\r
-                break;\r
-\r
-            case HTTP_Request2::AUTH_DIGEST:\r
-                unset($this->serverChallenge);\r
-                $fullUrl = ('/' == $requestUrl[0])?\r
-                           $this->request->getUrl()->getScheme() . '://' .\r
-                            $requestHost . $requestUrl:\r
-                           $requestUrl;\r
-                foreach (array_keys(self::$challenges) as $key) {\r
-                    if ($key == substr($fullUrl, 0, strlen($key))) {\r
-                        $headers['authorization'] = $this->createDigestResponse(\r
-                            $auth['user'], $auth['password'], \r
-                            $requestUrl, self::$challenges[$key]\r
-                        );\r
-                        $this->serverChallenge =& self::$challenges[$key];\r
-                        break;\r
-                    }\r
-                }\r
-                break;\r
-\r
-            default:\r
-                throw new HTTP_Request2_Exception(\r
-                    "Unknown HTTP authentication scheme '{$auth['scheme']}'"\r
-                );\r
-        }\r
-    }\r
-\r
-   /**\r
-    * Adds 'Proxy-Authorization' header (if needed) to request headers array\r
-    *\r
-    * @param    array   request headers\r
-    * @param    string  request URL (needed for digest authentication)\r
-    * @throws   HTTP_Request2_Exception\r
-    */\r
-    protected function addProxyAuthorizationHeader(&$headers, $requestUrl)\r
-    {\r
-        if (!$this->request->getConfig('proxy_host') ||\r
-            !($user = $this->request->getConfig('proxy_user')) ||\r
-            (0 == strcasecmp('https', $this->request->getUrl()->getScheme()) &&\r
-             HTTP_Request2::METHOD_CONNECT != $this->request->getMethod())\r
-        ) {\r
-            return;\r
-        }\r
-\r
-        $password = $this->request->getConfig('proxy_password');\r
-        switch ($this->request->getConfig('proxy_auth_scheme')) {\r
-            case HTTP_Request2::AUTH_BASIC:\r
-                $headers['proxy-authorization'] =\r
-                    'Basic ' . base64_encode($user . ':' . $password);\r
-                break;\r
-\r
-            case HTTP_Request2::AUTH_DIGEST:\r
-                unset($this->proxyChallenge);\r
-                $proxyUrl = 'proxy://' . $this->request->getConfig('proxy_host') .\r
-                            ':' . $this->request->getConfig('proxy_port');\r
-                if (!empty(self::$challenges[$proxyUrl])) {\r
-                    $headers['proxy-authorization'] = $this->createDigestResponse(\r
-                        $user, $password,\r
-                        $requestUrl, self::$challenges[$proxyUrl]\r
-                    );\r
-                    $this->proxyChallenge =& self::$challenges[$proxyUrl];\r
-                }\r
-                break;\r
-\r
-            default:\r
-                throw new HTTP_Request2_Exception(\r
-                    "Unknown HTTP authentication scheme '" .\r
-                    $this->request->getConfig('proxy_auth_scheme') . "'"\r
-                );\r
-        }\r
-    }\r
-\r
-\r
-   /**\r
-    * Creates the string with the Request-Line and request headers\r
-    *\r
-    * @return   string\r
-    * @throws   HTTP_Request2_Exception\r
-    */\r
-    protected function prepareHeaders()\r
-    {\r
-        $headers = $this->request->getHeaders();\r
-        $url     = $this->request->getUrl();\r
-        $connect = HTTP_Request2::METHOD_CONNECT == $this->request->getMethod();\r
-        $host    = $url->getHost();\r
-\r
-        $defaultPort = 0 == strcasecmp($url->getScheme(), 'https')? 443: 80;\r
-        if (($port = $url->getPort()) && $port != $defaultPort || $connect) {\r
-            $host .= ':' . (empty($port)? $defaultPort: $port);\r
-        }\r
-        // Do not overwrite explicitly set 'Host' header, see bug #16146\r
-        if (!isset($headers['host'])) {\r
-            $headers['host'] = $host;\r
-        }\r
-\r
-        if ($connect) {\r
-            $requestUrl = $host;\r
-\r
-        } else {\r
-            if (!$this->request->getConfig('proxy_host') ||\r
-                0 == strcasecmp($url->getScheme(), 'https')\r
-            ) {\r
-                $requestUrl = '';\r
-            } else {\r
-                $requestUrl = $url->getScheme() . '://' . $host;\r
-            }\r
-            $path        = $url->getPath();\r
-            $query       = $url->getQuery();\r
-            $requestUrl .= (empty($path)? '/': $path) . (empty($query)? '': '?' . $query);\r
-        }\r
-\r
-        if ('1.1' == $this->request->getConfig('protocol_version') &&\r
-            extension_loaded('zlib') && !isset($headers['accept-encoding'])\r
-        ) {\r
-            $headers['accept-encoding'] = 'gzip, deflate';\r
-        }\r
-\r
-        $this->addAuthorizationHeader($headers, $host, $requestUrl);\r
-        $this->addProxyAuthorizationHeader($headers, $requestUrl);\r
-        $this->calculateRequestLength($headers);\r
-\r
-        $headersStr = $this->request->getMethod() . ' ' . $requestUrl . ' HTTP/' .\r
-                      $this->request->getConfig('protocol_version') . "\r\n";\r
-        foreach ($headers as $name => $value) {\r
-            $canonicalName = implode('-', array_map('ucfirst', explode('-', $name)));\r
-            $headersStr   .= $canonicalName . ': ' . $value . "\r\n";\r
-        }\r
-        return $headersStr . "\r\n";\r
-    }\r
-\r
-   /**\r
-    * Sends the request body\r
-    *\r
-    * @throws   HTTP_Request2_Exception\r
-    */\r
-    protected function writeBody()\r
-    {\r
-        if (in_array($this->request->getMethod(), self::$bodyDisallowed) ||\r
-            0 == $this->contentLength\r
-        ) {\r
-            return;\r
-        }\r
-\r
-        $position   = 0;\r
-        $bufferSize = $this->request->getConfig('buffer_size');\r
-        while ($position < $this->contentLength) {\r
-            if (is_string($this->requestBody)) {\r
-                $str = substr($this->requestBody, $position, $bufferSize);\r
-            } elseif (is_resource($this->requestBody)) {\r
-                $str = fread($this->requestBody, $bufferSize);\r
-            } else {\r
-                $str = $this->requestBody->read($bufferSize);\r
-            }\r
-            if (false === @fwrite($this->socket, $str, strlen($str))) {\r
-                throw new HTTP_Request2_Exception('Error writing request');\r
-            }\r
-            // Provide the length of written string to the observer, request #7630\r
-            $this->request->setLastEvent('sentBodyPart', strlen($str));\r
-            $position += strlen($str); \r
-        }\r
-    }\r
-\r
-   /**\r
-    * Reads the remote server's response\r
-    *\r
-    * @return   HTTP_Request2_Response\r
-    * @throws   HTTP_Request2_Exception\r
-    */\r
-    protected function readResponse()\r
-    {\r
-        $bufferSize = $this->request->getConfig('buffer_size');\r
-\r
-        do {\r
-            $response = new HTTP_Request2_Response($this->readLine($bufferSize), true);\r
-            do {\r
-                $headerLine = $this->readLine($bufferSize);\r
-                $response->parseHeaderLine($headerLine);\r
-            } while ('' != $headerLine);\r
-        } while (in_array($response->getStatus(), array(100, 101)));\r
-\r
-        $this->request->setLastEvent('receivedHeaders', $response);\r
-\r
-        // No body possible in such responses\r
-        if (HTTP_Request2::METHOD_HEAD == $this->request->getMethod() ||\r
-            (HTTP_Request2::METHOD_CONNECT == $this->request->getMethod() &&\r
-             200 <= $response->getStatus() && 300 > $response->getStatus()) ||\r
-            in_array($response->getStatus(), array(204, 304))\r
-        ) {\r
-            return $response;\r
-        }\r
-\r
-        $chunked = 'chunked' == $response->getHeader('transfer-encoding');\r
-        $length  = $response->getHeader('content-length');\r
-        $hasBody = false;\r
-        if ($chunked || null === $length || 0 < intval($length)) {\r
-            // RFC 2616, section 4.4:\r
-            // 3. ... If a message is received with both a\r
-            // Transfer-Encoding header field and a Content-Length header field,\r
-            // the latter MUST be ignored.\r
-            $toRead = ($chunked || null === $length)? null: $length;\r
-            $this->chunkLength = 0;\r
-\r
-            while (!feof($this->socket) && (is_null($toRead) || 0 < $toRead)) {\r
-                if ($chunked) {\r
-                    $data = $this->readChunked($bufferSize);\r
-                } elseif (is_null($toRead)) {\r
-                    $data = $this->fread($bufferSize);\r
-                } else {\r
-                    $data    = $this->fread(min($toRead, $bufferSize));\r
-                    $toRead -= strlen($data);\r
-                }\r
-                if ('' == $data && (!$this->chunkLength || feof($this->socket))) {\r
-                    break;\r
-                }\r
-\r
-                $hasBody = true;\r
-                if ($this->request->getConfig('store_body')) {\r
-                    $response->appendBody($data);\r
-                }\r
-                if (!in_array($response->getHeader('content-encoding'), array('identity', null))) {\r
-                    $this->request->setLastEvent('receivedEncodedBodyPart', $data);\r
-                } else {\r
-                    $this->request->setLastEvent('receivedBodyPart', $data);\r
-                }\r
-            }\r
-        }\r
-\r
-        if ($hasBody) {\r
-            $this->request->setLastEvent('receivedBody', $response);\r
-        }\r
-        return $response;\r
-    }\r
-\r
-   /**\r
-    * Reads until either the end of the socket or a newline, whichever comes first \r
-    *\r
-    * Strips the trailing newline from the returned data, handles global \r
-    * request timeout. Method idea borrowed from Net_Socket PEAR package. \r
-    *\r
-    * @param    int     buffer size to use for reading\r
-    * @return   Available data up to the newline (not including newline)\r
-    * @throws   HTTP_Request2_Exception     In case of timeout\r
-    */\r
-    protected function readLine($bufferSize)\r
-    {\r
-        $line = '';\r
-        while (!feof($this->socket)) {\r
-            if ($this->timeout) {\r
-                stream_set_timeout($this->socket, max($this->timeout - time(), 1));\r
-            }\r
-            $line .= @fgets($this->socket, $bufferSize);\r
-            $info  = stream_get_meta_data($this->socket);\r
-            if ($info['timed_out'] || $this->timeout && time() > $this->timeout) {\r
-                throw new HTTP_Request2_Exception(\r
-                    'Request timed out after ' . \r
-                    $this->request->getConfig('timeout') . ' second(s)'\r
-                );\r
-            }\r
-            if (substr($line, -1) == "\n") {\r
-                return rtrim($line, "\r\n");\r
-            }\r
-        }\r
-        return $line;\r
-    }\r
-\r
-   /**\r
-    * Wrapper around fread(), handles global request timeout\r
-    *\r
-    * @param    int     Reads up to this number of bytes\r
-    * @return   Data read from socket\r
-    * @throws   HTTP_Request2_Exception     In case of timeout\r
-    */\r
-    protected function fread($length)\r
-    {\r
-        if ($this->timeout) {\r
-            stream_set_timeout($this->socket, max($this->timeout - time(), 1));\r
-        }\r
-        $data = fread($this->socket, $length);\r
-        $info = stream_get_meta_data($this->socket);\r
-        if ($info['timed_out'] || $this->timeout && time() > $this->timeout) {\r
-            throw new HTTP_Request2_Exception(\r
-                'Request timed out after ' . \r
-                $this->request->getConfig('timeout') . ' second(s)'\r
-            );\r
-        }\r
-        return $data;\r
-    }\r
-\r
-   /**\r
-    * Reads a part of response body encoded with chunked Transfer-Encoding\r
-    *\r
-    * @param    int     buffer size to use for reading\r
-    * @return   string\r
-    * @throws   HTTP_Request2_Exception\r
-    */\r
-    protected function readChunked($bufferSize)\r
-    {\r
-        // at start of the next chunk?\r
-        if (0 == $this->chunkLength) {\r
-            $line = $this->readLine($bufferSize);\r
-            if (!preg_match('/^([0-9a-f]+)/i', $line, $matches)) {\r
-                throw new HTTP_Request2_Exception(\r
-                    "Cannot decode chunked response, invalid chunk length '{$line}'"\r
-                );\r
-            } else {\r
-                $this->chunkLength = hexdec($matches[1]);\r
-                // Chunk with zero length indicates the end\r
-                if (0 == $this->chunkLength) {\r
-                    $this->readLine($bufferSize);\r
-                    return '';\r
-                }\r
-            }\r
-        }\r
-        $data = $this->fread(min($this->chunkLength, $bufferSize));\r
-        $this->chunkLength -= strlen($data);\r
-        if (0 == $this->chunkLength) {\r
-            $this->readLine($bufferSize); // Trailing CRLF\r
-        }\r
-        return $data;\r
-    }\r
-}\r
-\r
-?>
\ No newline at end of file