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

104
discord/api/messages/delete.php Executable file
View File

@@ -0,0 +1,104 @@
<?php
/**
* API - Eliminar/Deshabilitar Mensaje Discord
* Cambia el estado del mensaje a 'deshabilitado' y opcionalmente lo elimina de Discord.
*/
header('Content-Type: application/json');
// Habilitar errores para debug (quitar en producción estricta)
ini_set('display_errors', 0);
error_reporting(E_ALL);
require_once __DIR__ . '/../../../shared/utils/helpers.php';
require_once __DIR__ . '/../../../shared/auth/jwt.php';
require_once __DIR__ . '/../../../shared/database/connection.php';
// Verificar autenticación
$userData = JWTAuth::authenticate();
if (!$userData) {
jsonResponse(['success' => false, 'error' => 'No autenticado'], 401);
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
jsonResponse(['success' => false, 'error' => 'Método no permitido'], 405);
}
$input = json_decode(file_get_contents('php://input'), true);
$messageId = $input['id'] ?? null;
if (empty($messageId) || !is_numeric($messageId)) {
jsonResponse(['success' => false, 'error' => 'ID de mensaje inválido o no proporcionado'], 400);
}
try {
$db = getDB();
// 1. Obtener detalles del mensaje para verificar permisos y Discord ID
$stmt = $db->prepare("SELECT usuario_id, canal_id, mensaje_discord_id, tipo_envio FROM mensajes_discord WHERE id = ?");
$stmt->execute([$messageId]);
$message = $stmt->fetch();
if (!$message) {
jsonResponse(['success' => false, 'error' => 'Mensaje no encontrado'], 404);
}
// Verificar permisos: solo Admin o el propietario pueden eliminar/deshabilitar
if ($userData->rol !== 'Admin' && $message['usuario_id'] != $userData->userId) {
jsonResponse(['success' => false, 'error' => 'No tiene permisos para eliminar este mensaje'], 403);
}
// 2. Intentar eliminar de Discord si existe un mensaje_discord_id y fue un envío inmediato
$discordDeletionSuccess = true;
$discordDeletionError = null;
if (!empty($message['mensaje_discord_id']) && $message['tipo_envio'] === 'inmediato') {
$botToken = $_ENV['DISCORD_BOT_TOKEN'] ?? getenv('DISCORD_BOT_TOKEN');
if (!$botToken) {
logToFile('discord/errors.log', "Error eliminando mensaje de Discord: Token de bot no configurado.", 'ERROR');
$discordDeletionError = "Token de bot no configurado, no se pudo eliminar de Discord.";
$discordDeletionSuccess = false;
} else {
$url = "https://discord.com/api/v10/channels/{$message['canal_id']}/messages/{$message['mensaje_discord_id']}";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bot ' . $botToken,
]);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlError = curl_error($ch);
curl_close($ch);
if ($curlError) {
$discordDeletionError = "Error cURL al eliminar de Discord: " . $curlError;
$discordDeletionSuccess = false;
} elseif ($httpCode !== 204) { // 204 No Content es la respuesta esperada para DELETE exitoso
$responseJson = json_decode($response, true);
$discordDeletionError = $responseJson['message'] ?? 'Error desconocido de Discord al eliminar';
$discordDeletionSuccess = false;
}
}
}
// 3. Deshabilitar el mensaje en la base de datos
// Si es un mensaje programado/recurrente pendiente, simplemente lo deshabilitamos sin intentar borrar de Discord
$updateStmt = $db->prepare("UPDATE mensajes_discord SET estado = 'deshabilitado' WHERE id = ?");
$updateStmt->execute([$messageId]);
logToFile('discord/messages.log', "Mensaje deshabilitado (ID: {$messageId}) por Usuario: {$userData->username}. Discord deletion: " . ($discordDeletionSuccess ? 'OK' : 'Fallido/' . $discordDeletionError));
jsonResponse([
'success' => true,
'message' => 'Mensaje deshabilitado correctamente.',
'discord_deletion_attempted' => !empty($message['mensaje_discord_id']) && $message['tipo_envio'] === 'inmediato',
'discord_deletion_success' => $discordDeletionSuccess,
'discord_deletion_error' => $discordDeletionError
]);
} catch (Exception $e) {
logToFile('discord/errors.log', "Error deshabilitando mensaje: " . $e->getMessage(), 'ERROR');
jsonResponse(['success' => false, 'error' => 'Ocurrió un error en el servidor.'], 500);
}

View File

@@ -0,0 +1,7 @@
[30-Nov-2025 16:17:06 America/Mexico_City] PHP Warning: file_put_contents(/var/www/html/bot/shared/utils/../logs/discord/messages.log): Failed to open stream: No such file or directory in /var/www/html/bot/shared/utils/helpers.php on line 40
[30-Nov-2025 16:20:55 America/Mexico_City] PHP Warning: file_put_contents(/var/www/html/bot/shared/utils/../logs/discord/messages.log): Failed to open stream: No such file or directory in /var/www/html/bot/shared/utils/helpers.php on line 40
[30-Nov-2025 16:22:33 America/Mexico_City] PHP Warning: file_put_contents(/var/www/html/bot/shared/utils/../logs/discord/messages.log): Failed to open stream: No such file or directory in /var/www/html/bot/shared/utils/helpers.php on line 40
[30-Nov-2025 16:34:09 America/Mexico_City] PHP Warning: file_put_contents(/var/www/html/bot/shared/utils/../logs/discord/messages.log): Failed to open stream: No such file or directory in /var/www/html/bot/shared/utils/helpers.php on line 40
[30-Nov-2025 16:34:29 America/Mexico_City] PHP Warning: file_put_contents(/var/www/html/bot/shared/utils/../logs/discord/messages.log): Failed to open stream: No such file or directory in /var/www/html/bot/shared/utils/helpers.php on line 40
[30-Nov-2025 17:02:10 America/Mexico_City] PHP Warning: file_put_contents(/var/www/html/bot/shared/utils/../logs/discord/messages.log): Failed to open stream: No such file or directory in /var/www/html/bot/shared/utils/helpers.php on line 40
[03-Dec-2025 20:51:19 America/Mexico_City] PHP Warning: file_put_contents(/var/www/html/bot/shared/utils/../logs/discord/messages.log): Failed to open stream: No such file or directory in /var/www/html/bot/shared/utils/helpers.php on line 40

49
discord/api/messages/retry.php Executable file
View File

@@ -0,0 +1,49 @@
<?php
/**
* API - Reintentar Mensaje Discord
* Cambia el estado de un mensaje a 'pendiente'.
*/
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';
// Verificar autenticación
$userData = JWTAuth::authenticate();
if (!$userData) {
jsonResponse(['success' => false, 'error' => 'No autenticado'], 401);
}
// Verificar permiso (reutilizamos 'send_messages' ya que es una acción relacionada)
if (!hasPermission('send_messages', 'discord')) {
jsonResponse(['success' => false, 'error' => 'No tienes permiso para gestionar mensajes de Discord.'], 403);
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
jsonResponse(['success' => false, 'error' => 'Método no permitido'], 405);
}
$input = json_decode(file_get_contents('php://input'), true);
$messageId = $input['id'] ?? null;
if (empty($messageId)) {
jsonResponse(['success' => false, 'error' => 'Falta el ID del mensaje.'], 400);
}
try {
$db = getDB();
// Cambiar el estado del mensaje a 'pendiente'
$stmt = $db->prepare("UPDATE mensajes_discord SET estado = 'pendiente' WHERE id = ?");
$stmt->execute([$messageId]);
if ($stmt->rowCount() > 0) {
jsonResponse(['success' => true, 'message' => 'Mensaje marcado como pendiente.']);
} else {
jsonResponse(['success' => false, 'error' => 'No se encontró el mensaje o no se pudo actualizar.']);
}
} catch (Exception $e) {
jsonResponse(['success' => false, 'error' => 'Error en la base de datos: ' . $e->getMessage()], 500);
}

221
discord/api/messages/send.php Executable file
View File

@@ -0,0 +1,221 @@
<?php
/**
* API - Enviar Mensaje Discord
*/
header('Content-Type: application/json');
// Habilitar errores para debug (quitar en producción estricta)
ini_set('display_errors', 0);
error_reporting(E_ALL);
require_once __DIR__ . '/../../../shared/utils/helpers.php';
require_once __DIR__ . '/../../../shared/auth/jwt.php';
require_once __DIR__ . '/../../../shared/database/connection.php';
// Verificar autenticación
$userData = JWTAuth::authenticate();
if (!$userData) {
jsonResponse(['success' => false, 'error' => 'No autenticado'], 401);
}
// Verificar permiso
if (!hasPermission('send_messages', 'discord')) {
jsonResponse(['success' => false, 'error' => 'No tienes permiso para enviar mensajes de Discord.'], 403);
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
jsonResponse(['success' => false, 'error' => 'Método no permitido'], 405);
}
$input = json_decode(file_get_contents('php://input'), true);
$destinatariosInput = $input['destinatario_id'] ?? []; // Puede ser un string o un array
$contenido = $input['contenido'] ?? '';
$tipoEnvio = $input['tipo_envio'] ?? 'inmediato'; // 'inmediato', 'programado', 'recurrente'
// Asegurarse de que $destinatariosInput sea siempre un array
if (!is_array($destinatariosInput)) {
$destinatariosInput = [$destinatariosInput];
}
$destinatarios = array_filter(array_map('trim', $destinatariosInput)); // Limpiar y filtrar vacíos
if (empty($destinatarios) || empty($contenido)) {
jsonResponse(['success' => false, 'error' => 'Faltan datos requeridos: destinatario(s) y contenido'], 400);
}
try {
// 1. Procesar contenido HTML para extraer imágenes y limpiar texto (una vez para todos)
$dom = new DOMDocument();
// Suprimir errores de HTML mal formado y usar UTF-8
libxml_use_internal_errors(true);
$dom->loadHTML('<?xml encoding="utf-8" ?>' . $contenido, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
libxml_clear_errors();
$embeds = [];
$images = $dom->getElementsByTagName('img');
// Extraer hasta 10 imágenes (límite de Discord)
$count = 0;
foreach ($images as $img) {
if ($count >= 10) break;
$src = $img->getAttribute('src');
if ($src) {
$embeds[] = [
'image' => ['url' => $src]
];
$count++;
}
}
// Limpiar texto: convertir saltos de línea y eliminar tags
$cleanContent = str_replace(['<br>', '<br/>', '<p>'], ["\n", "\n", "\n"], $contenido);
$cleanContent = strip_tags($cleanContent);
$cleanContent = html_entity_decode($cleanContent);
$cleanContent = trim($cleanContent);
$db = getDB();
$botToken = $_ENV['DISCORD_BOT_TOKEN'] ?? getenv('DISCORD_BOT_TOKEN');
if (!$botToken) {
throw new Exception("Token de bot no configurado");
}
$allResults = [];
foreach ($destinatarios as $destinatarioId) {
$messageStatus = 'pendiente'; // Estado por defecto para programados/recurrentes
$discordMessageId = null;
$errorMessage = null;
if ($tipoEnvio === 'inmediato') {
$url = "https://discord.com/api/v10/channels/{$destinatarioId}/messages";
$data = [
'content' => $cleanContent
];
if (!empty($embeds)) {
$data['embeds'] = $embeds;
}
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bot ' . $botToken,
'Content-Type: application/json'
]);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlError = curl_error($ch);
curl_close($ch);
$responseJson = json_decode($response, true);
if ($curlError) {
$errorMessage = "Error cURL: " . $curlError;
} elseif ($httpCode >= 400) {
$errorMessage = $responseJson['message'] ?? 'Error desconocido de Discord';
if (isset($responseJson['errors'])) {
$errorMessage .= ' - ' . json_encode($responseJson['errors']);
}
} else {
$messageStatus = 'enviado';
$discordMessageId = $responseJson['id'] ?? null;
}
}
// 3. Guardar en base de datos (Historial) para CADA destinatario
// Inmediato: estado 'enviado' o 'fallido'
// Programado/Recurrente: estado 'pendiente'
$stmt = $db->prepare("
INSERT INTO mensajes_discord (usuario_id, canal_id, contenido, estado, mensaje_discord_id, fecha_envio, tipo_envio)
VALUES (?, ?, ?, ?, ?, ?, ?)
");
$scheduledSendTime = null;
if ($tipoEnvio === 'programado' && isset($input['fecha_envio'])) {
// Convertir la fecha local a UTC para guardar en DB
$datetime = new DateTime($input['fecha_envio'], new DateTimeZone($_ENV['TIME_ZONE_ENVIOS'] ?? 'UTC'));
$datetime->setTimezone(new DateTimeZone('UTC'));
$scheduledSendTime = $datetime->format('Y-m-d H:i:s');
} elseif ($tipoEnvio === 'inmediato') {
$scheduledSendTime = date('Y-m-d H:i:s'); // La fecha de envío es ahora
}
$stmt->execute([
$userData->userId,
$destinatarioId,
$contenido,
($tipoEnvio === 'inmediato' && $messageStatus === 'fallido') ? 'fallido' : $messageStatus, // Estado correcto para inmediato/fallido
$discordMessageId,
$scheduledSendTime,
$tipoEnvio
]);
$messageDbId = $db->lastInsertId();
// Si es recurrente, guardar también en la tabla recurrentes_discord
if ($tipoEnvio === 'recurrente') {
// Validar y obtener hora de envío
$horaEnvio = $input['hora_envio'] ?? '09:00:00';
if (!preg_match('/^([01]\d|2[0-3]):([0-5]\d):([0-5]\d)$/', $horaEnvio) && !preg_match('/^([01]\d|2[0-3]):([0-5]\d)$/', $horaEnvio)) {
$horaEnvio = '09:00:00'; // Valor por defecto si es inválido
}
if (strlen($horaEnvio) === 5) { // Si viene sin segundos, añadir
$horaEnvio .= ':00';
}
$nextSendTime = null; // Esto debería ser calculado por un demonio de scheduling
$stmtRecur = $db->prepare("
INSERT INTO recurrentes_discord (mensaje_id, frecuencia, hora_envio, dia_semana, dia_mes, activo, proximo_envio)
VALUES (?, ?, ?, ?, ?, 1, ?)
");
$stmtRecur->execute([
$messageDbId,
$input['frecuencia'] ?? 'diario',
$horaEnvio,
$input['dia_semana'] ?? null,
$input['dia_mes'] ?? null,
$nextSendTime // Será calculado por el demonio
]);
}
$allResults[] = [
'destinatario_id' => $destinatarioId,
'message_db_id' => $messageDbId,
'status' => ($tipoEnvio === 'inmediato' && $messageStatus === 'fallido') ? 'fallido' : $messageStatus,
'error' => $errorMessage,
'discord_message_id' => $discordMessageId,
'tipo_envio' => $tipoEnvio
];
if ($messageStatus === 'enviado') {
logToFile('discord/messages.log', "Mensaje enviado a {$destinatarioId} por {$userData->username}");
} elseif ($messageStatus === 'pendiente') {
logToFile('discord/messages.log', "Mensaje {$tipoEnvio} guardado para {$destinatarioId} por {$userData->username}");
} else {
logToFile('discord/errors.log', "Error enviando mensaje a {$destinatarioId}: {$errorMessage}", 'ERROR');
}
}
// Determinar el éxito general de la operación
$overallSuccess = array_reduce($allResults, function($carry, $item) {
// Considerar éxito si al menos un mensaje fue enviado o está pendiente
return $carry || ($item['status'] === 'enviado' || $item['status'] === 'pendiente');
}, false);
jsonResponse([
'success' => $overallSuccess,
'message' => 'Procesamiento de mensajes completado.',
'details' => $allResults,
'overall_status' => $overallSuccess ? 'partial_success_or_pending' : 'all_failed'
]);
} catch (Exception $e) {
logToFile('discord/errors.log', "Error general en el envío de mensajes: " . $e->getMessage(), 'ERROR');
jsonResponse(['success' => false, 'error' => $e->getMessage()], 500);
}