* @copyright (C) 2006 - 2012 Adam Armstrong (as Observium)
* @copyright (C) 2013 LibreNMS Group
*/
use LibreNMS\Authentication\LegacyAuth;
use LibreNMS\Config;
/**
* Compare $t with the value of $vars[$v], if that exists
* @param string $v Name of the var to test
* @param string $t Value to compare $vars[$v] to
* @return boolean true, if values are the same, false if $vars[$v] is unset or values differ
*/
function var_eq($v, $t)
{
global $vars;
if (isset($vars[$v]) && $vars[$v] == $t) {
return true;
}
return false;
}
/**
* Get the value of $vars[$v], if it exists
* @param string $v Name of the var to get
* @return string|boolean The value of $vars[$v] if it exists, false if it does not exist
*/
function var_get($v)
{
global $vars;
if (isset($vars[$v])) {
return $vars[$v];
}
return false;
}
function data_uri($file, $mime)
{
$contents = file_get_contents($file);
$base64 = base64_encode($contents);
return ('data:' . $mime . ';base64,' . $base64);
}//end data_uri()
/**
* Convert string to nice case, mostly used for applications
*
* @param $item
* @return mixed|string
*/
function nicecase($item)
{
return \LibreNMS\Util\StringHelpers::niceCase($item);
}//end nicecase()
function toner2colour($descr, $percent)
{
$colour = get_percentage_colours(100 - $percent);
if (substr($descr, -1) == 'C' || stripos($descr, 'cyan') !== false) {
$colour['left'] = '55D6D3';
$colour['right'] = '33B4B1';
}
if (substr($descr, -1) == 'M' || stripos($descr, 'magenta') !== false) {
$colour['left'] = 'F24AC8';
$colour['right'] = 'D028A6';
}
if (substr($descr, -1) == 'Y' || stripos($descr, 'yellow') !== false
|| stripos($descr, 'giallo') !== false
|| stripos($descr, 'gul') !== false
) {
$colour['left'] = 'FFF200';
$colour['right'] = 'DDD000';
}
if (substr($descr, -1) == 'K' || stripos($descr, 'black') !== false
|| stripos($descr, 'nero') !== false
) {
$colour['left'] = '000000';
$colour['right'] = '222222';
}
return $colour;
}//end toner2colour()
/**
* Find all links in some text and turn them into html links.
*
* @param string $text
* @return string
*/
function linkify($text)
{
$regex = "#(http|https|ftp|ftps)://[a-z0-9\-.]*[a-z0-9\-]+(/\S*)?#i";
return preg_replace($regex, '$0', $text);
}
function generate_link($text, $vars, $new_vars = array())
{
return '' . $text . '';
}//end generate_link()
function generate_url($vars, $new_vars = [])
{
return \LibreNMS\Util\Url::generate($vars, $new_vars);
}
function escape_quotes($text)
{
return str_replace('"', "\'", str_replace("'", "\'", $text));
}//end escape_quotes()
function generate_overlib_content($graph_array, $text)
{
global $config;
$overlib_content = '
';
}
return $output;
}//end generate_dynamic_config_panel()
function get_ripe_api_whois_data_json($ripe_data_param, $ripe_query_param)
{
$ripe_whois_url = 'https://stat.ripe.net/data/' . $ripe_data_param . '/data.json?resource=' . $ripe_query_param;
return json_decode(file_get_contents($ripe_whois_url), true);
}//end get_ripe_api_whois_data_json()
/**
* Return the rows from 'ports' for all ports of a certain type as parsed by port_descr_parser.
* One or an array of strings can be provided as an argument; if an array is passed, all ports matching
* any of the types in the array are returned.
* @param $types mixed String or strings matching 'port_descr_type's.
* @return array Rows from the ports table for matching ports.
*/
function get_ports_from_type($given_types)
{
global $config;
# Make the arg an array if it isn't, so subsequent steps only have to handle arrays.
if (!is_array($given_types)) {
$given_types = array($given_types);
}
# Check the config for a '_descr' entry for each argument. This is how a 'custom_descr' entry can
# be key/valued to some other string that's actually searched for in the DB. Merge or append the
# configured value if it's an array or a string. Or append the argument itself if there's no matching
# entry in config.
$search_types = array();
foreach ($given_types as $type) {
if (isset($config[$type . '_descr']) === true) {
if (is_array($config[$type . '_descr']) === true) {
$search_types = array_merge($search_types, $config[$type . '_descr']);
} else {
$search_types[] = $config[$type . '_descr'];
}
} else {
$search_types[] = $type;
}
}
# Using the full list of strings to search the DB for, build the 'where' portion of a query that
# compares 'port_descr_type' with entry in the list. Also, since '@' is the convential wildcard,
# replace it with '%' so it functions as a wildcard in the SQL query.
$type_where = ' (';
$or = '';
$type_param = array();
foreach ($search_types as $type) {
if (!empty($type)) {
$type = strtr($type, '@', '%');
$type_where .= " $or `port_descr_type` LIKE ?";
$or = 'OR';
$type_param[] = $type;
}
}
$type_where .= ') ';
# Run the query with the generated 'where' and necessary parameters, and send it back.
$ports = dbFetchRows("SELECT * FROM `ports` as I, `devices` AS D WHERE $type_where AND I.device_id = D.device_id ORDER BY I.ifAlias", $type_param);
return $ports;
}
/**
* @param $filename
* @param $content
*/
function file_download($filename, $content)
{
$length = strlen($content);
header('Content-Description: File Transfer');
header('Content-Type: text/plain');
header("Content-Disposition: attachment; filename=$filename");
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . $length);
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Expires: 0');
header('Pragma: public');
echo $content;
}
function get_rules_from_json()
{
global $config;
return json_decode(file_get_contents($config['install_dir'] . '/misc/alert_rules.json'), true);
}
function search_oxidized_config($search_in_conf_textbox)
{
global $config;
$oxidized_search_url = $config['oxidized']['url'] . '/nodes/conf_search?format=json';
$postdata = http_build_query(
array(
'search_in_conf_textbox' => $search_in_conf_textbox,
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
return json_decode(file_get_contents($oxidized_search_url, false, $context), true);
}
/**
* @param $data
* @return bool|mixed
*/
function array_to_htmljson($data)
{
if (is_array($data)) {
$data = htmlentities(json_encode($data));
return str_replace(',', ', ', $data);
} else {
return false;
}
}
/**
* @param int $eventlog_severity
* @return string $eventlog_severity_icon
*/
function eventlog_severity($eventlog_severity)
{
switch ($eventlog_severity) {
case 1:
return "label-success"; //OK
case 2:
return "label-info"; //Informational
case 3:
return "label-primary"; //Notice
case 4:
return "label-warning"; //Warning
case 5:
return "label-danger"; //Critical
default:
return "label-default"; //Unknown
}
} // end eventlog_severity
/**
*
*/
function set_image_type()
{
return header('Content-type: ' . get_image_type());
}
function get_image_type()
{
global $config;
if ($config['webui']['graph_type'] === 'svg') {
return 'image/svg+xml';
} else {
return 'image/png';
}
}
function get_oxidized_nodes_list()
{
global $config;
$context = stream_context_create(array(
'http' => array(
'header' => "Accept: application/json",
)
));
$data = json_decode(file_get_contents($config['oxidized']['url'] . '/nodes?format=json', false, $context), true);
foreach ($data as $object) {
$device = device_by_name($object['name']);
if (! device_permitted($device['device_id'])) {
//user cannot see this device, so let's skip it.
continue;
}
$fa_color = $object['status'] == 'success' ? 'success' : 'danger';
echo "
" . generate_device_link($device);
if ($device['device_id'] == 0) {
echo "(device '" . $object['name'] . "' not in LibreNMS)";
}
echo "
";
}
}
// fetches disks for a system
function get_disks($device)
{
return dbFetchRows('SELECT * FROM `ucd_diskio` WHERE device_id = ? ORDER BY diskio_descr', array($device));
}
/**
* Get the fail2ban jails for a device... just requires the device ID
* an empty return means either no jails or fail2ban is not in use
* @param $device_id
* @return array
*/
function get_fail2ban_jails($device_id)
{
$options = array(
'filter' => array(
'type' => array('=', 'fail2ban'),
),
);
$component = new LibreNMS\Component();
$f2bc = $component->getComponents($device_id, $options);
if (isset($f2bc[$device_id])) {
$id = $component->getFirstComponentID($f2bc, $device_id);
return json_decode($f2bc[$device_id][$id]['jails']);
}
return array();
}
/**
* Get the Postgres databases for a device... just requires the device ID
* an empty return means Postres is not in use
* @param $device_id
* @return array
*/
function get_postgres_databases($device_id)
{
$options = array(
'filter' => array(
'type' => array('=', 'postgres'),
),
);
$component = new LibreNMS\Component();
$pgc = $component->getComponents($device_id, $options);
if (isset($pgc[$device_id])) {
$id = $component->getFirstComponentID($pgc, $device_id);
return json_decode($pgc[$device_id][$id]['databases']);
}
return array();
}
/**
* Get all disks (disk serial numbers) from the collected
* rrd files.
*
* @param array $device device for which we get the rrd's
* @param int $app_id application id on the device
* @return array list of disks
*/
function get_disks_with_smart($device, $app_id)
{
$disks = array();
$pattern = sprintf('%s/%s-%s-%s-*.rrd', get_rrd_dir($device['hostname']), 'app', 'smart', $app_id);
foreach (glob($pattern) as $rrd) {
$filename = basename($rrd, '.rrd');
list(,,, $disk) = explode("-", $filename, 4);
if ($disk) {
array_push($disks, $disk);
}
}
return $disks;
}
/**
* Gets all dashboards the user can access
* adds in the keys:
* username - the username of the owner of each dashboard
* default - the default dashboard for the logged in user
*
* @param int $user_id optionally get list for another user
* @return array list of dashboards
*/
function get_dashboards($user_id = null)
{
$user = is_null($user_id) ? Auth::user() : \App\Models\User::find($user_id);
$default = get_user_pref('dashboard');
return \App\Models\Dashboard::allAvailable($user)->with('user')->get()->map(function ($dashboard) use ($default) {
$dash = $dashboard->toArray();
$dash['username'] = $dashboard->user ? $dashboard->user->username : '';
$dash['default'] = $default == $dashboard->dashboard_id;
return $dash;
})->keyBy('dashboard_id')->all();
}
/**
* Return stacked graphs information
*
* @param string $transparency value of desired transparency applied to rrdtool options (values 01 - 99)
* @return array containing transparency and stacked setup
*/
function generate_stacked_graphs($transparency = '88')
{
if (Config::get('webui.graph_stacked') == true) {
return array('transparency' => $transparency, 'stacked' => '1');
} else {
return array('transparency' => '', 'stacked' => '-1');
}
}
/**
* Get the ZFS pools for a device... just requires the device ID
* an empty return means ZFS is not in use or there are currently no pools
* @param $device_id
* @return array
*/
function get_zfs_pools($device_id)
{
$options=array(
'filter' => array(
'type' => array('=', 'zfs'),
),
);
$component=new LibreNMS\Component();
$zfsc=$component->getComponents($device_id, $options);
if (isset($zfsc[$device_id])) {
$id = $component->getFirstComponentID($zfsc, $device_id);
return json_decode($zfsc[$device_id][$id]['pools']);
}
return array();
}
/**
* Get the ports for a device... just requires the device ID
* an empty return means portsactivity is not in use or there are currently no ports
* @param $device_id
* @return array
*/
function get_portactivity_ports($device_id)
{
$options=array(
'filter' => array(
'type' => array('=', 'portsactivity'),
),
);
$component=new LibreNMS\Component();
$portsc=$component->getComponents($device_id, $options);
if (isset($portsc[$device_id])) {
$id = $component->getFirstComponentID($portsc, $device_id);
return json_decode($portsc[$device_id][$id]['ports']);
}
return array();
}
/**
* Returns the sysname of a device with a html line break prepended.
* if the device has an empty sysname it will return device's hostname instead
* And finally if the device has no hostname it will return an empty string
* @param array device
* @return string
*/
function get_device_name($device)
{
$ret_str = '';
if (format_hostname($device) !== $device['sysName']) {
$ret_str = $device['sysName'];
} elseif ($device['hostname'] !== $device['ip']) {
$ret_str = $device['hostname'];
}
return $ret_str;
}
/**
* Returns state generic label from value with optional text
*/
function get_state_label($state_value, $state_text_param = null)
{
switch ($state_value) {
case 0: // OK
$state_text = (is_null($state_text_param) ? "OK": $state_text_param);
$state_label = "label-success";
break;
case 1: // Warning
$state_text = (is_null($state_text_param) ? "Warning": $state_text_param);
$state_label = "label-warning";
break;
case 2: // Critical
$state_text = (is_null($state_text_param) ? "Critical": $state_text_param);
$state_label = "label-danger";
break;
case 3:// Unknown
default:
$state_text = (is_null($state_text_param) ? "Unknown": $state_text_param);
$state_label = "label-default";
}
$state = "$state_text";
return $state;
}
/**
* Get state label color
*/
function get_sensor_label_color($sensor)
{
$current_label_color = "label-success";
if (is_null($sensor)) {
return "label-unknown";
}
if (!is_null($sensor['sensor_limit_warn']) && $sensor['sensor_current'] > $sensor['sensor_limit_warn']) {
$current_label_color = "label-warning";
}
if (!is_null($sensor['sensor_limit_low_warn']) && $sensor['sensor_current'] < $sensor['sensor_limit_low_warn']) {
$current_label_color = "label-warning";
}
if (!is_null($sensor['sensor_limit']) && $sensor['sensor_current'] > $sensor['sensor_limit']) {
$current_label_color = "label-danger";
}
if (!is_null($sensor['sensor_limit_low']) && $sensor['sensor_current'] < $sensor['sensor_limit_low']) {
$current_label_color = "label-danger";
}
return $current_label_color;
}