Example #1
0
 public function __construct($ip_addr)
 {
     try {
         if ($ip_addr == '127.0.0.1') {
             // Load local connections up with Columbus, OH.
             // Why?  ;)
             $cache = ['city' => 'Columbus', 'province' => 'OH', 'country' => 'US', 'timezone' => 'America/New_York', 'postal' => '43215'];
         } else {
             $cacheKey = 'iplookup-' . $ip_addr;
             $cache = Cache::Get($cacheKey);
             if (!$cache) {
                 $reader = new \GeoIp2\Database\Reader(ROOT_PDIR . 'components/geographic-codes/libs/maxmind-geolite-db/GeoLite2-City.mmdb');
                 /** @var \GeoIp2\Model\CityIspOrg $geo */
                 $geo = $reader->cityIspOrg($ip_addr);
                 //$geo = $reader->cityIspOrg('67.149.214.236');
                 $reader->close();
                 $sd = isset($geo->subdivisions[0]) ? $geo->subdivisions[0] : null;
                 $cache = ['city' => $geo->city->name, 'province' => $sd ? $sd->isoCode : '', 'country' => $geo->country->isoCode, 'timezone' => $geo->location->timeZone, 'postal' => $geo->postal->code];
                 Cache::Set($cacheKey, $cache, SECONDS_ONE_WEEK);
             }
         }
     } catch (\Exception $e) {
         // Well, we tried!  Load something at least.
         $cacheKey = 'iplookup-' . $ip_addr;
         $cache = ['city' => 'McMurdo Base', 'province' => '', 'country' => 'AQ', 'timezone' => 'CAST', 'postal' => ''];
         Cache::Set($cacheKey, $cache, SECONDS_ONE_HOUR);
     }
     $this->city = $cache['city'];
     $this->province = $cache['province'];
     $this->country = $cache['country'];
     $this->timezone = $cache['timezone'];
     $this->postal = $cache['postal'];
 }
Example #2
0
/**
 * Returns location information
 * @param string $ip
 * @return array
 */
function iplookup_find_location($ip)
{
    global $CFG;
    $info = array('city' => null, 'country' => null, 'longitude' => null, 'latitude' => null, 'error' => null, 'note' => '', 'title' => array());
    if (!empty($CFG->geoip2file) and file_exists($CFG->geoip2file)) {
        $reader = new GeoIp2\Database\Reader($CFG->geoip2file);
        $record = $reader->city($ip);
        if (empty($record)) {
            $info['error'] = get_string('iplookupfailed', 'error', $ip);
            return $info;
        }
        $info['city'] = core_text::convert($record->city->name, 'iso-8859-1', 'utf-8');
        $info['title'][] = $info['city'];
        $countrycode = $record->country->isoCode;
        $countries = get_string_manager()->get_list_of_countries(true);
        if (isset($countries[$countrycode])) {
            // Prefer our localized country names.
            $info['country'] = $countries[$countrycode];
        } else {
            $info['country'] = $record->country->names['en'];
        }
        $info['title'][] = $info['country'];
        $info['longitude'] = $record->location->longitude;
        $info['latitude'] = $record->location->latitude;
        $info['note'] = get_string('iplookupmaxmindnote', 'admin');
        return $info;
    } else {
        require_once $CFG->libdir . '/filelib.php';
        if (strpos($ip, ':') !== false) {
            // IPv6 is not supported by geoplugin.net.
            $info['error'] = get_string('invalidipformat', 'error');
            return $info;
        }
        $ipdata = download_file_content('http://www.geoplugin.net/json.gp?ip=' . $ip);
        if ($ipdata) {
            $ipdata = preg_replace('/^geoPlugin\\((.*)\\)\\s*$/s', '$1', $ipdata);
            $ipdata = json_decode($ipdata, true);
        }
        if (!is_array($ipdata)) {
            $info['error'] = get_string('cannotgeoplugin', 'error');
            return $info;
        }
        $info['latitude'] = (double) $ipdata['geoplugin_latitude'];
        $info['longitude'] = (double) $ipdata['geoplugin_longitude'];
        $info['city'] = s($ipdata['geoplugin_city']);
        $countrycode = $ipdata['geoplugin_countryCode'];
        $countries = get_string_manager()->get_list_of_countries(true);
        if (isset($countries[$countrycode])) {
            // prefer our localized country names
            $info['country'] = $countries[$countrycode];
        } else {
            $info['country'] = s($ipdata['geoplugin_countryName']);
        }
        $info['note'] = get_string('iplookupgeoplugin', 'admin');
        $info['title'][] = $info['city'];
        $info['title'][] = $info['country'];
        return $info;
    }
}
Example #3
0
 /**
  * @brief 使用GeoIp查询客户端国家、城市
  *
  * @param $ip    string  IP地址
  *
  * @return array
  */
 public static function getCity($ip)
 {
     if (!is_file(self::GEOIP_CITY_DB) || !is_readable(self::GEOIP_CITY_DB)) {
         throw new \Exception('GEO数据库未找到');
     }
     try {
         $reader = new \GeoIp2\Database\Reader(self::GEOIP_CITY_DB);
         $record = $reader->city($ip);
         return ['country' => $record->country->names['zh-CN'], 'city' => $record->city->names['zh-CN']];
     } catch (\Exception $e) {
         return ['country' => '火星', 'city' => ''];
     }
 }
Example #4
0
 public static function getTimezone()
 {
     if (($timezone = self::getEnv("envTimezone")) === null) {
         try {
             $mmdb = array_reverse(glob(Config::$geoip . "GeoLite2-City*.mmdb"))[0];
             $reader = new \GeoIp2\Database\Reader($mmdb);
             $ip = Request::getIp();
             $record = $reader->city($ip);
             $timezone = $record->location->timeZone;
             self::setTimezone($timezone);
         } catch (\Exception $e) {
             Logger::instance()->logError($e->getMessage());
             self::setTimezone(Config::$defaultTimezone);
         }
     }
     return new \DateTimeZone($timezone);
 }
Example #5
0
 public static function maxmindValidateFilename($filename)
 {
     if (file_exists(ABSPATH . $filename)) {
         $filename = ABSPATH . $filename;
     }
     if (!is_readable($filename)) {
         return '';
     }
     try {
         $reader = new \GeoIp2\Database\Reader($filename);
         $metadata = $reader->metadata();
         $reader->close();
     } catch (\Exception $e) {
         if (WP_DEBUG) {
             echo 'Error while creating reader for "' . $filename . '": ' . $e->getMessage();
         }
         return '';
     }
     return $filename;
 }
 public static function getUserData($service, $ip, $params = array())
 {
     if ($service == 'mod_geoip2') {
         if (isset($_SERVER[$params['country_code']]) && isset($_SERVER[$params['country_name']])) {
             $normalizedObject = new stdClass();
             $normalizedObject->country_code = strtolower($_SERVER[$params['country_code']]);
             $normalizedObject->country_name = strtolower($_SERVER[$params['country_name']]);
             $normalizedObject->city = isset($_SERVER[$params['mod_geo_ip_city_name']]) ? $_SERVER[$params['mod_geo_ip_city_name']] : '';
             $normalizedObject->city .= isset($params['mod_geo_ip_region_name']) && isset($_SERVER[$params['mod_geo_ip_region_name']]) ? ', ' . $_SERVER[$params['mod_geo_ip_region_name']] : '';
             $normalizedObject->lat = isset($_SERVER[$params['mod_geo_ip_latitude']]) ? $_SERVER[$params['mod_geo_ip_latitude']] : '0';
             $normalizedObject->lon = isset($_SERVER[$params['mod_geo_ip_longitude']]) ? $_SERVER[$params['mod_geo_ip_longitude']] : '0';
             return $normalizedObject;
         } else {
             return false;
         }
     } elseif ($service == 'php_geoip') {
         if (function_exists('geoip_record_by_name')) {
             $data = @geoip_record_by_name($ip);
             if ($data !== null) {
                 $normalizedObject = new stdClass();
                 $normalizedObject->country_code = isset($data['country_code']) ? strtolower($data['country_code']) : '';
                 $normalizedObject->country_name = isset($data['country_name']) ? strtolower($data['country_name']) : '';
                 $normalizedObject->city = isset($data['city']) ? strtolower($data['city']) : '';
                 $normalizedObject->city .= isset($data['region']) ? ', ' . strtolower($data['region']) : '';
                 $normalizedObject->lat = isset($data['latitude']) ? strtolower($data['latitude']) : '';
                 $normalizedObject->lon = isset($data['longitude']) ? strtolower($data['longitude']) : '';
                 return $normalizedObject;
             } else {
                 return false;
             }
         } else {
             return false;
         }
     } elseif ($service == 'max_mind') {
         if ($params['detection_type'] == 'country') {
             try {
                 $reader = new GeoIp2\Database\Reader('var/external/geoip/GeoLite2-Country.mmdb');
                 $countryData = $reader->country($ip);
                 $normalizedObject = new stdClass();
                 $normalizedObject->country_code = strtolower($countryData->raw['country']['iso_code']);
                 $normalizedObject->country_name = $countryData->raw['country']['names']['en'];
                 $normalizedObject->city = '';
                 $normalizedObject->lat = '';
                 $normalizedObject->lon = '';
                 return $normalizedObject;
             } catch (Exception $e) {
                 return false;
             }
         } elseif ($params['detection_type'] == 'city') {
             try {
                 $reader = new GeoIp2\Database\Reader(isset($params['city_file']) && $params['city_file'] != '' ? $params['city_file'] : 'var/external/geoip/GeoLite2-City.mmdb');
                 $countryData = $reader->city($ip);
                 $normalizedObject = new stdClass();
                 $normalizedObject->country_code = strtolower($countryData->raw['country']['iso_code']);
                 $normalizedObject->country_name = $countryData->raw['country']['names']['en'];
                 $normalizedObject->lat = isset($countryData->raw['location']['latitude']) ? $countryData->raw['location']['latitude'] : '0';
                 $normalizedObject->lon = isset($countryData->raw['location']['longitude']) ? $countryData->raw['location']['longitude'] : '0';
                 try {
                     $normalizedObject->city = $countryData->city->name != '' ? $countryData->city->name : (isset($countryData->raw['location']['time_zone']) ? $countryData->raw['location']['time_zone'] : '');
                     $regionName = isset($countryData->raw['mostSpecificSubdivision']['name']) ? ', ' . $countryData->raw['mostSpecificSubdivision']['name'] : '';
                     $normalizedObject->city .= isset($countryData->mostSpecificSubdivision->isoCode) ? ', ' . $countryData->mostSpecificSubdivision->isoCode : '';
                     $normalizedObject->city .= $regionName;
                 } catch (Exception $e) {
                     // Just in case of city error
                 }
                 return $normalizedObject;
             } catch (Exception $e) {
                 return false;
             }
         }
         return false;
     } elseif ($service == 'freegeoip') {
         $response = self::executeRequest('http://freegeoip.net/json/' . $ip);
         if (!empty($response)) {
             $responseData = json_decode($response);
             if (is_object($responseData)) {
                 $normalizedObject = new stdClass();
                 $normalizedObject->country_code = strtolower($responseData->country_code);
                 $normalizedObject->country_name = $responseData->country_name;
                 $normalizedObject->lat = $responseData->latitude;
                 $normalizedObject->lon = $responseData->longitude;
                 $normalizedObject->city = $responseData->city . ($responseData->region_name != '' ? ', ' . $responseData->region_name : '');
                 return $normalizedObject;
             }
         }
         return false;
     } elseif ($service == 'ipinfodbcom') {
         $response = self::executeRequest("http://api.ipinfodb.com/v3/ip-city/?key={$params['api_key']}&ip={$ip}&format=json");
         if (!empty($response)) {
             $responseData = json_decode($response);
             if (is_object($responseData)) {
                 if ($responseData->statusCode == 'OK') {
                     $normalizedObject = new stdClass();
                     $normalizedObject->country_code = strtolower($responseData->countryCode);
                     $normalizedObject->country_name = $responseData->countryName;
                     $normalizedObject->lat = $responseData->latitude;
                     $normalizedObject->lon = $responseData->longitude;
                     $normalizedObject->city = $responseData->cityName . ($responseData->regionName != '' ? ', ' . $responseData->regionName : '');
                     return $normalizedObject;
                 }
             }
         }
         return false;
     } elseif ($service == 'locatorhq') {
         $ip = isset($params['ip']) && !empty($params['ip']) ? $params['ip'] : $ip;
         $response = self::executeRequest("http://api.locatorhq.com/?user={$params['username']}&key={$params['api_key']}&ip={$ip}&format=json");
         if (!empty($response)) {
             $responseData = json_decode($response);
             if (is_object($responseData)) {
                 $normalizedObject = new stdClass();
                 $normalizedObject->country_code = strtolower($responseData->countryCode);
                 $normalizedObject->country_name = $responseData->countryName;
                 $normalizedObject->lat = $responseData->latitude;
                 $normalizedObject->lon = $responseData->longitude;
                 $normalizedObject->city = $responseData->city . ($responseData->region != '' ? ', ' . $responseData->region : '');
                 return $normalizedObject;
             }
             return false;
         }
     }
     return false;
 }
 /**
  * Get the client record
  *
  * @return GeoIp2\Model\Country
  */
 public function getClientRecord()
 {
     if ($this->clientRecord) {
         return $this->clientRecord;
     }
     //skip the process incase mode is not frontend or GeoIp is deactivated
     if (!$this->isGeoIpEnabled()) {
         return null;
     }
     // Get stats controller to get client ip
     $statsComponentContoller = $this->getComponent('Stats');
     if (!$statsComponentContoller) {
         return null;
     }
     //Get the country name and code by using the ipaddress through GeoIp2 library
     $countryDb = $this->getDirectory() . '/Data/GeoLite2-Country.mmdb';
     $activeLocale = \FWLanguage::getLanguageCodeById(FRONTEND_LANG_ID);
     $locale = in_array($activeLocale, $this->availableLocale) ? $activeLocale : $this->defaultLocale;
     try {
         $reader = new \GeoIp2\Database\Reader($countryDb, array($locale));
         $this->clientRecord = $reader->country($statsComponentContoller->getCounterInstance()->getClientIp());
         return $this->clientRecord;
     } catch (\Exception $e) {
         \DBG::log($e->getMessage());
         return null;
     }
 }
Example #8
0
 public function getTimeZone()
 {
     $tz = null;
     global $THISPATH;
     if (isset($this->user)) {
         if (isset($this->user->timezone)) {
             return $this->user->timezone;
         }
     }
     $geoipfile = $this->config->getValue('geoipfile', null);
     if ($geoipfile == null) {
         return $tz;
     }
     // echo "Enabled: " . var_export($geoipfile, true); exit;
     if (!class_exists('GeoIp2\\Database\\Reader')) {
         error_log("Not properly loaded GeoIP library through composer.phar.");
         return $tz;
     }
     if (!file_exists($THISPATH . $geoipfile)) {
         error_log("Cannot find configured GeoIP database :" . $THISPATH . $geoipfile);
         return $tz;
     }
     try {
         // $reader = new GeoIp2\Database\Reader($THISPATH . 'var/GeoLite2-City.mmdb');
         $reader = new GeoIp2\Database\Reader($THISPATH . $geoipfile);
         // 'var/GeoIP2-City.mmdb');
         $record = $reader->city($this->ip);
         $obj = array();
         $obj['lat'] = $record->location->latitude;
         $obj['lon'] = $record->location->longitude;
         $obj['tz'] = $record->location->timeZone;
         $tz = $obj['tz'];
     } catch (Exception $e) {
         // $tz = 'Europe/Amsterdam';
         error_log("Error looking up GeoIP for address: " . $this->ip);
     }
     return $tz;
 }
Example #9
0
 /**
  * Geolocation management.
  *
  * @param Country $defaultCountry
  *
  * @return Country|false
  */
 protected function geolocationManagement($defaultCountry)
 {
     if (!in_array($_SERVER['SERVER_NAME'], array('localhost', '127.0.0.1'))) {
         /* Check if Maxmind Database exists */
         if (@filemtime(_PS_GEOIP_DIR_ . _PS_GEOIP_CITY_FILE_)) {
             if (!isset($this->context->cookie->iso_code_country) || isset($this->context->cookie->iso_code_country) && !in_array(strtoupper($this->context->cookie->iso_code_country), explode(';', Configuration::get('PS_ALLOWED_COUNTRIES')))) {
                 $reader = new GeoIp2\Database\Reader(_PS_GEOIP_DIR_ . _PS_GEOIP_CITY_FILE_);
                 $record = $reader->city(Tools::getRemoteAddr());
                 if (is_object($record)) {
                     if (!in_array(strtoupper($record->country->isoCode), explode(';', Configuration::get('PS_ALLOWED_COUNTRIES'))) && !FrontController::isInWhitelistForGeolocation()) {
                         if (Configuration::get('PS_GEOLOCATION_BEHAVIOR') == _PS_GEOLOCATION_NO_CATALOG_) {
                             $this->restrictedCountry = Country::GEOLOC_FORBIDDEN;
                         } elseif (Configuration::get('PS_GEOLOCATION_BEHAVIOR') == _PS_GEOLOCATION_NO_ORDER_) {
                             $this->restrictedCountry = Country::GEOLOC_CATALOG_MODE;
                             $this->warning[] = sprintf($this->l('You cannot place a new order from your country (%s).'), $record->country->name);
                         }
                     } else {
                         $hasBeenSet = !isset($this->context->cookie->iso_code_country);
                         $this->context->cookie->iso_code_country = strtoupper($record->country->isoCode);
                     }
                 }
             }
             if (isset($this->context->cookie->iso_code_country) && $this->context->cookie->iso_code_country && !Validate::isLanguageIsoCode($this->context->cookie->iso_code_country)) {
                 $this->context->cookie->iso_code_country = Country::getIsoById(Configuration::get('PS_COUNTRY_DEFAULT'));
             }
             if (isset($this->context->cookie->iso_code_country) && ($idCountry = (int) Country::getByIso(strtoupper($this->context->cookie->iso_code_country)))) {
                 /* Update defaultCountry */
                 if ($defaultCountry->iso_code != $this->context->cookie->iso_code_country) {
                     $defaultCountry = new Country($idCountry);
                 }
                 if (isset($hasBeenSet) && $hasBeenSet) {
                     $this->context->cookie->id_currency = (int) ($defaultCountry->id_currency ? (int) $defaultCountry->id_currency : (int) Configuration::get('PS_CURRENCY_DEFAULT'));
                 }
                 return $defaultCountry;
             } elseif (Configuration::get('PS_GEOLOCATION_NA_BEHAVIOR') == _PS_GEOLOCATION_NO_CATALOG_ && !FrontController::isInWhitelistForGeolocation()) {
                 $this->restrictedCountry = Country::GEOLOC_FORBIDDEN;
             } elseif (Configuration::get('PS_GEOLOCATION_NA_BEHAVIOR') == _PS_GEOLOCATION_NO_ORDER_ && !FrontController::isInWhitelistForGeolocation()) {
                 $this->restrictedCountry = Country::GEOLOC_CATALOG_MODE;
                 $this->warning[] = sprintf($this->l('You cannot place a new order from your country (%s).'), isset($record->country->name) && $record->country->name ? $record->country->name : $this->l('Undefined'));
             }
         }
     }
     return false;
 }
Example #10
0
 public static function maxmindValidateFilename($filename)
 {
     // Maybe make path absolute
     if (file_exists(ABSPATH . $filename)) {
         $filename = ABSPATH . $filename;
     }
     if (!is_readable($filename)) {
         return '';
     }
     try {
         $reader = new \GeoIp2\Database\Reader($filename);
         $metadata = $reader->metadata();
         $reader->close();
     } catch (\Exception $e) {
         if (WP_DEBUG) {
             echo printf(__('Error while creating reader for "%s": %s', 'geoip-detect'), $filename, $e->getMessage());
         }
         return '';
     }
     return $filename;
 }
 public function add_geo_data($ip_string)
 {
     try {
         $reader = new \GeoIp2\Database\Reader(\Podlove\Geo_Ip::get_upload_file_path());
     } catch (\Exception $e) {
         return $this;
     }
     try {
         // geo ip lookup
         $record = $reader->city($ip_string);
         $this->lat = $record->location->latitude;
         $this->lng = $record->location->longitude;
         /**
          * Get most specific area for given record, beginning at the given area-type.
          *
          * Missing records will be created on the fly, based on data in $record.
          * 
          * @param object $record GeoIp object
          * @param string $type Area identifier. One of: city, subdivision, country, continent.
          */
         $get_area = function ($record, $type) use(&$get_area) {
             // get parent area for the given area-type
             $get_parent_area = function ($type) use($get_area, $record) {
                 switch ($type) {
                     case 'city':
                         return $get_area($record, 'subdivision');
                         break;
                     case 'subdivision':
                         return $get_area($record, 'country');
                         break;
                     case 'country':
                         return $get_area($record, 'continent');
                         break;
                     case 'continent':
                         // has no parent
                         break;
                 }
                 return null;
             };
             $subRecord = $record->{$type == 'subdivision' ? 'mostSpecificSubdivision' : $type};
             if (!$subRecord->geonameId) {
                 return $get_parent_area($type);
             }
             if ($area = GeoArea::find_one_by_property('geoname_id', $subRecord->geonameId)) {
                 return $area;
             }
             $area = new GeoArea();
             $area->geoname_id = $subRecord->geonameId;
             $area->type = $type;
             if (isset($subRecord->code)) {
                 $area->code = $subRecord->code;
             } elseif (isset($subRecord->isoCode)) {
                 $area->code = $subRecord->isoCode;
             }
             if ($area->type != 'continent') {
                 $parent_area = $get_parent_area($area->type);
                 $area->parent_id = $parent_area->id;
             }
             $area->save();
             // save name and translations
             foreach ($subRecord->names as $lang => $name) {
                 $n = new GeoAreaName();
                 $n->area_id = $area->id;
                 $n->language = $lang;
                 $n->name = $name;
                 $n->save();
             }
             return $area;
         };
         $area = $get_area($record, 'city');
         $this->geo_area_id = $area->id;
     } catch (\Exception $e) {
         // geo lookup might fail, but that's not grave
     }
     return $this;
 }
Example #12
0

// If the geo-location libraries are available, load the user's location!
if(Core::IsComponentAvailable('geographic-codes') && class_exists('GeoIp2\\Database\\Reader')){
	try{
		if(REMOTE_IP == '127.0.0.1'){
			// Load local connections up with Columbus, OH.
			// Why?  ;)
			$geocity     = 'Columbus';
			$geoprovince = 'OH';
			$geocountry  = 'US';
			$geotimezone = 'America/New_York';
			$geopostal   = '43215';
		}
		else{
			$reader = new GeoIp2\Database\Reader(ROOT_PDIR . 'components/geographic-codes/libs/maxmind-geolite-db/GeoLite2-City.mmdb');
			$profiler->record('Initialized GeoLite Database');

			$geo = $reader->cityIspOrg(REMOTE_IP);
			//$geo = $reader->cityIspOrg('67.149.214.236');
			$profiler->record('Read GeoLite Database');

			$reader->close();
			$profiler->record('Closed GeoLite Database');

			$geocity = $geo->city->name;
			// Some IP addresses do not resolve as a valid province.
			//This tends to happen with privately owned networks.
			if(isset($geo->subdivisions[0]) && $geo->subdivisions[0] !== null){
				/** @var GeoIp2\Record\Subdivision $geoprovinceobj */
				$geoprovinceobj = $geo->subdivisions[0];
Example #13
0
         echo "</pre>\n\n";
     }
     if (!empty($host)) {
         echo "<b>host</b> data:<br />\n";
         echo "<pre>";
         foreach ($host as $parse) {
             echo $parse . "\n";
         }
         echo "</pre>\n\n";
     }
 }
 //Geolocate the IP
 $latitude = NULL;
 $longitude = NULL;
 if (GEO_METHOD == 'LOCAL') {
     $maxmind = new \GeoIp2\Database\Reader(DIR_ROOT . '/include/maxmind/GeoLite2-City.mmdb');
     try {
         $geodata = $maxmind->city($ip);
         $latitude = $geodata->location->latitude;
         $longitude = $geodata->location->longitude;
     } catch (\GeoIp2\Exception\GeoIp2Exception $e) {
         echo "<br />Unable to geolocate IP using MaxMind.";
     }
 } else {
     if (GEO_METHOD == 'GEOPLUGIN') {
         $geoplugin = new geoPlugin();
         $geoplugin->locate($ip);
         $latitude = $geoplugin->latitude;
         $longitude = $geoplugin->longitude;
     }
 }
 /**
  * Handle an incoming request.
  *
  * @param  \Illuminate\Http\Request  $request
  * @param  \Closure  $next
  * @return mixed
  */
 public function handle($request, Closure $next)
 {
     // Get country code from IP address
     $reader = new \GeoIp2\Database\Reader(storage_path('geoip2/GeoLite2-Country.mmdb'));
     try {
         $record = $reader->country(Request::ip());
         $countryCode = strtolower($record->country->isoCode);
     } catch (\GeoIp2\Exception\AddressNotFoundException $e) {
         $countryCode = Config::get('locale.default');
     }
     // Get language from browser
     if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
         $languageCode = strtolower(substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2));
     }
     // Do we have this country set-up?
     $locales = Config::get('locale.locales', []);
     $redirects = Locale::getRedirects();
     if (isset($locales[$countryCode]) or isset($locales[$countryCode . '-' . $languageCode]) or isset($redirects[$countryCode])) {
         // Check to see if this is the current country, if not we need to redirect
         if (Locale::getUrlPrefix() != $countryCode . '-' . $languageCode and Locale::getUrlPrefix() != $countryCode or !Request::segment(1)) {
             // Find the best locale based upon country and language
             if (isset($locales[$countryCode . '-' . $languageCode])) {
                 return redirect(Locale::getAlternateUrl($countryCode . '-' . $languageCode));
             }
             if (isset($locales[$countryCode])) {
                 return redirect(Locale::getAlternateUrl($countryCode));
             }
             if (isset($redirects[$countryCode])) {
                 return redirect(Locale::getAlternateUrl($redirects[$countryCode]));
             }
         }
     }
     return redirect(Locale::getAlternateUrl(Config::get('locale.default')));
 }