Passed
Push — master ( e1268d...e92466 )
by Alexander
10:23
created

FileValidator::validateAttribute()   B

Complexity

Conditions 10
Paths 13

Size

Total Lines 21
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 10.2918

Importance

Changes 0
Metric Value
cc 10
eloc 13
nc 13
nop 2
dl 0
loc 21
ccs 12
cts 14
cp 0.8571
crap 10.2918
rs 7.6666
c 0
b 0
f 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * @link https://www.yiiframework.com/
5
 * @copyright Copyright (c) 2008 Yii Software LLC
6
 * @license https://www.yiiframework.com/license/
7
 */
8
9
namespace yii\validators;
10
11
use Yii;
12
use yii\helpers\FileHelper;
13
use yii\helpers\Html;
14
use yii\helpers\Json;
15
use yii\helpers\StringHelper;
16
use yii\web\JsExpression;
17
use yii\web\UploadedFile;
18
19
/**
20
 * FileValidator verifies if an attribute is receiving a valid uploaded file.
21
 *
22
 * Note that you should enable `fileinfo` PHP extension.
23
 *
24
 * @property-read int $sizeLimit The size limit for uploaded files.
25
 *
26
 * @author Qiang Xue <[email protected]>
27
 * @since 2.0
28
 */
29
class FileValidator extends Validator
30
{
31
    /**
32
     * @var array|string|null a list of file name extensions that are allowed to be uploaded.
33
     * This can be either an array or a string consisting of file extension names
34
     * separated by space or comma (e.g. "gif, jpg").
35
     * Extension names are case-insensitive. Defaults to null, meaning all file name
36
     * extensions are allowed.
37
     * @see wrongExtension for the customized message for wrong file type.
38
     */
39
    public $extensions;
40
    /**
41
     * @var bool whether to check file type (extension) with mime-type. If extension produced by
42
     * file mime-type check differs from uploaded file extension, the file will be considered as invalid.
43
     */
44
    public $checkExtensionByMimeType = true;
45
    /**
46
     * @var array|string|null a list of file MIME types that are allowed to be uploaded.
47
     * This can be either an array or a string consisting of file MIME types
48
     * separated by space or comma (e.g. "text/plain, image/png").
49
     * The mask with the special character `*` can be used to match groups of mime types.
50
     * For example `image/*` will pass all mime types, that begin with `image/` (e.g. `image/jpeg`, `image/png`).
51
     * Mime type names are case-insensitive. Defaults to null, meaning all MIME types are allowed.
52
     * @see wrongMimeType for the customized message for wrong MIME type.
53
     */
54
    public $mimeTypes;
55
    /**
56
     * @var int|null the minimum number of bytes required for the uploaded file.
57
     * Defaults to null, meaning no limit.
58
     * @see tooSmall for the customized message for a file that is too small.
59
     */
60
    public $minSize;
61
    /**
62
     * @var int|null the maximum number of bytes required for the uploaded file.
63
     * Defaults to null, meaning no limit.
64
     * Note, the size limit is also affected by `upload_max_filesize` and `post_max_size` INI setting
65
     * and the 'MAX_FILE_SIZE' hidden field value. See [[getSizeLimit()]] for details.
66
     * @see https://www.php.net/manual/en/ini.core.php#ini.upload-max-filesize
67
     * @see https://www.php.net/post-max-size
68
     * @see getSizeLimit
69
     * @see tooBig for the customized message for a file that is too big.
70
     */
71
    public $maxSize;
72
    /**
73
     * @var int the maximum file count the given attribute can hold.
74
     * Defaults to 1, meaning single file upload. By defining a higher number,
75
     * multiple uploads become possible. Setting it to `0` means there is no limit on
76
     * the number of files that can be uploaded simultaneously.
77
     *
78
     * > Note: The maximum number of files allowed to be uploaded simultaneously is
79
     * also limited with PHP directive `max_file_uploads`, which defaults to 20.
80
     *
81
     * @see https://www.php.net/manual/en/ini.core.php#ini.max-file-uploads
82
     * @see tooMany for the customized message when too many files are uploaded.
83
     */
84
    public $maxFiles = 1;
85
    /**
86
     * @var int the minimum file count the given attribute can hold.
87
     * Defaults to 0. Higher value means at least that number of files should be uploaded.
88
     *
89
     * @see tooFew for the customized message when too few files are uploaded.
90
     * @since 2.0.14
91
     */
92
    public $minFiles = 0;
93
    /**
94
     * @var string the error message used when a file is not uploaded correctly.
95
     */
96
    public $message;
97
    /**
98
     * @var string the error message used when no file is uploaded.
99
     * Note that this is the text of the validation error message. To make uploading files required,
100
     * you have to set [[skipOnEmpty]] to `false`.
101
     */
102
    public $uploadRequired;
103
    /**
104
     * @var string the error message used when the uploaded file is too large.
105
     * You may use the following tokens in the message:
106
     *
107
     * - {attribute}: the attribute name
108
     * - {file}: the uploaded file name
109
     * - {limit}: the maximum size allowed (see [[getSizeLimit()]])
110
     * - {formattedLimit}: the maximum size formatted
111
     *   with [[\yii\i18n\Formatter::asShortSize()|Formatter::asShortSize()]]
112
     */
113
    public $tooBig;
114
    /**
115
     * @var string the error message used when the uploaded file is too small.
116
     * You may use the following tokens in the message:
117
     *
118
     * - {attribute}: the attribute name
119
     * - {file}: the uploaded file name
120
     * - {limit}: the value of [[minSize]]
121
     * - {formattedLimit}: the value of [[minSize]] formatted
122
     *   with [[\yii\i18n\Formatter::asShortSize()|Formatter::asShortSize()]
123
     */
124
    public $tooSmall;
125
    /**
126
     * @var string the error message used if the count of multiple uploads exceeds limit.
127
     * You may use the following tokens in the message:
128
     *
129
     * - {attribute}: the attribute name
130
     * - {limit}: the value of [[maxFiles]]
131
     */
132
    public $tooMany;
133
    /**
134
     * @var string the error message used if the count of multiple uploads less that minFiles.
135
     * You may use the following tokens in the message:
136
     *
137
     * - {attribute}: the attribute name
138
     * - {limit}: the value of [[minFiles]]
139
     *
140
     * @since 2.0.14
141
     */
142
    public $tooFew;
143
    /**
144
     * @var string the error message used when the uploaded file has an extension name
145
     * that is not listed in [[extensions]]. You may use the following tokens in the message:
146
     *
147
     * - {attribute}: the attribute name
148
     * - {file}: the uploaded file name
149
     * - {extensions}: the list of the allowed extensions.
150
     */
151
    public $wrongExtension;
152
    /**
153
     * @var string the error message used when the file has an mime type
154
     * that is not allowed by [[mimeTypes]] property.
155
     * You may use the following tokens in the message:
156
     *
157
     * - {attribute}: the attribute name
158
     * - {file}: the uploaded file name
159
     * - {mimeTypes}: the value of [[mimeTypes]]
160
     */
161
    public $wrongMimeType;
162
163
164
    /**
165
     * {@inheritdoc}
166
     */
167 53
    public function init()
168
    {
169 53
        parent::init();
170 53
        if ($this->message === null) {
171 53
            $this->message = Yii::t('yii', 'File upload failed.');
172
        }
173 53
        if ($this->uploadRequired === null) {
174 53
            $this->uploadRequired = Yii::t('yii', 'Please upload a file.');
175
        }
176 53
        if ($this->tooMany === null) {
177 53
            $this->tooMany = Yii::t('yii', 'You can upload at most {limit, number} {limit, plural, one{file} other{files}}.');
178
        }
179 53
        if ($this->tooFew === null) {
180 53
            $this->tooFew = Yii::t('yii', 'You should upload at least {limit, number} {limit, plural, one{file} other{files}}.');
181
        }
182 53
        if ($this->wrongExtension === null) {
183 53
            $this->wrongExtension = Yii::t('yii', 'Only files with these extensions are allowed: {extensions}.');
184
        }
185 53
        if ($this->tooBig === null) {
186 53
            $this->tooBig = Yii::t('yii', 'The file "{file}" is too big. Its size cannot exceed {formattedLimit}.');
187
        }
188 53
        if ($this->tooSmall === null) {
189 53
            $this->tooSmall = Yii::t('yii', 'The file "{file}" is too small. Its size cannot be smaller than {formattedLimit}.');
190
        }
191 53
        if (!is_array($this->extensions)) {
192 38
            $this->extensions = preg_split('/[\s,]+/', strtolower((string)$this->extensions), -1, PREG_SPLIT_NO_EMPTY);
193
        } else {
194 17
            $this->extensions = array_map('strtolower', $this->extensions);
195
        }
196 53
        if ($this->wrongMimeType === null) {
197 53
            $this->wrongMimeType = Yii::t('yii', 'Only files with these MIME types are allowed: {mimeTypes}.');
198
        }
199 53
        if (!is_array($this->mimeTypes)) {
200 53
            $this->mimeTypes = preg_split('/[\s,]+/', strtolower((string)$this->mimeTypes), -1, PREG_SPLIT_NO_EMPTY);
201
        } else {
202 1
            $this->mimeTypes = array_map('strtolower', $this->mimeTypes);
203
        }
204
    }
205
206
    /**
207
     * {@inheritdoc}
208
     */
209 18
    public function validateAttribute($model, $attribute)
210
    {
211 18
        $files = $this->filterFiles(is_array($model->$attribute) ? $model->$attribute : [$model->$attribute]);
212 18
        $filesCount = count($files);
213 18
        if ($filesCount === 0 && $this->minFiles > 0) {
214
            $this->addError($model, $attribute, $this->uploadRequired);
215
216
            return;
217
        }
218
219 18
        if ($this->maxFiles > 0 && $filesCount > $this->maxFiles) {
220 2
            $this->addError($model, $attribute, $this->tooMany, ['limit' => $this->maxFiles]);
221
        }
222 18
        if ($this->minFiles > 0 && $this->minFiles > $filesCount) {
223 2
            $this->addError($model, $attribute, $this->tooFew, ['limit' => $this->minFiles]);
224
        }
225
226 18
        foreach ($files as $file) {
227 18
            $result = $this->validateValue($file);
228 18
            if (!empty($result)) {
229 8
                $this->addError($model, $attribute, $result[0], $result[1]);
230
            }
231
        }
232
    }
233
234
    /**
235
     * Files filter.
236
     * @param array $files
237
     * @return UploadedFile[]
238
     */
239 18
    private function filterFiles(array $files)
240
    {
241 18
        $result = [];
242
243 18
        foreach ($files as $fileName => $file) {
244 18
            if ($file instanceof UploadedFile && $file->error !== UPLOAD_ERR_NO_FILE) {
245 18
                $result[$fileName] = $file;
246
            }
247
        }
248
249 18
        return $result;
250
    }
251
252
    /**
253
     * {@inheritdoc}
254
     */
255 48
    protected function validateValue($value)
256
    {
257 48
        if (!$value instanceof UploadedFile || $value->error == UPLOAD_ERR_NO_FILE) {
258
            return [$this->uploadRequired, []];
259
        }
260
261 48
        switch ($value->error) {
262 48
            case UPLOAD_ERR_OK:
263 44
                if ($this->maxSize !== null && $value->size > $this->getSizeLimit()) {
264 1
                    return [
265 1
                        $this->tooBig,
266 1
                        [
267 1
                            'file' => $value->name,
268 1
                            'limit' => $this->getSizeLimit(),
269 1
                            'formattedLimit' => Yii::$app->formatter->asShortSize($this->getSizeLimit()),
270 1
                        ],
271 1
                    ];
272 44
                } elseif ($this->minSize !== null && $value->size < $this->minSize) {
273 1
                    return [
274 1
                        $this->tooSmall,
275 1
                        [
276 1
                            'file' => $value->name,
277 1
                            'limit' => $this->minSize,
278 1
                            'formattedLimit' => Yii::$app->formatter->asShortSize($this->minSize),
279 1
                        ],
280 1
                    ];
281 44
                } elseif (!empty($this->extensions) && !$this->validateExtension($value)) {
282 8
                    return [$this->wrongExtension, ['file' => $value->name, 'extensions' => implode(', ', $this->extensions)]];
283 39
                } elseif (!empty($this->mimeTypes) && !$this->validateMimeType($value)) {
284 5
                    return [$this->wrongMimeType, ['file' => $value->name, 'mimeTypes' => implode(', ', $this->mimeTypes)]];
0 ignored issues
show
Bug introduced by
It seems like $this->mimeTypes can also be of type string; however, parameter $pieces of implode() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

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

284
                    return [$this->wrongMimeType, ['file' => $value->name, 'mimeTypes' => implode(', ', /** @scrutinizer ignore-type */ $this->mimeTypes)]];
Loading history...
285
                }
286
287 34
                return null;
288 5
            case UPLOAD_ERR_INI_SIZE:
289 5
            case UPLOAD_ERR_FORM_SIZE:
290 1
                return [$this->tooBig, [
291 1
                    'file' => $value->name,
292 1
                    'limit' => $this->getSizeLimit(),
293 1
                    'formattedLimit' => Yii::$app->formatter->asShortSize($this->getSizeLimit()),
294 1
                ]];
295 5
            case UPLOAD_ERR_PARTIAL:
296 2
                Yii::warning('File was only partially uploaded: ' . $value->name, __METHOD__);
297 2
                break;
298 3
            case UPLOAD_ERR_NO_TMP_DIR:
299 1
                Yii::warning('Missing the temporary folder to store the uploaded file: ' . $value->name, __METHOD__);
300 1
                break;
301 2
            case UPLOAD_ERR_CANT_WRITE:
302 1
                Yii::warning('Failed to write the uploaded file to disk: ' . $value->name, __METHOD__);
303 1
                break;
304 1
            case UPLOAD_ERR_EXTENSION:
305 1
                Yii::warning('File upload was stopped by some PHP extension: ' . $value->name, __METHOD__);
306 1
                break;
307
            default:
308
                break;
309
        }
310
311 5
        return [$this->message, []];
312
    }
313
314
    /**
315
     * Returns the maximum size allowed for uploaded files.
316
     *
317
     * This is determined based on four factors:
318
     *
319
     * - 'upload_max_filesize' in php.ini
320
     * - 'post_max_size' in php.ini
321
     * - 'MAX_FILE_SIZE' hidden field
322
     * - [[maxSize]]
323
     *
324
     * @return int the size limit for uploaded files.
325
     */
326 2
    public function getSizeLimit()
327
    {
328
        // Get the lowest between post_max_size and upload_max_filesize, log a warning if the first is < than the latter
329 2
        $limit = $this->sizeToBytes(ini_get('upload_max_filesize'));
330 2
        $postLimit = $this->sizeToBytes(ini_get('post_max_size'));
331 2
        if ($postLimit > 0 && $postLimit < $limit) {
332
            Yii::warning('PHP.ini\'s \'post_max_size\' is less than \'upload_max_filesize\'.', __METHOD__);
333
            $limit = $postLimit;
334
        }
335 2
        if ($this->maxSize !== null && $limit > 0 && $this->maxSize < $limit) {
336 2
            $limit = $this->maxSize;
337
        }
338 2
        if (isset($_POST['MAX_FILE_SIZE']) && $_POST['MAX_FILE_SIZE'] > 0 && $_POST['MAX_FILE_SIZE'] < $limit) {
339 1
            $limit = (int) $_POST['MAX_FILE_SIZE'];
340
        }
341
342 2
        return $limit;
343
    }
344
345
    /**
346
     * {@inheritdoc}
347
     * @param bool $trim
348
     */
349 1
    public function isEmpty($value, $trim = false)
0 ignored issues
show
Unused Code introduced by
The parameter $trim is not used and could be removed. ( Ignorable by Annotation )

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

349
    public function isEmpty($value, /** @scrutinizer ignore-unused */ $trim = false)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
350
    {
351 1
        $value = is_array($value) ? reset($value) : $value;
352 1
        return !($value instanceof UploadedFile) || $value->error == UPLOAD_ERR_NO_FILE;
353
    }
354
355
    /**
356
     * Converts php.ini style size to bytes.
357
     *
358
     * @param string $sizeStr $sizeStr
359
     * @return int
360
     */
361 2
    private function sizeToBytes($sizeStr)
362
    {
363 2
        switch (substr($sizeStr, -1)) {
364 2
            case 'M':
365
            case 'm':
366 2
                return (int) $sizeStr * 1048576;
367
            case 'K':
368
            case 'k':
369
                return (int) $sizeStr * 1024;
370
            case 'G':
371
            case 'g':
372
                return (int) $sizeStr * 1073741824;
373
            default:
374
                return (int) $sizeStr;
375
        }
376
    }
377
378
    /**
379
     * Checks if given uploaded file have correct type (extension) according current validator settings.
380
     * @param UploadedFile $file
381
     * @return bool
382
     */
383 17
    protected function validateExtension($file)
384
    {
385 17
        $extension = mb_strtolower($file->extension, 'UTF-8');
386
387 17
        if ($this->checkExtensionByMimeType) {
388 13
            $mimeType = FileHelper::getMimeType($file->tempName, null, false);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $mimeType is correct as yii\helpers\FileHelper::...>tempName, null, false) targeting yii\helpers\BaseFileHelper::getMimeType() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
389 13
            if ($mimeType === null) {
0 ignored issues
show
introduced by
The condition $mimeType === null is always true.
Loading history...
390
                return false;
391
            }
392
393 13
            $extensionsByMimeType = FileHelper::getExtensionsByMimeType($mimeType);
394
395 13
            if (!in_array($extension, $extensionsByMimeType, true)) {
396
                return false;
397
            }
398
        }
399
400 17
        if (!empty($this->extensions)) {
401 17
            foreach ((array) $this->extensions as $ext) {
402 17
                if ($extension === $ext || StringHelper::endsWith($file->name, ".$ext", false)) {
403 12
                    return true;
404
                }
405
            }
406 8
            return false;
407
        }
408
409
        return true;
410
    }
411
412
    /**
413
     * {@inheritdoc}
414
     */
415
    public function clientValidateAttribute($model, $attribute, $view)
416
    {
417
        ValidationAsset::register($view);
418
        $options = $this->getClientOptions($model, $attribute);
419
        return 'yii.validation.file(attribute, messages, ' . Json::htmlEncode($options) . ');';
420
    }
421
422
    /**
423
     * {@inheritdoc}
424
     */
425
    public function getClientOptions($model, $attribute)
426
    {
427
        $label = $model->getAttributeLabel($attribute);
428
429
        $options = [];
430
        if ($this->message !== null) {
431
            $options['message'] = $this->formatMessage($this->message, [
432
                'attribute' => $label,
433
            ]);
434
        }
435
436
        $options['skipOnEmpty'] = $this->skipOnEmpty;
437
438
        if (!$this->skipOnEmpty) {
439
            $options['uploadRequired'] = $this->formatMessage($this->uploadRequired, [
440
                'attribute' => $label,
441
            ]);
442
        }
443
444
        if ($this->mimeTypes !== null) {
445
            $mimeTypes = [];
446
            foreach ($this->mimeTypes as $mimeType) {
447
                $mimeTypes[] = new JsExpression(Html::escapeJsRegularExpression($this->buildMimeTypeRegexp($mimeType)));
448
            }
449
            $options['mimeTypes'] = $mimeTypes;
450
            $options['wrongMimeType'] = $this->formatMessage($this->wrongMimeType, [
451
                'attribute' => $label,
452
                'mimeTypes' => implode(', ', $this->mimeTypes),
0 ignored issues
show
Bug introduced by
It seems like $this->mimeTypes can also be of type string; however, parameter $pieces of implode() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

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

452
                'mimeTypes' => implode(', ', /** @scrutinizer ignore-type */ $this->mimeTypes),
Loading history...
453
            ]);
454
        }
455
456
        if ($this->extensions !== null) {
457
            $options['extensions'] = $this->extensions;
458
            $options['wrongExtension'] = $this->formatMessage($this->wrongExtension, [
459
                'attribute' => $label,
460
                'extensions' => implode(', ', $this->extensions),
461
            ]);
462
        }
463
464
        if ($this->minSize !== null) {
465
            $options['minSize'] = $this->minSize;
466
            $options['tooSmall'] = $this->formatMessage($this->tooSmall, [
467
                'attribute' => $label,
468
                'limit' => $this->minSize,
469
                'formattedLimit' => Yii::$app->formatter->asShortSize($this->minSize),
470
            ]);
471
        }
472
473
        if ($this->maxSize !== null) {
474
            $options['maxSize'] = $this->maxSize;
475
            $options['tooBig'] = $this->formatMessage($this->tooBig, [
476
                'attribute' => $label,
477
                'limit' => $this->getSizeLimit(),
478
                'formattedLimit' => Yii::$app->formatter->asShortSize($this->getSizeLimit()),
479
            ]);
480
        }
481
482
        if ($this->maxFiles !== null) {
483
            $options['maxFiles'] = $this->maxFiles;
484
            $options['tooMany'] = $this->formatMessage($this->tooMany, [
485
                'attribute' => $label,
486
                'limit' => $this->maxFiles,
487
            ]);
488
        }
489
490
        return $options;
491
    }
492
493
    /**
494
     * Builds the RegExp from the $mask.
495
     *
496
     * @param string $mask
497
     * @return string the regular expression
498
     * @see mimeTypes
499
     */
500 13
    private function buildMimeTypeRegexp($mask)
501
    {
502 13
        return '/^' . str_replace('\*', '.*', preg_quote($mask, '/')) . '$/i';
503
    }
504
505
    /**
506
     * Checks the mimeType of the $file against the list in the [[mimeTypes]] property.
507
     *
508
     * @param UploadedFile $file
509
     * @return bool whether the $file mimeType is allowed
510
     * @throws \yii\base\InvalidConfigException
511
     * @see mimeTypes
512
     * @since 2.0.8
513
     */
514 17
    protected function validateMimeType($file)
515
    {
516 17
        $fileMimeType = $this->getMimeTypeByFile($file->tempName);
517 17
        if ($fileMimeType === null) {
518
            return false;
519
        }
520
521 17
        foreach ($this->mimeTypes as $mimeType) {
522 17
            if (strcasecmp($mimeType, $fileMimeType) === 0) {
523 3
                return true;
524
            }
525
526 14
            if (strpos($mimeType, '*') !== false && preg_match($this->buildMimeTypeRegexp($mimeType), $fileMimeType)) {
527 9
                return true;
528
            }
529
        }
530
531 5
        return false;
532
    }
533
534
    /**
535
     * Get MIME type by file path
536
     *
537
     * @param string $filePath
538
     * @return string|null
539
     * @throws \yii\base\InvalidConfigException
540
     * @since 2.0.26
541
     */
542 13
    protected function getMimeTypeByFile($filePath)
543
    {
544 13
        return FileHelper::getMimeType($filePath);
545
    }
546
}
547