Completed
Pull Request — master (#24)
by
unknown
02:23
created

Request::cleanUploadedFiles()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 6
rs 9.4285
cc 2
eloc 3
nc 2
nop 0
1
<?php
2
3
namespace PHPFastCGI\FastCGIDaemon\Http;
4
5
use Symfony\Component\HttpFoundation\Request as HttpFoundationRequest;
6
use Zend\Diactoros\ServerRequest;
7
use Zend\Diactoros\ServerRequestFactory;
8
9
/**
10
 * The default implementation of the RequestInterface.
11
 */
12
class Request implements RequestInterface
13
{
14
    /**
15
     * @var int
16
     */
17
    protected static $buffer_size = 10485760; // 10 MB
18
19
    /**
20
     * @var string
21
     */
22
    protected static $upload_dir = null;
23
24
    /**
25
     * @var array
26
     */
27
    protected $uploaded_files = [];
28
29
    /**
30
     * @var array
31
     */
32
    private $params;
33
34
    /**
35
     * @var resource
36
     */
37
    private $stdin;
38
39
    /**
40
     * Constructor.
41
     *
42
     * @param array    $params The FastCGI server params as an associative array
43
     * @param resource $stdin  The FastCGI stdin data as a stream resource
44
     */
45
    public function __construct(array $params, $stdin)
46
    {
47
        $this->params = [];
48
49
        foreach ($params as $name => $value) {
50
            $this->params[strtoupper($name)] = $value;
51
        }
52
53
        $this->stdin  = $stdin;
54
55
        rewind($this->stdin);
56
    }
57
58
    /**
59
     * {@inheritdoc}
60
     */
61
    public function getParams()
62
    {
63
        return $this->params;
64
    }
65
66
    /**
67
     * {@inheritdoc}
68
     */
69
    public function cleanUploadedFiles()
70
    {
71
        foreach ($this->uploaded_files as $file) {
72
            @unlink($file['tmp_name']);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
73
        }
74
    }
75
76
    /**
77
     * {@inheritdoc}
78
     */
79
    public static function setBufferSize($size)
80
    {
81
        static::$buffer_size = $size;
82
    }
83
84
    /**
85
     * {@inheritdoc}
86
     */
87
    public static function getBufferSize()
88
    {
89
        return static::$buffer_size;
90
    }
91
92
    /**
93
     * {@inheritdoc}
94
     */
95
    public static function setUploadDir($dir)
96
    {
97
        static::$upload_dir = $dir;
98
    }
99
100
    /**
101
     * {@inheritdoc}
102
     */
103
    public static function getUploadDir()
104
    {
105
        return static::$upload_dir ?: sys_get_temp_dir();
106
    }
107
108
    /**
109
     * {@inheritdoc}
110
     */
111
    public function getQuery()
112
    {
113
        $query = null;
114
115
        if (isset($this->params['QUERY_STRING'])) {
116
            parse_str($this->params['QUERY_STRING'], $query);
117
        }
118
119
        return $query ?: [];
120
    }
121
122
    /**
123
     * {@inheritdoc}
124
     */
125
    public function getPost()
126
    {
127
        $post = null;
128
129
        if (isset($this->params['REQUEST_METHOD']) && isset($this->params['CONTENT_TYPE'])) {
130
            $requestMethod = $this->params['REQUEST_METHOD'];
131
            $contentType   = $this->params['CONTENT_TYPE'];
132
133
            if (strcasecmp($requestMethod, 'POST') === 0 && stripos($contentType, 'application/x-www-form-urlencoded') === 0) {
134
                $postData = stream_get_contents($this->stdin);
135
                rewind($this->stdin);
136
137
                parse_str($postData, $post);
138
            }
139
        }
140
141
        return $post ?: [];
142
    }
143
144
    /**
145
     * {@inheritdoc}
146
     */
147
    public function getFile()
148
    {
149
        if (isset($this->params['REQUEST_METHOD']) && isset($this->params['CONTENT_TYPE'])) {
150
            $requestMethod = $this->params['REQUEST_METHOD'];
151
            $contentType   = $this->params['CONTENT_TYPE'];
152
153
            if (strcasecmp($requestMethod, 'POST') === 0 && stripos($contentType, 'multipart/form-data') === 0) {
154
                if (preg_match('/boundary=(.*)?/', $contentType, $matches)) {
155
                    list($postData, $this->uploaded_files) = $this->parseMultipartFormData($this->stdin, $matches[1]);
156
                    parse_str($postData, $post);
157
                    return $post;
158
                }
159
            }
160
        }
161
        return false;
162
    }
163
164
    private function parseMultipartFormData($stream, $boundary) {
165
        $post = "";
166
        $files = [];
167
        $field_type = $field_name = $filename = $mimetype = null;
0 ignored issues
show
Unused Code introduced by
$mimetype is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
168
        $in_header = $get_content = false;
0 ignored issues
show
Unused Code introduced by
$get_content is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
169
170
        while (!feof($stream)) {
171
            $get_content = $field_name && !$in_header;
0 ignored issues
show
Bug Best Practice introduced by
The expression $field_name of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
172
            $buffer = stream_get_line($stream, static::$buffer_size, "\r\n" . ($get_content ? '--'.$boundary : ''));
173
174
            if ($in_header && strlen($buffer) == 0) {
175
                $in_header = false;
176
            } else {
177
                if ($get_content) {
178
                    if ($field_type === 'data') {
179
                        $post .= (isset($post[0]) ? '&' : '') . $field_name . "=" . urlencode($buffer);
180
                    } elseif ($field_type === 'file' && $filename) {
181
                        $tmp_path = $this->getUploadDir().'/'.substr(md5(rand().time()), 0, 16);
182
                        $err = file_put_contents($tmp_path, $buffer);
183
                        $files[$field_name] = [
184
                            'type' => $mime_type ?: 'application/octet-stream',
0 ignored issues
show
Bug introduced by
The variable $mime_type does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
185
                            'name' => $filename,
186
                            'tmp_name' => $tmp_path,
187
                            'error' => ($err === false) ? true : 0,
188
                            'size' => filesize($tmp_path),
189
                        ];
190
                        $filename = $mime_type = null;
191
                    }
192
                    $field_name = $field_type = null;
193
                } elseif (strpos($buffer, 'Content-Disposition') === 0) {
194
                    $in_header = true;
195
                    if (preg_match('/name=\"([^\"]*)\"/', $buffer, $matches)) {
196
                        $field_name = $matches[1];
197
                    }
198
                    if ($is_file = preg_match('/filename=\"([^\"]*)\"/', $buffer, $matches)) {
199
                        $filename = $matches[1];
200
                    }
201
                    $field_type = $is_file ? 'file' : 'data';
202
                } elseif (strpos($buffer, 'Content-Type') === 0) {
203
                    $in_header = true;
204
                    if (preg_match('/Content-Type: (.*)?/', $buffer, $matches)) {
205
                        $mime_type = trim($matches[1]);
206
                    }
207
                }
208
            }
209
        }
210
211
        return [$post, $files];
212
    }
213
214
    /**
215
     * {@inheritdoc}
216
     */
217
    public function getCookies()
218
    {
219
        $cookies = [];
220
221
        if (isset($this->params['HTTP_COOKIE'])) {
222
            $cookiePairs = explode(';', $this->params['HTTP_COOKIE']);
223
224
            foreach ($cookiePairs as $cookiePair) {
225
                list($name, $value) = explode('=', trim($cookiePair));
226
                $cookies[$name] = $value;
227
            }
228
        }
229
230
        return $cookies;
231
    }
232
233
    /**
234
     * {@inheritdoc}
235
     */
236
    public function getStdin()
237
    {
238
        return $this->stdin;
239
    }
240
241
    /**
242
     * {@inheritdoc}
243
     */
244
    public function getServerRequest()
245
    {
246
        $query   = $this->getQuery();
247
        $post    = $this->getFile() ?: $this->getPost();
248
        $cookies = $this->getCookies();
249
250
        $server  = ServerRequestFactory::normalizeServer($this->params);
251
        $headers = ServerRequestFactory::marshalHeaders($server);
252
        $uri     = ServerRequestFactory::marshalUriFromServer($server, $headers);
253
        $method  = ServerRequestFactory::get('REQUEST_METHOD', $server, 'GET');
254
255
        $request = new ServerRequest($server, $this->uploaded_files, $uri, $method, $this->stdin, $headers);
256
257
        return $request
258
            ->withCookieParams($cookies)
259
            ->withQueryParams($query)
260
            ->withParsedBody($post);
261
    }
262
263
    /**
264
     * {@inheritdoc}
265
     */
266
    public function getHttpFoundationRequest()
267
    {
268
        $query   = $this->getQuery();
269
        $post    = $this->getFile() ?: $this->getPost();
270
        $cookies = $this->getCookies();
271
272
        return new HttpFoundationRequest($query, $post, [], $cookies, $this->uploaded_files, $this->params, $this->stdin);
273
    }
274
}
275