sql.php 38 KB

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