sql.php 43 KB

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