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

@ -6,286 +6,249 @@
*
* @package observium
* @subpackage ajax
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2022 Observium Limited
* @copyright (C) Adam Armstrong
*
*/
$config['install_dir'] = "../..";
include_once("../../includes/observium.inc.php");
include_once("../../includes/sql-config.inc.php");
include($config['html_dir'] . "/includes/functions.inc.php");
include($config['html_dir'] . "/includes/authenticate.inc.php");
if (!$_SESSION['authenticated'])
{
print_json_status('failed', 'Unauthorized.');
exit();
if (!$_SESSION['authenticated']) {
print_json_status('failed', 'Unauthorized.');
exit();
}
$vars = get_vars([ 'JSON', 'POST' ]); // Got a JSON payload. Replace $var.
$readonly = $_SESSION['userlevel'] < 7;
$readonly = $_SESSION['userlevel'] < 7;
$limitwrite = $_SESSION['userlevel'] >= 9;
$readwrite = $_SESSION['userlevel'] >= 10;
switch ($vars['action']) {
case "theme":
$pref = 'web_theme_default';
if ($vars['value'] === 'reset') {
session_unset_var("theme");
if ($config['web_theme_default'] === 'system') {
// Override default
session_unset_var("theme_default");
}
case "theme":
$pref = 'web_theme_default';
if ($vars['value'] === 'reset') {
session_unset_var("theme");
if ($config['web_theme_default'] === 'system') {
// Override default
session_unset_var("theme_default");
}
if (del_user_pref($_SESSION['user_id'], $pref)) {
print_json_status('ok', 'Theme reset.');
}
} elseif (isset($config['themes'][$vars['value']]) || $vars['value'] === 'system') {
if (set_user_pref($_SESSION['user_id'], $pref, serialize($vars['value']))) {
print_json_status('ok', 'Theme set.');
}
} else {
print_json_status('failed', 'Invalid theme.');
}
break;
if (del_user_pref($_SESSION['user_id'], $pref)) {
print_json_status('ok', 'Theme reset.');
}
} elseif (isset($config['themes'][$vars['value']]) || $vars['value'] === 'system') {
if (set_user_pref($_SESSION['user_id'], $pref, serialize($vars['value']))) {
print_json_status('ok', 'Theme set.');
}
} else {
print_json_status('failed', 'Invalid theme.');
}
break;
case "big_graphs":
$pref = 'graphs|size';
if (set_user_pref($_SESSION['user_id'], $pref, serialize('big'))) {
print_json_status('ok', 'Big graphs set.');
session_unset_var("big_graphs"); // clear old
}
//session_set_var("big_graphs", TRUE);
//print_json_status('ok', 'Big graphs set.');
break;
case "big_graphs":
$pref = 'graphs|size';
if (set_user_pref($_SESSION['user_id'], $pref, serialize('big'))) {
print_json_status('ok', 'Big graphs set.');
session_unset_var("big_graphs"); // clear old
}
break;
case "normal_graphs":
$pref = 'graphs|size';
if (set_user_pref($_SESSION['user_id'], $pref, serialize('normal'))) {
print_json_status('ok', 'Normal graphs set.');
session_unset_var("big_graphs"); // clear old
}
//session_unset_var("big_graphs");
//print_json_status('ok', 'Small graphs set.');
break;
case "normal_graphs":
$pref = 'graphs|size';
if (set_user_pref($_SESSION['user_id'], $pref, serialize('normal'))) {
print_json_status('ok', 'Normal graphs set.');
session_unset_var("big_graphs"); // clear old
}
break;
case "touch_on":
session_set_var("touch", TRUE);
print_json_status('ok', 'Touch mode enabled.');
break;
case "touch_on":
session_set_var("touch", TRUE);
print_json_status('ok', 'Touch mode enabled.');
break;
case "touch_off":
session_unset_var("touch");
print_json_status('ok', 'Touch mode disabled.');
break;
case "touch_off":
session_unset_var("touch");
print_json_status('ok', 'Touch mode disabled.');
break;
case "set_refresh":
session_set_var("dark_mode", TRUE);
print_json_status('ok', 'Dark mode set.');
break;
case "save_grid": // Save current layout of dashboard grid
case "alert_assoc_edit":
// Currently edit allowed only for Admins
if ($readonly) {
print_json_status('failed', 'Action not allowed.');
exit();
}
// Currently edit allowed only for Admins
if (!$readwrite) {
print_json_status('failed', 'Action not allowed.');
exit();
}
foreach ($vars['grid'] as $w) {
dbUpdate(['x' => $w['x'], 'y' => $w['y'], 'width' => $w['width'], 'height' => $w['height'],], 'dash_widgets',
'`widget_id` = ?', [$w['id']]
);
}
break;
if (dbFetchRow("SELECT * FROM `alert_tests` WHERE `alert_test_id` = ?", array($vars['alert_test_id']))) {
case "add_widget": // Add widget of 'widget_type' to dashboard 'dash_id'
$rows_updated = dbUpdate([ 'alert_assoc' => $vars['alert_assoc'] ], 'alert_tests', '`alert_test_id` = ?', [ $vars['alert_test_id'] ]);
// Currently edit allowed only for Admins
if ($readonly) {
print_json_status('failed', 'Action not allowed.');
exit();
}
if ($rows_updated) {
update_alert_table($vars['alert_test_id']);
print_json_status('ok', '', [ 'id' => $vars['alert_test_id'],
'redirect' => generate_url([ 'page' => 'alert_check', 'alert_test_id' => $vars['alert_test_id'] ]) ]);
} else {
print_json_status('failed', 'Database was not updated.');
}
} else {
print_json_status('failed', 'Alert Checker does not exist: [' . $vars['alert_test_id'] . ']');
}
break;
if (isset($vars['dash_id']) && isset($vars['widget_type'])) {
$widget_id = dbInsert(['dash_id' => $vars['dash_id'], 'widget_config' => json_encode([]), 'widget_type' => $vars['widget_type']],
'dash_widgets'
);
}
case "save_grid": // Save current layout of dashboard grid
if ($widget_id) {
print_json_status('ok', '', ['id' => $widget_id]);
} else {
//print_r($vars); // For debugging
}
break;
// Currently edit allowed only for Admins
if ($readonly) {
print_json_status('failed', 'Action not allowed.');
exit();
}
case "delete_ap":
foreach ($vars['grid'] as $w) {
dbUpdate(array('x' => $w['x'], 'y' => $w['y'], 'width' => $w['width'], 'height' => $w['height'],), 'dash_widgets',
'`widget_id` = ?', array($w['id'])
);
}
break;
// Currently edit allowed only for Admins
if ($readonly) {
print_json_status('failed', 'Action not allowed.');
exit();
}
case "add_widget": // Add widget of 'widget_type' to dashboard 'dash_id'
if (is_numeric($vars['id'])) {
$rows_deleted = dbDelete('wifi_aps', '`wifi_ap_id` = ?', [$vars['id']]);
}
// Currently edit allowed only for Admins
if ($readonly) {
print_json_status('failed', 'Action not allowed.');
exit();
}
if ($rows_deleted) {
print_json_status('ok', 'AP Deleted', ['id' => $vars['id']]);
}
if (isset($vars['dash_id']) && isset($vars['widget_type'])) {
$widget_id = dbInsert(array('dash_id' => $vars['dash_id'], 'widget_config' => json_encode(array()), 'widget_type' => $vars['widget_type']),
'dash_widgets'
);
}
break;
if ($widget_id) {
print_json_status('ok', '', [ 'id' => $widget_id ]);
} else {
//print_r($vars); // For debugging
}
break;
case "del_widget":
case "delete_ap":
// Currently edit allowed only for Admins
if ($readonly) {
print_json_status('failed', 'Action not allowed.');
exit();
}
// Currently edit allowed only for Admins
if ($readonly) {
print_json_status('failed', 'Action not allowed.');
exit();
}
if (is_numeric($vars['widget_id'])) {
$rows_deleted = dbDelete('dash_widgets', '`widget_id` = ?', [$vars['widget_id']]);
}
if (is_numeric($vars['id'])) {
$rows_deleted = dbDelete('wifi_aps', '`wifi_ap_id` = ?', array($vars['id']));
}
if ($rows_deleted) {
print_json_status('ok', 'Widget Deleted.', ['id' => $vars['widget_id']]);
}
break;
if ($rows_deleted) {
print_json_status('ok', 'AP Deleted', [ 'id' => $vars['id'] ]);
}
case "dash_rename":
break;
// Currently edit allowed only for Admins
if ($readonly) {
print_json_status('failed', 'Action not allowed.');
exit();
}
case "del_widget":
if (is_numeric($vars['dash_id'])) {
$rows_updated = dbUpdate(['dash_name' => $vars['dash_name']], 'dashboards', '`dash_id` = ?', [$vars['dash_id']]);
} else {
print_json_status('failed', 'Invalid Dashboard ID.');
}
// Currently edit allowed only for Admins
if ($readonly) {
print_json_status('failed', 'Action not allowed.');
exit();
}
if ($rows_updated) {
print_json_status('ok', 'Dashboard Name Updated.', ['id' => $vars['dash_id']]);
} else {
print_json_status('failed', 'Update Failed.');
}
if (is_numeric($vars['widget_id'])) {
$rows_deleted = dbDelete('dash_widgets', '`widget_id` = ?', array($vars['widget_id']));
}
break;
if ($rows_deleted) {
print_json_status('ok', 'Widget Deleted.', [ 'id' => $vars['widget_id'] ]);
}
break;
case "dash_delete":
case "dash_rename":
// Currently edit allowed only for Admins
if ($readonly) {
print_json_status('failed', 'Action not allowed.');
exit();
}
// Currently edit allowed only for Admins
if ($readonly) {
print_json_status('failed', 'Action not allowed.');
exit();
}
if (is_numeric($vars['dash_id'])) {
$rows_deleted = dbDelete('dash_widgets', '`dash_id` = ?', [$vars['dash_id']]);
$rows_deleted += dbDelete('dashboards', '`dash_id` = ?', [$vars['dash_id']]);
} else {
print_json_status('failed', 'Invalid Dashboard ID.');
}
if (is_numeric($vars['dash_id'])) {
$rows_updated = dbUpdate(array('dash_name' => $vars['dash_name']), 'dashboards', '`dash_id` = ?', array($vars['dash_id']));
} else {
print_json_status('failed', 'Invalid Dashboard ID.');
}
if ($rows_deleted) {
print_json_status('ok', 'Dashboard Deleted.', ['id' => $vars['dash_id']]);
} else {
print_json_status('failed', 'Deletion Failed.');
}
if ($rows_updated) {
print_json_status('ok', 'Dashboard Name Updated.', [ 'id' => $vars['dash_id'] ]);
} else {
print_json_status('failed', 'Update Failed.');
}
break;
break;
case "update_widget_config":
case "dash_delete":
//print_r($vars);
// Currently edit allowed only for Admins
if ($readonly) {
print_json_status('failed', 'Action not allowed.');
exit();
}
// Currently edit allowed only for Admins
if ($readonly) {
print_json_status('failed', 'Action not allowed.');
exit();
}
if (is_numeric($vars['dash_id'])) {
$rows_deleted = dbDelete('dash_widgets', '`dash_id` = ?', array($vars['dash_id']));
$rows_deleted += dbDelete('dashboards', '`dash_id` = ?', array($vars['dash_id']));
} else {
print_json_status('failed', 'Invalid Dashboard ID.');
}
$widget = dbFetchRow("SELECT * FROM `dash_widgets` WHERE `widget_id` = ?", [$vars['widget_id']]);
$widget['widget_config'] = safe_json_decode($widget['widget_config']);
if ($rows_deleted) {
print_json_status('ok', 'Dashboard Deleted.', [ 'id' => $vars['dash_id'] ]);
} else {
print_json_status('failed', 'Deletion Failed.');
}
// Verify config value applies to this widget here
break;
$default_on = ['legend'];
case "update_widget_config":
if (isset($vars['config_field']) && isset($vars['config_value'])) {
if (empty($vars['config_value']) ||
(in_array($vars['config_field'], $default_on) && get_var_true($vars['config_value'])) ||
(!in_array($vars['config_field'], $default_on) && get_var_false($vars['config_value']))) {
// Just unset the value if it's empty or it's a default value.
unset($widget['widget_config'][$vars['config_field']]);
} else {
$widget['widget_config'][$vars['config_field']] = $vars['config_value'];
}
//print_r($vars);
dbUpdate(['widget_config' => json_encode($widget['widget_config'])], 'dash_widgets',
'`widget_id` = ?', [$widget['widget_id']]
);
// Currently edit allowed only for Admins
if ($readonly) {
print_json_status('failed', 'Action not allowed.');
exit();
}
//echo dbError();
$widget = dbFetchRow("SELECT * FROM `dash_widgets` WHERE `widget_id` = ?", array($vars['widget_id']));
$widget['widget_config'] = safe_json_decode($widget['widget_config']);
print_json_status('ok', 'Widget Updated.', ['id' => $widget['widget_id']]);
} else {
print_json_status('failed', 'Update Failed.');
}
// Verify config value applies to this widget here
break;
$default_on = [ 'legend' ];
default:
if (isset($vars['config_field']) && isset($vars['config_value'])) {
if ( empty($vars['config_value']) ||
(in_array($vars['config_field'], $default_on) && get_var_true($vars['config_value'])) ||
(!in_array($vars['config_field'], $default_on) && get_var_false($vars['config_value'])) ) {
// Just unset the value if it's empty or it's a default value.
unset($widget['widget_config'][$vars['config_field']]);
} else {
$widget['widget_config'][$vars['config_field']] = $vars['config_value'];
}
// Validate CSRF Token
//r($vars);
$json = '';
if (!str_contains_array($vars['action'], ['widget', 'dash', 'settings_user']) && // widget & dashboard currently not send request token
!request_token_valid($vars, $json)) {
$json = safe_json_decode($json);
$json['reload'] = TRUE;
print_json_status('failed', 'CSRF Token missing. Reload page.', $json);
exit();
}
unset($json);
dbUpdate(array('widget_config' => json_encode($widget['widget_config'])), 'dash_widgets',
'`widget_id` = ?', array($widget['widget_id'])
);
//echo dbError();
print_json_status('ok', 'Widget Updated.', [ 'id' => $widget['widget_id'] ]);
} else {
print_json_status('failed', 'Update Failed.');
}
break;
default:
// Validate CSRF Token
//r($vars);
$json = '';
if (!str_contains_array($vars['action'], [ 'widget', 'dash', 'settings_user' ]) && // widget & dashboard currently not send request token
!request_token_valid($vars, $json)) {
$json = safe_json_decode($json);
$json['reload'] = TRUE;
print_json_status('failed', 'CSRF Token missing. Reload page.', $json);
exit();
}
unset($json);
$action_path = __DIR__ . '/actions/'. $vars['action'] . '.inc.php';
if (is_alpha($vars['action']) && is_file($action_path))
{
include $action_path;
} else {
print_json_status('failed', 'Unknown action requested.');
}
$action_path = __DIR__ . '/actions/' . $vars['action'] . '.inc.php';
if (is_alpha($vars['action']) && is_file($action_path)) {
include $action_path;
} else {
print_json_status('failed', 'Unknown action requested.');
}
}
// EOF

View File

@ -0,0 +1,38 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage ajax
* @copyright (C) Adam Armstrong
*
*/
// Currently edit allowed only for Admins
if (!$limitwrite) {
print_json_status('failed', 'Action not allowed.');
exit();
}
if ($alert_test = dbFetchRow("SELECT * FROM `alert_tests` WHERE `alert_test_id` = ?", [ $vars['alert_test_id'] ])) {
if ($alert_test['alert_assoc'] !== $vars['alert_assoc']) {
if (dbUpdate([ 'alert_assoc' => $vars['alert_assoc'] ], 'alert_tests', '`alert_test_id` = ?', [ $vars['alert_test_id'] ])) {
update_alert_table($vars['alert_test_id']);
print_json_status('ok', 'Associations updated.',
[ 'id' => $vars['alert_test_id'],
'redirect' => generate_url([ 'page' => 'alert_check', 'alert_test_id' => $vars['alert_test_id'] ]) ]);
} else {
print_json_status('failed', 'Database was not updated.');
}
} else {
print_json_status('warning', 'Associations not changed.');
}
} else {
print_json_status('failed', 'Alert Checker does not exist: [' . $vars['alert_test_id'] . ']');
}
// EOF

View File

@ -5,64 +5,72 @@
* This file is part of Observium.
*
* @package observium
* @subpackage ajax
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2021 Observium Limited
* @subpackage web
* @copyright (C) Adam Armstrong
*
*/
// Currently allowed only for Admins
if (!$readwrite) {
print_json_status('failed', 'Action not allowed.');
return;
// Currently allowed only for Admins and Limit Write
if (!$limitwrite) {
print_json_status('failed', 'Action not allowed.');
return;
}
$ok = TRUE;
foreach (array('entity_type', 'alert_name', 'alert_severity', 'alert_conditions') as $var) {
if (!isset($vars[$var]) || strlen($vars[$var]) == '0') {
$ok = FALSE;
$failed[] = $var;
}
foreach ([ 'entity_type', 'alert_name', 'alert_severity', 'alert_conditions' ] as $var) {
if (safe_empty($vars[$var])) {
$ok = FALSE;
$failed[] = $var;
}
}
if ($ok) {
if (dbExist('alert_tests', '`entity_type` = ? AND `alert_name` = ?', [ $vars['entity_type'], $vars['alert_name'] ])) {
print_json_status('failed', "Alert Checker '{$vars['alert_name']}' already exist.");
return;
}
if (dbExist('alert_tests', '`entity_type` = ? AND `alert_name` = ?', [ $vars['entity_type'], $vars['alert_name'] ])) {
print_json_status('failed', "Alert Checker '{$vars['alert_name']}' already exist.");
return;
}
$check_array = array();
$check_array = [];
$conditions = array();
foreach (explode("\n", trim($vars['alert_conditions'])) as $cond) {
$condition = array();
list($condition['metric'], $condition['condition'], $condition['value']) = explode(" ", trim($cond), 3);
$conditions[] = $condition;
}
$check_array['conditions'] = safe_json_encode($conditions);
$check_array['alert_assoc'] = $vars['alert_assoc'];
$check_array['entity_type'] = $vars['entity_type'];
$check_array['alert_name'] = $vars['alert_name'];
$check_array['alert_message'] = $vars['alert_message'];
$check_array['severity'] = $vars['alert_severity'];
$check_array['suppress_recovery'] = get_var_true($vars['alert_send_recovery']) ? 0 : 1;
$check_array['alerter'] = NULL;
$check_array['and'] = $vars['alert_and'];
$check_array['delay'] = $vars['alert_delay'];
$check_array['enable'] = '1';
$conditions = [];
foreach (explode("\n", trim($vars['alert_conditions'])) as $cond) {
if (preg_match(OBS_PATTERN_XSS, $cond)) {
print_json_status('failed', "Prevent XSS payload.");
return;
}
$condition = [];
[ $condition['metric'], $condition['condition'], $condition['value'] ] = explode(" ", trim($cond), 3);
if (!is_alpha($condition['metric'])) {
print_json_status('failed', "Incorrect condition metric '" . escape_html($condition['metric']) . "'");
return;
}
$conditions[] = $condition;
}
$check_array['conditions'] = safe_json_encode($conditions);
$check_array['alert_assoc'] = $vars['alert_assoc'];
$check_array['entity_type'] = $vars['entity_type'];
$check_array['alert_name'] = $vars['alert_name'];
$check_array['alert_message'] = $vars['alert_message'];
$check_array['severity'] = $vars['alert_severity'];
$check_array['suppress_recovery'] = get_var_true($vars['alert_send_recovery']) ? 0 : 1;
$check_array['alerter'] = NULL;
$check_array['and'] = $vars['alert_and'];
$check_array['delay'] = $vars['alert_delay'];
$check_array['enable'] = '1';
$check_id = dbInsert('alert_tests', $check_array);
$check_id = dbInsert('alert_tests', $check_array);
if (is_numeric($check_id)) {
update_alert_table($check_id);
if (is_numeric($check_id)) {
update_alert_table($check_id);
print_json_status('ok', '', [ 'id' => $check_id, 'redirect' => generate_url([ 'page' => 'alert_check', 'alert_test_id' => $check_id ]) ]);
} else {
print_json_status('ok', '', ['id' => $check_id, 'redirect' => generate_url(['page' => 'alert_check', 'alert_test_id' => $check_id])]);
} else {
print_json_status('failed', 'Alert creation failed. Please note that the alert name <b>must</b> be unique.');
}
print_json_status('failed', 'Alert creation failed. Please note that the alert name <b>must</b> be unique.');
}
} else {
print_json_status('failed', 'Missing required data. (' . implode(", ", $failed) . ')');
print_json_status('failed', 'Missing required data. (' . implode(", ", $failed) . ')');
}
// EOF

View File

@ -0,0 +1,37 @@
<?php
if ($_SESSION['userlevel'] >= 8) {
if (is_intnum($vars['value'])) {
$alert_entry = get_alert_entry_by_id($vars['value']);
if(!count($alert_entry)) {
print_json_status('failed', 'Alert entry not found. No update performed.');
die;
}
$update_array = [];
if ($alert_entry['ignore_until_ok'] != 1) {
$update_array['ignore_until_ok'] = '1';
}
if ($alert_entry['alert_status'] == 0) {
$update_array['alert_status'] = '3';
}
if (count($update_array)) {
//r($alert_entry);
dbUpdate($update_array, 'alert_table', 'alert_table_id = ?', [$alert_entry['alert_table_id']]);
$alert_device = device_by_id_cache($alert_entry['device_id']);
//print_message("Alert entry [{$vars['form_alert_table_id']}] for device '{$alert_device['hostname']}' suppressed.");
print_json_status('ok', 'alert '.$vars['form_alert_table_id'].' ignored until ok. status updated.', ['update_array' => $update_array]);
}
unset($update_array);
// FIXME - eventlog? audit log?
}
} else {
print_json_status('failed', 'Action not permitted. Not performed.');
}

View File

@ -6,21 +6,23 @@
*
* @package observium
* @subpackage ajax
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2022 Observium Limited
* @copyright (C) Adam Armstrong
*
*/
if ($readonly) { return; } // Currently edit allowed only for 7+
if ($readonly) {
return;
} // Currently edit allowed only for 7+
$widget = dbFetchRow("SELECT * FROM `dash_widgets` WHERE `widget_id` = ?", [ $vars['widget_id'] ]);
$widget = dbFetchRow("SELECT * FROM `dash_widgets` WHERE `widget_id` = ?", [$vars['widget_id']]);
$widget['widget_config'] = safe_json_decode($widget['widget_config']);
switch ($widget['widget_type']) {
case "graph":
case "graph":
if (safe_count($widget['widget_config'])) {
if (safe_count($widget['widget_config'])) {
// echo '
// <form onsubmit="return false">
@ -28,121 +30,120 @@ switch ($widget['widget_type']) {
// </form>
// ';
//r($widget['widget_config']);
//r($widget['widget_config']);
//r(isset($widget['widget_config']['legend']) && $widget['widget_config']['legend'] === 'no');
//r(isset($widget['widget_config']['legend']) && $widget['widget_config']['legend'] === 'no');
$modal_args = [
'id' => 'modal-edit_widget_' . $widget['widget_id'],
'title' => 'Configure Widget',
//'hide' => TRUE,
//'fade' => TRUE,
//'role' => 'dialog',
//'class' => 'modal-md',
];
$modal_args = [
'id' => 'modal-edit_widget_' . $widget['widget_id'],
'title' => 'Configure Widget',
//'hide' => TRUE,
//'fade' => TRUE,
//'role' => 'dialog',
//'class' => 'modal-md',
];
$form = [
'form_only' => TRUE, // Do not add modal open/close divs (it's generated outside)
'type' => 'horizontal',
'id' => 'edit_widget_' . $widget['widget_id'],
'userlevel' => 7, // Minimum user level for display form
'modal_args' => $modal_args, // !!! This generate modal specific form
//'help' => 'This will completely delete the rule and all associations and history.',
'class' => '', // Clean default box class!
//'url' => generate_url([ 'page' => 'syslog_rules' ]),
'onsubmit' => "return false",
];
$form['fieldset']['body'] = [ 'class' => 'modal-body' ]; // Required this class for modal body!
$form['fieldset']['footer'] = [ 'class' => 'modal-footer' ]; // Required this class for modal footer!
$form = [
'form_only' => TRUE, // Do not add modal open/close divs (it's generated outside)
'type' => 'horizontal',
'id' => 'edit_widget_' . $widget['widget_id'],
'userlevel' => 7, // Minimum user level for display form
'modal_args' => $modal_args, // !!! This generate modal specific form
//'help' => 'This will completely delete the rule and all associations and history.',
'class' => '', // Clean default box class!
//'url' => generate_url([ 'page' => 'syslog_rules' ]),
'onsubmit' => "return false",
];
$form['fieldset']['body'] = ['class' => 'modal-body']; // Required this class for modal body!
$form['fieldset']['footer'] = ['class' => 'modal-footer']; // Required this class for modal footer!
$form['row'][1]['widget-config-title'] = [
'type' => 'text',
'fieldset' => 'body',
'name' => 'Title',
'placeholder' => 'Graph Title',
'class' => 'input-xlarge',
'attribs' => [
'data-id' => $widget['widget_id'],
'data-field' => 'title',
'data-type' => 'text'
],
'value' => $widget['widget_config']['title']
];
$form['row'][2]['widget-config-legend'] = [
'type' => 'checkbox',
'fieldset' => 'body',
'name' => 'Show Legend',
//'placeholder' => 'Yes, please delete this rule.',
//'onchange' => "javascript: toggleAttrib('disabled', 'delete_button_".$la['la_id']."'); showDiv(!this.checked, 'warning_".$la['la_id']."_div');",
'attribs' => [
'data-id' => $widget['widget_id'],
'data-field' => 'legend',
'data-type' => 'checkbox'
],
'value' => safe_empty($widget['widget_config']['legend']) ? 'yes' : $widget['widget_config']['legend'] //'legend'
];
$form['row'][1]['widget-config-title'] = [
'type' => 'text',
'fieldset' => 'body',
'name' => 'Title',
'placeholder' => 'Graph Title',
'class' => 'input-xlarge',
'attribs' => [
'data-id' => $widget['widget_id'],
'data-field' => 'title',
'data-type' => 'text'
],
'value' => $widget['widget_config']['title']
];
$form['row'][2]['widget-config-legend'] = [
'type' => 'checkbox',
'fieldset' => 'body',
'name' => 'Show Legend',
//'placeholder' => 'Yes, please delete this rule.',
//'onchange' => "javascript: toggleAttrib('disabled', 'delete_button_".$la['la_id']."'); showDiv(!this.checked, 'warning_".$la['la_id']."_div');",
'attribs' => [
'data-id' => $widget['widget_id'],
'data-field' => 'legend',
'data-type' => 'checkbox'
],
'value' => safe_empty($widget['widget_config']['legend']) ? 'yes' : $widget['widget_config']['legend'] //'legend'
];
$form['row'][8]['close'] = [
'type' => 'submit',
'fieldset' => 'footer',
'div_class' => '', // Clean default form-action class!
'name' => 'Close',
'icon' => '',
'attribs' => [
'data-dismiss' => 'modal',
'aria-hidden' => 'true'
]
];
$form['row'][8]['close'] = [
'type' => 'submit',
'fieldset' => 'footer',
'div_class' => '', // Clean default form-action class!
'name' => 'Close',
'icon' => '',
'attribs' => [
'data-dismiss' => 'modal',
'aria-hidden' => 'true'
]
];
echo generate_form_modal($form);
unset($form);
echo generate_form_modal($form);
unset($form);
/*
echo '
<form onsubmit="return false" class="form form-horizontal" style="margin-bottom: 0px;">
<fieldset>
<div id="purpose_div" class="control-group" style="margin-bottom: 10px;"> <!-- START row-1 -->
<label class="control-label" for="purpose">Title</label>
<div id="purpose_div" class="controls">
<input type="text" placeholder="Graph Title" name="widget-config-title" class="input" data-field="title" style="width: 100%;" value="'.$widget['widget_config']['title'].'" data-id="'.$widget['widget_id'].'">
</div>
</div>
/*
echo '
<form onsubmit="return false" class="form form-horizontal" style="margin-bottom: 0px;">
<fieldset>
<div id="purpose_div" class="control-group" style="margin-bottom: 10px;"> <!-- START row-1 -->
<label class="control-label" for="purpose">Title</label>
<div id="purpose_div" class="controls">
<input type="text" placeholder="Graph Title" name="widget-config-title" class="input" data-field="title" style="width: 100%;" value="'.$widget['widget_config']['title'].'" data-id="'.$widget['widget_id'].'">
</div>
</div>
<div id="ignore_div" class="control-group" style="margin-bottom: 10px;"> <!-- START row-6 -->
<label class="control-label" for="ignore">Show Legend</label>
<div id="ignore_div" class="controls">
<input type="checkbox" name="widget-config-legend" data-field="legend" data-type="checkbox" value="legend" '.(isset($widget['widget_config']['legend']) && $widget['widget_config']['legend'] === 'no' ? '' : 'checked').' data-id="'.$widget['widget_id'].'">
</div>
</div>
</fieldset> <!-- END fieldset-body -->
<div id="ignore_div" class="control-group" style="margin-bottom: 10px;"> <!-- START row-6 -->
<label class="control-label" for="ignore">Show Legend</label>
<div id="ignore_div" class="controls">
<input type="checkbox" name="widget-config-legend" data-field="legend" data-type="checkbox" value="legend" '.(isset($widget['widget_config']['legend']) && $widget['widget_config']['legend'] === 'no' ? '' : 'checked').' data-id="'.$widget['widget_id'].'">
</div>
</div>
</fieldset> <!-- END fieldset-body -->
<div class="modal-footer">
<fieldset>
<button id="close" name="close" type="submit" class="btn btn-default text-nowrap" value="" data-dismiss="modal" aria-hidden="true">Close</button>
<!-- <button id="action" name="action" type="submit" class="btn btn-primary text-nowrap" value="add_contact"><i style="margin-right: 0px;" class="icon-ok icon-white"></i>&nbsp;&nbsp;Add Contact</button> -->
</fieldset>
</div>
<div class="modal-footer">
<fieldset>
<button id="close" name="close" type="submit" class="btn btn-default text-nowrap" value="" data-dismiss="modal" aria-hidden="true">Close</button>
<!-- <button id="action" name="action" type="submit" class="btn btn-primary text-nowrap" value="add_contact"><i style="margin-right: 0px;" class="icon-ok icon-white"></i>&nbsp;&nbsp;Add Contact</button> -->
</fieldset>
</div>
</form>';
*/
</form>';
*/
} else {
} else {
print_message('To add a graph to this widget, navigate to the required graph and use the "Add To Dashboard" function on the graph page.');
print_message('To add a graph to this widget, navigate to the required graph and use the "Add To Dashboard" function on the graph page.');
echo '<h3>Step 1. Locate Graph and click for Graph Browser.</h3>';
echo '<img class="img img-thumbnail" src="images/doc/add_graph_1">';
echo '<h3>Step 1. Locate Graph and click for Graph Browser.</h3>';
echo '<img class="img img-thumbnail" src="images/doc/add_graph_1">';
echo '<h3>Step 2. Select Add to Dashboard in Graph Browser.</h3>';
echo '<img class="img" src="images/doc/add_graph_2">';
}
break;
default:
print_vars($widget);
echo '<h3>Step 2. Select Add to Dashboard in Graph Browser.</h3>';
echo '<img class="img" src="images/doc/add_graph_2">';
}
break;
default:
r($widget['widget_config']);
}
// EOF

View File

@ -4,9 +4,9 @@
*
* This file is part of Observium.
*
* @package observium
* @subpackage ajax
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2021 Observium Limited
* @package observium
* @subpackage ajax
* @copyright (C) Adam Armstrong
*
*/
@ -15,15 +15,14 @@ $update_ports = [];
//r($vars);
//$ports_attribs = get_device_entities_attribs($device_id, 'port'); // Get all attribs
foreach($vars['port'] as $port_id => $port_data)
{
foreach ($vars['port'] as $port_id => $port_data) {
if (is_entity_write_permitted('port', $port_id)) {
$port = get_port_by_id_cache($port_id);
$port = get_port_by_id_cache($port_id);
$device = device_by_id_cache($port['device_id']);
$updated = FALSE;
$update_array = array();
$updated = FALSE;
$update_array = [];
$port_attribs = get_entity_attribs('port', $port['port_id']);
@ -32,7 +31,7 @@ foreach($vars['port'] as $port_id => $port_data)
}
// Check ignored and disabled port
foreach (array('ignore', 'disabled') as $param) {
foreach (['ignore', 'disabled'] as $param) {
$old_param = $port[$param] ? 1 : 0;
$new_param = (isset($port_data[$param]) && $port_data[$param]) ? 1 : 0;
if ($old_param != $new_param) {
@ -41,7 +40,7 @@ foreach($vars['port'] as $port_id => $port_data)
}
if (count($update_array)) {
dbUpdate($update_array, 'ports', '`port_id` = ?', array($port_id));
dbUpdate($update_array, 'ports', '`port_id` = ?', [$port_id]);
$updated = TRUE;
}
@ -50,7 +49,7 @@ foreach($vars['port'] as $port_id => $port_data)
$old_ifSpeed_bool = isset($port['ifSpeed_custom']);
$new_ifSpeed_bool = isset($port_data['ifSpeed_custom_bool']) && $port_data['ifSpeed_custom_bool'];
if ($new_ifSpeed_bool) {
$port_data['ifSpeed_custom'] = (int) unit_string_to_numeric($port_data['ifSpeed_custom'], 1000);
$port_data['ifSpeed_custom'] = (int)unit_string_to_numeric($port_data['ifSpeed_custom'], 1000);
if ($port_data['ifSpeed_custom'] <= 0) {
// Wrong ifSpeed, skip
//print_warning("Passed incorrect value for port speed: ".unit_string_to_numeric($port_data['ifSpeed_custom'], 1000));
@ -65,7 +64,7 @@ foreach($vars['port'] as $port_id => $port_data)
//r($vars['ifSpeed_custom_' . $port_id]); r($port['ifSpeed_custom']);
set_entity_attrib('port', $port_id, 'ifSpeed_custom', $port_data['ifSpeed_custom'], $device['device_id']);
$update_array['ifSpeed_custom'] = $port_data['ifSpeed_custom'];
$updated = TRUE;
$updated = TRUE;
}
} elseif ($old_ifSpeed_bool !== $new_ifSpeed_bool) {
// Added or removed
@ -88,9 +87,9 @@ foreach($vars['port'] as $port_id => $port_data)
}
// Query updated sensors array
if ($rows_updated) {
print_json_status('ok', $rows_updated.' port(s) updated.', [ 'update_array' => $update_ports ]);
print_json_status('ok', $rows_updated . ' port(s) updated.', ['update_array' => $update_ports]);
} else {
print_json_status('failed', 'No update performed.');
print_json_status('failed', 'No update performed.');
}
unset($ports_attribs);

View File

@ -0,0 +1,35 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage web
* @copyright (C) Adam Armstrong
*
*/
// Currently, allowed only for Admins
if (!$readwrite) {
print_json_status('failed', 'Insufficient permissions to delete role.');
return;
}
$role_id = (int)$vars['role_id'];
if ($role_id > 0) {
$rows_deleted = dbDelete('roles', '`role_id` = ?', [$role_id]);
//$rows_deleted = 0;
if ($rows_deleted > 0) {
dbDelete('roles_entity_permissions', '`role_id` = ?', [$role_id]);
dbDelete('roles_permissions', '`role_id` = ?', [$role_id]);
dbDelete('roles_users', '`role_id` = ?', [$role_id]);
print_json_status('ok', 'Role deleted successfully.', ['reload' => TRUE]);
} else {
print_json_status('failed', 'Failed to delete role.');
}
} else {
print_json_status('failed', 'Invalid role ID.');
}
// EOF

View File

@ -4,96 +4,96 @@
*
* This file is part of Observium.
*
* @package observium
* @subpackage ajax
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2021 Observium Limited
* @package observium
* @subpackage ajax
* @copyright (C) Adam Armstrong
*
*/
$rows_updated = 0;
$rows_updated = 0;
$update_entities = [];
//r($vars);
foreach ($vars['sensors'] as $sensor_id => $sensor_update) {
$update_array = [];
if (is_entity_write_permitted('sensor', $sensor_id)) {
$update_array = [];
if (is_entity_write_permitted('sensor', $sensor_id)) {
$sensor = get_sensor_by_id($sensor_id);
$sensor = get_sensor_by_id($sensor_id);
$device_id = $sensor['device_id'];
$device_id = $sensor['device_id'];
if (!$sensor['sensor_state']) {
// Normal sensors
$fields_switch = [ 'sensor_ignore', 'sensor_custom_limit' ];
$fields_limit = [ 'sensor_limit', 'sensor_limit_warn', 'sensor_limit_low_warn', 'sensor_limit_low' ];
if (!$sensor['sensor_state']) {
// Normal sensors
$fields_switch = ['sensor_ignore', 'sensor_custom_limit'];
$fields_limit = ['sensor_limit', 'sensor_limit_warn', 'sensor_limit_low_warn', 'sensor_limit_low'];
} else {
// State sensors not allow edit limits
$fields_switch = array('sensor_ignore');
$fields_limit = array();
}
// Switch selectors
foreach ($fields_switch as $field) {
$sensor_update[$field] = get_var_true($sensor_update[$field]) ? '1' : '0';
if ($sensor_update[$field] != $sensor[$field]) {
$update_array[$field] = $sensor_update[$field];
}
}
// Limits
if ($sensor_update['sensor_reset_limit']) {
// Reset limits
if ($sensor['sensor_custom_limit']) {
$update_array['sensor_custom_limit'] = '0';
}
$update_array['sensor_limit_low'] = [ 'NULL' ];
$update_array['sensor_limit_low_warn'] = [ 'NULL' ];
$update_array['sensor_limit_warn'] = [ 'NULL' ];
$update_array['sensor_limit'] = [ 'NULL' ];
} elseif ($sensor_update['sensor_custom_limit']) {
foreach ($fields_limit as $field) {
$sensor_update[$field] = !is_numeric($sensor_update[$field]) ? [ 'NULL' ] : (float)$sensor_update[$field];
$sensor[$field] = !is_numeric($sensor[$field]) ? [ 'NULL' ] : (float)$sensor[$field];
if ($sensor_update[$field] !== $sensor[$field]) {
$update_array[$field] = $sensor_update[$field];
} else {
// State sensors not allow edit limits
$fields_switch = ['sensor_ignore'];
$fields_limit = [];
}
}
}
if (count($update_array)) {
dbUpdate($update_array, 'sensors', '`sensor_id` = ?', array($sensor['sensor_id']));
$msg = 'Sensor updated (custom): ' . $sensor['sensor_class'] . ' ' . $sensor['sensor_type'] . ' ' . $sensor['sensor_id'] . ' ' . escape_html($sensor['sensor_descr']) . ' ';
if ($update_array['sensor_limit_low']) {
$msg .= '[L: ' . $update_array['sensor_limit_low'] . ']';
}
if ($update_array['sensor_limit_low_warn']) {
$msg .= '[Lw: ' . $update_array['sensor_limit_low_warn'] . ']';
}
if ($update_array['sensor_limit_warn']) {
$msg .= '[Hw: ' . $update_array['sensor_limit_warn'] . ']';
}
if ($update_array['sensor_limit']) {
$msg .= '[H: ' . $update_array['sensor_limit'] . ']';
}
log_event($msg, $device_id, 'sensor', $sensor['sensor_id']);
$rows_updated++;
// Switch selectors
foreach ($fields_switch as $field) {
$sensor_update[$field] = get_var_true($sensor_update[$field]) ? '1' : '0';
if ($sensor_update[$field] != $sensor[$field]) {
$update_array[$field] = $sensor_update[$field];
}
}
$update_entities[$sensor_id] = $update_array;
}
// Limits
if ($sensor_update['sensor_reset_limit']) {
// Reset limits
if ($sensor['sensor_custom_limit']) {
$update_array['sensor_custom_limit'] = '0';
}
$update_array['sensor_limit_low'] = ['NULL'];
$update_array['sensor_limit_low_warn'] = ['NULL'];
$update_array['sensor_limit_warn'] = ['NULL'];
$update_array['sensor_limit'] = ['NULL'];
} elseif ($sensor_update['sensor_custom_limit']) {
foreach ($fields_limit as $field) {
$sensor_update[$field] = !is_numeric($sensor_update[$field]) ? ['NULL'] : (float)$sensor_update[$field];
$sensor[$field] = !is_numeric($sensor[$field]) ? ['NULL'] : (float)$sensor[$field];
if ($sensor_update[$field] !== $sensor[$field]) {
$update_array[$field] = $sensor_update[$field];
}
}
}
unset($update_array);
if (count($update_array)) {
dbUpdate($update_array, 'sensors', '`sensor_id` = ?', [$sensor['sensor_id']]);
$msg = 'Sensor updated (custom): ' . $sensor['sensor_class'] . ' ' . $sensor['sensor_type'] . ' ' . $sensor['sensor_id'] . ' ' . escape_html($sensor['sensor_descr']) . ' ';
if ($update_array['sensor_limit_low']) {
$msg .= '[L: ' . $update_array['sensor_limit_low'] . ']';
}
if ($update_array['sensor_limit_low_warn']) {
$msg .= '[Lw: ' . $update_array['sensor_limit_low_warn'] . ']';
}
if ($update_array['sensor_limit_warn']) {
$msg .= '[Hw: ' . $update_array['sensor_limit_warn'] . ']';
}
if ($update_array['sensor_limit']) {
$msg .= '[H: ' . $update_array['sensor_limit'] . ']';
}
log_event($msg, $device_id, 'sensor', $sensor['sensor_id']);
$rows_updated++;
} // End write permission check
$update_entities[$sensor_id] = $update_array;
}
unset($update_array);
} // End write permission check
} // end sensors loop
// Query updated sensors array
if ($rows_updated) {
print_json_status('ok', $rows_updated.' sensor(s) updated.', [ 'update_array' => $update_entities ]);
print_json_status('ok', $rows_updated . ' sensor(s) updated.', ['update_array' => $update_entities]);
} else {
print_json_status('failed', 'No update performed.');
print_json_status('failed', 'No update performed.');
}
// 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,46 +14,46 @@
// Allowed only for authenticated
if (!$_SESSION['authenticated'] || $_SESSION['user_id'] != $vars['user_id']) {
print_json_status('failed', "Unauthenticated");
//print_json_status('failed', var_export($vars, TRUE));
return;
print_json_status('failed', "Unauthenticated");
//print_json_status('failed', var_export($vars, TRUE));
return;
}
$user_id = $_SESSION['user_id'];
foreach (process_sql_vars($vars) as $param => $entry) {
// This sets:
// $deletes = array();
// $sets = array();
// $errors = array();
// $set_attribs = array(); // set obs_attribs
$$param = $entry;
// This sets:
// $deletes = array();
// $sets = array();
// $errors = array();
// $set_attribs = array(); // set obs_attribs
$$param = $entry;
}
$updates = 0;
// Set fields that were submitted with custom value
if (safe_count($sets)) {
$query = 'SELECT * FROM `users_prefs` WHERE `user_id` = ?' . generate_query_values_and(array_keys($sets), 'pref');
// Fetch current rows in config file so we know which one to UPDATE and which one to INSERT
$in_db = [];
foreach (dbFetchRows($query, [ $user_id ]) as $row) {
$in_db[$row['pref']] = $row['value'];
}
foreach ($sets as $key => $value) {
$serialize = serialize($value);
if (!isset($in_db[$key]) || $serialize !== $in_db[$key]) {
set_user_pref($user_id, $key, $serialize);
$updates++;
$query = 'SELECT * FROM `users_prefs` WHERE `user_id` = ?' . generate_query_values_and(array_keys($sets), 'pref');
// Fetch current rows in config file so we know which one to UPDATE and which one to INSERT
$in_db = [];
foreach (dbFetchRows($query, [$user_id]) as $row) {
$in_db[$row['pref']] = $row['value'];
}
foreach ($sets as $key => $value) {
$serialize = serialize($value);
if (!isset($in_db[$key]) || $serialize !== $in_db[$key]) {
set_user_pref($user_id, $key, $serialize);
$updates++;
}
}
}
}
// Delete fields that were reset to default
if (safe_count($deletes)) {
dbDelete('users_prefs', '`user_id` = ? ' . generate_query_values_and($deletes, 'pref'), [ $user_id ]);
$updates++;
dbDelete('users_prefs', '`user_id` = ? ' . generate_query_values_and($deletes, 'pref'), [$user_id]);
$updates++;
}
/*
@ -64,19 +64,19 @@ foreach ($set_attribs as $attrib => $value) {
}
*/
if ($updates) {
$status = 'ok';
$message = "Settings updated. Please note Web UI setting takes effect only after reload the page.";
$status = 'ok';
$message = "Settings updated. Please note Web UI setting takes effect only after reload the page.";
if (safe_count($errors)) {
$status = 'warning';
$message .= ' Errors: ' . implode('; ', $errors) . '.';
}
print_json_status($status, $message, [ 'reload' => TRUE ]);
if (safe_count($errors)) {
$status = 'warning';
$message .= ' Errors: ' . implode('; ', $errors) . '.';
}
print_json_status($status, $message, ['reload' => TRUE]);
} elseif (safe_count($errors)) {
$status = 'failed';
$message = 'Errors: ' . implode('; ', $errors) . '.';
print_json_status($status, $message);
$status = 'failed';
$message = 'Errors: ' . implode('; ', $errors) . '.';
print_json_status($status, $message);
}
//process_sql_vars($vars);

View File

@ -4,63 +4,63 @@
*
* 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
*
*/
switch (str_replace('->', '|', $vars['setting'])) {
case "theme":
case "web_theme_default":
$pref = 'web_theme_default';
if ($vars['value'] === 'reset') {
session_unset_var("theme");
if ($config['web_theme_default'] === 'system') {
// Override default
session_unset_var("theme_default");
}
case "theme":
case "web_theme_default":
$pref = 'web_theme_default';
if ($vars['value'] === 'reset') {
session_unset_var("theme");
if ($config['web_theme_default'] === 'system') {
// Override default
session_unset_var("theme_default");
}
if (del_user_pref($_SESSION['user_id'], $pref)) {
print_json_status('ok', 'Theme reset.');
}
} elseif (isset($config['themes'][$vars['value']]) || $vars['value'] === 'system') {
if (set_user_pref($_SESSION['user_id'], $pref, serialize($vars['value']))) {
print_json_status('ok', 'Theme set.');
}
} else {
print_json_status('failed', 'Invalid theme.');
}
break;
if (del_user_pref($_SESSION['user_id'], $pref)) {
print_json_status('ok', 'Theme reset.');
}
} elseif (isset($config['themes'][$vars['value']]) || $vars['value'] === 'system') {
if (set_user_pref($_SESSION['user_id'], $pref, serialize($vars['value']))) {
print_json_status('ok', 'Theme set.');
}
} else {
print_json_status('failed', 'Invalid theme.');
}
break;
case "big_graphs":
$pref = 'graphs|size';
if (set_user_pref($_SESSION['user_id'], $pref, serialize('big'))) {
print_json_status('ok', 'Big graphs set.');
session_unset_var("big_graphs"); // clear old
}
//session_set_var("big_graphs", TRUE);
//print_json_status('ok', 'Big graphs set.');
break;
case "big_graphs":
$pref = 'graphs|size';
if (set_user_pref($_SESSION['user_id'], $pref, serialize('big'))) {
print_json_status('ok', 'Big graphs set.');
session_unset_var("big_graphs"); // clear old
}
//session_set_var("big_graphs", TRUE);
//print_json_status('ok', 'Big graphs set.');
break;
case "normal_graphs":
$pref = 'graphs|size';
if (set_user_pref($_SESSION['user_id'], $pref, serialize('normal'))) {
print_json_status('ok', 'Normal graphs set.');
session_unset_var("big_graphs"); // clear old
}
//session_unset_var("big_graphs");
//print_json_status('ok', 'Small graphs set.');
break;
case "normal_graphs":
$pref = 'graphs|size';
if (set_user_pref($_SESSION['user_id'], $pref, serialize('normal'))) {
print_json_status('ok', 'Normal graphs set.');
session_unset_var("big_graphs"); // clear old
}
//session_unset_var("big_graphs");
//print_json_status('ok', 'Small graphs set.');
break;
case "sensors|web_measured_compact":
// BOOL values
$pref = $vars['setting'];
if (set_user_pref($_SESSION['user_id'], $pref, serialize(get_var_true($vars['value'])))) {
print_json_status('ok', 'Setting was set.', [ 'reload' => TRUE ]);
}
break;
case "sensors|web_measured_compact":
// BOOL values
$pref = $vars['setting'];
if (set_user_pref($_SESSION['user_id'], $pref, serialize(get_var_true($vars['value'])))) {
print_json_status('ok', 'Setting was set.', ['reload' => TRUE]);
}
break;
}
// EOF

View File

@ -4,55 +4,55 @@
*
* This file is part of Observium.
*
* @package observium
* @subpackage ajax
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2021 Observium Limited
* @package observium
* @subpackage ajax
* @copyright (C) Adam Armstrong
*
*/
$rows_updated = 0;
$rows_updated = 0;
$update_entities = [];
//r($vars);
foreach ($vars['status'] as $status_id => $status_update) {
$update_array = [];
if(is_entity_write_permitted('status', $status_id)) {
$status = get_status_by_id($status_id);
$update_array = [];
if (is_entity_write_permitted('status', $status_id)) {
$status = get_status_by_id($status_id);
$device_id = $status['device_id'];
$device_id = $status['device_id'];
$fields_switch = array('status_ignore');
$fields_limit = array();
$fields_switch = ['status_ignore'];
$fields_limit = [];
// Switch selectors
foreach ($fields_switch as $field) {
$status_update[$field] = get_var_true($status_update[$field]) ? '1' : '0';
if ($status_update[$field] != $status[$field]) {
$update_array[$field] = $status_update[$field];
}
}
// Switch selectors
foreach ($fields_switch as $field) {
$status_update[$field] = get_var_true($status_update[$field]) ? '1' : '0';
if ($status_update[$field] != $status[$field]) {
$update_array[$field] = $status_update[$field];
}
}
if (count($update_array)) {
dbUpdate($update_array, 'status', '`status_id` = ?', array($status['status_id']));
$msg = 'Status updated (custom): ' . $status['status_type'] . ' ' . $status['status_id'] . ' ' . escape_html($status['status_descr']) . ' ';
log_event($msg, $device_id, 'status', $status['status_id']);
$rows_updated++;
if (count($update_array)) {
dbUpdate($update_array, 'status', '`status_id` = ?', [$status['status_id']]);
$msg = 'Status updated (custom): ' . $status['status_type'] . ' ' . $status['status_id'] . ' ' . escape_html($status['status_descr']) . ' ';
log_event($msg, $device_id, 'status', $status['status_id']);
$rows_updated++;
$update_entities[$status_id] = $update_array;
}
$update_entities[$status_id] = $update_array;
}
unset($update_array);
unset($update_array);
} // End write permission check
} // End write permission check
} // end entity loop
// Query updated array
if ($rows_updated) {
print_json_status('ok', $rows_updated.' status(es) updated.', [ 'update_array' => $update_entities ]);
print_json_status('ok', $rows_updated . ' status(es) updated.', ['update_array' => $update_entities]);
} else {
print_json_status('failed', 'No update performed.');
print_json_status('failed', 'No update performed.');
}
// EOF

View File

@ -1,5 +1,4 @@
<?php
/**
* Observium
*
@ -7,55 +6,48 @@
*
* @package observium
* @subpackage ajax
* @author Adam Armstrong <adama@observium.org>
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2019 Observium Limited
* @copyright (C) Adam Armstrong
*
*/
$config['install_dir'] = "../..";
include_once("../../includes/observium.inc.php");
include_once("../../includes/sql-config.inc.php");
include($config['html_dir'] . "/includes/functions.inc.php");
include($config['html_dir'] . "/includes/authenticate.inc.php");
if (!$_SESSION['authenticated']) { echo("unauthenticated"); exit; }
if (!$_SESSION['authenticated']) {
echo("unauthenticated");
exit;
}
if ($_SESSION['userlevel'] >= '5')
{
if ($_SESSION['userlevel'] >= '5') {
switch ($_GET['entity_type'])
{
switch ($_GET['entity_type']) {
case "sensor":
foreach (dbFetch("SELECT * FROM `sensors` WHERE device_id = ?", array($_GET['device_id'])) as $sensor)
{
if(is_entity_permitted($sensor, 'sensor'))
{
$string = addslashes($sensor['sensor_descr']);
echo("obj.options[obj.options.length] = new Option('".$string."','".$sensor['sensor_id']."');\n");
}
}
break;
case "sensor":
foreach (dbFetchRows("SELECT * FROM `sensors` WHERE device_id = ?", [$_GET['device_id']]) as $sensor) {
if (is_entity_permitted($sensor, 'sensor')) {
$string = addslashes($sensor['sensor_descr']);
echo("obj.options[obj.options.length] = new Option('" . $string . "','" . $sensor['sensor_id'] . "');\n");
}
}
break;
case "netscalervsvr":
foreach (dbFetch("SELECT * FROM `netscaler_vservers` WHERE `device_id` = ?", array($_GET['device_id'])) as $entity)
{
$string = addslashes($entity['vsvr_label']);
echo("obj.options[obj.options.length] = new Option('".$string."','".$entity['vsvr_id']."');\n");
}
break;
case "netscalervsvr":
foreach (dbFetchRows("SELECT * FROM `netscaler_vservers` WHERE `device_id` = ?", [$_GET['device_id']]) as $entity) {
$string = addslashes($entity['vsvr_label']);
echo("obj.options[obj.options.length] = new Option('" . $string . "','" . $entity['vsvr_id'] . "');\n");
}
break;
case "port":
foreach (dbFetch("SELECT * FROM `ports` WHERE `device_id` = ? AND `deleted` = '0'", array($_GET['device_id'])) as $port)
{
$string = addslashes($port['port_label_short']." - ".$port['ifAlias']);
echo("obj.options[obj.options.length] = new Option('".$string."','".$port['port_id']."');\n");
}
break;
}
case "port":
foreach (dbFetchRows("SELECT * FROM `ports` WHERE `device_id` = ? AND `deleted` = '0'", [$_GET['device_id']]) as $port) {
$string = addslashes($port['port_label_short'] . " - " . $port['ifAlias']);
echo("obj.options[obj.options.length] = new Option('" . $string . "','" . $port['port_id'] . "');\n");
}
break;
}
}
?>
// EOF

View File

@ -5,42 +5,38 @@
*
* This file is part of Observium.
*
* @package observium
* @subpackage ajax
* @author Adam Armstrong <adama@observium.org>
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2019 Observium Limited
* @package observium
* @subpackage ajax
* @author Adam Armstrong <adama@observium.org>
* @copyright (C) Adam Armstrong
*
*/
$config['install_dir'] = "../..";
include_once("../../includes/observium.inc.php");
include_once("../../includes/sql-config.inc.php");
include($config['html_dir'] . "/includes/functions.inc.php");
include($config['html_dir'] . "/includes/authenticate.inc.php");
if (!$_SESSION['authenticated']) { echo("unauthenticated"); exit; }
if (!$_SESSION['authenticated']) {
echo("unauthenticated");
exit;
}
if (is_numeric($_GET['device_id']) && device_permitted($_GET['device_id']))
{
foreach (dbFetchRows("SELECT `port_id`,`port_label_short`,`ifAlias`,`ifDescr`,`ifName` FROM `ports` WHERE `device_id` = ? AND deleted = 0 ORDER BY ifIndex", array($_GET['device_id'])) as $interface)
{
$descr = array();
if (empty($interface['port_label_short']))
{
$device = device_by_id_cache($interface['port_id']);
process_port_label($interface, $device);
}
$descr[] = $interface['port_label_short'];
if (is_numeric($_GET['device_id']) && device_permitted($_GET['device_id'])) {
foreach (dbFetchRows("SELECT `port_id`,`port_label_short`,`ifAlias`,`ifDescr`,`ifName` FROM `ports` WHERE `device_id` = ? AND deleted = 0 ORDER BY ifIndex", [$_GET['device_id']]) as $interface) {
$descr = [];
if (empty($interface['port_label_short'])) {
$device = device_by_id_cache($interface['port_id']);
process_port_label($interface, $device);
}
$descr[] = $interface['port_label_short'];
if ($interface['ifAlias'])
{
// second part
$descr[] = $interface['ifAlias'];
if ($interface['ifAlias']) {
// second part
$descr[] = $interface['ifAlias'];
}
$string = addslashes(implode(" - ", $descr));
echo("obj.options[obj.options.length] = new Option('" . $string . "','" . $interface['port_id'] . "');\n");
}
$string = addslashes(implode(" - ", $descr));
echo("obj.options[obj.options.length] = new Option('".$string."','".$interface['port_id']."');\n");
}
}
// EOF

View File

@ -5,55 +5,53 @@
*
* This file is part of Observium.
*
* @package observium
* @subpackage ajax
* @author Adam Armstrong <adama@observium.org>
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2019 Observium Limited
* @package observium
* @subpackage ajax
* @author Adam Armstrong <adama@observium.org>
* @copyright (C) Adam Armstrong
*
*/
$config['install_dir'] = "../..";
include_once("../../includes/observium.inc.php");
include_once("../../includes/sql-config.inc.php");
include($config['html_dir'] . "/includes/functions.inc.php");
include($config['html_dir'] . "/includes/authenticate.inc.php");
if (!$_SESSION['authenticated']) { echo("unauthenticated"); exit; }
if (!$_SESSION['authenticated']) {
echo("unauthenticated");
exit;
}
$result = array();
$result = [];
if ($_SESSION['userlevel'] >= '5')
{
if ($_SESSION['userlevel'] >= '5') {
switch ($_GET['entity_type'])
{
switch ($_GET['entity_type']) {
case "port":
case "port":
$where_array = build_ports_where_array($GLOBALS['vars']);
$where_array = build_ports_where_array($GLOBALS['vars']);
$where = ' WHERE 1 ';
$where .= implode('', $where_array);
$where = ' WHERE 1 ';
$where .= implode('', $where_array);
$query = 'SELECT *, `ports`.`port_id` AS `port_id` FROM `ports`';
//$query .= ' LEFT JOIN `ports-state` AS S ON `ports`.`port_id` = S.`port_id`';
$query .= $where;
$query = 'SELECT *, `ports`.`port_id` AS `port_id` FROM `ports`';
//$query .= ' LEFT JOIN `ports-state` AS S ON `ports`.`port_id` = S.`port_id`';
$query .= $where;
$ports_db = dbFetchRows($query, $param);
port_permitted_array($ports_db);
$ports_db = dbFetchRows($query, $param);
port_permitted_array($ports_db);
foreach ($ports_db as $port) {
humanize_port($port);
$device = device_by_id_cache($port['device_id']);
array_push($result, [ intval($port['port_id']), $device['hostname'], $port['port_label'], $port['ifAlias'], $port['ifOperStatus'] == 'up' ? 'up' : 'down' ]);
}
break;
foreach ($ports_db as $port) {
humanize_port($port);
$device = device_by_id_cache($port['device_id']);
array_push($result, [intval($port['port_id']), $device['hostname'], $port['port_label'], $port['ifAlias'], $port['ifOperStatus'] == 'up' ? 'up' : 'down']);
}
break;
}
}
header('Content-Type: application/json');
print json_encode($result, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
header('Content-Type: application/json');
print json_encode($result, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
}

View File

@ -6,18 +6,18 @@
*
* @package observium
* @subpackage web
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2021 Observium Limited
* @copyright (C) Adam Armstrong
*
*/
$config['install_dir'] = "../..";
require_once("../../includes/observium.inc.php");
require_once($config['install_dir']."/includes/sql-config.inc.php");
include($config['html_dir'] . "/includes/functions.inc.php");
include($config['html_dir'] . "/includes/authenticate.inc.php");
if (!$_SESSION['authenticated']) { print_error('Session expired, please log in again!'); exit; }
if (!$_SESSION['authenticated']) {
print_error('Session expired, please log in again!');
exit;
}
ob_start();
@ -25,288 +25,268 @@ $vars = get_vars([ 'JSON', 'POST', 'GET' ]);
$vars['page'] = "popup";
if(isset($vars['debug'])) { r($vars); }
if (isset($vars['debug'])) {
r($vars);
}
switch ($vars['entity_type']) {
case "port":
if (is_numeric($vars['entity_id']) && (port_permitted($vars['entity_id']))) {
$port = get_port_by_id($vars['entity_id']);
echo generate_port_popup($port);
} else {
print_warning("You are not permitted to view this port.");
}
break;
case "port":
if (is_numeric($vars['entity_id']) && (port_permitted($vars['entity_id']))) {
$port = get_port_by_id($vars['entity_id']);
echo generate_port_popup($port);
} else {
print_warning("You are not permitted to view this port.");
}
break;
case "link":
if (is_numeric($vars['entity_id_a']) && (port_permitted($vars['entity_id_a']))) {
$port = get_port_by_id($vars['entity_id_a']);
echo generate_port_popup($port);
} else {
print_warning("You are not permitted to view this port.");
}
if (is_numeric($vars['entity_id_b']) && (port_permitted($vars['entity_id_b']))) {
$port = get_port_by_id($vars['entity_id_b']);
echo generate_port_popup($port, '','none'); // suppress graph for b side of link
} else {
print_warning("You are not permitted to view this port.");
}
break;
case "device":
if (is_numeric($vars['entity_id']) && device_permitted($vars['entity_id'])) {
$device = device_by_id_cache($vars['entity_id']);
echo generate_device_popup($device, $vars);
} else {
print_warning("You are not permitted to view this device.");
}
break;
case "group":
if (is_numeric($vars['entity_id']) && $_SESSION['userlevel'] >= 5) {
$group = get_group_by_id($vars['entity_id']);
echo generate_group_popup_header($group, array());
} else {
print_warning("You are not permitted to view this group.");
}
break;
case "mac":
if (preg_match('/^' . OBS_PATTERN_MAC . '$/i', $vars['entity_id'])) {
$mac = format_mac($vars['entity_id']);
// Other way by using Pear::Net_MAC, see here: http://pear.php.net/manual/en/package.networking.net-mac.importvendors.php
$url = 'https://api.macvendors.com/' . urlencode($mac);
$response = get_http_request($url);
if ($response) {
echo 'MAC vendor: ' . $response;
} else {
echo 'Not Found';
}
} else {
echo 'Not correct MAC address';
}
break;
case "ip":
list($ip) = explode('/', $vars['entity_id']);
if ($ip_version = get_ip_version($ip)) {
$cache_key = 'response_' . $vars['entity_type'] . '_' . $ip;
$cache_entry = get_cache_session($cache_key);
//r($cache_entry);
if (ishit_cache_session()) {
//echo '<h2>CACHED!</h2>';
echo $cache_entry;
exit;
}
$response = '';
$reverse_dns = gethostbyaddr6($ip);
if ($reverse_dns) {
$response .= '<h4>' . $reverse_dns . '</h4><hr />' . PHP_EOL;
}
// WHOIS
if (!isset($config['http_proxy']) && is_executable($config['whois'])) {
// Use direct whois cmd query (preferred)
// NOTE, for now not tested and not supported for KRNIC, ie: 202.30.50.0, 2001:02B8:00A2::
$cmd = $config['whois'] . ' ' . $ip;
$whois = external_exec($cmd);
$multi_whois = explode('# start', $whois); // Some time whois return multiple (ie: whois 8.8.8.8), than use last
if (safe_count($multi_whois) > 1) {
$whois = array_pop($multi_whois);
case "link":
if (is_numeric($vars['entity_id_a']) && (port_permitted($vars['entity_id_a']))) {
$port = get_port_by_id($vars['entity_id_a']);
echo generate_port_popup($port);
} else {
print_warning("You are not permitted to view this port.");
}
$org = 0;
foreach (explode("\n", $whois) as $line) {
if (preg_match('/^(\w[\w\s\-\/]+):.*$/', $line, $matches)) {
if (in_array($matches[1], [ 'Ref', 'source', 'nic-hdl-br' ])) {
if ($org === 1) {
$response .= PHP_EOL;
$org++;
if (is_numeric($vars['entity_id_b']) && (port_permitted($vars['entity_id_b']))) {
$port = get_port_by_id($vars['entity_id_b']);
echo generate_port_popup($port, '', 'none'); // suppress graph for b side of link
} else {
print_warning("You are not permitted to view this port.");
}
break;
case "device":
if (is_numeric($vars['entity_id']) && device_permitted($vars['entity_id'])) {
$device = device_by_id_cache($vars['entity_id']);
echo generate_device_popup($device, $vars);
} else {
print_warning("You are not permitted to view this device.");
}
break;
case "group":
if (is_numeric($vars['entity_id']) && $_SESSION['userlevel'] >= 5) {
$group = get_group_by_id($vars['entity_id']);
echo generate_group_popup_header($group);
} else {
print_warning("You are not permitted to view this group.");
}
break;
case "mac":
if (preg_match('/^' . OBS_PATTERN_MAC . '$/i', $vars['entity_id'])) {
// Other way by using Pear::Net_MAC, see here: http://pear.php.net/manual/en/package.networking.net-mac.importvendors.php
if ($response = get_http_def('macvendors_mac', [ 'mac' => format_mac($vars['entity_id']) ])) {
echo 'MAC vendor: ' . escape_html($response);
} else {
echo 'Not Found';
}
} else {
echo 'Not correct MAC address';
}
break;
case "ip":
$ip = explode('/', $vars['entity_id'])[0];
if ($ip_version = get_ip_version($ip)) {
$cache_key = 'response_' . $vars['entity_type'] . '_' . $ip;
$cache_entry = get_cache_session($cache_key);
//r($cache_entry);
if (ishit_cache_session()) {
//echo '<h2>CACHED!</h2>';
echo $cache_entry;
exit;
}
$response = '';
if ($reverse_dns = gethostbyaddr6($ip)) {
$response .= '<h4>' . escape_html($reverse_dns) . '</h4><hr />' . PHP_EOL;
}
// WHOIS
$response .= escape_html(ip_whois($ip));
if ($response) {
$cache_entry = '<pre class="small">' . $response . '</pre>';
// @session_start();
// $_SESSION['cache']['response_' . $vars['entity_type'] . '_' . $ip] = '<pre class="small">' . $response . '</pre>';
// session_commit();
} else {
$cache_entry = 'Not Found';
//echo 'Not Found';
}
set_cache_session($cache_key, $cache_entry);
echo $cache_entry;
} else {
echo 'Not correct IP address';
}
break;
case 'autodiscovery':
// if (isset($vars['autodiscovery_id']))
// {
// $vars['entity_id'] = $vars['autodiscovery_id'];
// }
//r($vars);
if (is_numeric($vars['entity_id']) &&
$_SESSION['userlevel'] > 7) {
$cache_key = 'response_' . $vars['entity_type'] . '_' . $vars['entity_id'];
$cache_entry = get_cache_session($cache_key);
//r($cache_entry);
if (ishit_cache_session()) {
//echo '<h2>CACHED!</h2>';
echo $cache_entry;
exit;
}
$entry = dbFetchRow('SELECT `remote_hostname`, `remote_ip`, `last_reason`, UNIX_TIMESTAMP(`last_checked`) AS `last_checked_unixtime` FROM `autodiscovery` WHERE `autodiscovery_id` = ?', [$vars['entity_id']]);
$hostname = $entry['remote_hostname'];
$ip = $entry['remote_ip'];
//r($entry);
// 'ok','no_xdp','no_fqdn','no_dns','no_ip_permit','no_ping','no_snmp','no_db','duplicated','unknown'
switch ($entry['last_reason']) {
case 'ok':
$last_reason = "Remote host $hostname ($ip) successfully added to db.";
break;
case 'no_xdp':
$last_reason = 'Remote platform ignored by XDP autodiscovery configuration.';
break;
case 'no_fqdn':
$last_reason = "Remote IP $ip does not seem to have FQDN.";
break;
case 'no_dns':
$last_reason = "Remote host $hostname not resolved.";
break;
case 'no_ip_permit':
$last_reason = "Remote IP $ip not permitted in autodiscovery configuration or invalid.";
break;
case 'no_ping':
$last_reason = "Remote host $hostname not pingable.";
break;
case 'no_snmp':
$last_reason = "Remote host $hostname not SNMPable by configured auth parameters.";
break;
case 'duplicated':
$last_reason = "Remote host $hostname ($ip) already found in db.";
break;
case 'no_db':
$last_reason = "Remote host $hostname ($ip) success, but not added by an DB error.";
break;
default:
$last_reason = "Remote host $hostname ($ip) not added by unknown reason.";
break;
}
$cache_entry = '<div style="width: 280px;">';
$cache_entry .= "<h4>" . escape_html($last_reason) . "</h4><hr />";
$cache_entry .= '<strong style="margin-left: 10px;">Autodiscovery checked:</strong> ' .
format_uptime(get_time() - $entry['last_checked_unixtime'], 'shorter') . ' ago</span>';
$cache_entry .= '</div>';
//$cache_entry .= build_table_row($entry);
set_cache_session($cache_key, $cache_entry);
echo $cache_entry;
} else {
print_warning("You are not permitted to view this entry.");
}
break;
case 'latlon':
// Check if latitude and longitude are set
if (!isset($vars['lat'], $vars['lon'])) {
echo "ERROR: Latitude and Longitude required";
break;
}
$location = [];
// Fetch devices and their locations
$devices = dbFetchRows("SELECT * FROM `devices` LEFT JOIN `devices_locations` USING (`device_id`) " .
generate_where_clause(generate_query_permitted_ng(['devices']),
"location_lat = ? AND location_lon = ?"),
[$vars['lat'], $vars['lon']]);
foreach ($devices as $device) {
if (!$config['web_show_disabled'] && $device["disabled"]) {
continue;
}
break;
}
if (in_array($matches[1], array('Organization', 'org', 'mnt-irt'))) {
$org++; // has org info
} elseif ($matches[1] === 'Comment') {
continue; // skip comments
if ($device['location'] != '') {
$location['location_name'] = $device['location'];
}
// Categorize devices as up or down
if ($device["status"] == "0" && $device["ignore"] == "0") {
$location["down_hosts"][] = $device;
} else {
$location["up_hosts"][] = $device;
}
$response .= $line . PHP_EOL;
}
}
} else {
// Use RIPE whois API query
$whois_url = 'https://stat.ripe.net/data/whois/data.json?';
$whois_url .= 'sourceapp=' . urlencode(OBSERVIUM_PRODUCT . '-' . get_unique_id());
$whois_url .= '&resource=' . urlencode($ip);
if ($request = get_http_request($whois_url)) {
$request = safe_json_decode($request); // Convert to array
if ($request['status'] === 'ok' && safe_count($request['data']['records'])) {
$whois_parts = array();
foreach ($request['data']['records'] as $i => $parts) {
$key = $parts[0]['key'];
// Display location information
if (!isset($location['location_name'])) {
echo "Unknown Location";
} else {
$num_up = safe_count($location["up_hosts"]);
$num_down = safe_count($location["down_hosts"]);
$total_hosts = $num_up + $num_down;
if (in_array($key, [ 'NetRange', 'inetnum', 'inet6num' ])) {
$org = 0;
$state = 'unknown';
if ($num_down > 0) {
$state = 'down';
} elseif ($num_up > 0) {
$state = 'up';
}
$whois_parts[0] = '';
foreach ($parts as $part) {
if (in_array($part['key'], [ 'Ref', 'source', 'nic-hdl-br' ])) {
break;
}
if (in_array($part['key'], [ 'Organization', 'org', 'mnt-irt' ])) {
$org = 1; // has org info
$org_name = $part['value'];
} elseif ($part['key'] === 'Comment') {
continue; // skip comments
}
$whois_parts[0] .= sprintf('%-16s %s' . PHP_EOL, $part['key'] . ':', $part['value']);
// Generate tooltip content
$tooltip = "<h3>" . escape_html($location['location_name']) . "</h3><hr />";
$tooltip .= '<p><span class="label label-success">Up ' . $num_up . '</span>
<span class="label label-error">Down ' . $num_down . '</span></p>';
if($num_up < 50) {
foreach ($location["up_hosts"] as $host) {
$tooltip .= '<span class="label label-success">' . escape_html($host['hostname']) . '</span> ';
}
} elseif ($org === 1 && $key === 'OrgName' && strpos($org_name, $parts[0]['value']) === 0) {
$whois_parts[1] = '';
foreach ($parts as $part) {
if (in_array($part['key'], [ 'Ref', 'source', 'nic-hdl-br' ])) {
break;
}
if ($part['key'] === 'Comment') {
continue; // skip comments
}
$whois_parts[1] .= sprintf('%-16s %s' . PHP_EOL, $part['key'] . ':', $part['value']);
}
break;
}
}
$response .= implode(PHP_EOL, $whois_parts);
foreach ($location["down_hosts"] as $host) {
$tooltip .= '<span class="label label-error">' . escape_html($host['hostname']) . '</span> ';
}
//$tooltip .= "<p><small>Coordinates: ".$vars['lat'].",".$vars['lon']."</small></p>";
//print_vars($request['data']['records']);
}
echo $tooltip;
}
}
if ($response) {
$cache_entry = '<pre class="small">' . $response . '</pre>';
// @session_start();
// $_SESSION['cache']['response_' . $vars['entity_type'] . '_' . $ip] = '<pre class="small">' . $response . '</pre>';
// session_commit();
} else {
$cache_entry = 'Not Found';
//echo 'Not Found';
}
set_cache_session($cache_key, $cache_entry);
echo $cache_entry;
} else {
echo 'Not correct IP address';
}
break;
break;
case 'autodiscovery':
// if (isset($vars['autodiscovery_id']))
// {
// $vars['entity_id'] = $vars['autodiscovery_id'];
// }
//r($vars);
if (is_numeric($vars['entity_id']) &&
$_SESSION['userlevel'] > 7) {
$cache_key = 'response_' . $vars['entity_type'] . '_' . $vars['entity_id'];
$cache_entry = get_cache_session($cache_key);
//r($cache_entry);
if (ishit_cache_session()) {
//echo '<h2>CACHED!</h2>';
echo $cache_entry;
exit;
}
$entry = dbFetchRow('SELECT `remote_hostname`, `remote_ip`, `last_reason`, UNIX_TIMESTAMP(`last_checked`) AS `last_checked_unixtime` FROM `autodiscovery` WHERE `autodiscovery_id` = ?', [ $vars['entity_id'] ]);
$hostname = $entry['remote_hostname'];
$ip = $entry['remote_ip'];
//r($entry);
// 'ok','no_xdp','no_fqdn','no_dns','no_ip_permit','no_ping','no_snmp','no_db','duplicated','unknown'
switch ($entry['last_reason']) {
case 'ok':
$last_reason = "Remote host $hostname ($ip) successfully added to db.";
break;
case 'no_xdp':
$last_reason = 'Remote platform ignored by XDP autodiscovery configuration.';
break;
case 'no_fqdn':
$last_reason = "Remote IP $ip does not seem to have FQDN.";
break;
case 'no_dns':
$last_reason = "Remote host $hostname not resolved.";
break;
case 'no_ip_permit':
$last_reason = "Remote IP $ip not permitted in autodiscovery configuration or invalid.";
break;
case 'no_ping':
$last_reason = "Remote host $hostname not pingable.";
break;
case 'no_snmp':
$last_reason = "Remote host $hostname not SNMPable by configured auth parameters.";
break;
case 'duplicated':
$last_reason = "Remote host $hostname ($ip) already found in db.";
break;
case 'no_db':
$last_reason = "Remote host $hostname ($ip) success, but not added by an DB error.";
break;
default:
$last_reason = "Remote host $hostname ($ip) not added by unknown reason.";
break;
}
$cache_entry = '<div style="width: 280px;">';
$cache_entry .= "<h4>$last_reason</h4><hr />";
$cache_entry .= '<strong style="margin-left: 10px;">Autodiscovery checked:</strong> '. format_uptime(time() - $entry['last_checked_unixtime'], 'shorter') . ' ago</span>';
$cache_entry .= '</div>';
//$cache_entry .= build_table_row($entry);
set_cache_session($cache_key, $cache_entry);
echo $cache_entry;
} else {
print_warning("You are not permitted to view this entry.");
}
break;
default:
if (isset($config['entities'][$vars['entity_type']])) {
$entity_ids = array();
foreach (explode(',', $vars['entity_id']) as $id) {
// Filter permitted IDs
if (is_numeric($id) && (is_entity_permitted($id, $vars['entity_type']))) {
$entity_ids[] = $id;
default:
if (isset($config['entities'][$vars['entity_type']])) {
$entity_ids = [];
foreach (explode(',', $vars['entity_id']) as $id) {
// Filter permitted IDs
if (is_numeric($id) && (is_entity_permitted($id, $vars['entity_type']))) {
$entity_ids[] = $id;
}
}
if (count($entity_ids)) {
echo generate_entity_popup_multi($entity_ids, $vars);
} else {
print_warning("You are not permitted to view this entity.");
}
} else {
print_error("Unknown entity type.");
}
}
if (count($entity_ids)) {
echo generate_entity_popup_multi($entity_ids, $vars);
//}
//elseif (is_numeric($vars['entity_id']) && (is_entity_permitted($vars['entity_id'], $vars['entity_type'])))
//{
// $entity = get_entity_by_id_cache($vars['entity_type'], $vars['entity_id']);
// echo generate_entity_popup($entity, $vars);
} else {
print_warning("You are not permitted to view this entity.");
}
} else {
print_error("Unknown entity type.");
}
break;
break;
}
exit;

95
html/ajax/geojson.php Normal file
View File

@ -0,0 +1,95 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage web
* @copyright (C) Adam Armstrong
*
*/
ini_set('allow_url_fopen', 0); // Why here?
include_once("../../includes/observium.inc.php");
include($config['html_dir'] . "/includes/authenticate.inc.php");
include($config['html_dir'] . "/includes/cache-data.inc.php");
if (!$_SESSION['authenticated']) {
echo("unauthenticated");
exit;
}
$vars = get_vars('GET');
$geo = [];
foreach (dbFetchRows("SELECT * FROM `devices` LEFT JOIN `devices_locations` USING (`device_id`) " . generate_where_clause(generate_query_permitted_ng(['devices']))) as $device) {
if (!$config['web_show_disabled'] && $device["disabled"]) {
continue;
}
$lat = (is_numeric($device['location_lat']) ? $device['location_lat'] : $config['geocoding']['default']['lat']);
$lon = (is_numeric($device['location_lon']) ? $device['location_lon'] : $config['geocoding']['default']['lon']);
if ($device["status"] == "0") {
if ($device["ignore"] == "0") {
$locations[$lat][$lon]["down_hosts"][] = $device;
}
} else {
$locations[$lat][$lon]["up_hosts"][] = $device;
}
}
foreach ($locations as $la => $lat) {
foreach ($lat as $lo => $lon) {
$tooltip = "";
$num_up = safe_count($lon["up_hosts"]);
$num_down = safe_count($lon["down_hosts"]);
$total_hosts = $num_up + $num_down;
$tooltip = '<p><span class="label label-success">Up ' . $num_up . '</span> <span class="label label-error">Down ' . $num_down . '</span></p>';
$state = 'unknown';
$location_name = "";
if ($num_down > 0) {
$state = 'down';
$location_name = ($lon['down_hosts'][0]['location'] === '' ? OBS_VAR_UNSET : $lon['down_hosts'][0]['location']);
$location_url = generate_location_url($lon['down_hosts'][0]['location']);
} elseif ($num_up > 0) {
$state = 'up';
$location_name = ($lon['up_hosts'][0]['location'] === '' ? OBS_VAR_UNSET : $lon['up_hosts'][0]['location']);
$location_url = generate_location_url($lon['up_hosts'][0]['location']);
}
$tooltip = "<h3>" . $location_name . "</h3><hr />" . $tooltip;
foreach ($lon["down_hosts"] as $down_host) {
$tooltip .= '<span class="label label-error">' . escape_html($down_host['hostname']) . '</span> ';
}
$feature = ['geometry' => ['type' => 'Point',
'coordinates' => [(float)$lo, (float)$la]],
'type' => 'Feature',
'properties' => ['name' => $location_name,
'state' => $state,
'id' => safename($location_name),
//'popupContent' => $tooltip,
'url' => $location_url]];
$features[] = $feature;
//echo "[$la, $lo, $num_up, $num_down, \"$tooltip\", '$location_name', '$location_url'],\n ";
}
}
$geo = ['type' => 'FeatureCollection', 'features' => $features];
header('Content-type: application/javascript');
//echo 'var geojson = ' . json_encode($geo) . ';';
//print_r($features);
echo safe_json_encode($geo);
//r($geo);
// EOF

View File

@ -0,0 +1,93 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage ajax
* @author Adam Armstrong <adama@observium.org>
* @copyright (C) Adam Armstrong
*
*/
include_once("../../includes/observium.inc.php");
include($config['html_dir'] . "/includes/authenticate.inc.php");
if (!$_SESSION['authenticated']) {
echo("unauthenticated");
exit;
}
if ($_SESSION['userlevel'] >= '5') {
$options = [];
$device_id = filter_input(INPUT_GET, 'device_id', FILTER_SANITIZE_NUMBER_INT);
$entity_type = filter_input(INPUT_GET, 'entity_type', FILTER_SANITIZE_STRING);
switch ($entity_type) {
case "device":
include($config['html_dir'] . '/includes/cache-data.inc.php');
$options = generate_device_form_values(NULL, NULL, [ 'filter_mode' => 'exclude', 'subtext' => '%location%', 'show_disabled' => TRUE, 'show_icon' => TRUE ]);
break;
case "sensor":
foreach (dbFetchRows("SELECT * FROM `sensors` WHERE device_id = ?", [ $device_id ]) as $sensor) {
if (is_entity_permitted($sensor, 'sensor')) {
$nice_class = nicecase($sensor['sensor_class']);
$symbol = str_replace('&deg;', '°', $config['sensor_types'][$sensor['sensor_class']]['symbol']);
$options[] = [
'value' => $sensor['sensor_id'],
'group' => $nice_class,
'name' => addslashes($sensor['sensor_descr']),
'subtext' => round($sensor['sensor_value'],2) . $symbol,
'icon' => $config['sensor_types'][$sensor['sensor_class']]['icon'],
//'class' => 'bg-info'
];
}
}
break;
case "netscalervsvr":
// Example for netscalervsvr type
foreach (dbFetchRows("SELECT * FROM `netscaler_vservers` WHERE device_id = ?", [ $device_id ]) as $entity) {
$options[] = [
'value' => $entity['vsvr_id'],
'name' => addslashes($entity['vsvr_label']),
//'subtext' => 'Extra details for netscalervsvr',
//'icon' => 'netscaler-icon',
//'class' => 'custom-class'
];
}
break;
case "port":
// Example for port type
foreach (dbFetchRows("SELECT * FROM `ports` WHERE device_id = ? AND deleted = 0", [$_GET['device_id']]) as $port) {
humanize_port($port);
$port_type = $port['human_type'];
$options[] = [
'value' => $port['port_id'],
'group' => $port_type,
'name' => addslashes($port['port_label_short']),
//'content' => addslashes($port['port_label_short']) . ' <span class="label">'.format_si($port['ifSpeed']).'bps</span> ',
'subtext' => '['.format_si($port['ifSpeed']).'bps] ' . addslashes($port['ifAlias']),
'icon' => $port['icon'],
//'class' => 'port-class'
];
}
break;
}
echo json_encode($options, JSON_UNESCAPED_UNICODE); // Return JSON encoded data
}

View File

@ -6,148 +6,152 @@
*
* @package observium
* @subpackage ajax
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2022 Observium Limited
* @copyright (C) Adam Armstrong
*
*/
// FIXME, create api-internal for such
$config['install_dir'] = "../..";
include_once("../../includes/observium.inc.php");
include_once("../../includes/sql-config.inc.php");
include($config['html_dir'] . "/includes/functions.inc.php");
include($config['html_dir'] . "/includes/authenticate.inc.php");
if (!$_SESSION['authenticated']) { echo('<li class="nav-header">Session expired, please log in again!</li>'); exit; }
if (!$_SESSION['authenticated']) {
echo('<li class="nav-header">Session expired, please log in again!</li>');
exit;
}
$vars = get_vars('GET');
$array_filter = in_array($vars['field'], [ 'syslog_program' ], TRUE); // modules with cached field
$vars = get_vars('GET');
$array_filter = in_array($vars['field'], ['syslog_program'], TRUE); // modules with cached field
if (!safe_empty($vars['field']) && $vars['cache'] !== 'no' && ($array_filter || safe_empty($vars['query']))) {
$cache_key = 'options_' . $vars['field'];
foreach ($vars as $param => $value) {
if (in_array($param, [ 'field', 'query', 'cache' ], TRUE)) { continue; }
$cache_key .= "_$param=$value";
}
$cache_key = 'options_' . $vars['field'];
foreach ($vars as $param => $value) {
if (in_array($param, ['field', 'query', 'cache'], TRUE)) {
continue;
}
$cache_key .= "_$param=$value";
}
} else {
$cache_key = '';
$cache_key = '';
}
$query = '';
if ($cache_key && $options = get_cache_session($cache_key)) {
// Return cached data (if not set in vars cache = 'no')
//header("Content-type: application/json; charset=utf-8");
//echo safe_json_encode(array('options' => $_SESSION['cache'][$cache_key]));
//$options = $_SESSION['cache'][$cache_key];
// Return cached data (if not set in vars cache = 'no')
//header("Content-type: application/json; charset=utf-8");
//echo safe_json_encode(array('options' => $_SESSION['cache'][$cache_key]));
//$options = $_SESSION['cache'][$cache_key];
} else {
$params = array();
//print_vars($vars);
switch ($vars['field']) {
case 'ipv4_network':
case 'ipv6_network':
list($ip_version) = explode('_', $vars['field']);
$query_permitted = generate_query_permitted('ports');
$network_permitted = dbFetchColumn('SELECT DISTINCT(`' . $ip_version . '_network_id`) FROM `' . $ip_version . '_addresses` WHERE 1' . $query_permitted);
$query = 'SELECT `' . $ip_version . '_network` FROM `' . $ip_version . '_networks` WHERE 1 ' . generate_query_values_and($network_permitted, $ip_version . '_network_id');
if (!safe_empty($vars['query'])) {
//$query .= ' AND `' . $ip_version . '_network` LIKE ?';
//$params[] = '%' . $vars['query'] . '%';
$query .= generate_query_values_and($vars['query'], $vars['field'], '%LIKE%');
}
$query .= ' ORDER BY `' . $ip_version . '_network`;';
//print_vars($query);
break;
$where = [];
$params = [];
//print_vars($vars);
switch ($vars['field']) {
case 'ipv4_network':
case 'ipv6_network':
$ip_version = explode('_', $vars['field'])[0];
$query_permitted = generate_query_permitted_ng('ports');
$network_permitted = dbFetchColumn('SELECT DISTINCT(`' . $ip_version . '_network_id`) FROM `' . $ip_version . '_addresses` WHERE ' . $query_permitted);
$where[] = generate_query_values($network_permitted, $ip_version . '_network_id');
if (!safe_empty($vars['query'])) {
//$query .= ' AND `' . $ip_version . '_network` LIKE ?';
//$params[] = '%' . $vars['query'] . '%';
$where[] = generate_query_values($vars['query'], $vars['field'], '%LIKE%');
}
$query = 'SELECT `' . $ip_version . '_network` FROM `' . $ip_version . '_networks` ';
$query .= generate_where_clause($where);
$query .= ' ORDER BY `' . $ip_version . '_network`;';
//print_vars($query);
break;
case 'ifspeed':
$query_permitted = generate_query_permitted('ports');
$query = 'SELECT `ifSpeed`, COUNT(`ifSpeed`) as `count` FROM `ports` WHERE `ifSpeed` > 0 '. $query_permitted .' GROUP BY ifSpeed ORDER BY `count` DESC';
$call_function = 'formatRates';
$call_params = array(4, 4);
break;
case 'ifspeed':
$query_permitted = generate_query_permitted('ports');
$query = 'SELECT `ifSpeed`, COUNT(`ifSpeed`) as `count` FROM `ports` WHERE `ifSpeed` > 0 ' .
$query_permitted . ' GROUP BY ifSpeed ORDER BY `count` DESC';
$call_function = 'formatRates';
$call_params = [4, 4];
break;
case 'syslog_program':
//$query_permitted = generate_query_permitted();
$query = 'SELECT DISTINCT `program` FROM `syslog`';
if (is_intnum($vars['device_id'])) {
$query .= ' WHERE ' . generate_query_values_ng($vars['device_id'], 'device_id');
}
$array_filter = TRUE; // Search query string in array instead sql query (when this faster)
break;
case 'syslog_program':
//$query_permitted = generate_query_permitted();
$query = 'SELECT DISTINCT `program` FROM `syslog`';
if (is_intnum($vars['device_id'])) {
$query .= ' WHERE ' . generate_query_values($vars['device_id'], 'device_id');
}
$array_filter = TRUE; // Search query string in array instead sql query (when this faster)
break;
case 'bgp_peer_as':
$column = 'bgpPeerRemoteAs';
$query_permitted = generate_query_permitted('devices');
// Combine AS number and AS text into string: ASXXXX: My AS text
$query = 'SELECT DISTINCT CONCAT(?, CONCAT_WS(?, `'.$column.'`, `astext`)) AS `'.$vars['field'].'` FROM `bgpPeers` WHERE 1 ' . $query_permitted;
$params[] = 'AS';
$params[] = ': ';
//$query = 'SELECT DISTINCT `' . $column . '`, `astext` FROM `bgpPeers` WHERE 1 ' . $cache['where']['devices_permitted'] . ' ORDER BY `' . $column . '`';
if (!safe_empty($vars['query'])) {
$query .= ' AND (`' . $column . '` LIKE ? OR `astext` LIKE ?)';
$params[] = '%' . $vars['query'] . '%';
$params[] = '%' . $vars['query'] . '%';
//$query .= generate_query_values_and($vars['query'], $vars['field'], '%LIKE%');
}
break;
case 'bgp_peer_as':
$column = 'bgpPeerRemoteAs';
$query_permitted = generate_query_permitted('devices');
// Combine AS number and AS text into string: ASXXXX: My AS text
$query = 'SELECT DISTINCT CONCAT(?, CONCAT_WS(?, `' . $column . '`, `astext`)) AS `' . $vars['field'] . '` FROM `bgpPeers` WHERE 1 ' . $query_permitted;
$params[] = 'AS';
$params[] = ': ';
if (!safe_empty($vars['query'])) {
$query .= ' AND (`' . $column . '` LIKE ? OR `astext` LIKE ?)';
$params[] = '%' . $vars['query'] . '%';
$params[] = '%' . $vars['query'] . '%';
//$query .= generate_query_values_and($vars['query'], $vars['field'], '%LIKE%');
}
break;
case 'bgp_local_ip':
case 'bgp_peer_ip':
$columns = array('local_ip' => 'bgpPeerLocalAddr',
'peer_ip' => 'bgpPeerRemoteAddr',
);
$param = str_replace('bgp_', '', $vars['field']);
$column = $columns[$param];
$query_permitted = generate_query_permitted('devices');
$query = 'SELECT DISTINCT `' . $column . '` FROM `bgpPeers` WHERE 1 ' . $query_permitted;
if (!safe_empty($vars['query'])) {
$query .= generate_query_values_and($vars['query'], $column, '%LIKE%');
}
break;
case 'bgp_local_ip':
case 'bgp_peer_ip':
$columns = ['local_ip' => 'bgpPeerLocalAddr',
'peer_ip' => 'bgpPeerRemoteAddr'];
$param = str_replace('bgp_', '', $vars['field']);
$column = $columns[$param];
if (!safe_empty($vars['query'])) {
$where[] = generate_query_values($vars['query'], $column, '%LIKE%');
}
$query = 'SELECT DISTINCT `' . $column . '` FROM `bgpPeers`';
$query .= generate_where_clause($where, generate_query_permitted_ng('devices'));
break;
default:
json_output('error', 'Search type unknown');
}
if (strlen($query)) {
$options = dbFetchColumn($query, $params);
if (safe_count($options)) {
if (isset($call_function)) {
$call_options = array();
foreach ($options as $option) {
$call_options[] = call_user_func_array($call_function, array_merge(array($option), $call_params));
}
$options = $call_options;
}
// Cache request in session var (need convert to common caching lib)
if ($cache_key) {
set_cache_session($cache_key, $options);
//@session_start();
//$_SESSION['cache'][$cache_key] = $options; // Cache query data in session for speedup
//session_write_close();
}
} else {
json_output('error', 'Data fields are empty');
default:
json_output('error', 'Search type unknown');
}
if (!safe_empty($query)) {
$options = dbFetchColumn($query, $params);
if (safe_count($options)) {
if (isset($call_function)) {
$call_options = [];
foreach ($options as $option) {
$call_options[] = call_user_func_array($call_function, array_merge([$option], $call_params));
}
$options = $call_options;
}
// Cache request in session var (need convert to common caching lib)
if ($cache_key) {
set_cache_session($cache_key, $options);
//@session_start();
//$_SESSION['cache'][$cache_key] = $options; // Cache query data in session for speedup
//session_write_close();
}
} else {
json_output('error', 'Data fields are empty');
}
}
}
}
if (safe_count($options)) {
// Filter/search query string in array, instead sql query, when this is faster (ie syslog program)
if ($array_filter) {
$new_options = [];
foreach ($options as $option) {
if (stripos($option, $vars['query']) !== FALSE) {
$new_options[] = $option;
}
// Filter/search query string in array, instead sql query, when this is faster (ie syslog program)
if ($array_filter) {
$new_options = [];
foreach ($options as $option) {
if (str_contains_array($option, $vars['query'])) {
$new_options[] = $option;
}
}
$options = $new_options;
}
$options = $new_options;
}
header("Content-type: application/json; charset=utf-8");
echo safe_json_encode(array( 'options' => $options ));
header("Content-type: application/json; charset=utf-8");
echo safe_json_encode(['options' => $options]);
} else {
json_output('error', 'Data fields are empty');
json_output('error', 'Data fields are empty');
}
// EOF

View File

@ -4,101 +4,90 @@
*
* This file is part of Observium.
*
* @package observium
* @subpackage web
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2021 Observium Limited
* @package observium
* @subpackage web
* @copyright (C) Adam Armstrong
*
*/
$config['install_dir'] = "../..";
include_once("../../includes/observium.inc.php");
include_once("../../includes/sql-config.inc.php");
include($config['html_dir'] . "/includes/functions.inc.php");
include($config['html_dir'] . "/includes/authenticate.inc.php");
if (!$_SESSION['authenticated']) { echo('<li class="nav-header">Session expired, please log in again!</li>'); exit; }
if (!$_SESSION['authenticated']) {
echo('<li class="nav-header">Session expired, please log in again!</li>');
exit;
}
include($config['html_dir'] . "/includes/cache-data.inc.php");
$query_limit = 8; // Limit per query
$vars = get_vars([ 'POST', 'GET' ]);
$vars = get_vars(['POST', 'GET']);
// Is there a POST/GET query string?
if (isset($vars['queryString'])) {
$queryString = trim($vars['queryString']);
$queryString = trim($vars['queryString']);
// Is the string length greater than 0?
if (strlen($queryString) > 0)
{
$query_param = "%$queryString%";
// Is the string length greater than 0?
if (strlen($queryString) > 0) {
$query_param = "%$queryString%";
// Start out with a clean slate
$search_results = array();
// Start out with a clean slate
$search_results = [];
// Increase query_limit by one, so we can show "+" on result display if there are more than $query_limit entries
$query_limit++;
// Increase query_limit by one, so we can show "+" on result display if there are more than $query_limit entries
$query_limit++;
// Prepare user permission SQL query for use in search module queries
$query_permitted_device = $cache['where']['devices_permitted'];
$query_permitted_port = $cache['where']['ports_permitted'];
// Run search modules
foreach ($config['wui']['search_modules'] as $module)
{
if (is_file($config['html_dir'] . "/includes/search/$module.inc.php"))
{
include($config['html_dir'] . "/includes/search/$module.inc.php");
}
}
// Reset query_limit
$query_limit--;
foreach ($search_results as $results)
{
$display_count = safe_count($results['results']);
// If there are more results than query_limit (can happen, as we ++'d above), cut array to desired size and add + to counter
if ($display_count > $query_limit)
{
$results['results'] = array_slice($results['results'], 0, $query_limit);
$display_count .= '+';
}
echo('<li class="nav-header">' . $results['descr'] . ': '. $display_count . '</li>' . PHP_EOL);
foreach ($results['results'] as $result)
{
$data = [];
foreach ($result['data'] as $str) {
$str = str_replace('| |', '|', $str);
$data[] = rtrim($str, ' |');
// Run search modules
foreach ($config['wui']['search_modules'] as $module) {
if (is_file($config['html_dir'] . "/includes/search/$module.inc.php")) {
include($config['html_dir'] . "/includes/search/$module.inc.php");
}
}
echo('<li class="divider" style="margin: 0px;"></li>' . PHP_EOL);
echo('<li style="margin: 0px;">' . PHP_EOL . ' <a href="'.$result['url'].'">' . PHP_EOL);
echo(' <dl style="border-left: 10px solid '.$result['colour'].'; " class="dl-horizontal dl-search">' . PHP_EOL);
echo(' <dt style="width: 64px; text-align: center; line-height: 41.5px;">' . get_icon($result['icon']) . '</dt>' . PHP_EOL);
echo(' <dd>' . PHP_EOL);
echo(' <strong>'.html_highlight(escape_html($result['name']), $queryString) . PHP_EOL);
echo(' <small>'. implode('<br />', $data) . '</small>' . PHP_EOL);
echo(' </strong>' . PHP_EOL);
echo(' </dd>' . PHP_EOL);
echo('</dl>' . PHP_EOL);
echo(' </a>' . PHP_EOL);
echo('</li>' . PHP_EOL);
}
}
if (!safe_count($search_results))
{
echo('<li class="nav-header">No search results.</li>');
// Reset query_limit
$query_limit--;
foreach ($search_results as $results) {
$display_count = safe_count($results['results']);
// If there are more results than query_limit (can happen, as we ++'d above), cut array to desired size and add + to counter
if ($display_count > $query_limit) {
$results['results'] = array_slice($results['results'], 0, $query_limit);
$display_count .= '+';
}
echo('<li class="nav-header">' . $results['descr'] . ': ' . $display_count . '</li>' . PHP_EOL);
foreach ($results['results'] as $result) {
$data = [];
foreach ($result['data'] as $str) {
$str = str_replace('| |', '|', $str);
$data[] = rtrim($str, ' |');
}
echo('<li class="divider" style="margin: 0px;"></li>' . PHP_EOL);
echo('<li style="margin: 0px;">' . PHP_EOL . ' <a href="' . $result['url'] . '">' . PHP_EOL);
echo(' <dl style="border-left: 10px solid ' . $result['colour'] . '; " class="dl-horizontal dl-search">' . PHP_EOL);
echo(' <dt style="width: 64px; text-align: center; line-height: 41.5px;">' . get_icon($result['icon']) . '</dt>' . PHP_EOL);
echo(' <dd>' . PHP_EOL);
echo(' <strong>' . html_highlight(escape_html($result['name']), $queryString) . PHP_EOL);
echo(' <small>' . implode('<br />', $data) . '</small>' . PHP_EOL);
echo(' </strong>' . PHP_EOL);
echo(' </dd>' . PHP_EOL);
echo('</dl>' . PHP_EOL);
echo(' </a>' . PHP_EOL);
echo('</li>' . PHP_EOL);
}
}
if (!safe_count($search_results)) {
echo('<li class="nav-header">No search results.</li>');
}
}
}
} else {
// There is no queryString, we shouldn't get here.
echo('<li class="nav-header">There should be no direct access to this script! Please reload the page.</li>');
// There is no queryString, we shouldn't get here.
echo('<li class="nav-header">There should be no direct access to this script! Please reload the page.</li>');
}
// EOF

View File

@ -6,444 +6,289 @@
*
* @package observium
* @subpackage ajax
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2021 Observium Limited
* @copyright (C) Adam Armstrong
*
*/
$config['install_dir'] = "../..";
include_once("../../includes/observium.inc.php");
include_once("../../includes/sql-config.inc.php");
include($config['html_dir'] . "/includes/functions.inc.php");
include($config['html_dir'] . "/includes/authenticate.inc.php");
if (!$_SESSION['authenticated'])
{
echo("unauthenticated");
exit;
if (!$_SESSION['authenticated']) {
echo("unauthenticated");
exit;
}
include_dir($config['html_dir'] . "/includes/widgets/");
$widget = dbFetchRow("SELECT * FROM `dash_widgets` WHERE widget_id = ?", array($_POST['id']));
$widget = dbFetchRow("SELECT * FROM `dash_widgets` WHERE `widget_id` = ?", [ $_POST['id'] ]);
$widget['height'] = (is_numeric($_POST['height']) ? $_POST['height'] : '3');
$widget['width'] = (is_numeric($_POST['width']) ? $_POST['width'] : '4');
$widget['height'] = is_numeric($_POST['height']) ? $_POST['height'] : 3;
$widget['width'] = is_numeric($_POST['width']) ? $_POST['width'] : 4;
print_dash_mod($widget);
function print_dash_mod ($mod)
{
function print_dash_mod($mod) {
global $config;
global $cache;
global $config, $cache;
$mod['vars'] = json_decode($mod['widget_config'], TRUE);
$mod['vars'] = safe_json_decode($mod['widget_config']);
$width = (is_numeric($mod['width']) ? $mod['width'] : 1240);
$height = (is_numeric($mod['height']) ? $mod['height'] : 80);
$width = is_numeric($mod['width']) ? $mod['width'] : 1240;
$height = is_numeric($mod['height']) ? $mod['height'] : 80;
switch ($mod['widget_type'])
{
switch ($mod['widget_type']) {
case "welcome":
echo '<div class="box box-solid do-not-update" style="padding:10px; padding-left: 375px; background-image: url(images/login-hamster-large.png); background-position: left 10px top -100px; background-repeat: no-repeat;">';
echo '<h3>Welcome to your new Observium dashboard!</h3>';
if(isset($mod['vars']['converted']))
{
echo 'This was autogenerated based on your previous front page. It can be modified to suit your requirements.<br />';
} else {
echo 'This is an autogenerated default dashboard. It can be modified to suit your requirements.<br />';
}
echo 'Please see the <strong><a href="'.OBSERVIUM_DOCS_URL.'/dashboard/" target="_blank">documentation</a></strong> for information about how to configure this dashboard. Including how to delete this widget!';
echo '</div>';
break;
case "welcome":
echo '<div class="box box-solid do-not-update" style="padding:10px; padding-left: 375px; background-image: url(images/hamster-login.png); background-position: left 10px top -100px; background-repeat: no-repeat;">';
echo '<h3>Welcome to your new Observium dashboard!</h3>';
if (isset($mod['vars']['converted'])) {
echo 'This was autogenerated based on your previous front page. It can be modified to suit your requirements.<br />';
} else {
echo 'This is an autogenerated default dashboard. It can be modified to suit your requirements.<br />';
}
echo 'Please see the <strong><a href="' . OBSERVIUM_DOCS_URL . '/dashboard/" target="_blank">documentation</a></strong> for information about how to configure this dashboard. Including how to delete this widget!';
echo '</div>';
break;
case "weathermap":
case "weathermap":
echo '<div class="box box-solid do-not-update">';
echo '<div class="box box-solid do-not-update">';
$wmap = dbFetchRow("SELECT * FROM `weathermaps` WHERE `wmap_name` = ?", array($mod['vars']['mapname']));
$wmap = dbFetchRow("SELECT * FROM `weathermaps` WHERE `wmap_name` = ?", [ $mod['vars']['mapname'] ]);
echo ' <div class="hover-hide widget-title" style="z-index: 900; position: absolute; overflow: hidden;" class="widget-title"><h4 style="wwriting-mode: vertical-lr; ttext-orientation: mixed;" class="box-title">' .
'' . htmlentities($wmap['wmap_name']) . '</h4>' .
'</div>' . PHP_EOL;
echo ' <div class="hover-hide widget-title" style="z-index: 900; position: absolute; overflow: hidden;" class="widget-title"><h4 style="wwriting-mode: vertical-lr; ttext-orientation: mixed;" class="box-title">' .
escape_html($wmap['wmap_name']) . '</h4></div>' . PHP_EOL;
echo ' <div class="box-content" style="overflow: hidden">';
echo '<div style="height:100%; overflow:hidden; width: 110%;">';
echo '<a href="'.generate_url(['page' => 'wmap', 'mapname' => $wmap['map_name']]).'">';
echo '<img src="/weathermap.php?mapname=' . htmlentities($wmap['wmap_name']) . '&action=draw&unique=' . time() . '&width='.$width.'&height='.$height.'">';
echo '</a>';
echo ' <div class="box-content" style="overflow: hidden">';
echo '<div style="height:100%; overflow:hidden; width: 110%;">';
echo '<a href="' . generate_url([ 'page' => 'wmap', 'mapname' => $wmap['map_name'] ]) . '">';
echo '<img src="/weathermap.php?mapname=' . escape_html($wmap['wmap_name']) . '&action=draw&unique=' . time() . '&width=' . $width . '&height=' . $height . '">';
echo '</a>';
echo '</div>';
echo ' </div>';
echo '</div>';
echo ' </div>';
echo '</div>';
break;
echo '</div>';
break;
case "map":
echo '<div class="box box-solid do-not-update">';
print_dash_map($mod, $width, $height);
echo '</div>';
break;
case "map":
echo '<div class="box box-solid do-not-update">';
print_dash_map($mod, $width, $height);
echo '</div>';
case "graph":
echo '<div class="box box-solid do-not-update">';
print_dash_graph($mod, $width, $height);
echo '</div>';
break;
break;
case "port_percent":
if($_SESSION['userlevel'] < 5)
{
echo '<div class="box box-solid" style="width: 100%; height: 100%; float:none; display: block; padding: 10px;">';
echo '<div class="alert statusbox alert-warning" style="border-left: 1px; width: 100%; height: 100%; margin-right: 10px; float:none; display: block;">';
echo '<div style="margin: auto; line-height: 75px; text-align: center;">You have insufficient permissions to view this widget.</div>';
echo '</div>';
echo '</div>';
} elseif ($height < 190) {
echo '<div class="box box-solid alert alert-warning" style="width: 100%; height: 100%; float:none; display: block; padding: 10px;">';
echo '<b>WARNING</b> This widget is not tall enough to display the requested content. Module <b>Port Percent</b> requires 190px or taller.';
echo '</div>';
} else {
include($config['html_dir'] . "/includes/status-portpercent.inc.php");
}
break;
case "port_percent":
if ($_SESSION['userlevel'] < 5) {
echo '<div class="box box-solid" style="width: 100%; height: 100%; float:none; display: block; padding: 10px;">';
echo '<div class="alert statusbox alert-warning" style="border-left: 1px; width: 100%; height: 100%; margin-right: 10px; float:none; display: block;">';
echo '<div style="margin: auto; line-height: 75px; text-align: center;">You have insufficient permissions to view this widget.</div>';
echo '</div>';
echo '</div>';
} elseif ($height < 190) {
echo '<div class="box box-solid alert alert-warning" style="width: 100%; height: 100%; float:none; display: block; padding: 10px;">';
echo '<b>WARNING</b> This widget is not tall enough to display the requested content. Module <b>Port Percent</b> requires 190px or taller.';
echo '</div>';
} else {
include($config['html_dir'] . "/includes/status-portpercent.inc.php");
}
break;
case "alert_table":
echo '<div class="box box-solid" style="overflow: hidden; height: auto; max-height: 100%">';
echo ' <div class="box-header" style="cursor: hand;"><h3 class="box-title">Alert Status</h3></div>';
echo ' <div class="box-content" style="overflow:auto;">';
print_alert_table(array('status' => 'failed',
'pagination' => FALSE,
'short' => TRUE)
);
echo ' </div>';
echo ' </div>';
echo '</div>';
break;
case "alert_table":
echo '<div class="box box-solid" style="overflow: hidden; height: auto; max-height: 100%">';
echo ' <div class="box-header" style="cursor: hand;"><h3 class="box-title">Alert Status</h3></div>';
echo ' <div class="box-content" style="height: ' . ($height - 40) . 'px; overflow: auto;">';
//echo ' <div class="box-content" style="overflow: scroll; overflow-x:scroll;">';
//echo ' <div class="box-content" style="overflow:auto;">';
case "status_summary":
echo '<div class="row">';
if($width > 1000) { $div_class = "col-md-6"; } else { $div_class = "col-md-12"; }
$short = !($width > 1000);
if($height < 210) { $hide_group_bar = 1; }
print_alert_table([ 'status' => 'failed', 'pagination' => FALSE, 'short' => $short ]);
echo ' </div>';
echo ' </div>';
echo '</div>';
include($config['html_dir'] . '/includes/cache-data.inc.php');
include($config['html_dir'] . "/includes/status-summary.inc.php");
echo '</div>';
break;
break;
case "alert_boxes":
case "old_status_boxes":
//r($height);
include($config['html_dir'] . '/includes/cache-data.inc.php');
//$count = round(($width) / 165) * round(($height+10) / 90); // 1.5 wide
$count = floor(($width+10) / 198) * floor(($height+10) / 96); // 1.5 wide
echo '<div style="width: auto; height: 100%; overflow-x: visible; overflow-y: visible; margin-right: -25px;">';
if($mod['widget_type'] == 'alert_boxes')
{
print_status_boxes($mod, $count);
} else {
print_status_boxes($config['frontpage']['device_status'], $count);
}
echo '</div>';
break;
case "status_summary":
echo '<div class="row">';
if ($width > 1000) {
$div_class = "col-md-6";
} else {
$div_class = "col-md-12";
}
case "old_status_table":
echo '<div class="box box-solid" style="overflow: hidden; height: auto; max-height: 100%">';
echo ' <div class="box-header" style="cursor: hand;"><h3 class="box-title">Status Warnings and Notifications</h3></div>';
echo ' <div class="box-content" style="height: ' . ($height - 40) .'px; overflow: auto;">';
if ($height < 210) {
$hide_group_bar = 1;
}
include($config['html_dir'] . '/includes/cache-data.inc.php');
echo generate_status_table($config['frontpage']['device_status']);
echo generate_box_close();
include($config['html_dir'] . '/includes/cache-data.inc.php');
include($config['html_dir'] . "/includes/status-summary.inc.php");
echo '</div>';
break;
break;
case "alert_boxes":
case "old_status_boxes":
//r($height);
include($config['html_dir'] . '/includes/cache-data.inc.php');
//$count = round(($width) / 165) * round(($height+10) / 90); // 1.5 wide
$count = floor(($width + 10) / 198) * floor(($height + 10) / 96); // 1.5 wide
echo '<div style="width: auto; height: 100%; overflow-x: visible; overflow-y: visible; margin-right: -25px;">';
if ($mod['widget_type'] == 'alert_boxes') {
print_status_boxes($mod, $count);
} else {
print_status_boxes($config['frontpage']['device_status'], $count);
}
echo '</div>';
break;
case "status_donuts":
include($config['html_dir'] . "/includes/status-donuts.inc.php");
break;
case "old_status_table":
echo '<div class="box box-solid" style="overflow: hidden; height: auto; max-height: 100%">';
echo ' <div class="box-header" style="cursor: hand;"><h3 class="box-title">Status Warnings and Notifications</h3></div>';
echo ' <div class="box-content" style="height: ' . ($height - 40) . 'px; overflow: auto;">';
case "syslog":
echo ' <div class="box box-solid" style="overflow: hidden; height: auto; max-height: 100%">';
echo ' <div class="box-header" style="cursor: hand;"><h3 class="box-title"><a href="/syslog/">Syslog</a></h3></div>';
echo ' <div class="box-content" style="overflow: hidden; overflow-x:scroll;">';
include($config['html_dir'] . '/includes/cache-data.inc.php');
echo generate_status_table($config['frontpage']['device_status']);
echo generate_box_close();
$syslog_vars = $mod['vars'];
break;
$syslog_vars = array_merge($syslog_vars, ['short' => TRUE, 'pagesize' => ($height - 36) / 26,
'priority' => $config['frontpage']['syslog']['priority']]);
case "status_donuts":
include($config['html_dir'] . "/includes/status-donuts.inc.php");
break;
print_syslogs($syslog_vars);
case "syslog":
echo ' <div class="box box-solid" style="overflow: hidden; height: auto; max-height: 100%">';
echo ' <div class="box-header" style="cursor: hand;"><h3 class="box-title"><a href="/syslog/">Syslog</a></h3></div>';
echo ' <div class="box-content" style="overflow: hidden; overflow-x:scroll;">';
echo ' </div>';
echo '</div>';
break;
$short = !($width > 1000);
case "syslog_alerts":
echo ' <div class="box box-solid" style="overflow: hidden; height: auto; max-height: 100%">';
echo ' <div class="box-header" style="cursor: hand;"><h3 class="box-title"><a href="/syslog_alerts/">Syslog Alerts</a></h3></div>';
echo ' <div class="box-content" style="overflow: hidden; overflow-x:scroll;">';
print_logalert_log(array('short' => TRUE, 'pagesize' => ($height - 36) / 26) );
echo ' </div>';
echo '</div>';
break;
$syslog_vars = array_merge($mod['vars'], [ 'short' => $short, 'pagesize' => ($height - 36) / 26,
'priority' => $config['frontpage']['syslog']['priority'] ]);
case "alertlog":
echo ' <div class="box box-solid" style="overflow: hidden; height: auto; max-height: 100%">';
echo ' <div class="box-header" style="cursor: hand;"><h3 class="box-title"><a href="/alert_log/">Alert Log</a></h3></div>';
echo ' <div class="box-content" style="overflow: hidden; overflow-x:scroll;">';
print_alert_log_short(array('short' => TRUE, 'pagesize' => ($height - 36) / 26));
echo ' </div>';
echo '</div>';
break;
print_syslogs($syslog_vars);
case "eventlog":
echo ' <div class="box box-solid" style="overflow: hidden; height: auto; max-height: 100%">';
echo ' <div class="box-header" style="cursor: hand;"><h3 class="box-title"><a href="/eventlog/">Eventlog</a></h3></div>';
echo ' <div class="box-content" style="overflow: hidden; overflow-x:scroll;">';
echo ' </div>';
echo '</div>';
break;
$pagesize = floor(($height - 36) / 26);
//if($width > 1000) { $pagesize -= 3; $short = FALSE; } else { $short = TRUE; }
case "syslog_alerts":
echo ' <div class="box box-solid" style="overflow: hidden; height: auto; max-height: 100%">';
echo ' <div class="box-header" style="cursor: hand;"><h3 class="box-title"><a href="/syslog_alerts/">Syslog Alerts</a></h3></div>';
echo ' <div class="box-content" style="overflow: hidden; overflow-x:scroll;">';
print_events(array('short' => TRUE, 'pagesize' => $pagesize, 'pageno' => 1,
'severity' => $config['frontpage']['eventlog']['severity']));
echo ' </div>';
echo '</div>';
break;
$short = !($width > 1000);
$alertlog_vars = array_merge($mod['vars'], [ 'short' => $short, 'pagesize' => ($height - 36) / 26 ]);
print_logalert_log($alertlog_vars);
echo ' </div>';
echo '</div>';
break;
case "alertlog":
echo ' <div class="box box-solid" style="overflow: hidden; height: auto; max-height: 100%">';
echo ' <div class="box-header" style="cursor: hand;"><h3 class="box-title"><a href="/alert_log/">Alert Log</a></h3></div>';
echo ' <div class="box-content" style="overflow: hidden; overflow-x:scroll;">';
$short = !($width > 1000);
$alertlog_vars = array_merge($mod['vars'], [ 'short' => $short, 'pagesize' => ($height - 36) / 26 ]);
print_alert_log($alertlog_vars);
echo ' </div>';
echo '</div>';
break;
case "eventlog":
echo ' <div class="box box-solid" style="overflow: hidden; height: auto; max-height: 100%">';
echo ' <div class="box-header" style="cursor: hand;"><h3 class="box-title"><a href="/eventlog/">Eventlog</a></h3></div>';
echo ' <div class="box-content" style="overflow: hidden; overflow-x:scroll;">';
$pagesize = floor(($height - 36) / 26);
$short = !($width > 1000);
$eventlog_vars = array_merge($mod['vars'], [ 'short' => $short, 'pagesize' => $pagesize, 'pageno' => 1,
'severity' => $config['frontpage']['eventlog']['severity'] ]);
print_events($eventlog_vars);
echo ' </div>';
echo '</div>';
break;
case "realtime":
echo ' <div class="box box-solid do-not-update" style="overflow: hidden;">';
$realtime_link = 'graph-realtime.php?type=bits&amp;id=430082&amp;interval=10';
case "realtime":
echo ' <div class="box box-solid do-not-update" style="overflow: hidden;">';
$realtime_link = 'graph-realtime.php?type=bits&amp;id=430082&amp;interval=10';
?>
<object data="<?php echo($realtime_link); ?>" type="image/svg+xml" width="<?php echo $width; ?>"
height="<?php echo $height; ?>">
<param name="src"
value="graph.php?type=bits&amp;id=<?php echo($port['port_id'] . "&amp;interval=" . $vars['interval']); ?>"/>
Your browser does not support SVG! You need to either use Firefox or Chrome, or download the Adobe SVG
plugin.
</object>
<?php
echo '</div>';
break;
?>
<object data="<?php echo($realtime_link); ?>" type="image/svg+xml" width="<?php echo $width; ?>"
height="<?php echo $height; ?>">
<param name="src"
value="graph.php?type=bits&amp;id=<?php echo($port['port_id'] . "&amp;interval=" . $vars['interval']); ?>"/>
Your browser does not support SVG! You need to either use Firefox or Chrome, or download the Adobe SVG
plugin.
</object>
<?php
echo '</div>';
break;
default:
echo '<div class="grid-stack-item-content box box-solid" style="overflow: hidden; justify-content: center; align-items: center;">';
echo ' <div class="box-content" style="overflow: hidden;">';
echo ' <h3 class="box-title">Unconfigured Module</h3>';
echo ' </div>';
echo '</div>';
break;
}
default:
//echo '</div>';
$widget_path = $config['html_dir'] . '/includes/widgets/' . $mod['widget_type'] . '.inc.php';
if (is_file($widget_path)) {
include($widget_path);
} else {
echo '<div class="grid-stack-item-content box box-solid" style="overflow: hidden; justify-content: center; align-items: center;">';
echo ' <div class="box-content" style="overflow: hidden;">';
echo ' <h3 class="box-title">Unconfigured Module</h3>';
echo ' </div>';
echo '</div>';
break;
}
}
//echo '</div>';
}
function print_dash_map ($vars, $width, $height)
function print_dash_map($mod, $width, $height)
{
global $config;
global $config;
?>
?>
<style type="text/css">
#map<?php echo $vars['widget_id']; ?> label {
#map<?php echo $mod['widget_id']; ?> label {
width: auto;
display: inline;
}
#map<?php echo $vars['widget_id']; ?> img {
#map<?php echo $mod['widget_id']; ?> img {
max-width: none;
}
#map<?php echo $vars['widget_id']; ?> {
#map<?php echo $mod['widget_id']; ?> {
height: 100%;
width: 100%;
}
</style>
<?php
<?php
echo '<div id="map'.$vars['widget_id'].'"></div>';
echo '<div id="map' . $mod['widget_id'] . '"></div>';
include($config['html_dir']. '/includes/map/leaflet.inc.php');
$vars = $mod['vars']; // set the $vars array to be used mostly by geojson
include($config['html_dir'] . '/includes/map/leaflet.inc.php');
} // End show_map
function print_dash_graph($mod, $width, $height) {
global $config;
$vars = $mod['vars'];
if (!isset($vars['type']))
{
echo '<div style="position: relative; top: 50%; transform: perspective(1px) translateY(-50%); width: 100%; text-align: center;">
<btn class="btn btn-primary" onclick="configWidget(' . $mod['widget_id'] . ')"><i class="icon-signal"/> &nbsp; Select Graph</btn>
</div>';
exit();
}
if (isset($vars['timestamp_from']) && preg_match(OBS_PATTERN_TIMESTAMP, $vars['timestamp_from'])) {
$vars['from'] = strtotime($vars['timestamp_from']);
unset($vars['timestamp_from']);
}
if (isset($vars['timestamp_to']) && preg_match(OBS_PATTERN_TIMESTAMP, $vars['timestamp_to'])) {
$vars['to'] = strtotime($vars['timestamp_to']);
unset($vars['timestamp_to']);
}
// Period alone is sufficient
/*
if (isset($vars['period']))
{
$vars['to'] = "now";
$vars['from'] = "-".$vars['period'];
}
if (!isset($vars['from']))
{
$vars['from'] = $config['time']['day'];
}
if (!isset($vars['to']))
{
$vars['to'] = $config['time']['now'];
}
*/
preg_match('/^(?P<type>[a-z0-9A-Z-]+)_(?P<subtype>.+)/', $vars['type'], $graphtype);
if (OBS_DEBUG) {
print_vars($graphtype);
}
$type = $graphtype['type'];
$subtype = $graphtype['subtype'];
if (is_numeric($vars['device'])) {
$device = device_by_id_cache($vars['device']);
} elseif (!empty($vars['device'])) {
$device = device_by_name($vars['device']);
} elseif ($type === "device" && is_numeric($vars['id'])) {
$device = device_by_id_cache($vars['id']);
}
$preserve_id = $vars['id'];
if (is_file($config['html_dir'] . "/includes/graphs/" . $type . "/auth.inc.php"))
{
include($config['html_dir'] . "/includes/graphs/" . $type . "/auth.inc.php");
}
$vars['id'] = $preserve_id;
if (!$auth) {
print_error_permission();
return;
}
if (isset($config['entities'][$type])) {
$entity = get_entity_by_id_cache($type, $vars['id']);
entity_rewrite($type, $entity);
}
if ($type === 'bgp') {
$entity = get_entity_by_id_cache('bgp_peer', $vars['id']);
entity_rewrite('bgp_peer', $entity);
}
//$device = device_by_id_cache($entity['device_id']);
//$graph_array['type'] = $vars['entity_type'] . '_' . $vars['graph_type'];
//$graph_array['id'] = $vars['entity_id'];
// Generate navbar with subtypes
$graph_array = $vars;
//$graph_array['from'] = '-1day';
//$graph_array['to'] = 'now';
$graph_array['width'] = $width - 76 + 14; // RRD graphs are 75px wider than request value
$graph_array['height'] = $height - 34; //68; // RRD graphs are taller than request value
if ($graph_array['width'] > 350)
{
$graph_array['width'] -= 6;
} // RRD graphs > 350px are 6 px wider because of larger legend font
if ($graph_array['width'] > 350)
{
$graph_array['height'] -= 6;
} // RRD graphs > 350px are 6 px taller because of larger legend font
$title_div = 'top:0px; left: 0px; padding: 4px; border-top-left-radius: 4px; border: 1px solid #e5e5e5; border-left: none; border-top: none; background-color: rgba(255, 255,255, 0.75); ';
$title_div = 'widget-title';
if ($height < 100)
{
$graph_array['height'] = $height;
$graph_array['width'] = $width;
$graph_array['graph_only'] = 'yes';
$title_div = 'top:5px; left: 5px; padding: none; border-radius: 2px; border: 1px solid #e5e5e5; background: rgba(255, 255, 255, 0.7);';
$title_div = 'widget-title-small';
} else {
$graph_array['draw_all'] = 'yes';
}
$t_len = $vars['width'] / 10;
$subtype_text = (isset($config['graph_types'][$type][$subtype]) ? $config['graph_types'][$type][$subtype]['descr'] : nicecase($subtype));
if (!isset($graph_array['title'])) {
if ($type === 'global')
{
$title = "Global :: " . $subtype_text;
} elseif (str_contains($type, "multi")) {
$count = safe_count($graph_array['id']);
$title = $count . ' ' . nicecase(str_replace("multi-", '', $type)) . ' :: ' . $subtype_text;
} else {
$title = device_name($device, $t_len / 2 - 2) . ($type === "device" ? ' :: ' : ' :: ' . truncate($entity['entity_shortname'], 32) . ' :: ' ) . $subtype_text;
}
} else {
$title = $graph_array['title'];
unset($graph_array['title']);
}
//$graph_array['format'] = 'png';
//$graph_array['img_id'] = generate_random_string(5);
//$graph_array['legend'] = 'no';
$graph_array['rigid_height'] = 'yes'; // Force height of graph to be same as height of graph_type.
$graph_array['class'] = 'image-refresh';
$graph = generate_graph_tag($graph_array, TRUE);
$link_array = $graph_array;
$link_array['page'] = "graphs";
unset($link_array['graph_only']);
unset($link_array['rigid_height']);
unset($link_array['height'], $link_array['width']);
$link = generate_url($link_array);
//echo ' <div class="box-header with-border">' . $device['hostname'] . '<span class="pull-right">' . truncate($entity['entity_name'], 32) . '</span></div>';
echo ' <div class="hover-hide ' . $title_div . '" style="z-index: 900; position: absolute; overflow: hidden;" class="widget-title"><h4 style="wwriting-mode: vertical-lr; ttext-orientation: mixed;" class="box-title">' .
'' . escape_html($title) . '</h4>' .
'</div>' . PHP_EOL;
echo ' <div class="box-content" style="overflow: hidden">';
echo '<div style="height:100%; overflow:hidden; width: 110%;">';
echo '<a href="'.$link.'">'.$graph['img_tag'].'</a>';
echo '</div>';
echo ' </div>';
}
// EOF