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