Commit version 24.12.13800

This commit is contained in:
2025-01-06 17:35:06 -05:00
parent b7f6a79c2c
commit 55d9218816
6133 changed files with 4239740 additions and 1374287 deletions

View File

@ -4,9 +4,9 @@
*
* This file is part of Observium.
*
* @package observium
* @subpackage web
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2022 Observium Limited
* @package observium
* @subpackage web
* @copyright (C) Adam Armstrong
*
*/
@ -16,263 +16,247 @@
* Display pages with IP addresses from device Interfaces.
*
* @param array $vars
* @return none
*
* @return void
*
*/
function print_addresses($vars)
{
// With pagination? (display page numbers in header)
$pagination = (isset($vars['pagination']) && $vars['pagination']);
pagination($vars, 0, TRUE); // Get default pagesize/pageno
$pageno = $vars['pageno'];
$pagesize = $vars['pagesize'];
$start = $pagesize * $pageno - $pagesize;
// With pagination? (display page numbers in header)
$pagination = (isset($vars['pagination']) && $vars['pagination']);
pagination($vars, 0, TRUE); // Get default pagesize/pageno
$pageno = $vars['pageno'];
$pagesize = $vars['pagesize'];
$start = $pagesize * $pageno - $pagesize;
if (in_array($vars['search'], array('6', 'v6', 'ipv6')) ||
in_array($vars['view'], array('6', 'v6', 'ipv6')))
{
$address_type = 'ipv6';
} else {
$address_type = 'ipv4';
}
$ip_array = array();
$param = array();
$where = ' WHERE 1 ';
$join_ports = FALSE;
$param_netscaler = array();
$where_netscaler = " WHERE `vsvr_ip` != '0.0.0.0' AND `vsvr_ip` != '' ";
foreach ($vars as $var => $value)
{
if ($value != '')
{
switch ($var)
{
case 'device':
case 'device_id':
$where .= generate_query_values_and($value, 'A.device_id');
$where_netscaler .= generate_query_values_and($value, 'N.device_id');
break;
case 'interface':
$where .= generate_query_values_and($value, 'I.ifDescr', 'LIKE%');
$join_ports = TRUE;
break;
case 'type':
$where .= generate_query_values_and($value, 'A.ip_type');
break;
case 'network':
if (!is_array($value))
{
$value = explode(',', $value);
}
if ($ids = get_entity_ids_ip_by_network($address_type, $value))
{
// Full network with prefix
$where .= generate_query_values_and($ids, 'A.ip_address_id');
} else {
// Part of network string
$where .= ' AND 0'; // Nothing!
}
$where_netscaler .= ' AND 0'; // Currently, unsupported for Netscaller
break;
case 'address':
if (!is_array($value)) {
$value = explode(',', $value);
}
// Remove prefix part
$addr = [];
foreach ($value as $tmp) {
list($addr[], $mask) = explode('/', $tmp);
}
if ($ids = get_entity_ids_ip_by_network($address_type, $addr)) {
// Full network with prefix
$where .= generate_query_values_and($ids, 'A.ip_address_id');
} else {
$where .= ' AND 0'; // Nothing!
}
/// FIXME. Netscaller hack
if (count($addr) && get_ip_version($addr[0])) {
// Netscaller for valid IP address
$where_netscaler .= generate_query_values_and($addr, 'N.vsvr_ip');
} else {
$where_netscaler .= generate_query_values_and($addr, 'N.vsvr_ip', '%LIKE%');
}
break;
}
}
}
$query_device_permitted = generate_query_permitted(array('device'));
$query_port_permitted = generate_query_permitted(array('device', 'port'));
// Also search netscaler Vserver IPs
$query_netscaler = 'FROM `netscaler_vservers` AS N ';
$query_netscaler .= 'LEFT JOIN `devices` USING(`device_id`) ';
$query_netscaler .= $where_netscaler . $query_device_permitted;
//$query_netscaler_count = 'SELECT COUNT(`vsvr_id`) ' . $query_netscaler;
$query_netscaler = 'SELECT * ' . $query_netscaler;
$query_netscaler .= ' ORDER BY `vsvr_ip`';
// Override by address type
if ($address_type == 'ipv6')
{
$query_netscaler = str_replace(array('vsvr_ip', '0.0.0.0'), array('vsvr_ipv6', '0:0:0:0:0:0:0:0'), $query_netscaler);
//$query_netscaler_count = str_replace(array('vsvr_ip', '0.0.0.0'), array('vsvr_ipv6', '0:0:0:0:0:0:0:0'), $query_netscaler_count);
}
$entries = dbFetchRows($query_netscaler, $param_netscaler);
// Rewrite netscaler addresses
foreach ($entries as $entry)
{
$ip_address = ($address_type == 'ipv4') ? $entry['vsvr_ip'] : $entry['vsvr_'.$address_type];
$ip_network = ($address_type == 'ipv4') ? $entry['vsvr_ip'].'/32' : $entry['vsvr_'.$address_type].'/128';
$ip_array[] = array('type' => 'netscalervsvr',
'device_id' => $entry['device_id'],
'hostname' => $entry['hostname'],
'vsvr_id' => $entry['vsvr_id'],
'vsvr_label' => $entry['vsvr_label'],
'ifAlias' => 'Netscaler: '.$entry['vsvr_type'].'/'.$entry['vsvr_entitytype'],
$address_type.'_address' => $ip_address,
$address_type.'_network' => $ip_network
);
}
//print_message($query_netscaler_count);
$query = 'FROM `ip_addresses` AS A ';
$query .= ' LEFT JOIN `ip_networks` AS N USING(`ip_network_id`)';
if ($join_ports)
{
$query .= ' LEFT JOIN `ports` USING(`port_id`)';
}
//$query .= ' LEFT JOIN `devices` USING(`device_id`)';
$query .= $where . $query_port_permitted;
//$query_count = 'SELECT COUNT(`ip_address_id`) ' . $query;
$query = 'SELECT A.*, N.* ' . $query;
$query .= ' ORDER BY A.`ip_binary`';
if ($ip_valid)
{
$pagination = FALSE;
}
// Override by address type
//$query = str_replace(array('ip_address', 'ip_network'), array($address_type.'_address', $address_type.'_network'), $query);
$query = preg_replace('/ip_(address|network|type|binary)/', $address_type.'_$1', $query);
//$query_count = str_replace(array('ip_address', 'ip_network'), array($address_type.'_address', $address_type.'_network'), $query_count);
// Query addresses
$entries = dbFetchRows($query, $param);
$ip_array = array_sort($ip_array, $address_type.'_address'); // Sort netscaller
$ip_array = array_merge($entries, $ip_array);
// Query address count
//if ($pagination) { $count = dbFetchCell($query_count, $param); }
if ($pagination)
{
$count = count($ip_array);
$ip_array = array_slice($ip_array, $start, $pagesize);
}
$list = array('device' => FALSE);
if (!isset($vars['device']) || empty($vars['device']) || $vars['page'] == 'search') { $list['device'] = TRUE; }
$string = generate_box_open($vars['header']);
$string .= '<table class="'.OBS_CLASS_TABLE_STRIPED.'">' . PHP_EOL;
if (!$short)
{
$string .= ' <thead>' . PHP_EOL;
$string .= ' <tr>' . PHP_EOL;
if ($list['device']) { $string .= ' <th>Device</th>' . PHP_EOL; }
$string .= ' <th>Interface</th>' . PHP_EOL;
$string .= ' <th>Address</th>' . PHP_EOL;
$string .= ' <th>Type</th>' . PHP_EOL;
$string .= ' <th>[VRF] Description</th>' . PHP_EOL;
$string .= ' </tr>' . PHP_EOL;
$string .= ' </thead>' . PHP_EOL;
}
$string .= ' <tbody>' . PHP_EOL;
$vrf_cache = [];
foreach ($ip_array as $entry)
{
$address_show = TRUE;
if ($ip_valid)
{
// If address not in specified network, don't show entry.
if ($address_type === 'ipv4')
{
$address_show = Net_IPv4::ipInNetwork($entry[$address_type.'_address'], $addr . '/' . $mask);
} else {
$address_show = Net_IPv6::isInNetmask($entry[$address_type.'_address'], $addr, $mask);
}
if (in_array($vars['search'], ['6', 'v6', 'ipv6']) ||
in_array($vars['view'], ['6', 'v6', 'ipv6'])) {
$address_type = 'ipv6';
} else {
$address_type = 'ipv4';
}
if ($address_show)
{
list($prefix, $length) = explode('/', $entry[$address_type.'_network']);
if ($entry['type'] == 'netscalervsvr')
{
$entity_link = generate_entity_link($entry['type'], $entry);
}
else if ($port = get_port_by_id_cache($entry['port_id']))
{
if ($port['ifInErrors_delta'] > 0 || $port['ifOutErrors_delta'] > 0)
{
$port_error = generate_port_link($port, '<span class="label label-important">Errors</span>', 'port_errors');
$ip_array = [];
$param = [];
$where = ' WHERE 1 ';
$join_ports = FALSE;
$param_netscaler = [];
$where_netscaler = " WHERE `vsvr_ip` != '0.0.0.0' AND `vsvr_ip` != '' ";
foreach ($vars as $var => $value) {
if ($value != '') {
switch ($var) {
case 'device':
case 'device_id':
$where .= generate_query_values_and($value, 'A.device_id');
$where_netscaler .= generate_query_values_and($value, 'N.device_id');
break;
case 'interface':
$where .= generate_query_values_and($value, 'I.ifDescr', 'LIKE%');
$join_ports = TRUE;
break;
case 'type':
$where .= generate_query_values_and($value, 'A.ip_type');
break;
case 'network':
if (!is_array($value)) {
$value = explode(',', $value);
}
if ($ids = get_entity_ids_ip_by_network($address_type, $value)) {
// Full network with prefix
$where .= generate_query_values_and($ids, 'A.ip_address_id');
} else {
// Part of network string
$where .= ' AND 0'; // Nothing!
}
$where_netscaler .= ' AND 0'; // Currently, unsupported for Netscaller
break;
case 'address':
if (!is_array($value)) {
$value = explode(',', $value);
}
// Remove prefix part
$addr = [];
foreach ($value as $tmp) {
[$addr[], $mask] = explode('/', $tmp);
}
if ($ids = get_entity_ids_ip_by_network($address_type, $addr)) {
// Full network with prefix
$where .= generate_query_values_and($ids, 'A.ip_address_id');
} else {
$where .= ' AND 0'; // Nothing!
}
/// FIXME. Netscaller hack
if (count($addr) && get_ip_version($addr[0])) {
// Netscaller for valid IP address
$where_netscaler .= generate_query_values_and($addr, 'N.vsvr_ip');
} else {
$where_netscaler .= generate_query_values_and($addr, 'N.vsvr_ip', '%LIKE%');
}
break;
}
}
// for port_label_short - generate_port_link($link_if, NULL, NULL, TRUE, TRUE)
$entity_link = generate_port_link_short($port) . ' ' . $port_error;
$entry['ifAlias'] = $port['ifAlias'];
}
else if ($vlan = dbFetchRow('SELECT * FROM `vlans` WHERE `device_id` = ? AND `ifIndex` = ?', array($entry['device_id'], $entry['ifIndex'])))
{
// Vlan ifIndex (without associated port)
$entity_link = 'Vlan ' . $vlan['vlan_vlan'];
$entry['ifAlias'] = $vlan['vlan_name'];
} else {
$entity_link = 'ifIndex ' . $entry['ifIndex'];
}
// Query VRFs
if ($entry['vrf_id'])
{
if (isset($vrf_cache[$entry['vrf_id']]))
{
$vrf_name = $vrf_cache[$entry['vrf_id']];
} else {
$vrf_name = dbFetchCell("SELECT `vrf_name` FROM `vrfs` WHERE `vrf_id` = ?", [ $entry['vrf_id'] ]);
$vrf_cache[$entry['vrf_id']] = $vrf_name;
}
$entry['ifAlias'] = '<span class="label label-default">'.$vrf_name.'</span>' . $entry['ifAlias'];
}
$device_link = generate_device_link($entry);
$string .= ' <tr>' . PHP_EOL;
if ($list['device'])
{
$string .= ' <td class="entity" style="white-space: nowrap">' . $device_link . '</td>' . PHP_EOL;
}
$string .= ' <td class="entity">' . $entity_link . '</td>' . PHP_EOL;
if ($address_type === 'ipv6') { $entry[$address_type.'_address'] = Net_IPv6::compress($entry[$address_type.'_address']); }
$string .= ' <td>' . generate_popup_link('ip', $entry[$address_type.'_address'] . '/' . $length) . '</td>' . PHP_EOL;
$type = strlen($entry[$address_type.'_type']) ? $entry[$address_type.'_type'] : get_ip_type($entry[$address_type.'_address'] . '/' . $length);
$type_class = $GLOBALS['config']['ip_types'][$type]['label-class'];
$string .= ' <td><span class="label label-'.$type_class.'">' . $type . '</span></td>' . PHP_EOL;
$string .= ' <td>' . $entry['ifAlias'] . '</td>' . PHP_EOL;
$string .= ' </tr>' . PHP_EOL;
}
}
$string .= ' </tbody>' . PHP_EOL;
$string .= '</table>';
$string .= generate_box_close();
$query_device_permitted = generate_query_permitted(['device']);
$query_port_permitted = generate_query_permitted(['device', 'port']);
// Print pagination header
if ($pagination) { $string = pagination($vars, $count) . $string . pagination($vars, $count); }
// Also search netscaler Vserver IPs
$query_netscaler = 'FROM `netscaler_vservers` AS N ';
$query_netscaler .= 'LEFT JOIN `devices` USING(`device_id`) ';
$query_netscaler .= $where_netscaler . $query_device_permitted;
//$query_netscaler_count = 'SELECT COUNT(`vsvr_id`) ' . $query_netscaler;
$query_netscaler = 'SELECT * ' . $query_netscaler;
$query_netscaler .= ' ORDER BY `vsvr_ip`';
// Override by address type
if ($address_type == 'ipv6') {
$query_netscaler = str_replace(['vsvr_ip', '0.0.0.0'], ['vsvr_ipv6', '0:0:0:0:0:0:0:0'], $query_netscaler);
//$query_netscaler_count = str_replace(array('vsvr_ip', '0.0.0.0'), array('vsvr_ipv6', '0:0:0:0:0:0:0:0'), $query_netscaler_count);
}
// Print addresses
echo $string;
$entries = dbFetchRows($query_netscaler, $param_netscaler);
// Rewrite netscaler addresses
foreach ($entries as $entry) {
$ip_address = ($address_type == 'ipv4') ? $entry['vsvr_ip'] : $entry['vsvr_' . $address_type];
$ip_network = ($address_type == 'ipv4') ? $entry['vsvr_ip'] . '/32' : $entry['vsvr_' . $address_type] . '/128';
$ip_array[] = ['type' => 'netscalervsvr',
'device_id' => $entry['device_id'],
'hostname' => $entry['hostname'],
'vsvr_id' => $entry['vsvr_id'],
'vsvr_label' => $entry['vsvr_label'],
'ifAlias' => 'Netscaler: ' . $entry['vsvr_type'] . '/' . $entry['vsvr_entitytype'],
$address_type . '_address' => $ip_address,
$address_type . '_network' => $ip_network
];
}
//print_message($query_netscaler_count);
$query = 'FROM `ip_addresses` AS A ';
$query .= ' LEFT JOIN `ip_networks` AS N USING(`ip_network_id`)';
if ($join_ports) {
$query .= ' LEFT JOIN `ports` USING(`port_id`)';
}
//$query .= ' LEFT JOIN `devices` USING(`device_id`)';
$query .= $where . $query_port_permitted;
//$query_count = 'SELECT COUNT(`ip_address_id`) ' . $query;
$query = 'SELECT A.*, N.* ' . $query;
$query .= ' ORDER BY A.`ip_binary`';
if ($ip_valid) {
$pagination = FALSE;
}
// Override by address type
//$query = str_replace(array('ip_address', 'ip_network'), array($address_type.'_address', $address_type.'_network'), $query);
$query = preg_replace('/ip_(address|network|type|binary)/', $address_type . '_$1', $query);
//$query_count = str_replace(array('ip_address', 'ip_network'), array($address_type.'_address', $address_type.'_network'), $query_count);
// Query addresses
$entries = dbFetchRows($query, $param);
$ip_array = array_sort($ip_array, $address_type . '_address'); // Sort netscaller
$ip_array = array_merge($entries, $ip_array);
// Query address count
//if ($pagination) { $count = dbFetchCell($query_count, $param); }
if ($pagination) {
$count = count($ip_array);
$ip_array = array_slice($ip_array, $start, $pagesize);
}
$list = ['device' => FALSE];
if (!isset($vars['device']) || empty($vars['device']) || $vars['page'] == 'search') {
$list['device'] = TRUE;
}
$string = generate_box_open($vars['header']);
$string .= '<table class="' . OBS_CLASS_TABLE_STRIPED . '">' . PHP_EOL;
if (!$short) {
$string .= ' <thead>' . PHP_EOL;
$string .= ' <tr>' . PHP_EOL;
if ($list['device']) {
$string .= ' <th>Device</th>' . PHP_EOL;
}
$string .= ' <th>Interface</th>' . PHP_EOL;
$string .= ' <th>Address</th>' . PHP_EOL;
$string .= ' <th>Type</th>' . PHP_EOL;
$string .= ' <th>[VRF] Description</th>' . PHP_EOL;
$string .= ' </tr>' . PHP_EOL;
$string .= ' </thead>' . PHP_EOL;
}
$string .= ' <tbody>' . PHP_EOL;
$vrf_cache = [];
foreach ($ip_array as $entry) {
$address_show = TRUE;
if ($ip_valid) {
// If address not in specified network, don't show entry.
if ($address_type === 'ipv4') {
$address_show = Net_IPv4 ::ipInNetwork($entry[$address_type . '_address'], $addr . '/' . $mask);
} else {
$address_show = Net_IPv6 ::isInNetmask($entry[$address_type . '_address'], $addr, $mask);
}
}
if ($address_show) {
[$prefix, $length] = explode('/', $entry[$address_type . '_network']);
if ($entry['type'] == 'netscalervsvr') {
$entity_link = generate_entity_link($entry['type'], $entry);
} elseif ($port = get_port_by_id_cache($entry['port_id'])) {
if ($port['ifInErrors_delta'] > 0 || $port['ifOutErrors_delta'] > 0) {
$port_error = generate_port_link($port, '<span class="label label-important">Errors</span>', 'port_errors');
}
// for port_label_short - generate_port_link($link_if, NULL, NULL, TRUE, TRUE)
$entity_link = generate_port_link_short($port) . ' ' . $port_error;
$entry['ifAlias'] = $port['ifAlias'];
} elseif ($vlan = dbFetchRow('SELECT * FROM `vlans` WHERE `device_id` = ? AND `ifIndex` = ?', [$entry['device_id'], $entry['ifIndex']])) {
// Vlan ifIndex (without associated port)
$entity_link = 'Vlan ' . $vlan['vlan_vlan'];
$entry['ifAlias'] = $vlan['vlan_name'];
} else {
$entity_link = 'ifIndex ' . $entry['ifIndex'];
}
// Query VRFs
if ($entry['vrf_id']) {
if (isset($vrf_cache[$entry['vrf_id']])) {
$vrf_name = $vrf_cache[$entry['vrf_id']];
} else {
$vrf_name = dbFetchCell("SELECT `vrf_name` FROM `vrfs` WHERE `vrf_id` = ?", [$entry['vrf_id']]);
$vrf_cache[$entry['vrf_id']] = $vrf_name;
}
$entry['ifAlias'] = '<span class="label label-default">' . $vrf_name . '</span> ' . $entry['ifAlias'];
}
$device_link = generate_device_link($entry);
$string .= ' <tr>' . PHP_EOL;
if ($list['device']) {
$string .= ' <td class="entity" style="white-space: nowrap">' . $device_link . '</td>' . PHP_EOL;
}
$string .= ' <td class="entity">' . $entity_link . '</td>' . PHP_EOL;
if ($address_type === 'ipv6') {
$entry[$address_type . '_address'] = Net_IPv6 ::compress($entry[$address_type . '_address']);
}
$string .= ' <td>' . generate_popup_link('ip', $entry[$address_type . '_address'] . '/' . $length) . '</td>' . PHP_EOL;
$type = strlen($entry[$address_type . '_type']) ? $entry[$address_type . '_type'] : get_ip_type($entry[$address_type . '_address'] . '/' . $length);
$type_class = $GLOBALS['config']['ip_types'][$type]['label-class'];
$string .= ' <td><span class="label label-' . $type_class . '">' . $type . '</span></td>' . PHP_EOL;
$string .= ' <td>' . $entry['ifAlias'] . '</td>' . PHP_EOL;
$string .= ' </tr>' . PHP_EOL;
}
}
$string .= ' </tbody>' . PHP_EOL;
$string .= '</table>';
$string .= generate_box_close();
// Print pagination header
if ($pagination) {
$string = pagination($vars, $count) . $string . pagination($vars, $count);
}
// Print addresses
echo $string;
}
// EOF

View File

@ -6,7 +6,7 @@
*
* @package observium
* @subpackage web
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2022 Observium Limited
* @copyright (C) Adam Armstrong
*
*/
@ -15,345 +15,456 @@
* Returns queries for data, an array of parameters and a query to get a count for use in paging
*
* @param array $vars
*
* @return array ($query, $param, $query_count)
*
*/
// TESTME needs unit testing
function build_alert_table_query($vars) {
$where = ' WHERE 1 ';
// default sort order
$sort = ' ORDER BY `device_id`, `alert_test_id`, `entity_type`, `entity_id` DESC ';
// Loop through the vars building a sql query from relevant values
foreach ($vars as $var => $value) {
if (!safe_empty($value)) {
switch ($var) {
// Search by device_id if we have a device or device_id
case 'device_id':
$where .= generate_query_values_and($value, 'device_id');
break;
case 'entity_type':
if ($value !== 'all') {
$where .= generate_query_values_and($value, 'entity_type');
}
break;
case 'entity_id':
$where .= generate_query_values_and($value, 'entity_id');
break;
case 'alert_test_id':
$where .= generate_query_values_and($value, 'alert_test_id');
break;
case 'status':
if ($value === 'failed_delayed') {
$where .= " AND `alert_status` IN (0,2)";
} elseif ($value === 'failed') {
$where .= " AND `alert_status` IN (0)";
} elseif ($value === 'suppressed') {
$where .= " AND `alert_status` = 3";
}
break;
case 'sort':
if ($value === 'changed') {
$sort = ' ORDER BY `last_changed` DESC ';
} elseif ($value === 'device') {
// fix this to sort by hostname
$sort = ' ORDER BY `device_id` ';
}
break;
}
// Loop through the vars building a sql query from relevant values
$where_array = [];
foreach ($vars as $var => $value) {
if (!safe_empty($value)) {
switch ($var) {
// Search by device_id if we have a device or device_id
case 'device_id':
$where_array[] = generate_query_values($value, 'device_id');
break;
case 'entity_type':
if ($value !== 'all') {
$where_array[] = generate_query_values($value, 'entity_type');
}
break;
case 'entity_id':
$where_array[] = generate_query_values($value, 'entity_id');
break;
case 'alert_test_id':
$where_array[] = generate_query_values($value, 'alert_test_id');
break;
case 'status':
$values = [];
foreach ((array)$value as $status) {
if ($status === 'failed') {
$values[] = 0;
} elseif ($status === 'ok') {
$values[] = 1;
} elseif ($status === 'delayed') {
$values[] = 2;
} elseif ($status === 'suppressed') {
$values[] = 3;
} elseif ($status === 'all') {
break 2;
}
}
$where_array[] = generate_query_values($values, 'alert_status');
break;
}
}
}
}
// Permissions query
$query_permitted = generate_query_permitted(array('device', 'alert'), array('hide_ignored' => TRUE));
// Permissions query
$query_permitted = generate_query_permitted_ng([ 'device', 'alert' ], [ 'hide_ignored' => TRUE ]);
// Base query
$query = 'FROM `alert_table` ';
//$query .= 'LEFT JOIN `alert_table-state` USING(`alert_table_id`) ';
$query .= $where . $query_permitted;
// Base query
$query = 'FROM `alert_table` ' . generate_where_clause($where_array, $query_permitted);
// Build the query to get a count of entries
$query_count = 'SELECT COUNT(`alert_table_id`) '.$query;
// Build the query to get a count of entries
$query_count = 'SELECT COUNT(`alert_table_id`) ' . $query;
// Build the query to get the list of entries
$query = 'SELECT * '.$query;
//$query .= ' ORDER BY `device_id`, `alert_test_id`, `entity_type`, `entity_id` DESC ';
$query .= $sort;
// Build the query to get the list of entries
$query = 'SELECT * ' . $query;
if (isset($vars['pagination']) && $vars['pagination']) {
pagination($vars, 0, TRUE); // Get default pagesize/pageno
$vars['start'] = $vars['pagesize'] * $vars['pageno'] - $vars['pagesize'];
$query .= 'LIMIT '.$vars['start'].','.$vars['pagesize'];
}
//$sort_order = get_sort_order($vars);
switch ($vars['sort']) {
case 'device':
// fix this to sort by hostname
//$query .= generate_query_sort('hostname', get_sort_order($vars));
$query .= generate_query_sort('device_id', get_sort_order($vars));
break;
return array($query, [], $query_count);
case 'last_changed':
case 'changed':
$query .= generate_query_sort('last_changed', 'DESC');
break;
default:
// default sort order
$query .= generate_query_sort([ 'device_id', 'alert_test_id', 'entity_type', 'entity_id' ], 'DESC');
}
if (isset($vars['pagination']) && $vars['pagination']) {
pagination($vars, 0, TRUE); // Get default pagesize/pageno
$query .= generate_query_limit($vars);
}
return [ $query, [], $query_count ];
}
/**
* Display alert_table entries.
*
* @param array $vars
*
* @return void
*
*/
function print_alert_table($vars) {
global $alert_rules, $config;
function print_alert_table($vars)
{
global $alert_rules, $config;
// This should be set outside, but do it here if it isn't
if (!is_array($alert_rules)) { $alert_rules = cache_alert_rules(); }
/// WARN HERE
// We use this here.
register_html_resource('js', 'bootstrap-confirmation.js');
if (isset($vars['device']) && !isset($vars['device_id'])) { $vars['device_id'] = $vars['device']; }
if (isset($vars['entity']) && !isset($vars['entity_id'])) { $vars['entity_id'] = $vars['entity']; }
// This should be set outside, but do it here if it isn't
if (!is_array($alert_rules)) {
$alert_rules = cache_alert_rules();
}
/// WARN HERE
// Short? (no pagination, small out)
$short = (isset($vars['short']) && $vars['short']);
if (isset($vars['device']) && !isset($vars['device_id'])) {
$vars['device_id'] = $vars['device'];
}
if (isset($vars['entity']) && !isset($vars['entity_id'])) {
$vars['entity_id'] = $vars['entity'];
}
// Short? (no pagination, small out)
$short = isset($vars['short']) && $vars['short'];
list($query, $param, $query_count) = build_alert_table_query($vars);
[ $query, $param, $query_count ] = build_alert_table_query($vars);
// Fetch alerts
$count = dbFetchCell($query_count, $param);
$alerts = dbFetchRows($query, $param);
// Fetch alerts
//$count = dbFetchCell($query_count, $param);
$alerts = dbFetchRows($query, $param);
// Set which columns we're going to show.
// We hide the columns that have been given as search options via $vars
$list = array('device_id' => FALSE, 'entity_id' => FALSE, 'entity_type' => FALSE, 'alert_test_id' => FALSE);
foreach ($list as $argument => $nope) {
if (!isset($vars[$argument]) || empty($vars[$argument]) || $vars[$argument] === "all") { $list[$argument] = TRUE; }
}
// Set which columns we're going to show.
// We hide the columns that have been given as search options via $vars
$list = ['device_id' => FALSE, 'entity_id' => FALSE, 'entity_type' => FALSE, 'alert_test_id' => FALSE];
foreach ($list as $argument => $nope) {
if (!isset($vars[$argument]) || empty($vars[$argument]) || $vars[$argument] === "all") {
$list[$argument] = TRUE;
}
}
if ($vars['format'] !== "condensed") {
$list['checked'] = TRUE;
$list['changed'] = TRUE;
$list['alerted'] = TRUE;
}
if ($vars['format'] !== "condensed") {
$list['checked'] = TRUE;
$list['changed'] = TRUE;
$list['alerted'] = TRUE;
}
if ($vars['short']) {
$list['checked'] = FALSE;
$list['alerted'] = FALSE;
}
if ($vars['short']) {
$list['checked'] = FALSE;
$list['alerted'] = FALSE;
}
// Hide device if we know entity_id
if (isset($vars['entity_id'])) { $list['device_id'] = FALSE; }
// Hide entity_type if we know the alert_test_id
if (isset($vars['alert_test_id']) || TRUE) { $list['entity_type'] = FALSE; } // Hide entity types in favour of icons to save space
// Hide device if we know entity_id
if (isset($vars['entity_id'])) {
$list['device_id'] = FALSE;
}
// Hide entity_type if we know the alert_test_id
if (isset($vars['alert_test_id']) || TRUE) {
$list['entity_type'] = FALSE;
} // Hide entity types in favour of icons to save space
if ($vars['pagination'] && !$short)
{
$pagination_html = pagination($vars, $count);
echo $pagination_html;
}
if ($vars['pagination'] && !$short) {
$count = dbFetchCell($query_count, $param);
$pagination_html = pagination($vars, $count);
echo $pagination_html;
}
echo generate_box_open($vars['header']);
echo generate_box_open($vars['header']);
echo '<table class="table table-condensed table-striped table-hover">' ;
echo '<table class="table table-condensed table-striped table-hover">';
if (!get_var_true($vars['no_header'])) {
echo '
if (!get_var_true($vars['no_header'])) {
echo '
<thead>
<tr>
<th class="state-marker"></th>
<th style="width: 1px;"></th>';
if ($list['device_id']) {
echo(' <th style="width: 15%">Device</th>');
}
if ($list['entity_type']) {
echo(' <th style="width: 10%">Type</th>');
}
if ($list['entity_id']) {
echo(' <th style="">Entity</th>');
}
if ($list['alert_test_id']) {
echo(' <th style="min-width: 15%;">Alert</th>');
}
echo '
<th style="width: 100px;">Status</th>';
if ($list['checked']) {
echo ' <th style="width: 95px;">Checked</th>';
}
if ($list['changed']) {
echo ' <th style="width: 95px;">Changed</th>';
}
if ($list['alerted']) {
echo ' <th style="width: 95px;">Alerted</th>';
}
echo ' <th style="width: 70px;"></th>
</tr>
</thead>';
}
echo '<tbody>'.PHP_EOL;
foreach ($alerts as $alert) {
// Set the alert_rule from the prebuilt cache array
$alert_rule = $alert_rules[$alert['alert_test_id']];
//r($alert_rule);
$alert['severity'] = $alert_rule['severity'];
// Process the alert entry, generating colours and classes from the data
humanize_alert_entry($alert);
// Get the entity array using the cache
$entity = get_entity_by_id_cache($alert['entity_type'], $alert['entity_id']);
$entity_type = entity_type_translate_array($alert['entity_type']);
// Get the device array using the cache
$device = device_by_id_cache($alert['device_id']);
// If our parent is an actual type, we need to use the type
/* -- Currently unused.
if(isset($entity_type['parent_type']))
{
$parent_entity_type = entity_type_translate_array($entity_type['parent_type']);
$parent_entity = get_entity_by_id_cache($entity_type['parent_type'], $entity[$entity_type['parent_id_field']]);
}
*/
echo('<tr class="'.$alert['html_row_class'].'" style="cursor: pointer;" onclick="openLink(\''.generate_url(array('page' => 'device', 'device' => $device['device_id'], 'tab' => 'alert', 'alert_entry' => $alert['alert_table_id'])).'\')">');
echo('<td class="state-marker"></td>');
echo('<td style="width: 1px;"></td>');
// If we know the device, don't show the device
if ($list['device_id']) {
echo('<td><span class="entity-title">'.generate_device_link_short($device).'</span></td>');
}
// If we're showing all entity types, print the entity type here
if ($list['entity_type']) { echo('<td>'.nicecase($alert['entity_type']).'</td>'); }
// Print a link to the entity
if ($list['entity_id'])
{
echo '<td><span class="entity-title">';
// If we have a parent type, display it here.
// FIXME - this is perhaps messy. Find a better way and a better layout. We can't have a new table column because it would be empty 90% of the time!
if (isset($entity_type['parent_type']))
{
echo ' <i class="' . $config['entities'][$entity_type['parent_type']]['icon'] . '"></i> '.generate_entity_link($entity_type['parent_type'], $entity[$entity_type['parent_id_field']]).'</span> - ';
}
echo ' <i class="' . $config['entities'][$alert['entity_type']]['icon'] . '"></i> '.generate_entity_link($alert['entity_type'], $alert['entity_id'], NULL, NULL, TRUE, $short).'</span>';
echo '</td>';
}
// Print link to the alert rule page
if ($list['alert_test_id'])
{
echo '<td class="entity"><a href="', generate_url(array('page' => 'alert_check', 'alert_test_id' => $alert_rule['alert_test_id'])), '">', escape_html($alert_rule['alert_name']), '</a></td>';
}
echo('<td>');
echo('<span class="label label-'.($alert['html_row_class'] !== 'up' ? $alert['html_row_class'] : 'success').'">' . generate_tooltip_link('', $alert['status'], '<div class="small" style="max-width: 500px;"><strong>'.$alert['last_message'].'</strong></div>', $alert['alert_class']) . '</span>');
echo('</td>');
// echo('<td class="'.$alert['class'].'">'.$alert['last_message'].'</td>');
if ($list['checked']) { echo('<td>'.generate_tooltip_link('', $alert['checked'], format_unixtime($alert['last_checked'], 'r')).'</td>'); }
if ($list['changed']) { echo('<td>'.generate_tooltip_link('', $alert['changed'], format_unixtime($alert['last_changed'], 'r')).'</td>'); }
if ($list['alerted']) { echo('<td>'.generate_tooltip_link('', $alert['alerted'], format_unixtime($alert['last_alerted'], 'r')).'</td>'); }
echo('<td>');
// This stuff should go in an external entity popup in the future.
$state = safe_json_decode($alert['state']);
$alert['state_popup'] = '';
if (safe_count($state['failed'])) {
$alert['state_popup'] .= generate_box_open(array('title' => 'Failed Tests')); //'<h4>Failed Tests</h4>';
$alert['state_popup'] .= '<table style="min-width: 400px;" class="table table-striped table-condensed">';
$alert['state_popup'] .= '<thead><tr><th>Metric</th><th>Cond</th><th>Value</th><th>Measured</th></tr></thead>';
foreach($state['failed'] as $test) {
$metric_def = $config['entities'][$alert['entity_type']]['metrics'][$test['metric']];
$format = NULL;
$symbol = '';
if (!safe_empty($test['value'])) {
if (isset($metric_def['format'])) {
$format = isset($entity[$metric_def['format']]) ? $entity[$metric_def['format']] : $metric_def['format'];
}
if (isset($metric_def['symbol'])) {
$symbol = isset($entity[$metric_def['symbol']]) ? $entity[$metric_def['symbol']] : $metric_def['symbol'];
}
if ($list['device_id']) {
echo(' <th style="width: 15%">Device</th>');
}
if ($list['entity_type']) {
echo(' <th style="width: 10%">Type</th>');
}
if ($list['entity_id']) {
echo(' <th style="">Entity</th>');
}
if ($list['alert_test_id']) {
echo(' <th style="min-width: 15%;">Alert</th>');
}
$alert['state_popup'] .= '<tr><td><strong>'.$test['metric'].'</strong></td><td>'.$test['condition'].'</td><td>'.
format_value($test['value'], $format).$symbol.'</td><td><i class="red">'.
format_value($state['metrics'][$test['metric']], $format).$symbol.'</i></td></tr>';
}
$alert['state_popup'] .= '</table>';
$alert['state_popup'] .= generate_box_close();
echo '
<th style="width: 100px;">Status</th>';
if ($list['checked']) {
echo ' <th style="width: 95px;">Checked</th>';
}
if ($list['changed']) {
echo ' <th style="width: 95px;">Changed</th>';
}
if ($list['alerted']) {
echo ' <th style="width: 95px;">Alerted</th>';
}
echo ' <th style="width: 70px;"></th>
</tr>
</thead>';
}
echo '<tbody>' . PHP_EOL;
foreach ($alerts as $alert) {
// Set the alert_rule from the prebuilt cache array
$alert_rule = $alert_rules[$alert['alert_test_id']];
//r($alert_rule);
$alert['severity'] = $alert_rule['severity'];
// Process the alert entry, generating colours and classes from the data
humanize_alert_entry($alert);
// Get the entity array using the cache
$entity = get_entity_by_id_cache($alert['entity_type'], $alert['entity_id']);
$entity_type = entity_type_translate_array($alert['entity_type']);
// Get the device array using the cache
$device = device_by_id_cache($alert['device_id']);
// If our parent is an actual type, we need to use the type
/* -- Currently unused.
if(isset($entity_type['parent_type']))
{
$parent_entity_type = entity_type_translate_array($entity_type['parent_type']);
$parent_entity = get_entity_by_id_cache($entity_type['parent_type'], $entity[$entity_type['parent_id_field']]);
}
*/
echo('<tr class="' . $alert['html_row_class'] . '" style="cursor: pointer;" onclick="openLink(\'' . generate_url(['page' => 'device', 'device' => $device['device_id'], 'tab' => 'alert', 'alert_entry' => $alert['alert_table_id']]) . '\')">');
echo('<td class="state-marker"></td>');
echo('<td style="width: 1px;"></td>');
// If we know the device, don't show the device
if ($list['device_id']) {
echo('<td><span class="entity-title">' . generate_device_link_short($device) . '</span></td>');
}
// If we're showing all entity types, print the entity type here
if ($list['entity_type']) {
echo('<td>' . nicecase($alert['entity_type']) . '</td>');
}
// Print a link to the entity
if ($list['entity_id']) {
echo '<td><span class="entity-title">';
// If we have a parent type, display it here.
// FIXME - this is perhaps messy. Find a better way and a better layout. We can't have a new table column because it would be empty 90% of the time!
if (isset($entity_type['parent_type'])) {
echo ' <i class="' . $config['entities'][$entity_type['parent_type']]['icon'] . '"></i> ' . generate_entity_link($entity_type['parent_type'], $entity[$entity_type['parent_id_field']]) . '</span> - ';
}
echo ' <i class="' . $config['entities'][$alert['entity_type']]['icon'] . '"></i> ' . generate_entity_link($alert['entity_type'], $alert['entity_id'], NULL, NULL, TRUE, $short) . '</span>';
echo '</td>';
}
// Print link to the alert rule page
if ($list['alert_test_id']) {
echo '<td class="entity"><a href="', generate_url(['page' => 'alert_check', 'alert_test_id' => $alert_rule['alert_test_id']]), '">', escape_html($alert_rule['alert_name']), '</a></td>';
}
echo('<td>');
echo('<span class="label label-' . ($alert['html_row_class'] !== 'up' ? $alert['html_row_class'] : 'success') . '">' . generate_tooltip_link('', $alert['status'], '<div class="small" style="max-width: 500px;"><strong>' . $alert['last_message'] . '</strong></div>', $alert['alert_class']) . '</span>');
echo('</td>');
// echo('<td class="'.$alert['class'].'">'.$alert['last_message'].'</td>');
if ($list['checked']) {
echo('<td>' . generate_tooltip_link('', $alert['checked'], format_unixtime($alert['last_checked'], 'r')) . '</td>');
}
if ($list['changed']) {
echo('<td>' . generate_tooltip_link('', $alert['changed'], format_unixtime($alert['last_changed'], 'r')) . '</td>');
}
if ($list['alerted']) {
echo('<td>' . generate_tooltip_link('', $alert['alerted'], format_unixtime($alert['last_alerted'], 'r')) . '</td>');
}
echo('<td>');
// This stuff should go in an external entity popup in the future.
$state = safe_json_decode($alert['state']);
$alert['state_popup'] = '';
if (is_array($state) && isset($state['failed']) && safe_count($state['failed'])) {
$alert['state_popup'] .= generate_box_open(['title' => 'Failed Tests']); //'<h4>Failed Tests</h4>';
$alert['state_popup'] .= '<table style="min-width: 400px;" class="table table-striped table-condensed">';
$alert['state_popup'] .= '<thead><tr><th>Metric</th><th>Cond</th><th>Value</th><th>Measured</th></tr></thead>';
foreach ($state['failed'] as $test) {
$metric_def = $config['entities'][$alert['entity_type']]['metrics'][$test['metric']];
$format = NULL;
$symbol = '';
if (!safe_empty($test['value'])) {
if (isset($metric_def['format'])) {
$format = isset($entity[$metric_def['format']]) ? $entity[$metric_def['format']] : $metric_def['format'];
}
if (isset($metric_def['symbol'])) {
$symbol = isset($entity[$metric_def['symbol']]) ? $entity[$metric_def['symbol']] : $metric_def['symbol'];
}
}
$alert['state_popup'] .= '<tr><td><strong>' . $test['metric'] . '</strong></td><td>' . $test['condition'] . '</td><td>' .
format_value($test['value'], $format) . $symbol . '</td><td><i class="red">' .
format_value($state['metrics'][$test['metric']], $format) . $symbol . '</i></td></tr>';
}
$alert['state_popup'] .= '</table>';
$alert['state_popup'] .= generate_box_close();
}
$alert['state_popup'] .= generate_entity_popup_graphs($alert, ['entity_type' => 'alert_entry']);
// Print (i) icon with popup of state.
echo(overlib_link('', get_icon('info-sign', 'text-primary'), $alert['state_popup'], NULL));
echo('&nbsp;&nbsp;<a href="' . generate_url(['page' => 'device', 'device' => $device['device_id'], 'tab' => 'alert', 'alert_entry' => $alert['alert_table_id']]) . '">' .
get_icon('edit', 'text-muted') . '</a>');
//echo '&nbsp;&nbsp;<a onclick="alert_ignore_until_ok('.$alert['alert_table_id'].')"><i class="icon-pause text-warning"></i></a>';
echo '&nbsp;&nbsp;';
$form = [
'type' => 'simple',
//'userlevel' => 10, // Minimum user level for display form
'id' => 'alert_entry_ignore_until_ok_' . $alert['alert_table_id'],
'style' => 'display:inline;',
];
$form['row'][0]['form_alert_table_id'] = [
'type' => 'hidden',
'value' => $alert['alert_table_id']
];
$form['row'][99]['form_alert_table_action'] = [
'type' => 'submit',
'icon_only' => TRUE, // hide button styles
'name' => '',
'readonly' => get_var_true($alert['alert_status'], '3'), // alert_status == 3 mean suppressed
'icon' => get_var_true($alert['alert_status'], '3') ? 'icon-ok-circle text-muted' : 'icon-ok-sign text-muted',
// confirmation dialog
'attribs' => [
'data-toggle' => 'confirm', // Enable confirmation dialog
'data-confirm-placement' => 'left',
'data-confirm-content' => 'Ignore until ok?',
//'data-confirm-content' => '<div class="alert alert-warning"><h4 class="alert-heading"><i class="icon-warning-sign"></i> Warning!</h4>
// This association will be deleted!</div>'),
],
'value' => 'alert_entry_ignore_until_ok'
];
// Only show ignore-until button if userlevel is above 8
if ($_SESSION['userlevel'] >= 8) {
//print_form($form);
unset($form);
echo '<i class="icon-ok-sign text-muted" data-toggle="confirmation" data-placement="left" data-title="Ignore until OK?" onclick="confirmAction(\'alert_entry_ignore_until_ok\', this, event)" data-value="'.$alert['alert_table_id'].'"></i>';
}
echo('</td>');
echo('</tr>');
}
$alert['state_popup'] .= generate_entity_popup_graphs($alert, array('entity_type' => 'alert_entry'));
echo ' </tbody>' . PHP_EOL;
echo '</table>' . PHP_EOL;
// Print (i) icon with popup of state.
echo(overlib_link('', get_icon('info-sign', 'text-primary'), $alert['state_popup'], NULL));
echo generate_box_close();
echo('&nbsp;&nbsp;<a href="'.generate_url([ 'page' => 'device', 'device' => $device['device_id'], 'tab' => 'alert', 'alert_entry' => $alert['alert_table_id'] ]) . '">' .
get_icon('edit', 'text-muted') . '</a>');
//echo '&nbsp;&nbsp;<a onclick="alert_ignore_until_ok('.$alert['alert_table_id'].')"><i class="icon-pause text-warning"></i></a>';
if ($vars['pagination'] && !$short) {
echo $pagination_html;
}
}
echo '&nbsp;&nbsp;';
function generate_alert_metrics_table($entity_type, &$metrics_list = []) {
global $config;
$form = [
'type' => 'simple',
//'userlevel' => 10, // Minimum user level for display form
'id' => 'alert_entry_ignore_until_ok_'.$alert['alert_table_id'],
'style' => 'display:inline;',
];
$form['row'][0]['form_alert_table_id'] = [
'type' => 'hidden',
'value' => $alert['alert_table_id']
];
$form['row'][99]['action'] = [
'type' => 'submit',
'icon_only' => TRUE, // hide button styles
'name' => '',
'readonly' => get_var_true($alert['alert_status'], '3'), // alert_status == 3 mean suppressed
'icon' => get_var_true($alert['alert_status'], '3') ? 'icon-ok-circle text-muted' : 'icon-ok-sign text-muted',
// confirmation dialog
'attribs' => [
'data-toggle' => 'confirm', // Enable confirmation dialog
'data-confirm-placement' => 'left',
'data-confirm-content' => 'Ignore until ok?',
//'data-confirm-content' => '<div class="alert alert-warning"><h4 class="alert-heading"><i class="icon-warning-sign"></i> Warning!</h4>
// This association will be deleted!</div>'),
],
'value' => 'alert_entry_ignore_until_ok'
];
// Only show ignore-until button if userlevel is above 8
if ($_SESSION['userlevel'] >= 8) {
print_form($form);
unset($form);
$metrics_list = [];
foreach ($config['entities'][$entity_type]['metrics'] as $metric => $entry) {
$metric_list = [
'metric' => $metric,
'description' => $entry['label'],
];
$metric_list['values'] = '';
if (is_array($entry['values'])) {
if (is_array_list($entry['values'])) {
$values = $entry['values'];
} else {
$values = [];
foreach ($entry['values'] as $value => $descr) {
$values[] = "$value ($descr)";
}
}
$metric_list['values'] = '<span class="label">' . implode('</span> <span class="label">', $values) . '</span>';
} elseif ($entry['type'] === 'integer') {
$metric_list['values'] = escape_html('<numeric>');
if (str_contains($metric, 'value')) {
$metric_list['values'] .= '<br />';
// some table fields
foreach (['limit_high', 'limit_high_warn', 'limit_low', 'limit_low_warn'] as $field) {
if (isset($config['entities'][$entity_type]['table_fields'][$field])) {
$metric_list['values'] .= '<span class="label">@' . $config['entities'][$entity_type]['table_fields'][$field] . '</span> ';
}
}
}
} else {
$metric_list['values'] = escape_html('<' . $entry['type'] . '>');
}
$metrics_list[] = $metric_list;
//$metrics_list[] = '<span class="label">'.$metric.'</span>&nbsp;-&nbsp;'.$entry['label'];
}
echo('</td>');
echo('</tr>');
// Common:
$metrics_list[] = [
'metric' => '',
'description' => '<Any metric>',
'values' => '<span class="label">@previous</span>'
];
$metrics_list[] = [
'metric' => 'time',
'description' => 'Time',
'values' => 'Format <code>HHdd</code> like <strong>1630</strong>'
];
$metrics_list[] = [
'metric' => 'weekday',
'description' => 'Weekday',
'values' => 'Day of the week as a number from Monday as <strong>1</strong> to Sunday as <strong>7</strong>'
];
}
$metrics_opts = [
'columns' => [
['Metrics', 'style="width: 5%;"'],
'Description',
'Values'
],
'metric' => ['class' => 'label'],
'description' => ['class' => 'text-nowrap'],
'values' => ['escape' => FALSE]
];
echo ' </tbody>'.PHP_EOL;
echo '</table>'.PHP_EOL;
echo generate_box_close();
if ($vars['pagination'] && !$short)
{
echo $pagination_html;
}
return '<div class="col-md-12" style="padding: 0;">' . PHP_EOL .
generate_box_open([ 'title' => 'List of known metrics:', 'title-style' => 'font-size: 16px;', 'box-style' => 'margin: 10px 0 0;' ]) . PHP_EOL .
build_table($metrics_list, $metrics_opts) . PHP_EOL .
generate_box_close() . PHP_EOL .
'</div>';
}
// EOF

View File

@ -6,7 +6,7 @@
*
* @package observium
* @subpackage web
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2022 Observium Limited
* @copyright (C) Adam Armstrong
*
*/
@ -22,157 +22,210 @@
* print_alert_log(array('short' => TRUE)) - show small block with last events
*
* @param array $vars
*
* @return none
*
*/
function print_alert_log($vars)
{
function print_alert_log($vars) {
global $alert_rules;
global $alert_rules, $config;
// This should be set outside, but do it here if it isn't
if (!is_array($alert_rules)) { $alert_rules = cache_alert_rules(); }
// Get events array
$events = get_alert_log($vars);
if (!$events['count'])
{
if(!$vars['no_empty_message']) {
// There have been no entries returned. Print the warning.
print_message('<h4>No alert log entries found!</h4>', FALSE);
// This should be set outside, but do it here if it isn't
if (!is_array($alert_rules)) {
$alert_rules = cache_alert_rules();
}
} else {
// Entries have been returned. Print the table.
$list = array('device' => FALSE, 'entity' => FALSE);
if (!isset($vars['device']) || empty($vars['device']) || $vars['page'] == 'alert_log') { $list['device'] = TRUE; }
if ($events['short'] || !isset($vars['entity']) || empty($vars['entity'])) { $list['entity'] = TRUE; }
if (!isset($vars['alert_test_id']) || empty($vars['alert_test_id']) || $vars['page'] == 'alert_check' || TRUE) { $list['alert_test_id'] = TRUE; }
if (!isset($vars['entity_type']) || empty($vars['entity_type']) || $vars['page'] == 'alert_check' || TRUE) { $list['entity_type'] = TRUE; }
$string = generate_box_open($vars['header']);
// Get events array
$events = get_alert_log($vars);
$string .= '<table class="table table-striped table-hover table-condensed-more">' . PHP_EOL;
if (!$events['short'])
{
$cols = array();
$cols[] = array(NULL, 'class="state-marker"');
$cols['date'] = array('Date', 'style="width: 160px"');
if ($list['device']) { $cols['device'] = 'Device'; }
if ($list['alert_test_id']) { $cols['alert_test_id'] = 'Alert Check'; }
if ($list['entity']) { $cols['entity'] = 'Entity'; }
$cols[] = 'Message';
$cols['status'] = 'Status';
//$cols['notified'] = array('Notified', 'style="width: 40px"');
$string .= get_table_header($cols); // , $vars); // Actually sorting is disabled now
}
$string .= ' <tbody>' . PHP_EOL;
foreach ($events['entries'] as $entry)
{
$alert_rule = $alert_rules[$entry['alert_test_id']];
// Functionize?
// Set colours and classes based on the status of the alert
switch ($entry['log_type']) {
case 'OK':
$entry['class'] = "green";
$entry['html_row_class'] = "success";
break;
case 'RECOVER_NOTIFY':
$entry['class'] = "green";
$entry['html_row_class'] = "info";
break;
case 'ALERT_NOTIFY':
case 'FAIL':
$entry['class'] = "red";
$entry['html_row_class'] = "error";
break;
case 'FAIL_DELAYED':
$entry['class'] = "purple";
$entry['html_row_class'] = "warning";
break;
case 'FAIL_SUPPRESSED':
case 'RECOVER_SUPPRESSED':
$entry['class'] = "purple";
$entry['html_row_class'] = "suppressed";
break;
default:
// Anything else set the colour to grey and the class to disabled.
$entry['class'] = "gray";
$entry['html_row_class'] = "disabled";
}
$string .= ' <tr class="'.$entry['html_row_class'].'">' . PHP_EOL;
$string .= '<td class="state-marker"></td>' . PHP_EOL;
if ($events['short']) {
$string .= ' <td class="syslog text-nowrap">';
$string .= generate_tooltip_time($entry['timestamp']) . '</td>' . PHP_EOL;
} else {
$string .= ' <td>';
$string .= format_timestamp($entry['timestamp']) . '</td>' . PHP_EOL;
}
if ($list['device'])
{
$dev = device_by_id_cache($entry['device_id']);
$device_vars = array('page' => 'device',
'device' => $entry['device_id'],
'tab' => 'logs',
'section' => 'alertlog');
$string .= ' <td class="entity">' . generate_device_link_short($dev, $device_vars) . '</td>' . PHP_EOL;
}
if ($list['alert_test_id']) { $string .= ' <td class="entity"><a href="'. generate_url(array('page' => 'alert_check', 'alert_test_id' => $alert_rule['alert_test_id'])). '">'. escape_html($alert_rule['alert_name']). '</a></td>'; }
if ($list['entity'])
{
$string .= ' <td class="entity">';
if ($list['entity_type']) { $string .= '<i class="' . $config['entities'][$entry['entity_type']]['icon'] . '"></i> '; }
if($events['short'])
{
$string .= ' ' . generate_entity_link($entry['entity_type'], $entry['entity_id'], NULL, NULL, NULL, TRUE) . '</td>' . PHP_EOL;
} else {
$string .= ' ' . generate_entity_link($entry['entity_type'], $entry['entity_id']) . '</td>' . PHP_EOL;
if (!$events['count']) {
if (!$vars['no_empty_message']) {
// There have been no entries returned. Print the warning.
print_message('<h4>No alert log entries found!</h4>', FALSE);
}
}
$string .= '<td>' . escape_html($entry['message']) . '</td>' . PHP_EOL;
if (!$vars['short'])
{
$string .= '<td>' . escape_html($entry['log_type']) . '</td>' . PHP_EOL;
/*
$string .= '<td class="text-right">';
if ($entry['notified'])
{
$string .= '<span class="label label-success">OK</span>';
} else if (!stristr($entry['log_type'], 'notify')) {
$string .= '<span class="label">SKIP</span>';
} else {
$string .= '<span class="label label-warning">NO</span>';
} else {
// Entries have been returned. Print the table.
$list = [
'device' => FALSE,
'entity' => FALSE,
'info' => !$events['short'] // informational icon
];
if (empty($vars['device']) || $vars['page'] == 'alert_log') {
$list['device'] = TRUE;
}
if ($events['short'] || empty($vars['entity'])) {
$list['entity'] = TRUE;
}
$string .= '</td>' . PHP_EOL;
*/
}
$string .= ' </tr>' . PHP_EOL;
if (empty($vars['alert_test_id']) || $vars['page'] == 'alert_check' || TRUE) {
$list['alert_test_id'] = TRUE;
}
if (empty($vars['entity_type']) || $vars['page'] == 'alert_check' || TRUE) {
$list['entity_type'] = TRUE;
}
$string = generate_box_open($vars['header']);
$string .= '<table class="table table-striped table-hover table-condensed-more">' . PHP_EOL;
if (!$events['short']) {
$cols = [];
$cols[] = [NULL, 'class="state-marker"'];
$cols['date'] = ['Date', 'style="width: 160px"'];
if ($list['device']) {
$cols['device'] = 'Device';
}
if ($list['alert_test_id']) {
$cols['alert_test_id'] = 'Alert Check';
}
if ($list['entity']) {
$cols['entity'] = 'Entity';
}
$cols[] = 'Message';
$cols['status'] = 'Status';
//$cols['notified'] = array('Notified', 'style="width: 40px"');
if ($list['info']) {
$cols['info'] = [NULL, 'style="width: 10px"'];
}
$string .= get_table_header($cols); // , $vars); // Actually sorting is disabled now
}
$string .= ' <tbody>' . PHP_EOL;
foreach ($events['entries'] as $entry) {
$alert_rule = $alert_rules[$entry['alert_test_id']];
// Functionize?
// Set colours and classes based on the status of the alert
switch ($entry['log_type']) {
case 'OK':
$entry['class'] = "green";
$entry['html_row_class'] = "success";
break;
case 'RECOVER_NOTIFY':
$entry['class'] = "green";
$entry['html_row_class'] = "info";
break;
case 'REMINDER_NOTIFY':
case 'ALERT_NOTIFY':
case 'FAIL':
$entry['class'] = "red";
$entry['html_row_class'] = "error";
break;
case 'FAIL_DELAYED':
$entry['class'] = "purple";
$entry['html_row_class'] = "warning";
break;
case 'FAIL_SUPPRESSED':
case 'RECOVER_SUPPRESSED':
$entry['class'] = "purple";
$entry['html_row_class'] = "suppressed";
break;
default:
// Anything else set the color to gray.
$entry['class'] = "gray";
$entry['html_row_class'] = "disabled";
}
$string .= ' <tr class="' . $entry['html_row_class'] . '">' . PHP_EOL;
$string .= '<td class="state-marker"></td>' . PHP_EOL;
if ($events['short']) {
$string .= ' <td class="syslog text-nowrap">';
$string .= generate_tooltip_time($entry['timestamp']) . '</td>' . PHP_EOL;
} else {
$string .= ' <td>';
$string .= format_timestamp($entry['timestamp']) . '</td>' . PHP_EOL;
}
if ($list['device']) {
$dev = device_by_id_cache($entry['device_id']);
$device_vars = [
'page' => 'device',
'device' => $entry['device_id'],
'tab' => 'logs',
'section' => 'alertlog'
];
$string .= ' <td class="entity">' . generate_device_link_short($dev, $device_vars) . '</td>' . PHP_EOL;
}
if ($list['alert_test_id']) {
$string .= ' <td class="entity"><a href="' . generate_url(['page' => 'alert_check', 'alert_test_id' => $alert_rule['alert_test_id']]) . '">' . escape_html($alert_rule['alert_name']) . '</a></td>';
}
if ($list['entity']) {
$string .= ' <td class="entity">';
if ($list['entity_type']) {
$string .= get_icon($GLOBALS['config']['entities'][$entry['entity_type']]['icon']) . ' ';
}
if ($events['short']) {
$string .= ' ' . generate_entity_link($entry['entity_type'], $entry['entity_id'], NULL, NULL, NULL, TRUE) . '</td>' . PHP_EOL;
} else {
$string .= ' ' . generate_entity_link($entry['entity_type'], $entry['entity_id']) . '</td>' . PHP_EOL;
}
}
$string .= '<td>' . escape_html($entry['message']) . '</td>' . PHP_EOL;
if (!$vars['short']) {
$string .= '<td>' . escape_html($entry['log_type']) . '</td>' . PHP_EOL;
/*
$string .= '<td class="text-right">';
if ($entry['notified'])
{
$string .= '<span class="label label-success">OK</span>';
} else if (!stristr($entry['log_type'], 'notify')) {
$string .= '<span class="label">SKIP</span>';
} else {
$string .= '<span class="label label-warning">NO</span>';
}
$string .= '</td>' . PHP_EOL;
*/
}
if ($list['info']) {
$state = '';
if ($log_state = safe_json_decode($entry['log_state'])) {
// Metrics
$state = generate_box_open(['title' => 'Polled values', 'header-border' => TRUE,
//'body-style' => 'padding: 0px !important;',
'box-style' => 'margin-bottom: 0px;']);
$state .= '<table class="table table-striped table-condensed-more">';
$state .= '<thead><tr><th>Metric</th><th>Value</th></tr><thead>';
$state .= '<tbody>';
$failed = [];
foreach ($log_state['failed'] as $metric) {
$failed[$metric['metric']] = $metric['metric'];
}
//r($log_state['failed']);
foreach ($log_state['metrics'] as $metric => $value) {
$value = format_value($value);
if (isset($failed[$metric])) {
$value = '<i class="red">' . $value . '</i>';
}
$state .= "<tr><td>$metric</td><td>$value</td></tr>";
}
$state .= '<tbody></table>';
$state = generate_tooltip_link(NULL, get_icon('info'), $state);
$state .= generate_box_close();
}
$string .= '<td>' . $state . '</td>' . PHP_EOL;
}
$string .= ' </tr>' . PHP_EOL;
}
$string .= ' </tbody>' . PHP_EOL;
$string .= '</table>';
$string .= generate_box_close();
// Print pagination header
if ($events['pagination_html']) {
$string = $events['pagination_html'] . $string . $events['pagination_html'];
}
// Print events
echo $string;
}
$string .= ' </tbody>' . PHP_EOL;
$string .= '</table>';
$string .= generate_box_close();
// Print pagination header
if ($events['pagination_html']) { $string = $events['pagination_html'] . $string . $events['pagination_html']; }
// Print events
echo $string;
}
}
/**
@ -182,14 +235,15 @@ function print_alert_log($vars)
* print_alert_log(array('short' => TRUE))
*
* @param array $vars
*
* @return none
*
*/
function print_alert_log_short($var)
{
$var['short'] = TRUE;
print_alert_log($var);
$var['short'] = TRUE;
print_alert_log($var);
}
/**
@ -201,127 +255,132 @@ function print_alert_log_short($var)
function get_alert_log($vars)
{
$array = array();
$array = [];
// Short events? (no pagination, small out)
$array['short'] = (isset($vars['short']) && $vars['short']);
// Short events? (no pagination, small out)
$array['short'] = (isset($vars['short']) && $vars['short']);
// With pagination? (display page numbers in header)
$array['pagination'] = (isset($vars['pagination']) && $vars['pagination']);
pagination($vars, 0, TRUE); // Get default pagesize/pageno
$array['pageno'] = $vars['pageno'];
$array['pagesize'] = $vars['pagesize'];
$start = $array['pagesize'] * $array['pageno'] - $array['pagesize'];
$pagesize = $array['pagesize'];
// With pagination? (display page numbers in header)
$array['pagination'] = (isset($vars['pagination']) && $vars['pagination']);
pagination($vars, 0, TRUE); // Get default pagesize/pageno
$array['pageno'] = $vars['pageno'];
$array['pagesize'] = $vars['pagesize'];
$start = $array['pagesize'] * $array['pageno'] - $array['pagesize'];
$pagesize = $array['pagesize'];
// Begin query generate
$param = array();
$where = ' WHERE 1 ';
foreach ($vars as $var => $value)
{
if ($value != '')
{
switch ($var)
{
// Begin query generate
$param = [];
$where = ' WHERE 1 ';
foreach ($vars as $var => $value) {
if (!safe_empty($value)) {
switch ($var) {
// case 'alert_entry':
// $where .= generate_query_values_and($value, 'alert_table_id');
// break;
case 'log_type':
$where .= generate_query_values_and($value, 'log_type');
break;
case 'alert_test_id':
$where .= generate_query_values_and($value, 'alert_test_id');
break;
case 'device':
case 'device_id':
$where .= generate_query_values_and($value, 'device_id');
break;
case 'entity_id':
$where .= generate_query_values_and($value, 'entity_id');
break;
case 'entity_type':
$where .= generate_query_values_and($value, 'entity_type');
break;
case 'message':
$where .= generate_query_values_and($value, 'message', '%LIKE%');
break;
case 'timestamp_from':
$where .= ' AND `timestamp` >= ?';
$param[] = $value;
break;
case 'timestamp_to':
$where .= ' AND `timestamp` <= ?';
$param[] = $value;
break;
}
case 'log_type':
$where .= generate_query_values_and($value, 'log_type');
break;
case 'alert_test_id':
$where .= generate_query_values_and($value, 'alert_test_id');
break;
case 'device':
case 'device_id':
$where .= generate_query_values_and($value, 'device_id');
break;
case 'entity_id':
$where .= generate_query_values_and($value, 'entity_id');
break;
case 'entity_type':
$where .= generate_query_values_and($value, 'entity_type');
break;
case 'message':
$where .= generate_query_values_and($value, 'message', '%LIKE%');
break;
case 'timestamp_from':
$where .= ' AND `timestamp` >= ?';
$param[] = $value;
break;
case 'timestamp_to':
$where .= ' AND `timestamp` <= ?';
$param[] = $value;
break;
}
}
}
}
// Show events only for permitted devices
$query_permitted = generate_query_permitted(); //generate_query_permitted(array('entity'));
// Show events only for permitted devices
$query_permitted = generate_query_permitted(); //generate_query_permitted(array('entity'));
$query = 'FROM `alert_log` ';
$query .= $where . $query_permitted;
$query_count = 'SELECT COUNT(`event_id`) '.$query;
$query_updated = 'SELECT MAX(`timestamp`) '.$query;
$query = 'FROM `alert_log` ';
$query .= $where . $query_permitted;
$query_count = 'SELECT COUNT(`event_id`) ' . $query;
$query_updated = 'SELECT MAX(`timestamp`) ' . $query;
$query = 'SELECT * '.$query;
$query .= ' ORDER BY `event_id` DESC ';
$query .= "LIMIT $start,$pagesize";
$query = 'SELECT * ' . $query;
$query .= ' ORDER BY `event_id` DESC ';
$query .= "LIMIT $start,$pagesize";
// Query events
$array['entries'] = dbFetchRows($query, $param);
// Query events
$array['entries'] = dbFetchRows($query, $param);
// Query events count
if ($array['pagination'] && !$array['short'])
{
$array['count'] = dbFetchCell($query_count, $param);
$array['pagination_html'] = pagination($vars, $array['count']);
} else {
$array['count'] = safe_count($array['entries']);
}
// Query events count
if ($array['pagination'] && !$array['short']) {
$array['count'] = dbFetchCell($query_count, $param);
$array['pagination_html'] = pagination($vars, $array['count']);
} else {
$array['count'] = safe_count($array['entries']);
}
// Query for last timestamp
$array['updated'] = dbFetchCell($query_updated, $param);
// Query for last timestamp
$array['updated'] = dbFetchCell($query_updated, $param);
return $array;
return $array;
}
function generate_alert_log_form_values($form_filter = FALSE, $column = NULL)
{
//global $cache;
function generate_alert_log_form_values($form_filter = FALSE, $column = NULL) {
//global $cache;
$form_items = array();
$filter = is_array($form_filter); // Use filer or not
$form_items = [];
$filter = is_array($form_filter); // Use filer or not
switch ($column)
{
case 'alert_test_id':
foreach ($GLOBALS['alert_rules'] as $alert_test_id => $entry)
{
if ($filter && !in_array($alert_test_id, $form_filter)) { continue; } // Skip filtered entries
switch ($column) {
case 'alert_test_id':
foreach ($GLOBALS['alert_rules'] as $alert_test_id => $entry) {
if ($filter && !in_array($alert_test_id, $form_filter)) {
continue;
} // Skip filtered entries
$form_items[$alert_test_id] = $entry['alert_name'];
}
natcasesort($form_items);
break;
case 'log_type':
foreach (array('OK','FAIL','FAIL_DELAYED','FAIL_SUPPRESSED','ALERT_NOTIFY','RECOVER_NOTIFY','RECOVER_SUPPRESSED') as $entry)
{
if ($filter && !in_array($entry, $form_filter)) { continue; } // Skip filtered entries
$form_items[$alert_test_id] = $entry['alert_name'];
}
natcasesort($form_items);
break;
case 'log_type':
foreach ([ 'OK', 'FAIL', 'FAIL_DELAYED', 'FAIL_SUPPRESSED', 'ALERT_NOTIFY',
'REMINDER_NOTIFY', 'RECOVER_NOTIFY', 'RECOVER_SUPPRESSED' ] as $entry) {
if ($filter && !in_array($entry, $form_filter)) {
continue;
} // Skip filtered entries
// Set colours and classes based on the status of the alert
if (strstr($entry, 'OK')) { $class = "success"; }
else if (strstr($entry, 'SUPPRESSED')) { $class = "suppressed"; }
else if (strstr($entry, 'DELAYED')) { $class = "warning"; }
else if (strstr($entry, 'ALERT') || strstr($entry, 'FAIL')) { $class = "danger"; }
else if (strstr($entry, 'RECOVER')) { $class = "info"; }
else { $class = "disabled"; }
$form_items[$entry] = array('name' => $entry, 'class' => 'bg-'.$class);
}
break;
}
return $form_items;
// Set colours and classes based on the status of the alert
if (str_contains($entry, 'OK')) {
$class = "success";
} elseif (str_contains($entry, 'SUPPRESSED')) {
$class = "suppressed";
} elseif (str_contains($entry, 'DELAYED')) {
$class = "warning";
} elseif (str_contains_array($entry, [ 'ALERT', 'FAIL', 'REMINDER' ])) {
$class = "danger";
} elseif (str_contains($entry, 'RECOVER')) {
$class = "info";
} else {
$class = "disabled";
}
$form_items[$entry] = ['name' => $entry, 'class' => 'bg-' . $class];
}
break;
}
return $form_items;
}
// EOF

View File

@ -4,9 +4,9 @@
*
* This file is part of Observium.
*
* @package observium
* @subpackage web
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2022 Observium Limited
* @package observium
* @subpackage web
* @copyright (C) Adam Armstrong
*
*/
@ -16,170 +16,193 @@
* Display pages with ARP/NDP tables addresses from devices.
*
* @param array $vars
*
* @return none
*
*/
function print_arptable($vars)
{
// With pagination? (display page numbers in header)
$pagination = (isset($vars['pagination']) && $vars['pagination']);
pagination($vars, 0, TRUE); // Get default pagesize/pageno
$pageno = $vars['pageno'];
$pagesize = $vars['pagesize'];
$start = $pagesize * $pageno - $pagesize;
// With pagination? (display page numbers in header)
$pagination = (isset($vars['pagination']) && $vars['pagination']);
pagination($vars, 0, TRUE); // Get default pagesize/pageno
$pageno = $vars['pageno'];
$pagesize = $vars['pagesize'];
$start = $pagesize * $pageno - $pagesize;
$param = array();
$where = ' WHERE 1 ';
foreach ($vars as $var => $value)
{
if ($value != '')
{
switch ($var)
{
case 'device':
case 'device_id':
$where .= generate_query_values_and($value, 'device_id');
break;
case 'port':
case 'port_id':
$where .= generate_query_values_and($value, 'I.port_id');
break;
case 'ip_version':
$where .= generate_query_values_and($value, 'ip_version');
break;
case 'address':
if (isset($vars['searchby']) && $vars['searchby'] === 'ip')
{
$value = trim($value);
if (str_contains($value, ':')) {
if (get_ip_version($value) === 5)
{
$value = ip_uncompress($value);
} else {
// FIXME. Need another conversion ("2001:b08:b08" -> "2001:0b08:0b08") -- mike
}
$param = [];
$where = ' WHERE 1 ';
foreach ($vars as $var => $value) {
if ($value != '') {
switch ($var) {
case 'device':
case 'device_id':
$where .= generate_query_values_and($value, 'device_id');
break;
case 'port':
case 'port_id':
$where .= generate_query_values_and($value, 'port_id');
break;
case 'ip_version':
$where .= generate_query_values_and($value, 'ip_version');
break;
case 'address':
if (isset($vars['searchby']) && $vars['searchby'] === 'ip') {
$value = trim($value);
if (str_contains($value, ':')) {
if (get_ip_version($value) === 5) {
$value = ip_uncompress($value);
} else {
// FIXME. Need another conversion ("2001:b08:b08" -> "2001:0b08:0b08") -- mike
}
}
$where .= generate_query_values_and($value, 'ip_address', '%LIKE%');
} else {
// MAC Addresses
$value = str_replace([':', ' ', '-', '.', '0x'], '', $value);
$where .= generate_query_values_and($value, 'mac_address', '%LIKE%');
}
break;
}
$where .= generate_query_values_and($value, 'ip_address', '%LIKE%');
} else {
// MAC Addresses
$value = str_replace([ ':', ' ', '-', '.', '0x' ], '', $value);
$where .= generate_query_values_and($value, 'mac_address', '%LIKE%');
}
break;
}
}
}
}
if(isset($vars['sort']))
{
switch($vars['sort'])
{
case "port":
$sort = " ORDER BY `I`.`port_label`";
break;
$sort_order = get_sort_order($vars);
case "ip_version":
$sort = " ORDER BY `ip_version`";
break;
if (isset($vars['sort'])) {
switch ($vars['sort']) {
case "port":
//$sort = " ORDER BY `port_label`, `mac_ifIndex`";
$sort = generate_query_sort(['-port_label', 'mac_ifIndex'], $sort_order);
break;
case "ip":
case "address":
$sort = " ORDER BY `ip_address`";
break;
case "ip_version":
//$sort = " ORDER BY `ip_version`";
$sort = generate_query_sort('ip_version', $sort_order);
break;
case "mac":
default:
$sort = " ORDER BY `mac_address`";
case "ip":
case "address":
//$sort = " ORDER BY `ip_address`";
$sort = generate_query_sort('ip_address', $sort_order);
break;
case "mac":
default:
//$sort = " ORDER BY `mac_address`";
$sort = generate_query_sort('mac_address', $sort_order);
}
}
}
// Show ARP tables only for permitted ports
$query_permitted = generate_query_permitted(array('port', 'device'), array('port_table' => 'I'));
// Show ARP tables only for permitted ports
$query_permitted = generate_query_permitted(['port', 'device'], ['port_null' => TRUE]); // allow empty port_id
$query = 'FROM `ip_mac` AS M ';
$query .= 'LEFT JOIN `ports` AS I ON I.`port_id` = M.`port_id` ';
$query .= $where . $query_permitted;
$query_count = 'SELECT COUNT(`mac_id`) ' . $query;
$query = 'SELECT * ' . $query;
$query .= $sort;
$query .= " LIMIT $start,$pagesize";
$query = 'FROM `ip_mac` ';
$query .= 'LEFT JOIN `ports` USING (`device_id`, `port_id`) ';
$query .= $where . $query_permitted;
$query_count = 'SELECT COUNT(`mac_id`) ' . $query;
$query = 'SELECT * ' . $query;
$query .= $sort;
$query .= " LIMIT $start,$pagesize";
// Query ARP/NDP table addresses
$entries = dbFetchRows($query, $param);
// Query ARP/NDP table address count
if ($pagination) { $count = dbFetchCell($query_count, $param); }
$list = array('device' => FALSE, 'port' => FALSE);
if (!isset($vars['device']) || empty($vars['device']) || $vars['page'] == 'search') { $list['device'] = TRUE; }
if (!isset($vars['port']) || empty($vars['port']) || $vars['page'] == 'search') { $list['port'] = TRUE; }
$string = generate_box_open();
$string .= '<table class="table table-striped table-hover table-condensed">' . PHP_EOL;
$cols = array(
'mac' => 'MAC Address',
'ip' => 'IP Address',
'device' => 'Device',
'port' => 'Port',
'!remote_device' => 'Remote Device',
'!remote_port' => 'Remote Port',
);
if (!$list['device']) { unset($cols['device']); }
if (!$list['port']) { unset($cols['port']); }
if (!$short)
{
$string .= get_table_header($cols, $vars); // Currently sorting is not available
}
foreach ($entries as $entry)
{
humanize_port($entry);
$ip_version = $entry['ip_version'];
$ip_address = ($ip_version == 6) ? Net_IPv6::compress($entry['ip_address']) : $entry['ip_address'];
$arp_host = dbFetchRow('SELECT * FROM `ipv'.$ip_version.'_addresses` AS A
LEFT JOIN `ports` AS I ON A.`port_id` = I.`port_id`
LEFT JOIN `devices` AS D ON D.`device_id` = I.`device_id`
WHERE A.`ipv'.$ip_version.'_address` = ?', array($ip_address));
$arp_name = ($arp_host) ? generate_device_link($arp_host) : '';
$arp_if = ($arp_host) ? generate_port_link($arp_host) : '';
if ($arp_host['device_id'] == $entry['device_id']) { $arp_name = 'Self Device'; }
if ($arp_host['port_id'] == $entry['port_id']) { $arp_if = 'Self Port'; }
$string .= ' <tr>' . PHP_EOL;
$string .= ' <td style="width: 160px;" class="entity">' . generate_popup_link('mac', format_mac($entry['mac_address'])) . '</td>' . PHP_EOL;
$string .= ' <td style="width: 140px;">' . generate_popup_link('ip', $ip_address) . '</td>' . PHP_EOL;
if ($list['device'])
{
$dev = device_by_id_cache($entry['device_id']);
$string .= ' <td class="entity" style="white-space: nowrap;">' . generate_device_link($dev) . '</td>' . PHP_EOL;
// Query ARP/NDP table addresses
$entries = dbFetchRows($query, $param);
// Query ARP/NDP table address count
if ($pagination) {
$count = dbFetchCell($query_count, $param);
}
if ($list['port'])
{
if ($entry['ifInErrors_delta'] > 0 || $entry['ifOutErrors_delta'] > 0)
{
$port_error = generate_port_link($entry, '<span class="label label-important">Errors</span>', 'port_errors');
}
$string .= ' <td class="entity">' . generate_port_link_short($entry) . ' ' . $port_error . '</td>' . PHP_EOL;
$list = ['device' => FALSE, 'port' => FALSE];
if (!isset($vars['device']) || empty($vars['device']) || $vars['page'] == 'search') {
$list['device'] = TRUE;
}
if (!isset($vars['port']) || empty($vars['port']) || $vars['page'] == 'search') {
$list['port'] = TRUE;
}
$string .= ' <td class="entity" style="width: 200px;">' . $arp_name . '</td>' . PHP_EOL;
$string .= ' <td class="entity">' . $arp_if . '</td>' . PHP_EOL;
$string .= ' </tr>' . PHP_EOL;
}
$string .= ' </tbody>' . PHP_EOL;
$string .= '</table>';
$string = generate_box_open();
$string .= generate_box_close();
$string .= '<table class="table table-striped table-hover table-condensed">' . PHP_EOL;
// Print pagination header
if ($pagination) { $string = pagination($vars, $count) . $string . pagination($vars, $count); }
$cols = [
'mac' => 'MAC Address',
'ip' => 'IP Address',
'device' => 'Device',
'port' => 'Port',
'!remote_device' => 'Remote Device',
'!remote_port' => 'Remote Port',
];
// Print ARP/NDP table
echo $string;
if (!$list['device']) {
unset($cols['device']);
}
if (!$list['port']) {
unset($cols['port']);
}
if (!$short) {
$string .= get_table_header($cols, $vars); // Currently sorting is not available
}
foreach ($entries as $entry) {
humanize_port($entry);
$ip_version = $entry['ip_version'];
$ip_address = ip_compress($entry['ip_address']);
// $arp_host = dbFetchRow('SELECT * FROM `ipv'.$ip_version.'_addresses` AS A
// LEFT JOIN `ports` AS I ON A.`port_id` = I.`port_id`
// LEFT JOIN `devices` AS D ON D.`device_id` = I.`device_id`
// WHERE A.`ipv'.$ip_version.'_address` = ?', array($ip_address));
$arp_host = dbFetchRow('SELECT * FROM `ipv' . $ip_version . '_addresses`
WHERE `ipv' . $ip_version . '_address` = ?', [$ip_address]);
if ($arp_host['device_id'] == $entry['device_id']) {
$arp_name = 'Self Device';
} else {
$arp_name = $arp_host ? generate_device_link($arp_host) : '';
}
if ($entry['port_id'] && $arp_host['port_id'] == $entry['port_id']) {
$arp_if = 'Self Port';
} else {
$arp_if = $arp_host ? generate_port_link($arp_host) : '';
}
$string .= ' <tr>' . PHP_EOL;
$string .= ' <td style="width: 160px;" class="entity">' . generate_popup_link('mac', format_mac($entry['mac_address'])) . '</td>' . PHP_EOL;
$string .= ' <td style="width: 140px;">' . generate_popup_link('ip', $ip_address) . '</td>' . PHP_EOL;
if ($list['device']) {
$dev = device_by_id_cache($entry['device_id']);
$string .= ' <td class="entity" style="white-space: nowrap;">' . generate_device_link($dev) . '</td>' . PHP_EOL;
}
if ($list['port']) {
if ($entry['ifInErrors_delta'] > 0 || $entry['ifOutErrors_delta'] > 0) {
$port_error = generate_port_link($entry, '<span class="label label-important">Errors</span>', 'port_errors');
}
if ($entry['port_id']) {
$port_string = generate_port_link_short($entry) . ' ' . $port_error;
} else {
// For VRF port_id can be unknown
$port_string = 'ifIndex ' . $entry['mac_ifIndex'];
}
$string .= ' <td class="entity">' . $port_string . '</td>' . PHP_EOL;
}
$string .= ' <td class="entity" style="width: 200px;">' . $arp_name . '</td>' . PHP_EOL;
$string .= ' <td class="entity">' . $arp_if . '</td>' . PHP_EOL;
$string .= ' </tr>' . PHP_EOL;
}
$string .= ' </tbody>' . PHP_EOL;
$string .= '</table>';
$string .= generate_box_close();
// Print pagination header
if ($pagination) {
$string = pagination($vars, $count) . $string . pagination($vars, $count);
}
// Print ARP/NDP table
echo $string;
}
// EOF

View File

@ -4,9 +4,9 @@
*
* This file is part of Observium.
*
* @package observium
* @subpackage web
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2022 Observium Limited
* @package observium
* @subpackage web
* @copyright (C) Adam Armstrong
*
*/
@ -14,169 +14,171 @@
* Display authentication log.
*
* @param array $vars
*
* @return none
*
*/
function print_authlog($vars)
{
$authlog = get_authlog_array($vars);
$authlog = get_authlog_array($vars);
if (!$authlog['count'])
{
// There have been no entries returned. Print the warning. Shouldn't happen, how did you get here without auth?!
print_warning('<h4>No authentication entries found!</h4>');
} else {
$string = generate_box_open($vars['header']);
// Entries have been returned. Print the table.
$string .= '<table class="'.OBS_CLASS_TABLE_STRIPED_MORE.'">' . PHP_EOL;
$cols = array(
//'NONE' => NULL,
'date' => array('Date', 'style="width: 150px;"'),
'user' => 'User',
'from' => 'From',
'ua' => array('User-Agent', 'style="width: 200px;"'),
'NONE' => 'Action',
);
if ($vars['page'] == 'preferences') { unset($cols['user']); }
$string .= get_table_header($cols); //, $vars); // Currently sorting is not available
$string .= '<tbody>' . PHP_EOL;
foreach ($authlog['entries'] as $entry)
{
if (strlen($entry['user_agent']) > 1)
{
$entry['detect_browser'] = detect_browser($entry['user_agent']);
//r($entry['detect_browser']);
$entry['user_agent'] = '<i class="' . $entry['detect_browser']['icon'] . '"></i>&nbsp;' . $entry['detect_browser']['browser_full'];
if ($entry['detect_browser']['platform'])
{
$entry['user_agent'] .= ' ('.$entry['detect_browser']['platform'].')';
if (!$authlog['count']) {
// There have been no entries returned. Print the warning. Shouldn't happen, how did you get here without auth?!
print_warning('<h4>No authentication entries found!</h4>');
} else {
$string = generate_box_open($vars['header']);
// Entries have been returned. Print the table.
$string .= '<table class="' . OBS_CLASS_TABLE_STRIPED_MORE . '">' . PHP_EOL;
$cols = [
[ 'date' => 'Date', 'style' => 'width: 150px;' ],
'user' => [ 'user' => 'User' ],
[ 'from' => 'From' ],
[ 'ua' => 'User-Agent', 'style' => 'width: 200px;' ],
[ 'Action' ],
];
if ($vars['page'] == 'preferences') {
unset($cols['user']);
}
}
if (strstr(strtolower($entry['result']), 'fail', true)) { $class = " class=\"error\""; } else { $class = ""; }
$string .= '
<tr'.$class.'>
<td>'.$entry['datetime'].'</td>';
if (isset($cols['user']))
{
$string .= '
<td>'.escape_html($entry['user']).'</td>';
}
$string .= '
<td>'. ($_SESSION['userlevel'] > 5 ? generate_popup_link('ip', $entry['address']) : preg_replace('/^\d+/', '*', $entry['address'])) . '</td>
<td>'.$entry['user_agent'].'</td>
<td>'.$entry['result'].'</td>
$string .= generate_table_header($cols); //, $vars); // Currently sorting is not available
$string .= '<tbody>' . PHP_EOL;
foreach ($authlog['entries'] as $entry) {
if (!safe_empty($entry['user_agent'])) {
$entry['detect_browser'] = detect_browser($entry['user_agent']);
//r($entry['detect_browser']);
$entry['user_agent'] = get_icon($entry['detect_browser']['icon']) . '&nbsp;' . $entry['detect_browser']['browser_full'];
if ($entry['detect_browser']['platform']) {
$entry['user_agent'] .= ' (' . $entry['detect_browser']['platform'] . ')';
}
}
if (str_icontains_array($entry['result'], 'fail')) {
$class = " class=\"error\"";
} else {
$class = "";
}
$string .= '
<tr' . $class . '>
<td>' . $entry['datetime'] . '</td>';
if (isset($cols['user'])) {
$string .= '
<td>' . escape_html($entry['user']) . '</td>';
}
$string .= '
<td>' . ($_SESSION['userlevel'] > 5 ? generate_popup_link('ip', $entry['address']) : preg_replace('/^\d+/', '*', $entry['address'])) . '</td>
<td>' . $entry['user_agent'] . '</td>
<td>' . $entry['result'] . '</td>
</tr>' . PHP_EOL;
}
$string .= ' </tbody>' . PHP_EOL;
$string .= '</table>';
$string .= generate_box_close();
// Add pagination header
if ($authlog['pagination_html']) {
$string = $authlog['pagination_html'] . $string . $authlog['pagination_html'];
}
// Print authlog
echo $string;
}
$string .= ' </tbody>' . PHP_EOL;
$string .= '</table>';
$string .= generate_box_close();
// Add pagination header
if ($authlog['pagination_html']) { $string = $authlog['pagination_html'] . $string . $authlog['pagination_html']; }
// Print authlog
echo $string;
}
}
// DOCME needs phpdoc block
function get_authlog_array($vars)
{
$array = array();
$array = [];
// Short authlog? (no pagination, small out)
$array['short'] = (isset($vars['short']) && $vars['short']);
if ($array['short'])
{
// For short, always limit to last 10 entries
$start = 0;
$pagesize = 10;
} else {
// With pagination? (display page numbers in header)
$array['pagination'] = (isset($vars['pagination']) && $vars['pagination']);
pagination($vars, 0, TRUE); // Get default pagesize/pageno
$array['pageno'] = $vars['pageno'];
$array['pagesize'] = $vars['pagesize'];
$start = $array['pagesize'] * $array['pageno'] - $array['pagesize'];
$pagesize = $array['pagesize'];
}
// Short authlog? (no pagination, small out)
$array['short'] = (isset($vars['short']) && $vars['short']);
if ($array['short']) {
// For short, always limit to last 10 entries
$start = 0;
$pagesize = 10;
} else {
// With pagination? (display page numbers in header)
$array['pagination'] = (isset($vars['pagination']) && $vars['pagination']);
pagination($vars, 0, TRUE); // Get default pagesize/pageno
$array['pageno'] = $vars['pageno'];
$array['pagesize'] = $vars['pagesize'];
$start = $array['pagesize'] * $array['pageno'] - $array['pagesize'];
$pagesize = $array['pagesize'];
}
$query = " FROM `authlog`" . generate_authlog_where($vars);
$query = " FROM `authlog`" . generate_authlog_where($vars);
$query_count = 'SELECT COUNT(`id`) '.$query;
$query_updated = 'SELECT MAX(`datetime`) '.$query;
$query_count = 'SELECT COUNT(`id`) ' . $query;
$query_updated = 'SELECT MAX(`datetime`) ' . $query;
$where =
$query = 'SELECT * '.$query;
$query .= ' ORDER BY `datetime` DESC ';
$query .= "LIMIT $start,$pagesize";
$where =
$query = 'SELECT * ' . $query;
$query .= ' ORDER BY `datetime` DESC ';
$query .= "LIMIT $start,$pagesize";
// Query authlog
$array['entries'] = dbFetchRows($query, $param);
// Query authlog
$array['entries'] = dbFetchRows($query, $param);
// Query authlog count
if ($array['pagination'] && !$array['short'])
{
$array['count'] = dbFetchCell($query_count, $param);
$array['pagination_html'] = pagination($vars, $array['count']);
} else {
$array['count'] = safe_count($array['entries']);
}
// Query authlog count
if ($array['pagination'] && !$array['short']) {
$array['count'] = dbFetchCell($query_count, $param);
$array['pagination_html'] = pagination($vars, $array['count']);
} else {
$array['count'] = safe_count($array['entries']);
}
// Query for last timestamp
$array['updated'] = dbFetchCell($query_updated, $param);
// Query for last timestamp
$array['updated'] = dbFetchCell($query_updated, $param);
return $array;
return $array;
}
function generate_authlog_where($vars)
{
$sql = '';
$sql = '';
// Build query
foreach ($vars as $var => $value)
{
switch ($var)
{
case "user_id":
if ($value == '') { continue 2; }
$value = auth_username_by_id($value);
//break;
case "user":
case "username":
if ($value == '') { continue 2; }
$sql .= generate_query_values_and($value, 'user');
break;
case "address":
case "ip":
if ($value == '') { continue 2; }
$sql .= generate_query_values_and($value, 'address', '%LIKE%');
break;
case "useragent":
case "user_agent":
$sql .= generate_query_values_and($value, 'user_agent', '%LIKE%');
break;
case "result":
//case "action":
$sql .= generate_query_values_and($value, 'result', 'LIKE%');
break;
// Build query
foreach ($vars as $var => $value) {
switch ($var) {
case "user_id":
if ($value == '') {
continue 2;
}
$value = auth_username_by_id($value);
//break;
case "user":
case "username":
if ($value == '') {
continue 2;
}
$sql .= generate_query_values_and($value, 'user');
break;
case "address":
case "ip":
if ($value == '') {
continue 2;
}
$sql .= generate_query_values_and($value, 'address', '%LIKE%');
break;
case "useragent":
case "user_agent":
$sql .= generate_query_values_and($value, 'user_agent', '%LIKE%');
break;
case "result":
//case "action":
$sql .= generate_query_values_and($value, 'result', 'LIKE%');
break;
}
}
if (strlen($sql)) {
$sql = ' WHERE 1' . $sql;
} elseif ($_SESSION['userlevel'] != 10) {
// Complete hide for non-priveleged users
$sql = ' WHERE 0';
}
}
if (strlen($sql))
{
$sql = ' WHERE 1' . $sql;
}
else if ($_SESSION['userlevel'] != 10)
{
// Complete hide for non-priveleged users
$sql = ' WHERE 0';
}
return $sql;
return $sql;
}
// EOF

File diff suppressed because it is too large Load Diff

View File

@ -4,9 +4,9 @@
*
* This file is part of Observium.
*
* @package observium
* @subpackage web
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2022 Observium Limited
* @package observium
* @subpackage web
* @copyright (C) Adam Armstrong
*
*/
@ -14,125 +14,129 @@
* Display dot1x sessions
*
* @param array $vars
*
* @return none
*
*/
function print_dot1xtable($vars)
{
// With pagination? (display page numbers in header)
$pagination = (isset($vars['pagination']) && $vars['pagination']);
pagination($vars, 0, TRUE); // Get default pagesize/pageno
$pageno = $vars['pageno'];
$pagesize = $vars['pagesize'];
$start = $pagesize * $pageno - $pagesize;
// With pagination? (display page numbers in header)
$pagination = (isset($vars['pagination']) && $vars['pagination']);
pagination($vars, 0, TRUE); // Get default pagesize/pageno
$pageno = $vars['pageno'];
$pagesize = $vars['pagesize'];
$start = $pagesize * $pageno - $pagesize;
$param = array();
$where = ' WHERE 1 ';
foreach ($vars as $var => $value)
{
if ($value != '')
{
switch ($var)
{
case 'device':
case 'device_id':
$where .= generate_query_values_and($value, 'device_id');
break;
case 'address':
if (isset($vars['searchby']) && $vars['searchby'] === 'ip')
{
$value = trim($value);
$where .= generate_query_values_and($value, 'ipv4_addr', '%LIKE%');
} elseif (isset($vars['searchby']) && $vars['searchby'] === 'mac') {
$value = str_replace([ ':', ' ', '-', '.', '0x' ], '', $value);
$where .= generate_query_values_and($value, 'M.mac_addr', '%LIKE%');
} else {
$value = trim($value);
$where .= generate_query_values_and($value, 'username', '%LIKE%');
}
break;
}
$param = [];
$where = ' WHERE 1 ';
foreach ($vars as $var => $value) {
if ($value != '') {
switch ($var) {
case 'device':
case 'device_id':
$where .= generate_query_values_and($value, 'device_id');
break;
case 'address':
if (isset($vars['searchby']) && $vars['searchby'] === 'ip') {
$value = trim($value);
$where .= generate_query_values_and($value, 'ipv4_addr', '%LIKE%');
} elseif (isset($vars['searchby']) && $vars['searchby'] === 'mac') {
$value = str_replace([':', ' ', '-', '.', '0x'], '', $value);
$where .= generate_query_values_and($value, 'M.mac_addr', '%LIKE%');
} else {
$value = trim($value);
$where .= generate_query_values_and($value, 'username', '%LIKE%');
}
break;
}
}
}
}
// Check permissions
$query_permitted = generate_query_permitted(array('device'), array('device_table' => 'M'));
// Check permissions
$query_permitted = generate_query_permitted(['device'], ['device_table' => 'M']);
$query = 'FROM `wifi_sessions` AS M ';
$query .= 'LEFT JOIN `wifi_radios` AS I ON I.`wifi_radio_id` = M.`radio_id` ';
$query .= $where . $query_permitted;
$query_count = 'SELECT COUNT(`wifi_session_id`) ' . $query;
$query = 'SELECT *, M.`mac_addr` AS `session_mac` ' . $query;
$query .= ' ORDER BY M.`timestamp` DESC';
$query .= " LIMIT $start,$pagesize";
$query = 'FROM `wifi_sessions` AS M ';
$query .= 'LEFT JOIN `wifi_radios` AS I ON I.`wifi_radio_id` = M.`radio_id` ';
$query .= $where . $query_permitted;
$query_count = 'SELECT COUNT(`wifi_session_id`) ' . $query;
$query = 'SELECT *, M.`mac_addr` AS `session_mac` ' . $query;
$query .= ' ORDER BY M.`timestamp` DESC';
$query .= " LIMIT $start,$pagesize";
// Query wireless sessions table
$entries = dbFetchRows($query, $param);
// Query wireless sessions table count
if ($pagination) { $count = dbFetchCell($query_count, $param); }
$aps_db = dbFetchRows("SELECT `wifi_accesspoint_id`, `name`, `ap_number` FROM `wifi_accesspoints`");
foreach ($aps_db as $ap_db)
{
$aps_sorted_db[$ap_db['wifi_accesspoint_id']] = $ap_db;
}
$list = array('device' => FALSE, 'port' => FALSE); // A radio is like a port
if (!isset($vars['device']) || empty($vars['device']) || $vars['page'] == 'search') { $list['device'] = TRUE; }
if (!isset($vars['port']) || empty($vars['port']) || $vars['page'] == 'search') { $list['port'] = TRUE; }
$string = generate_box_open();
$string .= '<table class="table table-striped table-hover table-condensed">' . PHP_EOL;
if (!$short)
{
$string .= ' <thead>' . PHP_EOL;
$string .= ' <tr>' . PHP_EOL;
$string .= ' <th>MAC Address</th>' . PHP_EOL;
$string .= ' <th>IP Address</th>' . PHP_EOL;
$string .= ' <th>Username</th>' . PHP_EOL;
$string .= ' <th>SSID/VLAN</th>' . PHP_EOL;
$string .= ' <th>Last Seen</th>' . PHP_EOL;
if ($list['device']) { $string .= ' <th>Device</th>' . PHP_EOL; }
if ($list['port']) { $string .= ' <th>Interface/AP</th>' . PHP_EOL; }
$string .= ' </tr>' . PHP_EOL;
$string .= ' </thead>' . PHP_EOL;
}
$string .= ' <tbody>' . PHP_EOL;
foreach ($entries as $entry)
{
$ap_id = $entry['accesspoint_id'];
$interface = $aps_sorted_db[$ap_id]['name'];
$string .= ' <tr>' . PHP_EOL;
$string .= ' <td style="width: 140px;">' . generate_popup_link('mac', format_mac($entry['session_mac'])) . '</td>' . PHP_EOL;
$string .= ' <td style="width: 140px;">' . generate_popup_link('ip', $entry['ipv4_addr']) . '</td>' . PHP_EOL;
$string .= ' <td style="white-space: nowrap;">' . $entry['username'] . '</td>' . PHP_EOL;
$string .= ' <td style="width: 140px;">' . $entry['ssid'] . '</td>' . PHP_EOL;
$string .= ' <td style="white-space: nowrap;">' . $entry['timestamp'] . '</td>' . PHP_EOL;
if ($list['device'])
{
$dev = device_by_id_cache($entry['device_id']);
$string .= ' <td class="entity" style="white-space: nowrap;">' . generate_device_link($dev) . '</td>' . PHP_EOL;
// Query wireless sessions table
$entries = dbFetchRows($query, $param);
// Query wireless sessions table count
if ($pagination) {
$count = dbFetchCell($query_count, $param);
}
if ($list['port'])
{
$string .= ' <td class="entity"><a href="' . generate_url(array('page' => 'device', 'device' => $entry['device_id'], 'tab' => 'wifi', 'view' => 'accesspoint', 'accesspoint' => $ap_id)).'">' . $interface . '</a></td>' . PHP_EOL;
$aps_db = dbFetchRows("SELECT `wifi_accesspoint_id`, `name`, `ap_number` FROM `wifi_accesspoints`");
foreach ($aps_db as $ap_db) {
$aps_sorted_db[$ap_db['wifi_accesspoint_id']] = $ap_db;
}
$string .= ' </tr>' . PHP_EOL;
}
$string .= ' </tbody>' . PHP_EOL;
$string .= '</table>';
$string .= generate_box_close();
$list = ['device' => FALSE, 'port' => FALSE]; // A radio is like a port
if (!isset($vars['device']) || empty($vars['device']) || $vars['page'] == 'search') {
$list['device'] = TRUE;
}
if (!isset($vars['port']) || empty($vars['port']) || $vars['page'] == 'search') {
$list['port'] = TRUE;
}
// Print pagination header
if ($pagination) { $string = pagination($vars, $count) . $string . pagination($vars, $count); }
$string = generate_box_open();
// Print wireless sessions
echo $string;
$string .= '<table class="table table-striped table-hover table-condensed">' . PHP_EOL;
if (!$short) {
$string .= ' <thead>' . PHP_EOL;
$string .= ' <tr>' . PHP_EOL;
$string .= ' <th>MAC Address</th>' . PHP_EOL;
$string .= ' <th>IP Address</th>' . PHP_EOL;
$string .= ' <th>Username</th>' . PHP_EOL;
$string .= ' <th>SSID/VLAN</th>' . PHP_EOL;
$string .= ' <th>Last Seen</th>' . PHP_EOL;
if ($list['device']) {
$string .= ' <th>Device</th>' . PHP_EOL;
}
if ($list['port']) {
$string .= ' <th>Interface/AP</th>' . PHP_EOL;
}
$string .= ' </tr>' . PHP_EOL;
$string .= ' </thead>' . PHP_EOL;
}
$string .= ' <tbody>' . PHP_EOL;
foreach ($entries as $entry) {
$ap_id = $entry['accesspoint_id'];
$interface = $aps_sorted_db[$ap_id]['name'];
$string .= ' <tr>' . PHP_EOL;
$string .= ' <td style="width: 140px;">' . generate_popup_link('mac', format_mac($entry['session_mac'])) . '</td>' . PHP_EOL;
$string .= ' <td style="width: 140px;">' . generate_popup_link('ip', $entry['ipv4_addr']) . '</td>' . PHP_EOL;
$string .= ' <td style="white-space: nowrap;">' . $entry['username'] . '</td>' . PHP_EOL;
$string .= ' <td style="width: 140px;">' . $entry['ssid'] . '</td>' . PHP_EOL;
$string .= ' <td style="white-space: nowrap;">' . $entry['timestamp'] . '</td>' . PHP_EOL;
if ($list['device']) {
$dev = device_by_id_cache($entry['device_id']);
$string .= ' <td class="entity" style="white-space: nowrap;">' . generate_device_link($dev) . '</td>' . PHP_EOL;
}
if ($list['port']) {
$string .= ' <td class="entity"><a href="' . generate_url(['page' => 'device', 'device' => $entry['device_id'], 'tab' => 'wifi', 'view' => 'accesspoint', 'accesspoint' => $ap_id]) . '">' . $interface . '</a></td>' . PHP_EOL;
}
$string .= ' </tr>' . PHP_EOL;
}
$string .= ' </tbody>' . PHP_EOL;
$string .= '</table>';
$string .= generate_box_close();
// Print pagination header
if ($pagination) {
$string = pagination($vars, $count) . $string . pagination($vars, $count);
}
// Print wireless sessions
echo $string;
}
// EOF

View File

@ -6,7 +6,7 @@
*
* @package observium
* @subpackage web
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2022 Observium Limited
* @copyright (C) Adam Armstrong
*
*/
@ -22,149 +22,153 @@
* print_events(array('short' => TRUE)) - show small block with last events
*
* @param array $vars
*
* @return null
*
*/
function print_events($vars) {
global $config;
function print_events($vars)
{
global $config;
// Get events array
$events = get_events_array($vars);
// Get events array
$events = get_events_array($vars);
if (!$events['count'])
{
// There have been no entries returned. Print the warning.
print_warning('<h4>No eventlog entries found!</h4>');
} else {
// Entries have been returned. Print the table.
$list = array('device' => FALSE, 'port' => FALSE);
if (!isset($vars['device']) || empty($vars['device']) || $vars['page'] === 'eventlog') {
$list['device'] = TRUE;
}
if ($events['short'] || !isset($vars['port']) || empty($vars['port'])) {
$list['entity'] = TRUE;
}
$string = generate_box_open($vars['header']);
$string .= '<table class="'.OBS_CLASS_TABLE_STRIPED_MORE.'">' . PHP_EOL;
if (!$events['short']) {
$string .= ' <thead>' . PHP_EOL;
$string .= ' <tr>' . PHP_EOL;
$string .= ' <th class="state-marker"></th>' . PHP_EOL;
$string .= ' <th>Date</th>' . PHP_EOL;
if ($list['device']) { $string .= ' <th>Device</th>' . PHP_EOL; }
if ($list['entity']) { $string .= ' <th>Entity</th>' . PHP_EOL; }
$string .= ' <th>Message</th>' . PHP_EOL;
$string .= ' </tr>' . PHP_EOL;
$string .= ' </thead>' . PHP_EOL;
}
$string .= ' <tbody>' . PHP_EOL;
foreach ($events['entries'] as $entry)
{
switch ($entry['severity'])
{
case "0": // Emergency
case "1": // Alert
case "2": // Critical
case "3": // Error
$entry['html_row_class'] = "error";
break;
case "4": // Warning
$entry['html_row_class'] = "warning";
break;
case "5": // Notification
$entry['html_row_class'] = "recovery";
break;
case "6": // Informational
$entry['html_row_class'] = "up";
break;
case "7": // Debugging
$entry['html_row_class'] = "suppressed";
break;
default:
}
$string .= ' <tr class="'.$entry['html_row_class'].'">' . PHP_EOL;
$string .= '<td class="state-marker"></td>' . PHP_EOL;
if ($events['short']) {
$string .= ' <td class="syslog text-nowrap">';
$string .= generate_tooltip_time($entry['timestamp']) . '</td>' . PHP_EOL;
} else {
$string .= ' <td style="width: 160px">';
$string .= format_timestamp($entry['timestamp']) . '</td>' . PHP_EOL;
}
if ($entry['device_id'] == 0 && safe_empty($entry['entity_type'])) {
// Compatibility for global events
$entry['entity_type'] = 'global';
}
if ($list['device']) {
if (in_array($entry['entity_type'], [ 'global', 'info' ] )) {
// Global, Info events
$string .= ' <td class="entity"><span class="label">'.strtoupper($entry['entity_type']).'</span></td>' . PHP_EOL;
} else {
$dev = device_by_id_cache($entry['device_id']);
$device_vars = array('page' => 'device',
'device' => $entry['device_id'],
'tab' => 'logs',
'section' => 'eventlog');
$string .= ' <td class="entity">' . generate_device_link_short($dev, $device_vars) . '</td>' . PHP_EOL;
if (!$events['count']) {
// There have been no entries returned. Print the warning.
print_warning('<h4>No eventlog entries found!</h4>');
} else {
// Entries have been returned. Print the table.
$list = ['device' => FALSE, 'port' => FALSE];
if (!isset($vars['device']) || empty($vars['device']) || $vars['page'] === 'eventlog') {
$list['device'] = TRUE;
}
}
if ($list['entity']) {
if ($entry['entity_type'] === 'device' && !$entry['entity_id']) {
$entry['entity_id'] = $entry['device_id'];
if ($events['short'] || !isset($vars['port']) || empty($vars['port'])) {
$list['entity'] = TRUE;
}
if ($entry['entity_type'] === 'port') {
$this_if = get_port_by_id_cache($entry['entity_id']);
$entry['link'] = '<span class="entity">' . get_icon('port') . ' ' . generate_port_link_short($this_if) . '</span>';
} elseif ($entry['entity_type'] === 'global') {
$entry['link'] = get_icon('info');
} elseif ($entry['entity_type'] === 'info') {
$entry['link'] = get_icon('important');
} else {
if (!empty($config['entities'][$entry['entity_type']]['icon']))
{
$entry['link'] = '<i class="' . $config['entities'][$entry['entity_type']]['icon'] . '"></i> <span class="entity">'.generate_entity_link($entry['entity_type'], $entry['entity_id']).'</span>';
} else {
$entry['link'] = nicecase($entry['entity_type']);
}
$string = generate_box_open($vars['header']);
$string .= '<table class="' . OBS_CLASS_TABLE_STRIPED_MORE . '">' . PHP_EOL;
if (!$events['short']) {
$string .= ' <thead>' . PHP_EOL;
$string .= ' <tr>' . PHP_EOL;
$string .= ' <th class="state-marker"></th>' . PHP_EOL;
$string .= ' <th>Date</th>' . PHP_EOL;
if ($list['device']) {
$string .= ' <th>Device</th>' . PHP_EOL;
}
if ($list['entity']) {
$string .= ' <th>Entity</th>' . PHP_EOL;
}
$string .= ' <th>Message</th>' . PHP_EOL;
$string .= ' </tr>' . PHP_EOL;
$string .= ' </thead>' . PHP_EOL;
}
if (!$events['short']) { $string .= ' <td style="white-space: nowrap">' . $entry['link'] . '</td>' . PHP_EOL; }
}
if ($events['short'])
{
$string .= ' <td class="syslog">';
if (strpos($entry['message'], $entry['link']) !== 0)
{
$string .= $entry['link'] . ' ';
$string .= ' <tbody>' . PHP_EOL;
foreach ($events['entries'] as $entry) {
switch ($entry['severity']) {
case "0": // Emergency
case "1": // Alert
case "2": // Critical
case "3": // Error
$entry['html_row_class'] = "error";
break;
case "4": // Warning
$entry['html_row_class'] = "warning";
break;
case "5": // Notification
$entry['html_row_class'] = "recovery";
break;
case "6": // Informational
$entry['html_row_class'] = "up";
break;
case "7": // Debugging
$entry['html_row_class'] = "suppressed";
break;
default:
}
$string .= ' <tr class="' . $entry['html_row_class'] . '">' . PHP_EOL;
$string .= '<td class="state-marker"></td>' . PHP_EOL;
if ($events['short']) {
$string .= ' <td class="syslog text-nowrap">';
$string .= generate_tooltip_time($entry['timestamp']) . '</td>' . PHP_EOL;
} else {
$string .= ' <td style="width: 160px">';
$string .= format_timestamp($entry['timestamp']) . '</td>' . PHP_EOL;
}
if ($entry['device_id'] == 0 && safe_empty($entry['entity_type'])) {
// Compatibility for global events
$entry['entity_type'] = 'global';
}
if ($list['device']) {
if (in_array($entry['entity_type'], ['global', 'info'])) {
// Global, Info events
$string .= ' <td class="entity"><span class="label">' . strtoupper($entry['entity_type']) . '</span></td>' . PHP_EOL;
} else {
$dev = device_by_id_cache($entry['device_id']);
$device_vars = ['page' => 'device',
'device' => $entry['device_id'],
'tab' => 'logs',
'section' => 'eventlog'];
$string .= ' <td class="entity">' . generate_device_link_short($dev, $device_vars) . '</td>' . PHP_EOL;
}
}
if ($list['entity']) {
if ($entry['entity_type'] === 'device' && !$entry['entity_id']) {
$entry['entity_id'] = $entry['device_id'];
}
if ($entry['entity_type'] === 'port') {
$this_if = get_port_by_id_cache($entry['entity_id']);
$entry['link'] = '<span class="entity">' . get_icon('port') . ' ' . generate_port_link_short($this_if) . '</span>';
} elseif ($entry['entity_type'] === 'global') {
$entry['link'] = get_icon('info');
} elseif ($entry['entity_type'] === 'info') {
$entry['link'] = get_icon('important');
} else {
if (!empty($config['entities'][$entry['entity_type']]['icon'])) {
$entry['link'] = '<i class="' . $config['entities'][$entry['entity_type']]['icon'] . '"></i> <span class="entity">' . generate_entity_link($entry['entity_type'], $entry['entity_id']) . '</span>';
} else {
$entry['link'] = nicecase($entry['entity_type']);
}
}
if (!$events['short']) {
$string .= ' <td style="white-space: nowrap">' . $entry['link'] . '</td>' . PHP_EOL;
}
}
if ($events['short']) {
$string .= ' <td class="syslog">';
if (strpos($entry['message'], $entry['link']) !== 0) {
$string .= $entry['link'] . ' ';
}
} else {
$string .= ' <td>';
}
// Use markdown parsed for Debug events, for allow links to docs (use Markdown Extra).
$message_escape = $entry['severity'] >= 7 ? get_markdown_extra($entry['message']) : escape_html($entry['message']);
$string .= $message_escape . '</td>' . PHP_EOL;
//$string .= $entry['message'] . '</td>' . PHP_EOL;
$string .= ' </tr>' . PHP_EOL;
}
} else {
$string .= ' <td>';
}
// Use markdown parsed for Debug events, for allow links to docs (use Markdown Extra).
$message_escape = $entry['severity'] >= 7 ? get_markdown($entry['message'], TRUE, TRUE) : escape_html($entry['message']);
$string .= $message_escape . '</td>' . PHP_EOL;
//$string .= $entry['message'] . '</td>' . PHP_EOL;
$string .= ' </tr>' . PHP_EOL;
$string .= ' </tbody>' . PHP_EOL;
$string .= '</table>';
$string .= generate_box_close();
// Print pagination header
if ($events['pagination_html']) {
$string = $events['pagination_html'] . $string . $events['pagination_html'];
}
// Print events
echo $string;
}
$string .= ' </tbody>' . PHP_EOL;
$string .= '</table>';
$string .= generate_box_close();
// Print pagination header
if ($events['pagination_html']) { $string = $events['pagination_html'] . $string . $events['pagination_html']; }
// Print events
echo $string;
}
}
/**
@ -174,162 +178,165 @@ function print_events($vars) {
* print_events(array('short' => TRUE))
*
* @param array $vars
*
* @return none
*
*/
function print_events_short($var)
{
$var['short'] = TRUE;
print_events($var);
function print_events_short($var) {
$var['short'] = TRUE;
print_events($var);
}
/**
* Generate array of eventlogs.
*
* Params:
* short
* pagination, pageno, pagesize
* short, pagination, pageno, pagesize
* device_id, entity_id, entity_type, message, timestamp_from, timestamp_to
*
* @param array $vars
*
* @return array Array of events
*/
function get_events_array($vars)
{
$array = array();
function get_events_array($vars) {
$array = [];
// Short events? (no pagination, small out)
$array['short'] = (isset($vars['short']) && $vars['short']);
// With pagination? (display page numbers in header)
$array['pagination'] = (isset($vars['pagination']) && $vars['pagination']);
pagination($vars, 0, TRUE); // Get default pagesize/pageno
$array['pageno'] = $vars['pageno'];
$array['pagesize'] = $vars['pagesize'];
$start = $array['pagesize'] * $array['pageno'] - $array['pagesize'];
$pagesize = $array['pagesize'];
// Short events? (no pagination, small out)
$array['short'] = (isset($vars['short']) && $vars['short']);
// With pagination? (display page numbers in header)
$array['pagination'] = (isset($vars['pagination']) && $vars['pagination']);
pagination($vars, 0, TRUE); // Get default pagesize/pageno
$array['pageno'] = $vars['pageno'];
$array['pagesize'] = $vars['pagesize'];
$start = $array['pagesize'] * $array['pageno'] - $array['pagesize'];
$pagesize = $array['pagesize'];
// Begin query generate
$param = array();
$where = ' WHERE 1 ';
foreach ($vars as $var => $value)
{
if ($value != '')
{
switch ($var)
{
case 'device':
case 'device_id':
$where .= generate_query_values_and($value, 'device_id');
break;
case 'port':
case 'entity':
case 'entity_id':
$where .= generate_query_values_and($value, 'entity_id');
break;
case 'severity':
$where .= generate_query_values_and($value, 'severity');
break;
case 'type':
case 'entity_type':
$where .= generate_query_values_and($value, 'entity_type');
break;
case 'message':
$where .= generate_query_values_and($value, 'message', '%LIKE%');
break;
case 'timestamp_from':
$where .= ' AND `timestamp` >= ?';
$param[] = $value;
break;
case 'timestamp_to':
$where .= ' AND `timestamp` <= ?';
$param[] = $value;
break;
case "group":
case "group_id":
$values = get_group_entities($value);
$where .= generate_query_values_and($values, 'entity_id');
$where .= generate_query_values_and(get_group_entity_type($value), 'entity_type');
break;
}
// Begin query generate
$where_array = [];
foreach ($vars as $var => $value) {
if ($value != '') {
switch ($var) {
case 'device':
case 'device_id':
$where_array[] = generate_query_values($value, 'device_id');
break;
case 'port':
case 'entity':
case 'entity_id':
$where_array[] = generate_query_values($value, 'entity_id');
break;
case 'severity':
$where_array[] = generate_query_values($value, 'severity');
break;
case 'type':
case 'entity_type':
$where_array[] = generate_query_values($value, 'entity_type');
break;
case 'message':
$where_array[] = generate_query_values($value, 'message', '%LIKE%');
break;
case 'timestamp_from':
$where_array[] = generate_query_values($value, 'timestamp', '>=');
break;
case 'timestamp_to':
$where_array[] = generate_query_values($value, 'timestamp', '<=');
break;
case "group":
case "group_id":
$values = get_group_entities($value);
$where_array[] = generate_query_values($values, 'entity_type');
$where_array[] = generate_query_values(get_group_entity_type($value), 'entity_type');
break;
}
}
}
}
// Show events only for permitted devices
$query_permitted = generate_query_permitted();
// Show events only for permitted devices
if ($_SESSION['userlevel'] >= 5) {
// Common only by device entity
$query_permitted = generate_query_permitted_ng();
} else {
// For limited users, use entity table and entity type
$query_permitted = generate_query_permitted_ng([ 'device', 'port', 'sensor', 'status', 'counter', 'bill' ], [ 'entity' => TRUE ]);
}
$query = 'FROM `eventlog` ';
$query .= $where . $query_permitted;
$query_count = 'SELECT COUNT(*) '.$query;
$query_updated = 'SELECT MAX(`timestamp`) '.$query;
$query = 'FROM `eventlog` ' . generate_where_clause($where_array, $query_permitted);
$query_count = 'SELECT COUNT(*) ' . $query;
$query_updated = 'SELECT MAX(`timestamp`) ' . $query;
$query = 'SELECT * '.$query;
$query .= ' ORDER BY `event_id` DESC ';
$query .= "LIMIT $start,$pagesize";
$query = 'SELECT * ' . $query;
$query .= ' ORDER BY `event_id` DESC ';
$query .= "LIMIT $start,$pagesize";
// Query events
$array['entries'] = dbFetchRows($query, $param);
// Query events
$array['entries'] = dbFetchRows($query);
// Query events count
if ($array['pagination'] && !$array['short'])
{
$array['count'] = dbFetchCell($query_count, $param);
$array['pagination_html'] = pagination($vars, $array['count']);
} else {
$array['count'] = safe_count($array['entries']);
}
// Query events count
if ($array['pagination'] && !$array['short']) {
$array['count'] = dbFetchCell($query_count);
$array['pagination_html'] = pagination($vars, $array['count']);
} else {
$array['count'] = safe_count($array['entries']);
}
// Query for last timestamp
//$array['updated'] = dbFetchCell($query_updated, $param);
// Query for last timestamp
//$array['updated'] = dbFetchCell($query_updated, $param);
return $array;
return $array;
}
function generate_eventlog_form_values($form_filter = FALSE, $column = NULL)
{
//global $cache;
global $config;
//global $cache;
global $config;
$form_items = array();
$filter = is_array($form_filter); // Use filer or not
$form_items = [];
$filter = is_array($form_filter); // Use filer or not
switch ($column)
{
case 'severities':
case 'severity':
// These complete same as syslog priorities
return generate_form_values('syslog', $form_filter, 'priorities');
break;
case 'entity_type':
case 'type':
case 'types':
// Use filter as items
if ($filter)
{
if (in_array('device', $form_filter))
{
// Device always first
$form_filter = array_unique(array_merge(array('device'), $form_filter));
}
if (in_array('global', $form_filter))
{
// Global always first
$form_filter = array_unique(array_merge(array('global'), $form_filter));
}
}
foreach ($form_filter as $type)
{
if (strlen($type) == 0) { continue; }
$form_items[$type]['name'] = nicecase($type);
switch ($column) {
case 'severities':
case 'severity':
// These complete same as syslog priorities
return generate_form_values('syslog', $form_filter, 'priorities');
break;
case 'entity_type':
case 'type':
case 'types':
// Use filter as items
if ($filter) {
if (in_array('device', $form_filter)) {
// Device always first
$form_filter = array_unique(array_merge(['device'], $form_filter));
}
if (in_array('global', $form_filter)) {
// Global always first
$form_filter = array_unique(array_merge(['global'], $form_filter));
}
}
foreach ($form_filter as $type) {
if (strlen($type) == 0) {
continue;
}
$form_items[$type]['name'] = nicecase($type);
if ($type == 'global')
{
$form_items[$type]['icon'] = $config['icon']['info'];
}
else if (!isset($config['entities'][$type]['icon']))
{
$form_items[$type]['icon'] = $config['entity_default']['icon'];
} else {
$form_items[$type]['icon'] = $config['entities'][$type]['icon'];
}
}
break;
}
return $form_items;
if ($type == 'global') {
$form_items[$type]['icon'] = $config['icon']['info'];
} elseif (!isset($config['entities'][$type]['icon'])) {
$form_items[$type]['icon'] = $config['entity_default']['icon'];
} else {
$form_items[$type]['icon'] = $config['entities'][$type]['icon'];
}
}
break;
}
return $form_items;
}
// EOF

View File

@ -6,7 +6,7 @@
*
* @package observium
* @subpackage web
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2022 Observium Limited
* @copyright (C) Adam Armstrong
*
*/
@ -14,224 +14,242 @@
* Display FDB table.
*
* @param array $vars
*
* @return none
*
*/
function print_fdbtable($vars) {
//r($vars);
$entries = get_fdbtable_array($vars);
function print_fdbtable($vars)
{
//r($vars);
$entries = get_fdbtable_array($vars);
if (!$entries['count']) {
// There have been no entries returned. Print the warning.
print_warning('<h4>No FDB entries found!</h4>');
return;
}
$list = array('device' => FALSE, 'port' => FALSE);
if (!isset($vars['device']) || is_array($vars['device']) || empty($vars['device']) || $vars['page'] === 'search') { $list['device'] = TRUE; }
if (!isset($vars['port']) || is_array($vars['port']) || empty($vars['port']) || $vars['page'] === 'search') { $list['port'] = TRUE; }
//r($list);
$string = generate_box_open();
$string .= '<table class="table table-striped table-hover table-condensed">' . PHP_EOL;
$cols = [
'device' => 'Device',
'mac' => [ 'MAC Address', 'style="width: 160px;"' ],
'status' => [ 'Status', 'style="width: 100px;"' ],
'port' => 'Port',
'trunk' => 'Trunk/Type',
'vlan_id' => 'VLAN ID',
'vlan_name' => 'VLAN NAME',
'changed' => [ 'Changed', 'style="width: 100px;"' ]
];
if (!$list['device']) { unset($cols['device']); }
if (!$list['port']) { unset($cols['port']); }
if (!$short) {
$string .= get_table_header($cols, $vars); // Currently, sorting is not available
}
//print_vars($entries['entries']);
foreach ($entries['entries'] as $entry) {
if ($entry['deleted']) {
$port = [];
$string .= ' <tr class="ignore">' . PHP_EOL;
} else {
$port = get_port_by_id_cache($entry['port_id']);
$string .= ' <tr>' . PHP_EOL;
if (!$entries['count']) {
// There have been no entries returned. Print the warning.
print_warning('<h4>No FDB entries found!</h4>');
return;
}
if ($list['device']) {
$dev = device_by_id_cache($entry['device_id']);
$string .= ' <td class="entity" style="white-space: nowrap;">' . generate_device_link($dev) . '</td>' . PHP_EOL;
$list = ['device' => FALSE, 'port' => FALSE];
if (!isset($vars['device']) || is_array($vars['device']) || empty($vars['device']) || $vars['page'] === 'search') {
$list['device'] = TRUE;
}
$string .= ' <td>' . generate_popup_link('mac', format_mac($entry['mac_address'])) . '</td>' . PHP_EOL;
$string .= ' <td>' . $entry['fdb_status'] . '</td>' . PHP_EOL;
if ($list['port']) {
$string .= ' <td class="entity">' . generate_port_link_short($port) . ' ' . $port_error . '</td>' . PHP_EOL;
if (!isset($vars['port']) || is_array($vars['port']) || empty($vars['port']) || $vars['page'] === 'search') {
$list['port'] = TRUE;
}
$string .= ' <td><span class="label">' . ($port['ifType'] === 'l2vlan' && empty($port['ifTrunk']) ? $port['human_type'] : $port['ifTrunk']) . '</span></td>' . PHP_EOL;
$string .= ' <td>' . ($entry['vlan_vlan'] ? 'Vlan' . $entry['vlan_vlan'] : '') . '</td>' . PHP_EOL;
$string .= ' <td>' . $entry['vlan_name'] . '</td>' . PHP_EOL;
$string .= ' <td>' . generate_tooltip_link(NULL, format_uptime((get_time() - $entry['fdb_last_change']), 'short-2') . ' ago', format_unixtime($entry['fdb_last_change'])) . '</td>' . PHP_EOL;
$string .= ' </tr>' . PHP_EOL;
}
$string .= ' </tbody>' . PHP_EOL;
$string .= '</table>';
//r($list);
$string .= generate_box_close();
$string = generate_box_open();
// Print pagination header
if ($entries['pagination_html']) {
$string = $entries['pagination_html'] . $string . $entries['pagination_html'];
}
$string .= '<table class="table table-striped table-hover table-condensed">' . PHP_EOL;
// Print FDB table
echo $string;
$cols = [
'device' => 'Device',
'mac' => ['MAC Address', 'style="width: 160px;"'],
'status' => ['Status', 'style="width: 100px;"'],
'port' => 'Port',
'trunk' => 'Trunk/Type',
'vlan_id' => 'VLAN ID',
'vlan_name' => 'VLAN NAME',
'changed' => ['Changed', 'style="width: 100px;"']
];
if (!$list['device']) {
unset($cols['device']);
}
if (!$list['port']) {
unset($cols['port']);
}
if (!$short) {
$string .= get_table_header($cols, $vars); // Currently, sorting is not available
}
//print_vars($entries['entries']);
foreach ($entries['entries'] as $entry) {
if ($entry['deleted']) {
$port = [];
$string .= ' <tr class="ignore">' . PHP_EOL;
} else {
$port = get_port_by_id_cache($entry['port_id']);
$string .= ' <tr>' . PHP_EOL;
}
if ($list['device']) {
$dev = device_by_id_cache($entry['device_id']);
$string .= ' <td class="entity" style="white-space: nowrap;">' . generate_device_link($dev) . '</td>' . PHP_EOL;
}
$string .= ' <td>' . generate_popup_link('mac', format_mac($entry['mac_address'])) . '</td>' . PHP_EOL;
$string .= ' <td>' . $entry['fdb_status'] . '</td>' . PHP_EOL;
if ($list['port']) {
$string .= ' <td class="entity">' . generate_port_link_short($port) . ' ' . $port_error . '</td>' . PHP_EOL;
}
$string .= ' <td><span class="label">' . ($port['ifType'] === 'l2vlan' && empty($port['ifTrunk']) ? $port['human_type'] : $port['ifTrunk']) . '</span></td>' . PHP_EOL;
$string .= ' <td>' . ($entry['vlan_vlan'] ? 'Vlan' . $entry['vlan_vlan'] : '') . '</td>' . PHP_EOL;
$string .= ' <td>' . $entry['vlan_name'] . '</td>' . PHP_EOL;
$string .= ' <td>' . generate_tooltip_link(NULL, format_uptime((get_time() - $entry['fdb_last_change']), 'short-2') . ' ago', format_unixtime($entry['fdb_last_change'])) . '</td>' . PHP_EOL;
$string .= ' </tr>' . PHP_EOL;
}
$string .= ' </tbody>' . PHP_EOL;
$string .= '</table>';
$string .= generate_box_close();
// Print pagination header
if ($entries['pagination_html']) {
$string = $entries['pagination_html'] . $string . $entries['pagination_html'];
}
// Print FDB table
echo $string;
}
/**
* Fetch FDB table array
*
* @param array $vars
*
* @return array
*
*/
function get_fdbtable_array($vars) {
$array = [];
$array = [];
// With pagination? (display page numbers in header)
$array['pagination'] = (isset($vars['pagination']) && $vars['pagination']);
pagination($vars, 0, TRUE); // Get default pagesize/pageno
$array['pageno'] = $vars['pageno'];
$array['pagesize'] = $vars['pagesize'];
$start = $array['pagesize'] * $array['pageno'] - $array['pagesize'];
$pagesize = $array['pagesize'];
// With pagination? (display page numbers in header)
$array['pagination'] = isset($vars['pagination']) && $vars['pagination'];
pagination($vars, 0, TRUE); // Get default pagesize/pageno
$array['pageno'] = $vars['pageno'];
$array['pagesize'] = $vars['pagesize'];
$start = $array['pagesize'] * $array['pageno'] - $array['pagesize'];
$pagesize = $array['pagesize'];
$params = [];
$where = ' WHERE 1 ';
$join_ports = FALSE;
if (!isset($vars['deleted'])) {
// Do not show deleted entries by default
$vars['deleted'] = 0;
}
foreach ($vars as $var => $value) {
// Skip empty variables (and array with empty first entry) when building query
if ($value == '' || (is_array($value) && count($value) == 1 && $value[0] == '')) { continue; }
switch ($var) {
case 'device':
case 'device_id':
$where .= generate_query_values_and($value, 'F.device_id');
break;
case 'port':
case 'port_id':
$where .= generate_query_values_and($value, 'F.port_id');
break;
case 'interface':
case 'port_name':
$where .= generate_query_values_and($value, 'I.ifDescr', 'LIKE%');
$join_ports = TRUE;
break;
case 'trunk':
if (get_var_true($value)) {
$where .= " AND (`I`.`ifTrunk` IS NOT NULL AND `I`.`ifTrunk` != '')";
$join_ports = TRUE;
}
else if (in_array($value, ['none', 'no', '0'])) {
$where .= " AND (`I`.`ifTrunk` IS NULL OR `I`.`ifTrunk` = '')";
$join_ports = TRUE;
}
break;
case 'vlan_id':
$where .= generate_query_values_and($value, 'F.vlan_id');
break;
case 'vlan_name':
$where .= generate_query_values_and($value, 'V.vlan_name');
break;
case 'address':
if (str_contains_array($value, ['*', '?'])) {
$like = 'LIKE';
}
else {
$like = '%LIKE%';
}
$where .= generate_query_values_and(str_replace([':', ' ', '-', '.', '0x'], '', $value), 'F.mac_address', $like);
break;
case 'deleted':
$where .= ' AND `deleted` = ?';
$params[] = $value;
$params = [];
$where_array = [];
$join_ports = FALSE;
if (!isset($vars['deleted'])) {
// Do not show deleted entries by default
$vars['deleted'] = 0;
}
}
if (isset($vars['sort'])) {
switch($vars['sort']) {
case "vlan_id":
$sort = " ORDER BY `V`.`vlan_vlan`";
break;
foreach ($vars as $var => $value) {
case "vlan_name":
$sort = " ORDER BY `V`.`vlan_name`";
break;
case "port":
$sort = " ORDER BY `I`.`port_label`";
$join_ports = TRUE;
break;
case "changed":
$sort = " ORDER BY `F`.`fdb_last_change`";
break;
case "mac":
default:
$sort = " ORDER BY `mac_address`";
// Skip empty variables (and array with empty first entry) when building query
if (safe_empty($value) || (safe_count($value) === 1 && safe_empty($value[0]))) {
continue;
}
switch ($var) {
case 'device':
case 'device_id':
$where_array[] = generate_query_values($value, 'F.device_id');
break;
case 'port':
case 'port_id':
$where_array[] = generate_query_values($value, 'F.port_id');
break;
case 'interface':
case 'port_name':
$where_array[] = generate_query_values($value, 'I.port_label', 'LIKE%');
$join_ports = TRUE;
break;
case 'trunk':
if (get_var_true($value)) {
$where_array[] = "(`I`.`ifTrunk` IS NOT NULL AND `I`.`ifTrunk` != '')";
$join_ports = TRUE;
} elseif (get_var_false($value, 'none')) {
$where_array[] = "(`I`.`ifTrunk` IS NULL OR `I`.`ifTrunk` = '')";
$join_ports = TRUE;
}
break;
case 'vlan_id':
$where_array[] = generate_query_values($value, 'F.vlan_id');
break;
case 'vlan_name':
$where_array[] = generate_query_values($value, 'V.vlan_name');
break;
case 'address':
if (str_contains_array($value, [ '*', '?' ])) {
$like = 'LIKE';
} else {
$like = '%LIKE%';
}
$where_array[] = generate_query_values(str_replace([':', ' ', '-', '.', '0x'], '', $value), 'F.mac_address', $like);
break;
case 'deleted':
$where_array[] = 'F.`deleted` = ?';
$params[] = $value;
}
}
}
// Show FDB tables only for permitted ports
$query_permitted = generate_query_permitted([ 'device', 'port' ], [ 'device_table' => 'F', 'port_table' => 'F', 'port_null' => TRUE ]);
$sort = '';
if (isset($vars['sort'])) {
$sort_order = get_sort_order($vars);
switch ($vars['sort']) {
case "vlan_id":
//$sort = " ORDER BY `V`.`vlan_vlan`";
$sort = generate_query_sort('V.vlan_vlan', $sort_order);
break;
$query = 'FROM `vlans_fdb` AS F ';
$query .= 'LEFT JOIN `vlans` as V ON F.`vlan_id` = V.`vlan_vlan` AND F.`device_id` = V.`device_id` ';
if ($join_ports) {
$query .= 'LEFT JOIN `ports` AS I ON I.`port_id` = F.`port_id` ';
}
$query .= $where . $query_permitted;
$query_count = 'SELECT COUNT(*) ' . $query;
$query = 'SELECT F.*, V.`vlan_vlan`, V.`vlan_name` ' . $query;
$query .= $sort;
$query .= " LIMIT $start,$pagesize";
case "vlan_name":
//$sort = " ORDER BY `V`.`vlan_name`";
$sort = generate_query_sort('V.vlan_name', $sort_order);
break;
//r($query);
//r($params);
case "port":
//$sort = " ORDER BY `I`.`port_label`";
$sort = generate_query_sort('I.port_label', $sort_order);
$join_ports = TRUE;
break;
// Query addresses
//$array['entries'] = dbFetchRows($query, $params, TRUE);
$array['entries'] = dbFetchRows($query, $params);
case "changed":
//$sort = " ORDER BY `F`.`fdb_last_change`";
$sort = generate_query_sort('F.fdb_last_change', $sort_order);
break;
if ($array['pagination']) {
// Query address count
$array['count'] = dbFetchCell($query_count, $params);
$array['pagination_html'] = pagination($vars, $array['count']);
} else {
$array['count'] = safe_count($array['entries']);
}
case "mac":
default:
//$sort = " ORDER BY `mac_address`";
$sort = generate_query_sort('mac_address', $sort_order);
}
} else {
$sort = '';
}
return $array;
// Show FDB tables only for permitted ports
$query_permitted = generate_query_permitted_ng([ 'device', 'port' ], [ 'device_table' => 'F', 'port_table' => 'F', 'port_null' => TRUE ]);
$query = 'FROM `vlans_fdb` AS F ';
$query .= 'LEFT JOIN `vlans` as V ON F.`vlan_id` = V.`vlan_vlan` AND F.`device_id` = V.`device_id` ';
if ($join_ports) {
$query .= 'LEFT JOIN `ports` AS I ON I.`port_id` = F.`port_id` ';
}
$query .= generate_where_clause($where_array, $query_permitted);
$query_count = 'SELECT COUNT(*) ' . $query;
$query = 'SELECT F.*, V.`vlan_vlan`, V.`vlan_name` ' . $query;
$query .= $sort;
$query .= " LIMIT $start,$pagesize";
//r($query);
//r($params);
// Query addresses
//$array['entries'] = dbFetchRows($query, $params, TRUE);
$array['entries'] = dbFetchRows($query, $params);
if ($array['pagination']) {
// Query address count
$array['count'] = dbFetchCell($query_count, $params);
$array['pagination_html'] = pagination($vars, $array['count']);
} else {
$array['count'] = safe_count($array['entries']);
}
return $array;
}
// EOF

View File

@ -6,111 +6,97 @@
*
* @package observium
* @subpackage web
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2022 Observium Limited
* @copyright (C) Adam Armstrong
*
*/
function generate_inventory_query($vars) {
function generate_inventory_query($vars)
{
$param = array();
$where = ' WHERE 1 ';
$select[] = 'entPhysical.*';
// By default hide deleted inventory
if (!isset($vars['deleted'])) {
$vars['deleted'] = '0';
}
$param = [];
$where = [];
foreach ($vars as $var => $value)
{
if ($value != '')
{
switch ($var)
{
case 'device':
case 'device_id':
$where .= generate_query_values_and($value, 'device_id');
break;
case 'os':
$where .= generate_query_values_and($value, 'os');
$select[] = 'devices.os';
$devices = TRUE;
break;
case 'parts':
case 'entPhysicalModelName':
$where .= generate_query_values_and($value, 'entPhysicalModelName', 'LIKE');
break;
case 'serial':
case 'entPhysicalSerialNum':
$where .= generate_query_values_and($value, 'entPhysicalSerialNum', '%LIKE%');
break;
case 'description':
case 'entPhysicalDescr':
$where .= generate_query_values_and($value, 'entPhysicalDescr', '%LIKE%');
break;
case 'class':
case 'entPhysicalClass':
$where .= generate_query_values_and($value, 'entPhysicalClass', '%LIKE%');
break;
case 'deleted':
$where .= generate_query_values_and($value, 'deleted', 'NOT NULL');
break;
}
$where[] = $GLOBALS['cache']['where']['devices_permitted'];
$select[] = 'entPhysical.*';
// By default hide deleted inventory
if (!isset($vars['deleted'])) {
$vars['deleted'] = '0';
}
}
// Show inventory only for permitted devices
//$query_permitted = generate_query_permitted(array('device'), array('device_table' => 'D'));
foreach ($vars as $var => $value) {
if ($value != '') {
switch ($var) {
case 'device':
case 'device_id':
$where[] = generate_query_values($value, 'device_id');
break;
case 'os':
$where[] = generate_query_values($value, 'os');
$select[] = 'devices.os';
$devices = TRUE;
break;
case 'parts':
case 'entPhysicalModelName':
$where[] = generate_query_values($value, 'entPhysicalModelName', 'LIKE');
break;
case 'serial':
case 'entPhysicalSerialNum':
$where[] = generate_query_values($value, 'entPhysicalSerialNum', '%LIKE%');
break;
case 'description':
case 'entPhysicalDescr':
$where[] = generate_query_values($value, 'entPhysicalDescr', '%LIKE%');
break;
case 'class':
case 'entPhysicalClass':
$where[] = generate_query_values($value, 'entPhysicalClass', '%LIKE%');
break;
case 'deleted':
$where[] = generate_query_values($value, 'deleted', 'NOT NULL');
break;
}
}
}
$query = 'FROM `entPhysical`';
$query = 'FROM `entPhysical`';
if ($vars['sort'] === 'hostname' || $vars['sort'] === 'device' || $vars['sort'] === 'device_id' || $devices == TRUE)
{
$query .= ' LEFT JOIN `devices` USING(`device_id`)';
$select[] = 'devices.hostname';
}
if ($vars['sort'] === 'hostname' || $vars['sort'] === 'device' || $vars['sort'] === 'device_id' || $devices == TRUE) {
$query .= ' LEFT JOIN `devices` USING(`device_id`)';
$select[] = 'devices.hostname';
}
$query .= $where . $GLOBALS['cache']['where']['devices_permitted'];
$query_count = 'SELECT COUNT(entPhysical_id) ' . $query;
$query .= generate_where_clause($where);
$query = 'SELECT ' . implode(', ', $select) . ' ' . $query;
$query_count = 'SELECT COUNT(entPhysical_id) ' . $query;
switch ($vars['sort_order'])
{
case 'desc':
$sort_order = 'DESC';
$sort_neg = 'ASC';
break;
case 'reset':
unset($vars['sort'], $vars['sort_order']);
// no break here
default:
$sort_order = 'ASC';
$sort_neg = 'DESC';
}
$query = 'SELECT ' . implode(', ', $select) . ' ' . $query;
switch($vars['sort']) {
case 'device':
case 'hostname':
$query .= ' ORDER BY `hostname` '.$sort_order;
break;
case 'descr':
case 'event':
$query .= ' ORDER BY `sensor_'.$vars['sort'].'` '.$sort_order;
break;
case 'value':
case 'last_change':
$query .= ' ORDER BY `sensor_'.$vars['sort'].'` '.$sort_order;
break;
default:
// $sql .= ' ORDER BY `hostname` '.$sort_order.', `sensor_descr` '.$sort_order;
}
$sort_order = get_sort_order($vars);
if (isset($vars['pageno'])) {
$start = $vars['pagesize'] * ($vars['pageno'] - 1);
$query .= ' LIMIT '.$start.','.$vars['pagesize'];
}
switch ($vars['sort']) {
case 'device':
case 'hostname':
//$query .= ' ORDER BY `hostname` '.$sort_order;
$query .= generate_query_sort('hostname', $sort_order);
break;
case 'descr':
case 'event':
case 'value':
case 'last_change':
$query .= generate_query_sort('sensor_' . $vars['sort'], $sort_order);
break;
default:
// $query .= ' ORDER BY `hostname` '.$sort_order.', `sensor_descr` '.$sort_order;
// $query .= generate_query_sort([ 'hostname', 'sensor_descr' ],$sort_order);
}
return array('query' => $query, 'query_count' => $query_count, 'param' => $param);
if (isset($vars['pageno'])) {
$start = $vars['pagesize'] * ($vars['pageno'] - 1);
$query .= ' LIMIT ' . $start . ',' . $vars['pagesize'];
}
return [ 'query' => $query, 'query_count' => $query_count, 'param' => $param ];
}
@ -118,120 +104,129 @@ function generate_inventory_query($vars) {
* Display Devices Inventory.
*
* @param array $vars
*
* @return void|boolean
*
*/
function print_inventory($vars) {
// On "Inventory" device tab display hierarchical list
if ($vars['page'] === 'device' && is_numeric($vars['device']) && device_permitted($vars['device'])) {
// DHTML expandable tree
register_html_resource('js', 'mktree.js');
register_html_resource('css', 'mktree.css');
echo generate_box_open($vars['header']);
echo('<table class="table table-striped table-condensed "><tr><td>');
echo('<div class="btn-group pull-right" style="margin-top:5px; margin-right: 5px;">
function print_inventory($vars)
{
// On "Inventory" device tab display hierarchical list
if ($vars['page'] === 'device' && is_numeric($vars['device']) && device_permitted($vars['device'])) {
// DHTML expandable tree
register_html_resource('js', 'mktree.js');
register_html_resource('css', 'mktree.css');
echo generate_box_open($vars['header']);
echo('<table class="table table-striped table-condensed "><tr><td>');
echo('<div class="btn-group pull-right" style="margin-top:5px; margin-right: 5px;">
<button class="btn btn-small" onClick="expandTree(\'enttree\');return false;"><i class="icon-plus muted small"></i> Expand</button>
<button class="btn btn-small" onClick="collapseTree(\'enttree\');return false;"><i class="icon-minus muted small"></i> Collapse</button>
</div>');
echo('<div style="clear: left; margin: 5px;"><ul class="mktree" id="enttree" style="margin-left: -10px;">');
print_ent_physical(0, 0, "liOpen");
echo('</ul></div>');
echo('</td></tr></table>');
echo generate_box_close();
echo('<div style="clear: left; margin: 5px;"><ul class="mktree" id="enttree" style="margin-left: -10px;">');
print_ent_physical(0, 0, "liOpen");
echo('</ul></div>');
echo('</td></tr></table>');
echo generate_box_close();
return TRUE;
}
// With pagination? (display page numbers in header)
$pagination = (isset($vars['pagination']) && $vars['pagination']);
pagination($vars, 0, TRUE); // Get default pagesize/pageno
$pageno = $vars['pageno'];
$pagesize = $vars['pagesize'];
$start = $pagesize * $pageno - $pagesize;
$queries = generate_inventory_query($vars);
// Query inventories
$entries = dbFetchRows($queries['query'], $queries['param']);
// Query inventory count
if ($pagination) { $count = dbFetchCell($queries['query_count'], $queries['param']); }
$list = array('device' => FALSE);
if (!isset($vars['device']) || empty($vars['device']) || $vars['page'] === 'inventory') { $list['device'] = TRUE; }
$string = generate_box_open($vars['header']);
$string .= '<table class="'.OBS_CLASS_TABLE_STRIPED.'">' . PHP_EOL;
if (!$short) {
$string .= ' <thead>' . PHP_EOL;
$string .= ' <tr>' . PHP_EOL;
if ($list['device']) { $string .= ' <th>Device</th>' . PHP_EOL; }
$string .= ' <th>Name</th>' . PHP_EOL;
$string .= ' <th>Description</th>' . PHP_EOL;
$string .= ' <th>Part #</th>' . PHP_EOL;
$string .= ' <th>Serial #</th>' . PHP_EOL;
$string .= ' <th>Removed</th>' . PHP_EOL;
$string .= ' </tr>' . PHP_EOL;
$string .= ' </thead>' . PHP_EOL;
}
$string .= ' <tbody>' . PHP_EOL;
foreach ($entries as $entry) {
$string .= ' <tr>' . PHP_EOL;
if ($list['device']) {
$string .= ' <td class="entity" style="white-space: nowrap">' . generate_device_link($entry, NULL, array('page' => 'device', 'tab' => 'entphysical')) . '</td>' . PHP_EOL;
return TRUE;
}
if ($entry['ifIndex']) {
$interface = get_port_by_ifIndex($entry['device_id'], $entry['ifIndex']);
$entry['entPhysicalName'] = generate_port_link($interface);
} elseif ($entry['entPhysicalClass'] === "sensor") {
$sensor = dbFetchRow("SELECT * FROM `sensors`
WHERE `device_id` = ? AND (`entPhysicalIndex` = ? OR `sensor_index` = ?)", array($entry['device_id'], $entry['entPhysicalIndex'], $entry['entPhysicalIndex']));
$entry['entPhysicalName'] = generate_entity_link('sensor', $sensor);
// With pagination? (display page numbers in header)
$pagination = (isset($vars['pagination']) && $vars['pagination']);
pagination($vars, 0, TRUE); // Get default pagesize/pageno
$pageno = $vars['pageno'];
$pagesize = $vars['pagesize'];
$start = $pagesize * $pageno - $pagesize;
$queries = generate_inventory_query($vars);
// Query inventories
$entries = dbFetchRows($queries['query'], $queries['param']);
// Query inventory count
if ($pagination) {
$count = dbFetchCell($queries['query_count'], $queries['param']);
}
$string .= ' <td style="width: 160px;">' . $entry['entPhysicalName'] . '</td>' . PHP_EOL;
$string .= ' <td>' . $entry['entPhysicalDescr'] . '</td>' . PHP_EOL;
$string .= ' <td>' . $entry['entPhysicalModelName'] . '</td>' . PHP_EOL;
$string .= ' <td>' . $entry['entPhysicalSerialNum'] . '</td>' . PHP_EOL;
$string .= ' <td>' . $entry['deleted'] . '</td>' . PHP_EOL;
$string .= ' </tr>' . PHP_EOL;
}
$list = ['device' => FALSE];
if (!isset($vars['device']) || empty($vars['device']) || $vars['page'] === 'inventory') {
$list['device'] = TRUE;
}
$string .= ' </tbody>' . PHP_EOL;
$string .= '</table>';
$string .= generate_box_close();
$string = generate_box_open($vars['header']);
$string .= '<table class="' . OBS_CLASS_TABLE_STRIPED . '">' . PHP_EOL;
if (!$short) {
$string .= ' <thead>' . PHP_EOL;
$string .= ' <tr>' . PHP_EOL;
if ($list['device']) {
$string .= ' <th>Device</th>' . PHP_EOL;
}
$string .= ' <th>Name</th>' . PHP_EOL;
$string .= ' <th>Description</th>' . PHP_EOL;
$string .= ' <th>Part #</th>' . PHP_EOL;
$string .= ' <th>Serial #</th>' . PHP_EOL;
$string .= ' <th>Removed</th>' . PHP_EOL;
$string .= ' </tr>' . PHP_EOL;
$string .= ' </thead>' . PHP_EOL;
}
$string .= ' <tbody>' . PHP_EOL;
// Print pagination header
if ($pagination) { $string = pagination($vars, $count) . $string . pagination($vars, $count); }
foreach ($entries as $entry) {
$string .= ' <tr>' . PHP_EOL;
if ($list['device']) {
$string .= ' <td class="entity" style="white-space: nowrap">' . generate_device_link($entry, NULL, ['page' => 'device', 'tab' => 'entphysical']) . '</td>' . PHP_EOL;
}
if ($entry['ifIndex']) {
$interface = get_port_by_ifIndex($entry['device_id'], $entry['ifIndex']);
$entry['entPhysicalName'] = generate_port_link($interface);
} elseif ($entry['entPhysicalClass'] === "sensor") {
$sensor = dbFetchRow("SELECT * FROM `sensors`
WHERE `device_id` = ? AND (`entPhysicalIndex` = ? OR `sensor_index` = ?)", [$entry['device_id'], $entry['entPhysicalIndex'], $entry['entPhysicalIndex']]);
$entries_allowed = array('entPhysical_id', 'device_id', 'entPhysicalIndex', 'entPhysicalDescr',
'entPhysicalClass','entPhysicalName','entPhysicalHardwareRev','entPhysicalFirmwareRev',
'entPhysicalSoftwareRev','entPhysicalAlias','entPhysicalAssetID','entPhysicalIsFRU',
'entPhysicalModelName','entPhysicalVendorType','entPhysicalSerialNum','entPhysicalContainedIn',
'entPhysicalParentRelPos','entPhysicalMfgName');
$entry['entPhysicalName'] = generate_entity_link('sensor', $sensor);
}
$string .= ' <td style="width: 160px;">' . $entry['entPhysicalName'] . '</td>' . PHP_EOL;
$string .= ' <td>' . $entry['entPhysicalDescr'] . '</td>' . PHP_EOL;
$string .= ' <td>' . $entry['entPhysicalModelName'] . '</td>' . PHP_EOL;
$string .= ' <td>' . $entry['entPhysicalSerialNum'] . '</td>' . PHP_EOL;
$string .= ' <td>' . $entry['deleted'] . '</td>' . PHP_EOL;
$string .= ' </tr>' . PHP_EOL;
}
$string .= ' </tbody>' . PHP_EOL;
$string .= '</table>';
$string .= generate_box_close();
// Print pagination header
if ($pagination) {
$string = pagination($vars, $count) . $string . pagination($vars, $count);
}
$entries_allowed = ['entPhysical_id', 'device_id', 'entPhysicalIndex', 'entPhysicalDescr',
'entPhysicalClass', 'entPhysicalName', 'entPhysicalHardwareRev', 'entPhysicalFirmwareRev',
'entPhysicalSoftwareRev', 'entPhysicalAlias', 'entPhysicalAssetID', 'entPhysicalIsFRU',
'entPhysicalModelName', 'entPhysicalVendorType', 'entPhysicalSerialNum', 'entPhysicalContainedIn',
'entPhysicalParentRelPos', 'entPhysicalMfgName'];
foreach($entries as $entry) {
$entries_cleaned[$entry['entPhysical_id']] = array_intersect_key($entry, array_flip($entries_allowed));
}
foreach ($entries as $entry) {
$entries_cleaned[$entry['entPhysical_id']] = array_intersect_key($entry, array_flip($entries_allowed));
}
// Print Inventories
switch($vars['format'])
{
case "csv":
// Print Inventories
switch ($vars['format']) {
case "csv":
echo(implode(", ", $entry));
echo("\n");
echo(implode(", ", $entry));
echo("\n");
break;
default:
echo $string;
break;
}
break;
default:
echo $string;
break;
}
}
/**
@ -244,213 +239,216 @@ function print_inventory($vars) {
* @return null
*
*/
function print_ent_physical($entPhysicalContainedIn, $level, $class) {
global $device, $config;
function print_ent_physical($entPhysicalContainedIn, $level, $class)
{
global $device, $config;
$initial = $entPhysicalContainedIn === 0 && $level === 0;
$where = '`device_id` = ? AND `entPhysicalContainedIn` = ?';
if ($initial) {
// First level must be not deleted!
$where .= ' AND `deleted` IS NULL';
}
$initial = $entPhysicalContainedIn === 0 && $level === 0;
$where = '`device_id` = ? AND `entPhysicalContainedIn` = ?';
if ($initial) {
// First level must be not deleted!
$where .= ' AND `deleted` IS NULL';
}
$ents = dbFetchRows("SELECT * FROM `entPhysical` WHERE $where ORDER BY `entPhysicalContainedIn`, `ifIndex`, `entPhysicalIndex`", [ $device['device_id'], $entPhysicalContainedIn ]);
if ($initial && empty($ents)) {
// In some rare cases device report initial entity with index -1
//$entPhysicalContainedIn -= 1;
$entPhysicalContainedIn = dbFetchCell("SELECT MIN(`entPhysicalContainedIn`) FROM `entPhysical` WHERE `device_id` = ? AND `deleted` IS NULL", [ $device['device_id'] ]);
$ents = dbFetchRows("SELECT * FROM `entPhysical` WHERE $where ORDER BY `entPhysicalContainedIn`, `ifIndex`, `entPhysicalIndex`", [$device['device_id'], $entPhysicalContainedIn]);
if ($initial && empty($ents)) {
// In some rare cases device report initial entity with index -1
//$entPhysicalContainedIn -= 1;
$entPhysicalContainedIn = dbFetchCell("SELECT MIN(`entPhysicalContainedIn`) FROM `entPhysical` WHERE `device_id` = ? AND `deleted` IS NULL", [$device['device_id']]);
$ents = dbFetchRows("SELECT * FROM `entPhysical` WHERE $where ORDER BY `entPhysicalContainedIn`, `ifIndex`, `entPhysicalIndex`", [ $device['device_id'], $entPhysicalContainedIn ]);
}
//r($ents);
$ents = dbFetchRows("SELECT * FROM `entPhysical` WHERE $where ORDER BY `entPhysicalContainedIn`, `ifIndex`, `entPhysicalIndex`", [$device['device_id'], $entPhysicalContainedIn]);
}
//r($ents);
foreach ($ents as $ent) {
$link = '';
$value = NULL;
$text = " <li class='$class'>";
foreach ($ents as $ent) {
$link = '';
$value = NULL;
$text = " <li class='$class'>";
/*
Currently no icons for:
/*
Currently no icons for:
JUNIPER-MIB::jnxFruType.10.1.1.0 = INTEGER: frontPanelModule(8)
JUNIPER-MIB::jnxFruType.12.1.0.0 = INTEGER: controlBoard(5)
JUNIPER-MIB::jnxFruType.10.1.1.0 = INTEGER: frontPanelModule(8)
JUNIPER-MIB::jnxFruType.12.1.0.0 = INTEGER: controlBoard(5)
For Geist RCX, IPOMan:
outlet
relay
*/
For Geist RCX, IPOMan:
outlet
relay
*/
// icons
$icon = 'hardware'; // default icon
switch (TRUE) {
case str_starts($ent['entPhysicalClass'], 'chassis'):
$icon = 'device';
break;
case str_starts($ent['entPhysicalClass'], 'board'):
$icon = 'linecard'; // need something better
break;
case str_starts($ent['entPhysicalClass'], [ 'module', 'adapter' ]):
case str_contains_array($ent['entPhysicalClass'], 'Interface'):
$icon = 'linecard';
break;
case $ent['entPhysicalClass'] === 'port':
$icon = 'port';
break;
case str_starts($ent['entPhysicalClass'], [ 'container', 'fabric', 'backplane' ]):
case str_contains_array($ent['entPhysicalClass'], 'Concentrator'):
$icon = 'package';
break;
case str_starts($ent['entPhysicalClass'], [ 'stack' ]):
$icon = 'databases';
break;
case str_starts($ent['entPhysicalClass'], [ 'fan', 'airflow' ]):
$icon = 'fanspeed';
break;
case str_starts($ent['entPhysicalClass'], [ 'cpu', 'processor', 'cpm' ]):
$icon = 'processor';
break;
case str_starts($ent['entPhysicalClass'], [ 'disk', 'flash', 'mda', 'storage', 'drive' ]):
$icon = 'storage';
break;
case str_starts($ent['entPhysicalClass'], 'power'):
$icon = 'powersupply';
break;
case $ent['entPhysicalClass'] === 'sensor':
$sensor = dbFetchRow("SELECT * FROM `sensors` WHERE `device_id` = ? AND (`entPhysicalIndex` = ? OR `sensor_index` = ?)", array($device['device_id'], $ent['entPhysicalIndex'], $ent['entPhysicalIndex']));
if ($sensor['sensor_class']) {
$icon = $GLOBALS['config']['sensor_types'][$sensor['sensor_class']]['icon'];
$link = generate_entity_link('sensor', $sensor);
// icons
$icon = 'hardware'; // default icon
switch (TRUE) {
case str_starts($ent['entPhysicalClass'], 'chassis'):
$icon = 'device';
break;
case str_starts($ent['entPhysicalClass'], 'board'):
$icon = 'linecard'; // need something better
break;
case str_starts($ent['entPhysicalClass'], ['module', 'adapter']):
case str_contains($ent['entPhysicalClass'], 'Interface'):
$icon = 'linecard';
break;
case $ent['entPhysicalClass'] === 'port':
$icon = 'port';
break;
case str_starts($ent['entPhysicalClass'], ['container', 'fabric', 'backplane']):
case str_contains($ent['entPhysicalClass'], 'Concentrator'):
$icon = 'package';
break;
case str_starts($ent['entPhysicalClass'], ['stack']):
$icon = 'databases';
break;
case str_starts($ent['entPhysicalClass'], ['fan', 'airflow']):
$icon = 'fanspeed';
break;
case str_starts($ent['entPhysicalClass'], ['cpu', 'processor', 'cpm']):
$icon = 'processor';
break;
case str_starts($ent['entPhysicalClass'], ['disk', 'flash', 'mda', 'storage', 'drive']):
$icon = 'storage';
break;
case str_starts($ent['entPhysicalClass'], 'power'):
$icon = 'powersupply';
break;
case $ent['entPhysicalClass'] === 'sensor':
$sensor = dbFetchRow("SELECT * FROM `sensors` WHERE `device_id` = ? AND (`entPhysicalIndex` = ? OR `sensor_index` = ?)", [$device['device_id'], $ent['entPhysicalIndex'], $ent['entPhysicalIndex']]);
if ($sensor['sensor_class']) {
$icon = $GLOBALS['config']['sensor_types'][$sensor['sensor_class']]['icon'];
$link = generate_entity_link('sensor', $sensor);
humanize_sensor($sensor);
//r($sensor);
$value = nicecase($sensor['sensor_class']) . ': ' . $sensor['human_value'] . $sensor['sensor_symbol'];
} else {
$icon = 'sensor';
humanize_sensor($sensor);
//r($sensor);
$value = nicecase($sensor['sensor_class']) . ': ' . $sensor['human_value'] . $sensor['sensor_symbol'];
} else {
$icon = 'sensor';
}
break;
case str_starts($ent['entPhysicalClass'], ['routing', 'forwarding']):
$icon = 'routing';
break;
case $ent['entPhysicalClass'] === 'other':
$tmp_descr = $ent['entPhysicalDescr'] . ' ' . $ent['entPhysicalName'];
if (str_icontains_array($tmp_descr, ['switch'])) {
$icon = 'switching';
} elseif (str_icontains_array($tmp_descr, ['cpu', 'processor'])) {
$icon = 'processor';
} elseif (str_icontains_array($tmp_descr, ['ram', 'memory'])) {
$icon = 'mempool';
} elseif (str_icontains_array($tmp_descr, ['flash', 'storage'])) {
$icon = 'storage';
} elseif (str_icontains_array($tmp_descr, ['stack'])) {
$icon = 'databases';
} elseif (str_icontains_array($tmp_descr, ['board', 'slot'])) {
$icon = 'linecard'; // need something better
} elseif (str_contains_array($tmp_descr, ['Tray',])) {
$icon = 'package';
}
break;
}
break;
case str_starts($ent['entPhysicalClass'], [ 'routing', 'forwarding' ]):
$icon = 'routing';
break;
case $ent['entPhysicalClass'] === 'other':
$tmp_descr = $ent['entPhysicalDescr'] . ' ' . $ent['entPhysicalName'];
if (str_icontains_array($tmp_descr, [ 'switch' ])) {
$icon = 'switching';
} elseif (str_icontains_array($tmp_descr, [ 'cpu', 'processor' ])) {
$icon = 'processor';
} elseif (str_icontains_array($tmp_descr, [ 'ram', 'memory' ])) {
$icon = 'mempool';
} elseif (str_icontains_array($tmp_descr, [ 'flash', 'storage' ])) {
$icon = 'storage';
} elseif (str_icontains_array($tmp_descr, [ 'stack' ])) {
$icon = 'databases';
} elseif (str_icontains_array($tmp_descr, [ 'board', 'slot' ])) {
$icon = 'linecard'; // need something better
} elseif (str_contains_array($tmp_descr, [ 'Tray', ])) {
$icon = 'package';
if ($ent['deleted'] !== NULL) {
$icon = 'minus';
$icon = ':x:'; // emoji icon just for experiment
}
break;
$text .= get_icon($icon) . ' ';
if ($ent['entPhysicalParentRelPos'] > '-1') {
$text .= '<strong>' . $ent['entPhysicalParentRelPos'] . '.</strong> ';
}
$ent_text = '';
// port ifIndex
if ($ent['ifIndex'] && $port = get_port_by_ifIndex($device['device_id'], $ent['ifIndex'])) {
$link = generate_port_link($port);
}
if ($link) {
$ent['entPhysicalName'] = $link;
}
// vendor + model + hw
$ent_model = '';
if ($ent['entPhysicalModelName'] && is_valid_param($ent['entPhysicalModelName'], 'hardware')) {
if ($ent['entPhysicalMfgName'] && is_valid_param($ent['entPhysicalMfgName'], 'vendor')) {
$ent_model .= $ent['entPhysicalMfgName'];
}
$ent_model .= ' ' . $ent['entPhysicalModelName'];
if ($ent['entPhysicalHardwareRev'] && is_valid_param($ent['entPhysicalHardwareRev'], 'revision')) {
$ent_model .= " " . $ent['entPhysicalHardwareRev'];
}
$ent_model = trim($ent_model);
}
if ($ent['entPhysicalModelName'] && $ent_model) {
if ($ent['ifIndex']) {
// For ports different order
$ent_text .= "<strong>" . $ent['entPhysicalName'] . " (" . $ent_model . ")</strong>";
} else {
$ent_text .= "<strong>" . $ent_model . "</strong> (" . $ent['entPhysicalName'] . ")";
}
} elseif ($ent_model) {
$ent_text .= "<strong>" . $ent_model . "</strong>";
} elseif ($ent['entPhysicalName']) {
$ent_text .= "<strong>" . $ent['entPhysicalName'] . "</strong>";
} elseif ($ent['entPhysicalDescr']) {
$ent_text .= "<strong>" . $ent['entPhysicalDescr'] . "</strong>";
}
// entPhysicalAssetID
if (!safe_empty($ent['entPhysicalAssetID']) &&
!in_array($ent['entPhysicalAssetID'], ['zeroDotZero', 'zeroDotZero.0'])) {
$ent_text .= " (" . $ent['entPhysicalAssetID'] . ")";
}
// entPhysicalVendorType
if (!safe_empty($ent['entPhysicalVendorType']) &&
!in_array($ent['entPhysicalVendorType'], ['zeroDotZero', 'zeroDotZero.0'])) {
$ent_text .= " (" . $ent['entPhysicalVendorType'] . ")";
}
//$ent_text .= " [" . $ent['entPhysicalClass'] . "]"; // DEVEL
$ent_text .= "<br /><div class='small' style='margin-left: 20px;'>" . $ent['entPhysicalDescr'];
// Value
if ($value) {
$ent_text .= ' (' . $value . ')';
}
$text .= $ent_text;
// Serial, Hardware/Firmware/Software Rev
if ($ent['entPhysicalSerialNum']) {
$text .= ' <span class="label label-primary">SN: ' . $ent['entPhysicalSerialNum'] . '</span> ';
}
if ($ent['entPhysicalHardwareRev']) {
$text .= ' <span class="label label-default">HW: ' . $ent['entPhysicalHardwareRev'] . '</span> ';
}
if ($ent['entPhysicalFirmwareRev']) {
$text .= ' <span class="label label-info">FW: ' . $ent['entPhysicalFirmwareRev'] . '</span> ';
}
if ($ent['entPhysicalSoftwareRev']) {
$text .= ' <span class="label label-success">SW: ' . $ent['entPhysicalSoftwareRev'] . '</span> ';
}
// Deleted
if ($ent['deleted'] !== NULL) {
$text .= ' <span class="text-info">[Deleted: ' . $ent['deleted'] . ']</span> ';
}
$text .= "</div>";
echo($text);
$count = dbFetchCell("SELECT COUNT(*) FROM `entPhysical` WHERE `device_id` = ? AND `entPhysicalContainedIn` = ?", [$device['device_id'], $ent['entPhysicalIndex']]);
if ($count) {
echo("<ul>");
print_ent_physical($ent['entPhysicalIndex'], $level + 1, '');
echo("</ul>");
}
echo("</li>");
}
if ($ent['deleted'] !== NULL) {
$icon = 'minus';
$icon = ':x:'; // emoji icon just for experiment
}
$text .= get_icon($icon) . ' ';
if ($ent['entPhysicalParentRelPos'] > '-1') { $text .= '<strong>'.$ent['entPhysicalParentRelPos'].'.</strong> '; }
$ent_text = '';
// port ifIndex
if ($ent['ifIndex'] && $port = get_port_by_ifIndex($device['device_id'], $ent['ifIndex'])) {
$link = generate_port_link($port);
}
if ($link) {
$ent['entPhysicalName'] = $link;
}
// vendor + model + hw
$ent_model = '';
if ($ent['entPhysicalModelName'] && is_valid_param($ent['entPhysicalModelName'], 'hardware')) {
if ($ent['entPhysicalMfgName'] && is_valid_param($ent['entPhysicalMfgName'], 'vendor')) {
$ent_model .= $ent['entPhysicalMfgName'];
}
$ent_model .= ' ' . $ent['entPhysicalModelName'];
if ($ent['entPhysicalHardwareRev'] && is_valid_param($ent['entPhysicalHardwareRev'], 'revision')) {
$ent_model .= " " . $ent['entPhysicalHardwareRev'];
}
$ent_model = trim($ent_model);
}
if ($ent['entPhysicalModelName'] && $ent_model) {
if ($ent['ifIndex']) {
// For ports different order
$ent_text .= "<strong>" . $ent['entPhysicalName'] . " (" . $ent_model . ")</strong>";
} else {
$ent_text .= "<strong>" . $ent_model . "</strong> (" . $ent['entPhysicalName'] . ")";
}
} elseif ($ent_model) {
$ent_text .= "<strong>" . $ent_model . "</strong>";
} elseif ($ent['entPhysicalName']) {
$ent_text .= "<strong>" . $ent['entPhysicalName'] . "</strong>";
} elseif ($ent['entPhysicalDescr']) {
$ent_text .= "<strong>" . $ent['entPhysicalDescr'] . "</strong>";
}
// entPhysicalAssetID
if (strlen($ent['entPhysicalAssetID']) &&
!in_array($ent['entPhysicalAssetID'], [ 'zeroDotZero', 'zeroDotZero.0' ])) {
$ent_text .= " (" . $ent['entPhysicalAssetID'] . ")";
}
// entPhysicalVendorType
if (strlen($ent['entPhysicalVendorType']) &&
!in_array($ent['entPhysicalVendorType'], [ 'zeroDotZero', 'zeroDotZero.0' ])) {
$ent_text .= " (" . $ent['entPhysicalVendorType'] . ")";
}
//$ent_text .= " [" . $ent['entPhysicalClass'] . "]"; // DEVEL
$ent_text .= "<br /><div class='small' style='margin-left: 20px;'>" . $ent['entPhysicalDescr'];
// Value
if ($value) {
$ent_text .= ' (' . $value . ')';
}
$text .= $ent_text;
// Serial, Hardware/Firmware/Software Rev
if ($ent['entPhysicalSerialNum']) {
$text .= ' <span class="label label-primary">SN: '.$ent['entPhysicalSerialNum'].'</span> ';
}
if ($ent['entPhysicalHardwareRev']) {
$text .= ' <span class="label label-default">HW: '.$ent['entPhysicalHardwareRev'].'</span> ';
}
if ($ent['entPhysicalFirmwareRev']) {
$text .= ' <span class="label label-info">FW: '.$ent['entPhysicalFirmwareRev'].'</span> ';
}
if ($ent['entPhysicalSoftwareRev']) {
$text .= ' <span class="label label-success">SW: '.$ent['entPhysicalSoftwareRev'].'</span> ';
}
// Deleted
if ($ent['deleted'] !== NULL) {
$text .= ' <span class="text-info">[Deleted: '.$ent['deleted'].']</span> ';
}
$text .= "</div>";
echo($text);
$count = dbFetchCell("SELECT COUNT(*) FROM `entPhysical` WHERE `device_id` = ? AND `entPhysicalContainedIn` = ?", array($device['device_id'], $ent['entPhysicalIndex']));
if ($count) {
echo("<ul>");
print_ent_physical($ent['entPhysicalIndex'], $level+1, '');
echo("</ul>");
}
echo("</li>");
}
}
// EOF

View File

@ -4,169 +4,163 @@
*
* This file is part of Observium.
*
* @package observium
* @subpackage web
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2022 Observium Limited
* @package observium
* @subpackage web
* @copyright (C) Adam Armstrong
*
*/
function print_logalert_log($vars)
{
global $config;
global $config;
$entries = get_logalert_log($vars);
$entries = get_logalert_log($vars);
if (!$entries['count'])
{
// There have been no entries returned. Print the warning.
print_warning('<h4>No logging alert entries found!</h4>');
return;
if (!$entries['count']) {
// There have been no entries returned. Print the warning.
print_warning('<h4>No logging alert entries found!</h4>');
return;
} else {
} else {
// Entries have been returned. Print the table.
$list = array('device' => FALSE, 'program' => TRUE);
if (!isset($vars['device']) || empty($vars['device']) || $vars['page'] == 'alert_log') { $list['device'] = TRUE; }
if (!isset($vars['la_id']) || empty($vars['la_id'])) { $list['la_id'] = TRUE; }
// Entries have been returned. Print the table.
$list = ['device' => FALSE, 'program' => TRUE];
if (!isset($vars['device']) || empty($vars['device']) || $vars['page'] == 'alert_log') {
$list['device'] = TRUE;
}
if (!isset($vars['la_id']) || empty($vars['la_id'])) {
$list['la_id'] = TRUE;
}
$string = generate_box_open($vars['header']);
$string = generate_box_open($vars['header']);
$string .= '<table class="table table-striped table-hover table-condensed-more">' . PHP_EOL;
$string .= '<table class="table table-striped table-hover table-condensed-more">' . PHP_EOL;
if (!$entries['short'])
{
$cols = array();
$cols[] = array(NULL, 'class="state-marker"');
$cols['date'] = array('Date', 'style="width: 140px"');
if ($list['device'])
{
$cols['device'] = array('Device', 'style="width: 150px;"');
}
if ($list['la_id'])
{
$cols['la_id'] = array('Alert Rule', 'style="width: 150px;"');
}
$cols[] = array('Program', 'style="width: 80px"');
$cols[] = 'Message';
//$cols[] = array('Notified', 'style="width: 40px"');
$string .= get_table_header($cols); // , $vars); // Actually sorting is disabled now
}
$string .= ' <tbody>' . PHP_EOL;
if (!$entries['short']) {
$cols = [];
$cols[] = [NULL, 'class="state-marker"'];
$cols['date'] = ['Date', 'style="width: 140px"'];
if ($list['device']) {
$cols['device'] = ['Device', 'style="width: 150px;"'];
}
if ($list['la_id']) {
$cols['la_id'] = ['Alert Rule', 'style="width: 150px;"'];
}
$cols[] = ['Program', 'style="width: 80px"'];
$cols[] = 'Message';
//$cols[] = array('Notified', 'style="width: 40px"');
$string .= get_table_header($cols); // , $vars); // Actually sorting is disabled now
}
$string .= ' <tbody>' . PHP_EOL;
// Cache syslog rules
if (!isset($GLOBALS['cache']['syslog']['syslog_rules'])) {
$GLOBALS['cache']['syslog']['syslog_rules'] = [];
foreach (dbFetchRows("SELECT * FROM `syslog_rules` ORDER BY `la_name`") as $la) {
$syslog_rules[$la['la_id']] = $la;
$GLOBALS['cache']['syslog']['syslog_rules'][$la['la_id']] = $la;
}
}
if ($entries['short']) {
$vars['short'] = $entries['short'];
}
foreach ($entries['entries'] as $entry) {
$string .= generate_syslog_row($entry, $vars, $list);
}
$string .= ' </tbody>' . PHP_EOL;
$string .= '</table>';
$string .= generate_box_close();
// Cache syslog rules
if (!isset($GLOBALS['cache']['syslog']['syslog_rules']))
{
$GLOBALS['cache']['syslog']['syslog_rules'] = [];
foreach (dbFetchRows("SELECT * FROM `syslog_rules` ORDER BY `la_name`") as $la)
{
$syslog_rules[$la['la_id']] = $la;
$GLOBALS['cache']['syslog']['syslog_rules'][$la['la_id']] = $la;
}
}
if ($entries['short'])
{
$vars['short'] = $entries['short'];
}
foreach ($entries['entries'] as $entry)
{
$string .= generate_syslog_row($entry, $vars, $list);
// Print pagination header
if ($entries['pagination_html']) {
$string = $entries['pagination_html'] . $string . $entries['pagination_html'];
}
$string .= ' </tbody>' . PHP_EOL;
$string .= '</table>';
$string .= generate_box_close();
}
// Print pagination header
if ($entries['pagination_html']) { $string = $entries['pagination_html'] . $string . $entries['pagination_html']; }
// Print events
echo $string;
// Print events
echo $string;
}
function get_logalert_log($vars)
{
$array = array();
$array = [];
// Short events? (no pagination, small out)
$array['short'] = (isset($vars['short']) && $vars['short']);
// Short events? (no pagination, small out)
$array['short'] = (isset($vars['short']) && $vars['short']);
// With pagination? (display page numbers in header)
$array['pagination'] = (isset($vars['pagination']) && $vars['pagination']);
pagination($vars, 0, TRUE); // Get default pagesize/pageno
$array['pageno'] = $vars['pageno'];
$array['pagesize'] = $vars['pagesize'];
$start = $array['pagesize'] * $array['pageno'] - $array['pagesize'];
$pagesize = $array['pagesize'];
// With pagination? (display page numbers in header)
$array['pagination'] = (isset($vars['pagination']) && $vars['pagination']);
pagination($vars, 0, TRUE); // Get default pagesize/pageno
$array['pageno'] = $vars['pageno'];
$array['pagesize'] = $vars['pagesize'];
$start = $array['pagesize'] * $array['pageno'] - $array['pagesize'];
$pagesize = $array['pagesize'];
// Begin query generate
$param = array();
$where = ' WHERE 1 ';
foreach ($vars as $var => $value)
{
if ($value != '')
{
switch ($var)
{
case 'la_id':
$where .= generate_query_values_and($value, 'la_id');
break;
case 'device':
case 'device_id':
$where .= generate_query_values_and($value, 'device_id');
break;
case 'program':
$where .= generate_query_values_and($value, 'program', '%LIKE%');
break;
case 'message':
$where .= generate_query_values_and($value, 'message', '%LIKE%');
break;
case 'timestamp_from':
$where .= ' AND `timestamp` >= ?';
$param[] = $value;
break;
case 'timestamp_to':
$where .= ' AND `timestamp` <= ?';
$param[] = $value;
break;
}
// Begin query generate
$param = [];
$where = ' WHERE 1 ';
foreach ($vars as $var => $value) {
if ($value != '') {
switch ($var) {
case 'la_id':
$where .= generate_query_values_and($value, 'la_id');
break;
case 'device':
case 'device_id':
$where .= generate_query_values_and($value, 'device_id');
break;
case 'program':
$where .= generate_query_values_and($value, 'program', '%LIKE%');
break;
case 'message':
$where .= generate_query_values_and($value, 'message', '%LIKE%');
break;
case 'timestamp_from':
$where .= ' AND `timestamp` >= ?';
$param[] = $value;
break;
case 'timestamp_to':
$where .= ' AND `timestamp` <= ?';
$param[] = $value;
break;
}
}
}
}
// Show events only for permitted devices
$query_permitted = generate_query_permitted(); //generate_query_permitted(array('entity'));
// Show events only for permitted devices
$query_permitted = generate_query_permitted(); //generate_query_permitted(array('entity'));
$query = 'FROM `syslog_alerts` ';
$query .= $where . $query_permitted;
$query_count = 'SELECT COUNT(`la_id`) '.$query;
$query_updated = 'SELECT MAX(`timestamp`) '.$query;
$query = 'FROM `syslog_alerts` ';
$query .= $where . $query_permitted;
$query_count = 'SELECT COUNT(`la_id`) ' . $query;
$query_updated = 'SELECT MAX(`timestamp`) ' . $query;
$query = 'SELECT * '.$query;
$query .= ' ORDER BY `lal_id` DESC ';
$query .= "LIMIT $start,$pagesize";
$query = 'SELECT * ' . $query;
$query .= ' ORDER BY `lal_id` DESC ';
$query .= "LIMIT $start,$pagesize";
// Query events
$array['entries'] = dbFetchRows($query, $param);
// Query events
$array['entries'] = dbFetchRows($query, $param);
// Query events count
if ($array['pagination'] && !$array['short'])
{
$array['count'] = dbFetchCell($query_count, $param);
$array['pagination_html'] = pagination($vars, $array['count']);
} else {
$array['count'] = safe_count($array['entries']);
}
// Query events count
if ($array['pagination'] && !$array['short']) {
$array['count'] = dbFetchCell($query_count, $param);
$array['pagination_html'] = pagination($vars, $array['count']);
} else {
$array['count'] = safe_count($array['entries']);
}
// Query for last timestamp
$array['updated'] = dbFetchCell($query_updated, $param);
// Query for last timestamp
$array['updated'] = dbFetchCell($query_updated, $param);
//r($array);
return $array;
return $array;
}

View File

@ -4,9 +4,9 @@
*
* This file is part of Observium.
*
* @package observium
* @subpackage web
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2022 Observium Limited
* @package observium
* @subpackage web
* @copyright (C) Adam Armstrong
*
*/
@ -16,107 +16,108 @@
* Display pages with MAC addresses from device Interfaces.
*
* @param array $vars
*
* @return none
*
*/
function print_mac_addresses($vars)
{
// With pagination? (display page numbers in header)
$pagination = (isset($vars['pagination']) && $vars['pagination']);
pagination($vars, 0, TRUE); // Get default pagesize/pageno
$pageno = $vars['pageno'];
$pagesize = $vars['pagesize'];
$start = $pagesize * $pageno - $pagesize;
// With pagination? (display page numbers in header)
$pagination = (isset($vars['pagination']) && $vars['pagination']);
pagination($vars, 0, TRUE); // Get default pagesize/pageno
$pageno = $vars['pageno'];
$pagesize = $vars['pagesize'];
$start = $pagesize * $pageno - $pagesize;
$param = array();
$where = ' WHERE 1 ';
foreach ($vars as $var => $value)
{
if ($value != '')
{
switch ($var)
{
case 'device':
case 'device_id':
$where .= generate_query_values_and($value, 'device_id');
break;
case 'interface':
$where .= generate_query_values_and($value, 'ifDescr', 'LIKE');
break;
case 'address':
$value = str_replace([ ':', ' ', '-', '.', '0x' ], '', $value);
$where .= generate_query_values_and($value, 'ifPhysAddress', '%LIKE%');
break;
}
$param = [];
$where = ' WHERE 1 ';
foreach ($vars as $var => $value) {
if ($value != '') {
switch ($var) {
case 'device':
case 'device_id':
$where .= generate_query_values_and($value, 'device_id');
break;
case 'interface':
$where .= generate_query_values_and($value, 'ifDescr', 'LIKE');
break;
case 'address':
$value = str_replace([':', ' ', '-', '.', '0x'], '', $value);
$where .= generate_query_values_and($value, 'ifPhysAddress', '%LIKE%');
break;
}
}
}
}
$where .= ' AND `ifPhysAddress` IS NOT NULL'; //Exclude empty MACs
$where .= ' AND `ifPhysAddress` IS NOT NULL'; //Exclude empty MACs
// Show MACs only for permitted ports
$query_permitted = generate_query_permitted(array('port'));
// Show MACs only for permitted ports
$query_permitted = generate_query_permitted(['port']);
$query = 'FROM `ports` ';
$query .= $where . $query_permitted;
$query_count = 'SELECT COUNT(*) ' . $query;
$query = 'SELECT * ' . $query;
$query .= ' ORDER BY `ifPhysAddress`';
$query .= " LIMIT $start,$pagesize";
$query = 'FROM `ports` ';
$query .= $where . $query_permitted;
$query_count = 'SELECT COUNT(*) ' . $query;
$query = 'SELECT * ' . $query;
$query .= ' ORDER BY `ifPhysAddress`';
$query .= " LIMIT $start,$pagesize";
// Query addresses
$entries = dbFetchRows($query, $param);
// Query address count
if ($pagination) { $count = dbFetchCell($query_count, $param); }
$list = array('device' => FALSE);
if (!isset($vars['device']) || empty($vars['device']) || $vars['page'] == 'search') { $list['device'] = TRUE; }
$string = generate_box_open($vars['header']);
$string .= '<table class="table table-striped table-hover table-condensed">' . PHP_EOL;
if (!$short)
{
$string .= ' <thead>' . PHP_EOL;
$string .= ' <tr>' . PHP_EOL;
if ($list['device']) { $string .= ' <th>Device</th>' . PHP_EOL; }
$string .= ' <th>Interface</th>' . PHP_EOL;
$string .= ' <th>MAC Address</th>' . PHP_EOL;
$string .= ' <th>Description</th>' . PHP_EOL;
$string .= ' </tr>' . PHP_EOL;
$string .= ' </thead>' . PHP_EOL;
}
$string .= ' <tbody>' . PHP_EOL;
foreach ($entries as $entry)
{
if (port_permitted($entry['port_id']))
{
humanize_port($entry);
$string .= ' <tr>' . PHP_EOL;
if ($list['device'])
{
$dev = device_by_id_cache($entry['device_id']);
$string .= ' <td class="entity" style="white-space: nowrap;">' . generate_device_link($dev) . '</td>' . PHP_EOL;
}
if ($entry['ifInErrors_delta'] > 0 || $entry['ifOutErrors_delta'] > 0)
{
$port_error = generate_port_link($entry, '<span class="label label-important">Errors</span>', 'port_errors');
}
$string .= ' <td class="entity">' . generate_port_link_short($entry) . ' ' . $port_error . '</td>' . PHP_EOL;
$string .= ' <td style="width: 160px;">' . generate_popup_link('mac', $entry['human_mac'], array('page' => 'search', 'search' => 'mac', 'address' => $entry['human_mac'])) . '</td>' . PHP_EOL;
$string .= ' <td>' . $entry['ifAlias'] . '</td>' . PHP_EOL;
$string .= ' </tr>' . PHP_EOL;
// Query addresses
$entries = dbFetchRows($query, $param);
// Query address count
if ($pagination) {
$count = dbFetchCell($query_count, $param);
}
}
$string .= ' </tbody>' . PHP_EOL;
$string .= '</table>';
$string .= generate_box_close();
$list = ['device' => FALSE];
if (!isset($vars['device']) || empty($vars['device']) || $vars['page'] == 'search') {
$list['device'] = TRUE;
}
// Print pagination header
if ($pagination) { $string = pagination($vars, $count) . $string . pagination($vars, $count); }
$string = generate_box_open($vars['header']);
$string .= '<table class="table table-striped table-hover table-condensed">' . PHP_EOL;
if (!$short) {
$string .= ' <thead>' . PHP_EOL;
$string .= ' <tr>' . PHP_EOL;
if ($list['device']) {
$string .= ' <th>Device</th>' . PHP_EOL;
}
$string .= ' <th>Interface</th>' . PHP_EOL;
$string .= ' <th>MAC Address</th>' . PHP_EOL;
$string .= ' <th>Description</th>' . PHP_EOL;
$string .= ' </tr>' . PHP_EOL;
$string .= ' </thead>' . PHP_EOL;
}
$string .= ' <tbody>' . PHP_EOL;
// Print MAC addresses
echo $string;
foreach ($entries as $entry) {
if (port_permitted($entry['port_id'])) {
humanize_port($entry);
$string .= ' <tr>' . PHP_EOL;
if ($list['device']) {
$dev = device_by_id_cache($entry['device_id']);
$string .= ' <td class="entity" style="white-space: nowrap;">' . generate_device_link($dev) . '</td>' . PHP_EOL;
}
if ($entry['ifInErrors_delta'] > 0 || $entry['ifOutErrors_delta'] > 0) {
$port_error = generate_port_link($entry, '<span class="label label-important">Errors</span>', 'port_errors');
}
$string .= ' <td class="entity">' . generate_port_link_short($entry) . ' ' . $port_error . '</td>' . PHP_EOL;
$string .= ' <td style="width: 160px;">' . generate_popup_link('mac', $entry['human_mac'], ['page' => 'search', 'search' => 'mac', 'address' => $entry['human_mac']]) . '</td>' . PHP_EOL;
$string .= ' <td>' . $entry['ifAlias'] . '</td>' . PHP_EOL;
$string .= ' </tr>' . PHP_EOL;
}
}
$string .= ' </tbody>' . PHP_EOL;
$string .= '</table>';
$string .= generate_box_close();
// Print pagination header
if ($pagination) {
$string = pagination($vars, $count) . $string . pagination($vars, $count);
}
// Print MAC addresses
echo $string;
}
// EOF

File diff suppressed because it is too large Load Diff

View File

@ -6,7 +6,7 @@
*
* @package observium
* @subpackage web
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2022 Observium Limited
* @copyright (C) Adam Armstrong
*
*/
@ -21,130 +21,138 @@
* print_neighbours(array('pagesize' => 10, 'device' = 4)) - display 10 neighbours for device_id 4
*
* @param array $vars
*
* @return none
*
*/
function print_neighbours($vars)
{
// Get neighbours array
$neighbours = get_neighbours_array($vars);
// Get neighbours array
$neighbours = get_neighbours_array($vars);
if (!$neighbours['count'])
{
// There have been no entries returned. Print the warning.
print_warning('<h4>No neighbours found!</h4>');
} else {
// Entries have been returned. Print the table.
$list = array('device' => FALSE);
if ($vars['page'] !== 'device') { $list['device'] = TRUE; }
if (in_array($vars['graph'], array('bits', 'upkts', 'nupkts', 'pktsize', 'percent', 'errors', 'etherlike', 'fdb_count')))
{
$graph_types = array($vars['graph']);
if (!$neighbours['count']) {
// There have been no entries returned. Print the warning.
print_warning('<h4>No neighbours found!</h4>');
} else {
$graph_types = array('bits', 'upkts', 'errors');
}
$string = generate_box_open($vars['header']);
$string .= '<table class="table table-hover table-striped table-condensed">' . PHP_EOL;
$cols = array(
array(NULL, 'class="state-marker"'),
'device_a' => 'Local Device',
'port_a' => 'Local Port',
'NONE' => NULL,
'device_b' => 'Remote Device',
'port_b' => 'Remote Port',
'protocol' => 'Protocol',
'last_change' => 'Last changed',
);
if ($_SESSION['userlevel'] > 7)
{
$cols[] = '';//'Autodiscovery'
}
if (!$list['device']) { unset($cols[0], $cols['device_a']); }
$string .= get_table_header($cols, $vars);
$string .= ' <tbody>' . PHP_EOL;
$protocol_classmap = [
'cdp' => 'success',
'lldp' => 'warning',
'amap' => 'primary',
'mndp' => 'error',
'fdp' => 'delayed',
'edp' => 'suppressed'
];
foreach ($neighbours['entries'] as $entry)
{
$string .= ' <tr class="' . $entry['row_class'] . '">' . PHP_EOL;
if ($list['device'])
{
$string .= ' <td class="state-marker"></td>';
$string .= ' <td><span class="entity">' . generate_device_link($entry, NULL, array('tab' => 'ports', 'view' => 'neighbours')) . '</span></td>' . PHP_EOL;
}
$port = get_port_by_id_cache($entry['port_id']);
$string .= ' <td><span class="entity">'.generate_port_link($port) . '</span><br />' . escape_html($port['ifAlias']) . '</td>' . PHP_EOL;
$string .= ' <td><i class="icon-resize-horizontal text-success"></i></td>' . PHP_EOL;
//$string .= "<td></td><td></td>";
// r($entry['remote_port_id']); r($entry['remote_port']);
if (isset($entry['remote_port_id']) && is_numeric($entry['remote_port_id']))
{
$remote_port = get_port_by_id_cache($entry['remote_port_id']);
$remote_device = device_by_id_cache($remote_port['device_id']);
$remote_info = strlen($remote_device['hardware']) ? '<br />' . escape_html($remote_device['hardware']) : '';
if (strlen($remote_device['version']))
{
$remote_info .= '<br /><small><i>' . $GLOBALS['config']['os'][$remote_device['os']]['text'] . '&nbsp;' .
escape_html($remote_device['version']) . '</i></small>';
// Entries have been returned. Print the table.
$list = [ 'device' => FALSE ];
if ($vars['page'] !== 'device') {
$list['device'] = TRUE;
}
if (empty($remote_info))
{
$remote_info = '<br />' . escape_html(truncate($entry['remote_platform'], '100'));
if (strlen($entry['remote_version']))
{
$remote_info .= '<br /><small><i>' . escape_html(truncate($entry['remote_version'], 150)) . '</i></small>';
}
if (in_array($vars['graph'], ['bits', 'upkts', 'nupkts', 'pktsize', 'percent', 'errors', 'etherlike', 'fdb_count'])) {
$graph_types = [$vars['graph']];
} else {
$graph_types = ['bits', 'upkts', 'errors'];
}
$string .= ' <td><span class="entity">' . generate_device_link($remote_device) .'</span>' . $remote_info . '</td>' . PHP_EOL;
$string .= ' <td><span class="entity">' . generate_port_link($remote_port) . '</span><br />' . escape_html($remote_port['ifAlias']) . '</td>' . PHP_EOL;
} else {
$remote_ip = strlen($entry['remote_address']) ? ' ('.generate_popup_link('ip', $entry['remote_address']).')' : '';
$remote_version = strlen($entry['remote_version']) ? ' <br /><small><i>'.escape_html(truncate($entry['remote_version'], 150)).'</i></small>' : '';
$string .= ' <td><span class="entity">' . escape_html($entry['remote_hostname']) . $remote_ip . '</span><br />';
$string .= escape_html(truncate($entry['remote_platform'], '100')) . $remote_version . PHP_EOL;
$string .= '</td>';
$string .= ' <td><span class="entity">' . escape_html($entry['remote_port']) . '</span></td>' . PHP_EOL;
}
$string = generate_box_open($vars['header']);
if (isset($protocol_classmap[$entry['protocol']])) { $entry['protocol_class'] = 'label-'.$protocol_classmap[$entry['protocol']]; }
$string .= '<table class="table table-hover table-striped table-condensed">' . PHP_EOL;
$string .= ' <td><span class="label '.$entry['protocol_class'].'">' . strtoupper($entry['protocol']) . '</span></td>' . PHP_EOL;
$string .= ' <td class="text-nowrap">' . format_uptime(get_time() - $entry['last_change_unixtime'], 'shorter') . ' ago</td>' . PHP_EOL;
if ($_SESSION['userlevel'] > 7)
{
$string .= ' <td>' . generate_popup_link('autodiscovery', $entry['autodiscovery_id']) . '</td>' . PHP_EOL;
}
$string .= ' </tr>' . PHP_EOL;
$header = [
'state-marker' => '',
[ 'device_a' => 'Local Device' ],
[ 'port_a' => 'Local Port' ],
'',
[ 'device_b' => 'Remote Device' ],
[ 'port_b' => 'Remote Port' ],
[ 'protocol' => 'Protocol' ],
[ 'last_change' => 'Last changed', 'class' => 'text-nowrap' ],
];
if ($_SESSION['userlevel'] > 7) {
$header[] = ''; // 'Autodiscovery'
}
if (!$list['device']) {
//r($header);
unset($header[0], $header['state-marker']);
}
$string .= generate_table_header($header, $vars);
$string .= ' <tbody>' . PHP_EOL;
$protocol_classmap = [
'cdp' => 'success',
'lldp' => 'warning',
'amap' => 'primary',
'mndp' => 'error',
'fdp' => 'delayed',
'edp' => 'suppressed'
];
foreach ($neighbours['entries'] as $entry) {
$string .= ' <tr class="' . $entry['row_class'] . '">' . PHP_EOL;
if ($list['device']) {
$string .= ' <td class="state-marker"></td>';
$string .= ' <td><span class="entity">' . generate_device_link($entry, NULL, [ 'tab' => 'ports', 'view' => 'neighbours' ]) . '</span></td>' . PHP_EOL;
}
$port = get_port_by_id_cache($entry['port_id']);
$string .= ' <td><span class="entity">' . generate_port_link($port) . '</span><br />' . escape_html($port['ifAlias']) . '</td>' . PHP_EOL;
$string .= ' <td><i class="icon-resize-horizontal text-success"></i></td>' . PHP_EOL;
//$string .= "<td></td><td></td>";
//r($entry); //r($entry['remote_port']);
if ((is_intnum($entry['remote_device_id']) && $entry['remote_device_id']) || is_intnum($entry['remote_port_id'])) {
$remote_port = $entry['remote_port_id'] ? get_port_by_id_cache($entry['remote_port_id']) : [];
if ($entry['remote_device_id']) {
$remote_device = device_by_id_cache($entry['remote_device_id']);
} else {
$remote_device = device_by_id_cache($remote_port['device_id']);
}
$remote_info = !safe_empty($remote_device['hardware']) ? '<br />' . escape_html($remote_device['hardware']) : '';
if (!safe_empty($remote_device['version'])) {
$remote_info .= '<br /><small><i>' . $GLOBALS['config']['os'][$remote_device['os']]['text'] . '&nbsp;' .
escape_html($remote_device['version']) . '</i></small>';
}
if (empty($remote_info)) {
$remote_info = '<br />' . escape_html(truncate($entry['remote_platform'], '100'));
if (!safe_empty($entry['remote_version'])) {
$remote_info .= '<br /><small><i>' . escape_html(truncate($entry['remote_version'], 150)) . '</i></small>';
}
}
$string .= ' <td><span class="entity">' . generate_device_link($remote_device) . '</span>' . $remote_info . '</td>' . PHP_EOL;
if ($remote_port) {
$string .= ' <td><span class="entity">' . generate_port_link($remote_port) . '</span><br />' . escape_html($remote_port['ifAlias']) . '</td>' . PHP_EOL;
} else {
$string .= ' <td><span class="entity">' . escape_html($entry['remote_port']) . '</span></td>' . PHP_EOL;
}
} else {
$remote_ip = !safe_empty($entry['remote_address']) ? ' (' . generate_popup_link('ip', $entry['remote_address']) . ')' : '';
$remote_version = !safe_empty($entry['remote_version']) ? ' <br /><small><i>' . escape_html(truncate($entry['remote_version'], 150)) . '</i></small>' : '';
$string .= ' <td><span class="entity">' . escape_html($entry['remote_hostname']) . $remote_ip . '</span><br />';
$string .= escape_html(truncate($entry['remote_platform'], '100')) . $remote_version . PHP_EOL;
$string .= '</td>';
$string .= ' <td><span class="entity">' . escape_html($entry['remote_port']) . '</span></td>' . PHP_EOL;
}
if (isset($protocol_classmap[$entry['protocol']])) {
$entry['protocol_class'] = 'label-' . $protocol_classmap[$entry['protocol']];
}
$string .= ' <td><span class="label ' . $entry['protocol_class'] . '">' . strtoupper($entry['protocol']) . '</span></td>' . PHP_EOL;
$string .= ' <td class="text-nowrap">' . format_uptime(get_time() - $entry['last_change_unixtime'], 'shorter') . ' ago</td>' . PHP_EOL;
if ($_SESSION['userlevel'] > 7) {
$string .= ' <td>' . generate_popup_link('autodiscovery', $entry['autodiscovery_id']) . '</td>' . PHP_EOL;
}
$string .= ' </tr>' . PHP_EOL;
}
$string .= ' </tbody>' . PHP_EOL;
$string .= '</table>';
$string .= generate_box_close();
// Print pagination header
if ($neighbours['pagination_html']) {
$string = $neighbours['pagination_html'] . $string . $neighbours['pagination_html'];
}
// Print
echo $string;
}
$string .= ' </tbody>' . PHP_EOL;
$string .= '</table>';
$string .= generate_box_close();
// Print pagination header
if ($neighbours['pagination_html']) { $string = $neighbours['pagination_html'] . $string . $neighbours['pagination_html']; }
// Print
echo $string;
}
}
/**
@ -155,153 +163,150 @@ function print_neighbours($vars)
*/
function get_neighbours_array($vars)
{
$array = array();
$array = [];
// With pagination? (display page numbers in header)
$array['pagination'] = (isset($vars['pagination']) && $vars['pagination']);
pagination($vars, 0, TRUE); // Get default pagesize/pageno
$array['pageno'] = $vars['pageno'];
$array['pagesize'] = $vars['pagesize'];
$start = $array['pagesize'] * $array['pageno'] - $array['pagesize'];
$pagesize = $array['pagesize'];
// With pagination? (display page numbers in header)
$array['pagination'] = isset($vars['pagination']) && $vars['pagination'];
pagination($vars, 0, TRUE); // Get default pagesize/pageno
$array['pageno'] = $vars['pageno'];
$array['pagesize'] = $vars['pagesize'];
$start = $array['pagesize'] * $array['pageno'] - $array['pagesize'];
$pagesize = $array['pagesize'];
// Active by default
if (!isset($vars['active'])) { $vars['active'] = '1'; }
elseif ($vars['active'] === 'any') { unset($vars['active']); }
// Active by default
if (!isset($vars['active'])) {
$vars['active'] = '1';
} elseif ($vars['active'] === 'any') {
unset($vars['active']);
}
// Begin query generate
$param = array();
$where = ' WHERE 1 ';
foreach ($vars as $var => $value) {
if ($value != '') {
switch ($var) {
case 'device':
case 'device_id':
// Begin query generate
$param = [];
$where = ' WHERE 1 ';
$where_array = [];
foreach ($vars as $var => $value) {
if (!safe_empty($value)) {
switch ($var) {
case 'device':
case 'device_id':
case 'device_a':
$where_array[] = generate_query_values($value, 'device_id');
break;
case 'port':
case 'port_id':
case 'port_a':
$where_array[] = generate_query_values($value, 'port_id');
break;
case 'remote':
case 'device_b':
$where_array[] = generate_query_values($value, 'remote_hostname');
break;
case 'port_b':
$where_array[] = generate_query_values($value, 'remote_port');
break;
case 'protocol':
$where_array[] = generate_query_values($value, 'protocol');
break;
case 'platform':
$where_array[] = generate_query_values($value, 'remote_platform');
break;
case 'version':
$where_array[] = generate_query_values($value, 'remote_version');
break;
case 'active':
$value = !get_var_false($value, 'no') ? 1 : 0;
$where_array[] = generate_query_values($value, 'active');
break;
case 'known':
if ($value === 'NULL' || $value == 0) {
$where_array[] = 'ISNULL(`remote_port_id`)';
} else {
$where_array[] = '!ISNULL(`remote_port_id`)';
}
break;
}
}
}
// Show neighbours only for permitted devices and ports
//$query_permitted = $GLOBALS['cache']['where']['ports_permitted'];
$query_permitted = generate_query_permitted_ng([ 'ports', 'devices' ]);
if ($vars['sort'] === 'port_a') {
$query = 'SELECT `neighbours`.*, UNIX_TIMESTAMP(`last_change`) AS `last_change_unixtime`, `ports`.`port_label` ';
$query .= 'FROM `neighbours` LEFT JOIN `ports` USING(`port_id`,`device_id`) ';
} else {
$query = 'SELECT `neighbours`.*, UNIX_TIMESTAMP(`last_change`) AS `last_change_unixtime` ';
$query .= 'FROM `neighbours` ';
}
$query .= generate_where_clause($where_array, $query_permitted);
// Query neighbours
$array['entries'] = dbFetchRows($query, $param);
//r($array['entries']);
foreach ($array['entries'] as &$entry) {
$device = device_by_id_cache($entry['device_id']);
if (!$entry['active']) {
$entry['row_class'] = 'disabled';
} elseif ((isset($device['status']) && !$device['status'])) {
$entry['row_class'] = 'error';
} elseif (isset($device['disabled']) && $device['disabled']) {
$entry['row_class'] = 'ignore';
}
$entry['hostname'] = $device['hostname'];
//$entry['row_class'] = $device['row_class'];
}
// Sorting
// FIXME. Sorting can be as function, but in must before print_table_header and after get table from db
switch ($vars['sort_order']) {
case 'desc':
$sort_order = SORT_DESC;
$sort_neg = SORT_ASC;
break;
case 'reset':
unset($vars['sort'], $vars['sort_order']);
// no break here
default:
$sort_order = SORT_ASC;
$sort_neg = SORT_DESC;
}
switch ($vars['sort']) {
case 'device_a':
$where .= generate_query_values_and($value, 'device_id');
break;
case 'port':
case 'port_id':
$array['entries'] = array_sort_by($array['entries'], 'hostname', $sort_order, SORT_STRING);
break;
case 'port_a':
$where .= generate_query_values_and($value, 'port_id');
break;
$array['entries'] = array_sort_by($array['entries'], 'port_label', $sort_order, SORT_STRING);
break;
case 'device_b':
$where .= generate_query_values_and($value, 'remote_hostname');
break;
$array['entries'] = array_sort_by($array['entries'], 'remote_hostname', $sort_order, SORT_STRING);
break;
case 'port_b':
$where .= generate_query_values_and($value, 'remote_port');
break;
$array['entries'] = array_sort_by($array['entries'], 'remote_port', $sort_order, SORT_STRING);
break;
case 'protocol':
$where .= generate_query_values_and($value, 'protocol');
break;
case 'platform':
$where .= generate_query_values_and($value, 'remote_platform');
break;
case 'version':
$where .= generate_query_values_and($value, 'remote_version');
break;
case 'active':
$value = !get_var_false($value, 'no') ? '1' : '0';
$where .= generate_query_values_and($value, 'active');
break;
case 'remote_port_id':
if ($value === 'NULL' || $value == 0) {
$where .= ' AND isnull(`remote_port_id`)';
} else {
$where .= ' AND !isnull(`remote_port_id`)';
}
break;
}
$array['entries'] = array_sort_by($array['entries'], 'protocol', $sort_order, SORT_STRING);
break;
case 'last_change':
$array['entries'] = array_sort_by($array['entries'], 'last_change_unixtime', $sort_order, SORT_NUMERIC);
break;
default:
// Not sorted
}
}
// Show neighbours only for permitted devices and ports
//$query_permitted = $GLOBALS['cache']['where']['ports_permitted'];
$query_permitted = generate_query_permitted(array('ports', 'devices'));
if ($vars['sort'] === 'port_a') {
$query = 'SELECT `neighbours`.*, UNIX_TIMESTAMP(`last_change`) AS `last_change_unixtime`, `ports`.`port_label` ';
$query .= 'FROM `neighbours` LEFT JOIN `ports` USING(`port_id`,`device_id`) ';
} else {
$query = 'SELECT `neighbours`.*, UNIX_TIMESTAMP(`last_change`) AS `last_change_unixtime` ';
$query .= 'FROM `neighbours` ';
}
$query .= $where . ' ' . $query_permitted;
// Query neighbours
$array['entries'] = dbFetchRows($query, $param);
//r($array['entries']);
foreach ($array['entries'] as &$entry)
{
$device = &$GLOBALS['cache']['devices']['id'][$entry['device_id']];
if (!$entry['active'])
{
$entry['row_class'] = 'disabled';
// Query neighbours count
$array['count'] = safe_count($array['entries']);
if ($array['pagination']) {
$array['pagination_html'] = pagination($vars, $array['count']);
$array['entries'] = array_chunk($array['entries'], $vars['pagesize']);
$array['entries'] = $array['entries'][$vars['pageno'] - 1];
}
elseif ((isset($device['status']) && !$device['status']))
{
$entry['row_class'] = 'error';
}
elseif (isset($device['disabled']) && $device['disabled'])
{
$entry['row_class'] = 'ignore';
}
$entry['hostname'] = $device['hostname'];
//$entry['row_class'] = $device['row_class'];
}
// Sorting
// FIXME. Sorting can be as function, but in must before print_table_header and after get table from db
switch ($vars['sort_order']) {
case 'desc':
$sort_order = SORT_DESC;
$sort_neg = SORT_ASC;
break;
case 'reset':
unset($vars['sort'], $vars['sort_order']);
// no break here
default:
$sort_order = SORT_ASC;
$sort_neg = SORT_DESC;
}
switch ($vars['sort'])
{
case 'device_a':
$array['entries'] = array_sort_by($array['entries'], 'hostname', $sort_order, SORT_STRING);
break;
case 'port_a':
$array['entries'] = array_sort_by($array['entries'], 'port_label', $sort_order, SORT_STRING);
break;
case 'device_b':
$array['entries'] = array_sort_by($array['entries'], 'remote_hostname', $sort_order, SORT_STRING);
break;
case 'port_b':
$array['entries'] = array_sort_by($array['entries'], 'remote_port', $sort_order, SORT_STRING);
break;
case 'protocol':
$array['entries'] = array_sort_by($array['entries'], 'protocol', $sort_order, SORT_STRING);
break;
case 'last_change':
$array['entries'] = array_sort_by($array['entries'], 'last_change_unixtime', $sort_order, SORT_NUMERIC);
break;
default:
// Not sorted
}
// Query for last timestamp
//$array['updated'] = dbFetchCell($query_updated, $param);
// Query neighbours count
$array['count'] = safe_count($array['entries']);
if ($array['pagination'])
{
$array['pagination_html'] = pagination($vars, $array['count']);
$array['entries'] = array_chunk($array['entries'], $vars['pagesize']);
$array['entries'] = $array['entries'][$vars['pageno'] - 1];
}
// Query for last timestamp
//$array['updated'] = dbFetchCell($query_updated, $param);
return $array;
return $array;
}
// EOF

View File

@ -4,9 +4,9 @@
*
* This file is part of Observium.
*
* @package observium
* @subpackage web
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2022 Observium Limited
* @package observium
* @subpackage web
* @copyright (C) Adam Armstrong
*
*/
@ -25,374 +25,424 @@
* @return void
*
*/
function print_bgp_peer_table($vars) {
function print_bgp_peer_table($vars)
{
$entries = get_bgp_array($vars);
//r($entries);
$entries = get_bgp_array($vars);
//r($entries);
if (!$entries['count']) {
// There have been no entries returned. Print the warning.
print_warning('<h4>No BGP peers found!</h4>');
return;
}
// Entries have been returned. Print the table.
$list = [ 'device' => FALSE ];
if ($vars['page'] !== 'device') {
$list['device'] = TRUE;
}
switch ($vars['graph']) {
case 'prefixes_ipv4unicast':
case 'prefixes_ipv4multicast':
case 'prefixes_ipv4vpn':
case 'prefixes_ipv6unicast':
case 'prefixes_ipv6multicast':
case 'macaccounting_bits':
case 'macaccounting_pkts':
case 'updates':
$table_class = 'table-striped-two';
$list['graph'] = TRUE;
break;
default:
$table_class = 'table-striped';
$list['graph'] = FALSE;
}
$string = generate_box_open();
$string .= '<table class="table ' . $table_class . ' table-hover table-condensed ">' . PHP_EOL;
$cols = [
[ NULL, 'class="state-marker"' ],
[ NULL, 'style="width: 1px;"' ],
'device' => [ 'Local address', 'style="width: 150px;"' ],
'local_as' => [ 'Local AS / VRF', 'style="width: 110px;"' ],
[ NULL, 'style="width: 20px;"' ],
'peer_ip' => [ 'Peer address', 'style="width: 150px;"' ],
'peer_as' => [ 'Remote AS', 'style="width: 90px;"' ],
'type' => [ 'Type', 'style="width: 50px;"' ],
[ 'Family', 'style="width: 50px;"' ],
'state' => 'State',
'uptime' => 'Uptime / Updates',
];
//if (!$list['device']) { unset($cols['device']); }
$string .= get_table_header($cols, $vars);
$string .= ' <tbody>' . PHP_EOL;
foreach ($entries['entries'] as $peer) {
$local_dev = device_by_id_cache($peer['device_id']);
$local_as = ($list['device'] ? ' (AS' . $peer['human_local_as'] . ')' : '');
$local_name = generate_device_link_short($local_dev, [ 'tab' => 'routing', 'proto' => 'bgp' ], 18);
$local_ip = generate_device_link($local_dev, $peer['human_localip'] . $local_as, [ 'tab' => 'routing', 'proto' => 'bgp' ]);
$peer_as = 'AS' . $peer['human_remote_as'];
if ($peer['peer_device_id']) {
$peer_dev = device_by_id_cache($peer['peer_device_id']);
$peer_name = generate_device_link_short($peer_dev, [ 'tab' => 'routing', 'proto' => 'bgp' ], 18);
} else {
$peer_name = $peer['reverse_dns'];
}
$peer_ip = generate_entity_link("bgp_peer", $peer, $peer['human_remoteip']);
$peer_afis = &$entries['afisafi'][$peer['device_id']][$peer['bgpPeer_id']];
$peer_afis_html = [];
// Generate AFI/SAFI labels
foreach ($peer_afis as $peer_afi) {
// $peer_afi_html = '<span class="label-group">';
if (isset($GLOBALS['config']['routing_afis_name'][$peer_afi['afi']])) {
$afi_num = $GLOBALS['config']['routing_afis_name'][$peer_afi['afi']];
$afi_class = $GLOBALS['config']['routing_afis'][$afi_num]['class'];
} else {
$afi_class = 'default';
}
if (isset($GLOBALS['config']['routing_safis_name'][$peer_afi['safi']])) {
// Named SAFI
$safi_num = $GLOBALS['config']['routing_safis_name'][$peer_afi['safi']];
$safi_class = $GLOBALS['config']['routing_safis'][$safi_num]['class'];
} elseif (isset($GLOBALS['config']['routing_safis'][$peer_afi['safi']])) {
// Numeric SAFI
$safi_num = $peer_afi['safi'];
$peer_afi['safi'] = $GLOBALS['config']['routing_safis'][$safi_num]['name'];
$safi_class = $GLOBALS['config']['routing_safis'][$safi_num]['class'];
} else {
$safi_class = 'default';
}
$peer_afi_items = [
[ 'event' => $afi_class, 'text' => $peer_afi['afi'] ],
[ 'event' => $safi_class, 'text' => $peer_afi['safi'] ],
];
$peer_afi_html = get_label_group($peer_afi_items);
//r($peer_afi_html);
$peer_afis_html[] = $peer_afi_html;
if (!$entries['count']) {
// There have been no entries returned. Print the warning.
print_warning('<h4>No BGP peers found!</h4>');
return;
}
$string .= ' <tr class="' . $peer['html_row_class'] . '">' . PHP_EOL;
$string .= ' <td class="state-marker"></td>' . PHP_EOL;
$string .= ' <td></td>' . PHP_EOL;
$string .= ' <td style="white-space: nowrap" class="entity">' . $local_ip . '<br />' . $local_name . '</td>' . PHP_EOL;
$string .= ' <td><strong><span class="label label-' . $peer['peer_local_class'] . '">AS' . $peer['human_local_as'] . '</span></strong>';
if (!safe_empty($peer['virtual_name'])) {
$vitual_type = isset($GLOBALS['config']['os'][$local_dev['os']]['snmp']['virtual_type']) ? nicecase($GLOBALS['config']['os'][$local_dev['os']]['snmp']['virtual_type']) : 'VRF';
$string .= '<br /><span class="label">'.$vitual_type.': '.$peer['virtual_name'].'</span>';
// Entries have been returned. Print the table.
$list = ['device' => FALSE];
if ($vars['page'] !== 'device') {
$list['device'] = TRUE;
}
$string .= '</td>' . PHP_EOL;
$string .= ' <td><span class="text-success"><i class="glyphicon glyphicon-arrow-right"></i></span></td>' . PHP_EOL;
$string .= ' <td style="white-space: nowrap" class="entity">' . $peer_ip . '<br />' . $peer_name . '</td>' . PHP_EOL;
$string .= ' <td><strong>' . $peer_as . '</strong><br />' . $peer['astext'] . '</td>' . PHP_EOL;
$string .= ' <td><span class="label label-' . $peer['peer_type_class'] . '">' . $peer['peer_type'] . '</span></td>' . PHP_EOL;
$string .= ' <td>' . implode('<br />', $peer_afis_html) . '</td>' . PHP_EOL;
$string .= ' <td><strong><span class=" label label-' . $peer['admin_class'] . '">' . $peer['bgpPeerAdminStatus'] . '</span><br /><span class="label label-' . $peer['state_class'] . '">' . $peer['bgpPeerState'] . '</span></strong></td>' . PHP_EOL;
$string .= ' <td style="white-space: nowrap">' . format_uptime($peer['bgpPeerFsmEstablishedTime']) . '<br />
Updates: <i class="icon-circle-arrow-down text-success"></i> ' . format_si($peer['bgpPeerInUpdates']) . ' <i class="icon-circle-arrow-up text-primary"></i> ' . format_si($peer['bgpPeerOutUpdates']) . '</td>' . PHP_EOL;
$string .= ' </tr>' . PHP_EOL;
// Graphs
$peer_graph = FALSE;
switch ($vars['graph']) {
case 'prefixes_ipv4unicast':
case 'prefixes_ipv4multicast':
case 'prefixes_ipv4vpn':
case 'prefixes_ipv6unicast':
case 'prefixes_ipv6multicast':
$afisafi = preg_replace('/prefixes_(ipv[46])(\w+)/', '$1.$2', $vars['graph']); // prefixes_ipv6unicast ->> ipv6.unicast
if (isset($peer_afis[$afisafi]) && $peer['bgpPeer_id']) {
$graph_array['type'] = 'bgp_' . $vars['graph'];
$graph_array['id'] = $peer['bgpPeer_id'];
$peer_graph = TRUE;
}
break;
case 'prefixes_ipv4unicast':
case 'prefixes_ipv4multicast':
case 'prefixes_ipv4vpn':
case 'prefixes_ipv6unicast':
case 'prefixes_ipv6multicast':
case 'macaccounting_bits':
case 'macaccounting_pkts':
case 'updates':
$table_class = 'table-striped-two';
$list['graph'] = TRUE;
break;
default:
$table_class = 'table-striped';
$list['graph'] = FALSE;
}
case 'updates':
if ($peer['bgpPeer_id']) {
$graph_array['type'] = 'bgp_updates';
$graph_array['id'] = $peer['bgpPeer_id'];
$peer_graph = TRUE;
}
break;
$string = generate_box_open();
case 'macaccounting_bits':
case 'macaccounting_pkts':
// FIXME. I really still not know it works or not? -- mike
// This part copy-pasted from old code as is
$acc = dbFetchRow("SELECT * FROM `mac_accounting` AS M
$string .= '<table class="table ' . $table_class . ' table-hover table-condensed ">' . PHP_EOL;
$cols = [
[NULL, 'class="state-marker"'],
[NULL, 'style="width: 1px;"'],
'device' => ['Local address', 'style="width: 150px;"'],
'local_as' => ['Local AS / VRF', 'style="width: 110px;"'],
[NULL, 'style="width: 20px;"'],
'peer_ip' => ['Peer address', 'style="width: 150px;"'],
'peer_as' => ['Remote AS', 'style="width: 90px;"'],
'type' => ['Type', 'style="width: 50px;"'],
['Family', 'style="width: 50px;"'],
'state' => 'State',
'uptime' => 'Uptime / Updates',
];
//if (!$list['device']) { unset($cols['device']); }
$string .= get_table_header($cols, $vars);
$string .= ' <tbody>' . PHP_EOL;
foreach ($entries['entries'] as $peer) {
$local_dev = device_by_id_cache($peer['device_id']);
$local_as = ($list['device'] ? ' (AS' . $peer['human_local_as'] . ')' : '');
$local_name = generate_device_link_short($local_dev, ['tab' => 'routing', 'proto' => 'bgp'], 18);
$local_ip = generate_device_link($local_dev, $peer['human_localip'] . $local_as, ['tab' => 'routing', 'proto' => 'bgp']);
$peer_as = 'AS' . $peer['human_remote_as'];
if ($peer['peer_device_id']) {
$peer_dev = device_by_id_cache($peer['peer_device_id']);
$peer_name = generate_device_link_short($peer_dev, ['tab' => 'routing', 'proto' => 'bgp'], 18);
} else {
$peer_name = $peer['reverse_dns'];
}
$peer_ip = generate_entity_link("bgp_peer", $peer, $peer['human_remoteip']);
$peer_ip = generate_link($peer['human_remoteip'], ['page' => 'routing' , 'proto' => 'bgp', 'peer_ip' => $peer['human_remoteip'], 'view' => 'graphs', 'graph' => 'updates']);
$peer_afis = &$entries['afisafi'][$peer['device_id']][$peer['bgpPeer_id']];
$peer_afis_html = [];
// Generate AFI/SAFI labels
foreach ($peer_afis as $peer_afi) {
// $peer_afi_html = '<span class="label-group">';
if (isset($GLOBALS['config']['routing_afis_name'][$peer_afi['afi']])) {
$afi_num = $GLOBALS['config']['routing_afis_name'][$peer_afi['afi']];
$afi_class = $GLOBALS['config']['routing_afis'][$afi_num]['class'];
} else {
$afi_class = 'default';
}
if (isset($GLOBALS['config']['routing_safis_name'][$peer_afi['safi']])) {
// Named SAFI
$safi_num = $GLOBALS['config']['routing_safis_name'][$peer_afi['safi']];
$safi_class = $GLOBALS['config']['routing_safis'][$safi_num]['class'];
} elseif (isset($GLOBALS['config']['routing_safis'][$peer_afi['safi']])) {
// Numeric SAFI
$safi_num = $peer_afi['safi'];
$peer_afi['safi'] = $GLOBALS['config']['routing_safis'][$safi_num]['name'];
$safi_class = $GLOBALS['config']['routing_safis'][$safi_num]['class'];
} else {
$safi_class = 'default';
}
$peer_afi_items = [
['event' => $afi_class, 'text' => $peer_afi['afi']],
['event' => $safi_class, 'text' => $peer_afi['safi']],
];
$peer_afi_html = get_label_group($peer_afi_items);
//r($peer_afi_html);
$peer_afis_html[] = $peer_afi_html;
}
$string .= ' <tr class="' . $peer['html_row_class'] . '">' . PHP_EOL;
$string .= ' <td class="state-marker"></td>' . PHP_EOL;
$string .= ' <td></td>' . PHP_EOL;
$string .= ' <td style="white-space: nowrap" class="entity">' . $local_ip . '<br />' . $local_name . '</td>' . PHP_EOL;
$string .= ' <td><strong><span class="label label-' . $peer['peer_local_class'] . '">AS' . $peer['human_local_as'] . '</span></strong>';
if (!safe_empty($peer['virtual_name'])) {
$vitual_type = isset($GLOBALS['config']['os'][$local_dev['os']]['snmp']['virtual_type']) ? nicecase($GLOBALS['config']['os'][$local_dev['os']]['snmp']['virtual_type']) : 'VRF';
$string .= '<br /><span class="label label-primary">' . $vitual_type . ': ' . $peer['virtual_name'] . '</span>';
}
$string .= '</td>' . PHP_EOL;
$string .= ' <td><span class="text-success"><i class="glyphicon glyphicon-arrow-right"></i></span></td>' . PHP_EOL;
$string .= ' <td style="white-space: nowrap" class="entity">' . $peer_ip . '<br />' . $peer_name . '</td>' . PHP_EOL;
$string .= ' <td><a href="'.generate_url(['page' => 'routing' , 'proto' => 'bgp', 'peer_as' => $peer['human_remote_as'], 'view' => 'graphs', 'graph' => 'updates']).'">
<span class="label label-' . $peer['peer_type_class'] . '">' . $peer_as . '</span>
</a>
<br /><small>' . $peer['astext'] . '</small></td>' . PHP_EOL;
$string .= ' <td><span class="label label-' . $peer['peer_type_class'] . '">' . $peer['peer_type'] . '</span></td>' . PHP_EOL;
$string .= ' <td>' . implode('<br />', $peer_afis_html) . '</td>' . PHP_EOL;
$string .= ' <td><strong><span class=" label label-' . $peer['admin_class'] . '">' . $peer['bgpPeerAdminStatus'] . '</span><br /><span class="label label-' . $peer['state_class'] . '">' . $peer['bgpPeerState'] . '</span></strong></td>' . PHP_EOL;
$string .= ' <td style="white-space: nowrap">' . format_uptime($peer['bgpPeerFsmEstablishedTime']) . '<br />
Updates: <i class="icon-circle-arrow-down text-success"></i> ' . format_si($peer['bgpPeerInUpdates']) . ' <i class="icon-circle-arrow-up text-primary"></i> ' . format_si($peer['bgpPeerOutUpdates']) . '</td>' . PHP_EOL;
$string .= ' </tr>' . PHP_EOL;
// Graphs
$peer_graph = FALSE;
switch ($vars['graph']) {
case 'prefixes_ipv4unicast':
case 'prefixes_ipv4multicast':
case 'prefixes_ipv4vpn':
case 'prefixes_ipv6unicast':
case 'prefixes_ipv6multicast':
$afisafi = preg_replace('/prefixes_(ipv[46])(\w+)/', '$1.$2', $vars['graph']); // prefixes_ipv6unicast ->> ipv6.unicast
if (isset($peer_afis[$afisafi]) && $peer['bgpPeer_id']) {
$graph_array['type'] = 'bgp_' . $vars['graph'];
$graph_array['id'] = $peer['bgpPeer_id'];
$peer_graph = TRUE;
}
break;
case 'updates':
if ($peer['bgpPeer_id']) {
$graph_array['type'] = 'bgp_updates';
$graph_array['id'] = $peer['bgpPeer_id'];
$peer_graph = TRUE;
}
break;
case 'macaccounting_bits':
case 'macaccounting_pkts':
// FIXME. I really still not know it works or not? -- mike
// This part copy-pasted from old code as is
$acc = dbFetchRow("SELECT * FROM `mac_accounting` AS M
LEFT JOIN `ip_mac` AS I ON M.mac = I.mac_address
LEFT JOIN `ports` AS P ON P.port_id = M.port_id
LEFT JOIN `devices` AS D ON D.device_id = P.device_id
WHERE I.ip_address = ?", array($peer['bgpPeerRemoteAddr']));
$database = get_rrd_path($device, "cip-" . $acc['ifIndex'] . "-" . $acc['mac'] . ".rrd");
if (is_array($acc) && is_file($database)) {
$peer_graph = TRUE;
$graph_array['id'] = $acc['ma_id'];
$graph_array['type'] = $vars['graph'];
WHERE I.ip_address = ?", [$peer['bgpPeerRemoteAddr']]);
$database = get_rrd_path($device, "cip-" . $acc['ifIndex'] . "-" . $acc['mac'] . ".rrd");
if (is_array($acc) && is_file($database)) {
$peer_graph = TRUE;
$graph_array['id'] = $acc['ma_id'];
$graph_array['type'] = $vars['graph'];
}
break;
}
if ($peer_graph) {
$graph_array['to'] = get_time();
$string .= ' <tr class="' . $peer['html_row_class'] . '">' . PHP_EOL;
$string .= ' <td class="state-marker"></td><td colspan="10" style="white-space: nowrap">' . PHP_EOL;
$string .= generate_graph_row($graph_array);
$string .= ' </td>' . PHP_EOL . ' </tr>' . PHP_EOL;
} elseif ($list['graph']) {
// Empty row for correct view class table-striped-two
$string .= ' <tr class="' . $peer['html_row_class'] . '"><td class="state-marker"></td><td colspan="10"></td></tr>' . PHP_EOL;
}
break;
}
if ($peer_graph) {
$graph_array['to'] = get_time();
$string .= ' <tr class="' . $peer['html_row_class'] . '">' . PHP_EOL;
$string .= ' <td class="state-marker"></td><td colspan="10" style="white-space: nowrap">' . PHP_EOL;
$string .= ' </tbody>' . PHP_EOL;
$string .= '</table>';
$string .= generate_graph_row($graph_array);
$string .= generate_box_close();
$string .= ' </td>' . PHP_EOL . ' </tr>' . PHP_EOL;
} elseif ($list['graph']) {
// Empty row for correct view class table-striped-two
$string .= ' <tr class="' . $peer['html_row_class'] . '"><td class="state-marker"></td><td colspan="10"></td></tr>' . PHP_EOL;
// Print pagination header
if ($entries['pagination_html']) {
$string = $entries['pagination_html'] . $string . $entries['pagination_html'];
}
}
$string .= ' </tbody>' . PHP_EOL;
$string .= '</table>';
$string .= generate_box_close();
// Print pagination header
if ($entries['pagination_html']) {
$string = $entries['pagination_html'] . $string . $entries['pagination_html'];
}
// Print
echo $string;
// Print
echo $string;
}
// Populate bgp page specific bgp stuff. FIXME - replace
function bgp_cache_populate()
{
global $config;
global $cache;
foreach (dbFetchRows('SELECT `device_id`,`bgpPeer_id`,`local_as`,`bgpPeerState`,`bgpPeerAdminStatus`,`bgpPeerRemoteAs` FROM `bgpPeers`' . generate_where_clause(generate_query_permitted_ng(['device']))) as $bgp) {
if (!$config['web_show_disabled']) {
if (in_array($bgp['device_id'], $cache['devices']['disabled'])) {
continue;
}
}
// Cast id. Seems there's no need to do this as it's the db's primary key.
//$bgp['bgpPeer_id'] = (int)$bgp['bgpPeer_id'];
if (device_permitted($bgp)) {
$cache['bgp']['permitted'][] = $bgp['bgpPeer_id']; // Collect permitted peers
if ($bgp['bgpPeerAdminStatus'] === 'start' || $bgp['bgpPeerAdminStatus'] === 'running') {
$cache['bgp']['start'][] = $bgp['bgpPeer_id']; // Collect START peers (bgpPeerAdminStatus = (start || running))
if ($bgp['bgpPeerState'] !== 'established') {
} else {
$cache['bgp']['up'][] = $bgp['bgpPeer_id']; // Collect UP peers (bgpPeerAdminStatus = (start || running), bgpPeerState = established)
}
} else {
$cache['routing']['bgp']['down']++;
}
if ($bgp['local_as'] == $bgp['bgpPeerRemoteAs']) {
$cache['bgp']['internal'][] = $bgp['bgpPeer_id']; // Collect iBGP peers
} else {
$cache['bgp']['external'][] = $bgp['bgpPeer_id']; // Collect eBGP peers
}
}
}
}
/**
* Params:
*
* pagination, pageno, pagesize
* device, type, adminstatus, state
*/
function get_bgp_array($vars) {
$array = [];
function get_bgp_array($vars)
{
$array = [];
// With pagination? (display page numbers in header)
//$array['pagination'] = (isset($vars['pagination']) && $vars['pagination']);
$array['pagination'] = TRUE;
pagination($vars, 0, TRUE); // Get default pagesize/pageno
$array['pageno'] = $vars['pageno'];
$array['pagesize'] = $vars['pagesize'];
$start = $array['pagesize'] * $array['pageno'] - $array['pagesize'];
$pagesize = $array['pagesize'];
// With pagination? (display page numbers in header)
//$array['pagination'] = (isset($vars['pagination']) && $vars['pagination']);
$array['pagination'] = TRUE;
pagination($vars, 0, TRUE); // Get default pagesize/pageno
$array['pageno'] = $vars['pageno'];
$array['pagesize'] = $vars['pagesize'];
$start = $array['pagesize'] * $array['pageno'] - $array['pagesize'];
$pagesize = $array['pagesize'];
// Require cached IDs from html/includes/cache-data.inc.php
$cache_bgp = &$GLOBALS['cache']['bgp'];
// populate bgp cache for use here
bgp_cache_populate();
$cache_bgp = &$GLOBALS['cache']['bgp'];
// Begin query generate
$param = [];
$where = [];
foreach ($vars as $var => $value) {
if (!safe_empty($value)) {
switch ($var) {
case "group":
case "group_id":
$values = get_group_entities($value);
$where[] = generate_query_values_ng($values, 'bgpPeer_id');
break;
// Begin query generate
$single_device = FALSE;
$param = [];
$where = [];
foreach ($vars as $var => $value) {
if (!safe_empty($value)) {
switch ($var) {
case "group":
case "group_id":
$values = get_group_entities($value);
$where[] = generate_query_values($values, 'bgpPeer_id');
break;
case 'device':
case 'device_id':
$where[] = generate_query_values_ng($value, 'device_id');
break;
case 'device':
case 'device_id':
$where[] = generate_query_values($value, 'device_id');
$single_device = $vars['page'] === 'device' && device_permitted($value);
break;
case 'peer':
case 'peer_id':
$where[] = generate_query_values_ng($value, 'peer_device_id');
break;
case 'peer':
case 'peer_id':
$where[] = generate_query_values($value, 'peer_device_id');
break;
case 'local_ip':
$where[] = generate_query_values_ng(ip_uncompress($value), 'bgpPeerLocalAddr');
break;
case 'local_ip':
$where[] = generate_query_values(ip_uncompress($value), 'bgpPeerLocalAddr');
break;
case 'peer_ip':
$where[] = generate_query_values_ng(ip_uncompress($value), 'bgpPeerRemoteAddr');
break;
case 'peer_ip':
$where[] = generate_query_values(ip_uncompress($value), 'bgpPeerRemoteAddr');
break;
case 'local_as':
$where[] = generate_query_values_ng(bgp_asdot_to_asplain($value), 'local_as');
break;
case 'local_as':
$where[] = generate_query_values(bgp_asdot_to_asplain($value), 'local_as');
break;
case 'peer_as':
if (is_string($value) && preg_match_all('/AS(?<as>[\d\.]+):/', $value, $matches)) {
//r($matches);
$value = $matches['as'];
}
$where[] = generate_query_values_ng(bgp_asdot_to_asplain($value), 'bgpPeerRemoteAs');
break;
case 'peer_as':
if (is_string($value) && preg_match_all('/AS(?<as>[\d\.]+):/', $value, $matches)) {
//r($matches);
$value = $matches['as'];
}
$where[] = generate_query_values(bgp_asdot_to_asplain($value), 'bgpPeerRemoteAs');
break;
case 'type':
if ($value === 'external' || $value === 'ebgp') {
$where[] = generate_query_values_ng($cache_bgp['external'], 'bgpPeer_id');
} elseif ($value === 'internal' || $value === 'ibgp') {
$where[] = generate_query_values_ng($cache_bgp['internal'], 'bgpPeer_id');
}
break;
case 'type':
if ($value === 'external' || $value === 'ebgp') {
$where[] = generate_query_values($cache_bgp['external'], 'bgpPeer_id');
} elseif ($value === 'internal' || $value === 'ibgp') {
$where[] = generate_query_values($cache_bgp['internal'], 'bgpPeer_id');
}
break;
case 'adminstatus':
if ($value === 'stop') {
$where[] = generate_query_values_ng($cache_bgp['start'], 'bgpPeer_id', '!='); // NOT IN
} elseif ($value === 'start') {
$where[] = generate_query_values_ng($cache_bgp['start'], 'bgpPeer_id');
}
break;
case 'adminstatus':
if ($value === 'stop') {
$where[] = generate_query_values($cache_bgp['start'], 'bgpPeer_id', '!='); // NOT IN
} elseif ($value === 'start') {
$where[] = generate_query_values($cache_bgp['start'], 'bgpPeer_id');
}
break;
case 'state':
if ($value === 'down') {
$where[] = generate_query_values($cache_bgp['up'], 'bgpPeer_id', '!='); // NOT IN
} elseif ($value === 'up') {
$where[] = generate_query_values($cache_bgp['up'], 'bgpPeer_id');
}
break;
}
}
}
// Show peers only for permitted devices
/*
if ($single_device) {
// skip extra permissions check
} elseif ($_SESSION['userlevel'] < 5) {
$where[] = generate_query_values_ng($cache_bgp['permitted'], 'bgpPeer_id');
} elseif (!$GLOBALS['config']['web_show_disabled'] && $GLOBALS['cache']['devices']['stat']['disabled']) {
// Exclude disabled devices for Global Read+
$where[] = generate_query_values_ng($GLOBALS['cache']['devices']['disabled'], 'device_id', '!=');
} */
$where[] = generate_query_permitted_ng('device');
$where = generate_where_clause($where);
$query_count = 'SELECT COUNT(*) FROM `bgpPeers` ' . $where; // Use only bgpPeer_id and device_id in query!
$array['count'] = dbFetchCell($query_count, $param);
//$array['count'] = dbFetchCell($query_count, $param, TRUE);
// Pagination
$array['pagination_html'] = pagination($vars, $array['count']);
$query = 'SELECT `hostname`, `bgpLocalAs`, `bgpPeers`.*';
$query .= ' FROM `bgpPeers`';
$query .= ' JOIN `devices` USING (`device_id`) ';
$query .= $where;
$sort_dir = $vars['sort_order'] === 'desc' ? ' DESC' : '';
switch ($vars['sort']) {
case "device":
$sort = " ORDER BY `hostname`" . $sort_dir;
break;
case "local_as":
$sort = " ORDER BY `local_as`$sort_dir, `virtual_name`$sort_dir";
break;
case "peer_ip":
$sort = " ORDER BY `bgpPeerRemoteAddr`" . $sort_dir;
break;
case "peer_as":
$sort = " ORDER BY `bgpPeerRemoteAs`" . $sort_dir;
break;
case 'state':
if ($value === 'down') {
$where[] = generate_query_values_ng($cache_bgp['up'], 'bgpPeer_id', '!='); // NOT IN
} elseif ($value === 'up') {
$where[] = generate_query_values_ng($cache_bgp['up'], 'bgpPeer_id');
}
break;
}
$sort = " ORDER BY `bgpPeerAdminStatus`" . $sort_dir . ", `bgpPeerState`" . $sort_dir;
break;
case 'uptime':
$sort = " ORDER BY `bgpPeerFsmEstablishedTime`" . $sort_dir;
break;
default:
$sort = " ORDER BY `hostname`" . $sort_dir . ", `bgpPeerRemoteAs`" . $sort_dir . ", `bgpPeerRemoteAddr`" . $sort_dir;
}
}
// Show peers only for permitted devices
if ($_SESSION['userlevel'] < 5) {
$where[] = generate_query_values_ng($cache_bgp['permitted'], 'bgpPeer_id');
} elseif (!$GLOBALS['config']['web_show_disabled'] && $GLOBALS['cache']['devices']['stat']['disabled']) {
// Exclude disabled devices for Global Read+
$where[] = generate_query_values_ng($GLOBALS['cache']['devices']['disabled'], 'device_id', '!=');
}
$query .= $sort;
$query .= " LIMIT $start,$pagesize";
if (!safe_empty($where)) {
$where = 'WHERE ' . implode(' AND ', $where);
} else {
$where = '';
}
//r($where);
$peer_devices = [];
// Query BGP
foreach (dbFetchRows($query, $param) as $entry) {
humanize_bgp($entry);
$query_count = 'SELECT COUNT(*) FROM `bgpPeers` ' . $where; // Use only bgpPeer_id and device_id in query!
$array['count'] = dbFetchCell($query_count, $param);
//$array['count'] = dbFetchCell($query_count, $param, TRUE);
// Collect peer devices for AFI/SAFI
$peer_devices[$entry['device_id']] = 1;
// Pagination
$array['pagination_html'] = pagination($vars, $array['count']);
$query = 'SELECT `hostname`, `bgpLocalAs`, `bgpPeers`.*';
$query .= ' FROM `bgpPeers`';
$query .= ' JOIN `devices` USING (`device_id`) ';
$query .= $where;
$sort_dir = $vars['sort_order'] === 'desc' ? ' DESC' : '';
switch($vars['sort']) {
case "device":
$sort = " ORDER BY `hostname`".$sort_dir;
break;
case "local_as":
$sort = " ORDER BY `local_as`$sort_dir, `virtual_name`$sort_dir";
break;
case "peer_ip":
$sort = " ORDER BY `bgpPeerRemoteAddr`".$sort_dir;
break;
case "peer_as":
$sort = " ORDER BY `bgpPeerRemoteAs`".$sort_dir;
break;
case 'state':
$sort = " ORDER BY `bgpPeerAdminStatus`".$sort_dir.", `bgpPeerState`".$sort_dir;
break;
case 'uptime':
$sort = " ORDER BY `bgpPeerFsmEstablishedTime`".$sort_dir;
break;
default:
$sort = " ORDER BY `hostname`".$sort_dir.", `bgpPeerRemoteAs`".$sort_dir.", `bgpPeerRemoteAddr`".$sort_dir;
}
$query .= $sort;
$query .= " LIMIT $start,$pagesize";
$peer_devices = [];
// Query BGP
foreach (dbFetchRows($query, $param) as $entry) {
humanize_bgp($entry);
// Collect peer devices for AFI/SAFI
$peer_devices[$entry['device_id']] = 1;
$array['entries'][] = $entry;
}
// Query AFI/SAFI
if (!safe_empty($peer_devices)) {
$query_afi = 'SELECT * FROM `bgpPeers_cbgp` WHERE 1' . generate_query_values_and(array_keys($peer_devices), 'device_id');
foreach (dbFetchRows($query_afi) as $entry) {
$array['afisafi'][$entry['device_id']][$entry['bgpPeer_id']][$entry['afi'] . '.' . $entry['safi']] = [ 'afi' => $entry['afi'], 'safi' => $entry['safi'] ];
$array['entries'][] = $entry;
}
}
return $array;
// Query AFI/SAFI
if (!safe_empty($peer_devices)) {
$query_afi = 'SELECT * FROM `bgpPeers_cbgp` WHERE 1' . generate_query_values_and(array_keys($peer_devices), 'device_id');
foreach (dbFetchRows($query_afi) as $entry) {
$array['afisafi'][$entry['device_id']][$entry['bgpPeer_id']][$entry['afi'] . '.' . $entry['safi']] = ['afi' => $entry['afi'], 'safi' => $entry['safi']];
}
}
return $array;
}
// EOF

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -6,251 +6,52 @@
*
* @package observium
* @subpackage web
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2021 Observium Limited
* @copyright (C) Adam Armstrong
*
*/
/**
* Display status alerts.
*
* Display pages with alerts about device troubles.
* Examples:
* print_status(array('devices' => TRUE)) - display for devices down
*
* Another statuses:
* devices, uptime, ports, errors, services, bgp
*
* @param array $options
* @return none
*
*/
function print_status_old($options)
{
global $config;
function generate_alert_entries($vars) {
$max_interval = filter_var($options['max']['interval'], FILTER_VALIDATE_INT, array('options' => array('default' => 24, 'min_range' => 1)));
$max_count = filter_var($options['max']['count'], FILTER_VALIDATE_INT, array('options' => array('default' => 200, 'min_range' => 1)));
global $alert_rules;
global $config;
$string = '<table class="table table-striped table-hover table-condensed">' . PHP_EOL;
/* $string .= ' <thead>' . PHP_EOL;
$string .= ' <tr>' . PHP_EOL;
$string .= ' <th>Device</th>' . PHP_EOL;
$string .= ' <th>Type</th>' . PHP_EOL;
$string .= ' <th>Status</th>' . PHP_EOL;
$string .= ' <th>Entity</th>' . PHP_EOL;
// $string .= ' <th>Location</th>' . PHP_EOL;
$string .= ' <th>Information</th>' . PHP_EOL;
$string .= ' </tr>' . PHP_EOL;
$string .= ' </thead>' . PHP_EOL;
$string .= ' <tbody>' . PHP_EOL;
*/
$query_device_permitted = generate_query_permitted(array('device'), array('device_table' => 'D', 'hide_ignored' => TRUE));
$query_port_permitted = generate_query_permitted(array('port'), array('port_table' => 'I', 'hide_ignored' => TRUE));
// Show Device Status
if ($options['devices'])
{
$query = 'SELECT * FROM `devices` AS D';
$query .= ' WHERE D.`status` = 0' . $query_device_permitted;
$query .= ' ORDER BY D.`hostname` ASC';
$entries = dbFetchRows($query);
foreach ($entries as $device)
{
$string .= ' <tr>' . PHP_EOL;
$string .= ' <td class="entity">' . generate_device_link_short($device) . '</td>' . PHP_EOL;
// $string .= ' <td><span class="badge badge-inverse">Device</span></td>' . PHP_EOL;
$string .= ' <td><span class="label label-important">Device Down</span></td>' . PHP_EOL;
$string .= ' <td class="entity"><i class="'.$config['icon']['devices'].'"></i> ' . generate_device_link_short($device) . '</td>' . PHP_EOL;
// $string .= ' <td style="white-space: nowrap">' . escape_html(truncate($device['location'], 30)) . '</td>' . PHP_EOL;
$string .= ' <td style="white-space: nowrap">' . deviceUptime($device, 'short') . '</td>' . PHP_EOL;
$string .= ' </tr>' . PHP_EOL;
// This should be set outside, but do it here if it isn't
if (!is_array($alert_rules)) {
$alert_rules = cache_alert_rules();
}
}
/// WARN HERE
// Uptime
if ($options['uptime'])
{
if (filter_var($config['uptime_warning'], FILTER_VALIDATE_FLOAT) !== FALSE && $config['uptime_warning'] > 0)
{
$query = 'SELECT * FROM `devices` AS D';
// Since reboot event more complicated than just device uptime less than some time
//$query .= ' WHERE D.`status` = 1 AND D.`uptime` > 0 AND D.`uptime` < ' . $config['uptime_warning'];
$query .= ' WHERE D.`status` = 1 AND D.`uptime` > 0 AND D.`last_rebooted` > ?';
$query .= $query_device_permitted;
$query .= 'ORDER BY D.`hostname` ASC';
$entries = dbFetchRows($query, array($config['time']['now'] - $config['uptime_warning'] - 10));
$vars['sort'] = 'alert_last_changed';
foreach ($entries as $device)
{
$string .= ' <tr>' . PHP_EOL;
$string .= ' <td class="entity">' . generate_device_link_short($device) . '</td>' . PHP_EOL;
// $string .= ' <td><span class="badge badge-inverse">Device</span></td>' . PHP_EOL;
$string .= ' <td><span class="label label-success">Device Rebooted</span></td>' . PHP_EOL;
$string .= ' <td class="entity"><i class="'.$config['icon']['devices'].'"></i> ' . generate_device_link_short($device) . '</td>' . PHP_EOL;
// $string .= ' <td style="white-space: nowrap">' . escape_html(truncate($device['location'], 30)) . '</td>' . PHP_EOL;
$string .= ' <td style="white-space: nowrap">Uptime ' . format_uptime($device['uptime'], 'short') . '</td>' . PHP_EOL;
$string .= ' </tr>' . PHP_EOL;
}
[ $query, $param, $query_count ] = build_alert_table_query($vars);
// Fetch alerts
//$count = dbFetchCell($query_count, $param);
$alerts = dbFetchRows($query, $param);
$array = [];
foreach ($alerts as $alert) {
$alert_rule = &$alert_rules[$alert['alert_test_id']];
$alert['severity'] = $alert_rule['severity'];
humanize_alert_entry($alert);
$device = device_by_id_cache($alert['device_id']);
$array[] = [
'sev' => 100,
'icon' => $config['entities'][$alert['entity_type']]['icon'],
'alert_test_id' => $alert['alert_test_id'],
'event' => '<a href="' . generate_url(['page' => 'alert_check', 'alert_test_id' => $alert_rule['alert_test_id']]) . '">' . escape_html($alert_rule['alert_name']) . '</a>',
'entity_type' => $alert['entity_type'],
'entity_id' => $alert['entity_id'],
'entity_link' => $alert['entity_type'] !== "device" ? generate_entity_link($alert['entity_type'], $alert['entity_id'], NULL, NULL, TRUE, TRUE) : NULL,
'device_id' => $device['device_id'],
'device_link' => generate_device_link_short($device),
'time' => $alert['changed']
];
}
}
// Ports Down
if ($options['ports'] || $options['neighbours'] || $options['links'])
{
$options['neighbours'] = $options['neighbours'] && !$options['ports']; // Disable 'neighbours' if 'ports' already enabled
$query = 'SELECT * FROM `ports` AS I ';
if ($options['neighbours'])
{
$query .= 'INNER JOIN `neighbours` AS L ON I.`port_id` = L.`port_id` ';
}
$query .= 'LEFT JOIN `devices` AS D ON I.`device_id` = D.`device_id` ';
$query .= "WHERE D.`status` = 1 AND D.ignore = 0 AND I.ignore = 0 AND I.deleted = 0 AND I.`ifAdminStatus` = 'up' AND (I.`ifOperStatus` = 'lowerLayerDown' OR I.`ifOperStatus` = 'down') ";
if ($options['neighbours'])
{
$query .= ' AND L.`active` = 1 ';
}
$query .= $query_port_permitted;
$query .= ' AND I.`ifLastChange` >= DATE_SUB(NOW(), INTERVAL '.$max_interval.' HOUR) ';
if ($options['neighbours']) { $query .= 'GROUP BY L.`port_id` '; }
$query .= 'ORDER BY I.`ifLastChange` DESC, D.`hostname` ASC, I.`ifDescr` * 1 ASC ';
$entries = dbFetchRows($query);
$i = 1;
foreach ($entries as $port)
{
if ($i > $max_count)
{
$string .= ' <tr><td></td><td><span class="badge badge-info">Port</span></td>';
$string .= '<td><span class="label label-important">Port Down</span></td>';
$string .= '<td colspan=3>Too many ports down. See <strong><a href="'.generate_url(array('page'=>'ports'), array('state'=>'down')).'">All DOWN ports</a></strong>.</td></tr>' . PHP_EOL;
break;
}
humanize_port($port);
$string .= ' <tr>' . PHP_EOL;
$string .= ' <td class="entity">' . generate_device_link_short($port) . '</td>' . PHP_EOL;
// $string .= ' <td><span class="badge badge-info">Port</span></td>' . PHP_EOL;
$string .= ' <td><span class="label label-important">Port Down</span></td>' . PHP_EOL;
$string .= ' <td class="entity">' . get_icon('port') . ' ' . generate_port_link_short($port) . '</td>' . PHP_EOL;
// $string .= ' <td style="white-space: nowrap">' . escape_html(truncate($port['location'], 30)) . '</td>' . PHP_EOL;
$string .= ' <td style="white-space: nowrap">Down for ' . format_uptime($config['time']['now'] - strtotime($port['ifLastChange']), 'short'); // This is like deviceUptime()
if ($options['links']) { $string .= ' ('.nicecase($port['protocol']).': ' .$port['remote_hostname'].' / ' .$port['remote_port'] .')'; }
$string .= '</td>' . PHP_EOL;
$string .= ' </tr>' . PHP_EOL;
$i++;
}
}
// Ports Errors (only deltas)
if ($options['errors'])
{
$query = 'SELECT * FROM `ports` AS I ';
//$query .= 'LEFT JOIN `ports-state` AS E ON I.`port_id` = E.`port_id` ';
$query .= 'LEFT JOIN `devices` AS D ON I.`device_id` = D.`device_id` ';
$query .= "WHERE D.`status` = 1 AND I.`ifOperStatus` = 'up' AND (I.`ifInErrors_delta` > 0 OR I.`ifOutErrors_delta` > 0)";
$query .= $query_port_permitted;
$query .= 'ORDER BY D.`hostname` ASC, I.`ifDescr` * 1 ASC';
$entries = dbFetchRows($query);
foreach ($entries as $port)
{
humanize_port($port);
$string .= ' <tr>' . PHP_EOL;
$string .= ' <td class="entity">' . generate_device_link_short($port) . '</td>' . PHP_EOL;
// $string .= ' <td><span class="badge badge-info">Port</span></td>' . PHP_EOL;
$string .= ' <td><span class="label label-important">Port Errors</span></td>' . PHP_EOL;
$string .= ' <td class="entity">' . get_icon('port') . ' ' . generate_port_link_short($port, NULL, 'port_errors') . '</td>' . PHP_EOL;
// $string .= ' <td style="white-space: nowrap">' . escape_html(truncate($port['location'], 30)) . '</td>' . PHP_EOL;
$string .= ' <td>Errors ';
if ($port['ifInErrors_delta']) { $string .= 'In: ' . $port['ifInErrors_delta']; }
if ($port['ifInErrors_delta'] && $port['ifOutErrors_delta']) { $string .= ', '; }
if ($port['ifOutErrors_delta']) { $string .= 'Out: ' . $port['ifOutErrors_delta']; }
$string .= '</td>' . PHP_EOL;
$string .= ' </tr>' . PHP_EOL;
}
}
// BGP
if ($options['bgp'])
{
if (isset($config['enable_bgp']) && $config['enable_bgp'])
{
// Description for BGP states
$bgpstates = 'IDLE - Router is searching routing table to see whether a route exists to reach the neighbor. &#xA;';
$bgpstates .= 'CONNECT - Router found a route to the neighbor and has completed the three-way TCP handshake. &#xA;';
$bgpstates .= 'OPEN SENT - Open message sent, with parameters for the BGP session. &#xA;';
$bgpstates .= 'OPEN CONFIRM - Router received agreement on the parameters for establishing session. &#xA;';
$bgpstates .= 'ACTIVE - Router did not receive agreement on parameters of establishment. &#xA;';
//$bgpstates .= 'ESTABLISHED - Peering is established; routing begins.';
$query = 'SELECT * FROM `devices` AS D ';
$query .= 'LEFT JOIN `bgpPeers` AS B ON B.`device_id` = D.`device_id` ';
$query .= "WHERE D.`status` = 1 AND (`bgpPeerAdminStatus` = 'start' OR `bgpPeerAdminStatus` = 'running') AND `bgpPeerState` != 'established' ";
$query .= $query_device_permitted;
$query .= 'ORDER BY D.`hostname` ASC';
$entries = dbFetchRows($query);
foreach ($entries as $peer)
{
humanize_bgp($peer);
$peer_ip = generate_entity_link("bgp_peer", $peer, $peer['human_remoteip']);
$string .= ' <tr>' . PHP_EOL;
$string .= ' <td class="entity">' . generate_device_link_short($peer, [ 'tab' => 'routing', 'proto' => 'bgp' ]) . '</td>' . PHP_EOL;
// $string .= ' <td><span class="badge badge-warning">BGP</span></td>' . PHP_EOL;
$string .= ' <td><span class="label label-warning" title="' . $bgpstates . '">BGP ' . nicecase($peer['bgpPeerState']) . '</span></td>' . PHP_EOL;
$string .= ' <td class="entity" style="white-space: nowrap"><i class="'.$config['icon']['bgp'].'"></i> ' . $peer_ip . '</td>' . PHP_EOL;
// $string .= ' <td style="white-space: nowrap">' . escape_html(truncate($peer['location'], 30)) . '</td>' . PHP_EOL;
$string .= ' <td><strong>AS' . $peer['human_remote_as'] . ' :</strong> ' . $peer['astext'] . '</td>' . PHP_EOL;
$string .= ' </tr>' . PHP_EOL;
}
}
}
// $string .= ' </tbody>' . PHP_EOL;
$string .= '</table>';
// Final print all statuses
echo($string);
}
function generate_alert_entries($vars)
{
global $alert_rules;
global $config;
// This should be set outside, but do it here if it isn't
if (!is_array($alert_rules)) { $alert_rules = cache_alert_rules(); }
/// WARN HERE
$vars['sort'] = 'alert_last_changed';
list($query, $param, $query_count) = build_alert_table_query($vars);
// Fetch alerts
$count = dbFetchCell($query_count, $param);
$alerts = dbFetchRows($query, $param);
foreach ($alerts as $alert)
{
$alert_rule = &$alert_rules[$alert['alert_test_id']];
$alert['severity'] = $alert_rule['severity'];
humanize_alert_entry($alert);
$device = device_by_id_cache($alert['device_id']);
$array[] = array('sev' => 100,
'icon_tag' => '<i class="' . $config['entities'][$alert['entity_type']]['icon'] . '"></i>',
'alert_test_id' => $alert['alert_test_id'],
'event' => '<a href="'. generate_url(array('page' => 'alert_check', 'alert_test_id' => $alert_rule['alert_test_id'])). '">'. escape_html($alert_rule['alert_name']). '</a>',
'entity_type' => $alert['entity_type'],
'entity_id' => $alert['entity_id'],
'entity_link' => ($alert['entity_type'] != "device" ? generate_entity_link($alert['entity_type'], $alert['entity_id'],NULL, NULL, TRUE, TRUE) : NULL),
'device_id' => $device['device_id'],
'device_link' => generate_device_link_short($device),
'time' => $alert['changed']);
}
return $array;
return $array;
}
@ -269,261 +70,280 @@ function generate_alert_entries($vars)
* @return void|true
*
*/
function print_status_boxes($options, $limit = NULL) {
if (isset($options['widget_type']) && $options['widget_type'] === 'alert_boxes') {
$status_array = generate_alert_entries(array('status' => 'failed')); //, 'entity_id' => '1'));
} elseif ($status_array = get_status_array($options)) {
$status_array = array_sort($status_array, 'sev', 'SORT_DESC');
}
$count = safe_count($status_array);
if ($count === 0) {
echo '<div class="alert statusbox alert-info" style="border-left: 1px; width: 80%; height: 75px; margin-left:10%; float:none; display: block;">';
echo '<div style="margin: auto; line-height: 75px; text-align: center;">There are currently no ongoing alert events.</div>';
echo '</div>';
return;
}
$i = 1;
foreach ($status_array as $entry)
{
if ($i >= $limit)
{
echo('<div class="alert statusbox alert-danger" style="border-left: 1px;">');
echo '<div style="margin: auto; line-height: 75px; text-align: center;"><b>' . $count . ' more...</b></div>';
echo('</div>');
return;
function print_status_boxes($options, $limit = NULL)
{
if (isset($options['widget_type']) && $options['widget_type'] === 'alert_boxes') {
$status_array = generate_alert_entries(['status' => 'failed']); //, 'entity_id' => '1'));
} elseif ($status_array = get_status_array($options)) {
$status_array = array_sort($status_array, 'sev', 'SORT_DESC');
}
if ($entry['entity_link'])
{
$entry['entity_link'] = preg_replace('/(<a.*?>)(.{0,20}).*(<\/a>)/', '\\1\\2\\3', $entry['entity_link']);
$count = safe_count($status_array);
if ($count === 0) {
echo '<div class="alert statusbox alert-info" style="border-left: 1px; width: 80%; height: 75px; margin-left:10%; float:none; display: block;">';
echo '<div style="margin: auto; line-height: 75px; text-align: center;">There are currently no ongoing alert events.</div>';
echo '</div>';
return;
}
if ($entry['sev'] > 51) { $class = "alert-danger"; }
elseif ($entry['sev'] > 20) { $class = "alert-warning"; }
else { $class = "alert-info"; }
$i = 1;
foreach ($status_array as $entry) {
if ($i >= $limit) {
echo('<div class="alert statusbox alert-danger" style="border-left: 1px;">');
echo '<div style="margin: auto; line-height: 75px; text-align: center;"><b>' . $count . ' more...</b></div>';
echo('</div>');
//if ($entry['wide']) { $class .= ' statusbox-wide'; }
return;
}
echo('<div class="alert statusbox ' . $class . '" style="text-align: center;position: relative;">
if ($entry['entity_link']) {
$entry['entity_link'] = preg_replace('/(<a.*?>)(.{0,20}).*(<\/a>)/', '\\1\\2\\3', $entry['entity_link']);
}
if ($entry['sev'] > 51) {
$class = "alert-danger";
} elseif ($entry['sev'] > 20) {
$class = "alert-warning";
} else {
$class = "alert-info";
}
//if ($entry['wide']) { $class .= ' statusbox-wide'; }
echo('<div class="alert statusbox ' . $class . '" style="text-align: center;position: relative;">
<p style="margin: 0; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);">');
echo '<h4>' . $entry['device_link'] . '</h4>';
echo '' . $entry['event'] . '<br />';
echo '<h4 style="margin-bottom: 2px;">' . ($entry['entity_link'] ? $entry['icon_tag'] . $entry['entity_link'] : 'Device') . ' </h4>';
echo '<small>' . $entry['time'] . '</small>';
echo('</p></div>');
echo '<h4>' . $entry['device_link'] . '</h4>';
echo '' . $entry['event'] . '<br />';
echo '<h4 style="margin-bottom: 2px;">' . ($entry['entity_link'] ? get_icon($entry['icon']) . $entry['entity_link'] : 'Device') . ' </h4>';
echo '<small>' . $entry['time'] . '</small>';
echo('</p></div>');
$count--;
$i++;
}
$count--;
$i++;
}
return TRUE;
return TRUE;
}
function generate_status_table($options, $print = FALSE)
{
function generate_status_table($options, $print = FALSE) {
$status_array = get_status_array($options);
$status_array = array_sort($status_array, 'sev', 'SORT_DESC');
$i = 1; $string = '';
$string .= '<table style="" class="table table-striped table-hover table-condensed">' . PHP_EOL;
$status_array = get_status_array($options);
$status_array = array_sort($status_array, 'sev', 'SORT_DESC');
$string = '<table style="" class="table table-striped table-hover table-condensed">' . PHP_EOL;
foreach ($status_array as $entry)
{
if ($entry['sev'] > 51) { $class = "danger"; $row_class = 'error'; }
elseif ($entry['sev'] > 20) { $class = "warning"; $row_class = 'warning'; }
else { $class = "info"; }
foreach ($status_array as $entry) {
if ($entry['sev'] > 51) {
$class = "danger";
$row_class = 'error';
} elseif ($entry['sev'] > 20) {
$class = "warning";
$row_class = 'warning';
} else {
$class = "info";
$row_class = '';
}
$string .= ' <tr class="' . $row_class . '">' . PHP_EOL;
$string .= ' <td class="state-marker"></td>';
$string .= ' <td class="entity">' . $entry['device_link'] . '</td>' . PHP_EOL;
$string .= ' <td><span class="label label-' . $class . '" title="' . $entry['event'] . '">' . $entry['class'] . ' ' . $entry['event'] . '</span></td>' . PHP_EOL;
$string .= ' <td class="entity" style="white-space: nowrap">' . get_icon($entry['icon']) . ($entry['entity_link'] ?: $entry['device_link']) . '</td>' . PHP_EOL;
$string .= ' <td>' . $entry['time'] . '</td>' . PHP_EOL;
$string .= ' </tr>' . PHP_EOL;
}
$string .= '</table>';
if ($print) {
echo $string;
return TRUE;
}
$string .= ' <tr class="'.$row_class.'">' . PHP_EOL;
$string .= ' <td class="state-marker"></td>';
$string .= ' <td class="entity">' . $entry['device_link'] . '</td>' . PHP_EOL;
$string .= ' <td><span class="label label-'.$class.'" title="' . $entry['event'] . '">'.$entry['class'].' '.$entry['event'].'</span></td>' . PHP_EOL;
$string .= ' <td class="entity" style="white-space: nowrap">'. $entry['icon_tag'] . ($entry['entity_link'] ? $entry['entity_link'] : $entry['device_link']) . '</td>' . PHP_EOL;
$string .= ' <td>' . $entry['time'] . '</td>' . PHP_EOL;
$string .= ' </tr>' . PHP_EOL;
}
$string .= '</table>';
if($print == TRUE)
{
echo $string;
return TRUE;
} else {
return $string;
}
}
// DOCME needs phpdoc block
function get_status_array($options)
{
// Mike: I know that there are duplicated variables, but later will remove global
global $config;
function get_status_array($options) {
global $config;
$max_interval = filter_var($options['max']['interval'], FILTER_VALIDATE_INT, array('options' => array('default' => 24, 'min_range' => 1)));
$max_count = filter_var($options['max']['count'], FILTER_VALIDATE_INT, array('options' => array('default' => 200, 'min_range' => 1)));
$query_device_permitted = generate_query_permitted(array('device'), array('device_table' => 'D', 'hide_ignored' => TRUE, 'hide_disabled' => TRUE));
$query_port_permitted = generate_query_permitted(array('port'), array('port_table' => 'I', 'hide_ignored' => TRUE));
$boxes = [];
$max_interval = filter_var($options['max']['interval'], FILTER_VALIDATE_INT, ['options' => ['default' => 24, 'min_range' => 1]]);
$max_count = filter_var($options['max']['count'], FILTER_VALIDATE_INT, ['options' => ['default' => 200, 'min_range' => 1]]);
$query_device_permitted = generate_query_permitted_ng([ 'device' ], [ 'hide_ignored' => TRUE, 'hide_disabled' => TRUE ]);
// Show Device Status
if ($options['devices'])
{
$query = 'SELECT * FROM `devices` AS D ';
$query .= 'WHERE D.`status` = 0' . $query_device_permitted;
$query .= 'ORDER BY D.`hostname` ASC';
$entries = dbFetchRows($query);
foreach ($entries as $device)
{
$boxes[] = array('sev' => 100,
'class' => 'Device',
'event' => 'Down',
'device_link' => generate_device_link_short($device),
'time' => deviceUptime($device, 'short-3'),
'icon_tag' => '<i class="' . $config['entities']['device']['icon'] . '"></i>');
// Show Device Status
if ($options['devices']) {
$query = 'SELECT * FROM `devices`';
$query .= generate_where_clause('`status` = 0', $query_device_permitted);
$query .= 'ORDER BY `hostname` ASC';
foreach (dbFetchRows($query) as $device) {
$boxes[] = [
'sev' => 100,
'class' => 'Device',
'event' => 'Down',
'device_link' => generate_device_link_short($device),
'time' => device_uptime($device, 'short-3'),
'icon' => $config['entities']['device']['icon']
];
}
}
}
// Uptime
if ($options['uptime'])
{
if (filter_var($config['uptime_warning'], FILTER_VALIDATE_FLOAT) !== FALSE && $config['uptime_warning'] > 0)
{
$query = 'SELECT * FROM `devices` AS D ';
// Since reboot event more complicated than just device uptime less than some time
//$query .= ' WHERE D.`status` = 1 AND D.`uptime` > 0 AND D.`uptime` < ' . $config['uptime_warning'];
$query .= ' WHERE D.`status` = 1 AND D.`uptime` > 0 AND D.`last_rebooted` > ?';
$query .= $query_device_permitted;
$query .= 'ORDER BY D.`hostname` ASC';
$entries = dbFetchRows($query, array($config['time']['now'] - $config['uptime_warning'] - 10));
// Uptime
if ($options['uptime'] && $config['uptime_warning'] > 0 &&
filter_var($config['uptime_warning'], FILTER_VALIDATE_FLOAT) !== FALSE) {
$where_array = [ '`status` = 1', '`uptime` > 0' ];
$where_array[] = generate_query_values(get_time() - $config['uptime_warning'] - 10, 'last_rebooted', '>');
$query = 'SELECT * FROM `devices`';
$query .= generate_where_clause($where_array, $query_device_permitted);
$query .= 'ORDER BY `hostname` ASC';
foreach ($entries as $device)
{
$boxes[] = array('sev' => 10,
'class' => 'Device',
'event' => 'Rebooted',
'device_link' => generate_device_link_short($device),
'time' => deviceUptime($device, 'short-3'),
'location' => $device['location'],
'icon_tag' => '<i class="' . $config['entities']['device']['icon'] . '"></i>');
}
foreach (dbFetchRows($query) as $device) {
$boxes[] = [
'sev' => 10,
'class' => 'Device',
'event' => 'Rebooted',
'device_link' => generate_device_link_short($device),
'time' => device_uptime($device, 'short-3'),
'location' => $device['location'],
'icon' => $config['entities']['device']['icon']
];
}
}
}
// Ports Down
if ($options['ports'] || $options['neighbours'])
{
$options['neighbours'] = $options['neighbours'] && !$options['ports']; // Disable 'neighbours' if 'ports' already enabled
// Ports Down
if ($options['ports'] || $options['neighbours']) {
$query = 'SELECT * FROM `ports` AS I ';
if ($options['neighbours'])
{
$query .= 'INNER JOIN `neighbours` as L ON I.`port_id` = L.`port_id` ';
$options['neighbours'] = $options['neighbours'] && !$options['ports']; // Disable 'neighbours' if 'ports' already enabled
$query_port_permitted = generate_query_permitted([ 'port' ], [ 'port_table' => 'I', 'hide_ignored' => TRUE ]);
$query = 'SELECT * FROM `ports` AS I ';
if ($options['neighbours']) {
$query .= 'INNER JOIN `neighbours` as L ON I.`port_id` = L.`port_id` ';
}
$query .= 'LEFT JOIN `devices` AS D ON I.`device_id` = D.`device_id` ';
$where_array = [ 'D.`status` = 1', 'D.`ignore` = 0', 'I.`ignore` = 0', 'I.`deleted` = 0' ];
$where_array[] = generate_query_values('up', 'I.ifAdminStatus');
$where_array[] = generate_query_values([ 'down', 'lowerLayerDown' ], 'I.ifOperStatus');
if ($options['neighbours']) {
$where_array[] = 'L.`active` = 1';
}
$where_array[] = generate_query_values('DATE_SUB(NOW(), INTERVAL ' . $max_interval . ' HOUR)', 'I.ifLastChange', '>=');
$query .= generate_where_clause($where_array, $query_port_permitted);
if ($options['neighbours']) {
$query .= ' GROUP BY L.`port_id`'; // hrm.. this works?
}
$query .= ' ORDER BY I.`ifLastChange` DESC, D.`hostname` ASC, I.`ifDescr` * 1 ASC';
$i = 1;
foreach (dbFetchRows($query) as $port) {
if ($i > $max_count) {
// Limit to 200 ports on overview page
break;
}
//humanize_port($port);
$boxes[] = [
'sev' => 50,
'class' => 'Port',
'event' => 'Down',
'device_link' => generate_device_link_short($port),
'entity_link' => generate_port_link_short($port),
'time' => format_uptime(get_time() - strtotime($port['ifLastChange'])),
'location' => $device['location'],
'icon' => $config['entities']['port']['icon']
];
}
}
$query .= 'LEFT JOIN `devices` AS D ON I.`device_id` = D.`device_id` ';
$query .= "WHERE D.`status` = 1 AND D.ignore = 0 AND I.ignore = 0 AND I.deleted = 0 AND I.`ifAdminStatus` = 'up' AND (I.`ifOperStatus` = 'lowerLayerDown' OR I.`ifOperStatus` = 'down') ";
if ($options['neighbours'])
{
$query .= ' AND L.`active` = 1 ';
// Ports Errors (only deltas)
if ($options['errors']) {
foreach ($GLOBALS['cache']['ports']['errored'] as $port_id) {
if (in_array($port_id, $GLOBALS['cache']['ports']['ignored'])) {
continue;
} // Skip ignored ports
if (in_array($port['ifType'], $config['ports']['ignore_errors_iftype'])) {
continue;
} // Skip iftypes we ignore
$port = get_port_by_id($port_id);
$device = device_by_id_cache($port['device_id']);
humanize_port($port);
$port['text'] = [];
if ($port['ifInErrors_delta']) {
$port['text'][] = 'Rx: ' . format_number($port['ifInErrors_delta']) . ' (' . format_number($port['ifInErrors_rate']) . '/s)';
}
if ($port['ifOutErrors_delta']) {
$port['text'][] = 'Tx: ' . format_number($port['ifOutErrors_delta']) . ' (' . format_number($port['ifOutErrors_rate']) . '/s)';
}
$port['string'] = implode(', ', $port['text']);
if ($port['ifInErrors_rate'] > 1 || $port['ifOutErrors_rate'] > 1) {
$sev = 70;
} else {
$sev = 45;
}
$boxes[] = [
'sev' => $sev,
'class' => 'Port',
'event' => 'Errors',
'device_link' => generate_device_link_short($device),
'entity_link' => generate_port_link_short($port),
'time' => $port['string'],
'location' => $device['location'],
'icon' => $config['entities']['port']['icon']
];
}
}
$query .= $query_port_permitted;
$query .= ' AND I.`ifLastChange` >= DATE_SUB(NOW(), INTERVAL '.$max_interval.' HOUR) ';
if ($options['neighbours'])
{
$query .= 'GROUP BY L.`port_id` ';
// BGP
if ($options['bgp'] && isset($config['enable_bgp']) && $config['enable_bgp']) {
$where_array = [ '`status` = 1' ];
$where_array[] = generate_query_values([ 'start', 'running' ], 'bgpPeerAdminStatus');
$where_array[] = generate_query_values('established', 'bgpPeerState', '!=');
$query = 'SELECT * FROM `bgpPeers`';
$query .= ' LEFT JOIN `devices` USING(`device_id`)';
$query .= generate_where_clause($where_array, $query_device_permitted);
$query .= ' ORDER BY D.`hostname` ASC';
foreach (dbFetchRows($query) as $peer) {
humanize_bgp($peer);
if (isset($options['bgp_peer_name']) && $options['bgp_peer_name'] === "peer_dns" &&
!safe_empty($peer['reverse_dns'])) {
$peer_link = generate_entity_link("bgp_peer", $peer, short_hostname($peer['reverse_dns']));
} else {
$peer_link = generate_entity_link("bgp_peer", $peer, $peer['human_remoteip']);
}
$peer['wide'] = str_contains($peer['bgpPeerRemoteAddr'], ':');
$boxes[] = [
'sev' => 75,
'class' => 'BGP Session',
'event' => 'Down',
'device_link' => generate_device_link_short($peer),
'entity_link' => $peer_link,
'wide' => $peer['wide'],
'time' => format_uptime($peer['bgpPeerFsmEstablishedTime'], 'short-3'),
'location' => $device['location'],
'icon' => $config['entities']['bgp_peer']['icon']
];
}
}
$query .= 'ORDER BY I.`ifLastChange` DESC, D.`hostname` ASC, I.`ifDescr` * 1 ASC ';
$entries = dbFetchRows($query);
$i = 1;
foreach ($entries as $port)
{
if ($i > $max_count)
{
// Limit to 200 ports on overview page
break;
}
//humanize_port($port);
$boxes[] = array('sev' => 50,
'class' => 'Port',
'event' => 'Down',
'device_link' => generate_device_link_short($port),
'entity_link' => generate_port_link_short($port),
'time' => format_uptime($config['time']['now'] - strtotime($port['ifLastChange'])),
'location' => $device['location'],
'icon_tag' => '<i class="' . $config['entities']['port']['icon'] . '"></i>');
}
}
// Ports Errors (only deltas)
if ($options['errors'])
{
foreach ($GLOBALS['cache']['ports']['errored'] as $port_id)
{
if (in_array($port_id, $GLOBALS['cache']['ports']['ignored'])) { continue; } // Skip ignored ports
if (in_array($port['ifType'], $config['ports']['ignore_errors_iftype'])) { continue; } // Skip iftypes we ignore
$port = get_port_by_id($port_id);
$device = device_by_id_cache($port['device_id']);
humanize_port($port);
$port['text'] = [];
if ($port['ifInErrors_delta']) { $port['text'][] = 'Rx: ' . format_number($port['ifInErrors_delta']) . ' (' . format_number($port['ifInErrors_rate']) . '/s)'; }
if ($port['ifOutErrors_delta']) { $port['text'][] = 'Tx: ' . format_number($port['ifOutErrors_delta']) . ' (' . format_number($port['ifOutErrors_rate']) . '/s)'; }
$port['string'] = implode(', ', $port['text']);
if($port['ifInErrors_rate'] > 1 || $port['ifOutErrors_rate'] > 1) { $sev = 70; } else { $sev = 45; }
$boxes[] = array('sev' => $sev,
'class' => 'Port',
'event' => 'Errors',
'device_link' => generate_device_link_short($device),
'entity_link' => generate_port_link_short($port),
'time' => $port['string'],
'location' => $device['location'],
'icon_tag' => '<i class="' . $config['entities']['port']['icon'] . '"></i>');
}
}
// BGP
if ($options['bgp'])
{
if (isset($config['enable_bgp']) && $config['enable_bgp'])
{
$query = 'SELECT * FROM `bgpPeers` AS B ';
$query .= 'LEFT JOIN `devices` AS D ON B.`device_id` = D.`device_id` ';
//$query .= 'LEFT JOIN `bgpPeers-state` AS BS ON B.`bgpPeer_id` = BS.`bgpPeer_id` ';
$query .= "WHERE D.`status` = 1 AND (`bgpPeerAdminStatus` = 'start' OR `bgpPeerAdminStatus` = 'running') AND `bgpPeerState` != 'established' ";
$query .= $query_device_permitted;
$query .= 'ORDER BY D.`hostname` ASC';
$entries = dbFetchRows($query);
foreach ($entries as $peer)
{
humanize_bgp($peer);
$peer_ip = generate_entity_link("bgp_peer", $peer, $peer['human_remoteip']);
$peer['wide'] = str_contains($peer['bgpPeerRemoteAddr'], ':');
$boxes[] = array('sev' => 75,
'class' => 'BGP Session',
'event' => 'Down',
'device_link' => generate_device_link_short($peer),
'entity_link' => $peer_ip,
'wide' => $peer['wide'],
'time' => format_uptime($peer['bgpPeerFsmEstablishedTime'], 'short-3'),
'location' => $device['location'],
'icon_tag' => '<i class="' . $config['entities']['bgp_peer']['icon'] . '"></i>');
}
}
}
// Return boxes array
return $boxes;
// Return boxes array
return $boxes;
}
// EOF

File diff suppressed because it is too large Load Diff

View File

@ -6,64 +6,126 @@
*
* @package observium
* @subpackage web
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2022 Observium Limited
* @copyright (C) Adam Armstrong
*
*/
function get_vlans($vars) {
$vlans = [];
$query_permitted = generate_query_permitted_ng();
$query_permitted_ports = generate_query_permitted_ng([ 'device', 'port' ]);
$vls = dbFetchRows("SELECT * FROM `vlans`");
foreach ($vls as $vlan) {
if (safe_empty($vlan['vlan_name'])) {
// Empty vlan name
$vlan['vlan_name'] = 'Vlan ' . $vlan['vlan_vlan'];
// Known Vlans
$vlans = [];
foreach (dbFetchRows("SELECT * FROM `vlans`" . generate_where_clause($query_permitted)) as $vlan) {
if (safe_empty($vlan['vlan_name'])) {
// Empty vlan name
$vlan['vlan_name'] = 'Vlan ' . $vlan['vlan_vlan'];
}
$vlans[$vlan['vlan_vlan']]['names'][$vlan['vlan_name']]++;
$vlans[$vlan['vlan_vlan']]['devices'][$vlan['device_id']]++;
$vlans[$vlan['vlan_vlan']]['counts']['devices'] = 0;
$vlans[$vlan['vlan_vlan']]['counts']['ports_tagged'] = 0;
$vlans[$vlan['vlan_vlan']]['counts']['ports_untagged'] = 0;
}
$vlans[$vlan['vlan_vlan']]['names'][$vlan['vlan_name']]++;
$vlans[$vlan['vlan_vlan']]['counts']['devices'] = 0;
$vlans[$vlan['vlan_vlan']]['counts']['ports_tagged'] = 0;
$vlans[$vlan['vlan_vlan']]['counts']['ports_untagged'] = 0;
}
foreach ($vlans as $vlan => &$entry) {
$entry['counts']['devices'] = safe_count($entry['devices']);
}
//r($vlans);
$sql = 'SELECT `ifVlan`, COUNT(`ifVlan`) AS `count` FROM `ports` WHERE `deleted` != 1 GROUP BY `ifVlan`';
foreach (dbFetchRows($sql) as $otherport) {
if (safe_empty($otherport['ifVlan'])) {
continue;
// Untagged Vlans
$sql = 'SELECT `ifVlan`, COUNT(`ifVlan`) AS `count` FROM `ports` ' .
generate_where_clause('(`ifVlan` IS NOT NULL AND `ifVlan` != "") AND `deleted` != 1', $query_permitted_ports) . ' GROUP BY `ifVlan`';
foreach (dbFetchRows($sql) as $otherport) {
$vlans[$otherport['ifVlan']]['counts']['ports_untagged'] = $otherport['count'];
}
$vlans[$otherport['ifVlan']]['counts']['ports_untagged'] = $otherport['count'];
}
$dev_counts = dbFetchRows("SELECT `vlan_vlan`, COUNT(`vlan_vlan`) AS `count` FROM `vlans` GROUP BY `vlan_vlan`");
foreach ($dev_counts as $dev_count) {
$vlans[$dev_count['vlan_vlan']]['counts']['devices'] = $dev_count['count'];
}
$port_counts = dbFetchRows("SELECT `vlan`, COUNT(`vlan`) AS `count` FROM `ports_vlans` GROUP BY `vlan`");
foreach ($port_counts as $port_count) {
if (!isset($vlans[$port_count['vlan']])) {
print_error("Unknown VLAN ID '" . $port_count['vlan'] . "' with " . $port_count['count'] . " ports count.");
//print_debug("Unknown VLAN ID '".$port_count['vlan']."' with ".$port_count['count']." ports count.");
continue;
$sql = 'SELECT `vlan`, COUNT(`vlan`) AS `count` FROM `ports_vlans` '.generate_where_clause($query_permitted_ports).' GROUP BY `vlan`';
foreach (dbFetchRows($sql) as $port_count) {
if (!isset($vlans[$port_count['vlan']])) {
//print_error("Unknown VLAN ID '" . $port_count['vlan'] . "' with " . $port_count['count'] . " ports count.");
print_debug("Unknown VLAN ID '".$port_count['vlan']."' with ".$port_count['count']." ports count.");
continue;
}
$vlans[$port_count['vlan']]['counts']['ports_tagged'] = $port_count['count'];
}
$vlans[$port_count['vlan']]['counts']['ports_tagged'] = $port_count['count'];
}
$mac_counts = dbFetchRows("SELECT `vlan_id`, COUNT(DISTINCT(`mac_address`)) AS `count` FROM `vlans_fdb` GROUP BY `vlan_id`");
foreach ($mac_counts as $mac_count) {
if (!isset($vlans[$mac_count['vlan_id']])) {
//print_error("Unknown VLAN ID '".$mac_count['vlan_id']."' with ".$mac_count['count']." mac count.");
print_debug("Unknown VLAN ID '" . $mac_count['vlan_id'] . "' with " . $mac_count['count'] . " mac count.");
continue;
$sql = 'SELECT `vlan_id`, COUNT(DISTINCT(`mac_address`)) AS `count` FROM `vlans_fdb` ' .
generate_where_clause('`deleted` != 1', $query_permitted_ports) . ' GROUP BY `vlan_id`';
foreach (dbFetchRows($sql) as $mac_count) {
if (!isset($vlans[$mac_count['vlan_id']])) {
//print_error("Unknown VLAN ID '".$mac_count['vlan_id']."' with ".$mac_count['count']." mac count.");
print_debug("Unknown VLAN ID '" . $mac_count['vlan_id'] . "' with " . $mac_count['count'] . " mac count.");
continue;
}
$vlans[$mac_count['vlan_id']]['counts']['macs'] = $mac_count['count'];
}
$vlans[$mac_count['vlan_id']]['counts']['macs'] = $mac_count['count'];
}
ksort($vlans);
ksort($vlans);
return $vlans;
return $vlans;
}
function print_vlan_ports_row($device, $vlan, $vars) {
if (!is_numeric($vlan['vlan_vlan'])) {
return;
}
if (!isset($device['device_id']) && isset($vlan['device_id'])) {
$device = device_by_id_cache($vlan['device_id']);
}
$graph_type = isset($vars['graph']) ? 'port_' . $vars['graph'] : 'port_bits';
$filters = $vars['filters'] ?? [ 'deleted' => TRUE ];
echo('<tr>');
if (FALSE && $vars['view'] === "graphs" && $vars['graph'] === 'fdb_count') {
// FIXME. I not know, how to add this graph
echo('<td style="width: 100px;" class="entity-title"> Vlan ' . $vlan['vlan_vlan'] . PHP_EOL);
print_port_minigraph($vlan, 'vlan_fdbcount', 'twoday');
echo('</td>');
} else {
echo('<td style="width: 100px;" class="entity-title"> Vlan ' . $vlan['vlan_vlan'] . '</td>');
}
echo('<td style="width: 200px;" class="small">' . $vlan['vlan_name'] . '</td>');
echo('<td class="strong">');
$params = [ $device['device_id'], $vlan['vlan_vlan'] ];
$vlan_ports = [];
$sql = "SELECT * FROM `ports_vlans` LEFT JOIN `ports` USING(`device_id`, `port_id`)";
$sql .= generate_where_clause('`device_id` = ? AND `vlan` = ?' , build_ports_where_filter($device, $filters));
foreach (dbFetchRows($sql, $params) as $otherport) {
$vlan_ports[$otherport['ifIndex']] = $otherport;
}
$sql = "SELECT * FROM `ports`";
$sql .= generate_where_clause('`device_id` = ? AND `ifVlan` = ?' , build_ports_where_filter($device, $filters));
foreach (dbFetchRows($sql, $params) as $otherport) {
$vlan_ports[$otherport['ifIndex']] = array_merge($otherport, [ 'untagged' => '1' ]);
}
//r($vlan_ports);
ksort($vlan_ports);
$port_links = [];
foreach ($vlan_ports as $port) {
//humanize_port($port);
if ($vars['view'] === "graphs") {
print_port_minigraph($port, $graph_type, 'twoday');
continue;
}
$link = generate_port_link_short($port);
if ($port['untagged']) {
$link .= "(U)";
}
$port_links[] = $link;
}
echo implode(', ', $port_links);
echo('</td></tr>');
}
// EOF