Network Platforms), kinds of the RMM providers' * engine (functions/rmm.php) in the network family: a platform's sites are linked to clients, * and its gateways, switches and access points become assets kept up to date, each known by * its MAC address - so a device keeps its asset when its controller moves. * * Three ways in, one kind each: * * unifi A controller, signed in to with a local admin's user name and password - the * classic, self-hosted UniFi Network application, which can't make API keys * (POST /api/login, then /api/s//...). A UniFi OS console or UniFi OS * Server is signed in to the same way when it is one (/api/auth/login, and the * same API under /proxy/network). This API isn't documented by Ubiquiti, but * it is what UniFi's own pages use. * unifi_os A UniFi OS console, or UniFi OS Server, with an API key made under Settings > * Control Plane > Integrations - the official Network API, at * /proxy/network/integration/v1 (or /integration/v1 on a controller that has it). * unifi_cloud Every console a UI account owns - or every one of an organization's, with an * organization key - through the Site Manager API at api.ui.com and its * connector to each console's official Network API (console firmware 5.0.3 or * later). Nothing needs to reach the consoles. * * A site's id there: the site's short name (default) on a controller, its id from the Network * API on a console, and - through Site Manager - its console's and its own, as one. */ // Where the Site Manager API is defined('UNIFI_SITE_MANAGER_URL') || define('UNIFI_SITE_MANAGER_URL', 'https://api.ui.com'); /** * A console asked directly (unifi_os) has its sites' device counts asked of it, a request each, only * when it has at most this many - a console with hundreds of sites would spend its requests a minute * on counts. Its linked sites are counted as their devices come in. */ const UNIFI_COUNT_SITES_MAX = 50; /** The UniFi kinds - one for each way in. */ function rmmUnifiKinds(): array { return [ 'unifi' => rmmUnifiKind('unifi'), 'unifi_os' => rmmUnifiKind('unifi_os'), 'unifi_cloud' => rmmUnifiKind('unifi_cloud'), ]; } /** One UniFi kind, as rmmProviderKinds() describes a kind. */ function rmmUnifiKind(string $key): array { $insecure = [ 'label' => 'Accept the certificate it made for itself', 'icon' => 'fa-certificate', 'type' => 'switch', 'required' => false, 'placeholder' => '', 'help' => 'A self-hosted controller makes its own certificate, which nothing trusts - turn this on for one you run yourself. Leave it off for an address with a real certificate.', 'needed' => '', 'on' => 'its own certificate accepted', 'off' => 'its certificate checked', ]; $kind = [ 'family' => 'network', 'short' => 'UniFi', 'icon' => 'fas fa-wifi', 'seal' => true, 'device_kinds' => ['Firewall/Router' => 'Gateways', 'Switch' => 'Switches', 'Access Point' => 'Access points', 'Other' => 'Other UniFi devices'], 'attention' => ['patches_pending' => 'Firmware update available'], 'links' => ['open' => 'Open in UniFi'], 'clients' => 'rmmUnifiSites', 'devices' => 'rmmUnifiDevices', 'networks' => 'rmmUnifiNetworks', 'seen' => 'rmmUnifiSeen', 'alerts' => 'rmmUnifiAlerts', 'alert' => 'rmmUnifiAlert', 'alerts_help' => 'UniFi has no alerts to read, so ITFlow asks it every minute which devices are offline - a gateway or switch is an error, an access point or anything else a warning. A site whose gateway is offline has the one ticket, for the gateway.', 'dashboard' => 'rmmUnifiDashboard', 'docs_url' => 'https://help.ui.com/hc/en-us/articles/30076656117655', ]; if ($key === 'unifi') { return array_merge($kind, [ 'name' => 'UniFi controller (sign-in)', 'default_name' => 'UniFi Controller', 'about' => 'A self-hosted UniFi Network controller, signed in to with a local admin - its sites, and their gateways, switches and access points as assets.', 'docs_url' => '', 'fields' => [ 'api_url' => [ 'label' => 'Controller address', 'icon' => 'fa-server', 'type' => 'url', 'required' => true, 'placeholder' => 'https://unifi.example.com:8443', 'help' => 'As you open it in a browser, with its port - 8443 on a classic controller.', 'needed' => 'The controller\'s address is needed - as you open it in a browser, like https://unifi.example.com:8443.', ], 'api_key' => [ 'label' => 'User name', 'icon' => 'fa-user', 'type' => 'text', 'required' => true, 'placeholder' => 'itflow', 'help' => 'A local admin of the controller, just for ITFlow - one with view-only access is enough. Not a UI account with two-step sign-in.', 'needed' => 'The user name ITFlow signs in with is needed.', ], 'api_secret' => [ 'label' => 'Password', 'icon' => 'fa-lock', 'type' => 'secret', 'required' => true, 'placeholder' => '', 'spaces' => true, 'help' => 'Kept encrypted with this ITFlow\'s own key.', 'needed' => 'The password is needed.', ], 'insecure' => $insecure, ], 'hints' => [ 'auth' => 'check the user name and password - a local admin of the controller, not a UI account.', 'not_found' => 'is that the controller\'s address, with its port?', 'not_json' => 'is that the controller\'s address, with its port?', 'certificate' => ' - a controller with a certificate it made for itself needs "Accept the certificate it made for itself" on.', ], ]); } if ($key === 'unifi_os') { return array_merge($kind, [ 'name' => 'UniFi console (API key)', 'default_name' => 'UniFi Console', 'about' => 'A UniFi OS console or UniFi OS Server, with an API key - the official Network API.', 'fields' => [ 'api_url' => [ 'label' => 'Console address', 'icon' => 'fa-server', 'type' => 'url', 'required' => true, 'placeholder' => 'https://192.168.1.1', 'help' => 'As you open it in a browser - with its port on UniFi OS Server, usually 11443. ITFlow needs to be able to reach it.', 'needed' => 'The console\'s address is needed - as you open it in a browser.', ], 'api_key' => [ 'label' => 'API key', 'icon' => 'fa-key', 'type' => 'secret', 'required' => true, 'placeholder' => '', 'help' => 'In UniFi Network: Settings > Control Plane > Integrations. Kept encrypted with this ITFlow\'s own key.', 'needed' => 'The API key is needed - make one in UniFi Network under Settings > Control Plane > Integrations.', ], 'insecure' => $insecure, ], 'hints' => [ 'auth' => 'check the key, made in UniFi Network under Settings > Control Plane > Integrations.', 'not_found' => 'is that the console\'s address? A classic controller has no API keys - add it as a UniFi controller (sign-in).', 'not_json' => 'is that the console\'s address?', 'certificate' => ' - a console with a certificate it made for itself needs "Accept the certificate it made for itself" on.', ], ]); } return array_merge($kind, [ 'name' => 'UniFi Site Manager (cloud)', 'default_name' => 'UniFi Site Manager', 'about' => 'Every UniFi console your UI account or organization has, through api.ui.com - nothing needs to reach them.', 'fields' => [ 'api_key' => [ 'label' => 'Site Manager API key', 'icon' => 'fa-key', 'type' => 'secret', 'required' => true, 'placeholder' => '', 'help' => 'At unifi.ui.com, under API. An organization\'s key reaches every console in it; anyone else\'s reaches the consoles they own. Consoles need firmware 5.0.3 or later. Kept encrypted with this ITFlow\'s own key.', 'needed' => 'The Site Manager API key is needed - make one at unifi.ui.com, under API.', ], ], 'hints' => [ 'auth' => 'check the key, made at unifi.ui.com under API - and, for a console someone else owns, that it is an organization key.', 'not_found' => 'that console may need firmware 5.0.3 or later, or have no Network application.', 'not_json' => '', 'rate' => 'Site Manager lets each console be asked 100 times a minute.', ], ]); } /* * ------------------------------------------------------------------ Asking UniFi */ /** The options every request of a platform takes - its own certificate accepted, when it says so. */ function rmmUnifiOpts(array $provider): array { return ['insecure' => intval($provider['rmm_provider_insecure'] ?? 0) === 1]; } /** * Signed in to a controller (unifi) - ['ok', 'cookie', 'prefix', 'csrf', 'error']. A classic * controller signs in at /api/login; a UniFi OS one answers that with 404 and signs in at * /api/auth/login, its Network API under /proxy/network. Kept for the request; $again signs in * afresh, for a session that ended. */ function rmmUnifiSession(array $provider, bool $again = false): array { static $sessions = []; $id = intval($provider['rmm_provider_id'] ?? 0); if (!$again && isset($sessions[$id])) { return $sessions[$id]; } $base = rmmUrlClean($provider['rmm_provider_api_url'] ?? ''); $user = trim((string) ($provider['rmm_provider_api_key'] ?? '')); $password = rmmSecret($provider, 'api_secret'); $name = rmmProviderName($provider); if ($base === '' || $user === '' || $password === '') { return ['ok' => false, 'cookie' => '', 'prefix' => '', 'csrf' => '', 'error' => 'Its address, user name and password aren\'t set' . ($password === '' && (string) ($provider['rmm_provider_api_secret'] ?? '') !== '' ? ' - its password can\'t be read, so type it again' : '') . '.']; } $body = ['username' => $user, 'password' => $password, 'remember' => false]; $prefix = ''; $answer = rmmHttp($provider, 'POST', "$base/api/login", [], $body, 30, rmmUnifiOpts($provider)); if ($answer['code'] === 404) { $prefix = '/proxy/network'; $answer = rmmHttp($provider, 'POST', "$base/api/auth/login", [], $body, 30, rmmUnifiOpts($provider)); } if (in_array($answer['code'], [400, 401, 403], true)) { $said = is_array($answer['json']) ? (string) ($answer['json']['meta']['msg'] ?? $answer['json']['message'] ?? '') : ''; $why = str_contains(strtolower($said), 'ubic_2fa') || str_contains(strtolower($said), '2fa') ? ' - that account has two-step sign-in, so use a local admin without it' : ' - check the user name and password: a local admin of the controller, not a UI account'; return $sessions[$id] = ['ok' => false, 'cookie' => '', 'prefix' => $prefix, 'csrf' => '', 'error' => "$name turned the sign-in away (HTTP {$answer['code']})$why."]; } if (!$answer['ok']) { return $sessions[$id] = ['ok' => false, 'cookie' => '', 'prefix' => $prefix, 'csrf' => '', 'error' => $answer['error']]; } $cookies = array_filter($answer['headers']['cookies'] ?? [], function ($cookie) { return preg_match('/^(unifises|TOKEN|csrf_token)=/', $cookie) === 1; }); if (!$cookies) { return $sessions[$id] = ['ok' => false, 'cookie' => '', 'prefix' => $prefix, 'csrf' => '', 'error' => "$name answered the sign-in, but didn't sign ITFlow in - is that a UniFi controller's address?"]; } return $sessions[$id] = ['ok' => true, 'cookie' => implode('; ', $cookies), 'prefix' => $prefix, 'csrf' => (string) ($answer['headers']['x-csrf-token'] ?? ''), 'error' => '']; } /** * Ask a controller (unifi) - GET /api/: ['ok', 'data', 'error', 'code']. Its answers are * {meta: {rc}, data: [...]}; a session that ended is signed in again, once. */ function rmmUnifiController(array $provider, string $path, int $timeout = 60): array { $base = rmmUrlClean($provider['rmm_provider_api_url'] ?? ''); $session = rmmUnifiSession($provider); for ($try = 0; $try < 2; $try++) { if (!$session['ok']) { return ['ok' => false, 'data' => [], 'error' => $session['error'], 'code' => 0]; } $headers = $session['csrf'] !== '' ? ['X-CSRF-Token: ' . $session['csrf']] : []; $answer = rmmHttp($provider, 'GET', $base . $session['prefix'] . '/api/' . ltrim($path, '/'), $headers, null, $timeout, rmmUnifiOpts($provider) + ['cookie' => $session['cookie']]); if ($answer['code'] === 401 && $try === 0) { $session = rmmUnifiSession($provider, true); continue; } break; } if (!$answer['ok']) { return ['ok' => false, 'data' => [], 'error' => $answer['error'], 'code' => $answer['code']]; } $rc = (string) ($answer['json']['meta']['rc'] ?? ''); if ($rc !== 'ok' || !rmmIsList($answer['json']['data'] ?? null)) { $said = rmmText($answer['json']['meta']['msg'] ?? '', 200); return ['ok' => false, 'data' => [], 'error' => rmmProviderName($provider) . ' answered, but not with what was asked for' . ($said !== '' ? " ($said)" : '') . ' - nothing was changed', 'code' => $answer['code']]; } return ['ok' => true, 'data' => $answer['json']['data'], 'error' => '', 'code' => $answer['code']]; } /** * Where a console's official Network API is (unifi_os) - /proxy/network/integration on UniFi OS, * /integration on a controller that has it. ['ok', 'base', 'version', 'error'], found once a request. */ function rmmUnifiNetworkApi(array $provider): array { static $found = []; $id = intval($provider['rmm_provider_id'] ?? 0); if (isset($found[$id])) { return $found[$id]; } $base = rmmUrlClean($provider['rmm_provider_api_url'] ?? ''); $key = rmmSecret($provider, 'api_key'); if ($base === '' || $key === '') { return ['ok' => false, 'base' => '', 'version' => '', 'error' => 'Its address and API key aren\'t set' . ($key === '' && (string) ($provider['rmm_provider_api_key'] ?? '') !== '' ? ' - its key can\'t be read, so paste it again' : '') . '.']; } $first = null; foreach (['/proxy/network/integration', '/integration'] as $path) { $answer = rmmHttp($provider, 'GET', "$base$path/v1/info", ['X-API-KEY: ' . $key], null, 30, rmmUnifiOpts($provider)); if ($answer['ok']) { return $found[$id] = ['ok' => true, 'base' => "$base$path", 'version' => rmmText($answer['json']['applicationVersion'] ?? '', 50), 'error' => '']; } $first = $first ?? $answer; if ($answer['code'] !== 404) { break; } } return $found[$id] = ['ok' => false, 'base' => '', 'version' => '', 'error' => $first['error']]; } /** * Ask the official Network API - of a console (unifi_os) by its address, or of one of the account's * consoles through Site Manager's connector (unifi_cloud, $console its id). A list is read page by * page: ['ok', 'data' (every item, or the one object), 'total', 'error', 'code']. */ function rmmUnifiNetwork(array $provider, string $path, array $query = [], string $console = '', bool $list = true): array { if ($provider['rmm_provider_kind'] === 'unifi_cloud') { $key = rmmSecret($provider, 'api_key'); $base = rtrim(UNIFI_SITE_MANAGER_URL, '/') . '/v1/connector/consoles/' . rawurlencode($console) . '/proxy/network/integration'; } else { $api = rmmUnifiNetworkApi($provider); if (!$api['ok']) { return ['ok' => false, 'data' => [], 'total' => 0, 'error' => $api['error'], 'code' => 0]; } $key = rmmSecret($provider, 'api_key'); $base = $api['base']; } $items = []; $offset = 0; for ($page = 0; $page < 50; $page++) { $ask = $list ? $query + ['offset' => $offset, 'limit' => $query['limit'] ?? 200] : $query; $answer = rmmHttp($provider, 'GET', $base . '/v1/' . ltrim($path, '/') . ($ask ? '?' . http_build_query($ask, '', '&') : ''), ['X-API-KEY: ' . $key], null, 30, rmmUnifiOpts($provider)); if (!$answer['ok']) { return ['ok' => false, 'data' => [], 'total' => 0, 'error' => $answer['error'], 'code' => $answer['code']]; } if (!$list) { return ['ok' => true, 'data' => $answer['json'], 'total' => 1, 'error' => '', 'code' => $answer['code']]; } if (!rmmIsList($answer['json']['data'] ?? null)) { return ['ok' => false, 'data' => [], 'total' => 0, 'error' => rmmProviderName($provider) . ' answered, but not with a list - nothing was changed', 'code' => $answer['code']]; } $items = array_merge($items, $answer['json']['data']); $total = intval($answer['json']['totalCount'] ?? count($items)); $offset += count($answer['json']['data']); if (!$answer['json']['data'] || $offset >= $total || !empty($query['limit'])) { return ['ok' => true, 'data' => $items, 'total' => $total, 'error' => '', 'code' => $answer['code']]; } } return ['ok' => true, 'data' => $items, 'total' => count($items), 'error' => '', 'code' => 200]; } /** * The consoles a Site Manager key reaches (unifi_cloud) - ['ok', 'consoles' => [id => name], 'down' => [id => since], 'skipped', 'error']. * down - the ones Site Manager says aren't connected, with when that changed. Asked once a request. */ function rmmUnifiConsoles(array $provider): array { static $asked = []; $id = intval($provider['rmm_provider_id'] ?? 0); if (isset($asked[$id]) && $asked[$id]['ok']) { return $asked[$id]; } return $asked[$id] = rmmUnifiConsolesAsk($provider); } /** The consoles, asked of Site Manager - as rmmUnifiConsoles() gives them. */ function rmmUnifiConsolesAsk(array $provider): array { $key = rmmSecret($provider, 'api_key'); if ($key === '') { return ['ok' => false, 'consoles' => [], 'down' => [], 'skipped' => 0, 'error' => 'Its Site Manager API key isn\'t set' . ((string) ($provider['rmm_provider_api_key'] ?? '') !== '' ? ' - it can\'t be read, so paste it again' : '') . '.']; } $consoles = []; $down = []; $skipped = 0; $next = ''; for ($page = 0; $page < 50; $page++) { $query = ['pageSize' => 200] + ($next !== '' ? ['nextToken' => $next] : []); $answer = rmmHttp($provider, 'GET', rtrim(UNIFI_SITE_MANAGER_URL, '/') . '/v1/hosts?' . http_build_query($query, '', '&'), ['X-API-KEY: ' . $key]); if (!$answer['ok']) { return ['ok' => false, 'consoles' => [], 'down' => [], 'skipped' => 0, 'error' => $answer['error']]; } if (!rmmIsList($answer['json']['data'] ?? null)) { return ['ok' => false, 'consoles' => [], 'down' => [], 'skipped' => 0, 'error' => 'Site Manager answered, but not with a list of consoles - nothing was changed']; } foreach ($answer['json']['data'] as $host) { if (!is_array($host) || !isset($host['id'])) { continue; } // Only UniFi OS consoles have the connector - a self-hosted Network server doesn't if (strtolower((string) ($host['type'] ?? '')) !== 'console') { $skipped++; continue; } $state = is_array($host['reportedState'] ?? null) ? $host['reportedState'] : []; $name = rmmText($state['name'] ?? $state['hostname'] ?? '', 150); $consoles[(string) $host['id']] = $name !== '' ? $name : 'Console ' . substr((string) $host['id'], 0, 8); if (isset($state['state']) && strtolower((string) $state['state']) !== 'connected') { $since = strtotime((string) ($host['lastConnectionStateChange'] ?? '')); $down[(string) $host['id']] = $since ?: time(); } } $next = (string) ($answer['json']['nextToken'] ?? ''); if ($next === '') { break; } } return ['ok' => true, 'consoles' => $consoles, 'down' => $down, 'skipped' => $skipped, 'error' => '']; } /* * ------------------------------------------------------------------ Its sites and devices */ /** What a Site Manager site's id stands for - remote id => [console, site] - from the last listing this request. */ function rmmUnifiCloudSites(?array $set = null): array { static $sites = []; if ($set !== null) { $sites = $set + $sites; } return $sites; } /** A controller or console with only its Default site goes by the platform's name instead. */ function rmmUnifiLoneDefault(array $provider, array $sites): array { if (count($sites) === 1 && strtolower($sites[0]['name']) === 'default') { $sites[0]['name'] = rmmText($provider['rmm_provider_name'] ?? '', 200) ?: $sites[0]['name']; } return $sites; } /** A platform's sites - ['ok', 'clients' => [id, name, sites, devices], 'error', 'about'], as a kind's clients function gives them. */ function rmmUnifiSites(array $provider): array { $sites = []; $kind = (string) $provider['rmm_provider_kind']; if ($kind === 'unifi') { // stat/sites has the device counts; an admin limited to some sites may only have self/sites $answer = rmmUnifiController($provider, 'stat/sites'); if (!$answer['ok'] && in_array($answer['code'], [401, 403], true)) { $answer = rmmUnifiController($provider, 'self/sites'); } if (!$answer['ok']) { return ['ok' => false, 'clients' => [], 'error' => $answer['error']]; } foreach ($answer['data'] as $site) { if (!is_array($site) || !preg_match('/^[A-Za-z0-9_.-]{1,100}$/', (string) ($site['name'] ?? ''))) { continue; } $devices = intval($site['device_count'] ?? 0); if (!$devices && is_array($site['health'] ?? null)) { foreach ($site['health'] as $health) { if (is_array($health) && in_array($health['subsystem'] ?? '', ['wlan', 'lan', 'wan'], true)) { $devices += intval($health['num_adopted'] ?? 0); } } } $label = rmmText($site['desc'] ?? '', 200); $sites[] = ['id' => (string) $site['name'], 'name' => $label !== '' ? $label : (string) $site['name'], 'sites' => 1, 'devices' => $devices]; } $sites = rmmUnifiLoneDefault($provider, $sites); $session = rmmUnifiSession($provider); return ['ok' => true, 'clients' => $sites, 'error' => '', 'about' => $session['prefix'] !== '' ? 'It is a UniFi OS console, signed in to with a user name.' : 'It is a classic controller, signed in to with a user name.']; } if ($kind === 'unifi_os') { $answer = rmmUnifiNetwork($provider, 'sites'); if (!$answer['ok']) { return ['ok' => false, 'clients' => [], 'error' => $answer['error']]; } foreach ($answer['data'] as $site) { if (!is_array($site) || !preg_match('/^[A-Za-z0-9-]{1,100}$/', (string) ($site['id'] ?? ''))) { continue; } // Its device count is a request of its own - asked for a console with few sites, while the sync's listing has time; else the count kept stays $count = count($answer['data']) > UNIFI_COUNT_SITES_MAX || rmmPastDeadline() ? ['ok' => false] : rmmUnifiNetwork($provider, 'sites/' . $site['id'] . '/devices', ['limit' => 1]); $label = rmmText($site['name'] ?? '', 200); $sites[] = ['id' => (string) $site['id'], 'name' => $label !== '' ? $label : (string) ($site['internalReference'] ?? $site['id']), 'sites' => 1, 'devices' => $count['ok'] ? $count['total'] : null]; } $sites = rmmUnifiLoneDefault($provider, $sites); $api = rmmUnifiNetworkApi($provider); return ['ok' => true, 'clients' => $sites, 'error' => '', 'about' => 'Its Network API' . ($api['version'] !== '' ? ' is version ' . $api['version'] : ' answered') . '.']; } /* * Through Site Manager - each console's sites, named with the console when it has more than one. Site * Manager's own list of sites (rmmUnifiSiteManagerSites()) has every site's device count, in a request or * two, so no site is asked for its count. A console is asked for its sites through its connector - which * allows 100 requests a minute a console - only when that list says it has sites ITFlow doesn't know: a * console with just its Default site, which ITFlow has already, isn't asked at all. Past the sync's * listing time (rmmDeadline()), the consoles not asked yet are asked next sync, and their sites stay. */ $consoles = rmmUnifiConsoles($provider); if (!$consoles['ok']) { return ['ok' => false, 'clients' => [], 'error' => $consoles['error']]; } $listing = rmmUnifiSiteManagerSites($provider); $known = rmmUnifiKnownSites($provider); $map = []; $unreached = []; $left = 0; foreach ($consoles['consoles'] as $console => $console_name) { $key = substr(md5((string) $console), 0, 16); $listed = $listing['ok'] ? ($listing['sites'][$console] ?? []) : null; $have = $known[$key] ?? []; // Just its Default site, which ITFlow has - nothing to ask the console if ($listed !== null && count($listed) === 1 && isset($listed['default']) && count($have) === 1) { $id = (string) array_key_first($have); $map[$id] = [(string) $console, (string) substr($id, 17)]; $label = rmmText($listed['default']['desc'], 100); $sites[] = ['id' => $id, 'name' => $label === '' || strtolower($label) === 'default' ? $console_name : $label, 'sites' => 1, 'devices' => $listed['default']['devices']]; continue; } if (rmmPastDeadline()) { $left++; continue; } $answer = rmmUnifiNetwork($provider, 'sites', [], $console); if (!$answer['ok']) { $unreached[] = $console_name; continue; } $many = count($answer['data']) > 1; foreach ($answer['data'] as $site) { if (!is_array($site) || !preg_match('/^[A-Za-z0-9-]{1,60}$/', (string) ($site['id'] ?? ''))) { continue; } $id = "$key." . $site['id']; $map[$id] = [$console, (string) $site['id']]; // A console's one Default site is the console; the rest go by their names, with the console's when it has more $label = rmmText($site['name'] ?? '', 100); $plain = $label === '' || strtolower($label) === 'default'; $reference = (string) ($site['internalReference'] ?? ''); $sites[] = ['id' => $id, 'name' => $plain ? $console_name . ($many ? ' (Default)' : '') : ($many ? "$label ($console_name)" : $label), 'sites' => 1, 'devices' => $listed[$reference]['devices'] ?? null]; } } rmmUnifiCloudSites($map); $partial = $left ? "Listed the sites of " . number_format(count($consoles['consoles']) - $left) . ' of ' . number_format(count($consoles['consoles'])) . ' consoles - the other ' . number_format($left) . ' next sync' : ''; if ($left && !$sites && !$unreached) { return ['ok' => true, 'clients' => [], 'error' => '', 'partial' => $partial, 'about' => '']; } if ($unreached && !$sites) { return ['ok' => false, 'clients' => [], 'error' => 'Site Manager answered, but none of its consoles did through its connector (' . implode(', ', array_slice($unreached, 0, 5)) . ') - consoles need firmware 5.0.3 or later and the Network application']; } $about = count($consoles['consoles']) . ' console' . (count($consoles['consoles']) === 1 ? '' : 's') . ' through Site Manager'; if ($unreached) { $about .= ' - ' . count($unreached) . ' didn\'t answer through its connector: ' . implode(', ', array_slice($unreached, 0, 5)); } if ($consoles['skipped']) { $about .= '; ' . $consoles['skipped'] . ' self-hosted controller' . ($consoles['skipped'] === 1 ? '' : 's') . ' left out - add ' . ($consoles['skipped'] === 1 ? 'it' : 'them') . ' as a UniFi controller (sign-in)'; } return ['ok' => true, 'clients' => $sites, 'error' => '', 'about' => "It reaches $about.", 'partial' => $partial]; } /** * Every site Site Manager lists, with its device count - ['ok', 'sites' => [console id => [short name => * ['desc', 'devices']]], 'error']. A site's short name there is its internalReference in the Network API - * "default" for a console's first. Not ok when Site Manager doesn't list them: each console is asked. */ function rmmUnifiSiteManagerSites(array $provider): array { $key = rmmSecret($provider, 'api_key'); $sites = []; $next = ''; for ($page = 0; $page < 50; $page++) { $query = ['pageSize' => 500] + ($next !== '' ? ['nextToken' => $next] : []); $answer = rmmHttp($provider, 'GET', rtrim(UNIFI_SITE_MANAGER_URL, '/') . '/v1/sites?' . http_build_query($query, '', '&'), ['X-API-KEY: ' . $key]); if (!$answer['ok'] || !rmmIsList($answer['json']['data'] ?? null)) { return ['ok' => false, 'sites' => [], 'error' => $answer['ok'] ? 'Site Manager answered, but not with a list of sites' : $answer['error']]; } foreach ($answer['json']['data'] as $site) { $host = is_array($site) ? (string) ($site['hostId'] ?? '') : ''; $name = is_array($site['meta'] ?? null) ? (string) ($site['meta']['name'] ?? '') : ''; if ($host === '' || $name === '') { continue; } $total = $site['statistics']['counts']['totalDevice'] ?? null; $sites[$host][$name] = ['desc' => (string) ($site['meta']['desc'] ?? ''), 'devices' => is_numeric($total) ? intval($total) : null]; } $next = (string) ($answer['json']['nextToken'] ?? ''); if ($next === '') { break; } } return ['ok' => true, 'sites' => $sites, 'error' => '']; } /** The sites ITFlow has of a Site Manager platform, still listed - [the console's part of their ids => [id => name]]. */ function rmmUnifiKnownSites(array $provider): array { global $mysqli; $known = []; $sql = mysqli_query($mysqli, "SELECT rmm_client_remote_id, rmm_client_name FROM rmm_clients WHERE rmm_client_provider_id = " . intval($provider['rmm_provider_id'] ?? 0) . " AND rmm_client_removed_at IS NULL"); while ($sql && ($row = mysqli_fetch_row($sql))) { if (preg_match('/^([a-f0-9]{16})\.[A-Za-z0-9-]{1,60}$/', (string) $row[0], $m)) { $known[$m[1]][(string) $row[0]] = (string) $row[1]; } } return $known; } /** One site's devices - ['ok', 'devices', 'error'], each as rmmDeviceSave() takes it. */ function rmmUnifiDevices(array $provider, string $site): array { $kind = (string) $provider['rmm_provider_kind']; $devices = []; if ($kind === 'unifi') { $answer = rmmUnifiController($provider, 's/' . rawurlencode($site) . '/stat/device'); 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); } } return ['ok' => true, 'devices' => $devices, 'error' => '']; } $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']]; } rmmUnifiSiteDevices($provider, $site, $answer['data']); foreach ($answer['data'] as $device) { if (is_array($device) && rmmMac($device['macAddress'] ?? '') !== '') { $devices[] = rmmUnifiNetworkDevice($device); } } 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])) { // Its id is its console's, hashed, and its own - the consoles list says which console that is [$key, $site_id] = array_pad(explode('.', $site, 2), 2, ''); $consoles = preg_match('/^[a-f0-9]{16}$/', $key) && preg_match('/^[A-Za-z0-9-]{1,60}$/', $site_id) ? rmmUnifiConsoles($provider) : ['ok' => false, 'consoles' => []]; foreach ($consoles['consoles'] as $console => $console_name) { if (substr(md5((string) $console), 0, 16) === $key) { rmmUnifiCloudSites([$site => [(string) $console, $site_id]]); } } $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 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' => '']; } /* * ------------------------------------------------------------------ Offline alerts * * UniFi has no alerts the API reads, so its kinds make them: a device of a linked site that is * offline is an alert, until it is online again. One is "off::" - when it went offline, * by the controller's last_seen, or when ITFlow first saw it offline - and stays that while it is * open, so the same device going offline again is a new alert on the same ticket (about offline). */ /** What the last look at a platform's sites found - [devices' statuses by MAC, sites asked: rmm_client_id => bool]. $set keeps it. */ function rmmUnifiAlertLook(array $provider, ?array $set = null): array { static $looks = []; $id = intval($provider['rmm_provider_id'] ?? 0); if ($set !== null) { $looks[$id] = $set; } return $looks[$id] ?? [[], []]; } /** An offline device as an alert - $message what it says, the device's name going offline when it is ''. */ function rmmUnifiAlertShape(string $remote_id, array $device, ?string $cleared_at, string $message = ''): array { $type = (string) ($device['asset']['type'] ?? ''); $onset = explode(':', $remote_id)[2] ?? ''; return [ 'remote_id' => $remote_id, 'device_remote_id' => (string) $device['remote_id'], 'type' => 'offline', 'about' => 'offline', 'severity' => in_array($type, ['Firewall/Router', 'Switch'], true) ? 'error' : 'warning', 'message' => $message !== '' ? $message : rmmText($device['hostname'] ?? '', 200) . ' went offline', 'raised_at' => ctype_digit($onset) ? date('Y-m-d H:i:s', intval($onset)) : null, 'snoozed' => false, 'cleared_at' => $cleared_at, ]; } /** The id of the offline alert a device has open - or a new one, from when it went offline. */ function rmmUnifiAlertId(int $provider_id, string $mac, int $since): string { global $mysqli; $open = mysqli_fetch_row(mysqli_query($mysqli, "SELECT rmm_alert_remote_id FROM rmm_alerts JOIN rmm_devices ON rmm_device_id = rmm_alert_device_id WHERE rmm_alert_provider_id = $provider_id AND rmm_device_remote_id = '" . escapeSql($mac) . "' AND rmm_alert_about = 'offline' AND rmm_alert_cleared_at IS NULL ORDER BY rmm_alert_id DESC LIMIT 1")); return $open ? (string) $open[0] : "off:$mac:$since"; } /** * The devices of a platform's linked sites that are offline now, as alerts (functions/rmm.php, Alerts), * asked of UniFi a site at a time. A site whose gateway is offline has the one alert, on the gateway - * the rest are offline because of it. Through Site Manager, a console it says isn't connected can't be * asked: its site has an alert on its gateway, from what the last sync brought in. */ function rmmUnifiAlerts(array $provider): array { global $mysqli; $provider_id = intval($provider['rmm_provider_id']); $cloud = $provider['rmm_provider_kind'] === 'unifi_cloud'; $alerts = []; $statuses = []; $asked = []; $errors = []; foreach (rmmLinkedClients($provider_id) as $rmm_client) { if ($rmm_client['client_archived_at'] !== null) { continue; } $rmm_client_id = intval($rmm_client['rmm_client_id']); $answer = rmmUnifiDevices($provider, (string) $rmm_client['rmm_client_remote_id']); $asked[$rmm_client_id] = $answer['ok']; if (!$answer['ok']) { // A console Site Manager says is offline - the alert goes on its gateway, as ITFlow has it $where = $cloud ? rmmUnifiSiteWhere($provider, (string) $rmm_client['rmm_client_remote_id']) : null; $consoles = $where ? rmmUnifiConsoles($provider) : ['down' => [], 'consoles' => []]; if ($where && isset($consoles['down'][$where[0]])) { $gateway_type = escapeSql(rmmProviderAssetTypes($provider)['Firewall/Router'] ?? 'Firewall/Router'); $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT rmm_device_remote_id, rmm_device_hostname, asset_type FROM rmm_devices LEFT JOIN assets ON asset_id = rmm_device_asset_id AND rmm_device_asset_id > 0 WHERE rmm_device_provider_id = $provider_id AND rmm_device_rmm_client_id = $rmm_client_id AND rmm_device_removed_at IS NULL ORDER BY asset_type = '$gateway_type' DESC, rmm_device_hostname LIMIT 1")); if ($row) { $mac = (string) $row['rmm_device_remote_id']; $console_name = $consoles['consoles'][$where[0]] ?? $row['rmm_device_hostname']; $alerts[] = rmmUnifiAlertShape(rmmUnifiAlertId($provider_id, $mac, intval($consoles['down'][$where[0]])), ['remote_id' => $mac, 'hostname' => $row['rmm_device_hostname'], 'asset' => ['type' => 'Firewall/Router']], null, "$console_name went offline - Site Manager can't reach it"); continue; } } $errors[] = $rmm_client['rmm_client_name'] . ': ' . $answer['error']; continue; } $offline = []; foreach ($answer['devices'] as $device) { $statuses[(string) $device['remote_id']] = ['status' => (string) $device['status'], 'device' => $device]; if ($device['status'] === 'offline') { $offline[] = $device; } } $gateways = array_values(array_filter($offline, function ($device) { return ($device['asset']['type'] ?? '') === 'Firewall/Router'; })); foreach ($gateways ?: $offline as $device) { $mac = (string) $device['remote_id']; $since = !empty($device['last_seen_at']) ? intval(strtotime($device['last_seen_at'])) : time(); $more = $gateways ? count($offline) - count($gateways) : 0; $alerts[] = rmmUnifiAlertShape(rmmUnifiAlertId($provider_id, $mac, $since), $device, null, $more ? rmmText($device['hostname'] ?? '', 200) . " went offline, and $more more of the site's devices with it" : ''); } } rmmUnifiAlertLook($provider, [$statuses, $asked]); if ($errors && !$statuses && !$alerts) { return ['ok' => false, 'alerts' => [], 'error' => $errors[0]]; } return ['ok' => true, 'alerts' => $alerts, 'error' => '']; } /** * One offline alert, by its id - cleared once its device is online again, null once UniFi no longer * has the device or its site isn't linked. A device of a site that couldn't be asked is still offline. */ function rmmUnifiAlert(array $provider, string $remote_id): array { global $mysqli; $mac = explode(':', $remote_id)[1] ?? ''; [$statuses, $asked] = rmmUnifiAlertLook($provider); if (isset($statuses[$mac])) { return ['ok' => true, 'alert' => rmmUnifiAlertShape($remote_id, $statuses[$mac]['device'], $statuses[$mac]['status'] === 'offline' ? null : date('Y-m-d H:i:s')), 'error' => '']; } $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT rmm_device_rmm_client_id, rmm_device_hostname, rmm_device_remote_id FROM rmm_devices WHERE rmm_device_provider_id = " . intval($provider['rmm_provider_id']) . " AND rmm_device_remote_id = '" . escapeSql($mac) . "' LIMIT 1")); if ($row && isset($asked[intval($row['rmm_device_rmm_client_id'])]) && !$asked[intval($row['rmm_device_rmm_client_id'])]) { return ['ok' => true, 'alert' => rmmUnifiAlertShape($remote_id, ['remote_id' => $mac, 'hostname' => $row['rmm_device_hostname']], null), 'error' => '']; } return ['ok' => true, 'alert' => null, 'error' => '']; } /** A controller's device (stat/device) as a device. */ function rmmUnifiControllerDevice(array $device): array { $mac = rmmMac($device['mac'] ?? ''); $type = strtolower((string) ($device['type'] ?? '')); $model = rmmUnifiModelName((string) ($device['model'] ?? '')); $firmware = rmmText($device['version'] ?? '', 100); // 1 connected, 4 upgrading and 5 provisioning are up; 0 disconnected, 6 heartbeat missed, 10 and 11 isolated are down $state = intval($device['state'] ?? -1); $status = in_array($state, [1, 4, 5], true) ? 'online' : (in_array($state, [0, 6, 10, 11], true) ? 'offline' : ''); $uptime = intval($device['uptime'] ?? 0); $gateway = in_array($type, ['ugw', 'udm', 'uxg'], true); $name = rmmText($device['name'] ?? '', 200); $ip = rmmText($device['ip'] ?? '', 100); return [ 'remote_id' => $mac, 'mac' => $mac, 'hostname' => $name !== '' ? $name : trim($model . ' ' . strtoupper(substr($mac, -6))), 'site' => '', 'role' => '', 'platform' => 'unifi', 'os' => $firmware, 'status' => $status, 'last_seen_at' => rmmTime($device['last_seen'] ?? null), 'boot_at' => $status === 'online' && $uptime > 0 ? date('Y-m-d H:i:s', time() - $uptime) : null, 'public_ip' => $gateway ? (string) ($device['wan1']['ip'] ?? '') : '', 'local_ips' => $ip, 'patches_pending' => !empty($device['upgradable']), 'agent_version' => '', 'asset' => [ 'type' => $gateway ? 'Firewall/Router' : ($type === 'usw' ? 'Switch' : (in_array($type, ['uap', 'ubb'], true) ? 'Access Point' : 'Other')), 'make' => 'Ubiquiti', 'model' => $model, 'serial' => (string) ($device['serial'] ?? ''), 'os' => $firmware, 'ip' => $ip, 'mac' => $mac, ], ]; } /** The official Network API's device (sites/{id}/devices) as a device. */ function rmmUnifiNetworkDevice(array $device): array { $mac = rmmMac($device['macAddress'] ?? ''); $features = array_map('strval', (array) ($device['features'] ?? [])); $state = strtoupper((string) ($device['state'] ?? '')); $status = $state === 'ONLINE' || $state === 'UPDATING' ? 'online' : (in_array($state, ['OFFLINE', 'CONNECTION_INTERRUPTED', 'ISOLATED'], true) ? 'offline' : ''); $model = rmmUnifiModelName((string) ($device['model'] ?? '')); $firmware = rmmText($device['firmwareVersion'] ?? '', 100); $name = rmmText($device['name'] ?? '', 200); $ip = rmmText($device['ipAddress'] ?? '', 100); return [ 'remote_id' => $mac, 'mac' => $mac, 'hostname' => $name !== '' ? $name : trim($model . ' ' . strtoupper(substr($mac, -6))), 'site' => '', 'role' => '', 'platform' => 'unifi', 'os' => $firmware, 'status' => $status, 'local_ips' => $ip, 'patches_pending' => !empty($device['firmwareUpdatable']), 'agent_version' => '', 'asset' => [ 'type' => in_array('gateway', $features, true) ? 'Firewall/Router' : (in_array('switching', $features, true) ? 'Switch' : (in_array('accessPoint', $features, true) ? 'Access Point' : 'Other')), 'make' => 'Ubiquiti', 'model' => $model, 'serial' => '', 'os' => $firmware, 'ip' => $ip, 'mac' => $mac, ], ]; } /** * A model code as people know it - U7PG2 is the UAP-AC-Pro. The code as it is for one not here, * and a name - the official Network API often says the name itself - as it is. */ function rmmUnifiModelName(string $code): string { $names = [ 'U7PG2' => 'UAP-AC-Pro', 'U7LT' => 'UAP-AC-Lite', 'U7LR' => 'UAP-AC-LR', 'U7MSH' => 'UAP-AC-Mesh', 'U7NHD' => 'UAP-nanoHD', 'U7HD' => 'UAP-AC-HD', 'U7SHD' => 'UAP-AC-SHD', 'UFLHD' => 'UAP-FlexHD', 'U7IW' => 'UAP-AC-IW', 'UAL6' => 'U6-Lite', 'UALR6' => 'U6-LR', 'UAP6MP' => 'U6-Pro', 'UAE6' => 'U6-Enterprise', 'UGW3' => 'USG', 'UGW4' => 'USG-Pro-4', 'UGWXG' => 'USG-XG-8', 'UDM' => 'UDM', 'UDMPRO' => 'UDM-Pro', 'UDMPROSE' => 'UDM-SE', 'UDR' => 'UDR', 'US8' => 'US-8', 'US8P60' => 'US-8-60W', 'US8P150' => 'US-8-150W', 'US16P150' => 'US-16-150W', 'US24' => 'US-24', 'US24P250' => 'US-24-250W', 'US24P500' => 'US-24-500W', 'US48' => 'US-48', 'US48P500' => 'US-48-500W', 'US48P750' => 'US-48-750W', 'USMINI' => 'USW-Flex-Mini', 'USL8LP' => 'USW-Lite-8-PoE', 'USL16LP' => 'USW-Lite-16-PoE', ]; $code = rmmText($code, 100); return $names[strtoupper($code)] ?? $code; } /** Where Open in UniFi goes - the controller or console, or unifi.ui.com through Site Manager. */ function rmmUnifiDashboard(array $provider): string { if ($provider['rmm_provider_kind'] === 'unifi_cloud') { return 'https://unifi.ui.com'; } return rmmUrlClean($provider['rmm_provider_api_url'] ?? ''); }