sql.php 35 KB

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