Passed
Push — master ( b6cd05...9f5262 )
by Gaetano
05:39
created

Http   C

Complexity

Total Complexity 56

Size/Duplication

Total Lines 280
Duplicated Lines 0 %

Test Coverage

Coverage 64.41%

Importance

Changes 6
Bugs 1 Features 0
Metric Value
eloc 140
c 6
b 1
f 0
dl 0
loc 280
ccs 76
cts 118
cp 0.6441
rs 5.5199
wmc 56

3 Methods

Rating   Name   Duplication   Size   Complexity  
F parseResponseHeaders() 0 187 49
A parseAcceptHeader() 0 15 3
A decodeChunked() 0 43 4

How to fix   Complexity   

Complex Class

Complex classes like Http often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Http, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace PhpXmlRpc\Helper;
4
5
use PhpXmlRpc\Exception\HttpException;
6
use PhpXmlRpc\PhpXmlRpc;
7
use PhpXmlRpc\Traits\LoggerAware;
8
9
class Http
10
{
11
    use LoggerAware;
12
13
    /**
14
     * Decode a string that is encoded with "chunked" transfer encoding as defined in rfc2068 par. 19.4.6.
15
     * Code shamelessly stolen from nusoap library by Dietrich Ayala.
16
     * @internal this function will become protected in the future
17
     *
18
     * @param string $buffer the string to be decoded
19
     * @return string
20
     */
21
    public static function decodeChunked($buffer)
22
    {
23
        // length := 0
24
        $length = 0;
25
        $new = '';
26
27
        // read chunk-size, chunk-extension (if any) and crlf
28
        // get the position of the linebreak
29
        $chunkEnd = strpos($buffer, "\r\n") + 2;
30
        $temp = substr($buffer, 0, $chunkEnd);
31
        $chunkSize = hexdec(trim($temp));
32
        $chunkStart = $chunkEnd;
33
        while ($chunkSize > 0) {
34
            $chunkEnd = strpos($buffer, "\r\n", $chunkStart + $chunkSize);
0 ignored issues
show
Bug introduced by
$chunkStart + $chunkSize of type double is incompatible with the type integer expected by parameter $offset of strpos(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

34
            $chunkEnd = strpos($buffer, "\r\n", /** @scrutinizer ignore-type */ $chunkStart + $chunkSize);
Loading history...
35
36
            // just in case we got a broken connection
37
            if ($chunkEnd == false) {
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing $chunkEnd of type integer to the boolean false. If you are specifically checking for 0, consider using something more explicit like === 0 instead.
Loading history...
38
                $chunk = substr($buffer, $chunkStart);
39
                // append chunk-data to entity-body
40
                $new .= $chunk;
41
                $length += strlen($chunk);
42
                break;
43
            }
44
45
            // read chunk-data and crlf
46
            $chunk = substr($buffer, $chunkStart, $chunkEnd - $chunkStart);
47
            // append chunk-data to entity-body
48
            $new .= $chunk;
49
            // length := length + chunk-size
50
            $length += strlen($chunk);
51
            // read chunk-size and crlf
52
            $chunkStart = $chunkEnd + 2;
53
54
            $chunkEnd = strpos($buffer, "\r\n", $chunkStart) + 2;
55
            if ($chunkEnd == false) {
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing $chunkEnd of type integer to the boolean false. If you are specifically checking for 0, consider using something more explicit like === 0 instead.
Loading history...
56
                break; // just in case we got a broken connection
57
            }
58
            $temp = substr($buffer, $chunkStart, $chunkEnd - $chunkStart);
59
            $chunkSize = hexdec(trim($temp));
60
            $chunkStart = $chunkEnd;
61
        }
62
63
        return $new;
64
    }
65
66
    /**
67
     * Parses HTTP an http response's headers and separates them from the body.
68
     *
69
     * @param string $data the http response, headers and body. It will be stripped of headers
70
     * @param bool $headersProcessed when true, we assume that response inflating and dechunking has been already carried out
71
     * @param int $debug when > 0, logs to screen messages detailing info about the parsed data
72
     * @return array with keys 'headers', 'cookies', 'raw_data' and 'status_code'
73 699
     * @throws HttpException
74
     *
75 699
     * @todo if $debug is < 0, we could avoid populating 'raw_data' and 'headers' in the returned value - but that would
76
     *       be a weird API...
77
     */
78 699
    public function parseResponseHeaders(&$data, $headersProcessed = false, $debug = 0)
79
    {
80
        $httpResponse = array('raw_data' => $data, 'headers'=> array(), 'cookies' => array(), 'status_code' => null);
81 32
82 32
        // Support "web-proxy-tunnelling" connections for https through proxies
83 32
        if (preg_match('/^HTTP\/1\.[0-1] 200 Connection established/', $data)) {
84
            // Look for CR/LF or simple LF as line separator (even though it is not valid http)
85
            $pos = strpos($data, "\r\n\r\n");
86
            if ($pos || is_int($pos)) {
0 ignored issues
show
introduced by
The condition is_int($pos) is always true.
Loading history...
87
                $bd = $pos + 4;
88
            } else {
89
                $pos = strpos($data, "\n\n");
90
                if ($pos || is_int($pos)) {
91
                    $bd = $pos + 2;
92
                } else {
93 32
                    // No separation between response headers and body: fault?
94
                    $bd = 0;
95
                }
96 32
            }
97
            if ($bd) {
98
                // this filters out all http headers from proxy. maybe we could take them into account, too?
99
                $data = substr($data, $bd);
100
            } else {
101
                $this->getLogger()->errorLog('XML-RPC: ' . __METHOD__ . ': HTTPS via proxy error, tunnel connection possibly failed');
102
                throw new HttpException(PhpXmlRpc::$xmlrpcstr['http_error'] . ' (HTTPS via proxy error, tunnel connection possibly failed)', PhpXmlRpc::$xmlrpcerr['http_error']);
103
            }
104 699
        }
105 1
106
        // Strip HTTP 1.1 100 Continue header if present
107
        while (preg_match('/^HTTP\/1\.1 1[0-9]{2} /', $data)) {
108 1
            $pos = strpos($data, 'HTTP', 12);
109
            // server sent a Continue header without any (valid) content following...
110
            // give the client a chance to know it
111
            if (!$pos && !is_int($pos)) {
112
                /// @todo this construct works fine in php 3, 4 and 5 - 8; would it not be enough to have !== false now ?
113 1
114
                break;
115
            }
116
            $data = substr($data, $pos);
117
        }
118 699
119 32
        // When using Curl to query servers using Digest Auth, we get back a double set of http headers.
120 32
        // Same when following redirects
121
        // We strip out the 1st...
122
        /// @todo we should let the caller know that there was a redirect involved
123
        if ($headersProcessed && preg_match('/^HTTP\/[0-9](?:\.[0-9])? (?:401|30[1278]) /', $data)) {
124 699
            if (preg_match('/(\r?\n){2}HTTP\/[0-9](?:\.[0-9])? 200 /', $data)) {
125 699
                $data = preg_replace('/^HTTP\/[0-9](?:\.[0-9])? (?:401|30[1278]) .+?(?:\r?\n){2}(HTTP\/[0-9.]+ 200 )/s', '$1', $data, 1);
126 699
            }
127
        }
128
129 699
        if (preg_match('/^HTTP\/([0-9](?:\.[0-9])?) ([0-9]{3}) /', $data, $matches)) {
130 3
            $httpResponse['protocol_version'] = $matches[1];
131 3
            $httpResponse['status_code'] = $matches[2];
132 3
        }
133
134
        if ($httpResponse['status_code'] !== '200') {
135
            $errstr = substr($data, 0, strpos($data, "\n") - 1);
136
            $this->getLogger()->errorLog('XML-RPC: ' . __METHOD__ . ': HTTP error, got response: ' . $errstr);
137 696
            throw new HttpException(PhpXmlRpc::$xmlrpcstr['http_error'] . ' (' . $errstr . ')', PhpXmlRpc::$xmlrpcerr['http_error'], null, $httpResponse['status_code']);
138 696
        }
139 695
140
        // be tolerant to usage of \n instead of \r\n to separate headers and data (even though it is not valid http)
141 1
        $pos = strpos($data, "\r\n\r\n");
142 1
        if ($pos || is_int($pos)) {
0 ignored issues
show
introduced by
The condition is_int($pos) is always true.
Loading history...
143 1
            $bd = $pos + 4;
144
        } else {
145
            $pos = strpos($data, "\n\n");
146
            if ($pos || is_int($pos)) {
147
                $bd = $pos + 2;
148
            } else {
149
                // No separation between response headers and body: fault?
150
                // we could take some action here instead of going on...
151
                $bd = 0;
152 696
            }
153
        }
154 696
155
        // be tolerant to line endings, and extra empty lines
156 696
        $ar = preg_split("/\r?\n/", trim(substr($data, 0, $pos)));
157 696
158 696
        foreach ($ar as $line) {
159
            // take care of multi-line headers and cookies
160
            $arr = explode(':', $line, 2);
161
            if (count($arr) > 1) {
162
                $headerName = strtolower(trim($arr[0]));
163
                /// @todo some other headers (the ones that allow a CSV list of values) do allow many values to be
164 696
                ///       passed using multiple header lines.
165 22
                ///       We should add content to $xmlrpc->_xh['headers'][$headerName] instead of replacing it for those...
166
                /// @todo should we drop support for rfc2965 (set-cookie2) cookies? It has been obsoleted since 2011
167
                if ($headerName == 'set-cookie' || $headerName == 'set-cookie2') {
168
                    if ($headerName == 'set-cookie2') {
169
                        // version 2 cookies:
170 22
                        // there could be many cookies on one line, comma separated
171
                        $cookies = explode(',', $arr[1]);
172 22
                    } else {
173
                        $cookies = array($arr[1]);
174
                    }
175 22
                    foreach ($cookies as $cookie) {
176 22
                        // glue together all received cookies, using a comma to separate them (same as php does with getallheaders())
177
                        if (isset($httpResponse['headers'][$headerName])) {
178 22
                            $httpResponse['headers'][$headerName] .= ', ' . trim($cookie);
179
                        } else {
180
                            $httpResponse['headers'][$headerName] = trim($cookie);
181
                        }
182
                        // parse cookie attributes, in case user wants to correctly honour them
183 22
                        // feature creep: only allow rfc-compliant cookie attributes?
184 22
                        // @todo support for server sending multiple time cookie with same name, but using different PATHs
185 22
                        $cookie = explode(';', $cookie);
186 22
                        foreach ($cookie as $pos => $val) {
187 22
                            $val = explode('=', $val, 2);
188
                            $tag = trim($val[0]);
189 22
                            $val = isset($val[1]) ? trim($val[1]) : '';
190 22
                            /// @todo with version 1 cookies, we should strip leading and trailing " chars
191 22
                            if ($pos == 0) {
192 22
                                $cookiename = $tag;
193
                                $httpResponse['cookies'][$tag] = array();
194 22
                                $httpResponse['cookies'][$cookiename]['value'] = urldecode($val);
195 22
                            } else {
196
                                if ($tag != 'value') {
197
                                    $httpResponse['cookies'][$cookiename][$tag] = $val;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $cookiename does not seem to be defined for all execution paths leading up to this point.
Loading history...
198
                                }
199
                            }
200
                        }
201 696
                    }
202
                } else {
203
                    $httpResponse['headers'][$headerName] = trim($arr[1]);
204
                }
205 1
            } elseif (isset($headerName)) {
206
                /// @todo version1 cookies might span multiple lines, thus breaking the parsing above
207
                $httpResponse['headers'][$headerName] .= ' ' . trim($line);
208
            }
209 696
        }
210
211 696
        $data = substr($data, $bd);
212 3
213 3
        if ($debug && count($httpResponse['headers'])) {
214 3
            $msg = '';
215
            foreach ($httpResponse['headers'] as $header => $value) {
216 3
                $msg .= "HEADER: $header: $value\n";
217
            }
218
            foreach ($httpResponse['cookies'] as $header => $value) {
219 3
                $msg .= "COOKIE: $header={$value['value']}\n";
220
            }
221
            $this->getLogger()->debugMessage($msg);
222
        }
223
224 696
        // if CURL was used for the call, http headers have been processed, and dechunking + reinflating have been carried out
225
        if (!$headersProcessed) {
226
227 374
            // Decode chunked encoding sent by http 1.1 servers
228
            if (isset($httpResponse['headers']['transfer-encoding']) && $httpResponse['headers']['transfer-encoding'] == 'chunked') {
229
                if (!$data = static::decodeChunked($data)) {
230
                    $this->getLogger()->errorLog('XML-RPC: ' . __METHOD__ . ': errors occurred when trying to rebuild the chunked data received from server');
231
                    throw new HttpException(PhpXmlRpc::$xmlrpcstr['dechunk_fail'], PhpXmlRpc::$xmlrpcerr['dechunk_fail'], null, $httpResponse['status_code']);
232
                }
233
            }
234
235
            // Decode gzip-compressed stuff
236 374
            // code shamelessly inspired from nusoap library by Dietrich Ayala
237 71
            if (isset($httpResponse['headers']['content-encoding'])) {
238 71
                $httpResponse['headers']['content-encoding'] = str_replace('x-', '', $httpResponse['headers']['content-encoding']);
239
                if ($httpResponse['headers']['content-encoding'] == 'deflate' || $httpResponse['headers']['content-encoding'] == 'gzip') {
240 71
                    // if decoding works, use it. else assume data wasn't gzencoded
241 71
                    if (function_exists('gzinflate')) {
242 32
                        if ($httpResponse['headers']['content-encoding'] == 'deflate' && $degzdata = @gzuncompress($data)) {
243 32
                            $data = $degzdata;
244 32
                            if ($debug) {
245
                                $this->getLogger()->debugMessage("---INFLATED RESPONSE---[" . strlen($data) . " chars]---\n$data\n---END---");
246 39
                            }
247 39
                        } elseif ($httpResponse['headers']['content-encoding'] == 'gzip' && $degzdata = @gzinflate(substr($data, 10))) {
248 39
                            $data = $degzdata;
249 35
                            if ($debug) {
250
                                $this->getLogger()->debugMessage("---INFLATED RESPONSE---[" . strlen($data) . " chars]---\n$data\n---END---");
251
                            }
252
                        } else {
253 64
                            $this->getLogger()->errorLog('XML-RPC: ' . __METHOD__ . ': errors occurred when trying to decode the deflated data received from server');
254
                            throw new HttpException(PhpXmlRpc::$xmlrpcstr['decompress_fail'], PhpXmlRpc::$xmlrpcerr['decompress_fail'], null, $httpResponse['status_code']);
255
                        }
256
                    } else {
257
                        $this->getLogger()->errorLog('XML-RPC: ' . __METHOD__ . ': the server sent deflated data. Your php install must have the Zlib extension compiled in to support this.');
258
                        throw new HttpException(PhpXmlRpc::$xmlrpcstr['cannot_decompress'], PhpXmlRpc::$xmlrpcerr['cannot_decompress'], null, $httpResponse['status_code']);
259
                    }
260
                }
261
            }
262
        } // end of 'if needed, de-chunk, re-inflate response'
263 696
264
        return $httpResponse;
265
    }
266
267
    /**
268
     * Parses one of the http headers which can have a list of values with quality param.
269
     * @see https://www.rfc-editor.org/rfc/rfc7231#section-5.3.1
270
     *
271
     * @param string $header
272
     * @return string[]
273
     */
274
    public function parseAcceptHeader($header)
275
    {
276
        $accepted = array();
277
        foreach(explode(',', $header) as $c) {
278
            if (preg_match('/^([^;]+); *q=([0-9.]+)/', $c, $matches)) {
279
                $c = $matches[1];
280
                $w = $matches[2];
281
            } else {
282
                $c = preg_replace('/;.*/', '', $c);
283
                $w = 1;
284
            }
285
            $accepted[(trim($c))] = $w;
286
        }
287
        arsort($accepted);
288
        return array_keys($accepted);
289
    }
290
}
291