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