This commit is contained in:
2026-09-15 10:35:56 +08:00
commit 782f8ea7aa
4086 changed files with 631288 additions and 0 deletions
@@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
namespace Esun\ImageManager\Block\Adminhtml\Category;
use Esun\ImageManager\Model\Category;
use Esun\ImageManager\Model\CategoryFactory;
use Magento\Backend\Block\Template;
use Magento\Backend\Block\Template\Context;
class EditBlock extends Template
{
private ?Category $category = null;
public function __construct(
Context $context,
private readonly CategoryFactory $categoryFactory,
array $data = []
) {
parent::__construct($context, $data);
}
public function getCategory(): Category
{
if ($this->category === null) {
$this->category = $this->categoryFactory->create();
$id = (int) $this->getRequest()->getParam('id');
if ($id > 0) {
$this->category->load($id);
}
}
return $this->category;
}
public function getSaveUrl(): string
{
return $this->getUrl('esun_image_manager/category/save');
}
public function getBackUrl(): string
{
return $this->getUrl('esun_image_manager/category/index');
}
}
@@ -0,0 +1,64 @@
<?php
declare(strict_types=1);
namespace Esun\ImageManager\Block\Adminhtml\Category;
use Esun\ImageManager\Model\ResourceModel\Category\Collection;
use Esun\ImageManager\Model\ResourceModel\Category\CollectionFactory;
use Magento\Backend\Block\Template;
use Magento\Backend\Block\Template\Context;
class ListBlock extends Template
{
private ?Collection $categories = null;
public function __construct(
Context $context,
private readonly CollectionFactory $collectionFactory,
array $data = []
) {
parent::__construct($context, $data);
}
public function getCategories(): Collection
{
if ($this->categories === null) {
$this->categories = $this->collectionFactory->create()
->setOrder('sort_order', 'ASC')
->setOrder('category_id', 'DESC');
$query = trim((string) $this->getRequest()->getParam('query'));
if ($query !== '') {
$this->categories->addFieldToFilter(
['name', 'identifier'],
[['like' => '%' . $query . '%'], ['like' => '%' . $query . '%']]
);
}
}
return $this->categories;
}
public function getQueryFilter(): string
{
return trim((string) $this->getRequest()->getParam('query'));
}
public function getNewUrl(): string
{
return $this->getUrl('esun_image_manager/category/new');
}
public function getIndexUrl(): string
{
return $this->getUrl('esun_image_manager/category/index');
}
public function getEditUrl(int $id): string
{
return $this->getUrl('esun_image_manager/category/edit', ['id' => $id]);
}
public function getDeleteUrl(int $id): string
{
return $this->getUrl('esun_image_manager/category/delete', ['id' => $id]);
}
}
@@ -0,0 +1,67 @@
<?php
declare(strict_types=1);
namespace Esun\ImageManager\Block\Adminhtml\Image;
use Esun\ImageManager\Model\Image;
use Esun\ImageManager\Model\ImageFactory;
use Esun\ImageManager\Model\ResourceModel\Category\CollectionFactory as CategoryCollectionFactory;
use Magento\Backend\Block\Template;
use Magento\Backend\Block\Template\Context;
use Magento\Framework\UrlInterface;
use Magento\Store\Model\StoreManagerInterface;
class EditBlock extends Template
{
private ?Image $image = null;
public function __construct(
Context $context,
private readonly ImageFactory $imageFactory,
private readonly CategoryCollectionFactory $categoryCollectionFactory,
private readonly StoreManagerInterface $storeManager,
array $data = []
) {
parent::__construct($context, $data);
}
public function getImageModel(): Image
{
if ($this->image === null) {
$this->image = $this->imageFactory->create();
$id = (int) $this->getRequest()->getParam('id');
if ($id > 0) {
$this->image->load($id);
}
}
return $this->image;
}
public function getCategories()
{
return $this->categoryCollectionFactory->create()
->addFieldToFilter('status', 1)
->setOrder('sort_order', 'ASC')
->setOrder('name', 'ASC');
}
public function getMediaUrl(string $path): string
{
return $this->storeManager->getStore()->getBaseUrl(UrlInterface::URL_TYPE_MEDIA) . ltrim($path, '/');
}
public function getSaveUrl(): string
{
return $this->getUrl('esun_image_manager/image/save');
}
public function getBackUrl(): string
{
return $this->getUrl('esun_image_manager/image/index');
}
public function getCategoryUrl(): string
{
return $this->getUrl('esun_image_manager/category/new');
}
}
@@ -0,0 +1,46 @@
<?php
declare(strict_types=1);
namespace Esun\ImageManager\Controller\Adminhtml\Category;
use Esun\ImageManager\Model\CategoryFactory;
use Esun\ImageManager\Model\ResourceModel\Image\CollectionFactory as ImageCollectionFactory;
use Magento\Backend\App\Action;
use Magento\Framework\Exception\LocalizedException;
class Delete extends Action
{
public const ADMIN_RESOURCE = 'Esun_ImageManager::categories_delete';
public function __construct(
Action\Context $context,
private readonly CategoryFactory $categoryFactory,
private readonly ImageCollectionFactory $imageCollectionFactory
) {
parent::__construct($context);
}
public function execute()
{
try {
$category = $this->categoryFactory->create()->load((int) $this->getRequest()->getParam('id'));
if (!$category->getId()) {
throw new LocalizedException(__('The category no longer exists.'));
}
$imageCount = $this->imageCollectionFactory->create()
->addFieldToFilter('main_table.category_id', (int) $category->getId())
->getSize();
if ($imageCount > 0) {
throw new LocalizedException(
__('This category contains %1 image(s). Move or delete them first.', $imageCount)
);
}
$category->delete();
$this->messageManager->addSuccessMessage(__('The image category has been deleted.'));
} catch (\Throwable $e) {
$this->messageManager->addErrorMessage($e->getMessage());
}
return $this->resultRedirectFactory->create()->setPath('esun_image_manager/category/index');
}
}
@@ -0,0 +1,35 @@
<?php
declare(strict_types=1);
namespace Esun\ImageManager\Controller\Adminhtml\Category;
use Esun\ImageManager\Model\CategoryFactory;
use Magento\Backend\App\Action;
use Magento\Framework\View\Result\PageFactory;
class Edit extends Action
{
public const ADMIN_RESOURCE = 'Esun_ImageManager::categories_save';
public function __construct(
Action\Context $context,
private readonly PageFactory $pageFactory,
private readonly CategoryFactory $categoryFactory
) {
parent::__construct($context);
}
public function execute()
{
$id = (int) $this->getRequest()->getParam('id');
if ($id > 0 && !$this->categoryFactory->create()->load($id)->getId()) {
$this->messageManager->addErrorMessage(__('The category no longer exists.'));
return $this->resultRedirectFactory->create()->setPath('esun_image_manager/category/index');
}
$page = $this->pageFactory->create();
$page->getConfig()->getTitle()->prepend($id ? __('Edit Image Category') : __('New Image Category'));
return $page;
}
}
@@ -0,0 +1,25 @@
<?php
declare(strict_types=1);
namespace Esun\ImageManager\Controller\Adminhtml\Category;
use Magento\Backend\App\Action;
use Magento\Framework\View\Result\PageFactory;
class Index extends Action
{
public const ADMIN_RESOURCE = 'Esun_ImageManager::categories';
public function __construct(Action\Context $context, private readonly PageFactory $pageFactory)
{
parent::__construct($context);
}
public function execute()
{
$page = $this->pageFactory->create();
$page->getConfig()->getTitle()->prepend(__('Image Categories'));
return $page;
}
}
@@ -0,0 +1,8 @@
<?php
declare(strict_types=1);
namespace Esun\ImageManager\Controller\Adminhtml\Category;
class NewAction extends Edit
{
}
@@ -0,0 +1,58 @@
<?php
declare(strict_types=1);
namespace Esun\ImageManager\Controller\Adminhtml\Category;
use Esun\ImageManager\Model\CategoryFactory;
use Magento\Backend\App\Action;
use Magento\Framework\Exception\LocalizedException;
class Save extends Action
{
public const ADMIN_RESOURCE = 'Esun_ImageManager::categories_save';
public function __construct(Action\Context $context, private readonly CategoryFactory $categoryFactory)
{
parent::__construct($context);
}
public function execute()
{
$id = (int) $this->getRequest()->getParam('category_id');
$redirect = $this->resultRedirectFactory->create();
try {
$category = $this->categoryFactory->create();
if ($id > 0) {
$category->load($id);
if (!$category->getId()) {
throw new LocalizedException(__('The category no longer exists.'));
}
}
$name = trim((string) $this->getRequest()->getParam('name'));
$identifier = strtolower(trim((string) $this->getRequest()->getParam('identifier')));
$identifier = trim((string) preg_replace('/[^a-z0-9_-]+/', '-', $identifier), '-');
if ($name === '' || $identifier === '') {
throw new LocalizedException(__('Name and identifier are required.'));
}
$category->addData([
'name' => $name,
'identifier' => $identifier,
'description' => trim((string) $this->getRequest()->getParam('description')),
'status' => $this->getRequest()->getParam('status') === '0' ? 0 : 1,
'sort_order' => (int) $this->getRequest()->getParam('sort_order'),
])->save();
$this->messageManager->addSuccessMessage(__('The image category has been saved.'));
return $redirect->setPath('esun_image_manager/category/index');
} catch (\Throwable $e) {
$this->messageManager->addErrorMessage($e->getMessage());
return $redirect->setPath(
$id ? 'esun_image_manager/category/edit' : 'esun_image_manager/category/new',
$id ? ['id' => $id] : []
);
}
}
}
@@ -0,0 +1,46 @@
<?php
declare(strict_types=1);
namespace Esun\ImageManager\Controller\Adminhtml\Image;
use Esun\ImageManager\Model\ImageFactory;
use Esun\ImageManager\Model\MediaUploader;
use Magento\Backend\App\Action;
use Magento\Framework\Exception\LocalizedException;
class Delete extends Action
{
public const ADMIN_RESOURCE = 'Esun_ImageManager::images_delete';
public function __construct(
Action\Context $context,
private readonly ImageFactory $imageFactory,
private readonly MediaUploader $mediaUploader
) {
parent::__construct($context);
}
public function execute()
{
try {
$image = $this->imageFactory->create()->load((int) $this->getRequest()->getParam('id'));
if (!$image->getId()) {
throw new LocalizedException(__('The image no longer exists.'));
}
$paths = [
(string) $image->getData('thumbnail_path'),
(string) $image->getData('image_path'),
(string) $image->getData('icon_path'),
];
$image->delete();
foreach ($paths as $path) {
$this->mediaUploader->delete($path);
}
$this->messageManager->addSuccessMessage(__('The image has been deleted.'));
} catch (\Throwable $e) {
$this->messageManager->addErrorMessage($e->getMessage());
}
return $this->resultRedirectFactory->create()->setPath('esun_image_manager/image/index');
}
}
@@ -0,0 +1,35 @@
<?php
declare(strict_types=1);
namespace Esun\ImageManager\Controller\Adminhtml\Image;
use Esun\ImageManager\Model\ImageFactory;
use Magento\Backend\App\Action;
use Magento\Framework\View\Result\PageFactory;
class Edit extends Action
{
public const ADMIN_RESOURCE = 'Esun_ImageManager::images_save';
public function __construct(
Action\Context $context,
private readonly PageFactory $pageFactory,
private readonly ImageFactory $imageFactory
) {
parent::__construct($context);
}
public function execute()
{
$id = (int) $this->getRequest()->getParam('id');
if ($id > 0 && !$this->imageFactory->create()->load($id)->getId()) {
$this->messageManager->addErrorMessage(__('The image no longer exists.'));
return $this->resultRedirectFactory->create()->setPath('esun_image_manager/image/index');
}
$page = $this->pageFactory->create();
$page->getConfig()->getTitle()->prepend($id ? __('Edit Image') : __('New Image'));
return $page;
}
}
@@ -0,0 +1,25 @@
<?php
declare(strict_types=1);
namespace Esun\ImageManager\Controller\Adminhtml\Image;
use Magento\Backend\App\Action;
use Magento\Framework\View\Result\PageFactory;
class Index extends Action
{
public const ADMIN_RESOURCE = 'Esun_ImageManager::images';
public function __construct(Action\Context $context, private readonly PageFactory $pageFactory)
{
parent::__construct($context);
}
public function execute()
{
$page = $this->pageFactory->create();
$page->getConfig()->getTitle()->prepend(__('Image Manager'));
return $page;
}
}
@@ -0,0 +1,8 @@
<?php
declare(strict_types=1);
namespace Esun\ImageManager\Controller\Adminhtml\Image;
class NewAction extends Edit
{
}
@@ -0,0 +1,88 @@
<?php
declare(strict_types=1);
namespace Esun\ImageManager\Controller\Adminhtml\Image;
use Esun\ImageManager\Model\CategoryFactory;
use Esun\ImageManager\Model\ImageFactory;
use Esun\ImageManager\Model\MediaUploader;
use Magento\Backend\App\Action;
use Magento\Framework\Exception\LocalizedException;
class Save extends Action
{
public const ADMIN_RESOURCE = 'Esun_ImageManager::images_save';
public function __construct(
Action\Context $context,
private readonly ImageFactory $imageFactory,
private readonly CategoryFactory $categoryFactory,
private readonly MediaUploader $mediaUploader
) {
parent::__construct($context);
}
public function execute()
{
$id = (int) $this->getRequest()->getParam('image_id');
$redirect = $this->resultRedirectFactory->create();
$uploadedPaths = [];
try {
$image = $this->imageFactory->create();
if ($id > 0) {
$image->load($id);
if (!$image->getId()) {
throw new LocalizedException(__('The image no longer exists.'));
}
}
$title = trim((string) $this->getRequest()->getParam('title'));
$categoryId = (int) $this->getRequest()->getParam('category_id');
if ($title === '' || !$this->categoryFactory->create()->load($categoryId)->getId()) {
throw new LocalizedException(__('Title and a valid category are required.'));
}
$oldPaths = [];
foreach (['thumbnail', 'image', 'icon'] as $field) {
$pathField = $field . '_path';
$oldPaths[$field] = (string) $image->getData($pathField);
$newPath = $this->mediaUploader->save($field);
if ($newPath !== null) {
$uploadedPaths[$field] = $newPath;
$image->setData($pathField, $newPath);
} elseif ($this->getRequest()->getParam('delete_' . $field)) {
$image->setData($pathField, '');
}
}
$image->addData([
'category_id' => $categoryId,
'title' => $title,
'description' => trim((string) $this->getRequest()->getParam('description')),
'link_url' => trim((string) $this->getRequest()->getParam('link_url')),
'status' => $this->getRequest()->getParam('status') === '0' ? 0 : 1,
'sort_order' => (int) $this->getRequest()->getParam('sort_order'),
])->save();
foreach ($oldPaths as $field => $oldPath) {
$currentPath = (string) $image->getData($field . '_path');
if ($oldPath !== '' && $oldPath !== $currentPath) {
$this->mediaUploader->delete($oldPath);
}
}
$this->messageManager->addSuccessMessage(__('The image has been saved.'));
return $redirect->setPath('esun_image_manager/image/index');
} catch (\Throwable $e) {
foreach ($uploadedPaths as $path) {
$this->mediaUploader->delete($path);
}
$this->messageManager->addErrorMessage($e->getMessage());
return $redirect->setPath(
$id ? 'esun_image_manager/image/edit' : 'esun_image_manager/image/new',
$id ? ['id' => $id] : []
);
}
}
}
@@ -0,0 +1,25 @@
<?php
declare(strict_types=1);
namespace Esun\ImageManager\Model;
use Magento\Framework\Model\AbstractModel;
use Magento\Framework\DataObject\IdentityInterface;
class Category extends AbstractModel implements IdentityInterface
{
public const CACHE_TAG = 'esun_image_category';
protected $_cacheTag = self::CACHE_TAG;
protected $_eventPrefix = self::CACHE_TAG;
protected function _construct(): void
{
$this->_init(\Esun\ImageManager\Model\ResourceModel\Category::class);
}
public function getIdentities(): array
{
return [self::CACHE_TAG . '_' . (int) $this->getId()];
}
}
@@ -0,0 +1,25 @@
<?php
declare(strict_types=1);
namespace Esun\ImageManager\Model;
use Magento\Framework\Model\AbstractModel;
use Magento\Framework\DataObject\IdentityInterface;
class Image extends AbstractModel implements IdentityInterface
{
public const CACHE_TAG = 'esun_image';
protected $_cacheTag = self::CACHE_TAG;
protected $_eventPrefix = self::CACHE_TAG;
protected function _construct(): void
{
$this->_init(\Esun\ImageManager\Model\ResourceModel\Image::class);
}
public function getIdentities(): array
{
return [self::CACHE_TAG . '_' . (int) $this->getId()];
}
}
@@ -0,0 +1,96 @@
<?php
declare(strict_types=1);
namespace Esun\ImageManager\Model;
use Esun\ImageManager\Model\ResourceModel\Category\CollectionFactory as CategoryCollectionFactory;
use Esun\ImageManager\Model\ResourceModel\Image\CollectionFactory as ImageCollectionFactory;
use Magento\Framework\UrlInterface;
use Magento\Store\Model\StoreManagerInterface;
class ImageProvider
{
public function __construct(
private readonly CategoryCollectionFactory $categoryCollectionFactory,
private readonly ImageCollectionFactory $imageCollectionFactory,
private readonly StoreManagerInterface $storeManager
) {
}
public function getCategory(string $identifier): ?Category
{
$category = $this->categoryCollectionFactory->create()
->addFieldToFilter('identifier', trim($identifier))
->addFieldToFilter('status', 1)
->setPageSize(1)
->getFirstItem();
return $category->getId() ? $category : null;
}
public function getCategoryById(int $categoryId): ?Category
{
if ($categoryId <= 0) {
return null;
}
$category = $this->categoryCollectionFactory->create()
->addFieldToFilter('category_id', $categoryId)
->addFieldToFilter('status', 1)
->setPageSize(1)
->getFirstItem();
return $category->getId() ? $category : null;
}
/**
* @return array<int, array<string, int|string>>
*/
public function getImages(string $categoryIdentifier): array
{
$category = $this->getCategory($categoryIdentifier);
return $category ? $this->getImagesByCategoryId((int) $category->getId()) : [];
}
/**
* @return array<int, array<string, int|string>>
*/
public function getImagesByCategoryId(int $categoryId): array
{
$category = $this->getCategoryById($categoryId);
if (!$category) {
return [];
}
$collection = $this->imageCollectionFactory->create();
$collection->addFieldToFilter('main_table.category_id', (int) $category->getId());
$collection->addFieldToFilter('main_table.status', 1);
$collection->setOrder('main_table.sort_order', 'ASC');
$collection->setOrder('main_table.image_id', 'ASC');
$items = [];
foreach ($collection as $image) {
$items[] = [
'id' => (int) $image->getId(),
'title' => (string) $image->getData('title'),
'description' => (string) $image->getData('description'),
'thumbnail_url' => $this->getMediaUrl((string) $image->getData('thumbnail_path')),
'image_url' => $this->getMediaUrl((string) $image->getData('image_path')),
'icon_url' => $this->getMediaUrl((string) $image->getData('icon_path')),
'link_url' => (string) $image->getData('link_url'),
'sort_order' => (int) $image->getData('sort_order'),
];
}
return $items;
}
private function getMediaUrl(string $path): string
{
if ($path === '') {
return '';
}
return $this->storeManager->getStore()->getBaseUrl(UrlInterface::URL_TYPE_MEDIA)
. ltrim($path, '/');
}
}
@@ -0,0 +1,199 @@
<?php
declare(strict_types=1);
namespace Esun\ImageManager\Model;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\App\Request\Http;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Filesystem;
use Magento\MediaStorage\Model\File\UploaderFactory;
class MediaUploader
{
private const MEDIA_DIRECTORY = 'esun/image-manager';
private const PNG_SIGNATURE = "\x89PNG\r\n\x1a\n";
private const PNG_TEXT_CHUNKS = ['iTXt', 'tEXt', 'zTXt'];
public function __construct(
private readonly UploaderFactory $uploaderFactory,
private readonly Filesystem $filesystem,
private readonly Http $request
) {
}
public function save(string $field): ?string
{
$file = $this->request->getFiles($field);
if (!is_array($file)
|| empty($file['tmp_name'])
|| (int) ($file['error'] ?? UPLOAD_ERR_NO_FILE) === UPLOAD_ERR_NO_FILE
) {
return null;
}
if ((int) ($file['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
throw new LocalizedException(__('The %1 image could not be uploaded.', $field));
}
$this->sanitizePngUpload((string) $file['tmp_name']);
$relativeDirectory = self::MEDIA_DIRECTORY . '/' . $field . '/' . date('Y/m');
$media = $this->filesystem->getDirectoryWrite(DirectoryList::MEDIA);
$media->create($relativeDirectory);
$uploader = $this->uploaderFactory->create(['fileId' => $field]);
$uploader->setAllowedExtensions(['jpg', 'jpeg', 'png', 'gif', 'webp']);
$uploader->setAllowRenameFiles(true);
$uploader->setFilesDispersion(true);
$saved = $uploader->save($media->getAbsolutePath($relativeDirectory));
if (!is_array($saved) || empty($saved['file'])) {
throw new LocalizedException(__('Unable to save the %1 image.', $field));
}
return trim($relativeDirectory . '/' . ltrim((string) $saved['file'], '/'), '/');
}
/**
* Strip optional PNG text chunks before Magento asks GD to validate the image.
*
* Some image exporters embed multi-megabyte iTXt payloads in tiny icons.
* libpng versions with stricter chunk limits reject those files before GD can
* inspect the actual pixels. Text chunks do not affect image rendering, so
* rebuilding the PNG without them keeps the original image and CRC-protected
* critical chunks intact while avoiding environment-dependent validation.
*/
public function sanitizePngUpload(string $path): void
{
if ($path === '' || !is_file($path)) {
return;
}
$source = @fopen($path, 'rb');
if ($source === false) {
return;
}
$signature = fread($source, 8);
if ($signature !== self::PNG_SIGNATURE) {
fclose($source);
return;
}
$temporary = tempnam(dirname($path), 'esun-png-');
if ($temporary === false) {
fclose($source);
throw new LocalizedException(__('Unable to prepare the PNG image for validation.'));
}
$target = @fopen($temporary, 'wb');
if ($target === false) {
fclose($source);
@unlink($temporary);
throw new LocalizedException(__('Unable to prepare the PNG image for validation.'));
}
$removedText = false;
$hasHeader = false;
$hasImageData = false;
$hasEnd = false;
try {
$this->writeAll($target, self::PNG_SIGNATURE);
while (!feof($source)) {
$header = fread($source, 8);
if ($header === '') {
break;
}
if (strlen($header) !== 8) {
throw new LocalizedException(__('The uploaded PNG image is incomplete.'));
}
$chunk = unpack('Nlength/a4type', $header);
$length = (int) ($chunk['length'] ?? -1);
$type = (string) ($chunk['type'] ?? '');
if ($length < 0 || !preg_match('/^[A-Za-z]{4}$/', $type)) {
throw new LocalizedException(__('The uploaded PNG image has an invalid chunk.'));
}
$skip = in_array($type, self::PNG_TEXT_CHUNKS, true);
if ($skip) {
$this->copyBytes($source, null, $length + 4);
$removedText = true;
} else {
$this->writeAll($target, $header);
$this->copyBytes($source, $target, $length + 4);
}
$hasHeader = $hasHeader || $type === 'IHDR';
$hasImageData = $hasImageData || $type === 'IDAT';
if ($type === 'IEND') {
$hasEnd = true;
break;
}
}
if (!$hasHeader || !$hasImageData || !$hasEnd) {
throw new LocalizedException(__('The uploaded PNG image is incomplete.'));
}
fclose($source);
$source = null;
fflush($target);
fclose($target);
$target = null;
if ($removedText && !@copy($temporary, $path)) {
throw new LocalizedException(__('Unable to prepare the PNG image for validation.'));
}
} finally {
if (is_resource($source)) {
fclose($source);
}
if (is_resource($target)) {
fclose($target);
}
@unlink($temporary);
}
}
/** @param resource $source @param resource|null $target */
private function copyBytes($source, $target, int $remaining): void
{
while ($remaining > 0) {
$data = fread($source, min(8192, $remaining));
if ($data === false || $data === '') {
throw new LocalizedException(__('The uploaded PNG image is incomplete.'));
}
if ($target !== null) {
$this->writeAll($target, $data);
}
$remaining -= strlen($data);
}
}
/** @param resource $target */
private function writeAll($target, string $data): void
{
$offset = 0;
$length = strlen($data);
while ($offset < $length) {
$written = fwrite($target, substr($data, $offset));
if ($written === false || $written === 0) {
throw new LocalizedException(__('Unable to prepare the PNG image for validation.'));
}
$offset += $written;
}
}
public function delete(string $path): void
{
$path = ltrim($path, '/');
if ($path === '' || !str_starts_with($path, self::MEDIA_DIRECTORY . '/')) {
return;
}
$media = $this->filesystem->getDirectoryWrite(DirectoryList::MEDIA);
if ($media->isExist($path)) {
$media->delete($path);
}
}
}
@@ -0,0 +1,14 @@
<?php
declare(strict_types=1);
namespace Esun\ImageManager\Model\ResourceModel;
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
class Category extends AbstractDb
{
protected function _construct(): void
{
$this->_init('esun_image_category', 'category_id');
}
}
@@ -0,0 +1,16 @@
<?php
declare(strict_types=1);
namespace Esun\ImageManager\Model\ResourceModel\Category;
use Esun\ImageManager\Model\Category;
use Esun\ImageManager\Model\ResourceModel\Category as CategoryResource;
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
class Collection extends AbstractCollection
{
protected function _construct(): void
{
$this->_init(Category::class, CategoryResource::class);
}
}
@@ -0,0 +1,14 @@
<?php
declare(strict_types=1);
namespace Esun\ImageManager\Model\ResourceModel;
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
class Image extends AbstractDb
{
protected function _construct(): void
{
$this->_init('esun_image', 'image_id');
}
}
@@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
namespace Esun\ImageManager\Model\ResourceModel\Image;
use Esun\ImageManager\Model\Image;
use Esun\ImageManager\Model\ResourceModel\Image as ImageResource;
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
class Collection extends AbstractCollection
{
protected function _construct(): void
{
$this->_init(Image::class, ImageResource::class);
}
protected function _initSelect()
{
parent::_initSelect();
$this->getSelect()->joinLeft(
['category' => $this->getTable('esun_image_category')],
'main_table.category_id = category.category_id',
['category_name' => 'name']
);
$this->addFilterToMap('image_id', 'main_table.image_id');
$this->addFilterToMap('title', 'main_table.title');
$this->addFilterToMap('category_id', 'main_table.category_id');
$this->addFilterToMap('category_name', 'category.name');
$this->addFilterToMap('status', 'main_table.status');
$this->addFilterToMap('sort_order', 'main_table.sort_order');
$this->addFilterToMap('created_at', 'main_table.created_at');
$this->addFilterToMap('updated_at', 'main_table.updated_at');
return $this;
}
}
@@ -0,0 +1,30 @@
<?php
declare(strict_types=1);
namespace Esun\ImageManager\Model\Source;
use Esun\ImageManager\Model\ResourceModel\Category\CollectionFactory;
use Magento\Framework\Data\OptionSourceInterface;
class CategoryOptions implements OptionSourceInterface
{
public function __construct(private readonly CollectionFactory $collectionFactory)
{
}
public function toOptionArray(): array
{
$options = [];
$collection = $this->collectionFactory->create()
->setOrder('sort_order', 'ASC')
->setOrder('name', 'ASC');
foreach ($collection as $category) {
$options[] = [
'value' => (int) $category->getId(),
'label' => (string) $category->getData('name'),
];
}
return $options;
}
}
@@ -0,0 +1,17 @@
<?php
declare(strict_types=1);
namespace Esun\ImageManager\Model\Source;
use Magento\Framework\Data\OptionSourceInterface;
class StatusOptions implements OptionSourceInterface
{
public function toOptionArray(): array
{
return [
['value' => 1, 'label' => __('Enabled')],
['value' => 0, 'label' => __('Disabled')],
];
}
}
@@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
namespace Esun\ImageManager\Plugin\MediaGallery;
use Esun\ImageManager\Model\MediaUploader;
use Magento\Framework\App\Request\Http;
use Magento\MediaGalleryUi\Model\UploadImage;
class SanitizePngUploadPlugin
{
public function __construct(
private readonly Http $request,
private readonly MediaUploader $mediaUploader
) {
}
/**
* Sanitize the temporary file before Magento Media Gallery creates its
* uploader and invokes the environment-specific GD/libpng validator.
*
* @return array{0: string, 1: string}
*/
public function beforeExecute(UploadImage $subject, string $targetFolder, string $type): array
{
$file = $this->request->getFiles('image');
if (is_array($file)
&& !empty($file['tmp_name'])
&& (int) ($file['error'] ?? UPLOAD_ERR_NO_FILE) === UPLOAD_ERR_OK
) {
$this->mediaUploader->sanitizePngUpload((string) $file['tmp_name']);
}
return [$targetFolder, $type];
}
}
@@ -0,0 +1,53 @@
<?php
declare(strict_types=1);
namespace Esun\ImageManager\Ui\Component\Listing\Column;
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,
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['image_id'])) {
continue;
}
$id = (int) $item['image_id'];
$title = (string) ($item['title'] ?? '');
$item[$fieldName]['edit'] = [
'href' => $this->urlBuilder->getUrl('esun_image_manager/image/edit', ['id' => $id]),
'label' => __('Edit'),
];
$item[$fieldName]['delete'] = [
'href' => $this->urlBuilder->getUrl('esun_image_manager/image/delete', ['id' => $id]),
'label' => __('Delete'),
'confirm' => [
'title' => __('Delete %1', $title),
'message' => __('Are you sure you want to delete this image?'),
],
];
}
return $dataSource;
}
}
@@ -0,0 +1,51 @@
<?php
declare(strict_types=1);
namespace Esun\ImageManager\Ui\Component\Listing\Column;
use Magento\Framework\UrlInterface;
use Magento\Framework\View\Element\UiComponent\ContextInterface;
use Magento\Framework\View\Element\UiComponentFactory;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Ui\Component\Listing\Columns\Column;
class Thumbnail extends Column
{
public function __construct(
ContextInterface $context,
UiComponentFactory $uiComponentFactory,
private readonly StoreManagerInterface $storeManager,
private readonly UrlInterface $urlBuilder,
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');
$mediaBaseUrl = $this->storeManager->getStore()->getBaseUrl(UrlInterface::URL_TYPE_MEDIA);
foreach ($dataSource['data']['items'] as &$item) {
$path = (string) ($item['thumbnail_path'] ?: $item['image_path'] ?: $item['icon_path']);
if ($path === '') {
continue;
}
$url = $mediaBaseUrl . ltrim($path, '/');
$item[$fieldName . '_src'] = $url;
$item[$fieldName . '_orig_src'] = $url;
$item[$fieldName . '_alt'] = (string) ($item['title'] ?? '');
$item[$fieldName . '_link'] = $this->urlBuilder->getUrl(
'esun_image_manager/image/edit',
['id' => (int) $item['image_id']]
);
}
return $dataSource;
}
}
@@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
namespace Esun\ImageManager\Ui\DataProvider\Image;
use Esun\ImageManager\Model\ResourceModel\Image\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 addFilter(Filter $filter): void
{
if ($filter->getField() !== 'fulltext') {
parent::addFilter($filter);
return;
}
$connection = $this->collection->getConnection();
$value = '%' . (string) $filter->getValue() . '%';
$this->collection->getSelect()->where(
$connection->quoteInto('main_table.title LIKE ?', $value)
. ' OR '
. $connection->quoteInto('category.name LIKE ?', $value)
);
}
}
+22
View File
@@ -0,0 +1,22 @@
<?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_Catalog::catalog">
<resource id="Esun_ImageManager::root" title="Esun Image Manager" sortOrder="86">
<resource id="Esun_ImageManager::images" title="Manage Images" sortOrder="10">
<resource id="Esun_ImageManager::images_save" title="Save Images" sortOrder="10"/>
<resource id="Esun_ImageManager::images_delete" title="Delete Images" sortOrder="20"/>
</resource>
<resource id="Esun_ImageManager::categories" title="Manage Categories" sortOrder="20">
<resource id="Esun_ImageManager::categories_save" title="Save Categories" sortOrder="10"/>
<resource id="Esun_ImageManager::categories_delete" title="Delete Categories" sortOrder="20"/>
</resource>
</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:framework:ObjectManager/etc/config.xsd">
<type name="Magento\MediaGalleryUi\Model\UploadImage">
<plugin name="esun_image_manager_sanitize_png_upload"
type="Esun\ImageManager\Plugin\MediaGallery\SanitizePngUploadPlugin"
sortOrder="10"/>
</type>
</config>
@@ -0,0 +1,17 @@
<?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_ImageManager::esun" title="Esun" module="Esun_ImageManager"
sortOrder="31" resource="Magento_Backend::admin"/>
<add id="Esun_ImageManager::root" title="Image Manager" module="Esun_ImageManager"
sortOrder="10" parent="Esun_ImageManager::esun"
resource="Esun_ImageManager::root"/>
<add id="Esun_ImageManager::images" title="Images" module="Esun_ImageManager"
sortOrder="10" parent="Esun_ImageManager::root"
action="esun_image_manager/image/index" resource="Esun_ImageManager::images"/>
<add id="Esun_ImageManager::categories" title="Categories" module="Esun_ImageManager"
sortOrder="20" parent="Esun_ImageManager::root"
action="esun_image_manager/category/index" resource="Esun_ImageManager::categories"/>
</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_image_manager" frontName="esun_image_manager">
<module name="Esun_ImageManager" before="Magento_Backend"/>
</route>
</router>
</config>
@@ -0,0 +1,53 @@
<?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_image_category" resource="default" engine="innodb" comment="Esun Image Categories">
<column xsi:type="int" name="category_id" unsigned="true" nullable="false" identity="true" comment="Category ID"/>
<column xsi:type="varchar" name="name" nullable="false" length="255" comment="Name"/>
<column xsi:type="varchar" name="identifier" nullable="false" length="128" comment="Identifier"/>
<column xsi:type="text" name="description" nullable="true" comment="Description"/>
<column xsi:type="smallint" name="status" unsigned="true" nullable="false" default="1" comment="Status"/>
<column xsi:type="int" name="sort_order" unsigned="false" nullable="false" default="0" comment="Sort Order"/>
<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="category_id"/>
</constraint>
<constraint xsi:type="unique" referenceId="ESUN_IMAGE_CATEGORY_IDENTIFIER">
<column name="identifier"/>
</constraint>
<index referenceId="ESUN_IMAGE_CATEGORY_STATUS_SORT" indexType="btree">
<column name="status"/>
<column name="sort_order"/>
</index>
</table>
<table name="esun_image" resource="default" engine="innodb" comment="Esun Managed Images">
<column xsi:type="int" name="image_id" unsigned="true" nullable="false" identity="true" comment="Image ID"/>
<column xsi:type="int" name="category_id" unsigned="true" nullable="false" comment="Category ID"/>
<column xsi:type="varchar" name="title" nullable="false" length="255" comment="Title"/>
<column xsi:type="text" name="description" nullable="true" comment="Description"/>
<column xsi:type="varchar" name="thumbnail_path" nullable="true" length="1024" comment="Thumbnail Path"/>
<column xsi:type="varchar" name="image_path" nullable="true" length="1024" comment="Image Path"/>
<column xsi:type="varchar" name="icon_path" nullable="true" length="1024" comment="Icon Path"/>
<column xsi:type="varchar" name="link_url" nullable="true" length="1024" comment="Link URL"/>
<column xsi:type="smallint" name="status" unsigned="true" nullable="false" default="1" comment="Status"/>
<column xsi:type="int" name="sort_order" unsigned="false" nullable="false" default="0" comment="Sort Order"/>
<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="image_id"/>
</constraint>
<constraint xsi:type="foreign" referenceId="ESUN_IMAGE_CATEGORY_ID_ESUN_IMAGE_CATEGORY_CATEGORY_ID"
table="esun_image" column="category_id"
referenceTable="esun_image_category" referenceColumn="category_id"
onDelete="NO ACTION"/>
<index referenceId="ESUN_IMAGE_CATEGORY_STATUS_SORT" indexType="btree">
<column name="category_id"/>
<column name="status"/>
<column name="sort_order"/>
</index>
</table>
</schema>
@@ -0,0 +1,44 @@
{
"esun_image_category": {
"column": {
"category_id": true,
"name": true,
"identifier": true,
"description": true,
"status": true,
"sort_order": true,
"created_at": true,
"updated_at": true
},
"constraint": {
"PRIMARY": true,
"ESUN_IMAGE_CATEGORY_IDENTIFIER": true
},
"index": {
"ESUN_IMAGE_CATEGORY_STATUS_SORT": true
}
},
"esun_image": {
"column": {
"image_id": true,
"category_id": true,
"title": true,
"description": true,
"thumbnail_path": true,
"image_path": true,
"icon_path": true,
"link_url": true,
"status": true,
"sort_order": true,
"created_at": true,
"updated_at": true
},
"constraint": {
"PRIMARY": true,
"ESUN_IMAGE_CATEGORY_ID_ESUN_IMAGE_CATEGORY_CATEGORY_ID": true
},
"index": {
"ESUN_IMAGE_CATEGORY_STATUS_SORT": true
}
}
}
+11
View File
@@ -0,0 +1,11 @@
<?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_ImageManager">
<sequence>
<module name="Magento_Backend"/>
<module name="Magento_MediaStorage"/>
<module name="Magento_MediaGalleryUi"/>
</sequence>
</module>
</config>
@@ -0,0 +1,8 @@
<?php
use Magento\Framework\Component\ComponentRegistrar;
ComponentRegistrar::register(
ComponentRegistrar::MODULE,
'Esun_ImageManager',
__DIR__
);
@@ -0,0 +1,11 @@
<?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\ImageManager\Block\Adminhtml\Category\EditBlock"
name="esun.image.manager.category.edit"
template="Esun_ImageManager::category/edit.phtml"/>
</referenceContainer>
</body>
</page>
@@ -0,0 +1,11 @@
<?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\ImageManager\Block\Adminhtml\Category\ListBlock"
name="esun.image.manager.category.list"
template="Esun_ImageManager::category/list.phtml"/>
</referenceContainer>
</body>
</page>
@@ -0,0 +1,5 @@
<?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">
<update handle="esun_image_manager_category_edit"/>
</page>
@@ -0,0 +1,11 @@
<?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\ImageManager\Block\Adminhtml\Image\EditBlock"
name="esun.image.manager.image.edit"
template="Esun_ImageManager::image/edit.phtml"/>
</referenceContainer>
</body>
</page>
@@ -0,0 +1,9 @@
<?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">
<uiComponent name="esun_image_listing"/>
</referenceContainer>
</body>
</page>
@@ -0,0 +1,5 @@
<?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">
<update handle="esun_image_manager_image_edit"/>
</page>
@@ -0,0 +1,51 @@
<?php
/** @var \Esun\ImageManager\Block\Adminhtml\Category\EditBlock $block */
$category = $block->getCategory();
?>
<form method="post" action="<?= $block->escapeUrl($block->getSaveUrl()) ?>">
<?= $block->getBlockHtml('formkey') ?>
<input type="hidden" name="category_id" value="<?= (int) $category->getId() ?>">
<div class="page-main-actions"><div class="page-actions">
<a class="action-secondary" href="<?= $block->escapeUrl($block->getBackUrl()) ?>">
<span><?= $block->escapeHtml(__('Back')) ?></span>
</a>
<button class="action-primary" type="submit"><span><?= $block->escapeHtml(__('Save Category')) ?></span></button>
</div></div>
<fieldset class="admin__fieldset">
<div class="admin__field _required">
<label class="admin__field-label"><span><?= $block->escapeHtml(__('Name')) ?></span></label>
<div class="admin__field-control">
<input class="admin__control-text" type="text" name="name" required
value="<?= $block->escapeHtmlAttr((string) $category->getData('name')) ?>">
</div>
</div>
<div class="admin__field _required">
<label class="admin__field-label"><span><?= $block->escapeHtml(__('Identifier')) ?></span></label>
<div class="admin__field-control">
<input class="admin__control-text" type="text" name="identifier" required
value="<?= $block->escapeHtmlAttr((string) $category->getData('identifier')) ?>">
<p class="note"><?= $block->escapeHtml(__('Used by homepage blocks, for example: application.')) ?></p>
</div>
</div>
<div class="admin__field">
<label class="admin__field-label"><span><?= $block->escapeHtml(__('Description')) ?></span></label>
<div class="admin__field-control">
<textarea class="admin__control-textarea" name="description" rows="5"><?= $block->escapeHtml((string) $category->getData('description')) ?></textarea>
</div>
</div>
<div class="admin__field">
<label class="admin__field-label"><span><?= $block->escapeHtml(__('Status')) ?></span></label>
<div class="admin__field-control"><select class="admin__control-select" name="status">
<option value="1" <?= !$category->getId() || (int) $category->getData('status') === 1 ? 'selected' : '' ?>><?= $block->escapeHtml(__('Enabled')) ?></option>
<option value="0" <?= $category->getId() && (int) $category->getData('status') === 0 ? 'selected' : '' ?>><?= $block->escapeHtml(__('Disabled')) ?></option>
</select></div>
</div>
<div class="admin__field">
<label class="admin__field-label"><span><?= $block->escapeHtml(__('Sort Order')) ?></span></label>
<div class="admin__field-control">
<input class="admin__control-text" type="number" name="sort_order"
value="<?= (int) $category->getData('sort_order') ?>">
</div>
</div>
</fieldset>
</form>
@@ -0,0 +1,64 @@
<?php /** @var \Esun\ImageManager\Block\Adminhtml\Category\ListBlock $block */ ?>
<div class="page-main-actions">
<div class="page-actions">
<a class="action-primary" href="<?= $block->escapeUrl($block->getNewUrl()) ?>">
<span><?= $block->escapeHtml(__('Add Category')) ?></span>
</a>
</div>
</div>
<form method="get" action="<?= $block->escapeUrl($block->getIndexUrl()) ?>"
style="display:flex;gap:1rem;align-items:flex-end;margin-bottom:2rem">
<div class="admin__field" style="margin:0;min-width:32rem">
<label class="admin__field-label" style="float:none;width:auto;text-align:left">
<span><?= $block->escapeHtml(__('Name or Identifier')) ?></span>
</label>
<div class="admin__field-control" style="float:none;width:auto">
<input class="admin__control-text" type="text" name="query"
value="<?= $block->escapeHtmlAttr($block->getQueryFilter()) ?>">
</div>
</div>
<button class="action-secondary" type="submit"><span><?= $block->escapeHtml(__('Filter')) ?></span></button>
<a class="action-secondary" href="<?= $block->escapeUrl($block->getIndexUrl()) ?>">
<span><?= $block->escapeHtml(__('Reset')) ?></span>
</a>
</form>
<div class="admin__data-grid-wrap">
<table class="data-grid">
<thead><tr>
<th class="data-grid-th"><?= $block->escapeHtml(__('ID')) ?></th>
<th class="data-grid-th"><?= $block->escapeHtml(__('Name')) ?></th>
<th class="data-grid-th"><?= $block->escapeHtml(__('Identifier')) ?></th>
<th class="data-grid-th"><?= $block->escapeHtml(__('Status')) ?></th>
<th class="data-grid-th"><?= $block->escapeHtml(__('Sort Order')) ?></th>
<th class="data-grid-th"><?= $block->escapeHtml(__('Updated')) ?></th>
<th class="data-grid-th"><?= $block->escapeHtml(__('Action')) ?></th>
</tr></thead>
<tbody>
<?php if ($block->getCategories()->getSize() === 0): ?>
<tr><td colspan="7" class="empty-text"><?= $block->escapeHtml(__('No categories found.')) ?></td></tr>
<?php endif; ?>
<?php foreach ($block->getCategories() as $category): ?>
<tr>
<td><?= (int) $category->getId() ?></td>
<td><?= $block->escapeHtml($category->getData('name')) ?></td>
<td><code><?= $block->escapeHtml($category->getData('identifier')) ?></code></td>
<td><?= $category->getData('status') ? $block->escapeHtml(__('Enabled')) : $block->escapeHtml(__('Disabled')) ?></td>
<td><?= (int) $category->getData('sort_order') ?></td>
<td><?= $block->escapeHtml($category->getData('updated_at')) ?></td>
<td>
<a href="<?= $block->escapeUrl($block->getEditUrl((int) $category->getId())) ?>">
<?= $block->escapeHtml(__('Edit')) ?>
</a>
<span aria-hidden="true"> | </span>
<a href="<?= $block->escapeUrl($block->getDeleteUrl((int) $category->getId())) ?>"
onclick="return confirm('<?= $block->escapeJs(__('Delete this category?')) ?>')">
<?= $block->escapeHtml(__('Delete')) ?>
</a>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
@@ -0,0 +1,109 @@
<?php
/** @var \Esun\ImageManager\Block\Adminhtml\Image\EditBlock $block */
$image = $block->getImageModel();
?>
<form method="post" action="<?= $block->escapeUrl($block->getSaveUrl()) ?>" enctype="multipart/form-data">
<?= $block->getBlockHtml('formkey') ?>
<input type="hidden" name="image_id" value="<?= (int) $image->getId() ?>">
<div class="page-main-actions"><div class="page-actions">
<a class="action-secondary" href="<?= $block->escapeUrl($block->getBackUrl()) ?>">
<span><?= $block->escapeHtml(__('Back')) ?></span>
</a>
<button class="action-primary" type="submit"><span><?= $block->escapeHtml(__('Save Image')) ?></span></button>
</div></div>
<fieldset class="admin__fieldset">
<div class="admin__field _required">
<label class="admin__field-label"><span><?= $block->escapeHtml(__('Title')) ?></span></label>
<div class="admin__field-control">
<input class="admin__control-text" type="text" name="title" required
value="<?= $block->escapeHtmlAttr((string) $image->getData('title')) ?>">
</div>
</div>
<div class="admin__field _required">
<label class="admin__field-label"><span><?= $block->escapeHtml(__('Category')) ?></span></label>
<div class="admin__field-control">
<select class="admin__control-select" name="category_id" required>
<option value=""><?= $block->escapeHtml(__('Please select')) ?></option>
<?php foreach ($block->getCategories() as $category): ?>
<option value="<?= (int) $category->getId() ?>"
<?= (int) $image->getData('category_id') === (int) $category->getId() ? 'selected' : '' ?>>
<?= $block->escapeHtml($category->getData('name')) ?>
</option>
<?php endforeach; ?>
</select>
<p class="note">
<a href="<?= $block->escapeUrl($block->getCategoryUrl()) ?>" target="_blank">
<?= $block->escapeHtml(__('Create a new category')) ?>
</a>
</p>
</div>
</div>
<div class="admin__field">
<label class="admin__field-label"><span><?= $block->escapeHtml(__('Description')) ?></span></label>
<div class="admin__field-control">
<textarea class="admin__control-textarea" name="description" rows="6"><?= $block->escapeHtml((string) $image->getData('description')) ?></textarea>
</div>
</div>
<?php foreach (['thumbnail' => __('Thumbnail'), 'image' => __('Image'), 'icon' => __('Icon')] as $field => $label): ?>
<?php $path = (string) $image->getData($field . '_path'); ?>
<div class="admin__field">
<label class="admin__field-label"><span><?= $block->escapeHtml($label) ?></span></label>
<div class="admin__field-control">
<?php if ($path): ?>
<div style="margin-bottom:1.5rem">
<strong style="display:block;margin-bottom:.8rem">
<?= $block->escapeHtml(__('Current %1', $label)) ?>
</strong>
<a href="<?= $block->escapeUrl($block->getMediaUrl($path)) ?>"
target="_blank"
rel="noopener">
<img src="<?= $block->escapeUrl($block->getMediaUrl($path)) ?>"
alt="<?= $block->escapeHtmlAttr(__('Current %1', $label)) ?>"
style="display:block;max-width:32rem;max-height:20rem;margin-bottom:1rem;border:1px solid #d6d6d6;background:#fff;padding:.5rem">
</a>
<code style="display:block;margin-bottom:.8rem">
<?= $block->escapeHtml($path) ?>
</code>
<label>
<input type="checkbox"
name="delete_<?= $block->escapeHtmlAttr($field) ?>"
value="1">
<?= $block->escapeHtml(__('Delete current file')) ?>
</label>
</div>
<?php elseif ($image->getId()): ?>
<p class="note" style="margin-bottom:1rem">
<?= $block->escapeHtml(__('No current %1 has been uploaded.', $label)) ?>
</p>
<?php endif; ?>
<input type="file" name="<?= $block->escapeHtmlAttr($field) ?>"
accept="image/jpeg,image/png,image/gif,image/webp">
<p class="note"><?= $block->escapeHtml(__('Allowed: JPG, PNG, GIF and WebP.')) ?></p>
</div>
</div>
<?php endforeach; ?>
<div class="admin__field">
<label class="admin__field-label"><span><?= $block->escapeHtml(__('Link URL')) ?></span></label>
<div class="admin__field-control">
<input class="admin__control-text" type="text" name="link_url"
value="<?= $block->escapeHtmlAttr((string) $image->getData('link_url')) ?>">
</div>
</div>
<div class="admin__field">
<label class="admin__field-label"><span><?= $block->escapeHtml(__('Status')) ?></span></label>
<div class="admin__field-control"><select class="admin__control-select" name="status">
<option value="1" <?= !$image->getId() || (int) $image->getData('status') === 1 ? 'selected' : '' ?>><?= $block->escapeHtml(__('Enabled')) ?></option>
<option value="0" <?= $image->getId() && (int) $image->getData('status') === 0 ? 'selected' : '' ?>><?= $block->escapeHtml(__('Disabled')) ?></option>
</select></div>
</div>
<div class="admin__field">
<label class="admin__field-label"><span><?= $block->escapeHtml(__('Sort Order')) ?></span></label>
<div class="admin__field-control">
<input class="admin__control-text" type="number" name="sort_order"
value="<?= (int) $image->getData('sort_order') ?>">
</div>
</div>
</fieldset>
</form>
@@ -0,0 +1,117 @@
<?xml version="1.0" encoding="UTF-8"?>
<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_image_listing.esun_image_listing_data_source</item>
</item>
</argument>
<settings>
<buttons>
<button name="add">
<url path="esun_image_manager/image/new"/>
<class>primary</class>
<label translate="true">Add Image</label>
</button>
</buttons>
<spinner>esun_image_columns</spinner>
<deps>
<dep>esun_image_listing.esun_image_listing_data_source</dep>
</deps>
</settings>
<dataSource name="esun_image_listing_data_source" component="Magento_Ui/js/grid/provider">
<settings>
<storageConfig>
<param name="indexField" xsi:type="string">image_id</param>
</storageConfig>
<updateUrl path="mui/index/render"/>
</settings>
<aclResource>Esun_ImageManager::images</aclResource>
<dataProvider class="Esun\ImageManager\Ui\DataProvider\Image\ListingDataProvider"
name="esun_image_listing_data_source">
<settings>
<requestFieldName>id</requestFieldName>
<primaryFieldName>image_id</primaryFieldName>
</settings>
</dataProvider>
</dataSource>
<listingToolbar name="listing_top">
<settings>
<sticky>true</sticky>
</settings>
<bookmark name="bookmarks"/>
<columnsControls name="columns_controls"/>
<filterSearch name="fulltext"/>
<filters name="listing_filters"/>
<paging name="listing_paging"/>
</listingToolbar>
<columns name="esun_image_columns">
<column name="image_id">
<settings>
<filter>textRange</filter>
<sorting>desc</sorting>
<label translate="true">ID</label>
</settings>
</column>
<column name="preview"
class="Esun\ImageManager\Ui\Component\Listing\Column\Thumbnail"
component="Magento_Ui/js/grid/columns/thumbnail">
<settings>
<altField>title</altField>
<hasPreview>1</hasPreview>
<label translate="true">Thumbnail</label>
<sortable>false</sortable>
<filter>false</filter>
</settings>
</column>
<column name="title">
<settings>
<filter>text</filter>
<label translate="true">Title</label>
</settings>
</column>
<column name="category_id" component="Magento_Ui/js/grid/columns/select">
<settings>
<options class="Esun\ImageManager\Model\Source\CategoryOptions"/>
<filter>select</filter>
<dataType>select</dataType>
<label translate="true">Category</label>
</settings>
</column>
<column name="status" component="Magento_Ui/js/grid/columns/select">
<settings>
<options class="Esun\ImageManager\Model\Source\StatusOptions"/>
<filter>select</filter>
<dataType>select</dataType>
<label translate="true">Status</label>
</settings>
</column>
<column name="sort_order">
<settings>
<filter>textRange</filter>
<dataType>number</dataType>
<label translate="true">Sort Order</label>
</settings>
</column>
<column name="updated_at"
class="Magento\Ui\Component\Listing\Columns\Date"
component="Magento_Ui/js/grid/columns/date">
<settings>
<filter>dateRange</filter>
<dataType>date</dataType>
<label translate="true">Updated</label>
</settings>
</column>
<actionsColumn name="actions"
class="Esun\ImageManager\Ui\Component\Listing\Column\Actions">
<settings>
<indexField>image_id</indexField>
<resizeEnabled>false</resizeEnabled>
<resizeDefaultWidth>110</resizeDefaultWidth>
</settings>
</actionsColumn>
</columns>
</listing>