From 4e3e02111bf905d47093a716edd056e2d9fbdb72 Mon Sep 17 00:00:00 2001 From: lizandrogd <77708265+lizandrogd@users.noreply.github.com> Date: Tue, 20 Jan 2026 23:55:00 -0500 Subject: [PATCH] up --- api/webhook.php | 32 +++++++++++++++++++++++++------- config/config_enhanced.php | 24 +++++++++++++++++++++++- services/WhatsAppService.php | 9 +++++++++ 3 files changed, 57 insertions(+), 8 deletions(-) diff --git a/api/webhook.php b/api/webhook.php index f0e29bf..c639a6d 100644 --- a/api/webhook.php +++ b/api/webhook.php @@ -4,7 +4,9 @@ * Fecha: 13 de noviembre de 2025 */ -require_once __DIR__ . '/../config/config_enhanced.php'; +require_once __DIR__ . '/../config/config.php'; + + // Headers para API header('Content-Type: application/json; charset=utf-8'); @@ -18,12 +20,23 @@ class WhatsAppWebhook { private $botService; public function __construct() { - $this->db = Database::getInstance(); - $this->whatsappService = new WhatsAppService(); - $this->botService = new BotService(); + error_log('[webhook] __construct start'); + try { + $this->db = Database::getInstance(); + $this->whatsappService = new WhatsAppService(); + $this->botService = new BotService(); + } catch (Throwable $t) { + error_log('[webhook] constructor failed: ' . $t->getMessage()); + if (function_exists('writeLog')) { + writeLog('ERROR', 'Webhook constructor failed: ' . $t->getMessage(), ['trace' => $t->getTraceAsString()]); + } + throw $t; + } + error_log('[webhook] __construct end'); } public function handleRequest() { + error_log('[webhook] handleRequest start, method=' . ($_SERVER['REQUEST_METHOD'] ?? 'unknown')); $method = $_SERVER['REQUEST_METHOD']; if ($method === 'GET') { @@ -251,10 +264,15 @@ if (php_sapi_name() !== 'cli') { try { $webhook = new WhatsAppWebhook(); $webhook->handleRequest(); - } catch (Exception $e) { - error_log("Fatal error in webhook: " . $e->getMessage()); + } catch (Throwable $t) { + // Manejar excepciones fatales y errores (Throwable) + error_log("Fatal error in webhook: " . $t->getMessage()); + error_log($t->getTraceAsString()); + if (function_exists('writeLog')) { + writeLog('ERROR', 'Fatal error in webhook: ' . $t->getMessage(), ['trace' => $t->getTraceAsString()]); + } http_response_code(500); - echo json_encode(['error' => 'Error fatal del servidor']); + echo json_encode(['error' => 'Error fatal del servidor', 'detail' => $t->getMessage()]); } } ?> \ No newline at end of file diff --git a/config/config_enhanced.php b/config/config_enhanced.php index 54d1b5b..a4b8812 100644 --- a/config/config_enhanced.php +++ b/config/config_enhanced.php @@ -7,6 +7,7 @@ */ // Función para cargar archivo .env +if (!function_exists('loadEnvFile')) { function loadEnvFile($path) { if (!file_exists($path)) { return false; @@ -30,14 +31,17 @@ function loadEnvFile($path) { return true; } +} // Cargar .env si existe -$envLoaded = loadEnvFile(__DIR__ . '/../.env'); +$envLoaded = function_exists('loadEnvFile') ? loadEnvFile(__DIR__ . '/../.env') : false; // Función helper para obtener variables de entorno con fallback +if (!function_exists('env')) { function env($key, $default = null) { return $_ENV[$key] ?? getenv($key) ?: $default; } +} // Configuración de la base de datos define('DB_HOST', env('DB_HOST', 'localhost')); @@ -122,6 +126,7 @@ if (!defined('AUTO_DETECTED_URL')) { } // Función para logging centralizado +if (!function_exists('writeLog')) { function writeLog($level, $message, $context = []) { if (!ENABLE_LOGGING) return; @@ -143,18 +148,24 @@ function writeLog($level, $message, $context = []) { file_put_contents($logDir . '/system.log', $logMessage, FILE_APPEND | LOCK_EX); } +} // Función para verificar si la instalación está completada +if (!function_exists('isInstallationCompleted')) { function isInstallationCompleted() { return file_exists(dirname(__DIR__) . '/.installation_completed'); } +} // Función para verificar login +if (!function_exists('isUserLoggedIn')) { function isUserLoggedIn() { return isset($_SESSION['admin_logged_in']) && $_SESSION['admin_logged_in'] === true; } +} // Función para verificar intentos de login +if (!function_exists('checkLoginAttempts')) { function checkLoginAttempts($ip) { $attemptsFile = dirname(__DIR__) . '/.login_attempts.json'; @@ -178,8 +189,10 @@ function checkLoginAttempts($ip) { return $ipData['attempts'] < MAX_LOGIN_ATTEMPTS; } +} // Función para registrar intento de login fallido +if (!function_exists('recordFailedLogin')) { function recordFailedLogin($ip) { $attemptsFile = dirname(__DIR__) . '/.login_attempts.json'; @@ -201,8 +214,10 @@ function recordFailedLogin($ip) { file_put_contents($attemptsFile, json_encode($attempts)); writeLog('WARNING', 'Failed login attempt', ['ip' => $ip, 'attempts' => $attempts[$ip]['attempts']]); } +} // Función para limpiar intentos de login exitoso +if (!function_exists('clearLoginAttempts')) { function clearLoginAttempts($ip) { $attemptsFile = dirname(__DIR__) . '/.login_attempts.json'; @@ -214,6 +229,7 @@ function clearLoginAttempts($ip) { writeLog('INFO', 'Successful login', ['ip' => $ip]); } +} // Autoloader mejorado spl_autoload_register(function ($class) { @@ -236,6 +252,7 @@ spl_autoload_register(function ($class) { }); // Función para obtener configuración desde base de datos +if (!function_exists('getConfigFromDB')) { function getConfigFromDB($key, $default = null) { static $configs = null; @@ -267,8 +284,10 @@ function getConfigFromDB($key, $default = null) { return $configs[$key] ?? $default; } +} // Función para validar configuración de WhatsApp +if (!function_exists('validateWhatsAppConfig')) { function validateWhatsAppConfig() { $errors = []; @@ -286,14 +305,17 @@ function validateWhatsAppConfig() { return $errors; } +} // Función para crear directorio si no existe +if (!function_exists('ensureDirectoryExists')) { function ensureDirectoryExists($path) { if (!is_dir($path)) { mkdir($path, 0755, true); writeLog('INFO', 'Directory created', ['path' => $path]); } } +} // Crear directorios necesarios ensureDirectoryExists(dirname(__DIR__) . '/logs'); diff --git a/services/WhatsAppService.php b/services/WhatsAppService.php index 6df9707..8942401 100644 --- a/services/WhatsAppService.php +++ b/services/WhatsAppService.php @@ -5,6 +5,15 @@ * Fecha: 13 de noviembre de 2025 */ +// Asegurar que las funciones de configuración estén cargadas si este archivo +// se incluye directamente sin pasar por `config.php`. +if (!function_exists('getWhatsAppConfigFromDB')) { + $possible = __DIR__ . '/../config/config.php'; + if (file_exists($possible)) { + require_once $possible; + } +} + class WhatsAppService { private $token;