sql.php 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195
  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. // PDO::quote() может вернуть false при ошибке
  19. try {
  20. $quoted = $connection->quote($string);
  21. if ($quoted === false) {
  22. // Если quote() не сработал, используем addslashes
  23. return addslashes($string);
  24. }
  25. // Убираем внешние кавычки
  26. if (strlen($quoted) >= 2 && $quoted[0] === "'" && $quoted[strlen($quoted)-1] === "'") {
  27. return substr($quoted, 1, -1);
  28. }
  29. return $quoted;
  30. } catch (Exception $e) {
  31. // В случае ошибки возвращаем addslashes
  32. return addslashes($string);
  33. }
  34. } elseif ($connection instanceof mysqli) {
  35. return mysqli_real_escape_string($connection, $string);
  36. } elseif (is_resource($connection) && get_resource_type($connection) === 'mysql link') {
  37. return mysql_real_escape_string($string, $connection);
  38. } elseif ($connection instanceof PostgreSQL) {
  39. return pg_escape_string($connection, $string);
  40. } else {
  41. return addslashes($string);
  42. }
  43. }
  44. function new_connection ($db_type, $db_host, $db_user, $db_password, $db_name)
  45. {
  46. // Создаем временный логгер для отладки до установки соединения
  47. $temp_debug_message = function($message) {
  48. error_log("DB_CONNECTION_DEBUG: " . $message);
  49. };
  50. $temp_debug_message("Starting new_connection function");
  51. $temp_debug_message("DB parameters - type: $db_type, host: $db_host, user: $db_user, db: $db_name");
  52. try {
  53. $temp_debug_message("Constructing DSN");
  54. // Определяем DSN в зависимости от типа базы данных
  55. $dsn = "";
  56. $options = [
  57. PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
  58. PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
  59. PDO::ATTR_EMULATE_PREPARES => false,
  60. ];
  61. if ($db_type === 'mysql') {
  62. $dsn = "mysql:host=$db_host;dbname=$db_name;charset=utf8mb4";
  63. $options[PDO::MYSQL_ATTR_INIT_COMMAND] = "SET NAMES utf8mb4";
  64. } elseif ($db_type === 'pgsql' || $db_type === 'postgresql') {
  65. $dsn = "pgsql:host=$db_host;dbname=$db_name;options='--client_encoding=UTF8'";
  66. $options[PDO::ATTR_PERSISTENT] = true; // Опционально: включение постоянных соединений для PostgreSQL
  67. } else {
  68. throw new Exception("Unsupported database type: $db_type. Supported types: mysql, pgsql");
  69. }
  70. $temp_debug_message("DSN: $dsn");
  71. $temp_debug_message("PDO options: " . json_encode($options));
  72. $temp_debug_message("Attempting to create PDO connection");
  73. $result = new PDO($dsn, $db_user, $db_password, $options);
  74. // Теперь у нас есть соединение, можем использовать LOG_DEBUG
  75. $temp_debug_message("PDO connection created successfully");
  76. $temp_debug_message("PDO connection info: " . ($result->getAttribute(PDO::ATTR_CONNECTION_STATUS) ?? 'N/A for PostgreSQL'));
  77. // Проверяем наличие атрибутов перед использованием
  78. if ($db_type === 'mysql') {
  79. $temp_debug_message("PDO client version: " . $result->getAttribute(PDO::ATTR_CLIENT_VERSION));
  80. $temp_debug_message("PDO server version: " . $result->getAttribute(PDO::ATTR_SERVER_VERSION));
  81. // Проверка кодировки для MySQL
  82. $stmt = $result->query("SHOW VARIABLES LIKE 'character_set_connection'");
  83. $charset = $stmt->fetch(PDO::FETCH_ASSOC);
  84. $temp_debug_message("Database character set: " . ($charset['Value'] ?? 'not set'));
  85. } elseif ($db_type === 'pgsql' || $db_type === 'postgresql') {
  86. // Проверка кодировки для PostgreSQL
  87. $stmt = $result->query("SHOW server_encoding");
  88. $charset = $stmt->fetch(PDO::FETCH_ASSOC);
  89. $temp_debug_message("PostgreSQL server encoding: " . ($charset['server_encoding'] ?? 'not set'));
  90. // Получаем версию PostgreSQL
  91. $stmt = $result->query("SELECT version()");
  92. $version = $stmt->fetch(PDO::FETCH_ASSOC);
  93. $temp_debug_message("PostgreSQL version: " . ($version['version'] ?? 'unknown'));
  94. }
  95. return $result;
  96. } catch (PDOException $e) {
  97. // Логируем ошибку через error_log, так как соединение не установлено
  98. error_log("DB_CONNECTION_ERROR: Failed to connect to $db_type");
  99. error_log("DB_CONNECTION_ERROR: DSN: $dsn");
  100. error_log("DB_CONNECTION_ERROR: User: $db_user");
  101. error_log("DB_CONNECTION_ERROR: Error code: " . $e->getCode());
  102. error_log("DB_CONNECTION_ERROR: Error message: " . $e->getMessage());
  103. error_log("DB_CONNECTION_ERROR: Trace: " . $e->getTraceAsString());
  104. // Также выводим в консоль для немедленной обратной связи
  105. echo "Error connect to $db_type " . PHP_EOL;
  106. echo "Error message: " . $e->getMessage() . PHP_EOL;
  107. echo "DSN: $dsn" . PHP_EOL;
  108. exit();
  109. } catch (Exception $e) {
  110. // Обработка других исключений (например, неподдерживаемый тип БД)
  111. error_log("DB_CONNECTION_ERROR: " . $e->getMessage());
  112. echo "Error: " . $e->getMessage() . PHP_EOL;
  113. exit();
  114. }
  115. }
  116. /**
  117. * Преобразует ассоциативный массив в человекочитаемый текстовый формат (подобие YAML/Perl hash)
  118. */
  119. function hash_to_text($hash_ref, $indent = 0, &$seen = null) {
  120. if ($seen === null) {
  121. $seen = [];
  122. }
  123. if (!isset($hash_ref)) {
  124. return 'null';
  125. }
  126. if (is_array($hash_ref) && is_assoc($hash_ref)) {
  127. $spaces = str_repeat(' ', $indent);
  128. $lines = [];
  129. $keys = array_keys($hash_ref);
  130. sort($keys);
  131. foreach ($keys as $key) {
  132. $value = $hash_ref[$key];
  133. $formatted_key = preg_match('/^[a-zA-Z_]\w*$/', $key) ? $key : "'" . addslashes($key) . "'";
  134. $formatted_value = '';
  135. if (is_array($value)) {
  136. if (is_assoc($value)) {
  137. $formatted_value = ":\n" . hash_to_text($value, $indent + 1, $seen);
  138. } else {
  139. $formatted_value = array_to_text($value, $indent + 1, $seen);
  140. }
  141. } elseif (is_object($value)) {
  142. // Защита от циклических ссылок для объектов
  143. $obj_id = spl_object_hash($value);
  144. if (isset($seen[$obj_id])) {
  145. $formatted_value = '[circular reference]';
  146. } else {
  147. $seen[$obj_id] = true;
  148. $formatted_value = '[' . get_class($value) . ']';
  149. }
  150. } elseif ($value === null) {
  151. $formatted_value = 'null';
  152. } else {
  153. $formatted_value = "'" . addslashes((string)$value) . "'";
  154. }
  155. if ($formatted_value !== '') {
  156. $lines[] = "$spaces $formatted_key => $formatted_value";
  157. }
  158. }
  159. if (empty($lines)) {
  160. return "$spaces # empty";
  161. }
  162. return implode(",\n", $lines);
  163. } else {
  164. // Не ассоциативный массив или скаляр — обрабатываем как строку
  165. return "'" . (isset($hash_ref) ? addslashes((string)$hash_ref) : '') . "'";
  166. }
  167. }
  168. /**
  169. * Преобразует индексированный массив в текстовый формат
  170. */
  171. function array_to_text($array_ref, $indent = 0, &$seen = null) {
  172. if ($seen === null) {
  173. $seen = [];
  174. }
  175. if (!is_array($array_ref) || empty($array_ref)) {
  176. return '[]';
  177. }
  178. $spaces = str_repeat(' ', $indent);
  179. $lines = [];
  180. foreach ($array_ref as $item) {
  181. $formatted_item = '';
  182. if (is_array($item)) {
  183. if (is_assoc($item)) {
  184. $formatted_item = ":\n" . hash_to_text($item, $indent + 1, $seen);
  185. } else {
  186. $formatted_item = array_to_text($item, $indent + 1, $seen);
  187. }
  188. } elseif (is_object($item)) {
  189. $obj_id = spl_object_hash($item);
  190. if (isset($seen[$obj_id])) {
  191. $formatted_item = '[circular reference]';
  192. } else {
  193. $seen[$obj_id] = true;
  194. $formatted_item = '[' . get_class($item) . ']';
  195. }
  196. } elseif ($item === null) {
  197. $formatted_item = 'null';
  198. } else {
  199. $formatted_item = "'" . addslashes((string)$item) . "'";
  200. }
  201. if ($formatted_item !== '') {
  202. $lines[] = "$spaces $formatted_item";
  203. }
  204. }
  205. if (empty($lines)) {
  206. return "[]";
  207. }
  208. return "[\n" . implode(",\n", $lines) . "\n$spaces]";
  209. }
  210. /**
  211. * Проверяет, является ли массив ассоциативным
  212. */
  213. function is_assoc($array) {
  214. if (!is_array($array) || empty($array)) {
  215. return false;
  216. }
  217. return array_keys($array) !== range(0, count($array) - 1);
  218. }
  219. /**
  220. * Нормализует значение поля: преобразует NULL в 0 для числовых полей или в пустую строку для строковых
  221. *
  222. * @param string $key Имя поля
  223. * @param mixed $value Значение поля
  224. * @return mixed Нормализованное значение
  225. */
  226. function normalize_field_value($key, $value) {
  227. if ($value === null or $value === 'NULL') {
  228. // Регулярное выражение для определения числовых полей
  229. $numeric_field_pattern = '/\b(?:
  230. # ID поля
  231. id|_id|
  232. # Числовые счетчики
  233. count|_count|num|port|size|level|status|type|bytes|byte|
  234. # Временные метки
  235. _time|_timestamp|_at|time|timestamp|
  236. # Сетевые/трафик
  237. _in|_out|_int|forward|gateway|ip_int|quota|step|
  238. # Сетевые ID
  239. vlan|index|snmp|protocol|router|subnet|target|vendor|
  240. # Флаги/boolean (tinyint)
  241. action|active|blocked|changed|connected|default|deleted|dhcp|
  242. discovery|draft|dynamic|enabled|free|hotspot|link|nagios|netflow|
  243. notify|office|permanent|poe|queue|rights|save|skip|static|uniq|uplink|vpn
  244. )\b/ix';
  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. 'comments' => '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)) {
  832. # LOG_WARNING($db, "Create record for unknown table! Skip command.");
  833. return;
  834. }
  835. if (empty($newvalue)) {
  836. # LOG_WARNING($db, "Create record ($table) with empty data! Skip command.");
  837. return;
  838. }
  839. $changed_log = '';
  840. $field_list = '';
  841. $value_list = '';
  842. $params = [];
  843. foreach ($newvalue as $key => $value) {
  844. if (empty($value) and $value != '0') {
  845. $value = '';
  846. }
  847. if (!preg_match('/password/i', $key)) {
  848. $changed_log = $changed_log . " $key => $value,";
  849. }
  850. $field_list = $field_list . "`" . $key . "`,";
  851. $value = trim($value);
  852. $value_list = $value_list . "?,";
  853. $params[] = $value;
  854. }
  855. if (empty($value_list)) {
  856. return;
  857. }
  858. $changed_log = substr_replace($changed_log, "", -1);
  859. $field_list = substr_replace($field_list, "", -1);
  860. $value_list = substr_replace($value_list, "", -1);
  861. $new_sql = "insert into $table(" . $field_list . ") values(" . $value_list . ")";
  862. LOG_DEBUG($db, "Run sql: $new_sql");
  863. try {
  864. $stmt = $db->prepare($new_sql);
  865. $sql_result = $stmt->execute($params);
  866. if (!$sql_result) {
  867. LOG_ERROR($db, "INSERT Request");
  868. return;
  869. }
  870. $last_id = $db->lastInsertId();
  871. if ($table !== "sessions") {
  872. LOG_VERBOSE($db, "Create record in table $table: $changed_log with id: $last_id");
  873. }
  874. if ($table === 'User_auth') {
  875. run_sql($db, "UPDATE User_auth SET changed=1, dhcp_changed=1 WHERE id=" . $last_id);
  876. }
  877. if ($table === 'User_auth_alias') {
  878. //dns
  879. if (!empty($newvalue['alias']) and !preg_match('/\.$/', $newvalue['alias'])) {
  880. $add_dns['name_type'] = 'CNAME';
  881. $add_dns['name'] = $newvalue['alias'];
  882. $add_dns['value'] = get_dns_name($db, $newvalue['auth_id']);
  883. $add_dns['type'] = 'add';
  884. $add_dns['auth_id'] = $newvalue['auth_id'];
  885. insert_record($db, 'dns_queue', $add_dns);
  886. }
  887. }
  888. if ($table === 'User_auth') {
  889. //dns - A-record
  890. if (!empty($newvalue['dns_name']) and !empty($newvalue['ip']) and !$newvalue['dns_ptr_only'] and !preg_match('/\.$/', $newvalue['dns_name'])) {
  891. $add_dns['name_type'] = 'A';
  892. $add_dns['name'] = $newvalue['dns_name'];
  893. $add_dns['value'] = $newvalue['ip'];
  894. $add_dns['type'] = 'add';
  895. $add_dns['auth_id'] = $last_id;
  896. insert_record($db, 'dns_queue', $add_dns);
  897. }
  898. //dns - ptr
  899. if (!empty($newvalue['dns_name']) and !empty($newvalue['ip']) and $newvalue['dns_ptr_only'] and !preg_match('/\.$/', $newvalue['dns_name'])) {
  900. $add_dns['name_type'] = 'PTR';
  901. $add_dns['name'] = $newvalue['dns_name'];
  902. $add_dns['value'] = $newvalue['ip'];
  903. $add_dns['type'] = 'add';
  904. $add_dns['auth_id'] = $last_id;
  905. insert_record($db, 'dns_queue', $add_dns);
  906. }
  907. }
  908. return $last_id;
  909. } catch (PDOException $e) {
  910. LOG_ERROR($db, "SQL: $new_sql :" . $e->getMessage());
  911. return;
  912. }
  913. }
  914. function dump_record($db, $table, $filter)
  915. {
  916. $result = '';
  917. $old = get_record($db, $table, $filter);
  918. if (empty($old)) {
  919. return $result;
  920. }
  921. $result = 'record: ' . get_rec_str($old);
  922. return $result;
  923. }
  924. function get_rec_str($array)
  925. {
  926. $result = '';
  927. foreach ($array as $key => $value) {
  928. $result .= "[" . $key . "]=" . $value . ", ";
  929. }
  930. $result = preg_replace('/,\s+$/', '', $result);
  931. return $result;
  932. }
  933. function get_diff_rec($db, $table, $filter, $newvalue, $only_changed = false)
  934. {
  935. if (!isset($table) || !isset($filter) || !isset($newvalue)) {
  936. return '';
  937. }
  938. $old_sql = "SELECT * FROM `$table` WHERE $filter";
  939. try {
  940. $stmt = $db->query($old_sql);
  941. $old = $stmt->fetch(PDO::FETCH_ASSOC);
  942. if (!$old) {
  943. // Запись не найдена — возможно, ошибка или новая запись
  944. return "Record not found for filter: $filter";
  945. }
  946. $changed = [];
  947. $unchanged = [];
  948. foreach ($newvalue as $key => $new_val) {
  949. // Пропускаем ключи, которых нет в старой записи (например, служебные поля)
  950. if (!array_key_exists($key, $old)) {
  951. continue;
  952. }
  953. $old_val = $old[$key];
  954. // Сравниваем как строки, но аккуратно с null
  955. $old_str = ($old_val === null) ? '' : (string)$old_val;
  956. $new_str = ($new_val === null) ? '' : (string)$new_val;
  957. if ($old_str !== $new_str) {
  958. $changed[$key] = $new_str . ' [ old: ' . $old_str . ' ]';
  959. } else {
  960. $unchanged[$key] = $old_val;
  961. }
  962. }
  963. if ($only_changed) {
  964. return empty($changed) ? '' : hash_to_text($changed);
  965. }
  966. $output = '';
  967. if (!empty($changed)) {
  968. $output .= hash_to_text($changed);
  969. } else {
  970. $output .= "# no changes";
  971. }
  972. if (!empty($unchanged)) {
  973. $output .= "\r\nHas not changed:\r\n" . hash_to_text($unchanged);
  974. }
  975. return $output;
  976. } catch (PDOException $e) {
  977. LOG_ERROR($db, "SQL: $old_sql :" . $e->getMessage());
  978. return '';
  979. }
  980. }
  981. function delete_user_auth($db, $id) {
  982. $msg = '';
  983. $record = get_record_sql($db, 'SELECT * FROM User_auth WHERE id=' . $id);
  984. $txt_record = hash_to_text($record);
  985. // remove aliases
  986. $t_User_auth_alias = get_records_sql($db, 'SELECT * FROM User_auth_alias WHERE auth_id=' . $id);
  987. if (!empty($t_User_auth_alias)) {
  988. foreach ($t_User_auth_alias as $row) {
  989. $alias_txt = record_to_txt($db, 'User_auth_alias', 'id=' . $row['id']);
  990. if (delete_record($db, 'User_auth_alias', 'id=' . $row['id'])) {
  991. $msg = "Deleting an alias: " . $alias_txt . "::Success!\n" . $msg;
  992. } else {
  993. $msg = "Deleting an alias: " . $alias_txt . "::Fail!\n" . $msg;
  994. }
  995. }
  996. }
  997. // remove connections
  998. run_sql($db, 'DELETE FROM connections WHERE auth_id=' . $id);
  999. // remove user auth record
  1000. $changes = delete_record($db, "User_auth", "id=" . $id);
  1001. if ($changes) {
  1002. $msg = "Deleting ip-record: " . $txt_record . "::Success!\n" . $msg;
  1003. } else {
  1004. $msg = "Deleting ip-record: " . $txt_record . "::Fail!\n" . $msg;
  1005. }
  1006. LOG_WARNING($db, $msg);
  1007. $send_alert_delete = isNotifyDelete(get_notify_subnet($db, $record['ip']));
  1008. if ($send_alert_delete) { email(L_WARNING,$msg); }
  1009. return $changes;
  1010. }
  1011. function delete_user($db,$id)
  1012. {
  1013. //remove user record
  1014. $changes = delete_record($db, "User_list", "id=" . $id);
  1015. //if fail - exit
  1016. if (!isset($changes) or empty($changes)) { return; }
  1017. //remove auth records
  1018. $t_User_auth = get_records($db,'User_auth',"user_id=$id");
  1019. if (!empty($t_User_auth)) {
  1020. foreach ( $t_User_auth as $row ) { delete_user_auth($db,$row['id']); }
  1021. }
  1022. //remove device
  1023. $device = get_record($db, "devices", "user_id='$id'");
  1024. if (!empty($device)) {
  1025. LOG_INFO($db, "Delete device for user id: $id ".dump_record($db,'devices','user_id='.$id));
  1026. unbind_ports($db, $device['id']);
  1027. run_sql($db, "DELETE FROM connections WHERE device_id=" . $device['id']);
  1028. run_sql($db, "DELETE FROM device_l3_interfaces WHERE device_id=" . $device['id']);
  1029. run_sql($db, "DELETE FROM device_ports WHERE device_id=" . $device['id']);
  1030. run_sql($db, "DELETE FROM device_filter_instances WHERE device_id=" . $device['id']);
  1031. run_sql($db, "DELETE FROM gateway_subnets WHERE device_id=".$device['id']);
  1032. delete_record($db, "devices", "id=" . $device['id']);
  1033. }
  1034. //remove auth assign rules
  1035. run_sql($db, "DELETE FROM auth_rules WHERE user_id=$id");
  1036. return $changes;
  1037. }
  1038. function delete_device($db,$id)
  1039. {
  1040. LOG_INFO($db, "Try delete device id: $id ".dump_record($db,'devices','id='.$id));
  1041. //remove user record
  1042. $changes = delete_record($db, "devices", "id=" . $id);
  1043. //if fail - exit
  1044. if (!isset($changes) or empty($changes)) {
  1045. LOG_INFO($db,"Device id: $id has not been deleted");
  1046. return;
  1047. }
  1048. unbind_ports($db, $id);
  1049. run_sql($db, "DELETE FROM connections WHERE device_id=" . $id);
  1050. run_sql($db, "DELETE FROM device_l3_interfaces WHERE device_id=" . $id);
  1051. run_sql($db, "DELETE FROM device_ports WHERE device_id=" . $id);
  1052. run_sql($db, "DELETE FROM device_filter_instances WHERE device_id=" . $id);
  1053. run_sql($db, "DELETE FROM gateway_subnets WHERE device_id=".$id);
  1054. return $changes;
  1055. }
  1056. function record_to_txt($db, $table, $id) {
  1057. $record = get_record_sql($db, 'SELECT * FROM ' . $table . ' WHERE id =' . $id);
  1058. return hash_to_text($record);
  1059. }
  1060. $db_link = new_connection(DB_TYPE, DB_HOST, DB_USER, DB_PASS, DB_NAME);
  1061. ?>