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
@@ -0,0 +1,128 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package GeoIP Data for Magento 2 (System)
*/
namespace Amasty\Geoip\Block\Adminhtml\Settings;
use Magento\Backend\Block\Template\Context;
use Magento\Config\Block\System\Config\Form\Field;
use Magento\Framework\Data\Form\Element\AbstractElement;
use Magento\Framework\Exception\LocalizedException;
use Amasty\Geoip\Model\Import as ModelImport;
class DownloadNImport extends Field
{
/**
* @var ModelImport $import
*/
protected $import;
/**
* DownloadNImport constructor.
*
* @param Context $context
* @param ModelImport $import
* @param array $data
*/
public function __construct(
Context $context,
ModelImport $import,
array $data = []
) {
parent::__construct($context, $data);
$this->import = $import;
}
/**
* Return element html
*
* @param AbstractElement $element
*
* @return string
*
* @throws LocalizedException
*/
public function _getElementHtml(AbstractElement $element)
{
$importTypes = [
'location',
'block',
'block_v6'
];
$urls = [];
foreach ($importTypes as $type) {
$startDownloadingUrl = $this->getUrl(
'amasty_geoip/geoip/startDownloading',
[
'type' => $type,
'action' => 'download_and_import'
]
);
$startUrl = $this->getUrl(
'amasty_geoip/geoip/start',
[
'type' => $type,
'action' => 'download_and_import'
]
);
$processUrl = $this->getUrl(
'amasty_geoip/geoip/process',
[
'type' => $type,
'action' => 'download_and_import'
]
);
$commitUrl = $this->getUrl(
'amasty_geoip/geoip/commit',
[
'type' => $type,
'action' => 'download_and_import'
]
);
$urls[] = [
'start' => $startUrl,
'process' => $processUrl,
'commit' => $commitUrl,
'download' => $startDownloadingUrl
];
}
$block = $this->getLayout()
->createBlock(\Amasty\Geoip\Block\Adminhtml\Template::class)
->setTemplate('Amasty_Geoip::download_n_import.phtml')
->setConfig(json_encode($urls));
$this->setDNIData($block);
return $block->toHtml();
}
public function setDNIData($block)
{
if ($block->geoipHelper->isDone() && $this->import->importTableHasData()) {
$width = 100;
$completedClass = "-completed";
$importedClass = "-completed";
$importDate = $block->_scopeConfig->getValue('amgeoip/import/date_download');
if (!empty($importDate)) {
$importDate = __('Last Imported: ') . $importDate;
}
} else {
$width = 0;
$completedClass = "-failed";
$importedClass = "-failed";
$importDate = '';
}
$block->setWidth($width)
->setCompletedClass($completedClass)
->setImportedClass($importedClass)
->setImportDate($importDate);
}
}
+137
View File
@@ -0,0 +1,137 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package GeoIP Data for Magento 2 (System)
*/
namespace Amasty\Geoip\Block\Adminhtml\Settings;
use Amasty\Geoip\Block\Adminhtml\Template as TemplateBlock;
use Amasty\Geoip\Model\Import as ImportModel;
use Magento\Backend\Block\Template\Context;
use Magento\Config\Block\System\Config\Form\Field;
use Magento\Framework\Data\Form\Element\AbstractElement;
class Import extends Field
{
/**
* @var ImportModel
*/
protected $import;
/**
* DownloadNImport constructor.
* @param Context $context
* @param ImportModel $import
* @param array $data
*/
public function __construct(
Context $context,
ImportModel $import,
array $data = []
) {
parent::__construct($context, $data);
$this->import = $import;
}
public function _getElementHtml(AbstractElement $element)
{
$importTypes = [
'location',
'block',
'block_v6'
];
$urls = [];
foreach ($importTypes as $type) {
$startUrl = $this->getUrl(
'amasty_geoip/geoip/start',
[
'type' => $type,
'action' => 'import'
]
);
$processUrl = $this->getUrl(
'amasty_geoip/geoip/process',
[
'type' => $type,
'action' => 'import'
]
);
$commitUrl = $this->getUrl(
'amasty_geoip/geoip/commit',
[
'type' => $type,
'action' => 'import'
]
);
$urls[] = ['start' => $startUrl, 'process' => $processUrl, 'commit' => $commitUrl];
}
$block = $this->getLayout()
->createBlock(\Amasty\Geoip\Block\Adminhtml\Template::class)
->setTemplate('Amasty_Geoip::import.phtml')
->setConfig(json_encode($urls))
;
$this->setImportData($block);
return $block->toHtml();
}
/**
* @param TemplateBlock $block
*/
public function setImportData($block)
{
$importFilesAvailable = false;
$fileBlockPath = $block->geoipHelper->getCsvFilePath('block');
$fileBlockV6Path = $block->geoipHelper->getCsvFilePath('block_v6');
$fileLocationPath = $block->geoipHelper->getCsvFilePath('location');
$blockFileExist = false;
$blockV6FileExist = false;
$locationFileExist = false;
if ($block->geoipHelper->isFileExist($fileBlockPath)) {
$blockFileExist = true;
}
if ($block->geoipHelper->isFileExist($fileBlockV6Path)) {
$blockV6FileExist = true;
}
if ($block->geoipHelper->isFileExist($fileLocationPath)) {
$locationFileExist = true;
}
if ($blockFileExist && $locationFileExist && $blockV6FileExist) {
$importFilesAvailable = true;
}
$importDate = '';
if ($block->geoipHelper->isDone() && $this->import->importTableHasData()) {
$width = 100;
$importedClass = '-completed';
if ($block->_scopeConfig->getValue('amgeoip/import/date')) {
$importDate = __('Last Imported: ') . $block->_scopeConfig->getValue('amgeoip/import/date');
}
} else {
$width = 0;
$importedClass = '-failed';
}
$block
->setWidth($width)
->setImportFilesAvailable($importFilesAvailable)
->setBlockFileExist($blockFileExist)
->setBlockV6FileExist($blockV6FileExist)
->setLocationFileExist($locationFileExist)
->setImportedClass($importedClass)
->setImportDate($importDate);
}
}
+25
View File
@@ -0,0 +1,25 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package GeoIP Data for Magento 2 (System)
*/
namespace Amasty\Geoip\Block\Adminhtml;
class Template extends \Magento\Backend\Block\Template
{
/**
* @var \Amasty\Geoip\Helper\Data
*/
public $geoipHelper;
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Amasty\Geoip\Helper\Data $geoipHelper
) {
parent::__construct($context);
$this->geoipHelper = $geoipHelper;
}
}
@@ -0,0 +1,34 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package GeoIP Data for Magento 2 (System)
*/
namespace Amasty\Geoip\Controller\Adminhtml\Geoip;
use Amasty\Geoip\Controller\Adminhtml\GeoipAbstract;
class Commit extends GeoipAbstract
{
public function execute()
{
$result = [];
try {
$type = $this->getRequest()->getParam('type');
$action = $this->getRequest()->getParam('action');
$isDownload = false;
if ($action == 'download_and_import') {
$isDownload = true;
}
$this->importModel->commitProcess($type, $isDownload);
$result['status'] = 'done';
$result['full_import_done'] = $this->geoipHelper->isDone() ? "1" : "0";
} catch (\Exception $e) {
$result['error'] = $e->getMessage();
}
$this->getResponse()->setBody($this->jsonHelper->jsonEncode($result));
}
}
@@ -0,0 +1,38 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package GeoIP Data for Magento 2 (System)
*/
namespace Amasty\Geoip\Controller\Adminhtml\Geoip;
use Amasty\Geoip\Controller\Adminhtml\GeoipAbstract as GeoipAbstract;
class Process extends GeoipAbstract
{
public function execute()
{
$result = [];
try {
$type = $this->getRequest()->getParam('type');
$action = $this->getRequest()->getParam('action');
$filePath = $this->geoipHelper->getCsvFilePath($type);
$ret = $this->importModel->doProcess($type, $filePath, $action);
$result['type'] = $type;
$result['status'] = 'processing';
$result['position'] = ceil($ret['current_row'] / $ret['rows_count'] * 100);
if ($result['position'] > 100) {
$result['position'] = 100;
}
if ($type == 'block' && $result['position'] == 100 && $ret['current_row'] + 3 < $ret['rows_count']) {
$result['position'] = 99;
}
} catch (\Exception $e) {
$result['error'] = $e->getMessage();
}
$this->getResponse()->setBody($this->jsonHelper->jsonEncode($result));
}
}
+38
View File
@@ -0,0 +1,38 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package GeoIP Data for Magento 2 (System)
*/
namespace Amasty\Geoip\Controller\Adminhtml\Geoip;
use Amasty\Geoip\Controller\Adminhtml\GeoipAbstract;
class Start extends GeoipAbstract
{
public function execute()
{
$result = [];
try {
$type = $this->getRequest()->getParam('type');
$action = $this->getRequest()->getParam('action');
$this->geoipHelper->resetDone();
$filePath = $this->geoipHelper->getCsvFilePath($type);
$ret = $this->importModel->startProcess(
$type,
$filePath,
$action,
$this->geoipHelper->_geoipIgnoredLines[$type]
);
$result['position'] = ceil($ret['current_row'] / $ret['rows_count'] * 100);
$result['status'] = 'started';
$result['file'] = $this->geoipHelper->_geoipCsvFiles[$type];
} catch (\Exception $e) {
$result['error'] = $e->getMessage();
}
$this->getResponse()->setBody($this->jsonHelper->jsonEncode($result));
}
}
@@ -0,0 +1,100 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package GeoIP Data for Magento 2 (System)
*/
namespace Amasty\Geoip\Controller\Adminhtml\Geoip;
use Amasty\Geoip\Controller\Adminhtml\GeoipAbstract;
class StartDownloading extends GeoipAbstract
{
public function execute()
{
$result = [];
try {
$type = $this->getRequest()->getParam('type');
$url = $this->_getFileUrl($type);
$dir = $this->geoipHelper->getDirPath();
$newFilePath = $this->geoipHelper->getCsvFilePath($type);
$needToUpdate = true;
$needToDownload = true;
if ($this->driverFile->isExists($newFilePath)) {
$hashUrl = $this->getHashUrl($type);
if ($hashUrl
&& hash_file('md5', $newFilePath) == trim($this->driverFile->fileGetContents($hashUrl))
) {
$needToDownload = false;
if ($this->geoipHelper->isDone(false)) {
$needToUpdate = false;
}
} else {
$this->driverFile->deleteFile($newFilePath);
}
}
if ($needToUpdate && !$this->driverFile->isExists($dir)) {
$this->driverFile->createDirectory($dir, 0770);
}
if ($needToUpdate) {
if ($needToDownload) {
$source = $this->driverFile->fileOpen($url, 'r');
$dest = $this->driverFile->fileOpen($newFilePath, 'w');
//@codingStandardsIgnoreStart
stream_copy_to_stream($source, $dest);
//@codingStandardsIgnoreEnd
}
$result['status'] = 'finish_downloading';
} else {
$result['status'] = 'done';
}
$result['file'] = $this->geoipHelper->_geoipCsvFiles[$type];
} catch (\Exception $e) {
$result['error'] = $e->getMessage();
}
$this->getResponse()->setBody($this->jsonHelper->jsonEncode($result));
}
protected function _getFileUrl($type)
{
$url = '';
switch ($type) {
case 'block':
$url = $this->geoipHelper->getUrlBlockFile();
break;
case 'location':
$url = $this->geoipHelper->getUrlLocationFile();
break;
case 'block_v6':
$url = $this->geoipHelper->getUrlBlockV6File();
break;
}
return $url;
}
/**
* @param string $type
*
* @return string
*/
private function getHashUrl($type)
{
switch ($type) {
case 'block':
return $this->geoipHelper->getHashUrlBlock();
case 'location':
return $this->geoipHelper->getHashUrlLocation();
case 'block_v6':
return $this->geoipHelper->getHashUrlBlockV6();
}
return '';
}
}
@@ -0,0 +1,63 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package GeoIP Data for Magento 2 (System)
*/
namespace Amasty\Geoip\Controller\Adminhtml;
use Amasty\Geoip\Helper\Data as Helper;
use Amasty\Geoip\Model\Import;
use Amasty\Geoip\Model\Geolocation;
use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\Json\Helper\Data as JsonData;
use Magento\Framework\Filesystem\Driver\File;
/**
* Class GeoipAbstract
*/
abstract class GeoipAbstract extends Action
{
/**
* @var Import
*/
protected $importModel;
/**
* @var Helper
*/
protected $geoipHelper;
/**
* @var JsonData
*/
protected $jsonHelper;
/**
* @var File
*/
protected $driverFile;
/**
* @var Geolocation
*/
protected $geolocationModel;
public function __construct(
Context $context,
Import $importModel,
Helper $geoipHelper,
JsonData $jsonHelper,
File $driverFile,
Geolocation $geolocationModel
) {
parent::__construct($context);
$this->importModel = $importModel;
$this->geoipHelper = $geoipHelper;
$this->jsonHelper = $jsonHelper;
$this->driverFile = $driverFile;
$this->geolocationModel = $geolocationModel;
}
}
+282
View File
@@ -0,0 +1,282 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package GeoIP Data for Magento 2 (System)
*/
namespace Amasty\Geoip\Helper;
use Magento\Config\App\Config\Type\System;
use Magento\Framework\App\Cache\StateInterface;
use Magento\Framework\App\Cache\Type\Config;
use Magento\Framework\App\Config\ConfigResource\ConfigInterface;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Framework\App\Helper\Context;
use Magento\Framework\Exception\FileSystemException;
use Magento\Framework\Filesystem\Driver\File;
use Magento\Framework\ObjectManagerInterface;
class Data extends AbstractHelper
{
public const BLOCK_FILE = 'amgeoip/general/block_file_url';
public const BLOCK_V6_FILE = 'amgeoip/general/block_v6_file_url';
public const LOCATION_FILE = 'amgeoip/general/location_file_url';
public const BLOCK_HASH = 'amgeoip/general/block_hash_url';
public const BLOCK_V6_HASH = 'amgeoip/general/block_v6_hash_url';
public const LOCATION_HASH = 'amgeoip/general/location_hash_url';
public const FORCED_IP_ENABLED = 'amgeoip/debug/force_ip_enabled';
public const FORCED_IP = 'amgeoip/debug/forced_ip';
/**
* @var array
*/
public $_geoipCsvFiles = [
'block' => 'GeoLite2-City-Blocks-IPv4.csv',
'block_v6' => 'GeoLite2-City-Blocks-IPv6.csv',
'location' => 'GeoLite2-City-Locations-en.csv'
];
/**
* @var array
*/
public $_geoipIgnoredLines = [
'block' => 1,
'block_v6' => 1,
'location' => 1
];
/**
* @var DirectoryList
*/
protected $directoryList;
/**
* Resource model of config data
*
* @var ConfigInterface
*/
protected $_resource;
/**
* @var StateInterface $_state
*/
protected $_state;
/**
* @var bool
*/
protected $_cacheEnabled;
/**
* @var File
*/
private $fileDriver;
/**
* @var ObjectManagerInterface
*/
private $objectManager;
public function __construct(
Context $context,
DirectoryList $directoryList,
ConfigInterface $_resource,
StateInterface $state,
File $fileDriver,
ObjectManagerInterface $objectManager
) {
parent::__construct($context);
$this->directoryList = $directoryList;
$this->_resource = $_resource;
$this->fileDriver = $fileDriver;
$this->_state = $state;
$this->objectManager = $objectManager;
}
/**
* @return string
*/
public function getUrlBlockFile()
{
return $this->scopeConfig->getValue(self::BLOCK_FILE);
}
/**
* @return string
*/
public function getUrlBlockV6File()
{
return $this->scopeConfig->getValue(self::BLOCK_V6_FILE);
}
/**
* @return string
*/
public function getUrlLocationFile()
{
return $this->scopeConfig->getValue(self::LOCATION_FILE);
}
/**
* @return string
*/
public function getHashUrlBlock()
{
return $this->scopeConfig->getValue(self::BLOCK_HASH);
}
/**
* @return string
*/
public function getHashUrlBlockV6()
{
return $this->scopeConfig->getValue(self::BLOCK_V6_HASH);
}
/**
* @return string
*/
public function getHashUrlLocation()
{
return $this->scopeConfig->getValue(self::LOCATION_HASH);
}
/**
* @param bool $flushCache
* @return bool
*/
public function isDone($flushCache = true)
{
if ($flushCache) {
$this->flushConfigCache();
}
return $this->scopeConfig->getValue('amgeoip/import/location')
&& $this->scopeConfig->getValue('amgeoip/import/block')
&& $this->scopeConfig->getValue('amgeoip/import/block_v6');
}
/**
*
*/
public function resetDone()
{
$this->_resource->saveConfig('amgeoip/import/block', 0, 'default', 0);
$this->_resource->saveConfig('amgeoip/import/block_v6', 0, 'default', 0);
$this->_resource->saveConfig('amgeoip/import/location', 0, 'default', 0);
}
/**
* @return string
* @throws FileSystemException
*/
public function getDirPath()
{
$varDir = $this->directoryList->getPath('var');
$dir = $varDir . DIRECTORY_SEPARATOR . 'amasty' . DIRECTORY_SEPARATOR . 'geoip';
return $dir;
}
/**
* @param $type
* @return string
* @throws FileSystemException
*/
public function getCsvFilePath($type)
{
$dir = $this->getDirPath();
$file = $dir . DIRECTORY_SEPARATOR . $this->_geoipCsvFiles[$type];
return $file;
}
/**
* is file exist
*
* @param string $filePath
*
* @return bool
*/
public function isFileExist($filePath)
{
try {
return $this->fileDriver->isExists($filePath);
} catch (FileSystemException $exception) {
return false;
}
}
/**
*
*/
public function flushConfigCache()
{
if (class_exists(System::class)) {
$this->objectManager->get(System::class)->clean();
} else {
$this->objectManager->get(Config::class)
->clean(
\Zend_Cache::CLEANING_MODE_MATCHING_TAG,
['config_scopes']
);
}
}
/**
* @param $type
* @return bool
*/
public function isCacheEnabled($type)
{
if (!isset($this->_cacheEnabled)) {
$this->_cacheEnabled = $this->_state->isEnabled($type);
}
return $this->_cacheEnabled;
}
/**
* @param $ip
*
* @return string
*
* @throws \Exception
*/
public function getLongIpV6($ip)
{
$ipN = inet_pton($ip);
$binary = '';
for ($bit = strlen($ipN) - 1; $bit >= 0; $bit--) {
$binary = sprintf('%08b', ord($ipN[$bit])) . $binary;
}
if (function_exists('gmp_init')) {
return gmp_strval(gmp_init($binary, 2), 10);
} elseif (function_exists('bcadd')) {
$decimal = '0';
$strLength = strlen($binary);
for ($i = 0; $i < $strLength; $i++) {
$decimal = bcmul($decimal, '2', 0);
$decimal = bcadd($decimal, $binary[$i], 0);
}
return $decimal;
} else {
throw new \Magento\Framework\Exception\LocalizedException(__('GMP or BCMATH extension not installed!'));
}
}
public function isForcedIpEnabled(): bool
{
return $this->scopeConfig->isSetFlag(self::FORCED_IP_ENABLED);
}
public function getForcedIp(): ?string
{
return $this->scopeConfig->getValue(self::FORCED_IP);
}
}
@@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package GeoIP Data for Magento 2 (System)
*/
namespace Amasty\Geoip\Model\Config\BackendModel;
use Magento\Framework\App\Config\Value;
use Magento\Framework\Exception\LocalizedException;
class IpValidation extends Value
{
/**
* @throws LocalizedException
*/
public function beforeSave(): self
{
if (empty($this->getValue())) {
throw new LocalizedException(__('Invalid Ip Address.'));
}
$ipIsValid = (bool)filter_var($this->getValue(), FILTER_VALIDATE_IP);
if (!$ipIsValid) {
throw new LocalizedException(__('Invalid Ip Address.'));
}
return parent::beforeSave();
}
}
+103
View File
@@ -0,0 +1,103 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package GeoIP Data for Magento 2 (System)
*/
namespace Amasty\Geoip\Model;
use Amasty\Geoip\Helper\Data as Helper;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\DB\Select;
use Magento\Framework\Model\AbstractModel;
class Geolocation extends AbstractModel
{
/**
* @var Helper
*/
public $geoipHelper;
/**
* @var ResourceConnection
*/
protected $resource;
/**
* Geolocation constructor.
*
* @param Helper $geoipHelper
* @param ResourceConnection $resource
*/
public function __construct(
Helper $geoipHelper,
ResourceConnection $resource
) {
$this->geoipHelper = $geoipHelper;
$this->resource = $resource;
}
/**
* load location data by IP
*
* @param $ip
*
* @return $this
*
* @throws \Exception
*/
public function locate($ip)
{
$ip = $this->geoipHelper->isForcedIpEnabled() ? $this->geoipHelper->getForcedIp() : $ip;
$isIpv6 = (bool)filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6);
if ($this->geoipHelper->isDone(false) && $ip) {
if ($isIpv6) {
$ip = $this->getPreparedIp($ip, ':');
$longIP = $this->geoipHelper->getLongIpV6($ip);
$blockTable = 'amasty_geoip_block_v6';
} else {
$ip = $this->getPreparedIp($ip, '.');
$longIP = sprintf("%u", ip2long($ip));
$blockTable = 'amasty_geoip_block';
}
if (!empty($longIP)) {
$connection = $this->resource->getConnection('read');
$blockSelect = $connection->select()
->from($this->resource->getTableName($blockTable))
->reset(Select::COLUMNS)
->columns(['geoip_loc_id', 'latitude', 'longitude'])
->where('start_ip_num <= ?', $longIP)
->order('start_ip_num DESC')
->limit(1);
$select = $connection->select()
->from(['b' => $blockSelect])
->joinInner(
['l' => $this->resource->getTableName('amasty_geoip_location')],
'l.geoip_loc_id = b.geoip_loc_id',
null
)
->reset(Select::COLUMNS)
->columns(['l.*', 'b.latitude', 'b.longitude']);
if ($result = $connection->fetchRow($select)) {
$this->setData($result);
}
}
}
return $this;
}
private function getPreparedIp(string $ip, string $addressSeparator): string
{
$addressParts = explode($addressSeparator, $ip);
array_pop($addressParts);
$addressParts[] = '0'; // Mask IP according to EU GDPR law
return implode($addressSeparator, $addressParts);
}
}
+542
View File
@@ -0,0 +1,542 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package GeoIP Data for Magento 2 (System)
*/
namespace Amasty\Geoip\Model;
use Amasty\Geoip\Helper\Data;
use Exception;
use Magento\Backend\Model\Session;
use Magento\Framework\App\Config\ConfigResource\ConfigInterface;
use Magento\Framework\App\Config\ReinitableConfigInterface;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\DeploymentConfig;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\Config\ConfigOptionsListConstants;
use Magento\Framework\Filesystem\Driver\File;
use Magento\Framework\Model\AbstractModel;
use Magento\Framework\Stdlib\DateTime\DateTime;
use Magento\Framework\Message\ManagerInterface;
class Import extends AbstractModel
{
/**
* @var string
*/
protected $_tablePrefix;
/**
* @var int
*/
protected $_rowsPerTransaction = 10000;
/**
* Resource model of config data
*
* @var ConfigInterface
*/
protected $configInterface;
/**
* Database write connection
*
* @var ResourceConnection
*/
protected $resource;
/**
* @var ScopeConfigInterface
*/
protected $scopeConfig;
/**
* @var DateTime
*/
protected $coreDate;
/**
* @var Session
*/
protected $backendSession;
/**
* @var DeploymentConfig $_deploymentConfig
*/
protected $_deploymentConfig;
/**
* @var ReinitableConfigInterface $reinitableInterface
*/
protected $reinitableInterface;
/**
* @var Data $helper
*/
protected $helper;
/**
* @var bool
*/
protected $_firstTime = true;
/**
* @var File
*/
private $driverFile;
/**
* @var ManagerInterface
*/
private $messageManager;
/**
* Import constructor.
*
* @param ConfigInterface $configInterface
* @param ReinitableConfigInterface $reinitableConfig
* @param ResourceConnection $resource
* @param ScopeConfigInterface $scopeConfig
* @param DateTime $coreDate
* @param Session $backendSession
* @param DeploymentConfig $deploymentConfig
* @param Data $helper
* @param File $driverFile
* @param ManagerInterface $messageManager
*/
public function __construct(
ConfigInterface $configInterface,
ReinitableConfigInterface $reinitableConfig,
ResourceConnection $resource,
ScopeConfigInterface $scopeConfig,
DateTime $coreDate,
Session $backendSession,
DeploymentConfig $deploymentConfig,
Data $helper,
File $driverFile,
ManagerInterface $messageManager
) {
$this->configInterface = $configInterface;
$this->reinitableInterface = $reinitableConfig;
$this->resource = $resource;
$this->scopeConfig = $scopeConfig;
$this->coreDate = $coreDate;
$this->backendSession = $backendSession;
$this->_deploymentConfig = $deploymentConfig;
$this->helper = $helper;
$this->driverFile = $driverFile;
$this->messageManager = $messageManager;
}
/**
* @param $table
* @param $filePath
* @param $action
* @param int $ignoredLines
*
* @return array
*
* @throws Exception
*/
public function startProcess($table, $filePath, $action, $ignoredLines = 0)
{
$allowedTableTypes = ['block', 'location', 'block_v6'];
if (!in_array($table, $allowedTableTypes)) {
throw new \Magento\Framework\Exception\LocalizedException('Invalid table type');
}
$importProcess = [
'position' => 0,
'tmp_table' => null,
'rows_count' => $this->_getRowsCount($filePath),
'current_row' => 0
];
$write = $this->resource->getConnection();
$columns = $write->getTables('amasty_geoip_' . $table . '_');
foreach ($columns as $key => $column) {
if ($table == 'block' && preg_match('/.+_block_v6/', $column)) {
unset($columns[$key]);
}
}
$oldTemporary = implode(', ', $columns);
if (!empty($oldTemporary)) {
$write->dropTable($oldTemporary);
}
if (($handle = $this->driverFile->fileOpen($filePath, "r")) !== false) {
$tmpTableName = $this->_prepareImport($table);
while ($ignoredLines > 0 && ($data = $this->driverFile->fileGetCsv($handle, 0, ",")) !== false) {
$ignoredLines--;
}
$importProcess['position'] = $this->driverFile->fileTell($handle);
$importProcess['tmp_table'] = $tmpTableName;
}
$write->truncateTable($this->resource->getTableName('amasty_geoip_block'));
$write->truncateTable($this->resource->getTableName('amasty_geoip_block_v6'));
$write->truncateTable($this->resource->getTableName('amasty_geoip_location'));
$this->helper->flushConfigCache();
$this->_saveInDb($table, $importProcess);
return $importProcess;
}
/**
* @return bool
*/
public function importTableHasData()
{
$write = $this->resource->getConnection();
$blockTable = $this->resource->getTableName('amasty_geoip_block');
$blockV6Table = $this->resource->getTableName('amasty_geoip_block_v6');
$locationTable = $this->resource->getTableName('amasty_geoip_location');
$countBlock = $write->select('count(block_id)')->from($blockTable)->limit(1);
$countBlockV6 = $write->select('count(block_id)')->from($blockV6Table)->limit(1);
$countLocation = $write->select('count(location_id)')->from($locationTable)->limit(1);
$block = $write->fetchCol($countBlock);
$blockV6 = $write->fetchCol($countBlockV6);
$location = $write->fetchCol($countLocation);
return array_key_exists(0, $block)
&& array_key_exists(0, $blockV6)
&& array_key_exists(0, $location)
&& $block[0]
&& $location[0];
}
/**
* @param $filePath
*
* @return int
*/
protected function _getRowsCount($filePath)
{
$lineCount = 0;
$handle = $this->driverFile->fileOpen($filePath, "r");
while (!$this->driverFile->endOfFile($handle)) {
$this->driverFile->fileGetCsv($handle);
$lineCount++;
}
$this->driverFile->fileClose($handle);
return $lineCount;
}
/**
* @param $table
*
* @return string
*/
protected function _prepareImport($table)
{
$write = $this->resource->getConnection();
$targetTable = $this->resource->getTableName('amasty_geoip_' . $table);
$tmpTableName = uniqid($targetTable . '_');
//@codingStandardsIgnoreStart
$query = 'create table ' . $tmpTableName . ' like ' . $targetTable;
//@codingStandardsIgnoreEnd
$write->query($query);
$write->changeTableEngine($tmpTableName, 'innodb');
return $tmpTableName;
}
/**
* @param $table
* @param $filePath
* @param $action
*
* @return array
* @throws Exception
*/
public function doProcess($table, $filePath, $action)
{
$ret = [];
if (($handle = $this->driverFile->fileOpen($filePath, "r")) !== false) {
$this->helper->flushConfigCache();
$importProcess = $this->_getFromDb($table);
if (!$importProcess) {
throw new \Magento\Framework\Exception\LocalizedException('run start before');
}
$tmpTableName = $importProcess['tmp_table'];
try {
$position = $importProcess['position'];
$this->driverFile->fileSeek($handle, $position);
$transactionIterator = 0;
if ($action != 'import') {
$this->_tablePrefix = (string)$this->_deploymentConfig->get(
ConfigOptionsListConstants::CONFIG_PATH_DB_PREFIX
);
}
$dataForImport = [];
while (($data = $this->driverFile->fileGetCsv($handle, 0, ",")) !== false) {
$dataForImport[] = $data;
$transactionIterator++;
if ($transactionIterator >= $this->_rowsPerTransaction) {
break;
}
}
if (count($dataForImport)) {
$this->_importItem($table, $tmpTableName, $dataForImport);
}
if ($this->_rowsPerTransaction > $importProcess['rows_count']) {
$importProcess['current_row'] = $importProcess['rows_count'];
}
$importProcess['current_row'] += $transactionIterator;
$importProcess['position'] = $this->driverFile->fileTell($handle);
$this->_saveInDb($table, $importProcess);
$ret = $importProcess;
} catch (Exception $e) {
if ($action == 'import') {
$this->_destroyImport($tmpTableName);
}
throw new \Magento\Framework\Exception\LocalizedException(__($e->getMessage()));
}
}
return $ret;
}
/**
* @param $table
* @param bool $isDownload
*
* @return bool
* @throws Exception
*/
public function commitProcess($table, $isDownload = false)
{
$ret = false;
$this->helper->flushConfigCache();
$importProcess = $this->_getFromDb($table);
if ($importProcess) {
$tmpTableName = $importProcess['tmp_table'];
if ($isDownload) {
$configDate = 'date_download';
} else {
$configDate = 'date';
}
try {
$this->configInterface
->saveConfig('amgeoip/import/' . $table, 1, 'default', 0)
->saveConfig('amgeoip/import/' . $configDate, $this->coreDate->gmtDate(), 'default', 0);
$this->reinitableInterface->reinit();
$this->_doneImport($table, $tmpTableName);
} catch (Exception $e) {
$this->messageManager->addErrorMessage($e->getMessage());
}
$ret = true;
} else {
throw new \Magento\Framework\Exception\LocalizedException(__('run start before'));
}
return $ret;
}
/**
* @param $table
* @param $tmpTableName
*/
protected function _doneImport($table, $tmpTableName)
{
$write = $this->resource->getConnection();
$targetTable = $this->resource->getTableName('amasty_geoip_' . $table);
if ($write->isTableExists($tmpTableName)) {
$write->dropTable($targetTable);
$write->renameTable($tmpTableName, $targetTable);
}
}
/**
* @param $table
* @param $tmpTableName
* @param $dataForImport
*/
protected function _importItem($table, $tmpTableName, &$dataForImport)
{
$dataForInsert = [];
$write = $this->resource->getConnection();
foreach ($dataForImport as $data) {
if ($table == 'block' && is_array($data) && isset($data[0])) {
list($ip, $mask) = explode('/', $data[0]);
$ip2long = ip2long($ip);
$min = ($ip2long >> (32 - $mask)) << (32 - $mask);
$max = $ip2long | ~(-1 << (32 - $mask));
$dataForInsert[] = [
'start_ip_num' => $min,
'end_ip_num' => $max,
'geoip_loc_id' => $data[1],
'postal_code' => $data[6],
'latitude' => $data[7],
'longitude' => $data[8]
];
} elseif ($table == 'location' && is_array($data)) {
$dataForInsert[] = [
'geoip_loc_id' => $data[0],
'country' => $data[4],
'city' => $data[10]
];
} elseif ($table == 'block_v6' && is_array($data) && isset($data[0])) {
list($ip, $mask) = explode('/', $data[0]);
$firstAddrBin = inet_pton($ip);
//@codingStandardsIgnoreStart
$elem = unpack('H*', $firstAddrBin);
//@codingStandardsIgnoreEnd
$firstAddrHex = reset($elem);
$firstAddrStr = inet_ntop($firstAddrBin);
$flexBits = 128 - $mask;
$lastAddrHex = $firstAddrHex;
$pos = 31;
while ($flexBits > 0) {
$orig = substr($lastAddrHex, $pos, 1);
$origVal = hexdec($orig);
$newVal = $origVal | (pow(2, min(4, $flexBits)) - 1);
$new = dechex($newVal);
$lastAddrHex = substr_replace($lastAddrHex, $new, $pos, 1);
$flexBits -= 4;
$pos--;
}
$lastAddrBin = pack('H*', $lastAddrHex);
$lastAddrStr = inet_ntop($lastAddrBin);
$dataForInsert[] = [
'start_ip_num' => $this->helper->getLongIpV6($firstAddrStr),
'end_ip_num' => $this->helper->getLongIpV6($lastAddrStr),
'geoip_loc_id' => $data[1],
'postal_code' => $data[6],
'latitude' => $data[7],
'longitude' => $data[8]
];
}
}
$write->insertMultiple($tmpTableName, $dataForInsert);
}
/**
* @param $tmpTableName
*/
protected function _destroyImport($tmpTableName)
{
$write = $this->resource->getConnection();
$write->dropTable($tmpTableName);
$this->_clearDb();
}
/**
* @param $table
* @param $importProcess
*/
protected function _saveInDb($table, $importProcess)
{
$this->configInterface->saveConfig(
'amgeoip/import/position/' . $table,
$importProcess['position'],
'default',
0
);
$this->configInterface->saveConfig(
'amgeoip/import/tmp_table/' . $table,
$importProcess['tmp_table'],
'default',
0
);
$this->configInterface->saveConfig(
'amgeoip/import/rows_count/' . $table,
$importProcess['rows_count'],
'default',
0
);
$this->configInterface->saveConfig(
'amgeoip/import/current_row/' . $table,
$importProcess['current_row'],
'default',
0
);
}
/**
* @param $table
*
* @return array
*/
protected function _getFromDb($table)
{
$importProcess = [];
$importProcess['position'] = $this->scopeConfig->getValue(
'amgeoip/import/position/' . $table,
'default',
0
);
$importProcess['tmp_table'] = $this->scopeConfig->getValue(
'amgeoip/import/tmp_table/' . $table,
'default',
0
);
$importProcess['rows_count'] = $this->scopeConfig->getValue(
'amgeoip/import/rows_count/' . $table,
'default',
0
);
$importProcess['current_row'] = $this->scopeConfig->getValue(
'amgeoip/import/current_row/' . $table,
'default',
0
);
return $importProcess;
}
/**
*
*/
protected function _clearDb()
{
$this->configInterface->deleteConfig('amgeoip/import/position/location', 'default', 0);
$this->configInterface->deleteConfig('amgeoip/import/position/block', 'default', 0);
$this->configInterface->deleteConfig('amgeoip/import/position/block_v6', 'default', 0);
$this->configInterface->deleteConfig('amgeoip/import/tmp_table/location', 'default', 0);
$this->configInterface->deleteConfig('amgeoip/import/tmp_table/block', 'default', 0);
$this->configInterface->deleteConfig('amgeoip/import/tmp_table/block_v6', 'default', 0);
$this->configInterface->deleteConfig('amgeoip/import/rows_count/location', 'default', 0);
$this->configInterface->deleteConfig('amgeoip/import/rows_count/block', 'default', 0);
$this->configInterface->deleteConfig('amgeoip/import/rows_count/block_v6', 'default', 0);
$this->configInterface->deleteConfig('amgeoip/import/current_row/location', 'default', 0);
$this->configInterface->deleteConfig('amgeoip/import/current_row/block', 'default', 0);
$this->configInterface->deleteConfig('amgeoip/import/current_row/block_v6', 'default', 0);
}
}
+46
View File
@@ -0,0 +1,46 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package GeoIP Data for Magento 2 (System)
*/
namespace Amasty\Geoip\Observer\Admin;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Message\ManagerInterface;
class SystemConfig implements ObserverInterface
{
/**
* @var ManagerInterface
*/
protected $messageManager;
/**
* SystemConfig constructor.
*
* @param ManagerInterface $messageManager
*/
public function __construct(
ManagerInterface $messageManager
) {
$this->messageManager = $messageManager;
}
/**
* @param Observer $observer
*/
public function execute(Observer $observer)
{
$section = $observer->getRequest()->getParam('section');
if ($section == 'amgeoip') {
$this->messageManager->addWarning(
__('When import in progress please do not close this '
. 'browser window and do not attempt to operate Magento backend in separate tabs. '
. 'Import usually takes from 10 to 20 minutes.')
);
}
}
}
+65
View File
@@ -0,0 +1,65 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package GeoIP Data for Magento 2 (System)
*/
namespace Amasty\Geoip\Setup\Patch\Data;
use Magento\Framework\Module\ResourceInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\Patch\DataPatchInterface;
use Magento\Framework\Setup\Patch\NonTransactionableInterface;
class ChangeDbEngine implements DataPatchInterface, NonTransactionableInterface
{
/**
* @var ResourceInterface
*/
private $moduleResource;
/**
* @var ModuleDataSetupInterface
*/
private $moduleDataSetup;
public function __construct(
ResourceInterface $moduleResource,
ModuleDataSetupInterface $moduleDataSetup
) {
$this->moduleResource = $moduleResource;
$this->moduleDataSetup = $moduleDataSetup;
}
public function apply()
{
$setupDataVersion = (string)$this->moduleResource->getDataVersion('Amasty_Geoip');
if ($setupDataVersion && version_compare($setupDataVersion, '1.5.1', '<')) {
$tables = [
'amasty_geoip_block_v6',
'amasty_geoip_block',
'amasty_geoip_location'
];
foreach ($tables as $table) {
$this->moduleDataSetup->getConnection()->changeTableEngine(
$this->moduleDataSetup->getTable($table),
'INNODB'
);
}
}
}
public static function getDependencies()
{
return [];
}
public function getAliases()
{
return [];
}
}
+50
View File
@@ -0,0 +1,50 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package GeoIP Data for Magento 2 (System)
*/
namespace Amasty\Geoip\Setup;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
use Magento\Framework\Setup\UninstallInterface;
class Uninstall implements UninstallInterface
{
public function uninstall(SchemaSetupInterface $setup, ModuleContextInterface $context)
{
$this->uninstallTables($setup)
->uninstallConfigData($setup);
}
private function uninstallTables(SchemaSetupInterface $setup): self
{
$tablesToDrop = [
'amasty_geoip_block_v6',
'amasty_geoip_location',
'amasty_geoip_block'
];
foreach ($tablesToDrop as $table) {
$setup->getConnection()->dropTable(
$setup->getTable($table)
);
}
return $this;
}
private function uninstallConfigData(SchemaSetupInterface $setup): self
{
$setup->getConnection()->delete(
$setup->getTable('core_config_data'),
"`path` LIKE 'amgeoip%'"
);
return $this;
}
}
+145
View File
@@ -0,0 +1,145 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package GeoIP Data for Magento 2 (System)
*/
// @codingStandardsIgnoreFile
namespace Amasty\Geoip\Test\Unit\Helper;
use Amasty\Geoip\Helper\Data;
use Amasty\Geoip\Test\Unit\Traits;
use PHPUnit_Framework_MockObject_MockObject as MockObject;
/**
* Class DataTest
*
* @see Data
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class DataTest extends \PHPUnit\Framework\TestCase
{
use Traits\ObjectManagerTrait;
use Traits\ReflectionTrait;
public const EXIST_FILE = BP . '/' . 'index.php';
public const NOT_EXIST_FILE = BP . '/' . 'missingIndexFile.php';
/**
* @covers Data::isDone
*
* @dataProvider isDoneDataProvider
*
* @throws \ReflectionException
*/
public function testIsDone($flushCache, $amount, $value, $expectedResult)
{
/** @var Data|MockObject $helper */
$helper = $this->getMockBuilder(Data::class)
->disableOriginalConstructor()
->setMethods(['flushConfigCache'])
->getMock();
$helper->expects($this->exactly($amount))->method('flushConfigCache');
/** @var \Magento\Framework\App\Config\ScopeConfigInterface|MockObject $scopeConfig */
$scopeConfig = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class);
$scopeConfig->expects($this->any())->method('getValue')->willReturn($value);
$this->setProperty($helper, 'scopeConfig', $scopeConfig, Data::class);
$this->assertEquals($expectedResult, $helper->isDone($flushCache));
}
/**
* @covers Data::isFileExist
*
* @dataProvider isFileExistDataProvider
*
* @throws \ReflectionException
*/
public function testIsFileExist($file, $expectedResult)
{
$this->markTestSkipped();
/** @var \Magento\Framework\Filesystem\Driver\File $fileDriver */
$fileDriver = $this->getObjectManager()->getObject(\Magento\Framework\Filesystem\Driver\File::class);
/** @var Data $helper */
$helper = $this->getObjectManager()->getObject(Data::class,
[
'fileDriver' => $fileDriver
]
);
$this->assertEquals($expectedResult, $helper->isFileExist($file));
}
/**
* @covers Data::isCacheEnabled
*
* @dataProvider isCacheEnabledDataProvider
*
* @throws \ReflectionException
*/
public function testIsCacheEnabled($expectedResult, $value = null)
{
/** @var \Magento\Framework\App\Cache\StateInterface|MockObject $state */
$state = $this->createMock(\Magento\Framework\App\Cache\StateInterface::class);
$state->expects($this->any())->method('isEnabled')->willReturn(true);
/** @var Data $helper */
$helper = $this->getObjectManager()->getObject(Data::class,
[
'_cacheEnabled' => $value,
'_state' => $state
]
);
$this->assertEquals($expectedResult, $helper->isCacheEnabled('redis'));
}
/**
* Data provider for isCacheEnabled test
* @return array
*/
public function isCacheEnabledDataProvider()
{
return [
[true, true],
[false, false],
[true],
];
}
/**
* Data provider for isFileExist test
* @return array
*/
public function isFileExistDataProvider()
{
return [
[self::EXIST_FILE, true],
[self::NOT_EXIST_FILE, false],
];
}
/**
* Data provider for isDone test
* @return array
*/
public function isDoneDataProvider()
{
return [
[true, 1, true, true],
[false, 0, false, false],
[false, 0, true, true],
[true, 1, false, false],
[1, 1, false, false],
[0, 0, false, false],
['test', 1, false, false],
[-1, 1, false, false],
];
}
}
+158
View File
@@ -0,0 +1,158 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package GeoIP Data for Magento 2 (System)
*/
// @codingStandardsIgnoreFile
namespace Amasty\Geoip\Test\Unit\Model;
use Amasty\Geoip\Model\Import;
use Amasty\Geoip\Test\Unit\Traits;
use Magento\Framework\Filesystem\Driver\File;
use Magento\Framework\App\Config\ConfigResource\ConfigInterface;
use PHPUnit_Framework_MockObject_MockObject as MockObject;
/**
* Class ImportTest
*
* @see ImportTest
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class ImportTest extends \PHPUnit\Framework\TestCase
{
use Traits\ObjectManagerTrait;
use Traits\ReflectionTrait;
public const TEST_FILE = BP . '/' . 'index.php';
/**
* @var \Magento\Framework\App\Config\ConfigResource\ConfigInterface|MockObject
*/
private $config;
/**
* @var \Magento\Framework\DB\Adapter\AdapterInterface|MockObject
*/
private $connection;
/**
* @var \Magento\Framework\App\ResourceConnection|MockObject
*/
private $resource;
/**
* @var Import
*/
private $model;
/**
* @var \Magento\Framework\Filesystem\Driver\File
*/
private $fileDriver;
public function setUp(): void
{
$this->markTestSkipped();
/** @var File $fileDriver */
$this->fileDriver = $this->getObjectManager()->getObject(File::class);
/** @var ConfigInterface|MockObject $config */
$this->config = $this->createMock(ConfigInterface::class);
$this->config->expects($this->any())->method('saveConfig')->willReturn($this->config);
/** @var \Magento\Framework\DB\Adapter\AdapterInterface|MockObject connection */
$this->connection = $this->createMock(\Magento\Framework\DB\Adapter\AdapterInterface::class);
/** @var \Magento\Framework\App\ResourceConnection|MockObject resource */
$this->resource = $this->createMock(\Magento\Framework\App\ResourceConnection::class);
$this->resource->expects($this->any())->method('getConnection')->willReturn($this->connection);
$this->resource->expects($this->any())->method('getTableName')->willReturn('amasty_geoip_search_test');
/** @var Import|MockObject $model */
$this->model = $this->getObjectManager()->getObject(Import::class,
[
'configInterface' => $this->config,
'resource' => $this->resource,
'driverFile' => $this->fileDriver
]
);
}
/**
* @covers Import::commitProcess
*
* @throws \ReflectionException
*/
public function testCommitProcess()
{
$this->connection->expects($this->any())->method('isTableExists')->willReturn(true);
$this->assertTrue($this->model->commitProcess('test_table'));
}
/**
* @covers Import::doProcess
*
* @dataProvider startProcessAndDoProccessDataProvider
*
* @throws \ReflectionException
*/
public function testDoProcess($key)
{
$result = $this->model->doProcess('test_table', self::TEST_FILE, 'import');
$this->assertArrayHasKey($key, $result);
}
/**
* @covers Import::startProcess
*
* @dataProvider startProcessAndDoProccessDataProvider
*
* @throws \ReflectionException
*/
public function testStartProcess($key, $expectedResult = null)
{
$this->connection->expects($this->any())->method('getTables')->willReturn(['table1, table2']);
/** @var Import|MockObject $model */
$model = $this->getMockBuilder(Import::class)
->disableOriginalConstructor()
->setMethods(['_prepareImport', '_getRowsCount', '_saveInDb'])
->getMock();
$helper = $this->createMock(\Amasty\Geoip\Helper\Data::class);
$helper->expects($this->any())->method('flushConfigCache');
$this->setProperty($model, 'driverFile', $this->fileDriver, Import::class);
$this->setProperty($model, 'resource', $this->resource, Import::class);
$this->setProperty($model, 'helper', $helper, Import::class);
$this->setProperty($model, 'configInterface', $this->config, Import::class);
$model->expects($this->any())->method('_prepareImport')->willReturn(true);
$model->expects($this->any())->method('_getRowsCount')->willReturn(10);
$model->expects($this->any())->method('_saveInDb')->willReturn(true);
$result = $model->startProcess('block', self::TEST_FILE, 'import');
$this->assertArrayHasKey($key, $result);
}
/**
* Data provider for startProcess and doProcess test
* @return array
*/
public function startProcessAndDoProccessDataProvider()
{
return [
['position'],
['tmp_table'],
['rows_count'],
['current_row']
];
}
}
@@ -0,0 +1,33 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package GeoIP Data for Magento 2 (System)
*/
namespace Amasty\Geoip\Test\Unit\Traits;
/**
* Create Object Manager instance for test purposes.
*
* @codingStandardsIgnoreFile
*/
trait ObjectManagerTrait
{
/**
* @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager
*/
private $objectManager;
/**
* @return \Magento\Framework\TestFramework\Unit\Helper\ObjectManager
*/
private function getObjectManager()
{
if (!$this->objectManager) {
$this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this);
}
return $this->objectManager;
}
}
+69
View File
@@ -0,0 +1,69 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package GeoIP Data for Magento 2 (System)
*/
namespace Amasty\Geoip\Test\Unit\Traits;
/**
* Provide useful methods with reflection.
*
* @codingStandardsIgnoreFile
*/
trait ReflectionTrait
{
/**
* @param object $object
* @param string $methodName
* @param array $parameters
*
* @return mixed
* @throws \ReflectionException
*/
private function invokeMethod($object, $methodName, array $parameters = [])
{
$reflection = new \ReflectionClass(get_class($object));
$method = $reflection->getMethod($methodName);
$method->setAccessible(true);
return $method->invokeArgs($object, $parameters);
}
/**
* @param object $object
* @param string $propertyName
* @param mixed $value
* @param string $originalClassName
*
* @return object
* @throws \ReflectionException
*/
private function setProperty($object, $propertyName, $value, $originalClassName = '')
{
$reflection = new \ReflectionClass($originalClassName ?: get_class($object));
$property = $reflection->getProperty($propertyName);
$property->setAccessible(true);
$property->setValue($object, $value);
return $object;
}
/**
* @param $object
* @param $propertyName
* @param string $originalClassName
*
* @return mixed
* @throws \ReflectionException
*/
private function getProperty($object, $propertyName, $originalClassName = '')
{
$reflection = new \ReflectionClass($originalClassName ?: get_class($object));
$property = $reflection->getProperty($propertyName);
$property->setAccessible(true);
return $property->getValue($object);
}
}
+21
View File
@@ -0,0 +1,21 @@
{
"name": "amasty/geoip",
"description": "Amasty Geoip Data",
"require": {
"php": ">=7.3",
"amasty/base": ">=1.14.7"
},
"type": "magento2-module",
"version": "1.5.9",
"license": [
"proprietary"
],
"autoload": {
"files": [
"registration.php"
],
"psr-4": {
"Amasty\\Geoip\\": ""
}
}
}
+23
View File
@@ -0,0 +1,23 @@
<?xml version="1.0"?>
<!--
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package GeoIP Data for Magento 2 (System)
*/-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Acl/etc/acl.xsd">
<acl>
<resources>
<resource id="Magento_Backend::admin">
<resource id="Magento_Backend::stores">
<resource id="Magento_Backend::stores_settings">
<resource id="Magento_Config::config">
<resource id="Amasty_Geoip::amasty_geoip" title="Amasty Geoip Data" />
</resource>
</resource>
</resource>
</resource>
</resources>
</acl>
</config>
+13
View File
@@ -0,0 +1,13 @@
<?xml version="1.0"?>
<!--
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package GeoIP Data for Magento 2 (System)
*/-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="controller_action_predispatch_adminhtml_system_config_edit">
<observer name="amasty_geoip_system_config" instance="Amasty\Geoip\Observer\Admin\SystemConfig" />
</event>
</config>
+7
View File
@@ -0,0 +1,7 @@
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
<router id="admin">
<route id="amasty_geoip" frontName="amasty_geoip">
<module name="Amasty_Geoip" />
</route>
</router>
</config>
+46
View File
@@ -0,0 +1,46 @@
<?xml version="1.0"?>
<!--
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package GeoIP Data for Magento 2 (System)
*/-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:Config/etc/system_file.xsd">
<system>
<section id="amgeoip" translate="label" type="text" sortOrder="70504" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Geo Ip Data</label>
<tab>amasty</tab>
<resource>Amasty_Geoip::amasty_geoip</resource>
<group id="download_import" translate="label" type="text" sortOrder="1" showInDefault="1" showInWebsite="0" showInStore="0">
<label>Download and Import</label>
<field id="download_import_button" translate="label comment" type="button" sortOrder="1" showInDefault="1" showInWebsite="0" showInStore="0">
<frontend_model>Amasty\Geoip\Block\Adminhtml\Settings\DownloadNImport</frontend_model>
</field>
</group>
<group id="import" translate="label" type="text" sortOrder="2" showInDefault="1" showInWebsite="0" showInStore="0">
<label>Import</label>
<field id="import_button" translate="label comment" type="button" sortOrder="1" showInDefault="1" showInWebsite="0" showInStore="0">
<frontend_model>Amasty\Geoip\Block\Adminhtml\Settings\Import</frontend_model>
</field>
</group>
<group id="debug" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="0" showInStore="0">
<label>Debug</label>
<field id="force_ip_enabled" translate="label" type="select" sortOrder="10" showInDefault="1" showInWebsite="0" showInStore="0">
<label>Enable Force IP</label>
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
</field>
<field id="forced_ip" translate="label comment" sortOrder="20" type="text" showInDefault="1" showInWebsite="0" showInStore="0">
<label>Force IP Address</label>
<comment>You can set IP address for testing. Please be careful to avoid issues on production.</comment>
<backend_model>Amasty\Geoip\Model\Config\BackendModel\IpValidation</backend_model>
<validate>required-entry</validate>
<depends>
<field id="force_ip_enabled">1</field>
</depends>
</field>
</group>
</section>
</system>
</config>
+22
View File
@@ -0,0 +1,22 @@
<?xml version="1.0"?>
<!--
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package GeoIP Data for Magento 2 (System)
*/-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Store/etc/config.xsd">
<default>
<amgeoip>
<general>
<location_file_url>https://amasty.com/media/downloads/geoip/databases/GeoLite2-City-Locations-en.csv</location_file_url>
<block_file_url>https://amasty.com/media/downloads/geoip/databases/GeoLite2-City-Blocks-IPv4.csv</block_file_url>
<block_v6_file_url>https://amasty.com/media/downloads/geoip/databases/GeoLite2-City-Blocks-IPv6.csv</block_v6_file_url>
<location_hash_url>https://amasty.com/media/downloads/geoip/databases/location_hash.md5</location_hash_url>
<block_hash_url>https://amasty.com/media/downloads/geoip/databases/block_hash.md5</block_hash_url>
<block_v6_hash_url>https://amasty.com/media/downloads/geoip/databases/block_hash_ipv6.md5</block_v6_hash_url>
</general>
</amgeoip>
</default>
</config>
+60
View File
@@ -0,0 +1,60 @@
<?xml version="1.0"?>
<!--
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package GeoIP Data for Magento 2 (System)
*/-->
<schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd">
<table name="amasty_geoip_block" resource="default" engine="innodb" comment="Amasty Geoip Block Table">
<column xsi:type="int" name="block_id" padding="10" unsigned="true" nullable="false" identity="true" comment="Block Id"/>
<column xsi:type="int" name="start_ip_num" padding="10" unsigned="true" nullable="false" identity="false" comment="Start Ip Num"/>
<column xsi:type="int" name="end_ip_num" padding="10" unsigned="true" nullable="false" identity="false" comment="End Ip Num"/>
<column xsi:type="int" name="geoip_loc_id" padding="10" unsigned="true" nullable="false" identity="false" comment="Geoip Loc Id"/>
<column xsi:type="text" name="postal_code" nullable="true" comment="Postal Code"/>
<column xsi:type="float" name="latitude" scale="0" precision="10" unsigned="false" nullable="true" comment="Latitude"/>
<column xsi:type="float" name="longitude" scale="0" precision="10" unsigned="false" nullable="true" comment="Longitude"/>
<constraint xsi:type="primary" referenceId="PRIMARY">
<column name="block_id"/>
</constraint>
<index referenceId="AMASTY_GEOIP_BLOCK_GEOIP_LOC_ID" indexType="btree">
<column name="geoip_loc_id"/>
</index>
<index referenceId="AMASTY_GEOIP_BLOCK_START_IP_NUM_END_IP_NUM" indexType="btree">
<column name="start_ip_num"/>
<column name="end_ip_num"/>
</index>
</table>
<table name="amasty_geoip_location" resource="default" engine="innodb" comment="Amasty Geoip Location Table">
<column xsi:type="int" name="location_id" padding="10" unsigned="true" nullable="false" identity="true" comment="Location Id"/>
<column xsi:type="int" name="geoip_loc_id" padding="10" unsigned="true" nullable="false" identity="false" comment="Geoip Loc Id"/>
<column xsi:type="text" name="country" nullable="true" comment="Country"/>
<column xsi:type="text" name="city" nullable="true" comment="City"/>
<column xsi:type="text" name="region" nullable="true" comment="Region"/>
<constraint xsi:type="primary" referenceId="PRIMARY">
<column name="location_id"/>
</constraint>
<index referenceId="AMASTY_GEOIP_LOCATION_GEOIP_LOC_ID" indexType="btree">
<column name="geoip_loc_id"/>
</index>
</table>
<table name="amasty_geoip_block_v6" resource="default" engine="innodb" comment="Amasty Geoip Block Table IpV6">
<column xsi:type="int" name="block_id" padding="10" unsigned="true" nullable="false" identity="true" comment="Block Id"/>
<column xsi:type="varchar" name="start_ip_num" nullable="false" length="40" comment="Start Ip Num"/>
<column xsi:type="varchar" name="end_ip_num" nullable="false" length="40" comment="End Ip Num"/>
<column xsi:type="int" name="geoip_loc_id" padding="10" unsigned="true" nullable="false" identity="false" comment="Geoip Loc Id"/>
<column xsi:type="text" name="postal_code" nullable="true" comment="Postal Code"/>
<column xsi:type="float" name="latitude" scale="0" precision="10" unsigned="false" nullable="true" comment="Latitude"/>
<column xsi:type="float" name="longitude" scale="0" precision="10" unsigned="false" nullable="true" comment="Longitude"/>
<constraint xsi:type="primary" referenceId="PRIMARY">
<column name="block_id"/>
</constraint>
<index referenceId="AMASTY_GEOIP_BLOCK_V6_GEOIP_LOC_ID" indexType="btree">
<column name="geoip_loc_id"/>
</index>
<index referenceId="AMASTY_GEOIP_BLOCK_V6_START_IP_NUM_END_IP_NUM" indexType="btree">
<column name="start_ip_num"/>
<column name="end_ip_num"/>
</index>
</table>
</schema>
+53
View File
@@ -0,0 +1,53 @@
{
"amasty_geoip_block": {
"column": {
"block_id": true,
"start_ip_num": true,
"end_ip_num": true,
"geoip_loc_id": true,
"postal_code": true,
"latitude": true,
"longitude": true
},
"index": {
"AMASTY_GEOIP_BLOCK_GEOIP_LOC_ID": true,
"AMASTY_GEOIP_BLOCK_START_IP_NUM_END_IP_NUM": true
},
"constraint": {
"PRIMARY": true
}
},
"amasty_geoip_location": {
"column": {
"location_id": true,
"geoip_loc_id": true,
"country": true,
"city": true,
"region": true
},
"index": {
"AMASTY_GEOIP_LOCATION_GEOIP_LOC_ID": true
},
"constraint": {
"PRIMARY": true
}
},
"amasty_geoip_block_v6": {
"column": {
"block_id": true,
"start_ip_num": true,
"end_ip_num": true,
"geoip_loc_id": true,
"postal_code": true,
"latitude": true,
"longitude": true
},
"index": {
"AMASTY_GEOIP_BLOCK_V6_GEOIP_LOC_ID": true,
"AMASTY_GEOIP_BLOCK_V6_START_IP_NUM_END_IP_NUM": true
},
"constraint": {
"PRIMARY": true
}
}
}
+13
View File
@@ -0,0 +1,13 @@
<?xml version="1.0"?>
<!--
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package GeoIP Data for Magento 2 (System)
*/-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Amasty_Geoip">
</module>
</config>
+16
View File
@@ -0,0 +1,16 @@
"Last Imported: ","Last Imported: "
"GMP or BCMATH extension not installed!","GMP or BCMATH extension not installed!"
"Invalid Ip Address.","Invalid Ip Address."
"run start before","run start before"
"When import in progress please do not close this browser window and do not attempt to operate Magento backend in separate tabs. Import usually takes from 10 to 20 minutes.","When import in progress please do not close this browser window and do not attempt to operate Magento backend in separate tabs. Import usually takes from 10 to 20 minutes."
Download,Download
Import,Import
Completed,Completed
"Download and Import","Download and Import"
"GeoIp data is up-to-date.","GeoIp data is up-to-date."
Error.,Error.
"Geo Ip Data","Geo Ip Data"
Debug,Debug
"Enable Force IP","Enable Force IP"
"Force IP Address","Force IP Address"
"You can set IP address for testing. Please be careful to avoid issues on production.","You can set IP address for testing. Please be careful to avoid issues on production."
1 Last Imported: Last Imported:
2 GMP or BCMATH extension not installed! GMP or BCMATH extension not installed!
3 Invalid Ip Address. Invalid Ip Address.
4 run start before run start before
5 When import in progress please do not close this browser window and do not attempt to operate Magento backend in separate tabs. Import usually takes from 10 to 20 minutes. When import in progress please do not close this browser window and do not attempt to operate Magento backend in separate tabs. Import usually takes from 10 to 20 minutes.
6 Download Download
7 Import Import
8 Completed Completed
9 Download and Import Download and Import
10 GeoIp data is up-to-date. GeoIp data is up-to-date.
11 Error. Error.
12 Geo Ip Data Geo Ip Data
13 Debug Debug
14 Enable Force IP Enable Force IP
15 Force IP Address Force IP Address
16 You can set IP address for testing. Please be careful to avoid issues on production. You can set IP address for testing. Please be careful to avoid issues on production.
+11
View File
@@ -0,0 +1,11 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package GeoIP Data for Magento 2 (System)
*/
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Amasty_Geoip',
__DIR__
);
@@ -0,0 +1,73 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package GeoIP Data for Magento 2 (System)
*/
/**
* @var \Amasty\Geoip\Block\Adminhtml\Settings\DownloadNImport $block
*/
?>
<div class="amgeoip-import-container" data-bind="scope: 'import'">
<div class="amgeoip-progressbar-container">
<span class="amgeoip-state -done"
data-bind="css: {'-done': downloadStarted() || initialStatus}">
<?= $block->escapeHtml(__("Download")) ?>
</span>
<span class="amgeoip-state -import"
data-bind="css: {'-done': isDownloadCompleted()}">
<?= $block->escapeHtml(__("Import")) ?>
</span>
<span class="amgeoip-state -endimport"
data-bind="css: {'-done': importDone()}">
<?= $block->escapeHtml(__("Completed")) ?>
</span>
<div class="amgeoip-download-container">
<span class="amgeoip-counter -hidden"
data-bind="attr: {'data-count': downloadCounter}, style: {left: downloadStatusWidth() + '%'}, css: {'-hidden': !isShowDownloadCounter()}"></span>
<span class="amgeoip-begin -done" data-bind="css: {'-done': downloadStarted() || initialStatus}"></span>
<div class="amgeoip-line-container">
<div class="amgeoip-line" data-bind="style: {width: downloadStatusWidth() + '%'}"></div>
</div>
</div>
<div class="amgeoip-download-state -download">
<span class="amgeoip-label -import <?= $block->escapeHtml($block->getCompletedClass()) ?>"
data-bind="css: {'-completed': isDownloadCompleted()}"></span>
<div class="amgeoip-line-container">
<span class="amgeoip-counter -hidden"
data-bind="
attr: {'data-count': importCounter},
style: {left: importStatusWidth() + '%'},
css: {'-hidden': !isShowImportCounter()}">
</span>
<div class="amgeoip-line" data-bind="style: {width: importStatusWidth() + '%'}" style="width: <?= (int)$block->getWidth() ?>%"></div>
</div>
<span class="<?= $block->escapeHtml($block->getImportedClass()) ?> amgeoip-label -endimport" data-bind="css: {'-completed': importDone()}"></span>
</div>
</div>
<span class="amgeoip-import-date"><?= $block->escapeHtml($block->getImportDate()) ?></span>
<p class="amgeoip-message" data-bind="text: message"></p>
<button class="action-default amgeoip-button"
type="button"
data-bind="
click: initImportAndDownload.bind($data),
attr: {title: $t('Download and Import')},
i18n: 'Download and Import'">
</button>
</div>
<script type="text/x-magento-init">
{
"*": {
"Magento_Ui/js/core/app": {
"components": {
"import": {
"component": "Amasty_Geoip/js/image-optimization",
"importItems": <?= /* @noEscape */ $block->getConfig(); ?>,
"initialDownloadPercent" : <?= (int)$block->getWidth() ?>
}
}
}
}
}
</script>
@@ -0,0 +1,55 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package GeoIP Data for Magento 2 (System)
*/
/**
* @var \Amasty\Geoip\Block\Adminhtml\Settings\Import $block
*/
?>
<div class="amgeoip-import-container" data-bind="scope: 'import'">
<div class="amgeoip-progressbar-container -import">
<span class="amgeoip-state -import" data-bind="css: {'-done': isDownloadCompleted()}">
<?= $block->escapeHtml(__('Import')) ?>
</span>
<span class="amgeoip-state -completed" data-bind="css: {'-done': importDone()}">
<?= $block->escapeHtml(__("Completed")) ?>
</span>
<div class="amgeoip-download-state">
<span class="amgeoip-begin -done" data-bind="css: {'-done': isDownloadCompleted()}"></span>
<div class="amgeoip-line-container">
<span class="amgeoip-counter -hidden"
data-bind="
attr: {'data-count': importCounter},
style: {left: importStatusWidth() + '%'},
css: {'-hidden': !isShowImportCounter()}"></span>
<div class="amgeoip-line"
data-bind="style: {width: importStatusWidth() + '%'}"
style="width: <?= (int)$block->getWidth() ?>%"></div>
</div>
<span class="<?= $block->escapeHtml($block->getImportedClass()) ?> amgeoip-label -endimport"
data-bind="css: {'-completed': importDone()}"></span>
</div>
</div>
<div class="amgeoip-files-container">
<div class="amgeoip-files <?= $block->getBlockFileExist() ? '-available' : '' ?>">
var/amasty/geoip/GeoLite2-City-Blocks-IPv4.csv
</div>
<div class="amgeoip-files <?= $block->getBlockV6FileExist() ? '-available' : '' ?>">
var/amasty/geoip/GeoLite2-City-Blocks-IPv6.csv
</div>
<div class="amgeoip-files <?= $block->getLocationFileExist() ? '-available' : '' ?>">
var/amasty/geoip/GeoLite2-City-Locations-en.csv
</div>
</div>
<button class="amgeoip-button action-default"
type="button"
data-bind="
disable: !initialStatus(),
click: initImport.bind($data),
i18n: 'Import',
attr: {title: $t('Import')}">
</button>
</div>
@@ -0,0 +1,2 @@
@import "module/_import";
@import "module/_variables";
+213
View File
@@ -0,0 +1,213 @@
//
// Geo Ip Import Styles
// ____________________________________________
//
// Common
// --------------------------------------------
& when (@media-common = true) {
.amgeoip-import-container {
.amgeoip-message {
color: #ff0000;
}
.amgeoip-button {
margin-top: 30px;
border: none;
border-radius: 3px;
background-color: #e3e3e3;
transition: background-color .3s ease-in;
}
.amgeoip-button:hover {
background: #ccc;
}
.amgeoip-state {
position: relative;
bottom: 8px;
padding: 0;
width: 80px;
height: 18px;
background: #fff;
color: #bbb;
vertical-align: middle;
text-align: center;
font-weight: 400;
}
.amgeoip-state.-done {
color: #514943;
font-weight: 600;
}
.amgeoip-state.-endimport {
left: 190px;
}
.amgeoip-state.-endimport.-done {
left: 184px;
}
.amgeoip-state.-import {
left: 94px;
}
}
.amgeoip-download-state {
& {
margin-left: 25px;
padding: 0 31px 0 27px;
width: 130px;
height: 28px;
}
&.-download {
position: relative;
bottom: 23px;
left: 155px;
}
.amgeoip-label {
position: relative;
z-index: 10;
padding: 14px 32px 4px 0;
}
.amgeoip-label.-import {
top: 21px;
right: 31px;
}
.amgeoip-label.-endimport {
bottom: 2px;
left: 128px;
}
}
.amgeoip-download-state,
.amgeoip-download-container {
& {
position: relative;
}
.amgeoip-begin {
position: relative;
right: 30px;
bottom: 1px;
z-index: 10;
padding-right: 33px;
padding-bottom: 28px;
background: @amgeoip-icon-step__initial__background no-repeat center;
}
.amgeoip-begin.-done {
background: @amgeoip-icon-download__background no-repeat center;
}
.amgeoip-counter {
position: absolute;
bottom: 9px;
left: 34%;
text-align: center;
}
.amgeoip-counter:before {
position: absolute;
right: ~'calc(100% - 17px)';
bottom: 0;
left: -17px;
width: 34px;
height: 21px;
background: @amgeoip-icon-counter__background no-repeat center;
content: attr(data-count);
line-height: 14px;
}
.amgeoip-counter.-hidden {
display: none;
}
}
.amgeoip-download-container {
position: relative;
left: 52px;
width: 130px;
}
.amgeoip-progressbar-container.-import {
.amgeoip-state.-completed {
top: 0;
left: 100px;
}
.amgeoip-state.-import {
top: 0;
left: 15px;
}
.amgeoip-download-container {
left: 0;
}
.amgeoip-download-state {
padding-bottom: 20px;
}
}
.amgeoip-line-container {
& {
position: relative;
top: 2px;
background: #e3e3e3;
}
.amgeoip-line {
position: relative;
height: 4px;
background-color: #2196f3;
background-size: 20px 20px;
white-space: nowrap;
}
}
.amgeoip-download-state .amgeoip-label.-failed,
.amgeoip-download-state .amgeoip-label {
background: @amgeoip-icon-step__initial__background no-repeat center;
}
.amgeoip-download-container .amgeoip-label.-completed,
.amgeoip-download-state .amgeoip-label.-completed {
background: @amgeoip-icon-step__finish__background no-repeat center;
}
.amgeoip-files-container {
& {
margin-top: 20px;
}
.amgeoip-files {
position: relative;
}
.amgeoip-files.-available {
padding-left: 25px;
}
.amgeoip-files.-available:before {
position: absolute;
top: 3px;
left: 0;
width: 16px;
height: 16px;
background: @amgeoip-icon__available no-repeat center;
content: '';
}
}
.amgeoip-import-date {
display: block;
margin-top: 15px;
color: #bbb;
}
}
@@ -0,0 +1,12 @@
//
// Geo Ip Variables
// ____________________________________________
//
// Variables
// --------------------------------------------
@amgeoip-icon-step__initial__background: url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzAiIGhlaWdodD0iMzAiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PGNpcmNsZSBjeD0iMTUiIGN5PSIxNSIgcj0iMTQuNSIgZmlsbD0iI2ZmZiIgc3Ryb2tlPSIjRTNFM0UzIi8+PC9zdmc+');
@amgeoip-icon-download__background: url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzAiIGhlaWdodD0iMzAiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PGNpcmNsZSBjeD0iMTUiIGN5PSIxNSIgcj0iMTUiIGZpbGw9IiMyMTk2RjMiLz48Y2lyY2xlIGN4PSIxNSIgY3k9IjE1IiByPSI1IiBmaWxsPSIjZmZmIi8+PC9zdmc+');
@amgeoip-icon-step__finish__background: url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNDIiIGhlaWdodD0iNDIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PGcgZmlsdGVyPSJ1cmwoI2ZpbHRlcjBfZCkiPjxjaXJjbGUgY3g9IjIxIiBjeT0iMTkiIHI9IjE1IiBmaWxsPSIjMjE5NkYzIi8+PC9nPjxwYXRoIGQ9Ik0yNi42NiAxNC4yMzVsLTguMDQgNy44NDctMy4yNC0zLjE1YS44MS44MSAwIDAwLTEuMTQgMCAuNzY4Ljc2OCAwIDAwMCAxLjExNWwzLjggMy43MThjLjE2LjE1Ny4zNi4yMzUuNTYuMjM1LjIgMCAuNC0uMDc4LjU2LS4yMzVsOC42LTguNDE1YS43NjguNzY4IDAgMDAwLTEuMTE1Yy0uMjgtLjMxMy0uOC0uMzEzLTEuMSAweiIgZmlsbD0iI2ZmZiIvPjxkZWZzPjxmaWx0ZXIgaWQ9ImZpbHRlcjBfZCIgeD0iMCIgeT0iMCIgd2lkdGg9IjQyIiBoZWlnaHQ9IjQyIiBmaWx0ZXJVbml0cz0idXNlclNwYWNlT25Vc2UiIGNvbG9yLWludGVycG9sYXRpb24tZmlsdGVycz0ic1JHQiI+PGZlRmxvb2QgZmxvb2Qtb3BhY2l0eT0iMCIgcmVzdWx0PSJCYWNrZ3JvdW5kSW1hZ2VGaXgiLz48ZmVDb2xvck1hdHJpeCBpbj0iU291cmNlQWxwaGEiIHZhbHVlcz0iMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMTI3IDAiLz48ZmVPZmZzZXQgZHk9IjIiLz48ZmVHYXVzc2lhbkJsdXIgc3RkRGV2aWF0aW9uPSIzIi8+PGZlQ29sb3JNYXRyaXggdmFsdWVzPSIwIDAgMCAwIDAuMTMzMzMzIDAgMCAwIDAgMC4xODE2NDcgMCAwIDAgMCAwLjQzNTI5NCAwIDAgMCAwLjQyIDAiLz48ZmVCbGVuZCBpbjI9IkJhY2tncm91bmRJbWFnZUZpeCIgcmVzdWx0PSJlZmZlY3QxX2Ryb3BTaGFkb3ciLz48ZmVCbGVuZCBpbj0iU291cmNlR3JhcGhpYyIgaW4yPSJlZmZlY3QxX2Ryb3BTaGFkb3ciIHJlc3VsdD0ic2hhcGUiLz48L2ZpbHRlcj48L2RlZnM+PC9zdmc+');
@amgeoip-icon-counter__background: url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNDYiIGhlaWdodD0iMzQiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PGcgZmlsdGVyPSJ1cmwoI2ZpbHRlcjBfZCkiPjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNOCA0YTIgMiAwIDAwLTIgMnYxNGEyIDIgMCAwMDIgMmgxMmwyLjIgMi45MzNhMSAxIDAgMDAxLjYgMEwyNiAyMmgxMmEyIDIgMCAwMDItMlY2YTIgMiAwIDAwLTItMkg4eiIgZmlsbD0iI2ZmZiIvPjwvZz48ZGVmcz48ZmlsdGVyIGlkPSJmaWx0ZXIwX2QiIHg9IjAiIHk9IjAiIHdpZHRoPSI0NiIgaGVpZ2h0PSIzMy4zMzMiIGZpbHRlclVuaXRzPSJ1c2VyU3BhY2VPblVzZSIgY29sb3ItaW50ZXJwb2xhdGlvbi1maWx0ZXJzPSJzUkdCIj48ZmVGbG9vZCBmbG9vZC1vcGFjaXR5PSIwIiByZXN1bHQ9IkJhY2tncm91bmRJbWFnZUZpeCIvPjxmZUNvbG9yTWF0cml4IGluPSJTb3VyY2VBbHBoYSIgdmFsdWVzPSIwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAxMjcgMCIvPjxmZU9mZnNldCBkeT0iMiIvPjxmZUdhdXNzaWFuQmx1ciBzdGREZXZpYXRpb249IjMiLz48ZmVDb2xvck1hdHJpeCB2YWx1ZXM9IjAgMCAwIDAgMC4xMzMzMzMgMCAwIDAgMCAwLjE4MDM5MiAwIDAgMCAwIDAuNDM1Mjk0IDAgMCAwIDAuMjIgMCIvPjxmZUJsZW5kIGluMj0iQmFja2dyb3VuZEltYWdlRml4IiByZXN1bHQ9ImVmZmVjdDFfZHJvcFNoYWRvdyIvPjxmZUJsZW5kIGluPSJTb3VyY2VHcmFwaGljIiBpbjI9ImVmZmVjdDFfZHJvcFNoYWRvdyIgcmVzdWx0PSJzaGFwZSIvPjwvZmlsdGVyPjwvZGVmcz48L3N2Zz4=');
@amgeoip-icon__available: url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0iTTEyLjA0MyA0LjE4OEw2LjMgMTAuNDY2bC0yLjMxNC0yLjUyYS41MzUuNTM1IDAgMDAtLjgxNSAwIC42NjYuNjY2IDAgMDAwIC44OTJsMi43MTUgMi45NzRhLjU0MS41NDEgMCAwMC40LjE4OC41NDEuNTQxIDAgMDAuNC0uMTg4bDYuMTQzLTYuNzMyYS42NjcuNjY3IDAgMDAwLS44OTIuNTA1LjUwNSAwIDAwLS43ODYgMHoiIGZpbGw9IiM2MUM4NTIiLz48L3N2Zz4=');
@@ -0,0 +1,213 @@
define([
'uiElement',
'jquery',
'mage/translate',
'Magento_Ui/js/modal/alert'
], function (Element, $, $t, message) {
'use strict';
return Element.extend({
defaults: {
importItems: [],
downloadStatusWidth: 0,
initialDownloadPercent: 0,
importStatusWidth: 0,
downloadCounter: '',
importCounter: '',
downloadStarted: false,
isDownloadCompleted: false,
initialStatus: false,
importDone: false,
isShowImportCounter: false,
isShowDownloadCounter: false,
message: '',
messages: {
upToDate: $t('GeoIp data is up-to-date.'),
error: $t('Error.')
}
},
initialize: function () {
this._super();
this.initialStatus(this.getInitialStatus());
this.downloadStatusWidth(this.initialDownloadPercent);
this.importStatusWidth(this.initialDownloadPercent);
this.importDone(this.initialStatus());
this.isDownloadCompleted(this.initialStatus());
this.downloadStep = 1;
this.urls = [];
this.isDownload = false;
},
initObservable: function () {
this._super().observe([
'downloadStatusWidth',
'downloadCounter',
'importStatusWidth',
'downloadStarted',
'isDownloadCompleted',
'importDone',
'importCounter',
'isShowImportCounter',
'isShowDownloadCounter',
'initialStatus',
'message'
]);
return this;
},
getInitialStatus: function () {
return !!this.initialDownloadPercent;
},
initImportAndDownload: function () {
this.initialStatus(false);
this.isDownloadCompleted(false);
this.importDone(false);
this.importStatusWidth(0);
this.importItems.each(function (item) {
this.runDownloading(item.start, item.process, item.commit, item.download);
}.bind(this));
},
initImport: function () {
this.importDone(false);
this.importStatusWidth(0);
this.importItems.each(function (item) {
this.run(item.start, item.process, item.commit, item.download);
}.bind(this));
},
runDownloading: function (startUrl, processUrl, commitUrl, startDownloadingUrl) {
this.isDownload = true;
this.isShowDownloadCounter(true);
this.downloadStarted(true);
this.downloadStatusWidth(30);
this.downloadCounter('0/3');
$.ajax({
url: startDownloadingUrl,
type: 'POST',
dataType: 'json',
data: { form_key: FORM_KEY }
}).done($.proxy(function (response) {
switch (response.status) {
case 'finish_downloading':
this.doneDownloading(startUrl, processUrl, commitUrl);
break;
case 'done':
this.isShowDownloadCounter(false);
this.downloadStatusWidth(100);
this.isDownloadCompleted(true);
this.importDone(true);
this.initialStatus(true);
this.importStatusWidth(100);
this.message(this.messages.upToDate);
break;
case response.error:
this.isShowDownloadCounter(false);
this.message(this.messages.error);
this.downloadStarted(false);
this.downloadStatusWidth(0);
message({ content: response.error });
break;
default:
this.isShowDownloadCounter(false);
this.downloadStarted(false);
}
}, this));
},
doneDownloading: function (startUrl, processUrl, commitUrl) {
if (this.downloadStep === 3) {
this.downloadStatusWidth(100);
this.isDownloadCompleted(true);
this.isShowDownloadCounter(false);
this.urls.each(function (type) {
this.run(type[0], type[1], type[2]);
}.bind(this));
return this.run(startUrl, processUrl, commitUrl);
}
this.downloadStatusWidth(this.downloadStep * 30);
this.downloadCounter(this.downloadStep + '/3');
this.urls.push([startUrl, processUrl, commitUrl]);
this.downloadStep++;
},
run: function (startUrl, processUrl, commitUrl) {
$.ajax({
url: startUrl,
type: 'POST',
dataType: 'json',
data: { form_key: FORM_KEY, is_download: this.isDownload }
}).done(function (response) {
if (response.status === 'started') {
this.isShowImportCounter(true);
this.importCounter('0%');
this.process(processUrl, commitUrl);
} else if (response.error) {
this.importError(response);
}
}.bind(this));
},
process: function (processUrl, commitUrl) {
$.ajax({
url: processUrl,
type: 'POST',
dataType: 'json',
data: { form_key: FORM_KEY }
}).done(function (response) {
if (response.status == 'processing') {
if (response.type === 'block') {
this.importStatusWidth(response.position);
this.importCounter(response.position + '%');
}
if (response.position == 100) {
return this.commit(commitUrl);
}
this.process(processUrl, commitUrl);
} else if (response.error) {
this.importError(response);
}
}.bind(this));
},
commit: function (commitUrl) {
$.ajax({
url: commitUrl,
type: 'POST',
dataType: 'json',
data: { form_key: FORM_KEY }
}).done(function (response) {
if (response.status == 'done') {
this.done(response);
}
}.bind(this));
},
done: function (response) {
if (response.full_import_done == 1) {
location.reload();
}
},
importError: function (response) {
this.isShowImportCounter(false);
this.message(this.messages.error);
this.importDone(false);
this.importCounter(0);
message({ content: response.error });
}
});
});