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
/**
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 47
    public function init()
168
    {
169 47
        parent::init();
170 47
        if ($this->message === null) {
171 47
            $this->message = Yii::t('yii', 'File upload failed.');
172
        }
173 47
        if ($this->uploadRequired === null) {
174 47
            $this->uploadRequired = Yii::t('yii', 'Please upload a file.');
175
        }
176 47
        if ($this->tooMany === null) {
177 47
            $this->tooMany = Yii::t('yii', 'You can upload at most {limit, number} {limit, plural, one{file} other{files}}.');
178
        }
179 47
        if ($this->tooFew === null) {
180 47
            $this->tooFew = Yii::t('yii', 'You should upload at least {limit, number} {limit, plural, one{file} other{files}}.');
181
        }
182 47
        if ($this->wrongExtension === null) {
183 47
            $this->wrongExtension = Yii::t('yii', 'Only files with these extensions are allowed: {extensions}.');
184
        }
185 47
        if ($this->tooBig === null) {
186 47
            $this->tooBig = Yii::t('yii', 'The file "{file}" is too big. Its size cannot exceed {formattedLimit}.');
187
        }
188 47
        if ($this->tooSmall === null) {
189 47
            $this->tooSmall = Yii::t('yii', 'The file "{file}" is too small. Its size cannot be smaller than {formattedLimit}.');
190
        }
191 47
        if (!is_array($this->extensions)) {
192 32
            $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 47
        if ($this->wrongMimeType === null) {
197 47
            $this->wrongMimeType = Yii::t('yii', 'Only files with these MIME types are allowed: {mimeTypes}.');
198
        }
199 47
        if (!is_array($this->mimeTypes)) {
200 47
            $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 12
    public function validateAttribute($model, $attribute)
210
    {
211 12
        if ($this->maxFiles != 1 || $this->minFiles > 1) {
212 4
            $rawFiles = $model->$attribute;
213 4
            if (!is_array($rawFiles)) {
214 1
                $this->addError($model, $attribute, $this->uploadRequired);
215
216 1
                return;
217
            }
218
219 4
            $files = $this->filterFiles($rawFiles);
220 4
            $model->$attribute = $files;
221
222 4
            if (empty($files)) {
223 1
                $this->addError($model, $attribute, $this->uploadRequired);
224
225 1
                return;
226
            }
227
228 4
            $filesCount = count($files);
229 4
            if ($this->maxFiles && $filesCount > $this->maxFiles) {
230 1
                $this->addError($model, $attribute, $this->tooMany, ['limit' => $this->maxFiles]);
231
            }
232
233 4
            if ($this->minFiles && $this->minFiles > $filesCount) {
234 1
                $this->addError($model, $attribute, $this->tooFew, ['limit' => $this->minFiles]);
235
            }
236
237 4
            foreach ($files as $file) {
238 4
                $result = $this->validateValue($file);
239 4
                if (!empty($result)) {
240 1
                    $this->addError($model, $attribute, $result[0], $result[1]);
241
                }
242
            }
243
        } else {
244 9
            $result = $this->validateValue($model->$attribute);
245 9
            if (!empty($result)) {
246 8
                $this->addError($model, $attribute, $result[0], $result[1]);
247
            }
248
        }
249
    }
250
251
    /**
252
     * Files filter.
253
     * @param array $files
254
     * @return UploadedFile[]
255
     */
256 4
    private function filterFiles(array $files)
257
    {
258 4
        $result = [];
259
260 4
        foreach ($files as $fileName => $file) {
261 4
            if ($file instanceof UploadedFile && $file->error !== UPLOAD_ERR_NO_FILE) {
262 4
                $result[$fileName] = $file;
263
            }
264
        }
265
266 4
        return $result;
267
    }
268
269
    /**
270
     * {@inheritdoc}
271
     */
272 42
    protected function validateValue($value)
273
    {
274 42
        if (!$value instanceof UploadedFile || $value->error == UPLOAD_ERR_NO_FILE) {
275 1
            return [$this->uploadRequired, []];
276
        }
277
278 42
        switch ($value->error) {
279 42
            case UPLOAD_ERR_OK:
280 38
                if ($this->maxSize !== null && $value->size > $this->getSizeLimit()) {
281 1
                    return [
282 1
                        $this->tooBig,
283 1
                        [
284 1
                            'file' => $value->name,
285 1
                            'limit' => $this->getSizeLimit(),
286 1
                            'formattedLimit' => Yii::$app->formatter->asShortSize($this->getSizeLimit()),
287 1
                        ],
288 1
                    ];
289 38
                } elseif ($this->minSize !== null && $value->size < $this->minSize) {
290 1
                    return [
291 1
                        $this->tooSmall,
292 1
                        [
293 1
                            'file' => $value->name,
294 1
                            'limit' => $this->minSize,
295 1
                            'formattedLimit' => Yii::$app->formatter->asShortSize($this->minSize),
296 1
                        ],
297 1
                    ];
298 38
                } elseif (!empty($this->extensions) && !$this->validateExtension($value)) {
299 8
                    return [$this->wrongExtension, ['file' => $value->name, 'extensions' => implode(', ', $this->extensions)]];
300 33
                } elseif (!empty($this->mimeTypes) && !$this->validateMimeType($value)) {
301 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

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

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

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