5 * @license GPL 2 (http://www.gnu.org/licenses/gpl.html)
6 * @author Andreas Goetz <cpuidle@gmx.de>
10 define('HTTP_NL',"\r\n");
14 * Adds DokuWiki specific configs to the HTTP client
16 * @author Andreas Goetz <cpuidle@gmx.de>
18 class DokuHTTPClient
extends HTTPClient
{
23 * @author Andreas Gohr <andi@splitbrain.org>
25 function DokuHTTPClient(){
28 // call parent constructor
31 // set some values from the config
32 $this->proxy_host
= $conf['proxy']['host'];
33 $this->proxy_port
= $conf['proxy']['port'];
34 $this->proxy_user
= $conf['proxy']['user'];
35 $this->proxy_pass
= conf_decodeString($conf['proxy']['pass']);
36 $this->proxy_ssl
= $conf['proxy']['ssl'];
41 * Wraps an event around the parent function
43 * @triggers HTTPCLIENT_REQUEST_SEND
44 * @author Andreas Gohr <andi@splitbrain.org>
46 function sendRequest($url,$data='',$method='GET'){
47 $httpdata = array('url' => $url,
50 $evt = new Doku_Event('HTTPCLIENT_REQUEST_SEND',$httpdata);
51 if($evt->advise_before()){
52 $url = $httpdata['url'];
53 $data = $httpdata['data'];
54 $method = $httpdata['method'];
58 return parent
::sendRequest($url,$data,$method);
64 * This class implements a basic HTTP client
66 * It supports POST and GET, Proxy usage, basic authentication,
67 * handles cookies and referers. It is based upon the httpclient
68 * function from the VideoDB project.
70 * @link http://www.splitbrain.org/go/videodb
71 * @author Andreas Goetz <cpuidle@gmx.de>
72 * @author Andreas Gohr <andi@splitbrain.org>
75 //set these if you like
76 var $agent; // User agent
77 var $http; // HTTP version defaults to 1.0
78 var $timeout; // read timeout (seconds)
83 var $max_bodysize_abort = true; // if set, abort if the response body is bigger than max_bodysize
84 var $header_regexp; // if set this RE must match against the headers, else abort
87 var $start = 0; // for timings
89 // don't set these, read on error
93 // read these after a successful request
98 // set these to do basic authentication
102 // set these if you need to use a proxy
107 var $proxy_ssl; //boolean set to true if your proxy needs SSL
109 // what we use as boundary on multipart/form-data posts
110 var $boundary = '---DokuWikiHTTPClient--4523452351';
115 * @author Andreas Gohr <andi@splitbrain.org>
117 function HTTPClient(){
118 $this->agent
= 'Mozilla/4.0 (compatible; DokuWiki HTTP Client; '.PHP_OS
.')';
120 $this->cookies
= array();
122 $this->max_redirect
= 3;
123 $this->redirect_count
= 0;
125 $this->headers
= array();
127 $this->debug
= false;
128 $this->max_bodysize
= 0;
129 $this->header_regexp
= '';
130 if(extension_loaded('zlib')) $this->headers
['Accept-encoding'] = 'gzip';
131 $this->headers
['Accept'] = 'text/xml,application/xml,application/xhtml+xml,'.
132 'text/html,text/plain,image/png,image/jpeg,image/gif,*/*';
133 $this->headers
['Accept-Language'] = 'en-us';
138 * Simple function to do a GET request
140 * Returns the wanted page or false on an error;
142 * @param string $url The URL to fetch
143 * @param bool $sloppy304 Return body on 304 not modified
144 * @author Andreas Gohr <andi@splitbrain.org>
146 function get($url,$sloppy304=false){
147 if(!$this->sendRequest($url)) return false;
148 if($this->status
== 304 && $sloppy304) return $this->resp_body
;
149 if($this->status
< 200 ||
$this->status
> 206) return false;
150 return $this->resp_body
;
154 * Simple function to do a POST request
156 * Returns the resulting page or false on an error;
158 * @author Andreas Gohr <andi@splitbrain.org>
160 function post($url,$data){
161 if(!$this->sendRequest($url,$data,'POST')) return false;
162 if($this->status
< 200 ||
$this->status
> 206) return false;
163 return $this->resp_body
;
167 * Send an HTTP request
169 * This method handles the whole HTTP communication. It respects set proxy settings,
170 * builds the request headers, follows redirects and parses the response.
172 * Post data should be passed as associative array. When passed as string it will be
173 * sent as is. You will need to setup your own Content-Type header then.
175 * @param string $url - the complete URL
176 * @param mixed $data - the post data either as array or raw data
177 * @param string $method - HTTP Method usually GET or POST.
178 * @return bool - true on success
179 * @author Andreas Goetz <cpuidle@gmx.de>
180 * @author Andreas Gohr <andi@splitbrain.org>
182 function sendRequest($url,$data='',$method='GET'){
183 $this->start
= $this->_time();
187 // don't accept gzip if truncated bodies might occur
188 if($this->max_bodysize
&&
189 !$this->max_bodysize_abort
&&
190 $this->headers
['Accept-encoding'] == 'gzip'){
191 unset($this->headers
['Accept-encoding']);
194 // parse URL into bits
195 $uri = parse_url($url);
196 $server = $uri['host'];
197 $path = $uri['path'];
198 if(empty($path)) $path = '/';
199 if(!empty($uri['query'])) $path .= '?'.$uri['query'];
200 $port = $uri['port'];
201 if(isset($uri['user'])) $this->user
= $uri['user'];
202 if(isset($uri['pass'])) $this->pass
= $uri['pass'];
205 if($this->proxy_host
){
207 $server = $this->proxy_host
;
208 $port = $this->proxy_port
;
209 if (empty($port)) $port = 8080;
211 $request_url = $path;
213 if (empty($port)) $port = ($uri['scheme'] == 'https') ?
443 : 80;
216 // add SSL stream prefix if needed - needs SSL support in PHP
217 if($port == 443 ||
$this->proxy_ssl
) $server = 'ssl://'.$server;
220 $headers = $this->headers
;
221 $headers['Host'] = $uri['host'];
222 $headers['User-Agent'] = $this->agent
;
223 $headers['Referer'] = $this->referer
;
224 $headers['Connection'] = 'Close';
225 if($method == 'POST'){
227 if($headers['Content-Type'] == 'multipart/form-data'){
228 $headers['Content-Type'] = 'multipart/form-data; boundary='.$this->boundary
;
229 $data = $this->_postMultipartEncode($data);
231 $headers['Content-Type'] = 'application/x-www-form-urlencoded';
232 $data = $this->_postEncode($data);
235 $headers['Content-Length'] = strlen($data);
237 }elseif($method == 'GET'){
238 $data = ''; //no data allowed on GET requests
241 $headers['Authorization'] = 'Basic '.base64_encode($this->user
.':'.$this->pass
);
243 if($this->proxy_user
) {
244 $headers['Proxy-Authorization'] = 'Basic '.base64_encode($this->proxy_user
.':'.$this->proxy_pass
);
251 $socket = @fsockopen
($server,$port,$errno, $errstr, $this->timeout
);
253 $resp->status
= '-100';
254 $this->error
= "Could not connect to $server:$port\n$errstr ($errno)";
258 stream_set_blocking($socket,0);
261 $request = "$method $request_url HTTP/".$this->http
.HTTP_NL
;
262 $request .= $this->_buildHeaders($headers);
263 $request .= $this->_getCookies();
267 $this->_debug('request',$request);
270 $towrite = strlen($request);
272 while($written < $towrite){
273 $ret = fwrite($socket, substr($request,$written));
275 $this->status
= -100;
276 $this->error
= 'Failed writing to socket';
283 // read headers from socket
286 if(time()-$start > $this->timeout
){
287 $this->status
= -100;
288 $this->error
= sprintf('Timeout while reading headers (%.3fs)',$this->_time() - $this->start
);
292 $this->error
= 'Premature End of File (socket)';
295 $r_headers .= fgets($socket,1024);
296 }while(!preg_match('/\r?\n\r?\n$/',$r_headers));
298 $this->_debug('response headers',$r_headers);
300 // check if expected body size exceeds allowance
301 if($this->max_bodysize
&& preg_match('/\r?\nContent-Length:\s*(\d+)\r?\n/i',$r_headers,$match)){
302 if($match[1] > $this->max_bodysize
){
303 $this->error
= 'Reported content length exceeds allowed response size';
304 if ($this->max_bodysize_abort
)
310 if (!preg_match('/^HTTP\/(\d\.\d)\s*(\d+).*?\n/', $r_headers, $m)) {
311 $this->error
= 'Server returned bad answer';
314 $this->status
= $m[2];
316 // handle headers and cookies
317 $this->resp_headers
= $this->_parseHeaders($r_headers);
318 if(isset($this->resp_headers
['set-cookie'])){
319 foreach ((array) $this->resp_headers
['set-cookie'] as $cookie){
320 list($cookie) = explode(';',$cookie,2);
321 list($key,$val) = explode('=',$cookie,2);
323 if($val == 'deleted'){
324 if(isset($this->cookies
[$key])){
325 unset($this->cookies
[$key]);
328 $this->cookies
[$key] = $val;
333 $this->_debug('Object headers',$this->resp_headers
);
335 // check server status code to follow redirect
336 if($this->status
== 301 ||
$this->status
== 302 ){
337 if (empty($this->resp_headers
['location'])){
338 $this->error
= 'Redirect but no Location Header found';
340 }elseif($this->redirect_count
== $this->max_redirect
){
341 $this->error
= 'Maximum number of redirects exceeded';
344 $this->redirect_count++
;
345 $this->referer
= $url;
346 // handle non-RFC-compliant relative redirects
347 if (!preg_match('/^http/i', $this->resp_headers
['location'])){
348 if($this->resp_headers
['location'][0] != '/'){
349 $this->resp_headers
['location'] = $uri['scheme'].'://'.$uri['host'].':'.$uri['port'].
350 dirname($uri['path']).'/'.$this->resp_headers
['location'];
352 $this->resp_headers
['location'] = $uri['scheme'].'://'.$uri['host'].':'.$uri['port'].
353 $this->resp_headers
['location'];
356 // perform redirected request, always via GET (required by RFC)
357 return $this->sendRequest($this->resp_headers
['location'],array(),'GET');
361 // check if headers are as expected
362 if($this->header_regexp
&& !preg_match($this->header_regexp
,$r_headers)){
363 $this->error
= 'The received headers did not match the given regexp';
367 //read body (with chunked encoding if needed)
369 if(preg_match('/transfer\-(en)?coding:\s*chunked\r\n/i',$r_headers)){
374 $this->error
= 'Premature End of File (socket)';
377 if(time()-$start > $this->timeout
){
378 $this->status
= -100;
379 $this->error
= sprintf('Timeout while reading chunk (%.3fs)',$this->_time() - $this->start
);
382 $byte = fread($socket,1);
383 $chunk_size .= $byte;
384 } while (preg_match('/[a-zA-Z0-9]/',$byte)); // read chunksize including \r
386 $byte = fread($socket,1); // readtrailing \n
387 $chunk_size = hexdec($chunk_size);
389 $this_chunk = fread($socket,$chunk_size);
390 $r_body .= $this_chunk;
391 $byte = fread($socket,2); // read trailing \r\n
394 if($this->max_bodysize
&& strlen($r_body) > $this->max_bodysize
){
395 $this->error
= 'Allowed response size exceeded';
396 if ($this->max_bodysize_abort
)
401 } while ($chunk_size);
403 // read entire socket
404 while (!feof($socket)) {
405 if(time()-$start > $this->timeout
){
406 $this->status
= -100;
407 $this->error
= sprintf('Timeout while reading response (%.3fs)',$this->_time() - $this->start
);
410 $r_body .= fread($socket,4096);
411 $r_size = strlen($r_body);
412 if($this->max_bodysize
&& $r_size > $this->max_bodysize
){
413 $this->error
= 'Allowed response size exceeded';
414 if ($this->max_bodysize_abort
)
419 if(isset($this->resp_headers
['content-length']) &&
420 !isset($this->resp_headers
['transfer-encoding']) &&
421 $this->resp_headers
['content-length'] == $r_size){
422 // we read the content-length, finish here
429 $status = socket_get_status($socket);
432 // decode gzip if needed
433 if(isset($this->resp_headers
['content-encoding']) &&
434 $this->resp_headers
['content-encoding'] == 'gzip' &&
435 strlen($r_body) > 10 && substr($r_body,0,3)=="\x1f\x8b\x08"){
436 $this->resp_body
= @gzinflate
(substr($r_body, 10));
438 $this->resp_body
= $r_body;
441 $this->_debug('response body',$this->resp_body
);
442 $this->redirect_count
= 0;
449 * @author Andreas Gohr <andi@splitbrain.org>
451 function _debug($info,$var=null){
452 if(!$this->debug
) return;
453 print '<b>'.$info.'</b> '.($this->_time() - $this->start
).'s<br />';
457 $content = htmlspecialchars(ob_get_contents());
459 print '<pre>'.$content.'</pre>';
464 * Return current timestamp in microsecond resolution
467 list($usec, $sec) = explode(" ", microtime());
468 return ((float)$usec +
(float)$sec);
472 * convert given header string to Header array
474 * All Keys are lowercased.
476 * @author Andreas Gohr <andi@splitbrain.org>
478 function _parseHeaders($string){
480 $lines = explode("\n",$string);
481 foreach($lines as $line){
482 list($key,$val) = explode(':',$line,2);
483 $key = strtolower(trim($key));
485 if(empty($val)) continue;
486 if(isset($headers[$key])){
487 if(is_array($headers[$key])){
488 $headers[$key][] = $val;
490 $headers[$key] = array($headers[$key],$val);
493 $headers[$key] = $val;
500 * convert given header array to header string
502 * @author Andreas Gohr <andi@splitbrain.org>
504 function _buildHeaders($headers){
506 foreach($headers as $key => $value){
507 if(empty($value)) continue;
508 $string .= $key.': '.$value.HTTP_NL
;
514 * get cookies as http header string
516 * @author Andreas Goetz <cpuidle@gmx.de>
518 function _getCookies(){
520 foreach ($this->cookies
as $key => $val){
521 $headers .= "$key=$val; ";
523 $headers = substr($headers, 0, -2);
524 if ($headers !== '') $headers = "Cookie: $headers".HTTP_NL
;
529 * Encode data for posting
531 * @author Andreas Gohr <andi@splitbrain.org>
533 function _postEncode($data){
534 foreach($data as $key => $val){
535 if($url) $url .= '&';
536 $url .= urlencode($key).'='.urlencode($val);
542 * Encode data for posting using multipart encoding
544 * @fixme use of urlencode might be wrong here
545 * @author Andreas Gohr <andi@splitbrain.org>
547 function _postMultipartEncode($data){
548 $boundary = '--'.$this->boundary
;
550 foreach($data as $key => $val){
551 $out .= $boundary.HTTP_NL
;
553 $out .= 'Content-Disposition: form-data; name="'.urlencode($key).'"'.HTTP_NL
;
554 $out .= HTTP_NL
; // end of headers
558 $out .= 'Content-Disposition: form-data; name="'.urlencode($key).'"';
559 if($val['filename']) $out .= '; filename="'.urlencode($val['filename']).'"';
561 if($val['mimetype']) $out .= 'Content-Type: '.$val['mimetype'].HTTP_NL
;
562 $out .= HTTP_NL
; // end of headers
563 $out .= $val['body'];
567 $out .= "$boundary--".HTTP_NL
;
573 //Setup VIM: ex: et ts=4 enc=utf-8 :