Completed
Push — 2.1 ( 5c7bdb...e70364 )
by
unknown
11:17 queued 21s
created

MultipartFormDataParser::setUploadFileMaxSize()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
crap 1
1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii\web;
9
10
use yii\base\BaseObject;
11
use yii\helpers\ArrayHelper;
12
use yii\helpers\StringHelper;
13
14
/**
15
 * MultipartFormDataParser parses content encoded as 'multipart/form-data'.
16
 * This parser provides the fallback for the 'multipart/form-data' processing on non POST requests,
17
 * for example: the one with 'PUT' request method.
18
 *
19
 * In order to enable this parser you should configure [[Request::parsers]] in the following way:
20
 *
21
 * ```php
22
 * return [
23
 *     'components' => [
24
 *         'request' => [
25
 *             'parsers' => [
26
 *                 'multipart/form-data' => 'yii\web\MultipartFormDataParser'
27
 *             ],
28
 *         ],
29
 *         // ...
30
 *     ],
31
 *     // ...
32
 * ];
33
 * ```
34
 *
35
 * Method [[parse()]] of this parser automatically populates `$_FILES` with the files parsed from raw body.
36
 *
37
 * > Note: since this is a request parser, it will initialize `$_FILES` values on [[Request::getBodyParams()]].
38
 * Until this method is invoked, `$_FILES` array will remain empty even if there are submitted files in the
39
 * request body. Make sure you have requested body params before any attempt to get uploaded file in case
40
 * you are using this parser.
41
 *
42
 * Usage example:
43
 *
44
 * ```php
45
 * use yii\http\UploadedFile;
46
 *
47
 * $restRequestData = Yii::$app->request->getBodyParams();
48
 * $uploadedFile = UploadedFile::getInstancesByName('photo');
49
 *
50
 * $model = new Item();
51
 * $model->populate($restRequestData);
52
 * copy($uploadedFile->tempName, '/path/to/file/storage/photo.jpg');
53
 * ```
54
 *
55
 * > Note: although this parser fully emulates regular structure of the `$_FILES`, related temporary
56
 * files, which are available via `tmp_name` key, will not be recognized by PHP as uploaded ones.
57
 * Thus functions like `is_uploaded_file()` and `move_uploaded_file()` will fail on them. This also
58
 * means [[UploadedFile::saveAs()]] will fail as well.
59
 *
60
 * @property int $uploadFileMaxCount Maximum upload files count.
61
 * @property int $uploadFileMaxSize Upload file max size in bytes.
62
 *
63
 * @author Paul Klimov <[email protected]>
64
 * @since 2.0.10
65
 */
66
class MultipartFormDataParser extends BaseObject implements RequestParserInterface
67
{
68
    /**
69
     * @var bool whether to parse raw body even for 'POST' request and `$_FILES` already populated.
70
     * By default this option is disabled saving performance for 'POST' requests, which are already
71
     * processed by PHP automatically.
72
     * > Note: if this option is enabled, value of `$_FILES` will be reset on each parse.
73
     * @since 2.0.13
74
     */
75
    public $force = false;
76
77
    /**
78
     * @var int upload file max size in bytes.
79
     */
80
    private $_uploadFileMaxSize;
81
    /**
82
     * @var int maximum upload files count.
83
     */
84
    private $_uploadFileMaxCount;
85
86
87
    /**
88
     * @return int upload file max size in bytes.
89
     */
90 4
    public function getUploadFileMaxSize()
91
    {
92 4
        if ($this->_uploadFileMaxSize === null) {
93 3
            $this->_uploadFileMaxSize = $this->getByteSize(ini_get('upload_max_filesize'));
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->getByteSize(ini_g...'upload_max_filesize')) can also be of type double. However, the property $_uploadFileMaxSize is declared as type integer. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
94
        }
95 4
        return $this->_uploadFileMaxSize;
96
    }
97
98
    /**
99
     * @param int $uploadFileMaxSize upload file max size in bytes.
100
     */
101 1
    public function setUploadFileMaxSize($uploadFileMaxSize)
102
    {
103 1
        $this->_uploadFileMaxSize = $uploadFileMaxSize;
104 1
    }
105
106
    /**
107
     * @return int maximum upload files count.
108
     */
109 4
    public function getUploadFileMaxCount()
110
    {
111 4
        if ($this->_uploadFileMaxCount === null) {
112 3
            $this->_uploadFileMaxCount = ini_get('max_file_uploads');
0 ignored issues
show
Documentation Bug introduced by
The property $_uploadFileMaxCount was declared of type integer, but ini_get('max_file_uploads') is of type string. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
113
        }
114 4
        return $this->_uploadFileMaxCount;
115
    }
116
117
    /**
118
     * @param int $uploadFileMaxCount maximum upload files count.
119
     */
120 1
    public function setUploadFileMaxCount($uploadFileMaxCount)
121
    {
122 1
        $this->_uploadFileMaxCount = $uploadFileMaxCount;
123 1
    }
124
125
    /**
126
     * {@inheritdoc}
127
     */
128 6
    public function parse($request)
129
    {
130 6
        if (!$this->force) {
131 5
            if (!empty($_POST) || !empty($_FILES)) {
132
                // normal POST request is parsed by PHP automatically
133 5
                return $_POST;
134
            }
135
        } else {
136 1
            $_FILES = [];
137
        }
138
139 4
        $contentType = $request->getContentType();
140 4
        $rawBody = $request->getBody()->__toString();
141
142 4
        if (empty($rawBody)) {
143
            return [];
144
        }
145
146 4
        if (!preg_match('/boundary=(.*)$/is', $contentType, $matches)) {
147
            return [];
148
        }
149 4
        $boundary = $matches[1];
150
151 4
        $bodyParts = preg_split('/\\R?-+' . preg_quote($boundary, '/') . '/s', $rawBody);
152 4
        array_pop($bodyParts); // last block always has no data, contains boundary ending like `--`
153
154 4
        $bodyParams = [];
155 4
        $filesCount = 0;
156 4
        foreach ($bodyParts as $bodyPart) {
157 4
            if (empty($bodyPart)) {
158 4
                continue;
159
            }
160 4
            [$headers, $value] = preg_split('/\\R\\R/', $bodyPart, 2);
0 ignored issues
show
Bug introduced by
The variable $headers 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...
Bug introduced by
The variable $value does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
161 4
            $headers = $this->parseHeaders($headers);
0 ignored issues
show
Documentation introduced by
$headers is of type array, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
162
163 4
            if (!isset($headers['content-disposition']['name'])) {
164
                continue;
165
            }
166
167 4
            if (isset($headers['content-disposition']['filename'])) {
168
                // file upload:
169 4
                if ($filesCount >= $this->getUploadFileMaxCount()) {
170 1
                    continue;
171
                }
172
173
                $fileInfo = [
174 4
                    'name' => $headers['content-disposition']['filename'],
175 4
                    'type' => ArrayHelper::getValue($headers, 'content-type', 'application/octet-stream'),
176 4
                    'size' => StringHelper::byteLength($value),
177 4
                    'error' => UPLOAD_ERR_OK,
178
                    'tmp_name' => null,
179
                ];
180
181 4
                if ($fileInfo['size'] > $this->getUploadFileMaxSize()) {
182 1
                    $fileInfo['error'] = UPLOAD_ERR_INI_SIZE;
183
                } else {
184 4
                    $tmpResource = tmpfile();
185 4
                    if ($tmpResource === false) {
186
                        $fileInfo['error'] = UPLOAD_ERR_CANT_WRITE;
187
                    } else {
188 4
                        $tmpResourceMetaData = stream_get_meta_data($tmpResource);
189 4
                        $tmpFileName = $tmpResourceMetaData['uri'];
190 4
                        if (empty($tmpFileName)) {
191
                            $fileInfo['error'] = UPLOAD_ERR_CANT_WRITE;
192
                            @fclose($tmpResource);
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...
193
                        } else {
194 4
                            fwrite($tmpResource, $value);
195 4
                            $fileInfo['tmp_name'] = $tmpFileName;
196 4
                            $fileInfo['tmp_resource'] = $tmpResource; // save file resource, otherwise it will be deleted
197
                        }
198
                    }
199
                }
200
201 4
                $this->addFile($_FILES, $headers['content-disposition']['name'], $fileInfo);
202
203 4
                $filesCount++;
204
            } else {
205
                // regular parameter:
206 4
                $this->addValue($bodyParams, $headers['content-disposition']['name'], $value);
207
            }
208
        }
209
210 4
        return $bodyParams;
211
    }
212
213
    /**
214
     * Parses content part headers.
215
     * @param string $headerContent headers source content
216
     * @return array parsed headers.
217
     */
218 4
    private function parseHeaders($headerContent)
219
    {
220 4
        $headers = [];
221 4
        $headerParts = preg_split('/\\R/s', $headerContent, -1, PREG_SPLIT_NO_EMPTY);
222 4
        foreach ($headerParts as $headerPart) {
223 4
            if (($separatorPos = strpos($headerPart, ':')) === false) {
224
                continue;
225
            }
226
227 4
            [$headerName, $headerValue] = explode(':', $headerPart, 2);
0 ignored issues
show
Bug introduced by
The variable $headerName 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...
Bug introduced by
The variable $headerValue 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...
228 4
            $headerName = strtolower(trim($headerName));
229 4
            $headerValue = trim($headerValue);
230
231 4
            if (strpos($headerValue, ';') === false) {
232 4
                $headers[$headerName] = $headerValue;
233
            } else {
234 4
                $headers[$headerName] = [];
235 4
                foreach (explode(';', $headerValue) as $part) {
236 4
                    $part = trim($part);
237 4
                    if (strpos($part, '=') === false) {
238 4
                        $headers[$headerName][] = $part;
239
                    } else {
240 4
                        [$name, $value] = explode('=', $part, 2);
0 ignored issues
show
Bug introduced by
The variable $name 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...
Bug introduced by
The variable $value 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...
241 4
                        $name = strtolower(trim($name));
242 4
                        $value = trim(trim($value), '"');
243 4
                        $headers[$headerName][$name] = $value;
244
                    }
245
                }
246
            }
247
        }
248
249 4
        return $headers;
250
    }
251
252
    /**
253
     * Adds value to the array by input name, e.g. `Item[name]`.
254
     * @param array $array array which should store value.
255
     * @param string $name input name specification.
256
     * @param mixed $value value to be added.
257
     */
258 2
    private function addValue(&$array, $name, $value)
259
    {
260 2
        $nameParts = preg_split('/\\]\\[|\\[/s', $name);
261 2
        $current = &$array;
262 2
        foreach ($nameParts as $namePart) {
263 2
            $namePart = trim($namePart, ']');
264 2
            if ($namePart === '') {
265
                $current[] = [];
266
                $lastKey = array_pop(array_keys($current));
0 ignored issues
show
Bug introduced by
array_keys($current) cannot be passed to array_pop() as the parameter $array expects a reference.
Loading history...
267
                $current = &$current[$lastKey];
268
            } else {
269 2
                if (!isset($current[$namePart])) {
270 2
                    $current[$namePart] = [];
271
                }
272 2
                $current = &$current[$namePart];
273
            }
274
        }
275 2
        $current = $value;
276 2
    }
277
278
    /**
279
     * Adds file info to the uploaded files array by input name, e.g. `Item[file]`.
280
     * @param array $files array containing uploaded files
281
     * @param string $name input name specification.
282
     * @param array $info file info.
283
     */
284 4
    private function addFile(&$files, $name, $info)
285
    {
286 4
        if (strpos($name, '[') === false) {
287 4
            $files[$name] = $info;
288 4
            return;
289
        }
290
291
        $fileInfoAttributes = [
292 1
            'name',
293
            'type',
294
            'size',
295
            'error',
296
            'tmp_name',
297
            'tmp_resource',
298
        ];
299
300 1
        $nameParts = preg_split('/\\]\\[|\\[/s', $name);
301 1
        $baseName = array_shift($nameParts);
302 1
        if (!isset($files[$baseName])) {
303 1
            $files[$baseName] = [];
304 1
            foreach ($fileInfoAttributes as $attribute) {
305 1
                $files[$baseName][$attribute] = [];
306
            }
307
        } else {
308
            foreach ($fileInfoAttributes as $attribute) {
309
                $files[$baseName][$attribute] = (array) $files[$baseName][$attribute];
310
            }
311
        }
312
313 1
        foreach ($fileInfoAttributes as $attribute) {
314 1
            if (!isset($info[$attribute])) {
315
                continue;
316
            }
317
318 1
            $current = &$files[$baseName][$attribute];
319 1
            foreach ($nameParts as $namePart) {
320 1
                $namePart = trim($namePart, ']');
321 1
                if ($namePart === '') {
322
                    $current[] = [];
323
                    $lastKey = array_pop(array_keys($current));
0 ignored issues
show
Bug introduced by
array_keys($current) cannot be passed to array_pop() as the parameter $array expects a reference.
Loading history...
324
                    $current = &$current[$lastKey];
325
                } else {
326 1
                    if (!isset($current[$namePart])) {
327 1
                        $current[$namePart] = [];
328
                    }
329 1
                    $current = &$current[$namePart];
330
                }
331
            }
332 1
            $current = $info[$attribute];
333
        }
334 1
    }
335
336
    /**
337
     * Gets the size in bytes from verbose size representation.
338
     * For example: '5K' => 5*1024
339
     * @param string $verboseSize verbose size representation.
340
     * @return int actual size in bytes.
341
     */
342 3
    private function getByteSize($verboseSize)
343
    {
344 3
        if (empty($verboseSize)) {
345
            return 0;
346
        }
347 3
        if (is_numeric($verboseSize)) {
348
            return (int) $verboseSize;
349
        }
350 3
        $sizeUnit = trim($verboseSize, '0123456789');
351 3
        $size = str_replace($sizeUnit, '', $verboseSize);
352 3
        $size = trim($size);
353 3
        if (!is_numeric($size)) {
354
            return 0;
355
        }
356 3
        switch (strtolower($sizeUnit)) {
357 3
            case 'kb':
358 3
            case 'k':
359
                return $size * 1024;
360 3
            case 'mb':
361 3
            case 'm':
362 3
                return $size * 1024 * 1024;
363
            case 'gb':
364
            case 'g':
365
                return $size * 1024 * 1024 * 1024;
366
            default:
367
                return 0;
368
        }
369
    }
370
}
371