3 namespace PhpXmlRpc\Helper;
5 use PhpXmlRpc\PhpXmlRpc;
10 * Decode a string that is encoded w/ "chunked" transfer encoding
11 * as defined in rfc2068 par. 19.4.6
12 * code shamelessly stolen from nusoap library by Dietrich Ayala.
14 * @param string $buffer the string to be decoded
18 public static function decodeChunked($buffer)
24 // read chunk-size, chunk-extension (if any) and crlf
25 // get the position of the linebreak
26 $chunkEnd = strpos($buffer, "\r\n") + 2;
27 $temp = substr($buffer, 0, $chunkEnd);
28 $chunkSize = hexdec(trim($temp));
29 $chunkStart = $chunkEnd;
30 while ($chunkSize > 0) {
31 $chunkEnd = strpos($buffer, "\r\n", $chunkStart + $chunkSize);
33 // just in case we got a broken connection
34 if ($chunkEnd == false) {
35 $chunk = substr($buffer, $chunkStart);
36 // append chunk-data to entity-body
38 $length += strlen($chunk);
42 // read chunk-data and crlf
43 $chunk = substr($buffer, $chunkStart, $chunkEnd - $chunkStart);
44 // append chunk-data to entity-body
46 // length := length + chunk-size
47 $length += strlen($chunk);
48 // read chunk-size and crlf
49 $chunkStart = $chunkEnd + 2;
51 $chunkEnd = strpos($buffer, "\r\n", $chunkStart) + 2;
52 if ($chunkEnd == false) {
53 break; //just in case we got a broken connection
55 $temp = substr($buffer, $chunkStart, $chunkEnd - $chunkStart);
56 $chunkSize = hexdec(trim($temp));
57 $chunkStart = $chunkEnd;
64 * Parses HTTP an http response headers and separates them from the body.
66 * @param string $data the http response,headers and body. It will be stripped of headers
67 * @param bool $headersProcessed when true, we assume that response inflating and dechunking has been already carried out
69 * @return array with keys 'headers' and 'cookies'
72 public function parseResponseHeaders(&$data, $headersProcessed = false, $debug=0)
74 $httpResponse = array('raw_data' => $data, 'headers'=> array(), 'cookies' => array());
76 // Support "web-proxy-tunelling" connections for https through proxies
77 if (preg_match('/^HTTP\/1\.[0-1] 200 Connection established/', $data)) {
78 // Look for CR/LF or simple LF as line separator,
79 // (even though it is not valid http)
80 $pos = strpos($data, "\r\n\r\n");
81 if ($pos || is_int($pos)) {
84 $pos = strpos($data, "\n\n");
85 if ($pos || is_int($pos)) {
88 // No separation between response headers and body: fault?
93 // this filters out all http headers from proxy.
94 // maybe we could take them into account, too?
95 $data = substr($data, $bd);
97 error_log('XML-RPC: ' . __METHOD__ . ': HTTPS via proxy error, tunnel connection possibly failed');
98 throw new \Exception(PhpXmlRpc::$xmlrpcstr['http_error'] . ' (HTTPS via proxy error, tunnel connection possibly failed)', PhpXmlRpc::$xmlrpcerr['http_error']);
102 // Strip HTTP 1.1 100 Continue header if present
103 while (preg_match('/^HTTP\/1\.1 1[0-9]{2} /', $data)) {
104 $pos = strpos($data, 'HTTP', 12);
105 // server sent a Continue header without any (valid) content following...
106 // give the client a chance to know it
107 if (!$pos && !is_int($pos)) {
108 // works fine in php 3, 4 and 5
112 $data = substr($data, $pos);
114 if (!preg_match('/^HTTP\/[0-9.]+ 200 /', $data)) {
115 $errstr = substr($data, 0, strpos($data, "\n") - 1);
116 error_log('XML-RPC: ' . __METHOD__ . ': HTTP error, got response: ' . $errstr);
117 throw new \Exception(PhpXmlRpc::$xmlrpcstr['http_error'] . ' (' . $errstr . ')', PhpXmlRpc::$xmlrpcerr['http_error']);
120 // be tolerant to usage of \n instead of \r\n to separate headers and data
121 // (even though it is not valid http)
122 $pos = strpos($data, "\r\n\r\n");
123 if ($pos || is_int($pos)) {
126 $pos = strpos($data, "\n\n");
127 if ($pos || is_int($pos)) {
130 // No separation between response headers and body: fault?
131 // we could take some action here instead of going on...
135 // be tolerant to line endings, and extra empty lines
136 $ar = preg_split("/\r?\n/", trim(substr($data, 0, $pos)));
137 while (list(, $line) = @each($ar)) {
138 // take care of multi-line headers and cookies
139 $arr = explode(':', $line, 2);
140 if (count($arr) > 1) {
141 $headerName = strtolower(trim($arr[0]));
142 /// @todo some other headers (the ones that allow a CSV list of values)
143 /// do allow many values to be passed using multiple header lines.
144 /// We should add content to $xmlrpc->_xh['headers'][$headerName]
145 /// instead of replacing it for those...
146 if ($headerName == 'set-cookie' || $headerName == 'set-cookie2') {
147 if ($headerName == 'set-cookie2') {
148 // version 2 cookies:
149 // there could be many cookies on one line, comma separated
150 $cookies = explode(',', $arr[1]);
152 $cookies = array($arr[1]);
154 foreach ($cookies as $cookie) {
155 // glue together all received cookies, using a comma to separate them
156 // (same as php does with getallheaders())
157 if (isset($httpResponse['headers'][$headerName])) {
158 $httpResponse['headers'][$headerName] .= ', ' . trim($cookie);
160 $httpResponse['headers'][$headerName] = trim($cookie);
162 // parse cookie attributes, in case user wants to correctly honour them
163 // feature creep: only allow rfc-compliant cookie attributes?
164 // @todo support for server sending multiple time cookie with same name, but using different PATHs
165 $cookie = explode(';', $cookie);
166 foreach ($cookie as $pos => $val) {
167 $val = explode('=', $val, 2);
168 $tag = trim($val[0]);
169 $val = trim(@$val[1]);
170 /// @todo with version 1 cookies, we should strip leading and trailing " chars
173 $httpResponse['cookies'][$tag] = array();
174 $httpResponse['cookies'][$cookiename]['value'] = urldecode($val);
176 if ($tag != 'value') {
177 $httpResponse['cookies'][$cookiename][$tag] = $val;
183 $httpResponse['headers'][$headerName] = trim($arr[1]);
185 } elseif (isset($headerName)) {
186 /// @todo version1 cookies might span multiple lines, thus breaking the parsing above
187 $httpResponse['headers'][$headerName] .= ' ' . trim($line);
191 $data = substr($data, $bd);
193 if ($debug && count($httpResponse['headers'])) {
195 foreach ($httpResponse['headers'] as $header => $value) {
196 $msg .= "HEADER: $header: $value\n";
198 foreach ($httpResponse['cookies'] as $header => $value) {
199 $msg .= "COOKIE: $header={$value['value']}\n";
201 $this->debugMessage($msg);
204 // if CURL was used for the call, http headers have been processed,
205 // and dechunking + reinflating have been carried out
206 if (!$headersProcessed) {
207 // Decode chunked encoding sent by http 1.1 servers
208 if (isset($httpResponse['headers']['transfer-encoding']) && $httpResponse['headers']['transfer-encoding'] == 'chunked') {
209 if (!$data = Http::decodeChunked($data)) {
210 error_log('XML-RPC: ' . __METHOD__ . ': errors occurred when trying to rebuild the chunked data received from server');
211 throw new \Exception(PhpXmlRpc::$xmlrpcstr['dechunk_fail'], PhpXmlRpc::$xmlrpcerr['dechunk_fail']);
215 // Decode gzip-compressed stuff
216 // code shamelessly inspired from nusoap library by Dietrich Ayala
217 if (isset($httpResponse['headers']['content-encoding'])) {
218 $httpResponse['headers']['content-encoding'] = str_replace('x-', '', $httpResponse['headers']['content-encoding']);
219 if ($httpResponse['headers']['content-encoding'] == 'deflate' || $httpResponse['headers']['content-encoding'] == 'gzip') {
220 // if decoding works, use it. else assume data wasn't gzencoded
221 if (function_exists('gzinflate')) {
222 if ($httpResponse['headers']['content-encoding'] == 'deflate' && $degzdata = @gzuncompress($data)) {
225 $this->debugMessage("---INFLATED RESPONSE---[" . strlen($data) . " chars]---\n$data\n---END---");
227 } elseif ($httpResponse['headers']['content-encoding'] == 'gzip' && $degzdata = @gzinflate(substr($data, 10))) {
230 $this->debugMessage("---INFLATED RESPONSE---[" . strlen($data) . " chars]---\n$data\n---END---");
233 error_log('XML-RPC: ' . __METHOD__ . ': errors occurred when trying to decode the deflated data received from server');
234 throw new \Exception(PhpXmlRpc::$xmlrpcstr['decompress_fail'], PhpXmlRpc::$xmlrpcerr['decompress_fail']);
237 error_log('XML-RPC: ' . __METHOD__ . ': the server sent deflated data. Your php install must have the Zlib extension compiled in to support this.');
238 throw new \Exception(PhpXmlRpc::$xmlrpcstr['cannot_decompress'], PhpXmlRpc::$xmlrpcerr['cannot_decompress']);
242 } // end of 'if needed, de-chunk, re-inflate response'
244 return $httpResponse;
248 * Echoes a debug message, taking care of escaping it when not in console mode
250 * @param string $message
252 protected function debugMessage($message)
254 if (PHP_SAPI != 'cli') {
255 print "<PRE>\n".htmlentities($message)."\n</PRE>";
257 print "\n$message\n";