1
0

sql.php 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209
  1. <?php
  2. if (! defined("CONFIG")) die("Not defined");
  3. if (! defined("SQL")) { die("Not defined"); }
  4. function db_escape($connection, $value) {
  5. // Обработка специальных значений
  6. if ($value === null) {
  7. return '';
  8. }
  9. if (is_bool($value)) {
  10. return $value ? 1 : 0;
  11. }
  12. if (is_int($value) || is_float($value)) {
  13. return $value;
  14. }
  15. // Для строковых значений
  16. $string = (string)$value;
  17. if ($connection instanceof PDO) {
  18. // Определяем тип базы данных
  19. $driver = $connection->getAttribute(PDO::ATTR_DRIVER_NAME);
  20. if ($driver === false) {
  21. // Не удалось определить драйвер, используем универсальный метод
  22. return addslashes($string);
  23. }
  24. try {
  25. $quoted = $connection->quote($string);
  26. if ($quoted === false) {
  27. return addslashes($string);
  28. }
  29. // Убираем внешние кавычки для совместимости
  30. if (strlen($quoted) >= 2 && $quoted[0] === "'" && $quoted[strlen($quoted)-1] === "'") {
  31. return substr($quoted, 1, -1);
  32. }
  33. return $quoted;
  34. } catch (Exception $e) {
  35. return addslashes($string);
  36. }
  37. } elseif ($connection instanceof mysqli) {
  38. return mysqli_real_escape_string($connection, $string);
  39. } elseif (is_resource($connection) && get_resource_type($connection) === 'mysql link') {
  40. return mysql_real_escape_string($string, $connection);
  41. } elseif (is_resource($connection) && get_resource_type($connection) === 'pgsql link') {
  42. return pg_escape_string($connection, $string);
  43. } else {
  44. // Последнее средство
  45. return addslashes($string);
  46. }
  47. }
  48. function new_connection ($db_type, $db_host, $db_user, $db_password, $db_name, $db_port = null)
  49. {
  50. // Создаем временный логгер для отладки до установки соединения
  51. $temp_debug_message = function($message) {
  52. error_log("DB_CONNECTION_DEBUG: " . $message);
  53. };
  54. $temp_debug_message("Starting new_connection function");
  55. $temp_debug_message("DB parameters - type: $db_type, host: $db_host, user: $db_user, db: $db_name");
  56. if (function_exists('filter_var') && defined('FILTER_SANITIZE_FULL_SPECIAL_CHARS')) {
  57. $db_host = filter_var($db_host, FILTER_SANITIZE_FULL_SPECIAL_CHARS);
  58. } else {
  59. // Для PHP < 8.1
  60. $db_host = htmlspecialchars($db_host, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
  61. }
  62. $db_name = preg_replace('/[^a-zA-Z0-9_-]/', '', $db_name);
  63. try {
  64. $temp_debug_message("Constructing DSN");
  65. // Определяем DSN в зависимости от типа базы данных
  66. $dsn = "";
  67. $options = [
  68. PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
  69. PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
  70. PDO::ATTR_EMULATE_PREPARES => false,
  71. ];
  72. if ($db_type === 'mysql') {
  73. $dsn = "mysql:host=$db_host;dbname=$db_name;charset=utf8mb4";
  74. if (!empty($db_port)) { $dsn .= ";port=$db_port"; }
  75. } elseif ($db_type === 'pgsql' || $db_type === 'postgresql') {
  76. $dsn = "pgsql:host=$db_host;dbname=$db_name";
  77. if (!empty($db_port)) { $dsn .= ";port=$db_port"; }
  78. $options[PDO::PGSQL_ATTR_DISABLE_PREPARES] = false;
  79. } else {
  80. throw new Exception("Unsupported database type: $db_type. Supported types: mysql, pgsql");
  81. }
  82. $temp_debug_message("DSN: $dsn");
  83. $temp_debug_message("PDO options: " . json_encode($options));
  84. $temp_debug_message("Attempting to create PDO connection");
  85. $result = new PDO($dsn, $db_user, $db_password, $options);
  86. // Устанавливаем кодировку для PostgreSQL
  87. if ($db_type === 'pgsql' || $db_type === 'postgresql') {
  88. $result->exec("SET client_encoding TO 'UTF8'");
  89. }
  90. $temp_debug_message("PDO connection created successfully");
  91. $temp_debug_message("PDO connection info: " . ($result->getAttribute(PDO::ATTR_CONNECTION_STATUS) ?? 'N/A for PostgreSQL'));
  92. // Проверяем наличие атрибутов перед использованием
  93. if ($db_type === 'mysql') {
  94. $temp_debug_message("PDO client version: " . $result->getAttribute(PDO::ATTR_CLIENT_VERSION));
  95. $temp_debug_message("PDO server version: " . $result->getAttribute(PDO::ATTR_SERVER_VERSION));
  96. // Проверка кодировки для MySQL
  97. $stmt = $result->query("SHOW VARIABLES LIKE 'character_set_connection'");
  98. $charset = $stmt->fetch(PDO::FETCH_ASSOC);
  99. $temp_debug_message("Database character set: " . ($charset['Value'] ?? 'not set'));
  100. } elseif ($db_type === 'pgsql' || $db_type === 'postgresql') {
  101. // Проверка кодировки для PostgreSQL
  102. $stmt = $result->query("SHOW server_encoding");
  103. $charset = $stmt->fetch(PDO::FETCH_ASSOC);
  104. $temp_debug_message("PostgreSQL server encoding: " . ($charset['server_encoding'] ?? 'not set'));
  105. // Получаем версию PostgreSQL
  106. $stmt = $result->query("SELECT version()");
  107. $version = $stmt->fetch(PDO::FETCH_ASSOC);
  108. $temp_debug_message("PostgreSQL version: " . ($version['version'] ?? 'unknown'));
  109. }
  110. return $result;
  111. } catch (PDOException $e) {
  112. // Логируем ошибку через error_log, так как соединение не установлено
  113. error_log("DB_CONNECTION_ERROR: Failed to connect to $db_type");
  114. error_log("DB_CONNECTION_ERROR: DSN: $dsn");
  115. error_log("DB_CONNECTION_ERROR: User: $db_user");
  116. error_log("DB_CONNECTION_ERROR: Error code: " . $e->getCode());
  117. error_log("DB_CONNECTION_ERROR: Error message: " . $e->getMessage());
  118. error_log("DB_CONNECTION_ERROR: Trace: " . $e->getTraceAsString());
  119. // Также выводим в консоль для немедленной обратной связи
  120. echo "Error connect to $db_type " . PHP_EOL;
  121. echo "Error message: " . $e->getMessage() . PHP_EOL;
  122. echo "DSN: $dsn" . PHP_EOL;
  123. exit();
  124. } catch (Exception $e) {
  125. // Обработка других исключений (например, неподдерживаемый тип БД)
  126. error_log("DB_CONNECTION_ERROR: " . $e->getMessage());
  127. echo "Error: " . $e->getMessage() . PHP_EOL;
  128. exit();
  129. }
  130. }
  131. /**
  132. * Преобразует ассоциативный массив в человекочитаемый текстовый формат (подобие YAML/Perl hash)
  133. */
  134. function hash_to_text($hash_ref, $indent = 0, &$seen = null) {
  135. if ($seen === null) {
  136. $seen = [];
  137. }
  138. if (!isset($hash_ref)) {
  139. return 'null';
  140. }
  141. if (is_array($hash_ref) && is_assoc($hash_ref)) {
  142. $spaces = str_repeat(' ', $indent);
  143. $lines = [];
  144. $keys = array_keys($hash_ref);
  145. sort($keys);
  146. foreach ($keys as $key) {
  147. $value = $hash_ref[$key];
  148. $formatted_key = preg_match('/^[a-zA-Z_]\w*$/', $key) ? $key : "'" . addslashes($key) . "'";
  149. $formatted_value = '';
  150. if (is_array($value)) {
  151. if (is_assoc($value)) {
  152. $formatted_value = ":\n" . hash_to_text($value, $indent + 1, $seen);
  153. } else {
  154. $formatted_value = array_to_text($value, $indent + 1, $seen);
  155. }
  156. } elseif (is_object($value)) {
  157. // Защита от циклических ссылок для объектов
  158. $obj_id = spl_object_hash($value);
  159. if (isset($seen[$obj_id])) {
  160. $formatted_value = '[circular reference]';
  161. } else {
  162. $seen[$obj_id] = true;
  163. $formatted_value = '[' . get_class($value) . ']';
  164. }
  165. } elseif ($value === null) {
  166. $formatted_value = 'null';
  167. } else {
  168. $formatted_value = "'" . addslashes((string)$value) . "'";
  169. }
  170. if ($formatted_value !== '') {
  171. $lines[] = "$spaces $formatted_key => $formatted_value";
  172. }
  173. }
  174. if (empty($lines)) {
  175. return "$spaces # empty";
  176. }
  177. return implode(",\n", $lines);
  178. } else {
  179. // Не ассоциативный массив или скаляр — обрабатываем как строку
  180. return "'" . (isset($hash_ref) ? addslashes((string)$hash_ref) : '') . "'";
  181. }
  182. }
  183. /**
  184. * Преобразует индексированный массив в текстовый формат
  185. */
  186. function array_to_text($array_ref, $indent = 0, &$seen = null) {
  187. if ($seen === null) {
  188. $seen = [];
  189. }
  190. if (!is_array($array_ref) || empty($array_ref)) {
  191. return '[]';
  192. }
  193. $spaces = str_repeat(' ', $indent);
  194. $lines = [];
  195. foreach ($array_ref as $item) {
  196. $formatted_item = '';
  197. if (is_array($item)) {
  198. if (is_assoc($item)) {
  199. $formatted_item = ":\n" . hash_to_text($item, $indent + 1, $seen);
  200. } else {
  201. $formatted_item = array_to_text($item, $indent + 1, $seen);
  202. }
  203. } elseif (is_object($item)) {
  204. $obj_id = spl_object_hash($item);
  205. if (isset($seen[$obj_id])) {
  206. $formatted_item = '[circular reference]';
  207. } else {
  208. $seen[$obj_id] = true;
  209. $formatted_item = '[' . get_class($item) . ']';
  210. }
  211. } elseif ($item === null) {
  212. $formatted_item = 'null';
  213. } else {
  214. $formatted_item = "'" . addslashes((string)$item) . "'";
  215. }
  216. if ($formatted_item !== '') {
  217. $lines[] = "$spaces $formatted_item";
  218. }
  219. }
  220. if (empty($lines)) {
  221. return "[]";
  222. }
  223. return "[\n" . implode(",\n", $lines) . "\n$spaces]";
  224. }
  225. /**
  226. * Проверяет, является ли массив ассоциативным
  227. */
  228. function is_assoc($array) {
  229. if (!is_array($array) || empty($array)) {
  230. return false;
  231. }
  232. return array_keys($array) !== range(0, count($array) - 1);
  233. }
  234. /**
  235. * Нормализует значение поля: преобразует NULL в 0 для числовых полей или в пустую строку для строковых
  236. *
  237. * @param string $key Имя поля
  238. * @param mixed $value Значение поля
  239. * @return mixed Нормализованное значение
  240. */
  241. function normalize_field_value($key, $value) {
  242. if ($value === null or $value === 'NULL') {
  243. // Регулярное выражение для определения числовых полей
  244. $numeric_field_pattern = '/\b(?:id|_id|count|_count|num|port|size|level|status|type|bytes|byte|_time|_timestamp|_at|time|timestamp|_in|_out|_int|forward|gateway|ip_int|quota|step|vlan|index|snmp|protocol|router|subnet|target|vendor|action|active|blocked|changed|connected|default|deleted|dhcp|discovery|draft|dynamic|enabled|free|hotspot|link|nagios|netflow|notify|office|permanent|poe|queue|rights|save|skip|static|uniq|uplink|vpn)\b/i';
  245. if (preg_match($numeric_field_pattern, $key)) {
  246. return 0;
  247. } else {
  248. return '';
  249. }
  250. }
  251. return $value;
  252. }
  253. /**
  254. * Нормализует всю запись (ассоциативный массив)
  255. *
  256. * @param array $record Запись из БД
  257. * @return array Нормализованная запись
  258. */
  259. function normalize_record($record) {
  260. if (!is_array($record) || empty($record)) {
  261. return $record;
  262. }
  263. $normalized = [];
  264. foreach ($record as $key => $value) {
  265. $normalized[$key] = normalize_field_value($key, $value);
  266. }
  267. return $normalized;
  268. }
  269. /**
  270. * Нормализует массив записей
  271. *
  272. * @param array $records Массив записей из БД
  273. * @return array Нормализованные записи
  274. */
  275. function normalize_records($records) {
  276. if (!is_array($records) || empty($records)) {
  277. return $records;
  278. }
  279. $normalized = [];
  280. foreach ($records as $index => $record) {
  281. $normalized[$index] = normalize_record($record);
  282. }
  283. return $normalized;
  284. }
  285. function run_sql($db, $query)
  286. {
  287. // Проверка прав доступа для UPDATE, DELETE, INSERT
  288. if (preg_match('/^\s*(UPDATE|DELETE|INSERT)/i', $query)) {
  289. $table_name = null;
  290. // Определяем имя таблицы для проверки прав
  291. if (preg_match('/^\s*UPDATE\s+(\w+)/i', $query, $matches)) {
  292. $table_name = $matches[1];
  293. $operation = 'update';
  294. } elseif (preg_match('/^\s*DELETE\s+FROM\s+(\w+)/i', $query, $matches)) {
  295. $table_name = $matches[1];
  296. $operation = 'del';
  297. } elseif (preg_match('/^\s*INSERT\s+INTO\s+(\w+)/i', $query, $matches)) {
  298. $table_name = $matches[1];
  299. $operation = 'add';
  300. }
  301. // Проверяем права доступа
  302. if ($table_name && !allow_update($table_name, $operation)) {
  303. LOG_DEBUG($db, "Access denied: $query");
  304. return false;
  305. }
  306. }
  307. // Выполняем запрос
  308. try {
  309. $stmt = $db->query($query);
  310. // Возвращаем результат в зависимости от типа запроса
  311. if (preg_match('/^\s*SELECT/i', $query)) {
  312. // Для SELECT возвращаем PDOStatement
  313. return $stmt;
  314. } elseif (preg_match('/^\s*INSERT/i', $query)) {
  315. // Для INSERT возвращаем ID вставленной записи
  316. return $db->lastInsertId();
  317. } elseif (preg_match('/^\s*(UPDATE|DELETE)/i', $query)) {
  318. // Для UPDATE/DELETE возвращаем количество затронутых строк
  319. return $stmt->rowCount();
  320. }
  321. // Для других типов запросов возвращаем результат как есть
  322. return $stmt;
  323. } catch (PDOException $e) {
  324. LOG_ERROR($db, "At simple SQL: $query :" . $e->getMessage());
  325. return false;
  326. }
  327. }
  328. function get_count_records($db, $table, $filter)
  329. {
  330. if (!empty($filter)) {
  331. $filter = 'where ' . $filter;
  332. }
  333. $t_count = get_record_sql($db, "SELECT count(*) as cnt FROM $table $filter");
  334. if (!empty($t_count) and isset($t_count['cnt'])) { return $t_count['cnt']; }
  335. return 0;
  336. }
  337. /**
  338. * Получить одну запись из таблицы по фильтру
  339. */
  340. function get_record($db, $table, $filter) {
  341. if (!isset($table) || !isset($filter)) {
  342. return null;
  343. }
  344. if (preg_match('/=$/', $filter)) {
  345. LOG_ERROR($db, "Search record ($table) with illegal filter $filter! Skip command.");
  346. return null;
  347. }
  348. $sql = "SELECT * FROM $table WHERE $filter";
  349. return get_record_sql($db, $sql);
  350. }
  351. /**
  352. * Получить несколько записей из таблицы по фильтру
  353. */
  354. function get_records($db, $table, $filter = '') {
  355. if (!isset($table)) {
  356. return [];
  357. }
  358. if (!empty($filter)) {
  359. if (preg_match('/=$/', $filter)) {
  360. LOG_ERROR($db, "Search record ($table) with illegal filter $filter! Skip command.");
  361. return [];
  362. }
  363. $filter = "WHERE $filter";
  364. }
  365. $sql = "SELECT * FROM $table $filter";
  366. return get_records_sql($db, $sql);
  367. }
  368. /**
  369. * Получить одну запись по произвольному SQL-запросу
  370. */
  371. function get_record_sql($db, $sql) {
  372. if (empty($sql)) {
  373. return null;
  374. }
  375. // Добавляем LIMIT 1, если его нет
  376. if (!preg_match('/\bLIMIT\s+\d+$/i', $sql)) {
  377. $sql .= " LIMIT 1";
  378. }
  379. $result = get_records_sql($db, $sql);
  380. // Возвращаем первую запись или null
  381. return !empty($result) ? $result[0] : null;
  382. }
  383. /**
  384. * Получить несколько записей по произвольному SQL-запросу
  385. */
  386. function get_records_sql($db, $sql) {
  387. $result = [];
  388. if (empty($sql)) {
  389. return $result;
  390. }
  391. try {
  392. $stmt = $db->query($sql);
  393. $records = $stmt->fetchAll(PDO::FETCH_ASSOC);
  394. if (!empty($records)) {
  395. $result = normalize_records($records);
  396. }
  397. return $result;
  398. } catch (PDOException $e) {
  399. LOG_ERROR($db, "SQL: $sql : " . $e->getMessage());
  400. return $result;
  401. }
  402. }
  403. /**
  404. * Получить одно значение поля по SQL-запросу
  405. */
  406. function get_single_field($db, $sql) {
  407. $record = get_record_sql($db, $sql);
  408. if (!empty($record) && is_array($record)) {
  409. // Получаем первое значение из записи
  410. return reset($record) ?: 0;
  411. }
  412. return 0;
  413. }
  414. /**
  415. * Получить ID записи из таблицы по фильтру
  416. */
  417. function get_id_record($db, $table, $filter) {
  418. if (empty($filter)) {
  419. return 0;
  420. }
  421. $record = get_record($db, $table, $filter);
  422. return !empty($record['id']) ? $record['id'] : 0;
  423. }
  424. function set_changed($db, $id)
  425. {
  426. $auth['changed'] = 1;
  427. update_record($db, "user_auth", "id=" . $id, $auth);
  428. }
  429. //action: add,update,del
  430. function allow_update($table, $action = 'update', $field = '')
  431. {
  432. //always allow modification for tables
  433. if (preg_match('/(variables|dns_cache|worklog|sessions)/i', $table)) {
  434. return 1;
  435. }
  436. if (isset($_SESSION['login'])) {
  437. $work_user = $_SESSION['login'];
  438. }
  439. if (isset($_SESSION['user_id'])) {
  440. $work_id = $_SESSION['user_id'];
  441. }
  442. if (isset($_SESSION['acl'])) {
  443. $user_level = $_SESSION['acl'];
  444. }
  445. if (!isset($work_user) or !isset($work_id) or empty($user_level)) {
  446. return 0;
  447. }
  448. //always allow Administrator
  449. if ($user_level == 1) {
  450. return 1;
  451. }
  452. //always forbid ViewOnly
  453. if ($user_level == 3) {
  454. return 0;
  455. }
  456. //allow tables for Operator
  457. if (preg_match('/(dns_queue|user_auth_alias)/i', $table)) {
  458. return 1;
  459. }
  460. if ($action == 'update') {
  461. $operator_acl = [
  462. 'user_auth' => [
  463. 'description' => '1',
  464. 'dns_name' => '1',
  465. 'dns_ptr_only' => '1',
  466. 'firmware' => '1',
  467. 'link_check' => '1',
  468. 'nagios' => '1',
  469. 'nagios_handler' => '1',
  470. 'Wikiname' => '1'
  471. ],
  472. 'user_list' => [
  473. 'fio' => '1',
  474. 'login' => '1',
  475. ],
  476. ];
  477. if (!isset($operator_acl[$table])) {
  478. return 0;
  479. }
  480. if (isset($operator_acl[$table]) and empty($field)) {
  481. return 1;
  482. }
  483. if (!isset($operator_acl[$table][$field])) {
  484. return 0;
  485. }
  486. if (empty($operator_acl[$table][$field]) or $operator_acl[$table][$field] == '0') {
  487. return 0;
  488. }
  489. return 1;
  490. }
  491. return 0;
  492. }
  493. function update_record($db, $table, $filter, $newvalue)
  494. {
  495. if (!isset($table)) {
  496. # LOG_WARNING($db, "Change record for unknown table! Skip command.");
  497. return;
  498. }
  499. if (!isset($filter)) {
  500. # LOG_WARNING($db, "Change record ($table) with empty filter! Skip command.");
  501. return;
  502. }
  503. if (preg_match('/=$/', $filter)) {
  504. LOG_WARNING($db, "Change record ($table) with illegal filter $filter! Skip command.");
  505. return;
  506. }
  507. if (!isset($newvalue)) {
  508. # LOG_WARNING($db, "Change record ($table [ $filter ]) with empty data! Skip command.");
  509. return;
  510. }
  511. if (!allow_update($table, 'update')) {
  512. LOG_INFO($db, "Access denied: $table [ $filter ]");
  513. return 1;
  514. }
  515. $old_sql = "SELECT * FROM $table WHERE $filter";
  516. try {
  517. $stmt = $db->query($old_sql);
  518. $old = $stmt->fetch(PDO::FETCH_ASSOC);
  519. } catch (PDOException $e) {
  520. LOG_ERROR($db, "SQL: $old_sql :" . $e->getMessage());
  521. return;
  522. }
  523. $rec_id = NULL;
  524. if (!empty($old['id'])) {
  525. $rec_id = $old['id'];
  526. }
  527. $changed_log = '';
  528. $set_parts = [];
  529. $params = [];
  530. $network_changed = 0;
  531. $dhcp_changed = 0;
  532. $dns_changed = 0;
  533. $acl_fields = [
  534. 'ip' => '1',
  535. 'ip_int' => '1',
  536. 'enabled' => '1',
  537. 'dhcp' => '1',
  538. 'filter_group_id' => '1',
  539. 'deleted' => '1',
  540. 'dhcp_acl' => '1',
  541. 'queue_id' => '1',
  542. 'mac' => '1',
  543. 'blocked' => '1',
  544. ];
  545. $dhcp_fields = [
  546. 'ip' => '1',
  547. 'dhcp' => '1',
  548. 'deleted' => '1',
  549. 'dhcp_option_set' =>'1',
  550. 'dhcp_acl' => '1',
  551. 'mac' => '1',
  552. ];
  553. $dns_fields = [
  554. 'ip' => '1',
  555. 'dns_name' => '1',
  556. 'dns_ptr_only' => '1',
  557. 'alias' => '1',
  558. ];
  559. foreach ($newvalue as $key => $value) {
  560. if (!allow_update($table, 'update', $key)) {
  561. continue;
  562. }
  563. if (!isset($value)) {
  564. $value = '';
  565. }
  566. $value = trim($value);
  567. if (isset($old[$key]) && strcmp($old[$key], $value) == 0) {
  568. continue;
  569. }
  570. if ($table === "user_auth") {
  571. if (!empty($acl_fields["$key"])) {
  572. $network_changed = 1;
  573. }
  574. if (!empty($dhcp_fields["$key"])) {
  575. $dhcp_changed = 1;
  576. }
  577. if (!empty($dns_fields["$key"])) {
  578. $dns_changed = 1;
  579. }
  580. }
  581. if ($table === "user_auth_alias") {
  582. if (!empty($dns_fields["$key"])) {
  583. $dns_changed = 1;
  584. }
  585. }
  586. if (!preg_match('/password/i', $key)) {
  587. $changed_log = $changed_log . " $key => $value (old: " . ($old[$key] ?? '') . "),";
  588. }
  589. $set_parts[] = "$key = ?";
  590. $params[] = $value;
  591. }
  592. if ($table === "user_auth" and $dns_changed) {
  593. if (!empty($old['dns_name']) and !empty($old['ip']) and !$old['dns_ptr_only'] and !preg_match('/\.$/', $old['dns_name'])) {
  594. $del_dns['name_type'] = 'A';
  595. $del_dns['name'] = $old['dns_name'];
  596. $del_dns['value'] = $old['ip'];
  597. $del_dns['type'] = 'del';
  598. if (!empty($rec_id)) {
  599. $del_dns['auth_id'] = $rec_id;
  600. }
  601. insert_record($db, 'dns_queue', $del_dns);
  602. }
  603. if (!empty($old['dns_name']) and !empty($old['ip']) and $old['dns_ptr_only'] and !preg_match('/\.$/', $old['dns_name'])) {
  604. $del_dns['name_type'] = 'PTR';
  605. $del_dns['name'] = $old['dns_name'];
  606. $del_dns['value'] = $old['ip'];
  607. $del_dns['type'] = 'del';
  608. if (!empty($rec_id)) {
  609. $del_dns['auth_id'] = $rec_id;
  610. }
  611. insert_record($db, 'dns_queue', $del_dns);
  612. }
  613. if (!empty($newvalue['dns_name']) and !empty($newvalue['ip']) and !$newvalue['dns_ptr_only'] and !preg_match('/\.$/', $newvalue['dns_name'])) {
  614. $new_dns['name_type'] = 'A';
  615. $new_dns['name'] = $newvalue['dns_name'];
  616. $new_dns['value'] = $newvalue['ip'];
  617. $new_dns['type'] = 'add';
  618. if (!empty($rec_id)) {
  619. $new_dns['auth_id'] = $rec_id;
  620. }
  621. insert_record($db, 'dns_queue', $new_dns);
  622. }
  623. if (!empty($newvalue['dns_name']) and !empty($newvalue['ip']) and $newvalue['dns_ptr_only'] and !preg_match('/\.$/', $newvalue['dns_name'])) {
  624. $new_dns['name_type'] = 'PTR';
  625. $new_dns['name'] = $newvalue['dns_name'];
  626. $new_dns['value'] = $newvalue['ip'];
  627. $new_dns['type'] = 'add';
  628. if (!empty($rec_id)) {
  629. $new_dns['auth_id'] = $rec_id;
  630. }
  631. insert_record($db, 'dns_queue', $new_dns);
  632. }
  633. }
  634. if ($table === "user_auth_alias" and $dns_changed) {
  635. $auth_id = NULL;
  636. if ($old['auth_id']) {
  637. $auth_id = $old['auth_id'];
  638. }
  639. if (!empty($old['alias']) and !preg_match('/\.$/', $old['alias'])) {
  640. $del_dns['name_type'] = 'CNAME';
  641. $del_dns['name'] = $old['alias'];
  642. $del_dns['type'] = 'del';
  643. if (!empty($auth_id)) {
  644. $del_dns['auth_id'] = $auth_id;
  645. $del_dns['value'] = get_dns_name($db, $auth_id);
  646. }
  647. insert_record($db, 'dns_queue', $del_dns);
  648. }
  649. if (!empty($newvalue['alias']) and !preg_match('/\.$/', $newvalue['alias'])) {
  650. $new_dns['name_type'] = 'CNAME';
  651. $new_dns['name'] = $newvalue['alias'];
  652. $new_dns['type'] = 'add';
  653. if (!empty($auth_id)) {
  654. $new_dns['auth_id'] = $auth_id;
  655. $new_dns['value'] = get_dns_name($db, $auth_id);
  656. }
  657. insert_record($db, 'dns_queue', $new_dns);
  658. }
  659. }
  660. if (empty($set_parts)) {
  661. return 1;
  662. }
  663. if ($network_changed) {
  664. $set_parts[] = "changed = '1'";
  665. }
  666. if ($dhcp_changed) {
  667. $set_parts[] = "dhcp_changed = '1'";
  668. }
  669. $changed_log = substr_replace($changed_log, "", -1);
  670. $run_sql = implode(", ", $set_parts);
  671. if ($table === 'user_auth') {
  672. $changed_time = GetNowTimeString();
  673. $run_sql .= ", changed_time = ?";
  674. $params[] = $changed_time;
  675. }
  676. $new_sql = "UPDATE $table SET $run_sql WHERE $filter";
  677. LOG_DEBUG($db, "Run sql: $new_sql");
  678. try {
  679. $stmt = $db->prepare($new_sql);
  680. $sql_result = $stmt->execute($params);
  681. if (!$sql_result) {
  682. LOG_ERROR($db, "UPDATE Request: $new_sql");
  683. return;
  684. }
  685. if ($table !== "sessions") {
  686. LOG_VERBOSE($db, "Change table $table WHERE $filter set $changed_log");
  687. }
  688. return $sql_result;
  689. } catch (PDOException $e) {
  690. LOG_ERROR($db, "SQL: $new_sql :" . $e->getMessage());
  691. return;
  692. }
  693. }
  694. function delete_record($db, $table, $filter)
  695. {
  696. if (!allow_update($table, 'del')) {
  697. # LOG_INFO($db, "User does not have write permission");
  698. return;
  699. }
  700. if (!isset($table)) {
  701. # LOG_WARNING($db, "Delete FROM unknown table! Skip command.");
  702. return;
  703. }
  704. if (!isset($filter)) {
  705. LOG_WARNING($db, "Delete FROM table $table with empty filter! Skip command.");
  706. return;
  707. }
  708. if (preg_match('/=$/', $filter)) {
  709. LOG_WARNING($db, "Change record ($table) with illegal filter $filter! Skip command.");
  710. return;
  711. }
  712. $old_sql = "SELECT * FROM $table WHERE $filter";
  713. try {
  714. $stmt = $db->query($old_sql);
  715. $old = $stmt->fetch(PDO::FETCH_ASSOC);
  716. } catch (PDOException $e) {
  717. LOG_ERROR($db, "SQL: $old_sql :" . $e->getMessage());
  718. return;
  719. }
  720. $rec_id = NULL;
  721. if (!empty($old['id'])) {
  722. $rec_id = $old['id'];
  723. }
  724. $changed_log = 'record: ';
  725. if (!empty($old)) {
  726. asort($old, SORT_STRING);
  727. $old = array_reverse($old, 1);
  728. foreach ($old as $key => $value) {
  729. if (empty($value)) {
  730. continue;
  731. }
  732. if (preg_match('/action/', $key)) {
  733. continue;
  734. }
  735. if (preg_match('/status/', $key)) {
  736. continue;
  737. }
  738. if (preg_match('/time/', $key)) {
  739. continue;
  740. }
  741. if (preg_match('/found/', $key)) {
  742. continue;
  743. }
  744. $changed_log = $changed_log . " $key => $value,";
  745. }
  746. }
  747. $delete_it = 1;
  748. //never delete user ip record
  749. if ($table === 'user_auth') {
  750. $delete_it = 0;
  751. $changed_time = GetNowTimeString();
  752. $new_sql = "UPDATE $table SET deleted=1, changed=1, changed_time='" . $changed_time . "' WHERE $filter";
  753. LOG_DEBUG($db, "Run sql: $new_sql");
  754. try {
  755. $sql_result = $db->exec($new_sql);
  756. if ($sql_result === false) {
  757. LOG_ERROR($db, "UPDATE Request (from delete)");
  758. return;
  759. }
  760. } catch (PDOException $e) {
  761. LOG_ERROR($db, "SQL: $new_sql :" . $e->getMessage());
  762. return;
  763. }
  764. //dns - A-record
  765. if (!empty($old['dns_name']) and !empty($old['ip']) and !$old['dns_ptr_only'] and !preg_match('/\.$/', $old['dns_name'])) {
  766. $del_dns['name_type'] = 'A';
  767. $del_dns['name'] = $old['dns_name'];
  768. $del_dns['value'] = $old['ip'];
  769. $del_dns['type'] = 'del';
  770. if (!empty($rec_id)) {
  771. $del_dns['auth_id'] = $rec_id;
  772. }
  773. insert_record($db, 'dns_queue', $del_dns);
  774. }
  775. //ptr
  776. if (!empty($old['dns_name']) and !empty($old['ip']) and $old['dns_ptr_only'] and !preg_match('/\.$/', $old['dns_name'])) {
  777. $del_dns['name_type'] = 'PTR';
  778. $del_dns['name'] = $old['dns_name'];
  779. $del_dns['value'] = $old['ip'];
  780. $del_dns['type'] = 'del';
  781. if (!empty($rec_id)) {
  782. $del_dns['auth_id'] = $rec_id;
  783. }
  784. insert_record($db, 'dns_queue', $del_dns);
  785. }
  786. LOG_VERBOSE($db, "Deleted FROM table $table WHERE $filter $changed_log");
  787. return $changed_log;
  788. }
  789. //never delete permanent user
  790. if ($table === 'user_list' and $old['permanent']) { return; }
  791. //remove aliases
  792. if ($table === 'user_auth_alias') {
  793. //dns
  794. if (!empty($old['alias']) and !preg_match('/\.$/', $old['alias'])) {
  795. $del_dns['name_type'] = 'CNAME';
  796. $del_dns['name'] = $old['alias'];
  797. $del_dns['value'] = '';
  798. $del_dns['type'] = 'del';
  799. if (!empty($old['auth_id'])) {
  800. $del_dns['auth_id'] = $old['auth_id'];
  801. $del_dns['value'] = get_dns_name($db, $old['auth_id']);
  802. }
  803. insert_record($db, 'dns_queue', $del_dns);
  804. }
  805. }
  806. if ($delete_it) {
  807. $new_sql = "DELETE FROM $table WHERE $filter";
  808. LOG_DEBUG($db, "Run sql: $new_sql");
  809. try {
  810. $sql_result = $db->exec($new_sql);
  811. if ($sql_result === false) {
  812. LOG_ERROR($db, "DELETE Request: $new_sql");
  813. return;
  814. }
  815. } catch (PDOException $e) {
  816. LOG_ERROR($db, "SQL: $new_sql : " . $e->getMessage());
  817. return;
  818. }
  819. } else { return; }
  820. if ($table !== "sessions") {
  821. LOG_VERBOSE($db, "Deleted FROM table $table WHERE $filter $changed_log");
  822. }
  823. return $changed_log;
  824. }
  825. function insert_record($db, $table, $newvalue)
  826. {
  827. if (!allow_update($table, 'add')) {
  828. // LOG_WARNING($db, "User does not have write permission");
  829. return;
  830. }
  831. if (!isset($table) || empty($table)) {
  832. // LOG_WARNING($db, "Create record for unknown table! Skip command.");
  833. return;
  834. }
  835. if (empty($newvalue) || !is_array($newvalue)) {
  836. // LOG_WARNING($db, "Create record ($table) with empty data! Skip command.");
  837. return;
  838. }
  839. // Валидация имени таблицы (защита от SQL-инъекций через имя таблицы)
  840. if (!preg_match('/^[a-z_][a-z0-9_]*$/', $table)) {
  841. // LOG_WARNING($db, "Invalid table name: $table");
  842. return;
  843. }
  844. $changed_log = '';
  845. $field_list = [];
  846. $value_list = [];
  847. $params = [];
  848. foreach ($newvalue as $key => $value) {
  849. // Валидация имени колонки
  850. if (!preg_match('/^[a-z_][a-z0-9_]*$/', $key)) {
  851. // Пропускаем недопустимые имена колонок
  852. continue;
  853. }
  854. // Обработка пустых значений
  855. if ('' === $value && '0' !== $value) {
  856. $value = null; // или оставить как '', но null безопаснее для SQL
  857. } else {
  858. $value = trim((string)$value);
  859. }
  860. // Логирование (без паролей)
  861. if (!preg_match('/password/i', $key)) {
  862. $changed_log .= " $key => " . ($value ?? 'NULL') . ",";
  863. }
  864. $field_list[] = $key;
  865. $value_list[] = '?';
  866. $params[] = $value;
  867. }
  868. if (empty($field_list)) {
  869. return;
  870. }
  871. // Формируем SQL
  872. $field_list_str = implode(',', $field_list);
  873. $value_list_str = implode(',', $value_list);
  874. $new_sql = "INSERT INTO $table ($field_list_str) VALUES ($value_list_str)";
  875. LOG_DEBUG($db, "Run sql: $new_sql");
  876. try {
  877. $stmt = $db->prepare($new_sql);
  878. $sql_result = $stmt->execute($params);
  879. if (!$sql_result) {
  880. LOG_ERROR($db, "INSERT Request");
  881. return;
  882. }
  883. $last_id = $db->lastInsertId();
  884. if ($table !== "sessions") {
  885. LOG_VERBOSE($db, "Create record in table $table: $changed_log with id: $last_id");
  886. }
  887. if ($table === 'user_auth') {
  888. run_sql($db, "UPDATE user_auth SET changed=1, dhcp_changed=1 WHERE id=" . $last_id);
  889. }
  890. if ($table === 'user_auth_alias') {
  891. //dns
  892. if (!empty($newvalue['alias']) and !preg_match('/\.$/', $newvalue['alias'])) {
  893. $add_dns['name_type'] = 'CNAME';
  894. $add_dns['name'] = $newvalue['alias'];
  895. $add_dns['value'] = get_dns_name($db, $newvalue['auth_id']);
  896. $add_dns['type'] = 'add';
  897. $add_dns['auth_id'] = $newvalue['auth_id'];
  898. insert_record($db, 'dns_queue', $add_dns);
  899. }
  900. }
  901. if ($table === 'user_auth') {
  902. //dns - A-record
  903. if (!empty($newvalue['dns_name']) and !empty($newvalue['ip']) and !$newvalue['dns_ptr_only'] and !preg_match('/\.$/', $newvalue['dns_name'])) {
  904. $add_dns['name_type'] = 'A';
  905. $add_dns['name'] = $newvalue['dns_name'];
  906. $add_dns['value'] = $newvalue['ip'];
  907. $add_dns['type'] = 'add';
  908. $add_dns['auth_id'] = $last_id;
  909. insert_record($db, 'dns_queue', $add_dns);
  910. }
  911. //dns - ptr
  912. if (!empty($newvalue['dns_name']) and !empty($newvalue['ip']) and $newvalue['dns_ptr_only'] and !preg_match('/\.$/', $newvalue['dns_name'])) {
  913. $add_dns['name_type'] = 'PTR';
  914. $add_dns['name'] = $newvalue['dns_name'];
  915. $add_dns['value'] = $newvalue['ip'];
  916. $add_dns['type'] = 'add';
  917. $add_dns['auth_id'] = $last_id;
  918. insert_record($db, 'dns_queue', $add_dns);
  919. }
  920. }
  921. return $last_id;
  922. } catch (PDOException $e) {
  923. LOG_ERROR($db, "SQL: $new_sql :" . $e->getMessage());
  924. return;
  925. }
  926. }
  927. function dump_record($db, $table, $filter)
  928. {
  929. $result = '';
  930. $old = get_record($db, $table, $filter);
  931. if (empty($old)) {
  932. return $result;
  933. }
  934. $result = 'record: ' . get_rec_str($old);
  935. return $result;
  936. }
  937. function get_rec_str($array)
  938. {
  939. $result = '';
  940. foreach ($array as $key => $value) {
  941. $result .= "[" . $key . "]=" . $value . ", ";
  942. }
  943. $result = preg_replace('/,\s+$/', '', $result);
  944. return $result;
  945. }
  946. function get_diff_rec($db, $table, $filter, $newvalue, $only_changed = false)
  947. {
  948. if (!isset($table) || !isset($filter) || !isset($newvalue)) {
  949. return '';
  950. }
  951. $old_sql = "SELECT * FROM $table WHERE $filter";
  952. try {
  953. $stmt = $db->query($old_sql);
  954. $old = $stmt->fetch(PDO::FETCH_ASSOC);
  955. if (!$old) {
  956. // Запись не найдена — возможно, ошибка или новая запись
  957. return "Record not found for filter: $filter";
  958. }
  959. $changed = [];
  960. $unchanged = [];
  961. foreach ($newvalue as $key => $new_val) {
  962. // Пропускаем ключи, которых нет в старой записи (например, служебные поля)
  963. if (!array_key_exists($key, $old)) {
  964. continue;
  965. }
  966. $old_val = $old[$key];
  967. // Сравниваем как строки, но аккуратно с null
  968. $old_str = ($old_val === null) ? '' : (string)$old_val;
  969. $new_str = ($new_val === null) ? '' : (string)$new_val;
  970. if ($old_str !== $new_str) {
  971. $changed[$key] = $new_str . ' [ old: ' . $old_str . ' ]';
  972. } else {
  973. $unchanged[$key] = $old_val;
  974. }
  975. }
  976. if ($only_changed) {
  977. return empty($changed) ? '' : hash_to_text($changed);
  978. }
  979. $output = '';
  980. if (!empty($changed)) {
  981. $output .= hash_to_text($changed);
  982. } else {
  983. $output .= "# no changes";
  984. }
  985. if (!empty($unchanged)) {
  986. $output .= "\r\nHas not changed:\r\n" . hash_to_text($unchanged);
  987. }
  988. return $output;
  989. } catch (PDOException $e) {
  990. LOG_ERROR($db, "SQL: $old_sql :" . $e->getMessage());
  991. return '';
  992. }
  993. }
  994. function delete_user_auth($db, $id) {
  995. $msg = '';
  996. $record = get_record_sql($db, 'SELECT * FROM user_auth WHERE id=' . $id);
  997. $txt_record = hash_to_text($record);
  998. // remove aliases
  999. $t_user_auth_alias = get_records_sql($db, 'SELECT * FROM user_auth_alias WHERE auth_id=' . $id);
  1000. if (!empty($t_user_auth_alias)) {
  1001. foreach ($t_user_auth_alias as $row) {
  1002. $alias_txt = record_to_txt($db, 'user_auth_alias', 'id=' . $row['id']);
  1003. if (delete_record($db, 'user_auth_alias', 'id=' . $row['id'])) {
  1004. $msg = "Deleting an alias: " . $alias_txt . "::Success!\n" . $msg;
  1005. } else {
  1006. $msg = "Deleting an alias: " . $alias_txt . "::Fail!\n" . $msg;
  1007. }
  1008. }
  1009. }
  1010. // remove connections
  1011. run_sql($db, 'DELETE FROM connections WHERE auth_id=' . $id);
  1012. // remove user auth record
  1013. $changes = delete_record($db, "user_auth", "id=" . $id);
  1014. if ($changes) {
  1015. $msg = "Deleting ip-record: " . $txt_record . "::Success!\n" . $msg;
  1016. } else {
  1017. $msg = "Deleting ip-record: " . $txt_record . "::Fail!\n" . $msg;
  1018. }
  1019. LOG_WARNING($db, $msg);
  1020. $send_alert_delete = isNotifyDelete(get_notify_subnet($db, $record['ip']));
  1021. if ($send_alert_delete) { email(L_WARNING,$msg); }
  1022. return $changes;
  1023. }
  1024. function delete_user($db,$id)
  1025. {
  1026. //remove user record
  1027. $changes = delete_record($db, "user_list", "id=" . $id);
  1028. //if fail - exit
  1029. if (!isset($changes) or empty($changes)) { return; }
  1030. //remove auth records
  1031. $t_user_auth = get_records($db,'user_auth',"user_id=$id");
  1032. if (!empty($t_user_auth)) {
  1033. foreach ( $t_user_auth as $row ) { delete_user_auth($db,$row['id']); }
  1034. }
  1035. //remove device
  1036. $device = get_record($db, "devices", "user_id='$id'");
  1037. if (!empty($device)) {
  1038. LOG_INFO($db, "Delete device for user id: $id ".dump_record($db,'devices','user_id='.$id));
  1039. unbind_ports($db, $device['id']);
  1040. run_sql($db, "DELETE FROM connections WHERE device_id=" . $device['id']);
  1041. run_sql($db, "DELETE FROM device_l3_interfaces WHERE device_id=" . $device['id']);
  1042. run_sql($db, "DELETE FROM device_ports WHERE device_id=" . $device['id']);
  1043. run_sql($db, "DELETE FROM device_filter_instances WHERE device_id=" . $device['id']);
  1044. run_sql($db, "DELETE FROM gateway_subnets WHERE device_id=".$device['id']);
  1045. delete_record($db, "devices", "id=" . $device['id']);
  1046. }
  1047. //remove auth assign rules
  1048. run_sql($db, "DELETE FROM auth_rules WHERE user_id=$id");
  1049. return $changes;
  1050. }
  1051. function delete_device($db,$id)
  1052. {
  1053. LOG_INFO($db, "Try delete device id: $id ".dump_record($db,'devices','id='.$id));
  1054. //remove user record
  1055. $changes = delete_record($db, "devices", "id=" . $id);
  1056. //if fail - exit
  1057. if (!isset($changes) or empty($changes)) {
  1058. LOG_INFO($db,"Device id: $id has not been deleted");
  1059. return;
  1060. }
  1061. unbind_ports($db, $id);
  1062. run_sql($db, "DELETE FROM connections WHERE device_id=" . $id);
  1063. run_sql($db, "DELETE FROM device_l3_interfaces WHERE device_id=" . $id);
  1064. run_sql($db, "DELETE FROM device_ports WHERE device_id=" . $id);
  1065. run_sql($db, "DELETE FROM device_filter_instances WHERE device_id=" . $id);
  1066. run_sql($db, "DELETE FROM gateway_subnets WHERE device_id=".$id);
  1067. return $changes;
  1068. }
  1069. function record_to_txt($db, $table, $id) {
  1070. $record = get_record_sql($db, 'SELECT * FROM ' . $table . ' WHERE id =' . $id);
  1071. return hash_to_text($record);
  1072. }
  1073. $db_link = new_connection(DB_TYPE, DB_HOST, DB_USER, DB_PASS, DB_NAME);
  1074. ?>