GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — master ( f9fd4d...f5c98f )
by Robert
11:43
created

MultipartFormDataParser::parseHeaders()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 33
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 20
CRAP Score 6.0038

Importance

Changes 0
Metric Value
dl 0
loc 33
ccs 20
cts 21
cp 0.9524
rs 8.439
c 0
b 0
f 0
cc 6
eloc 23
nc 6
nop 1
crap 6.0038
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\web\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
96 4
        return $this->_uploadFileMaxSize;
97
    }
98
99
    /**
100
     * @param int $uploadFileMaxSize upload file max size in bytes.
101
     */
102 1
    public function setUploadFileMaxSize($uploadFileMaxSize)
103
    {
104 1
        $this->_uploadFileMaxSize = $uploadFileMaxSize;
105 1
    }
106
107
    /**
108
     * @return int maximum upload files count.
109
     */
110 4
    public function getUploadFileMaxCount()
111
    {
112 4
        if ($this->_uploadFileMaxCount === null) {
113 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...
114
        }
115
116 4
        return $this->_uploadFileMaxCount;
117
    }
118
119
    /**
120
     * @param int $uploadFileMaxCount maximum upload files count.
121
     */
122 1
    public function setUploadFileMaxCount($uploadFileMaxCount)
123
    {
124 1
        $this->_uploadFileMaxCount = $uploadFileMaxCount;
125 1
    }
126
127
    /**
128
     * @inheritdoc
129
     */
130 6
    public function parse($rawBody, $contentType)
131
    {
132 6
        if (!$this->force) {
133 5
            if (!empty($_POST) || !empty($_FILES)) {
134
                // normal POST request is parsed by PHP automatically
135 5
                return $_POST;
136
            }
137
        } else {
138 1
            $_FILES = [];
139
        }
140
141 4
        if (empty($rawBody)) {
142
            return [];
143
        }
144
145 4
        if (!preg_match('/boundary=(.*)$/is', $contentType, $matches)) {
146
            return [];
147
        }
148 4
        $boundary = $matches[1];
149
150 4
        $bodyParts = preg_split('/\\R?-+' . preg_quote($boundary, '/') . '/s', $rawBody);
151 4
        array_pop($bodyParts); // last block always has no data, contains boundary ending like `--`
152
153 4
        $bodyParams = [];
154 4
        $filesCount = 0;
155 4
        foreach ($bodyParts as $bodyPart) {
156 4
            if (empty($bodyPart)) {
157 4
                continue;
158
            }
159 4
            list($headers, $value) = preg_split('/\\R\\R/', $bodyPart, 2);
160 4
            $headers = $this->parseHeaders($headers);
161
162 4
            if (!isset($headers['content-disposition']['name'])) {
163
                continue;
164
            }
165
166 4
            if (isset($headers['content-disposition']['filename'])) {
167
                // file upload:
168 4
                if ($filesCount >= $this->getUploadFileMaxCount()) {
169 1
                    continue;
170
                }
171
172
                $fileInfo = [
173 4
                    'name' => $headers['content-disposition']['filename'],
174 4
                    'type' => ArrayHelper::getValue($headers, 'content-type', 'application/octet-stream'),
175 4
                    'size' => StringHelper::byteLength($value),
176 4
                    'error' => UPLOAD_ERR_OK,
177
                    'tmp_name' => null,
178
                ];
179
180 4
                if ($fileInfo['size'] > $this->getUploadFileMaxSize()) {
181 1
                    $fileInfo['error'] = UPLOAD_ERR_INI_SIZE;
182
                } else {
183 4
                    $tmpResource = tmpfile();
184 4
                    if ($tmpResource === false) {
185
                        $fileInfo['error'] = UPLOAD_ERR_CANT_WRITE;
186
                    } else {
187 4
                        $tmpResourceMetaData = stream_get_meta_data($tmpResource);
188 4
                        $tmpFileName = $tmpResourceMetaData['uri'];
189 4
                        if (empty($tmpFileName)) {
190
                            $fileInfo['error'] = UPLOAD_ERR_CANT_WRITE;
191
                            @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...
192
                        } else {
193 4
                            fwrite($tmpResource, $value);
194 4
                            $fileInfo['tmp_name'] = $tmpFileName;
195 4
                            $fileInfo['tmp_resource'] = $tmpResource; // save file resource, otherwise it will be deleted
196
                        }
197
                    }
198
                }
199
200 4
                $this->addFile($_FILES, $headers['content-disposition']['name'], $fileInfo);
201
202 4
                $filesCount++;
203
            } else {
204
                // regular parameter:
205 4
                $this->addValue($bodyParams, $headers['content-disposition']['name'], $value);
206
            }
207
        }
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
            list($headerName, $headerValue) = explode(':', $headerPart, 2);
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
                        list($name, $value) = explode('=', $part, 2);
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 2
    private function addValue(&$array, $name, $value)
258
    {
259 2
        $nameParts = preg_split('/\\]\\[|\\[/s', $name);
260 2
        $current = &$array;
261 2
        foreach ($nameParts as $namePart) {
262 2
            $namePart = trim($namePart, ']');
263 2
            if ($namePart === '') {
264
                $current[] = [];
265
                $keys = array_keys($current);
266
                $lastKey = array_pop($keys);
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
     *
339
     * For example: '5K' => 5*1024.
340
     * @param string $verboseSize verbose size representation.
341
     * @return int actual size in bytes.
342
     */
343 3
    private function getByteSize($verboseSize)
344
    {
345 3
        if (empty($verboseSize)) {
346
            return 0;
347
        }
348 3
        if (is_numeric($verboseSize)) {
349
            return (int) $verboseSize;
350
        }
351 3
        $sizeUnit = trim($verboseSize, '0123456789');
352 3
        $size = str_replace($sizeUnit, '', $verboseSize);
353 3
        $size = trim($size);
354 3
        if (!is_numeric($size)) {
355
            return 0;
356
        }
357 3
        switch (strtolower($sizeUnit)) {
358 3
            case 'kb':
359 3
            case 'k':
360
                return $size * 1024;
361 3
            case 'mb':
362 3
            case 'm':
363 3
                return $size * 1024 * 1024;
364
            case 'gb':
365
            case 'g':
366
                return $size * 1024 * 1024 * 1024;
367
            default:
368
                return 0;
369
        }
370
    }
371
}
372