]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/HttpClient.php
Update translations
[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                     break;
124                 case -4:
125                     $this->errormsg = 'DNS lookup failure (-4)';
126                     break;
127                 case -5:
128                     $this->errormsg = 'Connection refused or timed out (-5)';
129                     break;
130                 default:
131                     $this->errormsg = 'Connection failed (' . $errno . ')';
132                     $this->errormsg .= ' ' . $errstr;
133                     $this->debug($this->errormsg);
134             }
135             return false;
136         }
137         socket_set_timeout($fp, $this->timeout);
138         if ($this->method == 'POST' and preg_match("/\<methodCall\>/", $this->postdata))
139             $request = $this->buildRequest("text/xml"); //xmlrpc
140         else if ($this->method == 'POST' and strstr("\r\nContent-Disposition: form-data; filename=",
141             $this->postdata)
142         ) {
143             //file upload
144             $boundary = $this->boundary;
145             $request = $this->buildRequest("multipart/form-data; boundary=\"$boundary\"");
146         } else
147             $request = $this->buildRequest();
148         $this->debug('Request', $request);
149         fwrite($fp, $request);
150         // Reset all the variables that should not persist between requests
151         $this->headers = array();
152         $this->content = '';
153         $this->errormsg = '';
154         // Set a couple of flags
155         $inHeaders = true;
156         $atStart = true;
157         // Now start reading back the response
158         while (!feof($fp)) {
159             $line = fgets($fp, 4096);
160             if ($atStart) {
161                 // Deal with first line of returned data
162                 $atStart = false;
163                 if ($line === false) {
164                     $this->errormsg = "Empty " . $this->method . " response";
165                     return false;
166                 }
167                 if (!preg_match('/HTTP\/(\\d\\.\\d)\\s*(\\d+)\\s*(.*)/', $line, $m)) {
168                     $this->errormsg = "Status code line invalid: " . htmlentities($line);
169                     $this->debug($this->errormsg);
170                     return false;
171                 }
172                 // $http_version = $m[1]; // not used
173                 $this->status = $m[2];
174                 $status_string = $m[3];
175                 $this->debug(trim($line));
176                 continue;
177             }
178             if ($inHeaders) {
179                 if (trim($line) == '') {
180                     $inHeaders = false;
181                     $this->debug('Received Headers', $this->headers);
182                     if ($this->headers_only) {
183                         break; // Skip the rest of the input
184                     }
185                     continue;
186                 }
187                 if (!preg_match('/([^:]+):\\s*(.*)/', $line, $m)) {
188                     // Skip to the next header
189                     continue;
190                 }
191                 $key = strtolower(trim($m[1]));
192                 $val = trim($m[2]);
193                 // Deal with the possibility of multiple headers of same name
194                 if (isset($this->headers[$key])) {
195                     if (is_array($this->headers[$key])) {
196                         $this->headers[$key][] = $val;
197                     } else {
198                         $this->headers[$key] = array($this->headers[$key], $val);
199                     }
200                 } else {
201                     $this->headers[$key] = $val;
202                 }
203                 continue;
204             }
205             // We're not in the headers, so append the line to the contents
206             $this->content .= $line;
207         }
208         fclose($fp);
209         // If data is compressed, uncompress it
210         if (isset($this->headers['content-encoding']) && $this->headers['content-encoding'] == 'gzip') {
211             $this->debug('Content is gzip encoded, unzipping it');
212             $this->content = substr($this->content, 10); // See http://www.php.net/manual/en/function.gzencode.php
213             $this->content = gzinflate($this->content);
214         }
215         // If $persist_cookies, deal with any cookies
216         if ($this->persist_cookies && isset($this->headers['set-cookie']) && $this->host == $this->cookie_host) {
217             $cookies = $this->headers['set-cookie'];
218             if (!is_array($cookies)) {
219                 $cookies = array($cookies);
220             }
221             foreach ($cookies as $cookie) {
222                 if (preg_match('/([^=]+)=([^;]+);/', $cookie, $m)) {
223                     $this->cookies[$m[1]] = $m[2];
224                 }
225             }
226             // Record domain of cookies for security reasons
227             $this->cookie_host = $this->host;
228         }
229         if ($this->status == '401') {
230             $this->errormsg = '401 ' . $status_string;
231             return false;
232         }
233         // If $persist_referers, set the referer ready for the next request
234         if (isset($this->persist_referers)) {
235             $this->debug('Persisting referer: ' . $this->getRequestURL());
236             $this->referer = $this->getRequestURL();
237         }
238         // Finally, if handle_redirects and a redirect is sent, do that
239         if (isset($this->handle_redirects)) {
240             if (++$this->redirect_count >= $this->max_redirects) {
241                 $this->errormsg = 'Number of redirects exceeded maximum (' . $this->max_redirects . ')';
242                 $this->debug($this->errormsg);
243                 $this->redirect_count = 0;
244                 return false;
245             }
246             $location = isset($this->headers['location']) ? $this->headers['location'] : '';
247             $uri = isset($this->headers['uri']) ? $this->headers['uri'] : '';
248             if ($location || $uri) {
249                 $url = parse_url($location . $uri);
250                 if ($this->method == 'POST')
251                     return $this->doRequest();
252                 else
253                     // This will FAIL if redirect is to a different site
254                     return $this->get($url['path']);
255             }
256         }
257         return true;
258     }
259
260     function buildRequest($ContentType = 'application/x-www-form-urlencoded')
261     {
262         $headers = array();
263         // Using 1.1 leads to all manner of problems, such as "chunked" encoding
264         $headers[] = "{$this->method} {$this->path} HTTP/1.0";
265         $headers[] = "Host: {$this->host}";
266         $headers[] = "User-Agent: {$this->user_agent}";
267         $headers[] = "Accept: {$this->accept}";
268         if ($this->use_gzip) {
269             $headers[] = "Accept-encoding: {$this->accept_encoding}";
270         }
271         $headers[] = "Accept-language: {$this->accept_language}";
272         if (!empty($this->referer)) {
273             $headers[] = "Referer: {$this->referer}";
274         }
275         // Cookies
276         if (!empty($this->cookies)) {
277             $cookie = 'Cookie: ';
278             foreach ($this->cookies as $key => $value) {
279                 $cookie .= "$key=$value; ";
280             }
281             $headers[] = $cookie;
282         }
283         // Basic authentication
284         if (!empty($this->username) && !empty($this->password)) {
285             $headers[] = 'Authorization: BASIC ' . base64_encode($this->username . ':' . $this->password);
286         }
287         // If this is a POST, set the content type and length
288         if ($this->postdata) {
289             $headers[] = 'Content-Type: ' . $ContentType;
290             $headers[] = 'Content-Length: ' . strlen($this->postdata);
291         }
292         $request = implode("\r\n", $headers) . "\r\n\r\n" . $this->postdata;
293         return $request;
294     }
295
296     function getStatus()
297     {
298         return $this->status;
299     }
300
301     function getContent()
302     {
303         return $this->content;
304     }
305
306     function getHeaders()
307     {
308         return $this->headers;
309     }
310
311     function getHeader($header)
312     {
313         $header = strtolower($header);
314         if (isset($this->headers[$header])) {
315             return $this->headers[$header];
316         } else {
317             return false;
318         }
319     }
320
321     function getError()
322     {
323         return $this->errormsg;
324     }
325
326     function getCookies()
327     {
328         return $this->cookies;
329     }
330
331     function getRequestURL()
332     {
333         $url = 'http://' . $this->host;
334         if ($this->port != 80) {
335             $url = 'https://' . $this->host;
336             $url .= ':' . $this->port;
337         }
338         $url .= $this->path;
339         return $url;
340     }
341
342     // Setter methods
343     function setUserAgent($string)
344     {
345         $this->user_agent = $string;
346     }
347
348     function setAuthorization($username, $password)
349     {
350         $this->username = $username;
351         $this->password = $password;
352     }
353
354     function setCookies($array)
355     {
356         $this->cookies = $array;
357     }
358
359     // Option setting methods
360     function useGzip($boolean)
361     {
362         $this->use_gzip = $boolean;
363     }
364
365     function setPersistCookies($boolean)
366     {
367         $this->persist_cookies = $boolean;
368     }
369
370     function setPersistReferers($boolean)
371     {
372         $this->persist_referers = $boolean;
373     }
374
375     function setHandleRedirects($boolean)
376     {
377         $this->handle_redirects = $boolean;
378     }
379
380     function setMaxRedirects($num)
381     {
382         $this->max_redirects = $num;
383     }
384
385     function setHeadersOnly($boolean)
386     {
387         $this->headers_only = $boolean;
388     }
389
390     function setDebug($boolean)
391     {
392         $this->debug = $boolean;
393     }
394
395     // "Quick" static methods
396     static function quickGet($url)
397     {
398         $bits = parse_url($url);
399         $host = $bits['host'];
400         $port = isset($bits['port']) ? $bits['port'] : 80;
401         $path = isset($bits['path']) ? $bits['path'] : '/';
402         if (isset($bits['query'])) {
403             $path .= '?' . $bits['query'];
404         }
405         $client = new HttpClient($host, $port);
406         if (!$client->get($path)) {
407             return false;
408         } else {
409             return $client->getContent();
410         }
411     }
412
413     static function quickPost($url, $data)
414     {
415         $bits = parse_url($url);
416         $host = $bits['host'];
417         $port = isset($bits['port']) ? $bits['port'] : 80;
418         $path = isset($bits['path']) ? $bits['path'] : '/';
419         $client = new HttpClient($host, $port);
420         if (!$client->post($path, $data)) {
421             return false;
422         } else {
423             return $client->getContent();
424         }
425     }
426
427     function debug($msg, $object = null)
428     {
429         if ($this->debug) {
430             print '<div style="border: 1px solid red; padding: 0.5em; margin: 0.5em;"><strong>HttpClient Debug:</strong> ' . $msg;
431             if ($object) {
432                 ob_start();
433                 print_r($object);
434                 $content = htmlentities(ob_get_contents());
435                 ob_end_clean();
436                 print '<pre>' . $content . '</pre>';
437             }
438             print '</div>';
439         }
440     }
441 }
442
443 // Local Variables:
444 // mode: php
445 // tab-width: 8
446 // c-basic-offset: 4
447 // c-hanging-comment-ender-p: nil
448 // indent-tabs-mode: nil
449 // End: