3 * StatusNet, the distributed open-source microblogging tool
5 * Utility for doing HTTP-related things
9 * LICENCE: This program is free software: you can redistribute it and/or modify
10 * it under the terms of the GNU Affero General Public License as published by
11 * the Free Software Foundation, either version 3 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU Affero General Public License for more details.
19 * You should have received a copy of the GNU Affero General Public License
20 * along with this program. If not, see <http://www.gnu.org/licenses/>.
24 * @author Evan Prodromou <evan@status.net>
25 * @copyright 2009 StatusNet, Inc.
26 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
27 * @link http://status.net/
30 if (!defined('STATUSNET')) {
34 require_once 'HTTP/Request2.php';
35 require_once 'HTTP/Request2/Response.php';
38 * Useful structure for HTTP responses
40 * We make HTTP calls in several places, and we have several different
41 * ways of doing them. This class hides the specifics of what underlying
42 * library (curl or PHP-HTTP or whatever) that's used.
44 * This extends the HTTP_Request2_Response class with methods to get info
45 * about any followed redirects.
47 * Originally used the name 'HTTPResponse' to match earlier code, but
48 * this conflicts with a class in in the PECL HTTP extension.
52 * @author Evan Prodromou <evan@status.net>
53 * @author Brion Vibber <brion@status.net>
54 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
55 * @link http://status.net/
57 class StatusNet_HTTPResponse extends HTTP_Request2_Response
59 function __construct(HTTP_Request2_Response $response, $url, $redirects=0)
61 foreach (get_object_vars($response) as $key => $val) {
64 $this->url = strval($url);
65 $this->redirectCount = intval($redirects);
69 * Get the count of redirects that have been followed, if any.
72 function getRedirectCount()
74 return $this->redirectCount;
78 * Gets the final target URL, after any redirects have been followed.
87 * Check if the response is OK, generally a 200 or other 2xx status code.
92 $status = $this->getStatus();
93 return ($status >= 200 && $status < 300);
98 * Utility class for doing HTTP client stuff
100 * We make HTTP calls in several places, and we have several different
101 * ways of doing them. This class hides the specifics of what underlying
102 * library (curl or PHP-HTTP or whatever) that's used.
104 * This extends the PEAR HTTP_Request2 package:
105 * - sends StatusNet-specific User-Agent header
106 * - 'follow_redirects' config option, defaulting off
107 * - 'max_redirs' config option, defaulting to 10
108 * - extended response class adds getRedirectCount() and getUrl() methods
109 * - get() and post() convenience functions return body content directly
113 * @author Evan Prodromou <evan@status.net>
114 * @author Brion Vibber <brion@status.net>
115 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
116 * @link http://status.net/
119 class HTTPClient extends HTTP_Request2
122 function __construct($url=null, $method=self::METHOD_GET, $config=array())
124 $this->config['max_redirs'] = 10;
125 $this->config['follow_redirects'] = true;
127 // We've had some issues with keepalive breaking with
128 // HEAD requests, such as to youtube which seems to be
129 // emitting chunked encoding info for an empty body
130 // instead of not emitting anything. This may be a
131 // bug on YouTube's end, but the upstream libray
132 // ought to be investigated to see if we can handle
133 // it gracefully in that case as well.
134 $this->config['protocol_version'] = '1.0';
136 parent::__construct($url, $method, $config);
137 $this->setHeader('User-Agent', $this->userAgent());
141 * Convenience/back-compat instantiator
144 public static function start()
146 return new HTTPClient();
150 * Convenience function to run a GET request.
152 * @return StatusNet_HTTPResponse
153 * @throws HTTP_Request2_Exception
155 public function get($url, $headers=array())
157 return $this->doRequest($url, self::METHOD_GET, $headers);
161 * Convenience function to run a HEAD request.
163 * @return StatusNet_HTTPResponse
164 * @throws HTTP_Request2_Exception
166 public function head($url, $headers=array())
168 return $this->doRequest($url, self::METHOD_HEAD, $headers);
172 * Convenience function to POST form data.
175 * @param array $headers optional associative array of HTTP headers
176 * @param array $data optional associative array or blob of form data to submit
177 * @return StatusNet_HTTPResponse
178 * @throws HTTP_Request2_Exception
180 public function post($url, $headers=array(), $data=array())
183 $this->addPostParameter($data);
185 return $this->doRequest($url, self::METHOD_POST, $headers);
189 * @return StatusNet_HTTPResponse
190 * @throws HTTP_Request2_Exception
192 protected function doRequest($url, $method, $headers)
195 $this->setMethod($method);
197 foreach ($headers as $header) {
198 $this->setHeader($header);
201 $response = $this->send();
205 protected function log($level, $detail) {
206 $method = $this->getMethod();
207 $url = $this->getUrl();
208 common_log($level, __CLASS__ . ": HTTP $method $url - $detail");
212 * Pulls up StatusNet's customized user-agent string, so services
213 * we hit can track down the responsible software.
219 return "StatusNet/".STATUSNET_VERSION." (".STATUSNET_CODENAME.")";
223 * Actually performs the HTTP request and returns a
224 * StatusNet_HTTPResponse object with response body and header info.
226 * Wraps around parent send() to add logging and redirection processing.
228 * @return StatusNet_HTTPResponse
229 * @throw HTTP_Request2_Exception
231 public function send()
233 $maxRedirs = intval($this->config['max_redirs']);
234 if (empty($this->config['follow_redirects'])) {
240 $response = parent::send();
241 } catch (HTTP_Request2_Exception $e) {
242 $this->log(LOG_ERR, $e->getMessage());
245 $code = $response->getStatus();
246 if ($code >= 200 && $code < 300) {
247 $reason = $response->getReasonPhrase();
248 $this->log(LOG_INFO, "$code $reason");
249 } elseif ($code >= 300 && $code < 400) {
250 $url = $this->getUrl();
251 $target = $response->getHeader('Location');
253 if (++$redirs >= $maxRedirs) {
254 common_log(LOG_ERR, __CLASS__ . ": Too many redirects: skipping $code redirect from $url to $target");
258 $this->setUrl($target);
259 $this->setHeader('Referer', $url);
260 common_log(LOG_INFO, __CLASS__ . ": Following $code redirect from $url to $target");
262 } catch (HTTP_Request2_Exception $e) {
263 common_log(LOG_ERR, __CLASS__ . ": Invalid $code redirect from $url to $target");
266 $reason = $response->getReasonPhrase();
267 $this->log(LOG_ERR, "$code $reason");
270 } while ($maxRedirs);
271 return new StatusNet_HTTPResponse($response, $this->getUrl(), $redirs);