File.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Customer\Model\Metadata\Form;
  7. use Magento\Customer\Model\FileProcessor;
  8. use Magento\Customer\Model\FileProcessorFactory;
  9. use Magento\Framework\Api\ArrayObjectSearch;
  10. use Magento\Framework\Api\Data\ImageContentInterface;
  11. use Magento\Framework\App\Filesystem\DirectoryList;
  12. use Magento\Framework\App\ObjectManager;
  13. use Magento\Framework\File\UploaderFactory;
  14. use Magento\Framework\Filesystem;
  15. /**
  16. * Processes files that are save for customer.
  17. *
  18. * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
  19. */
  20. class File extends AbstractData
  21. {
  22. /**
  23. * Validator for check not protected extensions
  24. *
  25. * @var \Magento\MediaStorage\Model\File\Validator\NotProtectedExtension
  26. */
  27. protected $_validatorNotProtectedExtensions;
  28. /**
  29. * Core data
  30. *
  31. * @var \Magento\Framework\Url\EncoderInterface
  32. */
  33. protected $urlEncoder;
  34. /**
  35. * @var \Magento\MediaStorage\Model\File\Validator\NotProtectedExtension
  36. */
  37. protected $_fileValidator;
  38. /**
  39. * @var Filesystem
  40. */
  41. protected $_fileSystem;
  42. /**
  43. * @var UploaderFactory
  44. */
  45. private $uploaderFactory;
  46. /**
  47. * @var FileProcessor
  48. */
  49. protected $fileProcessor;
  50. /**
  51. * @var FileProcessorFactory
  52. * @deprecated 101.0.0
  53. */
  54. protected $fileProcessorFactory;
  55. /**
  56. * Constructor
  57. *
  58. * @param \Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate
  59. * @param \Psr\Log\LoggerInterface $logger
  60. * @param \Magento\Customer\Api\Data\AttributeMetadataInterface $attribute
  61. * @param \Magento\Framework\Locale\ResolverInterface $localeResolver
  62. * @param string|array $value
  63. * @param string $entityTypeCode
  64. * @param bool $isAjax
  65. * @param \Magento\Framework\Url\EncoderInterface $urlEncoder
  66. * @param \Magento\MediaStorage\Model\File\Validator\NotProtectedExtension $fileValidator
  67. * @param Filesystem $fileSystem
  68. * @param UploaderFactory $uploaderFactory
  69. * @param \Magento\Customer\Model\FileProcessorFactory|null $fileProcessorFactory
  70. * @SuppressWarnings(PHPMD.ExcessiveParameterList)
  71. */
  72. public function __construct(
  73. \Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate,
  74. \Psr\Log\LoggerInterface $logger,
  75. \Magento\Customer\Api\Data\AttributeMetadataInterface $attribute,
  76. \Magento\Framework\Locale\ResolverInterface $localeResolver,
  77. $value,
  78. $entityTypeCode,
  79. $isAjax,
  80. \Magento\Framework\Url\EncoderInterface $urlEncoder,
  81. \Magento\MediaStorage\Model\File\Validator\NotProtectedExtension $fileValidator,
  82. Filesystem $fileSystem,
  83. UploaderFactory $uploaderFactory,
  84. \Magento\Customer\Model\FileProcessorFactory $fileProcessorFactory = null
  85. ) {
  86. parent::__construct($localeDate, $logger, $attribute, $localeResolver, $value, $entityTypeCode, $isAjax);
  87. $this->urlEncoder = $urlEncoder;
  88. $this->_fileValidator = $fileValidator;
  89. $this->_fileSystem = $fileSystem;
  90. $this->uploaderFactory = $uploaderFactory;
  91. $this->fileProcessorFactory = $fileProcessorFactory ?: ObjectManager::getInstance()
  92. ->get(\Magento\Customer\Model\FileProcessorFactory::class);
  93. $this->fileProcessor = $this->fileProcessorFactory->create(['entityTypeCode' => $this->_entityTypeCode]);
  94. }
  95. /**
  96. * @inheritdoc
  97. * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  98. */
  99. public function extractValue(\Magento\Framework\App\RequestInterface $request)
  100. {
  101. $extend = $this->_getRequestValue($request);
  102. $attrCode = $this->getAttribute()->getAttributeCode();
  103. if ($this->_requestScope || !isset($_FILES[$attrCode])) {
  104. $value = [];
  105. if (strpos($this->_requestScope, '/') !== false) {
  106. $scopes = explode('/', $this->_requestScope);
  107. $mainScope = array_shift($scopes);
  108. } else {
  109. $mainScope = $this->_requestScope;
  110. $scopes = [];
  111. }
  112. if (!empty($_FILES[$mainScope])) {
  113. foreach ($_FILES[$mainScope] as $fileKey => $scopeData) {
  114. foreach ($scopes as $scopeName) {
  115. if (isset($scopeData[$scopeName])) {
  116. $scopeData = $scopeData[$scopeName];
  117. } else {
  118. $scopeData[$scopeName] = [];
  119. }
  120. }
  121. if (isset($scopeData[$attrCode])) {
  122. $value[$fileKey] = $scopeData[$attrCode];
  123. }
  124. }
  125. } elseif (isset($extend[0]['file']) && !empty($extend[0]['file'])) {
  126. /**
  127. * This case is required by file uploader UI component
  128. *
  129. * $extend[0]['file'] - uses for AJAX validation
  130. * $extend[0] - uses for POST request
  131. */
  132. $value = $this->getIsAjaxRequest() ? $extend[0]['file'] : $extend[0];
  133. } else {
  134. $value = [];
  135. }
  136. } else {
  137. if (isset($_FILES[$attrCode])) {
  138. $value = $_FILES[$attrCode];
  139. } else {
  140. $value = [];
  141. }
  142. }
  143. if (!empty($extend['delete'])) {
  144. $value['delete'] = true;
  145. }
  146. return $value;
  147. }
  148. /**
  149. * Validate file by attribute validate rules. Returns array of errors.
  150. *
  151. * @param array $value
  152. * @return string[]
  153. */
  154. protected function _validateByRules($value)
  155. {
  156. $label = $value['name'];
  157. $rules = $this->getAttribute()->getValidationRules();
  158. $extension = pathinfo($value['name'], PATHINFO_EXTENSION);
  159. $fileExtensions = ArrayObjectSearch::getArrayElementByName(
  160. $rules,
  161. 'file_extensions'
  162. );
  163. if ($fileExtensions !== null) {
  164. $extensions = explode(',', $fileExtensions);
  165. $extensions = array_map('trim', $extensions);
  166. if (!in_array($extension, $extensions)) {
  167. return [__('"%1" is not a valid file extension.', $extension)];
  168. }
  169. }
  170. /**
  171. * Check protected file extension
  172. */
  173. if (!$this->_fileValidator->isValid($extension)) {
  174. return $this->_fileValidator->getMessages();
  175. }
  176. if (!$this->_isUploadedFile($value['tmp_name'])) {
  177. return [__('"%1" is not a valid file.', $label)];
  178. }
  179. $maxFileSize = ArrayObjectSearch::getArrayElementByName(
  180. $rules,
  181. 'max_file_size'
  182. );
  183. if ($maxFileSize !== null) {
  184. $size = $value['size'];
  185. if ($maxFileSize < $size) {
  186. return [__('"%1" exceeds the allowed file size.', $label)];
  187. }
  188. }
  189. return [];
  190. }
  191. /**
  192. * Helper function that checks if the file was uploaded.
  193. *
  194. * This helper function is needed for testing.
  195. *
  196. * @param string $filename
  197. * @return bool
  198. */
  199. protected function _isUploadedFile($filename)
  200. {
  201. if (is_uploaded_file($filename)) {
  202. return true;
  203. }
  204. // This case is required for file uploader UI component
  205. $temporaryFile = FileProcessor::TMP_DIR . '/' . pathinfo($filename)['basename'];
  206. if ($this->fileProcessor->isExist($temporaryFile)) {
  207. return true;
  208. }
  209. return false;
  210. }
  211. /**
  212. * @inheritdoc
  213. * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  214. * @SuppressWarnings(PHPMD.NPathComplexity)
  215. */
  216. public function validateValue($value)
  217. {
  218. if ($this->getIsAjaxRequest()) {
  219. return true;
  220. }
  221. $errors = [];
  222. $attribute = $this->getAttribute();
  223. $label = $attribute->getStoreLabel();
  224. $toDelete = !empty($value['delete']) ? true : false;
  225. $toUpload = !empty($value['tmp_name']) ? true : false;
  226. if (!$toUpload && !$toDelete && $this->_value) {
  227. return true;
  228. }
  229. if (!$attribute->isRequired() && !$toUpload) {
  230. return true;
  231. }
  232. if ($attribute->isRequired() && !$toUpload) {
  233. $errors[] = __('"%1" is a required value.', $label);
  234. }
  235. if ($toUpload) {
  236. $errors = array_merge($errors, $this->_validateByRules($value));
  237. }
  238. if (count($errors) == 0) {
  239. return true;
  240. }
  241. return $errors;
  242. }
  243. /**
  244. * @inheritdoc
  245. *
  246. * @return ImageContentInterface|array|string|null
  247. */
  248. public function compactValue($value)
  249. {
  250. if ($this->getIsAjaxRequest()) {
  251. return $this;
  252. }
  253. // Remove outdated file (in the case of file uploader UI component)
  254. if (empty($value) && !empty($this->_value)) {
  255. $this->fileProcessor->removeUploadedFile($this->_value);
  256. return $value;
  257. }
  258. if (isset($value['file']) && !empty($value['file'])) {
  259. if ($value['file'] == $this->_value) {
  260. return $this->_value;
  261. }
  262. $result = $this->processUiComponentValue($value);
  263. } else {
  264. $result = $this->processInputFieldValue($value);
  265. }
  266. return $result;
  267. }
  268. /**
  269. * Process file uploader UI component data
  270. *
  271. * @param array $value
  272. * @return string|null
  273. */
  274. protected function processUiComponentValue(array $value)
  275. {
  276. $result = $this->fileProcessor->moveTemporaryFile($value['file']);
  277. return $result;
  278. }
  279. /**
  280. * Process input type=file component data
  281. *
  282. * @param string $value
  283. * @return bool|int|string
  284. */
  285. protected function processInputFieldValue($value)
  286. {
  287. $toDelete = false;
  288. if ($this->_value) {
  289. if (!$this->getAttribute()->isRequired()
  290. && !empty($value['delete'])
  291. ) {
  292. $toDelete = true;
  293. }
  294. if (!empty($value['tmp_name'])) {
  295. $toDelete = true;
  296. }
  297. }
  298. $mediaDir = $this->_fileSystem->getDirectoryWrite(DirectoryList::MEDIA);
  299. $result = $this->_value;
  300. if ($toDelete) {
  301. $mediaDir->delete($this->_entityTypeCode . '/' . ltrim($this->_value, '/'));
  302. $result = '';
  303. }
  304. if (!empty($value['tmp_name'])) {
  305. try {
  306. $uploader = $this->uploaderFactory->create(['fileId' => $value]);
  307. $uploader->setFilesDispersion(true);
  308. $uploader->setFilenamesCaseSensitivity(false);
  309. $uploader->setAllowRenameFiles(true);
  310. $uploader->save($mediaDir->getAbsolutePath($this->_entityTypeCode), $value['name']);
  311. $result = $uploader->getUploadedFileName();
  312. } catch (\Exception $e) {
  313. $this->_logger->critical($e);
  314. }
  315. }
  316. return $result;
  317. }
  318. /**
  319. * @inheritdoc
  320. */
  321. public function restoreValue($value)
  322. {
  323. return $this->_value;
  324. }
  325. /**
  326. * @inheritdoc
  327. */
  328. public function outputValue($format = \Magento\Customer\Model\Metadata\ElementFactory::OUTPUT_FORMAT_TEXT)
  329. {
  330. $output = '';
  331. if ($this->_value) {
  332. switch ($format) {
  333. case \Magento\Customer\Model\Metadata\ElementFactory::OUTPUT_FORMAT_JSON:
  334. $output = ['value' => $this->_value, 'url_key' => $this->urlEncoder->encode($this->_value)];
  335. break;
  336. }
  337. }
  338. return $output;
  339. }
  340. /**
  341. * Get file processor
  342. *
  343. * @return FileProcessor
  344. * @deprecated 100.1.3
  345. */
  346. protected function getFileProcessor()
  347. {
  348. return $this->fileProcessor;
  349. }
  350. }