Exemplo n.º 1
0
 /**
  * Returns the Location for the provided IPv4 address.
  *
  * @param string $ip4 IPv4 address.
  *
  * @return Location
  * @throws ProviderGeoIpNotFound
  */
 public function getLocationFromIPv4($ip4)
 {
     // get by starting block
     $subNet = $this->str($ip4)->explode('.')->removeLast()->implode('.')->val();
     $ipStart = $subNet . '.0';
     // get by start ip
     $ipLong = ip2long($ip4);
     $cityBlock = CityBlockIp4Entity::findOne(['rangeStart' => ip2long($ipStart)]);
     // verify that end ip is within range
     if (!$cityBlock || !($ipLong <= $cityBlock->rangeEnd)) {
         throw new ProviderGeoIpNotFound('GeoIp entry not found');
     }
     // get location info
     $locationInfo = LocationEntity::findOne(['geoId' => $cityBlock->geoId]);
     // populate location variable
     $location = new Location();
     $location->setContinent($locationInfo->continentCode, $locationInfo->continentName);
     $location->setCountry($locationInfo->countryCode, $locationInfo->countryName);
     $location->setCityName($locationInfo->cityName);
     $location->setSubdivision1($locationInfo->subdivision1Code, $locationInfo->subdivision1Name);
     $location->setSubdivision2($locationInfo->subdivision2Code, $locationInfo->subdivision2Name);
     $location->setTimeZone($locationInfo->timeZone);
     return $location;
 }
Exemplo n.º 2
0
 /**
  * Import IPv4 city block entries.
  *
  * @throws \Webiny\Component\StdLib\StdObject\StringObject\StringObjectException
  */
 public function importIp4CityBlock()
 {
     // city blocks db file
     $cbFile = $this->dbFolder . 'GeoLite2-City-Blocks-IPv4.csv';
     // start the import
     echo "\nImporting city IPv4 block ... please give it couple of minutes to finish. (like 10-15min, there is 3M+ records to import)";
     $handle = fopen($cbFile, "r");
     fgetcsv($handle, 0, ",");
     // remove the header row
     while (($row = fgetcsv($handle, 0, ",")) !== false) {
         // calculate ip range block
         $cidr = $this->str($row[0])->explode('/');
         $ip_count = 1 << 32 - $cidr->last()->val();
         $start = ip2long($cidr->first()->val());
         $end = $start + $ip_count;
         // save the record
         $cityBlockEntity = new CityBlockIp4Entity();
         $cityBlockEntity->rangeStart = $start;
         $cityBlockEntity->rangeEnd = $end;
         $cityBlockEntity->geoId = floatval($row[1]);
         $cityBlockEntity->save();
     }
     fclose($handle);
     // ensure range index
     $index = new SingleIndex('ipStart', 'rangeStart');
     $this->mongo->createIndex('GeoIpCityBlockIp4', $index);
     echo "\nCity IPv4 block import done\n";
 }