From 47deaba513b52bd4aef4b7dc36687c251a48cc7c Mon Sep 17 00:00:00 2001 From: johnnyq Date: Mon, 23 Nov 2026 00:57:43 -0500 Subject: [PATCH] Bring network platform sites' networks and VLANs into their clients' networks, matched by subnet and kept up detail by detail, with a platform card on the network page, with database 4.1.6 --- CHANGELOG.md | 5 +- admin/database_updates/4.1.6.php | 36 ++++ admin/post/rmm.php | 11 +- admin/rmm_clients.php | 14 +- agent/network.php | 23 ++ db.sql | 26 +++ functions.php | 1 + functions/client.php | 2 +- functions/network.php | 3 + functions/rmm.php | 15 +- functions/rmm_network.php | 346 +++++++++++++++++++++++++++++++ functions/rmm_unifi.php | 111 ++++++++-- 12 files changed, 572 insertions(+), 21 deletions(-) create mode 100644 admin/database_updates/4.1.6.php create mode 100644 functions/rmm_network.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 6a1fd6d75..2f28cdf12 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,7 @@ This file documents all notable changes made to ITFlow. ### Upgrading -Update from Maintenance > Update — Queue Update hands the job to cron, which updates the files and applies this release's four database changes (4.1.1 to 4.1.5) in the same pass. They add a column to RMM providers for the asset type each kind of device comes in as, three to rack items for devices side by side in a holder, the tables for phone systems, and two columns for network platforms, and change nothing that is there. Nothing else is required. +Update from Maintenance > Update — Queue Update hands the job to cron, which updates the files and applies this release's five database changes (4.1.1 to 4.1.6) in the same pass. They add a column to RMM providers for the asset type each kind of device comes in as, three to rack items for devices side by side in a holder, the tables for phone systems, and two columns and a table for network platforms and their networks, and change nothing that is there. Nothing else is required. ### New Features & Updates @@ -24,6 +24,7 @@ Update from Maintenance > Update — Queue Update hands the job to cron, which u - Phone Systems: Yealink and Polycom desk phones report themselves as they start up and register - the Setup window has the lines for each - and become Phone assets of their domain's client, named after their extension, with their make, model, firmware, IP and MAC address. A client's asset that already has the phone's MAC address is used instead. The asset keeps up with new firmware and IP addresses, except for fields changed in ITFlow, and has a card saying whether the phone is registered and its line. The Domains page counts each domain's phones. - Screen pops: pick your extension under My desk phone in Your account > Preferences, and calls on your desk phone pop up at the bottom right of every page as they ring - the contact and their client, or the caller's name and number, with their open tickets and New Ticket (Quick Ticket, with the client and contact picked). Answered, it counts your talk time; ended, Add to Ticket puts the call on a ticket once its record is in, with the ticket you made for it picked. It comes from the phones, through the same Setup lines. - Network Platforms: Admin > Network Platforms brings in your clients' UniFi gateways, switches and access points as assets - from a controller you host, signed in to with a local view-only admin; from a UniFi console, with an API key made in UniFi Network; or from every console on your UI account through UniFi's Site Manager, with nothing to open up on the clients' networks. Link each site to its client and its devices come in, matched to the assets you have by MAC address, serial number or name, with their model, firmware, IP and MAC address kept up to date. An asset shows whether the device is online, how long it has been up, its public IP and whether a firmware update is waiting. It uses the same sync as RMM Providers, and its devices don't count as managed devices on recurring invoices. The password or API key is kept encrypted with this install's own key. +- Network Platforms: a linked site's networks and VLANs come in as its client's networks - matched to the one with the same subnet, or made - with their name, type, VLAN, subnet, gateway, DNS servers and DHCP range. Each detail follows UniFi until you change it in ITFlow, and the network's page has a card for the platform. WAN connections, site-to-site VPNs and VLANs with no subnet stay out. A network deleted in ITFlow isn't made again until Bring back on its site's row. ### Bug Fixes @@ -65,6 +66,8 @@ Update from Maintenance > Update — Queue Update hands the job to cron, which u - `functions/rmm_unifi.php` has the three UniFi kinds: `unifi` signs in to a classic controller (`/api/login`, the `unifises` and `csrf_token` cookies) or a UniFi OS console (`/api/auth/login`, the `TOKEN` cookie and `X-CSRF-Token`, under `/proxy/network`), and signs in again once on a 401; `unifi_os` reads the Network Integration API (`X-API-KEY`, `/proxy/network/integration/v1` or `/integration/v1`, offset paging); `unifi_cloud` lists Site Manager's hosts and reads each console's integration API through `/v1/connector/consoles/{id}/proxy/network/integration/v1`, leaving out self-hosted controllers and naming the consoles it can't reach. `UNIFI_SITE_MANAGER_URL` can be defined in `config.php` to point it elsewhere for testing. A device's `remote_id` is its MAC address. - A kind with `seal` keeps `api_key` and `api_secret` as `enc1:` AES-256-GCM, keyed from `backupEncryptionKey()`; `rmmSecret($provider, $field)` reads them and `rmmSecretSeal()` writes them. `rmmHttp()` takes `insecure` and `cookies` options and returns the response headers and cookies. Kinds' `fields` can be `switch`, `text`, `url` or `secret` (with `spaces` for a password), and a kind can have `default_name`, `device_kinds` and `attention`. - `rmmAssetMatch()` matches by MAC address first, against `asset_interfaces` normalized by `rmmMac()`, then serial and name; `rmmAssetWrite()` writes `ip` and `mac` to the primary interface. `recurringSeatManagedSql(0)`, the managed-device seat options and `recurringSeatManagedLineCount()` count `rmm`-family providers only, and so does `rmmClientSummary()`. `rmmClientSuggestions()` also tries a site's name without a trailing `(console name)`. +- Database 4.1.6: `rmm_networks` - one network of a platform's site and the ITFlow network it is (0 once deleted there, so it isn't made again), with `rmm_network_synced` holding what the sync last wrote to each detail. Re-runnable. `functions/rmm_network.php` has `rmmNetworksSync()`, called by `rmmSync()` after each linked client's devices for a kind with a `networks` function, `rmmNetworkSave()` (match by `network` CIDR among the client's unarchived networks, or insert), `rmmNetworkFollow()` (the follow rule, with the two DNS columns kept together), `rmmNetworksForget()` (from `rmmForgetClientDevices()`), `rmmNetworksDeleted()` (from `networkDelete()`) and `rmmNetworksFor()` for the network page. A list with no networks marks none gone. +- `rmmUnifiNetworks($provider, $site)` reads a classic controller's `rest/networkconf` (purposes `corporate`, `guest` and `remote-user-vpn` with an `ip_subnet`) or the Network Integration API's `sites/{id}/networks` and each one's details (`GATEWAY` or `SWITCH` managed, with `ipv4Configuration`); a 404 on the list is a version without it, not an error. `rmmUnifiSiteWhere()` gives a Site Manager site's console and id. ## [26.12] diff --git a/admin/database_updates/4.1.6.php b/admin/database_updates/4.1.6.php new file mode 100644 index 000000000..fd6ece6ad --- /dev/null +++ b/admin/database_updates/4.1.6.php @@ -0,0 +1,36 @@ + 0"))[0]); mysqli_query($mysqli, "DELETE FROM rmm_devices WHERE rmm_device_provider_id = $provider_id"); + if (rmmNetworksReady()) { + mysqli_query($mysqli, "DELETE FROM rmm_networks WHERE rmm_network_provider_id = $provider_id"); + } if (rmmAlertsReady()) { mysqli_query($mysqli, "DELETE FROM rmm_alerts WHERE rmm_alert_provider_id = $provider_id"); } @@ -280,10 +283,16 @@ if (isset($_GET['rmm_bring_back'])) { $rmm_client_id = intval($rmm_client['rmm_client_id']); mysqli_query($mysqli, "DELETE FROM rmm_devices WHERE rmm_device_rmm_client_id = $rmm_client_id AND rmm_device_asset_id = 0"); $brought = mysqli_affected_rows($mysqli); + $brought_networks = 0; + if (rmmNetworksReady()) { + mysqli_query($mysqli, "DELETE FROM rmm_networks WHERE rmm_network_rmm_client_id = $rmm_client_id AND rmm_network_network_id = 0"); + $brought_networks = mysqli_affected_rows($mysqli); + } set_time_limit(180); $sync = rmmSync(rmmProviderRow($rmm_client['rmm_client_provider_id']), $rmm_client_id, 150); $words = rmmFamilyWords(rmmFamily($rmm_client)); - logAudit($words['audit'], "Edit", "$session_name brought back $brought deleted devices of " . escapeSql(rmmProviderName($rmm_client) . " {$words['client']} {$rmm_client['rmm_client_name']}"), intval($rmm_client['rmm_client_client_id']), intval($rmm_client['rmm_client_provider_id'])); + $brought_words = implode(' and ', array_filter([$brought || !$brought_networks ? "$brought deleted device" . ($brought === 1 ? '' : 's') : '', $brought_networks ? "$brought_networks deleted network" . ($brought_networks === 1 ? '' : 's') : ''])); + logAudit($words['audit'], "Edit", "$session_name brought back $brought_words of " . escapeSql(rmmProviderName($rmm_client) . " {$words['client']} {$rmm_client['rmm_client_name']}"), intval($rmm_client['rmm_client_client_id']), intval($rmm_client['rmm_client_provider_id'])); flashAlert('' . escapeHtml($rmm_client['rmm_client_name']) . ' - ' . escapeHtml($sync['note']), $sync['ok'] ? 'success' : 'warning'); redirect('rmm_clients.php?provider_id=' . intval($rmm_client['rmm_client_provider_id'])); diff --git a/admin/rmm_clients.php b/admin/rmm_clients.php index 5cacd5869..0d54e6368 100644 --- a/admin/rmm_clients.php +++ b/admin/rmm_clients.php @@ -67,7 +67,9 @@ if (!isset($sortable_columns[$sort])) { $sort = 'rmm_client_name'; } -$sql = mysqli_query($mysqli, "SELECT SQL_CALC_FOUND_ROWS rmm_clients.*, client_name, client_abbreviation, client_archived_at, +// A network platform's networks deleted in ITFlow are brought back with its devices +$networks_deleted_sql = rmmNetworksReady() ? "(SELECT COUNT(*) FROM rmm_networks WHERE rmm_network_rmm_client_id = rmm_clients.rmm_client_id AND rmm_network_removed_at IS NULL AND rmm_network_network_id = 0)" : '0'; +$sql = mysqli_query($mysqli, "SELECT SQL_CALC_FOUND_ROWS rmm_clients.*, client_name, client_abbreviation, client_archived_at, $networks_deleted_sql AS networks_deleted, (SELECT COUNT(*) FROM rmm_devices WHERE rmm_device_rmm_client_id = rmm_clients.rmm_client_id AND rmm_device_removed_at IS NULL AND rmm_device_asset_id > 0) AS assets_in, (SELECT COUNT(*) FROM rmm_devices WHERE rmm_device_rmm_client_id = rmm_clients.rmm_client_id AND rmm_device_removed_at IS NULL AND rmm_device_asset_id = 0) AS assets_deleted, (SELECT COUNT(*) FROM rmm_devices WHERE rmm_device_rmm_client_id = rmm_clients.rmm_client_id AND rmm_device_removed_at IS NULL AND rmm_device_status = 'overdue') AS devices_overdue @@ -191,6 +193,8 @@ $devices_in = intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT COUNT(*) FRO $suggested = $suggestions[$rmm_client_id] ?? 0; $sites = intval($row['rmm_client_sites']); $deleted = intval($row['assets_deleted']); + $networks_deleted = intval($row['networks_deleted']); + $deleted_words = implode(' and ', array_filter([$deleted ? "$deleted deleted device" . ($deleted === 1 ? '' : 's') : '', $networks_deleted ? "$networks_deleted deleted network" . ($networks_deleted === 1 ? '' : 's') : ''])); $overdue = intval($row['devices_overdue']); $link_url = "modals/rmm/rmm_client_link.php?id=$rmm_client_id"; ?> @@ -250,11 +254,11 @@ $devices_in = intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT COUNT(*) FRO - + - Bring back deleted + data-confirm-title="Bring back ?" data-confirm-button="Bring back" + data-confirm-text=""> + Bring back deleted diff --git a/agent/network.php b/agent/network.php index 500210ed5..567d50422 100644 --- a/agent/network.php +++ b/agent/network.php @@ -302,6 +302,29 @@ if (!$network || ($client_url && intval($network['network_client_id']) !== intva + +
+
+

+
+
+
+
Site
+
In
+
+ +

stopped listing it - it is kept here as it was.

+ +
Kept up from - a detail you change here stays as you set it. As said .
+ +
+
+ +

Notes

diff --git a/db.sql b/db.sql index bf9cd5c1a..bca21722c 100644 --- a/db.sql +++ b/db.sql @@ -3631,6 +3631,32 @@ CREATE TABLE `rmm_devices` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `rmm_networks` +-- + +DROP TABLE IF EXISTS `rmm_networks`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8mb4 */; +CREATE TABLE `rmm_networks` ( + `rmm_network_id` int(11) NOT NULL AUTO_INCREMENT, + `rmm_network_provider_id` int(11) NOT NULL, + `rmm_network_rmm_client_id` int(11) NOT NULL, + `rmm_network_remote_id` varchar(100) NOT NULL, + `rmm_network_client_id` int(11) NOT NULL DEFAULT 0, + `rmm_network_network_id` int(11) NOT NULL DEFAULT 0, + `rmm_network_name` varchar(200) NOT NULL DEFAULT '', + `rmm_network_synced` text DEFAULT NULL, + `rmm_network_synced_at` datetime DEFAULT NULL, + `rmm_network_removed_at` datetime DEFAULT NULL, + `rmm_network_created_at` datetime NOT NULL DEFAULT current_timestamp(), + PRIMARY KEY (`rmm_network_id`), + UNIQUE KEY `rmm_network_remote` (`rmm_network_provider_id`,`rmm_network_rmm_client_id`,`rmm_network_remote_id`), + KEY `rmm_network_network_id` (`rmm_network_network_id`), + KEY `rmm_network_client_id` (`rmm_network_client_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `rmm_providers` -- diff --git a/functions.php b/functions.php index f1ecd90bd..80ac7ddb8 100644 --- a/functions.php +++ b/functions.php @@ -128,6 +128,7 @@ require_once __DIR__ . '/functions/sms.php'; require_once __DIR__ . '/functions/rmm.php'; require_once __DIR__ . '/functions/rmm_tactical.php'; require_once __DIR__ . '/functions/rmm_unifi.php'; +require_once __DIR__ . '/functions/rmm_network.php'; require_once __DIR__ . '/functions/phone.php'; require_once __DIR__ . '/functions/client_onboarding.php'; require_once __DIR__ . '/functions/ticket_mention.php'; diff --git a/functions/client.php b/functions/client.php index 182a59e5b..756ba0480 100644 --- a/functions/client.php +++ b/functions/client.php @@ -79,7 +79,7 @@ function clientMergeTables() { ['portal_announcements', 'announcement_client_id'], ['sms_messages', 'sms_message_client_id'], ['kb_article_feedback', 'kb_article_feedback_client_id'], ['order_items', 'order_item_client_id'], ['po_items', 'po_item_client_id'], ['expense_import_rules', 'import_rule_client_id'], ['income_import_rules', 'import_rule_client_id'], - ['rmm_clients', 'rmm_client_client_id'], ['rmm_devices', 'rmm_device_client_id'], ['rmm_alerts', 'rmm_alert_client_id'], + ['rmm_clients', 'rmm_client_client_id'], ['rmm_devices', 'rmm_device_client_id'], ['rmm_alerts', 'rmm_alert_client_id'], ['rmm_networks', 'rmm_network_client_id'], ['phone_domains', 'phone_domain_client_id'], ['phone_calls', 'phone_call_client_id'], ['phone_devices', 'phone_device_client_id'], ['phone_events', 'phone_event_client_id'], ['managed_instances', 'managed_instance_client_id'], ['ai_usage', 'ai_usage_client_id'], ['logs', 'log_client_id'], ['notifications', 'notification_client_id'], diff --git a/functions/network.php b/functions/network.php index 4153a7391..d0343c603 100644 --- a/functions/network.php +++ b/functions/network.php @@ -218,6 +218,9 @@ function networkDelete($row) { $network_id = intval($row['network_id']); mysqli_query($mysqli, "UPDATE asset_interfaces SET interface_network_id = 0 WHERE interface_network_id = $network_id"); mysqli_query($mysqli, "DELETE FROM networks WHERE network_id = $network_id"); + if (function_exists('rmmNetworksDeleted')) { + rmmNetworksDeleted([$network_id]); + } logAudit("Network", "Delete", "$session_name deleted network " . escapeSql($row['network_name']), intval($row['network_client_id'])); } diff --git a/functions/rmm.php b/functions/rmm.php index 6eec8b6a8..e99d449bb 100644 --- a/functions/rmm.php +++ b/functions/rmm.php @@ -963,6 +963,7 @@ function rmmForgetClientDevices(int $rmm_client_id, string $name, string $why): } } mysqli_query($mysqli, "DELETE FROM rmm_devices WHERE rmm_device_rmm_client_id = $rmm_client_id"); + rmmNetworksForget($rmm_client_id); return $left; } @@ -998,7 +999,8 @@ function rmmSync(array $provider, int $only = 0, int $max_seconds = 120): array { global $mysqli, $session_name, $session_user_id, $session_ip, $session_user_agent; - $counts = ['clients' => 0, 'devices' => 0, 'created' => 0, 'linked' => 0, 'updated' => 0, 'removed' => 0, 'returned' => 0, 'skipped' => 0]; + $counts = ['clients' => 0, 'devices' => 0, 'created' => 0, 'linked' => 0, 'updated' => 0, 'removed' => 0, 'returned' => 0, 'skipped' => 0, + 'networks' => 0, 'networks_created' => 0, 'networks_linked' => 0, 'networks_updated' => 0, 'networks_removed' => 0, 'networks_returned' => 0]; $name = rmmProviderName($provider); if (!rmmProviderUsable($provider)) { return ['ok' => false, 'note' => "$name isn't set up, or is turned off.", 'counts' => $counts]; @@ -1147,6 +1149,15 @@ function rmmSync(array $provider, int $only = 0, int $max_seconds = 120): array } } $note_kept(intval($rmm_client['rmm_client_id']), (string) $rmm_client['rmm_client_name'], $kept); + // A network platform's networks and VLANs, as the client's networks (functions/rmm_network.php) + try { + $network_error = rmmNetworksSync($provider, $rmm_client, $counts); + } catch (Throwable $e) { + $network_error = $e->getMessage(); + } + if ($network_error !== '') { + $errors[] = $rmm_client['rmm_client_name'] . ': its networks - ' . $network_error; + } mysqli_query($mysqli, "UPDATE rmm_clients SET rmm_client_synced_at = NOW() WHERE rmm_client_id = " . intval($rmm_client['rmm_client_id'])); } @@ -1163,6 +1174,8 @@ function rmmSync(array $provider, int $only = 0, int $max_seconds = 120): array } } $note .= $done ? ' - ' . implode(', ', $done) : ''; + $networks_note = rmmNetworksNote($counts, $short); + $note .= $networks_note !== '' ? ". $networks_note" : ''; if ($stopped) { $note .= '. Stopped for time - the rest come in next sync'; } diff --git a/functions/rmm_network.php b/functions/rmm_network.php new file mode 100644 index 000000000..673776ede --- /dev/null +++ b/functions/rmm_network.php @@ -0,0 +1,346 @@ + 0; + } + return $ready; +} + +/** The details the sync writes to a network - its field => [column, what the history calls it]. */ +function rmmNetworkFields(): array +{ + return [ + 'name' => ['network_name', 'name'], 'type' => ['network_type', 'type'], 'vlan' => ['network_vlan', 'VLAN'], + 'network' => ['network', 'subnet'], 'gateway' => ['network_gateway', 'gateway'], 'primary_dns' => ['network_primary_dns', 'DNS'], + 'secondary_dns' => ['network_secondary_dns', 'second DNS'], 'dhcp_range' => ['network_dhcp_range', 'DHCP range'], + ]; +} + +/** A kind's network as the values of an ITFlow network - [field => value], or null when it has no subnet ITFlow can keep. */ +function rmmNetworkValues(array $net): ?array +{ + $subnet = trim((string) ($net['subnet'] ?? '')); + $info = networkSubnetInfo($subnet); + if (!$info) { + return null; + } + $name = rmmText($net['name'] ?? '', 200); + $host = normalizeIpAddress(trim(explode('/', $subnet)[0])); + $gateway = $host !== false && $host !== $info['network'] && isIpInSubnet($host, $info['cidr']) ? $host : ''; + + $range = ''; + $parsed = networkParseRange(trim((string) ($net['dhcp_start'] ?? '')) . ' - ' . trim((string) ($net['dhcp_stop'] ?? '')), $info); + if ($parsed) { + $range = intToIpv4($parsed[0]) . ' - ' . intToIpv4($parsed[1]); + } + $dns = []; + foreach ((array) ($net['dns'] ?? []) as $server) { + $server = normalizeIpAddress(trim((string) $server)); + if ($server !== false && !in_array($server, $dns, true)) { + $dns[] = $server; + } + } + // DHCP handing out the gateway as DNS - its own, when the platform names none + if (!$dns && $range !== '' && $gateway !== '') { + $dns[] = $gateway; + } + + // VLAN 1 is the untagged default network - no VLAN to write down + $vlan = intval($net['vlan'] ?? 0); + $purpose = (string) ($net['purpose'] ?? 'lan'); + return [ + 'name' => $name !== '' ? $name : $info['cidr'], + 'type' => $purpose === 'guest' ? 'Guest' : ($purpose === 'vpn' ? 'VPN' : networkGuessType($name)), + 'vlan' => $vlan >= 2 && $vlan <= 4094 ? (string) $vlan : '', + 'network' => $info['cidr'], + 'gateway' => $gateway, + 'primary_dns' => $dns[0] ?? '', + 'secondary_dns' => $dns[1] ?? '', + 'dhcp_range' => $range, + ]; +} + +/** A network's details as the sync compares them - [field => value], or null when it is gone. */ +function rmmNetworkCurrent(int $network_id): ?array +{ + global $mysqli; + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT network_id, network_client_id, network_archived_at, network_name, network_type, network_vlan, network, + network_gateway, network_primary_dns, network_secondary_dns, network_dhcp_range FROM networks WHERE network_id = $network_id")); + if (!$row) { + return null; + } + $current = ['client_id' => intval($row['network_client_id']), 'archived' => $row['network_archived_at'] !== null]; + foreach (rmmNetworkFields() as $field => [$column]) { + $current[$field] = $row[$column] === null ? '' : (string) $row[$column]; + } + return $current; +} + +/** The SQL that sets these details of a network. */ +function rmmNetworkSetSql(array $set): string +{ + $fields = rmmNetworkFields(); + $parts = []; + foreach ($set as $field => $value) { + $column = $fields[$field][0]; + $parts[] = $field === 'vlan' ? "$column = " . ($value === '' ? 'NULL' : intval($value)) : "$column = '" . escapeSql((string) $value) . "'"; + } + return implode(', ', $parts); +} + +/** + * Write what the platform says to a network, detail by detail: an empty one is filled in, one the + * sync wrote last time follows, and one changed in ITFlow is left as it is. [what changed (the + * history's words), what is the sync's now] - as rmmAssetFollow() does for an asset. + */ +function rmmNetworkFollow(int $network_id, array $current, array $values, array $synced_before): array +{ + global $mysqli; + $set = []; + $synced = []; + $ours = function ($field) use ($current, $synced_before) { + return array_key_exists($field, $synced_before) && (string) $synced_before[$field] === (string) ($current[$field] ?? ''); + }; + // The DNS servers go together - one set in ITFlow keeps the other as it is too + $dns_kept = false; + foreach (['primary_dns', 'secondary_dns'] as $field) { + $had = (string) ($current[$field] ?? ''); + if ($had !== '' && $had !== (string) ($values[$field] ?? '') && !$ours($field)) { + $dns_kept = true; + } + } + foreach ($values as $field => $new) { + $new = (string) $new; + $had = (string) ($current[$field] ?? ''); + $was_ours = $ours($field); + if ($dns_kept && in_array($field, ['primary_dns', 'secondary_dns'], true)) { + if (array_key_exists($field, $synced_before) && $was_ours) { + $synced[$field] = $synced_before[$field]; + } + continue; + } + if ($new === '') { + if ($was_ours) { + $synced[$field] = $synced_before[$field]; + } + continue; + } + if ($had === $new) { + $synced[$field] = $new; + continue; + } + if ($had === '' || $was_ours) { + $set[$field] = $new; + $synced[$field] = $new; + continue; + } + if (array_key_exists($field, $synced_before)) { + $synced[$field] = $synced_before[$field]; + } + } + if ($set) { + mysqli_query($mysqli, "UPDATE networks SET " . rmmNetworkSetSql($set) . " WHERE network_id = $network_id"); + } + $fields = rmmNetworkFields(); + return [array_map(function ($field) use ($fields) { + return $fields[$field][1]; + }, array_keys($set)), $synced]; +} + +/** "LAN, Guest and IoT" - a list in words. */ +function rmmNetworkWords(array $words): string +{ + return count($words) > 1 ? implode(', ', array_slice($words, 0, -1)) . ' and ' . end($words) : (string) ($words[0] ?? ''); +} + +/** + * One of a site's networks, brought into its client: matched or made, then kept up. Counts it in + * $counts (networks, networks_created, networks_linked, networks_updated, networks_returned). + */ +function rmmNetworkSave(array $provider, array $rmm_client, int $client_id, array $net, array &$counts): void +{ + global $mysqli; + $values = rmmNetworkValues($net); + $remote_id = rmmText($net['remote_id'] ?? '', 100); + if (!$values || $remote_id === '') { + return; + } + $provider_id = intval($provider['rmm_provider_id']); + $rmm_client_id = intval($rmm_client['rmm_client_id']); + $name = rmmProviderName($provider); + $short = rmmKind($provider)['short']; + $remote = escapeSql($remote_id); + $counts['networks']++; + + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT * FROM rmm_networks WHERE rmm_network_provider_id = $provider_id + AND rmm_network_rmm_client_id = $rmm_client_id AND rmm_network_remote_id = '$remote'")); + $network_id = $row ? intval($row['rmm_network_network_id']) : 0; + $synced_before = $row ? (json_decode((string) $row['rmm_network_synced'], true) ?: []) : []; + $current = $network_id ? rmmNetworkCurrent($network_id) : null; + if ($row && $row['rmm_network_removed_at'] !== null) { + $counts['networks_returned']++; + } + + if ($row && (!$network_id || !$current || $current['client_id'] !== $client_id)) { + // Deleted in ITFlow, or moved to another client there - not made again (Bring back makes it again) + mysqli_query($mysqli, "UPDATE rmm_networks SET rmm_network_network_id = 0, rmm_network_client_id = $client_id, rmm_network_name = '" . escapeSql($values['name']) . "', + rmm_network_synced_at = NOW(), rmm_network_removed_at = NULL WHERE rmm_network_id = " . intval($row['rmm_network_id'])); + return; + } + + $made = false; + if (!$row) { + // The client's network with the same subnet, that none of this platform's networks has already + $match = mysqli_fetch_row(mysqli_query($mysqli, "SELECT network_id FROM networks WHERE network_client_id = $client_id AND network_archived_at IS NULL + AND network = '" . escapeSql($values['network']) . "' AND network_id NOT IN (SELECT rmm_network_network_id FROM rmm_networks + WHERE rmm_network_provider_id = $provider_id AND rmm_network_network_id > 0 AND rmm_network_removed_at IS NULL) ORDER BY network_id LIMIT 1")); + if ($match) { + $network_id = intval($match[0]); + $current = rmmNetworkCurrent($network_id); + $counts['networks_linked']++; + } else { + mysqli_query($mysqli, "INSERT INTO networks SET " . rmmNetworkSetSql($values) . ", network_description = '', network_client_id = $client_id"); + $network_id = intval(mysqli_insert_id($mysqli)); + $current = rmmNetworkCurrent($network_id); + $made = true; + $counts['networks_created']++; + logAudit('Network', 'Create', escapeSql("$name brought in network {$values['name']} from its site {$rmm_client['rmm_client_name']}"), $client_id, $network_id); + } + } + + // Archived in ITFlow - left as it is + if ($current && $current['archived']) { + [$changed, $synced] = [[], $synced_before]; + } else { + [$changed, $synced] = $current ? rmmNetworkFollow($network_id, $current, $values, $made ? array_map('strval', $values) : $synced_before) : [[], []]; + } + $here = (string) ($current['name'] ?? $values['name']); + if (!$row && !$made) { + logAudit('Network', 'Edit', escapeSql("$name linked network $here to its network {$values['name']} in $short" . ($changed ? ' and filled in its ' . rmmNetworkWords($changed) : '')), $client_id, $network_id); + } elseif ($changed && !$made) { + $counts['networks_updated']++; + logAudit('Network', 'Edit', escapeSql("$name changed the " . rmmNetworkWords($changed) . " of network $here"), $client_id, $network_id); + } + + $synced_sql = escapeSql(json_encode($synced)); + $name_sql = escapeSql($values['name']); + if ($row) { + mysqli_query($mysqli, "UPDATE rmm_networks SET rmm_network_client_id = $client_id, rmm_network_name = '$name_sql', rmm_network_synced = '$synced_sql', + rmm_network_synced_at = NOW(), rmm_network_removed_at = NULL WHERE rmm_network_id = " . intval($row['rmm_network_id'])); + } else { + mysqli_query($mysqli, "INSERT INTO rmm_networks SET rmm_network_provider_id = $provider_id, rmm_network_rmm_client_id = $rmm_client_id, rmm_network_remote_id = '$remote', + rmm_network_client_id = $client_id, rmm_network_network_id = $network_id, rmm_network_name = '$name_sql', rmm_network_synced = '$synced_sql', rmm_network_synced_at = NOW()"); + } +} + +/** + * A linked site's networks, from its platform - each saved, and the ones it no longer lists marked. + * '' when that worked, or what went wrong; a platform whose version has no networks to list is fine. + */ +function rmmNetworksSync(array $provider, array $rmm_client, array &$counts): string +{ + global $mysqli; + $kind = rmmKind($provider); + if (!isset($kind['networks']) || !rmmNetworksReady()) { + return ''; + } + $answer = $kind['networks']($provider, (string) $rmm_client['rmm_client_remote_id']); + if (!$answer['ok']) { + return (string) $answer['error']; + } + if (!empty($answer['unoffered'])) { + return ''; + } + $client_id = intval($rmm_client['rmm_client_client_id']); + $listed = []; + foreach ($answer['networks'] as $net) { + if (is_array($net)) { + rmmNetworkSave($provider, $rmm_client, $client_id, $net, $counts); + $listed[] = escapeSql(rmmText($net['remote_id'] ?? '', 100)); + } + } + // The ones it no longer lists - not when it lists none at all, which is more often its access than the site + if ($listed) { + $rmm_client_id = intval($rmm_client['rmm_client_id']); + mysqli_query($mysqli, "UPDATE rmm_networks SET rmm_network_removed_at = NOW() WHERE rmm_network_rmm_client_id = $rmm_client_id + AND rmm_network_removed_at IS NULL AND rmm_network_remote_id NOT IN ('" . implode("', '", $listed) . "')"); + $counts['networks_removed'] += mysqli_affected_rows($mysqli); + } + return ''; +} + +/** The words for what a sync did with networks - "4 networks - 1 new, 3 matched to networks already here", or ''. */ +function rmmNetworksNote(array $counts, string $short): string +{ + if (!($counts['networks'] ?? 0) && !($counts['networks_removed'] ?? 0)) { + return ''; + } + $note = number_format($counts['networks']) . ' network' . ($counts['networks'] === 1 ? '' : 's'); + $done = []; + foreach (['networks_created' => 'new', 'networks_linked' => 'matched to networks already here', 'networks_updated' => 'updated', + 'networks_removed' => "no longer in $short", 'networks_returned' => "back in $short"] as $key => $words) { + if ($counts[$key] ?? 0) { + $done[] = number_format($counts[$key]) . " $words"; + } + } + return $note . ($done ? ' - ' . implode(', ', $done) : ''); +} + +/** What the sync knew of a site's networks is forgotten - unlinked, or linked to another client. The networks stay. */ +function rmmNetworksForget(int $rmm_client_id): void +{ + global $mysqli; + if (rmmNetworksReady()) { + mysqli_query($mysqli, "DELETE FROM rmm_networks WHERE rmm_network_rmm_client_id = $rmm_client_id"); + } +} + +/** Networks deleted in ITFlow - their platform's rows say so, so the sync doesn't make them again. */ +function rmmNetworksDeleted(array $network_ids): void +{ + global $mysqli; + $ids = array_filter(array_map('intval', $network_ids)); + if ($ids && rmmNetworksReady()) { + mysqli_query($mysqli, "UPDATE rmm_networks SET rmm_network_network_id = 0 WHERE rmm_network_network_id IN (" . implode(', ', $ids) . ")"); + } +} + +/** The platform rows of a network - with their platform's and site's names - for its page. */ +function rmmNetworksFor(int $network_id): array +{ + global $mysqli; + $rows = []; + if (!rmmNetworksReady() || !$network_id) { + return $rows; + } + $sql = mysqli_query($mysqli, "SELECT rmm_networks.*, rmm_providers.*, rmm_client_name FROM rmm_networks + JOIN rmm_providers ON rmm_provider_id = rmm_network_provider_id + JOIN rmm_clients ON rmm_clients.rmm_client_id = rmm_network_rmm_client_id + WHERE rmm_network_network_id = $network_id ORDER BY rmm_network_removed_at IS NOT NULL, rmm_network_id"); + while ($row = mysqli_fetch_assoc($sql)) { + $rows[] = $row; + } + return $rows; +} diff --git a/functions/rmm_unifi.php b/functions/rmm_unifi.php index e60ce02e0..abf838c62 100644 --- a/functions/rmm_unifi.php +++ b/functions/rmm_unifi.php @@ -57,6 +57,7 @@ function rmmUnifiKind(string $key): array 'links' => ['open' => 'Open in UniFi'], 'clients' => 'rmmUnifiSites', 'devices' => 'rmmUnifiDevices', + 'networks' => 'rmmUnifiNetworks', 'dashboard' => 'rmmUnifiDashboard', 'docs_url' => 'https://help.ui.com/hc/en-us/articles/30076656117655', ]; @@ -470,19 +471,11 @@ function rmmUnifiDevices(array $provider, string $site): array return ['ok' => true, 'devices' => $devices, 'error' => '']; } - $console = ''; - $site_id = $site; - if ($kind === 'unifi_cloud') { - $map = rmmUnifiCloudSites(); - if (!isset($map[$site])) { - rmmUnifiSites($provider); - $map = rmmUnifiCloudSites(); - } - if (!isset($map[$site])) { - return ['ok' => false, 'devices' => [], 'error' => 'Site Manager no longer lists that site']; - } - [$console, $site_id] = $map[$site]; + $where = rmmUnifiSiteWhere($provider, $site); + if (!$where) { + return ['ok' => false, 'devices' => [], 'error' => 'Site Manager no longer lists that site']; } + [$console, $site_id] = $where; $answer = rmmUnifiNetwork($provider, 'sites/' . rawurlencode($site_id) . '/devices', [], $console); if (!$answer['ok']) { return ['ok' => false, 'devices' => [], 'error' => $answer['error']]; @@ -495,6 +488,100 @@ function rmmUnifiDevices(array $provider, string $site): array return ['ok' => true, 'devices' => $devices, 'error' => '']; } +/** Where a site is - for Site Manager, the console it is on and its id there: [console, site id], or null when it no longer lists it. */ +function rmmUnifiSiteWhere(array $provider, string $site): ?array +{ + if ($provider['rmm_provider_kind'] !== 'unifi_cloud') { + return ['', $site]; + } + $map = rmmUnifiCloudSites(); + if (!isset($map[$site])) { + rmmUnifiSites($provider); + $map = rmmUnifiCloudSites(); + } + return $map[$site] ?? null; +} + +/** + * One site's networks and VLANs - ['ok', 'networks', 'error', 'unoffered'], each as rmmNetworkSave() takes + * it (functions/rmm_network.php). Only the ones the gateway or a switch routes, with a subnet, and on: + * a WAN, a site-to-site VPN or a VLAN with no subnet isn't one of the client's networks. + */ +function rmmUnifiNetworks(array $provider, string $site): array +{ + $networks = []; + if ($provider['rmm_provider_kind'] === 'unifi') { + $answer = rmmUnifiController($provider, 's/' . rawurlencode($site) . '/rest/networkconf'); + if (!$answer['ok']) { + return ['ok' => false, 'networks' => [], 'error' => $answer['error'], 'unoffered' => false]; + } + $purposes = ['corporate' => 'lan', 'guest' => 'guest', 'remote-user-vpn' => 'vpn']; + foreach ($answer['data'] as $net) { + if (!is_array($net) || !isset($purposes[$net['purpose'] ?? '']) || ($net['enabled'] ?? true) === false || trim((string) ($net['ip_subnet'] ?? '')) === '') { + continue; + } + $dhcp = !empty($net['dhcpd_enabled']); + $dns = []; + if ($dhcp && !empty($net['dhcpd_dns_enabled'])) { + foreach (['dhcpd_dns_1', 'dhcpd_dns_2', 'dhcpd_dns_3', 'dhcpd_dns_4'] as $field) { + if (trim((string) ($net[$field] ?? '')) !== '') { + $dns[] = (string) $net[$field]; + } + } + } + $networks[] = [ + 'remote_id' => (string) ($net['_id'] ?? ''), + 'name' => (string) ($net['name'] ?? ''), + 'purpose' => $purposes[$net['purpose']], + 'vlan' => !empty($net['vlan_enabled']) ? intval($net['vlan'] ?? 0) : 0, + 'subnet' => (string) $net['ip_subnet'], + 'dhcp_start' => $dhcp ? (string) ($net['dhcpd_start'] ?? '') : '', + 'dhcp_stop' => $dhcp ? (string) ($net['dhcpd_stop'] ?? '') : '', + 'dns' => $dns, + ]; + } + return ['ok' => true, 'networks' => $networks, 'error' => '', 'unoffered' => false]; + } + + // The official Network API - the list, then each network's details for its subnet and DHCP + $where = rmmUnifiSiteWhere($provider, $site); + if (!$where) { + return ['ok' => false, 'networks' => [], 'error' => 'Site Manager no longer lists that site', 'unoffered' => false]; + } + [$console, $site_id] = $where; + $answer = rmmUnifiNetwork($provider, 'sites/' . rawurlencode($site_id) . '/networks', [], $console); + if (!$answer['ok']) { + // A Network version older than its networks endpoint - nothing to bring in, and nothing wrong + return $answer['code'] === 404 ? ['ok' => true, 'networks' => [], 'error' => '', 'unoffered' => true] : ['ok' => false, 'networks' => [], 'error' => $answer['error'], 'unoffered' => false]; + } + foreach ($answer['data'] as $item) { + $id = is_array($item) ? (string) ($item['id'] ?? '') : ''; + if ($id === '' || !preg_match('/^[A-Za-z0-9-]{1,100}$/', $id) || ($item['enabled'] ?? true) === false || !in_array($item['management'] ?? '', ['GATEWAY', 'SWITCH'], true)) { + continue; + } + $details = rmmUnifiNetwork($provider, 'sites/' . rawurlencode($site_id) . '/networks/' . $id, [], $console, false); + if (!$details['ok']) { + return ['ok' => false, 'networks' => [], 'error' => $details['error'], 'unoffered' => false]; + } + $ipv4 = is_array($details['data']['ipv4Configuration'] ?? null) ? $details['data']['ipv4Configuration'] : []; + if (trim((string) ($ipv4['hostIpAddress'] ?? '')) === '' || !isset($ipv4['prefixLength'])) { + continue; + } + $dhcp = is_array($ipv4['dhcpConfiguration'] ?? null) && ($ipv4['dhcpConfiguration']['mode'] ?? '') === 'SERVER' ? $ipv4['dhcpConfiguration'] : []; + $networks[] = [ + 'remote_id' => $id, + 'name' => (string) ($details['data']['name'] ?? $item['name'] ?? ''), + 'purpose' => 'lan', + 'vlan' => intval($details['data']['vlanId'] ?? $item['vlanId'] ?? 0), + 'subnet' => $ipv4['hostIpAddress'] . '/' . intval($ipv4['prefixLength']), + 'dhcp_start' => (string) ($dhcp['ipAddressRange']['start'] ?? ''), + 'dhcp_stop' => (string) ($dhcp['ipAddressRange']['stop'] ?? ''), + 'dns' => array_map('strval', (array) ($dhcp['dnsServerIpAddressesOverride'] ?? [])), + ]; + } + return ['ok' => true, 'networks' => $networks, 'error' => '', 'unoffered' => false]; +} + /** A controller's device (stat/device) as a device. */ function rmmUnifiControllerDevice(array $device): array {