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