You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

FileValidator.php 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  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\web\UploadedFile;
  10. use yii\helpers\FileHelper;
  11. /**
  12. * FileValidator verifies if an attribute is receiving a valid uploaded file.
  13. *
  14. * Note that you should enable `fileinfo` PHP extension.
  15. *
  16. * @property integer $sizeLimit The size limit for uploaded files. This property is read-only.
  17. *
  18. * @author Qiang Xue <qiang.xue@gmail.com>
  19. * @since 2.0
  20. */
  21. class FileValidator extends Validator
  22. {
  23. /**
  24. * @var array|string a list of file name extensions that are allowed to be uploaded.
  25. * This can be either an array or a string consisting of file extension names
  26. * separated by space or comma (e.g. "gif, jpg").
  27. * Extension names are case-insensitive. Defaults to null, meaning all file name
  28. * extensions are allowed.
  29. * @see wrongType for the customized message for wrong file type.
  30. */
  31. public $extensions;
  32. /**
  33. * @var boolean whether to check file type (extension) with mime-type. If extension produced by
  34. * file mime-type check differs from uploaded file extension, the file will be considered as invalid.
  35. */
  36. public $checkExtensionByMimeType = true;
  37. /**
  38. * @var array|string a list of file MIME types that are allowed to be uploaded.
  39. * This can be either an array or a string consisting of file MIME types
  40. * separated by space or comma (e.g. "text/plain, image/png").
  41. * Mime type names are case-insensitive. Defaults to null, meaning all MIME types
  42. * are allowed.
  43. * @see wrongMimeType for the customized message for wrong MIME type.
  44. */
  45. public $mimeTypes;
  46. /**
  47. * @var integer the minimum number of bytes required for the uploaded file.
  48. * Defaults to null, meaning no limit.
  49. * @see tooSmall for the customized message for a file that is too small.
  50. */
  51. public $minSize;
  52. /**
  53. * @var integer the maximum number of bytes required for the uploaded file.
  54. * Defaults to null, meaning no limit.
  55. * Note, the size limit is also affected by 'upload_max_filesize' INI setting
  56. * and the 'MAX_FILE_SIZE' hidden field value.
  57. * @see tooBig for the customized message for a file that is too big.
  58. */
  59. public $maxSize;
  60. /**
  61. * @var integer the maximum file count the given attribute can hold.
  62. * It defaults to 1, meaning single file upload. By defining a higher number,
  63. * multiple uploads become possible.
  64. * @see tooMany for the customized message when too many files are uploaded.
  65. */
  66. public $maxFiles = 1;
  67. /**
  68. * @var string the error message used when a file is not uploaded correctly.
  69. */
  70. public $message;
  71. /**
  72. * @var string the error message used when no file is uploaded.
  73. * Note that this is the text of the validation error message. To make uploading files required,
  74. * you have to set [[skipOnEmpty]] to `false`.
  75. */
  76. public $uploadRequired;
  77. /**
  78. * @var string the error message used when the uploaded file is too large.
  79. * You may use the following tokens in the message:
  80. *
  81. * - {attribute}: the attribute name
  82. * - {file}: the uploaded file name
  83. * - {limit}: the maximum size allowed (see [[getSizeLimit()]])
  84. */
  85. public $tooBig;
  86. /**
  87. * @var string the error message used when the uploaded file is too small.
  88. * You may use the following tokens in the message:
  89. *
  90. * - {attribute}: the attribute name
  91. * - {file}: the uploaded file name
  92. * - {limit}: the value of [[minSize]]
  93. */
  94. public $tooSmall;
  95. /**
  96. * @var string the error message used if the count of multiple uploads exceeds limit.
  97. * You may use the following tokens in the message:
  98. *
  99. * - {attribute}: the attribute name
  100. * - {limit}: the value of [[maxFiles]]
  101. */
  102. public $tooMany;
  103. /**
  104. * @var string the error message used when the uploaded file has an extension name
  105. * that is not listed in [[extensions]]. You may use the following tokens in the message:
  106. *
  107. * - {attribute}: the attribute name
  108. * - {file}: the uploaded file name
  109. * - {extensions}: the list of the allowed extensions.
  110. */
  111. public $wrongExtension;
  112. /**
  113. * @var string the error message used when the file has an mime type
  114. * that is not listed in [[mimeTypes]].
  115. * You may use the following tokens in the message:
  116. *
  117. * - {attribute}: the attribute name
  118. * - {file}: the uploaded file name
  119. * - {mimeTypes}: the value of [[mimeTypes]]
  120. */
  121. public $wrongMimeType;
  122. /**
  123. * @inheritdoc
  124. */
  125. public function init()
  126. {
  127. parent::init();
  128. if ($this->message === null) {
  129. $this->message = Yii::t('yii', 'File upload failed.');
  130. }
  131. if ($this->uploadRequired === null) {
  132. $this->uploadRequired = Yii::t('yii', 'Please upload a file.');
  133. }
  134. if ($this->tooMany === null) {
  135. $this->tooMany = Yii::t('yii', 'You can upload at most {limit, number} {limit, plural, one{file} other{files}}.');
  136. }
  137. if ($this->wrongExtension === null) {
  138. $this->wrongExtension = Yii::t('yii', 'Only files with these extensions are allowed: {extensions}.');
  139. }
  140. if ($this->tooBig === null) {
  141. $this->tooBig = Yii::t('yii', 'The file "{file}" is too big. Its size cannot exceed {limit, number} {limit, plural, one{byte} other{bytes}}.');
  142. }
  143. if ($this->tooSmall === null) {
  144. $this->tooSmall = Yii::t('yii', 'The file "{file}" is too small. Its size cannot be smaller than {limit, number} {limit, plural, one{byte} other{bytes}}.');
  145. }
  146. if (!is_array($this->extensions)) {
  147. $this->extensions = preg_split('/[\s,]+/', strtolower($this->extensions), -1, PREG_SPLIT_NO_EMPTY);
  148. } else {
  149. $this->extensions = array_map('strtolower', $this->extensions);
  150. }
  151. if ($this->wrongMimeType === null) {
  152. $this->wrongMimeType = Yii::t('yii', 'Only files with these MIME types are allowed: {mimeTypes}.');
  153. }
  154. if (!is_array($this->mimeTypes)) {
  155. $this->mimeTypes = preg_split('/[\s,]+/', strtolower($this->mimeTypes), -1, PREG_SPLIT_NO_EMPTY);
  156. } else {
  157. $this->mimeTypes = array_map('strtolower', $this->mimeTypes);
  158. }
  159. }
  160. /**
  161. * @inheritdoc
  162. */
  163. public function validateAttribute($model, $attribute)
  164. {
  165. if ($this->maxFiles > 1) {
  166. $files = $model->$attribute;
  167. if (!is_array($files)) {
  168. $this->addError($model, $attribute, $this->uploadRequired);
  169. return;
  170. }
  171. foreach ($files as $i => $file) {
  172. if (!$file instanceof UploadedFile || $file->error == UPLOAD_ERR_NO_FILE) {
  173. unset($files[$i]);
  174. }
  175. }
  176. $model->$attribute = array_values($files);
  177. if (empty($files)) {
  178. $this->addError($model, $attribute, $this->uploadRequired);
  179. }
  180. if (count($files) > $this->maxFiles) {
  181. $this->addError($model, $attribute, $this->tooMany, ['limit' => $this->maxFiles]);
  182. } else {
  183. foreach ($files as $file) {
  184. $result = $this->validateValue($file);
  185. if (!empty($result)) {
  186. $this->addError($model, $attribute, $result[0], $result[1]);
  187. }
  188. }
  189. }
  190. } else {
  191. $result = $this->validateValue($model->$attribute);
  192. if (!empty($result)) {
  193. $this->addError($model, $attribute, $result[0], $result[1]);
  194. }
  195. }
  196. }
  197. /**
  198. * @inheritdoc
  199. */
  200. protected function validateValue($file)
  201. {
  202. if (!$file instanceof UploadedFile || $file->error == UPLOAD_ERR_NO_FILE) {
  203. return [$this->uploadRequired, []];
  204. }
  205. switch ($file->error) {
  206. case UPLOAD_ERR_OK:
  207. if ($this->maxSize !== null && $file->size > $this->maxSize) {
  208. return [$this->tooBig, ['file' => $file->name, 'limit' => $this->getSizeLimit()]];
  209. } elseif ($this->minSize !== null && $file->size < $this->minSize) {
  210. return [$this->tooSmall, ['file' => $file->name, 'limit' => $this->minSize]];
  211. } elseif (!empty($this->extensions) && !$this->validateExtension($file)) {
  212. return [$this->wrongExtension, ['file' => $file->name, 'extensions' => implode(', ', $this->extensions)]];
  213. } elseif (!empty($this->mimeTypes) && !in_array(FileHelper::getMimeType($file->tempName), $this->mimeTypes, false)) {
  214. return [$this->wrongMimeType, ['file' => $file->name, 'mimeTypes' => implode(', ', $this->mimeTypes)]];
  215. } else {
  216. return null;
  217. }
  218. case UPLOAD_ERR_INI_SIZE:
  219. case UPLOAD_ERR_FORM_SIZE:
  220. return [$this->tooBig, ['file' => $file->name, 'limit' => $this->getSizeLimit()]];
  221. case UPLOAD_ERR_PARTIAL:
  222. Yii::warning('File was only partially uploaded: ' . $file->name, __METHOD__);
  223. break;
  224. case UPLOAD_ERR_NO_TMP_DIR:
  225. Yii::warning('Missing the temporary folder to store the uploaded file: ' . $file->name, __METHOD__);
  226. break;
  227. case UPLOAD_ERR_CANT_WRITE:
  228. Yii::warning('Failed to write the uploaded file to disk: ' . $file->name, __METHOD__);
  229. break;
  230. case UPLOAD_ERR_EXTENSION:
  231. Yii::warning('File upload was stopped by some PHP extension: ' . $file->name, __METHOD__);
  232. break;
  233. default:
  234. break;
  235. }
  236. return [$this->message, []];
  237. }
  238. /**
  239. * Returns the maximum size allowed for uploaded files.
  240. * This is determined based on three factors:
  241. *
  242. * - 'upload_max_filesize' in php.ini
  243. * - 'MAX_FILE_SIZE' hidden field
  244. * - [[maxSize]]
  245. *
  246. * @return integer the size limit for uploaded files.
  247. */
  248. public function getSizeLimit()
  249. {
  250. $limit = $this->sizeToBytes(ini_get('upload_max_filesize'));
  251. if ($this->maxSize !== null && $limit > 0 && $this->maxSize < $limit) {
  252. $limit = $this->maxSize;
  253. }
  254. if (isset($_POST['MAX_FILE_SIZE']) && $_POST['MAX_FILE_SIZE'] > 0 && $_POST['MAX_FILE_SIZE'] < $limit) {
  255. $limit = (int) $_POST['MAX_FILE_SIZE'];
  256. }
  257. return $limit;
  258. }
  259. /**
  260. * @inheritdoc
  261. */
  262. public function isEmpty($value, $trim = false)
  263. {
  264. $value = is_array($value) ? reset($value) : $value;
  265. return !($value instanceof UploadedFile) || $value->error == UPLOAD_ERR_NO_FILE;
  266. }
  267. /**
  268. * Converts php.ini style size to bytes
  269. *
  270. * @param string $sizeStr $sizeStr
  271. * @return int
  272. */
  273. private function sizeToBytes($sizeStr)
  274. {
  275. switch (substr($sizeStr, -1)) {
  276. case 'M':
  277. case 'm':
  278. return (int) $sizeStr * 1048576;
  279. case 'K':
  280. case 'k':
  281. return (int) $sizeStr * 1024;
  282. case 'G':
  283. case 'g':
  284. return (int) $sizeStr * 1073741824;
  285. default:
  286. return (int) $sizeStr;
  287. }
  288. }
  289. /**
  290. * Checks if given uploaded file have correct type (extension) according current validator settings.
  291. * @param UploadedFile $file
  292. * @return boolean
  293. */
  294. protected function validateExtension($file)
  295. {
  296. $extension = mb_strtolower($file->extension, 'utf-8');
  297. if ($this->checkExtensionByMimeType) {
  298. $mimeType = FileHelper::getMimeType($file->tempName, null, false);
  299. if ($mimeType === null) {
  300. return false;
  301. }
  302. $extensionsByMimeType = FileHelper::getExtensionsByMimeType($mimeType);
  303. if (!in_array($extension, $extensionsByMimeType, true)) {
  304. return false;
  305. }
  306. }
  307. if (!in_array($extension, $this->extensions, true)) {
  308. return false;
  309. }
  310. return true;
  311. }
  312. /**
  313. * @inheritdoc
  314. */
  315. public function clientValidateAttribute($model, $attribute, $view)
  316. {
  317. ValidationAsset::register($view);
  318. $options = $this->getClientOptions($model, $attribute);
  319. return 'yii.validation.file(attribute, messages, ' . json_encode($options, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . ');';
  320. }
  321. /**
  322. * Returns the client side validation options.
  323. * @param \yii\base\Model $model the model being validated
  324. * @param string $attribute the attribute name being validated
  325. * @return array the client side validation options
  326. */
  327. protected function getClientOptions($model, $attribute)
  328. {
  329. $label = $model->getAttributeLabel($attribute);
  330. $options = [];
  331. if ($this->message !== null) {
  332. $options['message'] = Yii::$app->getI18n()->format($this->message, [
  333. 'attribute' => $label,
  334. ], Yii::$app->language);
  335. }
  336. $options['skipOnEmpty'] = $this->skipOnEmpty;
  337. if ( !$this->skipOnEmpty ) {
  338. $options['uploadRequired'] = Yii::$app->getI18n()->format($this->uploadRequired, [
  339. 'attribute' => $label,
  340. ], Yii::$app->language);
  341. }
  342. if ( $this->mimeTypes !== null ) {
  343. $options['mimeTypes'] = $this->mimeTypes;
  344. $options['wrongMimeType'] = Yii::$app->getI18n()->format($this->wrongMimeType, [
  345. 'attribute' => $label,
  346. 'mimeTypes' => join(', ', $this->mimeTypes)
  347. ], Yii::$app->language);
  348. }
  349. if ( $this->extensions !== null ) {
  350. $options['extensions'] = $this->extensions;
  351. $options['wrongExtension'] = Yii::$app->getI18n()->format($this->wrongExtension, [
  352. 'attribute' => $label,
  353. 'extensions' => join(', ', $this->extensions)
  354. ], Yii::$app->language);
  355. }
  356. if ( $this->minSize !== null ) {
  357. $options['minSize'] = $this->minSize;
  358. $options['tooSmall'] = Yii::$app->getI18n()->format($this->tooSmall, [
  359. 'attribute' => $label,
  360. 'limit' => $this->minSize
  361. ], Yii::$app->language);
  362. }
  363. if ( $this->maxSize !== null ) {
  364. $options['maxSize'] = $this->maxSize;
  365. $options['tooBig'] = Yii::$app->getI18n()->format($this->tooBig, [
  366. 'attribute' => $label,
  367. 'limit' => $this->maxSize
  368. ], Yii::$app->language);
  369. }
  370. if ( $this->maxFiles !== null ) {
  371. $options['maxFiles'] = $this->maxFiles;
  372. $options['tooMany'] = Yii::$app->getI18n()->format($this->tooMany, [
  373. 'attribute' => $label,
  374. 'limit' => $this->maxFiles
  375. ], Yii::$app->language);
  376. }
  377. return $options;
  378. }
  379. }