Skip to content

Commit d5f7f37

Browse files
authored
Merge pull request #14 from magefan/6959-maxmindapi
Add download GeoIp Database via MaxMind API
2 parents 6c72324 + 643b1f7 commit d5f7f37

File tree

5 files changed

+190
-8
lines changed

5 files changed

+190
-8
lines changed

Block/Adminhtml/System/Config/Form/MaxMindInfo.php

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,10 +48,15 @@ public function render(\Magento\Framework\Data\Form\Element\AbstractElement $ele
4848
{
4949
$dirList = $this->_dir->getPath('var'). '/magefan/geoip/GeoLite2-Country.mmdb';
5050

51+
if (!file_exists($dirList)) {
52+
try {
53+
$this->maxMind->update();
54+
} catch (\Exception $e) {
55+
}
56+
}
57+
5158
if (file_exists($dirList)) {
5259
$modified = date("F d, Y.", filemtime($dirList));
53-
} elseif ($this->maxMind->update()) {
54-
$modified = date("F d, Y.", filemtime($dirList));
5560
} else {
5661
$modified = __('Can not download DB.');
5762
}

Controller/Adminhtml/Maxmind/Update.php

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,9 +47,13 @@ public function __construct(
4747
public function execute()
4848
{
4949
$resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
50-
if ($this->maxMind->update()) {
50+
51+
try {
52+
$this->maxMind->update();
5153
$this->messageManager->addSuccessMessage('MaxMind GeoIP Database has been updated successfully.');
52-
} else {
54+
} catch (\Magento\Framework\Exception\LocalizedException $e) {
55+
$this->messageManager->addErrorMessage($e->getMessage());
56+
} catch (\Exception $e) {
5357
$this->messageManager->addErrorMessage('Something went wrong while updating the GeoIP database.');
5458
}
5559

Model/Config.php

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
<?php
2+
/**
3+
* Copyright © Magefan (support@magefan.com). All rights reserved.
4+
* See LICENSE.txt for license details (http://opensource.org/licenses/osl-3.0.php).
5+
*/
6+
7+
namespace Magefan\GeoIp\Model;
8+
9+
use Magento\Framework\App\Config\ScopeConfigInterface;
10+
use Magento\Store\Model\ScopeInterface;
11+
12+
class Config
13+
{
14+
const XML_PATH_LICENSE_KEY = 'mfgeoip/update_geoip/key';
15+
16+
/**
17+
* @var ScopeConfigInterface
18+
*/
19+
private $scopeConfig;
20+
21+
/**
22+
* Config constructor.
23+
* @param ScopeConfigInterface $scopeConfig
24+
*/
25+
public function __construct(
26+
ScopeConfigInterface $scopeConfig
27+
) {
28+
$this->scopeConfig = $scopeConfig;
29+
}
30+
31+
/**
32+
* @param $path
33+
* @param null $storeId
34+
* @return mixed
35+
*/
36+
public function getConfig($path, $storeId = null)
37+
{
38+
return $this->scopeConfig->getValue(
39+
$path,
40+
ScopeInterface::SCOPE_STORE,
41+
$storeId
42+
);
43+
}
44+
45+
/**
46+
* @param null $storeId
47+
* @return bool
48+
*/
49+
public function getLicenseKey($storeId = null)
50+
{
51+
return (string)$this->getConfig(
52+
self::XML_PATH_LICENSE_KEY,
53+
$storeId
54+
);
55+
}
56+
}

Model/GeoIpDatabase/MaxMind.php

Lines changed: 114 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,9 @@
66

77
namespace Magefan\GeoIp\Model\GeoIpDatabase;
88

9+
use Magefan\GeoIp\Model\Config;
10+
use Magento\Framework\Archive\Gz;
11+
use Magento\Framework\Archive\Tar;
912
/**
1013
* Class MaxMind
1114
* @package Magefan\GeoIp\Model\GeoIpDatabase
@@ -16,6 +19,7 @@ class MaxMind
1619
* Url
1720
*/
1821
const URL = 'https://magefan.com/media/geoip/GeoLite2-Country.mmdb';
22+
const URL_API = 'https://download.maxmind.com/app/geoip_download';
1923
/**
2024
* @var \Magento\Framework\Filesystem\DirectoryList
2125
*/
@@ -29,20 +33,44 @@ class MaxMind
2933
*/
3034
protected $_logger;
3135

36+
/**
37+
* @var Config
38+
*/
39+
private $config;
40+
41+
/**
42+
* @var Gz
43+
*/
44+
private $gz;
45+
46+
/**
47+
* @var Tar
48+
*/
49+
private $tar;
50+
3251
/**
3352
* MaxMind constructor.
3453
* @param \Magento\Framework\Filesystem\DirectoryList $dir
3554
* @param \Magento\Framework\Filesystem\Io\File $file
3655
* @param \Psr\Log\LoggerInterface $logger
56+
* @param Config $config
57+
* @param Gz $gz
58+
* @param Tar $tar
3759
*/
3860
public function __construct(
3961
\Magento\Framework\Filesystem\DirectoryList $dir,
4062
\Magento\Framework\Filesystem\Io\File $file,
41-
\Psr\Log\LoggerInterface $logger
63+
\Psr\Log\LoggerInterface $logger,
64+
Config $config,
65+
Gz $gz,
66+
Tar $tar
4267
) {
4368
$this->_dir = $dir;
4469
$this->_file = $file;
4570
$this->_logger = $logger;
71+
$this->config = $config;
72+
$this->gz = $gz;
73+
$this->tar = $tar;
4674
}
4775

4876
/**
@@ -67,6 +95,19 @@ protected function createDir($dirPath)
6795
* @throws \Magento\Framework\Exception\LocalizedException
6896
*/
6997
public function update()
98+
{
99+
if ($this->config->getLicenseKey()) {
100+
return $this->updateByAPI();
101+
} else {
102+
return $this->updateByMagefanServer();
103+
}
104+
}
105+
/**
106+
* @return bool
107+
* @throws \Magento\Framework\Exception\FileSystemException
108+
* @throws \Magento\Framework\Exception\LocalizedException
109+
*/
110+
public function updateByMagefanServer()
70111
{
71112
$dbPath = $this->_dir->getPath('var') . '/magefan/geoip';
72113
$this->createDir($dbPath);
@@ -78,19 +119,88 @@ public function update()
78119
//curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
79120
$result = curl_exec($ch);
80121
if (!$result) {
81-
throw new \Magento\Framework\Exception\LocalizedException(__('Can not download file GeoLite2-Country.mmdb'));
122+
throw new \Magento\Framework\Exception\LocalizedException(__('Can not download GeoLite2-Country.mmdb file.'));
82123
}
83124
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
84125
if ($http_code != 200) {
85-
throw new \Magento\Framework\Exception\LocalizedException(__('Fail download file. Http code: %1', $http_code) );
126+
throw new \Magento\Framework\Exception\LocalizedException(__('File download failed. Http code: %1.', $http_code) );
86127
}
87128
curl_close($ch);
88129

89130
$output_filename = $dbPath . '/' . 'GeoLite2-Country.mmdb';
90131
$fp = fopen($output_filename, 'w');
91132
if (!fwrite($fp, $result)) {
92-
throw new \Magento\Framework\Exception\LocalizedException(__('Can not save or overwrite file GeoLite2-Country.mmdb'));
133+
throw new \Magento\Framework\Exception\LocalizedException(__('Can not save or overwrite GeoLite2-Country.mmdb file.'));
134+
}
135+
fclose($fp);
136+
137+
return true;
138+
}
139+
140+
/**
141+
* Get GeoIP Databse via MaxMind API
142+
*
143+
* @return bool
144+
* @throws \Magento\Framework\Exception\FileSystemException
145+
* @throws \Magento\Framework\Exception\LocalizedException
146+
*/
147+
private function updateByAPI()
148+
{
149+
$dbPath = $this->_dir->getPath('var') . '/magefan/geoip';
150+
$this->createDir($dbPath);
151+
$url = self::URL_API . '?' . http_build_query([
152+
'edition_id' => 'GeoLite2-Country',
153+
'suffix' => 'tar.gz',
154+
'license_key' => $this->config->getLicenseKey()
155+
]);
156+
157+
$ch = curl_init($url);
158+
159+
$outputFilename = $dbPath . DIRECTORY_SEPARATOR . 'GeoLite2-Country.tar.gz';
160+
$fp = fopen($outputFilename, 'wb');
161+
162+
curl_setopt_array($ch, array(
163+
CURLOPT_HTTPGET => true,
164+
CURLOPT_BINARYTRANSFER => true,
165+
CURLOPT_HEADER => false,
166+
CURLOPT_FILE => $fp,
167+
));
168+
169+
$response = curl_exec($ch);
170+
171+
if (!$response) {
172+
throw new \Magento\Framework\Exception\LocalizedException(
173+
__('Can not download GeoLite2-Country.tar.gz archive.')
174+
);
93175
}
176+
177+
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
178+
if ($http_code != 200) {
179+
throw new \Magento\Framework\Exception\LocalizedException(
180+
__('File download failed. Http code: %1. Please check the license key.', $http_code)
181+
);
182+
}
183+
184+
curl_close($ch);
185+
186+
$unpackGz = $this->gz->unpack($outputFilename, $dbPath . DIRECTORY_SEPARATOR);
187+
$unpackTar = $this->tar->unpack($unpackGz, $dbPath . DIRECTORY_SEPARATOR);
188+
$dir = $this->_file->getDirectoriesList($unpackTar);
189+
$this->_file->mv($dir[0] . '/GeoLite2-Country.mmdb', $unpackTar . 'GeoLite2-Country.mmdb');
190+
191+
$this->_file->open(['path' => $unpackTar]);
192+
$list = $this->_file->ls();
193+
$this->_file->close();
194+
195+
foreach ($list as $info) {
196+
if ($info['text'] !== 'GeoLite2-Country.mmdb') {
197+
if (isset($info['id'])) {
198+
$this->_file->rmdirRecursive($info['id']);
199+
}
200+
$this->_file->rm($info['text']);
201+
}
202+
}
203+
94204
fclose($fp);
95205

96206
return true;

etc/adminhtml/system.xml

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,13 @@
3333
<field id="maxmind" translate="label comment" type="text" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
3434
<frontend_model>Magefan\GeoIp\Block\Adminhtml\System\Config\Form\MaxMindInfo</frontend_model>
3535
</field>
36+
<field id="key" translate="label comment" type="text" sortOrder="15" showInDefault="1" showInWebsite="0" showInStore="0">
37+
<label>License Key (optional)</label>
38+
<comment><![CDATA[
39+
Enter <a title="Generate a License Key" target="_blank" rel="nofollow noopener" href="https://support.maxmind.com/hc/en-us/articles/4407111582235-Generate-a-License-Key">MaxMind License Key</a> and save config to update the MaxMind GeoIP Database directly from MaxMind and not via the Magefan server.
40+
]]>
41+
</comment>
42+
</field>
3643
<field id="listbutton" translate="label" sortOrder="20" showInDefault="1" showInWebsite="1" showInStore="1">
3744
<frontend_model>Magefan\GeoIp\Block\Adminhtml\System\Config\Form\Button</frontend_model>
3845
</field>

0 commit comments

Comments
 (0)