Completed
Push — 2.1 ( 885479...e0a7ba )
by
unknown
11:53
created

MultipartFormDataParser::setUploadFileMaxCount()   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;
11
use yii\base\BaseObject;
12
use yii\helpers\ArrayHelper;
13
use yii\helpers\StringHelper;
14
use yii\http\ResourceStream;
15
16
/**
17
 * MultipartFormDataParser parses content encoded as 'multipart/form-data'.
18
 * This parser provides the fallback for the 'multipart/form-data' processing on non POST requests,
19
 * for example: the one with 'PUT' request method.
20
 *
21
 * In order to enable this parser you should configure [[Request::$parsers]] in the following way:
22
 *
23
 * ```php
24
 * return [
25
 *     'components' => [
26
 *         'request' => [
27
 *             'parsers' => [
28
 *                 'multipart/form-data' => 'yii\web\MultipartFormDataParser'
29
 *             ],
30
 *         ],
31
 *         // ...
32
 *     ],
33
 *     // ...
34
 * ];
35
 * ```
36
 *
37
 * Method [[parse()]] of this parser automatically populates [[Request::$uploadedFiles]] with the files parsed from raw body.
38
 *
39
 * Usage example:
40
 *
41
 * ```php
42
 * use yii\http\UploadedFile;
43
 *
44
 * $restRequestData = Yii::$app->request->getBodyParams();
45
 * $uploadedFile = Yii::$app->request->getUploadedFileByName('photo');
46
 *
47
 * $model = new Item();
48
 * $model->populate($restRequestData);
49
 * copy($uploadedFile->tempName, '/path/to/file/storage/photo.jpg');
50
 * ```
51
 *
52
 * > Note: although this parser populates temporary file name for the uploaded file instance, such temporary file will
53
 * not be recognized by PHP as uploaded one. Thus functions like `is_uploaded_file()` and `move_uploaded_file()` will
54
 * fail on it. This also means [[UploadedFile::saveAs()]] will fail as well.
55
 *
56
 * @property int $uploadFileMaxCount Maximum upload files count.
57
 * @property int $uploadFileMaxSize Upload file max size in bytes.
58
 *
59
 * @author Paul Klimov <[email protected]>
60
 * @since 2.0.10
61
 */
62
class MultipartFormDataParser extends BaseObject implements RequestParserInterface
63
{
64
    /**
65
     * @var bool whether to parse raw body even for 'POST' request and `$_FILES` already populated.
66
     * By default this option is disabled saving performance for 'POST' requests, which are already
67
     * processed by PHP automatically.
68
     * > Note: if this option is enabled, value of [[Request::$uploadedFiles]] will be reset on each parse.
69
     * @since 2.0.13
70
     */
71
    public $force = false;
72
73
    /**
74
     * @var int upload file max size in bytes.
75
     */
76
    private $_uploadFileMaxSize;
77
    /**
78
     * @var int maximum upload files count.
79
     */
80
    private $_uploadFileMaxCount;
81
82
83
    /**
84
     * @return int upload file max size in bytes.
85
     */
86 4
    public function getUploadFileMaxSize()
87
    {
88 4
        if ($this->_uploadFileMaxSize === null) {
89 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...
90
        }
91 4
        return $this->_uploadFileMaxSize;
92
    }
93
94
    /**
95
     * @param int $uploadFileMaxSize upload file max size in bytes.
96
     */
97 1
    public function setUploadFileMaxSize($uploadFileMaxSize)
98
    {
99 1
        $this->_uploadFileMaxSize = $uploadFileMaxSize;
100 1
    }
101
102
    /**
103
     * @return int maximum upload files count.
104
     */
105 4
    public function getUploadFileMaxCount()
106
    {
107 4
        if ($this->_uploadFileMaxCount === null) {
108 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...
109
        }
110 4
        return $this->_uploadFileMaxCount;
111
    }
112
113
    /**
114
     * @param int $uploadFileMaxCount maximum upload files count.
115
     */
116 1
    public function setUploadFileMaxCount($uploadFileMaxCount)
117
    {
118 1
        $this->_uploadFileMaxCount = $uploadFileMaxCount;
119 1
    }
120
121
    /**
122
     * {@inheritdoc}
123
     */
124 6
    public function parse($request)
125
    {
126 6
        if (!$this->force) {
127 5
            if (!empty($_POST) || !empty($_FILES)) {
128
                // normal POST request is parsed by PHP automatically
129 2
                return $_POST;
130
            }
131
        }
132
133 4
        $uploadedFiles = [];
134
135 4
        $contentType = $request->getContentType();
136 4
        $rawBody = $request->getBody()->__toString();
137
138 4
        if (empty($rawBody)) {
139
            return [];
140
        }
141
142 4
        if (!preg_match('/boundary=(.*)$/is', $contentType, $matches)) {
143
            return [];
144
        }
145 4
        $boundary = $matches[1];
146
147 4
        $bodyParts = preg_split('/\\R?-+' . preg_quote($boundary, '/') . '/s', $rawBody);
148 4
        array_pop($bodyParts); // last block always has no data, contains boundary ending like `--`
149
150 4
        $bodyParams = [];
151 4
        $filesCount = 0;
152 4
        foreach ($bodyParts as $bodyPart) {
153 4
            if (empty($bodyPart)) {
154 4
                continue;
155
            }
156 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...
157 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...
158
159 4
            if (!isset($headers['content-disposition']['name'])) {
160
                continue;
161
            }
162
163 4
            if (isset($headers['content-disposition']['filename'])) {
164
                // file upload:
165 4
                if ($filesCount >= $this->getUploadFileMaxCount()) {
166 1
                    continue;
167
                }
168
169
                $fileConfig = [
170 4
                    'class' => $request->uploadedFileClass,
171 4
                    'clientFilename' => $headers['content-disposition']['filename'],
172 4
                    'clientMediaType' => ArrayHelper::getValue($headers, 'content-type', 'application/octet-stream'),
173 4
                    'size' => StringHelper::byteLength($value),
174 4
                    'error' => UPLOAD_ERR_OK,
175
                    'tempFilename' => null,
176
                ];
177
178 4
                if ($fileConfig['size'] > $this->getUploadFileMaxSize()) {
179 1
                    $fileConfig['error'] = UPLOAD_ERR_INI_SIZE;
180
                } else {
181 4
                    $tmpResource = tmpfile();
182 4
                    if ($tmpResource === false) {
183
                        $fileConfig['error'] = UPLOAD_ERR_CANT_WRITE;
184
                    } else {
185 4
                        $tmpResourceMetaData = stream_get_meta_data($tmpResource);
186 4
                        $tmpFileName = $tmpResourceMetaData['uri'];
187 4
                        if (empty($tmpFileName)) {
188
                            $fileConfig['error'] = UPLOAD_ERR_CANT_WRITE;
189
                            @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...
190
                        } else {
191 4
                            fwrite($tmpResource, $value);
192 4
                            $fileConfig['tempFilename'] = $tmpFileName;
193 4
                            $fileConfig['stream'] = new ResourceStream(['resource' => $tmpResource]); // save file resource, otherwise it will be deleted
194
                        }
195
                    }
196
                }
197
198 4
                $this->addValue($uploadedFiles, $headers['content-disposition']['name'], Yii::createObject($fileConfig));
199
200 4
                $filesCount++;
201
            } else {
202
                // regular parameter:
203 4
                $this->addValue($bodyParams, $headers['content-disposition']['name'], $value);
204
            }
205
        }
206
207 4
        $request->setUploadedFiles($uploadedFiles);
208
209 4
        return $bodyParams;
210
    }
211
212
    /**
213
     * Parses content part headers.
214
     * @param string $headerContent headers source content
215
     * @return array parsed headers.
216
     */
217 4
    private function parseHeaders($headerContent)
218
    {
219 4
        $headers = [];
220 4
        $headerParts = preg_split('/\\R/s', $headerContent, -1, PREG_SPLIT_NO_EMPTY);
221 4
        foreach ($headerParts as $headerPart) {
222 4
            if (($separatorPos = strpos($headerPart, ':')) === false) {
223
                continue;
224
            }
225
226 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...
227 4
            $headerName = strtolower(trim($headerName));
228 4
            $headerValue = trim($headerValue);
229
230 4
            if (strpos($headerValue, ';') === false) {
231 4
                $headers[$headerName] = $headerValue;
232
            } else {
233 4
                $headers[$headerName] = [];
234 4
                foreach (explode(';', $headerValue) as $part) {
235 4
                    $part = trim($part);
236 4
                    if (strpos($part, '=') === false) {
237 4
                        $headers[$headerName][] = $part;
238
                    } else {
239 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...
240 4
                        $name = strtolower(trim($name));
241 4
                        $value = trim(trim($value), '"');
242 4
                        $headers[$headerName][$name] = $value;
243
                    }
244
                }
245
            }
246
        }
247
248 4
        return $headers;
249
    }
250
251
    /**
252
     * Adds value to the array by input name, e.g. `Item[name]`.
253
     * @param array $array array which should store value.
254
     * @param string $name input name specification.
255
     * @param mixed $value value to be added.
256
     */
257 4
    private function addValue(&$array, $name, $value)
258
    {
259 4
        $nameParts = preg_split('/\\]\\[|\\[/s', $name);
260 4
        $current = &$array;
261 4
        foreach ($nameParts as $namePart) {
262 4
            $namePart = trim($namePart, ']');
263 4
            if ($namePart === '') {
264
                $current[] = [];
265
                $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...
266
                $current = &$current[$lastKey];
267
            } else {
268 4
                if (!isset($current[$namePart])) {
269 4
                    $current[$namePart] = [];
270
                }
271 4
                $current = &$current[$namePart];
272
            }
273
        }
274 4
        $current = $value;
275 4
    }
276
277
    /**
278
     * Gets the size in bytes from verbose size representation.
279
     * For example: '5K' => 5*1024
280
     * @param string $verboseSize verbose size representation.
281
     * @return int actual size in bytes.
282
     */
283 3
    private function getByteSize($verboseSize)
284
    {
285 3
        if (empty($verboseSize)) {
286
            return 0;
287
        }
288 3
        if (is_numeric($verboseSize)) {
289
            return (int) $verboseSize;
290
        }
291 3
        $sizeUnit = trim($verboseSize, '0123456789');
292 3
        $size = str_replace($sizeUnit, '', $verboseSize);
293 3
        $size = trim($size);
294 3
        if (!is_numeric($size)) {
295
            return 0;
296
        }
297 3
        switch (strtolower($sizeUnit)) {
298 3
            case 'kb':
299 3
            case 'k':
300
                return $size * 1024;
301 3
            case 'mb':
302 3
            case 'm':
303 3
                return $size * 1024 * 1024;
304
            case 'gb':
305
            case 'g':
306
                return $size * 1024 * 1024 * 1024;
307
            default:
308
                return 0;
309
        }
310
    }
311
}
312