null, 'name' => '', 'platform_id' => '', 'type' => 'channel', 'platform' => 'discord', 'language_code' => 'es' ]; // Handle form submissions if ($_SERVER['REQUEST_METHOD'] === 'POST') { $current_user_id = $_SESSION['user_id']; $current_username = $_SESSION['username']; $action = $_POST['action'] ?? null; // Action: Add or Update Recipient if (isset($_POST['add_recipient']) || isset($_POST['update_recipient'])) { $platform = $_POST['platform'] ?? 'discord'; $type = $_POST['type'] ?? 'channel'; $name = $_POST['name'] ?? ''; $platform_id = $_POST['platform_id'] ?? ''; $language_code = $_POST['language_code'] ?? 'es'; $id = $_POST['id'] ?? null; if (empty($name) || empty($platform_id) || empty($type) || empty($platform)) { $error = "Todos los campos son obligatorios."; } elseif (!is_numeric($platform_id)) { $error = "El ID de Plataforma debe ser un número."; } else { try { if (isset($_POST['update_recipient'])) { // UPDATE $stmt = $pdo->prepare("UPDATE recipients SET name = ?, platform_id = ?, type = ?, platform = ?, language_code = ? WHERE id = ?"); $stmt->execute([$name, $platform_id, $type, $platform, $language_code, $id]); $details = 'Admin ' . $current_username . ' updated recipient: ' . $name . ' (' . $platform . ':' . $platform_id . ')'; log_activity($current_user_id, 'Recipient Updated', $details); header('Location: recipients.php?success=updated'); exit(); } else { // ADD $stmt = $pdo->prepare("INSERT INTO recipients (name, platform_id, type, platform, language_code) VALUES (?, ?, ?, ?, ?)"); $stmt->execute([$name, $platform_id, $type, $platform, $language_code]); $new_recipient_id = $pdo->lastInsertId(); $details = 'Admin ' . $current_username . ' added new recipient: ' . $name . ' (' . $platform . ':' . $platform_id . ')'; log_activity($current_user_id, 'Recipient Added', $details); $success = "Destinatario añadido con éxito."; } } catch (PDOException $e) { if ($e->errorInfo[1] == 1062) { $error = "El ID de Plataforma ('$platform_id') ya existe."; } else { $error = "Error en la base de datos: " . $e->getMessage(); } // Keep form data on error $edit_mode = isset($_POST['update_recipient']); $edit_recipient = ['id' => $id, 'name' => $name, 'platform_id' => $platform_id, 'type' => $type, 'platform' => $platform, 'language_code' => $language_code]; } } } // Action: Delete Single Recipient elseif (isset($_POST['delete_recipient'])) { $id_to_delete = $_POST['id_to_delete']; try { $stmt_recipient = $pdo->prepare("SELECT name, platform, platform_id FROM recipients WHERE id = ?"); $stmt_recipient->execute([$id_to_delete]); $recipient_info = $stmt_recipient->fetch(PDO::FETCH_ASSOC); $details = 'Admin ' . $current_username . ' deleted recipient: ' . ($recipient_info['name'] ?? 'Unknown') . ' (' . ($recipient_info['platform'] ?? 'N/A') . ':' . ($recipient_info['platform_id'] ?? 'N/A') . ')'; $stmt = $pdo->prepare("DELETE FROM recipients WHERE id = ?"); $stmt->execute([$id_to_delete]); log_activity($current_user_id, 'Recipient Deleted', $details); $success = "Destinatario eliminado con éxito."; } catch (PDOException $e) { $error = "Error al eliminar. Es posible que el destinatario esté en uso."; } } // Action: Kick Telegram User elseif ($action === 'kick_telegram_user') { $recipient_id_to_kick = $_POST['recipient_id_to_kick'] ?? null; $chat_id_to_kick_from = $_POST['chat_id_to_kick_from'] ?? null; if ($recipient_id_to_kick && $chat_id_to_kick_from) { try { // Get recipient's platform_id (Telegram user ID) $stmt = $pdo->prepare("SELECT platform_id, name FROM recipients WHERE id = ? AND platform = 'telegram' AND type = 'user'"); $stmt->execute([$recipient_id_to_kick]); $recipient_info = $stmt->fetch(PDO::FETCH_ASSOC); $telegram_user_id = $recipient_info['platform_id'] ?? null; $recipient_name = $recipient_info['name'] ?? 'Unknown'; if ($telegram_user_id) { // Get bot token $botToken = $_ENV['TELEGRAM_BOT_TOKEN'] ?? ''; if (empty($botToken)) { throw new Exception("Token de bot de Telegram no configurado."); } // Telegram API URL for banning a chat member $telegramApiUrl = "https://api.telegram.org/bot{$botToken}/banChatMember"; $params = [ 'chat_id' => $chat_id_to_kick_from, 'user_id' => $telegram_user_id, 'until_date' => time() + 30 // Ban for 30 seconds to ensure they are removed, then they can rejoin ]; $options = [ 'http' => [ 'header' => "Content-type: application/x-www-form-urlencoded\r\n", 'method' => 'POST', 'content' => http_build_query($params), ], ]; $context = stream_context_create($options); $result = file_get_contents($telegramApiUrl, false, $context); $response = json_decode($result, true); if ($response && $response['ok']) { // If successful, unban immediately to allow re-entry $unbanTelegramApiUrl = "https://api.telegram.org/bot{$botToken}/unbanChatMember"; $unbanParams = [ 'chat_id' => $chat_id_to_kick_from, 'user_id' => $telegram_user_id, 'only_if_banned' => true // Only try to unban if they are actually banned ]; $unbanOptions = [ 'http' => [ 'header' => "Content-type: application/x-www-form-urlencoded\r\n", 'method' => 'POST', 'content' => http_build_query($unbanParams), ], ]; $unbanContext = stream_context_create($unbanOptions); $unbanResult = file_get_contents($unbanTelegramApiUrl, false, $unbanContext); $unbanResponse = json_decode($unbanResult, true); if ($unbanResponse && $unbanResponse['ok']) { $success = "Usuario de Telegram expulsado del grupo (permite reingreso) y eliminado de la base de datos."; } else { // Log unban error but still proceed with local deletion as kick was successful error_log("Error al desbanear usuario de Telegram después de la expulsión: " . ($unbanResponse['description'] ?? 'Error desconocido')); $success = "Usuario de Telegram expulsado del grupo (error al permitir reingreso) y eliminado de la base de datos."; } // Delete from local DB regardless of unban success, as the kick itself was successful $stmt = $pdo->prepare("DELETE FROM recipients WHERE id = ?"); $stmt->execute([$recipient_id_to_kick]); $details = 'Admin ' . $current_username . ' kicked Telegram user: ' . $recipient_name . ' (ID: ' . $telegram_user_id . ') from group ID: ' . $chat_id_to_kick_from; log_activity($current_user_id, 'Telegram User Kicked', $details); } else { $error = "Error al expulsar usuario de Telegram: " . ($response['description'] ?? 'Error desconocido'); } } else { $error = "Usuario de Telegram no encontrado o no es un usuario válido para expulsar."; } } catch (Exception $e) { $error = "Error al procesar la expulsión: " . $e->getMessage(); } } else { $error = "Faltan parámetros para expulsar al usuario de Telegram."; } } // Action: Delete Multiple Recipients elseif ($action === 'delete_selected' && !empty($_POST['selected_recipients'])) { $deleted_count = 0; $error_count = 0; foreach ($_POST['selected_recipients'] as $recipient_id) { try { $stmt_recipient = $pdo->prepare("SELECT name, platform, platform_id FROM recipients WHERE id = ?"); $stmt_recipient->execute([$recipient_id]); $recipient_info = $stmt_recipient->fetch(PDO::FETCH_ASSOC); $details = 'Admin ' . $current_username . ' deleted recipient: ' . ($recipient_info['name'] ?? 'Unknown') . ' (' . ($recipient_info['platform'] ?? 'N/A') . ':' . ($recipient_info['platform_id'] ?? 'N/A') . ')'; $stmt = $pdo->prepare("DELETE FROM recipients WHERE id = ?"); $stmt->execute([$recipient_id]); log_activity($current_user_id, 'Recipient Deleted', $details); $deleted_count++; } catch (PDOException $e) { $error_count++; error_log("Error al eliminar destinatario ID $recipient_id: " . $e->getMessage()); } } if ($deleted_count > 0) { $success = "Se eliminaron $deleted_count destinatarios correctamente."; if ($error_count > 0) { $error = "Hubo errores al eliminar $error_count destinatarios."; } header('Location: recipients.php?success=deleted_multiple&deleted=' . $deleted_count . '&errors=' . $error_count); exit(); } else if ($error_count > 0) { $error = "No se pudo eliminar ningún destinatario. Por favor, inténtalo de nuevo."; } } } // Handle entering edit mode via GET request if (isset($_GET['action']) && $_GET['action'] === 'edit' && isset($_GET['id'])) { $edit_mode = true; $stmt = $pdo->prepare("SELECT * FROM recipients WHERE id = ?"); $stmt->execute([$_GET['id']]); $recipient_to_edit = $stmt->fetch(); if ($recipient_to_edit) { $edit_recipient = $recipient_to_edit; } } // Fetch all recipients to display $recipients = $pdo->query("SELECT * FROM recipients ORDER BY platform, type, name ASC")->fetchAll(); $pageTitle = 'Gestionar Destinatarios'; require_once __DIR__ . '/../templates/header.php'; // Display feedback messages if (isset($error)) echo "
$error
"; if (isset($success)) echo "
$success
"; if (isset($_GET['success'])) { if ($_GET['success'] === 'deleted_multiple') { $deleted = isset($_GET['deleted']) ? (int)$_GET['deleted'] : 0; $errors = isset($_GET['errors']) ? (int)$_GET['errors'] : 0; if ($deleted > 0) { echo '
Se eliminaron ' . $deleted . ' destinatarios correctamente.
'; } if ($errors > 0) { echo '
Hubo errores al eliminar ' . $errors . ' destinatarios.
'; } } else { echo "
Operación completada con éxito.
"; } } ?>

Gestionar Destinatarios

Lista de Destinatarios
Plataforma Nombre ID de Plataforma Tipo Idioma Añadido en Acciones