diff --git a/.gitattributes b/.gitattributes deleted file mode 100644 index 412eeda..0000000 --- a/.gitattributes +++ /dev/null @@ -1,22 +0,0 @@ -# Auto detect text files and perform LF normalization -* text=auto - -# Custom for Visual Studio -*.cs diff=csharp -*.sln merge=union -*.csproj merge=union -*.vbproj merge=union -*.fsproj merge=union -*.dbproj merge=union - -# Standard to msysgit -*.doc diff=astextplain -*.DOC diff=astextplain -*.docx diff=astextplain -*.DOCX diff=astextplain -*.dot diff=astextplain -*.DOT diff=astextplain -*.pdf diff=astextplain -*.PDF diff=astextplain -*.rtf diff=astextplain -*.RTF diff=astextplain diff --git a/.gitignore b/.gitignore deleted file mode 100644 index 5ebd21a..0000000 --- a/.gitignore +++ /dev/null @@ -1,163 +0,0 @@ -################# -## Eclipse -################# - -*.pydevproject -.project -.metadata -bin/ -tmp/ -*.tmp -*.bak -*.swp -*~.nib -local.properties -.classpath -.settings/ -.loadpath - -# External tool builders -.externalToolBuilders/ - -# Locally stored "Eclipse launch configurations" -*.launch - -# CDT-specific -.cproject - -# PDT-specific -.buildpath - - -################# -## Visual Studio -################# - -## Ignore Visual Studio temporary files, build results, and -## files generated by popular Visual Studio add-ons. - -# User-specific files -*.suo -*.user -*.sln.docstates - -# Build results -[Dd]ebug/ -[Rr]elease/ -*_i.c -*_p.c -*.ilk -*.meta -*.obj -*.pch -*.pdb -*.pgc -*.pgd -*.rsp -*.sbr -*.tlb -*.tli -*.tlh -*.tmp -*.vspscc -.builds -*.dotCover - -## TODO: If you have NuGet Package Restore enabled, uncomment this -#packages/ - -# Visual C++ cache files -ipch/ -*.aps -*.ncb -*.opensdf -*.sdf - -# Visual Studio profiler -*.psess -*.vsp - -# ReSharper is a .NET coding add-in -_ReSharper* - -# Installshield output folder -[Ee]xpress - -# DocProject is a documentation generator add-in -DocProject/buildhelp/ -DocProject/Help/*.HxT -DocProject/Help/*.HxC -DocProject/Help/*.hhc -DocProject/Help/*.hhk -DocProject/Help/*.hhp -DocProject/Help/Html2 -DocProject/Help/html - -# Click-Once directory -publish - -# Others -[Bb]in -[Oo]bj -sql -TestResults -*.Cache -ClientBin -stylecop.* -~$* -*.dbmdl -Generated_Code #added for RIA/Silverlight projects - -# Backup & report files from converting an old project file to a newer -# Visual Studio version. Backup files are not needed, because we have git ;-) -_UpgradeReport_Files/ -Backup*/ -UpgradeLog*.XML - - - -############ -## Windows -############ - -# Windows image file caches -Thumbs.db - -# Folder config file -Desktop.ini - - -############# -## Python -############# - -*.py[co] - -# Packages -*.egg -*.egg-info -dist -build -eggs -parts -bin -var -sdist -develop-eggs -.installed.cfg - -# Installer logs -pip-log.txt - -# Unit test / coverage reports -.coverage -.tox - -#Translations -*.mo - -#Mr Developer -.mr.developer.cfg - -# Mac crap -.DS_Store diff --git a/ChangeLog b/ChangeLog deleted file mode 100644 index a507867..0000000 --- a/ChangeLog +++ /dev/null @@ -1,185 +0,0 @@ -Revision History for PHP Module for IP2Location - -Please refer https://github.com/chrislim2888/IP2Location-PHP-Module/releases to future updates. - -8.2.1 Tue Mar 24 17:29:00 2020 - * Fixes - - - Fixed getCidr() function to return an array of subnet. - -8.2.0 Thu Mar 19 10:16:00 2020 - * Fixes - - - Added IP2Location web service lookup. - -8.1.1 Wed Oct 09 08:58:00 2019 - * Fixes - - - Reduce file I/O to improve query performance. - -8.1.0 Mon Sep 30 08:58:00 2019 - * Fixes - - - Optimized library performance. - -8.0.2 Sun Oct 1 10:01:00 2016 - * Fixes - - - Issue of shift operator for big number in php - -8.0.1 Tue Aug 1 11:00:00 2016 - * Fixes - - - Support 2 new interfaces: getDatabaseVersion and getModuleVersion - -8.0.0 Tue Jul 5 10:00:00 2016 - * Fixes - - - Add code to lookup for index section which available in new BIN format - -7.2.5 Fri Jun 10 15:40:23 2016 - * Fixes: - - - Fix the IP lookup issue for DB24 - -7.2.4 Wed Jan 06 14:44:23 2016 - * Fixes: - - - Fixed IPv6 lookup issue. - -7.2.3 Wed Aug 12 10:29:37 2015 - * Fixes: - - - Fix IPv4 lookup issue. - -7.2.2 Thu Jul 30 10:27:55 2015 - * Fixes: - - - Defended against 32 bit overflow in a couple more places. - - Added checks for default / unset / infinite memory limits. - - Fixed lookup function, in order for it to consistently return the correct datatype. - - - * Enhancements: - - - Cached the result of the memory limit calculation in order not to recheck it for each instantiation. - - - * Additions: - - - Added exception code constants to ease the handling of exceptional conditions in the client. - - Added the ability to set default returned fields on construction, in order not to have to pass them around constantly. - - -7.2.0 Wed Jul 29 14:07:23 2015 - **Special thanks to Mariano (mariano.perez.rodriguez [at] gmail.com) for working on this release** - - * Removals: - - - Removed IP2LocationRecord class, it served little purpose and an array response would be much more flexible (see below). - - Removed everything to do with endianness (there was some leftover code and constants). - - Removed IP version constants, they were unused. - - Removed the SHM_KEY constant in favor of a dynamic shared memory key calculation. - - Removed "$database" property in favor of a set of IP-version-directed metadata properties. - - Removed useless caching of lookup results in "$result" property. - - Removed closing PHP tag. - - - * Fixes: - - - Fixed possible overruns of the binary file by only reading as much as needed and not more. - - Fixed IPv6 lookup (it was never going to work: you were trying to compare a number to a BCMath string). - - Fixed binary search midpoint calculation. - - Fixed shared memory permissions so as not to leak information to other users / groups. - - Gave a unique number to each numeric class constant to prevent accidental misuse. - - - * Enhancements: - - - Automatically determine float size (this is not optimal, but as good as we're going to get). - - Removed "magic numbers" as much as possible and factored them out to class constants. - - IP address, version, and number are now selectable fields. - - The "$columns" array has been made static, no need for a copy for each possible instance. - - The "$columns" array has been reindexed with integer keys to avoid double lookup during binary search. - - The "$columns" array has had its entries multiplied by 4, in order to avoid repeatedly multiplying by 4 every time its values were going to be used. - - The memory buffer has been made static (this way, if two instances are created they can share the buffer instead of using up twice as much memory for the same data). - - Internal variable handling has been simplified with a single "$resource" property whose meaning changes as the caching method changes. - - The class constructor will now accept an empty filename, in this case, it will look for the most general database BIN in the file's directory and load that. - - Quadwords and IPv6 addresses are now parsed by a simple and highly portable routine. - - Low level reading abstracting away from the caching method has been implemented as a private method (this simplifies the low-level reading functions tremendously). - - Strings are now read by providing just a pointer to the word value describing its start: the length is automatically retrieved and only the necessary bytes are read (preventing overrun errors). - - Low level read routines have been greatly simplified. - - High level read routines have been added, specifically, those providing related fields have been grouped together. - - Binary search has been decoupled from field lookup (cleaning up the implementation). - - Binary search will now work correctly with IPv6 addresses. - - - * Additions: - - - Added "FIELD_NOT_KNOWN" to manage unknown field requests. - - Added "multiple" fields (eg. "COORDINATES" in order to get latitude and longitude at the same time). - - Added the "Ip2Location" namespace, and changed the class' name to "Database", so we now have "Ip2Location\Database", accordingly, the filename has been changed to "Database.php", this should be put in a directory named "Ip2Location" in order to comply with PSR-0 / PSR-4. - - A destructor has been added to properly detach from shared memory / close opened files. - - A static method has been added to tear down the shared memory segments created by the class (otherwise, it's a pain to delete them). - - Added a "getDate()" method, this will provide the database's compilation date as YYYY-MM-DD. - - Added a "getType()" method, returning the database type (1--24). - - Added a "getFields()" method, returning the supported fields. - - Rewrote the "lookup()" method: it now accepts either a field name (which could be a MULTIPLE field), or an array of field names, and it will return either a single field value (if a single field given), or an array (possibly named) of values found. - - -7.1.0 Thu Jul 23 15:15:36 2015 - Removed dependency php_gmp - Fixed shared memory issues - Fixed binary read functions - Restructure lookup algorithm - -7.0.0 Wed Aug 13 12:41:16 2014 - Added support to IP2Location IPv6 DB2-DB24 - -6.00 Wed May 08 08:43:22 2013 - Added support to IP2Location DB21-24 - Added new lookup method MEMORY_CACHE, and SHARED_MEMORY - New structure to use IP2Location class - -5.00 Fri Jan 14 09:59:15 2011 - Added support to IP2Location DB19-20 - Added new public function "getMcc" - Added new public function "getMnc" - Added new public function "getMobileBrand" - -4.00 Thu Oct 01 13:09:43 2009 - Merged all functions into one class - Changed functions name - -3.00 Wed Aug 13 10:00:00 2008 - Added support to IP2Location DB15-18 - Added new public function "IP2Location_get_idd_code" - Added new public function "IP2Location_get_area_code" - Added new public function "IP2Location_get_weather_code" - Added new public function "IP2Location_get_weather_name" - -2.20 Tue Sep 25 00:00:00 2007 - Support PHP4 and PHP5 - -2.10 Fri Oct 20 00:00:00 2006 - Support IP2Location DB11, DB12, DB13 & DB14 - -2.00 Fri Oct 20 00:00:00 2006 - Support IP2Location IPv6 - -1.30 Wed Nov 23 16:59:58 2005 - Minor Bug Fix - -1.20 Thu Nov 17 16:59:58 2005 - Minor Bug Fix - -1.10 Thu Oct 27 16:59:58 2005 - Support Big Endian Machines - -1.00 Thu Oct 13 16:59:58 2005 - First release for PHP 4.0 and above - Added new public function "IP2Location_open" - Added new public function "IP2Location_close" - Added new public function "IP2Location_get_all" - Added new public structure "IP2Location" - Added new public structure "IP2LocationRecord" diff --git a/IP2Location.php b/IP2Location.php index 2c0a1d3..dd4a6c1 100644 --- a/IP2Location.php +++ b/IP2Location.php @@ -31,7 +31,7 @@ class Database * * @var string */ - const VERSION = '8.2.3'; + public const VERSION = '8.3.0'; ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Error field constants /////////////////////////////////////////////////////////////////////////////////////////////////////////////// @@ -42,21 +42,21 @@ class Database * * @var string */ - const FIELD_NOT_SUPPORTED = 'This parameter is unavailable in selected .BIN data file. Please upgrade.'; + public const FIELD_NOT_SUPPORTED = 'This parameter is unavailable in selected .BIN data file. Please upgrade.'; /** * Unknown field message. * * @var string */ - const FIELD_NOT_KNOWN = 'This parameter is inexistent. Please verify.'; + public const FIELD_NOT_KNOWN = 'This parameter is inexistent. Please verify.'; /** * Invalid IP address message. * * @var string */ - const INVALID_IP_ADDRESS = 'Invalid IP address.'; + public const INVALID_IP_ADDRESS = 'Invalid IP address.'; ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Field selection constants /////////////////////////////////////////////////////////////////////////////////////////////////////////// @@ -67,203 +67,203 @@ class Database * * @var int */ - const COUNTRY_CODE = 1; + public const COUNTRY_CODE = 1; /** * Country name. * * @var int */ - const COUNTRY_NAME = 2; + public const COUNTRY_NAME = 2; /** * Region name. * * @var int */ - const REGION_NAME = 3; + public const REGION_NAME = 3; /** * City name. * * @var int */ - const CITY_NAME = 4; + public const CITY_NAME = 4; /** * Latitude. * * @var int */ - const LATITUDE = 5; + public const LATITUDE = 5; /** * Longitude. * * @var int */ - const LONGITUDE = 6; + public const LONGITUDE = 6; /** * ISP name. * * @var int */ - const ISP = 7; + public const ISP = 7; /** * Domain name. * * @var int */ - const DOMAIN_NAME = 8; + public const DOMAIN_NAME = 8; /** * Zip code. * * @var int */ - const ZIP_CODE = 9; + public const ZIP_CODE = 9; /** * Time zone. * * @var int */ - const TIME_ZONE = 10; + public const TIME_ZONE = 10; /** * Net speed. * * @var int */ - const NET_SPEED = 11; + public const NET_SPEED = 11; /** * IDD code. * * @var int */ - const IDD_CODE = 12; + public const IDD_CODE = 12; /** * Area code. * * @var int */ - const AREA_CODE = 13; + public const AREA_CODE = 13; /** * Weather station code. * * @var int */ - const WEATHER_STATION_CODE = 14; + public const WEATHER_STATION_CODE = 14; /** * Weather station name. * * @var int */ - const WEATHER_STATION_NAME = 15; + public const WEATHER_STATION_NAME = 15; /** * Mobile Country Code. * * @var int */ - const MCC = 16; + public const MCC = 16; /** * Mobile Network Code. * * @var int */ - const MNC = 17; + public const MNC = 17; /** * Mobile carrier name. * * @var int */ - const MOBILE_CARRIER_NAME = 18; + public const MOBILE_CARRIER_NAME = 18; /** * Elevation. * * @var int */ - const ELEVATION = 19; + public const ELEVATION = 19; /** * Usage type. * * @var int */ - const USAGE_TYPE = 20; + public const USAGE_TYPE = 20; /** * Country name and code. * * @var int */ - const COUNTRY = 101; + public const COUNTRY = 101; /** * Latitude and Longitude. * * @var int */ - const COORDINATES = 102; + public const COORDINATES = 102; /** * IDD and area codes. * * @var int */ - const IDD_AREA = 103; + public const IDD_AREA = 103; /** * Weather station name and code. * * @var int */ - const WEATHER_STATION = 104; + public const WEATHER_STATION = 104; /** * MCC, MNC, and mobile carrier name. * * @var int */ - const MCC_MNC_MOBILE_CARRIER_NAME = 105; + public const MCC_MNC_MOBILE_CARRIER_NAME = 105; /** * All fields at once. * * @var int */ - const ALL = 1001; + public const ALL = 1001; /** * Include the IP address of the looked up IP address. * * @var int */ - const IP_ADDRESS = 1002; + public const IP_ADDRESS = 1002; /** * Include the IP version of the looked up IP address. * * @var int */ - const IP_VERSION = 1003; + public const IP_VERSION = 1003; /** * Include the IP number of the looked up IP address. * * @var int */ - const IP_NUMBER = 1004; + public const IP_NUMBER = 1004; ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Exception code constants //////////////////////////////////////////////////////////////////////////////////////////////////////////// @@ -274,70 +274,70 @@ class Database * * @var int */ - const EXCEPTION = 10000; + public const EXCEPTION = 10000; /** * No shmop extension found. * * @var int */ - const EXCEPTION_NO_SHMOP = 10001; + public const EXCEPTION_NO_SHMOP = 10001; /** * Failed to open shmop memory segment for reading. * * @var int */ - const EXCEPTION_SHMOP_READING_FAILED = 10002; + public const EXCEPTION_SHMOP_READING_FAILED = 10002; /** * Failed to open shmop memory segment for writing. * * @var int */ - const EXCEPTION_SHMOP_WRITING_FAILED = 10003; + public const EXCEPTION_SHMOP_WRITING_FAILED = 10003; /** * Failed to create shmop memory segment. * * @var int */ - const EXCEPTION_SHMOP_CREATE_FAILED = 10004; + public const EXCEPTION_SHMOP_CREATE_FAILED = 10004; /** * The specified database file was not found. * * @var int */ - const EXCEPTION_DBFILE_NOT_FOUND = 10005; + public const EXCEPTION_DBFILE_NOT_FOUND = 10005; /** * Not enough memory to load database file. * * @var int */ - const EXCEPTION_NO_MEMORY = 10006; + public const EXCEPTION_NO_MEMORY = 10006; /** * No candidate databse files found. * * @var int */ - const EXCEPTION_NO_CANDIDATES = 10007; + public const EXCEPTION_NO_CANDIDATES = 10007; /** * Failed to open database file. * * @var int */ - const EXCEPTION_FILE_OPEN_FAILED = 10008; + public const EXCEPTION_FILE_OPEN_FAILED = 10008; /** * Failed to determine the current path. * * @var int */ - const EXCEPTION_NO_PATH = 10009; + public const EXCEPTION_NO_PATH = 10009; ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Caching method constants //////////////////////////////////////////////////////////////////////////////////////////////////////////// @@ -348,21 +348,21 @@ class Database * * @var int */ - const FILE_IO = 100001; + public const FILE_IO = 100001; /** * Read the whole database into a variable for caching. * * @var int */ - const MEMORY_CACHE = 100002; + public const MEMORY_CACHE = 100002; /** * Use shared memory objects for caching. * * @var int */ - const SHARED_MEMORY = 100003; + public const SHARED_MEMORY = 100003; ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Shared memory constants ///////////////////////////////////////////////////////////////////////////////////////////////////////////// @@ -373,14 +373,14 @@ class Database * * @var int */ - const SHM_PERMS = 0600; + public const SHM_PERMS = 0600; /** * Number of bytes to read/write at a time in order to load the shared memory cache (512k). * * @var int */ - const SHM_CHUNK_SIZE = 524288; + public const SHM_CHUNK_SIZE = 524288; ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Static data ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @@ -1268,7 +1268,7 @@ public function getCidr($ip) list($ipFrom, $ipTo) = $records; - $ipTo -= 1; + --$ipTo; while ($ipTo >= $ipFrom) { $maxSize = self::getMaxSize($ipFrom, 32); @@ -2130,21 +2130,21 @@ class WebService * * @var int */ - const EXCEPTION_NO_CURL = 10001; + public const EXCEPTION_NO_CURL = 10001; /** * Invalid API key format. * * @var int */ - const EXCEPTION_INVALID_API_KEY = 10002; + public const EXCEPTION_INVALID_API_KEY = 10002; /** * Web service error. * * @var int */ - const EXCEPTION_WEB_SERVICE_ERROR = 10003; + public const EXCEPTION_WEB_SERVICE_ERROR = 10003; /** * Constructor. @@ -2155,7 +2155,7 @@ class WebService * * @throws \Exception */ - public function __construct($apiKey, $package = 'WS1', $useSsl = true) + public function __construct($apiKey, $package = 'WS1', $useSsl = false) { if (!\extension_loaded('curl')) { throw new \Exception(__CLASS__ . ": Please make sure your PHP setup has the 'curl' extension enabled.", self::EXCEPTION_NO_CURL); @@ -2187,7 +2187,7 @@ public function __construct($apiKey, $package = 'WS1', $useSsl = true) */ public function lookup($ip, $addOns = [], $language = 'en') { - $response = $this->httpRequest('http' . (($this->useSsl) ? 's' : '') . '://api.ip2location.com/v2/?' . http_build_query([ + $response = $this->httpRequest('http://api.ip2location.com/v2/?' . http_build_query([ 'key' => $this->apiKey, 'ip' => $ip, 'package' => $this->package, @@ -2213,7 +2213,7 @@ public function lookup($ip, $addOns = [], $language = 'en') */ public function getCredit() { - $response = $this->httpRequest('http' . (($this->useSsl) ? 's' : '') . '://api.ip2location.com/v2/?' . http_build_query([ + $response = $this->httpRequest('http://api.ip2location.com/v2/?' . http_build_query([ 'key' => $this->apiKey, 'check' => true, ])); @@ -2259,3 +2259,63 @@ private function httpRequest($url) return false; } } + +/** + * IpTools class. + */ +class IpTools +{ + public function isIpv4($ip) + { + return (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) ? true : false; + } + + public function isIpv6($ip) + { + return (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) ? true : false; + } + + public function ipv4ToDecimal($ip) + { + if (!$this->isIpv4($ip)) { + return; + } + + return sprintf('%u', ip2long($ip)); + } + + public function ipv6ToDecimal($ipv6) + { + if (!$this->isIpv6($ipv6)) { + return; + } + + return (string) gmp_import(inet_pton($ipv6)); + } + + public function decimalToIpv4($number) + { + if (!preg_match('/^\d+$/', $number)) { + return; + } + + if ($number > 4294967295) { + return; + } + + return long2ip($number); + } + + public function decimalToIpv6($number) + { + if (!preg_match('/^\d+$/', $number)) { + return; + } + + if ($number <= 4294967295) { + return; + } + + return inet_ntop(str_pad(gmp_export($number), 16, "\0", STR_PAD_LEFT)); + } +} diff --git a/README.md b/README.md index 68905dc..7005de1 100644 --- a/README.md +++ b/README.md @@ -48,22 +48,35 @@ Below is the description of the functions available in the **Database** class. | Function Name | Description | |---|---| |Constructor|Expect 2 input parameters:
  1. Full path of IP2Location BIN data file.
  2. File Open Mode
For SHARED_MEMORY and MEMORY_CACHE, it will require your server to have sufficient memory to hold the BIN data, otherwise it will raise the errors during the object initialization.| -|getDate|Return the database's compilation date as a string of the form 'YYYY-MM-DD'| -|getType|Return the database's type, 1 to 24 respectively for DB1 to DB24. Please visit https://www.ip2location.com/databases for details.| -|getModuleVersion|Return the version of module| -|getDatabaseVersion|Return the version of database| -|lookup|Return the IP information in array. Below is the information returned:You can visit [IP2Location](https://www.ip2location.com/databases/db24-ip-country-region-city-latitude-longitude-zipcode-timezone-isp-domain-netspeed-areacode-weather-mobile-elevation-usagetype) for the description of each field. Note: although the above names are not exactly matched with the names given in this link, but they are self-described.| -|getCidr|Return an array of the complete IP list in CIDR format of the detected row record based on the given IP address.| +|**string** getDate()|Return the database's compilation date as a string of the form 'YYYY-MM-DD'| +|**string** getType()|Return the database's type, 1 to 24 respectively for DB1 to DB24. Please visit https://www.ip2location.com/databases for details.| +|**string** getModuleVersion()|Return the version of module| +|**string** getDatabaseVersion()|Return the version of database| +|**array** lookup($ip)|Return the IP information in array. Below is the information returned:You can visit [IP2Location](https://www.ip2location.com/databases/db24-ip-country-region-city-latitude-longitude-zipcode-timezone-isp-domain-netspeed-areacode-weather-mobile-elevation-usagetype) for the description of each field. Note: although the above names are not exactly matched with the names given in this link, but they are self-described.| +|**array** getCidr($ip)|Return an array of the complete IP list in CIDR format of the detected row record based on the given IP address.| ### WebService Class Below is the description of the functions available in the **WebService** class. -| Function Name | Description | -| ------------- | ------------------------------------------------------------ | -| Constructor | Expect 3 input parameters:
  1. IP2Location API Key.
  2. Package (WS1 - WS24)
  3. Use HTTPS or HTTP
| -| lookup | Return the IP information in array.