diff options
Diffstat (limited to 'inc/HTTP/HTTPClient.php')
-rw-r--r-- | inc/HTTP/HTTPClient.php | 539 |
1 files changed, 281 insertions, 258 deletions
diff --git a/inc/HTTP/HTTPClient.php b/inc/HTTP/HTTPClient.php index 05383d33e..e92edda02 100644 --- a/inc/HTTP/HTTPClient.php +++ b/inc/HTTP/HTTPClient.php @@ -2,7 +2,7 @@ namespace dokuwiki\HTTP; -define('HTTP_NL',"\r\n"); +define('HTTP_NL', "\r\n"); /** @@ -17,28 +17,29 @@ define('HTTP_NL',"\r\n"); * @author Andreas Gohr <andi@splitbrain.org> * @author Tobias Sarnowski <sarnowski@new-thoughts.org> */ -class HTTPClient { +class HTTPClient +{ //set these if you like public $agent; // User agent - public $http; // HTTP version defaults to 1.0 - public $timeout; // read timeout (seconds) - public $cookies; - public $referer; - public $max_redirect; - public $max_bodysize; + public $http = '1.0'; // HTTP version defaults to 1.0 + public $timeout = 15; // read timeout (seconds) + public $cookies = []; + public $referer = ''; + public $max_redirect = 3; + public $max_bodysize = 0; public $max_bodysize_abort = true; // if set, abort if the response body is bigger than max_bodysize - public $header_regexp; // if set this RE must match against the headers, else abort - public $headers; - public $debug; + public $header_regexp = ''; // if set this RE must match against the headers, else abort + public $headers = []; + public $debug = false; public $start = 0.0; // for timings public $keep_alive = true; // keep alive rocks // don't set these, read on error public $error; - public $redirect_count; + public $redirect_count = 0; // read these after a successful request - public $status; + public $status = 0; public $resp_body; public $resp_headers; @@ -55,7 +56,7 @@ class HTTPClient { public $proxy_except; // regexp of URLs to exclude from proxy // list of kept alive connections - protected static $connections = array(); + protected static $connections = []; // what we use as boundary on multipart/form-data posts protected $boundary = '---DokuWikiHTTPClient--4523452351'; @@ -65,21 +66,11 @@ class HTTPClient { * * @author Andreas Gohr <andi@splitbrain.org> */ - public function __construct(){ - $this->agent = 'Mozilla/4.0 (compatible; DokuWiki HTTP Client; '.PHP_OS.')'; - $this->timeout = 15; - $this->cookies = array(); - $this->referer = ''; - $this->max_redirect = 3; - $this->redirect_count = 0; - $this->status = 0; - $this->headers = array(); - $this->http = '1.0'; - $this->debug = false; - $this->max_bodysize = 0; - $this->header_regexp= ''; - if(extension_loaded('zlib')) $this->headers['Accept-encoding'] = 'gzip'; - $this->headers['Accept'] = 'text/xml,application/xml,application/xhtml+xml,'. + public function __construct() + { + $this->agent = 'Mozilla/4.0 (compatible; DokuWiki HTTP Client; ' . PHP_OS . ')'; + if (extension_loaded('zlib')) $this->headers['Accept-encoding'] = 'gzip'; + $this->headers['Accept'] = 'text/xml,application/xml,application/xhtml+xml,' . 'text/html,text/plain,image/png,image/jpeg,image/gif,*/*'; $this->headers['Accept-Language'] = 'en-us'; } @@ -90,16 +81,17 @@ class HTTPClient { * * Returns the wanted page or false on an error; * - * @param string $url The URL to fetch - * @param bool $sloppy304 Return body on 304 not modified + * @param string $url The URL to fetch + * @param bool $sloppy304 Return body on 304 not modified * @return false|string response body, false on error * * @author Andreas Gohr <andi@splitbrain.org> */ - public function get($url,$sloppy304=false){ - if(!$this->sendRequest($url)) return false; - if($this->status == 304 && $sloppy304) return $this->resp_body; - if($this->status < 200 || $this->status > 206) return false; + public function get($url, $sloppy304 = false) + { + if (!$this->sendRequest($url)) return false; + if ($this->status == 304 && $sloppy304) return $this->resp_body; + if ($this->status < 200 || $this->status > 206) return false; return $this->resp_body; } @@ -111,21 +103,22 @@ class HTTPClient { * This is a convenience wrapper around get(). The given parameters * will be correctly encoded and added to the given base URL. * - * @param string $url The URL to fetch - * @param array $data Associative array of parameters - * @param bool $sloppy304 Return body on 304 not modified + * @param string $url The URL to fetch + * @param array $data Associative array of parameters + * @param bool $sloppy304 Return body on 304 not modified * @return false|string response body, false on error * * @author Andreas Gohr <andi@splitbrain.org> */ - public function dget($url,$data,$sloppy304=false){ - if(strpos($url,'?')){ + public function dget($url, $data, $sloppy304 = false) + { + if (strpos($url, '?')) { $url .= '&'; - }else{ + } else { $url .= '?'; } $url .= $this->postEncode($data); - return $this->get($url,$sloppy304); + return $this->get($url, $sloppy304); } /** @@ -133,14 +126,15 @@ class HTTPClient { * * Returns the resulting page or false on an error; * - * @param string $url The URL to fetch - * @param array $data Associative array of parameters + * @param string $url The URL to fetch + * @param array $data Associative array of parameters * @return false|string response body, false on error * @author Andreas Gohr <andi@splitbrain.org> */ - public function post($url,$data){ - if(!$this->sendRequest($url,$data,'POST')) return false; - if($this->status < 200 || $this->status > 206) return false; + public function post($url, $data) + { + if (!$this->sendRequest($url, $data, 'POST')) return false; + if ($this->status < 200 || $this->status > 206) return false; return $this->resp_body; } @@ -153,103 +147,104 @@ class HTTPClient { * Post data should be passed as associative array. When passed as string it will be * sent as is. You will need to setup your own Content-Type header then. * - * @param string $url - the complete URL - * @param mixed $data - the post data either as array or raw data - * @param string $method - HTTP Method usually GET or POST. + * @param string $url - the complete URL + * @param mixed $data - the post data either as array or raw data + * @param string $method - HTTP Method usually GET or POST. * @return bool - true on success * * @author Andreas Goetz <cpuidle@gmx.de> * @author Andreas Gohr <andi@splitbrain.org> */ - public function sendRequest($url,$data='',$method='GET'){ - $this->start = microtime(true); - $this->error = ''; + public function sendRequest($url, $data = '', $method = 'GET') + { + $this->start = microtime(true); + $this->error = ''; $this->status = 0; $this->resp_body = ''; - $this->resp_headers = array(); + $this->resp_headers = []; // save unencoded data for recursive call $unencodedData = $data; // don't accept gzip if truncated bodies might occur - if($this->max_bodysize && + if ( + $this->max_bodysize && !$this->max_bodysize_abort && isset($this->headers['Accept-encoding']) && - $this->headers['Accept-encoding'] == 'gzip'){ + $this->headers['Accept-encoding'] == 'gzip' + ) { unset($this->headers['Accept-encoding']); } // parse URL into bits $uri = parse_url($url); $server = $uri['host']; - $path = !empty($uri['path']) ? $uri['path'] : '/'; - $uriPort = !empty($uri['port']) ? $uri['port'] : null; - if(!empty($uri['query'])) $path .= '?'.$uri['query']; - if(isset($uri['user'])) $this->user = $uri['user']; - if(isset($uri['pass'])) $this->pass = $uri['pass']; + $path = empty($uri['path']) ? '/' : $uri['path']; + $uriPort = empty($uri['port']) ? null : $uri['port']; + if (!empty($uri['query'])) $path .= '?' . $uri['query']; + if (isset($uri['user'])) $this->user = $uri['user']; + if (isset($uri['pass'])) $this->pass = $uri['pass']; // proxy setup - if($this->useProxyForUrl($url)){ + if ($this->useProxyForUrl($url)) { $request_url = $url; - $server = $this->proxy_host; - $port = $this->proxy_port; + $server = $this->proxy_host; + $port = $this->proxy_port; if (empty($port)) $port = 8080; - $use_tls = $this->proxy_ssl; - }else{ + $use_tls = $this->proxy_ssl; + } else { $request_url = $path; $port = $uriPort ?: ($uri['scheme'] == 'https' ? 443 : 80); - $use_tls = ($uri['scheme'] == 'https'); + $use_tls = ($uri['scheme'] == 'https'); } // add SSL stream prefix if needed - needs SSL support in PHP - if($use_tls) { - if(!in_array('ssl', stream_get_transports())) { + if ($use_tls) { + if (!in_array('ssl', stream_get_transports())) { $this->status = -200; $this->error = 'This PHP version does not support SSL - cannot connect to server'; } - $server = 'ssl://'.$server; + $server = 'ssl://' . $server; } // prepare headers - $headers = $this->headers; - $headers['Host'] = $uri['host'] + $headers = $this->headers; + $headers['Host'] = $uri['host'] . ($uriPort ? ':' . $uriPort : ''); $headers['User-Agent'] = $this->agent; - $headers['Referer'] = $this->referer; + $headers['Referer'] = $this->referer; - if($method == 'POST'){ - if(is_array($data)){ + if ($method == 'POST') { + if (is_array($data)) { if (empty($headers['Content-Type'])) { $headers['Content-Type'] = null; } - switch ($headers['Content-Type']) { - case 'multipart/form-data': - $headers['Content-Type'] = 'multipart/form-data; boundary=' . $this->boundary; - $data = $this->postMultipartEncode($data); - break; - default: - $headers['Content-Type'] = 'application/x-www-form-urlencoded'; - $data = $this->postEncode($data); + if ($headers['Content-Type'] == 'multipart/form-data') { + $headers['Content-Type'] = 'multipart/form-data; boundary=' . $this->boundary; + $data = $this->postMultipartEncode($data); + } else { + $headers['Content-Type'] = 'application/x-www-form-urlencoded'; + $data = $this->postEncode($data); } } - }elseif($method == 'GET'){ + } elseif ($method == 'GET') { $data = ''; //no data allowed on GET requests } $contentlength = strlen($data); - if($contentlength) { + if ($contentlength) { $headers['Content-Length'] = $contentlength; } - if($this->user) { - $headers['Authorization'] = 'Basic '.base64_encode($this->user.':'.$this->pass); + if ($this->user) { + $headers['Authorization'] = 'Basic ' . base64_encode($this->user . ':' . $this->pass); } - if($this->proxy_user) { - $headers['Proxy-Authorization'] = 'Basic '.base64_encode($this->proxy_user.':'.$this->proxy_pass); + if ($this->proxy_user) { + $headers['Proxy-Authorization'] = 'Basic ' . base64_encode($this->proxy_user . ':' . $this->proxy_pass); } // already connected? - $connectionId = $this->uniqueConnectionId($server,$port); + $connectionId = $this->uniqueConnectionId($server, $port); $this->debug('connection pool', self::$connections); $socket = null; if (isset(self::$connections[$connectionId])) { @@ -259,8 +254,8 @@ class HTTPClient { if (is_null($socket) || feof($socket)) { $this->debug('opening connection', $connectionId); // open socket - $socket = @fsockopen($server,$port,$errno, $errstr, $this->timeout); - if (!$socket){ + $socket = @fsockopen($server, $port, $errno, $errstr, $this->timeout); + if (!$socket) { $this->status = -100; $this->error = "Could not connect to $server:$port\n$errstr ($errno)"; return false; @@ -268,11 +263,11 @@ class HTTPClient { // try to establish a CONNECT tunnel for SSL try { - if($this->ssltunnel($socket, $request_url)){ + if ($this->ssltunnel($socket, $request_url)) { // no keep alive for tunnels $this->keep_alive = false; // tunnel is authed already - if(isset($headers['Proxy-Authentication'])) unset($headers['Proxy-Authentication']); + if (isset($headers['Proxy-Authentication'])) unset($headers['Proxy-Authentication']); } } catch (HTTPClientException $e) { $this->status = $e->getCode(); @@ -303,66 +298,65 @@ class HTTPClient { stream_set_blocking($socket, 0); // build request - $request = "$method $request_url HTTP/".$this->http.HTTP_NL; + $request = "$method $request_url HTTP/" . $this->http . HTTP_NL; $request .= $this->buildHeaders($headers); $request .= $this->getCookies(); $request .= HTTP_NL; $request .= $data; - $this->debug('request',$request); + $this->debug('request', $request); $this->sendData($socket, $request, 'request'); // read headers from socket $r_headers = ''; - do{ + do { $r_line = $this->readLine($socket, 'headers'); $r_headers .= $r_line; - }while($r_line != "\r\n" && $r_line != "\n"); + } while ($r_line != "\r\n" && $r_line != "\n"); - $this->debug('response headers',$r_headers); + $this->debug('response headers', $r_headers); // check if expected body size exceeds allowance - if($this->max_bodysize && preg_match('/\r?\nContent-Length:\s*(\d+)\r?\n/i',$r_headers,$match)){ - if($match[1] > $this->max_bodysize){ + if ($this->max_bodysize && preg_match('/\r?\nContent-Length:\s*(\d+)\r?\n/i', $r_headers, $match)) { + if ($match[1] > $this->max_bodysize) { if ($this->max_bodysize_abort) throw new HTTPClientException('Reported content length exceeds allowed response size'); - else - $this->error = 'Reported content length exceeds allowed response size'; + else $this->error = 'Reported content length exceeds allowed response size'; } } // get Status if (!preg_match('/^HTTP\/(\d\.\d)\s*(\d+).*?\n/s', $r_headers, $m)) - throw new HTTPClientException('Server returned bad answer '.$r_headers); + throw new HTTPClientException('Server returned bad answer ' . $r_headers); $this->status = $m[2]; // handle headers and cookies $this->resp_headers = $this->parseHeaders($r_headers); - if(isset($this->resp_headers['set-cookie'])){ - foreach ((array) $this->resp_headers['set-cookie'] as $cookie){ - list($cookie) = sexplode(';', $cookie, 2, ''); - list($key, $val) = sexplode('=', $cookie, 2, ''); + if (isset($this->resp_headers['set-cookie'])) { + foreach ((array)$this->resp_headers['set-cookie'] as $cookie) { + [$cookie] = sexplode(';', $cookie, 2, ''); + [$key, $val] = sexplode('=', $cookie, 2, ''); $key = trim($key); - if($val == 'deleted'){ - if(isset($this->cookies[$key])){ + if ($val == 'deleted') { + if (isset($this->cookies[$key])) { unset($this->cookies[$key]); } - }elseif($key){ + } elseif ($key) { $this->cookies[$key] = $val; } } } - $this->debug('Object headers',$this->resp_headers); + $this->debug('Object headers', $this->resp_headers); // check server status code to follow redirect - if(in_array($this->status, [301, 302, 303, 307, 308])){ - if (empty($this->resp_headers['location'])){ + if (in_array($this->status, [301, 302, 303, 307, 308])) { + if (empty($this->resp_headers['location'])) { throw new HTTPClientException('Redirect but no Location Header found'); - }elseif($this->redirect_count == $this->max_redirect){ + } elseif ($this->redirect_count == $this->max_redirect) { throw new HTTPClientException('Maximum number of redirects exceeded'); - }else{ + } else { // close the connection because we don't handle content retrieval here // that's the easiest way to clean up the connection fclose($socket); @@ -371,32 +365,32 @@ class HTTPClient { $this->redirect_count++; $this->referer = $url; // handle non-RFC-compliant relative redirects - if (!preg_match('/^http/i', $this->resp_headers['location'])){ - if($this->resp_headers['location'][0] != '/'){ - $this->resp_headers['location'] = $uri['scheme'].'://'.$uri['host'].':'.$uriPort. - dirname($path).'/'.$this->resp_headers['location']; - }else{ - $this->resp_headers['location'] = $uri['scheme'].'://'.$uri['host'].':'.$uriPort. + if (!preg_match('/^http/i', $this->resp_headers['location'])) { + if ($this->resp_headers['location'][0] != '/') { + $this->resp_headers['location'] = $uri['scheme'] . '://' . $uri['host'] . ':' . $uriPort . + dirname($path) . '/' . $this->resp_headers['location']; + } else { + $this->resp_headers['location'] = $uri['scheme'] . '://' . $uri['host'] . ':' . $uriPort . $this->resp_headers['location']; } } - if($this->status == 307 || $this->status == 308) { + if ($this->status == 307 || $this->status == 308) { // perform redirected request, same method as before (required by RFC) - return $this->sendRequest($this->resp_headers['location'],$unencodedData,$method); - }else{ + return $this->sendRequest($this->resp_headers['location'], $unencodedData, $method); + } else { // perform redirected request, always via GET (required by RFC) - return $this->sendRequest($this->resp_headers['location'],array(),'GET'); + return $this->sendRequest($this->resp_headers['location'], [], 'GET'); } } } // check if headers are as expected - if($this->header_regexp && !preg_match($this->header_regexp,$r_headers)) + if ($this->header_regexp && !preg_match($this->header_regexp, $r_headers)) throw new HTTPClientException('The received headers did not match the given regexp'); //read body (with chunked encoding if needed) - $r_body = ''; - if( + $r_body = ''; + if ( ( isset($this->resp_headers['transfer-encoding']) && $this->resp_headers['transfer-encoding'] == 'chunked' @@ -408,7 +402,7 @@ class HTTPClient { $abort = false; do { $chunk_size = ''; - while (preg_match('/^[a-zA-Z0-9]?$/',$byte=$this->readData($socket,1,'chunk'))){ + while (preg_match('/^[a-zA-Z0-9]?$/', $byte = $this->readData($socket, 1, 'chunk'))) { // read chunksize until \r $chunk_size .= $byte; if (strlen($chunk_size) > 128) // set an abritrary limit on the size of chunks @@ -417,7 +411,7 @@ class HTTPClient { $this->readLine($socket, 'chunk'); // readtrailing \n $chunk_size = hexdec($chunk_size); - if($this->max_bodysize && $chunk_size+strlen($r_body) > $this->max_bodysize){ + if ($this->max_bodysize && $chunk_size + strlen($r_body) > $this->max_bodysize) { if ($this->max_bodysize_abort) throw new HTTPClientException('Allowed response size exceeded'); $this->error = 'Allowed response size exceeded'; @@ -430,7 +424,10 @@ class HTTPClient { $this->readData($socket, 2, 'chunk'); // read trailing \r\n } } while ($chunk_size && !$abort); - }elseif(isset($this->resp_headers['content-length']) && !isset($this->resp_headers['transfer-encoding'])){ + } elseif ( + isset($this->resp_headers['content-length']) && + !isset($this->resp_headers['transfer-encoding']) + ) { /* RFC 2616 * If a message is received with both a Transfer-Encoding header field and a Content-Length * header field, the latter MUST be ignored. @@ -438,22 +435,22 @@ class HTTPClient { // read up to the content-length or max_bodysize // for keep alive we need to read the whole message to clean up the socket for the next read - if( + if ( !$this->keep_alive && $this->max_bodysize && $this->max_bodysize < $this->resp_headers['content-length'] ) { $length = $this->max_bodysize + 1; - }else{ + } else { $length = $this->resp_headers['content-length']; } $r_body = $this->readData($socket, $length, 'response (content-length limited)', true); - }elseif( !isset($this->resp_headers['transfer-encoding']) && $this->max_bodysize && !$this->keep_alive){ - $r_body = $this->readData($socket, $this->max_bodysize+1, 'response (content-length limited)', true); + } elseif (!isset($this->resp_headers['transfer-encoding']) && $this->max_bodysize && !$this->keep_alive) { + $r_body = $this->readData($socket, $this->max_bodysize + 1, 'response (content-length limited)', true); } elseif ((int)$this->status === 204) { // request has no content - } else{ + } else { // read entire socket while (!feof($socket)) { $r_body .= $this->readData($socket, 4096, 'response (unlimited)', true); @@ -461,8 +458,8 @@ class HTTPClient { } // recheck body size, we might have read max_bodysize+1 or even the whole body, so we abort late here - if($this->max_bodysize){ - if(strlen($r_body) > $this->max_bodysize){ + if ($this->max_bodysize) { + if (strlen($r_body) > $this->max_bodysize) { if ($this->max_bodysize_abort) { throw new HTTPClientException('Allowed response size exceeded'); } else { @@ -470,7 +467,6 @@ class HTTPClient { } } } - } catch (HTTPClientException $err) { $this->error = $err->getMessage(); if ($err->getCode()) @@ -480,27 +476,31 @@ class HTTPClient { return false; } - if (!$this->keep_alive || - (isset($this->resp_headers['connection']) && $this->resp_headers['connection'] == 'Close')) { + if ( + !$this->keep_alive || + (isset($this->resp_headers['connection']) && $this->resp_headers['connection'] == 'Close') + ) { // close socket fclose($socket); unset(self::$connections[$connectionId]); } // decode gzip if needed - if(isset($this->resp_headers['content-encoding']) && + if ( + isset($this->resp_headers['content-encoding']) && $this->resp_headers['content-encoding'] == 'gzip' && - strlen($r_body) > 10 && substr($r_body,0,3)=="\x1f\x8b\x08"){ + strlen($r_body) > 10 && substr($r_body, 0, 3) == "\x1f\x8b\x08" + ) { $this->resp_body = @gzinflate(substr($r_body, 10)); - if($this->resp_body === false){ + if ($this->resp_body === false) { $this->error = 'Failed to decompress gzip encoded content'; $this->resp_body = $r_body; } - }else{ + } else { $this->resp_body = $r_body; } - $this->debug('response body',$this->resp_body); + $this->debug('response body', $this->resp_body); $this->redirect_count = 0; return true; } @@ -512,35 +512,37 @@ class HTTPClient { * * @param resource &$socket * @param string &$requesturl - * @throws HTTPClientException when a tunnel is needed but could not be established * @return bool true if a tunnel was established + * @throws HTTPClientException when a tunnel is needed but could not be established */ - protected function ssltunnel(&$socket, &$requesturl){ - if(!$this->useProxyForUrl($requesturl)) return false; + protected function ssltunnel(&$socket, &$requesturl) + { + if (!$this->useProxyForUrl($requesturl)) return false; $requestinfo = parse_url($requesturl); - if($requestinfo['scheme'] != 'https') return false; - if(empty($requestinfo['port'])) $requestinfo['port'] = 443; + if ($requestinfo['scheme'] != 'https') return false; + if (empty($requestinfo['port'])) $requestinfo['port'] = 443; // build request - $request = "CONNECT {$requestinfo['host']}:{$requestinfo['port']} HTTP/1.0".HTTP_NL; - $request .= "Host: {$requestinfo['host']}".HTTP_NL; - if($this->proxy_user) { - $request .= 'Proxy-Authorization: Basic '.base64_encode($this->proxy_user.':'.$this->proxy_pass).HTTP_NL; + $request = "CONNECT {$requestinfo['host']}:{$requestinfo['port']} HTTP/1.0" . HTTP_NL; + $request .= "Host: {$requestinfo['host']}" . HTTP_NL; + if ($this->proxy_user) { + $request .= 'Proxy-Authorization: Basic ' . + base64_encode($this->proxy_user . ':' . $this->proxy_pass) . HTTP_NL; } $request .= HTTP_NL; - $this->debug('SSL Tunnel CONNECT',$request); + $this->debug('SSL Tunnel CONNECT', $request); $this->sendData($socket, $request, 'SSL Tunnel CONNECT'); // read headers from socket $r_headers = ''; - do{ + do { $r_line = $this->readLine($socket, 'headers'); $r_headers .= $r_line; - }while($r_line != "\r\n" && $r_line != "\n"); + } while ($r_line != "\r\n" && $r_line != "\n"); - $this->debug('SSL Tunnel Response',$r_headers); - if(preg_match('/^HTTP\/1\.[01] 200/i',$r_headers)){ + $this->debug('SSL Tunnel Response', $r_headers); + if (preg_match('/^HTTP\/1\.[01] 200/i', $r_headers)) { // set correct peer name for verification (enabled since PHP 5.6) stream_context_set_option($socket, 'ssl', 'peer_name', $requestinfo['host']); @@ -554,13 +556,14 @@ class HTTPClient { } if (@stream_socket_enable_crypto($socket, true, $cryptoMethod)) { - $requesturl = ($requestinfo['path'] ?? '/'). - (!empty($requestinfo['query'])?'?'.$requestinfo['query']:''); + $requesturl = ($requestinfo['path'] ?? '/') . + (empty($requestinfo['query']) ? '' : '?' . $requestinfo['query']); return true; } throw new HTTPClientException( - 'Failed to set up crypto for secure connection to '.$requestinfo['host'], -151 + 'Failed to set up crypto for secure connection to ' . $requestinfo['host'], + -151 ); } @@ -570,38 +573,39 @@ class HTTPClient { /** * Safely write data to a socket * - * @param resource $socket An open socket handle - * @param string $data The data to write - * @param string $message Description of what is being read + * @param resource $socket An open socket handle + * @param string $data The data to write + * @param string $message Description of what is being read * @throws HTTPClientException * * @author Tom N Harris <tnharris@whoopdedo.org> */ - protected function sendData($socket, $data, $message) { + protected function sendData($socket, $data, $message) + { // send request $towrite = strlen($data); $written = 0; - while($written < $towrite){ + while ($written < $towrite) { // check timeout $time_used = microtime(true) - $this->start; - if($time_used > $this->timeout) - throw new HTTPClientException(sprintf('Timeout while sending %s (%.3fs)',$message, $time_used), -100); - if(feof($socket)) + if ($time_used > $this->timeout) + throw new HTTPClientException(sprintf('Timeout while sending %s (%.3fs)', $message, $time_used), -100); + if (feof($socket)) throw new HTTPClientException("Socket disconnected while writing $message"); // select parameters $sel_r = null; - $sel_w = array($socket); + $sel_w = [$socket]; $sel_e = null; // wait for stream ready or timeout (1sec) - if(@stream_select($sel_r,$sel_w,$sel_e,1) === false){ + if (@stream_select($sel_r, $sel_w, $sel_e, 1) === false) { usleep(1000); continue; } // write to stream - $nbytes = fwrite($socket, substr($data,$written,4096)); - if($nbytes === false) + $nbytes = fwrite($socket, substr($data, $written, 4096)); + if ($nbytes === false) throw new HTTPClientException("Failed writing to socket while sending $message", -100); $written += $nbytes; } @@ -613,16 +617,17 @@ class HTTPClient { * Reads up to a given number of bytes or throws an exception if the * response times out or ends prematurely. * - * @param resource $socket An open socket handle in non-blocking mode - * @param int $nbytes Number of bytes to read - * @param string $message Description of what is being read - * @param bool $ignore_eof End-of-file is not an error if this is set - * @throws HTTPClientException + * @param resource $socket An open socket handle in non-blocking mode + * @param int $nbytes Number of bytes to read + * @param string $message Description of what is being read + * @param bool $ignore_eof End-of-file is not an error if this is set * @return string * + * @throws HTTPClientException * @author Tom N Harris <tnharris@whoopdedo.org> */ - protected function readData($socket, $nbytes, $message, $ignore_eof = false) { + protected function readData($socket, $nbytes, $message, $ignore_eof = false) + { $r_data = ''; // Does not return immediately so timeout and eof can be checked if ($nbytes < 0) $nbytes = 0; @@ -631,27 +636,33 @@ class HTTPClient { $time_used = microtime(true) - $this->start; if ($time_used > $this->timeout) throw new HTTPClientException( - sprintf('Timeout while reading %s after %d bytes (%.3fs)', $message, - strlen($r_data), $time_used), -100); - if(feof($socket)) { - if(!$ignore_eof) + sprintf( + 'Timeout while reading %s after %d bytes (%.3fs)', + $message, + strlen($r_data), + $time_used + ), + -100 + ); + if (feof($socket)) { + if (!$ignore_eof) throw new HTTPClientException("Premature End of File (socket) while reading $message"); break; } if ($to_read > 0) { // select parameters - $sel_r = array($socket); + $sel_r = [$socket]; $sel_w = null; $sel_e = null; // wait for stream ready or timeout (1sec) - if(@stream_select($sel_r,$sel_w,$sel_e,1) === false){ + if (@stream_select($sel_r, $sel_w, $sel_e, 1) === false) { usleep(1000); continue; } $bytes = fread($socket, $to_read); - if($bytes === false) + if ($bytes === false) throw new HTTPClientException("Failed reading from socket while reading $message", -100); $r_data .= $bytes; $to_read -= strlen($bytes); @@ -665,36 +676,38 @@ class HTTPClient { * * Always returns a complete line, including the terminating \n. * - * @param resource $socket An open socket handle in non-blocking mode - * @param string $message Description of what is being read - * @throws HTTPClientException + * @param resource $socket An open socket handle in non-blocking mode + * @param string $message Description of what is being read * @return string * + * @throws HTTPClientException * @author Tom N Harris <tnharris@whoopdedo.org> */ - protected function readLine($socket, $message) { + protected function readLine($socket, $message) + { $r_data = ''; do { $time_used = microtime(true) - $this->start; if ($time_used > $this->timeout) throw new HTTPClientException( sprintf('Timeout while reading %s (%.3fs) >%s<', $message, $time_used, $r_data), - -100); - if(feof($socket)) + -100 + ); + if (feof($socket)) throw new HTTPClientException("Premature End of File (socket) while reading $message"); // select parameters - $sel_r = array($socket); + $sel_r = [$socket]; $sel_w = null; $sel_e = null; // wait for stream ready or timeout (1sec) - if(@stream_select($sel_r,$sel_w,$sel_e,1) === false){ + if (@stream_select($sel_r, $sel_w, $sel_e, 1) === false) { usleep(1000); continue; } $r_data = fgets($socket, 1024); - } while (!preg_match('/\n$/',$r_data)); + } while (!preg_match('/\n$/', $r_data)); return $r_data; } @@ -703,16 +716,17 @@ class HTTPClient { * * Uses _debug_text or _debug_html depending on the SAPI name * + * @param string $info + * @param mixed $var * @author Andreas Gohr <andi@splitbrain.org> * - * @param string $info - * @param mixed $var */ - protected function debug($info,$var=null){ - if(!$this->debug) return; - if(php_sapi_name() == 'cli'){ + protected function debug($info, $var = null) + { + if (!$this->debug) return; + if (PHP_SAPI == 'cli') { $this->debugText($info, $var); - }else{ + } else { $this->debugHtml($info, $var); } } @@ -721,16 +735,17 @@ class HTTPClient { * print debug info as HTML * * @param string $info - * @param mixed $var + * @param mixed $var */ - protected function debugHtml($info, $var=null){ - print '<b>'.$info.'</b> '.(microtime(true) - $this->start).'s<br />'; - if(!is_null($var)){ + protected function debugHtml($info, $var = null) + { + echo '<b>' . $info . '</b> ' . (microtime(true) - $this->start) . 's<br />'; + if (!is_null($var)) { ob_start(); print_r($var); $content = htmlspecialchars(ob_get_contents()); ob_end_clean(); - print '<pre>'.$content.'</pre>'; + echo '<pre>' . $content . '</pre>'; } } @@ -738,12 +753,13 @@ class HTTPClient { * prints debug info as plain text * * @param string $info - * @param mixed $var + * @param mixed $var */ - protected function debugText($info, $var=null){ - print '*'.$info.'* '.(microtime(true) - $this->start)."s\n"; - if(!is_null($var)) print_r($var); - print "\n-----------------------------------------------\n"; + protected function debugText($info, $var = null) + { + echo '*' . $info . '* ' . (microtime(true) - $this->start) . "s\n"; + if (!is_null($var)) print_r($var); + echo "\n-----------------------------------------------\n"; } /** @@ -751,28 +767,29 @@ class HTTPClient { * * All Keys are lowercased. * - * @author Andreas Gohr <andi@splitbrain.org> - * * @param string $string * @return array + * @author Andreas Gohr <andi@splitbrain.org> + * */ - protected function parseHeaders($string){ - $headers = array(); - $lines = explode("\n",$string); + protected function parseHeaders($string) + { + $headers = []; + $lines = explode("\n", $string); array_shift($lines); //skip first line (status) - foreach($lines as $line){ - list($key, $val) = sexplode(':', $line, 2, ''); + foreach ($lines as $line) { + [$key, $val] = sexplode(':', $line, 2, ''); $key = trim($key); $val = trim($val); $key = strtolower($key); - if(!$key) continue; - if(isset($headers[$key])){ - if(is_array($headers[$key])){ + if (!$key) continue; + if (isset($headers[$key])) { + if (is_array($headers[$key])) { $headers[$key][] = $val; - }else{ - $headers[$key] = array($headers[$key],$val); + } else { + $headers[$key] = [$headers[$key], $val]; } - }else{ + } else { $headers[$key] = $val; } } @@ -782,16 +799,17 @@ class HTTPClient { /** * convert given header array to header string * - * @author Andreas Gohr <andi@splitbrain.org> - * * @param array $headers * @return string + * @author Andreas Gohr <andi@splitbrain.org> + * */ - protected function buildHeaders($headers){ + protected function buildHeaders($headers) + { $string = ''; - foreach($headers as $key => $value){ - if($value === '') continue; - $string .= $key.': '.$value.HTTP_NL; + foreach ($headers as $key => $value) { + if ($value === '') continue; + $string .= $key . ': ' . $value . HTTP_NL; } return $string; } @@ -799,73 +817,77 @@ class HTTPClient { /** * get cookies as http header string * + * @return string * @author Andreas Goetz <cpuidle@gmx.de> * - * @return string */ - protected function getCookies(){ + protected function getCookies() + { $headers = ''; - foreach ($this->cookies as $key => $val){ + foreach ($this->cookies as $key => $val) { $headers .= "$key=$val; "; } $headers = substr($headers, 0, -2); - if ($headers) $headers = "Cookie: $headers".HTTP_NL; + if ($headers) $headers = "Cookie: $headers" . HTTP_NL; return $headers; } /** * Encode data for posting * - * @author Andreas Gohr <andi@splitbrain.org> - * * @param array $data * @return string + * @author Andreas Gohr <andi@splitbrain.org> + * */ - protected function postEncode($data){ - return http_build_query($data,'','&'); + protected function postEncode($data) + { + return http_build_query($data, '', '&'); } /** * Encode data for posting using multipart encoding * * @fixme use of urlencode might be wrong here - * @author Andreas Gohr <andi@splitbrain.org> - * * @param array $data * @return string + * @author Andreas Gohr <andi@splitbrain.org> + * */ - protected function postMultipartEncode($data){ - $boundary = '--'.$this->boundary; + protected function postMultipartEncode($data) + { + $boundary = '--' . $this->boundary; $out = ''; - foreach($data as $key => $val){ - $out .= $boundary.HTTP_NL; - if(!is_array($val)){ - $out .= 'Content-Disposition: form-data; name="'.urlencode($key).'"'.HTTP_NL; + foreach ($data as $key => $val) { + $out .= $boundary . HTTP_NL; + if (!is_array($val)) { + $out .= 'Content-Disposition: form-data; name="' . urlencode($key) . '"' . HTTP_NL; $out .= HTTP_NL; // end of headers $out .= $val; $out .= HTTP_NL; - }else{ - $out .= 'Content-Disposition: form-data; name="'.urlencode($key).'"'; - if($val['filename']) $out .= '; filename="'.urlencode($val['filename']).'"'; + } else { + $out .= 'Content-Disposition: form-data; name="' . urlencode($key) . '"'; + if ($val['filename']) $out .= '; filename="' . urlencode($val['filename']) . '"'; $out .= HTTP_NL; - if($val['mimetype']) $out .= 'Content-Type: '.$val['mimetype'].HTTP_NL; + if ($val['mimetype']) $out .= 'Content-Type: ' . $val['mimetype'] . HTTP_NL; $out .= HTTP_NL; // end of headers $out .= $val['body']; $out .= HTTP_NL; } } - $out .= "$boundary--".HTTP_NL; + $out .= "$boundary--" . HTTP_NL; return $out; } /** * Generates a unique identifier for a connection. * - * @param string $server - * @param string $port + * @param string $server + * @param string $port * @return string unique identifier */ - protected function uniqueConnectionId($server, $port) { + protected function uniqueConnectionId($server, $port) + { return "$server:$port"; } @@ -877,7 +899,8 @@ class HTTPClient { * @param string $url * @return bool */ - protected function useProxyForUrl($url) { + protected function useProxyForUrl($url) + { return $this->proxy_host && (!$this->proxy_except || !preg_match('/' . $this->proxy_except . '/i', $url)); } } |