PageRenderTime 54ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/pear/Net/GeoIP.php

https://bitbucket.org/synergylearning/campusconnect
PHP | 904 lines | 637 code | 29 blank | 238 comment | 50 complexity | cd2bbe4acb243000693ade95e9094974 MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception, LGPL-3.0, GPL-3.0, LGPL-2.1, Apache-2.0, BSD-3-Clause, AGPL-3.0
  1. <?php
  2. /**
  3. * +----------------------------------------------------------------------+
  4. * | PHP version 5 |
  5. * +----------------------------------------------------------------------+
  6. * | Copyright (C) 2004 MaxMind LLC |
  7. * +----------------------------------------------------------------------+
  8. * | This library is free software; you can redistribute it and/or |
  9. * | modify it under the terms of the GNU Lesser General Public |
  10. * | License as published by the Free Software Foundation; either |
  11. * | version 2.1 of the License, or (at your option) any later version. |
  12. * | |
  13. * | This library is distributed in the hope that it will be useful, |
  14. * | but WITHOUT ANY WARRANTY; without even the implied warranty of |
  15. * | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
  16. * | Lesser General Public License for more details. |
  17. * | |
  18. * | You should have received a copy of the GNU Lesser General Public |
  19. * | License along with this library; if not, write to the Free Software |
  20. * | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 |
  21. * | USA, or view it online at http://www.gnu.org/licenses/lgpl.txt. |
  22. * +----------------------------------------------------------------------+
  23. * | Authors: Jim Winstead <jimw@apache.org> (original Maxmind version) |
  24. * | Hans Lellelid <hans@xmpl.org> |
  25. * +----------------------------------------------------------------------+
  26. *
  27. * @category Net
  28. * @package Net_GeoIP
  29. * @author Jim Winstead <jimw@apache.org> (original Maxmind PHP API)
  30. * @author Hans Lellelid <hans@xmpl.org>
  31. * @license LGPL http://www.gnu.org/licenses/lgpl.txt
  32. * @link http://pear.php.net/package/Net_GeoIp
  33. * $Id$
  34. */
  35. require_once 'PEAR/Exception.php';
  36. /**
  37. * GeoIP class provides an API for performing geo-location lookups based on IP
  38. * address.
  39. *
  40. * To use this class you must have a [binary version] GeoIP database. There is
  41. * a free GeoIP country database which can be obtained from Maxmind:
  42. * {@link http://www.maxmind.com/app/geoip_country}
  43. *
  44. *
  45. * <b>SIMPLE USE</b>
  46. *
  47. *
  48. * Create an instance:
  49. *
  50. * <code>
  51. * $geoip = Net_GeoIP::getInstance('/path/to/geoipdb.dat', Net_GeoIP::SHARED_MEMORY);
  52. * </code>
  53. *
  54. * Depending on which database you are using (free, or one of paid versions)
  55. * you must use appropriate lookup method:
  56. *
  57. * <code>
  58. * // for free country db:
  59. * $country_name = $geoip->lookupCountryName($_SERVER['REMOTE_ADDR']);
  60. * $country_code = $geoip->lookupCountryCode($_SERVER['REMOTE_ADDR']);
  61. *
  62. * // for [non-free] region db:
  63. * list($ctry_code, $region) = $geoip->lookupRegion($_SERVER['REMOTE_ADDR']);
  64. *
  65. * // for [non-free] city db:
  66. * $location = $geoip->lookupLocation($_SERVER['REMOTE_ADDR']);
  67. * print "city: " . $location->city . ", " . $location->region;
  68. * print "lat: " . $location->latitude . ", long: " . $location->longitude;
  69. *
  70. * // for organization or ISP db:
  71. * $org_or_isp_name = $geoip->lookupOrg($_SERVER['REMOTE_ADDR']);
  72. * </code>
  73. *
  74. *
  75. * <b>MULTIPLE INSTANCES</b>
  76. *
  77. *
  78. * You can have several instances of this class, one for each database file
  79. * you are using. You should use the static getInstance() singleton method
  80. * to save on overhead of setting up database segments. Note that only one
  81. * instance is stored per filename, and any flags will be ignored if an
  82. * instance already exists for the specifiedfilename.
  83. *
  84. * <b>Special note on using SHARED_MEMORY flag</b>
  85. *
  86. * If you are using SHARED_MEMORY (shmop) you can only use SHARED_MEMORY for
  87. * one (1) instance (i.e. for one database). Any subsequent attempts to
  88. * instantiate using SHARED_MEMORY will read the same shared memory block
  89. * already initialized, and therefore will cause problems since the expected
  90. * database format won't match the database in the shared memory block.
  91. *
  92. * Note that there is no easy way to flag "nice errors" to prevent attempts
  93. * to create new instances using SHARED_MEMORY flag and it is also not posible
  94. * (in a safe way) to allow new instances to overwrite the shared memory block.
  95. *
  96. * In short, is you are using multiple databses, use the SHARED_MEMORY flag
  97. * with care.
  98. *
  99. *
  100. * <b>LOOKUPS ON HOSTNAMES</b>
  101. *
  102. *
  103. * Note that this PHP API does NOT support lookups on hostnames. This is so
  104. * that the public API can be kept simple and so that the lookup functions
  105. * don't need to try name lookups if IP lookup fails (which would be the only
  106. * way to keep the API simple and support name-based lookups).
  107. *
  108. * If you do not know the IP address, you can convert an name to IP very
  109. * simply using PHP native functions or other libraries:
  110. *
  111. * <code>
  112. * $geoip->lookupCountryName(gethostbyname('www.sunset.se'));
  113. * </code>
  114. *
  115. * Or, if you don't know whether an address is a name or ip address, use
  116. * application-level logic:
  117. *
  118. * <code>
  119. * if (ip2long($ip_or_name) === false) {
  120. * $ip = gethostbyname($ip_or_name);
  121. * } else {
  122. * $ip = $ip_or_name;
  123. * }
  124. * $ctry = $geoip->lookupCountryName($ip);
  125. * </code>
  126. *
  127. * @category Net
  128. * @package Net_GeoIP
  129. * @author Jim Winstead <jimw@apache.org> (original Maxmind PHP API)
  130. * @author Hans Lellelid <hans@xmpl.org>
  131. * @license LGPL http://www.gnu.org/licenses/lgpl.txt
  132. * @link http://pear.php.net/package/Net_GeoIp
  133. */
  134. class Net_GeoIP
  135. {
  136. /**
  137. * Exception error code used for invalid IP address.
  138. */
  139. const ERR_INVALID_IP = 218624992; // crc32('Net_GeoIP::ERR_INVALID_IP')
  140. /**
  141. * Exception error code when there is a DB-format-related error.
  142. */
  143. const ERR_DB_FORMAT = 866184008; // crc32('Net_GeoIP::ERR_DB_FORMAT')
  144. public static $COUNTRY_CODES = array(
  145. "", "AP", "EU", "AD", "AE", "AF", "AG", "AI", "AL", "AM", "AN", "AO", "AQ",
  146. "AR", "AS", "AT", "AU", "AW", "AZ", "BA", "BB", "BD", "BE", "BF", "BG", "BH",
  147. "BI", "BJ", "BM", "BN", "BO", "BR", "BS", "BT", "BV", "BW", "BY", "BZ", "CA",
  148. "CC", "CD", "CF", "CG", "CH", "CI", "CK", "CL", "CM", "CN", "CO", "CR", "CU",
  149. "CV", "CX", "CY", "CZ", "DE", "DJ", "DK", "DM", "DO", "DZ", "EC", "EE", "EG",
  150. "EH", "ER", "ES", "ET", "FI", "FJ", "FK", "FM", "FO", "FR", "FX", "GA", "GB",
  151. "GD", "GE", "GF", "GH", "GI", "GL", "GM", "GN", "GP", "GQ", "GR", "GS", "GT",
  152. "GU", "GW", "GY", "HK", "HM", "HN", "HR", "HT", "HU", "ID", "IE", "IL", "IN",
  153. "IO", "IQ", "IR", "IS", "IT", "JM", "JO", "JP", "KE", "KG", "KH", "KI", "KM",
  154. "KN", "KP", "KR", "KW", "KY", "KZ", "LA", "LB", "LC", "LI", "LK", "LR", "LS",
  155. "LT", "LU", "LV", "LY", "MA", "MC", "MD", "MG", "MH", "MK", "ML", "MM", "MN",
  156. "MO", "MP", "MQ", "MR", "MS", "MT", "MU", "MV", "MW", "MX", "MY", "MZ", "NA",
  157. "NC", "NE", "NF", "NG", "NI", "NL", "NO", "NP", "NR", "NU", "NZ", "OM", "PA",
  158. "PE", "PF", "PG", "PH", "PK", "PL", "PM", "PN", "PR", "PS", "PT", "PW", "PY",
  159. "QA", "RE", "RO", "RU", "RW", "SA", "SB", "SC", "SD", "SE", "SG", "SH", "SI",
  160. "SJ", "SK", "SL", "SM", "SN", "SO", "SR", "ST", "SV", "SY", "SZ", "TC", "TD",
  161. "TF", "TG", "TH", "TJ", "TK", "TM", "TN", "TO", "TL", "TR", "TT", "TV", "TW",
  162. "TZ", "UA", "UG", "UM", "US", "UY", "UZ", "VA", "VC", "VE", "VG", "VI", "VN",
  163. "VU", "WF", "WS", "YE", "YT", "RS", "ZA", "ZM", "ME", "ZW", "A1", "A2", "O1",
  164. "AX", "GG", "IM", "JE", "BL", "MF"
  165. );
  166. public static $COUNTRY_CODES3 = array(
  167. "","AP","EU","AND","ARE","AFG","ATG","AIA","ALB","ARM","ANT","AGO","AQ","ARG",
  168. "ASM","AUT","AUS","ABW","AZE","BIH","BRB","BGD","BEL","BFA","BGR","BHR","BDI",
  169. "BEN","BMU","BRN","BOL","BRA","BHS","BTN","BV","BWA","BLR","BLZ","CAN","CC",
  170. "COD","CAF","COG","CHE","CIV","COK","CHL","CMR","CHN","COL","CRI","CUB","CPV",
  171. "CX","CYP","CZE","DEU","DJI","DNK","DMA","DOM","DZA","ECU","EST","EGY","ESH",
  172. "ERI","ESP","ETH","FIN","FJI","FLK","FSM","FRO","FRA","FX","GAB","GBR","GRD",
  173. "GEO","GUF","GHA","GIB","GRL","GMB","GIN","GLP","GNQ","GRC","GS","GTM","GUM",
  174. "GNB","GUY","HKG","HM","HND","HRV","HTI","HUN","IDN","IRL","ISR","IND","IO",
  175. "IRQ","IRN","ISL","ITA","JAM","JOR","JPN","KEN","KGZ","KHM","KIR","COM","KNA",
  176. "PRK","KOR","KWT","CYM","KAZ","LAO","LBN","LCA","LIE","LKA","LBR","LSO","LTU",
  177. "LUX","LVA","LBY","MAR","MCO","MDA","MDG","MHL","MKD","MLI","MMR","MNG","MAC",
  178. "MNP","MTQ","MRT","MSR","MLT","MUS","MDV","MWI","MEX","MYS","MOZ","NAM","NCL",
  179. "NER","NFK","NGA","NIC","NLD","NOR","NPL","NRU","NIU","NZL","OMN","PAN","PER",
  180. "PYF","PNG","PHL","PAK","POL","SPM","PCN","PRI","PSE","PRT","PLW","PRY","QAT",
  181. "REU","ROU","RUS","RWA","SAU","SLB","SYC","SDN","SWE","SGP","SHN","SVN","SJM",
  182. "SVK","SLE","SMR","SEN","SOM","SUR","STP","SLV","SYR","SWZ","TCA","TCD","TF",
  183. "TGO","THA","TJK","TKL","TLS","TKM","TUN","TON","TUR","TTO","TUV","TWN","TZA",
  184. "UKR","UGA","UM","USA","URY","UZB","VAT","VCT","VEN","VGB","VIR","VNM","VUT",
  185. "WLF","WSM","YEM","YT","SRB","ZAF","ZMB","MNE","ZWE","A1","A2","O1",
  186. "ALA","GGY","IMN","JEY","BLM","MAF"
  187. );
  188. public static $COUNTRY_NAMES = array(
  189. "", "Asia/Pacific Region", "Europe", "Andorra", "United Arab Emirates",
  190. "Afghanistan", "Antigua and Barbuda", "Anguilla", "Albania", "Armenia",
  191. "Netherlands Antilles", "Angola", "Antarctica", "Argentina", "American Samoa",
  192. "Austria", "Australia", "Aruba", "Azerbaijan", "Bosnia and Herzegovina",
  193. "Barbados", "Bangladesh", "Belgium", "Burkina Faso", "Bulgaria", "Bahrain",
  194. "Burundi", "Benin", "Bermuda", "Brunei Darussalam", "Bolivia", "Brazil",
  195. "Bahamas", "Bhutan", "Bouvet Island", "Botswana", "Belarus", "Belize",
  196. "Canada", "Cocos (Keeling) Islands", "Congo, The Democratic Republic of the",
  197. "Central African Republic", "Congo", "Switzerland", "Cote D'Ivoire", "Cook Islands",
  198. "Chile", "Cameroon", "China", "Colombia", "Costa Rica", "Cuba", "Cape Verde",
  199. "Christmas Island", "Cyprus", "Czech Republic", "Germany", "Djibouti",
  200. "Denmark", "Dominica", "Dominican Republic", "Algeria", "Ecuador", "Estonia",
  201. "Egypt", "Western Sahara", "Eritrea", "Spain", "Ethiopia", "Finland", "Fiji",
  202. "Falkland Islands (Malvinas)", "Micronesia, Federated States of", "Faroe Islands",
  203. "France", "France, Metropolitan", "Gabon", "United Kingdom",
  204. "Grenada", "Georgia", "French Guiana", "Ghana", "Gibraltar", "Greenland",
  205. "Gambia", "Guinea", "Guadeloupe", "Equatorial Guinea", "Greece", "South Georgia and the South Sandwich Islands",
  206. "Guatemala", "Guam", "Guinea-Bissau",
  207. "Guyana", "Hong Kong", "Heard Island and McDonald Islands", "Honduras",
  208. "Croatia", "Haiti", "Hungary", "Indonesia", "Ireland", "Israel", "India",
  209. "British Indian Ocean Territory", "Iraq", "Iran, Islamic Republic of",
  210. "Iceland", "Italy", "Jamaica", "Jordan", "Japan", "Kenya", "Kyrgyzstan",
  211. "Cambodia", "Kiribati", "Comoros", "Saint Kitts and Nevis", "Korea, Democratic People's Republic of",
  212. "Korea, Republic of", "Kuwait", "Cayman Islands",
  213. "Kazakstan", "Lao People's Democratic Republic", "Lebanon", "Saint Lucia",
  214. "Liechtenstein", "Sri Lanka", "Liberia", "Lesotho", "Lithuania", "Luxembourg",
  215. "Latvia", "Libyan Arab Jamahiriya", "Morocco", "Monaco", "Moldova, Republic of",
  216. "Madagascar", "Marshall Islands", "Macedonia",
  217. "Mali", "Myanmar", "Mongolia", "Macau", "Northern Mariana Islands",
  218. "Martinique", "Mauritania", "Montserrat", "Malta", "Mauritius", "Maldives",
  219. "Malawi", "Mexico", "Malaysia", "Mozambique", "Namibia", "New Caledonia",
  220. "Niger", "Norfolk Island", "Nigeria", "Nicaragua", "Netherlands", "Norway",
  221. "Nepal", "Nauru", "Niue", "New Zealand", "Oman", "Panama", "Peru", "French Polynesia",
  222. "Papua New Guinea", "Philippines", "Pakistan", "Poland", "Saint Pierre and Miquelon",
  223. "Pitcairn Islands", "Puerto Rico", "Palestinian Territory",
  224. "Portugal", "Palau", "Paraguay", "Qatar", "Reunion", "Romania",
  225. "Russian Federation", "Rwanda", "Saudi Arabia", "Solomon Islands",
  226. "Seychelles", "Sudan", "Sweden", "Singapore", "Saint Helena", "Slovenia",
  227. "Svalbard and Jan Mayen", "Slovakia", "Sierra Leone", "San Marino", "Senegal",
  228. "Somalia", "Suriname", "Sao Tome and Principe", "El Salvador", "Syrian Arab Republic",
  229. "Swaziland", "Turks and Caicos Islands", "Chad", "French Southern Territories",
  230. "Togo", "Thailand", "Tajikistan", "Tokelau", "Turkmenistan",
  231. "Tunisia", "Tonga", "Timor-Leste", "Turkey", "Trinidad and Tobago", "Tuvalu",
  232. "Taiwan", "Tanzania, United Republic of", "Ukraine",
  233. "Uganda", "United States Minor Outlying Islands", "United States", "Uruguay",
  234. "Uzbekistan", "Holy See (Vatican City State)", "Saint Vincent and the Grenadines",
  235. "Venezuela", "Virgin Islands, British", "Virgin Islands, U.S.",
  236. "Vietnam", "Vanuatu", "Wallis and Futuna", "Samoa", "Yemen", "Mayotte",
  237. "Serbia", "South Africa", "Zambia", "Montenegro", "Zimbabwe",
  238. "Anonymous Proxy","Satellite Provider","Other",
  239. "Aland Islands","Guernsey","Isle of Man","Jersey","Saint Barthelemy","Saint Martin"
  240. );
  241. // storage / caching flags
  242. const STANDARD = 0;
  243. const MEMORY_CACHE = 1;
  244. const SHARED_MEMORY = 2;
  245. // Database structure constants
  246. const COUNTRY_BEGIN = 16776960;
  247. const STATE_BEGIN_REV0 = 16700000;
  248. const STATE_BEGIN_REV1 = 16000000;
  249. const STRUCTURE_INFO_MAX_SIZE = 20;
  250. const DATABASE_INFO_MAX_SIZE = 100;
  251. const COUNTRY_EDITION = 106;
  252. const REGION_EDITION_REV0 = 112;
  253. const REGION_EDITION_REV1 = 3;
  254. const CITY_EDITION_REV0 = 111;
  255. const CITY_EDITION_REV1 = 2;
  256. const ORG_EDITION = 110;
  257. const SEGMENT_RECORD_LENGTH = 3;
  258. const STANDARD_RECORD_LENGTH = 3;
  259. const ORG_RECORD_LENGTH = 4;
  260. const MAX_RECORD_LENGTH = 4;
  261. const MAX_ORG_RECORD_LENGTH = 300;
  262. const FULL_RECORD_LENGTH = 50;
  263. const US_OFFSET = 1;
  264. const CANADA_OFFSET = 677;
  265. const WORLD_OFFSET = 1353;
  266. const FIPS_RANGE = 360;
  267. // SHMOP memory address
  268. const SHM_KEY = 0x4f415401;
  269. /**
  270. * @var int
  271. */
  272. private $flags = 0;
  273. /**
  274. * @var resource
  275. */
  276. private $filehandle;
  277. /**
  278. * @var string
  279. */
  280. private $memoryBuffer;
  281. /**
  282. * @var int
  283. */
  284. private $databaseType;
  285. /**
  286. * @var int
  287. */
  288. private $databaseSegments;
  289. /**
  290. * @var int
  291. */
  292. private $recordLength;
  293. /**
  294. * The memory addr "id" for use with SHMOP.
  295. * @var int
  296. */
  297. private $shmid;
  298. /**
  299. * Support for singleton pattern.
  300. * @var array
  301. */
  302. private static $instances = array();
  303. /**
  304. * Construct a Net_GeoIP instance.
  305. * You should use the getInstance() method if you plan to use multiple databases or
  306. * the same database from several different places in your script.
  307. *
  308. * @param string $filename Path to binary geoip database.
  309. * @param int $flags Flags
  310. *
  311. * @see getInstance()
  312. */
  313. public function __construct($filename = null, $flags = null)
  314. {
  315. if ($filename !== null) {
  316. $this->open($filename, $flags);
  317. }
  318. // store the instance, so that it will be returned by a call to
  319. // getInstance() (with the same db filename).
  320. self::$instances[$filename] = $this;
  321. }
  322. /**
  323. * Calls the close() function to free any resources.
  324. * @see close()
  325. *
  326. * COMMENTED OUT TO ADDRESS BUG IN PHP 5.0.4, 5.0.5dev. THIS RESOURCE
  327. * SHOULD AUTOMATICALLY BE FREED AT SCRIPT CLOSE, SO A DESTRUCTOR
  328. * IS A GOOD IDEA BUT NOT NECESSARILY A NECESSITY.
  329. public function __destruct()
  330. {
  331. $this->close();
  332. }
  333. */
  334. /**
  335. * Singleton method, use this to get an instance and avoid re-parsing the db.
  336. *
  337. * Unique instances are instantiated based on the filename of the db. The flags
  338. * are ignored -- in that requests to for instance with same filename but different
  339. * flags will return the already-instantiated instance. For example:
  340. * <code>
  341. * // create new instance with memory_cache enabled
  342. * $geoip = Net_GeoIP::getInstance('C:\mydb.dat', Net_GeoIP::MEMORY_CACHE);
  343. * ....
  344. *
  345. * // later in code, request instance with no flags specified.
  346. * $geoip = Net_GeoIP::getInstance('C:\mydb.dat');
  347. *
  348. * // Normally this means no MEMORY_CACHE but since an instance
  349. * // with memory cache enabled has already been created for 'C:\mydb.dat', the
  350. * // existing instance (with memory cache) will be returned.
  351. * </code>
  352. *
  353. * NOTE: You can only use SHARED_MEMORY flag for one instance! Any subsquent instances
  354. * that attempt to use the SHARED_MEMORY will use the *same* shared memory, which will break
  355. * your script.
  356. *
  357. * @param string $filename Filename
  358. * @param int $flags Flags that control class behavior.
  359. * + Net_GeoIp::SHARED_MEMORY
  360. * Use SHMOP to share a db among multiple PHP instances.
  361. * NOTE: ONLY ONE GEOIP INSTANCE CAN USE SHARED MEMORY!!!
  362. * + Net_GeoIp::MEMORY_CACHE
  363. * Store the full contents of the database in memory for current script.
  364. * This is useful if you access the database several times in a script.
  365. * + Net_GeoIp::STANDARD
  366. * [default] standard no-cache version.
  367. *
  368. * @return Net_GeoIP
  369. */
  370. public static function getInstance($filename = null, $flags = null)
  371. {
  372. if (!isset(self::$instances[$filename])) {
  373. self::$instances[$filename] = new Net_GeoIP($filename, $flags);
  374. }
  375. return self::$instances[$filename];
  376. }
  377. /**
  378. * Opens geoip database at filename and with specified flags.
  379. *
  380. * @param string $filename File to open
  381. * @param int $flags Flags
  382. *
  383. * @return void
  384. *
  385. * @throws PEAR_Exception if unable to open specified file or shared memory.
  386. */
  387. public function open($filename, $flags = null)
  388. {
  389. if ($flags !== null) {
  390. $this->flags = $flags;
  391. }
  392. if ($this->flags & self::SHARED_MEMORY) {
  393. $this->shmid = @shmop_open(self::SHM_KEY, "a", 0, 0);
  394. if ($this->shmid === false) {
  395. $this->loadSharedMemory($filename);
  396. $this->shmid = @shmop_open(self::SHM_KEY, "a", 0, 0);
  397. if ($this->shmid === false) { // should never be false as loadSharedMemory() will throw Exc if cannot create
  398. throw new PEAR_Exception("Unable to open shared memory at key: " . dechex(self::SHM_KEY));
  399. }
  400. }
  401. } else {
  402. $this->filehandle = fopen($filename, "rb");
  403. if (!$this->filehandle) {
  404. throw new PEAR_Exception("Unable to open file: $filename");
  405. }
  406. if ($this->flags & self::MEMORY_CACHE) {
  407. $s_array = fstat($this->filehandle);
  408. $this->memoryBuffer = fread($this->filehandle, $s_array['size']);
  409. }
  410. }
  411. $this->setupSegments();
  412. }
  413. /**
  414. * Loads the database file into shared memory.
  415. *
  416. * @param string $filename Path to database file to read into shared memory.
  417. *
  418. * @return void
  419. *
  420. * @throws PEAR_Exception - if unable to read the db file.
  421. */
  422. protected function loadSharedMemory($filename)
  423. {
  424. $fp = fopen($filename, "rb");
  425. if (!$fp) {
  426. throw new PEAR_Exception("Unable to open file: $filename");
  427. }
  428. $s_array = fstat($fp);
  429. $size = $s_array['size'];
  430. if ($shmid = @shmop_open(self::SHM_KEY, "w", 0, 0)) {
  431. shmop_delete($shmid);
  432. shmop_close($shmid);
  433. }
  434. if ($shmid = @shmop_open(self::SHM_KEY, "c", 0644, $size)) {
  435. $offset = 0;
  436. while ($offset < $size) {
  437. $buf = fread($fp, 524288);
  438. shmop_write($shmid, $buf, $offset);
  439. $offset += 524288;
  440. }
  441. shmop_close($shmid);
  442. }
  443. fclose($fp);
  444. }
  445. /**
  446. * Parses the database file to determine what kind of database is being used and setup
  447. * segment sizes and start points that will be used by the seek*() methods later.
  448. *
  449. * @return void
  450. */
  451. protected function setupSegments()
  452. {
  453. $this->databaseType = self::COUNTRY_EDITION;
  454. $this->recordLength = self::STANDARD_RECORD_LENGTH;
  455. if ($this->flags & self::SHARED_MEMORY) {
  456. $offset = shmop_size($this->shmid) - 3;
  457. for ($i = 0; $i < self::STRUCTURE_INFO_MAX_SIZE; $i++) {
  458. $delim = shmop_read($this->shmid, $offset, 3);
  459. $offset += 3;
  460. if ($delim == (chr(255).chr(255).chr(255))) {
  461. $this->databaseType = ord(shmop_read($this->shmid, $offset, 1));
  462. $offset++;
  463. if ($this->databaseType === self::REGION_EDITION_REV0) {
  464. $this->databaseSegments = self::STATE_BEGIN_REV0;
  465. } elseif ($this->databaseType === self::REGION_EDITION_REV1) {
  466. $this->databaseSegments = self::STATE_BEGIN_REV1;
  467. } elseif (($this->databaseType === self::CITY_EDITION_REV0)
  468. || ($this->databaseType === self::CITY_EDITION_REV1)
  469. || ($this->databaseType === self::ORG_EDITION)) {
  470. $this->databaseSegments = 0;
  471. $buf = shmop_read($this->shmid, $offset, self::SEGMENT_RECORD_LENGTH);
  472. for ($j = 0; $j < self::SEGMENT_RECORD_LENGTH; $j++) {
  473. $this->databaseSegments += (ord($buf[$j]) << ($j * 8));
  474. }
  475. if ($this->databaseType === self::ORG_EDITION) {
  476. $this->recordLength = self::ORG_RECORD_LENGTH;
  477. }
  478. }
  479. break;
  480. } else {
  481. $offset -= 4;
  482. }
  483. }
  484. if ($this->databaseType == self::COUNTRY_EDITION) {
  485. $this->databaseSegments = self::COUNTRY_BEGIN;
  486. }
  487. } else {
  488. $filepos = ftell($this->filehandle);
  489. fseek($this->filehandle, -3, SEEK_END);
  490. for ($i = 0; $i < self::STRUCTURE_INFO_MAX_SIZE; $i++) {
  491. $delim = fread($this->filehandle, 3);
  492. if ($delim == (chr(255).chr(255).chr(255))) {
  493. $this->databaseType = ord(fread($this->filehandle, 1));
  494. if ($this->databaseType === self::REGION_EDITION_REV0) {
  495. $this->databaseSegments = self::STATE_BEGIN_REV0;
  496. } elseif ($this->databaseType === self::REGION_EDITION_REV1) {
  497. $this->databaseSegments = self::STATE_BEGIN_REV1;
  498. } elseif ($this->databaseType === self::CITY_EDITION_REV0
  499. || $this->databaseType === self::CITY_EDITION_REV1
  500. || $this->databaseType === self::ORG_EDITION) {
  501. $this->databaseSegments = 0;
  502. $buf = fread($this->filehandle, self::SEGMENT_RECORD_LENGTH);
  503. for ($j = 0; $j < self::SEGMENT_RECORD_LENGTH; $j++) {
  504. $this->databaseSegments += (ord($buf[$j]) << ($j * 8));
  505. }
  506. if ($this->databaseType === self::ORG_EDITION) {
  507. $this->recordLength = self::ORG_RECORD_LENGTH;
  508. }
  509. }
  510. break;
  511. } else {
  512. fseek($this->filehandle, -4, SEEK_CUR);
  513. }
  514. }
  515. if ($this->databaseType === self::COUNTRY_EDITION) {
  516. $this->databaseSegments = self::COUNTRY_BEGIN;
  517. }
  518. fseek($this->filehandle, $filepos, SEEK_SET);
  519. }
  520. }
  521. /**
  522. * Closes the geoip database.
  523. *
  524. * @return int Status of close command.
  525. */
  526. public function close()
  527. {
  528. if ($this->flags & self::SHARED_MEMORY) {
  529. return shmop_close($this->shmid);
  530. } else {
  531. // right now even if file was cached in RAM the file was not closed
  532. // so it's safe to expect no error w/ fclose()
  533. return fclose($this->filehandle);
  534. }
  535. }
  536. /**
  537. * Get the country index.
  538. *
  539. * This method is called by the lookupCountryCode() and lookupCountryName()
  540. * methods. It lookups up the index ('id') for the country which is the key
  541. * for the code and name.
  542. *
  543. * @param string $addr IP address (hostname not allowed)
  544. *
  545. * @throws PEAR_Exception - if IP address is invalid.
  546. * - if database type is incorrect
  547. *
  548. * @return string ID for the country
  549. */
  550. protected function lookupCountryId($addr)
  551. {
  552. $ipnum = ip2long($addr);
  553. if ($ipnum === false) {
  554. throw new PEAR_Exception("Invalid IP address: " . var_export($addr, true), self::ERR_INVALID_IP);
  555. }
  556. if ($this->databaseType !== self::COUNTRY_EDITION) {
  557. throw new PEAR_Exception("Invalid database type; lookupCountry*() methods expect Country database.");
  558. }
  559. return $this->seekCountry($ipnum) - self::COUNTRY_BEGIN;
  560. }
  561. /**
  562. * Returns 2-letter country code (e.g. 'CA') for specified IP address.
  563. * Use this method if you have a Country database.
  564. *
  565. * @param string $addr IP address (hostname not allowed).
  566. *
  567. * @return string 2-letter country code
  568. *
  569. * @throws PEAR_Exception (see lookupCountryId())
  570. * @see lookupCountryId()
  571. */
  572. public function lookupCountryCode($addr)
  573. {
  574. return self::$COUNTRY_CODES[$this->lookupCountryId($addr)];
  575. }
  576. /**
  577. * Returns full country name for specified IP address.
  578. * Use this method if you have a Country database.
  579. *
  580. * @param string $addr IP address (hostname not allowed).
  581. *
  582. * @return string Country name
  583. * @throws PEAR_Exception (see lookupCountryId())
  584. * @see lookupCountryId()
  585. */
  586. public function lookupCountryName($addr)
  587. {
  588. return self::$COUNTRY_NAMES[$this->lookupCountryId($addr)];
  589. }
  590. /**
  591. * Using the record length and appropriate start points, seek to the country that corresponds
  592. * to the converted IP address integer.
  593. *
  594. * @param int $ipnum Result of ip2long() conversion.
  595. *
  596. * @return int Offset of start of record.
  597. * @throws PEAR_Exception - if fseek() fails on the file or no results after traversing the database (indicating corrupt db).
  598. */
  599. protected function seekCountry($ipnum)
  600. {
  601. $offset = 0;
  602. for ($depth = 31; $depth >= 0; --$depth) {
  603. if ($this->flags & self::MEMORY_CACHE) {
  604. $buf = substr($this->memoryBuffer, 2 * $this->recordLength * $offset, 2 * $this->recordLength);
  605. } elseif ($this->flags & self::SHARED_MEMORY) {
  606. $buf = shmop_read($this->shmid, 2 * $this->recordLength * $offset, 2 * $this->recordLength);
  607. } else {
  608. if (fseek($this->filehandle, 2 * $this->recordLength * $offset, SEEK_SET) !== 0) {
  609. throw new PEAR_Exception("fseek failed");
  610. }
  611. $buf = fread($this->filehandle, 2 * $this->recordLength);
  612. }
  613. $x = array(0,0);
  614. for ($i = 0; $i < 2; ++$i) {
  615. for ($j = 0; $j < $this->recordLength; ++$j) {
  616. $x[$i] += ord($buf[$this->recordLength * $i + $j]) << ($j * 8);
  617. }
  618. }
  619. if ($ipnum & (1 << $depth)) {
  620. if ($x[1] >= $this->databaseSegments) {
  621. return $x[1];
  622. }
  623. $offset = $x[1];
  624. } else {
  625. if ($x[0] >= $this->databaseSegments) {
  626. return $x[0];
  627. }
  628. $offset = $x[0];
  629. }
  630. }
  631. throw new PEAR_Exception("Error traversing database - perhaps it is corrupt?");
  632. }
  633. /**
  634. * Lookup the organization (or ISP) for given IP address.
  635. * Use this method if you have an Organization/ISP database.
  636. *
  637. * @param string $addr IP address (hostname not allowed).
  638. *
  639. * @throws PEAR_Exception - if IP address is invalid.
  640. * - if database is of wrong type
  641. *
  642. * @return string The organization
  643. */
  644. public function lookupOrg($addr)
  645. {
  646. $ipnum = ip2long($addr);
  647. if ($ipnum === false) {
  648. throw new PEAR_Exception("Invalid IP address: " . var_export($addr, true), self::ERR_INVALID_IP);
  649. }
  650. if ($this->databaseType !== self::ORG_EDITION) {
  651. throw new PEAR_Exception("Invalid database type; lookupOrg() method expects Org/ISP database.", self::ERR_DB_FORMAT);
  652. }
  653. return $this->getOrg($ipnum);
  654. }
  655. /**
  656. * Lookup the region for given IP address.
  657. * Use this method if you have a Region database.
  658. *
  659. * @param string $addr IP address (hostname not allowed).
  660. *
  661. * @return array Array containing country code and region: array($country_code, $region)
  662. *
  663. * @throws PEAR_Exception - if IP address is invalid.
  664. */
  665. public function lookupRegion($addr)
  666. {
  667. $ipnum = ip2long($addr);
  668. if ($ipnum === false) {
  669. throw new PEAR_Exception("Invalid IP address: " . var_export($addr, true), self::ERR_INVALID_IP);
  670. }
  671. if ($this->databaseType !== self::REGION_EDITION_REV0 && $this->databaseType !== self::REGION_EDITION_REV1) {
  672. throw new PEAR_Exception("Invalid database type; lookupRegion() method expects Region database.", self::ERR_DB_FORMAT);
  673. }
  674. return $this->getRegion($ipnum);
  675. }
  676. /**
  677. * Lookup the location record for given IP address.
  678. * Use this method if you have a City database.
  679. *
  680. * @param string $addr IP address (hostname not allowed).
  681. *
  682. * @return Net_GeoIP_Location The full location record.
  683. *
  684. * @throws PEAR_Exception - if IP address is invalid.
  685. */
  686. public function lookupLocation($addr)
  687. {
  688. include_once 'Net/GeoIP/Location.php';
  689. $ipnum = ip2long($addr);
  690. if ($ipnum === false) {
  691. throw new PEAR_Exception("Invalid IP address: " . var_export($addr, true), self::ERR_INVALID_IP);
  692. }
  693. if ($this->databaseType !== self::CITY_EDITION_REV0 && $this->databaseType !== self::CITY_EDITION_REV1) {
  694. throw new PEAR_Exception("Invalid database type; lookupLocation() method expects City database.");
  695. }
  696. return $this->getRecord($ipnum);
  697. }
  698. /**
  699. * Seek and return organization (or ISP) name for converted IP addr.
  700. *
  701. * @param int $ipnum Converted IP address.
  702. *
  703. * @return string The organization
  704. */
  705. protected function getOrg($ipnum)
  706. {
  707. $seek_org = $this->seekCountry($ipnum);
  708. if ($seek_org == $this->databaseSegments) {
  709. return null;
  710. }
  711. $record_pointer = $seek_org + (2 * $this->recordLength - 1) * $this->databaseSegments;
  712. if ($this->flags & self::SHARED_MEMORY) {
  713. $org_buf = shmop_read($this->shmid, $record_pointer, self::MAX_ORG_RECORD_LENGTH);
  714. } else {
  715. fseek($this->filehandle, $record_pointer, SEEK_SET);
  716. $org_buf = fread($this->filehandle, self::MAX_ORG_RECORD_LENGTH);
  717. }
  718. $org_buf = substr($org_buf, 0, strpos($org_buf, 0));
  719. return $org_buf;
  720. }
  721. /**
  722. * Seek and return the region info (array containing country code and region name) for converted IP addr.
  723. *
  724. * @param int $ipnum Converted IP address.
  725. *
  726. * @return array Array containing country code and region: array($country_code, $region)
  727. */
  728. protected function getRegion($ipnum)
  729. {
  730. if ($this->databaseType == self::REGION_EDITION_REV0) {
  731. $seek_region = $this->seekCountry($ipnum) - self::STATE_BEGIN_REV0;
  732. if ($seek_region >= 1000) {
  733. $country_code = "US";
  734. $region = chr(($seek_region - 1000)/26 + 65) . chr(($seek_region - 1000)%26 + 65);
  735. } else {
  736. $country_code = self::$COUNTRY_CODES[$seek_region];
  737. $region = "";
  738. }
  739. return array($country_code, $region);
  740. } elseif ($this->databaseType == self::REGION_EDITION_REV1) {
  741. $seek_region = $this->seekCountry($ipnum) - self::STATE_BEGIN_REV1;
  742. //print $seek_region;
  743. if ($seek_region < self::US_OFFSET) {
  744. $country_code = "";
  745. $region = "";
  746. } elseif ($seek_region < self::CANADA_OFFSET) {
  747. $country_code = "US";
  748. $region = chr(($seek_region - self::US_OFFSET)/26 + 65) . chr(($seek_region - self::US_OFFSET)%26 + 65);
  749. } elseif ($seek_region < self::WORLD_OFFSET) {
  750. $country_code = "CA";
  751. $region = chr(($seek_region - self::CANADA_OFFSET)/26 + 65) . chr(($seek_region - self::CANADA_OFFSET)%26 + 65);
  752. } else {
  753. $country_code = self::$COUNTRY_CODES[($seek_region - self::WORLD_OFFSET) / self::FIPS_RANGE];
  754. $region = "";
  755. }
  756. return array ($country_code,$region);
  757. }
  758. }
  759. /**
  760. * Seek and populate Net_GeoIP_Location object for converted IP addr.
  761. * Note: this
  762. *
  763. * @param int $ipnum Converted IP address.
  764. *
  765. * @return Net_GeoIP_Location
  766. */
  767. protected function getRecord($ipnum)
  768. {
  769. $seek_country = $this->seekCountry($ipnum);
  770. if ($seek_country == $this->databaseSegments) {
  771. return null;
  772. }
  773. $record_pointer = $seek_country + (2 * $this->recordLength - 1) * $this->databaseSegments;
  774. if ($this->flags & self::SHARED_MEMORY) {
  775. $record_buf = shmop_read($this->shmid, $record_pointer, self::FULL_RECORD_LENGTH);
  776. } else {
  777. fseek($this->filehandle, $record_pointer, SEEK_SET);
  778. $record_buf = fread($this->filehandle, self::FULL_RECORD_LENGTH);
  779. }
  780. $record = new Net_GeoIP_Location();
  781. $record_buf_pos = 0;
  782. $char = ord(substr($record_buf, $record_buf_pos, 1));
  783. $record->countryCode = self::$COUNTRY_CODES[$char];
  784. $record->countryCode3 = self::$COUNTRY_CODES3[$char];
  785. $record->countryName = self::$COUNTRY_NAMES[$char];
  786. $record_buf_pos++;
  787. $str_length = 0;
  788. //get region
  789. $char = ord(substr($record_buf, $record_buf_pos+$str_length, 1));
  790. while ($char != 0) {
  791. $str_length++;
  792. $char = ord(substr($record_buf, $record_buf_pos+$str_length, 1));
  793. }
  794. if ($str_length > 0) {
  795. $record->region = substr($record_buf, $record_buf_pos, $str_length);
  796. }
  797. $record_buf_pos += $str_length + 1;
  798. $str_length = 0;
  799. //get city
  800. $char = ord(substr($record_buf, $record_buf_pos+$str_length, 1));
  801. while ($char != 0) {
  802. $str_length++;
  803. $char = ord(substr($record_buf, $record_buf_pos+$str_length, 1));
  804. }
  805. if ($str_length > 0) {
  806. $record->city = substr($record_buf, $record_buf_pos, $str_length);
  807. }
  808. $record_buf_pos += $str_length + 1;
  809. $str_length = 0;
  810. //get postal code
  811. $char = ord(substr($record_buf, $record_buf_pos+$str_length, 1));
  812. while ($char != 0) {
  813. $str_length++;
  814. $char = ord(substr($record_buf, $record_buf_pos+$str_length, 1));
  815. }
  816. if ($str_length > 0) {
  817. $record->postalCode = substr($record_buf, $record_buf_pos, $str_length);
  818. }
  819. $record_buf_pos += $str_length + 1;
  820. $str_length = 0;
  821. $latitude = 0;
  822. $longitude = 0;
  823. for ($j = 0;$j < 3; ++$j) {
  824. $char = ord(substr($record_buf, $record_buf_pos++, 1));
  825. $latitude += ($char << ($j * 8));
  826. }
  827. $record->latitude = ($latitude/10000) - 180;
  828. for ($j = 0;$j < 3; ++$j) {
  829. $char = ord(substr($record_buf, $record_buf_pos++, 1));
  830. $longitude += ($char << ($j * 8));
  831. }
  832. $record->longitude = ($longitude/10000) - 180;
  833. if ($this->databaseType === self::CITY_EDITION_REV1) {
  834. $dmaarea_combo = 0;
  835. if ($record->countryCode == "US") {
  836. for ($j = 0;$j < 3;++$j) {
  837. $char = ord(substr($record_buf, $record_buf_pos++, 1));
  838. $dmaarea_combo += ($char << ($j * 8));
  839. }
  840. $record->dmaCode = floor($dmaarea_combo/1000);
  841. $record->areaCode = $dmaarea_combo%1000;
  842. }
  843. }
  844. return $record;
  845. }
  846. }