sql.php 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179
  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(?: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';
  230. if (preg_match($numeric_field_pattern, $key)) {
  231. return 0;
  232. } else {
  233. return '';
  234. }
  235. }
  236. return $value;
  237. }
  238. /**
  239. * Нормализует всю запись (ассоциативный массив)
  240. *
  241. * @param array $record Запись из БД
  242. * @return array Нормализованная запись
  243. */
  244. function normalize_record($record) {
  245. if (!is_array($record) || empty($record)) {
  246. return $record;
  247. }
  248. $normalized = [];
  249. foreach ($record as $key => $value) {
  250. $normalized[$key] = normalize_field_value($key, $value);
  251. }
  252. return $normalized;
  253. }
  254. /**
  255. * Нормализует массив записей
  256. *
  257. * @param array $records Массив записей из БД
  258. * @return array Нормализованные записи
  259. */
  260. function normalize_records($records) {
  261. if (!is_array($records) || empty($records)) {
  262. return $records;
  263. }
  264. $normalized = [];
  265. foreach ($records as $index => $record) {
  266. $normalized[$index] = normalize_record($record);
  267. }
  268. return $normalized;
  269. }
  270. function run_sql($db, $query)
  271. {
  272. // Проверка прав доступа для UPDATE, DELETE, INSERT
  273. if (preg_match('/^\s*(UPDATE|DELETE|INSERT)/i', $query)) {
  274. $table_name = null;
  275. // Определяем имя таблицы для проверки прав
  276. if (preg_match('/^\s*UPDATE\s+(\w+)/i', $query, $matches)) {
  277. $table_name = $matches[1];
  278. $operation = 'update';
  279. } elseif (preg_match('/^\s*DELETE\s+FROM\s+(\w+)/i', $query, $matches)) {
  280. $table_name = $matches[1];
  281. $operation = 'del';
  282. } elseif (preg_match('/^\s*INSERT\s+INTO\s+(\w+)/i', $query, $matches)) {
  283. $table_name = $matches[1];
  284. $operation = 'add';
  285. }
  286. // Проверяем права доступа
  287. if ($table_name && !allow_update($table_name, $operation)) {
  288. LOG_DEBUG($db, "Access denied: $query");
  289. return false;
  290. }
  291. }
  292. // Выполняем запрос
  293. try {
  294. $stmt = $db->query($query);
  295. // Возвращаем результат в зависимости от типа запроса
  296. if (preg_match('/^\s*SELECT/i', $query)) {
  297. // Для SELECT возвращаем PDOStatement
  298. return $stmt;
  299. } elseif (preg_match('/^\s*INSERT/i', $query)) {
  300. // Для INSERT возвращаем ID вставленной записи
  301. return $db->lastInsertId();
  302. } elseif (preg_match('/^\s*(UPDATE|DELETE)/i', $query)) {
  303. // Для UPDATE/DELETE возвращаем количество затронутых строк
  304. return $stmt->rowCount();
  305. }
  306. // Для других типов запросов возвращаем результат как есть
  307. return $stmt;
  308. } catch (PDOException $e) {
  309. LOG_ERROR($db, "At simple SQL: $query :" . $e->getMessage());
  310. return false;
  311. }
  312. }
  313. function get_count_records($db, $table, $filter)
  314. {
  315. if (!empty($filter)) {
  316. $filter = 'where ' . $filter;
  317. }
  318. $t_count = get_record_sql($db, "SELECT count(*) as cnt FROM $table $filter");
  319. if (!empty($t_count) and isset($t_count['cnt'])) { return $t_count['cnt']; }
  320. return 0;
  321. }
  322. /**
  323. * Получить одну запись из таблицы по фильтру
  324. */
  325. function get_record($db, $table, $filter) {
  326. if (!isset($table) || !isset($filter)) {
  327. return null;
  328. }
  329. if (preg_match('/=$/', $filter)) {
  330. LOG_ERROR($db, "Search record ($table) with illegal filter $filter! Skip command.");
  331. return null;
  332. }
  333. $sql = "SELECT * FROM $table WHERE $filter";
  334. return get_record_sql($db, $sql);
  335. }
  336. /**
  337. * Получить несколько записей из таблицы по фильтру
  338. */
  339. function get_records($db, $table, $filter = '') {
  340. if (!isset($table)) {
  341. return [];
  342. }
  343. if (!empty($filter)) {
  344. if (preg_match('/=$/', $filter)) {
  345. LOG_ERROR($db, "Search record ($table) with illegal filter $filter! Skip command.");
  346. return [];
  347. }
  348. $filter = "WHERE $filter";
  349. }
  350. $sql = "SELECT * FROM $table $filter";
  351. return get_records_sql($db, $sql);
  352. }
  353. /**
  354. * Получить одну запись по произвольному SQL-запросу
  355. */
  356. function get_record_sql($db, $sql) {
  357. if (empty($sql)) {
  358. return null;
  359. }
  360. // Добавляем LIMIT 1, если его нет
  361. if (!preg_match('/\bLIMIT\s+\d+$/i', $sql)) {
  362. $sql .= " LIMIT 1";
  363. }
  364. $result = get_records_sql($db, $sql);
  365. // Возвращаем первую запись или null
  366. return !empty($result) ? $result[0] : null;
  367. }
  368. /**
  369. * Получить несколько записей по произвольному SQL-запросу
  370. */
  371. function get_records_sql($db, $sql) {
  372. $result = [];
  373. if (empty($sql)) {
  374. return $result;
  375. }
  376. try {
  377. $stmt = $db->query($sql);
  378. $records = $stmt->fetchAll(PDO::FETCH_ASSOC);
  379. if (!empty($records)) {
  380. $result = normalize_records($records);
  381. }
  382. return $result;
  383. } catch (PDOException $e) {
  384. LOG_ERROR($db, "SQL: $sql : " . $e->getMessage());
  385. return $result;
  386. }
  387. }
  388. /**
  389. * Получить одно значение поля по SQL-запросу
  390. */
  391. function get_single_field($db, $sql) {
  392. $record = get_record_sql($db, $sql);
  393. if (!empty($record) && is_array($record)) {
  394. // Получаем первое значение из записи
  395. return reset($record) ?: 0;
  396. }
  397. return 0;
  398. }
  399. /**
  400. * Получить ID записи из таблицы по фильтру
  401. */
  402. function get_id_record($db, $table, $filter) {
  403. if (empty($filter)) {
  404. return 0;
  405. }
  406. $record = get_record($db, $table, $filter);
  407. return !empty($record['id']) ? $record['id'] : 0;
  408. }
  409. function set_changed($db, $id)
  410. {
  411. $auth['changed'] = 1;
  412. update_record($db, "user_auth", "id=" . $id, $auth);
  413. }
  414. //action: add,update,del
  415. function allow_update($table, $action = 'update', $field = '')
  416. {
  417. //always allow modification for tables
  418. if (preg_match('/(variables|dns_cache|worklog|sessions)/i', $table)) {
  419. return 1;
  420. }
  421. if (isset($_SESSION['login'])) {
  422. $work_user = $_SESSION['login'];
  423. }
  424. if (isset($_SESSION['user_id'])) {
  425. $work_id = $_SESSION['user_id'];
  426. }
  427. if (isset($_SESSION['acl'])) {
  428. $user_level = $_SESSION['acl'];
  429. }
  430. if (!isset($work_user) or !isset($work_id) or empty($user_level)) {
  431. return 0;
  432. }
  433. //always allow Administrator
  434. if ($user_level == 1) {
  435. return 1;
  436. }
  437. //always forbid ViewOnly
  438. if ($user_level == 3) {
  439. return 0;
  440. }
  441. //allow tables for Operator
  442. if (preg_match('/(dns_queue|user_auth_alias)/i', $table)) {
  443. return 1;
  444. }
  445. if ($action == 'update') {
  446. $operator_acl = [
  447. 'user_auth' => [
  448. 'comments' => '1',
  449. 'dns_name' => '1',
  450. 'dns_ptr_only' => '1',
  451. 'firmware' => '1',
  452. 'link_check' => '1',
  453. 'nagios' => '1',
  454. 'nagios_handler' => '1',
  455. 'Wikiname' => '1'
  456. ],
  457. 'user_list' => [
  458. 'fio' => '1',
  459. 'login' => '1',
  460. ],
  461. ];
  462. if (!isset($operator_acl[$table])) {
  463. return 0;
  464. }
  465. if (isset($operator_acl[$table]) and empty($field)) {
  466. return 1;
  467. }
  468. if (!isset($operator_acl[$table][$field])) {
  469. return 0;
  470. }
  471. if (empty($operator_acl[$table][$field]) or $operator_acl[$table][$field] == '0') {
  472. return 0;
  473. }
  474. return 1;
  475. }
  476. return 0;
  477. }
  478. function update_record($db, $table, $filter, $newvalue)
  479. {
  480. if (!isset($table)) {
  481. # LOG_WARNING($db, "Change record for unknown table! Skip command.");
  482. return;
  483. }
  484. if (!isset($filter)) {
  485. # LOG_WARNING($db, "Change record ($table) with empty filter! Skip command.");
  486. return;
  487. }
  488. if (preg_match('/=$/', $filter)) {
  489. LOG_WARNING($db, "Change record ($table) with illegal filter $filter! Skip command.");
  490. return;
  491. }
  492. if (!isset($newvalue)) {
  493. # LOG_WARNING($db, "Change record ($table [ $filter ]) with empty data! Skip command.");
  494. return;
  495. }
  496. if (!allow_update($table, 'update')) {
  497. LOG_INFO($db, "Access denied: $table [ $filter ]");
  498. return 1;
  499. }
  500. $old_sql = "SELECT * FROM $table WHERE $filter";
  501. try {
  502. $stmt = $db->query($old_sql);
  503. $old = $stmt->fetch(PDO::FETCH_ASSOC);
  504. } catch (PDOException $e) {
  505. LOG_ERROR($db, "SQL: $old_sql :" . $e->getMessage());
  506. return;
  507. }
  508. $rec_id = NULL;
  509. if (!empty($old['id'])) {
  510. $rec_id = $old['id'];
  511. }
  512. $changed_log = '';
  513. $set_parts = [];
  514. $params = [];
  515. $network_changed = 0;
  516. $dhcp_changed = 0;
  517. $dns_changed = 0;
  518. $acl_fields = [
  519. 'ip' => '1',
  520. 'ip_int' => '1',
  521. 'enabled' => '1',
  522. 'dhcp' => '1',
  523. 'filter_group_id' => '1',
  524. 'deleted' => '1',
  525. 'dhcp_acl' => '1',
  526. 'queue_id' => '1',
  527. 'mac' => '1',
  528. 'blocked' => '1',
  529. ];
  530. $dhcp_fields = [
  531. 'ip' => '1',
  532. 'dhcp' => '1',
  533. 'deleted' => '1',
  534. 'dhcp_option_set' =>'1',
  535. 'dhcp_acl' => '1',
  536. 'mac' => '1',
  537. ];
  538. $dns_fields = [
  539. 'ip' => '1',
  540. 'dns_name' => '1',
  541. 'dns_ptr_only' => '1',
  542. 'alias' => '1',
  543. ];
  544. foreach ($newvalue as $key => $value) {
  545. if (!allow_update($table, 'update', $key)) {
  546. continue;
  547. }
  548. if (!isset($value)) {
  549. $value = '';
  550. }
  551. $value = trim($value);
  552. if (isset($old[$key]) && strcmp($old[$key], $value) == 0) {
  553. continue;
  554. }
  555. if ($table === "user_auth") {
  556. if (!empty($acl_fields["$key"])) {
  557. $network_changed = 1;
  558. }
  559. if (!empty($dhcp_fields["$key"])) {
  560. $dhcp_changed = 1;
  561. }
  562. if (!empty($dns_fields["$key"])) {
  563. $dns_changed = 1;
  564. }
  565. }
  566. if ($table === "user_auth_alias") {
  567. if (!empty($dns_fields["$key"])) {
  568. $dns_changed = 1;
  569. }
  570. }
  571. if (!preg_match('/password/i', $key)) {
  572. $changed_log = $changed_log . " $key => $value (old: " . ($old[$key] ?? '') . "),";
  573. }
  574. $set_parts[] = "`$key` = ?";
  575. $params[] = $value;
  576. }
  577. if ($table === "user_auth" and $dns_changed) {
  578. if (!empty($old['dns_name']) and !empty($old['ip']) and !$old['dns_ptr_only'] and !preg_match('/\.$/', $old['dns_name'])) {
  579. $del_dns['name_type'] = 'A';
  580. $del_dns['name'] = $old['dns_name'];
  581. $del_dns['value'] = $old['ip'];
  582. $del_dns['type'] = 'del';
  583. if (!empty($rec_id)) {
  584. $del_dns['auth_id'] = $rec_id;
  585. }
  586. insert_record($db, 'dns_queue', $del_dns);
  587. }
  588. if (!empty($old['dns_name']) and !empty($old['ip']) and $old['dns_ptr_only'] and !preg_match('/\.$/', $old['dns_name'])) {
  589. $del_dns['name_type'] = 'PTR';
  590. $del_dns['name'] = $old['dns_name'];
  591. $del_dns['value'] = $old['ip'];
  592. $del_dns['type'] = 'del';
  593. if (!empty($rec_id)) {
  594. $del_dns['auth_id'] = $rec_id;
  595. }
  596. insert_record($db, 'dns_queue', $del_dns);
  597. }
  598. if (!empty($newvalue['dns_name']) and !empty($newvalue['ip']) and !$newvalue['dns_ptr_only'] and !preg_match('/\.$/', $newvalue['dns_name'])) {
  599. $new_dns['name_type'] = 'A';
  600. $new_dns['name'] = $newvalue['dns_name'];
  601. $new_dns['value'] = $newvalue['ip'];
  602. $new_dns['type'] = 'add';
  603. if (!empty($rec_id)) {
  604. $new_dns['auth_id'] = $rec_id;
  605. }
  606. insert_record($db, 'dns_queue', $new_dns);
  607. }
  608. if (!empty($newvalue['dns_name']) and !empty($newvalue['ip']) and $newvalue['dns_ptr_only'] and !preg_match('/\.$/', $newvalue['dns_name'])) {
  609. $new_dns['name_type'] = 'PTR';
  610. $new_dns['name'] = $newvalue['dns_name'];
  611. $new_dns['value'] = $newvalue['ip'];
  612. $new_dns['type'] = 'add';
  613. if (!empty($rec_id)) {
  614. $new_dns['auth_id'] = $rec_id;
  615. }
  616. insert_record($db, 'dns_queue', $new_dns);
  617. }
  618. }
  619. if ($table === "user_auth_alias" and $dns_changed) {
  620. $auth_id = NULL;
  621. if ($old['auth_id']) {
  622. $auth_id = $old['auth_id'];
  623. }
  624. if (!empty($old['alias']) and !preg_match('/\.$/', $old['alias'])) {
  625. $del_dns['name_type'] = 'CNAME';
  626. $del_dns['name'] = $old['alias'];
  627. $del_dns['type'] = 'del';
  628. if (!empty($auth_id)) {
  629. $del_dns['auth_id'] = $auth_id;
  630. $del_dns['value'] = get_dns_name($db, $auth_id);
  631. }
  632. insert_record($db, 'dns_queue', $del_dns);
  633. }
  634. if (!empty($newvalue['alias']) and !preg_match('/\.$/', $newvalue['alias'])) {
  635. $new_dns['name_type'] = 'CNAME';
  636. $new_dns['name'] = $newvalue['alias'];
  637. $new_dns['type'] = 'add';
  638. if (!empty($auth_id)) {
  639. $new_dns['auth_id'] = $auth_id;
  640. $new_dns['value'] = get_dns_name($db, $auth_id);
  641. }
  642. insert_record($db, 'dns_queue', $new_dns);
  643. }
  644. }
  645. if (empty($set_parts)) {
  646. return 1;
  647. }
  648. if ($network_changed) {
  649. $set_parts[] = "`changed` = '1'";
  650. }
  651. if ($dhcp_changed) {
  652. $set_parts[] = "`dhcp_changed` = '1'";
  653. }
  654. $changed_log = substr_replace($changed_log, "", -1);
  655. $run_sql = implode(", ", $set_parts);
  656. if ($table === 'user_auth') {
  657. $changed_time = GetNowTimeString();
  658. $run_sql .= ", `changed_time` = ?";
  659. $params[] = $changed_time;
  660. }
  661. $new_sql = "UPDATE $table SET $run_sql WHERE $filter";
  662. LOG_DEBUG($db, "Run sql: $new_sql");
  663. try {
  664. $stmt = $db->prepare($new_sql);
  665. $sql_result = $stmt->execute($params);
  666. if (!$sql_result) {
  667. LOG_ERROR($db, "UPDATE Request: $new_sql");
  668. return;
  669. }
  670. if ($table !== "sessions") {
  671. LOG_VERBOSE($db, "Change table $table WHERE $filter set $changed_log");
  672. }
  673. return $sql_result;
  674. } catch (PDOException $e) {
  675. LOG_ERROR($db, "SQL: $new_sql :" . $e->getMessage());
  676. return;
  677. }
  678. }
  679. function delete_record($db, $table, $filter)
  680. {
  681. if (!allow_update($table, 'del')) {
  682. # LOG_INFO($db, "User does not have write permission");
  683. return;
  684. }
  685. if (!isset($table)) {
  686. # LOG_WARNING($db, "Delete FROM unknown table! Skip command.");
  687. return;
  688. }
  689. if (!isset($filter)) {
  690. LOG_WARNING($db, "Delete FROM table $table with empty filter! Skip command.");
  691. return;
  692. }
  693. if (preg_match('/=$/', $filter)) {
  694. LOG_WARNING($db, "Change record ($table) with illegal filter $filter! Skip command.");
  695. return;
  696. }
  697. $old_sql = "SELECT * FROM $table WHERE $filter";
  698. try {
  699. $stmt = $db->query($old_sql);
  700. $old = $stmt->fetch(PDO::FETCH_ASSOC);
  701. } catch (PDOException $e) {
  702. LOG_ERROR($db, "SQL: $old_sql :" . $e->getMessage());
  703. return;
  704. }
  705. $rec_id = NULL;
  706. if (!empty($old['id'])) {
  707. $rec_id = $old['id'];
  708. }
  709. $changed_log = 'record: ';
  710. if (!empty($old)) {
  711. asort($old, SORT_STRING);
  712. $old = array_reverse($old, 1);
  713. foreach ($old as $key => $value) {
  714. if (empty($value)) {
  715. continue;
  716. }
  717. if (preg_match('/action/', $key)) {
  718. continue;
  719. }
  720. if (preg_match('/status/', $key)) {
  721. continue;
  722. }
  723. if (preg_match('/time/', $key)) {
  724. continue;
  725. }
  726. if (preg_match('/found/', $key)) {
  727. continue;
  728. }
  729. $changed_log = $changed_log . " $key => $value,";
  730. }
  731. }
  732. $delete_it = 1;
  733. //never delete user ip record
  734. if ($table === 'user_auth') {
  735. $delete_it = 0;
  736. $changed_time = GetNowTimeString();
  737. $new_sql = "UPDATE $table SET deleted=1, changed=1, `changed_time`='" . $changed_time . "' WHERE $filter";
  738. LOG_DEBUG($db, "Run sql: $new_sql");
  739. try {
  740. $sql_result = $db->exec($new_sql);
  741. if ($sql_result === false) {
  742. LOG_ERROR($db, "UPDATE Request (from delete)");
  743. return;
  744. }
  745. } catch (PDOException $e) {
  746. LOG_ERROR($db, "SQL: $new_sql :" . $e->getMessage());
  747. return;
  748. }
  749. //dns - A-record
  750. if (!empty($old['dns_name']) and !empty($old['ip']) and !$old['dns_ptr_only'] and !preg_match('/\.$/', $old['dns_name'])) {
  751. $del_dns['name_type'] = 'A';
  752. $del_dns['name'] = $old['dns_name'];
  753. $del_dns['value'] = $old['ip'];
  754. $del_dns['type'] = 'del';
  755. if (!empty($rec_id)) {
  756. $del_dns['auth_id'] = $rec_id;
  757. }
  758. insert_record($db, 'dns_queue', $del_dns);
  759. }
  760. //ptr
  761. if (!empty($old['dns_name']) and !empty($old['ip']) and $old['dns_ptr_only'] and !preg_match('/\.$/', $old['dns_name'])) {
  762. $del_dns['name_type'] = 'PTR';
  763. $del_dns['name'] = $old['dns_name'];
  764. $del_dns['value'] = $old['ip'];
  765. $del_dns['type'] = 'del';
  766. if (!empty($rec_id)) {
  767. $del_dns['auth_id'] = $rec_id;
  768. }
  769. insert_record($db, 'dns_queue', $del_dns);
  770. }
  771. LOG_VERBOSE($db, "Deleted FROM table $table WHERE $filter $changed_log");
  772. return $changed_log;
  773. }
  774. //never delete permanent user
  775. if ($table === 'user_list' and $old['permanent']) { return; }
  776. //remove aliases
  777. if ($table === 'user_auth_alias') {
  778. //dns
  779. if (!empty($old['alias']) and !preg_match('/\.$/', $old['alias'])) {
  780. $del_dns['name_type'] = 'CNAME';
  781. $del_dns['name'] = $old['alias'];
  782. $del_dns['value'] = '';
  783. $del_dns['type'] = 'del';
  784. if (!empty($old['auth_id'])) {
  785. $del_dns['auth_id'] = $old['auth_id'];
  786. $del_dns['value'] = get_dns_name($db, $old['auth_id']);
  787. }
  788. insert_record($db, 'dns_queue', $del_dns);
  789. }
  790. }
  791. if ($delete_it) {
  792. $new_sql = "DELETE FROM $table WHERE $filter";
  793. LOG_DEBUG($db, "Run sql: $new_sql");
  794. try {
  795. $sql_result = $db->exec($new_sql);
  796. if ($sql_result === false) {
  797. LOG_ERROR($db, "DELETE Request: $new_sql");
  798. return;
  799. }
  800. } catch (PDOException $e) {
  801. LOG_ERROR($db, "SQL: $new_sql : " . $e->getMessage());
  802. return;
  803. }
  804. } else { return; }
  805. if ($table !== "sessions") {
  806. LOG_VERBOSE($db, "Deleted FROM table $table WHERE $filter $changed_log");
  807. }
  808. return $changed_log;
  809. }
  810. function insert_record($db, $table, $newvalue)
  811. {
  812. if (!allow_update($table, 'add')) {
  813. # LOG_WARNING($db, "User does not have write permission");
  814. return;
  815. }
  816. if (!isset($table)) {
  817. # LOG_WARNING($db, "Create record for unknown table! Skip command.");
  818. return;
  819. }
  820. if (empty($newvalue)) {
  821. # LOG_WARNING($db, "Create record ($table) with empty data! Skip command.");
  822. return;
  823. }
  824. $changed_log = '';
  825. $field_list = '';
  826. $value_list = '';
  827. $params = [];
  828. foreach ($newvalue as $key => $value) {
  829. if (empty($value) and $value != '0') {
  830. $value = '';
  831. }
  832. if (!preg_match('/password/i', $key)) {
  833. $changed_log = $changed_log . " $key => $value,";
  834. }
  835. $field_list = $field_list . "`" . $key . "`,";
  836. $value = trim($value);
  837. $value_list = $value_list . "?,";
  838. $params[] = $value;
  839. }
  840. if (empty($value_list)) {
  841. return;
  842. }
  843. $changed_log = substr_replace($changed_log, "", -1);
  844. $field_list = substr_replace($field_list, "", -1);
  845. $value_list = substr_replace($value_list, "", -1);
  846. $new_sql = "insert into $table(" . $field_list . ") values(" . $value_list . ")";
  847. LOG_DEBUG($db, "Run sql: $new_sql");
  848. try {
  849. $stmt = $db->prepare($new_sql);
  850. $sql_result = $stmt->execute($params);
  851. if (!$sql_result) {
  852. LOG_ERROR($db, "INSERT Request");
  853. return;
  854. }
  855. $last_id = $db->lastInsertId();
  856. if ($table !== "sessions") {
  857. LOG_VERBOSE($db, "Create record in table $table: $changed_log with id: $last_id");
  858. }
  859. if ($table === 'user_auth') {
  860. run_sql($db, "UPDATE user_auth SET changed=1, dhcp_changed=1 WHERE id=" . $last_id);
  861. }
  862. if ($table === 'user_auth_alias') {
  863. //dns
  864. if (!empty($newvalue['alias']) and !preg_match('/\.$/', $newvalue['alias'])) {
  865. $add_dns['name_type'] = 'CNAME';
  866. $add_dns['name'] = $newvalue['alias'];
  867. $add_dns['value'] = get_dns_name($db, $newvalue['auth_id']);
  868. $add_dns['type'] = 'add';
  869. $add_dns['auth_id'] = $newvalue['auth_id'];
  870. insert_record($db, 'dns_queue', $add_dns);
  871. }
  872. }
  873. if ($table === 'user_auth') {
  874. //dns - A-record
  875. if (!empty($newvalue['dns_name']) and !empty($newvalue['ip']) and !$newvalue['dns_ptr_only'] and !preg_match('/\.$/', $newvalue['dns_name'])) {
  876. $add_dns['name_type'] = 'A';
  877. $add_dns['name'] = $newvalue['dns_name'];
  878. $add_dns['value'] = $newvalue['ip'];
  879. $add_dns['type'] = 'add';
  880. $add_dns['auth_id'] = $last_id;
  881. insert_record($db, 'dns_queue', $add_dns);
  882. }
  883. //dns - ptr
  884. if (!empty($newvalue['dns_name']) and !empty($newvalue['ip']) and $newvalue['dns_ptr_only'] and !preg_match('/\.$/', $newvalue['dns_name'])) {
  885. $add_dns['name_type'] = 'PTR';
  886. $add_dns['name'] = $newvalue['dns_name'];
  887. $add_dns['value'] = $newvalue['ip'];
  888. $add_dns['type'] = 'add';
  889. $add_dns['auth_id'] = $last_id;
  890. insert_record($db, 'dns_queue', $add_dns);
  891. }
  892. }
  893. return $last_id;
  894. } catch (PDOException $e) {
  895. LOG_ERROR($db, "SQL: $new_sql :" . $e->getMessage());
  896. return;
  897. }
  898. }
  899. function dump_record($db, $table, $filter)
  900. {
  901. $result = '';
  902. $old = get_record($db, $table, $filter);
  903. if (empty($old)) {
  904. return $result;
  905. }
  906. $result = 'record: ' . get_rec_str($old);
  907. return $result;
  908. }
  909. function get_rec_str($array)
  910. {
  911. $result = '';
  912. foreach ($array as $key => $value) {
  913. $result .= "[" . $key . "]=" . $value . ", ";
  914. }
  915. $result = preg_replace('/,\s+$/', '', $result);
  916. return $result;
  917. }
  918. function get_diff_rec($db, $table, $filter, $newvalue, $only_changed = false)
  919. {
  920. if (!isset($table) || !isset($filter) || !isset($newvalue)) {
  921. return '';
  922. }
  923. $old_sql = "SELECT * FROM `$table` WHERE $filter";
  924. try {
  925. $stmt = $db->query($old_sql);
  926. $old = $stmt->fetch(PDO::FETCH_ASSOC);
  927. if (!$old) {
  928. // Запись не найдена — возможно, ошибка или новая запись
  929. return "Record not found for filter: $filter";
  930. }
  931. $changed = [];
  932. $unchanged = [];
  933. foreach ($newvalue as $key => $new_val) {
  934. // Пропускаем ключи, которых нет в старой записи (например, служебные поля)
  935. if (!array_key_exists($key, $old)) {
  936. continue;
  937. }
  938. $old_val = $old[$key];
  939. // Сравниваем как строки, но аккуратно с null
  940. $old_str = ($old_val === null) ? '' : (string)$old_val;
  941. $new_str = ($new_val === null) ? '' : (string)$new_val;
  942. if ($old_str !== $new_str) {
  943. $changed[$key] = $new_str . ' [ old: ' . $old_str . ' ]';
  944. } else {
  945. $unchanged[$key] = $old_val;
  946. }
  947. }
  948. if ($only_changed) {
  949. return empty($changed) ? '' : hash_to_text($changed);
  950. }
  951. $output = '';
  952. if (!empty($changed)) {
  953. $output .= hash_to_text($changed);
  954. } else {
  955. $output .= "# no changes";
  956. }
  957. if (!empty($unchanged)) {
  958. $output .= "\r\nHas not changed:\r\n" . hash_to_text($unchanged);
  959. }
  960. return $output;
  961. } catch (PDOException $e) {
  962. LOG_ERROR($db, "SQL: $old_sql :" . $e->getMessage());
  963. return '';
  964. }
  965. }
  966. function delete_user_auth($db, $id) {
  967. $msg = '';
  968. $record = get_record_sql($db, 'SELECT * FROM user_auth WHERE id=' . $id);
  969. $txt_record = hash_to_text($record);
  970. // remove aliases
  971. $t_user_auth_alias = get_records_sql($db, 'SELECT * FROM user_auth_alias WHERE auth_id=' . $id);
  972. if (!empty($t_user_auth_alias)) {
  973. foreach ($t_user_auth_alias as $row) {
  974. $alias_txt = record_to_txt($db, 'user_auth_alias', 'id=' . $row['id']);
  975. if (delete_record($db, 'user_auth_alias', 'id=' . $row['id'])) {
  976. $msg = "Deleting an alias: " . $alias_txt . "::Success!\n" . $msg;
  977. } else {
  978. $msg = "Deleting an alias: " . $alias_txt . "::Fail!\n" . $msg;
  979. }
  980. }
  981. }
  982. // remove connections
  983. run_sql($db, 'DELETE FROM connections WHERE auth_id=' . $id);
  984. // remove user auth record
  985. $changes = delete_record($db, "user_auth", "id=" . $id);
  986. if ($changes) {
  987. $msg = "Deleting ip-record: " . $txt_record . "::Success!\n" . $msg;
  988. } else {
  989. $msg = "Deleting ip-record: " . $txt_record . "::Fail!\n" . $msg;
  990. }
  991. LOG_WARNING($db, $msg);
  992. $send_alert_delete = isNotifyDelete(get_notify_subnet($db, $record['ip']));
  993. if ($send_alert_delete) { email(L_WARNING,$msg); }
  994. return $changes;
  995. }
  996. function delete_user($db,$id)
  997. {
  998. //remove user record
  999. $changes = delete_record($db, "user_list", "id=" . $id);
  1000. //if fail - exit
  1001. if (!isset($changes) or empty($changes)) { return; }
  1002. //remove auth records
  1003. $t_user_auth = get_records($db,'user_auth',"user_id=$id");
  1004. if (!empty($t_user_auth)) {
  1005. foreach ( $t_user_auth as $row ) { delete_user_auth($db,$row['id']); }
  1006. }
  1007. //remove device
  1008. $device = get_record($db, "devices", "user_id='$id'");
  1009. if (!empty($device)) {
  1010. LOG_INFO($db, "Delete device for user id: $id ".dump_record($db,'devices','user_id='.$id));
  1011. unbind_ports($db, $device['id']);
  1012. run_sql($db, "DELETE FROM connections WHERE device_id=" . $device['id']);
  1013. run_sql($db, "DELETE FROM device_l3_interfaces WHERE device_id=" . $device['id']);
  1014. run_sql($db, "DELETE FROM device_ports WHERE device_id=" . $device['id']);
  1015. run_sql($db, "DELETE FROM device_filter_instances WHERE device_id=" . $device['id']);
  1016. run_sql($db, "DELETE FROM gateway_subnets WHERE device_id=".$device['id']);
  1017. delete_record($db, "devices", "id=" . $device['id']);
  1018. }
  1019. //remove auth assign rules
  1020. run_sql($db, "DELETE FROM auth_rules WHERE user_id=$id");
  1021. return $changes;
  1022. }
  1023. function delete_device($db,$id)
  1024. {
  1025. LOG_INFO($db, "Try delete device id: $id ".dump_record($db,'devices','id='.$id));
  1026. //remove user record
  1027. $changes = delete_record($db, "devices", "id=" . $id);
  1028. //if fail - exit
  1029. if (!isset($changes) or empty($changes)) {
  1030. LOG_INFO($db,"Device id: $id has not been deleted");
  1031. return;
  1032. }
  1033. unbind_ports($db, $id);
  1034. run_sql($db, "DELETE FROM connections WHERE device_id=" . $id);
  1035. run_sql($db, "DELETE FROM device_l3_interfaces WHERE device_id=" . $id);
  1036. run_sql($db, "DELETE FROM device_ports WHERE device_id=" . $id);
  1037. run_sql($db, "DELETE FROM device_filter_instances WHERE device_id=" . $id);
  1038. run_sql($db, "DELETE FROM gateway_subnets WHERE device_id=".$id);
  1039. return $changes;
  1040. }
  1041. function record_to_txt($db, $table, $id) {
  1042. $record = get_record_sql($db, 'SELECT * FROM ' . $table . ' WHERE id =' . $id);
  1043. return hash_to_text($record);
  1044. }
  1045. $db_link = new_connection(DB_TYPE, DB_HOST, DB_USER, DB_PASS, DB_NAME);
  1046. ?>