222 lines
8.6 KiB
PHP
Executable File
222 lines
8.6 KiB
PHP
Executable File
<?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);
|
|
}
|