- Created separate MoneyFlix project directory - Copied Node.js redirector from production server - Added CRM PHP code (Redirects module, Core classes, Config, Routes, Views) - Created comprehensive documentation (README_MONEYFLIX.md) - Added sync script to keep CRM code updated (sync-from-crm.sh) - Configured .gitignore for Node.js and PHP - Set up proper project structure for multi-client isolation This separates MoneyFlix from the main CRM to avoid confusion between different client systems and provides a dedicated environment for MoneyFlix-specific development and maintenance.
305 lines
9.4 KiB
PHP
305 lines
9.4 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Core;
|
|
|
|
use Exception;
|
|
use Throwable;
|
|
|
|
/**
|
|
* ErrorReporter - Sistema centralizado de reporte de erros
|
|
* Implementa logging e tratamento de erros conforme as regras do projeto
|
|
*/
|
|
class ErrorReporter
|
|
{
|
|
private static ?Logger $logger = null;
|
|
private static ?AlertManager $alertManager = null;
|
|
private static array $errorCounts = [];
|
|
private static int $maxErrorsPerMinute = 10;
|
|
|
|
/**
|
|
* Reportar erro/exception
|
|
*/
|
|
public static function report(Throwable $exception, array $context = []): void
|
|
{
|
|
try {
|
|
// Log simples para evitar loops infinitos
|
|
error_log("ErrorReporter: " . $exception->getMessage() . " in " . $exception->getFile() . ":" . $exception->getLine());
|
|
|
|
// Mostrar erro visual em desenvolvimento/localhost
|
|
self::displayErrorIfDebug($exception, $context);
|
|
|
|
// Desativar temporariamente o sistema completo para evitar loops
|
|
// self::logError($exception, $context);
|
|
// self::captureWithErrorMonitoring($exception, $context);
|
|
// self::checkErrorThreshold($exception);
|
|
// self::notifyIfCritical($exception, $context);
|
|
} catch (Throwable $e) {
|
|
// Fallback para evitar loops infinitos
|
|
error_log("ErrorReporter failed: " . $e->getMessage());
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Mostrar erro visual em desenvolvimento/localhost
|
|
*/
|
|
private static function displayErrorIfDebug(Throwable $exception, array $context = []): void
|
|
{
|
|
// Verificar se deve mostrar erro visual
|
|
$showDebug = false;
|
|
|
|
// Verificar variável de ambiente
|
|
if (($_ENV['APP_DEBUG'] ?? false) === true) {
|
|
$showDebug = true;
|
|
}
|
|
|
|
// Verificar parâmetro de URL
|
|
if (isset($_GET['view_errors']) && $_GET['view_errors'] === 'true') {
|
|
$showDebug = true;
|
|
}
|
|
|
|
// Verificar se é localhost
|
|
if (isset($_SERVER['HTTP_HOST']) && strpos($_SERVER['HTTP_HOST'], 'localhost') !== false) {
|
|
$showDebug = true;
|
|
}
|
|
|
|
if (!$showDebug) {
|
|
return;
|
|
}
|
|
|
|
// Verificar se já foi enviado output
|
|
if (headers_sent()) {
|
|
return;
|
|
}
|
|
|
|
// Definir status code
|
|
http_response_code(500);
|
|
|
|
// Mostrar erro detalhado
|
|
echo '<h1>500 Internal Server Error</h1>';
|
|
echo '<pre style="background: #f5f5f5; padding: 15px; border: 1px solid #ddd; border-radius: 4px; font-family: monospace; font-size: 12px;">';
|
|
echo '<strong>Error:</strong> ' . htmlspecialchars($exception->getMessage()) . "\n\n";
|
|
echo '<strong>File:</strong> ' . htmlspecialchars($exception->getFile()) . "\n";
|
|
echo '<strong>Line:</strong> ' . htmlspecialchars((string)$exception->getLine()) . "\n\n";
|
|
|
|
if (!empty($context)) {
|
|
echo '<strong>Context:</strong> ' . htmlspecialchars(json_encode($context, JSON_PRETTY_PRINT)) . "\n\n";
|
|
}
|
|
|
|
echo '<strong>Stack Trace:</strong>' . "\n";
|
|
echo htmlspecialchars($exception->getTraceAsString());
|
|
echo '</pre>';
|
|
|
|
// Parar execução em modo debug
|
|
if ($showDebug) {
|
|
exit;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Capturar erro com o novo sistema de monitorização
|
|
*/
|
|
private static function captureWithErrorMonitoring(Throwable $exception, array $context = []): void
|
|
{
|
|
try {
|
|
// Verificar se o módulo ErrorMonitoring está disponível
|
|
if (class_exists('\App\Modules\ErrorMonitoring\Services\ErrorCollector')) {
|
|
$collector = \App\Modules\ErrorMonitoring\Services\ErrorCollector::getInstance();
|
|
|
|
// Determinar ambiente
|
|
$environment = defined('APP_ENV') ? constant('APP_ENV') : 'production';
|
|
if (isset($_SERVER['SERVER_NAME']) && strpos($_SERVER['SERVER_NAME'], 'localhost') !== false) {
|
|
$environment = 'development';
|
|
}
|
|
|
|
$collector->setEnvironment($environment)
|
|
->addContext('error_reporter_context', $context)
|
|
->capture($exception, $context);
|
|
}
|
|
} catch (Throwable $e) {
|
|
// Silenciar erros do sistema de monitorização para não criar loops
|
|
error_log("ErrorMonitoring capture failed: " . $e->getMessage());
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Reportar erro simples
|
|
*/
|
|
public static function error(string $message, array $context = []): void
|
|
{
|
|
$exception = new Exception($message);
|
|
self::report($exception, $context);
|
|
}
|
|
|
|
/**
|
|
* Reportar warning
|
|
*/
|
|
public static function warning(string $message, array $context = []): void
|
|
{
|
|
self::getLogger()->warning($message, $context);
|
|
}
|
|
|
|
/**
|
|
* Reportar info
|
|
*/
|
|
public static function info(string $message, array $context = []): void
|
|
{
|
|
self::getLogger()->info($message, $context);
|
|
}
|
|
|
|
/**
|
|
* Log de erro detalhado
|
|
*/
|
|
private static function logError(Throwable $exception, array $context = []): void
|
|
{
|
|
$logger = self::getLogger();
|
|
|
|
$logData = [
|
|
'message' => $exception->getMessage(),
|
|
'file' => $exception->getFile(),
|
|
'line' => $exception->getLine(),
|
|
'trace' => $exception->getTraceAsString(),
|
|
'context' => $context,
|
|
'timestamp' => date('Y-m-d H:i:s'),
|
|
'user_id' => $_SESSION['user_id'] ?? null,
|
|
'request_uri' => $_SERVER['REQUEST_URI'] ?? null,
|
|
'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? null,
|
|
'ip' => $_SERVER['REMOTE_ADDR'] ?? null
|
|
];
|
|
|
|
$logger->error("Exception: " . $exception->getMessage(), $logData);
|
|
}
|
|
|
|
/**
|
|
* Verificar threshold de erros
|
|
*/
|
|
private static function checkErrorThreshold(Throwable $exception): void
|
|
{
|
|
$minute = date('Y-m-d H:i');
|
|
$errorKey = $exception->getMessage();
|
|
|
|
if (!isset(self::$errorCounts[$minute])) {
|
|
self::$errorCounts[$minute] = [];
|
|
}
|
|
|
|
if (!isset(self::$errorCounts[$minute][$errorKey])) {
|
|
self::$errorCounts[$minute][$errorKey] = 0;
|
|
}
|
|
|
|
self::$errorCounts[$minute][$errorKey]++;
|
|
|
|
// Limpar dados antigos (mais de 1 hora)
|
|
$oldMinute = date('Y-m-d H:i', strtotime('-1 hour'));
|
|
unset(self::$errorCounts[$oldMinute]);
|
|
|
|
// Alertar se muitos erros
|
|
if (self::$errorCounts[$minute][$errorKey] >= self::$maxErrorsPerMinute) {
|
|
self::getAlertManager()->createAlert(
|
|
'error_threshold',
|
|
'Muitos erros detectados',
|
|
"Erro '{$errorKey}' ocorreu " . self::$errorCounts[$minute][$errorKey] . " vezes no último minuto",
|
|
'high'
|
|
);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Notificar se erro crítico
|
|
*/
|
|
private static function notifyIfCritical(Throwable $exception, array $context = []): void
|
|
{
|
|
$criticalPatterns = [
|
|
'database connection',
|
|
'fatal error',
|
|
'memory limit',
|
|
'timeout',
|
|
'permission denied'
|
|
];
|
|
|
|
$message = strtolower($exception->getMessage());
|
|
|
|
foreach ($criticalPatterns as $pattern) {
|
|
if (strpos($message, $pattern) !== false) {
|
|
self::getAlertManager()->createAlert(
|
|
'critical_error',
|
|
'Erro Crítico Detectado',
|
|
$exception->getMessage(),
|
|
'critical',
|
|
$context
|
|
);
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Obter instância do Logger
|
|
*/
|
|
private static function getLogger(): ?Logger
|
|
{
|
|
if (self::$logger === null) {
|
|
try {
|
|
self::$logger = new Logger();
|
|
} catch (\Exception $e) {
|
|
// Fallback para evitar loops infinitos
|
|
error_log("Failed to create Logger: " . $e->getMessage());
|
|
return null;
|
|
}
|
|
}
|
|
return self::$logger;
|
|
}
|
|
|
|
/**
|
|
* Obter instância do AlertManager
|
|
*/
|
|
private static function getAlertManager(): AlertManager
|
|
{
|
|
if (self::$alertManager === null) {
|
|
self::$alertManager = new AlertManager();
|
|
}
|
|
return self::$alertManager;
|
|
}
|
|
|
|
/**
|
|
* Definir logger customizado
|
|
*/
|
|
public static function setLogger(Logger $logger): void
|
|
{
|
|
self::$logger = $logger;
|
|
}
|
|
|
|
/**
|
|
* Definir alert manager customizado
|
|
*/
|
|
public static function setAlertManager(AlertManager $alertManager): void
|
|
{
|
|
self::$alertManager = $alertManager;
|
|
}
|
|
|
|
/**
|
|
* Definir threshold de erros
|
|
*/
|
|
public static function setMaxErrorsPerMinute(int $max): void
|
|
{
|
|
self::$maxErrorsPerMinute = $max;
|
|
}
|
|
|
|
/**
|
|
* Obter estatísticas de erros
|
|
*/
|
|
public static function getErrorStats(): array
|
|
{
|
|
return [
|
|
'current_minute' => self::$errorCounts[date('Y-m-d H:i')] ?? [],
|
|
'total_errors' => array_sum(array_map('array_sum', self::$errorCounts))
|
|
];
|
|
}
|
|
|
|
/**
|
|
* Limpar estatísticas
|
|
*/
|
|
public static function clearStats(): void
|
|
{
|
|
self::$errorCounts = [];
|
|
}
|
|
}
|