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
+70
View File
@@ -0,0 +1,70 @@
<?php
/**
* Plumrocket Inc.
*
* NOTICE OF LICENSE
*
* This source file is subject to the End-user License Agreement
* that is available through the world-wide-web at this URL:
* http://wiki.plumrocket.net/wiki/EULA
* If you are unable to obtain it through the world-wide-web, please
* send an email to support@plumrocket.com so we can send you a copy immediately.
*
* @package Plumrocket_GeoIPLookup
* @copyright Copyright (c) 2020 Plumrocket Inc. (http://www.plumrocket.com)
* @license http://wiki.plumrocket.net/wiki/EULA End-user License Agreement
*/
namespace Plumrocket\GeoIPLookup\Model\Api;
use Plumrocket\GeoIPLookup\Api\GeoIPLookupInterface;
class GeoIPLookup implements GeoIPLookupInterface
{
/**
* @var \Plumrocket\GeoIPLookup\Model\GeoIPLookup
*/
private $geoIPLookup;
/**
* GeoIPLookup constructor.
*
* @param \Plumrocket\GeoIPLookup\Model\GeoIPLookup $geoIPLookup
*/
public function __construct(
\Plumrocket\GeoIPLookup\Model\GeoIPLookup $geoIPLookup
) {
$this->geoIPLookup = $geoIPLookup;
}
/**
* Returns GeoIpData with posibility change priority of services
*
* @param string $ip
* @param string $params
* @api
* @return string|array
*/
public function getGeoIpData($ip, $params = '')
{
$paramsArray = [];
if (!empty($params)) {
$paramsArray = explode(',', $params);
}
return [$this->geoIPLookup->getGeoLocation($ip, $paramsArray)];
}
/**
* Returns GeoIpData
*
* @param string $ip
* @api
* @return string|array
*/
public function getGeoIpDataWithDefaultServices($ip)
{
return [$this->geoIPLookup->getGeoLocation($ip)];
}
}
@@ -0,0 +1,34 @@
<?php
/**
* Plumrocket Inc.
*
* NOTICE OF LICENSE
*
* This source file is subject to the End-user License Agreement
* that is available through the world-wide-web at this URL:
* http://wiki.plumrocket.net/wiki/EULA
* If you are unable to obtain it through the world-wide-web, please
* send an email to support@plumrocket.com so we can send you a copy immediately.
*
* @package Plumrocket_GeoIPLookup
* @copyright Copyright (c) 2020 Plumrocket Inc. (http://www.plumrocket.com)
* @license http://wiki.plumrocket.net/wiki/EULA End-user License Agreement
*/
namespace Plumrocket\GeoIPLookup\Model\Cache;
/**
* @since 1.2.2
*/
interface GeoIpInterface
{
/**
* @return mixed
*/
public function get();
/**
* @param $data
*/
public function set($data);
}
@@ -0,0 +1,64 @@
<?php
/**
* Plumrocket Inc.
*
* NOTICE OF LICENSE
*
* This source file is subject to the End-user License Agreement
* that is available through the world-wide-web at this URL:
* http://wiki.plumrocket.net/wiki/EULA
* If you are unable to obtain it through the world-wide-web, please
* send an email to support@plumrocket.com so we can send you a copy immediately.
*
* @package Plumrocket_Csp
* @copyright Copyright (c) 2020 Plumrocket Inc. (http://www.plumrocket.com)
* @license http://wiki.plumrocket.net/wiki/EULA End-user License Agreement
*/
declare(strict_types=1);
namespace Plumrocket\GeoIPLookup\Model\Cache;
use Magento\Framework\Session\SessionManagerInterface;
/**
* @since 1.2.2
*/
class Session implements GeoIpInterface
{
/**
* @var \Magento\Framework\Session\SessionManagerInterface
*/
private $sessionManager;
/**
* @param \Magento\Framework\Session\SessionManagerInterface $sessionManager
*/
public function __construct(SessionManagerInterface $sessionManager)
{
$this->sessionManager = $sessionManager;
}
/**
* @return mixed
*/
public function get()
{
$sessionData = $this->sessionManager->getPrGeoipData();
$result = [];
if (!empty($sessionData) && is_array($sessionData)) {
$result = $sessionData;
}
return $result;
}
/**
* @param $data
*/
public function set($data)
{
$this->sessionManager->setPrGeoipData($data);
}
}
@@ -0,0 +1,393 @@
<?php
/**
* Plumrocket Inc.
*
* NOTICE OF LICENSE
*
* This source file is subject to the End-user License Agreement
* that is available through the world-wide-web at this URL:
* http://wiki.plumrocket.net/wiki/EULA
* If you are unable to obtain it through the world-wide-web, please
* send an email to support@plumrocket.com so we can send you a copy immediately.
*
* @package Plumrocket_GeoIPLookup
* @copyright Copyright (c) 2018 Plumrocket Inc. (http://www.plumrocket.com)
* @license http://wiki.plumrocket.net/wiki/EULA End-user License Agreement
*/
namespace Plumrocket\GeoIPLookup\Model\Data\Import;
use Magento\Directory\Model\ResourceModel\Country\CollectionFactory;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\File\Csv;
use Magento\Framework\Filesystem;
use Magento\Framework\Filesystem\Io\File;
use Magento\Framework\HTTP\Client\Curl;
use Magento\Framework\Stdlib\DateTime\DateTime;
use Plumrocket\GeoIPLookup\Helper\Config;
use Plumrocket\GeoIPLookup\Model\MmdbReader;
class AbstractModel
{
/**
* @var int
*/
public $steps = 1;
/**
* @var int
*/
public $step = 1;
/**
* @var string
*/
public $dataName = '';
/**
* @var string
*/
public $fileName = '';
/**
* @var string
*/
public $dataLabel = '';
/**
* @var string
*/
public $pathSourceFile = '';
/**
* @var string
*/
public $pathVersionsFile = Config::PATH_VERSION_FILE;
/**
* @var string
*/
public $versionsFileName = 'versions.csv';
/**
* @var string
*/
public $progressFileName = 'progress.csv';
/**
* @var \Magento\Directory\Model\ResourceModel\Country\Collection/null
*/
public $countryCollection = null;
/**
* @var \Magento\Framework\Filesystem\Io\File
*/
private $ioFile;
/**
* @var \Magento\Framework\Filesystem
*/
private $filesystem;
/**
* @var \Magento\Framework\File\Csv
*/
private $csv;
/**
* @var \Magento\Framework\Stdlib\DateTime\DateTime
*/
private $date;
/**
* @var \Magento\Framework\HTTP\Client\Curl
*/
private $curl;
/**
* @var \Magento\Directory\Model\ResourceModel\Country\CollectionFactory
*/
public $countryCollectionFactory;
/**
* @var \Plumrocket\GeoIPLookup\Model\MmdbReader
*/
private $mmdbReader;
/**
* AbstractModel constructor.
*
* @param \Magento\Framework\Filesystem\Io\File $ioFile
* @param \Magento\Framework\Filesystem $filesystem
* @param \Magento\Framework\File\Csv $csv
* @param \Magento\Framework\Stdlib\DateTime\DateTime $date
* @param \Magento\Framework\HTTP\Client\Curl $curl
* @param \Magento\Directory\Model\ResourceModel\Country\CollectionFactory $countryCollectionFactory
* @param \Plumrocket\GeoIPLookup\Model\MmdbReader $mmdbReader
*/
public function __construct(
File $ioFile,
Filesystem $filesystem,
Csv $csv,
DateTime $date,
Curl $curl,
CollectionFactory $countryCollectionFactory,
MmdbReader $mmdbReader
) {
$this->ioFile = $ioFile;
$this->filesystem = $filesystem;
$this->csv = $csv;
$this->date = $date;
$this->curl = $curl;
$this->countryCollectionFactory = $countryCollectionFactory;
$this->mmdbReader = $mmdbReader;
}
/**
* @param $url
* @return float|int
*/
public function retrieveRemoteFileSize($url)
{
$contentLength = 0;
$this->curl->setOptions([
CURLOPT_NOBODY => true,
CURLOPT_HEADER => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true
]);
$this->curl->get($url);
$data = $this->curl->getBody();
if ($data) {
$status = 404;
if (preg_match("/^HTTP\/1\.[01] (\d\d\d)/", $data, $matches)) {
$status = (int)$matches[1];
}
if (($status > 300 && $status <= 308)
|| (preg_match("/Content-Length: (\d+)/", $data, $matches) && $status === 200)
) {
$contentLength = (int)$matches[1];
}
}
return $contentLength;
}
/**
* @return array
*/
public function autoImportData(): array
{
set_time_limit(0);
$copyFile = false;
$importProgress = [
'status' => 'process',
'total' => 100,
'exec' => 1,
'step' => $this->step,
'message' => __('Download in Progress...'),
'remote_file_size' => $this->retrieveRemoteFileSize($this->pathSourceFile),
'local_file_name' => $this->getDataFile()
];
$this->setProgress($importProgress);
if ($this->ioFile->fileExists($this->getDataFile(), true)) {
$copyFile = true;
} else {
$this->ioFile->setAllowCreateFolders(true);
if ($this->ioFile->createDestinationDir($this->getDataPath())) {
$copyFile = $this->ioFile->cp($this->getPathSourceFile(), $this->getDataFile());
}
}
$this->mmdbReader->refresh();
$result = [
'status' => 'success',
'message' => $this->getInstalledMessage()
];
if (! $copyFile) {
$lastError = error_get_last();
$result = ['status' => 'fail', 'message' => $lastError['message']];
}
return $result;
}
/**
* @return string
*/
private function getPathSourceFile(): string
{
if (!empty($this->pathSourceFile)) {
$this->pathSourceFile .= '?t=' . $this->date->gmtTimestamp();
}
return $this->pathSourceFile;
}
/**
* @param $importProgress
*/
public function setProgress($importProgress)
{
$this->ioFile->setAllowCreateFolders(true);
if ($this->ioFile->createDestinationDir($this->getDataPath())) {
$this->csv->saveData(
$this->getProgressFile(),
[$importProgress]
);
}
}
/**
* @return array
*/
public function getProgress()
{
if ($this->ioFile->fileExists($this->getProgressFile(), true)) {
$csvData = $this->csv->getData($this->getProgressFile());
if (isset($csvData[0][6])
&& isset($csvData[0][5])
&& $this->ioFile->fileExists($csvData[0][6])
) {
$total = $csvData[0][5];
$exec = filesize($csvData[0][6]);
} else {
$total = (int)$csvData[0][1];
$exec = (int)$csvData[0][2];
}
$importProgress = [
'status' => $csvData[0][0],
'total' => $total,
'exec' => $exec,
'step' => (int)$csvData[0][3],
'message' => $csvData[0][4]
];
} else {
$importProgress = [
'status' => 'process',
'total' => 100,
'exec' => 1,
'step' => $this->step,
'message' => __('Download in Progress...')
];
}
return $importProgress;
}
/**
* @return mixed
*/
public function getInstalledVersion()
{
return ($metadata = $this->mmdbReader->metadata()) ? $metadata['buildDate'] : null;
}
/**
* @return string
*/
public function getInstalledMessage(): string
{
$metadata = $this->mmdbReader->metadata();
return $metadata ? (string)__(
'Installed Database - %1 (Build Date: %2)',
$metadata['databaseType'],
$metadata['buildDate']
) : '';
}
/**
* @return bool|mixed
*/
public function isLatestInstalledVersion()
{
$result = false;
$installedBuildDate = $this->getInstalledVersion();
if (!$installedBuildDate) {
return false;
}
$existVersion = null;
$copyFile = false;
$this->ioFile->setAllowCreateFolders(true);
if ($this->ioFile->createDestinationDir($this->getDataPath())) {
$copyFile = $this->ioFile->cp($this->pathVersionsFile, $this->getVersionsFile());
}
if ($copyFile) {
$csvData = $this->csv->getData($this->getVersionsFile());
foreach ($csvData as $data) {
if ($data[0] == $this->getDataName()) {
$existVersion = [
'data_name' => $data[0],
'file_date' => $data[1]
];
break;
}
}
$this->ioFile->rm($this->getVersionsFile());
if ($existVersion) {
$result = strtotime($existVersion['file_date']) === strtotime($installedBuildDate);
}
}
return $result;
}
/**
* @return string
*/
public function getDataName(): string
{
return $this->dataName;
}
/**
* @return string
*/
public function getDataLabel()
{
return $this->dataLabel;
}
/**
* @return string
*/
public function getDataPath()
{
return $this->filesystem->getDirectoryRead(DirectoryList::MEDIA)
->getAbsolutePath(Config::LOCAL_PATH);
}
/**
* @return string
*/
public function getDataFile()
{
return $this->getDataPath() . $this->fileName;
}
/**
* @return string
*/
public function getVersionsFile()
{
return $this->getDataPath() . $this->versionsFileName;
}
/**
* @return string
*/
public function getProgressFile()
{
return $this->getDataPath() . $this->progressFileName;
}
}
@@ -0,0 +1,43 @@
<?php
/**
* Plumrocket Inc.
*
* NOTICE OF LICENSE
*
* This source file is subject to the End-user License Agreement
* that is available through the world-wide-web at this URL:
* http://wiki.plumrocket.net/wiki/EULA
* If you are unable to obtain it through the world-wide-web, please
* send an email to support@plumrocket.com so we can send you a copy immediately.
*
* @package Plumrocket_GeoIPLookup
* @copyright Copyright (c) 2018 Plumrocket Inc. (http://www.plumrocket.com)
* @license http://wiki.plumrocket.net/wiki/EULA End-user License Agreement
*/
namespace Plumrocket\GeoIPLookup\Model\Data\Import;
use Plumrocket\GeoIPLookup\Helper\Config;
class Iptocountry extends AbstractModel
{
/**
* @var string
*/
public $dataLabel = 'IpToCountry GeoIP Database';
/**
* @var string
*/
public $dataName = Config::IPTOCOUNTRY_DATABASE_NAME;
/**
* @var string
*/
public $pathSourceFile = Config::IPTOCOUNTRY_SOURCE_FILE_URL;
/**
* @var string
*/
public $fileName = Config::IPTOCOUNTRY_SOURCE_FILE_NAME;
}
@@ -0,0 +1,43 @@
<?php
/**
* Plumrocket Inc.
*
* NOTICE OF LICENSE
*
* This source file is subject to the End-user License Agreement
* that is available through the world-wide-web at this URL:
* http://wiki.plumrocket.net/wiki/EULA
* If you are unable to obtain it through the world-wide-web, please
* send an email to support@plumrocket.com so we can send you a copy immediately.
*
* @package Plumrocket_GeoIPLookup
* @copyright Copyright (c) 2018 Plumrocket Inc. (http://www.plumrocket.com)
* @license http://wiki.plumrocket.net/wiki/EULA End-user License Agreement
*/
namespace Plumrocket\GeoIPLookup\Model\Data\Import;
use Plumrocket\GeoIPLookup\Helper\Config;
class Maxmindgeoip extends AbstractModel
{
/**
* @var string
*/
public $dataLabel = 'Maxmind GeoIP Database';
/**
* @var string
*/
public $dataName = Config::MAXMIND_DATABASE_NAME;
/**
* @var string
*/
public $pathSourceFile = Config::MAXMIND_SOURCE_FILE_URL;
/**
* @var string
*/
public $fileName = Config::MAXMIND_SOURCE_FILE_NAME;
}
+258
View File
@@ -0,0 +1,258 @@
<?php
/**
* Plumrocket Inc.
*
* NOTICE OF LICENSE
*
* This source file is subject to the End-user License Agreement
* that is available through the world-wide-web at this URL:
* http://wiki.plumrocket.net/wiki/EULA
* If you are unable to obtain it through the world-wide-web, please
* send an email to support@plumrocket.com so we can send you a copy immediately.
*
* @package Plumrocket_GeoIPLookup
* @copyright Copyright (c) 2018 Plumrocket Inc. (http://www.plumrocket.com)
* @license http://wiki.plumrocket.net/wiki/EULA End-user License Agreement
*/
namespace Plumrocket\GeoIPLookup\Model;
use Plumrocket\GeoIPLookup\Helper\Config;
use Plumrocket\GeoIPLookup\Model\Validator\IsEuropeanUnionCountry;
class GeoIPLookup
{
/**
* @var string
*/
const MAXMIND = 'maxmind';
/**
* @var string
*/
const IPTOCOUNTRY = 'iptocountry';
/**
* @var string
*/
const IPAPI = 'ipapi';
/**
* @var \Plumrocket\GeoIPLookup\Api\GeoIpServiceInterface[]
*/
private $geoIpModels = [];
/**
* @var \Plumrocket\GeoIPLookup\Helper\Config
*/
private $config;
/**
* @var \Plumrocket\GeoIPLookup\Model\Validator\IsEuropeanUnionCountry
*/
private $isEuropeanUnionCountry;
/**
* @var \Plumrocket\GeoIPLookup\Api\GeoIpServiceInterface[]
*/
private $geoIpServices;
/**
* @param \Plumrocket\GeoIPLookup\Helper\Config $config
* @param \Plumrocket\GeoIPLookup\Model\Validator\IsEuropeanUnionCountry $isEuropeanUnionCountry
* @param \Plumrocket\GeoIPLookup\Api\GeoIpServiceInterface[] $geoIpServices
*/
public function __construct(
Config $config,
IsEuropeanUnionCountry $isEuropeanUnionCountry,
array $geoIpServices
) {
$this->config = $config;
$this->isEuropeanUnionCountry = $isEuropeanUnionCountry;
$this->geoIpServices = $geoIpServices;
}
/**
* @return bool
*/
public function canUse(): bool
{
return $this->config->isConfiguredForUse();
}
/**
* @param int $ip
* @param array $priorityOfServices
* @return bool
*/
public function isInEuropeanUnion($ip = 0, $priorityOfServices = []): bool
{
return $this->isEuropeanUnionCountry->validate(
$this->getCountryCode($ip, $priorityOfServices)
);
}
/**
* @param int $ip
* @return array|string
*/
public function getGeoLocation($ip = 0, $priorityOfServices = [])
{
$result = null;
$geoIpModels = $this->getGeoIpModels($priorityOfServices);
if ($geoIpModels) {
foreach ($geoIpModels as $geoIpModel) {
$result = $geoIpModel->getGeoLocation($ip);
if ($result) {
break;
}
}
}
if (!empty($result) && !isset($result['is_in_european_union'])) {
$result['is_in_european_union'] = $this->isInEuropeanUnion($ip);
}
return (!empty($result)) ? $result : __('No records found')->getText();
}
/**
* @param int $ip
* @return null
*/
public function getCountryCode($ip = 0, $priorityOfServices = [])
{
$result = null;
$geoIpModels = $this->getGeoIpModels($priorityOfServices);
foreach ($geoIpModels as $geoIpModel) {
$result = $geoIpModel->getCountryCode($ip);
if ($result) {
break;
}
}
return (!empty($result)) ? $result : null;
}
/**
* @return array|null
*/
public function getGeoIpModels($priorityOfServices = [])
{
$serviceItems = [];
if (! $this->config->isModuleEnabled()) {
return null;
}
if (!empty($this->geoIpModels)) {
return $this->geoIpModels;
}
$services = [
self::MAXMIND => [
'model' => $this->geoIpServices['MaxMind'],
'enabled' => $this->config->enabledMaxmindGeoIp()
],
self::IPTOCOUNTRY => [
'model' => $this->geoIpServices['IpToCountry'],
'enabled' => $this->config->enabledIpToCountryGeoIp()
],
self::IPAPI => [
'model' => $this->geoIpServices['IpApi'],
'enabled' => $this->config->enabledIpApiGeoIp()
]
];
if (!empty($priorityOfServices)) {
foreach ($priorityOfServices as $sId) {
if (!empty($services[$sId])) {
$serviceItems[$sId] = $services[$sId];
}
}
} else {
$serviceItems = $services;
}
foreach ($serviceItems as $service) {
if ($service['enabled']) {
$this->geoIpModels[] = $service['model'];
}
}
return $this->geoIpModels;
}
/**
* @param $ip
* @return array
*/
public function geoIpLookupTest($ip)
{
$fields = [
'continent_code' => __('Continent'),
'continent_name' => __('Continent Code'),
'country_name' => __('Country'),
'country_code' => __('Country Code'),
'region_name' => __('Region Name'),
'city_name' => __('City'),
'postal_code' => __('Postal Code'),
'time_zone' => __('Time Zone'),
'is_in_european_union' => __('Is In European Union'),
'latitude' => __('Latitude'),
'longitude' => __('Longitude'),
'metro_code' => __('Metro Code'),
'subdivision_1_iso_code' => __('Subdivision 1 Iso Code'),
'subdivision_1_name' => __('Subdivision 1 Name'),
'subdivision_2_iso_code' => __('Subdivision 2 Iso Code'),
'subdivision_2_name' => __('Subdivision 2 Name'),
'database_name' => __('Database Name')
];
$result = [];
$text = '';
$geoData = $this->getGeoLocation($ip);
if (is_array($geoData)) {
$geoData['is_in_european_union'] = ($geoData['is_in_european_union'] === true) ? 'true' : 'false';
foreach ($fields as $key => $value) {
if (array_key_exists($key, $geoData) && !empty($geoData[$key])) {
$text .= $value . ": " . $geoData[$key] . "\n";
}
}
if (!empty($geoData['latitude']) && !empty($geoData['longitude'])) {
$result['latitude'] = $geoData['latitude'];
$result['longitude'] = $geoData['longitude'];
} elseif (!empty($geoData['country_name'])) {
$result['country_name'] = $geoData['country_name'];
}
} else {
$text = $geoData;
}
$result['text'] = $text;
return $result;
}
/**
* @param int $ip
* @param array $priorityOfServices
* @return null
*/
public function getCurrentCountryState($ip = 0, $priorityOfServices = [])
{
$result = null;
$geoIpModels = $this->getGeoIpModels($priorityOfServices);
foreach ($geoIpModels as $geoIpModel) {
$result = $geoIpModel->getCurrentCountryState($ip);
if ($result) {
break;
}
}
return (!empty($result)) ? $result : null;
}
}
@@ -0,0 +1,109 @@
<?php
/**
* Plumrocket Inc.
*
* NOTICE OF LICENSE
*
* This source file is subject to the End-user License Agreement
* that is available through the world-wide-web at this URL:
* http://wiki.plumrocket.net/wiki/EULA
* If you are unable to obtain it through the world-wide-web, please
* send an email to support@plumrocket.com so we can send you a copy immediately.
*
* @package Plumrocket_GeoIPLookup
* @copyright Copyright (c) 2020 Plumrocket Inc. (http://www.plumrocket.com)
* @license http://wiki.plumrocket.net/wiki/EULA End-user License Agreement
*/
declare(strict_types=1);
namespace Plumrocket\GeoIPLookup\Model;
use Magento\Framework\Exception\LocalizedException;
use Plumrocket\GeoIPLookup\Api\GeoLocationValidatorInterface;
use Plumrocket\GeoIPLookup\Api\LocationsListInterface;
/**
* @since 1.2.0
*/
class GeoLocationValidator implements GeoLocationValidatorInterface
{
/**
* @var \Plumrocket\GeoIPLookup\Model\GeoIPLookup
*/
private $geoIPLookup;
/**
* @var \Plumrocket\GeoIPLookup\Api\LocationsListInterface
*/
private $locationsList;
/**
* ValidateLocation constructor.
*
* @param \Plumrocket\GeoIPLookup\Model\GeoIPLookup $geoIPLookup
* @param \Plumrocket\GeoIPLookup\Api\LocationsListInterface $locationsList
*/
public function __construct(GeoIPLookup $geoIPLookup, LocationsListInterface $locationsList)
{
$this->geoIPLookup = $geoIPLookup;
$this->locationsList = $locationsList;
}
/**
* @inheritDoc
*/
public function validate(array $regions, array $counties, array $usaStates = [], ?string $ip = null): bool
{
if (! $this->geoIPLookup->canUse()) {
throw new LocalizedException(
__('Plumrocket IP Geolocation Lookup is disabled or no one GeoIP databases is enabled')
);
}
if ((empty($regions) && empty($counties))
|| in_array(LocationsListInterface::ALL, $regions, true)
) {
return true;
}
if (in_array(LocationsListInterface::EU, $regions, true) && $this->geoIPLookup->isInEuropeanUnion()) {
return true;
}
$countryCode = $this->geoIPLookup->getCountryCode();
if (null !== $countryCode) {
if ($usaStates && LocationsListInterface::COUNTRY_CODE_USA === $countryCode) {
return in_array($this->geoIPLookup->getCurrentCountryState(), $usaStates, true);
}
return in_array($countryCode, $counties, true);
}
if (in_array(LocationsListInterface::UNKNOWN, $regions, true)) {
return true;
}
return false;
}
/**
* @inheritDoc
*/
public function validateByMergedOptions(array $options, array $usaStates = [], ?string $ip = null): bool
{
$allRegionsKey = array_column($this->locationsList->getRegions(), 'value');
$regions = [];
$counties = [];
foreach ($options as $option) {
if (in_array($option, $allRegionsKey, true)) {
$regions[] = $option;
} else {
$counties[] = $option;
}
}
return $this->validate($regions, $counties, $usaStates, $ip);
}
}
@@ -0,0 +1,113 @@
<?php
/**
* Plumrocket Inc.
*
* NOTICE OF LICENSE
*
* This source file is subject to the End-user License Agreement
* that is available through the world-wide-web at this URL:
* http://wiki.plumrocket.net/wiki/EULA
* If you are unable to obtain it through the world-wide-web, please
* send an email to support@plumrocket.com so we can send you a copy immediately.
*
* @package Plumrocket_GeoIPLookup
* @copyright Copyright (c) 2020 Plumrocket Inc. (http://www.plumrocket.com)
* @license http://wiki.plumrocket.net/wiki/EULA End-user License Agreement
*/
declare(strict_types=1);
namespace Plumrocket\GeoIPLookup\Model;
use Magento\Directory\Model\Config\Source\Allregion;
use Magento\Directory\Model\Config\Source\Country;
use Plumrocket\GeoIPLookup\Api\LocationsListInterface;
/**
* @since 1.2.0
*/
class LocationsList implements LocationsListInterface
{
/**
* @var \Magento\Directory\Model\Config\Source\Country
*/
private $directoryCountry;
/**
* @var \Magento\Directory\Model\Config\Source\Allregion
*/
private $directoryRegion;
/**
* LocationsList constructor.
*
* @param \Magento\Directory\Model\Config\Source\Country $directoryCountry
* @param \Magento\Directory\Model\Config\Source\Allregion $directoryRegion
*/
public function __construct(
Country $directoryCountry,
Allregion $directoryRegion
) {
$this->directoryCountry = $directoryCountry;
$this->directoryRegion = $directoryRegion;
}
/**
* @inheritDoc
*/
public function getRegions(): array
{
return [
[
'value' => self::ALL,
'label' => __('Show to all site visitors'),
],
[
'value' => self::EU,
'label' => __('Only visitors from EU countries'),
],
[
'value' => self::UNKNOWN,
'label' => __('Unknown'),
],
];
}
/**
* @inheritDoc
*/
public function getCountries(): array
{
return $this->directoryCountry->toOptionArray(true);
}
/**
* @inheritDoc
*/
public function getCountryStates(string $countryName): array
{
$allRegions = $this->directoryRegion->toOptionArray();
$result = [];
foreach ($allRegions as $region) {
if ($region['label'] === $countryName) {
$regionOptions = $region['value'];
$result[] = [
'value' => self::ALL,
'label' => __('Show to all states')
];
foreach ($regionOptions as $regionOption) {
$result[] = [
'value' => $regionOption['label'],
'label' => $regionOption['label']
];
}
break;
}
}
return $result;
}
}
@@ -0,0 +1,175 @@
<?php
/**
* @package Plumrocket_GeoIPLookup
* @copyright Copyright (c) 2024 Plumrocket Inc. (https://plumrocket.com)
* @license https://plumrocket.com/license/ End-user License Agreement
*/
declare(strict_types=1);
namespace Plumrocket\GeoIPLookup\Model;
use Exception;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Exception\InvalidArgumentException;
use Magento\Framework\Filesystem;
use Plumrocket\GeoIPLookup\Helper\Config;
use Plumrocket\GeoIPLookup\Library\Mmdb\Reader;
/**
* @since 2.0.0
*/
class MmdbReader
{
/**
* @var \Magento\Framework\Filesystem
*/
private $filesystem;
/**
* @var string
*/
private $fileName;
/**
* @var string
*/
private $databaseName;
/**
* @var array
*/
private $fieldsMap;
/**
* @var \Plumrocket\GeoIPLookup\Library\Mmdb\Reader
*/
private $readerApi;
/**
* @var bool
*/
private $isDatabaseExists;
/**
* @param \Magento\Framework\Filesystem $filesystem
* @param string $fileName
* @param string $databaseName
* @param array $fieldsMap
* @throws \Magento\Framework\Exception\InvalidArgumentException
*/
public function __construct(
Filesystem $filesystem,
string $fileName = '',
string $databaseName = '',
array $fieldsMap = []
) {
if (!$fileName) {
throw new InvalidArgumentException(
__('Missing database. Use virtualType for set up database file.')
);
}
$this->filesystem = $filesystem;
$this->fileName = $fileName;
$this->databaseName = $databaseName;
$this->fieldsMap = $fieldsMap;
$this->createReader();
}
/**
* @param string $ipAddress
* @return array
* @throws \Plumrocket\GeoIPLookup\Library\Mmdb\Reader\InvalidDatabaseException
*/
public function get(string $ipAddress): array
{
if (!$this->isDatabaseExists) {
return [];
}
return $this->mapFields($this->readerApi->get($ipAddress));
}
/**
* @return array|null
*/
public function metadata(): ?array
{
if (!$this->isDatabaseExists) {
return null;
}
$metadata = $this->readerApi->metadata();
return [
'databaseType' => $metadata->databaseType,
'buildDate' => date('F d, Y', $metadata->buildEpoch)
];
}
/**
* @return MmdbReader
*/
public function refresh(): MmdbReader
{
$this->createReader();
return $this;
}
/**
* @return void
*/
private function createReader(): void
{
$database = $this->filesystem->getDirectoryRead(DirectoryList::MEDIA)
->getAbsolutePath(Config::LOCAL_PATH) . $this->fileName;
try {
$this->readerApi = new Reader($database);
$this->isDatabaseExists = true;
} catch (Exception $e) {
$this->isDatabaseExists = false;
}
}
/**
* @param array|null $ipData
* @return array[]|null
*/
private function mapFields(?array $ipData): ?array
{
if (! $ipData) {
return $ipData;
}
$result = ! $this->fieldsMap ? $ipData : [];
foreach ($this->fieldsMap as $resultFieldKey => $map) {
$mapPath = explode('.', $map);
$tmpValue = $ipData;
$i = 0;
do {
if (isset($tmpValue[$mapPath[$i]])) {
if (is_array($tmpValue[$mapPath[$i]])) {
$tmpValue = $tmpValue[$mapPath[$i]];
$i++;
continue;
}
$result[$resultFieldKey] = $tmpValue[$mapPath[$i]];
} else {
$result[$resultFieldKey] = '';
}
$i++;
} while (isset($mapPath[$i], $tmpValue[$mapPath[$i]]) && ! isset($result[$resultFieldKey]));
}
$result['database_name'] = $this->databaseName;
return $result;
}
}
@@ -0,0 +1,148 @@
<?php
/**
* @package Plumrocket_GeoIPLookup
* @copyright Copyright (c) 2024 Plumrocket Inc. (https://plumrocket.com)
* @license https://plumrocket.com/license/ End-user License Agreement
*/
namespace Plumrocket\GeoIPLookup\Model\Services;
use Magento\Framework\HTTP\PhpEnvironment\RemoteAddress;
use Plumrocket\GeoIPLookup\Api\GeoIpServiceInterface;
use Plumrocket\GeoIPLookup\Library\Mmdb\Reader\InvalidDatabaseException;
use Plumrocket\GeoIPLookup\Model\Cache\GeoIpInterface;
use Plumrocket\GeoIPLookup\Model\MmdbReader;
/**
* @since 2.0.0
*/
class AbstractMmdb implements GeoIpServiceInterface
{
/**
* @var \Magento\Framework\HTTP\PhpEnvironment\RemoteAddress
*/
private $remoteAddress;
/**
* @var \Plumrocket\GeoIPLookup\Model\Cache\GeoIpInterface
*/
private $geoIpCache;
/**
* @var \Plumrocket\GeoIPLookup\Model\MmdbReader
*/
private $mmdbReader;
/**
* @var array
*/
private $cacheKeyPostfixes;
/**
* @param \Magento\Framework\HTTP\PhpEnvironment\RemoteAddress $remoteAddress
* @param \Plumrocket\GeoIPLookup\Model\Cache\GeoIpInterface $geoIpCache
* @param \Plumrocket\GeoIPLookup\Model\MmdbReader $mmdbReader
* @param array $cacheKeyPostfixes
*/
public function __construct(
RemoteAddress $remoteAddress,
GeoIpInterface $geoIpCache,
MmdbReader $mmdbReader,
array $cacheKeyPostfixes
) {
$this->remoteAddress = $remoteAddress;
$this->geoIpCache = $geoIpCache;
$this->mmdbReader = $mmdbReader;
$this->cacheKeyPostfixes = $cacheKeyPostfixes;
}
/**
* @inheritDoc
*/
public function getGeoLocation(?string $ip): ?array
{
if (! $ip) {
$ip = $this->remoteAddress->getRemoteAddress();
}
if ($ip) {
$cacheKey = $ip . $this->cacheKeyPostfixes[$this->getShortMethodName(__METHOD__)];
$geoIpCache = $this->geoIpCache->get();
if (isset($geoIpCache[$cacheKey])) {
return $geoIpCache[$cacheKey];
}
try {
$result = $this->mmdbReader->get($ip);
} catch (InvalidDatabaseException $e) {
$result = null;
}
$geoIpCache[$cacheKey] = $result;
$this->geoIpCache->set($geoIpCache);
}
return $result ?? null;
}
/**
* @inheritDoc
*/
public function getCountryCode(?string $ip): ?string
{
if (! $ip) {
$ip = $this->remoteAddress->getRemoteAddress();
}
if ($ip) {
$cacheKey = $ip . $this->cacheKeyPostfixes[$this->getShortMethodName(__METHOD__)];
$geoIpCache = $this->geoIpCache->get();
if (isset($geoIpCache[$cacheKey])) {
return $geoIpCache[$cacheKey];
}
$result = $this->getGeoLocation($ip);
$result = $result['country_code'] ?? null;
$geoIpCache[$cacheKey] = $result;
$this->geoIpCache->set($geoIpCache);
}
return $result ?? null;
}
/**
* @inheritDoc
*/
public function getCurrentCountryState(?string $ip): ?string
{
if (! $ip) {
$ip = $this->remoteAddress->getRemoteAddress();
}
if ($ip) {
$cacheKey = $ip . $this->cacheKeyPostfixes[$this->getShortMethodName(__METHOD__)];
$geoIpCache = $this->geoIpCache->get();
if (isset($geoIpCache[$cacheKey])) {
return $geoIpCache[$cacheKey];
}
$result = $this->getGeoLocation($ip);
$result = $result['subdivision_1_name'] ?? null;
$geoIpCache[$cacheKey] = $result;
$this->geoIpCache->set($geoIpCache);
}
return $result ?? null;
}
/**
* @param string $method
* @return string
*/
private function getShortMethodName(string $method): string
{
return substr($method, strpos($method, '::') + 2);
}
}
+222
View File
@@ -0,0 +1,222 @@
<?php
/**
* Plumrocket Inc.
*
* NOTICE OF LICENSE
*
* This source file is subject to the End-user License Agreement
* that is available through the world-wide-web at this URL:
* http://wiki.plumrocket.net/wiki/EULA
* If you are unable to obtain it through the world-wide-web, please
* send an email to support@plumrocket.com so we can send you a copy immediately.
*
* @package Plumrocket_GeoIPLookup
* @copyright Copyright (c) 2018 Plumrocket Inc. (http://www.plumrocket.com)
* @license http://wiki.plumrocket.net/wiki/EULA End-user License Agreement
*/
namespace Plumrocket\GeoIPLookup\Model\Services;
use Magento\Framework\HTTP\Client\Curl;
use Magento\Framework\HTTP\PhpEnvironment\RemoteAddress;
use Magento\Framework\Serialize\Serializer\Json;
use Plumrocket\GeoIPLookup\Api\GeoIpServiceInterface;
use Plumrocket\GeoIPLookup\Helper\Config;
use Plumrocket\GeoIPLookup\Model\Cache\GeoIpInterface;
/**
* @since 2.0.0
*/
class IpApi implements GeoIpServiceInterface
{
/**
* @var \Magento\Framework\HTTP\Client\Curl
*/
private $curl;
/**
* @var string
*/
private $dataName = 'Ipapi.Com';
/**
* @var \Magento\Framework\HTTP\PhpEnvironment\RemoteAddress
*/
private $remoteAddress;
/**
* @var \Magento\Framework\Serialize\Serializer\Json
*/
private $jsonSerializer;
/**
* @var \Plumrocket\GeoIPLookup\Helper\Config
*/
private $configHelper;
/**
* @var \Plumrocket\GeoIPLookup\Model\Cache\GeoIpInterface
*/
private $geoIpCache;
/**
* @param \Magento\Framework\HTTP\Client\Curl $curl
* @param \Magento\Framework\HTTP\PhpEnvironment\RemoteAddress $remoteAddress
* @param \Magento\Framework\Serialize\Serializer\Json $jsonSerializer
* @param \Plumrocket\GeoIPLookup\Helper\Config $configHelper
* @param \Plumrocket\GeoIPLookup\Model\Cache\GeoIpInterface $geoIpCache
*/
public function __construct(
Curl $curl,
RemoteAddress $remoteAddress,
Json $jsonSerializer,
Config $configHelper,
GeoIpInterface $geoIpCache
) {
$this->curl = $curl;
$this->remoteAddress = $remoteAddress;
$this->jsonSerializer = $jsonSerializer;
$this->configHelper = $configHelper;
$this->geoIpCache = $geoIpCache;
}
/**
* @inheritDoc
*/
public function getGeoLocation(?string $ip): ?array
{
$result = null;
if (! $ip) {
$ip = $this->remoteAddress->getRemoteAddress();
}
if ($ip) {
$cacheKey = ip2long($ip) . '_gl_ipapi';
$geoipCache = $this->geoIpCache->get();
if (isset($geoipCache[$cacheKey])) {
return $geoipCache[$cacheKey];
}
$curlResult = $this->curlExec($ip);
if ($curlResult) {
$curlResultArr = $this->jsonSerializer->unserialize($curlResult);
if (isset($curlResultArr['error'])) {
return $result;
}
$result = [
'country_code' => $curlResultArr['country_code'] ?? '',
'country_name' => $curlResultArr['country_name'] ?? '',
'region_name' => $curlResultArr['region_name'] ?? '',
'city_name' => $curlResultArr['city'] ?? '',
'latitude' => $curlResultArr['latitude'] ?? '',
'longitude' => $curlResultArr['longitude'] ?? '',
'database_name' => $this->dataName
];
}
$result = (!empty($result)) ? $result : null;
$geoipCache[$cacheKey] = $result;
$this->geoIpCache->set($geoipCache);
}
return $result;
}
/**
* @inheritDoc
*/
public function getCountryCode(?string $ip): ?string
{
$result = null;
if (! $ip) {
$ip = $this->remoteAddress->getRemoteAddress();
}
if ($ip) {
$cacheKey = ip2long($ip) . '_cc_ipapi';
$geoipCache = $this->geoIpCache->get();
if (isset($geoipCache[$cacheKey])) {
return $geoipCache[$cacheKey];
}
$curlResult = $this->curlExec($ip);
if ($curlResult) {
$curlResultArr = $this->jsonSerializer->unserialize($curlResult);
if (isset($curlResultArr['error'])) {
return $result;
} else {
$result = $curlResultArr['country_code'];
}
}
$result = (!empty($result)) ? $result : null;
$geoipCache[$cacheKey] = $result;
$this->geoIpCache->set($geoipCache);
}
return $result;
}
/**
* @inheritDoc
*/
public function getCurrentCountryState(?string $ip): ?string
{
$result = null;
if (! $ip) {
$ip = $this->remoteAddress->getRemoteAddress();
}
if ($ip) {
$cacheKey = ip2long($ip) . '_cc_ipapi_cstate';
$geoipCache = $this->geoIpCache->get();
if (isset($geoipCache[$cacheKey])) {
return $geoipCache[$cacheKey];
}
$curlResult = $this->curlExec($ip);
if ($curlResult) {
$curlResultArr = $this->jsonSerializer->unserialize($curlResult);
if (isset($curlResultArr['error'])) {
return $result;
} else {
$result = $curlResultArr['region_name'];
}
}
$result = (!empty($result)) ? $result : null;
$geoipCache[$cacheKey] = $result;
$this->geoIpCache->set($geoipCache);
}
return $result;
}
/**
* @param $ip
* @return string
*/
private function curlExec($ip): string
{
$url = $this->configHelper->useIpApiHttps() ? "https://" : "http://";
$url .= $this->configHelper->getIpApiUrl($ip);
$options = [
CURLOPT_HEADER => 0,
CURLOPT_FRESH_CONNECT => 1,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_FORBID_REUSE => 1,
CURLOPT_TIMEOUT => 4,
];
$this->curl->post($url, $options);
return $this->curl->getBody();
}
}
@@ -0,0 +1,88 @@
<?php
/**
* Plumrocket Inc.
*
* NOTICE OF LICENSE
*
* This source file is subject to the End-user License Agreement
* that is available through the world-wide-web at this URL:
* http://wiki.plumrocket.net/wiki/EULA
* If you are unable to obtain it through the world-wide-web, please
* send an email to support@plumrocket.com so we can send you a copy immediately.
*
* @package Plumrocket_GeoIPLookup
* @copyright Copyright (c) 2020 Plumrocket Inc. (http://www.plumrocket.com)
* @license http://wiki.plumrocket.net/wiki/EULA End-user License Agreement
*/
namespace Plumrocket\GeoIPLookup\Model\System\Config\Source;
use Magento\Framework\Data\OptionSourceInterface;
use Plumrocket\GeoIPLookup\Helper\Config;
use Plumrocket\GeoIPLookup\Model\LocationsList;
/**
* @since 1.2.2
*/
class GeoTargeting implements OptionSourceInterface
{
/**
* @var \Plumrocket\GeoIPLookup\Helper\Config
*/
private $config;
/**
* @var \Plumrocket\GeoIPLookup\Model\LocationsList
*/
private $locationsList;
/**
* @param \Plumrocket\GeoIPLookup\Helper\Config $config
* @param \Plumrocket\GeoIPLookup\Model\LocationsList $locationsList
*/
public function __construct(
Config $config,
LocationsList $locationsList
) {
$this->config = $config;
$this->locationsList = $locationsList;
}
/**
* @return array
*/
public function toOptionArray(): array
{
$regions = $this->locationsList->getRegions();
$countries = $this->locationsList->getCountries();
if (! $this->config->isConfiguredForUse()) {
$regions = array_map([$this, 'addDisabledAttribute'], $regions);
$countries = array_map([$this, 'addDisabledAttribute'], $countries);
}
return [
[
'label' => __('By Region'),
'value' => $regions,
],
[
'label' => __('By Country'),
'value' => $countries,
],
];
}
/**
* @param array $option
* @return mixed
*/
public function addDisabledAttribute($option)
{
if (LocationsList::ALL !== $option['value']) {
$option['params']['disabled'] = 'disabled';
}
return $option;
}
}
@@ -0,0 +1,51 @@
<?php
/**
* Plumrocket Inc.
*
* NOTICE OF LICENSE
*
* This source file is subject to the End-user License Agreement
* that is available through the world-wide-web at this URL:
* http://wiki.plumrocket.net/wiki/EULA
* If you are unable to obtain it through the world-wide-web, please
* send an email to support@plumrocket.com so we can send you a copy immediately.
*
* @package Plumrocket_GeoIPLookup
* @copyright Copyright (c) 2020 Plumrocket Inc. (http://www.plumrocket.com)
* @license http://wiki.plumrocket.net/wiki/EULA End-user License Agreement
*/
declare(strict_types=1);
namespace Plumrocket\GeoIPLookup\Model\System\Config\Source;
use Magento\Framework\Data\OptionSourceInterface;
use Plumrocket\GeoIPLookup\Api\LocationsListInterface;
/**
* @since 1.2.2
*/
class GeoTargetingStates implements OptionSourceInterface
{
/**
* @var \Plumrocket\GeoIPLookup\Api\LocationsListInterface
*/
private $locationsList;
/**
* @param \Plumrocket\GeoIPLookup\Api\LocationsListInterface $locationsList
*/
public function __construct(
LocationsListInterface $locationsList
) {
$this->locationsList = $locationsList;
}
/**
* @return array
*/
public function toOptionArray()
{
return $this->locationsList->getCountryStates('United States');
}
}
@@ -0,0 +1,48 @@
<?php
/**
* Plumrocket Inc.
*
* NOTICE OF LICENSE
*
* This source file is subject to the End-user License Agreement
* that is available through the world-wide-web at this URL:
* http://wiki.plumrocket.net/wiki/EULA
* If you are unable to obtain it through the world-wide-web, please
* send an email to support@plumrocket.com so we can send you a copy immediately.
*
* @package Plumrocket_GeoIPLookup
* @copyright Copyright (c) 2018 Plumrocket Inc. (http://www.plumrocket.com)
* @license http://wiki.plumrocket.net/wiki/EULA End-user License Agreement
*/
namespace Plumrocket\GeoIPLookup\Model\System\Config\Source;
class Installmethods implements \Magento\Framework\Option\ArrayInterface
{
/**
* Apply automatic installation
*/
const AUTOMATIC = 'automatic';
/**
* Apply manual installation
*/
const MANUAL = 'manual';
/**
* {@inheritDoc}
*/
public function toOptionArray()
{
return [
[
'value' => self::AUTOMATIC,
'label' => __('Automatic Installation'),
],
[
'value' => self::MANUAL,
'label' => __('Manual Installation'),
],
];
}
}
@@ -0,0 +1,30 @@
<?php
/**
* @package Plumrocket_GeoIPLookup
* @copyright Copyright (c) 2025 Plumrocket Inc. (https://plumrocket.com)
* @license https://plumrocket.com/license End-user License Agreement
*/
declare(strict_types=1);
namespace Plumrocket\GeoIPLookup\Model\Validator;
/**
* @since 2.0.2
*/
class IsEuropeanUnionCountry
{
private $europeanUnionCountryIsoCodes = [
"CY","GR","EE","BG","LV","LT","SE","FI","AX","RO","HU","SK","PL","YT","RE","PT","GI","ES",
"IT","MT","AT", "DK","GB","IE","NL","BE","DE","LU","FR","CZ","HR","SI","MQ","GP","MF"
];
/**
* @param string $countryCode
* @return bool
*/
public function validate(string $countryCode): bool
{
return in_array($countryCode, $this->europeanUnionCountryIsoCodes, true);
}
}