Primer commit del sistema separado falta mejorar mucho

This commit is contained in:
nickpons666
2025-12-30 01:18:46 -06:00
commit 1679c73e52
2384 changed files with 472342 additions and 0 deletions

100
discord/api/templates/create.php Executable file
View File

@@ -0,0 +1,100 @@
<?php
/**
* API de Plantillas de Discord - Crear
* REFRACTORIZADO para usar la tabla `comandos_discord`
*/
header('Content-Type: application/json');
require_once __DIR__ . '/../../../shared/utils/helpers.php';
require_once __DIR__ . '/../../../shared/auth/jwt.php';
require_once __DIR__ . '/../../../shared/database/connection.php';
ini_set('display_errors', 0);
error_reporting(E_ALL);
try {
$userData = JWTAuth::requireAuth();
} catch (Exception $e) {
http_response_code(401);
echo json_encode(['success' => false, 'error' => 'No autenticado: ' . $e->getMessage()]);
exit;
}
if (!hasPermission('manage_templates', 'discord')) {
http_response_code(403);
echo json_encode(['success' => false, 'error' => 'No tienes permiso para crear plantillas de Discord.']);
exit;
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo json_encode(['success' => false, 'error' => 'Método no permitido.']);
exit;
}
$data = json_decode(file_get_contents('php://input'), true);
$nombre = trim($data['nombre'] ?? '');
$comando = ltrim(trim($data['comando'] ?? ''), '#/');
$contenido = $data['contenido'] ?? '';
if (empty($nombre) || empty($contenido)) {
http_response_code(400);
echo json_encode(['success' => false, 'error' => 'El nombre y el contenido de la plantilla son obligatorios.']);
exit;
}
$db = getDB();
try {
$db->beginTransaction();
// 1. Verificar si el comando ya existe en la tabla `comandos_discord`
if (!empty($comando)) {
$stmt = $db->prepare("SELECT id FROM comandos_discord WHERE comando = ?");
$stmt->execute([$comando]);
if ($stmt->fetch()) {
$db->rollBack();
http_response_code(409); // Conflict
echo json_encode(['success' => false, 'error' => 'Ya existe un comando con ese nombre.']);
exit;
}
}
// 2. Insertar la plantilla (sin la columna `comando`)
$stmt = $db->prepare("
INSERT INTO plantillas_discord (nombre, contenido, usuario_id, fecha_creacion, fecha_modificacion)
VALUES (?, ?, ?, NOW(), NOW())
");
$stmt->execute([$nombre, $contenido, $userData->userId]);
$newTemplateId = $db->lastInsertId();
// 3. Si hay un comando, insertarlo en la tabla `comandos_discord`
if (!empty($comando)) {
logToFile('discord/templates.log', "Intentando insertar comando en comandos_discord. Comando: {$comando}, Plantilla ID: {$newTemplateId}", 'INFO');
$stmt = $db->prepare("
INSERT INTO comandos_discord (comando, descripcion, plantilla_id)
VALUES (?, ?, ?)
");
// Usamos el nombre de la plantilla como descripción por defecto
$stmt->execute([$comando, $nombre, $newTemplateId]);
logToFile('discord/templates.log', "Comando insertado en comandos_discord. Comando: {$comando}, Plantilla ID: {$newTemplateId}", 'INFO');
}
$db->commit();
logToFile('discord/templates.log', "Plantilla creada: {$nombre} (ID: {$newTemplateId}), por Usuario: {$userData->username}");
echo json_encode([
'success' => true,
'message' => 'Plantilla creada correctamente.',
'templateId' => $newTemplateId
]);
} catch (Exception $e) {
if ($db->inTransaction()) {
$db->rollBack();
}
http_response_code(500);
logToFile('discord/errors.log', 'Error creando plantilla: ' . $e->getMessage(), 'ERROR');
echo json_encode(['success' => false, 'error' => 'Ocurrió un error en el servidor al crear la plantilla.']);
}

139
discord/api/templates/delete.php Executable file
View File

@@ -0,0 +1,139 @@
<?php
/**
* API de Plantillas de Discord - Eliminar
* Este script es llamado por la función deleteTemplate() en list.php
*/
// Habilitar logging de errores
ini_set('display_errors', 0);
error_reporting(E_ALL);
// Función de logging mejorada
function logError($message, $data = null) {
$logDir = '/var/www/html/bot/logs/discord/';
if (!is_dir($logDir)) {
@mkdir($logDir, 0777, true);
}
$logFile = $logDir . 'error.log';
$timestamp = date('Y-m-d H:i:s');
$logMessage = "[$timestamp] [ERROR] $message";
if ($data) {
$logMessage .= "\n" . (is_string($data) ? $data : json_encode($data, JSON_PRETTY_PRINT));
}
error_log($logMessage . "\n", 3, $logFile);
}
// Iniciar buffer para capturar cualquier salida no deseada
ob_start();
try {
header('Content-Type: application/json');
// Registrar inicio
logError("Inicio de eliminación de plantilla");
// Incluir dependencias
require_once __DIR__ . '/../../../shared/utils/helpers.php';
require_once __DIR__ . '/../../../shared/auth/jwt.php';
require_once __DIR__ . '/../../../shared/database/connection.php';
// Limpiar buffer por si hay salida no deseada
ob_clean();
// Autenticación JWT para API (no redirigir)
$userData = JWTAuth::authenticate();
if (!$userData) {
http_response_code(401);
echo json_encode(['success' => false, 'error' => 'Acceso no autorizado.']);
logError("Error de autenticación");
exit;
}
logError("Usuario autenticado: " . json_encode(['id' => $userData->userId, 'username' => $userData->username]));
// Verificar método
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo json_encode(['success' => false, 'error' => 'Método no permitido.']);
logError("Método no permitido: " . $_SERVER['REQUEST_METHOD']);
exit;
}
// Obtener datos del cuerpo de la petición
$input = file_get_contents('php://input');
$data = json_decode($input, true);
$template_id = $data['id'] ?? null;
logError("Datos recibidos", ['input' => $input, 'data' => $data, 'template_id' => $template_id]);
// Validar ID
if (!$template_id || !is_numeric($template_id)) {
http_response_code(400);
echo json_encode(['success' => false, 'error' => 'ID de plantilla inválido o no proporcionado.']);
logError("ID de plantilla inválido", ['template_id' => $template_id]);
exit;
}
// Conectar a la base de datos
try {
$db = getDB();
logError("Conexión a BD exitosa");
} catch (Exception $e) {
logError("Error al conectar a la base de datos", $e->getMessage());
throw $e;
}
// Iniciar transacción
$db->beginTransaction();
logError("Transacción iniciada");
try {
// 1. Eliminar comandos asociados (si existen)
$stmt = $db->prepare("DELETE FROM comandos_discord WHERE plantilla_id = ?");
$stmt->execute([$template_id]);
$deletedCommands = $stmt->rowCount();
logError("Comandos eliminados", ['count' => $deletedCommands]);
// 2. Intentar eliminar la plantilla
$stmt = $db->prepare("DELETE FROM plantillas_discord WHERE id = ?");
$stmt->execute([$template_id]);
$deleted = $stmt->rowCount();
if ($deleted > 0) {
$db->commit();
logError("Plantilla eliminada exitosamente", ['id' => $template_id]);
echo json_encode(['success' => true]);
} else {
$db->rollBack();
http_response_code(404);
logError("No se encontró la plantilla para eliminar", ['id' => $template_id]);
echo json_encode(['success' => false, 'error' => 'No se encontró la plantilla para eliminar.']);
}
} catch (Exception $e) {
$db->rollBack();
logError("Error en la transacción", [
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString()
]);
http_response_code(500);
echo json_encode([
'success' => false,
'error' => 'Ocurrió un error en el servidor.',
'detail' => $e->getMessage()
]);
}
} catch (Exception $e) {
logError("Error no manejado", [
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString()
]);
http_response_code(500);
echo json_encode([
'success' => false,
'error' => 'Error interno del servidor.',
'detail' => $e->getMessage()
]);
}
// Limpiar cualquier salida no deseada
ob_end_flush();

138
discord/api/templates/edit.php Executable file
View File

@@ -0,0 +1,138 @@
<?php
/**
* API de Plantillas de Discord - Editar
* REFRACTORIZADO para usar la tabla `comandos_discord`
*/
header('Content-Type: application/json');
require_once __DIR__ . '/../../../shared/utils/helpers.php';
require_once __DIR__ . '/../../../shared/auth/jwt.php';
require_once __DIR__ . '/../../../shared/database/connection.php';
ini_set('display_errors', 0);
error_reporting(E_ALL);
try {
$userData = JWTAuth::requireAuth();
} catch (Exception $e) {
http_response_code(401);
echo json_encode(['success' => false, 'error' => 'Acceso no autorizado.']);
exit;
}
if (!hasPermission('manage_templates', 'discord')) {
http_response_code(403);
echo json_encode(['success' => false, 'error' => 'No tienes permiso para editar plantillas de Discord.']);
exit;
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo json_encode(['success' => false, 'error' => 'Método no permitido.']);
exit;
}
$data = json_decode(file_get_contents('php://input'), true);
$plantilla_id = $data['id'] ?? null;
$nombre = trim($data['nombre'] ?? '');
$comando = ltrim(trim($data['comando'] ?? ''), '#/');
$contenido = $data['contenido'] ?? '';
if (!$plantilla_id || !is_numeric($plantilla_id)) {
http_response_code(400);
echo json_encode(['success' => false, 'error' => 'ID de plantilla inválido.']);
exit;
}
if (empty($nombre) || empty($contenido)) {
http_response_code(400);
echo json_encode(['success' => false, 'error' => 'El nombre y el contenido son obligatorios.']);
exit;
}
$db = getDB();
try {
logToFile('discord/templates.log', "Iniciando edición de plantilla (ID: {$plantilla_id}). Comando recibido: {$comando}", 'INFO');
$db->beginTransaction();
// 1. Verificar que la plantilla existe y el usuario tiene permiso
$stmt = $db->prepare("SELECT usuario_id FROM plantillas_discord WHERE id = ?");
$stmt->execute([$plantilla_id]);
$plantillaExistente = $stmt->fetch();
if (!$plantillaExistente) {
throw new Exception('Plantilla no encontrada.', 404);
}
if ($userData->rol !== 'Admin' && $plantillaExistente['usuario_id'] != $userData->userId) {
throw new Exception('No tiene permisos para editar esta plantilla.', 403);
}
// 2. Actualizar la plantilla en sí (nombre y contenido)
$stmt = $db->prepare("
UPDATE plantillas_discord
SET nombre = ?, contenido = ?, fecha_modificacion = NOW()
WHERE id = ?
");
$stmt->execute([$nombre, $contenido, $plantilla_id]);
// 3. Gestionar el comando en la tabla `comandos_discord`
// Primero, obtener el comando actual si existe
$stmt = $db->prepare("SELECT id, comando FROM comandos_discord WHERE plantilla_id = ?");
$stmt->execute([$plantilla_id]);
$comandoExistente = $stmt->fetch();
logToFile('discord/templates.log', "Comando existente para plantilla {$plantilla_id}: " . ($comandoExistente ? json_encode($comandoExistente) : 'Ninguno'), 'INFO');
// Antes de insertar/actualizar, verificar si el nuevo nombre de comando ya está en uso por OTRA plantilla
if (!empty($comando)) {
$stmt = $db->prepare("SELECT id FROM comandos_discord WHERE comando = ? AND plantilla_id != ?");
$stmt->execute([$comando, $plantilla_id]);
if ($stmt->fetch()) {
throw new Exception('Ya existe otro comando con ese nombre.', 409);
}
}
// Lógica de casos
if (!empty($comando) && $comandoExistente) {
// Caso: El comando se está modificando
if ($comando !== $comandoExistente['comando']) {
logToFile('discord/templates.log', "Modificando comando existente para plantilla {$plantilla_id}. De: {$comandoExistente['comando']} a: {$comando}", 'INFO');
$stmt = $db->prepare("UPDATE comandos_discord SET comando = ?, descripcion = ? WHERE id = ?");
$stmt->execute([$comando, $nombre, $comandoExistente['id']]);
} else {
logToFile('discord/templates.log', "Comando existente no modificado para plantilla {$plantilla_id}. Valor: {$comando}", 'INFO');
}
} elseif (!empty($comando) && !$comandoExistente) {
// Caso: Se está añadiendo un comando nuevo
logToFile('discord/templates.log', "Añadiendo nuevo comando para plantilla {$plantilla_id}. Comando: {$comando}", 'INFO');
$stmt = $db->prepare("INSERT INTO comandos_discord (comando, descripcion, plantilla_id) VALUES (?, ?, ?)");
$stmt->execute([$comando, $nombre, $plantilla_id]);
} elseif (empty($comando) && $comandoExistente) {
// Caso: Se está eliminando el comando
logToFile('discord/templates.log', "Eliminando comando existente para plantilla {$plantilla_id}. Comando: {$comandoExistente['comando']}", 'INFO');
$stmt = $db->prepare("DELETE FROM comandos_discord WHERE id = ?");
$stmt->execute([$comandoExistente['id']]);
} else {
logToFile('discord/templates.log', "No se gestionó comando para plantilla {$plantilla_id}. Comando recibido: {$comando}, Existente: " . ($comandoExistente ? $comandoExistente['comando'] : 'Ninguno'), 'INFO');
}
// Si no hay comando nuevo y no había uno existente, no se hace nada.
$db->commit();
logToFile('discord/templates.log', "Edición de plantilla completada (ID: {$plantilla_id}).", 'INFO');
echo json_encode([
'success' => true,
'message' => 'Plantilla actualizada correctamente.'
]);
} catch (Exception $e) {
if ($db->inTransaction()) {
$db->rollBack();
}
$code = $e->getCode() >= 400 ? $e->getCode() : 500;
http_response_code($code);
logToFile('discord/templates.log', 'ERROR: Error editando plantilla (ID: ' . ($plantilla_id ?? 'N/A') . '): ' . $e->getMessage(), 'ERROR');
echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}

64
discord/api/templates/list.php Executable file
View File

@@ -0,0 +1,64 @@
<?php
/**
* API de Plantillas de Discord - Listar
*/
header('Content-Type: application/json');
require_once __DIR__ . '/../../../shared/utils/helpers.php';
require_once __DIR__ . '/../../../shared/auth/jwt.php';
require_once __DIR__ . '/../../../shared/database/connection.php';
// Para depuración
ini_set('display_errors', 0);
error_reporting(E_ALL);
// Verificar autenticación
if (!isAuthenticated()) {
http_response_code(401);
echo json_encode(['success' => false, 'error' => 'No autenticado']);
exit;
}
// Verificar permiso
if (!hasPermission('view_templates', 'discord')) {
http_response_code(403);
echo json_encode(['success' => false, 'error' => 'No tienes permiso para ver las plantillas de Discord.']);
exit;
}
try {
$db = getDB();
// Búsqueda (opcional, para futuras mejoras)
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$sql = "
SELECT p.id, p.nombre, p.comando, p.fecha_modificacion, u.username
FROM plantillas_discord p
LEFT JOIN usuarios u ON p.usuario_id = u.id
";
$params = [];
if (!empty($search)) {
$sql .= " WHERE p.nombre LIKE ? OR p.comando LIKE ?";
$params[] = "%{$search}%";
$params[] = "%{$search}%";
}
$sql .= " ORDER BY p.fecha_modificacion DESC";
$stmt = $db->prepare($sql);
$stmt->execute($params);
$templates = $stmt->fetchAll();
echo json_encode([
'success' => true,
'templates' => $templates
]);
} catch (Exception $e) {
http_response_code(500);
error_log('Error en /discord/api/templates/list.php: ' . $e->getMessage());
echo json_encode(['success' => false, 'error' => 'Error del servidor al obtener las plantillas.']);
}

View File

@@ -0,0 +1,36 @@
[04-Dec-2025 14:59:12 America/Mexico_City] PHP Warning: file_put_contents(/var/www/html/bot/shared/utils/../logs/discord/templates.log): Failed to open stream: No such file or directory in /var/www/html/bot/shared/utils/helpers.php on line 40
[04-Dec-2025 14:59:12 America/Mexico_City] PHP Warning: file_put_contents(/var/www/html/bot/shared/utils/../logs/discord/templates.log): Failed to open stream: No such file or directory in /var/www/html/bot/shared/utils/helpers.php on line 40
[04-Dec-2025 14:59:13 America/Mexico_City] PHP Warning: file_put_contents(/var/www/html/bot/shared/utils/../logs/discord/templates.log): Failed to open stream: No such file or directory in /var/www/html/bot/shared/utils/helpers.php on line 40
[04-Dec-2025 15:57:13 America/Mexico_City] PHP Warning: file_put_contents(/var/www/html/bot/shared/utils/../logs/discord/templates.log): Failed to open stream: No such file or directory in /var/www/html/bot/shared/utils/helpers.php on line 40
[04-Dec-2025 15:57:13 America/Mexico_City] PHP Warning: file_put_contents(/var/www/html/bot/shared/utils/../logs/discord/templates.log): Failed to open stream: No such file or directory in /var/www/html/bot/shared/utils/helpers.php on line 40
[04-Dec-2025 15:57:13 America/Mexico_City] PHP Warning: file_put_contents(/var/www/html/bot/shared/utils/../logs/discord/templates.log): Failed to open stream: No such file or directory in /var/www/html/bot/shared/utils/helpers.php on line 40
[04-Dec-2025 15:57:13 America/Mexico_City] PHP Warning: file_put_contents(/var/www/html/bot/shared/utils/../logs/discord/templates.log): Failed to open stream: No such file or directory in /var/www/html/bot/shared/utils/helpers.php on line 40
[04-Dec-2025 15:58:35 America/Mexico_City] PHP Warning: file_put_contents(/var/www/html/bot/shared/utils/../logs/discord/templates.log): Failed to open stream: No such file or directory in /var/www/html/bot/shared/utils/helpers.php on line 40
[04-Dec-2025 15:58:35 America/Mexico_City] PHP Warning: file_put_contents(/var/www/html/bot/shared/utils/../logs/discord/templates.log): Failed to open stream: No such file or directory in /var/www/html/bot/shared/utils/helpers.php on line 40
[04-Dec-2025 15:58:35 America/Mexico_City] PHP Warning: file_put_contents(/var/www/html/bot/shared/utils/../logs/discord/templates.log): Failed to open stream: No such file or directory in /var/www/html/bot/shared/utils/helpers.php on line 40
[04-Dec-2025 15:58:35 America/Mexico_City] PHP Warning: file_put_contents(/var/www/html/bot/shared/utils/../logs/discord/templates.log): Failed to open stream: No such file or directory in /var/www/html/bot/shared/utils/helpers.php on line 40
[04-Dec-2025 15:58:49 America/Mexico_City] PHP Warning: file_put_contents(/var/www/html/bot/shared/utils/../logs/discord/templates.log): Failed to open stream: No such file or directory in /var/www/html/bot/shared/utils/helpers.php on line 40
[04-Dec-2025 15:58:49 America/Mexico_City] PHP Warning: file_put_contents(/var/www/html/bot/shared/utils/../logs/discord/templates.log): Failed to open stream: No such file or directory in /var/www/html/bot/shared/utils/helpers.php on line 40
[04-Dec-2025 15:58:49 America/Mexico_City] PHP Warning: file_put_contents(/var/www/html/bot/shared/utils/../logs/discord/templates.log): Failed to open stream: No such file or directory in /var/www/html/bot/shared/utils/helpers.php on line 40
[04-Dec-2025 15:58:49 America/Mexico_City] PHP Warning: file_put_contents(/var/www/html/bot/shared/utils/../logs/discord/templates.log): Failed to open stream: No such file or directory in /var/www/html/bot/shared/utils/helpers.php on line 40
[04-Dec-2025 15:59:17 America/Mexico_City] PHP Fatal error: Uncaught Error: Call to undefined function isAuthenticated() in /var/www/html/bot/discord/api/templates/delete.php:19
Stack trace:
#0 {main}
thrown in /var/www/html/bot/discord/api/templates/delete.php on line 19
[04-Dec-2025 15:59:57 America/Mexico_City] PHP Fatal error: Uncaught Error: Call to undefined function isAuthenticated() in /var/www/html/bot/discord/api/templates/delete.php:19
Stack trace:
#0 {main}
thrown in /var/www/html/bot/discord/api/templates/delete.php on line 19
[04-Dec-2025 22:04:20 UTC] PHP Parse error: syntax error, unexpected token "=" in /var/www/html/bot/discord/api/templates/delete.php on line 20
[04-Dec-2025 22:05:28 UTC] PHP Parse error: syntax error, unexpected token "exit", expecting "]" in /var/www/html/bot/discord/api/templates/delete.php on line 24
[04-Dec-2025 22:05:56 UTC] PHP Parse error: syntax error, unexpected token "exit", expecting "]" in /var/www/html/bot/discord/api/templates/delete.php on line 24
[04-Dec-2025 22:06:02 UTC] PHP Parse error: syntax error, unexpected token "exit", expecting "]" in /var/www/html/bot/discord/api/templates/delete.php on line 24
[04-Dec-2025 22:08:10 UTC] PHP Parse error: syntax error, unexpected token "\" in /var/www/html/bot/discord/api/templates/delete.php on line 26
[04-Dec-2025 22:11:10 UTC] PHP Parse error: syntax error, unexpected token "\" in /var/www/html/bot/discord/api/templates/delete.php on line 26
[04-Dec-2025 22:13:26 UTC] PHP Parse error: syntax error, unexpected token "\" in /var/www/html/bot/discord/api/templates/delete.php on line 18
[04-Dec-2025 22:28:45 UTC] PHP Parse error: syntax error, unexpected token "\" in /var/www/html/bot/discord/api/templates/delete.php on line 18
[04-Dec-2025 22:31:33 UTC] PHP Parse error: syntax error, unexpected token "\" in /var/www/html/bot/discord/api/templates/delete.php on line 18
[04-Dec-2025 22:32:17 UTC] PHP Parse error: syntax error, unexpected token "\" in /var/www/html/bot/discord/api/templates/delete.php on line 18
[04-Dec-2025 22:32:21 UTC] PHP Parse error: syntax error, unexpected token "\" in /var/www/html/bot/discord/api/templates/delete.php on line 18
[04-Dec-2025 22:32:47 UTC] PHP Parse error: syntax error, unexpected token "\" in /var/www/html/bot/discord/api/templates/delete.php on line 18
[04-Dec-2025 22:34:50 UTC] PHP Parse error: syntax error, unexpected token "\" in /var/www/html/bot/discord/api/templates/delete.php on line 19