]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/httpclient.php
Merge remote-tracking branch 'upstream/master' into social-master
[quix0rs-gnu-social.git] / lib / httpclient.php
1 <?php
2 /**
3  * StatusNet, the distributed open-source microblogging tool
4  *
5  * Utility for doing HTTP-related things
6  *
7  * PHP version 5
8  *
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.
13  *
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.
18  *
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/>.
21  *
22  * @category  Action
23  * @package   StatusNet
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/
28  */
29
30 if (!defined('GNUSOCIAL')) {
31     exit(1);
32 }
33
34 require_once 'HTTP/Request2.php';
35 require_once 'HTTP/Request2/Response.php';
36
37 /**
38  * Useful structure for HTTP responses
39  *
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.
43  *
44  * This extends the HTTP_Request2_Response class with methods to get info
45  * about any followed redirects.
46  * 
47  * Originally used the name 'HTTPResponse' to match earlier code, but
48  * this conflicts with a class in in the PECL HTTP extension.
49  *
50  * @category HTTP
51  * @package StatusNet
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/
56  */
57 class GNUsocial_HTTPResponse extends HTTP_Request2_Response
58 {
59     function __construct(HTTP_Request2_Response $response, $url, $redirects=0)
60     {
61         foreach (get_object_vars($response) as $key => $val) {
62             $this->$key = $val;
63         }
64         $this->url = strval($url);
65         $this->redirectCount = intval($redirects);
66     }
67
68     /**
69      * Get the count of redirects that have been followed, if any.
70      * @return int
71      */
72     function getRedirectCount()
73     {
74         return $this->redirectCount;
75     }
76
77     /**
78      * Gets the final target URL, after any redirects have been followed.
79      * @return string URL
80      */
81     function getUrl()
82     {
83         return $this->effectiveUrl;
84     }
85
86     /**
87      * Check if the response is OK, generally a 200 or other 2xx status code.
88      * @return bool
89      */
90     function isOk()
91     {
92         $status = $this->getStatus();
93         return ($status >= 200 && $status < 300);
94     }
95 }
96
97 /**
98  * Utility class for doing HTTP client stuff
99  *
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.
103  *
104  * This extends the PEAR HTTP_Request2 package:
105  * - sends StatusNet-specific User-Agent header
106  * - 'follow_redirects' config option, defaulting on
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
110  *
111  * @category HTTP
112  * @package  StatusNet
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/
117  */
118
119 class HTTPClient extends HTTP_Request2
120 {
121
122     function __construct($url=null, $method=self::METHOD_GET, $config=array())
123     {
124         $this->config['connect_timeout'] = common_config('http', 'connect_timeout') ?: $this->config['connect_timeout'];
125         $this->config['max_redirs'] = 10;
126         $this->config['follow_redirects'] = true;
127         
128         // We've had some issues with keepalive breaking with
129         // HEAD requests, such as to youtube which seems to be
130         // emitting chunked encoding info for an empty body
131         // instead of not emitting anything. This may be a
132         // bug on YouTube's end, but the upstream libray
133         // ought to be investigated to see if we can handle
134         // it gracefully in that case as well.
135         $this->config['protocol_version'] = '1.0';
136
137         // Default state of OpenSSL seems to have no trusted
138         // SSL certificate authorities, which breaks hostname
139         // verification and means we have a hard time communicating
140         // with other sites' HTTPS interfaces.
141         //
142         // Turn off verification unless we've configured a CA bundle.
143         if (common_config('http', 'ssl_cafile')) {
144             $this->config['ssl_cafile'] = common_config('http', 'ssl_cafile');
145         } else {
146             $this->config['ssl_verify_peer'] = false;
147         }
148
149         // This means "verify the cert hostname against what we connect to", it does not
150         // imply CA trust or anything like that. Just the hostname.
151         $this->config['ssl_verify_host'] = common_config('http', 'ssl_verify_host');
152
153         if (common_config('http', 'curl') && extension_loaded('curl')) {
154             $this->config['adapter'] = 'HTTP_Request2_Adapter_Curl';
155         }
156
157         foreach (array('host', 'port', 'user', 'password', 'auth_scheme') as $cf) {
158             $k = 'proxy_'.$cf;
159             $v = common_config('http', $k); 
160             if (!empty($v)) {
161                 $this->config[$k] = $v;
162             }
163         }
164
165         parent::__construct($url, $method, $config);
166         $this->setHeader('User-Agent', self::userAgent());
167     }
168
169     /**
170      * Convenience/back-compat instantiator
171      * @return HTTPClient
172      */
173     public static function start()
174     {
175         return new HTTPClient();
176     }
177
178     /**
179      * Quick static function to GET a URL
180      */
181     public static function quickGet($url, $accept=null, $params=array())
182     {
183         if (!empty($params)) {
184             $params = http_build_query($params, null, '&');
185             if (strpos($url, '?') === false) {
186                 $url .= '?' . $params;
187             } else {
188                 $url .= '&' . $params;
189             }
190         }
191
192         $client = new HTTPClient();
193         if (!is_null($accept)) {
194             $client->setHeader('Accept', $accept);
195         }
196         $response = $client->get($url);
197         if (!$response->isOk()) {
198             // TRANS: Exception. %s is a profile URL.
199             throw new Exception(sprintf(_m('Could not GET URL %s.'), $url), $response->getStatus());
200         }
201         return $response->getBody();
202     }
203
204     public static function quickGetJson($url, $params=array())
205     {
206         $data = json_decode(self::quickGet($url, null, $params));
207         if (is_null($data)) {
208             common_debug('Could not decode JSON data from URL: '.$url);
209             throw new ServerException('Could not decode JSON data from URL');
210         }
211         return $data;
212     }
213
214     /**
215      * Convenience function to run a GET request.
216      *
217      * @return GNUsocial_HTTPResponse
218      * @throws HTTP_Request2_Exception
219      */
220     public function get($url, $headers=array())
221     {
222         return $this->doRequest($url, self::METHOD_GET, $headers);
223     }
224
225     /**
226      * Convenience function to run a HEAD request.
227      *
228      * NOTE: Will probably turn into a GET request if you let it follow redirects!
229      *       That option is only there to be flexible and may be removed in the future!
230      *
231      * @return GNUsocial_HTTPResponse
232      * @throws HTTP_Request2_Exception
233      */
234     public function head($url, $headers=array(), $follow_redirects=false)
235     {
236         // Save the configured value for follow_redirects
237         $old_follow = $this->config['follow_redirects'];
238         try {
239             // Temporarily (possibly) override the follow_redirects setting
240             $this->config['follow_redirects'] = $follow_redirects;
241             return $this->doRequest($url, self::METHOD_HEAD, $headers);
242         } catch (Exception $e) {
243             // reset to the old value
244             $this->config['follow_redirects'] = $old_follow;
245
246             // Let the exception go on its merry way.
247             throw $e;
248         }
249         //we've either returned or thrown exception here
250
251         // reset to the old value
252         $this->config['follow_redirects'] = $old_follow;
253     }
254
255     /**
256      * Convenience function to POST form data.
257      *
258      * @param string $url
259      * @param array $headers optional associative array of HTTP headers
260      * @param array $data optional associative array or blob of form data to submit
261      * @return GNUsocial_HTTPResponse
262      * @throws HTTP_Request2_Exception
263      */
264     public function post($url, $headers=array(), $data=array())
265     {
266         if ($data) {
267             $this->addPostParameter($data);
268         }
269         return $this->doRequest($url, self::METHOD_POST, $headers);
270     }
271
272     /**
273      * @return GNUsocial_HTTPResponse
274      * @throws HTTP_Request2_Exception
275      */
276     protected function doRequest($url, $method, $headers)
277     {
278         $this->setUrl($url);
279
280         // Workaround for HTTP_Request2 not setting up SNI in socket contexts;
281         // This fixes cert validation for SSL virtual hosts using SNI.
282         // Requires PHP 5.3.2 or later and OpenSSL with SNI support.
283         if ($this->url->getScheme() == 'https' && defined('OPENSSL_TLSEXT_SERVER_NAME')) {
284             $this->config['ssl_SNI_enabled'] = true;
285             $this->config['ssl_SNI_server_name'] = $this->url->getHost();
286         }
287
288         $this->setMethod($method);
289         if ($headers) {
290             foreach ($headers as $header) {
291                 $this->setHeader($header);
292             }
293         }
294         $response = $this->send();
295         return $response;
296     }
297     
298     protected function log($level, $detail) {
299         $method = $this->getMethod();
300         $url = $this->getUrl();
301         common_log($level, __CLASS__ . ": HTTP $method $url - $detail");
302     }
303
304     /**
305      * Pulls up GNU Social's customized user-agent string, so services
306      * we hit can track down the responsible software.
307      *
308      * @return string
309      */
310     static public function userAgent()
311     {
312         return GNUSOCIAL_ENGINE . '/' . GNUSOCIAL_VERSION
313                 . ' (' . GNUSOCIAL_CODENAME . ')';
314     }
315
316     /**
317      * Actually performs the HTTP request and returns a
318      * GNUsocial_HTTPResponse object with response body and header info.
319      *
320      * Wraps around parent send() to add logging and redirection processing.
321      *
322      * @return GNUsocial_HTTPResponse
323      * @throw HTTP_Request2_Exception
324      */
325     public function send()
326     {
327         $maxRedirs = intval($this->config['max_redirs']);
328         if (empty($this->config['follow_redirects'])) {
329             $maxRedirs = 0;
330         }
331         $redirs = 0;
332         do {
333             try {
334                 $response = parent::send();
335             } catch (HTTP_Request2_Exception $e) {
336                 $this->log(LOG_ERR, $e->getMessage());
337                 throw $e;
338             }
339             $code = $response->getStatus();
340             if ($code >= 200 && $code < 300) {
341                 $reason = $response->getReasonPhrase();
342                 $this->log(LOG_INFO, "$code $reason");
343             } elseif ($code >= 300 && $code < 400) {
344                 $url = $this->getUrl();
345                 $target = $response->getHeader('Location');
346                 
347                 if (++$redirs >= $maxRedirs) {
348                     common_log(LOG_ERR, __CLASS__ . ": Too many redirects: skipping $code redirect from $url to $target");
349                     break;
350                 }
351                 try {
352                     $this->setUrl($target);
353                     $this->setHeader('Referer', $url);
354                     common_log(LOG_INFO, __CLASS__ . ": Following $code redirect from $url to $target");
355                     continue;
356                 } catch (HTTP_Request2_Exception $e) {
357                     common_log(LOG_ERR, __CLASS__ . ": Invalid $code redirect from $url to $target");
358                 }
359             } else {
360                 $reason = $response->getReasonPhrase();
361                 $this->log(LOG_ERR, "$code $reason");
362             }
363             break;
364         } while ($maxRedirs);
365         return new GNUsocial_HTTPResponse($response, $this->getUrl(), $redirs);
366     }
367 }