. * * @package LibreNMS * @link http://librenms.org * @copyright 2022 Tony Murray * @author Tony Murray */ namespace LibreNMS\Util; use Cache; use LibreNMS\Exceptions\InvalidOidException; class Oid { public static function isNumeric(string $oid): bool { return (bool) preg_match('/^[.\d]+$/', $oid); } public static function hasNumericRoot(string $oid): bool { return (bool) preg_match('/^\.?1/', $oid); } public static function hasNumeric(array $oids): bool { foreach ($oids as $oid) { if (self::isNumeric($oid)) { return true; } } return false; } /** * Converts an oid to numeric and caches the result * * @throws \LibreNMS\Exceptions\InvalidOidException */ public static function toNumeric(string $oid, string $mib = 'ALL', int $cache = 1800): string { if (Oid::isNumeric($oid)) { return $oid; } // we already have a specific mib, don't add a bunch of others if (str_contains($oid, '::')) { $mib = null; } $key = 'Oid:toNumeric:' . $oid . '/' . $mib; $numeric_oid = Cache::remember($key, $cache, function () use ($oid, $mib) { $snmpQuery = \SnmpQuery::numeric(); if ($mib) { $snmpQuery->mibs([$mib], append: $mib !== 'ALL'); // append to base mibs unless using ALL } return $snmpQuery->translate($oid); }); if (empty($numeric_oid)) { throw new InvalidOidException("Unable to translate oid $oid"); } return $numeric_oid; } /** * Convert a string to an oid encoded string */ public static function ofString(string $string): string { $oid = strlen($string); for ($i = 0; $i != strlen($string); $i++) { $oid .= '.' . ord($string[$i]); } return $oid; } }