Caching support will be added in future work after unit tests have been added.
* extlib: add PEAR HTTP_Request2 0.4.1 alpha
* extlib: update PEAR Net_URL2 to 0.3.0 beta for HTTP_Request2 compatibility
* moved direct usage of CURL and file_get_contents to HTTPClient class, excluding external-sourced libraries
* adapted GeonamesPlugin for new HTTPResponse interface
Note some plugins haven't been fully tested yet.
/* the code above is auto generated do not remove the tag below */
###END_AUTOCODE
- function _commonCurl($url, $redirs) {
- $curlh = curl_init();
- curl_setopt($curlh, CURLOPT_URL, $url);
- curl_setopt($curlh, CURLOPT_AUTOREFERER, true); // # setup referer header when folowing redirects
- curl_setopt($curlh, CURLOPT_CONNECTTIMEOUT, 10); // # seconds to wait
- curl_setopt($curlh, CURLOPT_MAXREDIRS, $redirs); // # max number of http redirections to follow
- curl_setopt($curlh, CURLOPT_USERAGENT, USER_AGENT);
- curl_setopt($curlh, CURLOPT_FOLLOWLOCATION, true); // Follow redirects
- curl_setopt($curlh, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($curlh, CURLOPT_FILETIME, true);
- curl_setopt($curlh, CURLOPT_HEADER, true); // Include header in output
- return $curlh;
+ static function _commonHttp($url, $redirs) {
+ $request = new HTTPClient($url);
+ $request->setConfig(array(
+ 'connect_timeout' => 10, // # seconds to wait
+ 'max_redirs' => $redirs, // # max number of http redirections to follow
+ 'follow_redirects' => true, // Follow redirects
+ 'store_body' => false, // We won't need body content here.
+ ));
+ return $request;
}
function _redirectWhere_imp($short_url, $redirs = 10, $protected = false) {
if(strpos($short_url,'://') === false){
return $short_url;
}
- $curlh = File_redirection::_commonCurl($short_url, $redirs);
- // Don't include body in output
- curl_setopt($curlh, CURLOPT_NOBODY, true);
- curl_exec($curlh);
- $info = curl_getinfo($curlh);
- curl_close($curlh);
-
- if (405 == $info['http_code']) {
- $curlh = File_redirection::_commonCurl($short_url, $redirs);
- curl_exec($curlh);
- $info = curl_getinfo($curlh);
- curl_close($curlh);
+ try {
+ $request = self::_commonHttp($short_url, $redirs);
+ // Don't include body in output
+ $request->setMethod(HTTP_Request2::METHOD_HEAD);
+ $response = $request->send();
+
+ if (405 == $response->getStatus()) {
+ // Server doesn't support HEAD method? Can this really happen?
+ // We'll try again as a GET and ignore the response data.
+ $request = self::_commonHttp($short_url, $redirs);
+ $response = $request->send();
+ }
+ } catch (Exception $e) {
+ // Invalid URL or failure to reach server
+ return $short_url;
}
- if (!empty($info['redirect_count']) && File::isProtected($info['url'])) {
- return File_redirection::_redirectWhere_imp($short_url, $info['redirect_count'] - 1, true);
+ if ($response->getRedirectCount() && File::isProtected($response->getUrl())) {
+ // Bump back up the redirect chain until we find a non-protected URL
+ return self::_redirectWhere_imp($short_url, $response->getRedirectCount() - 1, true);
}
- $ret = array('code' => $info['http_code']
- , 'redirects' => $info['redirect_count']
- , 'url' => $info['url']);
+ $ret = array('code' => $response->getStatus()
+ , 'redirects' => $response->getRedirectCount()
+ , 'url' => $response->getUrl());
- if (!empty($info['content_type'])) $ret['type'] = $info['content_type'];
+ $type = $response->getHeader('Content-Type');
+ if ($type) $ret['type'] = $type;
if ($protected) $ret['protected'] = true;
- if (!empty($info['download_content_length'])) $ret['size'] = $info['download_content_length'];
- if (isset($info['filetime']) && ($info['filetime'] > 0)) $ret['time'] = $info['filetime'];
+ $size = $response->getHeader('Content-Length'); // @fixme bytes?
+ if ($size) $ret['size'] = $size;
+ $time = $response->getHeader('Last-Modified');
+ if ($time) $ret['time'] = strtotime($time);
return $ret;
}
--- /dev/null
+<?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
--- /dev/null
+<?php\r
+/**\r
+ * Base class for HTTP_Request2 adapters\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: Adapter.php 274684 2009-01-26 23:07:27Z avb $\r
+ * @link http://pear.php.net/package/HTTP_Request2\r
+ */\r
+\r
+/**\r
+ * Class representing a HTTP response\r
+ */\r
+require_once 'HTTP/Request2/Response.php';\r
+\r
+/**\r
+ * Base class for HTTP_Request2 adapters\r
+ *\r
+ * HTTP_Request2 class itself only defines methods for aggregating the request\r
+ * data, all actual work of sending the request to the remote server and \r
+ * receiving its response is performed by adapters.\r
+ *\r
+ * @category HTTP\r
+ * @package HTTP_Request2\r
+ * @author Alexey Borzov <avb@php.net>\r
+ * @version Release: 0.4.1\r
+ */\r
+abstract class HTTP_Request2_Adapter\r
+{\r
+ /**\r
+ * A list of methods that MUST NOT have a request body, per RFC 2616\r
+ * @var array\r
+ */\r
+ protected static $bodyDisallowed = array('TRACE');\r
+\r
+ /**\r
+ * Methods having defined semantics for request body\r
+ *\r
+ * Content-Length header (indicating that the body follows, section 4.3 of\r
+ * RFC 2616) will be sent for these methods even if no body was added\r
+ *\r
+ * @var array\r
+ * @link http://pear.php.net/bugs/bug.php?id=12900\r
+ * @link http://pear.php.net/bugs/bug.php?id=14740\r
+ */\r
+ protected static $bodyRequired = array('POST', 'PUT');\r
+\r
+ /**\r
+ * Request being sent\r
+ * @var HTTP_Request2\r
+ */\r
+ protected $request;\r
+\r
+ /**\r
+ * Request body\r
+ * @var string|resource|HTTP_Request2_MultipartBody\r
+ * @see HTTP_Request2::getBody()\r
+ */\r
+ protected $requestBody;\r
+\r
+ /**\r
+ * Length of the request body\r
+ * @var integer\r
+ */\r
+ protected $contentLength;\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
+ abstract public function sendRequest(HTTP_Request2 $request);\r
+\r
+ /**\r
+ * Calculates length of the request body, adds proper headers\r
+ *\r
+ * @param array associative array of request headers, this method will \r
+ * add proper 'Content-Length' and 'Content-Type' headers \r
+ * to this array (or remove them if not needed)\r
+ */\r
+ protected function calculateRequestLength(&$headers)\r
+ {\r
+ $this->requestBody = $this->request->getBody();\r
+\r
+ if (is_string($this->requestBody)) {\r
+ $this->contentLength = strlen($this->requestBody);\r
+ } elseif (is_resource($this->requestBody)) {\r
+ $stat = fstat($this->requestBody);\r
+ $this->contentLength = $stat['size'];\r
+ rewind($this->requestBody);\r
+ } else {\r
+ $this->contentLength = $this->requestBody->getLength();\r
+ $headers['content-type'] = 'multipart/form-data; boundary=' .\r
+ $this->requestBody->getBoundary();\r
+ $this->requestBody->rewind();\r
+ }\r
+\r
+ if (in_array($this->request->getMethod(), self::$bodyDisallowed) ||\r
+ 0 == $this->contentLength\r
+ ) {\r
+ unset($headers['content-type']);\r
+ // No body: send a Content-Length header nonetheless (request #12900),\r
+ // but do that only for methods that require a body (bug #14740)\r
+ if (in_array($this->request->getMethod(), self::$bodyRequired)) {\r
+ $headers['content-length'] = 0;\r
+ } else {\r
+ unset($headers['content-length']);\r
+ }\r
+ } else {\r
+ if (empty($headers['content-type'])) {\r
+ $headers['content-type'] = 'application/x-www-form-urlencoded';\r
+ }\r
+ $headers['content-length'] = $this->contentLength;\r
+ }\r
+ }\r
+}\r
+?>\r
--- /dev/null
+<?php\r
+/**\r
+ * Adapter for HTTP_Request2 wrapping around cURL extension\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: Curl.php 278226 2009-04-03 21:32:48Z 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
+ * Adapter for HTTP_Request2 wrapping around cURL extension\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_Curl extends HTTP_Request2_Adapter\r
+{\r
+ /**\r
+ * Mapping of header names to cURL options\r
+ * @var array\r
+ */\r
+ protected static $headerMap = array(\r
+ 'accept-encoding' => CURLOPT_ENCODING,\r
+ 'cookie' => CURLOPT_COOKIE,\r
+ 'referer' => CURLOPT_REFERER,\r
+ 'user-agent' => CURLOPT_USERAGENT\r
+ );\r
+\r
+ /**\r
+ * Mapping of SSL context options to cURL options\r
+ * @var array\r
+ */\r
+ protected static $sslContextMap = array(\r
+ 'ssl_verify_peer' => CURLOPT_SSL_VERIFYPEER,\r
+ 'ssl_cafile' => CURLOPT_CAINFO,\r
+ 'ssl_capath' => CURLOPT_CAPATH,\r
+ 'ssl_local_cert' => CURLOPT_SSLCERT,\r
+ 'ssl_passphrase' => CURLOPT_SSLCERTPASSWD\r
+ );\r
+\r
+ /**\r
+ * Response being received\r
+ * @var HTTP_Request2_Response\r
+ */\r
+ protected $response;\r
+\r
+ /**\r
+ * Whether 'sentHeaders' event was sent to observers\r
+ * @var boolean\r
+ */\r
+ protected $eventSentHeaders = false;\r
+\r
+ /**\r
+ * Whether 'receivedHeaders' event was sent to observers\r
+ * @var boolean\r
+ */\r
+ protected $eventReceivedHeaders = false;\r
+\r
+ /**\r
+ * Position within request body\r
+ * @var integer\r
+ * @see callbackReadBody()\r
+ */\r
+ protected $position = 0;\r
+\r
+ /**\r
+ * Information about last transfer, as returned by curl_getinfo()\r
+ * @var array\r
+ */\r
+ protected $lastInfo;\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
+ if (!extension_loaded('curl')) {\r
+ throw new HTTP_Request2_Exception('cURL extension not available');\r
+ }\r
+\r
+ $this->request = $request;\r
+ $this->response = null;\r
+ $this->position = 0;\r
+ $this->eventSentHeaders = false;\r
+ $this->eventReceivedHeaders = false;\r
+\r
+ try {\r
+ if (false === curl_exec($ch = $this->createCurlHandle())) {\r
+ $errorMessage = 'Error sending request: #' . curl_errno($ch) .\r
+ ' ' . curl_error($ch);\r
+ }\r
+ } catch (Exception $e) {\r
+ }\r
+ $this->lastInfo = curl_getinfo($ch);\r
+ curl_close($ch);\r
+\r
+ if (!empty($e)) {\r
+ throw $e;\r
+ } elseif (!empty($errorMessage)) {\r
+ throw new HTTP_Request2_Exception($errorMessage);\r
+ }\r
+\r
+ if (0 < $this->lastInfo['size_download']) {\r
+ $this->request->setLastEvent('receivedBody', $this->response);\r
+ }\r
+ return $this->response;\r
+ }\r
+\r
+ /**\r
+ * Returns information about last transfer\r
+ *\r
+ * @return array associative array as returned by curl_getinfo()\r
+ */\r
+ public function getInfo()\r
+ {\r
+ return $this->lastInfo;\r
+ }\r
+\r
+ /**\r
+ * Creates a new cURL handle and populates it with data from the request\r
+ *\r
+ * @return resource a cURL handle, as created by curl_init()\r
+ * @throws HTTP_Request2_Exception\r
+ */\r
+ protected function createCurlHandle()\r
+ {\r
+ $ch = curl_init();\r
+\r
+ curl_setopt_array($ch, array(\r
+ // setup callbacks\r
+ CURLOPT_READFUNCTION => array($this, 'callbackReadBody'),\r
+ CURLOPT_HEADERFUNCTION => array($this, 'callbackWriteHeader'),\r
+ CURLOPT_WRITEFUNCTION => array($this, 'callbackWriteBody'),\r
+ // disallow redirects\r
+ CURLOPT_FOLLOWLOCATION => false,\r
+ // buffer size\r
+ CURLOPT_BUFFERSIZE => $this->request->getConfig('buffer_size'),\r
+ // connection timeout\r
+ CURLOPT_CONNECTTIMEOUT => $this->request->getConfig('connect_timeout'),\r
+ // save full outgoing headers, in case someone is interested\r
+ CURLINFO_HEADER_OUT => true,\r
+ // request url\r
+ CURLOPT_URL => $this->request->getUrl()->getUrl()\r
+ ));\r
+\r
+ // request timeout\r
+ if ($timeout = $this->request->getConfig('timeout')) {\r
+ curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);\r
+ }\r
+\r
+ // set HTTP version\r
+ switch ($this->request->getConfig('protocol_version')) {\r
+ case '1.0':\r
+ curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);\r
+ break;\r
+ case '1.1':\r
+ curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);\r
+ }\r
+\r
+ // set request method\r
+ switch ($this->request->getMethod()) {\r
+ case HTTP_Request2::METHOD_GET:\r
+ curl_setopt($ch, CURLOPT_HTTPGET, true);\r
+ break;\r
+ case HTTP_Request2::METHOD_POST:\r
+ curl_setopt($ch, CURLOPT_POST, true);\r
+ break;\r
+ default:\r
+ curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $this->request->getMethod());\r
+ }\r
+\r
+ // set proxy, if needed\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
+ curl_setopt($ch, CURLOPT_PROXY, $host . ':' . $port);\r
+ if ($user = $this->request->getConfig('proxy_user')) {\r
+ curl_setopt($ch, CURLOPT_PROXYUSERPWD, $user . ':' .\r
+ $this->request->getConfig('proxy_password'));\r
+ switch ($this->request->getConfig('proxy_auth_scheme')) {\r
+ case HTTP_Request2::AUTH_BASIC:\r
+ curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_BASIC);\r
+ break;\r
+ case HTTP_Request2::AUTH_DIGEST:\r
+ curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_DIGEST);\r
+ }\r
+ }\r
+ }\r
+\r
+ // set authentication data\r
+ if ($auth = $this->request->getAuth()) {\r
+ curl_setopt($ch, CURLOPT_USERPWD, $auth['user'] . ':' . $auth['password']);\r
+ switch ($auth['scheme']) {\r
+ case HTTP_Request2::AUTH_BASIC:\r
+ curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);\r
+ break;\r
+ case HTTP_Request2::AUTH_DIGEST:\r
+ curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);\r
+ }\r
+ }\r
+\r
+ // set SSL options\r
+ if (0 == strcasecmp($this->request->getUrl()->getScheme(), 'https')) {\r
+ foreach ($this->request->getConfig() as $name => $value) {\r
+ if ('ssl_verify_host' == $name && null !== $value) {\r
+ curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, $value? 2: 0);\r
+ } elseif (isset(self::$sslContextMap[$name]) && null !== $value) {\r
+ curl_setopt($ch, self::$sslContextMap[$name], $value);\r
+ }\r
+ }\r
+ }\r
+\r
+ $headers = $this->request->getHeaders();\r
+ // make cURL automagically send proper header\r
+ if (!isset($headers['accept-encoding'])) {\r
+ $headers['accept-encoding'] = '';\r
+ }\r
+\r
+ // set headers having special cURL keys\r
+ foreach (self::$headerMap as $name => $option) {\r
+ if (isset($headers[$name])) {\r
+ curl_setopt($ch, $option, $headers[$name]);\r
+ unset($headers[$name]);\r
+ }\r
+ }\r
+\r
+ $this->calculateRequestLength($headers);\r
+\r
+ // set headers not having special keys\r
+ $headersFmt = array();\r
+ foreach ($headers as $name => $value) {\r
+ $canonicalName = implode('-', array_map('ucfirst', explode('-', $name)));\r
+ $headersFmt[] = $canonicalName . ': ' . $value;\r
+ }\r
+ curl_setopt($ch, CURLOPT_HTTPHEADER, $headersFmt);\r
+\r
+ return $ch;\r
+ }\r
+\r
+ /**\r
+ * Callback function called by cURL for reading the request body\r
+ *\r
+ * @param resource cURL handle\r
+ * @param resource file descriptor (not used)\r
+ * @param integer maximum length of data to return\r
+ * @return string part of the request body, up to $length bytes \r
+ */\r
+ protected function callbackReadBody($ch, $fd, $length)\r
+ {\r
+ if (!$this->eventSentHeaders) {\r
+ $this->request->setLastEvent(\r
+ 'sentHeaders', curl_getinfo($ch, CURLINFO_HEADER_OUT)\r
+ );\r
+ $this->eventSentHeaders = true;\r
+ }\r
+ if (in_array($this->request->getMethod(), self::$bodyDisallowed) ||\r
+ 0 == $this->contentLength || $this->position >= $this->contentLength\r
+ ) {\r
+ return '';\r
+ }\r
+ if (is_string($this->requestBody)) {\r
+ $string = substr($this->requestBody, $this->position, $length);\r
+ } elseif (is_resource($this->requestBody)) {\r
+ $string = fread($this->requestBody, $length);\r
+ } else {\r
+ $string = $this->requestBody->read($length);\r
+ }\r
+ $this->request->setLastEvent('sentBodyPart', strlen($string));\r
+ $this->position += strlen($string);\r
+ return $string;\r
+ }\r
+\r
+ /**\r
+ * Callback function called by cURL for saving the response headers\r
+ *\r
+ * @param resource cURL handle\r
+ * @param string response header (with trailing CRLF)\r
+ * @return integer number of bytes saved\r
+ * @see HTTP_Request2_Response::parseHeaderLine()\r
+ */\r
+ protected function callbackWriteHeader($ch, $string)\r
+ {\r
+ // we may receive a second set of headers if doing e.g. digest auth\r
+ if ($this->eventReceivedHeaders || !$this->eventSentHeaders) {\r
+ // don't bother with 100-Continue responses (bug #15785)\r
+ if (!$this->eventSentHeaders ||\r
+ $this->response->getStatus() >= 200\r
+ ) {\r
+ $this->request->setLastEvent(\r
+ 'sentHeaders', curl_getinfo($ch, CURLINFO_HEADER_OUT)\r
+ );\r
+ }\r
+ $this->eventSentHeaders = true;\r
+ // we'll need a new response object\r
+ if ($this->eventReceivedHeaders) {\r
+ $this->eventReceivedHeaders = false;\r
+ $this->response = null;\r
+ }\r
+ }\r
+ if (empty($this->response)) {\r
+ $this->response = new HTTP_Request2_Response($string, false);\r
+ } else {\r
+ $this->response->parseHeaderLine($string);\r
+ if ('' == trim($string)) {\r
+ // don't bother with 100-Continue responses (bug #15785)\r
+ if (200 <= $this->response->getStatus()) {\r
+ $this->request->setLastEvent('receivedHeaders', $this->response);\r
+ }\r
+ $this->eventReceivedHeaders = true;\r
+ }\r
+ }\r
+ return strlen($string);\r
+ }\r
+\r
+ /**\r
+ * Callback function called by cURL for saving the response body\r
+ *\r
+ * @param resource cURL handle (not used)\r
+ * @param string part of the response body\r
+ * @return integer number of bytes saved\r
+ * @see HTTP_Request2_Response::appendBody()\r
+ */\r
+ protected function callbackWriteBody($ch, $string)\r
+ {\r
+ // cURL calls WRITEFUNCTION callback without calling HEADERFUNCTION if \r
+ // response doesn't start with proper HTTP status line (see bug #15716)\r
+ if (empty($this->response)) {\r
+ throw new HTTP_Request2_Exception("Malformed response: {$string}");\r
+ }\r
+ if ($this->request->getConfig('store_body')) {\r
+ $this->response->appendBody($string);\r
+ }\r
+ $this->request->setLastEvent('receivedBodyPart', $string);\r
+ return strlen($string);\r
+ }\r
+}\r
+?>\r
--- /dev/null
+<?php\r
+/**\r
+ * Mock adapter intended for testing\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: Mock.php 274406 2009-01-23 18:01:57Z 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
+ * Mock adapter intended for testing\r
+ *\r
+ * Can be used to test applications depending on HTTP_Request2 package without\r
+ * actually performing any HTTP requests. This adapter will return responses\r
+ * previously added via addResponse()\r
+ * <code>\r
+ * $mock = new HTTP_Request2_Adapter_Mock();\r
+ * $mock->addResponse("HTTP/1.1 ... ");\r
+ * \r
+ * $request = new HTTP_Request2();\r
+ * $request->setAdapter($mock);\r
+ * \r
+ * // This will return the response set above\r
+ * $response = $req->send();\r
+ * </code> \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_Mock extends HTTP_Request2_Adapter\r
+{\r
+ /**\r
+ * A queue of responses to be returned by sendRequest()\r
+ * @var array \r
+ */\r
+ protected $responses = array();\r
+\r
+ /**\r
+ * Returns the next response from the queue built by addResponse()\r
+ *\r
+ * If the queue is empty will return default empty response with status 400,\r
+ * if an Exception object was added to the queue it will be thrown.\r
+ *\r
+ * @param HTTP_Request2\r
+ * @return HTTP_Request2_Response\r
+ * @throws Exception\r
+ */\r
+ public function sendRequest(HTTP_Request2 $request)\r
+ {\r
+ if (count($this->responses) > 0) {\r
+ $response = array_shift($this->responses);\r
+ if ($response instanceof HTTP_Request2_Response) {\r
+ return $response;\r
+ } else {\r
+ // rethrow the exception,\r
+ $class = get_class($response);\r
+ $message = $response->getMessage();\r
+ $code = $response->getCode();\r
+ throw new $class($message, $code);\r
+ }\r
+ } else {\r
+ return self::createResponseFromString("HTTP/1.1 400 Bad Request\r\n\r\n");\r
+ }\r
+ }\r
+\r
+ /**\r
+ * Adds response to the queue\r
+ *\r
+ * @param mixed either a string, a pointer to an open file,\r
+ * a HTTP_Request2_Response or Exception object\r
+ * @throws HTTP_Request2_Exception\r
+ */\r
+ public function addResponse($response)\r
+ {\r
+ if (is_string($response)) {\r
+ $response = self::createResponseFromString($response);\r
+ } elseif (is_resource($response)) {\r
+ $response = self::createResponseFromFile($response);\r
+ } elseif (!$response instanceof HTTP_Request2_Response &&\r
+ !$response instanceof Exception\r
+ ) {\r
+ throw new HTTP_Request2_Exception('Parameter is not a valid response');\r
+ }\r
+ $this->responses[] = $response;\r
+ }\r
+\r
+ /**\r
+ * Creates a new HTTP_Request2_Response object from a string\r
+ *\r
+ * @param string\r
+ * @return HTTP_Request2_Response\r
+ * @throws HTTP_Request2_Exception\r
+ */\r
+ public static function createResponseFromString($str)\r
+ {\r
+ $parts = preg_split('!(\r?\n){2}!m', $str, 2);\r
+ $headerLines = explode("\n", $parts[0]); \r
+ $response = new HTTP_Request2_Response(array_shift($headerLines));\r
+ foreach ($headerLines as $headerLine) {\r
+ $response->parseHeaderLine($headerLine);\r
+ }\r
+ $response->parseHeaderLine('');\r
+ if (isset($parts[1])) {\r
+ $response->appendBody($parts[1]);\r
+ }\r
+ return $response;\r
+ }\r
+\r
+ /**\r
+ * Creates a new HTTP_Request2_Response object from a file\r
+ *\r
+ * @param resource file pointer returned by fopen()\r
+ * @return HTTP_Request2_Response\r
+ * @throws HTTP_Request2_Exception\r
+ */\r
+ public static function createResponseFromFile($fp)\r
+ {\r
+ $response = new HTTP_Request2_Response(fgets($fp));\r
+ do {\r
+ $headerLine = fgets($fp);\r
+ $response->parseHeaderLine($headerLine);\r
+ } while ('' != trim($headerLine));\r
+\r
+ while (!feof($fp)) {\r
+ $response->appendBody(fread($fp, 8192));\r
+ }\r
+ return $response;\r
+ }\r
+}\r
+?>
\ No newline at end of file
--- /dev/null
+<?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
--- /dev/null
+<?php\r
+/**\r
+ * Exception class for HTTP_Request2 package\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: Exception.php 273003 2009-01-07 19:28:22Z avb $\r
+ * @link http://pear.php.net/package/HTTP_Request2\r
+ */\r
+\r
+/**\r
+ * Base class for exceptions in PEAR\r
+ */\r
+require_once 'PEAR/Exception.php';\r
+\r
+/**\r
+ * Exception class for HTTP_Request2 package\r
+ *\r
+ * Such a class is required by the Exception RFC:\r
+ * http://pear.php.net/pepr/pepr-proposal-show.php?id=132\r
+ *\r
+ * @category HTTP\r
+ * @package HTTP_Request2\r
+ * @version Release: 0.4.1\r
+ */\r
+class HTTP_Request2_Exception extends PEAR_Exception\r
+{\r
+}\r
+?>
\ No newline at end of file
--- /dev/null
+<?php\r
+/**\r
+ * Helper class for building multipart/form-data request body\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: MultipartBody.php 287306 2009-08-14 15:22:52Z avb $\r
+ * @link http://pear.php.net/package/HTTP_Request2\r
+ */\r
+\r
+/**\r
+ * Class for building multipart/form-data request body\r
+ *\r
+ * The class helps to reduce memory consumption by streaming large file uploads\r
+ * from disk, it also allows monitoring of upload progress (see request #7630)\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/rfc1867\r
+ */\r
+class HTTP_Request2_MultipartBody\r
+{\r
+ /**\r
+ * MIME boundary\r
+ * @var string\r
+ */\r
+ private $_boundary;\r
+\r
+ /**\r
+ * Form parameters added via {@link HTTP_Request2::addPostParameter()}\r
+ * @var array\r
+ */\r
+ private $_params = array();\r
+\r
+ /**\r
+ * File uploads added via {@link HTTP_Request2::addUpload()}\r
+ * @var array\r
+ */\r
+ private $_uploads = array();\r
+\r
+ /**\r
+ * Header for parts with parameters\r
+ * @var string\r
+ */\r
+ private $_headerParam = "--%s\r\nContent-Disposition: form-data; name=\"%s\"\r\n\r\n";\r
+\r
+ /**\r
+ * Header for parts with uploads\r
+ * @var string\r
+ */\r
+ private $_headerUpload = "--%s\r\nContent-Disposition: form-data; name=\"%s\"; filename=\"%s\"\r\nContent-Type: %s\r\n\r\n";\r
+\r
+ /**\r
+ * Current position in parameter and upload arrays\r
+ *\r
+ * First number is index of "current" part, second number is position within\r
+ * "current" part\r
+ *\r
+ * @var array\r
+ */\r
+ private $_pos = array(0, 0);\r
+\r
+\r
+ /**\r
+ * Constructor. Sets the arrays with POST data.\r
+ *\r
+ * @param array values of form fields set via {@link HTTP_Request2::addPostParameter()}\r
+ * @param array file uploads set via {@link HTTP_Request2::addUpload()}\r
+ * @param bool whether to append brackets to array variable names\r
+ */\r
+ public function __construct(array $params, array $uploads, $useBrackets = true)\r
+ {\r
+ $this->_params = self::_flattenArray('', $params, $useBrackets);\r
+ foreach ($uploads as $fieldName => $f) {\r
+ if (!is_array($f['fp'])) {\r
+ $this->_uploads[] = $f + array('name' => $fieldName);\r
+ } else {\r
+ for ($i = 0; $i < count($f['fp']); $i++) {\r
+ $upload = array(\r
+ 'name' => ($useBrackets? $fieldName . '[' . $i . ']': $fieldName)\r
+ );\r
+ foreach (array('fp', 'filename', 'size', 'type') as $key) {\r
+ $upload[$key] = $f[$key][$i];\r
+ }\r
+ $this->_uploads[] = $upload;\r
+ }\r
+ }\r
+ }\r
+ }\r
+\r
+ /**\r
+ * Returns the length of the body to use in Content-Length header\r
+ *\r
+ * @return integer\r
+ */\r
+ public function getLength()\r
+ {\r
+ $boundaryLength = strlen($this->getBoundary());\r
+ $headerParamLength = strlen($this->_headerParam) - 4 + $boundaryLength;\r
+ $headerUploadLength = strlen($this->_headerUpload) - 8 + $boundaryLength;\r
+ $length = $boundaryLength + 6;\r
+ foreach ($this->_params as $p) {\r
+ $length += $headerParamLength + strlen($p[0]) + strlen($p[1]) + 2;\r
+ }\r
+ foreach ($this->_uploads as $u) {\r
+ $length += $headerUploadLength + strlen($u['name']) + strlen($u['type']) +\r
+ strlen($u['filename']) + $u['size'] + 2;\r
+ }\r
+ return $length;\r
+ }\r
+\r
+ /**\r
+ * Returns the boundary to use in Content-Type header\r
+ *\r
+ * @return string\r
+ */\r
+ public function getBoundary()\r
+ {\r
+ if (empty($this->_boundary)) {\r
+ $this->_boundary = '--' . md5('PEAR-HTTP_Request2-' . microtime());\r
+ }\r
+ return $this->_boundary;\r
+ }\r
+\r
+ /**\r
+ * Returns next chunk of request body\r
+ *\r
+ * @param integer Amount of bytes to read\r
+ * @return string Up to $length bytes of data, empty string if at end\r
+ */\r
+ public function read($length)\r
+ {\r
+ $ret = '';\r
+ $boundary = $this->getBoundary();\r
+ $paramCount = count($this->_params);\r
+ $uploadCount = count($this->_uploads);\r
+ while ($length > 0 && $this->_pos[0] <= $paramCount + $uploadCount) {\r
+ $oldLength = $length;\r
+ if ($this->_pos[0] < $paramCount) {\r
+ $param = sprintf($this->_headerParam, $boundary, \r
+ $this->_params[$this->_pos[0]][0]) .\r
+ $this->_params[$this->_pos[0]][1] . "\r\n";\r
+ $ret .= substr($param, $this->_pos[1], $length);\r
+ $length -= min(strlen($param) - $this->_pos[1], $length);\r
+\r
+ } elseif ($this->_pos[0] < $paramCount + $uploadCount) {\r
+ $pos = $this->_pos[0] - $paramCount;\r
+ $header = sprintf($this->_headerUpload, $boundary,\r
+ $this->_uploads[$pos]['name'],\r
+ $this->_uploads[$pos]['filename'],\r
+ $this->_uploads[$pos]['type']);\r
+ if ($this->_pos[1] < strlen($header)) {\r
+ $ret .= substr($header, $this->_pos[1], $length);\r
+ $length -= min(strlen($header) - $this->_pos[1], $length);\r
+ }\r
+ $filePos = max(0, $this->_pos[1] - strlen($header));\r
+ if ($length > 0 && $filePos < $this->_uploads[$pos]['size']) {\r
+ $ret .= fread($this->_uploads[$pos]['fp'], $length);\r
+ $length -= min($length, $this->_uploads[$pos]['size'] - $filePos);\r
+ }\r
+ if ($length > 0) {\r
+ $start = $this->_pos[1] + ($oldLength - $length) -\r
+ strlen($header) - $this->_uploads[$pos]['size'];\r
+ $ret .= substr("\r\n", $start, $length);\r
+ $length -= min(2 - $start, $length);\r
+ }\r
+\r
+ } else {\r
+ $closing = '--' . $boundary . "--\r\n";\r
+ $ret .= substr($closing, $this->_pos[1], $length);\r
+ $length -= min(strlen($closing) - $this->_pos[1], $length);\r
+ }\r
+ if ($length > 0) {\r
+ $this->_pos = array($this->_pos[0] + 1, 0);\r
+ } else {\r
+ $this->_pos[1] += $oldLength;\r
+ }\r
+ }\r
+ return $ret;\r
+ }\r
+\r
+ /**\r
+ * Sets the current position to the start of the body\r
+ *\r
+ * This allows reusing the same body in another request\r
+ */\r
+ public function rewind()\r
+ {\r
+ $this->_pos = array(0, 0);\r
+ foreach ($this->_uploads as $u) {\r
+ rewind($u['fp']);\r
+ }\r
+ }\r
+\r
+ /**\r
+ * Returns the body as string\r
+ *\r
+ * Note that it reads all file uploads into memory so it is a good idea not\r
+ * to use this method with large file uploads and rely on read() instead.\r
+ *\r
+ * @return string\r
+ */\r
+ public function __toString()\r
+ {\r
+ $this->rewind();\r
+ return $this->read($this->getLength());\r
+ }\r
+\r
+\r
+ /**\r
+ * Helper function to change the (probably multidimensional) associative array\r
+ * into the simple one.\r
+ *\r
+ * @param string name for item\r
+ * @param mixed item's values\r
+ * @param bool whether to append [] to array variables' names\r
+ * @return array array with the following items: array('item name', 'item value');\r
+ */\r
+ private static function _flattenArray($name, $values, $useBrackets)\r
+ {\r
+ if (!is_array($values)) {\r
+ return array(array($name, $values));\r
+ } else {\r
+ $ret = array();\r
+ foreach ($values as $k => $v) {\r
+ if (empty($name)) {\r
+ $newName = $k;\r
+ } elseif ($useBrackets) {\r
+ $newName = $name . '[' . $k . ']';\r
+ } else {\r
+ $newName = $name;\r
+ }\r
+ $ret = array_merge($ret, self::_flattenArray($newName, $v, $useBrackets));\r
+ }\r
+ return $ret;\r
+ }\r
+ }\r
+}\r
+?>\r
--- /dev/null
+<?php\r
+/**\r
+ * An observer useful for debugging / testing.\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 David Jean Louis <izi@php.net>\r
+ * @author Alexey Borzov <avb@php.net>\r
+ * @license http://opensource.org/licenses/bsd-license.php New BSD License\r
+ * @version CVS: $Id: Log.php 272593 2009-01-02 16:27:14Z avb $\r
+ * @link http://pear.php.net/package/HTTP_Request2\r
+ */\r
+\r
+/**\r
+ * Exception class for HTTP_Request2 package\r
+ */ \r
+require_once 'HTTP/Request2/Exception.php';\r
+\r
+/**\r
+ * A debug observer useful for debugging / testing.\r
+ *\r
+ * This observer logs to a log target data corresponding to the various request \r
+ * and response events, it logs by default to php://output but can be configured\r
+ * to log to a file or via the PEAR Log package.\r
+ *\r
+ * A simple example:\r
+ * <code>\r
+ * require_once 'HTTP/Request2.php';\r
+ * require_once 'HTTP/Request2/Observer/Log.php';\r
+ *\r
+ * $request = new HTTP_Request2('http://www.example.com');\r
+ * $observer = new HTTP_Request2_Observer_Log();\r
+ * $request->attach($observer);\r
+ * $request->send();\r
+ * </code>\r
+ *\r
+ * A more complex example with PEAR Log:\r
+ * <code>\r
+ * require_once 'HTTP/Request2.php';\r
+ * require_once 'HTTP/Request2/Observer/Log.php';\r
+ * require_once 'Log.php';\r
+ *\r
+ * $request = new HTTP_Request2('http://www.example.com');\r
+ * // we want to log with PEAR log\r
+ * $observer = new HTTP_Request2_Observer_Log(Log::factory('console'));\r
+ *\r
+ * // we only want to log received headers\r
+ * $observer->events = array('receivedHeaders');\r
+ *\r
+ * $request->attach($observer);\r
+ * $request->send();\r
+ * </code>\r
+ *\r
+ * @category HTTP\r
+ * @package HTTP_Request2\r
+ * @author David Jean Louis <izi@php.net>\r
+ * @author Alexey Borzov <avb@php.net>\r
+ * @license http://opensource.org/licenses/bsd-license.php New BSD License\r
+ * @version Release: 0.4.1\r
+ * @link http://pear.php.net/package/HTTP_Request2\r
+ */\r
+class HTTP_Request2_Observer_Log implements SplObserver\r
+{\r
+ // properties {{{\r
+\r
+ /**\r
+ * The log target, it can be a a resource or a PEAR Log instance.\r
+ *\r
+ * @var resource|Log $target\r
+ */\r
+ protected $target = null;\r
+\r
+ /**\r
+ * The events to log.\r
+ *\r
+ * @var array $events\r
+ */\r
+ public $events = array(\r
+ 'connect',\r
+ 'sentHeaders',\r
+ 'sentBodyPart',\r
+ 'receivedHeaders',\r
+ 'receivedBody',\r
+ 'disconnect',\r
+ );\r
+\r
+ // }}}\r
+ // __construct() {{{\r
+\r
+ /**\r
+ * Constructor.\r
+ *\r
+ * @param mixed $target Can be a file path (default: php://output), a resource,\r
+ * or an instance of the PEAR Log class.\r
+ * @param array $events Array of events to listen to (default: all events)\r
+ *\r
+ * @return void\r
+ */\r
+ public function __construct($target = 'php://output', array $events = array())\r
+ {\r
+ if (!empty($events)) {\r
+ $this->events = $events;\r
+ }\r
+ if (is_resource($target) || $target instanceof Log) {\r
+ $this->target = $target;\r
+ } elseif (false === ($this->target = @fopen($target, 'w'))) {\r
+ throw new HTTP_Request2_Exception("Unable to open '{$target}'");\r
+ }\r
+ }\r
+\r
+ // }}}\r
+ // update() {{{\r
+\r
+ /**\r
+ * Called when the request notify us of an event.\r
+ *\r
+ * @param HTTP_Request2 $subject The HTTP_Request2 instance\r
+ *\r
+ * @return void\r
+ */\r
+ public function update(SplSubject $subject)\r
+ {\r
+ $event = $subject->getLastEvent();\r
+ if (!in_array($event['name'], $this->events)) {\r
+ return;\r
+ }\r
+\r
+ switch ($event['name']) {\r
+ case 'connect':\r
+ $this->log('* Connected to ' . $event['data']);\r
+ break;\r
+ case 'sentHeaders':\r
+ $headers = explode("\r\n", $event['data']);\r
+ array_pop($headers);\r
+ foreach ($headers as $header) {\r
+ $this->log('> ' . $header);\r
+ }\r
+ break;\r
+ case 'sentBodyPart':\r
+ $this->log('> ' . $event['data']);\r
+ break;\r
+ case 'receivedHeaders':\r
+ $this->log(sprintf('< HTTP/%s %s %s',\r
+ $event['data']->getVersion(),\r
+ $event['data']->getStatus(),\r
+ $event['data']->getReasonPhrase()));\r
+ $headers = $event['data']->getHeader();\r
+ foreach ($headers as $key => $val) {\r
+ $this->log('< ' . $key . ': ' . $val);\r
+ }\r
+ $this->log('< ');\r
+ break;\r
+ case 'receivedBody':\r
+ $this->log($event['data']->getBody());\r
+ break;\r
+ case 'disconnect':\r
+ $this->log('* Disconnected');\r
+ break;\r
+ }\r
+ }\r
+ \r
+ // }}}\r
+ // log() {{{\r
+\r
+ /**\r
+ * Log the given message to the configured target.\r
+ *\r
+ * @param string $message Message to display\r
+ *\r
+ * @return void\r
+ */\r
+ protected function log($message)\r
+ {\r
+ if ($this->target instanceof Log) {\r
+ $this->target->debug($message);\r
+ } elseif (is_resource($this->target)) {\r
+ fwrite($this->target, $message . "\r\n");\r
+ }\r
+ }\r
+\r
+ // }}}\r
+}\r
+\r
+?>
\ No newline at end of file
--- /dev/null
+<?php\r
+/**\r
+ * Class representing a HTTP response\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: Response.php 287948 2009-09-01 17:12:18Z avb $\r
+ * @link http://pear.php.net/package/HTTP_Request2\r
+ */\r
+\r
+/**\r
+ * Exception class for HTTP_Request2 package\r
+ */ \r
+require_once 'HTTP/Request2/Exception.php';\r
+\r
+/**\r
+ * Class representing a HTTP response\r
+ *\r
+ * The class is designed to be used in "streaming" scenario, building the\r
+ * response as it is being received:\r
+ * <code>\r
+ * $statusLine = read_status_line();\r
+ * $response = new HTTP_Request2_Response($statusLine);\r
+ * do {\r
+ * $headerLine = read_header_line();\r
+ * $response->parseHeaderLine($headerLine);\r
+ * } while ($headerLine != '');\r
+ * \r
+ * while ($chunk = read_body()) {\r
+ * $response->appendBody($chunk);\r
+ * }\r
+ * \r
+ * var_dump($response->getHeader(), $response->getCookies(), $response->getBody());\r
+ * </code>\r
+ *\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-6\r
+ */\r
+class HTTP_Request2_Response\r
+{\r
+ /**\r
+ * HTTP protocol version (e.g. 1.0, 1.1)\r
+ * @var string\r
+ */\r
+ protected $version;\r
+\r
+ /**\r
+ * Status code\r
+ * @var integer\r
+ * @link http://tools.ietf.org/html/rfc2616#section-6.1.1\r
+ */\r
+ protected $code;\r
+\r
+ /**\r
+ * Reason phrase\r
+ * @var string\r
+ * @link http://tools.ietf.org/html/rfc2616#section-6.1.1\r
+ */\r
+ protected $reasonPhrase;\r
+\r
+ /**\r
+ * Associative array of response headers\r
+ * @var array\r
+ */\r
+ protected $headers = array();\r
+\r
+ /**\r
+ * Cookies set in the response\r
+ * @var array\r
+ */\r
+ protected $cookies = array();\r
+\r
+ /**\r
+ * Name of last header processed by parseHederLine()\r
+ *\r
+ * Used to handle the headers that span multiple lines\r
+ *\r
+ * @var string\r
+ */\r
+ protected $lastHeader = null;\r
+\r
+ /**\r
+ * Response body\r
+ * @var string\r
+ */\r
+ protected $body = '';\r
+\r
+ /**\r
+ * Whether the body is still encoded by Content-Encoding\r
+ *\r
+ * cURL provides the decoded body to the callback; if we are reading from\r
+ * socket the body is still gzipped / deflated\r
+ *\r
+ * @var bool\r
+ */\r
+ protected $bodyEncoded;\r
+\r
+ /**\r
+ * Associative array of HTTP status code / reason phrase.\r
+ *\r
+ * @var array\r
+ * @link http://tools.ietf.org/html/rfc2616#section-10\r
+ */\r
+ protected static $phrases = array(\r
+\r
+ // 1xx: Informational - Request received, continuing process\r
+ 100 => 'Continue',\r
+ 101 => 'Switching Protocols',\r
+\r
+ // 2xx: Success - The action was successfully received, understood and\r
+ // accepted\r
+ 200 => 'OK',\r
+ 201 => 'Created',\r
+ 202 => 'Accepted',\r
+ 203 => 'Non-Authoritative Information',\r
+ 204 => 'No Content',\r
+ 205 => 'Reset Content',\r
+ 206 => 'Partial Content',\r
+\r
+ // 3xx: Redirection - Further action must be taken in order to complete\r
+ // the request\r
+ 300 => 'Multiple Choices',\r
+ 301 => 'Moved Permanently',\r
+ 302 => 'Found', // 1.1\r
+ 303 => 'See Other',\r
+ 304 => 'Not Modified',\r
+ 305 => 'Use Proxy',\r
+ 307 => 'Temporary Redirect',\r
+\r
+ // 4xx: Client Error - The request contains bad syntax or cannot be \r
+ // fulfilled\r
+ 400 => 'Bad Request',\r
+ 401 => 'Unauthorized',\r
+ 402 => 'Payment Required',\r
+ 403 => 'Forbidden',\r
+ 404 => 'Not Found',\r
+ 405 => 'Method Not Allowed',\r
+ 406 => 'Not Acceptable',\r
+ 407 => 'Proxy Authentication Required',\r
+ 408 => 'Request Timeout',\r
+ 409 => 'Conflict',\r
+ 410 => 'Gone',\r
+ 411 => 'Length Required',\r
+ 412 => 'Precondition Failed',\r
+ 413 => 'Request Entity Too Large',\r
+ 414 => 'Request-URI Too Long',\r
+ 415 => 'Unsupported Media Type',\r
+ 416 => 'Requested Range Not Satisfiable',\r
+ 417 => 'Expectation Failed',\r
+\r
+ // 5xx: Server Error - The server failed to fulfill an apparently\r
+ // valid request\r
+ 500 => 'Internal Server Error',\r
+ 501 => 'Not Implemented',\r
+ 502 => 'Bad Gateway',\r
+ 503 => 'Service Unavailable',\r
+ 504 => 'Gateway Timeout',\r
+ 505 => 'HTTP Version Not Supported',\r
+ 509 => 'Bandwidth Limit Exceeded',\r
+\r
+ );\r
+\r
+ /**\r
+ * Constructor, parses the response status line\r
+ *\r
+ * @param string Response status line (e.g. "HTTP/1.1 200 OK")\r
+ * @param bool Whether body is still encoded by Content-Encoding\r
+ * @throws HTTP_Request2_Exception if status line is invalid according to spec\r
+ */\r
+ public function __construct($statusLine, $bodyEncoded = true)\r
+ {\r
+ if (!preg_match('!^HTTP/(\d\.\d) (\d{3})(?: (.+))?!', $statusLine, $m)) {\r
+ throw new HTTP_Request2_Exception("Malformed response: {$statusLine}");\r
+ }\r
+ $this->version = $m[1];\r
+ $this->code = intval($m[2]);\r
+ if (!empty($m[3])) {\r
+ $this->reasonPhrase = trim($m[3]);\r
+ } elseif (!empty(self::$phrases[$this->code])) {\r
+ $this->reasonPhrase = self::$phrases[$this->code];\r
+ }\r
+ $this->bodyEncoded = (bool)$bodyEncoded;\r
+ }\r
+\r
+ /**\r
+ * Parses the line from HTTP response filling $headers array\r
+ *\r
+ * The method should be called after reading the line from socket or receiving \r
+ * it into cURL callback. Passing an empty string here indicates the end of\r
+ * response headers and triggers additional processing, so be sure to pass an\r
+ * empty string in the end.\r
+ *\r
+ * @param string Line from HTTP response\r
+ */\r
+ public function parseHeaderLine($headerLine)\r
+ {\r
+ $headerLine = trim($headerLine, "\r\n");\r
+\r
+ // empty string signals the end of headers, process the received ones\r
+ if ('' == $headerLine) {\r
+ if (!empty($this->headers['set-cookie'])) {\r
+ $cookies = is_array($this->headers['set-cookie'])?\r
+ $this->headers['set-cookie']:\r
+ array($this->headers['set-cookie']);\r
+ foreach ($cookies as $cookieString) {\r
+ $this->parseCookie($cookieString);\r
+ }\r
+ unset($this->headers['set-cookie']);\r
+ }\r
+ foreach (array_keys($this->headers) as $k) {\r
+ if (is_array($this->headers[$k])) {\r
+ $this->headers[$k] = implode(', ', $this->headers[$k]);\r
+ }\r
+ }\r
+\r
+ // string of the form header-name: header value\r
+ } elseif (preg_match('!^([^\x00-\x1f\x7f-\xff()<>@,;:\\\\"/\[\]?={}\s]+):(.+)$!', $headerLine, $m)) {\r
+ $name = strtolower($m[1]);\r
+ $value = trim($m[2]);\r
+ if (empty($this->headers[$name])) {\r
+ $this->headers[$name] = $value;\r
+ } else {\r
+ if (!is_array($this->headers[$name])) {\r
+ $this->headers[$name] = array($this->headers[$name]);\r
+ }\r
+ $this->headers[$name][] = $value;\r
+ }\r
+ $this->lastHeader = $name;\r
+\r
+ // string \r
+ } elseif (preg_match('!^\s+(.+)$!', $headerLine, $m) && $this->lastHeader) {\r
+ if (!is_array($this->headers[$this->lastHeader])) {\r
+ $this->headers[$this->lastHeader] .= ' ' . trim($m[1]);\r
+ } else {\r
+ $key = count($this->headers[$this->lastHeader]) - 1;\r
+ $this->headers[$this->lastHeader][$key] .= ' ' . trim($m[1]);\r
+ }\r
+ }\r
+ } \r
+\r
+ /**\r
+ * Parses a Set-Cookie header to fill $cookies array\r
+ *\r
+ * @param string value of Set-Cookie header\r
+ * @link http://cgi.netscape.com/newsref/std/cookie_spec.html\r
+ */\r
+ protected function parseCookie($cookieString)\r
+ {\r
+ $cookie = array(\r
+ 'expires' => null,\r
+ 'domain' => null,\r
+ 'path' => null,\r
+ 'secure' => false\r
+ );\r
+\r
+ // Only a name=value pair\r
+ if (!strpos($cookieString, ';')) {\r
+ $pos = strpos($cookieString, '=');\r
+ $cookie['name'] = trim(substr($cookieString, 0, $pos));\r
+ $cookie['value'] = trim(substr($cookieString, $pos + 1));\r
+\r
+ // Some optional parameters are supplied\r
+ } else {\r
+ $elements = explode(';', $cookieString);\r
+ $pos = strpos($elements[0], '=');\r
+ $cookie['name'] = trim(substr($elements[0], 0, $pos));\r
+ $cookie['value'] = trim(substr($elements[0], $pos + 1));\r
+\r
+ for ($i = 1; $i < count($elements); $i++) {\r
+ if (false === strpos($elements[$i], '=')) {\r
+ $elName = trim($elements[$i]);\r
+ $elValue = null;\r
+ } else {\r
+ list ($elName, $elValue) = array_map('trim', explode('=', $elements[$i]));\r
+ }\r
+ $elName = strtolower($elName);\r
+ if ('secure' == $elName) {\r
+ $cookie['secure'] = true;\r
+ } elseif ('expires' == $elName) {\r
+ $cookie['expires'] = str_replace('"', '', $elValue);\r
+ } elseif ('path' == $elName || 'domain' == $elName) {\r
+ $cookie[$elName] = urldecode($elValue);\r
+ } else {\r
+ $cookie[$elName] = $elValue;\r
+ }\r
+ }\r
+ }\r
+ $this->cookies[] = $cookie;\r
+ }\r
+\r
+ /**\r
+ * Appends a string to the response body\r
+ * @param string\r
+ */\r
+ public function appendBody($bodyChunk)\r
+ {\r
+ $this->body .= $bodyChunk;\r
+ }\r
+\r
+ /**\r
+ * Returns the status code\r
+ * @return integer \r
+ */\r
+ public function getStatus()\r
+ {\r
+ return $this->code;\r
+ }\r
+\r
+ /**\r
+ * Returns the reason phrase\r
+ * @return string\r
+ */\r
+ public function getReasonPhrase()\r
+ {\r
+ return $this->reasonPhrase;\r
+ }\r
+\r
+ /**\r
+ * Returns either the named header or all response headers\r
+ *\r
+ * @param string Name of header to return\r
+ * @return string|array Value of $headerName header (null if header is\r
+ * not present), array of all response headers if\r
+ * $headerName is null\r
+ */\r
+ public function getHeader($headerName = null)\r
+ {\r
+ if (null === $headerName) {\r
+ return $this->headers;\r
+ } else {\r
+ $headerName = strtolower($headerName);\r
+ return isset($this->headers[$headerName])? $this->headers[$headerName]: null;\r
+ }\r
+ }\r
+\r
+ /**\r
+ * Returns cookies set in response\r
+ *\r
+ * @return array\r
+ */\r
+ public function getCookies()\r
+ {\r
+ return $this->cookies;\r
+ }\r
+\r
+ /**\r
+ * Returns the body of the response\r
+ *\r
+ * @return string\r
+ * @throws HTTP_Request2_Exception if body cannot be decoded\r
+ */\r
+ public function getBody()\r
+ {\r
+ if (!$this->bodyEncoded ||\r
+ !in_array(strtolower($this->getHeader('content-encoding')), array('gzip', 'deflate'))\r
+ ) {\r
+ return $this->body;\r
+\r
+ } else {\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
+ switch (strtolower($this->getHeader('content-encoding'))) {\r
+ case 'gzip':\r
+ $decoded = self::decodeGzip($this->body);\r
+ break;\r
+ case 'deflate':\r
+ $decoded = self::decodeDeflate($this->body);\r
+ }\r
+ } catch (Exception $e) {\r
+ }\r
+\r
+ if (!empty($oldEncoding)) {\r
+ mb_internal_encoding($oldEncoding);\r
+ }\r
+ if (!empty($e)) {\r
+ throw $e;\r
+ }\r
+ return $decoded;\r
+ }\r
+ }\r
+\r
+ /**\r
+ * Get the HTTP version of the response\r
+ *\r
+ * @return string\r
+ */ \r
+ public function getVersion()\r
+ {\r
+ return $this->version;\r
+ }\r
+\r
+ /**\r
+ * Decodes the message-body encoded by gzip\r
+ *\r
+ * The real decoding work is done by gzinflate() built-in function, this\r
+ * method only parses the header and checks data for compliance with\r
+ * RFC 1952\r
+ *\r
+ * @param string gzip-encoded data\r
+ * @return string decoded data\r
+ * @throws HTTP_Request2_Exception\r
+ * @link http://tools.ietf.org/html/rfc1952\r
+ */\r
+ public static function decodeGzip($data)\r
+ {\r
+ $length = strlen($data);\r
+ // If it doesn't look like gzip-encoded data, don't bother\r
+ if (18 > $length || strcmp(substr($data, 0, 2), "\x1f\x8b")) {\r
+ return $data;\r
+ }\r
+ if (!function_exists('gzinflate')) {\r
+ throw new HTTP_Request2_Exception('Unable to decode body: gzip extension not available');\r
+ }\r
+ $method = ord(substr($data, 2, 1));\r
+ if (8 != $method) {\r
+ throw new HTTP_Request2_Exception('Error parsing gzip header: unknown compression method');\r
+ }\r
+ $flags = ord(substr($data, 3, 1));\r
+ if ($flags & 224) {\r
+ throw new HTTP_Request2_Exception('Error parsing gzip header: reserved bits are set');\r
+ }\r
+\r
+ // header is 10 bytes minimum. may be longer, though.\r
+ $headerLength = 10;\r
+ // extra fields, need to skip 'em\r
+ if ($flags & 4) {\r
+ if ($length - $headerLength - 2 < 8) {\r
+ throw new HTTP_Request2_Exception('Error parsing gzip header: data too short');\r
+ }\r
+ $extraLength = unpack('v', substr($data, 10, 2));\r
+ if ($length - $headerLength - 2 - $extraLength[1] < 8) {\r
+ throw new HTTP_Request2_Exception('Error parsing gzip header: data too short');\r
+ }\r
+ $headerLength += $extraLength[1] + 2;\r
+ }\r
+ // file name, need to skip that\r
+ if ($flags & 8) {\r
+ if ($length - $headerLength - 1 < 8) {\r
+ throw new HTTP_Request2_Exception('Error parsing gzip header: data too short');\r
+ }\r
+ $filenameLength = strpos(substr($data, $headerLength), chr(0));\r
+ if (false === $filenameLength || $length - $headerLength - $filenameLength - 1 < 8) {\r
+ throw new HTTP_Request2_Exception('Error parsing gzip header: data too short');\r
+ }\r
+ $headerLength += $filenameLength + 1;\r
+ }\r
+ // comment, need to skip that also\r
+ if ($flags & 16) {\r
+ if ($length - $headerLength - 1 < 8) {\r
+ throw new HTTP_Request2_Exception('Error parsing gzip header: data too short');\r
+ }\r
+ $commentLength = strpos(substr($data, $headerLength), chr(0));\r
+ if (false === $commentLength || $length - $headerLength - $commentLength - 1 < 8) {\r
+ throw new HTTP_Request2_Exception('Error parsing gzip header: data too short');\r
+ }\r
+ $headerLength += $commentLength + 1;\r
+ }\r
+ // have a CRC for header. let's check\r
+ if ($flags & 2) {\r
+ if ($length - $headerLength - 2 < 8) {\r
+ throw new HTTP_Request2_Exception('Error parsing gzip header: data too short');\r
+ }\r
+ $crcReal = 0xffff & crc32(substr($data, 0, $headerLength));\r
+ $crcStored = unpack('v', substr($data, $headerLength, 2));\r
+ if ($crcReal != $crcStored[1]) {\r
+ throw new HTTP_Request2_Exception('Header CRC check failed');\r
+ }\r
+ $headerLength += 2;\r
+ }\r
+ // unpacked data CRC and size at the end of encoded data\r
+ $tmp = unpack('V2', substr($data, -8));\r
+ $dataCrc = $tmp[1];\r
+ $dataSize = $tmp[2];\r
+\r
+ // finally, call the gzinflate() function\r
+ // don't pass $dataSize to gzinflate, see bugs #13135, #14370\r
+ $unpacked = gzinflate(substr($data, $headerLength, -8));\r
+ if (false === $unpacked) {\r
+ throw new HTTP_Request2_Exception('gzinflate() call failed');\r
+ } elseif ($dataSize != strlen($unpacked)) {\r
+ throw new HTTP_Request2_Exception('Data size check failed');\r
+ } elseif ((0xffffffff & $dataCrc) != (0xffffffff & crc32($unpacked))) {\r
+ throw new HTTP_Request2_Exception('Data CRC check failed');\r
+ }\r
+ return $unpacked;\r
+ }\r
+\r
+ /**\r
+ * Decodes the message-body encoded by deflate\r
+ *\r
+ * @param string deflate-encoded data\r
+ * @return string decoded data\r
+ * @throws HTTP_Request2_Exception\r
+ */\r
+ public static function decodeDeflate($data)\r
+ {\r
+ if (!function_exists('gzuncompress')) {\r
+ throw new HTTP_Request2_Exception('Unable to decode body: gzip extension not available');\r
+ }\r
+ // RFC 2616 defines 'deflate' encoding as zlib format from RFC 1950,\r
+ // while many applications send raw deflate stream from RFC 1951.\r
+ // We should check for presence of zlib header and use gzuncompress() or\r
+ // gzinflate() as needed. See bug #15305\r
+ $header = unpack('n', substr($data, 0, 2));\r
+ return (0 == $header[1] % 31)? gzuncompress($data): gzinflate($data);\r
+ }\r
+}\r
+?>
\ No newline at end of file
<?php
-// +-----------------------------------------------------------------------+
-// | Copyright (c) 2007-2008, Christian Schmidt, Peytz & Co. A/S |
-// | All rights reserved. |
-// | |
-// | Redistribution and use in source and binary forms, with or without |
-// | modification, are permitted provided that the following conditions |
-// | are met: |
-// | |
-// | o Redistributions of source code must retain the above copyright |
-// | notice, this list of conditions and the following disclaimer. |
-// | o Redistributions in binary form must reproduce the above copyright |
-// | notice, this list of conditions and the following disclaimer in the |
-// | documentation and/or other materials provided with the distribution.|
-// | o The names of the authors may not be used to endorse or promote |
-// | products derived from this software without specific prior written |
-// | permission. |
-// | |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR |
-// | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT |
-// | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
-// | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT |
-// | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
-// | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
-// | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
-// | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
-// | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
-// | |
-// +-----------------------------------------------------------------------+
-// | Author: Christian Schmidt <schmidt at php dot net> |
-// +-----------------------------------------------------------------------+
-//
-// $Id: URL2.php,v 1.10 2008/04/26 21:57:08 schmidt Exp $
-//
-// Net_URL2 Class (PHP5 Only)
-
-// This code is released under the BSD License - http://www.opensource.org/licenses/bsd-license.php
/**
- * @license BSD License
+ * Net_URL2, a class representing a URL as per RFC 3986.
+ *
+ * PHP version 5
+ *
+ * LICENSE:
+ *
+ * Copyright (c) 2007-2009, Peytz & Co. A/S
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the distribution.
+ * * Neither the name of the PHP_LexerGenerator nor the names of its
+ * contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
+ * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * @category Networking
+ * @package Net_URL2
+ * @author Christian Schmidt <chsc@peytz.dk>
+ * @copyright 2007-2008 Peytz & Co. A/S
+ * @license http://www.opensource.org/licenses/bsd-license.php New BSD License
+ * @version CVS: $Id: URL2.php 286661 2009-08-02 12:50:54Z schmidt $
+ * @link http://www.rfc-editor.org/rfc/rfc3986.txt
+ */
+
+/**
+ * Represents a URL as per RFC 3986.
+ *
+ * @category Networking
+ * @package Net_URL2
+ * @author Christian Schmidt <chsc@peytz.dk>
+ * @copyright 2007-2008 Peytz & Co. ApS
+ * @license http://www.opensource.org/licenses/bsd-license.php New BSD License
+ * @version Release: @package_version@
+ * @link http://pear.php.net/package/Net_URL2
*/
class Net_URL2
{
* Do strict parsing in resolve() (see RFC 3986, section 5.2.2). Default
* is true.
*/
- const OPTION_STRICT = 'strict';
+ const OPTION_STRICT = 'strict';
/**
* Represent arrays in query using PHP's [] notation. Default is true.
*/
- const OPTION_USE_BRACKETS = 'use_brackets';
+ const OPTION_USE_BRACKETS = 'use_brackets';
/**
* URL-encode query variable keys. Default is true.
*/
- const OPTION_ENCODE_KEYS = 'encode_keys';
+ const OPTION_ENCODE_KEYS = 'encode_keys';
/**
* Query variable separators when parsing the query string. Every character
* is considered a separator. Default is specified by the
* arg_separator.input php.ini setting (this defaults to "&").
*/
- const OPTION_SEPARATOR_INPUT = 'input_separator';
+ const OPTION_SEPARATOR_INPUT = 'input_separator';
/**
* Query variable separator used when generating the query string. Default
/**
* Default options corresponds to how PHP handles $_GET.
*/
- private $options = array(
+ private $_options = array(
self::OPTION_STRICT => true,
self::OPTION_USE_BRACKETS => true,
self::OPTION_ENCODE_KEYS => true,
/**
* @var string|bool
*/
- private $scheme = false;
+ private $_scheme = false;
/**
* @var string|bool
*/
- private $userinfo = false;
+ private $_userinfo = false;
/**
* @var string|bool
*/
- private $host = false;
+ private $_host = false;
/**
* @var int|bool
*/
- private $port = false;
+ private $_port = false;
/**
* @var string
*/
- private $path = '';
+ private $_path = '';
/**
* @var string|bool
*/
- private $query = false;
+ private $_query = false;
/**
* @var string|bool
*/
- private $fragment = false;
+ private $_fragment = false;
/**
+ * Constructor.
+ *
* @param string $url an absolute or relative URL
- * @param array $options
+ * @param array $options an array of OPTION_xxx constants
*/
public function __construct($url, $options = null)
{
ini_get('arg_separator.output'));
if (is_array($options)) {
foreach ($options as $optionName => $value) {
- $this->setOption($optionName);
+ $this->setOption($optionName, $value);
}
}
if (preg_match('@^([a-z][a-z0-9.+-]*):@i', $url, $reg)) {
- $this->scheme = $reg[1];
+ $this->_scheme = $reg[1];
$url = substr($url, strlen($reg[0]));
}
}
$i = strcspn($url, '?#');
- $this->path = substr($url, 0, $i);
+ $this->_path = substr($url, 0, $i);
$url = substr($url, $i);
if (preg_match('@^\?([^#]*)@', $url, $reg)) {
- $this->query = $reg[1];
+ $this->_query = $reg[1];
$url = substr($url, strlen($reg[0]));
}
if ($url) {
- $this->fragment = substr($url, 1);
+ $this->_fragment = substr($url, 1);
}
}
+ /**
+ * Magic Setter.
+ *
+ * This method will magically set the value of a private variable ($var)
+ * with the value passed as the args
+ *
+ * @param string $var The private variable to set.
+ * @param mixed $arg An argument of any type.
+ * @return void
+ */
+ public function __set($var, $arg)
+ {
+ $method = 'set' . $var;
+ if (method_exists($this, $method)) {
+ $this->$method($arg);
+ }
+ }
+
+ /**
+ * Magic Getter.
+ *
+ * This is the magic get method to retrieve the private variable
+ * that was set by either __set() or it's setter...
+ *
+ * @param string $var The property name to retrieve.
+ * @return mixed $this->$var Either a boolean false if the
+ * property is not set or the value
+ * of the private property.
+ */
+ public function __get($var)
+ {
+ $method = 'get' . $var;
+ if (method_exists($this, $method)) {
+ return $this->$method();
+ }
+
+ return false;
+ }
+
/**
* Returns the scheme, e.g. "http" or "urn", or false if there is no
* scheme specified, i.e. if this is a relative URL.
*/
public function getScheme()
{
- return $this->scheme;
+ return $this->_scheme;
}
/**
- * @param string|bool $scheme
+ * Sets the scheme, e.g. "http" or "urn". Specify false if there is no
+ * scheme specified, i.e. if this is a relative URL.
+ *
+ * @param string|bool $scheme e.g. "http" or "urn", or false if there is no
+ * scheme specified, i.e. if this is a relative
+ * URL
*
* @return void
* @see getScheme()
*/
public function setScheme($scheme)
{
- $this->scheme = $scheme;
+ $this->_scheme = $scheme;
}
/**
*/
public function getUser()
{
- return $this->userinfo !== false ? preg_replace('@:.*$@', '', $this->userinfo) : false;
+ return $this->_userinfo !== false
+ ? preg_replace('@:.*$@', '', $this->_userinfo)
+ : false;
}
/**
*/
public function getPassword()
{
- return $this->userinfo !== false ? substr(strstr($this->userinfo, ':'), 1) : false;
+ return $this->_userinfo !== false
+ ? substr(strstr($this->_userinfo, ':'), 1)
+ : false;
}
/**
*/
public function getUserinfo()
{
- return $this->userinfo;
+ return $this->_userinfo;
}
/**
* in the userinfo part as username ":" password.
*
* @param string|bool $userinfo userinfo or username
- * @param string|bool $password
+ * @param string|bool $password optional password, or false
*
* @return void
*/
public function setUserinfo($userinfo, $password = false)
{
- $this->userinfo = $userinfo;
+ $this->_userinfo = $userinfo;
if ($password !== false) {
- $this->userinfo .= ':' . $password;
+ $this->_userinfo .= ':' . $password;
}
}
* Returns the host part, or false if there is no authority part, e.g.
* relative URLs.
*
- * @return string|bool
+ * @return string|bool a hostname, an IP address, or false
*/
public function getHost()
{
- return $this->host;
+ return $this->_host;
}
/**
- * @param string|bool $host
+ * Sets the host part. Specify false if there is no authority part, e.g.
+ * relative URLs.
+ *
+ * @param string|bool $host a hostname, an IP address, or false
*
* @return void
*/
public function setHost($host)
{
- $this->host = $host;
+ $this->_host = $host;
}
/**
*/
public function getPort()
{
- return $this->port;
+ return $this->_port;
}
/**
- * @param int|bool $port
+ * Sets the port number. Specify false if there is no port number specified,
+ * i.e. if the default port is to be used.
+ *
+ * @param int|bool $port a port number, or false
*
* @return void
*/
public function setPort($port)
{
- $this->port = intval($port);
+ $this->_port = intval($port);
}
/**
* Returns the authority part, i.e. [ userinfo "@" ] host [ ":" port ], or
- * false if there is no authority none.
+ * false if there is no authority.
*
* @return string|bool
*/
public function getAuthority()
{
- if (!$this->host) {
+ if (!$this->_host) {
return false;
}
$authority = '';
- if ($this->userinfo !== false) {
- $authority .= $this->userinfo . '@';
+ if ($this->_userinfo !== false) {
+ $authority .= $this->_userinfo . '@';
}
- $authority .= $this->host;
+ $authority .= $this->_host;
- if ($this->port !== false) {
- $authority .= ':' . $this->port;
+ if ($this->_port !== false) {
+ $authority .= ':' . $this->_port;
}
return $authority;
}
/**
- * @param string|false $authority
+ * Sets the authority part, i.e. [ userinfo "@" ] host [ ":" port ]. Specify
+ * false if there is no authority.
+ *
+ * @param string|false $authority a hostname or an IP addresse, possibly
+ * with userinfo prefixed and port number
+ * appended, e.g. "foo:bar@example.org:81".
*
* @return void
*/
public function setAuthority($authority)
{
- $this->user = false;
- $this->pass = false;
- $this->host = false;
- $this->port = false;
- if (preg_match('@^(([^\@]+)\@)?([^:]+)(:(\d*))?$@', $authority, $reg)) {
+ $this->_userinfo = false;
+ $this->_host = false;
+ $this->_port = false;
+ if (preg_match('@^(([^\@]*)\@)?([^:]+)(:(\d*))?$@', $authority, $reg)) {
if ($reg[1]) {
- $this->userinfo = $reg[2];
+ $this->_userinfo = $reg[2];
}
- $this->host = $reg[3];
+ $this->_host = $reg[3];
if (isset($reg[5])) {
- $this->port = intval($reg[5]);
+ $this->_port = intval($reg[5]);
}
}
}
*/
public function getPath()
{
- return $this->path;
+ return $this->_path;
}
/**
- * @param string $path
+ * Sets the path part (possibly an empty string).
+ *
+ * @param string $path a path
*
* @return void
*/
public function setPath($path)
{
- $this->path = $path;
+ $this->_path = $path;
}
/**
* Returns the query string (excluding the leading "?"), or false if "?"
- * isn't present in the URL.
+ * is not present in the URL.
*
* @return string|bool
* @see self::getQueryVariables()
*/
public function getQuery()
{
- return $this->query;
+ return $this->_query;
}
/**
- * @param string|bool $query
+ * Sets the query string (excluding the leading "?"). Specify false if "?"
+ * is not present in the URL.
+ *
+ * @param string|bool $query a query string, e.g. "foo=1&bar=2"
*
* @return void
* @see self::setQueryVariables()
*/
public function setQuery($query)
{
- $this->query = $query;
+ $this->_query = $query;
}
/**
- * Returns the fragment name, or false if "#" isn't present in the URL.
+ * Returns the fragment name, or false if "#" is not present in the URL.
*
* @return string|bool
*/
public function getFragment()
{
- return $this->fragment;
+ return $this->_fragment;
}
/**
- * @param string|bool $fragment
+ * Sets the fragment name. Specify false if "#" is not present in the URL.
+ *
+ * @param string|bool $fragment a fragment excluding the leading "#", or
+ * false
*
* @return void
*/
public function setFragment($fragment)
{
- $this->fragment = $fragment;
+ $this->_fragment = $fragment;
}
/**
* Returns the query string like an array as the variables would appear in
- * $_GET in a PHP script.
+ * $_GET in a PHP script. If the URL does not contain a "?", an empty array
+ * is returned.
*
* @return array
*/
$pattern = '/[' .
preg_quote($this->getOption(self::OPTION_SEPARATOR_INPUT), '/') .
']/';
- $parts = preg_split($pattern, $this->query, -1, PREG_SPLIT_NO_EMPTY);
+ $parts = preg_split($pattern, $this->_query, -1, PREG_SPLIT_NO_EMPTY);
$return = array();
foreach ($parts as $part) {
}
/**
+ * Sets the query string to the specified variable in the query string.
+ *
* @param array $array (name => value) array
*
* @return void
public function setQueryVariables(array $array)
{
if (!$array) {
- $this->query = false;
+ $this->_query = false;
} else {
foreach ($array as $name => $value) {
if ($this->getOption(self::OPTION_ENCODE_KEYS)) {
- $name = rawurlencode($name);
+ $name = self::urlencode($name);
}
if (is_array($value)) {
: ($name . '=' . $v);
}
} elseif (!is_null($value)) {
- $parts[] = $name . '=' . $value;
+ $parts[] = $name . '=' . self::urlencode($value);
} else {
$parts[] = $name;
}
}
- $this->query = implode($this->getOption(self::OPTION_SEPARATOR_OUTPUT),
- $parts);
+ $this->_query = implode($this->getOption(self::OPTION_SEPARATOR_OUTPUT),
+ $parts);
}
}
/**
- * @param string $name
- * @param mixed $value
+ * Sets the specified variable in the query string.
+ *
+ * @param string $name variable name
+ * @param mixed $value variable value
*
* @return array
*/
}
/**
- * @param string $name
+ * Removes the specifed variable from the query string.
+ *
+ * @param string $name a query string variable, e.g. "foo" in "?foo=1"
*
* @return void
*/
// See RFC 3986, section 5.3
$url = "";
- if ($this->scheme !== false) {
- $url .= $this->scheme . ':';
+ if ($this->_scheme !== false) {
+ $url .= $this->_scheme . ':';
}
$authority = $this->getAuthority();
if ($authority !== false) {
$url .= '//' . $authority;
}
- $url .= $this->path;
+ $url .= $this->_path;
- if ($this->query !== false) {
- $url .= '?' . $this->query;
+ if ($this->_query !== false) {
+ $url .= '?' . $this->_query;
}
- if ($this->fragment !== false) {
- $url .= '#' . $this->fragment;
+ if ($this->_fragment !== false) {
+ $url .= '#' . $this->_fragment;
}
return $url;
}
+ /**
+ * Returns a string representation of this URL.
+ *
+ * @return string
+ * @see toString()
+ */
+ public function __toString()
+ {
+ return $this->getURL();
+ }
+
/**
* Returns a normalized string representation of this URL. This is useful
* for comparison of URLs.
// See RFC 3886, section 6
// Schemes are case-insensitive
- if ($this->scheme) {
- $this->scheme = strtolower($this->scheme);
+ if ($this->_scheme) {
+ $this->_scheme = strtolower($this->_scheme);
}
// Hostnames are case-insensitive
- if ($this->host) {
- $this->host = strtolower($this->host);
+ if ($this->_host) {
+ $this->_host = strtolower($this->_host);
}
// Remove default port number for known schemes (RFC 3986, section 6.2.3)
- if ($this->port &&
- $this->scheme &&
- $this->port == getservbyname($this->scheme, 'tcp')) {
+ if ($this->_port &&
+ $this->_scheme &&
+ $this->_port == getservbyname($this->_scheme, 'tcp')) {
- $this->port = false;
+ $this->_port = false;
}
// Normalize case of %XX percentage-encodings (RFC 3986, section 6.2.2.1)
- foreach (array('userinfo', 'host', 'path') as $part) {
+ foreach (array('_userinfo', '_host', '_path') as $part) {
if ($this->$part) {
- $this->$part = preg_replace('/%[0-9a-f]{2}/ie', 'strtoupper("\0")', $this->$part);
+ $this->$part = preg_replace('/%[0-9a-f]{2}/ie',
+ 'strtoupper("\0")',
+ $this->$part);
}
}
// Path segment normalization (RFC 3986, section 6.2.2.3)
- $this->path = self::removeDotSegments($this->path);
+ $this->_path = self::removeDotSegments($this->_path);
// Scheme based normalization (RFC 3986, section 6.2.3)
- if ($this->host && !$this->path) {
- $this->path = '/';
+ if ($this->_host && !$this->_path) {
+ $this->_path = '/';
}
}
*/
public function isAbsolute()
{
- return (bool) $this->scheme;
+ return (bool) $this->_scheme;
}
/**
*/
public function resolve($reference)
{
- if (is_string($reference)) {
+ if (!$reference instanceof Net_URL2) {
$reference = new self($reference);
}
if (!$this->isAbsolute()) {
// A non-strict parser may ignore a scheme in the reference if it is
// identical to the base URI's scheme.
- if (!$this->getOption(self::OPTION_STRICT) && $reference->scheme == $this->scheme) {
- $reference->scheme = false;
+ if (!$this->getOption(self::OPTION_STRICT) && $reference->_scheme == $this->_scheme) {
+ $reference->_scheme = false;
}
$target = new self('');
- if ($reference->scheme !== false) {
- $target->scheme = $reference->scheme;
+ if ($reference->_scheme !== false) {
+ $target->_scheme = $reference->_scheme;
$target->setAuthority($reference->getAuthority());
- $target->path = self::removeDotSegments($reference->path);
- $target->query = $reference->query;
+ $target->_path = self::removeDotSegments($reference->_path);
+ $target->_query = $reference->_query;
} else {
$authority = $reference->getAuthority();
if ($authority !== false) {
$target->setAuthority($authority);
- $target->path = self::removeDotSegments($reference->path);
- $target->query = $reference->query;
+ $target->_path = self::removeDotSegments($reference->_path);
+ $target->_query = $reference->_query;
} else {
- if ($reference->path == '') {
- $target->path = $this->path;
- if ($reference->query !== false) {
- $target->query = $reference->query;
+ if ($reference->_path == '') {
+ $target->_path = $this->_path;
+ if ($reference->_query !== false) {
+ $target->_query = $reference->_query;
} else {
- $target->query = $this->query;
+ $target->_query = $this->_query;
}
} else {
- if (substr($reference->path, 0, 1) == '/') {
- $target->path = self::removeDotSegments($reference->path);
+ if (substr($reference->_path, 0, 1) == '/') {
+ $target->_path = self::removeDotSegments($reference->_path);
} else {
// Merge paths (RFC 3986, section 5.2.3)
- if ($this->host !== false && $this->path == '') {
- $target->path = '/' . $this->path;
+ if ($this->_host !== false && $this->_path == '') {
+ $target->_path = '/' . $this->_path;
} else {
- $i = strrpos($this->path, '/');
+ $i = strrpos($this->_path, '/');
if ($i !== false) {
- $target->path = substr($this->path, 0, $i + 1);
+ $target->_path = substr($this->_path, 0, $i + 1);
}
- $target->path .= $reference->path;
+ $target->_path .= $reference->_path;
}
- $target->path = self::removeDotSegments($target->path);
+ $target->_path = self::removeDotSegments($target->_path);
}
- $target->query = $reference->query;
+ $target->_query = $reference->_query;
}
$target->setAuthority($this->getAuthority());
}
- $target->scheme = $this->scheme;
+ $target->_scheme = $this->_scheme;
}
- $target->fragment = $reference->fragment;
+ $target->_fragment = $reference->_fragment;
return $target;
}
*
* @return string a path
*/
- private static function removeDotSegments($path)
+ public static function removeDotSegments($path)
{
$output = '';
// method
$j = 0;
while ($path && $j++ < 100) {
- // Step A
if (substr($path, 0, 2) == './') {
+ // Step 2.A
$path = substr($path, 2);
} elseif (substr($path, 0, 3) == '../') {
+ // Step 2.A
$path = substr($path, 3);
-
- // Step B
} elseif (substr($path, 0, 3) == '/./' || $path == '/.') {
+ // Step 2.B
$path = '/' . substr($path, 3);
-
- // Step C
} elseif (substr($path, 0, 4) == '/../' || $path == '/..') {
- $path = '/' . substr($path, 4);
- $i = strrpos($output, '/');
+ // Step 2.C
+ $path = '/' . substr($path, 4);
+ $i = strrpos($output, '/');
$output = $i === false ? '' : substr($output, 0, $i);
-
- // Step D
} elseif ($path == '.' || $path == '..') {
+ // Step 2.D
$path = '';
-
- // Step E
} else {
+ // Step 2.E
$i = strpos($path, '/');
if ($i === 0) {
$i = strpos($path, '/', 1);
return $output;
}
+ /**
+ * Percent-encodes all non-alphanumeric characters except these: _ . - ~
+ * Similar to PHP's rawurlencode(), except that it also encodes ~ in PHP
+ * 5.2.x and earlier.
+ *
+ * @param $raw the string to encode
+ * @return string
+ */
+ public static function urlencode($string)
+ {
+ $encoded = rawurlencode($string);
+ // This is only necessary in PHP < 5.3.
+ $encoded = str_replace('%7E', '~', $encoded);
+ return $encoded;
+ }
+
/**
* Returns a Net_URL2 instance representing the canonical URL of the
* currently executing PHP script.
// Begin with a relative URL
$url = new self($_SERVER['PHP_SELF']);
- $url->scheme = isset($_SERVER['HTTPS']) ? 'https' : 'http';
- $url->host = $_SERVER['SERVER_NAME'];
+ $url->_scheme = isset($_SERVER['HTTPS']) ? 'https' : 'http';
+ $url->_host = $_SERVER['SERVER_NAME'];
$port = intval($_SERVER['SERVER_PORT']);
- if ($url->scheme == 'http' && $port != 80 ||
- $url->scheme == 'https' && $port != 443) {
+ if ($url->_scheme == 'http' && $port != 80 ||
+ $url->_scheme == 'https' && $port != 443) {
- $url->port = $port;
+ $url->_port = $port;
}
return $url;
}
// Begin with a relative URL
$url = new self($_SERVER['REQUEST_URI']);
- $url->scheme = isset($_SERVER['HTTPS']) ? 'https' : 'http';
+ $url->_scheme = isset($_SERVER['HTTPS']) ? 'https' : 'http';
// Set host and possibly port
$url->setAuthority($_SERVER['HTTP_HOST']);
return $url;
*/
function setOption($optionName, $value)
{
- if (!array_key_exists($optionName, $this->options)) {
+ if (!array_key_exists($optionName, $this->_options)) {
return false;
}
- $this->options[$optionName] = $value;
+ $this->_options[$optionName] = $value;
}
/**
*/
function getOption($optionName)
{
- return isset($this->options[$optionName])
- ? $this->options[$optionName] : false;
+ return isset($this->_options[$optionName])
+ ? $this->_options[$optionName] : false;
}
}
'include'=>'HTTP/Request.php',
'check_class'=>'HTTP_Request'
),
+ array(
+ 'name'=>'HTTP_Request2',
+ 'pear'=>'HTTP_Request2',
+ 'url'=>'http://pear.php.net/package/HTTP_Request2',
+ 'include'=>'HTTP/Request2.php',
+ 'check_class'=>'HTTP_Request2'
+ ),
array(
'name'=>'Mail',
'pear'=>'Mail',
return strlen($url) >= common_config('site', 'shorturllength');
}
- protected function http_post($data) {
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_URL, $this->service_url);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
- curl_setopt($ch, CURLOPT_POST, 1);
- curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
- $response = curl_exec($ch);
- $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
- curl_close($ch);
- if (($code < 200) || ($code >= 400)) return false;
- return $response;
+ protected function http_post($data)
+ {
+ $request = HTTPClient::start();
+ $response = $request->post($this->service_url, null, $data);
+ return $response->getBody();
}
- protected function http_get($url) {
- $encoded_url = urlencode($url);
- return file_get_contents("{$this->service_url}$encoded_url");
+ protected function http_get($url)
+ {
+ $request = HTTPClient::start();
+ $response = $request->get($this->service_url . urlencode($url));
+ return $response->getBody();
}
protected function tidy($response) {
+++ /dev/null
-<?php
-/**
- * StatusNet, the distributed open-source microblogging tool
- *
- * Utility class for wrapping Curl
- *
- * PHP version 5
- *
- * LICENCE: This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- *
- * @category HTTP
- * @package StatusNet
- * @author Evan Prodromou <evan@status.net>
- * @copyright 2009 StatusNet, Inc.
- * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
- * @link http://status.net/
- */
-
-if (!defined('STATUSNET')) {
- exit(1);
-}
-
-define(CURLCLIENT_VERSION, "0.1");
-
-/**
- * Wrapper for Curl
- *
- * Makes Curl HTTP client calls within our HTTPClient framework
- *
- * @category HTTP
- * @package StatusNet
- * @author Evan Prodromou <evan@status.net>
- * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
- * @link http://status.net/
- */
-
-class CurlClient extends HTTPClient
-{
- function __construct()
- {
- }
-
- function head($url, $headers=null)
- {
- $ch = curl_init($url);
-
- $this->setup($ch);
-
- curl_setopt_array($ch,
- array(CURLOPT_NOBODY => true));
-
- if (!is_null($headers)) {
- curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
- }
-
- $result = curl_exec($ch);
-
- curl_close($ch);
-
- return $this->parseResults($result);
- }
-
- function get($url, $headers=null)
- {
- $ch = curl_init($url);
-
- $this->setup($ch);
-
- if (!is_null($headers)) {
- curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
- }
-
- $result = curl_exec($ch);
-
- curl_close($ch);
-
- return $this->parseResults($result);
- }
-
- function post($url, $headers=null, $body=null)
- {
- $ch = curl_init($url);
-
- $this->setup($ch);
-
- curl_setopt($ch, CURLOPT_POST, true);
-
- if (!is_null($body)) {
- curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
- }
-
- if (!is_null($headers)) {
- curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
- }
-
- $result = curl_exec($ch);
-
- curl_close($ch);
-
- return $this->parseResults($result);
- }
-
- function setup($ch)
- {
- curl_setopt_array($ch,
- array(CURLOPT_USERAGENT => $this->userAgent(),
- CURLOPT_HEADER => true,
- CURLOPT_RETURNTRANSFER => true));
- }
-
- function userAgent()
- {
- $version = curl_version();
- return parent::userAgent() . " CurlClient/".CURLCLIENT_VERSION . " cURL/" . $version['version'];
- }
-
- function parseResults($results)
- {
- $resp = new HTTPResponse();
-
- $lines = explode("\r\n", $results);
-
- if (preg_match("#^HTTP/1.[01] (\d\d\d) .+$#", $lines[0], $match)) {
- $resp->code = $match[1];
- } else {
- throw Exception("Bad format: initial line is not HTTP status line");
- }
-
- $lastk = null;
-
- for ($i = 1; $i < count($lines); $i++) {
- $l =& $lines[$i];
- if (mb_strlen($l) == 0) {
- $resp->body = implode("\r\n", array_slice($lines, $i + 1));
- break;
- }
- if (preg_match("#^(\S+):\s+(.*)$#", $l, $match)) {
- $k = $match[1];
- $v = $match[2];
-
- if (array_key_exists($k, $resp->headers)) {
- if (is_array($resp->headers[$k])) {
- $resp->headers[$k][] = $v;
- } else {
- $resp->headers[$k] = array($resp->headers[$k], $v);
- }
- } else {
- $resp->headers[$k] = $v;
- }
- $lastk = $k;
- } else if (preg_match("#^\s+(.*)$#", $l, $match)) {
- // continuation line
- if (is_null($lastk)) {
- throw Exception("Bad format: initial whitespace in headers");
- }
- $h =& $resp->headers[$lastk];
- if (is_array($h)) {
- $n = count($h);
- $h[$n-1] .= $match[1];
- } else {
- $h .= $match[1];
- }
- }
- }
-
- return $resp;
- }
-}
array('contentlimit' => null),
'message' =>
array('contentlimit' => null),
- 'http' =>
- array('client' => 'curl'), // XXX: should this be the default?
'location' =>
array('namespace' => 1), // 1 = geonames, 2 = Yahoo Where on Earth
);
exit(1);
}
+require_once 'HTTP/Request2.php';
+require_once 'HTTP/Request2/Response.php';
+
/**
* Useful structure for HTTP responses
*
* ways of doing them. This class hides the specifics of what underlying
* library (curl or PHP-HTTP or whatever) that's used.
*
+ * This extends the HTTP_Request2_Response class with methods to get info
+ * about any followed redirects.
+ *
* @category HTTP
- * @package StatusNet
- * @author Evan Prodromou <evan@status.net>
- * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
- * @link http://status.net/
+ * @package StatusNet
+ * @author Evan Prodromou <evan@status.net>
+ * @author Brion Vibber <brion@status.net>
+ * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
+ * @link http://status.net/
*/
-
-class HTTPResponse
+class HTTPResponse extends HTTP_Request2_Response
{
- public $code = null;
- public $headers = array();
- public $body = null;
+ function __construct(HTTP_Request2_Response $response, $url, $redirects=0)
+ {
+ foreach (get_object_vars($response) as $key => $val) {
+ $this->$key = $val;
+ }
+ $this->url = strval($url);
+ $this->redirectCount = intval($redirects);
+ }
+
+ /**
+ * Get the count of redirects that have been followed, if any.
+ * @return int
+ */
+ function getRedirectCount()
+ {
+ return $this->redirectCount;
+ }
+
+ /**
+ * Gets the final target URL, after any redirects have been followed.
+ * @return string URL
+ */
+ function getUrl()
+ {
+ return $this->url;
+ }
+
+ /**
+ * Check if the response is OK, generally a 200 status code.
+ * @return bool
+ */
+ function isOk()
+ {
+ return ($this->getStatus() == 200);
+ }
}
/**
* ways of doing them. This class hides the specifics of what underlying
* library (curl or PHP-HTTP or whatever) that's used.
*
+ * This extends the PEAR HTTP_Request2 package:
+ * - sends StatusNet-specific User-Agent header
+ * - 'follow_redirects' config option, defaulting off
+ * - 'max_redirs' config option, defaulting to 10
+ * - extended response class adds getRedirectCount() and getUrl() methods
+ * - get() and post() convenience functions return body content directly
+ *
* @category HTTP
* @package StatusNet
* @author Evan Prodromou <evan@status.net>
+ * @author Brion Vibber <brion@status.net>
* @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
* @link http://status.net/
*/
-class HTTPClient
+class HTTPClient extends HTTP_Request2
{
- static $_client = null;
- static function start()
+ function __construct($url=null, $method=self::METHOD_GET, $config=array())
{
- if (!is_null(self::$_client)) {
- return self::$_client;
- }
-
- $type = common_config('http', 'client');
-
- switch ($type) {
- case 'curl':
- self::$_client = new CurlClient();
- break;
- default:
- throw new Exception("Unknown HTTP client type '$type'");
- break;
- }
-
- return self::$_client;
+ $this->config['max_redirs'] = 10;
+ $this->config['follow_redirects'] = true;
+ parent::__construct($url, $method, $config);
+ $this->setHeader('User-Agent', $this->userAgent());
}
- function head($url, $headers)
+ /**
+ * Convenience/back-compat instantiator
+ * @return HTTPClient
+ */
+ public static function start()
{
- throw new Exception("HEAD method unimplemented");
+ return new HTTPClient();
}
- function get($url, $headers)
+ /**
+ * Convenience function to run a GET request.
+ *
+ * @return HTTPResponse
+ * @throws HTTP_Request2_Exception
+ */
+ public function get($url, $headers=array())
{
- throw new Exception("GET method unimplemented");
+ return $this->doRequest($url, self::METHOD_GET, $headers);
}
- function post($url, $headers, $body)
+ /**
+ * Convenience function to run a HEAD request.
+ *
+ * @return HTTPResponse
+ * @throws HTTP_Request2_Exception
+ */
+ public function head($url, $headers=array())
{
- throw new Exception("POST method unimplemented");
+ return $this->doRequest($url, self::METHOD_HEAD, $headers);
}
- function put($url, $headers, $body)
+ /**
+ * Convenience function to POST form data.
+ *
+ * @param string $url
+ * @param array $headers optional associative array of HTTP headers
+ * @param array $data optional associative array or blob of form data to submit
+ * @return HTTPResponse
+ * @throws HTTP_Request2_Exception
+ */
+ public function post($url, $headers=array(), $data=array())
{
- throw new Exception("PUT method unimplemented");
+ if ($data) {
+ $this->addPostParameter($data);
+ }
+ return $this->doRequest($url, self::METHOD_POST, $headers);
}
- function delete($url, $headers)
+ /**
+ * @return HTTPResponse
+ * @throws HTTP_Request2_Exception
+ */
+ protected function doRequest($url, $method, $headers)
{
- throw new Exception("DELETE method unimplemented");
+ $this->setUrl($url);
+ $this->setMethod($method);
+ if ($headers) {
+ foreach ($headers as $header) {
+ $this->setHeader($header);
+ }
+ }
+ $response = $this->send();
+ return $response;
+ }
+
+ protected function log($level, $detail) {
+ $method = $this->getMethod();
+ $url = $this->getUrl();
+ common_log($level, __CLASS__ . ": HTTP $method $url - $detail");
}
+ /**
+ * Pulls up StatusNet's customized user-agent string, so services
+ * we hit can track down the responsible software.
+ *
+ * @return string
+ */
function userAgent()
{
return "StatusNet/".STATUSNET_VERSION." (".STATUSNET_CODENAME.")";
}
+
+ /**
+ * Actually performs the HTTP request and returns an HTTPResponse object
+ * with response body and header info.
+ *
+ * Wraps around parent send() to add logging and redirection processing.
+ *
+ * @return HTTPResponse
+ * @throw HTTP_Request2_Exception
+ */
+ public function send()
+ {
+ $maxRedirs = intval($this->config['max_redirs']);
+ if (empty($this->config['follow_redirects'])) {
+ $maxRedirs = 0;
+ }
+ $redirs = 0;
+ do {
+ try {
+ $response = parent::send();
+ } catch (HTTP_Request2_Exception $e) {
+ $this->log(LOG_ERR, $e->getMessage());
+ throw $e;
+ }
+ $code = $response->getStatus();
+ if ($code >= 200 && $code < 300) {
+ $reason = $response->getReasonPhrase();
+ $this->log(LOG_INFO, "$code $reason");
+ } elseif ($code >= 300 && $code < 400) {
+ $url = $this->getUrl();
+ $target = $response->getHeader('Location');
+
+ if (++$redirs >= $maxRedirs) {
+ common_log(LOG_ERR, __CLASS__ . ": Too many redirects: skipping $code redirect from $url to $target");
+ break;
+ }
+ try {
+ $this->setUrl($target);
+ $this->setHeader('Referer', $url);
+ common_log(LOG_INFO, __CLASS__ . ": Following $code redirect from $url to $target");
+ continue;
+ } catch (HTTP_Request2_Exception $e) {
+ common_log(LOG_ERR, __CLASS__ . ": Invalid $code redirect from $url to $target");
+ }
+ } else {
+ $reason = $response->getReasonPhrase();
+ $this->log(LOG_ERR, "$code $reason");
+ }
+ break;
+ } while ($maxRedirs);
+ return new HTTPResponse($response, $this->getUrl(), $redirs);
+ }
}
* @link http://status.net/
*
*/
-class OAuthClientCurlException extends Exception
+class OAuthClientException extends Exception
{
}
function getRequestToken($url)
{
$response = $this->oAuthGet($url);
- parse_str($response);
- $token = new OAuthToken($oauth_token, $oauth_token_secret);
- return $token;
+ $arr = array();
+ parse_str($response, $arr);
+ if (isset($arr['oauth_token']) && isset($arr['oauth_token_secret'])) {
+ $token = new OAuthToken($arr['oauth_token'], @$arr['oauth_token_secret']);
+ return $token;
+ } else {
+ throw new OAuthClientException();
+ }
}
/**
}
/**
- * Make a HTTP request using cURL.
+ * Make a HTTP request.
*
* @param string $url Where to make the
* @param array $params post parameters
*/
function httpRequest($url, $params = null)
{
- $options = array(
- CURLOPT_RETURNTRANSFER => true,
- CURLOPT_FAILONERROR => true,
- CURLOPT_HEADER => false,
- CURLOPT_FOLLOWLOCATION => true,
- CURLOPT_USERAGENT => 'StatusNet',
- CURLOPT_CONNECTTIMEOUT => 120,
- CURLOPT_TIMEOUT => 120,
- CURLOPT_HTTPAUTH => CURLAUTH_ANY,
- CURLOPT_SSL_VERIFYPEER => false,
-
- // Twitter is strict about accepting invalid "Expect" headers
-
- CURLOPT_HTTPHEADER => array('Expect:')
- );
+ $request = new HTTPClient($url);
+ $request->setConfig(array(
+ 'connect_timeout' => 120,
+ 'timeout' => 120,
+ 'follow_redirects' => true,
+ 'ssl_verify_peer' => false,
+ ));
+
+ // Twitter is strict about accepting invalid "Expect" headers
+ $request->setHeader('Expect', '');
if (isset($params)) {
- $options[CURLOPT_POST] = true;
- $options[CURLOPT_POSTFIELDS] = $params;
+ $request->setMethod(HTTP_Request2::METHOD_POST);
+ $request->setBody($params);
}
- $ch = curl_init($url);
- curl_setopt_array($ch, $options);
- $response = curl_exec($ch);
-
- if ($response === false) {
- $msg = curl_error($ch);
- $code = curl_errno($ch);
- throw new OAuthClientCurlException($msg, $code);
+ try {
+ $response = $request->send();
+ $code = $response->getStatus();
+ if ($code < 200 || $code >= 400) {
+ throw new OAuthClientException($response->getBody(), $code);
+ }
+ return $response->getBody();
+ } catch (Exception $e) {
+ throw new OAuthClientException($e->getMessage(), $e->getCode());
}
-
- curl_close($ch);
-
- return $response;
}
}
array('nickname' => $profile->nickname)),
$tags));
- $context = stream_context_create(array('http' => array('method' => "POST",
- 'header' =>
- "Content-Type: text/xml\r\n".
- "User-Agent: StatusNet/".STATUSNET_VERSION."\r\n",
- 'content' => $req)));
- $file = file_get_contents($notify_url, false, $context);
+ $request = HTTPClient::start();
+ $httpResponse = $request->post($notify_url, array('Content-Type: text/xml'), $req);
- if ($file === false || mb_strlen($file) == 0) {
+ if (!$httpResponse || mb_strlen($httpResponse->getBody()) == 0) {
common_log(LOG_WARNING,
"XML-RPC empty results for ping ($notify_url, $notice->id) ");
continue;
}
- $response = xmlrpc_decode($file);
+ $response = xmlrpc_decode($httpResponse->getBody());
if (is_array($response) && xmlrpc_is_fault($response)) {
common_log(LOG_WARNING,
{
// XXX: Use OICU2 and OAuth to make authorized requests
- $postdata = http_build_query($this->stats);
-
- $opts =
- array('http' =>
- array(
- 'method' => 'POST',
- 'header' => 'Content-type: '.
- 'application/x-www-form-urlencoded',
- 'content' => $postdata,
- 'user_agent' => 'StatusNet/'.STATUSNET_VERSION
- )
- );
-
- $context = stream_context_create($opts);
-
$reporturl = common_config('snapshot', 'reporturl');
-
- $result = @file_get_contents($reporturl, false, $context);
-
- return $result;
+ $request = HTTPClient::start();
+ $request->post($reporturl, null, $this->stats);
}
/**
* @category Plugin
* @package StatusNet
* @author Evan Prodromou <evan@status.net>
+ * @author Brion Vibber <brion@status.net>
* @copyright 2009 StatusNet, Inc.
* @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
* @link http://status.net/
{
$args = $this->testArgs($notice);
common_debug("Blogspamnet args = " . print_r($args, TRUE));
- $request = xmlrpc_encode_request('testComment', array($args));
- $context = stream_context_create(array('http' => array('method' => "POST",
- 'header' =>
- "Content-Type: text/xml\r\n".
- "User-Agent: " . $this->userAgent(),
- 'content' => $request)));
- $file = file_get_contents($this->baseUrl, false, $context);
- $response = xmlrpc_decode($file);
+ $requestBody = xmlrpc_encode_request('testComment', array($args));
+
+ $request = HTTPClient::start();
+ $httpResponse = $request->post($this->baseUrl, array('Content-Type: text/xml'), $requestBody);
+
+ $response = xmlrpc_decode($httpResponse->getBody());
if (xmlrpc_is_fault($response)) {
throw new ServerException("$response[faultString] ($response[faultCode])", 500);
} else {
$result = $client->get('http://ws.geonames.org/search?'.$str);
- if ($result->code == "200") {
- $rj = json_decode($result->body);
+ if ($result->isOk()) {
+ $rj = json_decode($result->getBody());
if (count($rj->geonames) > 0) {
$n = $rj->geonames[0];
$result = $client->get('http://ws.geonames.org/hierarchyJSON?'.$str);
- if ($result->code == "200") {
+ if ($result->isOk()) {
- $rj = json_decode($result->body);
+ $rj = json_decode($result->getBody());
if (count($rj->geonames) > 0) {
$result =
$client->get('http://ws.geonames.org/findNearbyPlaceNameJSON?'.$str);
- if ($result->code == "200") {
+ if ($result->isOk()) {
- $rj = json_decode($result->body);
+ $rj = json_decode($result->getBody());
if (count($rj->geonames) > 0) {
$result = $client->get('http://ws.geonames.org/hierarchyJSON?'.$str);
- if ($result->code == "200") {
+ if ($result->isOk()) {
- $rj = json_decode($result->body);
+ $rj = json_decode($result->getBody());
if (count($rj->geonames) > 0) {
$y = @simplexml_load_string($response);
if (!isset($y->body)) return $url;
$x = $y->body->p[0]->a->attributes();
- if (isset($x['href'])) return $x['href'];
+ if (isset($x['href'])) {
+ common_log(LOG_INFO, __CLASS__ . ": shortened $url to $x[href]");
+ return $x['href'];
+ }
return $url;
}
}
}
}
- $request = xmlrpc_encode_request('pingback.ping', $args);
- $context = stream_context_create(array('http' => array('method' => "POST",
- 'header' =>
- "Content-Type: text/xml\r\n".
- "User-Agent: " . $this->userAgent(),
- 'content' => $request)));
- $file = file_get_contents($endpoint, false, $context);
- if (!$file) {
- common_log(LOG_WARNING,
- "Pingback request failed for '$url' ($endpoint)");
- } else {
- $response = xmlrpc_decode($file);
+ $request = HTTPClient::start();
+ try {
+ $response = $request->post($endpoint,
+ array('Content-Type: text/xml'),
+ xmlrpc_encode_request('pingback.ping', $args));
+ $response = xmlrpc_decode($response->getBody());
if (xmlrpc_is_fault($response)) {
common_log(LOG_WARNING,
"Pingback error for '$url' ($endpoint): ".
"Pingback success for '$url' ($endpoint): ".
"'$response'");
}
+ } catch (HTTP_Request2_Exception $e) {
+ common_log(LOG_WARNING,
+ "Pingback request failed for '$url' ($endpoint)");
}
}
class SimpleUrl extends ShortUrlApi
{
protected function shorten_imp($url) {
- $curlh = curl_init();
- curl_setopt($curlh, CURLOPT_CONNECTTIMEOUT, 20); // # seconds to wait
- curl_setopt($curlh, CURLOPT_USERAGENT, 'StatusNet');
- curl_setopt($curlh, CURLOPT_RETURNTRANSFER, true);
-
- curl_setopt($curlh, CURLOPT_URL, $this->service_url.urlencode($url));
- $short_url = curl_exec($curlh);
-
- curl_close($curlh);
- return $short_url;
+ return $this->http_get($url);
}
}
$friends_ids = $client->friendsIds();
} catch (Exception $e) {
common_log(LOG_WARNING, $this->name() .
- ' - cURL error getting friend ids ' .
- $e->getCode() . ' - ' . $e->getMessage());
+ ' - error getting friend ids: ' .
+ $e->getMessage());
return $friends;
}
$flink->find();
$flinks = array();
+ common_log(LOG_INFO, "hello");
while ($flink->fetch()) {
if (($flink->noticesync & FOREIGN_NOTICE_RECV) ==
FOREIGN_NOTICE_RECV) {
$flinks[] = clone($flink);
+ common_log(LOG_INFO, "sync: foreign id $flink->foreign_id");
+ } else {
+ common_log(LOG_INFO, "nothing to sync");
}
}
return $id;
}
+ /**
+ * Fetch a remote avatar image and save to local storage.
+ *
+ * @param string $url avatar source URL
+ * @param string $filename bare local filename for download
+ * @return bool true on success, false on failure
+ */
function fetchAvatar($url, $filename)
{
- $avatarfile = Avatar::path($filename);
+ common_debug($this->name() . " - Fetching Twitter avatar: $url");
- $out = fopen($avatarfile, 'wb');
- if (!$out) {
- common_log(LOG_WARNING, $this->name() .
- " - Couldn't open file $filename");
+ $request = HTTPClient::start();
+ $response = $request->get($url);
+ if ($response->isOk()) {
+ $avatarfile = Avatar::path($filename);
+ $ok = file_put_contents($avatarfile, $response->getBody());
+ if (!$ok) {
+ common_log(LOG_WARNING, $this->name() .
+ " - Couldn't open file $filename");
+ return false;
+ }
+ } else {
return false;
}
- common_debug($this->name() . " - Fetching Twitter avatar: $url");
-
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_URL, $url);
- curl_setopt($ch, CURLOPT_FILE, $out);
- curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
- curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
- curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0);
- $result = curl_exec($ch);
- curl_close($ch);
-
- fclose($out);
-
- return $result;
+ return true;
}
}
try {
$status = $client->statusesUpdate($statustxt);
- } catch (BasicAuthCurlException $e) {
+ } catch (HTTP_Request2_Exception $e) {
return process_error($e, $flink);
}
$auth_link = $client->getAuthorizeLink($req_tok);
- } catch (TwitterOAuthClientException $e) {
+ } catch (OAuthClientException $e) {
$msg = sprintf('OAuth client cURL error - code: %1s, msg: %2s',
$e->getCode(), $e->getMessage());
$this->serverError(_('Couldn\'t link your Twitter account.'));
exit(1);
}
-/**
- * Exception wrapper for cURL errors
- *
- * @category Integration
- * @package StatusNet
- * @author Adrian Lang <mail@adrianlang.de>
- * @author Brenda Wallace <shiny@cpan.org>
- * @author Craig Andrews <candrews@integralblue.com>
- * @author Dan Moore <dan@moore.cx>
- * @author Evan Prodromou <evan@status.net>
- * @author mEDI <medi@milaro.net>
- * @author Sarven Capadisli <csarven@status.net>
- * @author Zach Copley <zach@status.net> * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
- * @link http://status.net/
- *
- */
-class BasicAuthCurlException extends Exception
-{
-}
-
/**
* Class for talking to the Twitter API with HTTP Basic Auth.
*
*/
function httpRequest($url, $params = null, $auth = true)
{
- $options = array(
- CURLOPT_RETURNTRANSFER => true,
- CURLOPT_FAILONERROR => true,
- CURLOPT_HEADER => false,
- CURLOPT_FOLLOWLOCATION => true,
- CURLOPT_USERAGENT => 'StatusNet',
- CURLOPT_CONNECTTIMEOUT => 120,
- CURLOPT_TIMEOUT => 120,
- CURLOPT_HTTPAUTH => CURLAUTH_ANY,
- CURLOPT_SSL_VERIFYPEER => false,
-
- // Twitter is strict about accepting invalid "Expect" headers
-
- CURLOPT_HTTPHEADER => array('Expect:')
- );
-
- if (isset($params)) {
- $options[CURLOPT_POST] = true;
- $options[CURLOPT_POSTFIELDS] = $params;
- }
+ $request = HTTPClient::start();
+ $request->setConfig(array(
+ 'follow_redirects' => true,
+ 'connect_timeout' => 120,
+ 'timeout' => 120,
+ 'ssl_verifypeer' => false,
+ ));
if ($auth) {
- $options[CURLOPT_USERPWD] = $this->screen_name .
- ':' . $this->password;
+ $request->setAuth($this->screen_name, $this->password);
}
- $ch = curl_init($url);
- curl_setopt_array($ch, $options);
- $response = curl_exec($ch);
-
- if ($response === false) {
- $msg = curl_error($ch);
- $code = curl_errno($ch);
- throw new BasicAuthCurlException($msg, $code);
+ if (isset($params)) {
+ // Twitter is strict about accepting invalid "Expect" headers
+ $headers = array('Expect:');
+ $response = $request->post($url, $headers, $params);
+ } else {
+ $response = $request->get($url);
}
- curl_close($ch);
-
- return $response;
+ return $response->getBody();
}
}
$editurl = sprintf('http://hashtags.wikia.com/index.php?title=%s&action=edit',
urlencode($tag));
- $context = stream_context_create(array('http' => array('method' => "GET",
- 'header' =>
- "User-Agent: " . $this->userAgent())));
- $html = @file_get_contents($url, false, $context);
+ $request = HTTPClient::start();
+ $response = $request->get($url);
+ $html = $response->getBody();
$action->elementStart('div', array('id' => 'wikihashtags', 'class' => 'section'));
- if (!empty($html)) {
+ if ($response->isOk() && !empty($html)) {
$action->element('style', null,
"span.editsection { display: none }\n".
"table.toc { display: none }");
return true;
}
-
- function userAgent()
- {
- return 'WikiHashtagsPlugin/'.WIKIHASHTAGSPLUGIN_VERSION .
- ' StatusNet/' . STATUSNET_VERSION;
- }
}
function start()
{
- $this->log(LOG_INFO, "Starting EnjitQueueHandler");
- $this->log(LOG_INFO, "Broadcasting to ".common_config('enjit', 'apiurl'));
+ $this->log(LOG_INFO, "Starting EnjitQueueHandler");
+ $this->log(LOG_INFO, "Broadcasting to ".common_config('enjit', 'apiurl'));
return true;
}
$profile = Profile::staticGet($notice->profile_id);
- $this->log(LOG_INFO, "Posting Notice ".$notice->id." from ".$profile->nickname);
+ $this->log(LOG_INFO, "Posting Notice ".$notice->id." from ".$profile->nickname);
- if ( ! $notice->is_local ) {
- $this->log(LOG_INFO, "Skipping remote notice");
- return "skipped";
- }
+ if ( ! $notice->is_local ) {
+ $this->log(LOG_INFO, "Skipping remote notice");
+ return "skipped";
+ }
- #
- # Build an Atom message from the notice
- #
+ #
+ # Build an Atom message from the notice
+ #
$noticeurl = common_local_url('shownotice', array('notice' => $notice->id));
$msg = $profile->nickname . ': ' . $notice->content;
$atom .= "<updated>".common_date_w3dtf($notice->modified)."</updated>\n";
$atom .= "</entry>\n";
- $url = common_config('enjit', 'apiurl') . "/submit/". common_config('enjit','apikey');
- $data = "msg=$atom";
+ $url = common_config('enjit', 'apiurl') . "/submit/". common_config('enjit','apikey');
+ $data = array(
+ 'msg' => $atom,
+ );
- #
- # POST the message to $config['enjit']['apiurl']
- #
- $ch = curl_init();
+ #
+ # POST the message to $config['enjit']['apiurl']
+ #
+ $request = HTTPClient::start();
+ $response = $request->post($url, null, $data);
- curl_setopt($ch, CURLOPT_URL, $url);
-
- curl_setopt($ch, CURLOPT_HEADER, 1);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
- curl_setopt($ch, CURLOPT_POST, 1) ;
- curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
-
- # SSL and Debugging options
- #
- # curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
- # curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
- # curl_setopt($ch, CURLOPT_VERBOSE, 1);
-
- $result = curl_exec($ch);
-
- $code = curl_getinfo($ch, CURLINFO_HTTP_CODE );
-
- $this->log(LOG_INFO, "Response Code: $code");
-
- curl_close($ch);
-
- return $code;
+ return $response->isOk();
}
}