/** * Inserts the access log information in * the database * * @param array $alogs Access Log lines * @param $fromServer array The sender of these access logs * * @throws \Kassner\LogParser\FormatException */ public function insertAccessLogging(array $alogs, $fromServer, $parseString) { try { if (!(count($alogs) > 0)) { return; } $parser = new \Kassner\LogParser\LogParser(); $parser->setFormat($parseString); $toBeInserted = []; foreach ($alogs as $line) { $userSpec = $parser->parse($line); if ($userSpec->host === '::1') { continue; } $userSpec->device = parse_user_agent($userSpec->HeaderUserAgent); $city = new Reader(database_path() . '/GeoLite2-City.mmdb'); $geoRecord = $city->city($userSpec->host); $userSpec->fromServer = $fromServer; $userSpec->location = ['city' => $geoRecord->city->name, 'country' => $geoRecord->country->name]; $userSpec->createdAt = time(); $toBeInserted[] = $userSpec; } $this->mongoCollectionForAccess->batchInsert($toBeInserted); } catch (\Exception $e) { error_log(print_r($e, true)); } }
/** * Retrieves the location from the driver MaxMind and returns a location object. * * @param string $ip * * @return Location */ public function get($ip) { $location = new Location(); $settings = $this->config->get('location' . $this->instance->getConfigSeparator() . 'drivers.MaxMind.configuration'); try { if ($settings['web_service']) { $maxmind = new Client($settings['user_id'], $settings['license_key']); } else { $path = app_path('database/maxmind/GeoLite2-City.mmdb'); /* * Laravel 5 compatibility */ if ($this->instance->getConfigSeparator() === '.') { $path = base_path('database/maxmind/GeoLite2-City.mmdb'); } $maxmind = new Reader($path); } $record = $maxmind->city($ip); $location->ip = $ip; $location->isoCode = $record->country->isoCode; $location->countryName = $record->country->name; $location->cityName = $record->city->name; $location->postalCode = $record->postal->code; $location->latitude = $record->location->latitude; $location->driver = get_class($this); } catch (\Exception $e) { $location->error = true; } return $location; }
function addLanguage() { require_once '/home1/typograf/php/Net/vendor/autoload.php'; $reader = new Reader('/home1/typograf/php/Net/GeoLite2-Country.mmdb'); $ip_addr = $_SERVER['REMOTE_ADDR']; //$ip_addr = '157.7.205.139'; $langJa = ''; $referer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : NULL; $httpQuery = $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]; if (!strstr($httpQuery, "lang")) { if (!strstr($httpQuery, "?")) { $langJa = "?lang=ja"; } else { $langJa = getUrlquery(array("lang" => "ja")); $langJa = htmlspecialchars_decode($langJa); } } $record = $reader->country($ip_addr); $country = $record->country->name; //Japan or Germany // if access from Japan and the refere isn't typograffit and no language parameter // if ($country == "Japan" && !strstr($referer, "typograffit") && !strstr($httpQuery, "lang")) { header('Location: ' . $langJa); exit; } }
/** * Show the form for creating a new resource. * * @return Response */ public function create() { $validator = Validator::make(Input::get(), array('firstname' => 'required|max:20', 'lastname' => 'required|max:20', 'password' => 'required|min:8|max:30', 'email' => 'required|email|unique:users|max:40')); if ($validator->fails()) { $messages = array(); foreach ($validator->messages()->all() as $message) { array_push($messages, $message); } return json_encode($messages); } else { $user = new User(); $code = str_random(128); $user->firstname = Input::get('firstname'); $user->lastname = Input::get('lastname'); $user->activationCode = $code; try { $reader = new Reader(base_path() . '/GeoLite2-City.mmdb'); $record = $reader->city($_SERVER['REMOTE_ADDR']); $user->address = json_encode(array('street' => '', 'province' => $record->mostSpecificSubdivision->name, 'city' => $record->city->name, 'country' => $record->country->isoCode)); } catch (Exception $e) { } $user->email = Input::get('email'); $user->password = Hash::make(Input::get('password')); $user->save(); Mail::send('emails.auth.welcome', array('name' => Input::get('firstname'), 'code' => $code), function ($message) { $message->to(Input::get('email'), Input::get('firstname') . ' ' . Input::get('lastname'))->subject('Welcome ' . Input::get('firstname') . '!'); }); return 'success'; } }
/** * * @param string $ip * @param array $options * @return \GeoServices\GeoObject * @throws GeoException */ public function lookup($ip, $options = array()) { if (!filter_var($ip, FILTER_VALIDATE_IP)) { throw new GeoException('Invalid IP address is set'); } $this->ip = $ip; $parts = explode('.', $options[$this->method . 'db']); $ext = is_array($parts) ? end($parts) : ''; if (!isset($options[$this->method . 'db']) || !is_file($options[$this->method . 'db']) || !is_readable($options[$this->method . 'db']) || strtolower($ext) != 'mmdb') { throw new GeoException('db file is invalid for ' . $this->method); } $geo = new Reader($options[$this->method . 'db']); try { $data = $geo->city($ip); if (!$data) { throw new GeoException('Failed to get geoip data from ' . $this->method); } return $this->formalize($data); } catch (\GeoIp2\Exception\AddressNotFoundException $ex) { throw new GeoException($ex->getMessage()); } catch (\GeoIp2\Exception\AuthenticationException $ex) { throw new GeoException($ex->getMessage()); } catch (\Exception $ex) { throw new GeoException($ex->getMessage()); } }
/** * Extract the IP from the local database. */ protected function lookup() { try { $reader = new Reader($this->getLocalDataStoreFilepath()); $record = $reader->city($this->ip); if (isset($record->subdivisions[0])) { if (count($record->subdivisions) > 1) { // Use the first listed as the country and second as state // UK -> England -> Winchester $this->country = $record->subdivisions[0]->name; $this->region = $record->subdivisions[1]->name; } else { $this->region = $record->subdivisions[0]->name; } } $this->city = $record->city->name; $this->country = $record->country->name; $this->latitude = $record->location->latitude; $this->longitude = $record->location->longitude; $this->timezone = $record->location->timeZone; $this->zipcode = $record->location->postalCode; } catch (\Exception $exception) { if ($this->logger) { $this->logger->warn('IP LOOKUP: ' . $exception->getMessage()); } } }
/** * Perform command. */ public function perform() { try { $entry = []; $parser = new \Kassner\LogParser\LogParser(); $parser->setFormat('%h %l %u %t "%r" %>s %O "%{Referer}i" \\"%{User-Agent}i"'); $lines = file('/var/log/apache2/access.log', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); foreach ($lines as &$line) { $userSpec = $parser->parse($line); $userSpec->device = parse_user_agent($userSpec->HeaderUserAgent); $city = new Reader(__DIR__ . '/../Database/GeoLite2-City.mmdb'); $country = new Reader(__DIR__ . '/../Database/GeoLite2-Country.mmdb'); $userSpec->location = ['city' => $city->city($userSpec->host)->city->name, 'country' => $country->country($userSpec->host)->country->name]; $entry[] = $userSpec; } file_put_contents('/var/log/apache2/access.log', ''); } catch (\Exception $e) { file_put_contents('/var/log/apache2/access.log', ''); } if (count($entry) > 0) { AccessReport::odmCollection()->batchInsert($entry); print "wrote " . count($entry) . " records"; } else { print 0; } }
function wp_statistics_populate_geoip_info() { global $wpdb; // Find all rows in the table that currently don't have GeoIP info or have an unknown ('000') location. $result = $wpdb->get_results("SELECT id,ip FROM `{$wpdb->prefix}statistics_visitor` WHERE location = '' or location = '000' or location IS NULL"); // Try create a new reader instance. try { $upload_dir = wp_upload_dir(); $reader = new Reader($upload_dir['basedir'] . '/wp-statistics/GeoLite2-Country.mmdb'); } catch (Exception $e) { return "<div class='updated settings-error'><p><strong>" . __('Unable to load the GeoIP database, make sure you have downloaded it in the settings page.', 'wp_statistics') . "</strong></p></div>"; } $count = 0; // Loop through all the missing rows and update them if we find a locaiton for them. foreach ($result as $item) { $count++; // If the IP address is only a hash, don't bother updating the record. if (substr($item->ip, 0, 6) != '#hash#') { try { $record = $reader->country($item->ip); $location = $record->country->isoCode; if ($location == "") { $location = "000"; } } catch (Exception $e) { $location = "000"; } // Update the row in the database. $wpdb->update($wpdb->prefix . "statistics_visitor", array('location' => $location), array('id' => $item->id)); } } return "<div class='updated settings-error'><p><strong>" . sprintf(__('Updated %s GeoIP records in the visitors database.', 'wp_statistics'), $count) . "</strong></p></div>"; }
/** * @param string $clientIp * @return \Aijko\AijkoGeoip\Domain\Model\Client|NULL */ public function findByClientIp($clientIp) { $record = $this->reader->city($clientIp); if (NULL === $record) { return NULL; } return $this->buildClientObject($record, $clientIp); }
public function processIP($ip) { $status = null; $result = array(); $path = Config::inst()->get('IPInfoCache', 'GeoPath'); if (!$path) { $path = $this->defaultPath; } if (!file_exists($path)) { user_error('Error loading Geo database', E_USER_ERROR); } $request['ip'] = $ip; $request['type'] = MarketoRegionalDriver::ipVersion($ip); if ($request['type'] == 'IPv4') { $isPrivate = MarketoRegionalDriver::isPrivateIP($ip); if ($isPrivate) { $status = self::setStatus('IP_ADDRESS_RESERVED', null, $status); return json_encode(array('status' => $status)); } } $reader = new Reader('/usr/share/GeoIP/GeoLite2-City.mmdb'); $record = $reader->city($ip); $countryCode = null; try { $result['location']['continent_code'] = $record->continent->code; $result['location']['continent_names'] = $record->continent->names; $countryCode = $record->country->isoCode; $result['location']['country_code'] = $countryCode; $result['location']['country_names'] = $record->country->names; $result['location']['postal_code'] = $record->postal->code; $result['location']['city_names'] = $record->city->names; $result['location']['latitude'] = $record->location->latitude; $result['location']['longitude'] = $record->location->longitude; $result['location']['time_zone'] = $record->location->timeZone; } catch (Exception $e) { $status = self::setStatus('GEOIP_EXCEPTION', $e, $status); } $geoRegion = null; if ($countryCode) { $geoRegion = GeoRegion::get()->filter('RegionCode', $countryCode)->first(); if ($geoRegion && $geoRegion->exists()) { $result['location']['marketo_region_name'] = $geoRegion->Name; $result['location']['marketo_region_code'] = $geoRegion->RegionCode; $result['location']['marketo_region_time_zone'] = $geoRegion->TimeZone; } } if ($status) { // do not cache a failure return json_encode(array('request' => $request, 'status' => $status, 'result' => $result)); } else { // return cached success message $status = self::setStatus('SUCCESS_CACHED', null, $status); $this->json = json_encode(array('request' => $request, 'status' => $status, 'result' => $result)); } $dbStatus = self::setStatus('SUCCESS', null, null); $dbJson = json_encode(array('request' => $request, 'status' => $dbStatus, 'result' => $result)); return $dbJson; }
private function _populateClientsCurrentLocation() { if ($this->clientIP) { $DBReader = new GeoDBReader(__DIR__ . '/data/' . self::GEO_DB_FILE); $record = $DBReader->city($this->clientIP); //todo construct the string in a better way plz $this->clientCurrentLocation = $record->postal->code . ', ' . $record->country->isoCode; } }
/** * Get the raw GeoIP info using Maxmind. * * @param string $ip * * @return mixed */ public function getRaw($ip) { try { return $this->maxmind->city($ip); } catch (AddressNotFoundException $e) { // ignore } return []; }
public function __construct($ip) { $geoIpFile = Yii::getAlias('@app/components/analytics/enricher/GeoIP/GeoLite2-City.mmdb'); // Check if GeoIP file exists and is readable if (is_readable($geoIpFile)) { $reader = new Reader($geoIpFile); $this->record = $reader->city($ip); } }
/** * @return Report\Entities\User * @throws \MaxMind\Db\Reader\InvalidDatabaseException if the database * is corrupt or invalid */ public function newUser() { $user = new User(); $user->ip_address = '201.141.89.52'; $geoIp = new GeoIp(app_path('database/GeoLite2-City.mmdb')); $record = $geoIp->city($user->ip_address); $user->country = $record->country->names['es']; $user->city = $record->mostSpecificSubdivision->names['es']; return $user; }
/** * Queries city-db with given ip. * * @param string $ip * @return bool|\GeoIp2\Model\City */ public function getRecord($ip) { $reader = new Reader($this->app->pathCityDb); try { $record = $reader->city($ip); } catch (AddressNotFoundException $e) { return false; } return $record; }
public function testIsp() { $reader = new Reader('maxmind-db/test-data/GeoIP2-ISP-Test.mmdb'); $ipAddress = '1.128.0.0'; $record = $reader->isp($ipAddress); $this->assertEquals(1221, $record->autonomousSystemNumber); $this->assertEquals('Telstra Pty Ltd', $record->autonomousSystemOrganization); $this->assertEquals('Telstra Internet', $record->isp); $this->assertEquals('Telstra Internet', $record->organization); $this->assertEquals($ipAddress, $record->ipAddress); $reader->close(); }
function get_country_from_ip($ip) { $isoCode = ''; try { $reader = new Reader(TFLS_GEOIP_DB); $record = $reader->country($ip); $isoCode = $record->country->isoCode; } catch (Exception $e) { error_log($e->getMessage()); } return $isoCode; }
public static function parse($ip) { $reader = new Reader(storage_path("geoip/city.mmdb")); $address = ""; try { $record = $reader->city($ip); $address = $record->country->name . "-" . $record->city->name; } catch (AddressNotFoundException $e) { $address = "无记录"; } return $address; }
/** * @param string $properties * @param string $ip */ public function getLocationProperty($properties, $ip) { if (!$this->isValidIp($ip)) { throw new InvalidIpException(); } $location = array_shift($properties); $property = array_shift($properties); if (!$location || !$property) { throw new MissingPropertiesException(); } $record = $this->reader->city($ip); return $record->{$location}->{$property}; }
public function getLocation($ipAddress = '') { if (in_array($ipAddress, ['127.0.0.1'])) { return; } if (!file_exists(APP_DIR . '/config/GeoLite2-City.mmdb')) { return; } $reader = new Reader(APP_DIR . '/config/GeoLite2-City.mmdb'); $record = $reader->city($ipAddress); $location = $record->country->names['zh-CN'] . ' ' . $record->mostSpecificSubdivision->names['zh-CN'] . ' ' . $record->city->names['zh-CN']; $location .= ' ' . $record->location->latitude . ' ' . $record->location->longitude; return $location; }
public function __construct() { // Call the parent constructor (WP_Statistics::__constructor). parent::__construct(); // We may have set the location based on a private IP address in the hits class, if so, don't bother looking it up again. if ($this->location == '000') { // Now get the location information from the MaxMind database. try { // Get the WordPress upload directory information, which is where we have stored the MaxMind database. $upload_dir = wp_upload_dir(); // Create a new Reader and point it to the database. $reader = new Reader($upload_dir['basedir'] . '/wp-statistics/GeoLite2-Country.mmdb'); // Look up the IP address $record = $reader->country($this->ip); // Get the location. $location = $record->country->isoCode; // MaxMind returns a blank for location if it can't find it, but we want to use 000 so replace it. if ($location == "") { $location = "000"; } } catch (Exception $e) { $location = "000"; } // Store the location in the protected $location variable from the parent class. $this->location = $location; } // Check to see if we are excluded by the GeoIP rules. if (!$this->exclusion_match) { // Grab the excluded/included countries lists, force the country codes to be in upper case to match what the GeoIP code uses. $excluded_countries = explode("\n", strtoupper($this->get_option('excluded_countries'))); $included_countries_string = trim(strtoupper($this->get_option('included_countries'))); // We need to be really sure this isn't an empty string or explode will return an array with one entry instead of none. if ($included_countries_string == '') { $included_countries = array(); } else { $included_countries = explode("\n", $included_countries_string); } // Check to see if the current location is in the excluded countries list. if (in_array($this->location, $excluded_countries)) { $this->exclusion_match = TRUE; $this->exclusion_reason = "geoip"; } else { if (!in_array($this->location, $included_countries) && count($included_countries) > 0) { $this->exclusion_match = TRUE; $this->exclusion_reason = "geoip"; } } } }
public function index() { $period = Period::current()->select('id', 'start_at', 'finish_at')->first(); try { $reader = new Reader(storage_path('app/GeoLite2-Country.mmdb')); $record = $reader->country($request->ip()); $country = $record->country->isoCode; } catch (Exception $e) { $country = 'OM'; } if ($country == 'OM' && $period && app()->environment() !== 'local' && !in_array(app()->ip(), ['188.135.49.50'])) { $period = new StdClass(); } return response()->json($period, 200, [], JSON_NUMERIC_CHECK); }
public function run() { // Permite obtener campos de forma arbitraria. $faker = Faker::create(); $departament = Departament::all()->lists('id'); $category = Category::all()->lists('id'); $type = 'client'; // Permitre identificar origen de la solicitud. $geoIp = new GeoIp(app_path('database/GeoLite2-City.mmdb')); foreach (range(1, 100) as $index) { if ($index > 90) { $type = 'technical'; } $ip = $faker->ipv4; try { $record = $geoIp->city($ip); $user = new User(); $user->full_name = $faker->name; $user->username = $faker->numberBetween($min = 2011000000, $max = 2015000000); $user->email = $faker->email; $user->password = '******'; $user->category_id = $faker->randomElement($departament); $user->departament_id = $faker->randomElement($category); $user->type = $type; $user->ip_address = $ip; $user->country = $record->country->names['es']; $user->city = $record->mostSpecificSubdivision->names['es']; $user->authorized = $faker->randomElement([true, false]); $user->save(); } catch (Exception $e) { echo "undefined location for ip: " . $ip . "\n"; } } $user = new User(); $user->full_name = 'Cristian Gerardo Jaramillo Cruz'; $user->username = '******'; $user->email = '*****@*****.**'; $user->password = '******'; $user->category_id = '5'; $user->departament_id = '7'; $user->type = 'admin'; $user->authorized = true; $user->ip_address = '201.141.89.52'; $record = $geoIp->city($user->ip_address); $user->country = $record->country->names['es']; $user->city = $record->mostSpecificSubdivision->names['es']; $user->save(); }
public function index($tz = null) { if (!$tz) { $ip = '101.165.108.235'; $path = plugin_dir_path(__FILE__) . '../GeoLite2-City.mmdb'; $reader = new Reader($path); $record = $reader->city($ip); $timezone = $record->location->timeZone; if (!$timezone) { $timezone = 'Australia/Brisbane'; } return $timezone; } if ($tz) { return $tz; } }
public static function getCountryCodeByIP() { $country['code'] = ''; $country['name'] = ''; $country['id'] = ''; $ip = \Request::getClientIp(); if (!empty($ip)) { $reader = new Reader(app_path() . '/storage/external/GeoLite2-Country.mmdb'); $record = $reader->country('103.7.80.62'); $country = array(); $country['code'] = $record->country->isoCode; $country['name'] = $record->country->name; $dbCountry = CountryQuery::create()->findOneByCountryCode($country['code']); $country['id'] = $dbCountry->getId(); } return $country; }
public function __destruct() { try { if ($this->_reader instanceof Reader) { $this->_reader->close(); } } catch (\Exception $e) { } }
public function blockCountryComment(Result $result) { /** @var Comment $obj */ $obj = $result->getObject(); // globally allowed and disallowed $allow = $this->preferences->get('foolfuuka.plugins.geoip_region_lock.allow_comment'); $disallow = $this->preferences->get('foolfuuka.plugins.geoip_region_lock.disallow_comment'); $board_allow = trim($obj->radix->getValue('plugin_geo_ip_region_lock_allow_comment'), " ,"); $board_disallow = trim($obj->radix->getValue('plugin_geo_ip_region_lock_disallow_comment'), " ,"); // allow board settings to override global if ($board_allow || $board_disallow) { $allow = $board_allow; $disallow = $board_disallow; } if ($allow || $disallow) { $ip = Inet::dtop($obj->comment->poster_ip); $reader = new Reader($this->preferences->get('foolframe.maxmind.geoip2_db_path')); $country = null; try { $record = $reader->country($ip); $country = strtolower($record->country->isoCode); } catch (AddressNotFoundException $e) { $country = 'xx'; } if ($allow) { $allow = array_filter(explode(',', $allow)); foreach ($allow as $al) { if (strtolower(trim($al)) === $country) { return; } } throw new CommentSendingException(_i('Your nation has been blocked from posting.') . '<br/><br/>This product includes GeoLite2 data created by MaxMind, available from http://www.maxmind.com/'); } if ($disallow) { $disallow = array_filter(explode(',', $disallow)); foreach ($disallow as $disal) { if (strtolower(trim($disal)) == $country) { throw new CommentSendingException(_i('Your nation has been blocked from posting.') . '<br/><br/>This product includes GeoLite2 data created by MaxMind, available from http://www.maxmind.com/'); } } } } }
/** * Retrieve location data from database. * * @param float $ip * * @return object */ public function getLocation($ip = null) { // If no IP given then get client IP if (!$ip) { $ip = $this->getClientIp(); } // if were not in production and ip is 127.0.0.1 use default record if ($this->environment != 'production' && $ip == '127.0.0.1') { return $record = $this->default_record; } else { // Check IP to make sure it is valid if (!$this->checkIp($ip)) { throw new \Exception('IP Address is either not a valid IPv4/IPv6 address or falls within the private or reserved ranges'); } $reader = new Reader(storage_path('app/geoip.mmdb')); $record = $reader->city($ip); } return $record; }
/** * Method checks country code by native php function or search in db file if native function doesn't exist * @author Dmitry Fedorov <*****@*****.**> * @version 1.0.2 on 2015-08-05 * @return string|null */ public static function getCountryCode() { $country = null; if (function_exists('geoip_country_code_by_name')) { // trick for local using (@author Constantine <*****@*****.**>) $userIp = \Yii::$app->getRequest()->getUserIP(); if ($userIp == '127.0.0.1' || $userIp == '::1') { $userIp = self::DEFAULT_USER_IP; } $country = geoip_country_code_by_name($userIp); } else { $geoReader = new Reader(\Yii::getAlias('@geolocation/data/GeoLite2-Country.mmdb')); try { $country = $geoReader->country(\Yii::$app->getRequest()->getUserIP()); $country = $country->country->isoCode; } catch (AddressNotFoundException $e) { \Yii::getLogger()->log($e->getMessage(), Logger::LEVEL_WARNING); } } return $country; }
/** * Returns the 2-digit Country Code matching a given IP address. * * @param string ip_address The IP address for which to retrieve the Country Code. * @return string|bool A Country Code on success, or False on failure. */ public function get_country_code($ip_address) { //$ip_address = @gethostbyname($host); $country_code = ''; // IP address must be either an IPv4 or an IPv6 if (filter_var($ip_address, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false && filter_var($ip_address, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) === false) { $this->errors[] = sprintf(__('Method IP2Location::get_country_code() expects a valid IPv4 or IPv6 ' . 'address (it will not work with host names). "%s" was passed, which is ' . 'not a valid address.', $this->text_domain), $ip_address); $country_code = false; } if ($country_code !== false) { try { // Create the Reader object, which should be reused across lookups. $reader = new Reader(self::geoip_db_file()); $record = $reader->country($ip_address); $country_code = $record->country->isoCode; } catch (\Exception $e) { $this->errors[] = sprintf(__('Error(s) occurred while retrieving Geolocation information ' . 'for IP Address "%s". Error: %s.', $this->text_domain), $ip_address, $e->getMessage()); $country_code = false; } } return apply_filters('wc_aelia_ip2location_country_code', $country_code, $ip_address); }