sql.php 35 KB

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