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