init
This commit is contained in:
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun3d\GeoWebsiteRedirect\Block\Adminhtml\System\Config;
|
||||
|
||||
use Magento\Config\Block\System\Config\Form\Field;
|
||||
use Magento\Framework\Data\Form\Element\AbstractElement;
|
||||
|
||||
class TestIp extends Field
|
||||
{
|
||||
protected $_template = 'Esun3d_GeoWebsiteRedirect::system/config/test_ip.phtml';
|
||||
|
||||
protected function _getElementHtml(AbstractElement $element): string
|
||||
{
|
||||
$this->setData('element', $element);
|
||||
|
||||
return $this->_toHtml();
|
||||
}
|
||||
|
||||
public function getResolveUrl(): string
|
||||
{
|
||||
return $this->getUrl('geo_website_redirect/test/resolve');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun3d\GeoWebsiteRedirect\Controller\Adminhtml\Test;
|
||||
|
||||
use Esun3d\GeoWebsiteRedirect\Model\TestIpService;
|
||||
use Magento\Backend\App\Action;
|
||||
use Magento\Backend\App\Action\Context;
|
||||
use Magento\Framework\App\Action\HttpPostActionInterface;
|
||||
use Magento\Framework\Controller\Result\Json;
|
||||
use Magento\Framework\Controller\Result\JsonFactory;
|
||||
use Magento\Framework\Exception\LocalizedException;
|
||||
use Psr\Log\LoggerInterface;
|
||||
|
||||
class Resolve extends Action implements HttpPostActionInterface
|
||||
{
|
||||
public const ADMIN_RESOURCE = 'Esun3d_GeoWebsiteRedirect::config';
|
||||
|
||||
public function __construct(
|
||||
Context $context,
|
||||
private JsonFactory $jsonFactory,
|
||||
private TestIpService $testIpService,
|
||||
private LoggerInterface $logger
|
||||
) {
|
||||
parent::__construct($context);
|
||||
}
|
||||
|
||||
public function execute(): Json
|
||||
{
|
||||
$result = $this->jsonFactory->create();
|
||||
|
||||
try {
|
||||
return $result->setData([
|
||||
'success' => true,
|
||||
'data' => $this->testIpService->execute((string)$this->getRequest()->getParam('ip')),
|
||||
]);
|
||||
} catch (LocalizedException $exception) {
|
||||
return $result->setData(['success' => false, 'message' => $exception->getMessage()]);
|
||||
} catch (\Throwable $exception) {
|
||||
$this->logger->error('[GeoWebsiteRedirect] Admin IP test failed.', ['exception' => $exception]);
|
||||
|
||||
return $result->setData([
|
||||
'success' => false,
|
||||
'message' => (string)__('The IP test could not be completed. Check the logs and try again.'),
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun3d\GeoWebsiteRedirect\Model;
|
||||
|
||||
class BotDetector
|
||||
{
|
||||
public function __construct(private Config $config)
|
||||
{
|
||||
}
|
||||
|
||||
public function isBot(string $userAgent): bool
|
||||
{
|
||||
if (!$this->config->shouldIgnoreBots() || $userAgent === '') {
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach ($this->config->getIgnoredUserAgentPatterns() as $pattern) {
|
||||
if ($pattern !== '' && stripos($userAgent, $pattern) !== false) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun3d\GeoWebsiteRedirect\Model;
|
||||
|
||||
use Magento\Framework\App\Config\ScopeConfigInterface;
|
||||
|
||||
class Config
|
||||
{
|
||||
public const COOKIE_NAME = 'geo_website_choice';
|
||||
public const REDIRECT_SCOPE_HOMEPAGE = 'homepage';
|
||||
public const REDIRECT_SCOPE_ALL = 'all';
|
||||
|
||||
private const XML_PATH_ENABLED = 'geo_website_redirect/general/enabled';
|
||||
private const XML_PATH_REDIRECT_SCOPE = 'geo_website_redirect/general/redirect_scope';
|
||||
private const XML_PATH_PRESERVE_PATH = 'geo_website_redirect/general/preserve_path';
|
||||
private const XML_PATH_COOKIE_LIFETIME = 'geo_website_redirect/general/cookie_lifetime';
|
||||
private const XML_PATH_COOKIE_DOMAIN = 'geo_website_redirect/general/cookie_domain';
|
||||
private const XML_PATH_UK_WEBSITE = 'geo_website_redirect/mapping/uk_website';
|
||||
private const XML_PATH_AU_WEBSITE = 'geo_website_redirect/mapping/au_website';
|
||||
private const XML_PATH_EU_WEBSITE = 'geo_website_redirect/mapping/eu_website';
|
||||
private const XML_PATH_DEFAULT_WEBSITE = 'geo_website_redirect/mapping/default_website';
|
||||
private const XML_PATH_EU_COUNTRIES = 'geo_website_redirect/mapping/eu_countries';
|
||||
private const XML_PATH_IGNORE_BOTS = 'geo_website_redirect/exclusions/ignore_bots';
|
||||
private const XML_PATH_USER_AGENTS = 'geo_website_redirect/exclusions/user_agents';
|
||||
private const XML_PATH_EXCLUDED_PATHS = 'geo_website_redirect/exclusions/paths';
|
||||
|
||||
private const DEFAULT_COOKIE_LIFETIME = 2592000;
|
||||
|
||||
public function __construct(private ScopeConfigInterface $scopeConfig)
|
||||
{
|
||||
}
|
||||
|
||||
public function isEnabled(): bool
|
||||
{
|
||||
return $this->scopeConfig->isSetFlag(self::XML_PATH_ENABLED);
|
||||
}
|
||||
|
||||
public function getRedirectScope(): string
|
||||
{
|
||||
$scope = (string)$this->scopeConfig->getValue(self::XML_PATH_REDIRECT_SCOPE);
|
||||
|
||||
return $scope === self::REDIRECT_SCOPE_ALL ? self::REDIRECT_SCOPE_ALL : self::REDIRECT_SCOPE_HOMEPAGE;
|
||||
}
|
||||
|
||||
public function shouldPreservePath(): bool
|
||||
{
|
||||
return $this->scopeConfig->isSetFlag(self::XML_PATH_PRESERVE_PATH);
|
||||
}
|
||||
|
||||
public function getCookieLifetime(): int
|
||||
{
|
||||
$lifetime = (int)$this->scopeConfig->getValue(self::XML_PATH_COOKIE_LIFETIME);
|
||||
|
||||
return $lifetime > 0 ? $lifetime : self::DEFAULT_COOKIE_LIFETIME;
|
||||
}
|
||||
|
||||
public function getCookieDomain(): string
|
||||
{
|
||||
return trim((string)$this->scopeConfig->getValue(self::XML_PATH_COOKIE_DOMAIN));
|
||||
}
|
||||
|
||||
public function getUkWebsiteCode(): string
|
||||
{
|
||||
return trim((string)$this->scopeConfig->getValue(self::XML_PATH_UK_WEBSITE));
|
||||
}
|
||||
|
||||
public function getAuWebsiteCode(): string
|
||||
{
|
||||
return trim((string)$this->scopeConfig->getValue(self::XML_PATH_AU_WEBSITE));
|
||||
}
|
||||
|
||||
public function getEuWebsiteCode(): string
|
||||
{
|
||||
return trim((string)$this->scopeConfig->getValue(self::XML_PATH_EU_WEBSITE));
|
||||
}
|
||||
|
||||
public function getDefaultWebsiteCode(): string
|
||||
{
|
||||
return trim((string)$this->scopeConfig->getValue(self::XML_PATH_DEFAULT_WEBSITE));
|
||||
}
|
||||
|
||||
/** @return string[] */
|
||||
public function getEuCountryCodes(): array
|
||||
{
|
||||
return $this->parseCodes((string)$this->scopeConfig->getValue(self::XML_PATH_EU_COUNTRIES));
|
||||
}
|
||||
|
||||
public function shouldIgnoreBots(): bool
|
||||
{
|
||||
return $this->scopeConfig->isSetFlag(self::XML_PATH_IGNORE_BOTS);
|
||||
}
|
||||
|
||||
/** @return string[] */
|
||||
public function getIgnoredUserAgentPatterns(): array
|
||||
{
|
||||
return $this->parseLines((string)$this->scopeConfig->getValue(self::XML_PATH_USER_AGENTS));
|
||||
}
|
||||
|
||||
/** @return string[] */
|
||||
public function getExcludedPathPrefixes(): array
|
||||
{
|
||||
return array_map(
|
||||
static fn (string $path): string => strtolower(trim($path, "/ \t\n\r\0\x0B")),
|
||||
$this->parseLines((string)$this->scopeConfig->getValue(self::XML_PATH_EXCLUDED_PATHS))
|
||||
);
|
||||
}
|
||||
|
||||
/** @return string[] */
|
||||
private function parseCodes(string $value): array
|
||||
{
|
||||
$codes = preg_split('/[\s,]+/', strtoupper(trim($value)), -1, PREG_SPLIT_NO_EMPTY) ?: [];
|
||||
|
||||
return array_values(array_unique(array_filter(
|
||||
$codes,
|
||||
static fn (string $code): bool => (bool)preg_match('/^[A-Z]{2}$/', $code)
|
||||
)));
|
||||
}
|
||||
|
||||
/** @return string[] */
|
||||
private function parseLines(string $value): array
|
||||
{
|
||||
$lines = preg_split('/\R+/', trim($value), -1, PREG_SPLIT_NO_EMPTY) ?: [];
|
||||
|
||||
return array_values(array_filter(array_map('trim', $lines), 'strlen'));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun3d\GeoWebsiteRedirect\Model\Config\Source;
|
||||
|
||||
use Esun3d\GeoWebsiteRedirect\Model\Config;
|
||||
use Magento\Framework\Data\OptionSourceInterface;
|
||||
|
||||
class RedirectScope implements OptionSourceInterface
|
||||
{
|
||||
public function toOptionArray(): array
|
||||
{
|
||||
return [
|
||||
['value' => Config::REDIRECT_SCOPE_HOMEPAGE, 'label' => __('Homepage Only')],
|
||||
['value' => Config::REDIRECT_SCOPE_ALL, 'label' => __('All Pages')],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun3d\GeoWebsiteRedirect\Model\Config\Source;
|
||||
|
||||
use Magento\Framework\Data\OptionSourceInterface;
|
||||
use Magento\Store\Model\StoreManagerInterface;
|
||||
|
||||
class Website implements OptionSourceInterface
|
||||
{
|
||||
public function __construct(private StoreManagerInterface $storeManager)
|
||||
{
|
||||
}
|
||||
|
||||
public function toOptionArray(): array
|
||||
{
|
||||
$options = [];
|
||||
foreach ($this->storeManager->getWebsites(false) as $website) {
|
||||
$options[] = [
|
||||
'label' => (string)$website->getName(),
|
||||
'value' => (string)$website->getCode(),
|
||||
];
|
||||
}
|
||||
|
||||
return $options;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun3d\GeoWebsiteRedirect\Model;
|
||||
|
||||
use Amasty\Geoip\Model\Geolocation;
|
||||
use Magento\Framework\HTTP\PhpEnvironment\RemoteAddress;
|
||||
use Psr\Log\LoggerInterface;
|
||||
|
||||
class CountryResolver
|
||||
{
|
||||
public function __construct(
|
||||
private Geolocation $geolocation,
|
||||
private RemoteAddress $remoteAddress,
|
||||
private LoggerInterface $logger
|
||||
) {
|
||||
}
|
||||
|
||||
public function resolve(): ?string
|
||||
{
|
||||
try {
|
||||
$ip = (string)$this->remoteAddress->getRemoteAddress();
|
||||
if ($ip === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
$country = strtoupper(trim((string)$this->geolocation->locate($ip)->getData('country')));
|
||||
|
||||
return preg_match('/^[A-Z]{2}$/', $country) ? $country : null;
|
||||
} catch (\Throwable $exception) {
|
||||
$this->logger->error('[GeoWebsiteRedirect] Failed to resolve the visitor country.', [
|
||||
'exception' => $exception,
|
||||
]);
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun3d\GeoWebsiteRedirect\Model;
|
||||
|
||||
use Amasty\Geoip\Helper\Data as GeoipHelper;
|
||||
use Magento\Framework\App\ResourceConnection;
|
||||
use Magento\Framework\DB\Select;
|
||||
|
||||
class ExplicitIpLookup
|
||||
{
|
||||
public function __construct(
|
||||
private GeoipHelper $geoipHelper,
|
||||
private ResourceConnection $resource
|
||||
) {
|
||||
}
|
||||
|
||||
/** @return array<string, mixed>|null */
|
||||
public function lookup(string $ip): ?array
|
||||
{
|
||||
$isIpv6 = (bool)filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6);
|
||||
$maskedIp = $this->maskIp($ip, $isIpv6 ? ':' : '.');
|
||||
|
||||
if (!$this->geoipHelper->isDone(false)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$longIp = $isIpv6
|
||||
? $this->geoipHelper->getLongIpV6($maskedIp)
|
||||
: sprintf('%u', ip2long($maskedIp));
|
||||
if (empty($longIp)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$connection = $this->resource->getConnection('read');
|
||||
$blockTable = $isIpv6 ? 'amasty_geoip_block_v6' : 'amasty_geoip_block';
|
||||
$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']);
|
||||
$result = $connection->fetchRow($select);
|
||||
|
||||
if (!$result) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$result['masked_ip'] = $maskedIp;
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
private function maskIp(string $ip, string $separator): string
|
||||
{
|
||||
$parts = explode($separator, $ip);
|
||||
array_pop($parts);
|
||||
$parts[] = '0';
|
||||
|
||||
return implode($separator, $parts);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun3d\GeoWebsiteRedirect\Model;
|
||||
|
||||
use Magento\Framework\App\RequestInterface;
|
||||
use Magento\Framework\Stdlib\Cookie\CookieMetadata;
|
||||
use Magento\Framework\Stdlib\Cookie\CookieMetadataFactory;
|
||||
use Magento\Framework\Stdlib\CookieManagerInterface;
|
||||
|
||||
class RedirectCookie
|
||||
{
|
||||
public function __construct(
|
||||
private Config $config,
|
||||
private CookieManagerInterface $cookieManager,
|
||||
private CookieMetadataFactory $cookieMetadataFactory,
|
||||
private RequestInterface $request
|
||||
) {
|
||||
}
|
||||
|
||||
public function hasSelection(): bool
|
||||
{
|
||||
return trim((string)$this->cookieManager->getCookie(Config::COOKIE_NAME)) !== '';
|
||||
}
|
||||
|
||||
public function set(string $websiteCode): void
|
||||
{
|
||||
$metadata = $this->cookieMetadataFactory->createPublicCookieMetadata([
|
||||
CookieMetadata::KEY_DURATION => $this->config->getCookieLifetime(),
|
||||
CookieMetadata::KEY_SAME_SITE => 'Lax',
|
||||
]);
|
||||
$metadata->setPath('/');
|
||||
$metadata->setHttpOnly(false);
|
||||
|
||||
$domain = $this->config->getCookieDomain();
|
||||
if ($domain !== '') {
|
||||
$metadata->setDomain($domain);
|
||||
}
|
||||
if (method_exists($this->request, 'isSecure')) {
|
||||
$metadata->setSecure((bool)$this->request->isSecure());
|
||||
}
|
||||
|
||||
$this->cookieManager->setPublicCookie(Config::COOKIE_NAME, $websiteCode, $metadata);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun3d\GeoWebsiteRedirect\Model;
|
||||
|
||||
use Magento\Framework\App\Request\Http;
|
||||
|
||||
class RedirectEligibility
|
||||
{
|
||||
public function __construct(
|
||||
private Config $config,
|
||||
private BotDetector $botDetector,
|
||||
private RedirectCookie $redirectCookie
|
||||
) {
|
||||
}
|
||||
|
||||
public function canRedirect(Http $request): bool
|
||||
{
|
||||
if (!$this->config->isEnabled() || $this->redirectCookie->hasSelection()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!in_array(strtoupper($request->getMethod()), ['GET', 'HEAD'], true) || $request->isAjax()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$path = strtolower(trim($request->getPathInfo(), '/'));
|
||||
if ($this->config->getRedirectScope() === Config::REDIRECT_SCOPE_HOMEPAGE && $path !== '') {
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach ($this->config->getExcludedPathPrefixes() as $prefix) {
|
||||
if ($prefix !== '' && ($path === $prefix || str_starts_with($path, $prefix . '/'))) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return !$this->botDetector->isBot((string)$request->getServer('HTTP_USER_AGENT'));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun3d\GeoWebsiteRedirect\Model;
|
||||
|
||||
use Magento\Framework\App\Request\Http;
|
||||
use Magento\Framework\UrlInterface;
|
||||
use Magento\Store\Model\StoreManagerInterface;
|
||||
|
||||
class TargetUrlBuilder
|
||||
{
|
||||
public function __construct(
|
||||
private Config $config,
|
||||
private StoreManagerInterface $storeManager
|
||||
) {
|
||||
}
|
||||
|
||||
public function build(string $websiteCode, Http $request): ?string
|
||||
{
|
||||
$website = $this->storeManager->getWebsite($websiteCode);
|
||||
$defaultStore = $website->getDefaultStore();
|
||||
if (!$defaultStore || !$defaultStore->isActive()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$url = rtrim($defaultStore->getBaseUrl(UrlInterface::URL_TYPE_LINK, $request->isSecure()), '/') . '/';
|
||||
if (!$this->config->shouldPreservePath()) {
|
||||
return $url;
|
||||
}
|
||||
|
||||
$path = ltrim($request->getPathInfo(), '/');
|
||||
if ($path !== '') {
|
||||
$url .= $path;
|
||||
}
|
||||
|
||||
$query = [];
|
||||
parse_str((string)$request->getServer('QUERY_STRING'), $query);
|
||||
unset($query['market'], $query['store'], $query['___store'], $query['___from_store']);
|
||||
if ($query) {
|
||||
$url .= '?' . http_build_query($query);
|
||||
}
|
||||
|
||||
return $url;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun3d\GeoWebsiteRedirect\Model;
|
||||
|
||||
use Amasty\Geoip\Helper\Data as GeoipHelper;
|
||||
use Magento\Framework\Exception\LocalizedException;
|
||||
use Magento\Framework\UrlInterface;
|
||||
use Magento\Store\Model\StoreManagerInterface;
|
||||
|
||||
class TestIpService
|
||||
{
|
||||
public function __construct(
|
||||
private ExplicitIpLookup $ipLookup,
|
||||
private WebsiteResolver $websiteResolver,
|
||||
private StoreManagerInterface $storeManager,
|
||||
private GeoipHelper $geoipHelper
|
||||
) {
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
public function execute(string $ip): array
|
||||
{
|
||||
$ip = trim($ip);
|
||||
if (!filter_var($ip, FILTER_VALIDATE_IP)) {
|
||||
throw new LocalizedException(__('Enter a valid IPv4 or IPv6 address.'));
|
||||
}
|
||||
|
||||
$location = $this->ipLookup->lookup($ip);
|
||||
$country = strtoupper(trim((string)($location['country'] ?? '')));
|
||||
if (!$location || !preg_match('/^[A-Z]{2}$/', $country)) {
|
||||
throw new LocalizedException(__('No GeoIP record was found for this IP address.'));
|
||||
}
|
||||
|
||||
$websiteCode = $this->websiteResolver->resolve($country);
|
||||
if ($websiteCode === null) {
|
||||
throw new LocalizedException(__('No website is configured for country %1.', $country));
|
||||
}
|
||||
|
||||
$website = $this->storeManager->getWebsite($websiteCode);
|
||||
$defaultStore = $website->getDefaultStore();
|
||||
if (!$defaultStore || !$defaultStore->isActive()) {
|
||||
throw new LocalizedException(__('Website %1 has no active default store.', $websiteCode));
|
||||
}
|
||||
|
||||
return [
|
||||
'ip' => $ip,
|
||||
'masked_ip' => (string)$location['masked_ip'],
|
||||
'country' => $country,
|
||||
'city' => (string)($location['city'] ?? ''),
|
||||
'website_code' => $websiteCode,
|
||||
'website_name' => (string)$website->getName(),
|
||||
'target_url' => rtrim($defaultStore->getBaseUrl(UrlInterface::URL_TYPE_LINK, true), '/') . '/',
|
||||
'force_ip_enabled' => $this->geoipHelper->isForcedIpEnabled(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun3d\GeoWebsiteRedirect\Model;
|
||||
|
||||
class WebsiteResolver
|
||||
{
|
||||
public function __construct(private Config $config)
|
||||
{
|
||||
}
|
||||
|
||||
public function resolve(string $countryCode): ?string
|
||||
{
|
||||
$countryCode = strtoupper(trim($countryCode));
|
||||
if (!preg_match('/^[A-Z]{2}$/', $countryCode)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($countryCode === 'GB') {
|
||||
return $this->valueOrNull($this->config->getUkWebsiteCode());
|
||||
}
|
||||
if ($countryCode === 'AU') {
|
||||
return $this->valueOrNull($this->config->getAuWebsiteCode());
|
||||
}
|
||||
if (in_array($countryCode, $this->config->getEuCountryCodes(), true)) {
|
||||
return $this->valueOrNull($this->config->getEuWebsiteCode());
|
||||
}
|
||||
|
||||
return $this->valueOrNull($this->config->getDefaultWebsiteCode());
|
||||
}
|
||||
|
||||
private function valueOrNull(string $value): ?string
|
||||
{
|
||||
return $value !== '' ? $value : null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun3d\GeoWebsiteRedirect\Plugin;
|
||||
|
||||
use Esun3d\GeoWebsiteRedirect\Model\CountryResolver;
|
||||
use Esun3d\GeoWebsiteRedirect\Model\RedirectCookie;
|
||||
use Esun3d\GeoWebsiteRedirect\Model\RedirectEligibility;
|
||||
use Esun3d\GeoWebsiteRedirect\Model\TargetUrlBuilder;
|
||||
use Esun3d\GeoWebsiteRedirect\Model\WebsiteResolver;
|
||||
use Magento\Framework\App\FrontControllerInterface;
|
||||
use Magento\Framework\App\Request\Http as HttpRequest;
|
||||
use Magento\Framework\App\RequestInterface;
|
||||
use Magento\Framework\App\Response\Http as HttpResponse;
|
||||
use Magento\Store\Model\StoreManagerInterface;
|
||||
use Psr\Log\LoggerInterface;
|
||||
|
||||
class FrontControllerPlugin
|
||||
{
|
||||
public function __construct(
|
||||
private RedirectEligibility $eligibility,
|
||||
private CountryResolver $countryResolver,
|
||||
private WebsiteResolver $websiteResolver,
|
||||
private TargetUrlBuilder $targetUrlBuilder,
|
||||
private RedirectCookie $redirectCookie,
|
||||
private StoreManagerInterface $storeManager,
|
||||
private HttpResponse $response,
|
||||
private LoggerInterface $logger
|
||||
) {
|
||||
}
|
||||
|
||||
public function aroundDispatch(
|
||||
FrontControllerInterface $subject,
|
||||
callable $proceed,
|
||||
RequestInterface $request
|
||||
) {
|
||||
if (!$request instanceof HttpRequest || !$this->eligibility->canRedirect($request)) {
|
||||
return $proceed($request);
|
||||
}
|
||||
|
||||
try {
|
||||
$countryCode = $this->countryResolver->resolve();
|
||||
if ($countryCode === null) {
|
||||
return $proceed($request);
|
||||
}
|
||||
|
||||
$targetWebsite = $this->websiteResolver->resolve($countryCode);
|
||||
if ($targetWebsite === null) {
|
||||
return $proceed($request);
|
||||
}
|
||||
|
||||
if ((string)$this->storeManager->getWebsite()->getCode() === $targetWebsite) {
|
||||
$this->redirectCookie->set($targetWebsite);
|
||||
|
||||
return $proceed($request);
|
||||
}
|
||||
|
||||
$targetUrl = $this->targetUrlBuilder->build($targetWebsite, $request);
|
||||
if ($targetUrl === null) {
|
||||
return $proceed($request);
|
||||
}
|
||||
|
||||
$this->redirectCookie->set($targetWebsite);
|
||||
$this->response->setRedirect($targetUrl, 302);
|
||||
$this->response->setHeader('Cache-Control', 'private, no-store, max-age=0', true);
|
||||
|
||||
return $this->response;
|
||||
} catch (\Throwable $exception) {
|
||||
$this->logger->error('[GeoWebsiteRedirect] Failed to redirect the visitor.', [
|
||||
'exception' => $exception,
|
||||
]);
|
||||
|
||||
return $proceed($request);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun3d\GeoWebsiteRedirect\Plugin;
|
||||
|
||||
use Esun3d\GeoWebsiteRedirect\Model\Config;
|
||||
use Esun3d\LanguageUrlStoreResolver\ViewModel\LocaleSwitcher;
|
||||
|
||||
class LocaleSwitcherConfigPlugin
|
||||
{
|
||||
public function __construct(private Config $config)
|
||||
{
|
||||
}
|
||||
|
||||
public function afterGetConfig(LocaleSwitcher $subject, array $result): array
|
||||
{
|
||||
$result['geoRedirect'] = [
|
||||
'enabled' => $this->config->isEnabled(),
|
||||
'cookieName' => Config::COOKIE_NAME,
|
||||
'cookieLifetime' => $this->config->getCookieLifetime(),
|
||||
'cookieDomain' => $this->config->getCookieDomain(),
|
||||
];
|
||||
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun3d\GeoWebsiteRedirect\Test\Unit\Model;
|
||||
|
||||
use Esun3d\GeoWebsiteRedirect\Model\BotDetector;
|
||||
use Esun3d\GeoWebsiteRedirect\Model\Config;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
class BotDetectorTest extends TestCase
|
||||
{
|
||||
public function testMatchesConfiguredPatternCaseInsensitively(): void
|
||||
{
|
||||
$config = $this->createMock(Config::class);
|
||||
$config->method('shouldIgnoreBots')->willReturn(true);
|
||||
$config->method('getIgnoredUserAgentPatterns')->willReturn(['googlebot', 'spider']);
|
||||
|
||||
$detector = new BotDetector($config);
|
||||
|
||||
self::assertTrue($detector->isBot('Mozilla/5.0 compatible; GoogleBot/2.1'));
|
||||
self::assertFalse($detector->isBot('Mozilla/5.0 Chrome/140.0'));
|
||||
}
|
||||
|
||||
public function testDoesNotIgnoreBotsWhenDisabled(): void
|
||||
{
|
||||
$config = $this->createMock(Config::class);
|
||||
$config->method('shouldIgnoreBots')->willReturn(false);
|
||||
|
||||
self::assertFalse((new BotDetector($config))->isBot('Googlebot/2.1'));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun3d\GeoWebsiteRedirect\Test\Unit\Model;
|
||||
|
||||
use Esun3d\GeoWebsiteRedirect\Model\Config;
|
||||
use Magento\Framework\App\Config\ScopeConfigInterface;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
class ConfigTest extends TestCase
|
||||
{
|
||||
public function testParsesAndValidatesEuCountryCodes(): void
|
||||
{
|
||||
$config = $this->createConfig([
|
||||
'geo_website_redirect/mapping/eu_countries' => "de, FR\ninvalid es DE",
|
||||
]);
|
||||
|
||||
self::assertSame(['DE', 'FR', 'ES'], $config->getEuCountryCodes());
|
||||
}
|
||||
|
||||
public function testNormalizesExcludedPaths(): void
|
||||
{
|
||||
$config = $this->createConfig([
|
||||
'geo_website_redirect/exclusions/paths' => "/Checkout\n REST/ ",
|
||||
]);
|
||||
|
||||
self::assertSame(['checkout', 'rest'], $config->getExcludedPathPrefixes());
|
||||
}
|
||||
|
||||
public function testInvalidCookieLifetimeFallsBackToThirtyDays(): void
|
||||
{
|
||||
$config = $this->createConfig([
|
||||
'geo_website_redirect/general/cookie_lifetime' => '0',
|
||||
]);
|
||||
|
||||
self::assertSame(2592000, $config->getCookieLifetime());
|
||||
}
|
||||
|
||||
/** @param array<string,string> $values */
|
||||
private function createConfig(array $values): Config
|
||||
{
|
||||
$scopeConfig = $this->createMock(ScopeConfigInterface::class);
|
||||
$scopeConfig->method('getValue')->willReturnCallback(
|
||||
static fn (string $path): ?string => $values[$path] ?? null
|
||||
);
|
||||
|
||||
return new Config($scopeConfig);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun3d\GeoWebsiteRedirect\Test\Unit\Model;
|
||||
|
||||
use Esun3d\GeoWebsiteRedirect\Model\BotDetector;
|
||||
use Esun3d\GeoWebsiteRedirect\Model\Config;
|
||||
use Esun3d\GeoWebsiteRedirect\Model\RedirectCookie;
|
||||
use Esun3d\GeoWebsiteRedirect\Model\RedirectEligibility;
|
||||
use Magento\Framework\App\Request\Http;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
class RedirectEligibilityTest extends TestCase
|
||||
{
|
||||
public function testAllowsFirstNormalHomepageRequest(): void
|
||||
{
|
||||
self::assertTrue($this->createEligibility()->canRedirect($this->createRequest('/', 'Mozilla/5.0')));
|
||||
}
|
||||
|
||||
public function testRejectsBotRequest(): void
|
||||
{
|
||||
self::assertFalse($this->createEligibility(true)->canRedirect($this->createRequest('/', 'Googlebot/2.1')));
|
||||
}
|
||||
|
||||
public function testRejectsRequestWhenSelectionCookieExists(): void
|
||||
{
|
||||
self::assertFalse($this->createEligibility(false, true)->canRedirect($this->createRequest('/', 'Mozilla/5.0')));
|
||||
}
|
||||
|
||||
public function testRejectsDeepPathInHomepageMode(): void
|
||||
{
|
||||
self::assertFalse(
|
||||
$this->createEligibility()->canRedirect($this->createRequest('/pla-filament/product-a', 'Mozilla/5.0'))
|
||||
);
|
||||
}
|
||||
|
||||
private function createEligibility(bool $isBot = false, bool $hasSelection = false): RedirectEligibility
|
||||
{
|
||||
$config = $this->createMock(Config::class);
|
||||
$config->method('isEnabled')->willReturn(true);
|
||||
$config->method('getRedirectScope')->willReturn(Config::REDIRECT_SCOPE_HOMEPAGE);
|
||||
$config->method('getExcludedPathPrefixes')->willReturn(['checkout', 'rest']);
|
||||
|
||||
$botDetector = $this->createMock(BotDetector::class);
|
||||
$botDetector->method('isBot')->willReturn($isBot);
|
||||
|
||||
$cookie = $this->createMock(RedirectCookie::class);
|
||||
$cookie->method('hasSelection')->willReturn($hasSelection);
|
||||
|
||||
return new RedirectEligibility($config, $botDetector, $cookie);
|
||||
}
|
||||
|
||||
private function createRequest(string $path, string $userAgent): Http
|
||||
{
|
||||
$request = $this->createMock(Http::class);
|
||||
$request->method('getMethod')->willReturn('GET');
|
||||
$request->method('isAjax')->willReturn(false);
|
||||
$request->method('getPathInfo')->willReturn($path);
|
||||
$request->method('getServer')->with('HTTP_USER_AGENT')->willReturn($userAgent);
|
||||
|
||||
return $request;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun3d\GeoWebsiteRedirect\Test\Unit\Model;
|
||||
|
||||
use Amasty\Geoip\Helper\Data as GeoipHelper;
|
||||
use Esun3d\GeoWebsiteRedirect\Model\ExplicitIpLookup;
|
||||
use Esun3d\GeoWebsiteRedirect\Model\TestIpService;
|
||||
use Esun3d\GeoWebsiteRedirect\Model\WebsiteResolver;
|
||||
use Magento\Framework\Exception\LocalizedException;
|
||||
use Magento\Store\Model\Store;
|
||||
use Magento\Store\Model\StoreManagerInterface;
|
||||
use Magento\Store\Model\Website;
|
||||
use PHPUnit\Framework\MockObject\MockObject;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
class TestIpServiceTest extends TestCase
|
||||
{
|
||||
private ExplicitIpLookup&MockObject $ipLookup;
|
||||
private WebsiteResolver&MockObject $websiteResolver;
|
||||
private StoreManagerInterface&MockObject $storeManager;
|
||||
private GeoipHelper&MockObject $geoipHelper;
|
||||
private TestIpService $service;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
$this->ipLookup = $this->createMock(ExplicitIpLookup::class);
|
||||
$this->websiteResolver = $this->createMock(WebsiteResolver::class);
|
||||
$this->storeManager = $this->createMock(StoreManagerInterface::class);
|
||||
$this->geoipHelper = $this->createMock(GeoipHelper::class);
|
||||
$this->service = new TestIpService(
|
||||
$this->ipLookup,
|
||||
$this->websiteResolver,
|
||||
$this->storeManager,
|
||||
$this->geoipHelper
|
||||
);
|
||||
}
|
||||
|
||||
public function testRejectsInvalidIp(): void
|
||||
{
|
||||
$this->ipLookup->expects($this->never())->method('lookup');
|
||||
|
||||
$this->expectException(LocalizedException::class);
|
||||
$this->expectExceptionMessage('Enter a valid IPv4 or IPv6 address.');
|
||||
|
||||
$this->service->execute('not-an-ip');
|
||||
}
|
||||
|
||||
public function testReturnsResolvedWebsiteDetails(): void
|
||||
{
|
||||
$this->ipLookup->expects($this->once())->method('lookup')->with('2.16.34.1')->willReturn([
|
||||
'country' => 'GB',
|
||||
'city' => 'London',
|
||||
'masked_ip' => '2.16.34.0',
|
||||
]);
|
||||
$this->websiteResolver->expects($this->once())->method('resolve')->with('GB')->willReturn('uk');
|
||||
|
||||
$store = $this->createMock(Store::class);
|
||||
$store->method('isActive')->willReturn(true);
|
||||
$store->method('getBaseUrl')->willReturn('https://www.example.co.uk/');
|
||||
|
||||
$website = $this->createMock(Website::class);
|
||||
$website->method('getDefaultStore')->willReturn($store);
|
||||
$website->method('getName')->willReturn('United Kingdom');
|
||||
$this->storeManager->expects($this->once())->method('getWebsite')->with('uk')->willReturn($website);
|
||||
$this->geoipHelper->method('isForcedIpEnabled')->willReturn(true);
|
||||
|
||||
$this->assertSame([
|
||||
'ip' => '2.16.34.1',
|
||||
'masked_ip' => '2.16.34.0',
|
||||
'country' => 'GB',
|
||||
'city' => 'London',
|
||||
'website_code' => 'uk',
|
||||
'website_name' => 'United Kingdom',
|
||||
'target_url' => 'https://www.example.co.uk/',
|
||||
'force_ip_enabled' => true,
|
||||
], $this->service->execute('2.16.34.1'));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun3d\GeoWebsiteRedirect\Test\Unit\Model;
|
||||
|
||||
use Esun3d\GeoWebsiteRedirect\Model\Config;
|
||||
use Esun3d\GeoWebsiteRedirect\Model\WebsiteResolver;
|
||||
use PHPUnit\Framework\Attributes\DataProvider;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
class WebsiteResolverTest extends TestCase
|
||||
{
|
||||
#[DataProvider('countryProvider')]
|
||||
public function testResolvesCountryToWebsite(string $country, ?string $expected): void
|
||||
{
|
||||
$config = $this->createMock(Config::class);
|
||||
$config->method('getUkWebsiteCode')->willReturn('uk');
|
||||
$config->method('getAuWebsiteCode')->willReturn('au');
|
||||
$config->method('getEuWebsiteCode')->willReturn('eu');
|
||||
$config->method('getDefaultWebsiteCode')->willReturn('us_site');
|
||||
$config->method('getEuCountryCodes')->willReturn(['DE', 'FR', 'ES']);
|
||||
|
||||
self::assertSame($expected, (new WebsiteResolver($config))->resolve($country));
|
||||
}
|
||||
|
||||
public static function countryProvider(): array
|
||||
{
|
||||
return [
|
||||
'United Kingdom' => ['GB', 'uk'],
|
||||
'Australia' => ['AU', 'au'],
|
||||
'EU member' => ['DE', 'eu'],
|
||||
'default market' => ['US', 'us_site'],
|
||||
'lowercase input' => ['fr', 'eu'],
|
||||
'invalid country' => ['', null],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun3d\GeoWebsiteRedirect\Test\Unit\Plugin;
|
||||
|
||||
use Esun3d\GeoWebsiteRedirect\Model\CountryResolver;
|
||||
use Esun3d\GeoWebsiteRedirect\Model\RedirectCookie;
|
||||
use Esun3d\GeoWebsiteRedirect\Model\RedirectEligibility;
|
||||
use Esun3d\GeoWebsiteRedirect\Model\TargetUrlBuilder;
|
||||
use Esun3d\GeoWebsiteRedirect\Model\WebsiteResolver;
|
||||
use Esun3d\GeoWebsiteRedirect\Plugin\FrontControllerPlugin;
|
||||
use Magento\Framework\App\FrontControllerInterface;
|
||||
use Magento\Framework\App\Request\Http as HttpRequest;
|
||||
use Magento\Framework\App\Response\Http as HttpResponse;
|
||||
use Magento\Store\Api\Data\WebsiteInterface;
|
||||
use Magento\Store\Model\StoreManagerInterface;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use Psr\Log\LoggerInterface;
|
||||
|
||||
class FrontControllerPluginTest extends TestCase
|
||||
{
|
||||
public function testRedirectsToResolvedWebsiteWithoutCallingFrontController(): void
|
||||
{
|
||||
$request = $this->createMock(HttpRequest::class);
|
||||
$eligibility = $this->createMock(RedirectEligibility::class);
|
||||
$eligibility->method('canRedirect')->with($request)->willReturn(true);
|
||||
$countryResolver = $this->createMock(CountryResolver::class);
|
||||
$countryResolver->method('resolve')->willReturn('GB');
|
||||
$websiteResolver = $this->createMock(WebsiteResolver::class);
|
||||
$websiteResolver->method('resolve')->with('GB')->willReturn('uk');
|
||||
$targetUrlBuilder = $this->createMock(TargetUrlBuilder::class);
|
||||
$targetUrlBuilder->method('build')->with('uk', $request)->willReturn('https://en.example.test/');
|
||||
$cookie = $this->createMock(RedirectCookie::class);
|
||||
$cookie->expects(self::once())->method('set')->with('uk');
|
||||
|
||||
$currentWebsite = $this->createMock(WebsiteInterface::class);
|
||||
$currentWebsite->method('getCode')->willReturn('us_site');
|
||||
$storeManager = $this->createMock(StoreManagerInterface::class);
|
||||
$storeManager->method('getWebsite')->willReturn($currentWebsite);
|
||||
|
||||
$response = $this->createMock(HttpResponse::class);
|
||||
$response->expects(self::once())->method('setRedirect')->with('https://en.example.test/', 302);
|
||||
$response->expects(self::once())
|
||||
->method('setHeader')
|
||||
->with('Cache-Control', 'private, no-store, max-age=0', true);
|
||||
|
||||
$plugin = new FrontControllerPlugin(
|
||||
$eligibility,
|
||||
$countryResolver,
|
||||
$websiteResolver,
|
||||
$targetUrlBuilder,
|
||||
$cookie,
|
||||
$storeManager,
|
||||
$response,
|
||||
$this->createMock(LoggerInterface::class)
|
||||
);
|
||||
|
||||
$result = $plugin->aroundDispatch(
|
||||
$this->createMock(FrontControllerInterface::class),
|
||||
static fn () => throw new \LogicException('Front controller must not be called.'),
|
||||
$request
|
||||
);
|
||||
|
||||
self::assertSame($response, $result);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<?xml version="1.0"?>
|
||||
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="urn:magento:framework:Acl/etc/acl.xsd">
|
||||
<acl>
|
||||
<resources>
|
||||
<resource id="Magento_Backend::admin">
|
||||
<resource id="Magento_Backend::stores">
|
||||
<resource id="Magento_Backend::stores_settings">
|
||||
<resource id="Magento_Config::config">
|
||||
<resource id="Esun3d_GeoWebsiteRedirect::config"
|
||||
title="Geo Website Redirect Configuration"
|
||||
sortOrder="90"/>
|
||||
</resource>
|
||||
</resource>
|
||||
</resource>
|
||||
</resource>
|
||||
</resources>
|
||||
</acl>
|
||||
</config>
|
||||
@@ -0,0 +1,9 @@
|
||||
<?xml version="1.0"?>
|
||||
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
|
||||
<router id="admin">
|
||||
<route id="geo_website_redirect" frontName="geo_website_redirect">
|
||||
<module name="Esun3d_GeoWebsiteRedirect"/>
|
||||
</route>
|
||||
</router>
|
||||
</config>
|
||||
@@ -0,0 +1,104 @@
|
||||
<?xml version="1.0"?>
|
||||
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="urn:magento:framework:Config/etc/system_file.xsd">
|
||||
<system>
|
||||
<section id="geo_website_redirect"
|
||||
translate="label"
|
||||
sortOrder="910"
|
||||
showInDefault="1"
|
||||
showInWebsite="0"
|
||||
showInStore="0">
|
||||
<label>Geo Website Redirect</label>
|
||||
<tab>general</tab>
|
||||
<resource>Esun3d_GeoWebsiteRedirect::config</resource>
|
||||
<group id="general" translate="label" sortOrder="10" showInDefault="1" showInWebsite="0" showInStore="0">
|
||||
<label>General</label>
|
||||
<field id="enabled" translate="label comment" type="select" sortOrder="10" showInDefault="1" showInWebsite="0" showInStore="0">
|
||||
<label>Enable Geo Website Redirect</label>
|
||||
<comment>Redirects first-time visitors according to the country resolved from their IP address.</comment>
|
||||
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
|
||||
</field>
|
||||
<field id="redirect_scope" translate="label comment" type="select" sortOrder="20" showInDefault="1" showInWebsite="0" showInStore="0">
|
||||
<label>Redirect Scope</label>
|
||||
<comment>Homepage Only is recommended to avoid breaking deep links.</comment>
|
||||
<source_model>Esun3d\GeoWebsiteRedirect\Model\Config\Source\RedirectScope</source_model>
|
||||
<depends>
|
||||
<field id="enabled">1</field>
|
||||
</depends>
|
||||
</field>
|
||||
<field id="preserve_path" translate="label comment" type="select" sortOrder="30" showInDefault="1" showInWebsite="0" showInStore="0">
|
||||
<label>Preserve Request Path</label>
|
||||
<comment>Enable only when URL keys are consistent across websites.</comment>
|
||||
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
|
||||
<depends>
|
||||
<field id="enabled">1</field>
|
||||
<field id="redirect_scope">all</field>
|
||||
</depends>
|
||||
</field>
|
||||
<field id="cookie_lifetime" translate="label" type="text" sortOrder="40" showInDefault="1" showInWebsite="0" showInStore="0">
|
||||
<label>Selection Cookie Lifetime (Seconds)</label>
|
||||
<validate>required-entry validate-number validate-greater-than-zero</validate>
|
||||
<depends>
|
||||
<field id="enabled">1</field>
|
||||
</depends>
|
||||
</field>
|
||||
<field id="cookie_domain" translate="label comment" type="text" sortOrder="50" showInDefault="1" showInWebsite="0" showInStore="0">
|
||||
<label>Selection Cookie Domain</label>
|
||||
<comment>Use the shared parent domain, for example .esun3d.com. Leave blank for a host-only cookie.</comment>
|
||||
<depends>
|
||||
<field id="enabled">1</field>
|
||||
</depends>
|
||||
</field>
|
||||
</group>
|
||||
<group id="mapping" translate="label" sortOrder="20" showInDefault="1" showInWebsite="0" showInStore="0">
|
||||
<label>Website Mapping</label>
|
||||
<field id="uk_website" translate="label" type="select" sortOrder="10" showInDefault="1" showInWebsite="0" showInStore="0">
|
||||
<label>United Kingdom Website</label>
|
||||
<source_model>Esun3d\GeoWebsiteRedirect\Model\Config\Source\Website</source_model>
|
||||
</field>
|
||||
<field id="au_website" translate="label" type="select" sortOrder="20" showInDefault="1" showInWebsite="0" showInStore="0">
|
||||
<label>Australia Website</label>
|
||||
<source_model>Esun3d\GeoWebsiteRedirect\Model\Config\Source\Website</source_model>
|
||||
</field>
|
||||
<field id="eu_website" translate="label" type="select" sortOrder="30" showInDefault="1" showInWebsite="0" showInStore="0">
|
||||
<label>European Union Website</label>
|
||||
<source_model>Esun3d\GeoWebsiteRedirect\Model\Config\Source\Website</source_model>
|
||||
</field>
|
||||
<field id="default_website" translate="label" type="select" sortOrder="40" showInDefault="1" showInWebsite="0" showInStore="0">
|
||||
<label>Default Website</label>
|
||||
<source_model>Esun3d\GeoWebsiteRedirect\Model\Config\Source\Website</source_model>
|
||||
</field>
|
||||
<field id="eu_countries" translate="label comment" type="textarea" sortOrder="50" showInDefault="1" showInWebsite="0" showInStore="0">
|
||||
<label>EU Country Codes</label>
|
||||
<comment>Comma, space, or line separated ISO 3166-1 alpha-2 codes. GB is always handled by the UK mapping.</comment>
|
||||
</field>
|
||||
</group>
|
||||
<group id="exclusions" translate="label" sortOrder="30" showInDefault="1" showInWebsite="0" showInStore="0">
|
||||
<label>Exclusions</label>
|
||||
<field id="ignore_bots" translate="label" type="select" sortOrder="10" showInDefault="1" showInWebsite="0" showInStore="0">
|
||||
<label>Ignore Search Engines and Bots</label>
|
||||
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
|
||||
</field>
|
||||
<field id="user_agents" translate="label comment" type="textarea" sortOrder="20" showInDefault="1" showInWebsite="0" showInStore="0">
|
||||
<label>Ignored User-Agent Patterns</label>
|
||||
<comment>One case-insensitive text pattern per line.</comment>
|
||||
<depends>
|
||||
<field id="ignore_bots">1</field>
|
||||
</depends>
|
||||
</field>
|
||||
<field id="paths" translate="label comment" type="textarea" sortOrder="30" showInDefault="1" showInWebsite="0" showInStore="0">
|
||||
<label>Excluded Path Prefixes</label>
|
||||
<comment>One path prefix per line, without the leading slash.</comment>
|
||||
</field>
|
||||
</group>
|
||||
<group id="testing" translate="label" sortOrder="40" showInDefault="1" showInWebsite="0" showInStore="0">
|
||||
<label>Test IP</label>
|
||||
<field id="test_ip" translate="label comment" type="text" sortOrder="10" showInDefault="1" showInWebsite="0" showInStore="0">
|
||||
<label>IP Address</label>
|
||||
<comment>Tests GeoIP and website mapping without saving configuration or redirecting the browser.</comment>
|
||||
<frontend_model>Esun3d\GeoWebsiteRedirect\Block\Adminhtml\System\Config\TestIp</frontend_model>
|
||||
</field>
|
||||
</group>
|
||||
</section>
|
||||
</system>
|
||||
</config>
|
||||
@@ -0,0 +1,48 @@
|
||||
<?xml version="1.0"?>
|
||||
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Store:etc/config.xsd">
|
||||
<default>
|
||||
<geo_website_redirect>
|
||||
<general>
|
||||
<enabled>0</enabled>
|
||||
<redirect_scope>homepage</redirect_scope>
|
||||
<preserve_path>0</preserve_path>
|
||||
<cookie_lifetime>2592000</cookie_lifetime>
|
||||
<cookie_domain></cookie_domain>
|
||||
</general>
|
||||
<mapping>
|
||||
<uk_website>uk</uk_website>
|
||||
<au_website>au</au_website>
|
||||
<eu_website>eu</eu_website>
|
||||
<default_website>us_site</default_website>
|
||||
<eu_countries>AT,BE,BG,HR,CY,CZ,DK,EE,FI,FR,DE,GR,HU,IE,IT,LV,LT,LU,MT,NL,PL,PT,RO,SK,SI,ES,SE</eu_countries>
|
||||
</mapping>
|
||||
<exclusions>
|
||||
<ignore_bots>1</ignore_bots>
|
||||
<user_agents>googlebot
|
||||
bingbot
|
||||
slurp
|
||||
duckduckbot
|
||||
baiduspider
|
||||
yandexbot
|
||||
applebot
|
||||
facebookexternalhit
|
||||
twitterbot
|
||||
crawler
|
||||
spider
|
||||
bot</user_agents>
|
||||
<paths>rest
|
||||
graphql
|
||||
soap
|
||||
static
|
||||
media
|
||||
pub
|
||||
checkout
|
||||
customer
|
||||
paypal
|
||||
payment
|
||||
webhook</paths>
|
||||
</exclusions>
|
||||
</geo_website_redirect>
|
||||
</default>
|
||||
</config>
|
||||
@@ -0,0 +1,14 @@
|
||||
<?xml version="1.0"?>
|
||||
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
|
||||
<type name="Magento\Framework\App\FrontControllerInterface">
|
||||
<plugin name="esun3d_geo_website_redirect"
|
||||
type="Esun3d\GeoWebsiteRedirect\Plugin\FrontControllerPlugin"
|
||||
sortOrder="-10"/>
|
||||
</type>
|
||||
<type name="Esun3d\LanguageUrlStoreResolver\ViewModel\LocaleSwitcher">
|
||||
<plugin name="esun3d_geo_website_redirect_switcher_config"
|
||||
type="Esun3d\GeoWebsiteRedirect\Plugin\LocaleSwitcherConfigPlugin"
|
||||
sortOrder="10"/>
|
||||
</type>
|
||||
</config>
|
||||
@@ -0,0 +1,12 @@
|
||||
<?xml version="1.0"?>
|
||||
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
|
||||
<module name="Esun3d_GeoWebsiteRedirect">
|
||||
<sequence>
|
||||
<module name="Magento_Store"/>
|
||||
<module name="Magento_PageCache"/>
|
||||
<module name="Amasty_Geoip"/>
|
||||
<module name="Esun3d_LanguageUrlStoreResolver"/>
|
||||
</sequence>
|
||||
</module>
|
||||
</config>
|
||||
@@ -0,0 +1,10 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
use Magento\Framework\Component\ComponentRegistrar;
|
||||
|
||||
ComponentRegistrar::register(
|
||||
ComponentRegistrar::MODULE,
|
||||
'Esun3d_GeoWebsiteRedirect',
|
||||
__DIR__
|
||||
);
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
<?php
|
||||
/** @var \Esun3d\GeoWebsiteRedirect\Block\Adminhtml\System\Config\TestIp $block */
|
||||
$element = $block->getData('element');
|
||||
$inputId = $element->getHtmlId();
|
||||
$config = [
|
||||
'Esun3d_GeoWebsiteRedirect/js/test-ip' => [
|
||||
'url' => $block->getResolveUrl(),
|
||||
],
|
||||
];
|
||||
?>
|
||||
<div class="geo-website-test" data-mage-init='<?= /* @noEscape */ json_encode($config) ?>'>
|
||||
<div class="admin__field-control">
|
||||
<input id="<?= $block->escapeHtmlAttr($inputId) ?>"
|
||||
class="admin__control-text"
|
||||
type="text"
|
||||
placeholder="8.8.8.8"
|
||||
data-role="ip" />
|
||||
<button type="button" class="action-default scalable" data-role="test">
|
||||
<span><?= $block->escapeHtml(__('Test IP')) ?></span>
|
||||
</button>
|
||||
</div>
|
||||
<div class="message" data-role="message" hidden></div>
|
||||
<table class="admin__table-secondary" data-role="result" hidden>
|
||||
<tbody>
|
||||
<tr>
|
||||
<th><?= $block->escapeHtml(__('IP Address')) ?></th>
|
||||
<td data-field="ip"></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th><?= $block->escapeHtml(__('Masked IP Used by GeoIP')) ?></th>
|
||||
<td data-field="masked_ip"></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th><?= $block->escapeHtml(__('Country')) ?></th>
|
||||
<td data-field="country"></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th><?= $block->escapeHtml(__('City')) ?></th>
|
||||
<td data-field="city"></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th><?= $block->escapeHtml(__('Website')) ?></th>
|
||||
<td data-field="website"></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th><?= $block->escapeHtml(__('Target URL')) ?></th>
|
||||
<td><a data-field="target_url" target="_blank" rel="noopener"></a></td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
@@ -0,0 +1,74 @@
|
||||
define([
|
||||
'jquery',
|
||||
'mage/translate'
|
||||
], function ($, $t) {
|
||||
'use strict';
|
||||
|
||||
return function (config, element) {
|
||||
var container = $(element),
|
||||
input = container.find('[data-role="ip"]'),
|
||||
button = container.find('[data-role="test"]'),
|
||||
message = container.find('[data-role="message"]'),
|
||||
result = container.find('[data-role="result"]');
|
||||
|
||||
function showMessage(text, isError) {
|
||||
message
|
||||
.removeClass('message-error message-warning')
|
||||
.addClass(isError ? 'message-error' : 'message-warning')
|
||||
.text(text)
|
||||
.prop('hidden', !text);
|
||||
}
|
||||
|
||||
function showResult(data) {
|
||||
result.find('[data-field="ip"]').text(data.ip);
|
||||
result.find('[data-field="masked_ip"]').text(data.masked_ip);
|
||||
result.find('[data-field="country"]').text(data.country);
|
||||
result.find('[data-field="city"]').text(data.city || '-');
|
||||
result.find('[data-field="website"]').text(data.website_name + ' (' + data.website_code + ')');
|
||||
result.find('[data-field="target_url"]').text(data.target_url).attr('href', data.target_url);
|
||||
result.prop('hidden', false);
|
||||
|
||||
showMessage(
|
||||
data.force_ip_enabled
|
||||
? $t('Amasty Force IP is enabled. The live redirect may use its forced IP; this test always uses the IP entered above.')
|
||||
: '',
|
||||
false
|
||||
);
|
||||
}
|
||||
|
||||
function testIp() {
|
||||
result.prop('hidden', true);
|
||||
showMessage('', false);
|
||||
button.prop('disabled', true);
|
||||
|
||||
$.ajax({
|
||||
url: config.url,
|
||||
type: 'POST',
|
||||
dataType: 'json',
|
||||
data: {
|
||||
ip: input.val(),
|
||||
form_key: window.FORM_KEY
|
||||
}
|
||||
}).done(function (response) {
|
||||
if (response.success) {
|
||||
showResult(response.data);
|
||||
return;
|
||||
}
|
||||
|
||||
showMessage(response.message || $t('The IP test failed.'), true);
|
||||
}).fail(function () {
|
||||
showMessage($t('The IP test request failed.'), true);
|
||||
}).always(function () {
|
||||
button.prop('disabled', false);
|
||||
});
|
||||
}
|
||||
|
||||
button.on('click', testIp);
|
||||
input.on('keydown', function (event) {
|
||||
if (event.key === 'Enter') {
|
||||
event.preventDefault();
|
||||
testIp();
|
||||
}
|
||||
});
|
||||
};
|
||||
});
|
||||
@@ -0,0 +1,9 @@
|
||||
var config = {
|
||||
config: {
|
||||
mixins: {
|
||||
'Esun3d_LanguageUrlStoreResolver/js/locale-switcher': {
|
||||
'Esun3d_GeoWebsiteRedirect/js/locale-switcher-mixin': true
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,34 @@
|
||||
define([
|
||||
'jquery'
|
||||
], function ($) {
|
||||
'use strict';
|
||||
|
||||
return function (originalWidget) {
|
||||
return function (config, element) {
|
||||
var redirectConfig = (config.data || {}).geoRedirect || {};
|
||||
var $market = $(element).find('[data-role="market"]');
|
||||
|
||||
if (redirectConfig.enabled) {
|
||||
$market.on('change.geoWebsiteRedirect', function () {
|
||||
var websiteCode = String($(this).val() || '');
|
||||
var attributes = '; path=/; max-age=' + redirectConfig.cookieLifetime + '; SameSite=Lax';
|
||||
|
||||
if (!websiteCode) {
|
||||
return;
|
||||
}
|
||||
if (redirectConfig.cookieDomain) {
|
||||
attributes += '; domain=' + redirectConfig.cookieDomain;
|
||||
}
|
||||
if (window.location.protocol === 'https:') {
|
||||
attributes += '; Secure';
|
||||
}
|
||||
|
||||
document.cookie = redirectConfig.cookieName
|
||||
+ '=' + encodeURIComponent(websiteCode) + attributes;
|
||||
});
|
||||
}
|
||||
|
||||
return originalWidget(config, element);
|
||||
};
|
||||
};
|
||||
});
|
||||
Reference in New Issue
Block a user