Merge pull request #3941 from glensc/microtime
[dokuwiki.git] / inc / HTTP / HTTPClient.php
blob20305fc06c9835a21c3b56742d2c01b95d7d145d
1 <?php
3 namespace dokuwiki\HTTP;
5 define('HTTP_NL',"\r\n");
8 /**
9 * This class implements a basic HTTP client
11 * It supports POST and GET, Proxy usage, basic authentication,
12 * handles cookies and referrers. It is based upon the httpclient
13 * function from the VideoDB project.
15 * @link https://www.splitbrain.org/projects/videodb
16 * @author Andreas Goetz <cpuidle@gmx.de>
17 * @author Andreas Gohr <andi@splitbrain.org>
18 * @author Tobias Sarnowski <sarnowski@new-thoughts.org>
20 class HTTPClient {
21 //set these if you like
22 public $agent; // User agent
23 public $http; // HTTP version defaults to 1.0
24 public $timeout; // read timeout (seconds)
25 public $cookies;
26 public $referer;
27 public $max_redirect;
28 public $max_bodysize;
29 public $max_bodysize_abort = true; // if set, abort if the response body is bigger than max_bodysize
30 public $header_regexp; // if set this RE must match against the headers, else abort
31 public $headers;
32 public $debug;
33 public $start = 0.0; // for timings
34 public $keep_alive = true; // keep alive rocks
36 // don't set these, read on error
37 public $error;
38 public $redirect_count;
40 // read these after a successful request
41 public $status;
42 public $resp_body;
43 public $resp_headers;
45 // set these to do basic authentication
46 public $user;
47 public $pass;
49 // set these if you need to use a proxy
50 public $proxy_host;
51 public $proxy_port;
52 public $proxy_user;
53 public $proxy_pass;
54 public $proxy_ssl; //boolean set to true if your proxy needs SSL
55 public $proxy_except; // regexp of URLs to exclude from proxy
57 // list of kept alive connections
58 protected static $connections = array();
60 // what we use as boundary on multipart/form-data posts
61 protected $boundary = '---DokuWikiHTTPClient--4523452351';
63 /**
64 * Constructor.
66 * @author Andreas Gohr <andi@splitbrain.org>
68 public function __construct(){
69 $this->agent = 'Mozilla/4.0 (compatible; DokuWiki HTTP Client; '.PHP_OS.')';
70 $this->timeout = 15;
71 $this->cookies = array();
72 $this->referer = '';
73 $this->max_redirect = 3;
74 $this->redirect_count = 0;
75 $this->status = 0;
76 $this->headers = array();
77 $this->http = '1.0';
78 $this->debug = false;
79 $this->max_bodysize = 0;
80 $this->header_regexp= '';
81 if(extension_loaded('zlib')) $this->headers['Accept-encoding'] = 'gzip';
82 $this->headers['Accept'] = 'text/xml,application/xml,application/xhtml+xml,'.
83 'text/html,text/plain,image/png,image/jpeg,image/gif,*/*';
84 $this->headers['Accept-Language'] = 'en-us';
88 /**
89 * Simple function to do a GET request
91 * Returns the wanted page or false on an error;
93 * @param string $url The URL to fetch
94 * @param bool $sloppy304 Return body on 304 not modified
95 * @return false|string response body, false on error
97 * @author Andreas Gohr <andi@splitbrain.org>
99 public function get($url,$sloppy304=false){
100 if(!$this->sendRequest($url)) return false;
101 if($this->status == 304 && $sloppy304) return $this->resp_body;
102 if($this->status < 200 || $this->status > 206) return false;
103 return $this->resp_body;
107 * Simple function to do a GET request with given parameters
109 * Returns the wanted page or false on an error.
111 * This is a convenience wrapper around get(). The given parameters
112 * will be correctly encoded and added to the given base URL.
114 * @param string $url The URL to fetch
115 * @param array $data Associative array of parameters
116 * @param bool $sloppy304 Return body on 304 not modified
117 * @return false|string response body, false on error
119 * @author Andreas Gohr <andi@splitbrain.org>
121 public function dget($url,$data,$sloppy304=false){
122 if(strpos($url,'?')){
123 $url .= '&';
124 }else{
125 $url .= '?';
127 $url .= $this->postEncode($data);
128 return $this->get($url,$sloppy304);
132 * Simple function to do a POST request
134 * Returns the resulting page or false on an error;
136 * @param string $url The URL to fetch
137 * @param array $data Associative array of parameters
138 * @return false|string response body, false on error
139 * @author Andreas Gohr <andi@splitbrain.org>
141 public function post($url,$data){
142 if(!$this->sendRequest($url,$data,'POST')) return false;
143 if($this->status < 200 || $this->status > 206) return false;
144 return $this->resp_body;
148 * Send an HTTP request
150 * This method handles the whole HTTP communication. It respects set proxy settings,
151 * builds the request headers, follows redirects and parses the response.
153 * Post data should be passed as associative array. When passed as string it will be
154 * sent as is. You will need to setup your own Content-Type header then.
156 * @param string $url - the complete URL
157 * @param mixed $data - the post data either as array or raw data
158 * @param string $method - HTTP Method usually GET or POST.
159 * @return bool - true on success
161 * @author Andreas Goetz <cpuidle@gmx.de>
162 * @author Andreas Gohr <andi@splitbrain.org>
164 public function sendRequest($url,$data='',$method='GET'){
165 $this->start = microtime(true);
166 $this->error = '';
167 $this->status = 0;
168 $this->resp_body = '';
169 $this->resp_headers = array();
171 // save unencoded data for recursive call
172 $unencodedData = $data;
174 // don't accept gzip if truncated bodies might occur
175 if($this->max_bodysize &&
176 !$this->max_bodysize_abort &&
177 isset($this->headers['Accept-encoding']) &&
178 $this->headers['Accept-encoding'] == 'gzip'){
179 unset($this->headers['Accept-encoding']);
182 // parse URL into bits
183 $uri = parse_url($url);
184 $server = $uri['host'];
185 $path = !empty($uri['path']) ? $uri['path'] : '/';
186 $uriPort = !empty($uri['port']) ? $uri['port'] : null;
187 if(!empty($uri['query'])) $path .= '?'.$uri['query'];
188 if(isset($uri['user'])) $this->user = $uri['user'];
189 if(isset($uri['pass'])) $this->pass = $uri['pass'];
191 // proxy setup
192 if($this->useProxyForUrl($url)){
193 $request_url = $url;
194 $server = $this->proxy_host;
195 $port = $this->proxy_port;
196 if (empty($port)) $port = 8080;
197 $use_tls = $this->proxy_ssl;
198 }else{
199 $request_url = $path;
200 $port = $uriPort ?: ($uri['scheme'] == 'https' ? 443 : 80);
201 $use_tls = ($uri['scheme'] == 'https');
204 // add SSL stream prefix if needed - needs SSL support in PHP
205 if($use_tls) {
206 if(!in_array('ssl', stream_get_transports())) {
207 $this->status = -200;
208 $this->error = 'This PHP version does not support SSL - cannot connect to server';
210 $server = 'ssl://'.$server;
213 // prepare headers
214 $headers = $this->headers;
215 $headers['Host'] = $uri['host']
216 . ($uriPort ? ':' . $uriPort : '');
217 $headers['User-Agent'] = $this->agent;
218 $headers['Referer'] = $this->referer;
220 if($method == 'POST'){
221 if(is_array($data)){
222 if (empty($headers['Content-Type'])) {
223 $headers['Content-Type'] = null;
225 switch ($headers['Content-Type']) {
226 case 'multipart/form-data':
227 $headers['Content-Type'] = 'multipart/form-data; boundary=' . $this->boundary;
228 $data = $this->postMultipartEncode($data);
229 break;
230 default:
231 $headers['Content-Type'] = 'application/x-www-form-urlencoded';
232 $data = $this->postEncode($data);
235 }elseif($method == 'GET'){
236 $data = ''; //no data allowed on GET requests
239 $contentlength = strlen($data);
240 if($contentlength) {
241 $headers['Content-Length'] = $contentlength;
244 if($this->user) {
245 $headers['Authorization'] = 'Basic '.base64_encode($this->user.':'.$this->pass);
247 if($this->proxy_user) {
248 $headers['Proxy-Authorization'] = 'Basic '.base64_encode($this->proxy_user.':'.$this->proxy_pass);
251 // already connected?
252 $connectionId = $this->uniqueConnectionId($server,$port);
253 $this->debug('connection pool', self::$connections);
254 $socket = null;
255 if (isset(self::$connections[$connectionId])) {
256 $this->debug('reusing connection', $connectionId);
257 $socket = self::$connections[$connectionId];
259 if (is_null($socket) || feof($socket)) {
260 $this->debug('opening connection', $connectionId);
261 // open socket
262 $socket = @fsockopen($server,$port,$errno, $errstr, $this->timeout);
263 if (!$socket){
264 $this->status = -100;
265 $this->error = "Could not connect to $server:$port\n$errstr ($errno)";
266 return false;
269 // try to establish a CONNECT tunnel for SSL
270 try {
271 if($this->ssltunnel($socket, $request_url)){
272 // no keep alive for tunnels
273 $this->keep_alive = false;
274 // tunnel is authed already
275 if(isset($headers['Proxy-Authentication'])) unset($headers['Proxy-Authentication']);
277 } catch (HTTPClientException $e) {
278 $this->status = $e->getCode();
279 $this->error = $e->getMessage();
280 fclose($socket);
281 return false;
284 // keep alive?
285 if ($this->keep_alive) {
286 self::$connections[$connectionId] = $socket;
287 } else {
288 unset(self::$connections[$connectionId]);
292 if ($this->keep_alive && !$this->useProxyForUrl($request_url)) {
293 // RFC 2068, section 19.7.1: A client MUST NOT send the Keep-Alive
294 // connection token to a proxy server. We still do keep the connection the
295 // proxy alive (well except for CONNECT tunnels)
296 $headers['Connection'] = 'Keep-Alive';
297 } else {
298 $headers['Connection'] = 'Close';
301 try {
302 //set non-blocking
303 stream_set_blocking($socket, 0);
305 // build request
306 $request = "$method $request_url HTTP/".$this->http.HTTP_NL;
307 $request .= $this->buildHeaders($headers);
308 $request .= $this->getCookies();
309 $request .= HTTP_NL;
310 $request .= $data;
312 $this->debug('request',$request);
313 $this->sendData($socket, $request, 'request');
315 // read headers from socket
316 $r_headers = '';
318 $r_line = $this->readLine($socket, 'headers');
319 $r_headers .= $r_line;
320 }while($r_line != "\r\n" && $r_line != "\n");
322 $this->debug('response headers',$r_headers);
324 // check if expected body size exceeds allowance
325 if($this->max_bodysize && preg_match('/\r?\nContent-Length:\s*(\d+)\r?\n/i',$r_headers,$match)){
326 if($match[1] > $this->max_bodysize){
327 if ($this->max_bodysize_abort)
328 throw new HTTPClientException('Reported content length exceeds allowed response size');
329 else
330 $this->error = 'Reported content length exceeds allowed response size';
334 // get Status
335 if (!preg_match('/^HTTP\/(\d\.\d)\s*(\d+).*?\n/s', $r_headers, $m))
336 throw new HTTPClientException('Server returned bad answer '.$r_headers);
338 $this->status = $m[2];
340 // handle headers and cookies
341 $this->resp_headers = $this->parseHeaders($r_headers);
342 if(isset($this->resp_headers['set-cookie'])){
343 foreach ((array) $this->resp_headers['set-cookie'] as $cookie){
344 list($cookie) = sexplode(';', $cookie, 2, '');
345 list($key, $val) = sexplode('=', $cookie, 2, '');
346 $key = trim($key);
347 if($val == 'deleted'){
348 if(isset($this->cookies[$key])){
349 unset($this->cookies[$key]);
351 }elseif($key){
352 $this->cookies[$key] = $val;
357 $this->debug('Object headers',$this->resp_headers);
359 // check server status code to follow redirect
360 if(in_array($this->status, [301, 302, 303, 307, 308])){
361 if (empty($this->resp_headers['location'])){
362 throw new HTTPClientException('Redirect but no Location Header found');
363 }elseif($this->redirect_count == $this->max_redirect){
364 throw new HTTPClientException('Maximum number of redirects exceeded');
365 }else{
366 // close the connection because we don't handle content retrieval here
367 // that's the easiest way to clean up the connection
368 fclose($socket);
369 unset(self::$connections[$connectionId]);
371 $this->redirect_count++;
372 $this->referer = $url;
373 // handle non-RFC-compliant relative redirects
374 if (!preg_match('/^http/i', $this->resp_headers['location'])){
375 if($this->resp_headers['location'][0] != '/'){
376 $this->resp_headers['location'] = $uri['scheme'].'://'.$uri['host'].':'.$uriPort.
377 dirname($path).'/'.$this->resp_headers['location'];
378 }else{
379 $this->resp_headers['location'] = $uri['scheme'].'://'.$uri['host'].':'.$uriPort.
380 $this->resp_headers['location'];
383 if($this->status == 307 || $this->status == 308) {
384 // perform redirected request, same method as before (required by RFC)
385 return $this->sendRequest($this->resp_headers['location'],$unencodedData,$method);
386 }else{
387 // perform redirected request, always via GET (required by RFC)
388 return $this->sendRequest($this->resp_headers['location'],array(),'GET');
393 // check if headers are as expected
394 if($this->header_regexp && !preg_match($this->header_regexp,$r_headers))
395 throw new HTTPClientException('The received headers did not match the given regexp');
397 //read body (with chunked encoding if needed)
398 $r_body = '';
401 isset($this->resp_headers['transfer-encoding']) &&
402 $this->resp_headers['transfer-encoding'] == 'chunked'
403 ) || (
404 isset($this->resp_headers['transfer-coding']) &&
405 $this->resp_headers['transfer-coding'] == 'chunked'
408 $abort = false;
409 do {
410 $chunk_size = '';
411 while (preg_match('/^[a-zA-Z0-9]?$/',$byte=$this->readData($socket,1,'chunk'))){
412 // read chunksize until \r
413 $chunk_size .= $byte;
414 if (strlen($chunk_size) > 128) // set an abritrary limit on the size of chunks
415 throw new HTTPClientException('Allowed response size exceeded');
417 $this->readLine($socket, 'chunk'); // readtrailing \n
418 $chunk_size = hexdec($chunk_size);
420 if($this->max_bodysize && $chunk_size+strlen($r_body) > $this->max_bodysize){
421 if ($this->max_bodysize_abort)
422 throw new HTTPClientException('Allowed response size exceeded');
423 $this->error = 'Allowed response size exceeded';
424 $chunk_size = $this->max_bodysize - strlen($r_body);
425 $abort = true;
428 if ($chunk_size > 0) {
429 $r_body .= $this->readData($socket, $chunk_size, 'chunk');
430 $this->readData($socket, 2, 'chunk'); // read trailing \r\n
432 } while ($chunk_size && !$abort);
433 }elseif(isset($this->resp_headers['content-length']) && !isset($this->resp_headers['transfer-encoding'])){
434 /* RFC 2616
435 * If a message is received with both a Transfer-Encoding header field and a Content-Length
436 * header field, the latter MUST be ignored.
439 // read up to the content-length or max_bodysize
440 // for keep alive we need to read the whole message to clean up the socket for the next read
442 !$this->keep_alive &&
443 $this->max_bodysize &&
444 $this->max_bodysize < $this->resp_headers['content-length']
446 $length = $this->max_bodysize + 1;
447 }else{
448 $length = $this->resp_headers['content-length'];
451 $r_body = $this->readData($socket, $length, 'response (content-length limited)', true);
452 }elseif( !isset($this->resp_headers['transfer-encoding']) && $this->max_bodysize && !$this->keep_alive){
453 $r_body = $this->readData($socket, $this->max_bodysize+1, 'response (content-length limited)', true);
454 } elseif ((int)$this->status === 204) {
455 // request has no content
456 } else{
457 // read entire socket
458 while (!feof($socket)) {
459 $r_body .= $this->readData($socket, 4096, 'response (unlimited)', true);
463 // recheck body size, we might have read max_bodysize+1 or even the whole body, so we abort late here
464 if($this->max_bodysize){
465 if(strlen($r_body) > $this->max_bodysize){
466 if ($this->max_bodysize_abort) {
467 throw new HTTPClientException('Allowed response size exceeded');
468 } else {
469 $this->error = 'Allowed response size exceeded';
474 } catch (HTTPClientException $err) {
475 $this->error = $err->getMessage();
476 if ($err->getCode())
477 $this->status = $err->getCode();
478 unset(self::$connections[$connectionId]);
479 fclose($socket);
480 return false;
483 if (!$this->keep_alive ||
484 (isset($this->resp_headers['connection']) && $this->resp_headers['connection'] == 'Close')) {
485 // close socket
486 fclose($socket);
487 unset(self::$connections[$connectionId]);
490 // decode gzip if needed
491 if(isset($this->resp_headers['content-encoding']) &&
492 $this->resp_headers['content-encoding'] == 'gzip' &&
493 strlen($r_body) > 10 && substr($r_body,0,3)=="\x1f\x8b\x08"){
494 $this->resp_body = @gzinflate(substr($r_body, 10));
495 if($this->resp_body === false){
496 $this->error = 'Failed to decompress gzip encoded content';
497 $this->resp_body = $r_body;
499 }else{
500 $this->resp_body = $r_body;
503 $this->debug('response body',$this->resp_body);
504 $this->redirect_count = 0;
505 return true;
509 * Tries to establish a CONNECT tunnel via Proxy
511 * Protocol, Servername and Port will be stripped from the request URL when a successful CONNECT happened
513 * @param resource &$socket
514 * @param string &$requesturl
515 * @throws HTTPClientException when a tunnel is needed but could not be established
516 * @return bool true if a tunnel was established
518 protected function ssltunnel(&$socket, &$requesturl){
519 if(!$this->useProxyForUrl($requesturl)) return false;
520 $requestinfo = parse_url($requesturl);
521 if($requestinfo['scheme'] != 'https') return false;
522 if(empty($requestinfo['port'])) $requestinfo['port'] = 443;
524 // build request
525 $request = "CONNECT {$requestinfo['host']}:{$requestinfo['port']} HTTP/1.0".HTTP_NL;
526 $request .= "Host: {$requestinfo['host']}".HTTP_NL;
527 if($this->proxy_user) {
528 $request .= 'Proxy-Authorization: Basic '.base64_encode($this->proxy_user.':'.$this->proxy_pass).HTTP_NL;
530 $request .= HTTP_NL;
532 $this->debug('SSL Tunnel CONNECT',$request);
533 $this->sendData($socket, $request, 'SSL Tunnel CONNECT');
535 // read headers from socket
536 $r_headers = '';
538 $r_line = $this->readLine($socket, 'headers');
539 $r_headers .= $r_line;
540 }while($r_line != "\r\n" && $r_line != "\n");
542 $this->debug('SSL Tunnel Response',$r_headers);
543 if(preg_match('/^HTTP\/1\.[01] 200/i',$r_headers)){
544 // set correct peer name for verification (enabled since PHP 5.6)
545 stream_context_set_option($socket, 'ssl', 'peer_name', $requestinfo['host']);
547 // SSLv3 is broken, use only TLS connections.
548 // @link https://bugs.php.net/69195
549 if (PHP_VERSION_ID >= 50600 && PHP_VERSION_ID <= 50606) {
550 $cryptoMethod = STREAM_CRYPTO_METHOD_TLS_CLIENT;
551 } else {
552 // actually means neither SSLv2 nor SSLv3
553 $cryptoMethod = STREAM_CRYPTO_METHOD_SSLv23_CLIENT;
556 if (@stream_socket_enable_crypto($socket, true, $cryptoMethod)) {
557 $requesturl = $requestinfo['path'].
558 (!empty($requestinfo['query'])?'?'.$requestinfo['query']:'');
559 return true;
562 throw new HTTPClientException(
563 'Failed to set up crypto for secure connection to '.$requestinfo['host'], -151
567 throw new HTTPClientException('Failed to establish secure proxy connection', -150);
571 * Safely write data to a socket
573 * @param resource $socket An open socket handle
574 * @param string $data The data to write
575 * @param string $message Description of what is being read
576 * @throws HTTPClientException
578 * @author Tom N Harris <tnharris@whoopdedo.org>
580 protected function sendData($socket, $data, $message) {
581 // send request
582 $towrite = strlen($data);
583 $written = 0;
584 while($written < $towrite){
585 // check timeout
586 $time_used = microtime(true) - $this->start;
587 if($time_used > $this->timeout)
588 throw new HTTPClientException(sprintf('Timeout while sending %s (%.3fs)',$message, $time_used), -100);
589 if(feof($socket))
590 throw new HTTPClientException("Socket disconnected while writing $message");
592 // select parameters
593 $sel_r = null;
594 $sel_w = array($socket);
595 $sel_e = null;
596 // wait for stream ready or timeout (1sec)
597 if(@stream_select($sel_r,$sel_w,$sel_e,1) === false){
598 usleep(1000);
599 continue;
602 // write to stream
603 $nbytes = fwrite($socket, substr($data,$written,4096));
604 if($nbytes === false)
605 throw new HTTPClientException("Failed writing to socket while sending $message", -100);
606 $written += $nbytes;
611 * Safely read data from a socket
613 * Reads up to a given number of bytes or throws an exception if the
614 * response times out or ends prematurely.
616 * @param resource $socket An open socket handle in non-blocking mode
617 * @param int $nbytes Number of bytes to read
618 * @param string $message Description of what is being read
619 * @param bool $ignore_eof End-of-file is not an error if this is set
620 * @throws HTTPClientException
621 * @return string
623 * @author Tom N Harris <tnharris@whoopdedo.org>
625 protected function readData($socket, $nbytes, $message, $ignore_eof = false) {
626 $r_data = '';
627 // Does not return immediately so timeout and eof can be checked
628 if ($nbytes < 0) $nbytes = 0;
629 $to_read = $nbytes;
630 do {
631 $time_used = microtime(true) - $this->start;
632 if ($time_used > $this->timeout)
633 throw new HTTPClientException(
634 sprintf('Timeout while reading %s after %d bytes (%.3fs)', $message,
635 strlen($r_data), $time_used), -100);
636 if(feof($socket)) {
637 if(!$ignore_eof)
638 throw new HTTPClientException("Premature End of File (socket) while reading $message");
639 break;
642 if ($to_read > 0) {
643 // select parameters
644 $sel_r = array($socket);
645 $sel_w = null;
646 $sel_e = null;
647 // wait for stream ready or timeout (1sec)
648 if(@stream_select($sel_r,$sel_w,$sel_e,1) === false){
649 usleep(1000);
650 continue;
653 $bytes = fread($socket, $to_read);
654 if($bytes === false)
655 throw new HTTPClientException("Failed reading from socket while reading $message", -100);
656 $r_data .= $bytes;
657 $to_read -= strlen($bytes);
659 } while ($to_read > 0 && strlen($r_data) < $nbytes);
660 return $r_data;
664 * Safely read a \n-terminated line from a socket
666 * Always returns a complete line, including the terminating \n.
668 * @param resource $socket An open socket handle in non-blocking mode
669 * @param string $message Description of what is being read
670 * @throws HTTPClientException
671 * @return string
673 * @author Tom N Harris <tnharris@whoopdedo.org>
675 protected function readLine($socket, $message) {
676 $r_data = '';
677 do {
678 $time_used = microtime(true) - $this->start;
679 if ($time_used > $this->timeout)
680 throw new HTTPClientException(
681 sprintf('Timeout while reading %s (%.3fs) >%s<', $message, $time_used, $r_data),
682 -100);
683 if(feof($socket))
684 throw new HTTPClientException("Premature End of File (socket) while reading $message");
686 // select parameters
687 $sel_r = array($socket);
688 $sel_w = null;
689 $sel_e = null;
690 // wait for stream ready or timeout (1sec)
691 if(@stream_select($sel_r,$sel_w,$sel_e,1) === false){
692 usleep(1000);
693 continue;
696 $r_data = fgets($socket, 1024);
697 } while (!preg_match('/\n$/',$r_data));
698 return $r_data;
702 * print debug info
704 * Uses _debug_text or _debug_html depending on the SAPI name
706 * @author Andreas Gohr <andi@splitbrain.org>
708 * @param string $info
709 * @param mixed $var
711 protected function debug($info,$var=null){
712 if(!$this->debug) return;
713 if(php_sapi_name() == 'cli'){
714 $this->debugText($info, $var);
715 }else{
716 $this->debugHtml($info, $var);
721 * print debug info as HTML
723 * @param string $info
724 * @param mixed $var
726 protected function debugHtml($info, $var=null){
727 print '<b>'.$info.'</b> '.(microtime(true) - $this->start).'s<br />';
728 if(!is_null($var)){
729 ob_start();
730 print_r($var);
731 $content = htmlspecialchars(ob_get_contents());
732 ob_end_clean();
733 print '<pre>'.$content.'</pre>';
738 * prints debug info as plain text
740 * @param string $info
741 * @param mixed $var
743 protected function debugText($info, $var=null){
744 print '*'.$info.'* '.(microtime(true) - $this->start)."s\n";
745 if(!is_null($var)) print_r($var);
746 print "\n-----------------------------------------------\n";
750 * convert given header string to Header array
752 * All Keys are lowercased.
754 * @author Andreas Gohr <andi@splitbrain.org>
756 * @param string $string
757 * @return array
759 protected function parseHeaders($string){
760 $headers = array();
761 $lines = explode("\n",$string);
762 array_shift($lines); //skip first line (status)
763 foreach($lines as $line){
764 list($key, $val) = sexplode(':', $line, 2, '');
765 $key = trim($key);
766 $val = trim($val);
767 $key = strtolower($key);
768 if(!$key) continue;
769 if(isset($headers[$key])){
770 if(is_array($headers[$key])){
771 $headers[$key][] = $val;
772 }else{
773 $headers[$key] = array($headers[$key],$val);
775 }else{
776 $headers[$key] = $val;
779 return $headers;
783 * convert given header array to header string
785 * @author Andreas Gohr <andi@splitbrain.org>
787 * @param array $headers
788 * @return string
790 protected function buildHeaders($headers){
791 $string = '';
792 foreach($headers as $key => $value){
793 if($value === '') continue;
794 $string .= $key.': '.$value.HTTP_NL;
796 return $string;
800 * get cookies as http header string
802 * @author Andreas Goetz <cpuidle@gmx.de>
804 * @return string
806 protected function getCookies(){
807 $headers = '';
808 foreach ($this->cookies as $key => $val){
809 $headers .= "$key=$val; ";
811 $headers = substr($headers, 0, -2);
812 if ($headers) $headers = "Cookie: $headers".HTTP_NL;
813 return $headers;
817 * Encode data for posting
819 * @author Andreas Gohr <andi@splitbrain.org>
821 * @param array $data
822 * @return string
824 protected function postEncode($data){
825 return http_build_query($data,'','&');
829 * Encode data for posting using multipart encoding
831 * @fixme use of urlencode might be wrong here
832 * @author Andreas Gohr <andi@splitbrain.org>
834 * @param array $data
835 * @return string
837 protected function postMultipartEncode($data){
838 $boundary = '--'.$this->boundary;
839 $out = '';
840 foreach($data as $key => $val){
841 $out .= $boundary.HTTP_NL;
842 if(!is_array($val)){
843 $out .= 'Content-Disposition: form-data; name="'.urlencode($key).'"'.HTTP_NL;
844 $out .= HTTP_NL; // end of headers
845 $out .= $val;
846 $out .= HTTP_NL;
847 }else{
848 $out .= 'Content-Disposition: form-data; name="'.urlencode($key).'"';
849 if($val['filename']) $out .= '; filename="'.urlencode($val['filename']).'"';
850 $out .= HTTP_NL;
851 if($val['mimetype']) $out .= 'Content-Type: '.$val['mimetype'].HTTP_NL;
852 $out .= HTTP_NL; // end of headers
853 $out .= $val['body'];
854 $out .= HTTP_NL;
857 $out .= "$boundary--".HTTP_NL;
858 return $out;
862 * Generates a unique identifier for a connection.
864 * @param string $server
865 * @param string $port
866 * @return string unique identifier
868 protected function uniqueConnectionId($server, $port) {
869 return "$server:$port";
873 * Should the Proxy be used for the given URL?
875 * Checks the exceptions
877 * @param string $url
878 * @return bool
880 protected function useProxyForUrl($url) {
881 return $this->proxy_host && (!$this->proxy_except || !preg_match('/' . $this->proxy_except . '/i', $url));