Net_GeoIP
[ class tree: Net_GeoIP ] [ index: Net_GeoIP ] [ all elements ]

Source for file GeoIP.php

Documentation is available at GeoIP.php

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

Documentation generated on Mon, 11 Mar 2019 14:20:13 -0400 by phpDocumentor 1.4.4. PEAR Logo Copyright © PHP Group 2004.