FileValidator::init()   F
last analyzed

Complexity

Conditions 11
Paths 1024

Size

Total Lines 36
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 24
CRAP Score 11

Importance

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

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

348
    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...
349
    {
350 1
        $value = is_array($value) ? reset($value) : $value;
351 1
        return !($value instanceof UploadedFile) || $value->error == UPLOAD_ERR_NO_FILE;
352
    }
353
354
    /**
355
     * Converts php.ini style size to bytes.
356
     *
357
     * @param string $sizeStr $sizeStr
358
     * @return int
359
     */
360 2
    private function sizeToBytes($sizeStr)
361
    {
362 2
        switch (substr($sizeStr, -1)) {
363 2
            case 'M':
364
            case 'm':
365 2
                return (int) $sizeStr * 1048576;
366
            case 'K':
367
            case 'k':
368
                return (int) $sizeStr * 1024;
369
            case 'G':
370
            case 'g':
371
                return (int) $sizeStr * 1073741824;
372
            default:
373
                return (int) $sizeStr;
374
        }
375
    }
376
377
    /**
378
     * Checks if given uploaded file have correct type (extension) according current validator settings.
379
     * @param UploadedFile $file
380
     * @return bool
381
     */
382 17
    protected function validateExtension($file)
383
    {
384 17
        $extension = mb_strtolower($file->extension, 'UTF-8');
385
386 17
        if ($this->checkExtensionByMimeType) {
387 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...
388 13
            if ($mimeType === null) {
0 ignored issues
show
introduced by
The condition $mimeType === null is always true.
Loading history...
389
                return false;
390
            }
391
392 13
            $extensionsByMimeType = FileHelper::getExtensionsByMimeType($mimeType);
393
394 13
            if (!in_array($extension, $extensionsByMimeType, true)) {
395
                return false;
396
            }
397
        }
398
399 17
        if (!empty($this->extensions)) {
400 17
            foreach ((array) $this->extensions as $ext) {
401 17
                if ($extension === $ext || StringHelper::endsWith($file->name, ".$ext", false)) {
402 12
                    return true;
403
                }
404
            }
405 8
            return false;
406
        }
407
408
        return true;
409
    }
410
411
    /**
412
     * {@inheritdoc}
413
     */
414
    public function clientValidateAttribute($model, $attribute, $view)
415
    {
416
        ValidationAsset::register($view);
417
        $options = $this->getClientOptions($model, $attribute);
418
        return 'yii.validation.file(attribute, messages, ' . Json::htmlEncode($options) . ');';
419
    }
420
421
    /**
422
     * {@inheritdoc}
423
     */
424
    public function getClientOptions($model, $attribute)
425
    {
426
        $label = $model->getAttributeLabel($attribute);
427
428
        $options = [];
429
        if ($this->message !== null) {
430
            $options['message'] = $this->formatMessage($this->message, [
431
                'attribute' => $label,
432
            ]);
433
        }
434
435
        $options['skipOnEmpty'] = $this->skipOnEmpty;
436
437
        if (!$this->skipOnEmpty) {
438
            $options['uploadRequired'] = $this->formatMessage($this->uploadRequired, [
439
                'attribute' => $label,
440
            ]);
441
        }
442
443
        if ($this->mimeTypes !== null) {
444
            $mimeTypes = [];
445
            foreach ($this->mimeTypes as $mimeType) {
446
                $mimeTypes[] = new JsExpression(Html::escapeJsRegularExpression($this->buildMimeTypeRegexp($mimeType)));
447
            }
448
            $options['mimeTypes'] = $mimeTypes;
449
            $options['wrongMimeType'] = $this->formatMessage($this->wrongMimeType, [
450
                'attribute' => $label,
451
                '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

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