/** * 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; }
/** * @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); }
/** * Set the client IP to analyse * * @param $ip * * @return IVisitorInfo */ public function setClientIp($ip) { $this->_ip = $ip; try { $this->_record = $this->_reader->city($ip); } catch (\Exception $e) { $this->_record = null; } }
/** * 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 []; }
/** * @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 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(); }
/** * 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; } }
/** * * @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()); } } }
/** * 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'; } }
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; } }
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 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; }
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 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; } }
/** * 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; }
public function startTest($scopeId = 0) { $geoDbFile = \Yii::getAlias("@common/data/geo-ip/" . \console\controllers\GeoipController::FILE_NAME); if (!is_file($geoDbFile)) { throw new Exception('IDB file not found: ' . $geoDbFile); } $reader = new Reader(\Yii::getAlias("@common/data/geo-ip/" . \console\controllers\GeoipController::FILE_NAME)); $this->result = ['badProxy' => [], 'badScopes' => [], 'resume' => 'All proxies are correct']; $proxies = Proxies::find(); if ($scopeId != 0) { $proxies = $proxies->where(['scope_id' => $scopeId]); } $proxies = $proxies->all(); foreach ($proxies as $proxy) { $record = $reader->city($proxy->host); $this->_putRowToResult($proxy, $record->country->isoCode); } if (!empty($this->result['badProxy'])) { $this->result['resume'] = 'Total Diff Proxies: ' . count($this->result['badProxy']); } return; }
public static function getClientLocation($ip_address) { $location = ''; if (empty($ip_address)) { return $location; } $geo = new Reader(base_path() . '/database/GeoLite2-City.mmdb'); $record = $geo->city($ip_address); if (!empty($record)) { $location = array('ip' => $ip_address, 'country_code' => $record->country->isoCode, 'country' => $record->country->name, 'city' => $record->city->name, 'postal' => $record->postal->code, 'latitude' => $record->location->latitude, 'longitude' => $record->location->longitude); } /* $url = 'http://api.stylar.com/geoip/index.php?ip='.$ip_address; $crawler = \Seeties\Utils::webCrawler($url); $response = \Seeties\Utils::jsonDecodeToArray($crawler['content']); if ($crawler['http_code'] != 200 || empty($response)) { return $location; } $location = $response; */ return $location; }
public function processIP($ip) { $status = null; $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'] = self::ipVersion($ip); if ($request['type'] == 'IPv4') { $isPrivate = self::isPrivateIP($ip); if ($isPrivate) { $status = self::setStatus('IP_ADDRESS_RESERVED', null, $status); return json_encode(array('status' => $status)); } } $reader = new Reader($path); $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); } $pathISP = Config::inst()->get('IPInfoCache', 'GeoPathISP'); if (!$pathISP) { $pathISP = $this->defaultPathISP; } if (!file_exists($pathISP)) { user_error('Error loading Geo ISP database', E_USER_ERROR); } $reader = new Reader($pathISP); $record = $reader->isp($ip); if ($record) { $result['organization']['name'] = $record->organization; $result['organization']['isp'] = $record->isp; } if ($status) { $statusArray['code'] = self::setStatus(null, null, $status); $statusArray['message'] = self::getStatusMessage($status); // do not cache a failure $this->json = json_encode(array('request' => $request, 'status' => $statusArray, 'result' => array('maxmind-geoip2' => $result))); } else { // return cached success message $statusArray['code'] = self::setStatus('SUCCESS_CACHED', null, null); $statusArray['message'] = self::getStatusMessage($statusArray['code']); $this->json = json_encode(array('request' => $request, 'status' => $statusArray, 'result' => array('maxmind-geoip2' => $result))); } // we write a different json object with a cached status to the DB $statusArray['code'] = self::setStatus('SUCCESS', null, $status); $statusArray['message'] = self::getStatusMessage($statusArray['code']); $dbJson = json_encode(array('request' => $request, 'status' => $statusArray, 'result' => array('maxmind-geoip2' => $result))); return $dbJson; }
$row['duration'] = intval($row['duration']); } if (isset($row['traffic'])) { $row['traffic'] = intval($row['traffic']); } if (isset($row['service'])) { $row['service'] = intval($row['service']); } if (isset($row['protocol'])) { $row['protocol'] = intval($row['protocol']); } $data[] = $row; } $now = time(); foreach ($data as $index => $row) { $data[$index]['started_at'] = date('c', $row['started_at']); $data[$index]['ended_at'] = date('c', $row['ended_at']); $record = $reader->city($row['client_address']); $data[$index]['location'] = $record->city->names['zh-CN'] ?: $record->city->name ?: $record->mostSpecificSubdivision->names['zh-CN'] ?: $record->mostSpecificSubdivision->name ?: $record->country->names['zh-CN'] ?: $record->country->names['zh-CN']; } /*usort($data, function ($a, $b) { if ($a['started_at'] < $b['started_at']) { return -1; } else if ($a['started_at'] = $b['started_at']) { return 0; } else { return 1; } });*/ header('Content-Type: application/json; charset=UTF8'); echo json_encode($data);
use GeoIp2\Database\Reader; $geoDbFile = realpath("../../../../../website/var/config/GeoLite2-City.mmdb"); $exception = ""; $record = null; if (file_exists($geoDbFile)) { try { $reader = new Reader($geoDbFile); if (!empty($_SERVER['HTTP_CLIENT_IP'])) { $ip = $_SERVER['HTTP_CLIENT_IP']; } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; } else { $ip = $_SERVER['REMOTE_ADDR']; } if (!ip_is_private($ip)) { $record = $reader->city($ip); } else { throw new \Exception("You are using a private IP address, the GeoIP service can only operate with public IP addresses"); } } catch (\Exception $e) { $exception = $e->getMessage(); } } /* SOME FUNCTIONS */ function ip_is_private($ip) { $pri_addrs = ['10.0.0.0|10.255.255.255', '172.16.0.0|172.31.255.255', '192.168.0.0|192.168.255.255', '169.254.0.0|169.254.255.255', '127.0.0.0|127.255.255.255']; $long_ip = ip2long($ip); if ($long_ip != -1) { foreach ($pri_addrs as $pri_addr) { list($start, $end) = explode('|', $pri_addr);
/** * @expectedException InvalidArgumentException * @expectedExceptionMessage is not a valid IP address */ public function testInvalidAddress() { $reader = new Reader('maxmind-db/test-data/GeoIP2-City-Test.mmdb'); $reader->city('invalid'); $reader->close(); }
$referrer = isset($_GET['r']) ? $_GET['r'] : "none"; // page from which visitor came $origin = isset($_GET['o']) ? $_GET['o'] : "-"; // origin of the dislike (fb only) // connect $logdb = new PDO("sqlite:" . $dbfolder . $dbname); $ipReader = new Reader($dbGeofolder . '/data/GeoLite2-City.mmdb'); // check if database file exists first // first shot, create the tables // init if (!file_exists($dbfolder . $dbname)) { $logdb->exec("CREATE TABLE hits(id INTEGER PRIMARY KEY, counter INTEGER)"); $logdb->exec("CREATE TABLE tracker (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n browser TEXT default '',\n ip varchar(15) NOT NULL default '',\n d DATETIME NOT NULL default CURRENT_TIMESTAMP,\n referrer TEXT NOT NULL default '' ,\n iso_code TEXT default '',\n country_name TEXT default '',\n city_name TEXT default '',\n latitude TEXT default '0',\n longitude TEXT default '0',\n origin TEXT default '-')"); $logdb->exec("INSERT INTO hits(id, counter) VALUES (1, 0)"); } // get the geo-data $record = $ipReader->city($ip); $iso_code = isset($record->country) ? $record->country->isoCode : '?'; $country_name = isset($record->country) ? $record->country->name : '?'; $city_name = isset($record->city) ? $record->city->name : '?'; $latitude = isset($record->location) ? $record->location->latitude : '0'; $longitude = isset($record->location) ? $record->location->longitude : '0'; // and boom ... $logdb->exec("UPDATE hits SET counter=counter+1 WHERE id=1"); // track it! $logdb->exec("INSERT INTO tracker(browser, ip, referrer, iso_code, country_name, city_name, latitude, longitude, origin)\n VALUES ('{$browser}','{$ip}', '{$referrer}', '{$iso_code}', '{$country_name}', '{$city_name}', '{$latitude}', '{$longitude}', '{$origin}')\n "); // close connection $logdb = null; $ipReader->close(); // fake image echo file_get_contents(dirname(__FILE__) . '/blank.gif');
/** * @param $ip * * @return mixed */ public function city($ip) { return $this->readerCity->city($ip); }
/** * Get Geo Ip Data Information. * * @access protected * @param string $sIpAddress Specify an IP address. If NULL, it will address the current customer who visits the site. Default: NULL * @return object */ protected static function get($sIpAddress = null) { $sIpAddr = !empty($sIpAddress) ? $sIpAddress : Ip::get(); if ($sIpAddr == '127.0.0.1') { // Set a valid IP address, if it's the invalid local one $sIpAddr = '128.101.101.101'; } $oReader = new Reader(__DIR__ . '/GeoLite2-City.mmdb'); return @$oReader->city($sIpAddr); }
/** * Get time zone thanks to the IP Address * * @return string with time zone */ public function getTimeZoneByIpAddress() { try { $reader = new Reader($_SERVER['DOCUMENT_ROOT'] . '/GeoLite2-City.mmdb'); $record = $reader->city($this->ipAddress); return $record->location->timeZone; } catch (\Exception $e) { return $e->getMessage(); } }