FileValidator.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  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. namespace yii\validators;
  8. use Yii;
  9. use yii\helpers\FileHelper;
  10. use yii\helpers\Html;
  11. use yii\helpers\Json;
  12. use yii\web\JsExpression;
  13. use yii\web\UploadedFile;
  14. /**
  15. * FileValidator verifies if an attribute is receiving a valid uploaded file.
  16. *
  17. * Note that you should enable `fileinfo` PHP extension.
  18. *
  19. * @property int $sizeLimit The size limit for uploaded files. This property is read-only.
  20. *
  21. * @author Qiang Xue <qiang.xue@gmail.com>
  22. * @since 2.0
  23. */
  24. class FileValidator extends Validator
  25. {
  26. /**
  27. * @var array|string a list of file name extensions that are allowed to be uploaded.
  28. * This can be either an array or a string consisting of file extension names
  29. * separated by space or comma (e.g. "gif, jpg").
  30. * Extension names are case-insensitive. Defaults to null, meaning all file name
  31. * extensions are allowed.
  32. * @see wrongExtension for the customized message for wrong file type.
  33. */
  34. public $extensions;
  35. /**
  36. * @var bool whether to check file type (extension) with mime-type. If extension produced by
  37. * file mime-type check differs from uploaded file extension, the file will be considered as invalid.
  38. */
  39. public $checkExtensionByMimeType = true;
  40. /**
  41. * @var array|string a list of file MIME types that are allowed to be uploaded.
  42. * This can be either an array or a string consisting of file MIME types
  43. * separated by space or comma (e.g. "text/plain, image/png").
  44. * The mask with the special character `*` can be used to match groups of mime types.
  45. * For example `image/*` will pass all mime types, that begin with `image/` (e.g. `image/jpeg`, `image/png`).
  46. * Mime type names are case-insensitive. Defaults to null, meaning all MIME types are allowed.
  47. * @see wrongMimeType for the customized message for wrong MIME type.
  48. */
  49. public $mimeTypes;
  50. /**
  51. * @var int the minimum number of bytes required for the uploaded file.
  52. * Defaults to null, meaning no limit.
  53. * @see tooSmall for the customized message for a file that is too small.
  54. */
  55. public $minSize;
  56. /**
  57. * @var int the maximum number of bytes required for the uploaded file.
  58. * Defaults to null, meaning no limit.
  59. * Note, the size limit is also affected by `upload_max_filesize` and `post_max_size` INI setting
  60. * and the 'MAX_FILE_SIZE' hidden field value. See [[getSizeLimit()]] for details.
  61. * @see https://secure.php.net/manual/en/ini.core.php#ini.upload-max-filesize
  62. * @see https://secure.php.net/post-max-size
  63. * @see getSizeLimit
  64. * @see tooBig for the customized message for a file that is too big.
  65. */
  66. public $maxSize;
  67. /**
  68. * @var int the maximum file count the given attribute can hold.
  69. * Defaults to 1, meaning single file upload. By defining a higher number,
  70. * multiple uploads become possible. Setting it to `0` means there is no limit on
  71. * the number of files that can be uploaded simultaneously.
  72. *
  73. * > Note: The maximum number of files allowed to be uploaded simultaneously is
  74. * also limited with PHP directive `max_file_uploads`, which defaults to 20.
  75. *
  76. * @see https://secure.php.net/manual/en/ini.core.php#ini.max-file-uploads
  77. * @see tooMany for the customized message when too many files are uploaded.
  78. */
  79. public $maxFiles = 1;
  80. /**
  81. * @var int the minimum file count the given attribute can hold.
  82. * Defaults to 0. Higher value means at least that number of files should be uploaded.
  83. *
  84. * @see tooFew for the customized message when too few files are uploaded.
  85. * @since 2.0.14
  86. */
  87. public $minFiles = 0;
  88. /**
  89. * @var string the error message used when a file is not uploaded correctly.
  90. */
  91. public $message;
  92. /**
  93. * @var string the error message used when no file is uploaded.
  94. * Note that this is the text of the validation error message. To make uploading files required,
  95. * you have to set [[skipOnEmpty]] to `false`.
  96. */
  97. public $uploadRequired;
  98. /**
  99. * @var string the error message used when the uploaded file is too large.
  100. * You may use the following tokens in the message:
  101. *
  102. * - {attribute}: the attribute name
  103. * - {file}: the uploaded file name
  104. * - {limit}: the maximum size allowed (see [[getSizeLimit()]])
  105. * - {formattedLimit}: the maximum size formatted
  106. * with [[\yii\i18n\Formatter::asShortSize()|Formatter::asShortSize()]]
  107. */
  108. public $tooBig;
  109. /**
  110. * @var string the error message used when the uploaded file is too small.
  111. * You may use the following tokens in the message:
  112. *
  113. * - {attribute}: the attribute name
  114. * - {file}: the uploaded file name
  115. * - {limit}: the value of [[minSize]]
  116. * - {formattedLimit}: the value of [[minSize]] formatted
  117. * with [[\yii\i18n\Formatter::asShortSize()|Formatter::asShortSize()]
  118. */
  119. public $tooSmall;
  120. /**
  121. * @var string the error message used if the count of multiple uploads exceeds limit.
  122. * You may use the following tokens in the message:
  123. *
  124. * - {attribute}: the attribute name
  125. * - {limit}: the value of [[maxFiles]]
  126. */
  127. public $tooMany;
  128. /**
  129. * @var string the error message used if the count of multiple uploads less that minFiles.
  130. * You may use the following tokens in the message:
  131. *
  132. * - {attribute}: the attribute name
  133. * - {limit}: the value of [[minFiles]]
  134. *
  135. * @since 2.0.14
  136. */
  137. public $tooFew;
  138. /**
  139. * @var string the error message used when the uploaded file has an extension name
  140. * that is not listed in [[extensions]]. You may use the following tokens in the message:
  141. *
  142. * - {attribute}: the attribute name
  143. * - {file}: the uploaded file name
  144. * - {extensions}: the list of the allowed extensions.
  145. */
  146. public $wrongExtension;
  147. /**
  148. * @var string the error message used when the file has an mime type
  149. * that is not allowed by [[mimeTypes]] property.
  150. * You may use the following tokens in the message:
  151. *
  152. * - {attribute}: the attribute name
  153. * - {file}: the uploaded file name
  154. * - {mimeTypes}: the value of [[mimeTypes]]
  155. */
  156. public $wrongMimeType;
  157. /**
  158. * {@inheritdoc}
  159. */
  160. public function init()
  161. {
  162. parent::init();
  163. if ($this->message === null) {
  164. $this->message = Yii::t('yii', 'File upload failed.');
  165. }
  166. if ($this->uploadRequired === null) {
  167. $this->uploadRequired = Yii::t('yii', 'Please upload a file.');
  168. }
  169. if ($this->tooMany === null) {
  170. $this->tooMany = Yii::t('yii', 'You can upload at most {limit, number} {limit, plural, one{file} other{files}}.');
  171. }
  172. if ($this->tooFew === null) {
  173. $this->tooFew = Yii::t('yii', 'You should upload at least {limit, number} {limit, plural, one{file} other{files}}.');
  174. }
  175. if ($this->wrongExtension === null) {
  176. $this->wrongExtension = Yii::t('yii', 'Only files with these extensions are allowed: {extensions}.');
  177. }
  178. if ($this->tooBig === null) {
  179. $this->tooBig = Yii::t('yii', 'The file "{file}" is too big. Its size cannot exceed {formattedLimit}.');
  180. }
  181. if ($this->tooSmall === null) {
  182. $this->tooSmall = Yii::t('yii', 'The file "{file}" is too small. Its size cannot be smaller than {formattedLimit}.');
  183. }
  184. if (!is_array($this->extensions)) {
  185. $this->extensions = preg_split('/[\s,]+/', strtolower($this->extensions), -1, PREG_SPLIT_NO_EMPTY);
  186. } else {
  187. $this->extensions = array_map('strtolower', $this->extensions);
  188. }
  189. if ($this->wrongMimeType === null) {
  190. $this->wrongMimeType = Yii::t('yii', 'Only files with these MIME types are allowed: {mimeTypes}.');
  191. }
  192. if (!is_array($this->mimeTypes)) {
  193. $this->mimeTypes = preg_split('/[\s,]+/', strtolower($this->mimeTypes), -1, PREG_SPLIT_NO_EMPTY);
  194. } else {
  195. $this->mimeTypes = array_map('strtolower', $this->mimeTypes);
  196. }
  197. }
  198. /**
  199. * {@inheritdoc}
  200. */
  201. public function validateAttribute($model, $attribute)
  202. {
  203. if ($this->maxFiles != 1 || $this->minFiles > 1) {
  204. $rawFiles = $model->$attribute;
  205. if (!is_array($rawFiles)) {
  206. $this->addError($model, $attribute, $this->uploadRequired);
  207. return;
  208. }
  209. $files = $this->filterFiles($rawFiles);
  210. $model->$attribute = $files;
  211. if (empty($files)) {
  212. $this->addError($model, $attribute, $this->uploadRequired);
  213. return;
  214. }
  215. $filesCount = count($files);
  216. if ($this->maxFiles && $filesCount > $this->maxFiles) {
  217. $this->addError($model, $attribute, $this->tooMany, ['limit' => $this->maxFiles]);
  218. }
  219. if ($this->minFiles && $this->minFiles > $filesCount) {
  220. $this->addError($model, $attribute, $this->tooFew, ['limit' => $this->minFiles]);
  221. }
  222. foreach ($files as $file) {
  223. $result = $this->validateValue($file);
  224. if (!empty($result)) {
  225. $this->addError($model, $attribute, $result[0], $result[1]);
  226. }
  227. }
  228. } else {
  229. $result = $this->validateValue($model->$attribute);
  230. if (!empty($result)) {
  231. $this->addError($model, $attribute, $result[0], $result[1]);
  232. }
  233. }
  234. }
  235. /**
  236. * Files filter.
  237. * @param array $files
  238. * @return UploadedFile[]
  239. */
  240. private function filterFiles(array $files)
  241. {
  242. $result = [];
  243. foreach ($files as $fileName => $file) {
  244. if ($file instanceof UploadedFile && $file->error !== UPLOAD_ERR_NO_FILE) {
  245. $result[$fileName] = $file;
  246. }
  247. }
  248. return $result;
  249. }
  250. /**
  251. * {@inheritdoc}
  252. */
  253. protected function validateValue($value)
  254. {
  255. if (!$value instanceof UploadedFile || $value->error == UPLOAD_ERR_NO_FILE) {
  256. return [$this->uploadRequired, []];
  257. }
  258. switch ($value->error) {
  259. case UPLOAD_ERR_OK:
  260. if ($this->maxSize !== null && $value->size > $this->getSizeLimit()) {
  261. return [
  262. $this->tooBig,
  263. [
  264. 'file' => $value->name,
  265. 'limit' => $this->getSizeLimit(),
  266. 'formattedLimit' => Yii::$app->formatter->asShortSize($this->getSizeLimit()),
  267. ],
  268. ];
  269. } elseif ($this->minSize !== null && $value->size < $this->minSize) {
  270. return [
  271. $this->tooSmall,
  272. [
  273. 'file' => $value->name,
  274. 'limit' => $this->minSize,
  275. 'formattedLimit' => Yii::$app->formatter->asShortSize($this->minSize),
  276. ],
  277. ];
  278. } elseif (!empty($this->extensions) && !$this->validateExtension($value)) {
  279. return [$this->wrongExtension, ['file' => $value->name, 'extensions' => implode(', ', $this->extensions)]];
  280. } elseif (!empty($this->mimeTypes) && !$this->validateMimeType($value)) {
  281. return [$this->wrongMimeType, ['file' => $value->name, 'mimeTypes' => implode(', ', $this->mimeTypes)]];
  282. }
  283. return null;
  284. case UPLOAD_ERR_INI_SIZE:
  285. case UPLOAD_ERR_FORM_SIZE:
  286. return [$this->tooBig, [
  287. 'file' => $value->name,
  288. 'limit' => $this->getSizeLimit(),
  289. 'formattedLimit' => Yii::$app->formatter->asShortSize($this->getSizeLimit()),
  290. ]];
  291. case UPLOAD_ERR_PARTIAL:
  292. Yii::warning('File was only partially uploaded: ' . $value->name, __METHOD__);
  293. break;
  294. case UPLOAD_ERR_NO_TMP_DIR:
  295. Yii::warning('Missing the temporary folder to store the uploaded file: ' . $value->name, __METHOD__);
  296. break;
  297. case UPLOAD_ERR_CANT_WRITE:
  298. Yii::warning('Failed to write the uploaded file to disk: ' . $value->name, __METHOD__);
  299. break;
  300. case UPLOAD_ERR_EXTENSION:
  301. Yii::warning('File upload was stopped by some PHP extension: ' . $value->name, __METHOD__);
  302. break;
  303. default:
  304. break;
  305. }
  306. return [$this->message, []];
  307. }
  308. /**
  309. * Returns the maximum size allowed for uploaded files.
  310. *
  311. * This is determined based on four factors:
  312. *
  313. * - 'upload_max_filesize' in php.ini
  314. * - 'post_max_size' in php.ini
  315. * - 'MAX_FILE_SIZE' hidden field
  316. * - [[maxSize]]
  317. *
  318. * @return int the size limit for uploaded files.
  319. */
  320. public function getSizeLimit()
  321. {
  322. // Get the lowest between post_max_size and upload_max_filesize, log a warning if the first is < than the latter
  323. $limit = $this->sizeToBytes(ini_get('upload_max_filesize'));
  324. $postLimit = $this->sizeToBytes(ini_get('post_max_size'));
  325. if ($postLimit > 0 && $postLimit < $limit) {
  326. Yii::warning('PHP.ini\'s \'post_max_size\' is less than \'upload_max_filesize\'.', __METHOD__);
  327. $limit = $postLimit;
  328. }
  329. if ($this->maxSize !== null && $limit > 0 && $this->maxSize < $limit) {
  330. $limit = $this->maxSize;
  331. }
  332. if (isset($_POST['MAX_FILE_SIZE']) && $_POST['MAX_FILE_SIZE'] > 0 && $_POST['MAX_FILE_SIZE'] < $limit) {
  333. $limit = (int) $_POST['MAX_FILE_SIZE'];
  334. }
  335. return $limit;
  336. }
  337. /**
  338. * {@inheritdoc}
  339. * @param bool $trim
  340. */
  341. public function isEmpty($value, $trim = false)
  342. {
  343. $value = is_array($value) ? reset($value) : $value;
  344. return !($value instanceof UploadedFile) || $value->error == UPLOAD_ERR_NO_FILE;
  345. }
  346. /**
  347. * Converts php.ini style size to bytes.
  348. *
  349. * @param string $sizeStr $sizeStr
  350. * @return int
  351. */
  352. private function sizeToBytes($sizeStr)
  353. {
  354. switch (substr($sizeStr, -1)) {
  355. case 'M':
  356. case 'm':
  357. return (int) $sizeStr * 1048576;
  358. case 'K':
  359. case 'k':
  360. return (int) $sizeStr * 1024;
  361. case 'G':
  362. case 'g':
  363. return (int) $sizeStr * 1073741824;
  364. default:
  365. return (int) $sizeStr;
  366. }
  367. }
  368. /**
  369. * Checks if given uploaded file have correct type (extension) according current validator settings.
  370. * @param UploadedFile $file
  371. * @return bool
  372. */
  373. protected function validateExtension($file)
  374. {
  375. $extension = mb_strtolower($file->extension, 'UTF-8');
  376. if ($this->checkExtensionByMimeType) {
  377. $mimeType = FileHelper::getMimeType($file->tempName, null, false);
  378. if ($mimeType === null) {
  379. return false;
  380. }
  381. $extensionsByMimeType = FileHelper::getExtensionsByMimeType($mimeType);
  382. if (!in_array($extension, $extensionsByMimeType, true)) {
  383. return false;
  384. }
  385. }
  386. if (!in_array($extension, $this->extensions, true)) {
  387. return false;
  388. }
  389. return true;
  390. }
  391. /**
  392. * {@inheritdoc}
  393. */
  394. public function clientValidateAttribute($model, $attribute, $view)
  395. {
  396. ValidationAsset::register($view);
  397. $options = $this->getClientOptions($model, $attribute);
  398. return 'yii.validation.file(attribute, messages, ' . Json::encode($options) . ');';
  399. }
  400. /**
  401. * {@inheritdoc}
  402. */
  403. public function getClientOptions($model, $attribute)
  404. {
  405. $label = $model->getAttributeLabel($attribute);
  406. $options = [];
  407. if ($this->message !== null) {
  408. $options['message'] = $this->formatMessage($this->message, [
  409. 'attribute' => $label,
  410. ]);
  411. }
  412. $options['skipOnEmpty'] = $this->skipOnEmpty;
  413. if (!$this->skipOnEmpty) {
  414. $options['uploadRequired'] = $this->formatMessage($this->uploadRequired, [
  415. 'attribute' => $label,
  416. ]);
  417. }
  418. if ($this->mimeTypes !== null) {
  419. $mimeTypes = [];
  420. foreach ($this->mimeTypes as $mimeType) {
  421. $mimeTypes[] = new JsExpression(Html::escapeJsRegularExpression($this->buildMimeTypeRegexp($mimeType)));
  422. }
  423. $options['mimeTypes'] = $mimeTypes;
  424. $options['wrongMimeType'] = $this->formatMessage($this->wrongMimeType, [
  425. 'attribute' => $label,
  426. 'mimeTypes' => implode(', ', $this->mimeTypes),
  427. ]);
  428. }
  429. if ($this->extensions !== null) {
  430. $options['extensions'] = $this->extensions;
  431. $options['wrongExtension'] = $this->formatMessage($this->wrongExtension, [
  432. 'attribute' => $label,
  433. 'extensions' => implode(', ', $this->extensions),
  434. ]);
  435. }
  436. if ($this->minSize !== null) {
  437. $options['minSize'] = $this->minSize;
  438. $options['tooSmall'] = $this->formatMessage($this->tooSmall, [
  439. 'attribute' => $label,
  440. 'limit' => $this->minSize,
  441. 'formattedLimit' => Yii::$app->formatter->asShortSize($this->minSize),
  442. ]);
  443. }
  444. if ($this->maxSize !== null) {
  445. $options['maxSize'] = $this->maxSize;
  446. $options['tooBig'] = $this->formatMessage($this->tooBig, [
  447. 'attribute' => $label,
  448. 'limit' => $this->getSizeLimit(),
  449. 'formattedLimit' => Yii::$app->formatter->asShortSize($this->getSizeLimit()),
  450. ]);
  451. }
  452. if ($this->maxFiles !== null) {
  453. $options['maxFiles'] = $this->maxFiles;
  454. $options['tooMany'] = $this->formatMessage($this->tooMany, [
  455. 'attribute' => $label,
  456. 'limit' => $this->maxFiles,
  457. ]);
  458. }
  459. return $options;
  460. }
  461. /**
  462. * Builds the RegExp from the $mask.
  463. *
  464. * @param string $mask
  465. * @return string the regular expression
  466. * @see mimeTypes
  467. */
  468. private function buildMimeTypeRegexp($mask)
  469. {
  470. return '/^' . str_replace('\*', '.*', preg_quote($mask, '/')) . '$/';
  471. }
  472. /**
  473. * Checks the mimeType of the $file against the list in the [[mimeTypes]] property.
  474. *
  475. * @param UploadedFile $file
  476. * @return bool whether the $file mimeType is allowed
  477. * @throws \yii\base\InvalidConfigException
  478. * @see mimeTypes
  479. * @since 2.0.8
  480. */
  481. protected function validateMimeType($file)
  482. {
  483. $fileMimeType = FileHelper::getMimeType($file->tempName);
  484. foreach ($this->mimeTypes as $mimeType) {
  485. if ($mimeType === $fileMimeType) {
  486. return true;
  487. }
  488. if (strpos($mimeType, '*') !== false && preg_match($this->buildMimeTypeRegexp($mimeType), $fileMimeType)) {
  489. return true;
  490. }
  491. }
  492. return false;
  493. }
  494. }