├── Api ├── IpToCountryRepositoryInterface.php └── IpToRegionRepositoryInterface.php ├── Block └── Adminhtml │ └── System │ └── Config │ └── Form │ ├── Button.php │ ├── CloudflareCheck.php │ ├── Info.php │ ├── IpInfo.php │ └── MaxMindInfo.php ├── Controller └── Adminhtml │ └── Maxmind │ └── Update.php ├── Cron └── UpdateMaxMind.php ├── LICENSE.txt ├── Model ├── Config.php ├── GeoIpDatabase │ └── MaxMind.php ├── IpToCountryRepository.php └── IpToRegionRepository.php ├── README.md ├── Setup └── Patch │ └── Data │ └── DropTable.php ├── composer.json ├── data ├── GeoLite2-City.mmdb └── GeoLite2-Country.mmdb ├── etc ├── acl.xml ├── adminhtml │ ├── routes.xml │ └── system.xml ├── config.xml ├── crontab.xml ├── di.xml └── module.xml ├── registration.php └── view └── adminhtml └── templates └── system └── config └── button └── button.phtml /Api/IpToCountryRepositoryInterface.php: -------------------------------------------------------------------------------- 1 | getTemplate()) { 26 | $this->setTemplate(static::BUTTON_TEMPLATE); 27 | } 28 | return $this; 29 | } 30 | /** 31 | * Render button 32 | * 33 | * @param \Magento\Framework\Data\Form\Element\AbstractElement $element 34 | * @return string 35 | */ 36 | public function render(\Magento\Framework\Data\Form\Element\AbstractElement $element) 37 | { 38 | // Remove scope label 39 | $element->unsScope()->unsCanUseWebsiteValue()->unsCanUseDefaultValue(); 40 | return parent::render($element); 41 | } 42 | 43 | /** 44 | * Get the button and scripts contents 45 | * 46 | * @param \Magento\Framework\Data\Form\Element\AbstractElement $element 47 | * @return string 48 | */ 49 | protected function _getElementHtml(\Magento\Framework\Data\Form\Element\AbstractElement $element) 50 | { 51 | return $this->_toHtml(); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /Block/Adminhtml/System/Config/Form/CloudflareCheck.php: -------------------------------------------------------------------------------- 1 | getRequest()->getServer('HTTP_CF_IPCOUNTRY'); 21 | $html = ''; 22 | 23 | if (!$countryCode) { 24 | $html = ''; 39 | } 40 | return $html; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Block/Adminhtml/System/Config/Form/Info.php: -------------------------------------------------------------------------------- 1 | ipToCountryRepository = $ipToCountryRepository; 43 | $this->ipToRegionRepository = $ipToRegionRepository; 44 | } 45 | 46 | /** 47 | * Return info block html 48 | * @param \Magento\Framework\Data\Form\Element\AbstractElement $element 49 | * @return string 50 | */ 51 | public function render(\Magento\Framework\Data\Form\Element\AbstractElement $element) 52 | { 53 | $country = $this->ipToCountryRepository->getVisitorCountryCode(); 54 | if ($country == "ZZ") { 55 | $country = 'Undefined'; 56 | } 57 | 58 | $ip = $this->ipToCountryRepository->getRemoteAddress(); 59 | $regionId = $this->ipToRegionRepository->getVisitorRegionCode(); 60 | 61 | $html = '
62 | Your IP Address: ' . $ip . '
63 | Country: ' . $country . '
64 | Region: ' . $regionId . ' 65 |
'; 66 | 67 | return $html; 68 | } 69 | 70 | } 71 | -------------------------------------------------------------------------------- /Block/Adminhtml/System/Config/Form/MaxMindInfo.php: -------------------------------------------------------------------------------- 1 | _dir = $dir; 38 | $this->maxMind = $maxMind; 39 | } 40 | 41 | /** 42 | * @param \Magento\Framework\Data\Form\Element\AbstractElement $element 43 | * @return string 44 | * @throws \Magento\Framework\Exception\FileSystemException 45 | * @throws \Magento\Framework\Exception\LocalizedException 46 | */ 47 | public function render(\Magento\Framework\Data\Form\Element\AbstractElement $element) 48 | { 49 | $dirList = $this->_dir->getPath('var'). '/magefan/geoip/GeoLite2-Country.mmdb'; 50 | 51 | if (!file_exists($dirList)) { 52 | try { 53 | $this->maxMind->update(); 54 | } catch (\Exception $e) { 55 | } 56 | } 57 | 58 | if (file_exists($dirList)) { 59 | $modified = date("F d, Y.", filemtime($dirList)); 60 | } else { 61 | $modified = __('Can not download DB.'); 62 | } 63 | 64 | $html = '
65 | This GeoIP extension includes GeoLite2 data created by MaxMind, available from 66 | https://www.maxmind.com.
67 | Last GeoIP Data Base Update: '. $modified .' 68 |
'; 69 | 70 | return $html; 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /Controller/Adminhtml/Maxmind/Update.php: -------------------------------------------------------------------------------- 1 | maxMind = $maxMind; 40 | } 41 | 42 | /** 43 | * @return \Magento\Framework\App\ResponseInterface|\Magento\Framework\Controller\ResultInterface 44 | * @throws \Magento\Framework\Exception\FileSystemException 45 | * @throws \Magento\Framework\Exception\LocalizedException 46 | */ 47 | public function execute() 48 | { 49 | $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT); 50 | 51 | try { 52 | $this->maxMind->update(); 53 | $this->messageManager->addSuccessMessage('MaxMind GeoIP Database has been updated successfully.'); 54 | } catch (\Magento\Framework\Exception\LocalizedException $e) { 55 | $this->messageManager->addErrorMessage($e->getMessage()); 56 | } catch (\Exception $e) { 57 | $this->messageManager->addErrorMessage('Something went wrong while updating the GeoIP database.'); 58 | } 59 | 60 | $resultRedirect->setUrl($this->_redirect->getRefererUrl()); 61 | return $resultRedirect; 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /Cron/UpdateMaxMind.php: -------------------------------------------------------------------------------- 1 | maxMind = $maxMind; 33 | $this->_logger = $logger; 34 | } 35 | 36 | /** 37 | * Execute Cron UpdateMaxMind 38 | */ 39 | public function execute() 40 | { 41 | try { 42 | $this->maxMind->update(); 43 | } catch (\Exception $e) { 44 | $this->_logger->debug($e->getMessage()); 45 | return false; 46 | } 47 | return true; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | 2 | Open Software License ("OSL") v. 3.0 3 | 4 | This Open Software License (the "License") applies to any original work of authorship (the "Original Work") whose owner (the "Licensor") has placed the following licensing notice adjacent to the copyright notice for the Original Work: 5 | 6 | Licensed under the Open Software License version 3.0 7 | 8 | 1. Grant of Copyright License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, for the duration of the copyright, to do the following: 9 | 10 | 1. to reproduce the Original Work in copies, either alone or as part of a collective work; 11 | 12 | 2. to translate, adapt, alter, transform, modify, or arrange the Original Work, thereby creating derivative works ("Derivative Works") based upon the Original Work; 13 | 14 | 3. to distribute or communicate copies of the Original Work and Derivative Works to the public, with the proviso that copies of Original Work or Derivative Works that You distribute or communicate shall be licensed under this Open Software License; 15 | 16 | 4. to perform the Original Work publicly; and 17 | 18 | 5. to display the Original Work publicly. 19 | 20 | 2. Grant of Patent License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, under patent claims owned or controlled by the Licensor that are embodied in the Original Work as furnished by the Licensor, for the duration of the patents, to make, use, sell, offer for sale, have made, and import the Original Work and Derivative Works. 21 | 22 | 3. Grant of Source Code License. The term "Source Code" means the preferred form of the Original Work for making modifications to it and all available documentation describing how to modify the Original Work. Licensor agrees to provide a machine-readable copy of the Source Code of the Original Work along with each copy of the Original Work that Licensor distributes. Licensor reserves the right to satisfy this obligation by placing a machine-readable copy of the Source Code in an information repository reasonably calculated to permit inexpensive and convenient access by You for as long as Licensor continues to distribute the Original Work. 23 | 24 | 4. Exclusions From License Grant. Neither the names of Licensor, nor the names of any contributors to the Original Work, nor any of their trademarks or service marks, may be used to endorse or promote products derived from this Original Work without express prior permission of the Licensor. Except as expressly stated herein, nothing in this License grants any license to Licensor's trademarks, copyrights, patents, trade secrets or any other intellectual property. No patent license is granted to make, use, sell, offer for sale, have made, or import embodiments of any patent claims other than the licensed claims defined in Section 2. No license is granted to the trademarks of Licensor even if such marks are included in the Original Work. Nothing in this License shall be interpreted to prohibit Licensor from licensing under terms different from this License any Original Work that Licensor otherwise would have a right to license. 25 | 26 | 5. External Deployment. The term "External Deployment" means the use, distribution, or communication of the Original Work or Derivative Works in any way such that the Original Work or Derivative Works may be used by anyone other than You, whether those works are distributed or communicated to those persons or made available as an application intended for use over a network. As an express condition for the grants of license hereunder, You must treat any External Deployment by You of the Original Work or a Derivative Work as a distribution under section 1(c). 27 | 28 | 6. Attribution Rights. You must retain, in the Source Code of any Derivative Works that You create, all copyright, patent, or trademark notices from the Source Code of the Original Work, as well as any notices of licensing and any descriptive text identified therein as an "Attribution Notice." You must cause the Source Code for any Derivative Works that You create to carry a prominent Attribution Notice reasonably calculated to inform recipients that You have modified the Original Work. 29 | 30 | 7. Warranty of Provenance and Disclaimer of Warranty. Licensor warrants that the copyright in and to the Original Work and the patent rights granted herein by Licensor are owned by the Licensor or are sublicensed to You under the terms of this License with the permission of the contributor(s) of those copyrights and patent rights. Except as expressly stated in the immediately preceding sentence, the Original Work is provided under this License on an "AS IS" BASIS and WITHOUT WARRANTY, either express or implied, including, without limitation, the warranties of non-infringement, merchantability or fitness for a particular purpose. THE ENTIRE RISK AS TO THE QUALITY OF THE ORIGINAL WORK IS WITH YOU. This DISCLAIMER OF WARRANTY constitutes an essential part of this License. No license to the Original Work is granted by this License except under this disclaimer. 31 | 32 | 8. Limitation of Liability. Under no circumstances and under no legal theory, whether in tort (including negligence), contract, or otherwise, shall the Licensor be liable to anyone for any indirect, special, incidental, or consequential damages of any character arising as a result of this License or the use of the Original Work including, without limitation, damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses. This limitation of liability shall not apply to the extent applicable law prohibits such limitation. 33 | 34 | 9. Acceptance and Termination. If, at any time, You expressly assented to this License, that assent indicates your clear and irrevocable acceptance of this License and all of its terms and conditions. If You distribute or communicate copies of the Original Work or a Derivative Work, You must make a reasonable effort under the circumstances to obtain the express assent of recipients to the terms of this License. This License conditions your rights to undertake the activities listed in Section 1, including your right to create Derivative Works based upon the Original Work, and doing so without honoring these terms and conditions is prohibited by copyright law and international treaty. Nothing in this License is intended to affect copyright exceptions and limitations (including 'fair use' or 'fair dealing'). This License shall terminate immediately and You may no longer exercise any of the rights granted to You by this License upon your failure to honor the conditions in Section 1(c). 35 | 36 | 10. Termination for Patent Action. This License shall terminate automatically and You may no longer exercise any of the rights granted to You by this License as of the date You commence an action, including a cross-claim or counterclaim, against Licensor or any licensee alleging that the Original Work infringes a patent. This termination provision shall not apply for an action alleging patent infringement by combinations of the Original Work with other software or hardware. 37 | 38 | 11. Jurisdiction, Venue and Governing Law. Any action or suit relating to this License may be brought only in the courts of a jurisdiction wherein the Licensor resides or in which Licensor conducts its primary business, and under the laws of that jurisdiction excluding its conflict-of-law provisions. The application of the United Nations Convention on Contracts for the International Sale of Goods is expressly excluded. Any use of the Original Work outside the scope of this License or after its termination shall be subject to the requirements and penalties of copyright or patent law in the appropriate jurisdiction. This section shall survive the termination of this License. 39 | 40 | 12. Attorneys' Fees. In any action to enforce the terms of this License or seeking damages relating thereto, the prevailing party shall be entitled to recover its costs and expenses, including, without limitation, reasonable attorneys' fees and costs incurred in connection with such action, including any appeal of such action. This section shall survive the termination of this License. 41 | 42 | 13. Miscellaneous. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. 43 | 44 | 14. Definition of "You" in This License. "You" throughout this License, whether in upper or lower case, means an individual or a legal entity exercising rights under, and complying with all of the terms of, this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with you. For purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. 45 | 46 | 15. Right to Use. You may use the Original Work in all ways not otherwise restricted or conditioned by this License or by law, and Licensor promises not to interfere with or be responsible for such uses by You. 47 | 48 | 16. Modification of This License. This License is Copyright (C) 2005 Lawrence Rosen. Permission is granted to copy, distribute, or communicate this License without modification. Nothing in this License permits You to modify this License as applied to the Original Work or to Derivative Works. However, You may modify the text of this License and copy, distribute or communicate your modified version (the "Modified License") and apply it to other original works of authorship subject to the following conditions: (i) You may not indicate in any way that your Modified License is the "Open Software License" or "OSL" and you may not use those names in the name of your Modified License; (ii) You must replace the notice specified in the first paragraph above with the notice "Licensed under " or with a notice of your own that is not confusingly similar to the notice in this License; and (iii) You may not claim that your original works are open source software unless your Modified License has been approved by Open Source Initiative (OSI) and You comply with its license review and certification process. -------------------------------------------------------------------------------- /Model/Config.php: -------------------------------------------------------------------------------- 1 | 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 | } 57 | -------------------------------------------------------------------------------- /Model/GeoIpDatabase/MaxMind.php: -------------------------------------------------------------------------------- 1 | _dir = $dir; 73 | $this->_file = $file; 74 | $this->_logger = $logger; 75 | $this->config = $config; 76 | $this->gz = $gz; 77 | $this->tar = $tar; 78 | } 79 | 80 | /** 81 | * @return bool 82 | * @throws \Magento\Framework\Exception\FileSystemException 83 | * @throws \Magento\Framework\Exception\LocalizedException 84 | */ 85 | protected function createDir($dirPath) 86 | { 87 | $ioAdapter = $this->_file; 88 | if (!is_dir($dirPath)) { 89 | if (!$ioAdapter->mkdir($dirPath, 0775)) { 90 | throw new \Magento\Framework\Exception\LocalizedException(__('Can not create folder' . $dirPath)); 91 | } 92 | } 93 | return true; 94 | } 95 | 96 | /** 97 | * @return bool 98 | * @throws \Magento\Framework\Exception\FileSystemException 99 | * @throws \Magento\Framework\Exception\LocalizedException 100 | */ 101 | public function update() 102 | { 103 | if ($this->config->getLicenseKey()) { 104 | return $this->updateByAPI(); 105 | } else { 106 | return $this->updateByMagefanServer(); 107 | } 108 | } 109 | /** 110 | * @return bool 111 | * @throws \Magento\Framework\Exception\FileSystemException 112 | * @throws \Magento\Framework\Exception\LocalizedException 113 | */ 114 | public function updateByMagefanServer() 115 | { 116 | $dbPath = $this->_dir->getPath('var') . '/magefan/geoip'; 117 | $this->createDir($dbPath); 118 | 119 | foreach ([self::URL, self::URL_CITY] as $url) { 120 | $ch = curl_init(); 121 | curl_setopt($ch, CURLOPT_URL, $url); 122 | curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 123 | 124 | $result = curl_exec($ch); 125 | if (!$result) { 126 | throw new \Magento\Framework\Exception\LocalizedException(__('Can not download GeoLite2-Country.mmdb file.')); 127 | } 128 | 129 | $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); 130 | if ($http_code != 200) { 131 | throw new \Magento\Framework\Exception\LocalizedException(__('File download failed. Http code: %1.', $http_code) ); 132 | } 133 | 134 | curl_close($ch); 135 | 136 | $urlArray = explode('/', $url); 137 | $output_filename = $dbPath . '/' . end($urlArray); 138 | 139 | $fp = fopen($output_filename, 'w'); 140 | if (!fwrite($fp, $result)) { 141 | throw new \Magento\Framework\Exception\LocalizedException(__('Can not save or overwrite GeoLite2-Country.mmdb file.')); 142 | } 143 | fclose($fp); 144 | } 145 | 146 | return true; 147 | } 148 | 149 | /** 150 | * Get GeoIP Databse via MaxMind API 151 | * 152 | * @return bool 153 | * @throws \Magento\Framework\Exception\FileSystemException 154 | * @throws \Magento\Framework\Exception\LocalizedException 155 | */ 156 | private function updateByAPI() 157 | { 158 | $dbPath = $this->_dir->getPath('var') . '/magefan/geoip'; 159 | $this->createDir($dbPath); 160 | 161 | foreach (['GeoLite2-Country', 'GeoLite2-City'] as $file) { 162 | $url = self::URL_API . '?' . http_build_query([ 163 | 'edition_id' => $file, 164 | 'suffix' => 'tar.gz', 165 | 'license_key' => $this->config->getLicenseKey() 166 | ]); 167 | 168 | $ch = curl_init($url); 169 | 170 | $outputFilename = $dbPath . DIRECTORY_SEPARATOR . $file . '.tar.gz'; 171 | $fp = fopen($outputFilename, 'wb'); 172 | 173 | curl_setopt_array($ch, array( 174 | CURLOPT_HTTPGET => true, 175 | CURLOPT_BINARYTRANSFER => true, 176 | CURLOPT_HEADER => false, 177 | CURLOPT_FILE => $fp, 178 | )); 179 | 180 | $response = curl_exec($ch); 181 | 182 | if (!$response) { 183 | throw new \Magento\Framework\Exception\LocalizedException( 184 | __('Can not download ' . $file . '.tar.gz archive.') 185 | ); 186 | } 187 | 188 | $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); 189 | if ($http_code != 200) { 190 | throw new \Magento\Framework\Exception\LocalizedException( 191 | __('File download failed. Http code: %1. Please check the license key.', $http_code) 192 | ); 193 | } 194 | 195 | curl_close($ch); 196 | 197 | $unpackGz = $this->gz->unpack($outputFilename, $dbPath . DIRECTORY_SEPARATOR); 198 | $unpackTar = $this->tar->unpack($unpackGz, $dbPath . DIRECTORY_SEPARATOR); 199 | $dir = $this->_file->getDirectoriesList($unpackTar); 200 | $this->_file->mv($dir[0] . '/' . $file . '.mmdb', $unpackTar . $file . '.mmdb'); 201 | 202 | $this->_file->open(['path' => $unpackTar]); 203 | $list = $this->_file->ls(); 204 | $this->_file->close(); 205 | 206 | foreach ($list as $info) { 207 | if (!in_array($info['text'], ['GeoLite2-Country.mmdb', 'GeoLite2-City.mmdb'])) { 208 | if (isset($info['id'])) { 209 | $this->_file->rmdirRecursive($info['id']); 210 | } 211 | $this->_file->rm($info['text']); 212 | } 213 | } 214 | 215 | fclose($fp); 216 | } 217 | 218 | return true; 219 | } 220 | } 221 | -------------------------------------------------------------------------------- /Model/IpToCountryRepository.php: -------------------------------------------------------------------------------- 1 | remoteAddress = $remoteAddress; 81 | $this->directoryList = $directoryList; 82 | $this->moduleDir = $moduleDir; 83 | $this->config = $config; 84 | $this->request = $httpRequest; 85 | } 86 | 87 | /** 88 | * Get Country Code by IP 89 | * @param string $ip 90 | * @return mixed 91 | */ 92 | public function getCountryCode($ip) 93 | { 94 | $ip = (string)$ip; 95 | if (!$ip) { 96 | return false; 97 | } 98 | 99 | if (!isset($this->ipToCountry[$ip])) { 100 | $this->ipToCountry[$ip] = false; 101 | 102 | $simulateCountry = $this->config->getValue(self::XML_PATH_SIMULATE_COUNTRY, ScopeInterface::SCOPE_STORE) ?: ''; 103 | if ($simulateCountry) { 104 | $allowedIPs = explode(',', $this->config->getValue(self::XML_PATH_ALLOW_IPS, ScopeInterface::SCOPE_STORE) ?: ''); 105 | foreach ($allowedIPs as $allowedIp) { 106 | $allowedIp = trim($allowedIp); 107 | if ($allowedIp && $allowedIp == $ip) { 108 | $this->ipToCountry[$ip] = $simulateCountry; 109 | return $this->ipToCountry[$ip]; 110 | } 111 | } 112 | } 113 | 114 | $cloudflareEnable = $this->config->getValue(self::XML_PATH_CLOUDFLARE_ENABLED, ScopeInterface::SCOPE_STORE); 115 | if ($cloudflareEnable) { 116 | $countryCode = $this->request->getServer('HTTP_CF_IPCOUNTRY'); 117 | if ($countryCode) { 118 | $this->ipToCountry[$ip] = $countryCode; 119 | } 120 | } 121 | 122 | if (!$this->ipToCountry[$ip]) { 123 | if (function_exists('geoip_country_code_by_name')) { 124 | $rf = new \ReflectionFunction('geoip_country_code_by_name'); 125 | $params = $rf->getParameters(); 126 | if (!$params || !is_array($params) || count($params) < 2) { /* Fix for custom geoip php libraries, so 0 or 1 params */ 127 | try { 128 | $this->ipToCountry[$ip] = geoip_country_code_by_name($ip); 129 | } catch (\Exception $e) { 130 | //do nothing 131 | } 132 | } 133 | } 134 | } 135 | 136 | if (!$this->ipToCountry[$ip]) { 137 | try { 138 | $filename = $this->directoryList->getPath('var') . DIRECTORY_SEPARATOR . 'magefan/geoip/GeoLite2-Country.mmdb'; 139 | if (file_exists($filename)) { 140 | $datFile = $filename; 141 | } else { 142 | $datFile = $this->moduleDir->getDir('Magefan_GeoIp') . '/data/GeoLite2-Country.mmdb'; 143 | //throw new \Exception('No .mmdb file'); 144 | } 145 | $reader = new \GeoIp2\Database\Reader($datFile); 146 | $record = $reader->country($ip); 147 | 148 | if ($record && $record->country && $record->country->isoCode) { 149 | $this->ipToCountry[$ip] = $record->country->isoCode; 150 | } 151 | } catch (\Exception $e) {} 152 | } 153 | } 154 | 155 | return $this->ipToCountry[$ip]; 156 | } 157 | 158 | /** 159 | * Retrieve current visitor country code by IP 160 | * @return string | false 161 | */ 162 | public function getVisitorCountryCode() 163 | { 164 | return $this->getCountryCode($this->getRemoteAddress()); 165 | } 166 | 167 | /** 168 | * Retrieve current IP 169 | * @return string 170 | */ 171 | public function getRemoteAddress() 172 | { 173 | return $this->remoteAddress->getRemoteAddress(); 174 | } 175 | } 176 | -------------------------------------------------------------------------------- /Model/IpToRegionRepository.php: -------------------------------------------------------------------------------- 1 | remoteAddress = $remoteAddress; 71 | $this->directoryList = $directoryList; 72 | $this->moduleDir = $moduleDir; 73 | $this->config = $config; 74 | $this->request = $httpRequest; 75 | } 76 | 77 | /** 78 | * Get Region Code by IP 79 | * @param string $ip 80 | * @return mixed 81 | */ 82 | public function getRegionCode($ip) 83 | { 84 | $ip = (string)$ip; 85 | if (!$ip) { 86 | return ''; 87 | } 88 | 89 | if (!isset($this->ipToRegion[$ip])) { 90 | $this->ipToRegion[$ip] = ''; 91 | 92 | try { 93 | $filename = $this->directoryList->getPath('var') . DIRECTORY_SEPARATOR . 'magefan/geoip/GeoLite2-City.mmdb'; 94 | if (file_exists($filename)) { 95 | $datFile = $filename; 96 | } else { 97 | $datFile = $this->moduleDir->getDir('Magefan_GeoIp') . '/data/GeoLite2-City.mmdb'; 98 | //throw new \Exception('No .mmdb file'); 99 | } 100 | 101 | $reader = new \GeoIp2\Database\Reader($datFile); 102 | $record = $reader->city($ip); 103 | if ($record && $record->subdivisions && isset($record->subdivisions[0])) { 104 | $this->ipToRegion[$ip] = $record->subdivisions[0]->isoCode; 105 | } 106 | } catch (\Exception $e) {} 107 | } 108 | 109 | return $this->ipToRegion[$ip]; 110 | } 111 | 112 | /** 113 | * Retrieve current visitor country code by IP 114 | * @return string | false 115 | */ 116 | public function getVisitorRegionCode() 117 | { 118 | return $this->getRegionCode($this->getRemoteAddress()); 119 | } 120 | 121 | /** 122 | * Retrieve current IP 123 | * @return string 124 | */ 125 | public function getRemoteAddress() 126 | { 127 | return $this->remoteAddress->getRemoteAddress(); 128 | } 129 | } 130 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Magento 2 GeoIP Database Extension by Magefan 2 | 3 | [![Total Downloads](https://poser.pugx.org/magefan/module-geoip/downloads)](https://packagist.org/packages/magefan/module-geoip) 4 | [![Latest Stable Version](https://poser.pugx.org/magefan/module-geoip/v/stable)](https://packagist.org/packages/magefan/module-geoip) 5 | 6 | 7 | 8 | This Magento 2 GeoIP module provides you PHP methods for getting customer country by IP, without any additional plugin for PHP. 9 | 10 | It is used for [Magento 2 Currency Auto Switcher](https://magefan.com/magento-2-currency-switcher-auto-currency-by-country) and [Magento 2 Auto Language Switcher](https://magefan.com/magento-2-auto-language-switcher) by Magefan 11 | 12 | ## 🇺🇦 Stand with Ukraine! [How can you help?](https://magefan.com/blog/join-our-donations) 13 | 14 | ## Requirements 15 | * Magento Community Edition 2.0.x-2.4.x or Magento Enterprise Edition 2.0.x-2.4.x 16 | 17 | ## Installation Method 1 - Installing via composer 18 | * Open command line 19 | * Using command "cd" navigate to your magento2 root directory 20 | * Run command: composer require magefan/module-geoip 21 | ``` 22 | composer require magefan/module-geoip 23 | php bin/magento setup:upgrade 24 | php bin/magento setup:di:compile 25 | php bin/magento setup:static-content:deploy 26 | ``` 27 | 28 | 29 | ## Installation Method 2 - Installing using archive 30 | * Install GeoIP2 PHP API (https://github.com/maxmind/GeoIP2-php). 31 | * Download [ZIP Archive](https://github.com/magefan/module-geoip/archive/master.zip) 32 | * Extract files 33 | * In your Magento 2 root directory create folder app/code/Magefan/GeoIp 34 | * Copy files and folders from archive to that folder 35 | * In command line, using "cd", navigate to your Magento 2 root directory 36 | * Run commands: 37 | ``` 38 | php bin/magento setup:upgrade 39 | php bin/magento setup:di:compile 40 | php bin/magento setup:static-content:deploy 41 | ``` 42 | 43 | ## How To Use 44 | ``` 45 | protected $ipToCountryRepository; 46 | 47 | public function __construct( 48 | \Magefan\GeoIp\Model\IpToCountryRepository $ipToCountryRepository, 49 | ....//other code 50 | ) { 51 | $this->ipToCountryRepository = $ipToCountryRepository; 52 | ...//other code 53 | } 54 | 55 | public function example() { 56 | $visitorCountyCode = $this->ipToCountryRepository->getVisitorCountryCode(); 57 | $someCountryCodeByIp = $this->ipToCountryRepository->getCountryCode('104.27.164.57'); 58 | ...//other code 59 | } 60 | ``` 61 | 62 | ## Support 63 | If you have any issues, please [contact us](mailto:support@magefan.com) 64 | then if you still need help, open a bug report in GitHub's 65 | [issue tracker](https://github.com/magefan/module-geoip/issues). 66 | 67 | ## Need More Features? 68 | Please contact us to get a quote 69 | https://magefan.com/contact 70 | 71 | ## License 72 | The code is licensed under [Open Software License ("OSL") v. 3.0](http://opensource.org/licenses/osl-3.0.php). 73 | 74 | This product includes GeoLite2 data created by MaxMind, available from 75 | https://www.maxmind.com. 76 | 77 | ## Originally use these databases: 78 | https://www.maxmind.com 79 | 80 | http://software77.net/geo-ip/ 81 | 82 | ## [Magento 2 Extensions](https://magefan.com/magento-2-extensions) by Magefan 83 | 84 | ### [Magento 2 Google Extensions](https://magefan.com/magento-2-extensions/google-extensions) 85 | 86 | * [Magento 2 Google Indexing](https://magefan.com/magento-2-google-indexing-api) 87 | * [Magento 2 Google Analytics 4](https://magefan.com/magento-2-google-analytics-4) 88 | * [Magento 2 Google Tag Manager](https://magefan.com/magento-2-google-tag-manager) 89 | * [Magento 2 Google Shopping Feed](https://magefan.com/magento-2-google-shopping-feed-extension) 90 | * [Magento 2 Google Customer Reviews](https://magefan.com/magento-2-google-customer-reviews) 91 | 92 | ### Magento 2 SEO Extensions 93 | 94 | * [Magento 2 SEO Extension](https://magefan.com/magento-2-seo-extension) 95 | * [Magento 2 Rich Snippets](https://magefan.com/magento-2-rich-snippets) 96 | * [Magento 2 HTML Sitemap](https://magefan.com/magento-2-html-sitemap-extension) 97 | * [Magento 2 XML Sitemap](https://magefan.com/magento-2-xml-sitemap-extension) 98 | * [Magento 2 Facebook Open Graph](https://magefan.com/magento-2-open-graph-extension-og-tags) 99 | * [Magento 2 Twitter Cards](https://magefan.com/magento-2-twitter-cards-extension) 100 | 101 | 102 | ### [Magento 2 Speed Optimization Extensions](https://magefan.com/magento-2-extensions/speed-optimization) 103 | 104 | * [Magento 2 Google Page Speed Optimizer](https://magefan.com/magento-2-google-page-speed-optimizer) 105 | * [Magento 2 Full Page Cache Warmer](https://magefan.com/magento-2-full-page-cache-warmer) 106 | * [Magento 2 Image Lazy Load](https://magefan.com/magento-2-image-lazy-load-extension) 107 | * [Magento 2 WebP Images](https://magefan.com/magento-2-webp-optimized-images) 108 | * [Magento 2 Rocket JavaScript](https://magefan.com/rocket-javascript-deferred-javascript) 109 | 110 | ### [Magento 2 Admin Panel Extensions](https://magefan.com/magento-2-extensions/admin-extensions) 111 | 112 | * [Magento 2 Size Chart Extension](https://magefan.com/magento-2-size-chart) 113 | * [Magento 2 Security Extension](https://magefan.com/magento-2-security-extension) 114 | * [Magento 2 Admin Action Log](https://magefan.com/magento-2-admin-action-log) 115 | * [Magento 2 Order Editor](https://magefan.com/magento-2-edit-order-extension) 116 | * [Magento 2 Better Order Grid](https://magefan.com/magento-2-better-order-grid-extension) 117 | * [Magento 2 Extended Product Grid](https://magefan.com/magento-2-product-grid-inline-editor) 118 | * [Magento 2 Product Tabs](https://magefan.com/magento-2/extensions/product-tabs) 119 | * [Magento 2 Facebook Pixel](https://magefan.com/magento-2-facebook-pixel-extension) 120 | * [Magento 2 Email Attachments](https://magefan.com/magento-2-email-attachments) 121 | * [Magento 2 Admin View](https://magefan.com/magento-2-admin-view-extension) 122 | * [Magento 2 Admin Email Notifications](https://magefan.com/magento-2-admin-email-notifications) 123 | * [Magento 2 Login As Customer](https://magefan.com/login-as-customer-magento-2-extension) 124 | 125 | ### Magento 2 Blog Extensions 126 | 127 | * [Magento 2 Blog](https://magefan.com/magento2-blog-extension) 128 | * [Magento 2 Multi Blog](https://magefan.com/magento-2-multi-blog-extension) 129 | * [Magento 2 Product Widget](https://magefan.com/magento-2-product-widget) 130 | 131 | ### [Magento 2 Marketing Automation Extensions](https://magefan.com/magento-2-extensions/marketing-automation) 132 | 133 | * [Magento 2 Cookie Consent](https://magefan.com/magento-2-cookie-consent) 134 | * [Magento 2 Product Labels](https://magefan.com/magento-2-product-labels) 135 | * [Magento 2 Base Price](https://magefan.com/magento-2-base-price) 136 | * [Magento 2 Dynamic Categories](https://magefan.com/magento-2-dynamic-categories) 137 | * [Magento 2 Dynamic Blocks and Pages Extension](https://magefan.com/magento-2-cms-display-rules-extension) 138 | * [Magento 2 Automatic Related Products](https://magefan.com/magento-2-automatic-related-products) 139 | * [Magento 2 Price History](https://magefan.com/magento-2-price-history) 140 | * [Magento 2 Mautic Integration](https://magefan.com/magento-2-mautic-extension) 141 | * [Magento 2 YouTube Video](https://magefan.com/magento2-youtube-extension) 142 | 143 | ### [Magento 2 Cart Extensions](https://magefan.com/magento-2-extensions/cart-extensions) 144 | 145 | * [Magento 2 Checkout Extension](https://magefan.com/better-magento-2-checkout-extension) 146 | * [Magento 2 Coupon Code](https://magefan.com/magento-2-coupon-code-link) 147 | * [Magento 2 Guest to Customer](https://magefan.com/magento2-convert-guest-to-customer) 148 | 149 | ### [Magento 2 Multi-Language Extensions](https://magefan.com/magento-2-extensions/multi-language-extensions) 150 | 151 | * [Magento 2 Hreflang Tags](https://magefan.com/magento2-alternate-hreflang-extension) 152 | * [Magento 2 Auto Currency Switcher](https://magefan.com/magento-2-currency-switcher-auto-currency-by-country) 153 | * [Magento 2 Auto Language Switcher](https://magefan.com/magento-2-auto-language-switcher) 154 | * [Magento 2 GeoIP Store Switcher](https://magefan.com/magento-2-geoip-switcher-extension) 155 | * [Magento 2 Translation](https://magefan.com/magento-2-translation-extension) 156 | 157 | ### [Developers Tools](https://magefan.com/magento-2-extensions/developer-tools) 158 | 159 | * [Magento 2 Zero Downtime Deployment](https://magefan.com/blog/magento-2-zero-downtime-deployment) 160 | * [Magento 2 Cron Schedule](https://magefan.com/magento-2-cron-schedule) 161 | * [Magento 2 CLI Extension](https://magefan.com/magento2-cli-extension) 162 | * [Magento 2 Conflict Detector](https://magefan.com/magento2-conflict-detector) 163 | 164 | ## [Shopify Apps](https://magefan.com/shopify/apps) by Magefan 165 | 166 | * [Shopify Login As Customer](https://apps.shopify.com/login-as-customer) 167 | * [Shopify Blog](https://apps.shopify.com/magefan-blog) 168 | * [Shopify Size Chart](https://magefan.com/shopify/apps/size-chart) 169 | * [Shopify Google Indexer](https://magefan.com/shopify/apps/google-indexing) 170 | * [Shopify Product Feeds](https://magefan.com/shopify/apps/product-feed) 171 | -------------------------------------------------------------------------------- /Setup/Patch/Data/DropTable.php: -------------------------------------------------------------------------------- 1 | moduleDataSetup = $moduleDataSetup; 31 | } 32 | 33 | public static function getDependencies() 34 | { 35 | return []; 36 | } 37 | 38 | public function getAliases() 39 | { 40 | return []; 41 | } 42 | 43 | public function apply() 44 | { 45 | $this->moduleDataSetup->startSetup(); 46 | $setup = $this->moduleDataSetup; 47 | $connection = $setup->getConnection(); 48 | 49 | $table = $connection->getTableName( 'magefan_geoip_country' ); 50 | if ($connection->isTableExists($table)) { 51 | $connection->dropTable($table); 52 | } 53 | 54 | $this->moduleDataSetup->endSetup(); 55 | } 56 | 57 | public static function getVersion() 58 | { 59 | return '2.2.0'; 60 | } 61 | } -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "magefan/module-geoip", 3 | "description": "Allows to get country code by IP", 4 | "require": { 5 | "magefan/module-community" : ">=2.2.10", 6 | "geoip2/geoip2": "^2.9.0" 7 | }, 8 | "suggest": { 9 | "magefan/module-auto-currency-switcher": "Install GeoIP Auto Currency Switcher Extension for Magento 2 (https://magefan.com/magento-2-currency-switcher-auto-currency-by-country). Use coupon code COMPOSER-FAN to get a 10% discount on magefan.com.", 10 | "magefan/module-auto-language-switcher": "Install GeoIP Auto Language/Store Switcher Extension for Magento 2 (https://magefan.com/magento-2-auto-language-switcher). Use coupon code COMPOSER-FAN to get a 10% discount on magefan.com." 11 | }, 12 | "type": "magento2-module", 13 | "version": "2.3.2", 14 | "autoload": { 15 | "psr-4": { 16 | "Magefan\\GeoIp\\": "" 17 | }, 18 | "files": [ 19 | "registration.php" 20 | ] 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /data/GeoLite2-City.mmdb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/magefan/module-geoip/833a1ef554c227ba64b8f01f57dc2326dd89445b/data/GeoLite2-City.mmdb -------------------------------------------------------------------------------- /data/GeoLite2-Country.mmdb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/magefan/module-geoip/833a1ef554c227ba64b8f01f57dc2326dd89445b/data/GeoLite2-Country.mmdb -------------------------------------------------------------------------------- /etc/acl.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /etc/adminhtml/routes.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /etc/adminhtml/system.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 10 | 11 | 12 | 13 | 14 |
15 | separator-top 16 | 17 | magefan 18 | Magefan_GeoIp::geo_ip 19 | 20 | 21 | 1 22 | 23 | Magefan\GeoIp\Block\Adminhtml\System\Config\Form\Info 24 | 25 | 26 | Magefan\GeoIp\Block\Adminhtml\System\Config\Form\IpInfo 27 | 28 | 29 | 30 | 31 | 32 | 1 33 | 34 | Magefan\GeoIp\Block\Adminhtml\System\Config\Form\MaxMindInfo 35 | 36 | 37 | 38 | MaxMind License Key and save config to update the MaxMind GeoIP Database directly from MaxMind and not via the Magefan server. 40 | ]]> 41 | 42 | 43 | 44 | Magefan\GeoIp\Block\Adminhtml\System\Config\Form\Button 45 | 46 | 47 | 48 | 49 | 1 50 | 51 | Magefan\GeoIp\Block\Adminhtml\System\Config\Form\CloudflareCheck 52 | 53 | 54 | 55 | Magento\Config\Model\Config\Source\Yesno 56 | Attention! This option will be ignored as you do not use Cloudflare for the website or IP Geolocation is disabled in your Cloudflare account. 58 |
59 | Note that without this option GeoLocation detection also works properly. 60 | ]]> 61 |
62 |
63 |
64 | 65 | 66 | 67 | 1 68 | 69 | 70 | 71 | 72 | 73 | Magento\Directory\Model\Config\Source\Country 74 | 77 | 78 | 79 | 80 |
81 |
82 |
83 | -------------------------------------------------------------------------------- /etc/config.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 10 | 11 | 12 | 13 | 1 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /etc/crontab.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 10 | 11 | 0 3 * * * 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /etc/di.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /etc/module.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /registration.php: -------------------------------------------------------------------------------- 1 | 7 | 8 |
9 | 12 |
13 | --------------------------------------------------------------------------------