Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

497 lines
18KB

  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\Html;
  10. use yii\helpers\Json;
  11. use yii\web\JsExpression;
  12. use yii\web\UploadedFile;
  13. use yii\helpers\FileHelper;
  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 integer $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 boolean 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 integer 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 integer 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 http://php.net/manual/en/ini.core.php#ini.upload-max-filesize
  62. * @see http://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 integer 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 http://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 string the error message used when a file is not uploaded correctly.
  82. */
  83. public $message;
  84. /**
  85. * @var string the error message used when no file is uploaded.
  86. * Note that this is the text of the validation error message. To make uploading files required,
  87. * you have to set [[skipOnEmpty]] to `false`.
  88. */
  89. public $uploadRequired;
  90. /**
  91. * @var string the error message used when the uploaded file is too large.
  92. * You may use the following tokens in the message:
  93. *
  94. * - {attribute}: the attribute name
  95. * - {file}: the uploaded file name
  96. * - {limit}: the maximum size allowed (see [[getSizeLimit()]])
  97. * - {formattedLimit}: the maximum size formatted
  98. * with [[\yii\i18n\Formatter::asShortSize()|Formatter::asShortSize()]]
  99. */
  100. public $tooBig;
  101. /**
  102. * @var string the error message used when the uploaded file is too small.
  103. * You may use the following tokens in the message:
  104. *
  105. * - {attribute}: the attribute name
  106. * - {file}: the uploaded file name
  107. * - {limit}: the value of [[minSize]]
  108. * - {formattedLimit}: the value of [[minSize]] formatted
  109. * with [[\yii\i18n\Formatter::asShortSize()|Formatter::asShortSize()]
  110. */
  111. public $tooSmall;
  112. /**
  113. * @var string the error message used if the count of multiple uploads exceeds limit.
  114. * You may use the following tokens in the message:
  115. *
  116. * - {attribute}: the attribute name
  117. * - {limit}: the value of [[maxFiles]]
  118. */
  119. public $tooMany;
  120. /**
  121. * @var string the error message used when the uploaded file has an extension name
  122. * that is not listed in [[extensions]]. You may use the following tokens in the message:
  123. *
  124. * - {attribute}: the attribute name
  125. * - {file}: the uploaded file name
  126. * - {extensions}: the list of the allowed extensions.
  127. */
  128. public $wrongExtension;
  129. /**
  130. * @var string the error message used when the file has an mime type
  131. * that is not allowed by [[mimeTypes]] property.
  132. * You may use the following tokens in the message:
  133. *
  134. * - {attribute}: the attribute name
  135. * - {file}: the uploaded file name
  136. * - {mimeTypes}: the value of [[mimeTypes]]
  137. */
  138. public $wrongMimeType;
  139. /**
  140. * @inheritdoc
  141. */
  142. public function init()
  143. {
  144. parent::init();
  145. if ($this->message === null) {
  146. $this->message = Yii::t('yii', 'File upload failed.');
  147. }
  148. if ($this->uploadRequired === null) {
  149. $this->uploadRequired = Yii::t('yii', 'Please upload a file.');
  150. }
  151. if ($this->tooMany === null) {
  152. $this->tooMany = Yii::t('yii', 'You can upload at most {limit, number} {limit, plural, one{file} other{files}}.');
  153. }
  154. if ($this->wrongExtension === null) {
  155. $this->wrongExtension = Yii::t('yii', 'Only files with these extensions are allowed: {extensions}.');
  156. }
  157. if ($this->tooBig === null) {
  158. $this->tooBig = Yii::t('yii', 'The file "{file}" is too big. Its size cannot exceed {formattedLimit}.');
  159. }
  160. if ($this->tooSmall === null) {
  161. $this->tooSmall = Yii::t('yii', 'The file "{file}" is too small. Its size cannot be smaller than {formattedLimit}.');
  162. }
  163. if (!is_array($this->extensions)) {
  164. $this->extensions = preg_split('/[\s,]+/', strtolower($this->extensions), -1, PREG_SPLIT_NO_EMPTY);
  165. } else {
  166. $this->extensions = array_map('strtolower', $this->extensions);
  167. }
  168. if ($this->wrongMimeType === null) {
  169. $this->wrongMimeType = Yii::t('yii', 'Only files with these MIME types are allowed: {mimeTypes}.');
  170. }
  171. if (!is_array($this->mimeTypes)) {
  172. $this->mimeTypes = preg_split('/[\s,]+/', strtolower($this->mimeTypes), -1, PREG_SPLIT_NO_EMPTY);
  173. } else {
  174. $this->mimeTypes = array_map('strtolower', $this->mimeTypes);
  175. }
  176. }
  177. /**
  178. * @inheritdoc
  179. */
  180. public function validateAttribute($model, $attribute)
  181. {
  182. if ($this->maxFiles != 1) {
  183. $files = $model->$attribute;
  184. if (!is_array($files)) {
  185. $this->addError($model, $attribute, $this->uploadRequired);
  186. return;
  187. }
  188. foreach ($files as $i => $file) {
  189. if (!$file instanceof UploadedFile || $file->error == UPLOAD_ERR_NO_FILE) {
  190. unset($files[$i]);
  191. }
  192. }
  193. $model->$attribute = array_values($files);
  194. if (empty($files)) {
  195. $this->addError($model, $attribute, $this->uploadRequired);
  196. }
  197. if ($this->maxFiles && count($files) > $this->maxFiles) {
  198. $this->addError($model, $attribute, $this->tooMany, ['limit' => $this->maxFiles]);
  199. } else {
  200. foreach ($files as $file) {
  201. $result = $this->validateValue($file);
  202. if (!empty($result)) {
  203. $this->addError($model, $attribute, $result[0], $result[1]);
  204. }
  205. }
  206. }
  207. } else {
  208. $result = $this->validateValue($model->$attribute);
  209. if (!empty($result)) {
  210. $this->addError($model, $attribute, $result[0], $result[1]);
  211. }
  212. }
  213. }
  214. /**
  215. * @inheritdoc
  216. */
  217. protected function validateValue($file)
  218. {
  219. if (!$file instanceof UploadedFile || $file->error == UPLOAD_ERR_NO_FILE) {
  220. return [$this->uploadRequired, []];
  221. }
  222. switch ($file->error) {
  223. case UPLOAD_ERR_OK:
  224. if ($this->maxSize !== null && $file->size > $this->getSizeLimit()) {
  225. return [
  226. $this->tooBig,
  227. [
  228. 'file' => $file->name,
  229. 'limit' => $this->getSizeLimit(),
  230. 'formattedLimit' => Yii::$app->formatter->asShortSize($this->getSizeLimit()),
  231. ],
  232. ];
  233. } elseif ($this->minSize !== null && $file->size < $this->minSize) {
  234. return [
  235. $this->tooSmall,
  236. [
  237. 'file' => $file->name,
  238. 'limit' => $this->minSize,
  239. 'formattedLimit' => Yii::$app->formatter->asShortSize($this->minSize),
  240. ],
  241. ];
  242. } elseif (!empty($this->extensions) && !$this->validateExtension($file)) {
  243. return [$this->wrongExtension, ['file' => $file->name, 'extensions' => implode(', ', $this->extensions)]];
  244. } elseif (!empty($this->mimeTypes) && !$this->validateMimeType($file)) {
  245. return [$this->wrongMimeType, ['file' => $file->name, 'mimeTypes' => implode(', ', $this->mimeTypes)]];
  246. }
  247. return null;
  248. case UPLOAD_ERR_INI_SIZE:
  249. case UPLOAD_ERR_FORM_SIZE:
  250. return [$this->tooBig, [
  251. 'file' => $file->name,
  252. 'limit' => $this->getSizeLimit(),
  253. 'formattedLimit' => Yii::$app->formatter->asShortSize($this->getSizeLimit()),
  254. ]];
  255. case UPLOAD_ERR_PARTIAL:
  256. Yii::warning('File was only partially uploaded: ' . $file->name, __METHOD__);
  257. break;
  258. case UPLOAD_ERR_NO_TMP_DIR:
  259. Yii::warning('Missing the temporary folder to store the uploaded file: ' . $file->name, __METHOD__);
  260. break;
  261. case UPLOAD_ERR_CANT_WRITE:
  262. Yii::warning('Failed to write the uploaded file to disk: ' . $file->name, __METHOD__);
  263. break;
  264. case UPLOAD_ERR_EXTENSION:
  265. Yii::warning('File upload was stopped by some PHP extension: ' . $file->name, __METHOD__);
  266. break;
  267. default:
  268. break;
  269. }
  270. return [$this->message, []];
  271. }
  272. /**
  273. * Returns the maximum size allowed for uploaded files.
  274. * This is determined based on four factors:
  275. *
  276. * - 'upload_max_filesize' in php.ini
  277. * - 'post_max_size' in php.ini
  278. * - 'MAX_FILE_SIZE' hidden field
  279. * - [[maxSize]]
  280. *
  281. * @return integer the size limit for uploaded files.
  282. */
  283. public function getSizeLimit()
  284. {
  285. // Get the lowest between post_max_size and upload_max_filesize, log a warning if the first is < than the latter
  286. $limit = $this->sizeToBytes(ini_get('upload_max_filesize'));
  287. $postLimit = $this->sizeToBytes(ini_get('post_max_size'));
  288. if ($postLimit > 0 && $postLimit < $limit) {
  289. Yii::warning('PHP.ini\'s \'post_max_size\' is less than \'upload_max_filesize\'.', __METHOD__);
  290. $limit = $postLimit;
  291. }
  292. if ($this->maxSize !== null && $limit > 0 && $this->maxSize < $limit) {
  293. $limit = $this->maxSize;
  294. }
  295. if (isset($_POST['MAX_FILE_SIZE']) && $_POST['MAX_FILE_SIZE'] > 0 && $_POST['MAX_FILE_SIZE'] < $limit) {
  296. $limit = (int) $_POST['MAX_FILE_SIZE'];
  297. }
  298. return $limit;
  299. }
  300. /**
  301. * @inheritdoc
  302. */
  303. public function isEmpty($value, $trim = false)
  304. {
  305. $value = is_array($value) ? reset($value) : $value;
  306. return !($value instanceof UploadedFile) || $value->error == UPLOAD_ERR_NO_FILE;
  307. }
  308. /**
  309. * Converts php.ini style size to bytes
  310. *
  311. * @param string $sizeStr $sizeStr
  312. * @return integer
  313. */
  314. private function sizeToBytes($sizeStr)
  315. {
  316. switch (substr($sizeStr, -1)) {
  317. case 'M':
  318. case 'm':
  319. return (int) $sizeStr * 1048576;
  320. case 'K':
  321. case 'k':
  322. return (int) $sizeStr * 1024;
  323. case 'G':
  324. case 'g':
  325. return (int) $sizeStr * 1073741824;
  326. default:
  327. return (int) $sizeStr;
  328. }
  329. }
  330. /**
  331. * Checks if given uploaded file have correct type (extension) according current validator settings.
  332. * @param UploadedFile $file
  333. * @return boolean
  334. */
  335. protected function validateExtension($file)
  336. {
  337. $extension = mb_strtolower($file->extension, 'UTF-8');
  338. if ($this->checkExtensionByMimeType) {
  339. $mimeType = FileHelper::getMimeType($file->tempName, null, false);
  340. if ($mimeType === null) {
  341. return false;
  342. }
  343. $extensionsByMimeType = FileHelper::getExtensionsByMimeType($mimeType);
  344. if (!in_array($extension, $extensionsByMimeType, true)) {
  345. return false;
  346. }
  347. }
  348. if (!in_array($extension, $this->extensions, true)) {
  349. return false;
  350. }
  351. return true;
  352. }
  353. /**
  354. * @inheritdoc
  355. */
  356. public function clientValidateAttribute($model, $attribute, $view)
  357. {
  358. ValidationAsset::register($view);
  359. $options = $this->getClientOptions($model, $attribute);
  360. return 'yii.validation.file(attribute, messages, ' . Json::encode($options) . ');';
  361. }
  362. /**
  363. * Returns the client-side validation options.
  364. * @param \yii\base\Model $model the model being validated
  365. * @param string $attribute the attribute name being validated
  366. * @return array the client-side validation options
  367. */
  368. protected function getClientOptions($model, $attribute)
  369. {
  370. $label = $model->getAttributeLabel($attribute);
  371. $options = [];
  372. if ($this->message !== null) {
  373. $options['message'] = Yii::$app->getI18n()->format($this->message, [
  374. 'attribute' => $label,
  375. ], Yii::$app->language);
  376. }
  377. $options['skipOnEmpty'] = $this->skipOnEmpty;
  378. if (!$this->skipOnEmpty) {
  379. $options['uploadRequired'] = Yii::$app->getI18n()->format($this->uploadRequired, [
  380. 'attribute' => $label,
  381. ], Yii::$app->language);
  382. }
  383. if ($this->mimeTypes !== null) {
  384. $mimeTypes = [];
  385. foreach ($this->mimeTypes as $mimeType) {
  386. $mimeTypes[] = new JsExpression(Html::escapeJsRegularExpression($this->buildMimeTypeRegexp($mimeType)));
  387. }
  388. $options['mimeTypes'] = $mimeTypes;
  389. $options['wrongMimeType'] = Yii::$app->getI18n()->format($this->wrongMimeType, [
  390. 'attribute' => $label,
  391. 'mimeTypes' => implode(', ', $this->mimeTypes),
  392. ], Yii::$app->language);
  393. }
  394. if ($this->extensions !== null) {
  395. $options['extensions'] = $this->extensions;
  396. $options['wrongExtension'] = Yii::$app->getI18n()->format($this->wrongExtension, [
  397. 'attribute' => $label,
  398. 'extensions' => implode(', ', $this->extensions),
  399. ], Yii::$app->language);
  400. }
  401. if ($this->minSize !== null) {
  402. $options['minSize'] = $this->minSize;
  403. $options['tooSmall'] = Yii::$app->getI18n()->format($this->tooSmall, [
  404. 'attribute' => $label,
  405. 'limit' => $this->minSize,
  406. 'formattedLimit' => Yii::$app->formatter->asShortSize($this->minSize),
  407. ], Yii::$app->language);
  408. }
  409. if ($this->maxSize !== null) {
  410. $options['maxSize'] = $this->maxSize;
  411. $options['tooBig'] = Yii::$app->getI18n()->format($this->tooBig, [
  412. 'attribute' => $label,
  413. 'limit' => $this->getSizeLimit(),
  414. 'formattedLimit' => Yii::$app->formatter->asShortSize($this->getSizeLimit()),
  415. ], Yii::$app->language);
  416. }
  417. if ($this->maxFiles !== null) {
  418. $options['maxFiles'] = $this->maxFiles;
  419. $options['tooMany'] = Yii::$app->getI18n()->format($this->tooMany, [
  420. 'attribute' => $label,
  421. 'limit' => $this->maxFiles,
  422. ], Yii::$app->language);
  423. }
  424. return $options;
  425. }
  426. /**
  427. * Builds the RegExp from the $mask
  428. *
  429. * @param string $mask
  430. * @return string the regular expression
  431. * @see mimeTypes
  432. */
  433. private function buildMimeTypeRegexp($mask)
  434. {
  435. return '/^' . str_replace('\*', '.*', preg_quote($mask, '/')) . '$/';
  436. }
  437. /**
  438. * Checks the mimeType of the $file against the list in the [[mimeTypes]] property
  439. *
  440. * @param UploadedFile $file
  441. * @return boolean whether the $file mimeType is allowed
  442. * @throws \yii\base\InvalidConfigException
  443. * @see mimeTypes
  444. * @since 2.0.8
  445. */
  446. protected function validateMimeType($file)
  447. {
  448. $fileMimeType = FileHelper::getMimeType($file->tempName);
  449. foreach ($this->mimeTypes as $mimeType) {
  450. if ($mimeType === $fileMimeType) {
  451. return true;
  452. }
  453. if (strpos($mimeType, '*') !== false && preg_match($this->buildMimeTypeRegexp($mimeType), $fileMimeType)) {
  454. return true;
  455. }
  456. }
  457. return false;
  458. }
  459. }