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

110
telegram/api/messages/delete.php Executable file
View 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);
}