1
0

sql.php 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320
  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. function get_record_sql($db, $sql) {
  472. if (empty($sql)) {
  473. return null;
  474. }
  475. // Добавляем LIMIT 1, если его нет
  476. if (!preg_match('/\bLIMIT\s+\d+$/i', $sql)) {
  477. $sql .= " LIMIT 1";
  478. }
  479. $result = get_records_sql($db, $sql);
  480. // Возвращаем первую запись или null
  481. return !empty($result) ? $result[0] : null;
  482. }
  483. /**
  484. * Получить несколько записей по произвольному SQL-запросу
  485. */
  486. function get_records_sql($db, $sql) {
  487. $result = [];
  488. if (empty($sql)) {
  489. return $result;
  490. }
  491. try {
  492. $stmt = $db->query($sql);
  493. $records = $stmt->fetchAll(PDO::FETCH_ASSOC);
  494. if (!empty($records)) {
  495. $result = normalize_records($records);
  496. }
  497. return $result;
  498. } catch (PDOException $e) {
  499. LOG_ERROR($db, "SQL: $sql : " . $e->getMessage());
  500. return $result;
  501. }
  502. }
  503. /**
  504. * Получить одно значение поля по SQL-запросу
  505. */
  506. function get_single_field($db, $sql) {
  507. $record = get_record_sql($db, $sql);
  508. if (!empty($record) && is_array($record)) {
  509. // Получаем первое значение из записи
  510. return reset($record) ?: 0;
  511. }
  512. return 0;
  513. }
  514. /**
  515. * Получить ID записи из таблицы по фильтру
  516. */
  517. function get_id_record($db, $table, $filter) {
  518. if (empty($filter)) {
  519. return 0;
  520. }
  521. $record = get_record($db, $table, $filter);
  522. return !empty($record['id']) ? $record['id'] : 0;
  523. }
  524. function set_changed($db, $id)
  525. {
  526. $auth['changed'] = 1;
  527. update_record($db, "user_auth", "id=" . $id, $auth);
  528. }
  529. function allow_update($table, $action = 'update', $field = '')
  530. {
  531. // 1. Таблицы с полным доступом (регистронезависимо, но без regex)
  532. static $full_access_tables = [
  533. 'variables' => true,
  534. 'dns_cache' => true,
  535. 'worklog' => true,
  536. 'sessions' => true
  537. ];
  538. if (isset($full_access_tables[strtolower($table)])) {
  539. return 1;
  540. }
  541. // 2. Получение данных сессии (единая точка)
  542. $login = $_SESSION['login'] ?? null;
  543. $user_id = $_SESSION['user_id'] ?? null;
  544. $acl = $_SESSION['acl'] ?? null;
  545. // Проверка аутентификации
  546. if (!$login || !$user_id || !$acl) {
  547. return 0;
  548. }
  549. // Приведение ACL к целому числу
  550. $user_level = (int)$acl;
  551. // 3. Права по уровням
  552. if ($user_level === 1) { // Администратор
  553. return 1;
  554. }
  555. if ($user_level === 3) { // ViewOnly
  556. return 0;
  557. }
  558. // 4. Таблицы с полным доступом для оператора
  559. static $operator_tables = [
  560. 'dns_queue' => true,
  561. 'user_auth_alias' => true
  562. ];
  563. if (isset($operator_tables[strtolower($table)])) {
  564. return 1;
  565. }
  566. // 5. Проверка полей для оператора (только при update)
  567. if ($action === 'update') {
  568. static $operator_acl = [
  569. 'user_auth' => [
  570. 'description' => true,
  571. 'dns_name' => true,
  572. 'dns_ptr_only' => true,
  573. 'firmware' => true,
  574. 'link_check' => true,
  575. 'nagios' => true,
  576. 'nagios_handler' => true,
  577. 'Wikiname' => true
  578. ],
  579. 'user_list' => [
  580. 'fio' => true,
  581. 'login' => true
  582. ]
  583. ];
  584. // Проверка существования таблицы в ACL
  585. if (!isset($operator_acl[$table])) {
  586. return 0;
  587. }
  588. // Если поле не указано — разрешаем (полный доступ к таблице)
  589. if ($field === '') {
  590. return 1;
  591. }
  592. // Проверка прав на конкретное поле
  593. return $operator_acl[$table][$field] ?? 0;
  594. }
  595. return 0;
  596. }
  597. function update_record($db, $table, $filter, $newvalue)
  598. {
  599. if (!isset($table)) {
  600. # LOG_WARNING($db, "Change record for unknown table! Skip command.");
  601. return;
  602. }
  603. if (!isset($filter)) {
  604. # LOG_WARNING($db, "Change record ($table) with empty filter! Skip command.");
  605. return;
  606. }
  607. if (preg_match('/=$/', $filter)) {
  608. LOG_WARNING($db, "Change record ($table) with illegal filter $filter! Skip command.");
  609. return;
  610. }
  611. if (!isset($newvalue)) {
  612. # LOG_WARNING($db, "Change record ($table [ $filter ]) with empty data! Skip command.");
  613. return;
  614. }
  615. if (!allow_update($table, 'update')) {
  616. LOG_INFO($db, "Access denied: $table [ $filter ]");
  617. return 1;
  618. }
  619. $old_sql = "SELECT * FROM $table WHERE $filter";
  620. try {
  621. $stmt = $db->query($old_sql);
  622. $old = $stmt->fetch(PDO::FETCH_ASSOC);
  623. } catch (PDOException $e) {
  624. LOG_ERROR($db, "SQL: $old_sql :" . $e->getMessage());
  625. return;
  626. }
  627. $rec_id = NULL;
  628. if (!empty($old['id'])) {
  629. $rec_id = $old['id'];
  630. }
  631. $changed_log = '';
  632. $set_parts = [];
  633. $params = [];
  634. $network_changed = 0;
  635. $dhcp_changed = 0;
  636. $dns_changed = 0;
  637. $acl_fields = [
  638. 'ip' => '1',
  639. 'ip_int' => '1',
  640. 'enabled' => '1',
  641. 'dhcp' => '1',
  642. 'filter_group_id' => '1',
  643. 'deleted' => '1',
  644. 'dhcp_acl' => '1',
  645. 'queue_id' => '1',
  646. 'mac' => '1',
  647. 'blocked' => '1',
  648. ];
  649. $dhcp_fields = [
  650. 'ip' => '1',
  651. 'dhcp' => '1',
  652. 'deleted' => '1',
  653. 'dhcp_option_set' =>'1',
  654. 'dhcp_acl' => '1',
  655. 'mac' => '1',
  656. ];
  657. $dns_fields = [
  658. 'ip' => '1',
  659. 'dns_name' => '1',
  660. 'dns_ptr_only' => '1',
  661. 'alias' => '1',
  662. ];
  663. foreach ($newvalue as $key => $value) {
  664. if (!allow_update($table, 'update', $key)) {
  665. continue;
  666. }
  667. if (!isset($value)) {
  668. $value = '';
  669. }
  670. $value = trim($value);
  671. if (isset($old[$key]) && strcmp($old[$key], $value) == 0) {
  672. continue;
  673. }
  674. if ($table === "user_auth") {
  675. if (!empty($acl_fields["$key"])) {
  676. $network_changed = 1;
  677. }
  678. if (!empty($dhcp_fields["$key"])) {
  679. $dhcp_changed = 1;
  680. }
  681. if (!empty($dns_fields["$key"])) {
  682. $dns_changed = 1;
  683. }
  684. }
  685. if ($table === "user_auth_alias") {
  686. if (!empty($dns_fields["$key"])) {
  687. $dns_changed = 1;
  688. }
  689. }
  690. if (!preg_match('/password/i', $key)) {
  691. $changed_log = $changed_log . " $key => $value (old: " . ($old[$key] ?? '') . "),";
  692. }
  693. $set_parts[] = "$key = ?";
  694. $params[] = $value;
  695. }
  696. if ($table === "user_auth" and $dns_changed) {
  697. if (!empty($old['dns_name']) and !empty($old['ip']) and !$old['dns_ptr_only'] and !preg_match('/\.$/', $old['dns_name'])) {
  698. $del_dns['name_type'] = 'A';
  699. $del_dns['name'] = $old['dns_name'];
  700. $del_dns['value'] = $old['ip'];
  701. $del_dns['operation_type'] = 'del';
  702. if (!empty($rec_id)) {
  703. $del_dns['auth_id'] = $rec_id;
  704. }
  705. insert_record($db, 'dns_queue', $del_dns);
  706. }
  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'] = 'PTR';
  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($newvalue['dns_name']) and !empty($newvalue['ip']) and !$newvalue['dns_ptr_only'] and !preg_match('/\.$/', $newvalue['dns_name'])) {
  718. $new_dns['name_type'] = 'A';
  719. $new_dns['name'] = $newvalue['dns_name'];
  720. $new_dns['value'] = $newvalue['ip'];
  721. $new_dns['operation_type'] = 'add';
  722. if (!empty($rec_id)) {
  723. $new_dns['auth_id'] = $rec_id;
  724. }
  725. insert_record($db, 'dns_queue', $new_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'] = 'PTR';
  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. }
  738. if ($table === "user_auth_alias" and $dns_changed) {
  739. $auth_id = NULL;
  740. if ($old['auth_id']) {
  741. $auth_id = $old['auth_id'];
  742. }
  743. if (!empty($old['alias']) and !preg_match('/\.$/', $old['alias'])) {
  744. $del_dns['name_type'] = 'CNAME';
  745. $del_dns['name'] = $old['alias'];
  746. $del_dns['operation_type'] = 'del';
  747. if (!empty($auth_id)) {
  748. $del_dns['auth_id'] = $auth_id;
  749. $del_dns['value'] = get_dns_name($db, $auth_id);
  750. }
  751. insert_record($db, 'dns_queue', $del_dns);
  752. }
  753. if (!empty($newvalue['alias']) and !preg_match('/\.$/', $newvalue['alias'])) {
  754. $new_dns['name_type'] = 'CNAME';
  755. $new_dns['name'] = $newvalue['alias'];
  756. $new_dns['operation_type'] = 'add';
  757. if (!empty($auth_id)) {
  758. $new_dns['auth_id'] = $auth_id;
  759. $new_dns['value'] = get_dns_name($db, $auth_id);
  760. }
  761. insert_record($db, 'dns_queue', $new_dns);
  762. }
  763. }
  764. if (empty($set_parts)) {
  765. return 1;
  766. }
  767. if ($network_changed) {
  768. $set_parts[] = "changed = '1'";
  769. }
  770. if ($dhcp_changed) {
  771. $set_parts[] = "dhcp_changed = '1'";
  772. }
  773. $changed_log = substr_replace($changed_log, "", -1);
  774. $run_sql = implode(", ", $set_parts);
  775. if ($table === 'user_auth') {
  776. $changed_time = GetNowTimeString();
  777. $run_sql .= ", changed_time = ?";
  778. $params[] = $changed_time;
  779. }
  780. $new_sql = "UPDATE $table SET $run_sql WHERE $filter";
  781. LOG_DEBUG($db, "Run sql: $new_sql");
  782. try {
  783. $stmt = $db->prepare($new_sql);
  784. $sql_result = $stmt->execute($params);
  785. if (!$sql_result) {
  786. LOG_ERROR($db, "UPDATE Request: $new_sql");
  787. return;
  788. }
  789. if ($table !== "sessions") {
  790. LOG_VERBOSE($db, "Change table $table WHERE $filter set $changed_log");
  791. }
  792. return $sql_result;
  793. } catch (PDOException $e) {
  794. LOG_ERROR($db, "SQL: $new_sql :" . $e->getMessage());
  795. return;
  796. }
  797. }
  798. function delete_record($db, $table, $filter)
  799. {
  800. if (!allow_update($table, 'del')) {
  801. # LOG_INFO($db, "User does not have write permission");
  802. return;
  803. }
  804. if (!isset($table)) {
  805. # LOG_WARNING($db, "Delete FROM unknown table! Skip command.");
  806. return;
  807. }
  808. if (!isset($filter)) {
  809. LOG_WARNING($db, "Delete FROM table $table with empty filter! Skip command.");
  810. return;
  811. }
  812. if (preg_match('/=$/', $filter)) {
  813. LOG_WARNING($db, "Change record ($table) with illegal filter $filter! Skip command.");
  814. return;
  815. }
  816. $old_sql = "SELECT * FROM $table WHERE $filter";
  817. try {
  818. $stmt = $db->query($old_sql);
  819. $old = $stmt->fetch(PDO::FETCH_ASSOC);
  820. } catch (PDOException $e) {
  821. LOG_ERROR($db, "SQL: $old_sql :" . $e->getMessage());
  822. return;
  823. }
  824. $rec_id = NULL;
  825. if (!empty($old['id'])) {
  826. $rec_id = $old['id'];
  827. }
  828. $changed_log = 'record: ';
  829. if (!empty($old)) {
  830. asort($old, SORT_STRING);
  831. $old = array_reverse($old, 1);
  832. foreach ($old as $key => $value) {
  833. if (empty($value)) {
  834. continue;
  835. }
  836. if (preg_match('/action/', $key)) {
  837. continue;
  838. }
  839. if (preg_match('/status/', $key)) {
  840. continue;
  841. }
  842. if (preg_match('/time/', $key)) {
  843. continue;
  844. }
  845. if (preg_match('/found/', $key)) {
  846. continue;
  847. }
  848. $changed_log = $changed_log . " $key => $value,";
  849. }
  850. }
  851. $delete_it = 1;
  852. //never delete user ip record
  853. if ($table === 'user_auth') {
  854. $delete_it = 0;
  855. $changed_time = GetNowTimeString();
  856. $new_sql = "UPDATE $table SET deleted=1, changed=1, changed_time='" . $changed_time . "' WHERE $filter";
  857. LOG_DEBUG($db, "Run sql: $new_sql");
  858. try {
  859. $sql_result = $db->exec($new_sql);
  860. if ($sql_result === false) {
  861. LOG_ERROR($db, "UPDATE Request (from delete)");
  862. return;
  863. }
  864. } catch (PDOException $e) {
  865. LOG_ERROR($db, "SQL: $new_sql :" . $e->getMessage());
  866. return;
  867. }
  868. //dns - A-record
  869. if (!empty($old['dns_name']) and !empty($old['ip']) and !$old['dns_ptr_only'] and !preg_match('/\.$/', $old['dns_name'])) {
  870. $del_dns['name_type'] = 'A';
  871. $del_dns['name'] = $old['dns_name'];
  872. $del_dns['value'] = $old['ip'];
  873. $del_dns['operation_type'] = 'del';
  874. if (!empty($rec_id)) {
  875. $del_dns['auth_id'] = $rec_id;
  876. }
  877. insert_record($db, 'dns_queue', $del_dns);
  878. }
  879. //ptr
  880. if (!empty($old['dns_name']) and !empty($old['ip']) and $old['dns_ptr_only'] and !preg_match('/\.$/', $old['dns_name'])) {
  881. $del_dns['name_type'] = 'PTR';
  882. $del_dns['name'] = $old['dns_name'];
  883. $del_dns['value'] = $old['ip'];
  884. $del_dns['operation_type'] = 'del';
  885. if (!empty($rec_id)) {
  886. $del_dns['auth_id'] = $rec_id;
  887. }
  888. insert_record($db, 'dns_queue', $del_dns);
  889. }
  890. LOG_VERBOSE($db, "Deleted FROM table $table WHERE $filter $changed_log");
  891. return $changed_log;
  892. }
  893. //never delete permanent user
  894. if ($table === 'user_list' and $old['permanent']) { return; }
  895. //remove aliases
  896. if ($table === 'user_auth_alias') {
  897. //dns
  898. if (!empty($old['alias']) and !preg_match('/\.$/', $old['alias'])) {
  899. $del_dns['name_type'] = 'CNAME';
  900. $del_dns['name'] = $old['alias'];
  901. $del_dns['value'] = '';
  902. $del_dns['operation_type'] = 'del';
  903. if (!empty($old['auth_id'])) {
  904. $del_dns['auth_id'] = $old['auth_id'];
  905. $del_dns['value'] = get_dns_name($db, $old['auth_id']);
  906. }
  907. insert_record($db, 'dns_queue', $del_dns);
  908. }
  909. }
  910. if ($delete_it) {
  911. $new_sql = "DELETE FROM $table WHERE $filter";
  912. LOG_DEBUG($db, "Run sql: $new_sql");
  913. try {
  914. $sql_result = $db->exec($new_sql);
  915. if ($sql_result === false) {
  916. LOG_ERROR($db, "DELETE Request: $new_sql");
  917. return;
  918. }
  919. } catch (PDOException $e) {
  920. LOG_ERROR($db, "SQL: $new_sql : " . $e->getMessage());
  921. return;
  922. }
  923. } else { return; }
  924. if ($table !== "sessions") {
  925. LOG_VERBOSE($db, "Deleted FROM table $table WHERE $filter $changed_log");
  926. }
  927. return $changed_log;
  928. }
  929. function insert_record($db, $table, $newvalue)
  930. {
  931. if (!allow_update($table, 'add')) {
  932. // LOG_WARNING($db, "User does not have write permission");
  933. return;
  934. }
  935. if (!isset($table) || empty($table)) {
  936. // LOG_WARNING($db, "Create record for unknown table! Skip command.");
  937. return;
  938. }
  939. if (empty($newvalue) || !is_array($newvalue)) {
  940. // LOG_WARNING($db, "Create record ($table) with empty data! Skip command.");
  941. return;
  942. }
  943. // Валидация имени таблицы (защита от SQL-инъекций через имя таблицы)
  944. if (!preg_match('/^[a-z_][a-z0-9_]*$/', $table)) {
  945. // LOG_WARNING($db, "Invalid table name: $table");
  946. return;
  947. }
  948. $changed_log = '';
  949. $field_list = [];
  950. $value_list = [];
  951. $params = [];
  952. foreach ($newvalue as $key => $value) {
  953. // Валидация имени колонки
  954. if (!preg_match('/^[a-z_][a-z0-9_]*$/', $key)) {
  955. // Пропускаем недопустимые имена колонок
  956. continue;
  957. }
  958. // Обработка пустых значений
  959. if ('' === $value && '0' !== $value) {
  960. $value = null; // или оставить как '', но null безопаснее для SQL
  961. } else {
  962. $value = trim((string)$value);
  963. }
  964. // Логирование (без паролей)
  965. if (!preg_match('/password/i', $key)) {
  966. $changed_log .= " $key => " . ($value ?? 'NULL') . ",";
  967. }
  968. $field_list[] = $key;
  969. $value_list[] = '?';
  970. $params[] = $value;
  971. }
  972. if (empty($field_list)) {
  973. return;
  974. }
  975. // Формируем SQL
  976. $field_list_str = implode(',', $field_list);
  977. $value_list_str = implode(',', $value_list);
  978. $new_sql = "INSERT INTO $table ($field_list_str) VALUES ($value_list_str)";
  979. LOG_DEBUG($db, "Run sql: $new_sql");
  980. try {
  981. $stmt = $db->prepare($new_sql);
  982. $sql_result = $stmt->execute($params);
  983. if (!$sql_result) {
  984. LOG_ERROR($db, "INSERT Request");
  985. return;
  986. }
  987. $last_id = $db->lastInsertId();
  988. if ($table !== "sessions") {
  989. LOG_VERBOSE($db, "Create record in table $table: $changed_log with id: $last_id");
  990. }
  991. if ($table === 'user_auth') {
  992. run_sql($db, "UPDATE user_auth SET changed=1, dhcp_changed=1 WHERE id=" . $last_id);
  993. }
  994. if ($table === 'user_auth_alias') {
  995. //dns
  996. if (!empty($newvalue['alias']) and !preg_match('/\.$/', $newvalue['alias'])) {
  997. $add_dns['name_type'] = 'CNAME';
  998. $add_dns['name'] = $newvalue['alias'];
  999. $add_dns['value'] = get_dns_name($db, $newvalue['auth_id']);
  1000. $add_dns['operation_type'] = 'add';
  1001. $add_dns['auth_id'] = $newvalue['auth_id'];
  1002. insert_record($db, 'dns_queue', $add_dns);
  1003. }
  1004. }
  1005. if ($table === 'user_auth') {
  1006. //dns - A-record
  1007. if (!empty($newvalue['dns_name']) and !empty($newvalue['ip']) and !$newvalue['dns_ptr_only'] and !preg_match('/\.$/', $newvalue['dns_name'])) {
  1008. $add_dns['name_type'] = 'A';
  1009. $add_dns['name'] = $newvalue['dns_name'];
  1010. $add_dns['value'] = $newvalue['ip'];
  1011. $add_dns['operation_type'] = 'add';
  1012. $add_dns['auth_id'] = $last_id;
  1013. insert_record($db, 'dns_queue', $add_dns);
  1014. }
  1015. //dns - ptr
  1016. if (!empty($newvalue['dns_name']) and !empty($newvalue['ip']) and $newvalue['dns_ptr_only'] and !preg_match('/\.$/', $newvalue['dns_name'])) {
  1017. $add_dns['name_type'] = 'PTR';
  1018. $add_dns['name'] = $newvalue['dns_name'];
  1019. $add_dns['value'] = $newvalue['ip'];
  1020. $add_dns['operation_type'] = 'add';
  1021. $add_dns['auth_id'] = $last_id;
  1022. insert_record($db, 'dns_queue', $add_dns);
  1023. }
  1024. }
  1025. return $last_id;
  1026. } catch (PDOException $e) {
  1027. LOG_ERROR($db, "SQL: $new_sql :" . $e->getMessage());
  1028. return;
  1029. }
  1030. }
  1031. function dump_record($db, $table, $filter)
  1032. {
  1033. $result = '';
  1034. $old = get_record($db, $table, $filter);
  1035. if (empty($old)) {
  1036. return $result;
  1037. }
  1038. $result = 'record: ' . get_rec_str($old);
  1039. return $result;
  1040. }
  1041. function get_rec_str($array)
  1042. {
  1043. $result = '';
  1044. foreach ($array as $key => $value) {
  1045. $result .= "[" . $key . "]=" . $value . ", ";
  1046. }
  1047. $result = preg_replace('/,\s+$/', '', $result);
  1048. return $result;
  1049. }
  1050. function get_diff_rec($db, $table, $filter, $newvalue, $only_changed = false)
  1051. {
  1052. if (!isset($table) || !isset($filter) || !isset($newvalue)) {
  1053. return '';
  1054. }
  1055. $old_sql = "SELECT * FROM $table WHERE $filter";
  1056. try {
  1057. $stmt = $db->query($old_sql);
  1058. $old = $stmt->fetch(PDO::FETCH_ASSOC);
  1059. if (!$old) {
  1060. // Запись не найдена — возможно, ошибка или новая запись
  1061. return "Record not found for filter: $filter";
  1062. }
  1063. $changed = [];
  1064. $unchanged = [];
  1065. foreach ($newvalue as $key => $new_val) {
  1066. // Пропускаем ключи, которых нет в старой записи (например, служебные поля)
  1067. if (!array_key_exists($key, $old)) {
  1068. continue;
  1069. }
  1070. $old_val = $old[$key];
  1071. // Сравниваем как строки, но аккуратно с null
  1072. $old_str = ($old_val === null) ? '' : (string)$old_val;
  1073. $new_str = ($new_val === null) ? '' : (string)$new_val;
  1074. if ($old_str !== $new_str) {
  1075. $changed[$key] = $new_str . ' [ old: ' . $old_str . ' ]';
  1076. } else {
  1077. $unchanged[$key] = $old_val;
  1078. }
  1079. }
  1080. if ($only_changed) {
  1081. return empty($changed) ? '' : hash_to_text($changed);
  1082. }
  1083. $output = '';
  1084. if (!empty($changed)) {
  1085. $output .= hash_to_text($changed);
  1086. } else {
  1087. $output .= "# no changes";
  1088. }
  1089. if (!empty($unchanged)) {
  1090. $output .= "\r\nHas not changed:\r\n" . hash_to_text($unchanged);
  1091. }
  1092. return $output;
  1093. } catch (PDOException $e) {
  1094. LOG_ERROR($db, "SQL: $old_sql :" . $e->getMessage());
  1095. return '';
  1096. }
  1097. }
  1098. function delete_user_auth($db, $id) {
  1099. $msg = '';
  1100. $record = get_record_sql($db, 'SELECT * FROM user_auth WHERE id=' . $id);
  1101. $txt_record = hash_to_text($record);
  1102. // remove aliases
  1103. $t_user_auth_alias = get_records_sql($db, 'SELECT * FROM user_auth_alias WHERE auth_id=' . $id);
  1104. if (!empty($t_user_auth_alias)) {
  1105. foreach ($t_user_auth_alias as $row) {
  1106. $alias_txt = record_to_txt($db, 'user_auth_alias', 'id=' . $row['id']);
  1107. if (delete_record($db, 'user_auth_alias', 'id=' . $row['id'])) {
  1108. $msg = "Deleting an alias: " . $alias_txt . "::Success!\n" . $msg;
  1109. } else {
  1110. $msg = "Deleting an alias: " . $alias_txt . "::Fail!\n" . $msg;
  1111. }
  1112. }
  1113. }
  1114. // remove connections
  1115. run_sql($db, 'DELETE FROM connections WHERE auth_id=' . $id);
  1116. // remove user auth record
  1117. $changes = delete_record($db, "user_auth", "id=" . $id);
  1118. if ($changes) {
  1119. $msg = "Deleting ip-record: " . $txt_record . "::Success!\n" . $msg;
  1120. } else {
  1121. $msg = "Deleting ip-record: " . $txt_record . "::Fail!\n" . $msg;
  1122. }
  1123. LOG_WARNING($db, $msg);
  1124. $send_alert_delete = isNotifyDelete(get_notify_subnet($db, $record['ip']));
  1125. if ($send_alert_delete) { email(L_WARNING,$msg); }
  1126. return $changes;
  1127. }
  1128. function delete_user($db,$id)
  1129. {
  1130. //remove user record
  1131. $changes = delete_record($db, "user_list", "id=" . $id);
  1132. //if fail - exit
  1133. if (!isset($changes) or empty($changes)) { return; }
  1134. //remove auth records
  1135. $t_user_auth = get_records($db,'user_auth',"user_id=$id");
  1136. if (!empty($t_user_auth)) {
  1137. foreach ( $t_user_auth as $row ) { delete_user_auth($db,$row['id']); }
  1138. }
  1139. //remove device
  1140. $device = get_record($db, "devices", "user_id='$id'");
  1141. if (!empty($device)) {
  1142. LOG_INFO($db, "Delete device for user id: $id ".dump_record($db,'devices','user_id='.$id));
  1143. unbind_ports($db, $device['id']);
  1144. run_sql($db, "DELETE FROM connections WHERE device_id=" . $device['id']);
  1145. run_sql($db, "DELETE FROM device_l3_interfaces WHERE device_id=" . $device['id']);
  1146. run_sql($db, "DELETE FROM device_ports WHERE device_id=" . $device['id']);
  1147. run_sql($db, "DELETE FROM device_filter_instances WHERE device_id=" . $device['id']);
  1148. run_sql($db, "DELETE FROM gateway_subnets WHERE device_id=".$device['id']);
  1149. delete_record($db, "devices", "id=" . $device['id']);
  1150. }
  1151. //remove auth assign rules
  1152. run_sql($db, "DELETE FROM auth_rules WHERE user_id=$id");
  1153. return $changes;
  1154. }
  1155. function delete_device($db,$id)
  1156. {
  1157. LOG_INFO($db, "Try delete device id: $id ".dump_record($db,'devices','id='.$id));
  1158. //remove user record
  1159. $changes = delete_record($db, "devices", "id=" . $id);
  1160. //if fail - exit
  1161. if (!isset($changes) or empty($changes)) {
  1162. LOG_INFO($db,"Device id: $id has not been deleted");
  1163. return;
  1164. }
  1165. unbind_ports($db, $id);
  1166. run_sql($db, "DELETE FROM connections WHERE device_id=" . $id);
  1167. run_sql($db, "DELETE FROM device_l3_interfaces WHERE device_id=" . $id);
  1168. run_sql($db, "DELETE FROM device_ports WHERE device_id=" . $id);
  1169. run_sql($db, "DELETE FROM device_filter_instances WHERE device_id=" . $id);
  1170. run_sql($db, "DELETE FROM gateway_subnets WHERE device_id=".$id);
  1171. return $changes;
  1172. }
  1173. function record_to_txt($db, $table, $id) {
  1174. $record = get_record_sql($db, 'SELECT * FROM ' . $table . ' WHERE id =' . $id);
  1175. return hash_to_text($record);
  1176. }
  1177. $db_link = new_connection(DB_TYPE, DB_HOST, DB_USER, DB_PASS, DB_NAME);
  1178. ?>