Skip to content

Commit b1e56f0

Browse files
silinmykolaandrewbess
authored andcommitted
Added fixes for FileUploader to compatibility with PHP 8.1
1 parent 6bbf0aa commit b1e56f0

File tree

12 files changed

+356
-147
lines changed

12 files changed

+356
-147
lines changed

app/code/Magento/Catalog/Controller/Adminhtml/Product/Gallery/Upload.php

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
use Magento\Framework\Exception\LocalizedException;
1212

1313
/**
14-
* Class Upload
14+
* The product gallery upload controller
1515
*/
1616
class Upload extends \Magento\Backend\App\Action implements HttpPostActionInterface
1717
{
@@ -20,7 +20,7 @@ class Upload extends \Magento\Backend\App\Action implements HttpPostActionInterf
2020
*
2121
* @see _isAllowed()
2222
*/
23-
const ADMIN_RESOURCE = 'Magento_Catalog::products';
23+
public const ADMIN_RESOURCE = 'Magento_Catalog::products';
2424

2525
/**
2626
* @var \Magento\Framework\Controller\Result\RawFactory
@@ -98,6 +98,9 @@ public function execute()
9898
$mediaDirectory->getAbsolutePath($this->productMediaConfig->getBaseTmpMediaPath())
9999
);
100100

101+
if ($result === false) {
102+
throw new LocalizedException(__('Something went wrong while saving the file(s).'));
103+
}
101104
$this->_eventManager->dispatch(
102105
'catalog_product_gallery_upload_image_after',
103106
['result' => $result, 'action' => $this]

app/code/Magento/Catalog/Model/ImageUploader.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -247,11 +247,11 @@ public function saveFileToTmpDir($fileId)
247247
throw new LocalizedException(__('File validation failed.'));
248248
}
249249
$result = $uploader->save($this->mediaDirectory->getAbsolutePath($baseTmpPath));
250-
unset($result['path']);
251250

252251
if (!$result) {
253252
throw new LocalizedException(__('File can not be saved to the destination folder.'));
254253
}
254+
unset($result['path']);
255255

256256
/**
257257
* Workaround for prototype 1.7 methods "isJSON", "evalJSON" on Windows OS

app/code/Magento/CatalogImportExport/Model/Import/Uploader.php

Lines changed: 27 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@
77

88
use Magento\Framework\App\Filesystem\DirectoryList;
99
use Magento\Framework\App\ObjectManager;
10+
use Magento\Framework\Exception\FileSystemException;
11+
use Magento\Framework\Exception\LocalizedException;
1012
use Magento\Framework\Exception\ValidatorException;
1113
use Magento\Framework\Filesystem;
1214
use Magento\Framework\Filesystem\Directory\TargetDirectory;
@@ -56,18 +58,14 @@ class Uploader extends \Magento\MediaStorage\Model\File\Uploader
5658
'png' => 'image/png',
5759
];
5860

59-
const DEFAULT_FILE_TYPE = 'application/octet-stream';
61+
public const DEFAULT_FILE_TYPE = 'application/octet-stream';
6062

6163
/**
62-
* Image factory.
63-
*
6464
* @var \Magento\Framework\Image\AdapterFactory
6565
*/
6666
protected $_imageFactory;
6767

6868
/**
69-
* Validator.
70-
*
7169
* @var \Magento\MediaStorage\Model\File\Validator\NotProtectedExtension
7270
*/
7371
protected $_validator;
@@ -114,6 +112,8 @@ class Uploader extends \Magento\MediaStorage\Model\File\Uploader
114112

115113
/**
116114
* Directory and filename must be no more than 255 characters in length
115+
*
116+
* @var int
117117
*/
118118
private $maxFilenameLength = 255;
119119

@@ -132,8 +132,8 @@ class Uploader extends \Magento\MediaStorage\Model\File\Uploader
132132
* @param string|null $filePath
133133
* @param \Magento\Framework\Math\Random|null $random
134134
* @param TargetDirectory|null $targetDirectory
135-
* @throws \Magento\Framework\Exception\FileSystemException
136-
* @throws \Magento\Framework\Exception\LocalizedException
135+
* @throws FileSystemException
136+
* @throws LocalizedException
137137
*/
138138
public function __construct(
139139
\Magento\MediaStorage\Helper\File\Storage\Database $coreFileStorageDb,
@@ -182,7 +182,7 @@ public function init()
182182
* @param string $fileName
183183
* @param bool $renameFileOff
184184
* @return array
185-
* @throws \Magento\Framework\Exception\LocalizedException
185+
* @throws LocalizedException
186186
*/
187187
public function move($fileName, $renameFileOff = false)
188188
{
@@ -197,11 +197,14 @@ public function move($fileName, $renameFileOff = false)
197197
}
198198

199199
$this->_setUploadFile($tmpFilePath);
200-
$rootDirectory = $this->getTargetDirectory()->getDirectoryRead(DirectoryList::ROOT);
200+
$rootDirectory = $this->targetDirectory->getDirectoryRead(DirectoryList::ROOT);
201201
$destDir = $rootDirectory->getAbsolutePath($this->getDestDir());
202202
$result = $this->save($destDir);
203-
unset($result['path']);
204-
$result['name'] = self::getCorrectFileName($result['name']);
203+
204+
if ($result) {
205+
unset($result['path']);
206+
$result['name'] = self::getCorrectFileName($result['name']);
207+
}
205208

206209
// Directory and filename must be no more than 255 characters in length
207210
if (strlen($result['file']) > $this->maxFilenameLength) {
@@ -219,29 +222,30 @@ public function move($fileName, $renameFileOff = false)
219222
* @param string $url
220223
* @param string $driver
221224
* @return string
222-
* @throws \Magento\Framework\Exception\LocalizedException
225+
* @throws LocalizedException
223226
*/
224227
private function downloadFileFromUrl($url, $driver)
225228
{
226229
$parsedUrlPath = parse_url($url, PHP_URL_PATH);
230+
227231
if (!$parsedUrlPath) {
228-
throw new \Magento\Framework\Exception\LocalizedException(__('Could not parse resource url.'));
232+
throw new LocalizedException(__('Could not parse resource url.'));
229233
}
230234
$urlPathValues = explode('/', $parsedUrlPath);
231235
$fileName = preg_replace('/[^a-z0-9\._-]+/i', '', end($urlPathValues));
232-
236+
//phpcs:ignore Magento2.Functions.DiscouragedFunction
233237
$fileExtension = pathinfo($fileName, PATHINFO_EXTENSION);
238+
234239
if ($fileExtension && !$this->checkAllowedExtension($fileExtension)) {
235-
throw new \Magento\Framework\Exception\LocalizedException(__('Disallowed file type.'));
240+
throw new LocalizedException(__('Disallowed file type.'));
236241
}
237-
238242
$tmpFileName = str_replace(".$fileExtension", '', $fileName);
239243
$tmpFileName .= '_' . $this->random->getRandomString(16);
240244
$tmpFileName .= $fileExtension ? ".$fileExtension" : '';
241245
$tmpFilePath = $this->_directory->getRelativePath($this->getTempFilePath($tmpFileName));
242246

243247
if (!$this->_directory->isWritable($this->getTmpDir())) {
244-
throw new \Magento\Framework\Exception\LocalizedException(
248+
throw new LocalizedException(
245249
__('Import images directory must be writable in order to process remote images.')
246250
);
247251
}
@@ -253,26 +257,12 @@ private function downloadFileFromUrl($url, $driver)
253257
return $tmpFilePath;
254258
}
255259

256-
/**
257-
* Retrieves target directory.
258-
*
259-
* @return TargetDirectory
260-
*/
261-
private function getTargetDirectory(): TargetDirectory
262-
{
263-
if (!isset($this->targetDirectory)) {
264-
$this->targetDirectory = ObjectManager::getInstance()->get(TargetDirectory::class);
265-
}
266-
267-
return $this->targetDirectory;
268-
}
269-
270260
/**
271261
* Prepare information about the file for moving
272262
*
273263
* @param string $filePath
274264
* @return void
275-
* @throws \Magento\Framework\Exception\LocalizedException
265+
* @throws LocalizedException
276266
*/
277267
protected function _setUploadFile($filePath)
278268
{
@@ -290,7 +280,7 @@ protected function _setUploadFile($filePath)
290280
$readable = false;
291281
}
292282
if (!$readable) {
293-
throw new \Magento\Framework\Exception\LocalizedException(
283+
throw new LocalizedException(
294284
__('File \'%1\' was not found or has read restriction.', $filePath)
295285
);
296286
}
@@ -322,7 +312,7 @@ protected function _readFileInfo($filePath)
322312
* Validate uploaded file by type and etc.
323313
*
324314
* @return void
325-
* @throws \Magento\Framework\Exception\LocalizedException
315+
* @throws LocalizedException
326316
*/
327317
protected function _validateFile()
328318
{
@@ -335,7 +325,7 @@ protected function _validateFile()
335325

336326
$fileExtension = pathinfo($filePath, PATHINFO_EXTENSION);
337327
if (!$this->checkAllowedExtension($fileExtension)) {
338-
throw new \Magento\Framework\Exception\LocalizedException(__('Disallowed file type.'));
328+
throw new LocalizedException(__('Disallowed file type.'));
339329
}
340330
//run validate callbacks
341331
foreach ($this->_validateCallbacks as $params) {
@@ -405,7 +395,7 @@ public function getDestDir()
405395
*/
406396
public function setDestDir($path)
407397
{
408-
$directoryRoot = $this->getTargetDirectory()->getDirectoryWrite(DirectoryList::ROOT);
398+
$directoryRoot = $this->targetDirectory->getDirectoryWrite(DirectoryList::ROOT);
409399
if (is_string($path) && $directoryRoot->isWritable($path)) {
410400
$this->_destDir = $path;
411401
return true;
@@ -429,7 +419,7 @@ protected function _moveFile($tmpPath, $destPath)
429419
$destinationRealPath = $this->_directory->getDriver()->getRealPath($destPath);
430420
$relativeDestPath = $this->_directory->getRelativePath($destPath);
431421
$isSameFile = $tmpRealPath === $destinationRealPath;
432-
$rootDirectory = $this->getTargetDirectory()->getDirectoryWrite(DirectoryList::ROOT);
422+
$rootDirectory = $this->targetDirectory->getDirectoryWrite(DirectoryList::ROOT);
433423
return $isSameFile ?: $this->_directory->copyFile($tmpPath, $relativeDestPath, $rootDirectory);
434424
} else {
435425
return false;

app/code/Magento/Config/Model/Config/Backend/File.php

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,10 @@
55
*/
66
namespace Magento\Config\Model\Config\Backend;
77

8+
use Exception;
89
use Magento\Framework\App\Config\ScopeConfigInterface;
910
use Magento\Framework\App\Filesystem\DirectoryList;
11+
use Magento\Framework\Exception\LocalizedException;
1012
use Magento\Framework\Filesystem;
1113
use Magento\MediaStorage\Model\File\Uploader;
1214

@@ -82,12 +84,14 @@ public function __construct(
8284
* Save uploaded file before saving config value
8385
*
8486
* @return $this
85-
* @throws \Magento\Framework\Exception\LocalizedException
87+
* @throws LocalizedException
88+
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
8689
*/
8790
public function beforeSave()
8891
{
8992
$value = $this->getValue();
9093
$file = $this->getFileData();
94+
9195
if (!empty($file)) {
9296
$uploadDir = $this->_getUploadDir();
9397
try {
@@ -97,11 +101,10 @@ public function beforeSave()
97101
$uploader->setAllowRenameFiles(true);
98102
$uploader->addValidateCallback('size', $this, 'validateMaxSize');
99103
$result = $uploader->save($uploadDir);
100-
} catch (\Exception $e) {
101-
throw new \Magento\Framework\Exception\LocalizedException(__('%1', $e->getMessage()));
104+
} catch (Exception $e) {
105+
throw new LocalizedException(__('%1', $e->getMessage()));
102106
}
103-
104-
$filename = $result['file'];
107+
$filename = ($result !== false) ? $result['file'] : '';
105108
if ($filename) {
106109
if ($this->_addWhetherScopeInfo()) {
107110
$filename = $this->_prependScopeInfo($filename);
@@ -148,7 +151,7 @@ protected function getFileData()
148151
*
149152
* @param string $filePath Path to temporary uploaded file
150153
* @return void
151-
* @throws \Magento\Framework\Exception\LocalizedException
154+
* @throws LocalizedException
152155
*/
153156
public function validateMaxSize($filePath)
154157
{
@@ -157,7 +160,7 @@ public function validateMaxSize($filePath)
157160
$directory->getRelativePath($filePath)
158161
)['size'] > $this->_maxFileSize * 1024
159162
) {
160-
throw new \Magento\Framework\Exception\LocalizedException(
163+
throw new LocalizedException(
161164
__('The file you\'re uploading exceeds the server size limit of %1 kilobytes.', $this->_maxFileSize)
162165
);
163166
}
@@ -179,14 +182,14 @@ protected function _addWhetherScopeInfo()
179182
* Return path to directory for upload file
180183
*
181184
* @return string
182-
* @throws \Magento\Framework\Exception\LocalizedException
185+
* @throws LocalizedException
183186
*/
184187
protected function _getUploadDir()
185188
{
186189
$fieldConfig = $this->getFieldConfig();
187190

188191
if (!array_key_exists('upload_dir', $fieldConfig)) {
189-
throw new \Magento\Framework\Exception\LocalizedException(
192+
throw new LocalizedException(
190193
__('The base directory to upload file is not specified.')
191194
);
192195
}

app/code/Magento/Customer/Model/FileProcessor.php

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ class FileProcessor
2727
/**
2828
* Temporary directory name
2929
*/
30-
const TMP_DIR = 'tmp';
30+
public const TMP_DIR = 'tmp';
3131

3232
private const CUSTOMER_FILE_URL_PATH = 'customer/index/viewfile';
3333

@@ -215,12 +215,13 @@ public function saveTemporaryFile($fileId)
215215
);
216216

217217
$result = $uploader->save($path);
218-
unset($result['path']);
218+
219219
if (!$result) {
220220
throw new LocalizedException(
221221
__('File can not be saved to the destination folder.')
222222
);
223223
}
224+
unset($result['path']);
224225

225226
return $result;
226227
}

0 commit comments

Comments
 (0)