sql.php 42 KB

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