]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/httpclient.php
Rebuilt HTTPClient class as an extension of PEAR HTTP_Request2 package, adding redire...
[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         return $this->redirectCount;
71     }
72
73     /**
74      * Gets the final target URL, after any redirects have been followed.
75      * @return string URL
76      */
77     function getUrl() {
78         return $this->url;
79     }
80 }
81
82 /**
83  * Utility class for doing HTTP client stuff
84  *
85  * We make HTTP calls in several places, and we have several different
86  * ways of doing them. This class hides the specifics of what underlying
87  * library (curl or PHP-HTTP or whatever) that's used.
88  *
89  * This extends the PEAR HTTP_Request2 package:
90  * - sends StatusNet-specific User-Agent header
91  * - 'follow_redirects' config option, defaulting off
92  * - 'max_redirs' config option, defaulting to 10
93  * - extended response class adds getRedirectCount() and getUrl() methods
94  * - get() and post() convenience functions return body content directly
95  *
96  * @category HTTP
97  * @package  StatusNet
98  * @author   Evan Prodromou <evan@status.net>
99  * @author   Brion Vibber <brion@status.net>
100  * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
101  * @link     http://status.net/
102  */
103
104 class HTTPClient extends HTTP_Request2
105 {
106
107     function __construct($url=null, $method=self::METHOD_GET, $config=array())
108     {
109         $this->config['max_redirs'] = 10;
110         $this->config['follow_redirects'] = false;
111         parent::__construct($url, $method, $config);
112         $this->setHeader('User-Agent', $this->userAgent());
113     }
114
115     /**
116      * Convenience function to run a get request and return the response body.
117      * Use when you don't need to get into details of the response.
118      *
119      * @return mixed string on success, false on failure
120      */
121     function get()
122     {
123         $this->setMethod(self::METHOD_GET);
124         return $this->doRequest();
125     }
126
127     /**
128      * Convenience function to post form data and return the response body.
129      * Use when you don't need to get into details of the response.
130      *
131      * @param array associative array of form data to submit
132      * @return mixed string on success, false on failure
133      */
134     public function post($data=array())
135     {
136         $this->setMethod(self::METHOD_POST);
137         if ($data) {
138             $this->addPostParameter($data);
139         }
140         return $this->doRequest();
141     }
142
143     /**
144      * @return mixed string on success, false on failure
145      */
146     protected function doRequest()
147     {
148         try {
149             $response = $this->send();
150             $code = $response->getStatus();
151             if (($code < 200) || ($code >= 400)) {
152                 return false;
153             }
154             return $response->getBody();
155         } catch (HTTP_Request2_Exception $e) {
156             $this->log(LOG_ERR, $e->getMessage());
157             return false;
158         }
159     }
160     
161     protected function log($level, $detail) {
162         $method = $this->getMethod();
163         $url = $this->getUrl();
164         common_log($level, __CLASS__ . ": HTTP $method $url - $detail");
165     }
166
167     /**
168      * Pulls up StatusNet's customized user-agent string, so services
169      * we hit can track down the responsible software.
170      */
171     function userAgent()
172     {
173         return "StatusNet/".STATUSNET_VERSION." (".STATUSNET_CODENAME.")";
174     }
175
176     function send()
177     {
178         $maxRedirs = intval($this->config['max_redirs']);
179         if (empty($this->config['follow_redirects'])) {
180             $maxRedirs = 0;
181         }
182         $redirs = 0;
183         do {
184             try {
185                 $response = parent::send();
186             } catch (HTTP_Request2_Exception $e) {
187                 $this->log(LOG_ERR, $e->getMessage());
188                 throw $e;
189             }
190             $code = $response->getStatus();
191             if ($code >= 200 && $code < 300) {
192                 $reason = $response->getReasonPhrase();
193                 $this->log(LOG_INFO, "$code $reason");
194             } elseif ($code >= 300 && $code < 400) {
195                 $url = $this->getUrl();
196                 $target = $response->getHeader('Location');
197                 
198                 if (++$redirs >= $maxRedirs) {
199                     common_log(LOG_ERR, __CLASS__ . ": Too many redirects: skipping $code redirect from $url to $target");
200                     break;
201                 }
202                 try {
203                     $this->setUrl($target);
204                     $this->setHeader('Referer', $url);
205                     common_log(LOG_INFO, __CLASS__ . ": Following $code redirect from $url to $target");
206                     continue;
207                 } catch (HTTP_Request2_Exception $e) {
208                     common_log(LOG_ERR, __CLASS__ . ": Invalid $code redirect from $url to $target");
209                 }
210             } else {
211                 $reason = $response->getReasonPhrase();
212                 $this->log(LOG_ERR, "$code $reason");
213             }
214             break;
215         } while ($maxRedirs);
216         return new HTTPResponse($response, $this->getUrl(), $redirs);
217     }
218 }