diff --git a/CHANGELOG.md b/CHANGELOG.md index 2f28cdf12..3482c0dd0 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 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. +Update from Maintenance > Update — Queue Update hands the job to cron, which updates the files and applies this release's six database changes (4.1.1 to 4.1.7) 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 two tables for network platforms, their networks and where devices plug in, and change nothing that is there. Nothing else is required. ### New Features & Updates @@ -25,6 +25,7 @@ Update from Maintenance > Update — Queue Update hands the job to cron, which u - 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. +- Network Platforms: an asset UniFi sees on the network has a Connection card - the switch and port it's plugged into, or the access point and Wi-Fi network it's on, with its IP address, and whether it's connected now or when it was last seen there. A UniFi switch's or access point's card lists the client's assets on it by port. Only devices that are the client's assets - by a MAC address on one of their interfaces, or their name - are kept, not every phone on the guest Wi-Fi. Through an API key UniFi says the switch or access point but not the port. ### Bug Fixes @@ -63,11 +64,12 @@ Update from Maintenance > Update — Queue Update hands the job to cron, which u - `api/phone/hook.php` takes desk phones' events through `phoneHookEvent()` - Yealink action URLs as GET (`e` = setup, registered, unregistered, failed, ringing, outgoing, answered or ended, with `mac`, `ip`, `model`, `fw`, `line`, `domain`, `number`, `name` and `call`; a variable the phone left unfilled counts as nothing) or Polycom telephony notifications posted as XML (`phoneHookPolycom()`), with the vendor, model and firmware from the User-Agent when the request doesn't say. `phoneDeviceSave()` keeps a phone by system and MAC in `phone_devices`, and `phoneDeviceAsset()` finds the client's asset by MAC (`asset_interfaces.interface_mac`, any separators) or makes a Phone asset with its interface and `extension` detail, then follows the phone the way RMM devices do: a field is written when empty or still what the phone said last. `phone_device_asset_id` -1 is an asset deleted in ITFlow, not made again. `phoneDomainLink()` runs it for the domain's phones. - Screen pops: `api/phone/hook.php` saves call events (ringing, outgoing, answered, ended, missed) with an outside number to `phone_events` for each agent whose `user_config_phone_line` (`ext@domain`, Your account > Preferences, `phoneLineChoices()`) the line is - `phoneEventSave()`, `phoneUsersForLine()`. `js/phone_pop.js`, loaded by `includes/footer.php` on pages in `agent/` for agents with a line, asks `agent/ajax.php?phone_pop` every 3 seconds while the page is visible; `phonePopCalls()` groups the agent's events of the last 4 hours by the phone's call id (else number and line) and answers at most two calls - ringing for 90 seconds after the last event, answered until ended, ended for 10 minutes - with the contact, client and open tickets for clients the agent can reach and, ended, the `phone_calls` record matched by number, line and time. The handler closes the session before working. New Ticket opens `ticket_quick.php` with `contact_id` and `phone_call` (the call key: timer off), or `ticket_add.php` with `phone_pop_call`; `add_ticket` remembers the ticket per key in the session (`phonePopTicketMade()`) and sets ticket source Phone, and `phone_call_ticket.php` takes `ticket_id` to pick it. phone_events still go after 2 days. - Database 4.1.5: `rmm_providers.rmm_provider_insecure` (accept a self-signed certificate) and `rmm_devices.rmm_device_mac` (12 lowercase hex digits, indexed). Re-runnable. A network platform is an `rmm_providers` row whose kind's `family` is `network`; its sites are `rmm_clients` rows and its devices `rmm_devices` rows, so the follow rule, gone-hold, Bring back and asset types work unchanged. `rmmFamily()`, `rmmFamilyWords()` and `rmmFamilyProviders()` in `functions/rmm.php` split the two; `admin/network_platforms.php` sets `$rmm_family = 'network'` and includes `admin/rmm_providers.php`. -- `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. +- `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 first - in `config.php`, behind `defined()` - 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. +- Database 4.1.7: `rmm_seen` - one of a client's assets as a platform's site last saw it: the MAC address it was seen by, `rmm_seen_via_mac` (the switch or access point - a platform device's `rmm_device_mac`), the port or SSID, IP, network and VLAN, and `rmm_seen_at`. Re-runnable. `rmmSeenSync()` in `functions/rmm_network.php`, after the networks, keeps the rows whose MAC is on one of the client's asset interfaces or whose hostname is the only asset of that name (`rmmSeenAssetMap()`), and deletes ones not seen for `RMM_SEEN_KEEP_DAYS` (90). `rmmSeenForAsset()` and `rmmSeenVia()` feed the asset page; a row is connected now within `RMM_SEEN_NOW_MINUTES` (35). `rmmUnifiSeen()` reads a controller's `stat/sta` (`sw_mac`, `sw_port`, `ap_mac`, `essid`) and its devices' `uplink`, or the integration API's `sites/{id}/clients` (`uplinkDeviceId`); `rmmUnifiSiteDevices()` keeps a site's device list for the request so it is asked for once. ## [26.12] diff --git a/admin/database_updates/4.1.7.php b/admin/database_updates/4.1.7.php new file mode 100644 index 000000000..320ac9a11 --- /dev/null +++ b/admin/database_updates/4.1.7.php @@ -0,0 +1,43 @@ +
has it under , which is linked to another client.
+ +
+
·
+ +
+
As said .
+ ' . escapeHtml($seen['via_asset_name']) . '' + : escapeHtml((string) ($seen['via_name'] ?? '') !== '' ? $seen['via_name'] : ($seen_wired ? 'A switch' : 'An access point') . " $seen_short doesn't list"); ?> +
+
+

Connection

+
+
+
+
+
+ +
IP
+
+ + +
Network
+
+ +
+
.
+
+
+ + 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]; + 'networks' => 0, 'networks_created' => 0, 'networks_linked' => 0, 'networks_updated' => 0, 'networks_removed' => 0, 'networks_returned' => 0, 'seen' => 0]; $name = rmmProviderName($provider); if (!rmmProviderUsable($provider)) { return ['ok' => false, 'note' => "$name isn't set up, or is turned off.", 'counts' => $counts]; @@ -1158,6 +1158,15 @@ function rmmSync(array $provider, int $only = 0, int $max_seconds = 120): array if ($network_error !== '') { $errors[] = $rmm_client['rmm_client_name'] . ': its networks - ' . $network_error; } + // And where the client's assets plug in + try { + $seen_error = rmmSeenSync($provider, $rmm_client, $counts); + } catch (Throwable $e) { + $seen_error = $e->getMessage(); + } + if ($seen_error !== '') { + $errors[] = $rmm_client['rmm_client_name'] . ': where its devices plug in - ' . $seen_error; + } mysqli_query($mysqli, "UPDATE rmm_clients SET rmm_client_synced_at = NOW() WHERE rmm_client_id = " . intval($rmm_client['rmm_client_id'])); } diff --git a/functions/rmm_network.php b/functions/rmm_network.php index 673776ede..d9e54930e 100644 --- a/functions/rmm_network.php +++ b/functions/rmm_network.php @@ -291,11 +291,12 @@ function rmmNetworksSync(array $provider, array $rmm_client, array &$counts): st return ''; } -/** The words for what a sync did with networks - "4 networks - 1 new, 3 matched to networks already here", or ''. */ +/** The words for what a sync did with networks - "4 networks - 1 new, 3 matched to networks already here. 12 assets seen on the network", or ''. */ function rmmNetworksNote(array $counts, string $short): string { + $seen = ($counts['seen'] ?? 0) ? '. ' . number_format($counts['seen']) . ' asset' . ($counts['seen'] === 1 ? '' : 's') . ' seen on the network' : ''; if (!($counts['networks'] ?? 0) && !($counts['networks_removed'] ?? 0)) { - return ''; + return ltrim($seen, '. '); } $note = number_format($counts['networks']) . ' network' . ($counts['networks'] === 1 ? '' : 's'); $done = []; @@ -305,7 +306,7 @@ function rmmNetworksNote(array $counts, string $short): string $done[] = number_format($counts[$key]) . " $words"; } } - return $note . ($done ? ' - ' . implode(', ', $done) : ''); + return $note . ($done ? ' - ' . implode(', ', $done) : '') . $seen; } /** What the sync knew of a site's networks is forgotten - unlinked, or linked to another client. The networks stay. */ @@ -315,6 +316,7 @@ function rmmNetworksForget(int $rmm_client_id): void if (rmmNetworksReady()) { mysqli_query($mysqli, "DELETE FROM rmm_networks WHERE rmm_network_rmm_client_id = $rmm_client_id"); } + rmmSeenForget($rmm_client_id); } /** Networks deleted in ITFlow - their platform's rows say so, so the sync doesn't make them again. */ @@ -344,3 +346,163 @@ function rmmNetworksFor(int $network_id): array } return $rows; } + +/* + * ------------------------------------------------------------------ Where things plug in + * + * A kind with a 'seen' function (rmmUnifiSeen()) says what a site's switches and access points + * see on them: each device by its MAC address, the switch or access point it is on (via_mac - + * one of the platform's devices), the port or Wi-Fi network, its IP address and network. Only + * the ones that are one of the client's assets - by a MAC address on one of its interfaces, or + * failing that the only asset with its name - are kept, in rmm_seen. + */ + +/** Whether the 4.1.7 database update is in - where things plug in. */ +function rmmSeenReady(): bool +{ + global $mysqli; + static $ready = null; + if ($ready === null) { + $result = rmmNetworkReady() ? mysqli_query($mysqli, "SHOW TABLES LIKE 'rmm_seen'") : false; + $ready = $result && mysqli_num_rows($result) > 0; + } + return $ready; +} + +/** How long a device stays connected after it was last seen, in minutes - a sync is every 15. */ +const RMM_SEEN_NOW_MINUTES = 35; + +/** How long what a site last saw of a device is kept, in days. */ +const RMM_SEEN_KEEP_DAYS = 90; + +/** A client's assets by the MAC addresses on their interfaces, and by name - ['mac' => [mac => asset_id], 'name' => [name => asset_id, 0 when more than one]]. */ +function rmmSeenAssetMap(int $client_id): array +{ + global $mysqli; + $map = ['mac' => [], 'name' => []]; + $named = []; + $sql = mysqli_query($mysqli, "SELECT asset_id, asset_name, interface_mac FROM assets + LEFT JOIN asset_interfaces ON interface_asset_id = asset_id AND interface_archived_at IS NULL + WHERE asset_client_id = $client_id AND asset_archived_at IS NULL"); + while ($row = mysqli_fetch_assoc($sql)) { + $asset_id = intval($row['asset_id']); + $mac = rmmMac($row['interface_mac'] ?? ''); + if ($mac !== '' && !isset($map['mac'][$mac])) { + $map['mac'][$mac] = $asset_id; + } + $named[mb_strtolower(trim((string) $row['asset_name']))][$asset_id] = true; + } + foreach ($named as $name => $ids) { + if ($name !== '') { + $map['name'][$name] = count($ids) === 1 ? array_key_first($ids) : 0; + } + } + return $map; +} + +/** What a linked site sees on its switches and access points, kept for the client's assets. '' when that worked, or what went wrong. */ +function rmmSeenSync(array $provider, array $rmm_client, array &$counts): string +{ + global $mysqli; + $kind = rmmKind($provider); + if (!isset($kind['seen']) || !rmmSeenReady()) { + return ''; + } + $answer = $kind['seen']($provider, (string) $rmm_client['rmm_client_remote_id']); + if (!$answer['ok']) { + return (string) $answer['error']; + } + $provider_id = intval($provider['rmm_provider_id']); + $rmm_client_id = intval($rmm_client['rmm_client_id']); + $client_id = intval($rmm_client['rmm_client_client_id']); + $map = rmmSeenAssetMap($client_id); + foreach ($answer['seen'] as $seen) { + $mac = is_array($seen) ? rmmMac($seen['mac'] ?? '') : ''; + if ($mac === '') { + continue; + } + $hostname = rmmText($seen['hostname'] ?? '', 200); + $asset_id = $map['mac'][$mac] ?? ($hostname !== '' ? ($map['name'][mb_strtolower($hostname)] ?? 0) : 0); + if (!$asset_id) { + continue; + } + $ip = normalizeIpAddress(trim((string) ($seen['ip'] ?? ''))); + $vlan = intval($seen['vlan'] ?? 0); + $set = "rmm_seen_client_id = $client_id, rmm_seen_asset_id = $asset_id, rmm_seen_hostname = '" . escapeSql($hostname) . "', + rmm_seen_ip = '" . escapeSql($ip === false ? '' : $ip) . "', rmm_seen_via_mac = '" . escapeSql(rmmMac($seen['via_mac'] ?? '')) . "', + rmm_seen_port = '" . escapeSql(rmmText($seen['port'] ?? '', 50)) . "', rmm_seen_wired = " . (!empty($seen['wired']) ? 1 : 0) . ", + rmm_seen_ssid = '" . escapeSql(rmmText($seen['ssid'] ?? '', 100)) . "', rmm_seen_network = '" . escapeSql(rmmText($seen['network'] ?? '', 200)) . "', + rmm_seen_vlan = " . ($vlan >= 1 && $vlan <= 4094 ? $vlan : 0) . ", rmm_seen_at = NOW()"; + mysqli_query($mysqli, "INSERT INTO rmm_seen SET rmm_seen_provider_id = $provider_id, rmm_seen_rmm_client_id = $rmm_client_id, rmm_seen_mac = '$mac', $set + ON DUPLICATE KEY UPDATE $set"); + $counts['seen']++; + } + mysqli_query($mysqli, "DELETE FROM rmm_seen WHERE rmm_seen_rmm_client_id = $rmm_client_id AND rmm_seen_at < NOW() - INTERVAL " . RMM_SEEN_KEEP_DAYS . " DAY"); + return ''; +} + +/** What a site saw of the client's assets is forgotten - unlinked, or linked to another client. */ +function rmmSeenForget(int $rmm_client_id): void +{ + global $mysqli; + if (rmmSeenReady()) { + mysqli_query($mysqli, "DELETE FROM rmm_seen WHERE rmm_seen_rmm_client_id = $rmm_client_id"); + } +} + +/** + * Where an asset was last seen on the network - newest first, each with its platform, the switch + * or access point it was on (via_asset_id and via_asset_name when that is one of the client's + * assets, via_name its name on the platform) and now (1 when it was there at the last sync). + */ +function rmmSeenForAsset(int $asset_id): array +{ + global $mysqli; + $rows = []; + if (!rmmSeenReady() || !$asset_id) { + return $rows; + } + $sql = mysqli_query($mysqli, "SELECT rmm_seen.*, rmm_provider_id, rmm_provider_name, rmm_provider_kind, via.rmm_device_hostname AS via_name, + via_asset.asset_id AS via_asset_id, via_asset.asset_name AS via_asset_name, via_asset.asset_type AS via_asset_type, + rmm_seen_at >= NOW() - INTERVAL " . RMM_SEEN_NOW_MINUTES . " MINUTE AS now + FROM rmm_seen + JOIN rmm_providers ON rmm_provider_id = rmm_seen_provider_id + JOIN rmm_clients ON rmm_clients.rmm_client_id = rmm_seen_rmm_client_id AND rmm_client_client_id = rmm_seen_client_id + LEFT JOIN rmm_devices via ON via.rmm_device_provider_id = rmm_seen_provider_id AND via.rmm_device_mac = rmm_seen_via_mac AND rmm_seen_via_mac <> '' AND via.rmm_device_removed_at IS NULL + LEFT JOIN assets via_asset ON via_asset.asset_id = via.rmm_device_asset_id AND via.rmm_device_asset_id > 0 AND via_asset.asset_archived_at IS NULL AND via_asset.asset_client_id = rmm_seen_client_id + WHERE rmm_seen_asset_id = $asset_id ORDER BY rmm_seen_at DESC, rmm_seen_id DESC LIMIT 5"); + while ($row = mysqli_fetch_assoc($sql)) { + $rows[] = $row; + } + return $rows; +} + +/** What is plugged into one of a platform's switches or on one of its access points - the assets seen on it lately, by port. */ +function rmmSeenVia(array $device): array +{ + global $mysqli; + $rows = []; + $mac = rmmMac($device['rmm_device_mac'] ?? ''); + if (!rmmSeenReady() || $mac === '') { + return $rows; + } + $provider_id = intval($device['rmm_device_provider_id']); + $sql = mysqli_query($mysqli, "SELECT rmm_seen.*, asset_name, asset_type, asset_client_id, rmm_seen_at >= NOW() - INTERVAL " . RMM_SEEN_NOW_MINUTES . " MINUTE AS now + FROM rmm_seen JOIN assets ON asset_id = rmm_seen_asset_id AND asset_archived_at IS NULL AND asset_client_id = rmm_seen_client_id + WHERE rmm_seen_provider_id = $provider_id AND rmm_seen_via_mac = '$mac' AND rmm_seen_at >= NOW() - INTERVAL 30 DAY + ORDER BY rmm_seen_wired DESC, rmm_seen_port = '', CAST(rmm_seen_port AS UNSIGNED), rmm_seen_port, asset_name LIMIT 200"); + while ($row = mysqli_fetch_assoc($sql)) { + $rows[] = $row; + } + return $rows; +} + +/** Where a seen row is on the network, in words - "Port 7", "Wi-Fi Staff", "Wired", "Wi-Fi". */ +function rmmSeenPlace(array $row): string +{ + if (intval($row['rmm_seen_wired'])) { + $port = (string) $row['rmm_seen_port']; + return $port === '' ? 'Wired' : (ctype_digit($port) ? "Port $port" : $port); + } + return trim('Wi-Fi ' . (string) $row['rmm_seen_ssid']); +} diff --git a/functions/rmm_unifi.php b/functions/rmm_unifi.php index abf838c62..cbcedeb58 100644 --- a/functions/rmm_unifi.php +++ b/functions/rmm_unifi.php @@ -58,6 +58,7 @@ function rmmUnifiKind(string $key): array 'clients' => 'rmmUnifiSites', 'devices' => 'rmmUnifiDevices', 'networks' => 'rmmUnifiNetworks', + 'seen' => 'rmmUnifiSeen', 'dashboard' => 'rmmUnifiDashboard', 'docs_url' => 'https://help.ui.com/hc/en-us/articles/30076656117655', ]; @@ -463,6 +464,7 @@ function rmmUnifiDevices(array $provider, string $site): array if (!$answer['ok']) { return ['ok' => false, 'devices' => [], 'error' => $answer['error']]; } + rmmUnifiSiteDevices($provider, $site, $answer['data']); foreach ($answer['data'] as $device) { if (is_array($device) && ($device['adopted'] ?? true) !== false && rmmMac($device['mac'] ?? '') !== '') { $devices[] = rmmUnifiControllerDevice($device); @@ -480,6 +482,7 @@ function rmmUnifiDevices(array $provider, string $site): array if (!$answer['ok']) { return ['ok' => false, 'devices' => [], 'error' => $answer['error']]; } + rmmUnifiSiteDevices($provider, $site, $answer['data']); foreach ($answer['data'] as $device) { if (is_array($device) && rmmMac($device['macAddress'] ?? '') !== '') { $devices[] = rmmUnifiNetworkDevice($device); @@ -582,6 +585,104 @@ function rmmUnifiNetworks(array $provider, string $site): array return ['ok' => true, 'networks' => $networks, 'error' => '', 'unoffered' => false]; } +/** A site's devices as UniFi gave them, kept for the request - the sync asks for them, then for where things plug in. $set keeps them; null when not asked yet. */ +function rmmUnifiSiteDevices(array $provider, string $site, ?array $set = null): ?array +{ + static $kept = []; + $key = intval($provider['rmm_provider_id'] ?? 0) . "\n$site"; + if ($set !== null) { + $kept[$key] = $set; + } + return $kept[$key] ?? null; +} + +/** + * What a site's switches and access points see - ['ok', 'seen', 'error'], each as rmmSeenSync() takes + * it (functions/rmm_network.php): the devices on it now, and what its own switches and access points + * are plugged into. A controller says the switch port; the official Network API only which device. + */ +function rmmUnifiSeen(array $provider, string $site): array +{ + $seen = []; + if ($provider['rmm_provider_kind'] === 'unifi') { + $devices = rmmUnifiSiteDevices($provider, $site); + if ($devices === null) { + $answer = rmmUnifiController($provider, 's/' . rawurlencode($site) . '/stat/device'); + if (!$answer['ok']) { + return ['ok' => false, 'seen' => [], 'error' => $answer['error']]; + } + $devices = $answer['data']; + } + // Its own switches and access points - what each is plugged into, or meshed to + foreach ($devices as $device) { + $uplink = is_array($device) && is_array($device['uplink'] ?? null) ? $device['uplink'] : []; + if (rmmMac($device['mac'] ?? '') === '' || rmmMac($uplink['uplink_mac'] ?? '') === '') { + continue; + } + $wireless = ($uplink['type'] ?? '') === 'wireless'; + $seen[] = [ + 'mac' => (string) $device['mac'], 'hostname' => (string) ($device['name'] ?? ''), 'ip' => (string) ($device['ip'] ?? ''), + 'via_mac' => (string) $uplink['uplink_mac'], 'port' => !$wireless && isset($uplink['uplink_remote_port']) ? (string) intval($uplink['uplink_remote_port']) : '', + 'wired' => !$wireless, 'ssid' => '', 'network' => '', 'vlan' => 0, + ]; + } + $answer = rmmUnifiController($provider, 's/' . rawurlencode($site) . '/stat/sta'); + if (!$answer['ok']) { + return ['ok' => false, 'seen' => [], 'error' => $answer['error']]; + } + foreach ($answer['data'] as $sta) { + if (!is_array($sta) || rmmMac($sta['mac'] ?? '') === '') { + continue; + } + $wired = !empty($sta['is_wired']); + $seen[] = [ + 'mac' => (string) $sta['mac'], 'hostname' => (string) ($sta['hostname'] ?? $sta['name'] ?? ''), 'ip' => (string) ($sta['ip'] ?? ''), + 'via_mac' => (string) ($wired ? ($sta['sw_mac'] ?? '') : ($sta['ap_mac'] ?? '')), + 'port' => $wired && isset($sta['sw_port']) ? (string) intval($sta['sw_port']) : '', + 'wired' => $wired, 'ssid' => $wired ? '' : (string) ($sta['essid'] ?? ''), + 'network' => (string) ($sta['network'] ?? ''), 'vlan' => intval($sta['vlan'] ?? 0), + ]; + } + return ['ok' => true, 'seen' => $seen, 'error' => '']; + } + + $where = rmmUnifiSiteWhere($provider, $site); + if (!$where) { + return ['ok' => false, 'seen' => [], 'error' => 'Site Manager no longer lists that site']; + } + [$console, $site_id] = $where; + $devices = rmmUnifiSiteDevices($provider, $site); + if ($devices === null) { + $answer = rmmUnifiNetwork($provider, 'sites/' . rawurlencode($site_id) . '/devices', [], $console); + if (!$answer['ok']) { + return ['ok' => false, 'seen' => [], 'error' => $answer['error']]; + } + $devices = $answer['data']; + } + $macs = []; + foreach ($devices as $device) { + if (is_array($device) && isset($device['id'])) { + $macs[(string) $device['id']] = (string) ($device['macAddress'] ?? ''); + } + } + $answer = rmmUnifiNetwork($provider, 'sites/' . rawurlencode($site_id) . '/clients', [], $console); + if (!$answer['ok']) { + // A Network version older than its clients endpoint - nothing to say, and nothing wrong + return $answer['code'] === 404 ? ['ok' => true, 'seen' => [], 'error' => ''] : ['ok' => false, 'seen' => [], 'error' => $answer['error']]; + } + foreach ($answer['data'] as $client) { + $type = is_array($client) ? (string) ($client['type'] ?? '') : ''; + if (!in_array($type, ['WIRED', 'WIRELESS'], true) || rmmMac($client['macAddress'] ?? '') === '') { + continue; + } + $seen[] = [ + 'mac' => (string) $client['macAddress'], 'hostname' => (string) ($client['name'] ?? ''), 'ip' => (string) ($client['ipAddress'] ?? ''), + 'via_mac' => $macs[(string) ($client['uplinkDeviceId'] ?? '')] ?? '', 'port' => '', 'wired' => $type === 'WIRED', 'ssid' => '', 'network' => '', 'vlan' => 0, + ]; + } + return ['ok' => true, 'seen' => $seen, 'error' => '']; +} + /** A controller's device (stat/device) as a device. */ function rmmUnifiControllerDevice(array $device): array {