init
This commit is contained in:
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\FileManager\Block\Adminhtml;
|
||||
|
||||
use Magento\Backend\Block\Template;
|
||||
use Magento\Backend\Block\Template\Context;
|
||||
use Magento\Framework\AuthorizationInterface;
|
||||
|
||||
class Upload extends Template
|
||||
{
|
||||
public function __construct(
|
||||
Context $context,
|
||||
private readonly AuthorizationInterface $authorization,
|
||||
array $data = []
|
||||
) {
|
||||
parent::__construct($context, $data);
|
||||
}
|
||||
|
||||
public function canUpload(): bool
|
||||
{
|
||||
return $this->authorization->isAllowed('Esun_FileManager::upload');
|
||||
}
|
||||
|
||||
public function getUploadUrl(): string
|
||||
{
|
||||
return $this->getUrl('esun_filemanager/file/upload');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\FileManager\Controller\Adminhtml\File;
|
||||
|
||||
use Magento\Backend\App\Action;
|
||||
use Magento\Framework\App\Action\HttpPostActionInterface;
|
||||
use Magento\Framework\Controller\Result\RedirectFactory;
|
||||
use Esun\FileManager\Model\DeleteService;
|
||||
use Esun\FileManager\Model\FileFactory;
|
||||
use Esun\FileManager\Model\ResourceModel\File as FileResource;
|
||||
|
||||
class Delete extends Action implements HttpPostActionInterface
|
||||
{
|
||||
public const ADMIN_RESOURCE = 'Esun_FileManager::delete';
|
||||
|
||||
public function __construct(
|
||||
Action\Context $context,
|
||||
private readonly RedirectFactory $redirectFactory,
|
||||
private readonly FileFactory $fileFactory,
|
||||
private readonly FileResource $fileResource,
|
||||
private readonly DeleteService $deleteService
|
||||
) {
|
||||
parent::__construct($context);
|
||||
}
|
||||
|
||||
public function execute()
|
||||
{
|
||||
$result = $this->redirectFactory->create();
|
||||
$result->setPath('*/*/index');
|
||||
$id = (int) $this->getRequest()->getParam('id');
|
||||
$file = $this->fileFactory->create();
|
||||
$this->fileResource->load($file, $id);
|
||||
if (!$file->getId()) {
|
||||
$this->messageManager->addErrorMessage(__('The file record no longer exists.'));
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
try {
|
||||
$this->deleteService->delete($file);
|
||||
$this->messageManager->addSuccessMessage(__('The file has been deleted.'));
|
||||
} catch (\Throwable $exception) {
|
||||
$this->messageManager->addErrorMessage($exception->getMessage());
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\FileManager\Controller\Adminhtml\File;
|
||||
|
||||
use Magento\Backend\App\Action;
|
||||
use Magento\Framework\View\Result\PageFactory;
|
||||
|
||||
class Index extends Action
|
||||
{
|
||||
public const ADMIN_RESOURCE = 'Esun_FileManager::filemanager';
|
||||
|
||||
public function __construct(
|
||||
Action\Context $context,
|
||||
private readonly PageFactory $pageFactory
|
||||
) {
|
||||
parent::__construct($context);
|
||||
}
|
||||
|
||||
public function execute()
|
||||
{
|
||||
$page = $this->pageFactory->create();
|
||||
$page->setActiveMenu('Esun_FileManager::filemanager');
|
||||
$page->getConfig()->getTitle()->prepend(__('File Manager'));
|
||||
|
||||
return $page;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\FileManager\Controller\Adminhtml\File;
|
||||
|
||||
use Esun\FileManager\Model\UploadService;
|
||||
use Magento\Backend\App\Action;
|
||||
use Magento\Framework\App\Action\HttpPostActionInterface;
|
||||
use Magento\Framework\Controller\Result\JsonFactory;
|
||||
use Magento\Framework\Exception\LocalizedException;
|
||||
use Psr\Log\LoggerInterface;
|
||||
|
||||
class Upload extends Action implements HttpPostActionInterface
|
||||
{
|
||||
public const ADMIN_RESOURCE = 'Esun_FileManager::upload';
|
||||
|
||||
public function __construct(
|
||||
Action\Context $context,
|
||||
private readonly JsonFactory $jsonFactory,
|
||||
private readonly UploadService $uploadService,
|
||||
private readonly LoggerInterface $logger
|
||||
) {
|
||||
parent::__construct($context);
|
||||
}
|
||||
|
||||
public function execute()
|
||||
{
|
||||
$result = $this->jsonFactory->create();
|
||||
$uploadedFiles = $this->normalizeFiles((array) $this->getRequest()->getFiles('files'));
|
||||
if (!$uploadedFiles) {
|
||||
$contentLength = (int) $this->getRequest()->getServer('CONTENT_LENGTH', 0);
|
||||
$postMaxSize = $this->getPostMaxSizeBytes();
|
||||
$message = $postMaxSize > 0 && $contentLength > $postMaxSize
|
||||
? (string) __(
|
||||
'The upload request exceeds the server limit of %1 MB.',
|
||||
round($postMaxSize / 1024 / 1024, 2)
|
||||
)
|
||||
: (string) __('Please select at least one file.');
|
||||
|
||||
return $result->setData([
|
||||
'error' => true,
|
||||
'message' => $message,
|
||||
'errors' => [],
|
||||
'files' => [],
|
||||
]);
|
||||
}
|
||||
|
||||
$saved = [];
|
||||
$errors = [];
|
||||
foreach ($uploadedFiles as $uploadedFile) {
|
||||
try {
|
||||
$saved[] = $this->uploadService->upload($uploadedFile);
|
||||
} catch (LocalizedException $exception) {
|
||||
$errors[] = $exception->getMessage();
|
||||
} catch (\Throwable $exception) {
|
||||
$this->logger->critical($exception);
|
||||
$errors[] = (string) __('The file could not be uploaded.');
|
||||
}
|
||||
}
|
||||
|
||||
$message = $saved
|
||||
? (string) __(
|
||||
'%1 file(s) uploaded successfully.',
|
||||
count($saved)
|
||||
)
|
||||
: (string) __('No files were uploaded.');
|
||||
|
||||
return $result->setData([
|
||||
'error' => !$saved,
|
||||
'hasErrors' => count($saved) !== count($uploadedFiles),
|
||||
'message' => $message,
|
||||
'errors' => $errors,
|
||||
'files' => $saved,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, array<string, mixed>>
|
||||
*/
|
||||
private function normalizeFiles(array $files): array
|
||||
{
|
||||
if (array_is_list($files)) {
|
||||
return array_values(array_filter(
|
||||
$files,
|
||||
static fn (mixed $file): bool => is_array($file) && array_key_exists('name', $file)
|
||||
));
|
||||
}
|
||||
|
||||
if (!isset($files['name'])) {
|
||||
return [];
|
||||
}
|
||||
if (!is_array($files['name'])) {
|
||||
return [$files];
|
||||
}
|
||||
|
||||
$normalized = [];
|
||||
foreach (array_keys($files['name']) as $index) {
|
||||
$normalized[] = [
|
||||
'name' => $files['name'][$index] ?? '',
|
||||
'type' => $files['type'][$index] ?? '',
|
||||
'tmp_name' => $files['tmp_name'][$index] ?? '',
|
||||
'error' => $files['error'][$index] ?? UPLOAD_ERR_NO_FILE,
|
||||
'size' => $files['size'][$index] ?? 0,
|
||||
];
|
||||
}
|
||||
|
||||
return $normalized;
|
||||
}
|
||||
|
||||
private function getPostMaxSizeBytes(): int
|
||||
{
|
||||
$value = trim((string) ini_get('post_max_size'));
|
||||
$bytes = (int) $value;
|
||||
$unit = strtolower(substr($value, -1));
|
||||
|
||||
return match ($unit) {
|
||||
'g' => $bytes * 1024 * 1024 * 1024,
|
||||
'm' => $bytes * 1024 * 1024,
|
||||
'k' => $bytes * 1024,
|
||||
default => $bytes,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -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.'));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\FileManager\Ui\Component\Listing\Column;
|
||||
|
||||
use Magento\Framework\AuthorizationInterface;
|
||||
use Magento\Framework\UrlInterface;
|
||||
use Magento\Framework\View\Element\UiComponent\ContextInterface;
|
||||
use Magento\Framework\View\Element\UiComponentFactory;
|
||||
use Magento\Ui\Component\Listing\Columns\Column;
|
||||
|
||||
class Actions extends Column
|
||||
{
|
||||
public function __construct(
|
||||
ContextInterface $context,
|
||||
UiComponentFactory $uiComponentFactory,
|
||||
private readonly UrlInterface $urlBuilder,
|
||||
private readonly AuthorizationInterface $authorization,
|
||||
array $components = [],
|
||||
array $data = []
|
||||
) {
|
||||
parent::__construct($context, $uiComponentFactory, $components, $data);
|
||||
}
|
||||
|
||||
public function prepareDataSource(array $dataSource): array
|
||||
{
|
||||
if (!isset($dataSource['data']['items'])) {
|
||||
return $dataSource;
|
||||
}
|
||||
|
||||
$fieldName = (string) $this->getData('name');
|
||||
foreach ($dataSource['data']['items'] as &$item) {
|
||||
if (!isset($item['id'], $item['url'])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$item[$fieldName]['copy'] = [
|
||||
'label' => __('Copy URL'),
|
||||
'url' => (string) $item['url'],
|
||||
];
|
||||
$item[$fieldName]['open'] = [
|
||||
'href' => (string) $item['url'],
|
||||
'label' => __('Open'),
|
||||
'target' => '_blank',
|
||||
];
|
||||
if ($this->authorization->isAllowed('Esun_FileManager::delete')) {
|
||||
$item[$fieldName]['delete'] = [
|
||||
'href' => $this->urlBuilder->getUrl(
|
||||
'esun_filemanager/file/delete',
|
||||
['id' => (int) $item['id']]
|
||||
),
|
||||
'label' => __('Delete'),
|
||||
'post' => true,
|
||||
'confirm' => [
|
||||
'title' => __('Delete %1', (string) ($item['filename'] ?? '')),
|
||||
'message' => __('Are you sure you want to delete this file?'),
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
return $dataSource;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\FileManager\Ui\Component\Listing\Column;
|
||||
|
||||
use Magento\Framework\View\Element\UiComponent\ContextInterface;
|
||||
use Magento\Framework\View\Element\UiComponentFactory;
|
||||
use Magento\Ui\Component\Listing\Columns\Column;
|
||||
|
||||
class Size extends Column
|
||||
{
|
||||
public function __construct(
|
||||
ContextInterface $context,
|
||||
UiComponentFactory $uiComponentFactory,
|
||||
array $components = [],
|
||||
array $data = []
|
||||
) {
|
||||
parent::__construct($context, $uiComponentFactory, $components, $data);
|
||||
}
|
||||
|
||||
public function prepareDataSource(array $dataSource): array
|
||||
{
|
||||
if (!isset($dataSource['data']['items'])) {
|
||||
return $dataSource;
|
||||
}
|
||||
|
||||
$fieldName = (string) $this->getData('name');
|
||||
foreach ($dataSource['data']['items'] as &$item) {
|
||||
$item[$fieldName] = $this->formatBytes((int) ($item[$fieldName] ?? 0));
|
||||
}
|
||||
|
||||
return $dataSource;
|
||||
}
|
||||
|
||||
private function formatBytes(int $bytes): string
|
||||
{
|
||||
$units = ['B', 'KB', 'MB', 'GB', 'TB'];
|
||||
$value = (float) $bytes;
|
||||
$unit = 0;
|
||||
while ($value >= 1024 && $unit < count($units) - 1) {
|
||||
$value /= 1024;
|
||||
++$unit;
|
||||
}
|
||||
|
||||
return number_format($value, $unit === 0 ? 0 : 2) . ' ' . $units[$unit];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\FileManager\Ui\DataProvider\File;
|
||||
|
||||
use Esun\FileManager\Model\ResourceModel\File\CollectionFactory;
|
||||
use Magento\Framework\Api\Filter;
|
||||
use Magento\Ui\DataProvider\AbstractDataProvider;
|
||||
|
||||
class ListingDataProvider extends AbstractDataProvider
|
||||
{
|
||||
public function __construct(
|
||||
string $name,
|
||||
string $primaryFieldName,
|
||||
string $requestFieldName,
|
||||
CollectionFactory $collectionFactory,
|
||||
array $meta = [],
|
||||
array $data = []
|
||||
) {
|
||||
$this->collection = $collectionFactory->create();
|
||||
parent::__construct($name, $primaryFieldName, $requestFieldName, $meta, $data);
|
||||
}
|
||||
|
||||
public function getData(): array
|
||||
{
|
||||
$data = parent::getData();
|
||||
if (!isset($data['items'])) {
|
||||
return $data;
|
||||
}
|
||||
|
||||
foreach ($data['items'] as &$item) {
|
||||
$item['media_directive'] = sprintf(
|
||||
'{{media url="%s"}}',
|
||||
(string) ($item['filepath'] ?? '')
|
||||
);
|
||||
}
|
||||
unset($item);
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
public function addFilter(Filter $filter): void
|
||||
{
|
||||
if ($filter->getField() === 'fulltext') {
|
||||
$this->collection->addFieldToFilter(
|
||||
'filename',
|
||||
['like' => '%' . (string) $filter->getValue() . '%']
|
||||
);
|
||||
|
||||
return;
|
||||
}
|
||||
parent::addFilter($filter);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\FileManager\ViewModel;
|
||||
|
||||
use Magento\Framework\View\Element\Block\ArgumentInterface;
|
||||
use Magento\Framework\File\Size;
|
||||
use Esun\FileManager\Model\Config as ModuleConfig;
|
||||
|
||||
class Config implements ArgumentInterface
|
||||
{
|
||||
public function __construct(
|
||||
private readonly ModuleConfig $config,
|
||||
private readonly Size $fileSize
|
||||
) {
|
||||
}
|
||||
|
||||
public function isEnabled(): bool
|
||||
{
|
||||
return $this->config->isEnabled();
|
||||
}
|
||||
|
||||
public function getAllowedExtensions(): string
|
||||
{
|
||||
return implode(', ', $this->config->getAllowedExtensions());
|
||||
}
|
||||
|
||||
public function getMaximumFileSizeMb(): string
|
||||
{
|
||||
$maximumBytes = min(
|
||||
$this->config->getMaximumFileSizeBytes(),
|
||||
$this->fileSize->getMaxFileSize()
|
||||
);
|
||||
|
||||
return number_format($maximumBytes / 1024 / 1024, 2, '.', '');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?xml version="1.0"?>
|
||||
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="urn:magento:framework:Acl/etc/acl.xsd">
|
||||
<acl>
|
||||
<resources>
|
||||
<resource id="Magento_Backend::admin">
|
||||
<resource id="Magento_Backend::content">
|
||||
<resource id="Esun_FileManager::filemanager" title="File Manager" sortOrder="90">
|
||||
<resource id="Esun_FileManager::upload" title="Upload Files" sortOrder="10"/>
|
||||
<resource id="Esun_FileManager::delete" title="Delete Files" sortOrder="20"/>
|
||||
</resource>
|
||||
</resource>
|
||||
</resource>
|
||||
</resources>
|
||||
</acl>
|
||||
</config>
|
||||
@@ -0,0 +1,9 @@
|
||||
<?xml version="1.0"?>
|
||||
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Backend:etc/menu.xsd">
|
||||
<menu>
|
||||
<add id="Esun_FileManager::filemanager" title="File Manager" module="Esun_FileManager"
|
||||
sortOrder="10" parent="Magento_MediaGalleryUi::media"
|
||||
action="esun_filemanager/file/index" resource="Esun_FileManager::filemanager"/>
|
||||
</menu>
|
||||
</config>
|
||||
@@ -0,0 +1,9 @@
|
||||
<?xml version="1.0"?>
|
||||
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
|
||||
<router id="admin">
|
||||
<route id="esun_filemanager" frontName="esun_filemanager">
|
||||
<module name="Esun_FileManager"/>
|
||||
</route>
|
||||
</router>
|
||||
</config>
|
||||
@@ -0,0 +1,42 @@
|
||||
<?xml version="1.0"?>
|
||||
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
|
||||
<system>
|
||||
<section id="filemanager" translate="label" type="text" sortOrder="950"
|
||||
showInDefault="1" showInWebsite="0" showInStore="0">
|
||||
<label>File Manager</label>
|
||||
<tab>general</tab>
|
||||
<resource>Esun_FileManager::filemanager</resource>
|
||||
<group id="general" translate="label" type="text" sortOrder="10"
|
||||
showInDefault="1" showInWebsite="0" showInStore="0">
|
||||
<label>General Settings</label>
|
||||
<field id="enabled" translate="label" type="select" sortOrder="10"
|
||||
showInDefault="1" showInWebsite="0" showInStore="0">
|
||||
<label>Enabled</label>
|
||||
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
|
||||
</field>
|
||||
<field id="allowed_extensions" translate="label comment" type="textarea" sortOrder="20"
|
||||
showInDefault="1" showInWebsite="0" showInStore="0">
|
||||
<label>Allowed Extensions</label>
|
||||
<comment>Comma or whitespace separated. Executable server-side script extensions are always blocked.</comment>
|
||||
<backend_model>Esun\FileManager\Model\Config\Backend\AllowedExtensions</backend_model>
|
||||
<validate>required-entry</validate>
|
||||
</field>
|
||||
<field id="max_file_size" translate="label comment" type="text" sortOrder="30"
|
||||
showInDefault="1" showInWebsite="0" showInStore="0">
|
||||
<label>Maximum File Size</label>
|
||||
<comment>Maximum size per file in MB. PHP upload_max_filesize and post_max_size must also allow it.</comment>
|
||||
<backend_model>Esun\FileManager\Model\Config\Backend\MaximumFileSize</backend_model>
|
||||
<validate>required-entry validate-number validate-greater-than-zero</validate>
|
||||
</field>
|
||||
<field id="upload_path" translate="label comment" type="text" sortOrder="40"
|
||||
showInDefault="1" showInWebsite="0" showInStore="0">
|
||||
<label>Upload Path</label>
|
||||
<comment>Relative to pub/media and restricted to uploads or a child path of uploads.</comment>
|
||||
<backend_model>Esun\FileManager\Model\Config\Backend\UploadPath</backend_model>
|
||||
<validate>required-entry</validate>
|
||||
</field>
|
||||
</group>
|
||||
</section>
|
||||
</system>
|
||||
</config>
|
||||
@@ -0,0 +1,14 @@
|
||||
<?xml version="1.0"?>
|
||||
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Store:etc/config.xsd">
|
||||
<default>
|
||||
<filemanager>
|
||||
<general>
|
||||
<enabled>1</enabled>
|
||||
<allowed_extensions>zip,rar,7z,tar,gz,bz2,pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif,webp</allowed_extensions>
|
||||
<max_file_size>100</max_file_size>
|
||||
<upload_path>uploads</upload_path>
|
||||
</general>
|
||||
</filemanager>
|
||||
</default>
|
||||
</config>
|
||||
@@ -0,0 +1,30 @@
|
||||
<?xml version="1.0"?>
|
||||
<schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd">
|
||||
<table name="esun_filemanager_file" resource="default" engine="innodb" comment="File Manager Files">
|
||||
<column xsi:type="int" name="id" unsigned="true" nullable="false" identity="true" comment="ID"/>
|
||||
<column xsi:type="varchar" name="filename" nullable="false" length="255" comment="File Name"/>
|
||||
<column xsi:type="varchar" name="filepath" nullable="false" length="512" comment="Media-relative File Path"/>
|
||||
<column xsi:type="text" name="url" nullable="false" comment="Public URL"/>
|
||||
<column xsi:type="varchar" name="extension" nullable="false" length="32" comment="Extension"/>
|
||||
<column xsi:type="varchar" name="mime_type" nullable="false" length="255" comment="MIME Type"/>
|
||||
<column xsi:type="bigint" name="size" unsigned="true" nullable="false" default="0" comment="Size in Bytes"/>
|
||||
<column xsi:type="timestamp" name="created_at" nullable="false" default="CURRENT_TIMESTAMP" comment="Created At"/>
|
||||
<column xsi:type="timestamp" name="updated_at" nullable="false" default="CURRENT_TIMESTAMP" on_update="true" comment="Updated At"/>
|
||||
<constraint xsi:type="primary" referenceId="PRIMARY">
|
||||
<column name="id"/>
|
||||
</constraint>
|
||||
<constraint xsi:type="unique" referenceId="ESUN_FILEMANAGER_FILE_FILEPATH_UNQ">
|
||||
<column name="filepath"/>
|
||||
</constraint>
|
||||
<index referenceId="ESUN_FILEMANAGER_FILE_FILENAME_IDX" indexType="btree">
|
||||
<column name="filename"/>
|
||||
</index>
|
||||
<index referenceId="ESUN_FILEMANAGER_FILE_EXTENSION_IDX" indexType="btree">
|
||||
<column name="extension"/>
|
||||
</index>
|
||||
<index referenceId="ESUN_FILEMANAGER_FILE_CREATED_AT_IDX" indexType="btree">
|
||||
<column name="created_at"/>
|
||||
</index>
|
||||
</table>
|
||||
</schema>
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"esun_filemanager_file": {
|
||||
"column": {
|
||||
"id": true,
|
||||
"filename": true,
|
||||
"filepath": true,
|
||||
"url": true,
|
||||
"extension": true,
|
||||
"mime_type": true,
|
||||
"size": true,
|
||||
"created_at": true,
|
||||
"updated_at": true
|
||||
},
|
||||
"constraint": {
|
||||
"PRIMARY": true,
|
||||
"ESUN_FILEMANAGER_FILE_FILEPATH_UNQ": true
|
||||
},
|
||||
"index": {
|
||||
"ESUN_FILEMANAGER_FILE_FILENAME_IDX": true,
|
||||
"ESUN_FILEMANAGER_FILE_EXTENSION_IDX": true,
|
||||
"ESUN_FILEMANAGER_FILE_CREATED_AT_IDX": true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
<?xml version="1.0"?>
|
||||
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
|
||||
<type name="Esun\FileManager\Model\FileUploader">
|
||||
<plugin name="save_asset_image" disabled="true"/>
|
||||
</type>
|
||||
</config>
|
||||
@@ -0,0 +1,12 @@
|
||||
<?xml version="1.0"?>
|
||||
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
|
||||
<module name="Esun_FileManager">
|
||||
<sequence>
|
||||
<module name="Magento_Backend"/>
|
||||
<module name="Magento_Config"/>
|
||||
<module name="Magento_MediaGalleryUi"/>
|
||||
<module name="Magento_Ui"/>
|
||||
</sequence>
|
||||
</module>
|
||||
</config>
|
||||
@@ -0,0 +1,10 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
use Magento\Framework\Component\ComponentRegistrar;
|
||||
|
||||
ComponentRegistrar::register(
|
||||
ComponentRegistrar::MODULE,
|
||||
'Esun_FileManager',
|
||||
__DIR__
|
||||
);
|
||||
@@ -0,0 +1,15 @@
|
||||
<?xml version="1.0"?>
|
||||
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
|
||||
<body>
|
||||
<referenceContainer name="content">
|
||||
<block class="Esun\FileManager\Block\Adminhtml\Upload" name="esun.filemanager.upload"
|
||||
template="Esun_FileManager::upload.phtml" before="-">
|
||||
<arguments>
|
||||
<argument name="view_model" xsi:type="object">Esun\FileManager\ViewModel\Config</argument>
|
||||
</arguments>
|
||||
</block>
|
||||
<uiComponent name="esun_filemanager_file_listing"/>
|
||||
</referenceContainer>
|
||||
</body>
|
||||
</page>
|
||||
@@ -0,0 +1,63 @@
|
||||
<?php
|
||||
/**
|
||||
* @var \Esun\FileManager\Block\Adminhtml\Upload $block
|
||||
* @var \Magento\Framework\Escaper $escaper
|
||||
* @var \Esun\FileManager\ViewModel\Config $viewModel
|
||||
*/
|
||||
$viewModel = $block->getData('view_model');
|
||||
?>
|
||||
<div class="vendor-filemanager-upload" data-role="filemanager-upload">
|
||||
<?php if (!$viewModel->isEnabled()): ?>
|
||||
<div class="message message-warning">
|
||||
<?= $escaper->escapeHtml(__('File Manager is disabled in Stores > Configuration > General > File Manager.')) ?>
|
||||
</div>
|
||||
<?php elseif ($block->canUpload()): ?>
|
||||
<form action="<?= $escaper->escapeUrl($block->getUploadUrl()) ?>"
|
||||
method="post" enctype="multipart/form-data" data-role="upload-form">
|
||||
<?= $block->getBlockHtml('formkey') ?>
|
||||
<input type="file" name="files[]" multiple required
|
||||
accept="<?= $escaper->escapeHtmlAttr('.' . str_replace(', ', ',.', $viewModel->getAllowedExtensions())) ?>"/>
|
||||
<button type="submit" class="action-primary">
|
||||
<span><?= $escaper->escapeHtml(__('Upload Files')) ?></span>
|
||||
</button>
|
||||
<span class="note">
|
||||
<?= $escaper->escapeHtml(
|
||||
__('Maximum: %1 MB. Formats: %2', $viewModel->getMaximumFileSizeMb(), $viewModel->getAllowedExtensions())
|
||||
) ?>
|
||||
</span>
|
||||
<div data-role="upload-progress" hidden>
|
||||
<progress data-role="upload-progress-bar" max="100" value="0"></progress>
|
||||
<span data-role="upload-progress-label">0%</span>
|
||||
</div>
|
||||
</form>
|
||||
<?php endif; ?>
|
||||
<?php if ($viewModel->isEnabled()): ?>
|
||||
<div class="message message-info">
|
||||
<strong><?= $escaper->escapeHtml(__('Page Builder Usage')) ?></strong>
|
||||
<div>
|
||||
<?= $escaper->escapeHtml(
|
||||
__('Copy the Media Directive from the grid and use it in a Page Builder HTML Code block.')
|
||||
) ?>
|
||||
</div>
|
||||
<div>
|
||||
<code><?= $escaper->escapeHtml(
|
||||
'<a href=\'{{media url="uploads/YYYY/MM/file.pdf"}}\'>Download attachment</a>'
|
||||
) ?></code>
|
||||
</div>
|
||||
<div>
|
||||
<code><?= $escaper->escapeHtml(
|
||||
'<img src=\'{{media url="uploads/YYYY/MM/image.jpg"}}\' alt="">'
|
||||
) ?></code>
|
||||
</div>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
<?php if ($viewModel->isEnabled() && $block->canUpload()): ?>
|
||||
<script type="text/x-magento-init">
|
||||
{
|
||||
"[data-role=filemanager-upload]": {
|
||||
"Esun_FileManager/js/upload": {}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
<?php endif; ?>
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
<?xml version="1.0"?>
|
||||
<listing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
|
||||
<argument name="data" xsi:type="array">
|
||||
<item name="js_config" xsi:type="array">
|
||||
<item name="provider" xsi:type="string">esun_filemanager_file_listing.esun_filemanager_file_listing_data_source</item>
|
||||
</item>
|
||||
</argument>
|
||||
<settings>
|
||||
<spinner>esun_filemanager_file_columns</spinner>
|
||||
<deps>
|
||||
<dep>esun_filemanager_file_listing.esun_filemanager_file_listing_data_source</dep>
|
||||
</deps>
|
||||
</settings>
|
||||
<dataSource name="esun_filemanager_file_listing_data_source" component="Magento_Ui/js/grid/provider">
|
||||
<settings>
|
||||
<storageConfig>
|
||||
<param name="indexField" xsi:type="string">id</param>
|
||||
</storageConfig>
|
||||
<updateUrl path="mui/index/render"/>
|
||||
</settings>
|
||||
<aclResource>Esun_FileManager::filemanager</aclResource>
|
||||
<dataProvider class="Esun\FileManager\Ui\DataProvider\File\ListingDataProvider"
|
||||
name="esun_filemanager_file_listing_data_source">
|
||||
<settings>
|
||||
<requestFieldName>id</requestFieldName>
|
||||
<primaryFieldName>id</primaryFieldName>
|
||||
</settings>
|
||||
</dataProvider>
|
||||
</dataSource>
|
||||
<listingToolbar name="listing_top">
|
||||
<settings>
|
||||
<sticky>true</sticky>
|
||||
</settings>
|
||||
<bookmark name="bookmarks"/>
|
||||
<columnsControls name="columns_controls"/>
|
||||
<filterSearch name="fulltext">
|
||||
<settings>
|
||||
<placeholder translate="true">Search file name</placeholder>
|
||||
</settings>
|
||||
</filterSearch>
|
||||
<filters name="listing_filters"/>
|
||||
<paging name="listing_paging">
|
||||
<settings>
|
||||
<options>
|
||||
<option name="20" xsi:type="array">
|
||||
<item name="value" xsi:type="number">20</item>
|
||||
<item name="label" xsi:type="string">20</item>
|
||||
</option>
|
||||
<option name="50" xsi:type="array">
|
||||
<item name="value" xsi:type="number">50</item>
|
||||
<item name="label" xsi:type="string">50</item>
|
||||
</option>
|
||||
<option name="100" xsi:type="array">
|
||||
<item name="value" xsi:type="number">100</item>
|
||||
<item name="label" xsi:type="string">100</item>
|
||||
</option>
|
||||
</options>
|
||||
<pageSize>20</pageSize>
|
||||
</settings>
|
||||
</paging>
|
||||
</listingToolbar>
|
||||
<columns name="esun_filemanager_file_columns">
|
||||
<column name="filename">
|
||||
<settings>
|
||||
<filter>text</filter>
|
||||
<label translate="true">File Name</label>
|
||||
</settings>
|
||||
</column>
|
||||
<column name="extension" component="Magento_Ui/js/grid/columns/select">
|
||||
<settings>
|
||||
<options class="Esun\FileManager\Model\Source\ExtensionOptions"/>
|
||||
<filter>select</filter>
|
||||
<dataType>select</dataType>
|
||||
<label translate="true">Type</label>
|
||||
</settings>
|
||||
</column>
|
||||
<column name="size" class="Esun\FileManager\Ui\Component\Listing\Column\Size">
|
||||
<settings>
|
||||
<filter>false</filter>
|
||||
<label translate="true">Size</label>
|
||||
</settings>
|
||||
</column>
|
||||
<column name="created_at" class="Magento\Ui\Component\Listing\Columns\Date"
|
||||
component="Magento_Ui/js/grid/columns/date">
|
||||
<settings>
|
||||
<filter>dateRange</filter>
|
||||
<dataType>date</dataType>
|
||||
<sorting>desc</sorting>
|
||||
<label translate="true">Uploaded At</label>
|
||||
</settings>
|
||||
</column>
|
||||
<column name="url">
|
||||
<settings>
|
||||
<filter>false</filter>
|
||||
<sortable>false</sortable>
|
||||
<label translate="true">URL</label>
|
||||
</settings>
|
||||
</column>
|
||||
<column name="media_directive">
|
||||
<settings>
|
||||
<filter>false</filter>
|
||||
<sortable>false</sortable>
|
||||
<label translate="true">Media Directive</label>
|
||||
</settings>
|
||||
</column>
|
||||
<actionsColumn name="actions" class="Esun\FileManager\Ui\Component\Listing\Column\Actions"
|
||||
component="Esun_FileManager/js/grid/columns/actions">
|
||||
<settings>
|
||||
<indexField>id</indexField>
|
||||
<resizeEnabled>false</resizeEnabled>
|
||||
<resizeDefaultWidth>170</resizeDefaultWidth>
|
||||
</settings>
|
||||
</actionsColumn>
|
||||
</columns>
|
||||
</listing>
|
||||
@@ -0,0 +1,58 @@
|
||||
define([
|
||||
'jquery',
|
||||
'Magento_Ui/js/grid/columns/actions',
|
||||
'mage/translate',
|
||||
'mage/backend/notification'
|
||||
], function ($, Actions) {
|
||||
'use strict';
|
||||
|
||||
function notify(message, isError) {
|
||||
$('body').notification('clear').notification('add', {
|
||||
error: isError,
|
||||
message: message,
|
||||
insertMethod: function (renderedMessage) {
|
||||
$('.page-main-actions').after(renderedMessage);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function fallbackCopy(value) {
|
||||
var input = $('<textarea>')
|
||||
.css({position: 'fixed', opacity: 0})
|
||||
.val(value)
|
||||
.appendTo('body');
|
||||
|
||||
input[0].select();
|
||||
document.execCommand('copy');
|
||||
input.remove();
|
||||
}
|
||||
|
||||
return Actions.extend({
|
||||
defaultCallback: function (actionIndex, recordId, action) {
|
||||
var promise;
|
||||
|
||||
if (actionIndex !== 'copy') {
|
||||
return this._super(actionIndex, recordId, action);
|
||||
}
|
||||
|
||||
try {
|
||||
if (navigator.clipboard && window.isSecureContext) {
|
||||
promise = navigator.clipboard.writeText(action.url);
|
||||
promise.then(function () {
|
||||
notify($.mage.__('URL copied successfully.'), false);
|
||||
}).catch(function () {
|
||||
fallbackCopy(action.url);
|
||||
notify($.mage.__('URL copied successfully.'), false);
|
||||
});
|
||||
} else {
|
||||
fallbackCopy(action.url);
|
||||
notify($.mage.__('URL copied successfully.'), false);
|
||||
}
|
||||
} catch (error) {
|
||||
notify($.mage.__('The URL could not be copied.'), true);
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,97 @@
|
||||
define([
|
||||
'jquery',
|
||||
'uiRegistry',
|
||||
'mage/translate',
|
||||
'mage/backend/notification'
|
||||
], function ($, registry) {
|
||||
'use strict';
|
||||
|
||||
function notify(message, isError) {
|
||||
$('body').notification('add', {
|
||||
error: isError,
|
||||
message: message,
|
||||
insertMethod: function (renderedMessage) {
|
||||
$('.page-main-actions').after(renderedMessage);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return function (config, element) {
|
||||
var $container = $(element),
|
||||
$form = $container.find('[data-role=upload-form]'),
|
||||
$button = $form.find('button[type=submit]'),
|
||||
$progress = $form.find('[data-role=upload-progress]'),
|
||||
$progressBar = $form.find('[data-role=upload-progress-bar]'),
|
||||
$progressLabel = $form.find('[data-role=upload-progress-label]');
|
||||
|
||||
function setProgress(percent) {
|
||||
$progressBar.val(percent);
|
||||
$progressLabel.text(percent + '%');
|
||||
}
|
||||
|
||||
$form.on('submit', function (event) {
|
||||
var data;
|
||||
|
||||
event.preventDefault();
|
||||
if (!$form.find('input[type=file]')[0].files.length) {
|
||||
notify($.mage.__('Please select at least one file.'), true);
|
||||
return;
|
||||
}
|
||||
|
||||
data = new FormData($form[0]);
|
||||
$button.prop('disabled', true);
|
||||
setProgress(0);
|
||||
$progress.prop('hidden', false);
|
||||
$.ajax({
|
||||
url: $form.attr('action'),
|
||||
method: 'POST',
|
||||
data: data,
|
||||
processData: false,
|
||||
contentType: false,
|
||||
dataType: 'json',
|
||||
xhr: function () {
|
||||
var xhr = $.ajaxSettings.xhr();
|
||||
|
||||
if (xhr.upload) {
|
||||
xhr.upload.addEventListener('progress', function (progressEvent) {
|
||||
if (progressEvent.lengthComputable) {
|
||||
setProgress(Math.round(
|
||||
progressEvent.loaded / progressEvent.total * 100
|
||||
));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return xhr;
|
||||
}
|
||||
}).done(function (response) {
|
||||
setProgress(100);
|
||||
if (response.ajaxExpired && response.ajaxRedirect) {
|
||||
window.location.href = response.ajaxRedirect;
|
||||
return;
|
||||
}
|
||||
$('body').notification('clear');
|
||||
if (response.message) {
|
||||
notify(response.message, response.error);
|
||||
}
|
||||
$.each(response.errors || [], function (index, message) {
|
||||
notify(message, true);
|
||||
});
|
||||
if ((response.files || []).length) {
|
||||
$form[0].reset();
|
||||
registry.async(
|
||||
'esun_filemanager_file_listing.esun_filemanager_file_listing_data_source'
|
||||
)(function (provider) {
|
||||
provider.reload({refresh: true});
|
||||
});
|
||||
}
|
||||
}).fail(function () {
|
||||
notify($.mage.__('The upload request failed.'), true);
|
||||
}).always(function () {
|
||||
$button.prop('disabled', false);
|
||||
$progress.prop('hidden', true);
|
||||
setProgress(0);
|
||||
});
|
||||
});
|
||||
};
|
||||
});
|
||||
Reference in New Issue
Block a user