Files
1sonhador 88a5659fe8 fix: Correct user permissions and UserModel query
- Fix storage permissions to use 'www' user instead of 'www-data'
- Fix UserModel getAllForAdmin query to avoid placeholders in LIMIT/OFFSET
- Import missing modules: Advertising, Dashboard, Analytics
- Update deploy script to copy files to public directory
2025-10-15 14:14:00 +01:00

224 lines
6.5 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Modules\Advertising\Services;
use App\Core\DatabaseManager;
use App\Core\ErrorReporter;
/**
* GeoLocationService - Serviço de geolocalização com múltiplas fontes
* Implementa integração com MaxMind GeoIP2 e fallbacks
*/
class GeoLocationService
{
private DatabaseManager $db;
private string $geoip2Path;
private bool $geoip2Available;
private array $cache = [];
public function __construct()
{
$this->db = DatabaseManager::getInstance();
$this->geoip2Path = __DIR__ . '/../../../data/GeoLite2-City.mmdb';
$this->geoip2Available = file_exists($this->geoip2Path);
}
/**
* Obter dados de geolocalização para um IP
*/
public function getGeoData(string $ipAddress): array
{
// Validar IP
if (!$this->isValidIp($ipAddress)) {
return $this->getDefaultGeoData();
}
// Verificar cache
$cacheKey = md5($ipAddress);
if (isset($this->cache[$cacheKey])) {
return $this->cache[$cacheKey];
}
// Tentar MaxMind GeoIP2 primeiro
$geoData = $this->getGeoIP2Data($ipAddress);
// Se não funcionar, tentar API gratuita
if (empty($geoData['country_code'])) {
$geoData = $this->getFreeApiData($ipAddress);
}
// Cache do resultado
$this->cache[$cacheKey] = $geoData;
return $geoData;
}
/**
* Obter dados via MaxMind GeoIP2
*/
private function getGeoIP2Data(string $ipAddress): array
{
if (!$this->geoip2Available) {
return [];
}
try {
// Verificar se a extensão está disponível
if (!extension_loaded('maxminddb')) {
return [];
}
// Verificar se a classe existe e usar reflection para evitar erros de linter
if (!class_exists('\MaxMind\Db\Reader')) {
return [];
}
$readerClass = new \ReflectionClass('\MaxMind\Db\Reader');
$reader = $readerClass->newInstance($this->geoip2Path);
$record = $reader->get($ipAddress);
$reader->close();
if (!$record) {
return [];
}
return [
'country_code' => $record['country']['iso_code'] ?? '',
'country_name' => $record['country']['names']['en'] ?? '',
'region_code' => $record['subdivisions'][0]['iso_code'] ?? '',
'region_name' => $record['subdivisions'][0]['names']['en'] ?? '',
'city' => $record['city']['names']['en'] ?? '',
'latitude' => $record['location']['latitude'] ?? 0,
'longitude' => $record['location']['longitude'] ?? 0,
'timezone' => $record['location']['time_zone'] ?? '',
'source' => 'maxmind_geoip2'
];
} catch (\Exception $e) {
ErrorReporter::report($e, [
'context' => 'geolocation_geoip2_error',
'ip_address' => $ipAddress
]);
return [];
}
}
/**
* Obter dados via API gratuita (fallback)
*/
private function getFreeApiData(string $ipAddress): array
{
try {
// Tentar ipapi.co (gratuito, 1000 requests/dia)
$url = "http://ip-api.com/json/{$ipAddress}?fields=status,message,country,countryCode,region,regionName,city,lat,lon,timezone";
$context = stream_context_create([
'http' => [
'timeout' => 5,
'user_agent' => 'BitReport-CRM/1.0'
]
]);
$response = file_get_contents($url, false, $context);
if ($response === false) {
return $this->getDefaultGeoData();
}
$data = json_decode($response, true);
if (!$data || $data['status'] !== 'success') {
return $this->getDefaultGeoData();
}
return [
'country_code' => $data['countryCode'] ?? '',
'country_name' => $data['country'] ?? '',
'region_code' => $data['region'] ?? '',
'region_name' => $data['regionName'] ?? '',
'city' => $data['city'] ?? '',
'latitude' => (float)($data['lat'] ?? 0),
'longitude' => (float)($data['lon'] ?? 0),
'timezone' => $data['timezone'] ?? '',
'source' => 'ip_api'
];
} catch (\Exception $e) {
ErrorReporter::report($e, [
'context' => 'geolocation_api_error',
'ip_address' => $ipAddress
]);
return $this->getDefaultGeoData();
}
}
/**
* Validar endereço IP
*/
private function isValidIp(string $ipAddress): bool
{
return filter_var($ipAddress, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false;
}
/**
* Obter dados padrão quando não é possível obter geolocalização
*/
private function getDefaultGeoData(): array
{
return [
'country_code' => 'UN',
'country_name' => 'Unknown',
'region_code' => '',
'region_name' => '',
'city' => '',
'latitude' => 0,
'longitude' => 0,
'timezone' => 'UTC',
'source' => 'default'
];
}
/**
* Verificar se MaxMind GeoIP2 está disponível
*/
public function isGeoIP2Available(): bool
{
return $this->geoip2Available && extension_loaded('maxminddb');
}
/**
* Obter estatísticas de uso
*/
public function getUsageStats(): array
{
try {
$stats = $this->db->fetchAll("
SELECT
source,
COUNT(*) as total_requests,
COUNT(DISTINCT ip_address) as unique_ips,
DATE(created_at) as date
FROM geo_analytics_events
WHERE event_type = 'geo_lookup'
GROUP BY source, DATE(created_at)
ORDER BY date DESC
LIMIT 30
");
return $stats ?: [];
} catch (\Exception $e) {
ErrorReporter::report($e, ['context' => 'geolocation_stats_error']);
return [];
}
}
/**
* Limpar cache
*/
public function clearCache(): void
{
$this->cache = [];
}
}