updated-packages

This commit is contained in:
RafficMohammed
2023-01-08 00:13:22 +05:30
parent 3ff7df7487
commit da241bacb6
12659 changed files with 563377 additions and 510538 deletions

View File

@@ -1,5 +0,0 @@
/vendor
composer.phar
composer.lock
.DS_Store
.idea/*

View File

@@ -1,16 +0,0 @@
language: php
php:
- 5.5
- 5.6
- 7.0
matrix:
allow_failures:
- php: 7.0
before_script:
- curl -s http://getcomposer.org/installer | php
- php composer.phar install --dev
script: phpunit

View File

@@ -1,4 +1,4 @@
# GeoIP for Laravel 5
# GeoIP for Laravel
[![Build Status](https://travis-ci.org/Torann/laravel-geoip.svg?branch=master)](https://travis-ci.org/Torann/laravel-geoip)
[![Latest Stable Version](https://poser.pugx.org/torann/geoip/v/stable.png)](https://packagist.org/packages/torann/geoip)
@@ -10,8 +10,8 @@
Determine the geographical location and currency of website visitors based on their IP addresses.
- [GeoIP for Laravel 5 on Packagist](https://packagist.org/packages/torann/geoip)
- [GeoIP for Laravel 5 on GitHub](https://github.com/Torann/laravel-geoip)
- [GeoIP for Laravel on Packagist](https://packagist.org/packages/torann/geoip)
- [GeoIP for Laravel on GitHub](https://github.com/Torann/laravel-geoip)
- [Upgrade Guides](http://lyften.com/projects/laravel-geoip/doc/upgrade.html)
## Official Documentation
@@ -22,51 +22,15 @@ Documentation for the package can be found on [Lyften.com](http://lyften.com/pro
For Laravel 4 Installation see [version 0.1.1](https://github.com/Torann/laravel-geoip/tree/0.1.1)
## Change Log
#### v1.0.2
- Support double IP addresses #25
#### v1.0.1
- Fix bug #60
#### v1.0.0
- Major code refactoring and cleanup
- Add currency support
- Add Location object
- Add cache drivers
- Add `state_name` to `$location` array #46
- Set locales in config #45
- Raise PHP requirement to 5.5
- Fix file structure to adher to PSR-4 file structure. #40
- Support custom Geo IP services
- Added ip-api.com service (Thanks to [nikkiii](https://github.com/nikkiii))
#### v0.2.1
- Add database_path to config
- Add update_url to config
- Add GeoIP database update command "php artisan geoip:update"
- Add some test
- Format code
#### v0.2.0
- Update to Laravel 5
- Support IPv6
- Log address not found exceptions
- Supports a custom default location
## Contributions
Many people have contributed to project since its inception.
Thanks to:
- [Dwight Watson](https://github.com/dwightwatson)
- [nikkiii](https://github.com/nikkiii)
- [jeffhennis](https://github.com/jeffhennis)
- [max-kovpak](https://github.com/max-kovpak)
- [dotpack](https://github.com/dotpack)
- [dotpack](https://github.com/dotpack)
- [Jess Archer](https://github.com/jessarcher)

View File

@@ -19,18 +19,19 @@
}
],
"require": {
"php": ">=5.5.9",
"illuminate/support": "5.0.* || 5.1.* || 5.2.* || 5.3.* || 5.4.* || 5.5.* || 5.6.* || 5.7.*",
"illuminate/console": "5.0.* || 5.1.* || 5.2.* || 5.3.* || 5.4.* || 5.5.* || 5.6.* || 5.7.*"
"php": "^7.1",
"illuminate/support": "~5.5|^6.0",
"illuminate/console": "~5.5|^6.0"
},
"suggest": {
"geoip2/geoip2": "Required to use the MaxMind database or web service with GeoIP (~2.1).",
"monolog/monolog": "Allows for storing location not found errors to the log"
},
"require-dev": {
"phpunit/phpunit": "^4.8",
"phpunit/phpunit": "^7.0",
"mockery/mockery": "^0.9.4",
"geoip2/geoip2": "~2.1"
"geoip2/geoip2": "~2.1",
"vlucas/phpdotenv": "^3.5"
},
"autoload": {
"files": [

View File

@@ -54,7 +54,7 @@ return [
'maxmind_database' => [
'class' => \Torann\GeoIP\Services\MaxMindDatabase::class,
'database_path' => storage_path('app/geoip.mmdb'),
'update_url' => 'https://geolite.maxmind.com/download/geoip/database/GeoLite2-City.mmdb.gz',
'update_url' => sprintf('https://download.maxmind.com/app/geoip_download?edition_id=GeoLite2-City&license_key=%s&suffix=tar.gz', env('MAXMIND_LICENSE_KEY')),
'locales' => ['en'],
],
@@ -72,7 +72,7 @@ return [
'continent_path' => storage_path('app/continents.json'),
'lang' => 'en',
],
'ipgeolocation' => [
'class' => \Torann\GeoIP\Services\IPGeoLocation::class,
'secure' => true,
@@ -87,6 +87,13 @@ return [
'secure' => true,
],
'ipfinder' => [
'class' => \Torann\GeoIP\Services\IPFinder::class,
'key' => env('IPFINDER_API_KEY'),
'secure' => true,
'locales' => ['en'],
],
],
/*

View File

@@ -1,19 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
backupStaticAttributes="false"
bootstrap="vendor/autoload.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
syntaxCheck="false"
verbose="true"
>
<testsuites>
<testsuite name="GeoIP Package Test Suite">
<directory>./tests</directory>
</testsuite>
</testsuites>
</phpunit>

View File

@@ -22,6 +22,7 @@ class Clear extends Command
/**
* Execute the console command for Laravel 5.5 and newer.
*
* @return void
*/
public function handle()
@@ -31,6 +32,7 @@ class Clear extends Command
/**
* Execute the console command.
*
* @return void
*/
public function fire()
@@ -50,7 +52,7 @@ class Clear extends Command
protected function isSupported()
{
return empty(app('geoip')->config('cache_tags')) === false
&& in_array(config('cache.default'), ['file', 'database']) === false;
&& in_array(config('cache.default'), ['file', 'database']) === false;
}
/**

View File

@@ -22,6 +22,7 @@ class Update extends Command
/**
* Execute the console command for Laravel 5.5 and newer.
*
* @return void
*/
public function handle()
@@ -42,6 +43,7 @@ class Update extends Command
// Ensure the selected service supports updating
if (method_exists($service, 'update') === false) {
$this->info('The current service "' . get_class($service) . '" does not support updating.');
return;
}
@@ -50,7 +52,8 @@ class Update extends Command
// Perform update
if ($result = $service->update()) {
$this->info($result);
} else {
}
else {
$this->error('Update failed!');
}
}

View File

@@ -133,7 +133,7 @@ class GeoIP
{
// If IP not set, user remote IP
$ip = $ip ?: $this->remote_ip;
// Check cache for location
if ($this->config('cache', 'none') !== 'none' && $location = $this->getCache()->get($ip)) {
$location->cached = true;
@@ -161,7 +161,7 @@ class GeoIP
if ($this->config('log_failures', true) === true) {
$log = new Logger('geoip');
$log->pushHandler(new StreamHandler(storage_path('logs/geoip.log'), Logger::ERROR));
$log->addError($e);
$log->error($e);
}
}
}
@@ -232,6 +232,7 @@ class GeoIP
$remotes_keys = [
'HTTP_X_FORWARDED_FOR',
'HTTP_CLIENT_IP',
'HTTP_X_REAL_IP',
'HTTP_X_FORWARDED',
'HTTP_FORWARDED_FOR',
'HTTP_FORWARDED',
@@ -284,7 +285,7 @@ class GeoIP
return false;
}
switch($this->config('cache', 'none')) {
switch ($this->config('cache', 'none')) {
case 'all':
return true;
case 'some' && $ip === null:

View File

@@ -2,6 +2,7 @@
namespace Torann\GeoIP;
use Illuminate\Support\Str;
use Illuminate\Support\ServiceProvider;
class GeoIPServiceProvider extends ServiceProvider
@@ -74,6 +75,6 @@ class GeoIPServiceProvider extends ServiceProvider
*/
protected function isLumen()
{
return str_contains($this->app->version(), 'Lumen') === true;
return Str::contains($this->app->version(), 'Lumen') === true;
}
}

View File

@@ -130,7 +130,8 @@ class Location implements ArrayAccess
/**
* Determine if the given attribute exists.
*
* @param mixed $offset
* @param mixed $offset
*
* @return bool
*/
public function offsetExists($offset)
@@ -141,7 +142,8 @@ class Location implements ArrayAccess
/**
* Get the value for a given offset.
*
* @param mixed $offset
* @param mixed $offset
*
* @return mixed
*/
public function offsetGet($offset)
@@ -152,8 +154,9 @@ class Location implements ArrayAccess
/**
* Set the value for a given offset.
*
* @param mixed $offset
* @param mixed $value
* @param mixed $offset
* @param mixed $value
*
* @return void
*/
public function offsetSet($offset, $value)
@@ -164,7 +167,8 @@ class Location implements ArrayAccess
/**
* Unset the value for a given offset.
*
* @param mixed $offset
* @param mixed $offset
*
* @return void
*/
public function offsetUnset($offset)
@@ -187,7 +191,8 @@ class Location implements ArrayAccess
/**
* Unset an attribute on the location.
*
* @param string $key
* @param string $key
*
* @return void
*/
public function __unset($key)

View File

@@ -2,7 +2,6 @@
namespace Torann\GeoIP\Services;
use Torann\GeoIP\GeoIP;
use Torann\GeoIP\Location;
use Illuminate\Support\Arr;
use Torann\GeoIP\Contracts\ServiceInterface;

View File

@@ -98,7 +98,7 @@ class IPApi extends AbstractService
*/
public function update()
{
$data = $this->client->get('http://dev.maxmind.com/static/csv/codes/country_continent.csv');
$data = $this->client->get('https://dev.maxmind.com/static/csv/codes/country_continent.csv');
// Verify server response
if ($this->client->getErrors() !== null) {

View File

@@ -3,6 +3,7 @@
namespace Torann\GeoIP\Services;
use Exception;
use Illuminate\Support\Arr;
use Torann\GeoIP\Support\HttpClient;
/**
@@ -47,6 +48,21 @@ class IPData extends AbstractService
throw new Exception('Request failed (' . $this->client->getErrors() . ')');
}
return $this->hydrate(json_decode($data[0], true));
$json = json_decode($data[0], true);
return $this->hydrate([
'ip' => $ip,
'iso_code' => $json['country_code'],
'country' => $json['country_name'],
'city' => $json['city'],
'state' => $json['region_code'],
'state_name' => $json['region'],
'postal_code' => $json['postal'],
'lat' => $json['latitude'],
'lon' => $json['longitude'],
'timezone' => Arr::get($json, 'time_zone.name'),
'continent' => Arr::get($json, 'continent_code'),
'currency' => Arr::get($json, 'currency.code'),
]);
}
}
}

View File

@@ -0,0 +1,58 @@
<?php
namespace Torann\GeoIP\Services;
use Exception;
use Illuminate\Support\Arr;
use Torann\GeoIP\Support\HttpClient;
/**
* Class GeoIP
* @package Torann\GeoIP\Services
*/
class IPFinder extends AbstractService
{
/**
* Http client instance.
*
* @var HttpClient
*/
protected $client;
/**
* The "booting" method of the service.
*
* @return void
*/
public function boot()
{
$this->client = new HttpClient([
'base_uri' => 'https://api.ipfinder.io/v1/',
'headers' => [
'User-Agent' => 'Laravel-GeoIP-Torann',
],
'query' => [
'token' => $this->config('key'),
],
]);
}
/**
* {@inheritdoc}
* @throws Exception
*/
public function locate($ip)
{
// Get data from client
$data = $this->client->get($ip);
// Verify server response
if ($this->client->getErrors() !== null || empty($data[0])) {
throw new Exception('Request failed (' . $this->client->getErrors() . ')');
}
$json = json_decode($data[0], true);
return $this->hydrate($json);
}
}

View File

@@ -23,11 +23,11 @@ class IPGeoLocation extends AbstractService
public function boot()
{
$base = [
'base_uri' => 'https://api.ipgeolocation.io/'
'base_uri' => 'https://api.ipgeolocation.io/',
];
if ($this->config('key')) {
$base['base_uri'] = $base['base_uri']."ipgeo?apiKey=". $this->config('key');
$base['base_uri'] = "{$base['base_uri']}ipgeo?apiKey=" . $this->config('key');
}
$this->client = new HttpClient($base);
@@ -48,7 +48,7 @@ class IPGeoLocation extends AbstractService
}
// Parse body content
$json = json_decode($data[0],true);
$json = json_decode($data[0], true);
return $this->hydrate($json);

View File

@@ -2,9 +2,9 @@
namespace Torann\GeoIP\Services;
use PharData;
use Exception;
use GeoIp2\Database\Reader;
use GeoIp2\Exception\AddressNotFoundException;
class MaxMindDatabase extends AbstractService
{
@@ -67,27 +67,97 @@ class MaxMindDatabase extends AbstractService
throw new Exception('Database path not set in config file.');
}
// Get settings
$url = $this->config('update_url');
$path = $this->config('database_path');
$this->withTemporaryDirectory(function ($directory) {
$tarFile = sprintf('%s/maxmind.tar.gz', $directory);
// Get header response
$headers = get_headers($url);
file_put_contents($tarFile, fopen($this->config('update_url'), 'r'));
if (substr($headers[0], 9, 3) != '200') {
throw new Exception('Unable to download database. ('. substr($headers[0], 13) .')');
$archive = new PharData($tarFile);
$file = $this->findDatabaseFile($archive);
$relativePath = "{$archive->getFilename()}/{$file->getFilename()}";
$archive->extractTo($directory, $relativePath);
file_put_contents($this->config('database_path'), fopen("{$directory}/{$relativePath}", 'r'));
});
return "Database file ({$this->config('database_path')}) updated.";
}
/**
* Provide a temporary directory to perform operations in and and ensure
* it is removed afterwards.
*
* @param callable $callback
* @return void
*/
protected function withTemporaryDirectory(callable $callback)
{
$directory = tempnam(sys_get_temp_dir(), 'maxmind');
if (file_exists($directory)) {
unlink($directory);
}
// Download zipped database to a system temp file
$tmpFile = tempnam(sys_get_temp_dir(), 'maxmind');
file_put_contents($tmpFile, fopen($url, 'r'));
mkdir($directory);
// Unzip and save database
file_put_contents($path, gzopen($tmpFile, 'r'));
try {
$callback($directory);
} finally {
$this->deleteDirectory($directory);
}
}
// Remove temp file
@unlink($tmpFile);
/**
* Recursively search the given archive to find the .mmdb file.
*
* @param \PharData $archive
* @return mixed
* @throws \Exception
*/
protected function findDatabaseFile($archive)
{
foreach ($archive as $file) {
if ($file->isDir()) {
return $this->findDatabaseFile(new PharData($file->getPathName()));
}
return "Database file ({$path}) updated.";
if (pathinfo($file, PATHINFO_EXTENSION) === 'mmdb') {
return $file;
}
}
throw new Exception('Database file could not be found within archive.');
}
/**
* Recursively delete the given directory.
*
* @param string $directory
* @return mixed
*/
protected function deleteDirectory(string $directory)
{
if (!file_exists($directory)) {
return true;
}
if (!is_dir($directory)) {
return unlink($directory);
}
foreach (scandir($directory) as $item) {
if ($item == '.' || $item == '..') {
continue;
}
if (!$this->deleteDirectory($directory . DIRECTORY_SEPARATOR . $item)) {
return false;
}
}
return rmdir($directory);
}
}

View File

@@ -3,7 +3,6 @@
namespace Torann\GeoIP\Services;
use GeoIp2\WebService\Client;
use GeoIp2\Exception\AddressNotFoundException;
class MaxMindWebService extends AbstractService
{

View File

@@ -1,84 +0,0 @@
<?php
namespace Torann\GeoIP\Tests;
use Mockery;
class CacheTest extends TestCase
{
/**
* @test
*/
public function shouldReturnValidLocation()
{
$data = [
'ip' => '81.2.69.142',
'iso_code' => 'US',
'lat' => 41.31,
'lon' => -72.92,
];
$cacheMock = Mockery::mock('Illuminate\Cache\CacheManager');
$cacheMock->shouldReceive('get')->with($data['ip'])->andReturn($data);
$geo_ip = $this->makeGeoIP([], $cacheMock);
$location = $geo_ip->getCache()->get($data['ip']);
$this->assertInstanceOf(\Torann\GeoIP\Location::class, $location);
$this->assertEquals($location->ip, $data['ip']);
$this->assertEquals($location->default, false);
}
/**
* @test
*/
public function shouldReturnInvalidLocation()
{
$cacheMock = Mockery::mock('Illuminate\Cache\CacheManager');
$geo_ip = $this->makeGeoIP([], $cacheMock);
$cacheMock->shouldReceive('get')->with('81.2.69.142')->andReturn(null);
$cacheMock->shouldReceive('tags')->with($geo_ip->config('cache_tags'))->andReturnSelf();
$this->assertEquals($geo_ip->getCache()->get('81.2.69.142'), null);
}
/**
* @test
*/
public function shouldSetLocation()
{
$location = new \Torann\GeoIP\Location([
'ip' => '81.2.69.142',
'iso_code' => 'US',
'lat' => 41.31,
'lon' => -72.92,
]);
$cacheMock = Mockery::mock('Illuminate\Cache\CacheManager');
$geo_ip = $this->makeGeoIP([], $cacheMock);
$cacheMock->shouldReceive('put')->withArgs(['81.2.69.142', $location->toArray(), $geo_ip->config('cache_expires')])->andReturn(null);
$cacheMock->shouldReceive('tags')->with($geo_ip->config('cache_tags'))->andReturnSelf();
$this->assertEquals($geo_ip->getCache()->set('81.2.69.142', $location), null);
}
/**
* @test
*/
public function shouldFlushLocations()
{
$cacheMock = Mockery::mock('Illuminate\Cache\CacheManager');
$geo_ip = $this->makeGeoIP([], $cacheMock);
$cacheMock->shouldReceive('flush')->andReturn(true);
$cacheMock->shouldReceive('tags')->with($geo_ip->config('cache_tags'))->andReturnSelf();
$this->assertEquals($geo_ip->getCache()->flush(), true);
}
}

View File

@@ -1,44 +0,0 @@
<?php
namespace Torann\GeoIP\Tests;
use Mockery;
class GeoIPTest extends TestCase
{
/**
* @test
*/
public function shouldGetUSDCurrency()
{
$geo_ip = $this->makeGeoIP();
$this->assertEquals($geo_ip->getCurrency('US'), 'USD');
}
/**
* @test
*/
public function testGetService()
{
$geo_ip = $this->makeGeoIP([
'service' => 'maxmind_database',
]);
// Get config values
$config = $this->getConfig()['services']['maxmind_database'];
unset($config['class']);
$this->assertInstanceOf(\Torann\GeoIP\Contracts\ServiceInterface::class, $geo_ip->getService());
}
/**
* @test
*/
public function testGetCache()
{
$geo_ip = $this->makeGeoIP();
$this->assertInstanceOf(\Torann\GeoIP\Cache::class, $geo_ip->getCache());
}
}

View File

@@ -1,69 +0,0 @@
<?php
namespace Torann\GeoIP\Tests\Services;
use Torann\GeoIP\Tests\TestCase;
class MaxMindDatabaseTest extends TestCase
{
/**
* @test
*/
public function shouldReturnConfigValue()
{
list($service, $config) = $this->getService();
$this->assertEquals($service->config('database_path'), $config['database_path']);
}
/**
* @test
*/
public function shouldReturnValidLocation()
{
list($service, $config) = $this->getService();
$location = $service->locate('81.2.69.142');
$this->assertInstanceOf(\Torann\GeoIP\Location::class, $location);
$this->assertEquals($location->ip, '81.2.69.142');
$this->assertEquals($location->default, false);
}
/**
* @test
*/
public function shouldReturnInvalidLocation()
{
list($service, $config) = $this->getService();
try {
$location = $service->locate('1.1.1.1');
$this->assertEquals($location->default, false);
}
catch (\GeoIp2\Exception\AddressNotFoundException $e) {
$this->assertEquals($e->getMessage(), 'The address 1.1.1.1 is not in the database.');
}
}
/**
* @test
*/
public function shouldUpdateLocalDatabase()
{
list($service, $config) = $this->getService();
$this->assertEquals($service->update(), "Database file ({$config['database_path']}) updated.");
@unlink($config['database_path']);
}
protected function getService()
{
$config = $this->getConfig()['services']['maxmind_database'];
$service = new $config['class']($config);
return [$service, $config];
}
}

View File

@@ -1,55 +0,0 @@
<?php
namespace Torann\GeoIP\Tests;
use Mockery;
use PHPUnit\Framework\TestCase as PHPUnitTestCase;
class TestCase extends PHPUnitTestCase
{
public static $functions;
public function setUp()
{
self::$functions = Mockery::mock();
}
public function tearDown()
{
Mockery::close();
}
protected function makeGeoIP(array $config = [], $cacheMock = null)
{
$cacheMock = $cacheMock ?: Mockery::mock('Illuminate\Cache\CacheManager');
$config = array_merge($this->getConfig(), $config);
$cacheMock->shouldReceive('tags')->with(['torann-geoip-location'])->andReturnSelf();
return new \Torann\GeoIP\GeoIP($config, $cacheMock);
}
protected function getConfig()
{
$config = include(__DIR__ . '/../config/geoip.php');
$this->databaseCheck($config['services']['maxmind_database']['database_path']);
return $config;
}
/**
* Check for test database and make a copy of it
* if it does not exist.
*
* @param string $database
*/
protected function databaseCheck($database)
{
if (file_exists($database) === false) {
@mkdir(dirname($database), 0755, true);
copy(__DIR__ . '/../resources/geoip.mmdb', $database);
}
}
}

View File

@@ -1,22 +0,0 @@
<?php
if (!function_exists('storage_path')) {
function storage_path($path = '')
{
return __DIR__ . DIRECTORY_SEPARATOR . 'tmp' . ($path ? DIRECTORY_SEPARATOR . $path : $path);
}
}
if (!function_exists('env')) {
function env($key, $default = null)
{
return $key;
}
}
if (! function_exists('app')) {
function app($key = null, $default = null)
{
return \Torann\GeoIP\Tests\TestCase::$functions->app($key, $default);
}
}

View File

@@ -1,2 +0,0 @@
*
!.gitignore