ltsecurityinc安防产品在线商城代码

This commit is contained in:
2026-09-14 17:47:10 +08:00
parent 57d8444c15
commit 6a3c9c5bd8
14539 changed files with 1775310 additions and 0 deletions
+451
View File
@@ -0,0 +1,451 @@
<?php
/**
* @author Olegnax
* @package Olegnax_Core
* @copyright Copyright (c) 2023 Olegnax (http://olegnax.com/). All rights reserved.
* See COPYING.txt for license details.
*/
namespace Olegnax\Core\Helper;
use Exception;
use Magento\Catalog\Helper\Product\Compare;
use Magento\Cms\Model\Template\FilterProvider;
use Magento\Customer\Model\Session;
use Magento\Framework\App\Area;
use Magento\Framework\App\Cache\Frontend\Pool;
use Magento\Framework\App\Cache\TypeListInterface;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\Config\Storage\WriterInterface;
use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Framework\App\Helper\Context;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\App\ProductMetadataInterface;
use Magento\Framework\App\State;
use Magento\Framework\UrlInterface;
use Magento\Framework\View\DesignInterface;
use Magento\Store\Model\ScopeInterface;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Wishlist\Helper\Data;
use Olegnax\Core\Block\ChildTemplate;
use Psr\Log\LoggerInterface;
class Helper extends AbstractHelper
{
const XML_PATH_CORE_LAZY = 'olegnax_core_settings/general/lazyload';
const CONFIG_MODULE = 'olegnax_core_settings';
const CHILD_TEMPLATE = ChildTemplate::class;
/**
* @var ObjectManager
*/
protected $objectManager;
/**
* @var array
*/
protected $isArea = [];
/**
* @var LoggerInterface
*/
public $logger;
public function __construct(
Context $context,
LoggerInterface $logger
)
{
$this->logger = $logger;
parent::__construct($context);
if (!$this->getModuleConfig(
'general/install_date',
0,
ScopeConfigInterface::SCOPE_TYPE_DEFAULT
)
) {
$this->setModuleConfig('general/install_date', time());
}
}
/**
* @return bool
*/
public function isEnabled()
{
return true;
}
public function setModuleConfig(
$path,
$value,
$scope = ScopeConfigInterface::SCOPE_TYPE_DEFAULT,
$scopeId = 0
) {
if (!empty($path)) {
$path = static::CONFIG_MODULE . '/' . $path;
}
return $this->setSystemValue($path, $value, $scope, $scopeId);
}
public function setSystemValue($path, $value, $scope = ScopeConfigInterface::SCOPE_TYPE_DEFAULT, $scopeId = 0)
{
$result = $this->_loadObject(WriterInterface::class)->save($path, $value, $scope, $scopeId);
$this->scopeConfig->clean();
return $result;
}
public function deleteSystemValue($path, $scope = ScopeConfigInterface::SCOPE_TYPE_DEFAULT, $scopeId = 0)
{
$result = $this->_loadObject(WriterInterface::class)->delete($path, $scope, $scopeId);
$this->scopeConfig->clean();
return $result;
}
/**
* @param string $path
* @return mixed
*/
public function _loadObject($path)
{
return ObjectManager::getInstance()->get($path);
}
/**
* @return string
*/
public function getThemeCode()
{
/** @var DesignInterface $appState */
$appState = $this->_loadObject(DesignInterface::class);
return $appState->getDesignTheme()->getCode();
}
/**
* @return bool
*/
public function isMobileTheme()
{
return (bool) preg_match('@^Olegnax\/a2m@', $this->getThemeCode());
}
/**
* @return bool
*/
public function isLazyLoadEnabled(){
return (bool) $this->getSystemValue(static::XML_PATH_CORE_LAZY);
}
/**
* @param string $path
* @param integer $storeCode
* @param string $scopeType
* @return mixed
*/
public function getModuleConfig($path = '', $storeCode = null, $scopeType = ScopeInterface::SCOPE_STORE)
{
if (empty($path)) {
$path = static::CONFIG_MODULE;
} else {
$path = static::CONFIG_MODULE . '/' . $path;
}
return $this->getSystemValue($path, $storeCode, $scopeType);
}
/**
* @param string $path
* @param integer $storeCode
* @param string $scopeType
* @return mixed
*/
public function getSystemValue($path, $storeCode = null, $scopeType = ScopeInterface::SCOPE_STORE)
{
$value = $this->scopeConfig->getValue(
$path,
$scopeType,
$storeCode
);
if (is_null($value)) {
$value = '';
}
return $value;
}
/**
* @param string $path
* @return mixed
*/
public function getSystemDefaultValue($path)
{
return $this->getSystemValue(
$path,
0,
ScopeConfigInterface::SCOPE_TYPE_DEFAULT
);
}
/**
* @return bool
*/
public function isAdmin()
{
return $this->isArea(Area::AREA_ADMINHTML);
}
/**
* @param string $area
* @return bool
*/
public function isArea($area = Area::AREA_FRONTEND)
{
if (!isset($this->isArea[$area])) {
/** @var State $state */
$state = $this->_loadObject(State::class);
try {
$this->isArea[$area] = ($state->getAreaCode() == $area);
} catch ( Exception $e) {
$this->isArea[$area] = false;
}
}
return $this->isArea[$area];
}
/**
* @param string $path
* @param array $arguments
* @return mixed
*/
public function _createObject($path, $arguments = [])
{
return ObjectManager::getInstance()->create($path, $arguments);
}
public function getLayoutTemplateHtml($block, $option_path = '', $fileName = '', $arguments = [])
{
$value = $this->getSystemValue($option_path);
if (is_string($value) || is_numeric($value)) {
return $this->getLayoutTemplateHtmlbyValue($block, $value, $fileName, $arguments);
}
return '';
}
/**
* @param string $path
* @param integer $storeCode
* @return mixed
*/
public function getConfig($path, $storeCode = null)
{
return $this->getSystemValue($path, $storeCode);
}
public function getLayoutTemplateHtmlbyValue(
$block,
$value = null,
$fileName = null,
$arguments = [],
$separator = '/'
) {
$_fileName = '';
if (empty($fileName)) {
$blockTemplate = $block->getTemplate();
if (preg_match('/(\.[^\.]+?)$/', $blockTemplate)) {
$fileName = preg_replace('/(\.[^\.]+?)$/', '%s%s$1', $blockTemplate);
} else {
$fileName .= '%s%s';
}
if (!preg_match('#([^_\:])_([^_\:])\:\:#i', $fileName)) {
$className = array_slice(array_filter(explode('\\', get_class($block))), 0, 2);
if ('Magento' !== $className[0]) {
$fileName = implode('_', $className) . '::' . $fileName;
}
}
} else {
$_fileName = $fileName;
}
$blockName = $separator . $block->getNameInLayout() . $separator . $_fileName . $separator . $value;
$fileName = sprintf($fileName, $separator, $value);
while ($block->getLayout()->getBlock($blockName)) {
$blockName .= '_0';
}
$_block = $block->getLayout()->createBlock(static::CHILD_TEMPLATE, $blockName);
$block->setChild($_block->getNameInLayout(), $_block);
if (!empty($arguments) && is_array($arguments)) {
$_block->addData($arguments);
}
$content = $_block->setTemplate($fileName)->toHtml();
return $content;
}
public function isLoggedIn()
{
return $this->_loadObject(Session::class)->isLoggedIn();
}
public function getWishlistCount()
{
return $this->_loadObject(Data::class)->getItemCount();
}
/**
* Get Product version
*
* @return string
*/
function getVersion()
{
return $this->_loadObject(ProductMetadataInterface::class)->getVersion();
}
/**
* @param string $version
* @param string $operator
* @return bool
*/
function getVersionCompare($version, $operator = '<=')
{
return version_compare($this->getVersion(), $version, $operator);
}
/**
* @return bool
*/
public function isLegacyJQuery() {
return $this->getVersionCompare('2.3.2');
}
public function getCompareListUrl()
{
return $this->_loadObject(Compare::class)->getListUrl();
}
public function getCompareListCount()
{
return $this->_loadObject(Compare::class)->getItemCount();
}
public function getBaseUrl($type = UrlInterface::URL_TYPE_LINK, $secure = null)
{
return $this->getStore()->getBaseUrl($type, $secure);
}
public function getStore()
{
/** @var StoreManagerInterface $storeManager */
$storeManager = $this->_loadObject(StoreManagerInterface::class);
return $storeManager->getStore();
}
public function isMobile()
{
$regex_match = "/(nokia|iphone|android|motorola|^mot\-|softbank|foma|docomo|kddi|up\.browser|up\.link|"
. "htc|dopod|blazer|netfront|helio|hosin|huawei|novarra|CoolPad|webos|techfaith|palmsource|"
. "blackberry|alcatel|amoi|ktouch|nexian|samsung|^sam\-|s[cg]h|^lge|ericsson|philips|sagem|wellcom|bunjalloo|maui|"
. "symbian|smartphone|mmp|midp|wap|phone|windows ce|iemobile|^spice|^bird|^zte\-|longcos|pantech|gionee|^sie\-|portalmmm|"
. "jig\s browser|hiptop|^ucweb|^benq|haier|^lct|opera\s*mobi|opera\*mini|320x320|240x320|176x220"
. ")/i";
if (preg_match($regex_match, strtolower((string)$_SERVER['HTTP_USER_AGENT']))) {
return TRUE;
}
if ((strpos(strtolower((string)$_SERVER['HTTP_ACCEPT']),'application/vnd.wap.xhtml+xml') > 0) or ((isset($_SERVER['HTTP_X_WAP_PROFILE']) or isset($_SERVER['HTTP_PROFILE'])))) {
return TRUE;
}
$mobile_ua = strtolower(substr($_SERVER['HTTP_USER_AGENT'], 0, 4));
$mobile_agents = array(
'w3c ','acs-','alav','alca','amoi','audi','avan','benq','bird','blac',
'blaz','brew','cell','cldc','cmd-','dang','doco','eric','hipt','inno',
'ipaq','java','jigs','kddi','keji','leno','lg-c','lg-d','lg-g','lge-',
'maui','maxo','midp','mits','mmef','mobi','mot-','moto','mwbp','nec-',
'newt','noki','oper','palm','pana','pant','phil','play','port','prox',
'qwap','sage','sams','sany','sch-','sec-','send','seri','sgh-','shar',
'sie-','siem','smal','smar','sony','sph-','symb','t-mo','teli','tim-',
'tosh','tsm-','upg1','upsi','vk-v','voda','wap-','wapa','wapi','wapp',
'wapr','webc','winw','winw','xda ','xda-');
if (in_array($mobile_ua,$mobile_agents)) {
return TRUE;
}
if (isset($_SERVER['ALL_HTTP']) && strpos(strtolower((string)$_SERVER['ALL_HTTP']),'OperaMini') > 0) {
return TRUE;
}
return FALSE;
}
public function getBlockTemplateProcessor($content = '')
{
if (empty($content) || !is_string($content)) {
$content = '';
}
$blockFilter = $this->_loadObject(FilterProvider::class)->getBlockFilter();
return $blockFilter->filter(trim($content));
}
public function getUrl($route = '', $params = [])
{
/** @var UrlInterface $urlBuilder */
$urlBuilder = $this->_loadObject(UrlInterface::class);
return $urlBuilder->getUrl($route, $params);
}
public function isHomePage()
{
$currentUrl = $this->getUrl('', ['_current' => true]);
$urlRewrite = $this->getUrl('*/*/*', ['_current' => true, '_use_rewrite' => true]);
return $currentUrl == $urlRewrite;
}
public function clearCache()
{
/** @var TypeListInterface $cacheTypeList */
$cacheTypeList = $this->_loadObject(TypeListInterface::class);
$types = [
'config',
'layout',
'block_html',
'collections',
'reflection',
'db_ddl',
'eav',
'config_integration',
'config_integration_api',
'full_page',
'translate',
'config_webservice',
];
foreach ($types as $type) {
$cacheTypeList->cleanType($type);
}
/** @var Pool $CacheFrontendPool */
$CacheFrontendPool = $this->_loadObject(Pool::class);
foreach ($CacheFrontendPool as $cacheFrontend) {
$cacheFrontend->getBackend()->clean();
}
}
public function getLogger()
{
return $this->logger;
}
public function log($level, $plugin, $message, array $context = [])
{
$message = sprintf('%s: %s', $plugin, trim($message));
$this->getLogger()->log($level, $message, $context);
// $this->getLogger()->debug($message, $context);
}
public function debug($plugin, $message, array $context = [])
{
$this->log(100, $plugin, $message, $context);
}
}
+738
View File
@@ -0,0 +1,738 @@
<?php
/**
* Copyright © All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Olegnax\Core\Helper;
use Exception;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Framework\App\Helper\Context;
use Magento\Framework\App\State;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Filesystem;
use Magento\Framework\Filesystem\Directory\WriteInterface;
use Magento\Framework\Filesystem\Glob;
use Magento\Framework\Filesystem\Io\File;
use Magento\Framework\Image\AdapterFactory;
use Magento\Framework\Image\Factory;
use Magento\Framework\UrlInterface;
use Magento\Store\Model\StoreManagerInterface;
/**
* Description of Image
*
* @author Master
*/
class Image extends AbstractHelper
{
const BASE_TEMPLATE_FILE_NAME = '{dirname}/{destinationSubdir}/{filename}_{width}_{height}.{extension}';
protected $_baseFile;
/**
* @var int
*/
protected $_width;
/**
* @var int
*/
protected $_height;
/**
* Default quality value (for JPEG images only).
*
* @var int
*/
protected $_quality = 90;
/**
* @var bool
*/
protected $_keepAspectRatio = true;
/**
* @var bool
*/
protected $_keepFrame = true;
/**
* @var bool
*/
protected $_keepTransparency = true;
/**
* @var bool
*/
protected $_constrainOnly = true;
/**
* @var bool
*/
protected $_cropOnly = false;
protected $_resizeTemplate = '';
/**
* @var int[]
*/
protected $_backgroundColor = [255, 255, 255];
/**
* @var \Magento\Framework\Image
*/
protected $_processor;
/**
* @var string
*/
protected $_destinationSubdir;
/**
* @var WriteInterface
*/
protected $_mediaDirectory;
/**
* Store Manager
*
* @var StoreManagerInterface
*/
protected $_storeManager;
/**
* @var Factory
*/
protected $_imageFactory;
/**
* @var array
*/
protected $attributes;
/**
* @var File
*/
protected $_file;
protected $_appState;
/**
* @var AdapterFactory
*/
protected $adapterFactory;
/**
* @var string
*/
private $__file;
public function __construct(
Context $context,
Filesystem $filesystem,
Factory $imageFactory,
File $file,
State $appState,
StoreManagerInterface $storeManager,
AdapterFactory $adapterFactory
) {
$this->_mediaDirectory = $filesystem->getDirectoryRead(DirectoryList::MEDIA);
$this->_imageFactory = $imageFactory;
$this->_file = $file;
$this->_storeManager = $storeManager;
$this->_appState = $appState;
$this->adapterFactory = $adapterFactory;
parent::__construct($context);
}
/**
* @return bool
*/
public function checkDependencies() {
try {
$this->adapterFactory->create();
return true;
} catch (Exception $e) {
$this->_logger->critical($e->getMessage());
return false;
}
}
public function adaptiveResize($size, $fileTemplate = null)
{
if (!empty($fileTemplate)) {
$this->setFileTemplate($fileTemplate);
}
try {
[$width, $height] = $this->prepareSize($size);
$this->setWidth($width);
$this->setHeight($height);
if ($this->_keepAspectRatio && $this->_cropOnly) {
$this->crop();
}
$this->resize();
} catch (Exception $e) {
if (State::MODE_DEVELOPER == $this->_appState->getMode()) {
$this->_logger->warning("Olegnax Core. Can\'t resize image, skipping. The file does not exist or not accessible: " . $e,
[$this->_baseFile]);
}
}
return $this;
}
public function setFileTemplate($fileTemplate)
{
$this->_resizeTemplate = $fileTemplate;
return $this;
}
private function prepareSize($size)
{
if (is_array($size) && 1 >= count($size)) {
$size = array_shift($size);
}
if (!is_array($size)) {
$size = [$size, $size];
}
$size = array_map('intval', $size);
$size = array_map('abs', $size);
return $size;
}
public function crop()
{
if ($this->_width == 0 && $this->_height == 0 && !$this->getBaseFile()) {
return $this;
}
if ($this->_fileExists($this->getResizedFile())) {
return $this;
}
$_imageSrcWidth = $this->getImageProcessor()->getOriginalWidth();
$_imageSrcHeight = $this->getImageProcessor()->getOriginalHeight();
$_imageSrcRatio = $_imageSrcWidth / $_imageSrcHeight;
$_ratio = $this->_width / $this->_height;
if ($_imageSrcRatio != $_ratio) {
if (1 > $_imageSrcRatio) {
$newHeight = round($_imageSrcWidth / $_ratio);
$deltHeight = $_imageSrcHeight - $newHeight;
$_deltHeight = floor($deltHeight / 2);
$__deltHeight = $deltHeight % 2;
$this->getImageProcessor()->crop($_deltHeight + $__deltHeight, 0, 0, $_deltHeight);
} elseif (1 < $_imageSrcRatio) {
$newWidth = round($_imageSrcHeight * $_ratio);
$deltWidth = $_imageSrcWidth - $newWidth;
$_deltWidth = floor($deltWidth / 2);
$__deltWidth = $deltWidth % 2;
$this->getImageProcessor()->crop(0, $_deltWidth + $__deltWidth, $_deltWidth, 0);
}
}
return $this;
}
/**
* @return string
*/
public function getBaseFile()
{
return $this->_baseFile;
}
/**
* Set filenames for base file and new file
*
* @param string $file
*
* @return Image
*/
public function setBaseFile($file)
{
if ($this->_fileExists($file)) {
$this->_baseFile = $file;
} elseif (State::MODE_DEVELOPER == $this->_appState->getMode()) {
$this->_logger->warning(__('Olegnax Core. The file does not exist or not accessible: ') . $file);
}
return $this;
}
/**
* First check this file on FS
* If it doesn't exist - try to download it from DB
*
* @param string $filename
*
* @return bool
*/
protected function _fileExists($filename)
{
return $this->_file->fileExists($this->_mediaDirectory->getAbsolutePath($filename));
}
/**
* @return string
*/
private function getResizedFile()
{
$path_data = pathinfo($this->getBaseFile());
if (is_array($path_data) && !empty($path_data)) {
if (array_key_exists('extension', $path_data)) {
$filename = str_replace(
[
'{dirname}',
'{basename}',
'{extension}',
'{filename}',
'{width}',
'{height}',
'{originalWidth}',
'{originalHeight}',
'{destinationSubdir}',
'{keepFrame}',
'{constrainOnly}',
'{keepAspectRatio}',
'{crop}',
'{keepTransparency}',
'{quality}',
],
[
$path_data['dirname'],
$path_data['basename'],
$path_data['extension'],
$path_data['filename'],
$this->getWidth(),
$this->getHeight(),
$this->getOriginalWidth(),
$this->getOriginalHeight(),
$this->getDestinationSubdir(),
$this->getQuality(),
$this->_keepFrame,
$this->_constrainOnly,
$this->_keepAspectRatio,
$this->_cropOnly,
$this->_keepTransparency,
],
$this->_resizeTemplate
);
return $filename;
}
}
return '';
}
/**
* @return int
*/
public function getWidth()
{
return $this->_width ?: $this->getOriginalWidth();
}
/**
* @param int $width
*
* @return Image
*/
public function setWidth($width)
{
$this->_width = abs((int)$width);
return $this;
}
/**
* @return int|null
*/
public function getOriginalWidth()
{
return $this->getImageProcessor()->getOriginalWidth();
}
/**
* @return \Magento\Framework\Image
*/
public function getImageProcessor()
{
if (!$this->_processor) {
$filename = $this->getBaseFile() ? $this->_mediaDirectory->getAbsolutePath($this->getBaseFile()) : null;
$this->_processor = $this->_imageFactory->create($filename);
}
$this->_processor->keepAspectRatio($this->_keepAspectRatio);
$this->_processor->keepFrame($this->_keepFrame);
$this->_processor->keepTransparency($this->_keepTransparency);
$this->_processor->constrainOnly($this->_constrainOnly);
$this->_processor->backgroundColor($this->_backgroundColor);
$this->_processor->quality($this->_quality);
return $this->_processor;
}
/**
* @return int
*/
public function getHeight()
{
return $this->_height ?: $this->getOriginalHeight();
}
/**
* @param int $height
*
* @return $this
*/
public function setHeight($height)
{
$this->_height = abs((int)$height);
return $this;
}
/**
* @return int|null
*/
public function getOriginalHeight()
{
return $this->getImageProcessor()->getOriginalHeight();
}
/**
* @return string
*/
public function getDestinationSubdir()
{
return $this->_destinationSubdir;
}
/**
* @param string $dir
*
* @return $this
*/
public function setDestinationSubdir($dir)
{
$this->_destinationSubdir = $dir;
return $this;
}
/**
* Get image quality
*
* @return int
*/
public function getQuality()
{
return $this->_quality;
}
/**
* Set image quality, values in percentage from 0 to 100
*
* @param int $quality
*
* @return $this
*/
public function setQuality($quality)
{
$quality = abs((int)$quality);
if (0 < $quality) {
$this->_quality = $quality;
}
return $this;
}
/**
* @return $this
* @see \Magento\Framework\Image\Adapter\AbstractAdapter
*/
public function resize()
{
if ($this->_width == 0
&& $this->_height == 0
|| !$this->getBaseFile()
|| !$this->_fileExists($this->getBaseFile())
) {
return $this;
}
$resizedFile = $this->getResizedFile();
if ($resizedFile && $this->_fileExists($resizedFile)) {
return $this;
}
$new_filename = $this->_mediaDirectory->getAbsolutePath($resizedFile);
$this->getImageProcessor()->resize($this->_width, $this->_height);
$this->getImageProcessor()->save($new_filename);
return $this;
}
/**
* @param \Magento\Framework\Image $processor
*
* @return $this
*/
public function setImageProcessor($processor)
{
$this->_processor = $processor;
return $this;
}
/**
* @return string
* @throws NoSuchEntityException
*/
public function getUrl()
{
$media_url = $this->_storeManager->getStore()->getBaseUrl(UrlInterface::URL_TYPE_MEDIA);
if ($this->getBaseFile()) {
$resizedFile = $this->getResizedFile();
if ($resizedFile && $this->_fileExists($resizedFile)) {
return $media_url . $this->getResizedFile();
}
}
return $media_url . $this->__file;
}
/**
* @param string $size
*
* @return $this
*/
public function setSize($size)
{
// determine width and height from string
$width = $height = 0;
if (is_numeric($size)) {
$width = $height = $size;
} elseif (is_array($size)) {
if (1 >= count($size)) {
[$width, $height] = $size;
} else {
$width = $height = array_shift($size);
}
} elseif (is_string($size)) {
[$width, $height] = explode('x', strtolower($size), 2);
}
foreach (['width', 'height'] as $wh) {
${$wh} = (int)${$wh};
if (empty(${$wh})) {
${$wh} = null;
}
}
// set sizes
$this->setWidth($width)->setHeight($height);
return $this;
}
/**
* @param $file
*
* @throws Exception
*/
public function removeResized($file)
{
if (!empty($file)) {
$this->init($file);
}
$file = $this->getBaseFile();
if (!empty($file)) {
$new_filename = pathinfo($file);
$filename = implode(
'_',
[
$new_filename['filename'],
'*',
]
);
$new_filename['filename'] = $filename . '.' . $new_filename['extension'];
$pattern = implode(
'/',
[
$this->getDestinationSubdir(),
$new_filename['dirname'],
$new_filename['filename'],
]
);
$pattern = $this->_mediaDirectory->getAbsolutePath($pattern);
$files = Glob::glob($pattern);
if (!empty($files)) {
foreach ($files as $_file) {
if ($this->_fileExists($_file)) {
$this->_file->rm($_file);
}
}
}
}
}
/**
* @param $file
* @param array $attributes
*
* @return $this
* @throws Exception
*/
public function init($file, $attributes = [])
{
$this->_reset();
$this->__file = $file;
$this->setBaseFile($file);
$this->attributes = $attributes;
$this->setImageProperties();
return $this;
}
/**
* Resset all attributes
*/
protected function _reset()
{
$this->_processor = null;
$this->_baseFile = null;
$this->setQuality(90);
$this->setFileTemplate(static::BASE_TEMPLATE_FILE_NAME);
$this->setBackgroundColor([255, 255, 255]);
$this->setConstrainOnly(true);
$this->setDestinationSubdir('resized');
$this->setKeepAspectRatio(true);
$this->setKeepFrame(true);
$this->setKeepTransparency(true);
$this->setWidth(null);
$this->setHeight(null);
}
/**
* @param int[] $rgbArray
*
* @return $this
*/
public function setBackgroundColor(array $rgbArray)
{
$this->_backgroundColor = $rgbArray;
return $this;
}
/**
* @param bool $flag
*
* @return $this
*/
public function setConstrainOnly($flag)
{
$this->_constrainOnly = $flag && $flag !== 'false';
return $this;
}
/**
* @param bool $keep
*
* @return $this
*/
public function setKeepAspectRatio($keep)
{
$this->_keepAspectRatio = $keep && $keep !== 'false';
return $this;
}
/**
* @param bool $keep
*
* @return $this
*/
public function setKeepFrame($keep)
{
$this->_keepFrame = $keep && $keep !== 'false';
return $this;
}
/**
* @param bool $keep
*
* @return $this
*/
public function setKeepTransparency($keep)
{
$this->_keepTransparency = $keep && $keep !== 'false';
return $this;
}
/**
* Set image properties
*
* @return $this
*/
protected function setImageProperties()
{
// Set 'keep frame' flag
$frame = $this->getAttribute('frame');
if (!empty($frame)) {
$this->setKeepFrame($frame);
}
// Set 'quality'
$quality = $this->getAttribute('quality');
if (!empty($quality)) {
$this->setQuality($quality);
}
// Set 'constrain only' flag
$constrain = $this->getAttribute('constrain');
if (!empty($constrain)) {
$this->setConstrainOnly($constrain);
}
// Set 'keep aspect ratio' flag
$aspectRatio = $this->getAttribute('aspect_ratio');
if (!empty($aspectRatio)) {
$this->setKeepAspectRatio($aspectRatio);
}
// Set 'keep $crop' flag
$crop = $this->getAttribute('crop');
if (!empty($crop)) {
$this->seCropOnly($crop);
}
// Set 'transparency' flag
$transparency = $this->getAttribute('transparency');
if (!empty($transparency)) {
$this->setKeepTransparency($transparency);
}
// Set background color
$background = (array)$this->getAttribute('background');
if (!empty($background)) {
$this->setBackgroundColor($background);
}
$fileTemplate = $this->getAttribute('fileTemplate');
$this->setFileTemplate(!empty($fileTemplate) ? $fileTemplate : static::BASE_TEMPLATE_FILE_NAME);
return $this;
}
/**
* Retrieve image attribute
*
* @param string $name
*
* @return string
*/
protected function getAttribute($name)
{
return $this->attributes[$name] ?? null;
}
/**
* @param bool $flag
*
* @return $this
*/
public function seCropOnly($flag)
{
$this->_cropOnly = $flag && $flag !== 'false';
return $this;
}
}
+330
View File
@@ -0,0 +1,330 @@
<?php
namespace Olegnax\Core\Helper;
use Exception;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\Helper\Context;
use Magento\Framework\App\ProductMetadataInterface;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Component\ComponentRegistrar;
use Magento\Framework\Component\ComponentRegistrarInterface;
use Magento\Framework\Filesystem\Directory\ReadFactory;
use Magento\Framework\HTTP\Adapter\CurlFactory;
use Magento\Framework\HTTP\AsyncClient\Request;
use Magento\Framework\HTTP\PhpEnvironment\RemoteAddress;
use Magento\Framework\Module\ModuleListInterface;
use Psr\Log\LoggerInterface;
class ModuleInfo extends Helper
{
const MODULE_URL = 'https://olegnax.com/extras/products-status/magento2_modules.json';
const CACHE_PERIOD = 24 * 60 * 60;
const XML_PATH_CACHE = 'olegnax_core/module/cache';
const XML_PATH_CACHE_DATE = 'olegnax_core/module/datacache';
/**
* @var ProductMetadataInterface
*/
protected $productMetadata;
/**
* @var CurlFactory
*/
protected $curlFactory;
/**
* @var RemoteAddress
*/
protected $remoteAddress;
/**
* @var RequestInterface
*/
protected $request;
/**
* @var array
*/
protected $data;
/**
* @var string
*/
protected $_moduleUrl;
/**
* @var ComponentRegistrarInterface
*/
protected $componentRegistrar;
/**
* @var ModuleListInterface
*/
protected $moduleList;
/**
* @var ReadFactory
*/
protected $readFactory;
public function __construct(
Context $context,
LoggerInterface $logger,
CurlFactory $curlFactory,
ProductMetadataInterface $productMetadata,
RemoteAddress $remoteAddress,
ComponentRegistrarInterface $componentRegistrar,
ModuleListInterface $moduleList,
ReadFactory $readFactory,
RequestInterface $request
) {
$this->curlFactory = $curlFactory;
$this->moduleList = $moduleList;
$this->productMetadata = $productMetadata;
$this->remoteAddress = $remoteAddress;
$this->componentRegistrar = $componentRegistrar;
$this->readFactory = $readFactory;
$this->request = $request;
parent::__construct($context, $logger);
}
public function getServer(
$name
) {
return $this->request->getServer($name);
}
public function getModuleInfo($moduleName, $onlyInstalled = true)
{
$data = $this->getModule($moduleName);
if ('' == $data['setup_version'] && $onlyInstalled) {
return [];
}
$apiData = $this->getData();
if (array_key_exists($moduleName, $apiData)) {
$data = array_replace($data, $apiData[$moduleName]);
}
if (!isset($data['theme_module'])) {
$data['theme_module'] = false;
}
$data['server_version'] = isset($data['version']) ? $data['version'] : $data['setup_version'];
$data['update_status'] = version_compare(
$data['server_version'],
$data['setup_version'],
'>'
);
return $data;
}
/**
* @param string $moduleName
* @return bool
*/
public function isActive($moduleName){
return $this->_moduleManager->isEnabled($moduleName);
}
protected function getModule($name)
{
$module = $this->moduleList->getOne($name);
if (empty($module)) {
$module = [
'name' => $name,
'setup_version' => $this->getComposerVersion($name),
];
}
if (empty($module['setup_version'])) {
$module['setup_version'] = $this->getComposerVersion($name);
}
$module['title'] = str_replace('_', ' ', $module['name']);
return (array)$module;
}
protected function getComposerVersion($moduleName, $type = ComponentRegistrar::MODULE)
{
$path = $this->componentRegistrar->getPath($type, $moduleName);
if ($path) {
$dirReader = $this->readFactory->create($path);
if ($dirReader->isExist('composer.json')) {
$data = $dirReader->readFile('composer.json');
$data = json_decode($data, true);
if (isset($data['version'])) {
return $data['version'];
}
}
if ($dirReader->isExist('etc/module.xml')) {
$data = $dirReader->readFile('etc/module.xml');
if (preg_match('/setup_version="([^\"]+)"/i', $data, $matches)) {
return $matches[1];
}
}
}
return '';
}
public function getData($forsed = false)
{
$date = (int)$this->getSystemDefaultValue(static::XML_PATH_CACHE_DATE);
try {
if (empty($this->data)) {
$this->data = $this->decodeData($this->getSystemDefaultValue(static::XML_PATH_CACHE));
}
if ($date + static::CACHE_PERIOD < time() || $forsed || empty($this->data)) {
$this->data = $this->decodeData($this->loadData());
if (!empty($this->data)) {
$this->setSystemValue(
static::XML_PATH_CACHE,
json_encode($this->data),
ScopeConfigInterface::SCOPE_TYPE_DEFAULT,
0
);
$this->setSystemValue(
static::XML_PATH_CACHE_DATE,
time(),
ScopeConfigInterface::SCOPE_TYPE_DEFAULT,
0
);
}
}
} catch (Exception $e) {
$this->data = [];
}
return $this->data;
}
private function decodeData($data = '')
{
if (empty($data)) {
return [];
}
return (array)json_decode($data, true);
}
protected function loadData()
{
$curl = $this->curlFactory->create();
$curl->setConfig(
[
'timeout' => 2,
'maxredirects' => 5,
'useragent' => sprintf(
'Olegnax: %s/%s (%s)',
$this->productMetadata->getName(),
$this->productMetadata->getVersion(),
$this->productMetadata->getEdition()
),
'referer' => $this->getSystemDefaultValue('web/unsecure/base_url'),
'verifypeer' => 0,
'verifyhost' => 0,
]
);
$curl->write(Request::METHOD_GET, $this->getModuleUrl());
$data = $curl->read();
$curl->close();
if(!empty($data)){
$data = preg_split('/^\r?$/m', $data, 2);
if(!empty($data) && isset($data[1])){
$data = trim($data[1]);
return $data;
}
}
return '[]';
}
public function getModuleUrl()
{
if ($this->_moduleUrl === null) {
$this->_moduleUrl = self::MODULE_URL . $this->getHash();
}
return $this->_moduleUrl;
}
public function getHash()
{
$args = ['hash' => base64_encode($this->getCurrentIp())];
$args = array_filter($args);
$query = '';
if (!empty($args)) {
$query = '?' . http_build_query($args);
}
return $query;
}
public function getCurrentIp()
{
$variable = [
'HTTP_X_REAL_IP',
'HTTP_CLIENT_IP',
'HTTP_X_FORWARDED_FOR'
];
$value = array_map([$this, 'getServer'], $variable);
$value = array_filter($value);
$value = array_map('trim', $value);
$value[] = $this->getRemoteAddress();
$value = array_filter($value);
$value = implode(',', $value);
return $value;
}
public function getRemoteAddress()
{
return $this->remoteAddress->getRemoteAddress();
}
public function getThemeInfo($themePath, $themeName = null, $onlyInstalled = true)
{
$data = $this->getTheme($themePath);
if ('' == $data['setup_version'] && $onlyInstalled) {
return [];
}
if (empty($themeName) && isset($data['name']) && !empty($data['name'])) {
$themeName = $data['name'];
}
$apiData = $this->getData();
if (!empty($themeName) && array_key_exists($themeName, $apiData)) {
$data = array_replace($data, $apiData[$themeName]);
}
$data['server_version'] = isset($data['version']) ? $data['version'] : $data['setup_version'];
$data['update_status'] = version_compare(
$data['server_version'],
$data['setup_version'],
'>'
);
return $data;
}
private function getTheme($themePath)
{
$theme = [
'path' => $themePath,
'setup_version' => $this->getComposerVersion($themePath, ComponentRegistrar::THEME),
];
$theme['established'] = !empty($theme['setup_version']);
$name = $this->getThemeName($themePath);
if (!empty($name)) {
$theme['name'] = $name;
}
return (array)$theme;
}
protected function getThemeName($path)
{
$path = $this->componentRegistrar->getPath(ComponentRegistrar::THEME, $path);
if ($path) {
$dirReader = $this->readFactory->create($path);
if ($dirReader->isExist('theme.xml')) {
$data = $dirReader->readFile('theme.xml');
if (preg_match('/<title>([^<>]+)<\/title>/i', $data, $matches)) {
return $matches[1];
}
}
}
return null;
}
}
+549
View File
@@ -0,0 +1,549 @@
<?php
/**
* @author Olegnax
* @package Olegnax_Core
* @copyright Copyright (c) 2023 Olegnax (http://olegnax.com/). All rights reserved.
* See COPYING.txt for license details.
*/
namespace Olegnax\Core\Helper;
use Exception;
use Magento\Catalog\Block\Product\Image as CatalogBlockProductImage;
use Magento\Catalog\Helper\Image;
use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\Product\Image\ParamsBuilder;
use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Framework\App\Helper\Context;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\App\ProductMetadataInterface;
use Magento\Framework\Config\View;
use Magento\Framework\View\ConfigInterface;
/**
* Description of Image
*
* @author Master
*/
class ProductImage extends AbstractHelper
{
const TEMPLATE = 'Magento_Catalog::product/image_with_borders.phtml';
const HOVER_TEMPLATE = 'Magento_Catalog::product/hover_image_with_borders.phtml';
/**
* @var Image
*/
protected $imageHelper;
/**
* @var ConfigInterface
*/
protected $viewConfig;
/**
* @var View
*/
protected $configView;
/**
* @var ParamsBuilder
*/
private $imageParamsBuilder;
/**
* @var string
*/
protected $_magentoVersion;
/**
* ProductImage constructor.
*
* @param Context $context
* @param Image $imageHelper
* @param ConfigInterface $viewConfig
* @param ParamsBuilder $imageParamsBuilder
*/
public function __construct(
Context $context,
Image $imageHelper,
ConfigInterface $viewConfig,
ParamsBuilder $imageParamsBuilder
) {
$this->imageHelper = $imageHelper;
$this->viewConfig = $viewConfig;
$this->imageParamsBuilder = $imageParamsBuilder;
parent::__construct($context);
}
/**
* @param Product $product
* @param string $imageId
* @param string $imageIdHover
* @param string $template
* @param array $attributes
* @param array $properties
*
* @return mixed
*/
public function getImageHover(
Product $product,
$imageId,
$imageIdHover,
$template = self::HOVER_TEMPLATE,
array $attributes = [],
$properties = []
) {
if (!$this->hasHoverImage($product, $imageId, $imageIdHover)) {
return $this->getImage($product, $imageId, self::TEMPLATE, $attributes, $properties);
}
$image = $this->_getImage($product, $imageId, $properties)->getUrl();
$imageMiscParams = $this->getImageParams($imageId);
$image_hoverMiscParams = $this->getImageParams($imageIdHover);
$image_hover = $this->resizeImage(
$product,
$imageIdHover,
[
$imageMiscParams['image_width'],
$imageMiscParams['image_height'],
],
$properties
)->getUrl();
$data = [
'data' => [
'template' => $template,
'product_id' => $product->getId(),
'product' => $product,
'image_id' => $imageId,
'image_hover_id' => $imageIdHover,
'image_url' => $image,
'image_hover_url' => $image_hover,
'label' => $this->getLabel($product, $imageMiscParams['image_type']),
'label_hover' => $this->getLabel($product, $image_hoverMiscParams['image_type']),
'width' => $imageMiscParams['image_width'],
'height' => $imageMiscParams['image_height'],
'ratio' => $this->getRatio($imageMiscParams['image_width'], $imageMiscParams['image_height']),
'class' => $this->getClass($attributes),
'custom_attributes' => $this->getStringCustomAttributes($attributes),
],
];
return $this->_createTemplate($data);
}
/**
* @param Product $product
* @param string $imageId
* @param string $imageId_hover
*
* @return bool
*/
public function hasHoverImage(Product $product, $imageId, $imageId_hover)
{
if ($imageId != $imageId_hover) {
$_imageId = $this->getImageParams($imageId);
$_imageId_hover = $this->getImageParams($imageId_hover);
if ($_imageId['image_type'] !== $_imageId_hover['image_type']) {
$image = $product->getData($_imageId['image_type']);
$image_hover = $product->getData($_imageId_hover['image_type']);
return $image && $image_hover && 'no_selection' !== $image_hover && $image !== $image_hover;
}
}
return false;
}
/**
* @param int $imageId
*
* @return array
*/
public function getImageParams($imageId)
{
$viewImageConfig = $this->getConfigView()->getMediaAttributes(
'Magento_Catalog',
Image::MEDIA_TYPE_CONFIG_NODE,
$imageId
);
$imageMiscParams = $this->imageParamsBuilder->build($viewImageConfig);
if (empty($imageMiscParams)) {
$imageMiscParams = $this->getDefaultParams();
$this->_logger->critical(sprintf('No options found for "%s" images!', $imageId));
}
return $imageMiscParams;
}
/**
* Retrieve config view
*
* @return View
*/
protected function getConfigView()
{
if (!$this->configView) {
$this->configView = $this->viewConfig->getViewConfig();
}
return $this->configView;
}
/**
* @return array
*/
protected function getDefaultParams()
{
return [
"image_type" => "small_image",
"image_height" => 240,
"image_width" => 240,
"background" => [255, 255, 255],
"quality" => 80,
"keep_aspect_ratio" => true,
"keep_frame" => true,
"keep_transparency" => true,
"constrain_only" => true,
];
}
/**
* @param Product $product
* @param string $imageId
* @param string $template
* @param array $attributes
* @param array $properties
*
* @return mixed
*/
public function getImage(
Product $product,
$imageId,
$template = self::TEMPLATE,
array $attributes = [],
$properties = []
) {
$image = $this->_getImage($product, $imageId, $properties);
$imageMiscParams = $this->getImageParams($imageId);
$data = [
'data' => [
'template' => $template,
'product_id' => $product->getId(),
'product' => $product,
'image_id' => $imageId,
'image_url' => $image->getUrl(),
'label' => $this->getLabel($product, $imageMiscParams['image_type']),
'width' => $imageMiscParams['image_width'],
'height' => $imageMiscParams['image_height'],
'ratio' => $this->getRatio($imageMiscParams['image_width'], $imageMiscParams['image_height']),
'class' => $this->getClass($attributes),
'custom_attributes' => $this->getStringCustomAttributes($attributes),
],
];
return $this->_createTemplate($data);
}
/**
* @param Product $product
* @param string $imageId
* @param array $properties
*
* @return Image
*/
private function _getImage(Product $product, $imageId, $properties = [])
{
return $this->imageHelper->init($product, $imageId, $properties);
}
/**
* @param Product $product
*
* @param string $imageType
*
* @return string
*/
private function getLabel(Product $product, string $imageType): string
{
$label = "";
if (!empty($imageType)) {
$label = $product->getData($imageType . '_' . 'label');
}
if (empty($label)) {
$label = $product->getName();
}
return (string)$label;
}
/**
* Calculate image ratio
*
* @param $width
* @param $height
*
* @return float
*/
private function getRatio(int $width, int $height): float
{
if ($width && $height) {
return $height / $width;
}
return 1.0;
}
/**
* Retrieve image class for HTML element
*
* @param array $attributes
*
* @return string
*/
private function getClass(array $attributes): string
{
return $attributes['class'] ?? 'product-image-photo';
}
/**
* Retrieve image custom attributes for HTML element
*
* @param array $attributes
*
* @return string|array
*/
private function getStringCustomAttributes(array $attributes)
{
if (!$this->compareVersion()) {
return $attributes;
}
$result = [];
foreach ($attributes as $name => $value) {
$result[] = $name . '="' . $value . '"';
}
return !empty($result) ? implode(' ', $result) : '';
}
/**
* @return string
*/
private function getMagentoVersion()
{
if (!$this->_magentoVersion) {
$this->_magentoVersion = ObjectManager::getInstance()->get(ProductMetadataInterface::class)->getVersion();
}
return $this->_magentoVersion;
}
/**
* @param $version
*
* @return bool
*/
protected function compareVersion($version = '2.4.0')
{
return version_compare($this->getMagentoVersion(), $version, '<');
}
/**
* @param array $data
*
* @return CatalogBlockProductImage
*/
private function _createTemplate($data = [])
{
return ObjectManager::getInstance()->create(CatalogBlockProductImage::class, $data);
}
/**
* @param Product $product
* @param string $imageId
* @param array|int $size
* @param array $properties
*
* @return Image
*/
public function resizeImage(Product $product, $imageId, $size, $properties = [])
{
$size = $this->prepareSize($size);
$image = $this->_getImage($product, $imageId, $properties);
$image->resize($size[0], $size[1]);
return $image;
}
/**
* @param array|int $size
*
* @return array
*/
private function prepareSize($size)
{
if (is_array($size) && 1 >= count($size)) {
$size = array_shift($size);
}
if (!is_array($size)) {
$size = [$size, $size];
}
$size = array_map('floatval', $size);
$size = array_map('abs', $size);
return $size;
}
/**
* @param Product $product
* @param string $imageId
* @param string $imageId_hover
* @param array|int $size
* @param string $template
* @param array $attributes
* @param array $properties
*
* @return CatalogBlockProductImage|mixed
*/
public function getResizedImageHover(
Product $product,
$imageId,
$imageId_hover,
$size,
$template = self::HOVER_TEMPLATE,
array $attributes = [],
$properties = []
) {
if (!is_array($template)) {
$template = [
$template,
self::TEMPLATE,
];
} else {
foreach ([self::HOVER_TEMPLATE, self::TEMPLATE] as $key => $value) {
if (!isset($template[$key]) || empty($template[$key])) {
$template[$key] = $value;
}
}
}
if (!$this->hasHoverImage($product, $imageId, $imageId_hover)) {
return $this->getResizedImage($product, $imageId, $size, $template[1], $attributes, $properties);
}
$imageMiscParams = $this->getImageParams($imageId);
if (empty($size)) {
$size = [$imageMiscParams['image_width'], $imageMiscParams['image_height']];
} elseif (is_array($size)) {
foreach (['image_width', 'image_height'] as $key => $value) {
if (!isset($size[$key]) || empty($size[$key])) {
$size[$key] = $imageMiscParams[$value];
}
}
}
$image = $this->resizeImage($product, $imageId, $size, $properties);
try {
[
$imageMiscParams['image_width'],
$imageMiscParams['image_height']
] = $image->getResizedImageInfo();
} catch (Exception $e) {
$this->_logger->error("OX Product Image: " . $e->getMessage());
$imageMiscParams['image_width'] = $imageMiscParams['image_height'] = 1;
}
$image = $image->getUrl();
$image_hover = $this->resizeImage($product, $imageId_hover, $size, $properties)->getUrl();
$image_hoverMiscParams = $this->getImageParams($imageId_hover);
if (array_key_exists('class', $attributes)) {
unset($attributes['class']);
}
$data = [
'data' => [
'template' => $template[0],
'product_id' => $product->getId(),
'product' => $product,
'image_id' => $imageId,
'image_hover_id' => $imageId_hover,
'image_url' => $image,
'image_hover_url' => $image_hover,
'label' => $this->getLabel($product, $imageMiscParams['image_type']),
'label_hover' => $this->getLabel($product, $image_hoverMiscParams['image_type']),
'width' => $imageMiscParams['image_width'],
'height' => $imageMiscParams['image_height'],
'ratio' => $this->getRatio($imageMiscParams['image_width'], $imageMiscParams['image_height']),
'class' => $this->getClass($attributes),
'custom_attributes' => $this->getStringCustomAttributes($attributes),
],
];
return $this->_createTemplate($data);
}
/**
* @param Product $product
* @param string $imageId
* @param array|int $size
* @param string $template
* @param array $attributes
* @param array $properties
*
* @return CatalogBlockProductImage|mixed
*/
public function getResizedImage(
Product $product,
$imageId,
$size,
$template = self::TEMPLATE,
array $attributes = [],
$properties = []
) {
$imageMiscParams = $this->getImageParams($imageId);
if (empty($size)) {
return $this->getImage($product, $imageId, $template, $attributes, $properties);
}
if (is_array($size)) {
foreach (['image_width', 'image_height'] as $key => $value) {
if (!isset($size[$key]) || empty($size[$key])) {
$size[$key] = $imageMiscParams[$value];
}
}
}
$image = $this->resizeImage($product, $imageId, $size, $properties);
$imageMiscParams = $this->getImageParams($imageId);
try {
[
$imageMiscParams['image_width'],
$imageMiscParams['image_height']
] = $image->getResizedImageInfo();
} catch (Exception $e) {
$this->_logger->error("OX Product Image: " . $e->getMessage());
$imageMiscParams['image_width'] = $imageMiscParams['image_height'] = 1;
}
$data = [
'data' => [
'template' => $template,
'product_id' => $product->getId(),
'product' => $product,
'image_id' => $imageId,
'image_url' => $image->getUrl(),
'label' => $this->getLabel($product, $imageMiscParams['image_type']),
'width' => $imageMiscParams['image_width'],
'height' => $imageMiscParams['image_height'],
'ratio' => $this->getRatio($imageMiscParams['image_width'], $imageMiscParams['image_height']),
'class' => $this->getClass($attributes),
'custom_attributes' => $this->getStringCustomAttributes($attributes),
],
];
return $this->_createTemplate($data);
}
/**
* @param Product $product
* @param string $image
* @param array|int $size
* @param array $properties
*
* @return string
*/
public function getUrlResizedImage(Product $product, $image, $size, $properties = [])
{
$image = $this->resizeImage($product, $image, $size, $properties);
return $image->getUrl();
}
}