save_user_config.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. <?php
  2. session_start();
  3. function dieAjaxError($message) {
  4. header('HTTP/1.0 403 Forbidden');
  5. header('Content-Type: application/json');
  6. die(json_encode(['success' => false, 'message' => $message]));
  7. }
  8. // Проверка AJAX-запроса
  9. if (empty($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !== 'xmlhttprequest') {
  10. dieAjaxError('Direct access not allowed');
  11. }
  12. // Опционально: CSRF проверка
  13. // if (empty($_POST['csrf']) || $_POST['csrf'] !== $_SESSION['csrf_token']) {
  14. // dieAjaxError('Invalid CSRF token');
  15. // }
  16. define("CONFIG", 1);
  17. $config_file = __DIR__ . '/config.php';
  18. if (!file_exists($config_file)) {
  19. dieAjaxError("Configuration file not found: $config_file");
  20. }
  21. $servers = require $config_file;
  22. // Получаем данные POST в JSON
  23. $input = json_decode(file_get_contents('php://input'), true);
  24. $server_name = $input['server'] ?? '';
  25. $username = $input['username'] ?? '';
  26. $config = $input['config'] ?? '';
  27. if (!isset($servers[$server_name]) || empty($username) || $config === null) {
  28. dieAjaxError('Invalid parameters');
  29. }
  30. // CCD-файл
  31. $ccd_file = $servers[$server_name]['ccd'] . "/" . $username;
  32. // Путь к скрипту
  33. $script_path = PUT_USER_CCD;
  34. // Команда для записи через stdin
  35. $command = sprintf(
  36. 'echo %s | sudo %s %s - 2>&1',
  37. escapeshellarg($config),
  38. escapeshellcmd($script_path),
  39. escapeshellarg($ccd_file)
  40. );
  41. exec($command, $output, $return_var);
  42. if ($return_var !== 0) {
  43. dieAjaxError(implode("\n", $output));
  44. }
  45. // Успешно
  46. header('Content-Type: application/json');
  47. echo json_encode(['success' => true, 'message' => 'Config saved successfully']);