init
This commit is contained in:
@@ -0,0 +1,51 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\FileManager\Model;
|
||||
|
||||
use Esun\FileManager\Model\Security\FilePolicy;
|
||||
use Magento\Framework\App\Config\ScopeConfigInterface;
|
||||
use Magento\Store\Model\ScopeInterface;
|
||||
|
||||
class Config
|
||||
{
|
||||
private const XML_PATH_ENABLED = 'filemanager/general/enabled';
|
||||
private const XML_PATH_ALLOWED_EXTENSIONS = 'filemanager/general/allowed_extensions';
|
||||
private const XML_PATH_MAX_FILE_SIZE = 'filemanager/general/max_file_size';
|
||||
private const XML_PATH_UPLOAD_PATH = 'filemanager/general/upload_path';
|
||||
|
||||
public function __construct(private readonly ScopeConfigInterface $scopeConfig)
|
||||
{
|
||||
}
|
||||
|
||||
public function isEnabled(): bool
|
||||
{
|
||||
return $this->scopeConfig->isSetFlag(self::XML_PATH_ENABLED, ScopeInterface::SCOPE_STORE);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string[]
|
||||
*/
|
||||
public function getAllowedExtensions(): array
|
||||
{
|
||||
$value = strtolower((string) $this->scopeConfig->getValue(self::XML_PATH_ALLOWED_EXTENSIONS));
|
||||
$extensions = preg_split('/[\s,]+/', $value, -1, PREG_SPLIT_NO_EMPTY) ?: [];
|
||||
|
||||
return array_values(array_intersect(
|
||||
array_unique($extensions),
|
||||
FilePolicy::getSupportedExtensions()
|
||||
));
|
||||
}
|
||||
|
||||
public function getMaximumFileSizeBytes(): int
|
||||
{
|
||||
$megabytes = (float) $this->scopeConfig->getValue(self::XML_PATH_MAX_FILE_SIZE);
|
||||
|
||||
return (int) round($megabytes * 1024 * 1024);
|
||||
}
|
||||
|
||||
public function getUploadPath(): string
|
||||
{
|
||||
return trim((string) $this->scopeConfig->getValue(self::XML_PATH_UPLOAD_PATH), '/');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\FileManager\Model\Config\Backend;
|
||||
|
||||
use Magento\Framework\App\Config\Value;
|
||||
use Magento\Framework\Exception\LocalizedException;
|
||||
use Esun\FileManager\Model\Security\FilePolicy;
|
||||
|
||||
class AllowedExtensions extends Value
|
||||
{
|
||||
/**
|
||||
* @throws LocalizedException
|
||||
*/
|
||||
public function beforeSave(): self
|
||||
{
|
||||
$value = strtolower((string) $this->getValue());
|
||||
$extensions = preg_split('/[\s,]+/', $value, -1, PREG_SPLIT_NO_EMPTY) ?: [];
|
||||
if (!$extensions) {
|
||||
throw new LocalizedException(__('At least one allowed extension is required.'));
|
||||
}
|
||||
|
||||
foreach ($extensions as $extension) {
|
||||
if (!preg_match('/^[a-z0-9]+$/', $extension)) {
|
||||
throw new LocalizedException(__('Invalid extension: %1', $extension));
|
||||
}
|
||||
if (in_array($extension, FilePolicy::BLOCKED_EXTENSIONS, true)) {
|
||||
throw new LocalizedException(__('The extension %1 is always forbidden.', $extension));
|
||||
}
|
||||
if (!in_array($extension, FilePolicy::getSupportedExtensions(), true)) {
|
||||
throw new LocalizedException(
|
||||
__('The extension %1 does not have a secure MIME policy.', $extension)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
$this->setValue(implode(',', array_values(array_unique($extensions))));
|
||||
|
||||
return parent::beforeSave();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\FileManager\Model\Config\Backend;
|
||||
|
||||
use Magento\Framework\App\Config\Value;
|
||||
use Magento\Framework\Exception\LocalizedException;
|
||||
|
||||
class MaximumFileSize extends Value
|
||||
{
|
||||
/**
|
||||
* @throws LocalizedException
|
||||
*/
|
||||
public function beforeSave(): self
|
||||
{
|
||||
$value = $this->getValue();
|
||||
if (!is_numeric($value) || (float) $value <= 0) {
|
||||
throw new LocalizedException(__('Maximum File Size must be greater than zero.'));
|
||||
}
|
||||
|
||||
return parent::beforeSave();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\FileManager\Model\Config\Backend;
|
||||
|
||||
use Magento\Framework\App\Config\Value;
|
||||
use Magento\Framework\Exception\LocalizedException;
|
||||
|
||||
class UploadPath extends Value
|
||||
{
|
||||
/**
|
||||
* @throws LocalizedException
|
||||
*/
|
||||
public function beforeSave(): self
|
||||
{
|
||||
$path = trim(str_replace('\\', '/', (string) $this->getValue()), '/');
|
||||
if (!preg_match('#^uploads(?:/[a-zA-Z0-9_-]+)*$#', $path)) {
|
||||
throw new LocalizedException(
|
||||
__('Upload Path must be "uploads" or a safe child directory of "uploads".')
|
||||
);
|
||||
}
|
||||
$this->setValue($path);
|
||||
|
||||
return parent::beforeSave();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\FileManager\Model;
|
||||
|
||||
use Magento\Framework\App\Filesystem\DirectoryList;
|
||||
use Magento\Framework\Exception\LocalizedException;
|
||||
use Magento\Framework\Filesystem;
|
||||
use Magento\Framework\Filesystem\Directory\WriteInterface;
|
||||
use Esun\FileManager\Model\ResourceModel\File as FileResource;
|
||||
|
||||
class DeleteService
|
||||
{
|
||||
private WriteInterface $mediaDirectory;
|
||||
|
||||
public function __construct(
|
||||
Filesystem $filesystem,
|
||||
private readonly FileResource $fileResource
|
||||
) {
|
||||
$this->mediaDirectory = $filesystem->getDirectoryWrite(DirectoryList::MEDIA);
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws LocalizedException
|
||||
*/
|
||||
public function delete(File $file): void
|
||||
{
|
||||
$relativePath = str_replace('\\', '/', (string) $file->getData('filepath'));
|
||||
if (!preg_match('#^uploads(?:/[\p{L}\p{N}._-]+)+$#u', $relativePath)
|
||||
|| str_contains($relativePath, '..')
|
||||
) {
|
||||
throw new LocalizedException(__('The stored file path is invalid.'));
|
||||
}
|
||||
|
||||
$connection = $this->fileResource->getConnection();
|
||||
$connection->beginTransaction();
|
||||
try {
|
||||
$this->fileResource->delete($file);
|
||||
if ($this->mediaDirectory->isFile($relativePath)) {
|
||||
$this->mediaDirectory->delete($relativePath);
|
||||
}
|
||||
$connection->commit();
|
||||
} catch (\Throwable $exception) {
|
||||
$connection->rollBack();
|
||||
throw new LocalizedException(__('The file could not be deleted.'), $exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\FileManager\Model;
|
||||
|
||||
use Magento\Framework\Model\AbstractModel;
|
||||
use Esun\FileManager\Model\ResourceModel\File as FileResource;
|
||||
|
||||
class File extends AbstractModel
|
||||
{
|
||||
protected function _construct(): void
|
||||
{
|
||||
$this->_init(FileResource::class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\FileManager\Model;
|
||||
|
||||
use Magento\Framework\File\Uploader;
|
||||
|
||||
class FileUploader extends Uploader
|
||||
{
|
||||
/**
|
||||
* Preserve safe Unicode file names prepared by Filename.
|
||||
*
|
||||
* @param string|null $fileName
|
||||
* @return string
|
||||
* @throws \InvalidArgumentException
|
||||
*/
|
||||
public static function getCorrectFileName($fileName)
|
||||
{
|
||||
$fileName = is_string($fileName) ? ltrim($fileName, '.') : '';
|
||||
if ($fileName === '' || strlen($fileName) > 255
|
||||
|| !preg_match('/^[\p{L}\p{N}._-]+\.[a-z0-9]+$/u', $fileName)
|
||||
|| str_contains($fileName, '..')
|
||||
) {
|
||||
throw new \InvalidArgumentException((string) __('The generated file name is invalid.'));
|
||||
}
|
||||
|
||||
return $fileName;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\FileManager\Model;
|
||||
|
||||
use Magento\Framework\Exception\LocalizedException;
|
||||
|
||||
class Filename
|
||||
{
|
||||
/**
|
||||
* @throws LocalizedException
|
||||
*/
|
||||
public function sanitize(string $originalName, string $extension): string
|
||||
{
|
||||
if ($originalName === '' || str_contains($originalName, "\0")
|
||||
|| str_contains($originalName, '../') || str_contains($originalName, '..\\')
|
||||
) {
|
||||
throw new LocalizedException(__('The file name is invalid.'));
|
||||
}
|
||||
|
||||
$leafName = basename(str_replace('\\', '/', $originalName));
|
||||
$stem = (string) pathinfo($leafName, PATHINFO_FILENAME);
|
||||
$stem = preg_replace('/[^\p{L}\p{N}._-]+/u', '_', $stem) ?? '';
|
||||
$stem = preg_replace('/\.{2,}/', '.', $stem) ?? '';
|
||||
$stem = trim($stem, ".-_ \t\n\r\0\x0B");
|
||||
if ($stem === '') {
|
||||
$stem = 'file';
|
||||
}
|
||||
|
||||
if (function_exists('mb_strcut')) {
|
||||
$stem = mb_strcut($stem, 0, 180, 'UTF-8');
|
||||
} else {
|
||||
$stem = substr($stem, 0, 180);
|
||||
}
|
||||
|
||||
return $stem . '.' . $extension;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\FileManager\Model\ResourceModel;
|
||||
|
||||
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
|
||||
|
||||
class File extends AbstractDb
|
||||
{
|
||||
protected function _construct(): void
|
||||
{
|
||||
$this->_init('esun_filemanager_file', 'id');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\FileManager\Model\ResourceModel\File;
|
||||
|
||||
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
|
||||
use Esun\FileManager\Model\File as FileModel;
|
||||
use Esun\FileManager\Model\ResourceModel\File as FileResource;
|
||||
|
||||
class Collection extends AbstractCollection
|
||||
{
|
||||
protected $_idFieldName = 'id';
|
||||
|
||||
protected function _construct(): void
|
||||
{
|
||||
$this->_init(FileModel::class, FileResource::class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\FileManager\Model\Security;
|
||||
|
||||
use Esun\FileManager\Model\Config;
|
||||
use Magento\Framework\Exception\LocalizedException;
|
||||
use Magento\Framework\File\Mime;
|
||||
|
||||
class FilePolicy
|
||||
{
|
||||
public const BLOCKED_EXTENSIONS = [
|
||||
'php', 'phtml', 'php3', 'php4', 'php5', 'phar', 'cgi', 'pl', 'sh', 'bin',
|
||||
];
|
||||
|
||||
private const MIME_TYPES = [
|
||||
'zip' => ['application/zip', 'application/x-zip', 'application/x-zip-compressed'],
|
||||
'rar' => ['application/vnd.rar', 'application/x-rar', 'application/x-rar-compressed'],
|
||||
'7z' => ['application/x-7z-compressed'],
|
||||
'tar' => ['application/x-tar'],
|
||||
'gz' => ['application/gzip', 'application/x-gzip'],
|
||||
'bz2' => ['application/x-bzip2', 'application/x-bzip'],
|
||||
'pdf' => ['application/pdf'],
|
||||
'doc' => ['application/msword', 'application/x-ole-storage', 'application/CDFV2'],
|
||||
'docx' => ['application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/zip'],
|
||||
'xls' => ['application/vnd.ms-excel', 'application/x-ole-storage', 'application/CDFV2'],
|
||||
'xlsx' => ['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/zip'],
|
||||
'ppt' => ['application/vnd.ms-powerpoint', 'application/x-ole-storage', 'application/CDFV2'],
|
||||
'pptx' => ['application/vnd.openxmlformats-officedocument.presentationml.presentation', 'application/zip'],
|
||||
'jpg' => ['image/jpeg'],
|
||||
'jpeg' => ['image/jpeg'],
|
||||
'png' => ['image/png'],
|
||||
'gif' => ['image/gif'],
|
||||
'webp' => ['image/webp'],
|
||||
];
|
||||
|
||||
public function __construct(
|
||||
private readonly Config $config,
|
||||
private readonly Mime $mime
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Return extensions with an explicit MIME policy.
|
||||
*
|
||||
* @return string[]
|
||||
*/
|
||||
public static function getSupportedExtensions(): array
|
||||
{
|
||||
return array_keys(self::MIME_TYPES);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{extension: string, mime_type: string}
|
||||
* @throws LocalizedException
|
||||
*/
|
||||
public function validate(array $file): array
|
||||
{
|
||||
$name = (string) ($file['name'] ?? '');
|
||||
$tmpName = (string) ($file['tmp_name'] ?? '');
|
||||
$size = (int) ($file['size'] ?? 0);
|
||||
$error = (int) ($file['error'] ?? UPLOAD_ERR_NO_FILE);
|
||||
|
||||
if ($error !== UPLOAD_ERR_OK || $tmpName === '' || !is_uploaded_file($tmpName)) {
|
||||
throw new LocalizedException(__('The file "%1" was not uploaded correctly.', $name));
|
||||
}
|
||||
if ($size <= 0 || $size > $this->config->getMaximumFileSizeBytes()) {
|
||||
throw new LocalizedException(__('The file "%1" exceeds the configured size limit or is empty.', $name));
|
||||
}
|
||||
|
||||
$extension = strtolower((string) pathinfo($name, PATHINFO_EXTENSION));
|
||||
$parts = preg_split('/\./', strtolower($name), -1, PREG_SPLIT_NO_EMPTY) ?: [];
|
||||
if (array_intersect($parts, self::BLOCKED_EXTENSIONS)) {
|
||||
throw new LocalizedException(__('The file "%1" contains a forbidden extension.', $name));
|
||||
}
|
||||
if ($extension === '' || !in_array($extension, $this->config->getAllowedExtensions(), true)) {
|
||||
throw new LocalizedException(__('The extension of "%1" is not allowed.', $name));
|
||||
}
|
||||
if (!isset(self::MIME_TYPES[$extension])) {
|
||||
throw new LocalizedException(__('No secure MIME policy is defined for extension "%1".', $extension));
|
||||
}
|
||||
|
||||
$mimeType = $this->mime->getMimeType($tmpName);
|
||||
if (!in_array($mimeType, self::MIME_TYPES[$extension], true)) {
|
||||
throw new LocalizedException(
|
||||
__('The MIME type "%1" does not match the .%2 extension.', $mimeType, $extension)
|
||||
);
|
||||
}
|
||||
return ['extension' => $extension, 'mime_type' => $mimeType];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\FileManager\Model\Source;
|
||||
|
||||
use Esun\FileManager\Model\Config;
|
||||
use Magento\Framework\Data\OptionSourceInterface;
|
||||
|
||||
class ExtensionOptions implements OptionSourceInterface
|
||||
{
|
||||
public function __construct(private readonly Config $config)
|
||||
{
|
||||
}
|
||||
|
||||
public function toOptionArray(): array
|
||||
{
|
||||
$options = [];
|
||||
foreach ($this->config->getAllowedExtensions() as $extension) {
|
||||
$options[] = ['value' => $extension, 'label' => strtoupper($extension)];
|
||||
}
|
||||
|
||||
return $options;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\FileManager\Model;
|
||||
|
||||
use Esun\FileManager\Model\ResourceModel\File as FileResource;
|
||||
use Esun\FileManager\Model\Security\FilePolicy;
|
||||
use Magento\Framework\App\Filesystem\DirectoryList;
|
||||
use Magento\Framework\Exception\LocalizedException;
|
||||
use Magento\Framework\Filesystem;
|
||||
use Magento\Framework\Filesystem\Directory\WriteInterface;
|
||||
use Magento\Framework\Stdlib\DateTime\TimezoneInterface;
|
||||
use Magento\Framework\UrlInterface;
|
||||
use Magento\Store\Model\StoreManagerInterface;
|
||||
|
||||
class UploadService
|
||||
{
|
||||
private WriteInterface $mediaDirectory;
|
||||
|
||||
public function __construct(
|
||||
Filesystem $filesystem,
|
||||
private readonly Config $config,
|
||||
private readonly FilePolicy $filePolicy,
|
||||
private readonly Filename $filename,
|
||||
private readonly FileUploaderFactory $uploaderFactory,
|
||||
private readonly FileFactory $fileFactory,
|
||||
private readonly FileResource $fileResource,
|
||||
private readonly StoreManagerInterface $storeManager,
|
||||
private readonly TimezoneInterface $timezone
|
||||
) {
|
||||
$this->mediaDirectory = $filesystem->getDirectoryWrite(DirectoryList::MEDIA);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{id: int, filename: string, url: string}
|
||||
* @throws LocalizedException
|
||||
*/
|
||||
public function upload(array $uploadedFile): array
|
||||
{
|
||||
if (!$this->config->isEnabled()) {
|
||||
throw new LocalizedException(__('File Manager is disabled.'));
|
||||
}
|
||||
|
||||
$validated = $this->filePolicy->validate($uploadedFile);
|
||||
$safeName = $this->filename->sanitize(
|
||||
(string) ($uploadedFile['name'] ?? ''),
|
||||
$validated['extension']
|
||||
);
|
||||
$relativeDirectory = $this->config->getUploadPath() . '/'
|
||||
. $this->timezone->date()->format('Y/m');
|
||||
$this->assertSafeRelativePath($relativeDirectory);
|
||||
$this->mediaDirectory->create($relativeDirectory);
|
||||
|
||||
$uploader = $this->uploaderFactory->create(['fileId' => $uploadedFile]);
|
||||
$uploader->setAllowedExtensions($this->config->getAllowedExtensions());
|
||||
$uploader->setAllowRenameFiles(true);
|
||||
$uploader->setFilesDispersion(false);
|
||||
$result = $uploader->save($this->mediaDirectory->getAbsolutePath($relativeDirectory), $safeName);
|
||||
if (!$result || empty($result['file'])) {
|
||||
throw new LocalizedException(__('The file could not be saved.'));
|
||||
}
|
||||
|
||||
$storedName = ltrim((string) $result['file'], '/');
|
||||
$relativePath = $relativeDirectory . '/' . $storedName;
|
||||
$this->assertSafeRelativePath($relativePath);
|
||||
$url = rtrim(
|
||||
$this->storeManager->getStore()->getBaseUrl(UrlInterface::URL_TYPE_MEDIA),
|
||||
'/'
|
||||
) . '/' . str_replace('%2F', '/', rawurlencode($relativePath));
|
||||
|
||||
try {
|
||||
$model = $this->fileFactory->create();
|
||||
$model->setData([
|
||||
'filename' => $storedName,
|
||||
'filepath' => $relativePath,
|
||||
'url' => $url,
|
||||
'extension' => $validated['extension'],
|
||||
'mime_type' => $validated['mime_type'],
|
||||
'size' => (int) ($uploadedFile['size'] ?? 0),
|
||||
]);
|
||||
$this->fileResource->save($model);
|
||||
} catch (\Throwable $exception) {
|
||||
if ($this->mediaDirectory->isFile($relativePath)) {
|
||||
$this->mediaDirectory->delete($relativePath);
|
||||
}
|
||||
throw new LocalizedException(__('The file record could not be saved.'), $exception);
|
||||
}
|
||||
|
||||
return ['id' => (int) $model->getId(), 'filename' => $storedName, 'url' => $url];
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws LocalizedException
|
||||
*/
|
||||
private function assertSafeRelativePath(string $path): void
|
||||
{
|
||||
$normalized = str_replace('\\', '/', $path);
|
||||
if ($normalized !== trim($normalized, '/') || str_contains($normalized, '..')
|
||||
|| !preg_match('#^uploads(?:/[\p{L}\p{N}._-]+)+$#u', $normalized)
|
||||
) {
|
||||
throw new LocalizedException(__('The generated upload path is invalid.'));
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user