1
0

sql.php 44 KB

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