Primer commit del sistema separado falta mejorar mucho
This commit is contained in:
110
telegram/api/messages/delete.php
Executable file
110
telegram/api/messages/delete.php
Executable file
@@ -0,0 +1,110 @@
|
||||
<?php
|
||||
/**
|
||||
* API - Eliminar/Deshabilitar Mensaje Telegram
|
||||
* Cambia el estado del mensaje a 'deshabilitado' y opcionalmente lo elimina de Telegram.
|
||||
*/
|
||||
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 Telegram ID
|
||||
$stmt = $db->prepare("SELECT usuario_id, chat_id, mensaje_telegram_id, tipo_envio FROM mensajes_telegram 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 Telegram si existe un mensaje_telegram_id y fue un envío inmediato
|
||||
$telegramDeletionSuccess = true;
|
||||
$telegramDeletionError = null;
|
||||
|
||||
if (!empty($message['mensaje_telegram_id']) && $message['tipo_envio'] === 'inmediato') {
|
||||
$botToken = $_ENV['TELEGRAM_BOT_TOKEN'] ?? getenv('TELEGRAM_BOT_TOKEN');
|
||||
if (!$botToken) {
|
||||
logToFile('telegram/errors.log', "Error eliminando mensaje de Telegram: Token de bot no configurado.", 'ERROR');
|
||||
$telegramDeletionError = "Token de bot no configurado, no se pudo eliminar de Telegram.";
|
||||
$telegramDeletionSuccess = false;
|
||||
} else {
|
||||
$telegramApiUrl = "https://api.telegram.org/bot{$botToken}/deleteMessage";
|
||||
|
||||
$postFields = [
|
||||
'chat_id' => $message['chat_id'],
|
||||
'message_id' => $message['mensaje_telegram_id']
|
||||
];
|
||||
|
||||
$ch = curl_init($telegramApiUrl);
|
||||
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
|
||||
curl_setopt($ch, CURLOPT_POST, true);
|
||||
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postFields));
|
||||
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) {
|
||||
$telegramDeletionError = "Error cURL al eliminar de Telegram: " . $curlError;
|
||||
$telegramDeletionSuccess = false;
|
||||
} elseif ($httpCode !== 200) { // 200 OK es la respuesta esperada para DELETE exitoso en Telegram (con 'ok': true)
|
||||
$responseJson = json_decode($response, true);
|
||||
if (!($responseJson['ok'] ?? false)) {
|
||||
$telegramDeletionError = $responseJson['description'] ?? 'Error desconocido de Telegram al eliminar';
|
||||
$telegramDeletionSuccess = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Deshabilitar el mensaje en la base de datos
|
||||
// Si es un mensaje programado/recurrente pendiente, simplemente lo deshabilitamos sin intentar borrar de Telegram
|
||||
$updateStmt = $db->prepare("UPDATE mensajes_telegram SET estado = 'deshabilitado' WHERE id = ?");
|
||||
$updateStmt->execute([$messageId]);
|
||||
|
||||
logToFile('telegram/messages.log', "Mensaje deshabilitado (ID: {$messageId}) por Usuario: {$userData->username}. Telegram deletion: " . ($telegramDeletionSuccess ? 'OK' : 'Fallido/' . $telegramDeletionError));
|
||||
|
||||
jsonResponse([
|
||||
'success' => true,
|
||||
'message' => 'Mensaje deshabilitado correctamente.',
|
||||
'telegram_deletion_attempted' => !empty($message['mensaje_telegram_id']) && $message['tipo_envio'] === 'inmediato',
|
||||
'telegram_deletion_success' => $telegramDeletionSuccess,
|
||||
'telegram_deletion_error' => $telegramDeletionError
|
||||
]);
|
||||
|
||||
} catch (Exception $e) {
|
||||
logToFile('telegram/errors.log', "Error deshabilitando mensaje: " . $e->getMessage(), 'ERROR');
|
||||
jsonResponse(['success' => false, 'error' => 'Ocurrió un error en el servidor.'], 500);
|
||||
}
|
||||
4
telegram/api/messages/php_errors.log
Executable file
4
telegram/api/messages/php_errors.log
Executable file
@@ -0,0 +1,4 @@
|
||||
[30-Nov-2025 16:36:15 America/Mexico_City] PHP Warning: file_put_contents(/var/www/html/bot/shared/utils/../logs/telegram/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:01:44 America/Mexico_City] PHP Warning: file_put_contents(/var/www/html/bot/shared/utils/../logs/telegram/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:07:42 America/Mexico_City] PHP Warning: file_put_contents(/var/www/html/bot/shared/utils/../logs/telegram/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:12:03 America/Mexico_City] PHP Warning: file_put_contents(/var/www/html/bot/shared/utils/../logs/telegram/messages.log): Failed to open stream: No such file or directory in /var/www/html/bot/shared/utils/helpers.php on line 40
|
||||
49
telegram/api/messages/retry.php
Executable file
49
telegram/api/messages/retry.php
Executable file
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
/**
|
||||
* API - Reintentar Mensaje Telegram
|
||||
* 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', 'telegram')) {
|
||||
jsonResponse(['success' => false, 'error' => 'No tienes permiso para gestionar mensajes de Telegram.'], 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_telegram 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);
|
||||
}
|
||||
213
telegram/api/messages/send.php
Executable file
213
telegram/api/messages/send.php
Executable file
@@ -0,0 +1,213 @@
|
||||
<?php
|
||||
/**
|
||||
* API - Enviar Mensaje Telegram (Adaptado para múltiples destinatarios y tipos de envío)
|
||||
*/
|
||||
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', 'telegram')) {
|
||||
jsonResponse(['success' => false, 'error' => 'No tienes permiso para enviar mensajes de Telegram.'], 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 {
|
||||
$db = getDB();
|
||||
$botToken = $_ENV['TELEGRAM_BOT_TOKEN'] ?? getenv('TELEGRAM_BOT_TOKEN');
|
||||
|
||||
if (!$botToken) {
|
||||
throw new Exception("Token de bot de Telegram no configurado.");
|
||||
}
|
||||
|
||||
// Procesar contenido HTML para extraer imágenes y texto
|
||||
$dom = new DOMDocument();
|
||||
libxml_use_internal_errors(true);
|
||||
$dom->loadHTML('<?xml encoding="utf-8" ?>' . $contenido, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
|
||||
libxml_clear_errors();
|
||||
|
||||
$imageUrl = null;
|
||||
$images = $dom->getElementsByTagName('img');
|
||||
if ($images->length > 0) {
|
||||
// Telegram Bot API generalmente solo permite una imagen por mensaje (en sendPhoto)
|
||||
// Tomamos la primera imagen encontrada
|
||||
$imageUrl = $images->item(0)->getAttribute('src');
|
||||
}
|
||||
|
||||
// Limpiar texto para Telegram (puede usar Markdown, pero primero quitamos HTML tags)
|
||||
$cleanContent = strip_tags($contenido); // Quitar tags HTML
|
||||
$cleanContent = html_entity_decode($cleanContent, ENT_QUOTES, 'UTF-8'); // Decodificar entidades HTML
|
||||
$cleanContent = trim($cleanContent);
|
||||
|
||||
$allResults = [];
|
||||
|
||||
foreach ($destinatarios as $destinatarioId) {
|
||||
$messageStatus = 'pendiente'; // Estado por defecto para programados/recurrentes si no es inmediato
|
||||
$telegramMessageId = null;
|
||||
$errorMessage = null;
|
||||
|
||||
if ($tipoEnvio === 'inmediato') {
|
||||
$telegramApiUrl = "https://api.telegram.org/bot{$botToken}/";
|
||||
|
||||
$postFields = [
|
||||
'chat_id' => $destinatarioId,
|
||||
];
|
||||
|
||||
if ($imageUrl) {
|
||||
// Si hay imagen, usar sendPhoto
|
||||
$postFields['photo'] = $imageUrl;
|
||||
// El caption del sendPhoto soporta HTML/Markdown, por simplicidad usamos el texto limpio
|
||||
$postFields['caption'] = $cleanContent;
|
||||
$method = 'sendPhoto';
|
||||
} else {
|
||||
// Si no hay imagen, usar sendMessage
|
||||
$postFields['text'] = $cleanContent;
|
||||
$method = 'sendMessage';
|
||||
}
|
||||
|
||||
$ch = curl_init($telegramApiUrl . $method);
|
||||
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
|
||||
curl_setopt($ch, CURLOPT_POST, true);
|
||||
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postFields));
|
||||
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 !== 200 || !($responseJson['ok'] ?? false)) {
|
||||
$errorMessage = $responseJson['description'] ?? 'Error desconocido de Telegram API';
|
||||
} else {
|
||||
$messageStatus = 'enviado';
|
||||
$telegramMessageId = $responseJson['result']['message_id'] ?? null;
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Guardar en base de datos (Historial) para CADA destinatario
|
||||
$stmt = $db->prepare("
|
||||
INSERT INTO mensajes_telegram (usuario_id, chat_id, contenido, estado, mensaje_telegram_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');
|
||||
}
|
||||
|
||||
$finalMessageStatus = ($tipoEnvio === 'inmediato' && $messageStatus === 'fallido') ? 'fallido' : $messageStatus;
|
||||
|
||||
$stmt->execute([
|
||||
$userData->userId,
|
||||
$destinatarioId,
|
||||
$contenido, // Guardamos el original con HTML/formato para referencia
|
||||
$finalMessageStatus,
|
||||
$telegramMessageId,
|
||||
$scheduledSendTime,
|
||||
$tipoEnvio
|
||||
]);
|
||||
|
||||
$messageDbId = $db->lastInsertId();
|
||||
|
||||
// Si es recurrente, guardar también en la tabla recurrentes_telegram
|
||||
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_telegram (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' => $finalMessageStatus,
|
||||
'error' => $errorMessage,
|
||||
'telegram_message_id' => $telegramMessageId,
|
||||
'tipo_envio' => $tipoEnvio
|
||||
];
|
||||
|
||||
if ($finalMessageStatus === 'enviado') {
|
||||
logToFile('telegram/messages.log', "Mensaje enviado a {$destinatarioId} por {$userData->username}");
|
||||
} elseif ($finalMessageStatus === 'pendiente') {
|
||||
logToFile('telegram/messages.log', "Mensaje {$tipoEnvio} guardado para {$destinatarioId} por {$userData->username}");
|
||||
} else {
|
||||
logToFile('telegram/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('telegram/errors.log', "Error general en el envío de mensajes: " . $e->getMessage(), 'ERROR');
|
||||
jsonResponse(['success' => false, 'error' => $e->getMessage()], 500);
|
||||
}
|
||||
Reference in New Issue
Block a user