Show where each asset plugs in from network platforms, with the switch port or access point on the asset and what is plugged into each UniFi switch and access point, with database 4.1.7

This commit is contained in:
johnnyq
2026-11-23 00:58:25 -05:00
parent 47deaba513
commit 52390ca6a4
9 changed files with 406 additions and 7 deletions

View File

@@ -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]

View File

@@ -0,0 +1,43 @@
<?php
/*
* ITFlow - Database update to version 4.1.7 (from 4.1.6)
* Included by admin/database_updates.php - do not access directly
*
* Where things plug in - from a network platform (functions/rmm_network.php).
*
* rmm_seen one of a client's assets as a platform's site last saw it on the network: the
* switch or access point it was on (its MAC address - a platform device's), the
* port or Wi-Fi network, its IP address and network. Only devices that are one of
* the client's assets are kept - not every phone that joined the guest Wi-Fi. A
* platform's own switches and access points have a row too, for what they are
* plugged into.
*
* Re-runnable: it only adds what isn't there.
*/
defined('FROM_DB_UPDATER') || die("Direct file access is not allowed");
mysqli_query($mysqli, "CREATE TABLE IF NOT EXISTS `rmm_seen` (
`rmm_seen_id` int(11) NOT NULL AUTO_INCREMENT,
`rmm_seen_provider_id` int(11) NOT NULL,
`rmm_seen_rmm_client_id` int(11) NOT NULL,
`rmm_seen_client_id` int(11) NOT NULL DEFAULT 0,
`rmm_seen_asset_id` int(11) NOT NULL DEFAULT 0,
`rmm_seen_mac` varchar(12) NOT NULL,
`rmm_seen_hostname` varchar(200) NOT NULL DEFAULT '',
`rmm_seen_ip` varchar(100) NOT NULL DEFAULT '',
`rmm_seen_via_mac` varchar(12) NOT NULL DEFAULT '',
`rmm_seen_port` varchar(50) NOT NULL DEFAULT '',
`rmm_seen_wired` tinyint(1) NOT NULL DEFAULT 1,
`rmm_seen_ssid` varchar(100) NOT NULL DEFAULT '',
`rmm_seen_network` varchar(200) NOT NULL DEFAULT '',
`rmm_seen_vlan` int(11) NOT NULL DEFAULT 0,
`rmm_seen_at` datetime DEFAULT NULL,
`rmm_seen_created_at` datetime NOT NULL DEFAULT current_timestamp(),
PRIMARY KEY (`rmm_seen_id`),
UNIQUE KEY `rmm_seen_device` (`rmm_seen_provider_id`, `rmm_seen_rmm_client_id`, `rmm_seen_mac`),
KEY `rmm_seen_asset_id` (`rmm_seen_asset_id`),
KEY `rmm_seen_via` (`rmm_seen_provider_id`, `rmm_seen_via_mac`),
KEY `rmm_seen_client_id` (`rmm_seen_client_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci");

View File

@@ -157,6 +157,9 @@ if (isset($_GET['delete_rmm_provider'])) {
if (rmmNetworksReady()) {
mysqli_query($mysqli, "DELETE FROM rmm_networks WHERE rmm_network_provider_id = $provider_id");
}
if (rmmSeenReady()) {
mysqli_query($mysqli, "DELETE FROM rmm_seen WHERE rmm_seen_provider_id = $provider_id");
}
if (rmmAlertsReady()) {
mysqli_query($mysqli, "DELETE FROM rmm_alerts WHERE rmm_alert_provider_id = $provider_id");
}

View File

@@ -508,12 +508,59 @@ if (mysqli_num_rows($sql) == 0) {
<?php if ($rmm_elsewhere) { ?>
<div class="small text-warning-emphasis mt-2"><i class="fas fa-fw fa-exclamation-triangle me-1"></i><?= escapeHtml($rmm_each_name) ?> has it under <?= escapeHtml($rmm_each['rmm_client_name']) ?>, which is linked to another client.</div>
<?php } ?>
<?php // A network platform's switch or access point - the client's assets seen on it lately (functions/rmm_network.php)
$rmm_via = rmmFamily($rmm_each) === 'network' ? rmmSeenVia($rmm_each) : [];
if ($rmm_via) {
$rmm_via_wired = count(array_filter($rmm_via, function ($row) { return intval($row['rmm_seen_wired']) === 1; })); ?>
<div class="mt-3" data-rmm-seen-via="<?= count($rmm_via) ?>">
<div class="small fw-semibold mb-1"><?= $rmm_via_wired === count($rmm_via) ? 'Plugged in here' : ($rmm_via_wired ? 'Plugged in and on its Wi-Fi' : 'On its Wi-Fi') ?> <span class="text-body-secondary fw-normal">&middot; <?= count($rmm_via) ?></span></div>
<ul class="list-unstyled small mb-0">
<?php foreach (array_slice($rmm_via, 0, 12) as $via_row) { ?>
<li class="d-flex gap-2<?= intval($via_row['now']) ? '' : ' text-body-secondary' ?>" title="<?= intval($via_row['now']) ? 'There now' : 'Last seen there ' . escapeHtml(timeAgo($via_row['rmm_seen_at'])) ?>">
<span class="text-body-secondary text-nowrap text-truncate flex-shrink-0" style="width: 6rem;"><?= escapeHtml(intval($via_row['rmm_seen_wired']) || (string) $via_row['rmm_seen_ssid'] === '' ? rmmSeenPlace($via_row) : $via_row['rmm_seen_ssid']) ?></span>
<a class="text-truncate" href="asset.php?client_id=<?= intval($via_row['asset_client_id']) ?>&asset_id=<?= intval($via_row['rmm_seen_asset_id']) ?>"><?= escapeHtml($via_row['asset_name']) ?></a>
</li>
<?php } ?>
<?php if (count($rmm_via) > 12) { ?><li class="text-body-secondary">and <?= count($rmm_via) - 12 ?> more</li><?php } ?>
</ul>
</div>
<?php } ?>
<?php } ?>
<div class="small text-body-secondary mt-2" title="<?= escapeHtml((string) $rmm_each['rmm_device_synced_at']) ?>">As <?= escapeHtml($rmm_each_kind['short'] ?? $rmm_each_name) ?> said <?= escapeHtml(timeAgo($rmm_each['rmm_device_synced_at'])) ?>.</div>
</div>
</div>
<?php } ?>
<?php // Where it plugs in, as a network platform last saw it (functions/rmm_network.php)
$seen_rows = rmmSeenForAsset($asset_id);
if ($seen_rows) {
$seen = $seen_rows[0];
$seen_short = rmmKind($seen)['short'] ?? rmmProviderName($seen);
$seen_wired = intval($seen['rmm_seen_wired']) === 1;
$seen_via = (string) ($seen['via_asset_name'] ?? '') !== '' ? '<a href="asset.php?client_id=' . $client_id . '&asset_id=' . intval($seen['via_asset_id']) . '">' . escapeHtml($seen['via_asset_name']) . '</a>'
: escapeHtml((string) ($seen['via_name'] ?? '') !== '' ? $seen['via_name'] : ($seen_wired ? 'A switch' : 'An access point') . " $seen_short doesn't list"); ?>
<div class="card mb-3" data-rmm-seen="<?= intval($seen['now']) ? 'now' : 'before' ?>">
<div class="card-header">
<h3 class="card-title mb-0"><i class="fas fa-fw <?= $seen_wired ? 'fa-ethernet' : 'fa-wifi' ?> text-secondary me-2"></i>Connection</h3>
</div>
<div class="card-body">
<dl class="itflow-asset-dl mb-0">
<dt><?= $seen_wired ? 'Plugged into' : 'On' ?></dt>
<dd><?= $seen_via ?><div class="small text-body-secondary"><?= escapeHtml(rmmSeenPlace($seen)) ?></div></dd>
<?php if ((string) $seen['rmm_seen_ip'] !== '') { ?>
<dt>IP</dt>
<dd><span class="font-monospace"><?= escapeHtml($seen['rmm_seen_ip']) ?></span><button type="button" class="itflow-copy clipboardjs" title="Copy IP" data-clipboard-text="<?= escapeHtml($seen['rmm_seen_ip']) ?>"><i class="far fa-copy"></i></button></dd>
<?php } ?>
<?php if ((string) $seen['rmm_seen_network'] !== '' || intval($seen['rmm_seen_vlan'])) { ?>
<dt>Network</dt>
<dd><?= escapeHtml(trim($seen['rmm_seen_network'] . (intval($seen['rmm_seen_vlan']) ? ' · VLAN ' . intval($seen['rmm_seen_vlan']) : ''), ' ·')) ?></dd>
<?php } ?>
</dl>
<div class="small text-body-secondary mt-2" title="<?= escapeHtml((string) $seen['rmm_seen_at']) ?>"><?= intval($seen['now']) ? 'Connected now - as ' . escapeHtml(rmmProviderName($seen)) . ' said ' . escapeHtml(timeAgo($seen['rmm_seen_at'])) : 'Last seen there ' . escapeHtml(timeAgo($seen['rmm_seen_at'])) . ', by ' . escapeHtml(rmmProviderName($seen)) ?>.</div>
</div>
</div>
<?php } ?>
<?php // The desk phone it is, as the phone last told its phone system's ITFlow (functions/phone.php)
foreach (phoneDevicesForAsset($asset_id) as $phone_device) {
$phone_status = phoneDeviceStatuses()[$phone_device['phone_device_status']] ?? phoneDeviceStatuses()[''];

32
db.sql
View File

@@ -3689,6 +3689,38 @@ CREATE TABLE `rmm_providers` (
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `rmm_seen`
--
DROP TABLE IF EXISTS `rmm_seen`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8mb4 */;
CREATE TABLE `rmm_seen` (
`rmm_seen_id` int(11) NOT NULL AUTO_INCREMENT,
`rmm_seen_provider_id` int(11) NOT NULL,
`rmm_seen_rmm_client_id` int(11) NOT NULL,
`rmm_seen_client_id` int(11) NOT NULL DEFAULT 0,
`rmm_seen_asset_id` int(11) NOT NULL DEFAULT 0,
`rmm_seen_mac` varchar(12) NOT NULL,
`rmm_seen_hostname` varchar(200) NOT NULL DEFAULT '',
`rmm_seen_ip` varchar(100) NOT NULL DEFAULT '',
`rmm_seen_via_mac` varchar(12) NOT NULL DEFAULT '',
`rmm_seen_port` varchar(50) NOT NULL DEFAULT '',
`rmm_seen_wired` tinyint(1) NOT NULL DEFAULT 1,
`rmm_seen_ssid` varchar(100) NOT NULL DEFAULT '',
`rmm_seen_network` varchar(200) NOT NULL DEFAULT '',
`rmm_seen_vlan` int(11) NOT NULL DEFAULT 0,
`rmm_seen_at` datetime DEFAULT NULL,
`rmm_seen_created_at` datetime NOT NULL DEFAULT current_timestamp(),
PRIMARY KEY (`rmm_seen_id`),
UNIQUE KEY `rmm_seen_device` (`rmm_seen_provider_id`,`rmm_seen_rmm_client_id`,`rmm_seen_mac`),
KEY `rmm_seen_asset_id` (`rmm_seen_asset_id`),
KEY `rmm_seen_via` (`rmm_seen_provider_id`,`rmm_seen_via_mac`),
KEY `rmm_seen_client_id` (`rmm_seen_client_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `service_assets`
--

View File

@@ -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_networks', 'rmm_network_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'], ['rmm_seen', 'rmm_seen_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'],

View File

@@ -1000,7 +1000,7 @@ 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,
'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']));
}

View File

@@ -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']);
}

View File

@@ -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
{