]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/httpclient.php
Merge branch 'master' of git@gitorious.org:statusnet/mainline into testing
[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('STATUSNET')) {
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  * @category HTTP
48  * @package StatusNet
49  * @author Evan Prodromou <evan@status.net>
50  * @author Brion Vibber <brion@status.net>
51  * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
52  * @link http://status.net/
53  */
54 class HTTPResponse extends HTTP_Request2_Response
55 {
56     function __construct(HTTP_Request2_Response $response, $url, $redirects=0)
57     {
58         foreach (get_object_vars($response) as $key => $val) {
59             $this->$key = $val;
60         }
61         $this->url = strval($url);
62         $this->redirectCount = intval($redirects);
63     }
64
65     /**
66      * Get the count of redirects that have been followed, if any.
67      * @return int
68      */
69     function getRedirectCount()
70     {
71         return $this->redirectCount;
72     }
73
74     /**
75      * Gets the final target URL, after any redirects have been followed.
76      * @return string URL
77      */
78     function getUrl()
79     {
80         return $this->url;
81     }
82
83     /**
84      * Check if the response is OK, generally a 200 or other 2xx status code.
85      * @return bool
86      */
87     function isOk()
88     {
89         $status = $this->getStatus();
90         return ($status >= 200 && $status < 300);
91     }
92 }
93
94 /**
95  * Utility class for doing HTTP client stuff
96  *
97  * We make HTTP calls in several places, and we have several different
98  * ways of doing them. This class hides the specifics of what underlying
99  * library (curl or PHP-HTTP or whatever) that's used.
100  *
101  * This extends the PEAR HTTP_Request2 package:
102  * - sends StatusNet-specific User-Agent header
103  * - 'follow_redirects' config option, defaulting off
104  * - 'max_redirs' config option, defaulting to 10
105  * - extended response class adds getRedirectCount() and getUrl() methods
106  * - get() and post() convenience functions return body content directly
107  *
108  * @category HTTP
109  * @package  StatusNet
110  * @author   Evan Prodromou <evan@status.net>
111  * @author   Brion Vibber <brion@status.net>
112  * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
113  * @link     http://status.net/
114  */
115
116 class HTTPClient extends HTTP_Request2
117 {
118
119     function __construct($url=null, $method=self::METHOD_GET, $config=array())
120     {
121         $this->config['max_redirs'] = 10;
122         $this->config['follow_redirects'] = true;
123         parent::__construct($url, $method, $config);
124         $this->setHeader('User-Agent', $this->userAgent());
125     }
126
127     /**
128      * Convenience/back-compat instantiator
129      * @return HTTPClient
130      */
131     public static function start()
132     {
133         return new HTTPClient();
134     }
135
136     /**
137      * Convenience function to run a GET request.
138      *
139      * @return HTTPResponse
140      * @throws HTTP_Request2_Exception
141      */
142     public function get($url, $headers=array())
143     {
144         return $this->doRequest($url, self::METHOD_GET, $headers);
145     }
146
147     /**
148      * Convenience function to run a HEAD request.
149      *
150      * @return HTTPResponse
151      * @throws HTTP_Request2_Exception
152      */
153     public function head($url, $headers=array())
154     {
155         return $this->doRequest($url, self::METHOD_HEAD, $headers);
156     }
157
158     /**
159      * Convenience function to POST form data.
160      *
161      * @param string $url
162      * @param array $headers optional associative array of HTTP headers
163      * @param array $data optional associative array or blob of form data to submit
164      * @return HTTPResponse
165      * @throws HTTP_Request2_Exception
166      */
167     public function post($url, $headers=array(), $data=array())
168     {
169         if ($data) {
170             $this->addPostParameter($data);
171         }
172         return $this->doRequest($url, self::METHOD_POST, $headers);
173     }
174
175     /**
176      * @return HTTPResponse
177      * @throws HTTP_Request2_Exception
178      */
179     protected function doRequest($url, $method, $headers)
180     {
181         $this->setUrl($url);
182         $this->setMethod($method);
183         if ($headers) {
184             foreach ($headers as $header) {
185                 $this->setHeader($header);
186             }
187         }
188         $response = $this->send();
189         return $response;
190     }
191     
192     protected function log($level, $detail) {
193         $method = $this->getMethod();
194         $url = $this->getUrl();
195         common_log($level, __CLASS__ . ": HTTP $method $url - $detail");
196     }
197
198     /**
199      * Pulls up StatusNet's customized user-agent string, so services
200      * we hit can track down the responsible software.
201      *
202      * @return string
203      */
204     function userAgent()
205     {
206         return "StatusNet/".STATUSNET_VERSION." (".STATUSNET_CODENAME.")";
207     }
208
209     /**
210      * Actually performs the HTTP request and returns an HTTPResponse object
211      * with response body and header info.
212      *
213      * Wraps around parent send() to add logging and redirection processing.
214      *
215      * @return HTTPResponse
216      * @throw HTTP_Request2_Exception
217      */
218     public function send()
219     {
220         $maxRedirs = intval($this->config['max_redirs']);
221         if (empty($this->config['follow_redirects'])) {
222             $maxRedirs = 0;
223         }
224         $redirs = 0;
225         do {
226             try {
227                 $response = parent::send();
228             } catch (HTTP_Request2_Exception $e) {
229                 $this->log(LOG_ERR, $e->getMessage());
230                 throw $e;
231             }
232             $code = $response->getStatus();
233             if ($code >= 200 && $code < 300) {
234                 $reason = $response->getReasonPhrase();
235                 $this->log(LOG_INFO, "$code $reason");
236             } elseif ($code >= 300 && $code < 400) {
237                 $url = $this->getUrl();
238                 $target = $response->getHeader('Location');
239                 
240                 if (++$redirs >= $maxRedirs) {
241                     common_log(LOG_ERR, __CLASS__ . ": Too many redirects: skipping $code redirect from $url to $target");
242                     break;
243                 }
244                 try {
245                     $this->setUrl($target);
246                     $this->setHeader('Referer', $url);
247                     common_log(LOG_INFO, __CLASS__ . ": Following $code redirect from $url to $target");
248                     continue;
249                 } catch (HTTP_Request2_Exception $e) {
250                     common_log(LOG_ERR, __CLASS__ . ": Invalid $code redirect from $url to $target");
251                 }
252             } else {
253                 $reason = $response->getReasonPhrase();
254                 $this->log(LOG_ERR, "$code $reason");
255             }
256             break;
257         } while ($maxRedirs);
258         return new HTTPResponse($response, $this->getUrl(), $redirs);
259     }
260 }