sql.php 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599
  1. <?php
  2. if (! defined("CONFIG")) die("Not defined");
  3. if (! defined("SQL")) { die("Not defined"); }
  4. /**
  5. * Prepares an audit log message with human-readable context using PDO.
  6. *
  7. * @param PDO $pdo Database connection
  8. * @param string $table Table name
  9. * @param array|null $old_data Record data before operation (null for insert)
  10. * @param array|null $new_data Record data after operation (null for delete)
  11. * @param int $record_id Record ID
  12. * @param string $operation Operation: 'insert', 'update', 'delete'
  13. * @return string|null Audit message or null if no relevant changes
  14. */
  15. function prepareAuditMessage(PDO $db, string $table, ?array $old_data, ?array $new_data, int $record_id, string $operation): ?string
  16. {
  17. // === 1. Определяем отслеживаемые таблицы ===
  18. $audit_config = [
  19. 'auth_rules' => [
  20. 'summary' => ['rule'],
  21. 'fields' => ['user_id', 'ou_id', 'rule_type', 'rule', 'description']
  22. ],
  23. 'building' => [
  24. 'summary' => ['name'],
  25. 'fields' => ['name', 'description']
  26. ],
  27. 'customers' => [
  28. 'summary' => ['login'],
  29. 'fields' => ['login', 'description', 'rights']
  30. ],
  31. 'devices' => [
  32. 'summary' => ['device_name'],
  33. 'fields' => [
  34. 'device_type', 'device_model_id', 'vendor_id', 'device_name', 'building_id',
  35. 'ip', 'login', 'protocol', 'control_port', 'port_count', 'sn',
  36. 'description', 'snmp_version', 'snmp3_auth_proto', 'snmp3_priv_proto',
  37. 'snmp3_user_rw', 'snmp3_user_ro', 'community', 'rw_community',
  38. 'discovery', 'netflow_save', 'user_acl', 'dhcp', 'nagios',
  39. 'active', 'queue_enabled', 'connected_user_only', 'user_id'
  40. ]
  41. ],
  42. 'device_filter_instances' => [
  43. 'summary' => [],
  44. 'fields' => ['instance_id', 'device_id']
  45. ],
  46. 'device_l3_interfaces' => [
  47. 'summary' => ['name'],
  48. 'fields' => ['device_id', 'snmpin', 'interface_type', 'name']
  49. ],
  50. 'device_models' => [
  51. 'summary' => ['model_name'],
  52. 'fields' => ['model_name', 'vendor_id', 'poe_in', 'poe_out', 'nagios_template']
  53. ],
  54. 'device_ports' => [
  55. 'summary' => ['port', 'ifname'],
  56. 'fields' => [
  57. 'device_id', 'snmp_index', 'port', 'ifname', 'port_name', 'description',
  58. 'target_port_id', 'auth_id', 'last_mac_count', 'uplink', 'nagios',
  59. 'skip', 'vlan', 'tagged_vlan', 'untagged_vlan', 'forbidden_vlan'
  60. ]
  61. ],
  62. 'filter_instances' => [
  63. 'summary' => ['name'],
  64. 'fields' => ['name', 'description']
  65. ],
  66. 'filter_list' => [
  67. 'summary' => ['name'],
  68. 'fields' => ['name', 'description', 'proto', 'dst', 'dstport', 'srcport', 'filter_type']
  69. ],
  70. 'gateway_subnets' => [
  71. 'summary' => [],
  72. 'fields' => ['device_id', 'subnet_id']
  73. ],
  74. 'group_filters' => [
  75. 'summary' => [],
  76. 'fields' => ['group_id', 'filter_id', 'rule_order', 'action']
  77. ],
  78. 'group_list' => [
  79. 'summary' => ['group_name'],
  80. 'fields' => ['instance_id', 'group_name', 'description']
  81. ],
  82. 'ou' => [
  83. 'summary' => ['ou_name'],
  84. 'fields' => [
  85. 'ou_name', 'description', 'default_users', 'default_hotspot',
  86. 'nagios_dir', 'nagios_host_use', 'nagios_ping', 'nagios_default_service',
  87. 'enabled', 'filter_group_id', 'queue_id', 'dynamic', 'life_duration', 'parent_id'
  88. ]
  89. ],
  90. 'queue_list' => [
  91. 'summary' => ['queue_name'],
  92. 'fields' => ['queue_name', 'download', 'upload']
  93. ],
  94. 'subnets' => [
  95. 'summary' => ['subnet'],
  96. 'fields' => [
  97. 'subnet', 'vlan_tag', 'ip_int_start', 'ip_int_stop', 'dhcp_start', 'dhcp_stop',
  98. 'dhcp_lease_time', 'gateway', 'office', 'hotspot', 'vpn', 'free', 'dhcp',
  99. 'static', 'dhcp_update_hostname', 'discovery', 'notify', 'description'
  100. ]
  101. ],
  102. 'user_auth' => [
  103. 'summary' => ['ip', 'dns_name'],
  104. 'fields' => [
  105. 'user_id', 'ou_id', 'ip', 'save_traf', 'enabled', 'dhcp', 'filter_group_id',
  106. 'dynamic', 'end_life', 'description', 'dns_name', 'dns_ptr_only', 'wikiname',
  107. 'dhcp_acl', 'queue_id', 'mac', 'dhcp_option_set', 'blocked', 'day_quota',
  108. 'month_quota', 'device_model_id', 'firmware', 'client_id', 'nagios',
  109. 'nagios_handler', 'link_check', 'deleted'
  110. ]
  111. ],
  112. 'user_auth_alias' => [
  113. 'summary' => ['alias'],
  114. 'fields' => ['auth_id', 'alias', 'description']
  115. ],
  116. 'user_list' => [
  117. 'summary' => ['login'],
  118. 'fields' => [
  119. 'login', 'description', 'enabled', 'blocked', 'deleted', 'ou_id',
  120. 'device_id', 'filter_group_id', 'queue_id', 'day_quota', 'month_quota', 'permanent'
  121. ]
  122. ],
  123. 'vendors' => [
  124. 'summary' => ['name'],
  125. 'fields' => ['name']
  126. ]
  127. ];
  128. if (!isset($audit_config[$table])) {
  129. return null;
  130. }
  131. $summary_fields = $audit_config[$table]['summary'];
  132. $monitored_fields = $audit_config[$table]['fields'];
  133. // === 3. Нормализуем данные и определяем изменения ===
  134. $changes = [];
  135. if ($operation === 'insert') {
  136. // Показываем все monitored поля как новые
  137. foreach ($monitored_fields as $field) {
  138. if (isset($new_data[$field])) {
  139. $changes[$field] = ['old' => null, 'new' => $new_data[$field]];
  140. }
  141. }
  142. } elseif ($operation === 'delete') {
  143. // Показываем все monitored поля как удалённые
  144. foreach ($monitored_fields as $field) {
  145. if (isset($old_data[$field])) {
  146. $changes[$field] = ['old' => $old_data[$field], 'new' => null];
  147. }
  148. }
  149. } elseif ($operation === 'update') {
  150. $old_data = $old_data ?: [];
  151. $new_data = $new_data ?: [];
  152. foreach ($monitored_fields as $field) {
  153. // Пропускаем, если поле не задано в new_data (например, частичное обновление)
  154. if (!array_key_exists($field, $new_data)) {
  155. continue;
  156. }
  157. $old_val = $old_data[$field] ?? null;
  158. $new_val = $new_data[$field] ?? null;
  159. $old_str = is_null($old_val) ? '' : (string)$old_val;
  160. $new_str = is_null($new_val) ? '' : (string)$new_val;
  161. if ($old_str !== $new_str) {
  162. $changes[$field] = ['old' => $old_val, 'new' => $new_val];
  163. }
  164. }
  165. }
  166. // Если нет изменений — выходим
  167. if (empty($changes)) {
  168. return null;
  169. }
  170. // === 4. Формируем краткое описание записи ===
  171. $summary_parts = [];
  172. foreach ($summary_fields as $field) {
  173. $val = $new_data[$field] ?? $old_data[$field] ?? null;
  174. if ($val !== null && $val !== '') {
  175. $summary_parts[] = (string)$val;
  176. }
  177. }
  178. $summary_label = !empty($summary_parts)
  179. ? '"' . implode(' | ', $summary_parts) . '"'
  180. : "ID=$record_id";
  181. // === 5. Расшифровка *_id полей ===
  182. $resolved_changes = [];
  183. foreach ($changes as $field => $change) {
  184. $old_resolved = resolveReferenceValue($db, $field, $change['old']);
  185. $new_resolved = resolveReferenceValue($db, $field, $change['new']);
  186. $resolved_changes[$field] = ['old' => $old_resolved, 'new' => $new_resolved];
  187. }
  188. // === 6. Формируем сообщение ===
  189. $op_label = match ($operation) {
  190. 'insert' => 'Created',
  191. 'update' => 'Updated',
  192. 'delete' => 'Deleted',
  193. default => ucfirst($operation),
  194. };
  195. $message = sprintf("[%s] %s (%s) in table `%s`:\n",
  196. $op_label,
  197. ucfirst($table),
  198. $summary_label,
  199. $table
  200. );
  201. foreach ($resolved_changes as $field => $change) {
  202. if ($operation === 'insert') {
  203. if (!is_null($change['new'])) {
  204. $message .= sprintf(" %s: %s\n", $field, (string)$change['new']);
  205. }
  206. } elseif ($operation === 'delete') {
  207. if (!is_null($change['old'])) {
  208. $message .= sprintf(" %s: %s\n", $field, (string)$change['old']);
  209. }
  210. } else { // update
  211. $old_display = is_null($change['old']) ? '[NULL]' : (string)$change['old'];
  212. $new_display = is_null($change['new']) ? '[NULL]' : (string)$change['new'];
  213. $message .= sprintf(" %s: \"%s\" → \"%s\"\n", $field, $old_display, $new_display);
  214. }
  215. }
  216. return rtrim($message);
  217. }
  218. // === Вспомогательная функция: расшифровка ссылок ===
  219. function resolveReferenceValue(PDO $db, string $field, $value): ?string
  220. {
  221. if ($value === null || $value === '') {
  222. return null;
  223. }
  224. // Только для целочисленных значений
  225. if (!is_numeric($value) || (string)(int)$value !== (string)$value) {
  226. return (string)$value;
  227. }
  228. $id = (int)$value;
  229. // Простая логика разрешения имён по *_id
  230. switch ($field) {
  231. case 'device_id':
  232. return get_device_name($db, $id) ?: "Device#{$id}";
  233. case 'building_id':
  234. return get_building($db, $id) ?: "Building#{$id}";
  235. case 'user_id':
  236. return get_login($db, $id) ?: "User#{$id}";
  237. case 'ou_id':
  238. return get_ou($db, $id) ?: "OU#{$id}";
  239. case 'vendor_id':
  240. return get_vendor_name($db, $id) ?: "Vendor#{$id}";
  241. case 'device_model_id':
  242. return get_device_model_name($db, $id) ?: "Model#{$id}";
  243. case 'instance_id':
  244. return get_filter_instance_description($db, $id) ?: "FilterInstance#{$id}";
  245. case 'subnet_id':
  246. return get_subnet_description($db, $id) ?: "Subnet#{$id}";
  247. case 'group_id':
  248. return get_group($db, $id) ?: "FilterGroup#{$id}";
  249. case 'filter_id':
  250. return get_filter($db, $id) ?: "Filter#{$id}";
  251. case 'filter_group_id':
  252. return get_group($db, $id) ?: "FilterGroup#{$id}";
  253. case 'queue_id':
  254. return get_queue($db, $id ) ?: "Queue#{$id}";
  255. case 'auth_id':
  256. if ($id <= 0) {
  257. return 'None';
  258. }
  259. $stmt = $db->prepare("
  260. SELECT
  261. COALESCE(ul.login, CONCAT('User#', ua.user_id)) AS login,
  262. ua.ip,
  263. ua.dns_name
  264. FROM user_auth ua
  265. LEFT JOIN user_list ul ON ul.id = ua.user_id
  266. WHERE ua.id = ?
  267. ");
  268. $stmt->execute([$id]);
  269. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  270. if (!$row) {
  271. return "Auth#{$id}";
  272. }
  273. $parts = [];
  274. if (!empty($row['login'])) {
  275. $parts[] = "login: " . $row['login'];
  276. }
  277. if (!empty($row['ip'])) {
  278. $parts[] = "IP: " . $row['ip'];
  279. }
  280. if (!empty($row['dns_name'])) {
  281. $parts[] = "DNS: " . $row['dns_name'];
  282. }
  283. if (empty($parts)) {
  284. return "Auth#{$id}";
  285. }
  286. return implode(', ', $parts);
  287. case 'target_port_id':
  288. if ($id === 0) return 'None';
  289. $stmt = $db->prepare("
  290. SELECT CONCAT(d.device_name, '[', dp.port, ']')
  291. FROM device_ports dp
  292. JOIN devices d ON d.id = dp.device_id
  293. WHERE dp.id = ?
  294. ");
  295. $stmt->execute([$id]);
  296. return $stmt->fetchColumn() ?: "Port#{$id}";
  297. default:
  298. // Неизвестное *_id — возвращаем как есть
  299. return (string)$value;
  300. }
  301. }
  302. function new_connection ($db_type, $db_host, $db_user, $db_password, $db_name, $db_port = null)
  303. {
  304. // Создаем временный логгер для отладки до установки соединения
  305. // $temp_debug_message = function($message) {
  306. // error_log("DB_CONNECTION_DEBUG: " . $message);
  307. // };
  308. // $temp_debug_message("Starting new_connection function");
  309. // $temp_debug_message("DB parameters - type: $db_type, host: $db_host, user: $db_user, db: $db_name");
  310. if (function_exists('filter_var') && defined('FILTER_SANITIZE_FULL_SPECIAL_CHARS')) {
  311. $db_host = filter_var($db_host, FILTER_SANITIZE_FULL_SPECIAL_CHARS);
  312. } else {
  313. // Для PHP < 8.1
  314. $db_host = htmlspecialchars($db_host, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
  315. }
  316. $db_name = preg_replace('/[^a-zA-Z0-9_-]/', '', $db_name);
  317. try {
  318. // $temp_debug_message("Constructing DSN");
  319. // Определяем DSN в зависимости от типа базы данных
  320. $dsn = "";
  321. $options = [
  322. PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
  323. PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
  324. PDO::ATTR_EMULATE_PREPARES => false,
  325. ];
  326. if ($db_type === 'mysql') {
  327. $dsn = "mysql:host=$db_host;dbname=$db_name;charset=utf8mb4";
  328. if (!empty($db_port)) { $dsn .= ";port=$db_port"; }
  329. } elseif ($db_type === 'pgsql' || $db_type === 'postgresql') {
  330. $dsn = "pgsql:host=$db_host;dbname=$db_name";
  331. if (!empty($db_port)) { $dsn .= ";port=$db_port"; }
  332. $options[PDO::PGSQL_ATTR_DISABLE_PREPARES] = false;
  333. } else {
  334. throw new Exception("Unsupported database type: $db_type. Supported types: mysql, pgsql");
  335. }
  336. // $temp_debug_message("DSN: $dsn");
  337. // $temp_debug_message("PDO options: " . json_encode($options));
  338. // $temp_debug_message("Attempting to create PDO connection");
  339. $result = new PDO($dsn, $db_user, $db_password, $options);
  340. // Устанавливаем кодировку для PostgreSQL
  341. if ($db_type === 'pgsql' || $db_type === 'postgresql') {
  342. $result->exec("SET client_encoding TO 'UTF8'");
  343. }
  344. // $temp_debug_message("PDO connection created successfully");
  345. // $temp_debug_message("PDO connection info: " . ($result->getAttribute(PDO::ATTR_CONNECTION_STATUS) ?? 'N/A for PostgreSQL'));
  346. // Проверяем наличие атрибутов перед использованием
  347. if ($db_type === 'mysql') {
  348. // $temp_debug_message("PDO client version: " . $result->getAttribute(PDO::ATTR_CLIENT_VERSION));
  349. // $temp_debug_message("PDO server version: " . $result->getAttribute(PDO::ATTR_SERVER_VERSION));
  350. // Проверка кодировки для MySQL
  351. $stmt = $result->query("SHOW VARIABLES LIKE 'character_set_connection'");
  352. $charset = $stmt->fetch(PDO::FETCH_ASSOC);
  353. // $temp_debug_message("Database character set: " . ($charset['Value'] ?? 'not set'));
  354. } elseif ($db_type === 'pgsql' || $db_type === 'postgresql') {
  355. // Проверка кодировки для PostgreSQL
  356. $stmt = $result->query("SHOW server_encoding");
  357. $charset = $stmt->fetch(PDO::FETCH_ASSOC);
  358. // $temp_debug_message("PostgreSQL server encoding: " . ($charset['server_encoding'] ?? 'not set'));
  359. // Получаем версию PostgreSQL
  360. $stmt = $result->query("SELECT version()");
  361. $version = $stmt->fetch(PDO::FETCH_ASSOC);
  362. // $temp_debug_message("PostgreSQL version: " . ($version['version'] ?? 'unknown'));
  363. }
  364. return $result;
  365. } catch (PDOException $e) {
  366. // Логируем ошибку через error_log, так как соединение не установлено
  367. error_log("DB_CONNECTION_ERROR: Failed to connect to $db_type");
  368. error_log("DB_CONNECTION_ERROR: DSN: $dsn");
  369. error_log("DB_CONNECTION_ERROR: User: $db_user");
  370. error_log("DB_CONNECTION_ERROR: Error code: " . $e->getCode());
  371. error_log("DB_CONNECTION_ERROR: Error message: " . $e->getMessage());
  372. error_log("DB_CONNECTION_ERROR: Trace: " . $e->getTraceAsString());
  373. // Также выводим в консоль для немедленной обратной связи
  374. echo "Error connect to $db_type " . PHP_EOL;
  375. echo "Error message: " . $e->getMessage() . PHP_EOL;
  376. echo "DSN: $dsn" . PHP_EOL;
  377. exit();
  378. } catch (Exception $e) {
  379. // Обработка других исключений (например, неподдерживаемый тип БД)
  380. error_log("DB_CONNECTION_ERROR: " . $e->getMessage());
  381. echo "Error: " . $e->getMessage() . PHP_EOL;
  382. exit();
  383. }
  384. }
  385. /**
  386. * Преобразует ассоциативный массив в человекочитаемый текстовый формат (подобие YAML/Perl hash)
  387. */
  388. function hash_to_text($hash_ref, $indent = 0, &$seen = null) {
  389. if ($seen === null) {
  390. $seen = [];
  391. }
  392. if (!isset($hash_ref)) {
  393. return 'null';
  394. }
  395. if (is_array($hash_ref) && is_assoc($hash_ref)) {
  396. $spaces = str_repeat(' ', $indent);
  397. $lines = [];
  398. $keys = array_keys($hash_ref);
  399. sort($keys);
  400. foreach ($keys as $key) {
  401. $value = $hash_ref[$key];
  402. $formatted_key = preg_match('/^[a-zA-Z_]\w*$/', $key) ? $key : "'" . addslashes($key) . "'";
  403. $formatted_value = '';
  404. if (is_array($value)) {
  405. if (is_assoc($value)) {
  406. $formatted_value = ":\n" . hash_to_text($value, $indent + 1, $seen);
  407. } else {
  408. $formatted_value = array_to_text($value, $indent + 1, $seen);
  409. }
  410. } elseif (is_object($value)) {
  411. // Защита от циклических ссылок для объектов
  412. $obj_id = spl_object_hash($value);
  413. if (isset($seen[$obj_id])) {
  414. $formatted_value = '[circular reference]';
  415. } else {
  416. $seen[$obj_id] = true;
  417. $formatted_value = '[' . get_class($value) . ']';
  418. }
  419. } elseif ($value === null) {
  420. $formatted_value = 'null';
  421. } else {
  422. $formatted_value = "'" . addslashes((string)$value) . "'";
  423. }
  424. if ($formatted_value !== '') {
  425. $lines[] = "$spaces $formatted_key => $formatted_value";
  426. }
  427. }
  428. if (empty($lines)) {
  429. return "$spaces # empty";
  430. }
  431. return implode(",\n", $lines);
  432. } else {
  433. // Не ассоциативный массив или скаляр — обрабатываем как строку
  434. return "'" . (isset($hash_ref) ? addslashes((string)$hash_ref) : '') . "'";
  435. }
  436. }
  437. /**
  438. * Преобразует индексированный массив в текстовый формат
  439. */
  440. function array_to_text($array_ref, $indent = 0, &$seen = null) {
  441. if ($seen === null) {
  442. $seen = [];
  443. }
  444. if (!is_array($array_ref) || empty($array_ref)) {
  445. return '[]';
  446. }
  447. $spaces = str_repeat(' ', $indent);
  448. $lines = [];
  449. foreach ($array_ref as $item) {
  450. $formatted_item = '';
  451. if (is_array($item)) {
  452. if (is_assoc($item)) {
  453. $formatted_item = ":\n" . hash_to_text($item, $indent + 1, $seen);
  454. } else {
  455. $formatted_item = array_to_text($item, $indent + 1, $seen);
  456. }
  457. } elseif (is_object($item)) {
  458. $obj_id = spl_object_hash($item);
  459. if (isset($seen[$obj_id])) {
  460. $formatted_item = '[circular reference]';
  461. } else {
  462. $seen[$obj_id] = true;
  463. $formatted_item = '[' . get_class($item) . ']';
  464. }
  465. } elseif ($item === null) {
  466. $formatted_item = 'null';
  467. } else {
  468. $formatted_item = "'" . addslashes((string)$item) . "'";
  469. }
  470. if ($formatted_item !== '') {
  471. $lines[] = "$spaces $formatted_item";
  472. }
  473. }
  474. if (empty($lines)) {
  475. return "[]";
  476. }
  477. return "[\n" . implode(",\n", $lines) . "\n$spaces]";
  478. }
  479. /**
  480. * Проверяет, является ли массив ассоциативным
  481. */
  482. function is_assoc($array) {
  483. if (!is_array($array) || empty($array)) {
  484. return false;
  485. }
  486. return array_keys($array) !== range(0, count($array) - 1);
  487. }
  488. /**
  489. * Нормализует значение поля: преобразует NULL в 0 для числовых полей или в пустую строку для строковых
  490. *
  491. * @param string $key Имя поля
  492. * @param mixed $value Значение поля
  493. * @return mixed Нормализованное значение
  494. */
  495. function normalize_field_value($key, $value) {
  496. if ($value === null or $value === 'NULL') {
  497. if (isset($numericFieldsSet[$key])) {
  498. return 0;
  499. } else {
  500. return '';
  501. }
  502. }
  503. return $value;
  504. }
  505. /**
  506. * Нормализует всю запись (ассоциативный массив)
  507. *
  508. * @param array $record Запись из БД
  509. * @return array Нормализованная запись
  510. */
  511. function normalize_record($record) {
  512. if (!is_array($record) || empty($record)) {
  513. return $record;
  514. }
  515. $normalized = [];
  516. foreach ($record as $key => $value) {
  517. $normalized[$key] = normalize_field_value($key, $value);
  518. }
  519. return $normalized;
  520. }
  521. /**
  522. * Нормализует массив записей
  523. *
  524. * @param array $records Массив записей из БД
  525. * @return array Нормализованные записи
  526. */
  527. function normalize_records($records) {
  528. if (!is_array($records) || empty($records)) {
  529. return $records;
  530. }
  531. $normalized = [];
  532. foreach ($records as $index => $record) {
  533. $normalized[$index] = normalize_record($record);
  534. }
  535. return $normalized;
  536. }
  537. /**
  538. * Выполняет SQL-запрос с поддержкой параметров.
  539. *
  540. * @param PDO $db
  541. * @param string $query
  542. * @param array $params (опционально)
  543. * @return mixed
  544. */
  545. function run_sql($db, $query, $params = [])
  546. {
  547. // Определяем тип запроса и таблицу для проверки прав
  548. $table_name = null;
  549. $operation = null;
  550. if (preg_match('/^\s*UPDATE\s+([a-zA-Z_][a-zA-Z0-9_]*)/i', $query, $matches)) {
  551. $table_name = $matches[1];
  552. $operation = 'update';
  553. } elseif (preg_match('/^\s*DELETE\s+FROM\s+([a-zA-Z_][a-zA-Z0-9_]*)/i', $query, $matches)) {
  554. $table_name = $matches[1];
  555. $operation = 'del';
  556. } elseif (preg_match('/^\s*INSERT\s+INTO\s+([a-zA-Z_][a-zA-Z0-9_]*)/i', $query, $matches)) {
  557. $table_name = $matches[1];
  558. $operation = 'add';
  559. }
  560. // Проверка прав доступа
  561. if ($table_name && $operation && !allow_update($db, $table_name, $operation)) {
  562. LOG_DEBUG($db, "Access denied: $query");
  563. return false;
  564. }
  565. try {
  566. $stmt = $db->prepare($query);
  567. $success = $stmt->execute($params);
  568. if (!$success) {
  569. LOG_ERROR($db, "Query execution failed: $query | params: " . json_encode($params));
  570. return false;
  571. }
  572. // Возвращаем результат в зависимости от типа запроса
  573. if (preg_match('/^\s*SELECT/i', $query)) {
  574. return $stmt; // PDOStatement для последующего fetch
  575. } elseif (preg_match('/^\s*INSERT/i', $query)) {
  576. return $db->lastInsertId();
  577. } elseif (preg_match('/^\s*(UPDATE|DELETE)/i', $query)) {
  578. return $stmt->rowCount();
  579. }
  580. return $stmt;
  581. } catch (PDOException $e) {
  582. LOG_ERROR($db, "SQL error: $query | params: " . json_encode($params) . " | " . $e->getMessage());
  583. return false;
  584. }
  585. }
  586. function get_count_records($db, $table, $filter, $filter_params = [])
  587. {
  588. // Валидация имени таблицы (защита от SQL-инъекций)
  589. if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $table)) {
  590. return 0;
  591. }
  592. $sql = "SELECT COUNT(*) AS cnt FROM $table";
  593. if (!empty($filter)) {
  594. $sql .= " WHERE $filter";
  595. }
  596. $result = get_record_sql($db, $sql, $filter_params);
  597. return !empty($result['cnt']) ? (int)$result['cnt'] : 0;
  598. }
  599. /**
  600. * Получить одну запись из таблицы по фильтру
  601. */
  602. function get_record($db, $table, $filter, $filter_params = [])
  603. {
  604. if (empty($table) || empty($filter)) {
  605. return null;
  606. }
  607. // Валидация имени таблицы
  608. if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $table)) {
  609. LOG_ERROR($db, "Invalid table name: $table");
  610. return null;
  611. }
  612. if (preg_match('/=$/', trim($filter))) {
  613. LOG_ERROR($db, "Search record ($table) with illegal filter '$filter'! Skip command.");
  614. return null;
  615. }
  616. $sql = "SELECT * FROM $table WHERE $filter";
  617. return get_record_sql($db, $sql, $filter_params);
  618. }
  619. /**
  620. * Получить несколько записей из таблицы по фильтру
  621. */
  622. function get_records($db, $table, $filter = '', $filter_params = [])
  623. {
  624. if (empty($table)) {
  625. return [];
  626. }
  627. // Валидация имени таблицы
  628. if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $table)) {
  629. LOG_ERROR($db, "Invalid table name: $table");
  630. return [];
  631. }
  632. if (!empty($filter)) {
  633. if (preg_match('/=$/', trim($filter))) {
  634. LOG_ERROR($db, "Search records ($table) with illegal filter '$filter'! Skip command.");
  635. return [];
  636. }
  637. $filter = "WHERE $filter";
  638. }
  639. $sql = "SELECT * FROM $table $filter";
  640. return get_records_sql($db, $sql, $filter_params);
  641. }
  642. /**
  643. * Получить одну запись по произвольному SQL-запросу
  644. *
  645. * @param PDO $db
  646. * @param string $sql
  647. * @param array|null $params
  648. * @return array|null
  649. */
  650. function get_record_sql($db, $sql, $params = []) {
  651. if (empty($sql)) {
  652. return null;
  653. }
  654. // Добавляем LIMIT 1, если его нет (только если нет параметризованных запросов!)
  655. // Важно: не трогаем запрос, если он уже содержит LIMIT с placeholder'ом
  656. if (!preg_match('/\bLIMIT\s+(\?|\d+)/i', $sql) && !preg_match('/\bLIMIT\s+\d+\s*(?:OFFSET\s+\d+)?\s*$/i', $sql)) {
  657. $sql .= " LIMIT 1";
  658. }
  659. $result = get_records_sql($db, $sql, $params);
  660. return !empty($result) ? $result[0] : null;
  661. }
  662. /**
  663. * Получить несколько записей по произвольному SQL-запросу
  664. *
  665. * @param PDO $db
  666. * @param string $sql
  667. * @param array|null $params
  668. * @return array
  669. */
  670. function get_records_sql($db, $sql, $params = [])
  671. {
  672. if (empty($sql)) {
  673. return [];
  674. }
  675. // Приводим $params к массиву
  676. $params = $params ?: [];
  677. // Логируем в DEBUG
  678. // LOG_DEBUG($db, "SQL: $sql | params: " . json_encode($params, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
  679. try {
  680. $stmt = $db->prepare($sql);
  681. $stmt->execute($params);
  682. $records = $stmt->fetchAll(PDO::FETCH_ASSOC);
  683. if (!empty($records)) {
  684. // return normalize_records($records);
  685. return $records;
  686. }
  687. return [];
  688. } catch (PDOException $e) {
  689. // Логируем ошибку с параметрами
  690. LOG_ERROR($db, "SQL error: $sql | params: " . json_encode($params, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . " | " . $e->getMessage());
  691. return [];
  692. }
  693. }
  694. /**
  695. * Получить одно значение поля по SQL-запросу
  696. */
  697. function get_single_field($db, $sql, $params = []) {
  698. $record = get_record_sql($db, $sql, $params);
  699. if (!empty($record) && is_array($record)) {
  700. return reset($record) ?: 0;
  701. }
  702. return 0;
  703. }
  704. /**
  705. * Получить ID записи из таблицы по фильтру
  706. */
  707. function get_id_record($db, $table, $filter, $params=[]) {
  708. if (empty($filter)) {
  709. return 0;
  710. }
  711. $record = get_record($db, $table, $filter, $params);
  712. return !empty($record['id']) ? $record['id'] : 0;
  713. }
  714. function set_changed($db, $id)
  715. {
  716. $auth['changed'] = 1;
  717. update_record($db, "user_auth", "id=?", $auth, [$id]);
  718. }
  719. function allow_update($db, $table, $action = 'update', $field = '')
  720. {
  721. // 1. Таблицы с полным доступом (регистронезависимо, но без regex)
  722. static $full_access_tables = [
  723. 'variables' => true,
  724. 'dns_cache' => true,
  725. 'worklog' => true,
  726. 'sessions' => true
  727. ];
  728. if (isset($full_access_tables[strtolower($table)])) {
  729. return 1;
  730. }
  731. // 2. Получение данных сессии (единая точка)
  732. // Получаем текущий IP
  733. $currentIp = null;
  734. if (!empty($_SESSION['ip'])) {
  735. $currentIp = filter_var($_SESSION['ip'], FILTER_VALIDATE_IP);
  736. }
  737. if (!$currentIp && function_exists('get_client_ip')) {
  738. $currentIp = filter_var(get_client_ip(), FILTER_VALIDATE_IP);
  739. }
  740. $currentIp = $currentIp ?: '127.0.0.1';
  741. // Получаем текущий логин
  742. $currentLogin = null;
  743. if (!empty($_SESSION['login'])) {
  744. $currentLogin = $_SESSION['login'];
  745. }
  746. if (!$currentLogin) {
  747. $currentLogin = getParam('login', null, null) ?: getParam('api_login', null, null);
  748. }
  749. $currentLogin = htmlspecialchars($currentLogin ?: 'http', ENT_QUOTES, 'UTF-8');
  750. // Получаем user_id
  751. $user_id = $_SESSION['user_id'] ?? null;
  752. // Получаем права
  753. $acl = $_SESSION['acl'] ?? null;
  754. if (empty($user_id) || empty($acl)) {
  755. $user_record = get_record_sql($db, "SELECT * FROM customers WHERE login=?", [ $currentLogin ]);
  756. if (!empty($user_record)) {
  757. $user_id = $user_record['id'];
  758. $acl = $user_record['rights'];
  759. }
  760. }
  761. // Проверка аутентификации
  762. if (!$currentLogin || !$user_id || !$acl) {
  763. return 0;
  764. }
  765. // Приведение ACL к целому числу
  766. $user_level = (int)$acl;
  767. // 3. Права по уровням
  768. if ($user_level === 1) { // Администратор
  769. return 1;
  770. }
  771. if ($user_level === 3) { // ViewOnly
  772. return 0;
  773. }
  774. // 4. Таблицы с полным доступом для оператора
  775. static $operator_tables = [
  776. 'dns_queue' => true,
  777. 'user_auth_alias' => true
  778. ];
  779. if (isset($operator_tables[strtolower($table)])) {
  780. return 1;
  781. }
  782. // 5. Проверка полей для оператора (только при update)
  783. if ($action === 'update') {
  784. static $operator_acl = [
  785. 'user_auth' => [
  786. 'description' => true,
  787. 'dns_name' => true,
  788. 'dns_ptr_only' => true,
  789. 'firmware' => true,
  790. 'link_check' => true,
  791. 'nagios' => true,
  792. 'nagios_handler' => true,
  793. 'wikiname' => true
  794. ],
  795. 'user_list' => [
  796. 'description' => true,
  797. 'login' => true
  798. ]
  799. ];
  800. // Проверка существования таблицы в ACL
  801. if (!isset($operator_acl[$table])) {
  802. return 0;
  803. }
  804. // Если поле не указано — разрешаем (полный доступ к таблице)
  805. if ($field === '') {
  806. return 1;
  807. }
  808. // Проверка прав на конкретное поле
  809. return $operator_acl[$table][$field] ?? 0;
  810. }
  811. return 0;
  812. }
  813. function update_record($db, $table, $filter, $newvalue, $filter_params = [])
  814. {
  815. if (!isset($table) || trim($table) === '') {
  816. return;
  817. }
  818. if (!isset($filter) || trim($filter) === '') {
  819. return;
  820. }
  821. if (preg_match('/=$/', trim($filter))) {
  822. LOG_WARNING($db, "Change record ($table) with illegal filter $filter! Skip command.");
  823. return;
  824. }
  825. if (!isset($newvalue) || !is_array($newvalue)) {
  826. return;
  827. }
  828. if (!allow_update($db, $table, 'update')) {
  829. LOG_INFO($db, "Access denied: $table [ $filter ]");
  830. return 1;
  831. }
  832. $old_record = get_record_sql($db,"SELECT * FROM $table WHERE $filter",$filter_params);
  833. if (empty($old_record)) { return; }
  834. $rec_id = $old_record['id'];
  835. $set_parts = [];
  836. $params = [];
  837. $network_changed = 0;
  838. $dhcp_changed = 0;
  839. $dns_changed = 0;
  840. $acl_fields = [
  841. 'ip' => '1',
  842. 'ip_int' => '1',
  843. 'enabled' => '1',
  844. 'dhcp' => '1',
  845. 'filter_group_id' => '1',
  846. 'deleted' => '1',
  847. 'dhcp_acl' => '1',
  848. 'queue_id' => '1',
  849. 'mac' => '1',
  850. 'blocked' => '1',
  851. ];
  852. $dhcp_fields = [
  853. 'ip' => '1',
  854. 'dhcp' => '1',
  855. 'deleted' => '1',
  856. 'dhcp_option_set' =>'1',
  857. 'dhcp_acl' => '1',
  858. 'mac' => '1',
  859. ];
  860. $dns_fields = [
  861. 'ip' => '1',
  862. 'dns_name' => '1',
  863. 'dns_ptr_only' => '1',
  864. 'alias' => '1',
  865. ];
  866. $valid_record=[];
  867. foreach ($newvalue as $key => $value) {
  868. if (!allow_update($db, $table, 'update', $key)) {
  869. continue;
  870. }
  871. if (!isset($value)) {
  872. $value = '';
  873. }
  874. $value = trim($value);
  875. if (isset($old_record[$key]) && strcmp($old_record[$key], $value) == 0) {
  876. continue;
  877. }
  878. if ($table === "user_auth") {
  879. if (!empty($acl_fields["$key"])) {
  880. $network_changed = 1;
  881. }
  882. if (!empty($dhcp_fields["$key"])) {
  883. $dhcp_changed = 1;
  884. }
  885. if (!empty($dns_fields["$key"])) {
  886. $dns_changed = 1;
  887. }
  888. }
  889. if ($table === "user_auth_alias") {
  890. if (!empty($dns_fields["$key"])) {
  891. $dns_changed = 1;
  892. }
  893. }
  894. $set_parts[] = "$key = ?";
  895. $params[] = $value;
  896. $valid_record[$key] = $value;
  897. }
  898. $changed_msg = prepareAuditMessage($db, $table, $old_record, $valid_record, $rec_id, 'update');
  899. // Если изменялась запись в таблице user_auth и поле dns_name было обновлено
  900. if ($table === "user_auth" && $dns_changed) {
  901. // --- УДАЛЕНИЕ СТАРЫХ DNS-ЗАПИСЕЙ (если они существовали) ---
  902. // Удаляем A-запись, если:
  903. // - у старой записи был указан dns_name и IP,
  904. // - запись не была только PTR (т.е. dns_ptr_only = 0),
  905. // - имя не заканчивается на точку (не FQDN в готовом виде)
  906. if (!empty($old_record['dns_name']) && !empty($old_record['ip']) && !$old_record['dns_ptr_only'] && !preg_match('/\.$/', $old_record['dns_name'])) {
  907. $del_dns['name_type'] = 'A';
  908. $del_dns['name'] = $old_record['dns_name'];
  909. $del_dns['value'] = $old_record['ip'];
  910. $del_dns['operation_type'] = 'del';
  911. if (!empty($rec_id)) { $del_dns['auth_id'] = $rec_id; }
  912. insert_record($db, 'dns_queue', $del_dns);
  913. }
  914. // Удаляем PTR-запись, если:
  915. // - у старой записи был указан dns_name и IP,
  916. // - запись была ТОЛЬКО PTR (dns_ptr_only = 1),
  917. // - имя не заканчивается на точку
  918. if (!empty($old_record['dns_name']) && !empty($old_record['ip']) && $old_record['dns_ptr_only'] && !preg_match('/\.$/', $old_record['dns_name'])) {
  919. $del_dns['name_type'] = 'PTR';
  920. $del_dns['name'] = $old_record['dns_name'];
  921. $del_dns['value'] = $old_record['ip'];
  922. $del_dns['operation_type'] = 'del';
  923. if (!empty($rec_id)) { $del_dns['auth_id'] = $rec_id; }
  924. insert_record($db, 'dns_queue', $del_dns);
  925. }
  926. // --- ДОБАВЛЕНИЕ НОВЫХ DNS-ЗАПИСЕЙ (если они заданы в обновлённой записи) ---
  927. // Формируем полную новую запись: берём значения из $valid_record, если они есть,
  928. // иначе — используем старые значения из $old_record
  929. $full_new_record = array_merge($old_record, $valid_record);
  930. // Добавляем A-запись, если:
  931. // - указаны dns_name и IP,
  932. // - запись НЕ только PTR (dns_ptr_only = 0),
  933. // - имя не заканчивается на точку
  934. if (!empty($full_new_record['dns_name']) && !empty($full_new_record['ip']) && empty($full_new_record['dns_ptr_only']) && !preg_match('/\.$/', $full_new_record['dns_name'])) {
  935. $new_dns = [
  936. 'name_type' => 'A',
  937. 'name' => $full_new_record['dns_name'],
  938. 'value' => $full_new_record['ip'],
  939. 'operation_type' => 'add'
  940. ];
  941. if (!empty($rec_id)) { $new_dns['auth_id'] = $rec_id; }
  942. // error_log("DNS ADD: A record for " . $full_new_record['dns_name']);
  943. insert_record($db, 'dns_queue', $new_dns);
  944. }
  945. // Добавляем PTR-запись, если:
  946. // - указаны dns_name и IP,
  947. // - запись помечена как ТОЛЬКО PTR (dns_ptr_only = 1),
  948. // - имя не заканчивается на точку
  949. if (!empty($full_new_record['dns_name']) && !empty($full_new_record['ip']) && !empty($full_new_record['dns_ptr_only']) && !preg_match('/\.$/', $full_new_record['dns_name'])) {
  950. $new_dns = [
  951. 'name_type' => 'PTR',
  952. 'name' => $full_new_record['dns_name'],
  953. 'value' => $full_new_record['ip'],
  954. 'operation_type' => 'add'
  955. ];
  956. if (!empty($rec_id)) {
  957. $new_dns['auth_id'] = $rec_id;
  958. }
  959. // error_log("DNS ADD: PTR record for " . $full_new_record['dns_name']);
  960. insert_record($db, 'dns_queue', $new_dns);
  961. }
  962. }
  963. // Если изменялась запись в таблице user_auth_alias и поле alias (DNS-псевдоним) было обновлено
  964. if ($table === "user_auth_alias" && $dns_changed) {
  965. // Определяем auth_id: берём из старой записи (при удалении/обновлении),
  966. // так как новая запись может не содержать его (например, при INSERT — old_record пуст)
  967. $auth_id = null;
  968. if (!empty($old_record['auth_id'])) { $auth_id = $old_record['auth_id']; }
  969. // --- УДАЛЕНИЕ СТАРОГО CNAME (если он существовал) ---
  970. // Удаляем CNAME-запись, если:
  971. // - у старой записи был указан alias,
  972. // - имя не заканчивается на точку (не является готовым FQDN)
  973. if (!empty($old_record['alias']) && !preg_match('/\.$/', $old_record['alias'])) {
  974. $del_dns['name_type'] = 'CNAME';
  975. $del_dns['name'] = $old_record['alias'];
  976. $del_dns['operation_type'] = 'del';
  977. // Привязываем к основной записи DNS через auth_id
  978. if (!empty($auth_id)) {
  979. $del_dns['auth_id'] = $auth_id;
  980. // Получаем целевое DNS-имя (A-запись), на которое должен указывать CNAME
  981. $del_dns['value'] = get_dns_name($db, $auth_id);
  982. }
  983. insert_record($db, 'dns_queue', $del_dns);
  984. }
  985. // --- ДОБАВЛЕНИЕ НОВОГО CNAME (если он задан) ---
  986. // Добавляем CNAME-запись, если:
  987. // - в новой записи указан alias,
  988. // - имя не заканчивается на точку
  989. if (!empty($valid_record['alias']) && !preg_match('/\.$/', $valid_record['alias'])) {
  990. $new_dns['name_type'] = 'CNAME';
  991. $new_dns['name'] = $valid_record['alias'];
  992. $new_dns['operation_type'] = 'add';
  993. // Привязываем к той же основной записи (auth_id из старой записи — актуален и для новой)
  994. if (!empty($auth_id)) {
  995. $new_dns['auth_id'] = $auth_id;
  996. // Целевое DNS-имя (A-запись) остаётся тем же
  997. $new_dns['value'] = get_dns_name($db, $auth_id);
  998. }
  999. insert_record($db, 'dns_queue', $new_dns);
  1000. }
  1001. }
  1002. if (empty($set_parts)) {
  1003. return 1;
  1004. }
  1005. if ($network_changed) {
  1006. $set_parts[] = "changed = 1";
  1007. }
  1008. if ($dhcp_changed) {
  1009. $set_parts[] = "dhcp_changed = 1";
  1010. }
  1011. $run_sql = implode(", ", $set_parts);
  1012. if ($table === 'user_auth') {
  1013. $changed_time = GetNowTimeString();
  1014. $run_sql .= ", changed_time = ?";
  1015. $params[] = $changed_time;
  1016. }
  1017. $new_sql = "UPDATE $table SET $run_sql WHERE $filter";
  1018. $all_params = array_merge($params, $filter_params);
  1019. LOG_DEBUG($db, "Run sql: $new_sql | params: " . json_encode($all_params, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
  1020. try {
  1021. $stmt = $db->prepare($new_sql);
  1022. $sql_result = $stmt->execute($all_params);
  1023. if (!$sql_result) {
  1024. LOG_ERROR($db, "UPDATE Request: $new_sql | params: " . json_encode($all_params, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
  1025. return;
  1026. }
  1027. if (!preg_match('/session/i', $table)) {
  1028. if (!empty($changed_msg)) {
  1029. if (!preg_match('/user/i', $table)) {
  1030. LOG_INFO($db, $changed_msg);
  1031. } else {
  1032. if ($table == 'user_auth' && !empty($old_record['ip'])) {
  1033. if (is_hotspot($db, $old_record['ip'])) {
  1034. LOG_INFO($db, $changed_msg, $rec_id);
  1035. } else {
  1036. LOG_WARNING($db, $changed_msg, $rec_id);
  1037. $send_alert_update = isNotifyUpdate(get_notify_subnet($db, $old_record['ip']));
  1038. if ($send_alert_update) { email(L_WARNING,$changed_msg); }
  1039. }
  1040. } else {
  1041. LOG_WARNING($db, $changed_msg);
  1042. }
  1043. }
  1044. }
  1045. }
  1046. return $sql_result;
  1047. } catch (PDOException $e) {
  1048. LOG_ERROR($db, "SQL: $new_sql | params: " . json_encode($all_params, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . " | error: " . $e->getMessage());
  1049. return;
  1050. }
  1051. }
  1052. function delete_records($db, $table, $filter, $filter_params = [])
  1053. {
  1054. // Сначала получаем ID записей, подходящих под фильтр
  1055. $records = get_records_sql($db, "SELECT id FROM $table WHERE $filter", $filter_params);
  1056. if (empty($records)) {
  1057. return true; // ничего не найдено — успех
  1058. }
  1059. // Удаляем каждую запись через уже существующую функцию delete_record
  1060. foreach ($records as $record) {
  1061. // Формируем фильтр по id и вызываем delete_record
  1062. delete_record($db, $table, "id = ?", [$record['id']]);
  1063. }
  1064. return true;
  1065. }
  1066. function update_records($db, $table, $filter, $newvalue, $filter_params = [])
  1067. {
  1068. // Получаем ID всех записей, подходящих под фильтр
  1069. $records = get_records_sql($db, "SELECT id FROM $table WHERE $filter", $filter_params);
  1070. if (empty($records)) {
  1071. return true; // ничего не найдено — считаем успехом
  1072. }
  1073. // Обновляем каждую запись по отдельности через уже существующую логику
  1074. foreach ($records as $record) {
  1075. update_record($db, $table, "id = ?", $newvalue, [$record['id']]);
  1076. }
  1077. return true;
  1078. }
  1079. function delete_record($db, $table, $filter, $filter_params = [])
  1080. {
  1081. if (!allow_update($db, $table, 'del')) {
  1082. return;
  1083. }
  1084. if (!isset($table)) {
  1085. return;
  1086. }
  1087. if (!isset($filter)) {
  1088. LOG_WARNING($db, "Delete FROM table $table with empty filter! Skip command.");
  1089. return;
  1090. }
  1091. if (preg_match('/=$/', $filter)) {
  1092. LOG_WARNING($db, "Change record ($table) with illegal filter $filter! Skip command.");
  1093. return;
  1094. }
  1095. $old_record = get_record_sql($db,"SELECT * FROM $table WHERE $filter",$filter_params);
  1096. if (empty($old_record)) { return; }
  1097. $rec_id = $old_record['id'];
  1098. //never delete permanent user
  1099. if ($table === 'user_list' and $old_record['permanent']) { return; }
  1100. $changed_msg = prepareAuditMessage($db, $table, $old_record, [], $rec_id, 'delete');
  1101. $delete_it = 1;
  1102. //never delete user ip record
  1103. if ($table === 'user_auth') {
  1104. $delete_it = 0;
  1105. update_record($db, $table, $filter, [ 'deleted'=>1, 'changed'=>1 ], $filter_params);
  1106. //dns - A-record
  1107. if (!empty($old_record['dns_name']) and !empty($old_record['ip']) and !$old_record['dns_ptr_only'] and !preg_match('/\.$/', $old_record['dns_name'])) {
  1108. $del_dns['name_type'] = 'A';
  1109. $del_dns['name'] = $old_record['dns_name'];
  1110. $del_dns['value'] = $old_record['ip'];
  1111. $del_dns['operation_type'] = 'del';
  1112. if (!empty($rec_id)) {
  1113. $del_dns['auth_id'] = $rec_id;
  1114. }
  1115. insert_record($db, 'dns_queue', $del_dns);
  1116. }
  1117. //ptr
  1118. if (!empty($old_record['dns_name']) and !empty($old_record['ip']) and $old_record['dns_ptr_only'] and !preg_match('/\.$/', $old_record['dns_name'])) {
  1119. $del_dns['name_type'] = 'PTR';
  1120. $del_dns['name'] = $old_record['dns_name'];
  1121. $del_dns['value'] = $old_record['ip'];
  1122. $del_dns['operation_type'] = 'del';
  1123. if (!empty($rec_id)) {
  1124. $del_dns['auth_id'] = $rec_id;
  1125. }
  1126. insert_record($db, 'dns_queue', $del_dns);
  1127. }
  1128. if (!empty($old_record['ip'])) {
  1129. if (is_hotspot($db, $old_record['ip'])) {
  1130. LOG_INFO($db, $changed_msg, $rec_id);
  1131. } else {
  1132. LOG_WARNING($db, $changed_msg, $rec_id);
  1133. $send_alert_delete = isNotifyDelete(get_notify_subnet($db, $old_record['ip']));
  1134. if ($send_alert_delete) { email(L_WARNING,$changed_msg); }
  1135. }
  1136. } else {
  1137. LOG_WARNING($db, $changed_msg, $rec_id);
  1138. }
  1139. return $old_record;
  1140. }
  1141. //remove aliases
  1142. if ($table === 'user_auth_alias') {
  1143. //dns
  1144. if (!empty($old_record['alias']) and !preg_match('/\.$/', $old_record['alias'])) {
  1145. $del_dns['name_type'] = 'CNAME';
  1146. $del_dns['name'] = $old_record['alias'];
  1147. $del_dns['value'] = '';
  1148. $del_dns['operation_type'] = 'del';
  1149. if (!empty($old_record['auth_id'])) {
  1150. $del_dns['auth_id'] = $old_record['auth_id'];
  1151. $del_dns['value'] = get_dns_name($db, $old_record['auth_id']);
  1152. }
  1153. insert_record($db, 'dns_queue', $del_dns);
  1154. }
  1155. }
  1156. if ($delete_it) {
  1157. $new_sql = "DELETE FROM $table WHERE $filter";
  1158. LOG_DEBUG($db, "Run sql: $new_sql | params: " . json_encode($filter_params, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
  1159. try {
  1160. $stmt = $db->prepare($new_sql);
  1161. $sql_result = $stmt->execute($filter_params);
  1162. if ($sql_result === false) {
  1163. LOG_ERROR($db, "DELETE Request: $new_sql | params: " . json_encode($filter_params));
  1164. return;
  1165. }
  1166. } catch (PDOException $e) {
  1167. LOG_ERROR($db, "SQL: $new_sql | params: " . json_encode($filter_params) . " : " . $e->getMessage());
  1168. return;
  1169. }
  1170. } else { return; }
  1171. if (!preg_match('/session/i', $table)) {
  1172. if (!empty($changed_msg)) {
  1173. if (!preg_match('/user/i', $table)) {
  1174. LOG_INFO($db, $changed_msg);
  1175. } else {
  1176. LOG_WARNING($db, $changed_msg);
  1177. }
  1178. }
  1179. }
  1180. return $old_record;
  1181. }
  1182. function insert_record($db, $table, $newvalue)
  1183. {
  1184. // Проверка прав на запись
  1185. if (!allow_update($db, $table, 'add')) {
  1186. LOG_DEBUG($db, "User does not have write permission for table '$table'");
  1187. return false;
  1188. }
  1189. // Проверка имени таблицы
  1190. if (!isset($table) || empty($table)) {
  1191. LOG_WARNING($db, "Create record for unknown/empty table! Skip command.");
  1192. return false;
  1193. }
  1194. // Проверка данных
  1195. if (empty($newvalue) || !is_array($newvalue)) {
  1196. LOG_WARNING($db, "Create record for table '$table' with empty or non-array data! Skip command.");
  1197. return false;
  1198. }
  1199. $field_list = [];
  1200. $value_list = [];
  1201. $params = [];
  1202. // Специальная обработка для user_auth
  1203. if ($table === 'user_auth') {
  1204. $newvalue['changed'] = 1;
  1205. if (!empty($newvalue['ou_id']) && !is_system_ou($db, $newvalue['ou_id'])) {
  1206. $newvalue['dhcp_changed'] = 1;
  1207. }
  1208. }
  1209. // Формирование списков полей и параметров
  1210. foreach ($newvalue as $key => $value) {
  1211. // Защита от пустых ключей
  1212. if (empty($key)) {
  1213. LOG_WARNING($db, "Skipping empty field key in table '$table'");
  1214. continue;
  1215. }
  1216. $field_list[] = $key;
  1217. $value_list[] = '?';
  1218. $params[] = $value;
  1219. }
  1220. // Проверка, что есть хотя бы одно поле для вставки
  1221. if (empty($field_list)) {
  1222. LOG_WARNING($db, "No valid fields to insert for table '$table' after processing");
  1223. return false;
  1224. }
  1225. // Формируем SQL
  1226. $field_list_str = implode(',', $field_list);
  1227. $value_list_str = implode(',', $value_list);
  1228. $new_sql = "INSERT INTO $table ($field_list_str) VALUES ($value_list_str)";
  1229. LOG_DEBUG($db, "Run sql: $new_sql | params: " . json_encode($params, JSON_UNESCAPED_UNICODE));
  1230. try {
  1231. $stmt = $db->prepare($new_sql);
  1232. if (!$stmt) {
  1233. $error_info = $db->errorInfo();
  1234. LOG_ERROR($db, "Failed to prepare INSERT statement for table '$table': " . json_encode($error_info));
  1235. return false;
  1236. }
  1237. $sql_result = $stmt->execute($params);
  1238. if (!$sql_result) {
  1239. $error_info = $stmt->errorInfo();
  1240. LOG_ERROR($db, "INSERT failed for table '$table': SQL: $new_sql | Params: " . json_encode($params) . " | Error: " . json_encode($error_info));
  1241. return false;
  1242. }
  1243. $last_id = $db->lastInsertId();
  1244. if (!$last_id) {
  1245. LOG_WARNING($db, "INSERT succeeded but lastInsertId() returned empty for table '$table'");
  1246. }
  1247. // Логирование аудита
  1248. if (!preg_match('/session/i', $table)) {
  1249. $changed_msg = prepareAuditMessage($db, $table, [], $newvalue, $last_id, 'insert');
  1250. if (!empty($changed_msg)) {
  1251. if (!preg_match('/user/i', $table)) {
  1252. LOG_INFO($db, $changed_msg);
  1253. } else {
  1254. if ($table == 'user_auth' && !empty($newvalue['ip'])) {
  1255. if (is_hotspot($db, $newvalue['ip'])) {
  1256. LOG_INFO($db, $changed_msg, $last_id);
  1257. } else {
  1258. LOG_WARNING($db, $changed_msg, $last_id);
  1259. $send_alert_create = isNotifyCreate(get_notify_subnet($db, $newvalue['ip']));
  1260. if ($send_alert_create) {
  1261. email(L_WARNING, $changed_msg);
  1262. }
  1263. }
  1264. } else {
  1265. LOG_WARNING($db, $changed_msg);
  1266. }
  1267. }
  1268. }
  1269. }
  1270. // Обработка DNS для user_auth_alias
  1271. if ($table === 'user_auth_alias') {
  1272. if (!empty($newvalue['alias']) && !preg_match('/\.$/', $newvalue['alias'])) {
  1273. $add_dns['name_type'] = 'CNAME';
  1274. $add_dns['name'] = $newvalue['alias'];
  1275. $add_dns['value'] = get_dns_name($db, $newvalue['auth_id']);
  1276. $add_dns['operation_type'] = 'add';
  1277. $add_dns['auth_id'] = $newvalue['auth_id'];
  1278. LOG_DEBUG($db, "Queueing DNS CNAME record for alias: " . $newvalue['alias']);
  1279. insert_record($db, 'dns_queue', $add_dns);
  1280. }
  1281. }
  1282. // Обработка DNS для user_auth
  1283. if ($table === 'user_auth') {
  1284. // A-record
  1285. if (!empty($newvalue['dns_name']) && !empty($newvalue['ip']) && !$newvalue['dns_ptr_only'] && !preg_match('/\.$/', $newvalue['dns_name'])) {
  1286. $add_dns['name_type'] = 'A';
  1287. $add_dns['name'] = $newvalue['dns_name'];
  1288. $add_dns['value'] = $newvalue['ip'];
  1289. $add_dns['operation_type'] = 'add';
  1290. $add_dns['auth_id'] = $last_id;
  1291. LOG_DEBUG($db, "Queueing DNS A record: " . $newvalue['dns_name'] . " -> " . $newvalue['ip']);
  1292. insert_record($db, 'dns_queue', $add_dns);
  1293. }
  1294. // PTR record
  1295. if (!empty($newvalue['dns_name']) && !empty($newvalue['ip']) && $newvalue['dns_ptr_only'] && !preg_match('/\.$/', $newvalue['dns_name'])) {
  1296. $add_dns['name_type'] = 'PTR';
  1297. $add_dns['name'] = $newvalue['dns_name'];
  1298. $add_dns['value'] = $newvalue['ip'];
  1299. $add_dns['operation_type'] = 'add';
  1300. $add_dns['auth_id'] = $last_id;
  1301. LOG_DEBUG($db, "Queueing DNS PTR record: " . $newvalue['dns_name'] . " -> " . $newvalue['ip']);
  1302. insert_record($db, 'dns_queue', $add_dns);
  1303. }
  1304. }
  1305. LOG_VERBOSE($db, "Successfully inserted record into '$table'. ID: $last_id");
  1306. return $last_id;
  1307. } catch (PDOException $e) {
  1308. LOG_ERROR($db, "SQL exception during INSERT into '$table': SQL: $new_sql | Params: " . json_encode($params) . " | Exception: " . $e->getMessage());
  1309. return false;
  1310. } catch (Exception $e) {
  1311. LOG_ERROR($db, "Unexpected exception during INSERT into '$table': " . $e->getMessage());
  1312. return false;
  1313. }
  1314. }
  1315. function dump_record($db, $table, $filter, $params = [])
  1316. {
  1317. $result = '';
  1318. $old = get_record($db, $table, $filter, $params);
  1319. if (empty($old)) {
  1320. return $result;
  1321. }
  1322. $result = 'record: ' . hash_to_text($old);
  1323. return $result;
  1324. }
  1325. function get_diff_rec($db, $table, $filter, $newvalue, $only_changed = true, $filter_params = [])
  1326. {
  1327. if (empty($table) || empty($filter) || !is_array($newvalue)) {
  1328. return '';
  1329. }
  1330. // Валидация имени таблицы
  1331. if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $table)) {
  1332. return '';
  1333. }
  1334. $old_sql = "SELECT * FROM $table WHERE $filter";
  1335. $old_record = get_record_sql($db, $old_sql, $filter_params);
  1336. if (empty($old_record)) { return ''; }
  1337. $changed = [];
  1338. $unchanged = [];
  1339. foreach ($newvalue as $key => $new_val) {
  1340. // Пропускаем поля, отсутствующие в БД
  1341. if (!array_key_exists($key, $old_record)) {
  1342. continue;
  1343. }
  1344. $old_record_val = $old_record[$key];
  1345. // Приведение к строке с учётом NULL
  1346. $old_record_str = ($old_record_val === null) ? '' : (string)$old_record_val;
  1347. $new_str = ($new_val === null) ? '' : (string)$new_val;
  1348. if ($old_record_str !== $new_str) {
  1349. $changed[$key] = "$new_str [old: $old_record_str]";
  1350. } elseif (!$only_changed) {
  1351. $unchanged[$key] = $old_record_val;
  1352. }
  1353. }
  1354. if ($only_changed) {
  1355. return !empty($changed) ? hash_to_text($changed) : '';
  1356. }
  1357. if (!empty($changed)) {
  1358. $output = hash_to_text($changed);
  1359. } else {
  1360. $output = "";
  1361. }
  1362. if (!empty($unchanged)) {
  1363. $output .= "\r\nHas not changed:\r\n" . hash_to_text($unchanged);
  1364. }
  1365. return $output;
  1366. }
  1367. function delete_user_auth($db, $id) {
  1368. // remove aliases
  1369. delete_records($db, 'user_auth_alias', 'auth_id=?', [ $id ]);
  1370. // remove connections
  1371. delete_records($db, 'connections', 'auth_id=?', [ $id ]);
  1372. // remove user auth record
  1373. $changes = delete_record($db, "user_auth", "id=?", [ $id ]);
  1374. return $changes;
  1375. }
  1376. function delete_user($db,$id)
  1377. {
  1378. //remove user record
  1379. $changes = delete_record($db, "user_list", "id=?", [ $id ]);
  1380. //if fail - exit
  1381. if (!isset($changes) or empty($changes)) { return; }
  1382. //remove auth records
  1383. $t_user_auth = get_records($db,'user_auth',"user_id=$id");
  1384. if (!empty($t_user_auth)) {
  1385. foreach ( $t_user_auth as $row ) { delete_user_auth($db,$row['id']); }
  1386. }
  1387. //remove device
  1388. $device = get_record($db, "devices", "user_id='$id'");
  1389. if (!empty($device)) {
  1390. unbind_ports($db, $device['id']);
  1391. delete_records($db, "connections","device_id=?", [$device['id']]);
  1392. delete_records($db, "device_l3_interfaces","device_id=?", [$device['id']]);
  1393. delete_records($db, "device_ports","device_id=?", [$device['id']]);
  1394. delete_records($db, "device_filter_instances","device_id=?", [$device['id']]);
  1395. delete_records($db, "gateway_subnets","device_id=?",[$device['id']]);
  1396. delete_record($db, "devices", "id=?", [$device['id']]);
  1397. }
  1398. //remove auth assign rules
  1399. delete_records($db, "auth_rules","user_id=?",[ $id ]);
  1400. return $changes;
  1401. }
  1402. function delete_device($db,$id)
  1403. {
  1404. //remove user record
  1405. $changes = delete_record($db, "devices", "id=?", [$id]);
  1406. //if fail - exit
  1407. if (!isset($changes) or empty($changes)) {
  1408. LOG_INFO($db,"Device id: $id has not been deleted");
  1409. return;
  1410. }
  1411. unbind_ports($db, $id);
  1412. delete_records($db, "connections","device_id=?", [$id]);
  1413. delete_records($db, "device_l3_interfaces","device_id=?", [$id]);
  1414. delete_records($db, "device_ports","device_id=?", [$id]);
  1415. delete_records($db, "device_filter_instances","device_id=?", [$id]);
  1416. delete_records($db, "gateway_subnets","device_id=?",[$id]);
  1417. return $changes;
  1418. }
  1419. function record_to_txt($db, $table, $id) {
  1420. $record = get_record_sql($db, 'SELECT * FROM ' . $table . ' WHERE id =?', [ $id ]);
  1421. return hash_to_text($record);
  1422. }
  1423. if (!defined("DB_TYPE")) { define("DB_TYPE","mysql"); }
  1424. $db_link = new_connection(DB_TYPE, DB_HOST, DB_USER, DB_PASS, DB_NAME);
  1425. ?>