Files
librenms-librenms/LibreNMS/Util/StringHelpers.php

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

207 lines
6.6 KiB
PHP
Raw Normal View History

<?php
/**
2021-11-17 19:23:55 -06:00
* StringHelpers.php
*
* -Description-
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* @link https://www.librenms.org
2021-09-10 20:09:53 +02:00
*
2021-11-17 19:23:55 -06:00
* @copyright 2021 Tony Murray
* @author Tony Murray <murraytony@gmail.com>
*/
namespace LibreNMS\Util;
class StringHelpers
{
/**
* Shorten text over 50 chars, if shortened, add ellipsis
*
2021-09-08 23:35:56 +02:00
* @param string $string
* @param int $max
* @return string
*/
public static function shortenText($string, $max = 30)
{
if (strlen($string) > 50) {
return substr($string, 0, $max) . '...';
}
return $string;
}
public static function niceCase($string)
{
$replacements = [
'bind' => 'BIND',
'cape' => 'CAPEv2',
'dbm' => 'dBm',
'dhcp-stats' => 'DHCP Stats',
'entropy' => 'Random entropy',
'exim-stats' => 'EXIM Stats',
'fbsd-nfs-client' => 'FreeBSD NFS Client',
'fbsd-nfs-server' => 'FreeBSD NFS Server',
'freeradius' => 'FreeRADIUS',
'gpsd' => 'GPSD',
'hv-monitor' => 'HV Monitor',
'mojo_cape_submit' => 'Mojo CAPE Submit',
'mailcow-postfix' => 'mailcow-dockerized postfix',
'mysql' => 'MySQL',
'nfs' => 'NFS',
'nfs-server' => 'NFS Server',
'nfs-stats' => 'NFS Stats',
'nfs-v3-stats' => 'NFS v3 Stats',
'ntp' => 'NTP',
'ntp-client' => 'NTP Client',
'ntp-server' => 'NTP Server',
'opengridscheduler' => 'Open Grid Scheduler',
add Opensearch\Elasticsearch monitoring (#14053) * add new poller * add a missing ; * formatting cleanup * graph stuff and metrics move * add rrd name * clean up metrics/rrd def * more metric/rrd def cleanup * cleanup * add basic opensearch graphs * add opensearch to apps.inc.php * begin work on opensearch app page * formatting cleanup * add translog graphs * add a missing graph * fix pending tasks * add the ability to fetch the saved cluster name * add fetching the cluster name * correct the opensearch comment * add combined shard stats * add indexing graphs * correct graph name * correct some units as being per second * add more graphs * add more items for graph sets * cleanup of units and naming... also more graphs * more graph stuff * change the RRD def again and define a few more graphs * finish basic graph sets * more graph stuff * another rrd def change * add more graphs * add some more graph sets * correct unit for c_task_max_in_time * more graph stuff * more graph stuff * correct the unit * add missing tw_time and another rrd def change * another unit change * add trc graphs * more graph stuff * add tseg graphs * add all shards graph to both cluster items * more graph stuff * update opensearch app page * add Opensearch\Elasticsearch app * add opensearch tests * run php-cs-fixer on two files * add alert examples for checking cluster status * remove an item that was accidentally added as a metric in the test but is not * derp! thanks jellyfrog * make it come up as Elisticsearch\Opensearch in the webui * no longer use components, but app_data, for cluster name change * update the web side for opensearch for using app_data * style fix * update opensearch for new app data stuff * update to the new Application model * update poller and device app page for ES/OS * style cleanup * update graphs * test fix * more test cleanup * Update alert_rules.json * begin work on breaking out the RRDs * update all non-multi rrd graphs for opensearch * update time_all * add a unass shards graph * correct rrd name * should all be good now * add missing tm stats * Un Assigned -> Unassigned * style cleanup * another style fix * remove cluster_name from saved metrics as it is not a metric Co-authored-by: Tony Murray <murraytony@gmail.com> Co-authored-by: Jellyfrog <Jellyfrog@users.noreply.github.com>
2022-08-15 14:44:20 -05:00
'opensearch' => 'Elasticsearch\Opensearch',
'os-updates' => 'OS Updates',
'php-fpm' => 'PHP-FPM',
'pi-hole' => 'Pi-hole',
'powerdns' => 'PowerDNS',
'powerdns-dnsdist' => 'PowerDNS dnsdist',
'powerdns-recursor' => 'PowerDNS Recursor',
'powermon' => 'PowerMon',
'pureftpd' => 'PureFTPd',
'rrdcached' => 'RRDCached',
'sdfsinfo' => 'SDFS info',
'smart' => 'SMART',
'ss' => 'Socket Statistics',
'ups-apcups' => 'UPS apcups',
'ups-nut' => 'UPS nut',
'zfs' => 'ZFS',
];
return isset($replacements[$string]) ? $replacements[$string] : ucwords(str_replace(['_', '-'], ' ', $string));
}
/**
* Convert a camel or studly case string to Title case (with spaces)
2021-09-10 20:09:53 +02:00
*
2021-09-08 23:35:56 +02:00
* @param string $string
* @return string
*/
public static function camelToTitle($string)
{
return ucwords(implode(' ', preg_split('/(?=[A-Z])/', $string)));
}
/**
* Sometimes devices store strings as non-unicode strings and return them directly.
* NetSnmp parses those as UTF-8, try to convert the string if it contains non-printable ascii characters.
*
* @param string|null $string
* @return string
*/
public static function inferEncoding(?string $string): ?string
{
if (empty($string) || preg_match('//u', $string) || ! function_exists('iconv')) {
return $string;
}
$charset = config('app.charset');
if (($converted = @iconv($charset, 'UTF-8', $string)) !== false) {
return (string) $converted;
}
if ($charset !== 'Windows-1252' && ($converted = @iconv('Windows-1252', 'UTF-8', $string)) !== false) {
return (string) $converted;
}
if ($charset !== 'CP850' && ($converted = @iconv('CP850', 'UTF-8', $string)) !== false) {
return (string) $converted;
}
\Log::debug('Failed to convert string: ' . $string);
return $string;
}
/**
* Generate a class name from a lowercase string containing - or _
* Remove - and _ and camel case words
*
* @param string $name The string to convert to a class name
* @param string|null $namespace namespace to prepend to the name for example: LibreNMS\
* @return string Class name
*/
public static function toClass(string $name, ?string $namespace = null): string
{
$pre_format = str_replace(['-', '_'], ' ', $name);
$class = str_replace(' ', '', ucwords(strtolower($pre_format)));
$class = preg_replace_callback('/^(\d)(.)/', function ($matches) {
$numbers = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine'];
return $numbers[$matches[1]] . strtoupper($matches[2]);
}, $class);
return $namespace . $class;
}
/**
* Check if variable can be cast to a string
*
* @param mixed $var
* @return bool
*/
public static function isStringable($var): bool
{
return $var === null || is_scalar($var) || (is_object($var) && method_exists($var, '__toString'));
}
public static function asciiToHex(string $ascii, string $seperator = ''): string
{
$hex = [];
$len = strlen($ascii);
for ($i = 0; $i < $len; $i++) {
$hex[] = str_pad(strtoupper(dechex(ord($ascii[$i]))), 2, '0', STR_PAD_LEFT);
}
return implode($seperator, $hex);
}
Entity Physical discovery: Rewrite to modern style (#16289) * Initial entity-physical code * Split out Entity-MIB trait * Cisco Cellular inventory * Fix bad test data * alfo80hd - we now include all entPhysical entries * Correct aos7 test data * Add entPhysicalClass as last resort for label in ui * aos add previously filtered data * Fixup arista-eos data * Update ariast_eos data * Arris, clean garbage in Rev fields * Aruba Instant custom inventory ported * ArubaOS CX add vendor type mib * aviat-wtm test data refresh * axos add shelf fix data fields a bit * ciena-rls * ciena-sds * Skip cimc for now... no test data * Cisco updates * Comware data update * Update dnos * Clean Edgeos garbage, make code from Arris shareable * Relaxed ifIndex match, some devices cheat and send back static strings instead of formatted OIDs * Regex refinement and updated edgeos with new clean data * Update edgeswitch data * Update eltex-mes21xx data * eltex-mes23xx * Guess at eltex-mes24xx since there is no test data * Update eurostor, fix firmware version * Apply fixes from StyleCI * fixes * Update fortigate data * Update fortiweb, ftd, and fusion * Update linux LSI * Fix hexToAscii null removal with different seperator handling * icotera add final snmprec data to avoid snmpsim bug * Update IOS data * Update mrv-od * Add junos translation * Generic data updates n-r * ruijie workaround snmpsim bug * Port saf-cfm * Recode Schleifenbauer, and fix entPhysicalIndex values * SmartAX fixes * sm-os and tait-infra93 * timos inventory was not right, fix it up * ubiquoss-pon * VRP, has custom data collection on top of normal adapt port ifIndex lookup to handle it * VRP exceeded the string length specified in ENTITY-MIB... * data updates * Final data update and code cleanup * Apply fixes from StyleCI * Lint fixes * Add missing SnmpResponse->pluck() code * Update db_schema.yaml * Fix bad test data * Another instant-on update * oops * Remove some unused code # Conflicts: # includes/html/pages/device/overview.inc.php --------- Co-authored-by: Tony Murray <murrant@users.noreply.github.com>
2024-08-21 01:12:09 -05:00
public static function hexToAscii(string $hex, string $seperator = ''): string
{
if ($seperator) {
$escaped_seperator = preg_quote($seperator);
$no_nulls = preg_replace("/(00$escaped_seperator(00)?|{$escaped_seperator}00)/", '', $hex);
$hex = str_replace($seperator, '', $no_nulls);
}
$string = '';
for ($i = 0; $i < strlen($hex) - 1; $i += 2) {
$string .= chr(hexdec(substr($hex, $i, 2)));
}
return $string;
}
public static function trimHexGarbage(string $string): string
{
$regex = '/((\.{2,}.{1,2})?\.+)?([0-9a-f]{2} )*([0-9a-f]{2})?$/';
return preg_replace($regex, '', str_replace("\n", '', $string));
}
public static function isHex(string $string): bool
{
return (bool) preg_match('/^[a-f0-9][a-f0-9]( [a-f0-9][a-f0-9])*$/is', trim($string));
}
}