ltsecurityinc安防产品在线商城代码

This commit is contained in:
2026-09-14 17:47:10 +08:00
parent 57d8444c15
commit 6a3c9c5bd8
14539 changed files with 1775310 additions and 0 deletions
@@ -0,0 +1,40 @@
<?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\Api;
interface GeoIPLookupInterface
{
/**
* Returns GeoIpData with possibility to choose services and their priority
*
* @param string $ip
* @param string $params comma separated list of services to use, e.g. 'ipapi,maxmind,iptocountry'
* @api
* @return string|array
*/
public function getGeoIpData($ip, $params = '');
/**
* Returns GeoIpData
*
* @param string $ip
* @api
* @return string|array
*/
public function getGeoIpDataWithDefaultServices($ip);
}
@@ -0,0 +1,32 @@
<?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\Api;
/**
* @since 2.0.0
*/
interface GeoIpServiceInterface
{
/**
* @param string|null $ip
* @return array|null
*/
public function getGeoLocation(?string $ip): ?array;
/**
* @param string|null $ip
* @return string|null
*/
public function getCountryCode(?string $ip): ?string;
/**
* @param string|null $ip
* @return string|null
*/
public function getCurrentCountryState(?string $ip): ?string;
}
@@ -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) 2020 Plumrocket Inc. (http://www.plumrocket.com)
* @license http://wiki.plumrocket.net/wiki/EULA End-user License Agreement
*/
namespace Plumrocket\GeoIPLookup\Api;
/**
* @since 1.2.0
*/
interface GeoLocationValidatorInterface
{
/**
* @param array $regions
* @param array $counties
* @param array $usaStates
* @param string|null $ip
* @return bool
* @throws \Magento\Framework\Exception\LocalizedException if extension isn't ready to look up
*/
public function validate(array $regions, array $counties, array $usaStates = [], ?string $ip = null): bool;
/**
* @param array $options regions and countries
* @param array $usaStates
* @param string|null $ip
* @return bool
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function validateByMergedOptions(array $options, array $usaStates = [], ?string $ip = null): bool;
}
@@ -0,0 +1,65 @@
<?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\Api;
/**
* @since 1.2.0
*/
interface LocationsListInterface
{
/**
* All site visitors
*/
public const ALL = 'all';
/**
* Only visitors from EU countries
*/
public const EU = 'eu';
/**
* Only visitors from unrecognized locations
*/
public const UNKNOWN = 'unknown';
public const COUNTRY_CODE_USA = 'US';
public const USA_STATE_CALIFORNIA = 'California';
/**
* Return array of regions as value-label pairs
*
* @return array Format: array(array('value' => '<value>', 'label' => '<label>'), ...)
*/
public function getRegions(): array;
/**
* Return array of counties as value-label pairs
*
* @return array Format: array(array('value' => '<value>', 'label' => '<label>'), ...)
*/
public function getCountries(): array;
/**
* Return array of states as value-label pairs
*
* @param string $countryName
* @return array Format: array(array('value' => '<value>', 'label' => '<label>'), ...)
*/
public function getCountryStates(string $countryName): array;
}
@@ -0,0 +1,103 @@
<?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\Block\Adminhtml\System\Config\Data\Buttons;
use Magento\Framework\Data\Form\Element\AbstractElement;
class AbstractBlock extends \Magento\Config\Block\System\Config\Form\Field
{
/**
* Template path
*/
public $template = "system/config/button.phtml";
/**
* Button Label
*/
public $buttonLabel;
/**
* @var \Plumrocket\GeoIPLookup\Helper\Config
*/
public $configHelper;
/**
* @param \Plumrocket\GeoIPLookup\Helper\Config $configHelper
* @param \Magento\Backend\Block\Template\Context $context
* @param array $data
*/
public function __construct(
\Plumrocket\GeoIPLookup\Helper\Config $configHelper,
\Magento\Backend\Block\Template\Context $context,
array $data = []
) {
parent::__construct($context, $data);
$this->configHelper = $configHelper;
}
/**
* @return $this|\Magento\Config\Block\System\Config\Form\Field
*/
protected function _prepareLayout()
{
parent::_prepareLayout();
if (!$this->getTemplate()) {
$this->setTemplate($this->template);
}
return $this;
}
/**
* @param \Magento\Framework\Data\Form\Element\AbstractElement $element
* @return string
*/
public function render(AbstractElement $element)
{
$element->unsScope()->unsCanUseWebsiteValue()->unsCanUseDefaultValue();
return parent::render($element);
}
/**
* @param \Magento\Framework\Data\Form\Element\AbstractElement $element
* @return string
*/
protected function _getElementHtml(AbstractElement $element)
{
$originalData = $element->getOriginalData();
$buttonLabel = !empty($originalData['button_label']) ? $originalData['button_label'] : $this->buttonLabel;
$this->addData(
[
'button_label' => __($buttonLabel),
'html_id' => $element->getHtmlId(),
'onclick' => $this->getOnclick($element->getHtmlId())
]
);
return $this->_toHtml();
}
/**
* @return string
*/
public function getOnclick($htmlId = null)
{
return 'return false;';
}
}
@@ -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) 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\Block\Adminhtml\System\Config\Data\Buttons;
use Plumrocket\GeoIPLookup\Helper\Config;
class Connection extends AbstractBlock
{
/**
* Button Label
*/
public $buttonLabel = 'Test Connection';
/**
* @param $htmlId
* @return null|string
*/
public function getOnclick($htmlId = null)
{
return sprintf(
'window.prGeoIptestApiConnection(\'%s\', \'%s\'); return false;',
$this->getUrl('prgeoiplookup/test/ipapiEndpoint'),
$htmlId
);
}
}
@@ -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) 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\Block\Adminhtml\System\Config\Data\Buttons;
class Install extends AbstractBlock
{
/**
* Button Label
*/
public $buttonLabel = 'Install Database';
/**
* @return string
*/
public function getOnclick($htmlId = null)
{
$serviceId = mb_substr($htmlId, 0, mb_strrpos($htmlId, "_"));
$urlAutomatic = $this->getUrl(
'prgeoiplookup/import/autoimport',
['dataId' => $serviceId]
);
$urlProgress = $this->getUrl(
'prgeoiplookup/import/importprogress',
['dataId' => $serviceId, 'is_progress' => 1]
);
return "window.runInstallation('$serviceId', '$urlAutomatic', '$urlProgress'); return false;";
}
}
@@ -0,0 +1,100 @@
<?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\Block\Adminhtml\System\Config\Data;
use Plumrocket\GeoIPLookup\Helper\Config;
class Enable extends \Magento\Config\Block\System\Config\Form\Field
{
/**
* @var \Plumrocket\GeoIPLookup\Helper\Data
*/
private $dataHelper;
/**
* @var \Plumrocket\GeoIPLookup\Model\Data\Import\Iptocountry
*/
private $ipToCountry;
/**
* @var \Plumrocket\GeoIPLookup\Model\Data\Import\Maxmindgeoip
*/
private $maxmindGeoIp;
/**
* Enable constructor.
*
* @param \Plumrocket\GeoIPLookup\Helper\Data $dataHelper
* @param \Plumrocket\GeoIPLookup\Model\Data\Import\Iptocountry $ipToCountry
* @param \Plumrocket\GeoIPLookup\Model\Data\Import\Maxmindgeoip $maxmindGeoIp
* @param \Magento\Backend\Block\Template\Context $context
* @param array $data
*/
public function __construct(
\Plumrocket\GeoIPLookup\Helper\Data $dataHelper,
\Plumrocket\GeoIPLookup\Model\Data\Import\Iptocountry $ipToCountry,
\Plumrocket\GeoIPLookup\Model\Data\Import\Maxmindgeoip $maxmindGeoIp,
\Magento\Backend\Block\Template\Context $context,
array $data = []
) {
$this->dataHelper = $dataHelper;
$this->ipToCountry = $ipToCountry;
$this->maxmindGeoIp = $maxmindGeoIp;
parent::__construct($context, $data);
}
/**
* @param \Magento\Framework\Data\Form\Element\AbstractElement $element
* @return string
*/
protected function _renderValue(\Magento\Framework\Data\Form\Element\AbstractElement $element)
{
$dataVersion = null;
$elementId = $element->getId();
$modelName = $this->dataHelper->getModelNameByElementId($elementId, false, true);
$tooltip = '';
switch ($modelName) {
case Config::IPTOCOUNTRY_GROUP:
$dataVersion = $this->ipToCountry->getInstalledMessage();
break;
case Config::MAXMIND_GROUP:
$dataVersion = $this->maxmindGeoIp->getInstalledMessage();
break;
}
if (! $dataVersion) {
$element->setDisabled('disabled');
$form = $element->getForm();
$serviceId = mb_substr($elementId, 0, mb_strrpos($elementId, "_"));
$fieldset = $form->getElement($serviceId);
$title = __('Please install %1 in order to enable this IP Geolocation method.', $fieldset->getLegend());
$tooltip .= '<div id="' . $serviceId . '_tooltip" class="tooltip">
<span><span><img src="' . $this->getViewFileUrl('Plumrocket_Base::images/error_msg_icon.gif')
. '" style="margin-top: 2px;float: right;" /></span></span>';
$tooltip .= '<div class="tooltip-content">' . $title . '</div></div>';
}
$html = '<td class="value with-tooltip">';
$html .= $this->_getElementHtml($element) . $tooltip;
$html .= '</td>';
return $html;
}
}
@@ -0,0 +1,97 @@
<?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\Block\Adminhtml\System\Config\Data;
use Plumrocket\GeoIPLookup\Helper\Config;
class Status extends \Magento\Config\Block\System\Config\Form\Field
{
/**
* @var \Plumrocket\GeoIPLookup\Helper\Data
*/
private $dataHelper;
/**
* @var \Plumrocket\GeoIPLookup\Model\Data\Import\Iptocountry
*/
private $ipToCountry;
/**
* @var \Plumrocket\GeoIPLookup\Model\Data\Import\Maxmindgeoip
*/
private $maxmindGeoIp;
/**
* Status constructor.
*
* @param \Plumrocket\GeoIPLookup\Helper\Data $dataHelper
* @param \Plumrocket\GeoIPLookup\Model\Data\Import\Iptocountry $ipToCountry
* @param \Plumrocket\GeoIPLookup\Model\Data\Import\Maxmindgeoip $maxmindGeoIp
* @param \Magento\Backend\Block\Template\Context $context
* @param array $data
*/
public function __construct(
\Plumrocket\GeoIPLookup\Helper\Data $dataHelper,
\Plumrocket\GeoIPLookup\Model\Data\Import\Iptocountry $ipToCountry,
\Plumrocket\GeoIPLookup\Model\Data\Import\Maxmindgeoip $maxmindGeoIp,
\Magento\Backend\Block\Template\Context $context,
array $data = []
) {
$this->dataHelper = $dataHelper;
$this->ipToCountry = $ipToCountry;
$this->maxmindGeoIp = $maxmindGeoIp;
parent::__construct($context, $data);
}
/**
* @param \Magento\Framework\Data\Form\Element\AbstractElement $element
* @return string
*/
protected function _getElementHtml(\Magento\Framework\Data\Form\Element\AbstractElement $element)
{
$dataVersion = null;
$elementId = $element->getId();
$modelName = $this->dataHelper->getModelNameByElementId($elementId, false, true);
switch ($modelName) {
case Config::IPTOCOUNTRY_GROUP:
$dataVersion = $this->ipToCountry->getInstalledMessage();
break;
case Config::MAXMIND_GROUP:
$dataVersion = $this->maxmindGeoIp->getInstalledMessage();
break;
}
$elementStyle = ($dataVersion) ? "color: green" : "color: red";
$elementText = $dataVersion ?: __('Not Installed')->render();
$html = '
<div id="' . $elementId . '" class="status-container">
<span class="status" style="' . $elementStyle . '">' . $elementText . '</span>
<div class="progress-container" style="display: none;">
<div class="progress-bar w3-light-grey w3-border">
<div class="progress-value w3-container w3-blue w3-center" style="width:0%">0%</div>
</div>
<div class="progress-title"></div>
</div>
</div>
';
return $html;
}
}
@@ -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\Block\Adminhtml\System\Config\Data\Test;
class Api extends \Magento\Config\Block\System\Config\Form\Field
{
/**
* Rest Api Static Path
*/
const REST_PATH = 'rest/V1/prgeoiplookup/';
/**
* @param \Magento\Framework\Data\Form\Element\AbstractElement $element
* @return string
*/
public function _getElementHtml(\Magento\Framework\Data\Form\Element\AbstractElement $element)
{
$html = '<p id="hidden_field_api_url">' . $this->getRestApiUrl() . '</p>'
. '<a id="rest_ip_test" target="_blank" href=""></a>';
return $html;
}
private function getRestApiUrl()
{
return $this->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_WEB) . self::REST_PATH;
}
}
@@ -0,0 +1,42 @@
<?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\Block\Adminhtml\System\Config\Data\Test;
class Button extends \Plumrocket\GeoIPLookup\Block\Adminhtml\System\Config\Data\Buttons\AbstractBlock
{
/**
* Button Label
*/
public $buttonLabel = 'Get Location From IP';
/**
* @param null $htmlId
* @return string
*/
public function getOnclick($htmlId = null)
{
$urlTest = $this->getUrl(
'prgeoiplookup/test/index'
);
return sprintf(
'window.geoipTest(\'%s\'); return false;',
$urlTest
);
}
}
@@ -0,0 +1,53 @@
<?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\Block\Adminhtml\System\Config\Data\Test;
class Ipaddress extends \Magento\Config\Block\System\Config\Form\Field
{
/**
* @var \Magento\Framework\HTTP\PhpEnvironment\RemoteAddress
*/
private $remoteAddress;
/**
* Ipaddress constructor.
*
* @param \Magento\Framework\HTTP\PhpEnvironment\RemoteAddress $remoteAddress
* @param \Magento\Backend\Block\Template\Context $context
* @param array $data
*/
public function __construct(
\Magento\Framework\HTTP\PhpEnvironment\RemoteAddress $remoteAddress,
\Magento\Backend\Block\Template\Context $context,
array $data = []
) {
$this->remoteAddress = $remoteAddress;
parent::__construct($context, $data);
}
/**
* @param \Magento\Framework\Data\Form\Element\AbstractElement $element
* @return string
*/
protected function _getElementHtml(\Magento\Framework\Data\Form\Element\AbstractElement $element)
{
$ip = $this->remoteAddress->getRemoteAddress();
$element->setValue($ip);
return parent::_getElementHtml($element);
}
}
@@ -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) 2018 Plumrocket Inc. (http://www.plumrocket.com)
* @license http://wiki.plumrocket.net/wiki/EULA End-user License Agreement
*/
namespace Plumrocket\GeoIPLookup\Block\Adminhtml\System\Config\Data\Test;
class Map extends \Magento\Config\Block\System\Config\Form\Field
{
/**
* @param \Magento\Framework\Data\Form\Element\AbstractElement $element
* @return string
*/
public function _getElementHtml(\Magento\Framework\Data\Form\Element\AbstractElement $element)
{
$html = __('Open in')
. " <a id='prgeoiplookup_google_map' target='_blank' href='https://www.google.com/maps'>"
. __('Google Maps') . "</a>";
return $html;
}
}
@@ -0,0 +1,144 @@
<?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\Block\Adminhtml\System\Config\Form;
use Magento\Backend\Block\Template\Context;
use Magento\Backend\Model\UrlInterface;
use Magento\Config\Block\System\Config\Form\Field;
use Magento\Framework\Data\Form\Element\AbstractElement;
use Magento\Framework\View\Element\Html\Select as HtmlSelect;
use Plumrocket\GeoIPLookup\Api\LocationsListInterface;
use Plumrocket\GeoIPLookup\Helper\Config;
use Plumrocket\GeoIPLookup\Model\System\Config\Source\GeoTargeting;
/**
* @since 1.2.2
*/
class GeoTargetingMultiSelect extends Field
{
/**
* @var \Plumrocket\GeoIPLookup\Model\System\Config\Source\GeoTargeting
*/
private $geoIPRestrictions;
/**
* @var \Plumrocket\GeoIPLookup\Helper\Config
*/
private $config;
/**
* @var \Magento\Backend\Model\UrlInterface
*/
private $backendUrl;
/**
* @param \Magento\Backend\Block\Template\Context $context
* @param \Plumrocket\GeoIPLookup\Model\System\Config\Source\GeoTargeting $geoIPRestrictions
* @param \Plumrocket\GeoIPLookup\Helper\Config $config
* @param \Magento\Backend\Model\UrlInterface $backendUrl
* @param array $data
*/
public function __construct(
Context $context,
GeoTargeting $geoIPRestrictions,
Config $config,
UrlInterface $backendUrl,
array $data = []
) {
parent::__construct($context, $data);
$this->geoIPRestrictions = $geoIPRestrictions;
$this->config = $config;
$this->backendUrl = $backendUrl;
}
/**
* @param \Magento\Framework\Data\Form\Element\AbstractElement $element
* @return string
*/
protected function _getElementHtml(AbstractElement $element)
{
$html = $this->getGeoIpRestrictionsNotice();
$value = $element->getEscapedValue();
$extraParams = ' multiple';
if (! $this->config->isConfiguredForUse()) {
$extraParams .= ' readonly="readonly"';
$value = LocationsListInterface::ALL;
}
/** @var HtmlSelect $select */
$select = $this->getLayout()->createBlock(HtmlSelect::class);
$optionArray = $this->geoIPRestrictions->toOptionArray();
$select->setOptions($optionArray)
->setId($element->getId())
->setName($element->getName())
->setValue(explode(',', $value))
->setExtraParams($extraParams)
->setClass($element->getClass());
$html .= $select->toHtml();
return $html;
}
public function getGeoIpRestrictionsNotice($withContainer = true)
{
$href = $this->backendUrl->getUrl('adminhtml/system_config/edit', [
'section' => 'prgeoiplookup',
]);
$message = '';
switch (true) {
case ! $this->config->isModuleEnabled():
$message = __(
'The GDPR Geo Targeting is disabled. Click <a target="_blank" href="%1">here</a> to open ' .
'Plumrocket IP Geolocation Lookup configuration and enable extension.',
$href
);
break;
case ! $this->config->getEnableMethodsNumber():
$message = __(
'Please enable at least one IP geolocation lookup database in order to use GDPR Geo Targeting. ' .
'Click <a target="_blank" href="%1">here</a> to open Plumrocket IP Geolocation Lookup configuration ' .
'and enable databases.',
$href
);
break;
}
return (bool) $withContainer && ! empty($message)
? $this->getPreparedNoticeHtml($message)
: $message;
}
/**
* @param $message
* @return string
*/
public function getPreparedNoticeHtml($message): string
{
$style = 'style="margin: 25px 5px;color: #eb5202;background: none;font-size:14px"';
return "<div $style><div><i>$message</i></div></div>";
}
}
@@ -0,0 +1,89 @@
<?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\Block\Adminhtml\System\Config\Form;
use Magento\Backend\Block\Template\Context;
use Magento\Config\Block\System\Config\Form\Field;
use Magento\Framework\Data\Form\Element\AbstractElement;
use Magento\Framework\View\Element\Html\Select as HtmlSelect;
use Plumrocket\GeoIPLookup\Api\LocationsListInterface;
use Plumrocket\GeoIPLookup\Helper\Config;
use Plumrocket\GeoIPLookup\Model\System\Config\Source\GeoTargetingStates;
/**
* @since 1.2.2
*/
class StatesGeoTargetingMultiSelect extends Field
{
/**
* @var \Plumrocket\GeoIPLookup\Model\System\Config\Source\GeoTargetingStates
*/
private $geoTargetingStates;
/**
* @var \Plumrocket\GeoIPLookup\Helper\Config
*/
private $config;
/**
* @param \Magento\Backend\Block\Template\Context $context
* @param \Plumrocket\GeoIPLookup\Model\System\Config\Source\GeoTargetingStates $geoTargetingStates
* @param \Plumrocket\GeoIPLookup\Helper\Config $config
* @param array $data
*/
public function __construct(
Context $context,
GeoTargetingStates $geoTargetingStates,
Config $config,
array $data = []
) {
parent::__construct($context, $data);
$this->geoTargetingStates = $geoTargetingStates;
$this->config = $config;
}
/**
* @param \Magento\Framework\Data\Form\Element\AbstractElement $element
* @return string
*/
protected function _getElementHtml(AbstractElement $element)
{
$value = $element->getEscapedValue();
$extraParams = ' multiple';
if (! $this->config->isConfiguredForUse()) {
$extraParams .= ' readonly="readonly"';
$value = LocationsListInterface::ALL;
}
/** @var HtmlSelect $select */
$select = $this->getLayout()->createBlock(HtmlSelect::class);
$optionArray = $this->geoTargetingStates->toOptionArray();
$select->setOptions($optionArray)
->setId($element->getId())
->setName($element->getName())
->setValue(explode(',', $value))
->setExtraParams($extraParams)
->setClass($element->getClass());
return $select->toHtml();
}
}
@@ -0,0 +1,73 @@
<?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\Block\Adminhtml\System\Config;
class Notice extends \Magento\Config\Block\System\Config\Form\Field
{
/**
* @var \Plumrocket\GeoIPLookup\Helper\Config
*/
private $config;
/**
* Notice constructor.
*
* @param \Plumrocket\GeoIPLookup\Helper\Config $config
* @param \Magento\Backend\Block\Template\Context $context
* @param array $data
*/
public function __construct(
\Plumrocket\GeoIPLookup\Helper\Config $config,
\Magento\Backend\Block\Template\Context $context,
array $data = []
) {
$this->config = $config;
parent::__construct($context, $data);
}
/**
* @param \Magento\Framework\Data\Form\Element\AbstractElement $element
* @return string
*/
public function render(\Magento\Framework\Data\Form\Element\AbstractElement $element)
{
$elementId = $element->getId();
$html = '';
$enableMethodsNumber = $this->config->getEnableMethodsNumber();
if ($enableMethodsNumber < 2) {
$text = __("Please Note!");
if ($enableMethodsNumber == 0) {
$text .= " " . __("You must enable at least one service for this extension to function properly.");
}
$text .= " " . __("We recommend to enable 2 or more services
below to provide the most accurate IP geolocation results.
");
$html .= '
<tr>
<td class="label" colspan="4" style="text-align:left;">
<div id="' . $elementId . '" class="prgeoiplookup-service-notice">' . $text . '</div>
</td>
</tr>
';
}
return $html;
}
}
@@ -0,0 +1,103 @@
<?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\Controller\Adminhtml\Import;
class Autoimport extends \Magento\Backend\App\Action
{
/**
* @var \Magento\Framework\Controller\Result\JsonFactory
*/
private $resultJsonFactory;
/**
* @var \Plumrocket\GeoIPLookup\Helper\Data
*/
private $dataHelper;
/**
* @var \Magento\Framework\Json\Helper\Data
*/
private $jsonHelper;
/**
* @var \Plumrocket\GeoIPLookup\Model\Data\Import\Maxmindgeoip
*/
private $maxmindgeoip;
/**
* @var \Plumrocket\GeoIPLookup\Model\Data\Import\Iptocountry
*/
private $iptocountry;
/**
* Autoimport constructor.
*
* @param \Magento\Backend\App\Action\Context $context
* @param \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory
* @param \Magento\Framework\Json\Helper\Data $jsonHelper
* @param \Plumrocket\GeoIPLookup\Helper\Data $dataHelper
* @param \Plumrocket\GeoIPLookup\Model\Data\Import\Maxmindgeoip $maxmindgeoip
* @param \Plumrocket\GeoIPLookup\Model\Data\Import\Iptocountry $iptocountry
*/
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory,
\Magento\Framework\Json\Helper\Data $jsonHelper,
\Plumrocket\GeoIPLookup\Helper\Data $dataHelper,
\Plumrocket\GeoIPLookup\Model\Data\Import\Maxmindgeoip $maxmindgeoip,
\Plumrocket\GeoIPLookup\Model\Data\Import\Iptocountry $iptocountry
) {
parent::__construct($context);
$this->resultJsonFactory = $resultJsonFactory;
$this->dataHelper = $dataHelper;
$this->jsonHelper = $jsonHelper;
$this->maxmindgeoip = $maxmindgeoip;
$this->iptocountry = $iptocountry;
}
/**
* @return \Magento\Framework\App\ResponseInterface|\Magento\Framework\Controller\Result\Json|\Magento\Framework\Controller\ResultInterface
*/
public function execute()
{
session_write_close();
$resultJson = $this->resultJsonFactory->create();
$dataId = $this->getRequest()->getParam('dataId');
$modelName = $this->dataHelper->getModelNameByElementId($dataId, false);
$importModel = $this->{$modelName};
if ($importModel->isLatestInstalledVersion()) {
$result = [
'status' => 'success',
'error' => __('Geolocation Database Update'),
'alert' => __(
"You have the latest %1 Geolocation Database available on our server.
Please check back later for the updates.",
$importModel->getDataLabel()
),
'message' => $importModel->getInstalledMessage()
];
} else {
$result = $importModel->autoImportData();
}
return $resultJson->setData(
$this->jsonHelper->jsonEncode($result)
);
}
}
@@ -0,0 +1,101 @@
<?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\Controller\Adminhtml\Import;
class Importprogress extends \Magento\Backend\App\Action
{
/**
* @var \Magento\Framework\Controller\Result\JsonFactory
*/
private $resultJsonFactory;
/**
* @var \Plumrocket\GeoIPLookup\Helper\Data
*/
private $dataHelper;
/**
* @var \Magento\Framework\Filesystem\Io\File
*/
private $ioFile;
/**
* @var \Magento\Framework\Json\Helper\Data
*/
private $jsonHelper;
/**
* @var \Plumrocket\GeoIPLookup\Model\Data\Import\Maxmindgeoip
*/
private $maxmindgeoip;
/**
* @var \Plumrocket\GeoIPLookup\Model\Data\Import\Iptocountry
*/
private $iptocountry;
/**
* Importprogress constructor.
*
* @param \Magento\Backend\App\Action\Context $context
* @param \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory
* @param \Magento\Framework\Json\Helper\Data $jsonHelper
* @param \Plumrocket\GeoIPLookup\Helper\Data $dataHelper
* @param \Magento\Framework\Filesystem\Io\File $ioFile
* @param \Plumrocket\GeoIPLookup\Model\Data\Import\Maxmindgeoip $maxmindgeoip
* @param \Plumrocket\GeoIPLookup\Model\Data\Import\Iptocountry $iptocountry
*/
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory,
\Magento\Framework\Json\Helper\Data $jsonHelper,
\Plumrocket\GeoIPLookup\Helper\Data $dataHelper,
\Magento\Framework\Filesystem\Io\File $ioFile,
\Plumrocket\GeoIPLookup\Model\Data\Import\Maxmindgeoip $maxmindgeoip,
\Plumrocket\GeoIPLookup\Model\Data\Import\Iptocountry $iptocountry
) {
parent::__construct($context);
$this->resultJsonFactory = $resultJsonFactory;
$this->dataHelper = $dataHelper;
$this->ioFile = $ioFile;
$this->jsonHelper = $jsonHelper;
$this->maxmindgeoip = $maxmindgeoip;
$this->iptocountry = $iptocountry;
}
/**
* @return \Magento\Framework\App\ResponseInterface|\Magento\Framework\Controller\Result\Json
* |\Magento\Framework\Controller\ResultInterface
*/
public function execute()
{
$resultJson = $this->resultJsonFactory->create();
$dataId = $this->getRequest()->getParam('dataId');
$modelName = $this->dataHelper->getModelNameByElementId($dataId, false);
$importModel = $this->{$modelName};
$importProgress = $importModel->getProgress();
if ($importProgress['status'] == 'success') {
$this->ioFile->rm($importModel->getProgressFile());
}
return $resultJson->setData(
$this->jsonHelper->jsonEncode($importProgress)
);
}
}
@@ -0,0 +1,71 @@
<?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\Controller\Adminhtml\Test;
class Index extends \Magento\Backend\App\Action
{
/**
* @var \Magento\Framework\Controller\Result\JsonFactory
*/
private $resultJsonFactory;
/**
* @var \Magento\Framework\Json\Helper\Data
*/
private $jsonHelper;
/**
* @var \Plumrocket\GeoIPLookup\Model\GeoIPLookup
*/
private $geoIPLookup;
/**
* Index constructor.
*
* @param \Magento\Backend\App\Action\Context $context
* @param \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory
* @param \Magento\Framework\Json\Helper\Data $jsonHelper
* @param \Plumrocket\GeoIPLookup\Model\GeoIPLookup $geoIPLookup
*/
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory,
\Magento\Framework\Json\Helper\Data $jsonHelper,
\Plumrocket\GeoIPLookup\Model\GeoIPLookup $geoIPLookup
) {
parent::__construct($context);
$this->resultJsonFactory = $resultJsonFactory;
$this->jsonHelper = $jsonHelper;
$this->geoIPLookup = $geoIPLookup;
}
/**
* @return \Magento\Framework\App\ResponseInterface|\Magento\Framework\Controller\Result\Json
* |\Magento\Framework\Controller\ResultInterface
*/
public function execute()
{
$resultJson = $this->resultJsonFactory->create();
$ip = $this->getRequest()->getParam('ip');
$result = $this->geoIPLookup->geoIpLookupTest($ip);
return $resultJson->setData(
$this->jsonHelper->jsonEncode($result)
);
}
}
@@ -0,0 +1,84 @@
<?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\Controller\Adminhtml\Test;
use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\HTTP\Client\Curl;
use Magento\Framework\Serialize\Serializer\Json;
use Plumrocket\GeoIPLookup\Helper\Config;
/**
* @since 2.0.1
*/
class IpapiEndpoint extends Action
{
/**
* @var \Plumrocket\GeoIPLookup\Helper\Config
*/
private $configHelper;
/**
* @var \Magento\Framework\HTTP\Client\Curl
*/
private $curl;
/**
* @var \Magento\Framework\Serialize\Serializer\Json
*/
private $serializer;
/**
* @param \Magento\Backend\App\Action\Context $context
* @param \Plumrocket\GeoIPLookup\Helper\Config $configHelper
* @param \Magento\Framework\HTTP\Client\Curl $curl
* @param \Magento\Framework\Serialize\Serializer\Json $serializer
*/
public function __construct(
Context $context,
Config $configHelper,
Curl $curl,
Json $serializer
) {
parent::__construct($context);
$this->configHelper = $configHelper;
$this->curl = $curl;
$this->serializer = $serializer;
}
public function execute()
{
$params = $this->getRequest()->getParams();
$protocol = !empty($params['use_ssl']) ? 'https://' : 'http://';
$baseUrl = $this->configHelper->getIpApiUrl(Config::DEFAULT_IP, false);
$url = $protocol . $baseUrl . "?access_key={$params['access_key']}";
$this->curl->get($url);
$response = $this->serializer->unserialize($this->curl->getBody());
$resultData = ['success' => false];
if (isset($response['success'])) {
if (isset($response['error']['info'])) {
if (isset($response['error']['code']) && $response['error']['code'] !== 101) {
$resultData['success'] = true;
} else {
$resultData['message'] = $response['error']['info'];
}
}
} else if (isset($response['ip']) && $response['ip'] === Config::DEFAULT_IP) {
$resultData['success'] = true;
}
/** @var \Magento\Framework\Controller\Result\Json $result */
$result = $this->resultFactory->create('json');
return $result->setData($resultData);
}
}
+239
View File
@@ -0,0 +1,239 @@
<?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\Helper;
use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Framework\App\Helper\Context;
use Plumrocket\Base\Model\ConfigUtils;
/**
* Class Config use for retrieve module configuration
*/
class Config extends AbstractHelper
{
/**
* Name of Maxmind Group
*/
public const MAXMIND_GROUP = 'maxmindgeoip';
/**
* Name of IpToCountry Group
*/
public const IPTOCOUNTRY_GROUP = 'iptocountry';
/**
* Name of Ipapi Group
*/
public const IPAPI_GROUP = 'ipapigeoip';
/**
* Local File Path
*/
public const LOCAL_PATH = 'prgeoiplookup/data/';
/**
* Name of GeoIp Test Group
*/
public const IPAPI_CONNECTION_URL = 'api.ipapi.com';
/**
* Default Ip for testing
*/
public const DEFAULT_IP = '192.168.1.1';
public const IPTOCOUNTRY_SOURCE_FILE_NAME = 'IpToCountry.mmdb';
public const IPTOCOUNTRY_SOURCE_FILE_URL = 'https://plumrocket.com/docs/wp-content/uploads/geoip/v2/' . self::IPTOCOUNTRY_SOURCE_FILE_NAME;
public const IPTOCOUNTRY_DATABASE_NAME = 'Iptocountry';
public const MAXMIND_SOURCE_FILE_NAME = 'MaxMind.mmdb';
public const MAXMIND_SOURCE_FILE_URL = 'https://plumrocket.com/docs/wp-content/uploads/geoip/v2/' . self::MAXMIND_SOURCE_FILE_NAME;
public const MAXMIND_DATABASE_NAME = 'Maxmind';
/**
* Version source file on Wiki
*/
public const PATH_VERSION_FILE = 'https://plumrocket.com/docs/wp-content/uploads/geoip/v2/versions.csv';
/**
* @var \Plumrocket\Base\Model\ConfigUtils
*/
private $configUtils;
/**
* @param \Magento\Framework\App\Helper\Context $context
* @param \Plumrocket\Base\Model\ConfigUtils $configUtils
*/
public function __construct(
Context $context,
ConfigUtils $configUtils
) {
parent::__construct($context);
$this->configUtils = $configUtils;
}
/**
* @param $path
* @param null $store
* @param null $scope
* @return mixed
*/
private function getConfigForCurrentSection($path, $store = null, $scope = null)
{
return $this->configUtils->getConfig(
'prgeoiplookup/'. $path,
$store,
$scope
);
}
/**
* @inheritDoc
*/
public function isModuleEnabled($store = null, $scope = null): bool
{
return $this->configUtils->isSetFlag('prgeoiplookup/general/enabled', $store, $scope);
}
/**
* @return bool
*/
public function isConfiguredForUse(): bool
{
return $this->isModuleEnabled() && $this->getEnableMethodsNumber();
}
/**
* @param int|string $store
* @return bool
*/
public function enabledMaxmindGeoIp($store = null)
{
return (bool)$this->getConfigForCurrentSection(
'methods/' . self::MAXMIND_GROUP . '/enabled',
$store
);
}
/**
* @param int|string $store
* @return string
*/
public function getMaxmindInstallMethod($store = null)
{
return $this->getConfigForCurrentSection(
'methods/' . self::MAXMIND_GROUP . '/install_method',
$store
);
}
/**
* @param int|string $store
* @return bool
*/
public function enabledIpToCountryGeoIp($store = null)
{
return (bool)$this->getConfigForCurrentSection(
'methods/' . self::IPTOCOUNTRY_GROUP . '/enabled',
$store
);
}
/**
* @param int|string $store
* @return string
*/
public function getIpToCountryInstallMethod($store = null)
{
return $this->getConfigForCurrentSection(
'methods/' . self::IPTOCOUNTRY_GROUP . '/install_method',
$store
);
}
/**
* @param int|string $store
* @return bool
*/
public function enabledIpApiGeoIp($store = null)
{
return (bool)$this->getConfigForCurrentSection(
'methods/' . self::IPAPI_GROUP . '/enabled',
$store
);
}
/**
* @param null $store
* @return bool
*/
public function useIpApiHttps($store = null)
{
return (bool) $this->getConfigForCurrentSection(
'methods/' . self::IPAPI_GROUP . '/use_https',
$store
);
}
/**
* @param null $store
* @return bool
*/
private function getIpApiAccessKey($store = null)
{
return (string)$this->getConfigForCurrentSection(
'methods/' . self::IPAPI_GROUP . '/access_key',
$store
);
}
/**
* @param $ip
* @return string
*/
public function getIpApiUrl($ip = self::DEFAULT_IP, $withAccessKey = true)
{
$apiUrl = self::IPAPI_CONNECTION_URL . '/' . $ip;
if ($withAccessKey) {
$apiUrl .= '?access_key=' . $this->getIpApiAccessKey();
}
return $apiUrl;
}
/**
* @param null $store
* @return int
*/
public function getEnableMethodsNumber($store = null)
{
$methodsArray = [self::MAXMIND_GROUP, self::IPTOCOUNTRY_GROUP, self::IPAPI_GROUP];
$count = 0;
foreach ($methodsArray as $method) {
if ($this->getConfigForCurrentSection(
'methods/' . $method . '/enabled',
$store
)) {
$count++;
}
}
return $count;
}
}
@@ -0,0 +1,67 @@
<?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\Helper\Config;
use Plumrocket\Base\Helper\ConfigUtils;
/**
* @since 1.2.2
*/
class CookieConsentGeo extends ConfigUtils
{
const XML_PATH_GEO_TARGETING = 'pr_cookie/main_settings/geo_targeting';
const XML_PATH_STATES_GEO_TARGETING = 'pr_cookie/main_settings/states_geo_targeting';
/**
* Retrieve config values
*
* @param null $store
* @param null $scope
* @return array
*/
public function getGeoTargeting($store = null, $scope = null): array
{
$geoTargetingConfig = (string) $this->getConfig(
self::XML_PATH_GEO_TARGETING,
$store,
$scope
);
return array_filter($this->prepareMultiselectValue($geoTargetingConfig));
}
/**
* Retrieve config values
*
* @param null $store
* @param null $scope
* @return array
*/
public function getStatesGeoTargeting($store = null, $scope = null): array
{
$geoTargetingConfig = (string) $this->getConfig(
self::XML_PATH_STATES_GEO_TARGETING,
$store,
$scope
);
return $this->prepareMultiselectValue($geoTargetingConfig);
}
}
+62
View File
@@ -0,0 +1,62 @@
<?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\Helper;
use Magento\Framework\App\Helper\AbstractHelper;
/**
* Class Data Helper
*/
class Data extends AbstractHelper
{
/**
* @var \Magento\Framework\Stdlib\DateTime\TimezoneInterface
*/
private $timezone;
/**
* @param \Magento\Framework\App\Helper\Context $context
* @param \Magento\Framework\Stdlib\DateTime\TimezoneInterface $timezone
*/
public function __construct(
\Magento\Framework\App\Helper\Context $context,
\Magento\Framework\Stdlib\DateTime\TimezoneInterface $timezone
) {
parent::__construct($context);
$this->timezone = $timezone;
}
/**
* @param $elementId
* @return mixed
*/
public function getModelNameByElementId($elementId, $upercase = true, $penultimate = false)
{
if ($penultimate) {
$elementId = mb_substr($elementId, 0, mb_strrpos($elementId, "_"));
}
$elements = explode('_', $elementId);
$modelName = end($elements);
if ($upercase) {
$modelName = ucfirst($modelName);
}
return $modelName;
}
}
@@ -0,0 +1,433 @@
<?php
declare(strict_types=1);
namespace Plumrocket\GeoIPLookup\Library\Mmdb;
use ArgumentCountError;
use BadMethodCallException;
use InvalidArgumentException;
use Plumrocket\GeoIPLookup\Library\Mmdb\Reader\Decoder;
use Plumrocket\GeoIPLookup\Library\Mmdb\Reader\InvalidDatabaseException;
use Plumrocket\GeoIPLookup\Library\Mmdb\Reader\Metadata;
use Plumrocket\GeoIPLookup\Library\Mmdb\Reader\Util;
use UnexpectedValueException;
use function chr;
use function count;
use function func_num_args;
use function is_resource;
use function ord;
/**
* Instances of this class provide a reader for the MaxMind DB format. IP
* addresses can be looked up using the get method.
*/
class Reader
{
/**
* @var int
*/
private static $DATA_SECTION_SEPARATOR_SIZE = 16;
/**
* @var string
*/
private static $METADATA_START_MARKER = "\xAB\xCD\xEFMaxMind.com";
/**
* @var int<0, max>
*/
private static $METADATA_START_MARKER_LENGTH = 14;
/**
* @var int
*/
private static $METADATA_MAX_SIZE = 131072; // 128 * 1024 = 128KiB
/**
* @var Decoder
*/
private $decoder;
/**
* @var resource
*/
private $fileHandle;
/**
* @var int
*/
private $fileSize;
/**
* @var int
*/
private $ipV4Start;
/**
* @var Metadata
*/
private $metadata;
/**
* Constructs a Reader for the MaxMind DB format. The file passed to it must
* be a valid MaxMind DB file such as a GeoIp2 database file.
*
* @param string $database
* the MaxMind DB file to use
*
* @throws \InvalidArgumentException for invalid database path or unknown arguments
* @throws InvalidDatabaseException
* if the database is invalid or there is an error reading
* from it
*/
public function __construct(string $database)
{
if (func_num_args() !== 1) {
throw new ArgumentCountError(
sprintf('%s() expects exactly 1 parameter, %d given', __METHOD__, func_num_args())
);
}
$fileHandle = fopen($database, 'rb');
if ($fileHandle === false) {
throw new InvalidArgumentException(
"The file \"$database\" does not exist or is not readable."
);
}
$this->fileHandle = $fileHandle;
$fileSize = filesize($database);
if ($fileSize === false) {
throw new UnexpectedValueException(
"Error determining the size of \"$database\"."
);
}
$this->fileSize = $fileSize;
$start = $this->findMetadataStart($database);
$metadataDecoder = new Decoder($this->fileHandle, $start);
[$metadataArray] = $metadataDecoder->decode($start);
$this->metadata = new Metadata($metadataArray);
$this->decoder = new Decoder(
$this->fileHandle,
$this->metadata->searchTreeSize + self::$DATA_SECTION_SEPARATOR_SIZE
);
$this->ipV4Start = $this->ipV4StartNode();
}
/**
* Retrieves the record for the IP address.
*
* @param string $ipAddress
* the IP address to look up
*
* @throws \BadMethodCallException if this method is called on a closed database
* @throws \InvalidArgumentException if something other than a single IP address is passed to the method
* @throws InvalidDatabaseException
* if the database is invalid or there is an error reading
* from it
*
* @return mixed the record for the IP address
*/
public function get(string $ipAddress)
{
if (func_num_args() !== 1) {
throw new ArgumentCountError(
sprintf('%s() expects exactly 1 parameter, %d given', __METHOD__, func_num_args())
);
}
[$record] = $this->getWithPrefixLen($ipAddress);
return $record;
}
/**
* Retrieves the record for the IP address and its associated network prefix length.
*
* @param string $ipAddress
* the IP address to look up
*
* @throws \BadMethodCallException if this method is called on a closed database
* @throws \InvalidArgumentException if something other than a single IP address is passed to the method
* @throws InvalidDatabaseException
* if the database is invalid or there is an error reading
* from it
*
* @return array an array where the first element is the record and the
* second the network prefix length for the record
*/
public function getWithPrefixLen(string $ipAddress): array
{
if (func_num_args() !== 1) {
throw new ArgumentCountError(
sprintf('%s() expects exactly 1 parameter, %d given', __METHOD__, func_num_args())
);
}
if (!is_resource($this->fileHandle)) {
throw new BadMethodCallException(
'Attempt to read from a closed MaxMind DB.'
);
}
[$pointer, $prefixLen] = $this->findAddressInTree($ipAddress);
if ($pointer === 0) {
return [null, $prefixLen];
}
return [$this->resolveDataPointer($pointer), $prefixLen];
}
/**
* @param string $ipAddress
* @return array|int[]
* @throws \Plumrocket\GeoIPLookup\Library\Mmdb\Reader\InvalidDatabaseException
*/
private function findAddressInTree(string $ipAddress): array
{
$packedAddr = inet_pton($ipAddress);
if ($packedAddr === false) {
throw new InvalidArgumentException(
"The value \"$ipAddress\" is not a valid IP address."
);
}
$rawAddress = unpack('C*', $packedAddr);
if ($rawAddress === false) {
throw new InvalidDatabaseException(
'Could not unpack the unsigned char of the packed in_addr representation.'
);
}
$bitCount = count($rawAddress) * 8;
// The first node of the tree is always node 0, at the beginning of the
// value
$node = 0;
$metadata = $this->metadata;
// Check if we are looking up an IPv4 address in an IPv6 tree. If this
// is the case, we can skip over the first 96 nodes.
if ($metadata->ipVersion === 6) {
if ($bitCount === 32) {
$node = $this->ipV4Start;
}
} elseif ($metadata->ipVersion === 4 && $bitCount === 128) {
throw new InvalidArgumentException(
"Error looking up $ipAddress. You attempted to look up an"
. ' IPv6 address in an IPv4-only database.'
);
}
$nodeCount = $metadata->nodeCount;
for ($i = 0; $i < $bitCount && $node < $nodeCount; ++$i) {
$tempBit = 0xFF & $rawAddress[($i >> 3) + 1];
$bit = 1 & ($tempBit >> 7 - ($i % 8));
$node = $this->readNode($node, $bit);
}
if ($node === $nodeCount) {
// Record is empty
return [0, $i];
}
if ($node > $nodeCount) {
// Record is a data pointer
return [$node, $i];
}
throw new InvalidDatabaseException(
'Invalid or corrupt database. Maximum search depth reached without finding a leaf node'
);
}
/**
* @return int
* @throws \Plumrocket\GeoIPLookup\Library\Mmdb\Reader\InvalidDatabaseException
*/
private function ipV4StartNode(): int
{
// If we have an IPv4 database, the start node is the first node
if ($this->metadata->ipVersion === 4) {
return 0;
}
$node = 0;
for ($i = 0; $i < 96 && $node < $this->metadata->nodeCount; ++$i) {
$node = $this->readNode($node, 0);
}
return $node;
}
/**
* @param int $nodeNumber
* @param int $index
* @return int
* @throws \Plumrocket\GeoIPLookup\Library\Mmdb\Reader\InvalidDatabaseException
*/
private function readNode(int $nodeNumber, int $index): int
{
$baseOffset = $nodeNumber * $this->metadata->nodeByteSize;
switch ($this->metadata->recordSize) {
case 24:
$bytes = Util::read($this->fileHandle, $baseOffset + $index * 3, 3);
$rc = unpack('N', "\x00" . $bytes);
if ($rc === false) {
throw new InvalidDatabaseException(
'Could not unpack the unsigned long of the node.'
);
}
[, $node] = $rc;
return $node;
case 28:
$bytes = Util::read($this->fileHandle, $baseOffset + 3 * $index, 4);
if ($index === 0) {
$middle = (0xF0 & ord($bytes[3])) >> 4;
} else {
$middle = 0x0F & ord($bytes[0]);
}
$rc = unpack('N', chr($middle) . substr($bytes, $index, 3));
if ($rc === false) {
throw new InvalidDatabaseException(
'Could not unpack the unsigned long of the node.'
);
}
[, $node] = $rc;
return $node;
case 32:
$bytes = Util::read($this->fileHandle, $baseOffset + $index * 4, 4);
$rc = unpack('N', $bytes);
if ($rc === false) {
throw new InvalidDatabaseException(
'Could not unpack the unsigned long of the node.'
);
}
[, $node] = $rc;
return $node;
default:
throw new InvalidDatabaseException(
'Unknown record size: '
. $this->metadata->recordSize
);
}
}
/**
* @param int $pointer
* @return mixed
* @throws \Plumrocket\GeoIPLookup\Library\Mmdb\Reader\InvalidDatabaseException
*/
private function resolveDataPointer(int $pointer)
{
$resolved = $pointer - $this->metadata->nodeCount
+ $this->metadata->searchTreeSize;
if ($resolved >= $this->fileSize) {
throw new InvalidDatabaseException(
"The MaxMind DB file's search tree is corrupt"
);
}
[$data] = $this->decoder->decode($resolved);
return $data;
}
/**
* This is an extremely naive but reasonably readable implementation. There
* are much faster algorithms (e.g., Boyer-Moore) for this if speed is ever
* an issue, but I suspect it won't be.
*
* @param string $filename
* @return int
* @throws \Plumrocket\GeoIPLookup\Library\Mmdb\Reader\InvalidDatabaseException
*/
private function findMetadataStart(string $filename): int
{
$handle = $this->fileHandle;
$fstat = fstat($handle);
if ($fstat === false) {
throw new InvalidDatabaseException(
"Error getting file information ($filename)."
);
}
$fileSize = $fstat['size'];
$marker = self::$METADATA_START_MARKER;
$markerLength = self::$METADATA_START_MARKER_LENGTH;
$minStart = $fileSize - min(self::$METADATA_MAX_SIZE, $fileSize);
for ($offset = $fileSize - $markerLength; $offset >= $minStart; --$offset) {
if (fseek($handle, $offset) !== 0) {
break;
}
$value = fread($handle, $markerLength);
if ($value === $marker) {
return $offset + $markerLength;
}
}
throw new InvalidDatabaseException(
"Error opening database file ($filename). " .
'Is this a valid MaxMind DB file?'
);
}
/**
* @throws \InvalidArgumentException if arguments are passed to the method
* @throws \BadMethodCallException if the database has been closed
*
* @return Metadata object for the database
*/
public function metadata(): Metadata
{
if (func_num_args()) {
throw new ArgumentCountError(
sprintf('%s() expects exactly 0 parameters, %d given', __METHOD__, func_num_args())
);
}
// Not technically required, but this makes it consistent with
// C extension, and it allows us to change our implementation later.
if (!is_resource($this->fileHandle)) {
throw new BadMethodCallException(
'Attempt to read from a closed MaxMind DB.'
);
}
return clone $this->metadata;
}
/**
* Closes the MaxMind DB and returns resources to the system.
*
* @throws \Exception
* if an I/O error occurs
*/
public function close(): void
{
if (func_num_args()) {
throw new ArgumentCountError(
sprintf('%s() expects exactly 0 parameters, %d given', __METHOD__, func_num_args())
);
}
if (!is_resource($this->fileHandle)) {
throw new BadMethodCallException(
'Attempt to close a closed MaxMind DB.'
);
}
fclose($this->fileHandle);
}
}
@@ -0,0 +1,515 @@
<?php
declare(strict_types=1);
namespace Plumrocket\GeoIPLookup\Library\Mmdb\Reader;
use RuntimeException;
use function chr;
use function extension_loaded;
use function ord;
use const PHP_INT_MAX;
use const PHP_INT_SIZE;
use const STR_PAD_LEFT;
class Decoder
{
/**
* @var resource
*/
private $fileStream;
/**
* @var int
*/
private $pointerBase;
/**
* This is only used for unit testing.
*
* @var bool
*/
private $pointerTestHack;
/**
* @var bool
*/
private $switchByteOrder;
private const _EXTENDED = 0;
private const _POINTER = 1;
private const _UTF8_STRING = 2;
private const _DOUBLE = 3;
private const _BYTES = 4;
private const _UINT16 = 5;
private const _UINT32 = 6;
private const _MAP = 7;
private const _INT32 = 8;
private const _UINT64 = 9;
private const _UINT128 = 10;
private const _ARRAY = 11;
// 12 is the container type
// 13 is the end marker type
private const _BOOLEAN = 14;
private const _FLOAT = 15;
/**
* @param resource $fileStream
* @param int $pointerBase
* @param bool $pointerTestHack
* @throws \Plumrocket\GeoIPLookup\Library\Mmdb\Reader\InvalidDatabaseException
*/
public function __construct(
$fileStream,
int $pointerBase = 0,
bool $pointerTestHack = false
) {
$this->fileStream = $fileStream;
$this->pointerBase = $pointerBase;
$this->pointerTestHack = $pointerTestHack;
$this->switchByteOrder = $this->isPlatformLittleEndian();
}
/**
* @param int $offset
* @return array
* @throws \Plumrocket\GeoIPLookup\Library\Mmdb\Reader\InvalidDatabaseException
*/
public function decode(int $offset): array
{
$ctrlByte = ord(Util::read($this->fileStream, $offset, 1));
++$offset;
$type = $ctrlByte >> 5;
// Pointers are a special case, we don't read the next $size bytes, we
// use the size to determine the length of the pointer and then follow
// it.
if ($type === self::_POINTER) {
[$pointer, $offset] = $this->decodePointer($ctrlByte, $offset);
// for unit testing
if ($this->pointerTestHack) {
return [$pointer];
}
[$result] = $this->decode($pointer);
return [$result, $offset];
}
if ($type === self::_EXTENDED) {
$nextByte = ord(Util::read($this->fileStream, $offset, 1));
$type = $nextByte + 7;
if ($type < 8) {
throw new InvalidDatabaseException(
'Something went horribly wrong in the decoder. An extended type '
. 'resolved to a type number < 8 ('
. $type
. ')'
);
}
++$offset;
}
[$size, $offset] = $this->sizeFromCtrlByte($ctrlByte, $offset);
return $this->decodeByType($type, $offset, $size);
}
/**
* @param int $type
* @param int $offset
* @param int<0, max> $size
* @return array
* @throws \Plumrocket\GeoIPLookup\Library\Mmdb\Reader\InvalidDatabaseException
*/
private function decodeByType(int $type, int $offset, int $size): array
{
switch ($type) {
case self::_MAP:
return $this->decodeMap($size, $offset);
case self::_ARRAY:
return $this->decodeArray($size, $offset);
case self::_BOOLEAN:
return [$this->decodeBoolean($size), $offset];
}
$newOffset = $offset + $size;
$bytes = Util::read($this->fileStream, $offset, $size);
switch ($type) {
case self::_BYTES:
case self::_UTF8_STRING:
return [$bytes, $newOffset];
case self::_DOUBLE:
$this->verifySize(8, $size);
return [$this->decodeDouble($bytes), $newOffset];
case self::_FLOAT:
$this->verifySize(4, $size);
return [$this->decodeFloat($bytes), $newOffset];
case self::_INT32:
return [$this->decodeInt32($bytes, $size), $newOffset];
case self::_UINT16:
case self::_UINT32:
case self::_UINT64:
case self::_UINT128:
return [$this->decodeUint($bytes, $size), $newOffset];
default:
throw new InvalidDatabaseException(
'Unknown or unexpected type: ' . $type
);
}
}
/**
* @param int $expected
* @param int $actual
* @return void
* @throws \Plumrocket\GeoIPLookup\Library\Mmdb\Reader\InvalidDatabaseException
*/
private function verifySize(int $expected, int $actual): void
{
if ($expected !== $actual) {
throw new InvalidDatabaseException(
"The MaxMind DB file's data section contains bad data (unknown data type or corrupt data)"
);
}
}
/**
* @param int $size
* @param int $offset
* @return array
* @throws \Plumrocket\GeoIPLookup\Library\Mmdb\Reader\InvalidDatabaseException
*/
private function decodeArray(int $size, int $offset): array
{
$array = [];
for ($i = 0; $i < $size; ++$i) {
[$value, $offset] = $this->decode($offset);
$array[] = $value;
}
return [$array, $offset];
}
/**
* @param int $size
* @return bool
*/
private function decodeBoolean(int $size): bool
{
return $size !== 0;
}
/**
* @param string $bytes
* @return float
* @throws \Plumrocket\GeoIPLookup\Library\Mmdb\Reader\InvalidDatabaseException
*/
private function decodeDouble(string $bytes): float
{
// This assumes IEEE 754 doubles, but most (all?) modern platforms
// use them.
$rc = unpack('E', $bytes);
if ($rc === false) {
throw new InvalidDatabaseException(
'Could not unpack a double value from the given bytes.'
);
}
[, $double] = $rc;
return $double;
}
/**
* @param string $bytes
* @return float
* @throws \Plumrocket\GeoIPLookup\Library\Mmdb\Reader\InvalidDatabaseException
*/
private function decodeFloat(string $bytes): float
{
// This assumes IEEE 754 floats, but most (all?) modern platforms
// use them.
$rc = unpack('G', $bytes);
if ($rc === false) {
throw new InvalidDatabaseException(
'Could not unpack a float value from the given bytes.'
);
}
[, $float] = $rc;
return $float;
}
/**
* @param string $bytes
* @param int $size
* @return int
* @throws \Plumrocket\GeoIPLookup\Library\Mmdb\Reader\InvalidDatabaseException
*/
private function decodeInt32(string $bytes, int $size): int
{
switch ($size) {
case 0:
return 0;
case 1:
case 2:
case 3:
$bytes = str_pad($bytes, 4, "\x00", STR_PAD_LEFT);
break;
case 4:
break;
default:
throw new InvalidDatabaseException(
"The MaxMind DB file's data section contains bad data (unknown data type or corrupt data)"
);
}
$rc = unpack('l', $this->maybeSwitchByteOrder($bytes));
if ($rc === false) {
throw new InvalidDatabaseException(
'Could not unpack a 32bit integer value from the given bytes.'
);
}
[, $int] = $rc;
return $int;
}
/**
* @param int $size
* @param int $offset
* @return array
* @throws \Plumrocket\GeoIPLookup\Library\Mmdb\Reader\InvalidDatabaseException
*/
private function decodeMap(int $size, int $offset): array
{
$map = [];
for ($i = 0; $i < $size; ++$i) {
[$key, $offset] = $this->decode($offset);
[$value, $offset] = $this->decode($offset);
$map[$key] = $value;
}
return [$map, $offset];
}
/**
* @param int $ctrlByte
* @param int $offset
* @return array
* @throws \Plumrocket\GeoIPLookup\Library\Mmdb\Reader\InvalidDatabaseException
*/
private function decodePointer(int $ctrlByte, int $offset): array
{
$pointerSize = (($ctrlByte >> 3) & 0x3) + 1;
$buffer = Util::read($this->fileStream, $offset, $pointerSize);
$offset += $pointerSize;
switch ($pointerSize) {
case 1:
$packed = chr($ctrlByte & 0x7) . $buffer;
$rc = unpack('n', $packed);
if ($rc === false) {
throw new InvalidDatabaseException(
'Could not unpack an unsigned short value from the given bytes (pointerSize is 1).'
);
}
[, $pointer] = $rc;
$pointer += $this->pointerBase;
break;
case 2:
$packed = "\x00" . chr($ctrlByte & 0x7) . $buffer;
$rc = unpack('N', $packed);
if ($rc === false) {
throw new InvalidDatabaseException(
'Could not unpack an unsigned long value from the given bytes (pointerSize is 2).'
);
}
[, $pointer] = $rc;
$pointer += $this->pointerBase + 2048;
break;
case 3:
$packed = chr($ctrlByte & 0x7) . $buffer;
// It is safe to use 'N' here, even on 32 bit machines as the
// first bit is 0.
$rc = unpack('N', $packed);
if ($rc === false) {
throw new InvalidDatabaseException(
'Could not unpack an unsigned long value from the given bytes (pointerSize is 3).'
);
}
[, $pointer] = $rc;
$pointer += $this->pointerBase + 526336;
break;
case 4:
// We cannot use unpack here as we might overflow on 32 bit
// machines
$pointerOffset = $this->decodeUint($buffer, $pointerSize);
$pointerBase = $this->pointerBase;
if (PHP_INT_MAX - $pointerBase >= $pointerOffset) {
$pointer = $pointerOffset + $pointerBase;
} else {
throw new RuntimeException(
'The database offset is too large to be represented on your platform.'
);
}
break;
default:
throw new InvalidDatabaseException(
'Unexpected pointer size ' . $pointerSize
);
}
return [$pointer, $offset];
}
/**
* @param string $bytes
* @param int $byteLength
* @return int|string
*/
private function decodeUint(string $bytes, int $byteLength)
{
if ($byteLength === 0) {
return 0;
}
// PHP integers are signed. PHP_INT_SIZE - 1 is the number of
// complete bytes that can be converted to an integer. However,
// we can convert another byte if the leading bit is zero.
$useRealInts = $byteLength <= PHP_INT_SIZE - 1
|| ($byteLength === PHP_INT_SIZE && (ord($bytes[0]) & 0x80) === 0);
if ($useRealInts) {
$integer = 0;
for ($i = 0; $i < $byteLength; ++$i) {
$part = ord($bytes[$i]);
$integer = ($integer << 8) + $part;
}
return $integer;
}
// We only use gmp or bcmath if the final value is too big
$integerAsString = '0';
for ($i = 0; $i < $byteLength; ++$i) {
$part = ord($bytes[$i]);
if (extension_loaded('gmp')) {
$integerAsString = gmp_strval(gmp_add(gmp_mul($integerAsString, '256'), $part));
} elseif (extension_loaded('bcmath')) {
$integerAsString = bcadd(bcmul($integerAsString, '256'), (string) $part);
} else {
throw new RuntimeException(
'The gmp or bcmath extension must be installed to read this database.'
);
}
}
return $integerAsString;
}
/**
* @param int $ctrlByte
* @param int $offset
* @return array|int[]
* @throws \Plumrocket\GeoIPLookup\Library\Mmdb\Reader\InvalidDatabaseException
*/
private function sizeFromCtrlByte(int $ctrlByte, int $offset): array
{
$size = $ctrlByte & 0x1F;
if ($size < 29) {
return [$size, $offset];
}
$bytesToRead = $size - 28;
$bytes = Util::read($this->fileStream, $offset, $bytesToRead);
if ($size === 29) {
$size = 29 + ord($bytes);
} elseif ($size === 30) {
$rc = unpack('n', $bytes);
if ($rc === false) {
throw new InvalidDatabaseException(
'Could not unpack an unsigned short value from the given bytes.'
);
}
[, $adjust] = $rc;
$size = 285 + $adjust;
} else {
$rc = unpack('N', "\x00" . $bytes);
if ($rc === false) {
throw new InvalidDatabaseException(
'Could not unpack an unsigned long value from the given bytes.'
);
}
[, $adjust] = $rc;
$size = $adjust + 65821;
}
return [$size, $offset + $bytesToRead];
}
/**
* @param string $bytes
* @return string
*/
private function maybeSwitchByteOrder(string $bytes): string
{
return $this->switchByteOrder ? strrev($bytes) : $bytes;
}
/**
* @return bool
* @throws \Plumrocket\GeoIPLookup\Library\Mmdb\Reader\InvalidDatabaseException
*/
private function isPlatformLittleEndian(): bool
{
$testint = 0x00FF;
$packed = pack('S', $testint);
$rc = unpack('v', $packed);
if ($rc === false) {
throw new InvalidDatabaseException(
'Could not unpack an unsigned short value from the given bytes.'
);
}
return $testint === current($rc);
}
}
@@ -0,0 +1,12 @@
<?php
declare(strict_types=1);
namespace Plumrocket\GeoIPLookup\Library\Mmdb\Reader;
use Exception;
/**
* This class should be thrown when unexpected data is found in the database.
*/
class InvalidDatabaseException extends Exception {}
@@ -0,0 +1,126 @@
<?php
declare(strict_types=1);
namespace Plumrocket\GeoIPLookup\Library\Mmdb\Reader;
use ArgumentCountError;
use function func_num_args;
/**
* This class provides the metadata for the MaxMind DB file.
*/
class Metadata
{
/**
* This is an unsigned 16-bit integer indicating the major version number
* for the database's binary format.
*
* @var int
*/
public $binaryFormatMajorVersion;
/**
* This is an unsigned 16-bit integer indicating the minor version number
* for the database's binary format.
*
* @var int
*/
public $binaryFormatMinorVersion;
/**
* This is an unsigned 64-bit integer that contains the database build
* timestamp as a Unix epoch value.
*
* @var int
*/
public $buildEpoch;
/**
* This is a string that indicates the structure of each data record
* associated with an IP address. The actual definition of these
* structures is left up to the database creator.
*
* @var string
*/
public $databaseType;
/**
* This key will always point to a map (associative array). The keys of
* that map will be language codes, and the values will be a description
* in that language as a UTF-8 string. May be undefined for some
* databases.
*
* @var array
*/
public $description;
/**
* This is an unsigned 16-bit integer which is always 4 or 6. It indicates
* whether the database contains IPv4 or IPv6 address data.
*
* @var int
*/
public $ipVersion;
/**
* An array of strings, each of which is a language code. A given record
* may contain data items that have been localized to some or all of
* these languages. This may be undefined.
*
* @var array
*/
public $languages;
/**
* @var int
*/
public $nodeByteSize;
/**
* This is an unsigned 32-bit integer indicating the number of nodes in
* the search tree.
*
* @var int
*/
public $nodeCount;
/**
* This is an unsigned 16-bit integer. It indicates the number of bits in a
* record in the search tree. Note that each node consists of two records.
*
* @var int
*/
public $recordSize;
/**
* @var int
*/
public $searchTreeSize;
/**
* @param array $metadata
*/
public function __construct(array $metadata)
{
if (func_num_args() !== 1) {
throw new ArgumentCountError(
sprintf('%s() expects exactly 1 parameter, %d given', __METHOD__, func_num_args())
);
}
$this->binaryFormatMajorVersion =
$metadata['binary_format_major_version'];
$this->binaryFormatMinorVersion =
$metadata['binary_format_minor_version'];
$this->buildEpoch = $metadata['build_epoch'];
$this->databaseType = $metadata['database_type'];
$this->languages = $metadata['languages'];
$this->description = $metadata['description'];
$this->ipVersion = $metadata['ip_version'];
$this->nodeCount = $metadata['node_count'];
$this->recordSize = $metadata['record_size'];
$this->nodeByteSize = $this->recordSize / 4;
$this->searchTreeSize = $this->nodeCount * $this->nodeByteSize;
}
}
@@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
namespace Plumrocket\GeoIPLookup\Library\Mmdb\Reader;
class Util
{
/**
* @param resource $stream
* @param int $offset
* @param int<0, max> $numberOfBytes
* @return string
* @throws \Plumrocket\GeoIPLookup\Library\Mmdb\Reader\InvalidDatabaseException
*/
public static function read($stream, int $offset, int $numberOfBytes): string
{
if ($numberOfBytes === 0) {
return '';
}
if (fseek($stream, $offset) === 0) {
$value = fread($stream, $numberOfBytes);
// We check that the number of bytes read is equal to the number
// asked for. We use ftell as getting the length of $value is
// much slower.
if ($value !== false && ftell($stream) - $offset === $numberOfBytes) {
return $value;
}
}
throw new InvalidDatabaseException(
'The MaxMind DB file contains bad data'
);
}
}
+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);
}
}
@@ -0,0 +1,82 @@
<?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\Plugin\Plumrocket;
use Magento\Framework\Exception\LocalizedException;
use Plumrocket\GeoIPLookup\Api\GeoLocationValidatorInterface;
use Plumrocket\GeoIPLookup\Helper\Config;
use Plumrocket\GeoIPLookup\Helper\Config\CookieConsentGeo as CookieConsentGeoConfigs;
/**
* @since 1.2.2
*/
class CanManageCookie
{
/**
* @var \Plumrocket\GeoIPLookup\Helper\Config
*/
private $config;
/**
* @var \Plumrocket\GeoIPLookup\Api\GeoLocationValidatorInterface
*/
private $geoLocationValidator;
/**
* @var \Plumrocket\GeoIPLookup\Helper\Config\CookieConsentGeo
*/
private $cookieConsentGeoConfig;
/**
* @param \Plumrocket\GeoIPLookup\Helper\Config $config
* @param \Plumrocket\GeoIPLookup\Api\GeoLocationValidatorInterface $geoLocationValidator
* @param \Plumrocket\GeoIPLookup\Helper\Config\CookieConsentGeo $cookieConsentGeoConfig
*/
public function __construct(
Config $config,
GeoLocationValidatorInterface $geoLocationValidator,
CookieConsentGeoConfigs $cookieConsentGeoConfig
) {
$this->config = $config;
$this->geoLocationValidator = $geoLocationValidator;
$this->cookieConsentGeoConfig = $cookieConsentGeoConfig;
}
/**
* @param \Plumrocket\CookieConsent\Api\CanManageCookieInterface $subject
* @param bool $result
* @return bool
*/
public function afterExecute(\Plumrocket\CookieConsent\Api\CanManageCookieInterface $subject, bool $result)
{
if ($result && $this->config->isConfiguredForUse()) {
try {
return $this->geoLocationValidator->validateByMergedOptions(
$this->cookieConsentGeoConfig->getGeoTargeting(),
$this->cookieConsentGeoConfig->getStatesGeoTargeting()
);
} catch (LocalizedException $e) {
return true;
}
}
return $result;
}
}
@@ -0,0 +1,80 @@
<?php
/**
* @package Plumrocket_GeoIPLookup
* @copyright Copyright (c) 2021 Plumrocket Inc. (https://www.plumrocket.com)
* @license https://www.plumrocket.com/license/ End-user License Agreement
*/
declare(strict_types=1);
namespace Plumrocket\GeoIPLookup\Plugin\Plumrocket\DataPrivacy;
use Magento\Framework\Exception\LocalizedException;
use Plumrocket\DataPrivacyApi\Api\ConsentCheckboxProviderInterface;
use Plumrocket\GeoIPLookup\Api\GeoLocationValidatorInterface;
use Plumrocket\GeoIPLookup\Helper\Config;
/**
* Integration with Data Privacy
*
* Filter checkboxes that is not passing geo ip restriction
*
* @since 1.2.5
*/
class FilterConsentCheckboxesPlugin
{
/**
* @var \Plumrocket\GeoIPLookup\Helper\Config
*/
private $config;
/**
* @var \Plumrocket\GeoIPLookup\Api\GeoLocationValidatorInterface
*/
private $geoLocationValidator;
/**
* @param \Plumrocket\GeoIPLookup\Helper\Config $config
* @param \Plumrocket\GeoIPLookup\Api\GeoLocationValidatorInterface $geoLocationValidator
*/
public function __construct(
Config $config,
GeoLocationValidatorInterface $geoLocationValidator
) {
$this->config = $config;
$this->geoLocationValidator = $geoLocationValidator;
}
/**
* @param \Plumrocket\DataPrivacyApi\Api\ConsentCheckboxProviderInterface $subject
* @param \Plumrocket\DataPrivacyApi\Api\Data\CheckboxInterface[] $result
* @param int $customerId
* @return \Plumrocket\DataPrivacyApi\Api\Data\CheckboxInterface[]
*/
public function afterGetEnabledCustomerCheckboxes(
ConsentCheckboxProviderInterface $subject,
array $result,
int $customerId
): array {
if ($result && $this->config->isConfiguredForUse()) {
try {
$checkboxes = [];
foreach ($result as $checkbox) {
$isAllowed = $this->geoLocationValidator->validateByMergedOptions(
$checkbox->getGeoTargeting(),
$checkbox->getGeoTargetingUsaStates()
);
if (! $isAllowed) {
continue;
}
$checkboxes[] = $checkbox;
}
return $checkboxes;
} catch (LocalizedException $e) {
return $result;
}
}
return $result;
}
}
+1
View File
@@ -0,0 +1 @@
IP Geolocation Lookup
@@ -0,0 +1,88 @@
<?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\Setup\Patch\Schema;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\Setup\Patch\SchemaPatchInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
use PDO;
class RemoveDeprecatedIpTablesFromDatabase implements SchemaPatchInterface
{
/**
* @var \Magento\Framework\Setup\SchemaSetupInterface
*/
private $schemaSetup;
/**
* @var \Magento\Framework\DB\Adapter\AdapterInterface
*/
private $connection;
/**
* @param \Magento\Framework\Setup\SchemaSetupInterface $schemaSetup
* @param \Magento\Framework\App\ResourceConnection $resourceConnection
*/
public function __construct(
SchemaSetupInterface $schemaSetup,
ResourceConnection $resourceConnection
) {
$this->schemaSetup = $schemaSetup;
$this->connection = $resourceConnection->getConnection();
}
/**
* @inheritDoc
*/
public function apply(): RemoveDeprecatedIpTablesFromDatabase
{
$this->schemaSetup->startSetup();
foreach ($this->getTablesToDelete() as $table) {
$this->connection->dropTable($this->connection->getTableName($table));
}
$this->schemaSetup->endSetup();
return $this;
}
/**
* @inheritDoc
*/
public static function getDependencies(): array
{
return [];
}
/**
* @inheritDoc
*/
public function getAliases(): array
{
return [];
}
/**
* @return array
*/
private function getTablesToDelete(): array
{
$tablesToDelete = $this->connection->query(
"SHOW TABLES LIKE '{$this->connection->getTableName('prgeoiplookup_maxmindgeoip_city_blocks')}%'"
)->fetchAll(PDO::FETCH_COLUMN);
$tablesToDelete[] = 'prgeoiplookup_maxmindgeoip_city_locations';
$tablesToDelete[] = 'prgeoiplookup_iptocountry';
$tablesToDelete[] = 'prgeoiplookup_installed_versions';
return $tablesToDelete;
}
}
+33
View File
@@ -0,0 +1,33 @@
<?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\Setup;
use Plumrocket\Base\Setup\AbstractUninstall;
class Uninstall extends AbstractUninstall
{
protected $_configSectionId = 'prgeoiplookup';
protected $_pathes = ['/app/code/Plumrocket/GeoIPLookup'];
protected $_tables =
[
'prgeoiplookup_installed_versions',
'prgeoiplookup_iptocountry',
'prgeoiplookup_maxmindgeoip_city_blocks',
'prgeoiplookup_maxmindgeoip_city_locations'
];
}
@@ -0,0 +1,504 @@
<?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\Test\Unit\Model;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\TestFramework\Unit\Helper\ObjectManager;
use PHPUnit\Framework\TestCase;
use Plumrocket\GeoIPLookup\Api\LocationsListInterface;
use Plumrocket\GeoIPLookup\Model\GeoIPLookup;
use Plumrocket\GeoIPLookup\Model\GeoLocationValidator;
use Plumrocket\GeoIPLookup\Model\LocationsList;
/**
* @since 1.2.0
*/
class GeoLocationValidatorTest extends TestCase
{
const CALIFORNIA = 'California';
/**
* @var \Plumrocket\GeoIPLookup\Model\GeoLocationValidator
*/
private $validateLocation;
/**
* @var \PHPUnit\Framework\MockObject\MockObject|\Plumrocket\GeoIPLookup\Model\GeoIPLookup
*/
private $geoIPLookup;
protected function setUp(): void
{
$objectManager = new ObjectManager($this);
$this->geoIPLookup = $this->createMock(GeoIPLookup::class);
$locationsList = $objectManager->getObject(LocationsList::class);
$this->validateLocation = $objectManager->getObject(
GeoLocationValidator::class,
[
'geoIPLookup' => $this->geoIPLookup,
'locationsList' => $locationsList
]
);
}
/**
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function testDisabledExtension()
{
$this->geoIPLookup
->expects($this->once())
->method('canUse')
->willReturn(false);
$this->expectException(LocalizedException::class);
$this->validateLocation->validate([], []);
}
/**
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function testValidateEmptyLocation()
{
$this->geoIPLookup
->expects($this->once())
->method('canUse')
->willReturn(true);
$this->geoIPLookup
->expects($this->never())
->method('getCountryCode');
$this->geoIPLookup
->expects($this->never())
->method('getCurrentCountryState');
$this->geoIPLookup
->expects($this->never())
->method('isInEuropeanUnion');
$this->assertTrue($this->validateLocation->validate([], []));
}
/**
* @dataProvider allRegionProvider
*
* @param array $regions
* @param array $countries
* @param array $usaStates
* @param bool $result
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function testAllRegion(array $regions, array $countries, array $usaStates, bool $result)
{
$this->geoIPLookup
->expects($this->once())
->method('canUse')
->willReturn(true);
$this->geoIPLookup
->expects($this->never())
->method('getCountryCode');
$this->geoIPLookup
->expects($this->never())
->method('getCurrentCountryState');
$this->geoIPLookup
->expects($this->never())
->method('isInEuropeanUnion');
$this->assertSame($result, $this->validateLocation->validate($regions, $countries, $usaStates));
}
public function allRegionProvider(): array
{
return [
[
'regions' => [LocationsListInterface::ALL],
'countries' => [],
'usaStates' => [],
'result' => true,
],
[
'regions' => [LocationsListInterface::ALL],
'countries' => ['AU'],
'usaStates' => [],
'result' => true,
],
[
'regions' => [LocationsListInterface::ALL],
'countries' => ['AU'],
'usaStates' => [LocationsListInterface::USA_STATE_CALIFORNIA],
'result' => true,
],
];
}
/**
* @dataProvider regionEUProvider
*
* @param string $case
* @param array $regions
* @param array $countries
* @param bool|null $isInEU
* @param string|null $countryCode
* @param bool $result
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function testRegionsEURegion(
string $case,
array $regions,
array $countries,
$isInEU,
$countryCode,
bool $result
) {
$this->geoIPLookup
->expects($this->once())
->method('canUse')
->willReturn(true);
$this->geoIPLookup
->expects($this->never())
->method('getCurrentCountryState');
$this->geoIPLookup
->method('getCountryCode')
->willReturn($countryCode);
$this->geoIPLookup
->expects($this->once())
->method('isInEuropeanUnion')
->willReturn($isInEU);
$this->assertSame($result, $this->validateLocation->validate($regions, $countries), $case);
}
public function regionEUProvider(): array
{
return [
[
'case' => 'EU <=> Country in EU',
'regions' => [LocationsListInterface::EU],
'countries' => [],
'isInEU' => true,
'countryCode' => 'DE',
'result' => true,
],
[
'case' => 'EU + Country in EU <=> Same country',
'regions' => [LocationsListInterface::EU],
'countries' => ['DE'],
'isInEU' => true,
'countryCode' => 'DE',
'result' => true,
],
[
'case' => 'EU + Country not in EU <=> Another country',
'regions' => [LocationsListInterface::EU],
'countries' => ['AU'],
'isInEU' => false,
'countryCode' => 'CA',
'result' => false,
],
[
'case' => 'EU + Country not in EU <=> Same country',
'regions' => [LocationsListInterface::EU],
'countries' => ['AU'],
'isInEU' => false,
'countryCode' => 'AU',
'result' => true,
],
[
'case' => 'EU + Country not in EU <=> Country in EU',
'regions' => [LocationsListInterface::EU],
'countries' => ['AU'],
'isInEU' => true,
'countryCode' => 'DE',
'result' => true,
],
[
'case' => 'EU + Country not in EU <=> Could not detect location',
'regions' => [LocationsListInterface::EU],
'countries' => ['AU'],
'isInEU' => null,
'countryCode' => null,
'result' => false,
],
];
}
/**
* @dataProvider regionUnknownProvider
*
* @param string $case
* @param array $regions
* @param array $countries
* @param $isInEU
* @param $countryCode
* @param bool $result
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function testUnknownRegion(
string $case,
array $regions,
array $countries,
$isInEU,
$countryCode,
bool $result
) {
$this->geoIPLookup
->expects($this->once())
->method('canUse')
->willReturn(true);
$this->geoIPLookup
->method('isInEuropeanUnion')
->willReturn($isInEU);
$this->geoIPLookup
->expects($this->once())
->method('getCountryCode')
->willReturn($countryCode);
$this->geoIPLookup
->expects($this->never())
->method('getCurrentCountryState')
->willReturn(null);
$this->assertSame($result, $this->validateLocation->validate($regions, $countries, []), $case);
}
public function regionUnknownProvider(): array
{
return [
[
'case' => 'Unknown <=> some country',
'regions' => [LocationsListInterface::UNKNOWN],
'countries' => [],
'isInEU' => true,
'countryCode' => 'FR',
'result' => false,
],
[
'case' => 'Unknown <=> Unknown',
'regions' => [LocationsListInterface::UNKNOWN],
'countries' => [],
'isInEU' => null,
'in_array(LocationsListInterface::UNKNOWN, $regions, true)' => null,
'result' => true,
],
[
'case' => 'EU + Unknown <=> Unknown',
'regions' => [LocationsListInterface::UNKNOWN, LocationsListInterface::EU],
'countries' => [],
'isInEU' => null,
'countryCode' => null,
'result' => true,
],
[
'case' => 'EU + Unknown + Country not in EU <=> Another country',
'regions' => [LocationsListInterface::UNKNOWN, LocationsListInterface::EU],
'countries' => ['AU'],
'isInEU' => false,
'countryCode' => ['CA'],
'result' => false,
],
];
}
/**
* @dataProvider countiesProvider
*
* @param string $case
* @param array $countries
* @param string $countryCode
* @param bool $result
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function testCountries(string $case, array $countries, string $countryCode, bool $result)
{
$this->geoIPLookup
->expects($this->once())
->method('canUse')
->willReturn(true);
$this->geoIPLookup
->expects($this->once())
->method('getCountryCode')
->willReturn($countryCode);
$this->geoIPLookup
->expects($this->never())
->method('getCurrentCountryState');
$this->geoIPLookup
->expects($this->never())
->method('isInEuropeanUnion');
$this->assertSame($result, $this->validateLocation->validate([], $countries), $case);
}
public function countiesProvider(): array
{
return [
[
'case' => 'Countries <=> Another country',
'countries' => ['PL', 'AU'],
'countryCode' => 'FR',
'result' => false,
],
[
'case' => 'Countries <=> One of the countries',
'countries' => ['PL', 'AU'],
'countryCode' => 'PL',
'result' => true,
],
];
}
/**
* @dataProvider statesProvider
*
* @param string $case
* @param array $regions
* @param array $countries
* @param array $usaStates
* @param $isInEU
* @param string $countryCode
* @param $countryState
* @param bool $result
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function testStates(
string $case,
array $regions,
array $countries,
array $usaStates,
$isInEU,
$countryCode,
$countryState,
bool $result
) {
$this->geoIPLookup
->expects($this->once())
->method('canUse')
->willReturn(true);
$this->geoIPLookup
->expects($this->once())
->method('getCountryCode')
->willReturn($countryCode);
$this->geoIPLookup
->method('getCurrentCountryState')
->willReturn($countryState);
$this->geoIPLookup
->method('isInEuropeanUnion')
->willReturn($isInEU);
$this->assertSame($result, $this->validateLocation->validate($regions, $countries, $usaStates), $case);
}
public function statesProvider(): array
{
return [
[
'case' => 'US + California <=> California',
'regions' => [],
'countries' => [LocationsListInterface::COUNTRY_CODE_USA],
'usaStates' => [LocationsListInterface::USA_STATE_CALIFORNIA],
'isInEU' => false,
'countryCode' => LocationsListInterface::COUNTRY_CODE_USA,
'countryState' => LocationsListInterface::USA_STATE_CALIFORNIA,
'result' => true,
],
[
'case' => 'US + California <=> Another state',
'regions' => [],
'countries' => [LocationsListInterface::COUNTRY_CODE_USA],
'usaStates' => [LocationsListInterface::USA_STATE_CALIFORNIA],
'isInEU' => false,
'countryCode' => LocationsListInterface::COUNTRY_CODE_USA,
'countryState' => 'Nevada',
'result' => false,
],
[
'case' => 'US + California <=> Another country',
'regions' => [],
'countries' => [LocationsListInterface::COUNTRY_CODE_USA],
'usaStates' => [LocationsListInterface::USA_STATE_CALIFORNIA],
'isInEU' => false,
'countryCode' => 'CA',
'countryState' => null,
'result' => false,
],
[
'case' => 'Unknown + US + California <=> Unknown',
'regions' => [LocationsListInterface::UNKNOWN],
'countries' => [LocationsListInterface::COUNTRY_CODE_USA],
'usaStates' => [LocationsListInterface::USA_STATE_CALIFORNIA],
'isInEU' => null,
'countryCode' => null,
'countryState' => null,
'result' => true,
],
];
}
/**
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function testParseOptions()
{
$this->geoIPLookup
->expects($this->exactly(3))
->method('canUse')
->willReturn(true);
$this->geoIPLookup
->expects($this->exactly(3))
->method('getCountryCode')
->willReturn('CA');
$this->geoIPLookup
->expects($this->exactly(3))
->method('isInEuropeanUnion')
->willReturn(false);
$this->assertFalse($this->validateLocation->validateByMergedOptions(
[LocationsListInterface::COUNTRY_CODE_USA, LocationsList::EU]
));
$this->assertTrue($this->validateLocation->validateByMergedOptions(
['CA', LocationsList::EU]
));
$this->assertTrue($this->validateLocation->validateByMergedOptions(
[LocationsList::UNKNOWN, 'CA', LocationsList::EU]
));
}
}
+18
View File
@@ -0,0 +1,18 @@
{
"name": "plumrocket/module-geo-ip-lookup",
"description": "N/A",
"require": {
"php": ">=7.1",
"plumrocket/module-plumbase": ">=2.10.1"
},
"type": "magento2-module",
"version": "2.0.5",
"autoload": {
"files": [
"registration.php"
],
"psr-4": {
"Plumrocket\\GeoIPLookup\\": ""
}
}
}
+37
View File
@@ -0,0 +1,37 @@
<?xml version="1.0"?>
<!--
/**
* 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
*/
-->
<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="Plumrocket_Base::elements">
<resource id="Plumrocket_GeoIPLookup::prgeoiplookup" title="IP Geolocation Lookup" sortOrder="3786959" />
</resource>
<resource id="Magento_Backend::stores">
<resource id="Magento_Backend::stores_settings">
<resource id="Magento_Config::config">
<resource id="Plumrocket_GeoIPLookup::configuration" title="IP Geolocation Lookup Section" />
</resource>
</resource>
</resource>
</resource>
</resources>
</acl>
</config>
+25
View File
@@ -0,0 +1,25 @@
<?xml version="1.0" ?>
<!--
/**
* 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
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Backend:etc/menu.xsd">
<menu>
<add module="Plumrocket_GeoIPLookup" parent="Plumrocket_Base::elements" id="Plumrocket_GeoIPLookup::prgeoiplookup" resource="Plumrocket_GeoIPLookup::prgeoiplookup" title="IP Geolocation Lookup" sortOrder="3786959"/>
<add module="Plumrocket_GeoIPLookup" parent="Plumrocket_GeoIPLookup::prgeoiplookup" id="Plumrocket_GeoIPLookup::configuration" resource="Plumrocket_GeoIPLookup::configuration" action="adminhtml/system_config/edit/section/prgeoiplookup" title="Configuration" sortOrder="100"/>
</menu>
</config>
+26
View File
@@ -0,0 +1,26 @@
<?xml version="1.0" ?>
<!--
/**
* 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
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
<router id="admin">
<route frontName="prgeoiplookup" id="prgeoiplookup">
<module name="Plumrocket_GeoIPLookup"/>
</route>
</router>
</config>
+192
View File
@@ -0,0 +1,192 @@
<?xml version="1.0" ?>
<!--
/**
* 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
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
<system>
<section id="prgeoiplookup" translate="label" type="text" sortOrder="3786959" showInDefault="1" showInWebsite="1" showInStore="1">
<label>IP Geolocation Lookup</label>
<tab>plumrocket</tab>
<resource>Plumrocket_GeoIPLookup::configuration</resource>
<group id="toolbox" translate="label" type="text" sortOrder="0" showInDefault="1" showInWebsite="1" showInStore="1">
<frontend_model>Plumrocket\Base\Block\Adminhtml\System\Config\Form\ToolbarFieldset</frontend_model>
<field id="version" type="text" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
<frontend_model>Plumrocket\Base\Block\Adminhtml\System\Config\Form\Version</frontend_model>
<attribute type="pr_extension_name">GeoIPLookup</attribute>
</field>
</group>
<!-- Begin of GENERAL group -->
<group id="general" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
<label>General</label>
<attribute type="expanded">1</attribute>
<field id="enabled" translate="label" type="select" sortOrder="20" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Enable Extension</label>
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
</field>
<field id="serial" translate="label comment" type="text" sortOrder="30" showInDefault="1" showInWebsite="0" showInStore="0">
<label>Serial Key</label>
<frontend_model>Plumrocket\Base\Block\Adminhtml\System\Config\Form\Serial</frontend_model>
<attribute type="pr_extension_name">GeoIPLookup</attribute>
</field>
</group>
<!-- End GENERAL -->
<!-- Begin of METHODS group -->
<group id="methods" translate="label" type="text" sortOrder="20" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Services</label>
<attribute type="expanded">1</attribute>
<field id="notice" translate="label comment" type="text" sortOrder="0" showInDefault="1" showInWebsite="1" showInStore="1">
<frontend_model>Plumrocket\GeoIPLookup\Block\Adminhtml\System\Config\Notice</frontend_model>
</field>
<!-- Begin of MAXMAINDGEOIP group -->
<group id="maxmindgeoip" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Maxmind IP Geolocation Database</label>
<field id="enabled" translate="label" type="select" sortOrder="20" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Enable</label>
<frontend_model>Plumrocket\GeoIPLookup\Block\Adminhtml\System\Config\Data\Enable</frontend_model>
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
</field>
<field id="status" translate="label" type="note" sortOrder="30" showInDefault="1" showInWebsite="0" showInStore="0">
<label>Database Status</label>
<frontend_model>Plumrocket\GeoIPLookup\Block\Adminhtml\System\Config\Data\Status</frontend_model>
</field>
<field id="install_method" translate="label" type="select" sortOrder="40" showInDefault="1" showInWebsite="0" showInStore="0">
<label>Installation Method</label>
<source_model>Plumrocket\GeoIPLookup\Model\System\Config\Source\Installmethods</source_model>
<frontend_class>install-method</frontend_class>
<comment><![CDATA[<span class="method_comment"></span>]]></comment>
</field>
<field id="install" translate="button_label" type="button" sortOrder="50" showInDefault="1" showInWebsite="0" showInStore="0">
<button_label>Install Database</button_label>
<frontend_model>Plumrocket\GeoIPLookup\Block\Adminhtml\System\Config\Data\Buttons\Install</frontend_model>
<depends>
<field id="install_method">automatic</field>
</depends>
</field>
</group>
<!-- End MAXMAINDGEOIP -->
<!-- Begin of IPTOCOUNTRY group -->
<group id="iptocountry" translate="label" type="text" sortOrder="20" showInDefault="1" showInWebsite="1" showInStore="1">
<label>IpToCountry IP Geolocation Database</label>
<field id="enabled" translate="label" type="select" sortOrder="20" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Enable</label>
<frontend_model>Plumrocket\GeoIPLookup\Block\Adminhtml\System\Config\Data\Enable</frontend_model>
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
</field>
<field id="status" translate="label" type="text" sortOrder="30" showInDefault="1" showInWebsite="0" showInStore="0">
<label>Database Status</label>
<frontend_model>Plumrocket\GeoIPLookup\Block\Adminhtml\System\Config\Data\Status</frontend_model>
</field>
<field id="install_method" translate="label" type="select" sortOrder="40" showInDefault="1" showInWebsite="0" showInStore="0">
<label>Installation Method</label>
<source_model>Plumrocket\GeoIPLookup\Model\System\Config\Source\Installmethods</source_model>
<frontend_class>install-method</frontend_class>
<comment><![CDATA[<span class="method_comment"></span>]]></comment>
</field>
<field id="install" translate="button_label" type="button" sortOrder="50" showInDefault="1" showInWebsite="0" showInStore="0">
<button_label>Install Database</button_label>
<frontend_model>Plumrocket\GeoIPLookup\Block\Adminhtml\System\Config\Data\Buttons\Install</frontend_model>
<depends>
<field id="install_method">automatic</field>
</depends>
</field>
</group>
<!-- End IPTOCOUNTRY -->
<!-- Begin of Ipapi group -->
<group id="ipapigeoip" translate="label" type="text" sortOrder="30" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Ipapi.Com - IP Geolocation API</label>
<field id="enabled" translate="label" type="select" sortOrder="20" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Enable</label>
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
<comment><![CDATA[
The API is provided by: <a target="_blank" href="https://ipapi.com">https://ipapi.com</a>.<br>
Limits: 10,000 Lookups in Free Plan. You can get more IP lookups with paid plans.
]]></comment>
</field>
<field id="use_https" translate="label" type="select" sortOrder="30" showInDefault="1" showInWebsite="0" showInStore="0">
<label>Use HTTPS Encryption</label>
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
<comment><![CDATA[HTTPS encryption is not available for the free plan, it can only be used with pro plans.]]></comment>
</field>
<field id="access_key" translate="label" type="password" sortOrder="40" showInDefault="1" showInWebsite="0" showInStore="0">
<label>Access Key</label>
</field>
<field id="connection_test" translate="button_label" type="button" sortOrder="50" showInDefault="1" showInWebsite="0" showInStore="0">
<button_label>Test Connection</button_label>
<frontend_model>Plumrocket\GeoIPLookup\Block\Adminhtml\System\Config\Data\Buttons\Connection</frontend_model>
</field>
</group>
<!-- End Ipapi -->
</group>
<!-- End METHODS -->
<!-- Begin of GEOIPTEST group -->
<group id="geoiptest" translate="label" type="text" sortOrder="30" showInDefault="1" showInWebsite="0" showInStore="0">
<label>IP Geolocation Lookup Test</label>
<field id="ip_address" translate="label comment" type="text" sortOrder="20" showInDefault="1" showInWebsite="0" showInStore="0">
<label>IP Address</label>
<frontend_model>Plumrocket\GeoIPLookup\Block\Adminhtml\System\Config\Data\Test\Ipaddress</frontend_model>
<comment><![CDATA[
Enter IP address to test IP geolocation lookup. Your own IP address is automatically populated in this field.
]]></comment>
</field>
<field id="test_geoip_lookup" translate="label" type="text" sortOrder="30" showInDefault="1" showInWebsite="0" showInStore="0">
<label>Test IP Geolocation Lookup</label>
<frontend_model>Plumrocket\GeoIPLookup\Block\Adminhtml\System\Config\Data\Test\Button</frontend_model>
</field>
<field id="geoinfo" translate="label" type="textarea" sortOrder="40" showInDefault="1" showInWebsite="0" showInStore="0">
<label>IP Geolocation Information</label>
</field>
<field id="location_on_map" translate="label" type="text" sortOrder="50" showInDefault="1" showInWebsite="0" showInStore="0">
<label>View Location on Map</label>
<frontend_model>Plumrocket\GeoIPLookup\Block\Adminhtml\System\Config\Data\Test\Map</frontend_model>
</field>
<field id="rest_ip" translate="label" type="text" sortOrder="60" showInDefault="1" showInWebsite="0" showInStore="0">
<label>REST API</label>
<frontend_model>Plumrocket\GeoIPLookup\Block\Adminhtml\System\Config\Data\Test\Api</frontend_model>
<comment><![CDATA[
Read more about REST API and other methods of retrieving Geolocation Lookup data in our <a target="_blank" href="https://plumrocket.com/docs/magento-geoip-lookup/v1">developer's guide</a>
]]></comment>
</field>
</group>
<!-- End GEOIPTEST -->
</section>
<section id="pr_cookie">
<group id="main_settings">
<field id="geo_targeting" translate="label comment" type="multiselect" sortOrder="200" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Geo Targeting</label>
<source_model>Plumrocket\GeoIPLookup\Model\System\Config\Source\GeoTargeting</source_model>
<frontend_model>Plumrocket\GeoIPLookup\Block\Adminhtml\System\Config\Form\GeoTargetingMultiSelect</frontend_model>
<frontend_class>geoip-select-with-chosen prgdpr-coutry</frontend_class>
<comment>Show cookie consent notice only to visitors from the selected list of countries / states.</comment>
</field>
<field id="states_geo_targeting" translate="label comment" type="multiselect" sortOrder="300" showInDefault="1" showInWebsite="1" showInStore="1">
<label>U.S. States</label>
<source_model>Plumrocket\GeoIPLookup\Model\System\Config\Source\GeoTargetingStates</source_model>
<frontend_model>Plumrocket\GeoIPLookup\Block\Adminhtml\System\Config\Form\StatesGeoTargetingMultiSelect</frontend_model>
<frontend_class>geoip-select-with-chosen prgdpr-ccpa</frontend_class>
<comment>You can select one or multiple U.S. states. For example, select "California" for CCPA law.</comment>
</field>
</group>
</section>
</system>
</config>
+39
View File
@@ -0,0 +1,39 @@
<?xml version="1.0"?>
<!--
/**
* 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
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Store:etc/config.xsd">
<default>
<prgeoiplookup>
<general>
<serial></serial>
</general>
<methods>
<ipapigeoip>
<use_https>0</use_https>
</ipapigeoip>
</methods>
</prgeoiplookup>
<!-- Default values for fields with "config_path" attribute -->
<prgdpr>
<cookie_consent>
<geoip_restriction>all</geoip_restriction>
</cookie_consent>
</prgdpr>
</default>
</config>
+132
View File
@@ -0,0 +1,132 @@
<?xml version="1.0"?>
<!--
/**
* 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
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Plumrocket\GeoIPLookup\Api\GeoIPLookupInterface" type="Plumrocket\GeoIPLookup\Model\Api\GeoIPLookup" />
<preference for="Plumrocket\GeoIPLookup\Api\GeoLocationValidatorInterface" type="Plumrocket\GeoIPLookup\Model\GeoLocationValidator" />
<preference for="Plumrocket\GeoIPLookup\Api\LocationsListInterface" type="Plumrocket\GeoIPLookup\Model\LocationsList" />
<preference for="Plumrocket\GeoIPLookup\Model\Cache\GeoIpInterface" type="Plumrocket\GeoIPLookup\Model\Cache\Session" />
<type name="Plumrocket\CCPA\Model\Validator\CcpaGeoLocationValidator">
<arguments>
<argument name="geoIpModel" xsi:type="object">Plumrocket\GeoIPLookup\Model\GeoIPLookup</argument>
</arguments>
</type>
<type name="Plumrocket\GeoIPLookup\Plugin\Plumrocket\CanManageCookie">
<arguments>
<argument name="geoLocationValidator" xsi:type="object">Plumrocket\GeoIPLookup\Api\GeoLocationValidatorInterface\Proxy</argument>
</arguments>
</type>
<type name="Plumrocket\CookieConsent\Api\CanManageCookieInterface">
<plugin name="prGeoIpCanManageCookie"
type="Plumrocket\GeoIPLookup\Plugin\Plumrocket\CanManageCookie" sortOrder="10"/>
</type>
<type name="Magento\Framework\HTTP\PhpEnvironment\RemoteAddress">
<arguments>
<argument name="alternativeHeaders" xsi:type="array">
<item name="cloud-flare-real-visitor-ip" xsi:type="string">HTTP_CF_CONNECTING_IP</item>
</argument>
</arguments>
</type>
<type name="Plumrocket\DataPrivacyApi\Api\ConsentCheckboxProviderInterface">
<plugin name="pr-geo-ip-filter-checkboxes"
type="Plumrocket\GeoIPLookup\Plugin\Plumrocket\DataPrivacy\FilterConsentCheckboxesPlugin"
sortOrder="10"/>
</type>
<virtualType name="Plumrocket\GeoIPLookup\Model\Services\IpToCountry\DbReader" type="Plumrocket\GeoIPLookup\Model\MmdbReader">
<arguments>
<argument name="fileName" xsi:type="const">Plumrocket\GeoIPLookup\Helper\Config::IPTOCOUNTRY_SOURCE_FILE_NAME</argument>
<argument name="databaseName" xsi:type="const">Plumrocket\GeoIPLookup\Helper\Config::IPTOCOUNTRY_DATABASE_NAME</argument>
<argument name="fieldsMap" xsi:type="array">
<item name="continent_code" xsi:type="string">continent.code</item>
<item name="continent_name" xsi:type="string">continent.names.en</item>
<item name="country_code" xsi:type="string">country.iso_code</item>
<item name="country_name" xsi:type="string">country.names.en</item>
<item name="is_in_european_union" xsi:type="string">country.is_in_european_union</item>
</argument>
</arguments>
</virtualType>
<virtualType name="Plumrocket\GeoIPLookup\Model\Services\MaxMind\DbReader" type="Plumrocket\GeoIPLookup\Model\MmdbReader">
<arguments>
<argument name="fileName" xsi:type="const">Plumrocket\GeoIPLookup\Helper\Config::MAXMIND_SOURCE_FILE_NAME</argument>
<argument name="databaseName" xsi:type="const">Plumrocket\GeoIPLookup\Helper\Config::MAXMIND_DATABASE_NAME</argument>
<argument name="fieldsMap" xsi:type="array">
<item name="postal_code" xsi:type="string">postal.code</item>
<item name="latitude" xsi:type="string">location.latitude</item>
<item name="longitude" xsi:type="string">location.longitude</item>
<item name="continent_code" xsi:type="string">continent.code</item>
<item name="continent_name" xsi:type="string">continent.names.en</item>
<item name="country_code" xsi:type="string">country.iso_code</item>
<item name="country_name" xsi:type="string">country.names.en</item>
<item name="subdivision_1_iso_code" xsi:type="string">subdivisions.0.iso_code</item>
<item name="subdivision_1_name" xsi:type="string">subdivisions.0.names.en</item>
<item name="subdivision_2_iso_code" xsi:type="string">subdivisions.1.iso_code</item>
<item name="subdivision_2_name" xsi:type="string">subdivisions.1.names.en</item>
<item name="city_name" xsi:type="string">city.names.en</item>
<item name="time_zone" xsi:type="string">location.time_zone</item>
<item name="is_in_european_union" xsi:type="string">country.is_in_european_union</item>
</argument>
</arguments>
</virtualType>
<virtualType name="Plumrocket\GeoIPLookup\Model\Services\IpToCountry" type="Plumrocket\GeoIPLookup\Model\Services\AbstractMmdb">
<arguments>
<argument name="mmdbReader" xsi:type="object">Plumrocket\GeoIPLookup\Model\Services\IpToCountry\DbReader</argument>
<argument name="cacheKeyPostfixes" xsi:type="array">
<item name="getGeoLocation" xsi:type="string">_gl_itc</item>
<item name="getCountryCode" xsi:type="string">_cc_itc</item>
<item name="getCurrentCountryState" xsi:type="string">_cc_itc_cs</item>
</argument>
</arguments>
</virtualType>
<virtualType name="Plumrocket\GeoIPLookup\Model\Services\MaxMind" type="Plumrocket\GeoIPLookup\Model\Services\AbstractMmdb">
<arguments>
<argument name="mmdbReader" xsi:type="object">Plumrocket\GeoIPLookup\Model\Services\MaxMind\DbReader</argument>
<argument name="cacheKeyPostfixes" xsi:type="array">
<item name="getGeoLocation" xsi:type="string">_gl_mx</item>
<item name="getCountryCode" xsi:type="string">_cc_mx</item>
<item name="getCurrentCountryState" xsi:type="string">_cc_mx_cs</item>
</argument>
</arguments>
</virtualType>
<type name="Plumrocket\GeoIPLookup\Model\GeoIPLookup">
<arguments>
<argument name="geoIpServices" xsi:type="array">
<item name="MaxMind" xsi:type="object">Plumrocket\GeoIPLookup\Model\Services\MaxMind</item>
<item name="IpToCountry" xsi:type="object">Plumrocket\GeoIPLookup\Model\Services\IpToCountry</item>
<item name="IpApi" xsi:type="object">Plumrocket\GeoIPLookup\Model\Services\IpApi</item>
</argument>
</arguments>
</type>
<type name="Plumrocket\GeoIPLookup\Model\Data\Import\Iptocountry">
<arguments>
<argument name="mmdbReader" xsi:type="object">Plumrocket\GeoIPLookup\Model\Services\IpToCountry\DbReader</argument>
</arguments>
</type>
<type name="Plumrocket\GeoIPLookup\Model\Data\Import\Maxmindgeoip">
<arguments>
<argument name="mmdbReader" xsi:type="object">Plumrocket\GeoIPLookup\Model\Services\MaxMind\DbReader</argument>
</arguments>
</type>
</config>
+15
View File
@@ -0,0 +1,15 @@
<?xml version="1.0" ?>
<!--
/**
* @package Plumrocket_GeoIPLookup
* @copyright Copyright (c) 2019 Plumrocket Inc. (https://plumrocket.com)
* @license https://plumrocket.com/license/ End-user License Agreement
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Plumrocket_GeoIPLookup">
<sequence>
<module name="Plumrocket_Base" />
</sequence>
</module>
</config>
@@ -0,0 +1,21 @@
<?xml version="1.0"?>
<!--
/**
* @package Plumrocket_GeoIPLookup
* @copyright Copyright (c) 2020 Plumrocket Inc. (https://plumrocket.com)
* @license https://plumrocket.com/license/ End-user License Agreement
*/
-->
<extensions xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:module:Plumrocket_Base:etc/pr_extensions.xsd">
<extension name="GeoIPLookup"
title="IP Geolocation Lookup"
config_section="prgeoiplookup"
is_enabled_path="prgeoiplookup/general/enabled"
documentation="https://plumrocket.com/docs/magento-ip-geolocation-lookup/v2"
url="https://plumrocket.com/magento-ip-geolocation-lookup"
marketplace_url="https://marketplace.magento.com/ip-geolocation-lookup.html"
>
<customer key="18771d78aa85ca47851fca7fdf3dd545bad4a02358"/>
</extension>
</extensions>
+33
View File
@@ -0,0 +1,33 @@
<?xml version="1.0"?>
<!--
/**
* 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
*/
-->
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Webapi:etc/webapi.xsd">
<route url="/V1/prgeoiplookup/:ip/params/:params" method="GET">
<service class="Plumrocket\GeoIPLookup\Api\GeoIPLookupInterface" method="getGeoIpData"/>
<resources>
<resource ref="anonymous"/>
</resources>
</route>
<route url="/V1/prgeoiplookup/:ip" method="GET">
<service class="Plumrocket\GeoIPLookup\Api\GeoIPLookupInterface" method="getGeoIpDataWithDefaultServices"/>
<resources>
<resource ref="anonymous"/>
</resources>
</route>
</routes>
+64
View File
@@ -0,0 +1,64 @@
"Please install %1 in order to enable this IP Geolocation method.","Please install %1 in order to enable this IP Geolocation method."
"Open in","Open in"
"Google Maps","Google Maps"
"Please Note!","Please Note!"
"You must enable at least one service for this extension to function properly.","You must enable at least one service for this extension to function properly."
"We recommend to enable 2 or more services
below to provide the most accurate IP geolocation results.
","We recommend to enable 2 or more services
below to provide the most accurate IP geolocation results.
"
"Geolocation Database Update","Geolocation Database Update"
"You have the latest %1 Geolocation Database available on our server.
Please check back later for the updates.","You have the latest %1 Geolocation Database available on our server.
Please check back later for the updates."
"Not Installed","Not Installed"
"Installed v%1 on %2","Installed v%1 on %2"
"Installed on %1","Installed on %1"
"Download in Progress...","Download in Progress..."
"Installation in Progress...","Installation in Progress..."
"Importing Geolocation Database... ","Importing Geolocation Database... "
Done!,Done!
"Data Import Error","Data Import Error"
"We couldn't find %1 CSV files in 'media/prgeoiplookup' folder.
\nPlease read our online manual for more info about manual installation method.","We couldn't find %1 CSV files in 'media/prgeoiplookup' folder.
\nPlease read our online manual for more info about manual installation method."
"No records found","No records found"
Continent,Continent
"Continent Code","Continent Code"
Country,Country
"Country Code","Country Code"
City,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"
"Automatic Installation","Automatic Installation"
"Manual Installation","Manual Installation"
"IP Geolocation Lookup","IP Geolocation Lookup"
General,General
"Enable Extension","Enable Extension"
"Serial Key","Serial Key"
"Your can find <strong>Serial Key</strong> in your account at <a target=""_blank"" href=""https://store.plumrocket.com/downloadable/customer/products/"">store.plumrocket.com</a>. For manual <a target=""_blank"" href=""http://wiki.plumrocket.com/wiki/License_Installation"">click here</a>.","Your can find <strong>Serial Key</strong> in your account at <a target=""_blank"" href=""https://store.plumrocket.com/downloadable/customer/products/"">store.plumrocket.com</a>. For manual <a target=""_blank"" href=""http://wiki.plumrocket.com/wiki/License_Installation"">click here</a>."
Services,Services
"Maxmind IP Geolocation Database","Maxmind IP Geolocation Database"
"Database Status","Database Status"
"Installation Method","Installation Method"
"Install Database","Install Database"
"IpToCountry IP Geolocation Database","IpToCountry IP Geolocation Database"
"Ipapi.Com - IP Geolocation API","Ipapi.Com - IP Geolocation API"
"Test Connection","Test Connection"
"IP Geolocation Lookup Test","IP Geolocation Lookup Test"
"IP Address","IP Address"
"Enter IP address to test IP Geolocation Lookup. Your own IP address is automatically populated in this field.","Enter IP address to test IP Geolocation Lookup. Your own IP address is automatically populated in this field."
"Test IP Geolocation Lookup","Test IP Geolocation Lookup"
"IP Geolocation Information","IP Geolocation Information"
"View Location on Map","View Location on Map"
"REST API","REST API"
1 Please install %1 in order to enable this IP Geolocation method. Please install %1 in order to enable this IP Geolocation method.
2 Open in Open in
3 Google Maps Google Maps
4 Please Note! Please Note!
5 You must enable at least one service for this extension to function properly. You must enable at least one service for this extension to function properly.
6 We recommend to enable 2 or more services below to provide the most accurate IP geolocation results. We recommend to enable 2 or more services below to provide the most accurate IP geolocation results.
7 Geolocation Database Update Geolocation Database Update
8 You have the latest %1 Geolocation Database available on our server. Please check back later for the updates. You have the latest %1 Geolocation Database available on our server. Please check back later for the updates.
9 Not Installed Not Installed
10 Installed v%1 on %2 Installed v%1 on %2
11 Installed on %1 Installed on %1
12 Download in Progress... Download in Progress...
13 Installation in Progress... Installation in Progress...
14 Importing Geolocation Database... Importing Geolocation Database...
15 Done! Done!
16 Data Import Error Data Import Error
17 We couldn't find %1 CSV files in 'media/prgeoiplookup' folder. \nPlease read our online manual for more info about manual installation method. We couldn't find %1 CSV files in 'media/prgeoiplookup' folder. \nPlease read our online manual for more info about manual installation method.
18 No records found No records found
19 Continent Continent
20 Continent Code Continent Code
21 Country Country
22 Country Code Country Code
23 City City
24 Postal Code Postal Code
25 Time Zone Time Zone
26 Is In European Union Is In European Union
27 Latitude Latitude
28 Longitude Longitude
29 Metro Code Metro Code
30 Subdivision 1 Iso Code Subdivision 1 Iso Code
31 Subdivision 1 Name Subdivision 1 Name
32 Subdivision 2 Iso Code Subdivision 2 Iso Code
33 Subdivision 2 Name Subdivision 2 Name
34 Database Name Database Name
35 Automatic Installation Automatic Installation
36 Manual Installation Manual Installation
37 IP Geolocation Lookup IP Geolocation Lookup
38 General General
39 Enable Extension Enable Extension
40 Serial Key Serial Key
41 Your can find <strong>Serial Key</strong> in your account at <a target="_blank" href="https://store.plumrocket.com/downloadable/customer/products/">store.plumrocket.com</a>. For manual <a target="_blank" href="http://wiki.plumrocket.com/wiki/License_Installation">click here</a>. Your can find <strong>Serial Key</strong> in your account at <a target="_blank" href="https://store.plumrocket.com/downloadable/customer/products/">store.plumrocket.com</a>. For manual <a target="_blank" href="http://wiki.plumrocket.com/wiki/License_Installation">click here</a>.
42 Services Services
43 Maxmind IP Geolocation Database Maxmind IP Geolocation Database
44 Database Status Database Status
45 Installation Method Installation Method
46 Install Database Install Database
47 IpToCountry IP Geolocation Database IpToCountry IP Geolocation Database
48 Ipapi.Com - IP Geolocation API Ipapi.Com - IP Geolocation API
49 Test Connection Test Connection
50 IP Geolocation Lookup Test IP Geolocation Lookup Test
51 IP Address IP Address
52 Enter IP address to test IP Geolocation Lookup. Your own IP address is automatically populated in this field. Enter IP address to test IP Geolocation Lookup. Your own IP address is automatically populated in this field.
53 Test IP Geolocation Lookup Test IP Geolocation Lookup
54 IP Geolocation Information IP Geolocation Information
55 View Location on Map View Location on Map
56 REST API REST API
+20
View File
@@ -0,0 +1,20 @@
<?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
*/
use Magento\Framework\Component\ComponentRegistrar;
ComponentRegistrar::register(ComponentRegistrar::MODULE, 'Plumrocket_GeoIPLookup', __DIR__);
@@ -0,0 +1,25 @@
<?xml version="1.0" ?>
<!--
/**
* 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
*/
-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<head>
<css src="Plumrocket_GeoIPLookup::css/prgeoiplookup.css" />
<script src="Plumrocket_GeoIPLookup::js/prgeoiplookup.js" />
</head>
</page>
@@ -0,0 +1,16 @@
<?xml version="1.0" ?>
<!--
/**
* @package Plumrocket_GeoIPLookup
* @copyright Copyright (c) 2024 Plumrocket Inc. (https://plumrocket.com)
* @license https://plumrocket.com/license/ End-user License Agreement
*/
-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceContainer name="js">
<block name="prgeoiplookup.dynamic.comment.script" template="Plumrocket_GeoIPLookup::system/config/script/dynamic_comment.phtml"/>
</referenceContainer>
</body>
</page>
@@ -0,0 +1,32 @@
<?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
*/
?>
<?php /** @var \Plumrocket\GeoIPLookup\Block\Adminhtml\System\Config\Data\Buttons\AbstractBlock $block */ ?>
<div class="pp-buttons-container">
<button id="<?= $block->escapeHtmlAttr($block->getHtmlId()) ?>"
onclick="<?= /* @noEscape */ $block->getOnclick($block->getHtmlId()) ?>">
<span>
<span>
<span>
<?= $block->escapeHtml($block->getButtonLabel()) ?>
</span>
</span>
</span>
</button>
</div>
@@ -0,0 +1,44 @@
<?php
/**
* @package Plumrocket_GeoIPLookup
* @copyright Copyright (c) 2024 Plumrocket Inc. (https://plumrocket.com)
* @license https://plumrocket.com/license/ End-user License Agreement
*/
use Plumrocket\GeoIPLookup\Model\System\Config\Source\Installmethods;
?>
<script type='text/javascript'>
require([
'jquery',
'mage/translate'
], function ($, $t) {
const setComment = function (installMethod) {
const commentField = $(installMethod).parent().find('.method_comment');
if (! commentField.length) {
return;
}
const fieldId = $(installMethod).attr('id') || '';
const dbName = fieldId.includes('iptocountry') ? 'IpToCountry' : 'MaxMind';
switch (installMethod.value) {
case '<?= /* @noEscape */ Installmethods::AUTOMATIC ?>':
commentField.html($t("Automatically download the " + dbName + " IP geolocation database from Plumrocket servers. This database includes country, state, city, postal code, time zone, locale, latitude, and longitude. The installation may take around 5 minutes. Ensure you have 100 MB of free space on your web server for this method."));
break;
case '<?= /* @noEscape */ Installmethods::MANUAL ?>':
commentField.html($t('Manually upload your own copy of the ' + dbName + ' IP geolocation database to your web server. This database includes country, state, city, postal code, time zone, locale, latitude, and longitude. The installation may take around 5 minutes. Ensure you have 100 MB of free space on your web server for this method. For manual installation instructions, please <a href=https://plumrocket.com/docs/magento-geoip-lookup/v1/devguide/databases-manual-installation#maxmind-geoip-database" target="_blank">click here</a>.'));
break;
}
};
const installMethods = $('.install-method');
installMethods.each(function () {
setComment(this);
});
installMethods.on('change', function (event) {
setComment(event.target);
});
});
</script>
@@ -0,0 +1,43 @@
/**
* 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
*/
.status-container .status{font-weight: bold;}
.progress-bar{width: 120px; display: inline-block;}
.w3-container:after,.w3-container:before{padding:0.01em 16px}
.w3-center{text-align:center!important}
.w3-border{border:1px solid #ccc!important}
/* Colors */
.w3-blue,.w3-hover-blue:hover{color:#fff!important;background-color:#2196F3!important}
.progress-title{display: inline-block; margin-left: 5px;}
.prgeoiplookup-service-notice {
padding:10px;
background-color:#f8f8f8;
border:1px solid #ddd;
margin-bottom:7px;
text-decoration: underline red;
}
#prgeoiplookup_geoiptest_geoinfo {
height: 305px;
}
#row_prgeoiplookup_geoiptest_geoinfo,
#row_prgeoiplookup_geoiptest_location_on_map,
#hidden_field_api_url,
#row_prgeoiplookup_geoiptest_rest_ip {
display: none;
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

@@ -0,0 +1,17 @@
/**
* 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_Extension
* @copyright Copyright (c) 2026 Plumrocket Inc. (http://www.plumrocket.com)
* @license http://wiki.plumrocket.net/wiki/EULA End-user License Agreement
*/
var __prinitparam = 'MzM5Njkw';
@@ -0,0 +1,202 @@
/**
* 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
*/
require([
'jquery',
'mage/storage',
'mage/translate',
'Magento_Ui/js/modal/alert',
'domReady!'
], function ($, storage, __, alert) {
'use strict';
window.runInstallation = function (serviceId, urlAutomatic, urlProgress) {
let resultId = serviceId + '_status',
timerProgress = null;
const enableSelect = function() {
let selectId = serviceId + '_enabled',
tooltip = serviceId + '_tooltip',
tooltipElement = $('#' + tooltip);
$('#' + selectId).prop('disabled', false);
if (tooltipElement) {
tooltipElement.remove();
}
};
const updateStatus = function(data) {
let percent = '0%',
color = 'green',
message = '';
switch (data.status) {
case "process":
$('#' + resultId + ' .status')[0].hide();
$('#' + resultId + ' .progress-container')[0].show();
percent = parseInt(parseInt(data.exec) * 100 / parseInt(data.total)) + '%';
message = data.message;
break;
case "success":
window.clearInterval(timerProgress);
$('body').loader('hide');
$('.loading-mask').css('background', 'rgba(255, 255, 255, 0.4)');
$('#' + resultId + ' .progress-container')[0].hide();
$('#' + resultId + ' .status')[0].setStyle({color: color}).update(data.message).show();
enableSelect();
break;
default:
window.clearInterval(timerProgress);
$('body').loader('hide');
$('.loading-mask').css('background', 'rgba(255, 255, 255, 0.4)');
$('#' + resultId + ' .progress-container')[0].hide();
color = 'red';
message = (typeof data.message !== "undefined") ? data.message : __("Import Failed!");
$('#' + resultId + ' .status')[0].setStyle({color: color}).update(message).show();
}
$('#' + resultId + ' .progress-container .progress-value')[0].setStyle({width: percent}).update(percent);
$('#' + resultId + ' .progress-container .progress-title')[0].update(message);
if ('alert' in data) {
window.showAlert(data.error,data.alert);
}
}
const getInstallationProgress = function () {
storage.get(
urlProgress
).done(function (response) {
response = JSON.parse(response);
if (response && response.status) {
updateStatus(response);
}
}).fail(function () {
window.clearInterval(timerProgress);
$('body').loader('hide');
$('.loading-mask').css('background', 'rgba(255, 255, 255, 0.4)');
});
return true;
};
updateStatus({
status: 'process',
exec: 1,
total: 100,
message: __('Installation in Progress...')
});
timerProgress = setInterval(getInstallationProgress, 3000);
$('body').loader('show');
$('.loading-mask').css('background', 'rgba(255, 255, 255, 0)');
storage.get(
urlAutomatic
).done(function(response) {
response = JSON.parse(response);
if (response) {
updateStatus(response);
}
}).fail(function() {
updateStatus({status: 'fail'});
});
};
window.prGeoIptestApiConnection = function (serviceUrl, serviceId) {
let accessKey = $('#prgeoiplookup_methods_ipapigeoip_access_key').val(),
useSsl = $('#prgeoiplookup_methods_ipapigeoip_use_https').val(),
resultText = __('Connection Error!'),
resultStyle = 'color: red;',
resultClass = 'message-error error';
serviceUrl += '?access_key=%1&use_ssl=%2'.replace('%1', accessKey).replace('%2', useSsl);
$.ajax({
showLoader: true,
url: serviceUrl,
type: "GET",
dataType: 'JSON'
}).done(function(response) {
if (response.success) {
resultText = __('Connection Successful!');
resultStyle = 'color: green;';
resultClass = 'message-success success';
}
if (response.hasOwnProperty('message')) {
resultText += '<br><p>' + response.message + '</p>';
}
}).always(function() {
let resultContainerId = serviceId + '_result',
resultBlock = $('#' + resultContainerId);
if (resultBlock.length) {
resultBlock.remove();
}
$('#' + serviceId).after(
'<div id="' + resultContainerId + '" class="message '
+ resultClass
+ '" style="background: none;'
+ resultStyle
+ '">'
+ resultText
+ '</div>'
);
});
};
window.geoipTest = function (testUrl) {
var ip = $('#prgeoiplookup_geoiptest_ip_address').val(),
url = testUrl + 'ip/' + ip,
geoInfo = $('#prgeoiplookup_geoiptest_geoinfo'),
map = $('#prgeoiplookup_google_map'),
mapUrl = 'https://maps.google.com/?q=',
apiTestEl = $('#rest_ip_test'),
restApiUrl = $('#hidden_field_api_url').text();
$('body').loader('show');
storage.get(
url
).done(function(response) {
response = JSON.parse(response);
geoInfo.val(response.text);
apiTestEl.attr('href', restApiUrl + ip);
apiTestEl.text(restApiUrl + ip);
if (response.latitude && response.longitude) {
map.attr('href', mapUrl + response.latitude + ',' + response.longitude);
} else if (response.country_name) {
map.attr('href', mapUrl + response.country_name);
}
var prefix = 'row_prgeoiplookup_geoiptest';
$('#' + prefix + '_rest_ip').show();
$('#' + prefix + '_geoinfo').show();
$('#' + prefix + '_location_on_map').show();
}).fail(function() {
}).always(function() {
$('body').loader('hide');
});
};
$('#prgeoiplookup_geoiptest_geoinfo').val('');
window.showAlert = function (title, message) {
alert({
title: title,
content: message
});
};
});