]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/HttpClient.php
Whitespace only
[SourceForge/phpwiki.git] / lib / HttpClient.php
1 <?php
2
3 /**
4    Version 0.9, 6th April 2003 - Simon Willison ( http://simon.incutio.com/ )
5    Manual: http://scripts.incutio.com/httpclient/
6
7    Copyright © 2003 Incutio Limited
8    License: http://www.opensource.org/licenses/artistic-license.php
9
10    File upload and xmlrpc support by Reini Urban for PhpWiki, 2006-12-28 18:12:47
11    Todo: proxy support
12 */
13
14 class HttpClient {
15     // Request vars
16     var $host;
17     var $port;
18     var $path;
19     var $method;
20     var $postdata = '';
21     var $cookies = array();
22     var $referer;
23     var $accept = 'text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,image/jpeg,image/gif,*/*';
24     var $accept_encoding = 'gzip';
25     var $accept_language = 'en-us';
26     var $user_agent = 'Incutio HttpClient v1.0';
27     var $boundary = "xYzZY"; // FIXME: check if this string doesn't occur in the data
28     // Options
29     var $timeout = 10;
30     var $use_gzip = true;
31     var $persist_cookies = true;  // If true, received cookies are placed in the $this->cookies array ready for the next request
32                                   // Note: This currently ignores the cookie path (and time) completely. Time is not important,
33                                   //       but path could possibly lead to security problems.
34     var $persist_referers = true; // For each request, sends path of last request as referer
35     var $debug = false;
36     var $handle_redirects = true; // Auaomtically redirect if Location or URI header is found
37     var $max_redirects = 5;
38     var $headers_only = false;    // If true, stops receiving once headers have been read.
39     // Basic authorization variables
40     var $username;
41     var $password;
42     // Response vars
43     var $status;
44     var $headers = array();
45     var $content = '';
46     var $errormsg;
47     // Tracker variables
48     var $redirect_count = 0;
49     var $cookie_host = '';
50
51     function HttpClient($host='localhost', $port=80) {
52         $this->host = $host;
53         $this->port = $port;
54     }
55     function get($path, $data = false) {
56         $this->path = $path;
57         $this->method = 'GET';
58         if ($data) {
59             $this->path .= '?'.$this->buildQueryString($data);
60         }
61         return $this->doRequest();
62     }
63     function post($path, $data) {
64         $this->path = $path;
65         $this->method = 'POST';
66         $this->postdata = $this->buildQueryString($data);
67         return $this->doRequest();
68     }
69     function postfile($path, $filename) {
70         $this->path = $path;
71         $this->method = 'POST';
72     $boundary = $this->boundary; //"httpclient_boundary";
73     $headers[] = "Content-Type: multipart/form-data; boundary=\"$boundary\"";
74     $basename = basename($filename);
75     $this->postdata =
76         "\r\n--$boundary\r\n"
77         ."Content-Disposition: form-data; filename=\"$basename\"\r\n"
78         ."Content-Type: application/octet-stream\r\n\r\n";
79     $this->postdata .= join("",file($filename));
80     $this->postdata .= "\r\n\r\n--$boundary--\r\n";
81         return $this->doRequest();
82     }
83     function buildQueryString($data) {
84         $querystring = '';
85         if (is_array($data)) {
86             // Change data in to postable data
87             foreach ($data as $key => $val) {
88                 if (is_array($val)) {
89                     foreach ($val as $val2) {
90                         $querystring .= urlencode($key).'='.urlencode($val2).'&';
91                     }
92                 } else {
93                     $querystring .= urlencode($key).'='.urlencode($val).'&';
94                 }
95             }
96             $querystring = substr($querystring, 0, -1); // Eliminate unnecessary &
97         } else {
98             $querystring = $data;
99         }
100         return $querystring;
101     }
102
103     function doRequest() {
104         // Performs the actual HTTP request, returning true or false depending on outcome
105         // Ensure that the PHP timeout is longer than the socket timeout
106         longer_timeout($this->timeout);
107         if (!$fp = @fsockopen($this->host, $this->port, $errno, $errstr, $this->timeout)) {
108             // Set error message
109             switch($errno) {
110             case -3:
111                 $this->errormsg = 'Socket creation failed (-3)';
112             case -4:
113                 $this->errormsg = 'DNS lookup failure (-4)';
114             case -5:
115                 $this->errormsg = 'Connection refused or timed out (-5)';
116             default:
117                 $this->errormsg = 'Connection failed ('.$errno.')';
118                 $this->errormsg .= ' '.$errstr;
119                 $this->debug($this->errormsg);
120             }
121             return false;
122         }
123         socket_set_timeout($fp, $this->timeout);
124     if ( $this->method == 'POST' and preg_match("/\<methodCall\>/", $this->postdata))
125         $request = $this->buildRequest("text/xml"); //xmlrpc
126     else if ( $this->method == 'POST' and strstr("\r\nContent-Disposition: form-data; filename=",
127                              $this->postdata))
128     {
129         //file upload
130         $boundary = $this->boundary;
131         $request = $this->buildRequest("multipart/form-data; boundary=\"$boundary\"");
132     } else
133         $request = $this->buildRequest();
134         $this->debug('Request', $request);
135         fwrite($fp, $request);
136         // Reset all the variables that should not persist between requests
137         $this->headers = array();
138         $this->content = '';
139         $this->errormsg = '';
140         // Set a couple of flags
141         $inHeaders = true;
142         $atStart = true;
143         // Now start reading back the response
144         while (!feof($fp)) {
145             $line = fgets($fp, 4096);
146             if ($atStart) {
147                 // Deal with first line of returned data
148                 $atStart = false;
149                 if ($line === false) {
150                     $this->errormsg = "Empty ". $this->method. " response";
151                     return false;
152                 }
153                 if (!preg_match('/HTTP\/(\\d\\.\\d)\\s*(\\d+)\\s*(.*)/', $line, $m)) {
154                     $this->errormsg = "Status code line invalid: ".htmlentities($line);
155                     $this->debug($this->errormsg);
156                     return false;
157                 }
158                 $http_version = $m[1]; // not used
159                 $this->status = $m[2];
160                 $status_string = $m[3]; // not used
161                 $this->debug(trim($line));
162                 continue;
163             }
164             if ($inHeaders) {
165                 if (trim($line) == '') {
166                     $inHeaders = false;
167                     $this->debug('Received Headers', $this->headers);
168                     if ($this->headers_only) {
169                         break; // Skip the rest of the input
170                     }
171                     continue;
172                 }
173                 if (!preg_match('/([^:]+):\\s*(.*)/', $line, $m)) {
174                     // Skip to the next header
175                     continue;
176                 }
177                 $key = strtolower(trim($m[1]));
178                 $val = trim($m[2]);
179                 // Deal with the possibility of multiple headers of same name
180                 if (isset($this->headers[$key])) {
181                     if (is_array($this->headers[$key])) {
182                         $this->headers[$key][] = $val;
183                     } else {
184                         $this->headers[$key] = array($this->headers[$key], $val);
185                     }
186                 } else {
187                     $this->headers[$key] = $val;
188                 }
189                 continue;
190             }
191             // We're not in the headers, so append the line to the contents
192             $this->content .= $line;
193         }
194         fclose($fp);
195         // If data is compressed, uncompress it
196         if (isset($this->headers['content-encoding']) && $this->headers['content-encoding'] == 'gzip') {
197             $this->debug('Content is gzip encoded, unzipping it');
198             $this->content = substr($this->content, 10); // See http://www.php.net/manual/en/function.gzencode.php
199             $this->content = gzinflate($this->content);
200         }
201         // If $persist_cookies, deal with any cookies
202         if ($this->persist_cookies && isset($this->headers['set-cookie']) && $this->host == $this->cookie_host) {
203             $cookies = $this->headers['set-cookie'];
204             if (!is_array($cookies)) {
205                 $cookies = array($cookies);
206             }
207             foreach ($cookies as $cookie) {
208                 if (preg_match('/([^=]+)=([^;]+);/', $cookie, $m)) {
209                     $this->cookies[$m[1]] = $m[2];
210                 }
211             }
212             // Record domain of cookies for security reasons
213             $this->cookie_host = $this->host;
214         }
215         if ($this->status == '401') {
216             $this->errormsg = '401 ' . $status_string;
217             return false;
218         }
219         // If $persist_referers, set the referer ready for the next request
220         if (isset($this->persist_referers)) {
221             $this->debug('Persisting referer: '.$this->getRequestURL());
222             $this->referer = $this->getRequestURL();
223         }
224         // Finally, if handle_redirects and a redirect is sent, do that
225         if (isset($this->handle_redirects)) {
226             if (++$this->redirect_count >= $this->max_redirects) {
227                 $this->errormsg = 'Number of redirects exceeded maximum ('.$this->max_redirects.')';
228                 $this->debug($this->errormsg);
229                 $this->redirect_count = 0;
230                 return false;
231             }
232             $location = isset($this->headers['location']) ? $this->headers['location'] : '';
233             $uri = isset($this->headers['uri']) ? $this->headers['uri'] : '';
234             if ($location || $uri) {
235                 $url = parse_url($location.$uri);
236                 if ($this->method == 'POST')
237                     return $this->doRequest();
238                 else
239                     // This will FAIL if redirect is to a different site
240                     return $this->get($url['path']);
241             }
242         }
243         return true;
244     }
245
246     function buildRequest($ContentType = 'application/x-www-form-urlencoded') {
247         $headers = array();
248     // Using 1.1 leads to all manner of problems, such as "chunked" encoding
249         $headers[] = "{$this->method} {$this->path} HTTP/1.0";
250         $headers[] = "Host: {$this->host}";
251         $headers[] = "User-Agent: {$this->user_agent}";
252         $headers[] = "Accept: {$this->accept}";
253         if ($this->use_gzip) {
254             $headers[] = "Accept-encoding: {$this->accept_encoding}";
255         }
256         $headers[] = "Accept-language: {$this->accept_language}";
257         if (!empty($this->referer)) {
258             $headers[] = "Referer: {$this->referer}";
259         }
260         // Cookies
261         if (!empty($this->cookies)) {
262             $cookie = 'Cookie: ';
263             foreach ($this->cookies as $key => $value) {
264                 $cookie .= "$key=$value; ";
265             }
266             $headers[] = $cookie;
267         }
268         // Basic authentication
269         if (!empty($this->username) && !empty($this->password)) {
270             $headers[] = 'Authorization: BASIC '.base64_encode($this->username.':'.$this->password);
271         }
272         // If this is a POST, set the content type and length
273         if ($this->postdata) {
274         $headers[] = 'Content-Type: ' . $ContentType;
275             $headers[] = 'Content-Length: '.strlen($this->postdata);
276         }
277         $request = implode("\r\n", $headers)."\r\n\r\n".$this->postdata;
278         return $request;
279     }
280     function getStatus() {
281         return $this->status;
282     }
283     function getContent() {
284         return $this->content;
285     }
286     function getHeaders() {
287         return $this->headers;
288     }
289     function getHeader($header) {
290         $header = strtolower($header);
291         if (isset($this->headers[$header])) {
292             return $this->headers[$header];
293         } else {
294             return false;
295         }
296     }
297     function getError() {
298         return $this->errormsg;
299     }
300     function getCookies() {
301         return $this->cookies;
302     }
303     function getRequestURL() {
304         $url = 'http://'.$this->host;
305         if ($this->port != 80) {
306             $url = 'https://'.$this->host;
307             $url .= ':'.$this->port;
308         }
309         $url .= $this->path;
310         return $url;
311     }
312     // Setter methods
313     function setUserAgent($string) {
314         $this->user_agent = $string;
315     }
316     function setAuthorization($username, $password) {
317         $this->username = $username;
318         $this->password = $password;
319     }
320     function setCookies($array) {
321         $this->cookies = $array;
322     }
323     // Option setting methods
324     function useGzip($boolean) {
325         $this->use_gzip = $boolean;
326     }
327     function setPersistCookies($boolean) {
328         $this->persist_cookies = $boolean;
329     }
330     function setPersistReferers($boolean) {
331         $this->persist_referers = $boolean;
332     }
333     function setHandleRedirects($boolean) {
334         $this->handle_redirects = $boolean;
335     }
336     function setMaxRedirects($num) {
337         $this->max_redirects = $num;
338     }
339     function setHeadersOnly($boolean) {
340         $this->headers_only = $boolean;
341     }
342     function setDebug($boolean) {
343         $this->debug = $boolean;
344     }
345     // "Quick" static methods
346     function quickGet($url) {
347         $bits = parse_url($url);
348         $host = $bits['host'];
349         $port = isset($bits['port']) ? $bits['port'] : 80;
350         $path = isset($bits['path']) ? $bits['path'] : '/';
351         if (isset($bits['query'])) {
352             $path .= '?'.$bits['query'];
353         }
354         $client = new HttpClient($host, $port);
355         if (!$client->get($path)) {
356             return false;
357         } else {
358             return $client->getContent();
359         }
360     }
361     function quickPost($url, $data) {
362         $bits = parse_url($url);
363         $host = $bits['host'];
364         $port = isset($bits['port']) ? $bits['port'] : 80;
365         $path = isset($bits['path']) ? $bits['path'] : '/';
366         $client = new HttpClient($host, $port);
367         if (!$client->post($path, $data)) {
368             return false;
369         } else {
370             return $client->getContent();
371         }
372     }
373     function debug($msg, $object = false) {
374         if ($this->debug) {
375             print '<div style="border: 1px solid red; padding: 0.5em; margin: 0.5em;"><strong>HttpClient Debug:</strong> '.$msg;
376             if ($object) {
377                 ob_start();
378                 print_r($object);
379                 $content = htmlentities(ob_get_contents());
380                 ob_end_clean();
381                 print '<pre>'.$content.'</pre>';
382             }
383             print '</div>';
384         }
385     }
386 }
387
388 // Local Variables:
389 // mode: php
390 // tab-width: 8
391 // c-basic-offset: 4
392 // c-hanging-comment-ender-p: nil
393 // indent-tabs-mode: nil
394 // End: