From 3650b12c75c4f302c5a14520f34369685137d9d6 Mon Sep 17 00:00:00 2001 From: Sean Mancini Date: Sun, 1 Mar 2026 18:49:19 -0500 Subject: [PATCH 01/26] PSR12 - First run Rename functions to match PSR12 requirements --- monitor.php | 308 ++++++++++++++++++++++----------------------- poller_monitor.php | 130 +++++++++---------- setup.php | 108 ++++++++-------- 3 files changed, 273 insertions(+), 273 deletions(-) diff --git a/monitor.php b/monitor.php index 7745aba..eb2c7ba 100644 --- a/monitor.php +++ b/monitor.php @@ -125,55 +125,55 @@ $_SESSION['monitor_muted_hosts'] = []; } -validate_request_vars(); +validateRequestVars(); if (!db_column_exists('host', 'monitor_icon')) { - monitor_setup_table(); + monitorSetupTable(); } -$thold_hosts = check_tholds(); +$thold_hosts = checkTholds(); switch(get_nfilter_request_var('action')) { case 'ajax_status': - ajax_status(); + ajaxStatus(); break; case 'ajax_mute_all': - mute_all_hosts(); - draw_page(); + muteAllHosts(); + drawPage(); break; case 'ajax_unmute_all': - unmute_all_hosts(); - draw_page(); + unmuteAllHosts(); + drawPage(); break; case 'dbchange': - load_dashboard_settings(); - draw_page(); + loadDashboardSettings(); + drawPage(); break; case 'remove': - remove_dashboard(); - draw_page(); + removeDashboard(); + drawPage(); break; case 'saveDb': - save_settings(); - draw_page(); + saveSettings(); + drawPage(); break; case 'save': - save_settings(); + saveSettings(); break; default: - draw_page(); + drawPage(); } exit; -function load_dashboard_settings() { +function loadDashboardSettings() { $dashboard = get_filter_request_var('dashboard'); if ($dashboard > 0) { @@ -197,11 +197,11 @@ function load_dashboard_settings() { } } -function draw_page() { +function drawPage() { global $config, $iclasses, $icolorsdisplay, $mon_zoom_state, $dozoomrefresh, $dozoombgndcolor, $font_sizes; global $new_form, $new_title; - $errored_list = get_hosts_down_or_triggered_by_permission(true); + $errored_list = getHostsDownOrTriggeredByPermission(true); if (cacti_sizeof($errored_list) && read_user_setting('monitor_error_zoom') == 'on') { if ($_SESSION['monitor_zoom_state'] == 0) { @@ -230,17 +230,17 @@ function draw_page() { $new_title = __('Create New Dashboard', 'monitor'); - find_down_hosts(); + findDownHosts(); general_header(); - draw_filter_and_status(); + drawFilterAndStatus(); print ''; // Default with permissions = default_by_permission // Tree = group_by_tree - $function = 'render_' . get_request_var('grouping'); + $function = 'render' . ucfirst(get_request_var('grouping')); if (function_exists($function) && get_request_var('view') != 'list') { if (get_request_var('grouping') == 'default' || get_request_var('grouping') == 'site') { @@ -250,7 +250,7 @@ function draw_page() { } print $function(); } else { - print render_default(); + print renderDefault(); } print ''; @@ -268,9 +268,9 @@ function draw_page() { } // If the host is down, we need to insert the embedded wav file - $monitor_sound = get_monitor_sound(); + $monitor_sound = getMonitorSound(); - if (is_monitor_audible()) { + if (isMonitorAudible()) { if (read_user_setting('monitor_sound_loop', read_config_option('monitor_sound_loop'))) { print ""; } else { @@ -278,16 +278,16 @@ function draw_page() { } } - print '
' . get_filter_text() . '
'; + print '
' . getFilterText() . '
'; bottom_footer(); } -function is_monitor_audible() { - return get_monitor_sound() != ''; +function isMonitorAudible() { + return getMonitorSound() != ''; } -function get_monitor_sound() { +function getMonitorSound() { $sound = read_user_setting('monitor_sound', read_config_option('monitor_sound')); clearstatcache(); $file = __DIR__ . '/sounds/' . $sound; @@ -296,8 +296,8 @@ function get_monitor_sound() { return $exists ? $sound : ''; } -function find_down_hosts() { - $dhosts = get_hosts_down_or_triggered_by_permission(false); +function findDownHosts() { + $dhosts = getHostsDownOrTriggeredByPermission(false); if (cacti_sizeof($dhosts)) { set_request_var('downhosts', 'true'); @@ -314,12 +314,12 @@ function find_down_hosts() { set_request_var('mute', 'false'); } } else { - unmute_all_hosts(); + unmuteAllHosts(); set_request_var('downhosts', 'false'); } } -function unmute_up_non_triggered_hosts($dhosts) { +function unmuteUpNonTriggeredHosts($dhosts) { if (isset($_SESSION['monitor_muted_hosts'])) { foreach ($_SESSION['monitor_muted_hosts'] as $index => $host_id) { if (array_search($host_id, $dhosts, true) === false) { @@ -329,27 +329,27 @@ function unmute_up_non_triggered_hosts($dhosts) { } } -function mute_all_hosts() { - $_SESSION['monitor_muted_hosts'] = get_hosts_down_or_triggered_by_permission(false); - mute_user(); +function muteAllHosts() { + $_SESSION['monitor_muted_hosts'] = getHostsDownOrTriggeredByPermission(false); + muteUser(); } -function unmute_all_hosts() { +function unmuteAllHosts() { $_SESSION['monitor_muted_hosts'] = []; - unmute_user(); + unmuteUser(); } -function mute_user() { +function muteUser() { set_request_var('mute', 'true'); set_user_setting('monitor_mute', 'true'); } -function unmute_user() { +function unmuteUser() { set_request_var('mute', 'false'); set_user_setting('monitor_mute','false'); } -function get_thold_where() { +function getTholdWhere() { if (get_request_var('status') == '2') { // breached return "(td.thold_enabled = 'on' AND (td.thold_alert != 0 OR td.bl_alert > 0))"; @@ -360,7 +360,7 @@ function get_thold_where() { } } -function check_tholds() { +function checkTholds() { $thold_hosts = []; if (api_plugin_is_enabled('thold')) { @@ -369,7 +369,7 @@ function check_tholds() { FROM thold_data AS td INNER JOIN data_local AS dl ON td.local_data_id=dl.id - WHERE ' . get_thold_where()), + WHERE ' . getTholdWhere()), 'host_id', 'host_id' ); } @@ -377,7 +377,7 @@ function check_tholds() { return $thold_hosts; } -function get_filter_text() { +function getFilterText() { $filter = '
'; switch(get_request_var('status')) { @@ -441,7 +441,7 @@ function get_filter_text() { return $filter; } -function draw_filter_dropdown($id, $title, $settings = [], $value = null) { +function drawFilterDropdown($id, $title, $settings = [], $value = null) { if ($value == null) { $value = get_nfilter_request_var($id); } @@ -466,7 +466,7 @@ function draw_filter_dropdown($id, $title, $settings = [], $value = null) { } } -function draw_filter_and_status() { +function drawFilterAndStatus() { global $criticalities, $page_refresh_interval, $classes, $monitor_grouping; global $monitor_view_type, $monitor_status, $monitor_trim; global $dozoombgndcolor, $dozoomrefresh, $zoom_hist_status, $zoom_hist_size, $mon_zoom_state; @@ -527,11 +527,11 @@ function draw_filter_and_status() { } } - draw_filter_dropdown('dashboard', __('Layout', 'monitor'), $dashboards); - draw_filter_dropdown('status', __('Status', 'monitor'), $monitor_status, $mon_zoom_status); - draw_filter_dropdown('view', __('View', 'monitor'), $monitor_view_type); - draw_filter_dropdown('grouping', __('Grouping', 'monitor'), $monitor_grouping); - draw_filter_dropdown('rows', __('Devices', 'monitor'), $item_rows); + drawFilterDropdown('dashboard', __('Layout', 'monitor'), $dashboards); + drawFilterDropdown('status', __('Status', 'monitor'), $monitor_status, $mon_zoom_status); + drawFilterDropdown('view', __('View', 'monitor'), $monitor_view_type); + drawFilterDropdown('grouping', __('Grouping', 'monitor'), $monitor_grouping); + drawFilterDropdown('rows', __('Devices', 'monitor'), $item_rows); // Buttons print '' . PHP_EOL; @@ -552,7 +552,7 @@ function draw_filter_and_status() { print '' . PHP_EOL; } - print '' . PHP_EOL; + print '' . PHP_EOL; print '' . PHP_EOL; print ''; print ''; @@ -564,14 +564,14 @@ function draw_filter_and_status() { print '' . __('Search', 'monitor') . ''; print ''; - draw_filter_dropdown('crit', __('Criticality', 'monitor'), $criticalities); + drawFilterDropdown('crit', __('Criticality', 'monitor'), $criticalities); if (get_request_var('view') != 'list') { - draw_filter_dropdown('size', __('Size', 'monitor'), $classes, $mon_zoom_size); + drawFilterDropdown('size', __('Size', 'monitor'), $classes, $mon_zoom_size); } if (get_request_var('view') == 'default' || get_request_var('view') == 'names') { - draw_filter_dropdown('trim', __('Trim', 'monitor'), $monitor_trim); + drawFilterDropdown('trim', __('Trim', 'monitor'), $monitor_trim); } if (get_nfilter_request_var('grouping') == 'tree') { @@ -588,7 +588,7 @@ function draw_filter_and_status() { } } - draw_filter_dropdown('tree', __('Tree', 'monitor'), $trees); + drawFilterDropdown('tree', __('Tree', 'monitor'), $trees); } if (get_nfilter_request_var('grouping') == 'site') { @@ -610,7 +610,7 @@ function draw_filter_and_status() { } } - draw_filter_dropdown('site', __('Sites', 'monitor'), $sites); + drawFilterDropdown('site', __('Sites', 'monitor'), $sites); } if (get_request_var('grouping') == 'template') { @@ -634,10 +634,10 @@ function draw_filter_and_status() { $templates = $templates_prefix + $templates_allowed + $templates_suffix; } - draw_filter_dropdown('template', __('Template', 'monitor'), $templates); + drawFilterDropdown('template', __('Template', 'monitor'), $templates); } - draw_filter_dropdown('refresh', __('Refresh', 'monitor'), $page_refresh_interval); + drawFilterDropdown('refresh', __('Refresh', 'monitor'), $page_refresh_interval); if (get_request_var('grouping') != 'tree') { print '' . PHP_EOL; @@ -1050,23 +1050,23 @@ function() { } -function get_mute_text() { - if (is_monitor_audible()) { +function getMuteText() { + if (isMonitorAudible()) { return __('Mute', 'monitor'); } else { return __('Acknowledge', 'monitor'); } } -function get_unmute_text() { - if (is_monitor_audible()) { +function getUnmuteText() { + if (isMonitorAudible()) { return __('Un-Mute', 'monitor'); } else { return __('Reset', 'monitor'); } } -function remove_dashboard() { +function removeDashboard() { $dashboard = get_filter_request_var('dashboard'); $name = db_fetch_cell_prepared('SELECT name @@ -1093,14 +1093,14 @@ function remove_dashboard() { set_request_var('dashboard', '0'); } -function save_settings() { +function saveSettings() { if (isset_request_var('dashboard') && get_filter_request_var('dashboard') != 0) { $save_db = true; } else { $save_db = false; } - validate_request_vars(); + validateRequestVars(); if (!$save_db) { if (cacti_sizeof($_REQUEST)) { @@ -1204,10 +1204,10 @@ function save_settings() { } } - validate_request_vars(true); + validateRequestVars(true); } -function validate_request_vars($force = false) { +function validateRequestVars($force = false) { // ================= input validation and session storage ================= $filters = [ 'refresh' => [ @@ -1309,7 +1309,7 @@ function validate_request_vars($force = false) { // ================= input validation ================= } -function render_group_concat(&$sql_where, $sql_join, $sql_field, $sql_data, $sql_suffix = '') { +function renderGroupConcat(&$sql_where, $sql_join, $sql_field, $sql_data, $sql_suffix = '') { // Remove empty entries if something was returned if (!empty($sql_data)) { $sql_data = trim(str_replace(',,',',',$sql_data), ','); @@ -1320,7 +1320,7 @@ function render_group_concat(&$sql_where, $sql_join, $sql_field, $sql_data, $sql } } -function render_where_join(&$sql_where, &$sql_join) { +function renderWhereJoin(&$sql_where, &$sql_join) { if (get_request_var('crit') > 0) { $awhere = 'h.monitor_criticality >= ' . get_request_var('crit'); } else { @@ -1350,7 +1350,7 @@ function render_where_join(&$sql_where, &$sql_join) { AND h.deleted = ""', [get_request_var('tree')]); - render_group_concat($awhere, ' AND ', 'h.id', $hlist); + renderGroupConcat($awhere, ' AND ', 'h.id', $hlist); } elseif (get_request_var('tree') == -2) { $hlist = db_fetch_cell('SELECT GROUP_CONCAT(DISTINCT h.id) FROM host AS h @@ -1359,7 +1359,7 @@ function render_where_join(&$sql_where, &$sql_join) { WHERE gti.host_id IS NULL AND h.deleted = ""'); - render_group_concat($awhere, ' AND ', 'h.id', $hlist); + renderGroupConcat($awhere, ' AND ', 'h.id', $hlist); } } @@ -1385,7 +1385,7 @@ function render_where_join(&$sql_where, &$sql_join) { AND h.monitor = "on" AND h.deleted = "" AND (h.status < 3 - OR ' . get_thold_where() . ' + OR ' . getTholdWhere() . ' OR ((h.availability_method > 0 OR h.snmp_version > 0) AND ((h.cur_time > h.monitor_warn AND h.monitor_warn > 0) OR (h.cur_time > h.monitor_alert AND h.monitor_alert > 0)) @@ -1421,7 +1421,7 @@ function render_where_join(&$sql_where, &$sql_join) { } // Render functions -function render_default() { +function renderDefault() { global $maxchars; $result = ''; @@ -1445,7 +1445,7 @@ function render_default() { $sql_order = get_order_string(); } - render_where_join($sql_where, $sql_join); + renderWhereJoin($sql_where, $sql_join); $poller_interval = read_config_option('poller_interval'); @@ -1486,9 +1486,9 @@ function render_default() { $sql_where"); } - $maxlen = get_monitor_trim_length($maxlen); + $maxlen = getMonitorTrimLength($maxlen); - $function = 'render_header_' . get_request_var('view'); + $function = 'renderHeader' . ucfirst(get_request_var('view')); if (function_exists($function)) { // Call the custom render_header_ function @@ -1499,13 +1499,13 @@ function render_default() { foreach ($hosts as $host) { if (is_device_allowed($host['id'])) { - $result .= render_host($host, true, $maxlen); + $result .= renderHost($host, true, $maxlen); } $count++; } - $function = 'render_footer_' . get_request_var('view'); + $function = 'renderFooter' . ucfirst(get_request_var('view')); if (function_exists($function)) { // Call the custom render_footer_ function @@ -1516,7 +1516,7 @@ function render_default() { return $result; } -function render_site() { +function renderSite() { global $maxchars; $result = ''; @@ -1535,7 +1535,7 @@ function render_site() { $rows = read_config_option('num_rows_table'); } - render_where_join($sql_where, $sql_join); + renderWhereJoin($sql_where, $sql_join); $sql_limit = ' LIMIT ' . ($rows * (get_request_var('page') - 1)) . ',' . $rows; @@ -1555,13 +1555,13 @@ function render_site() { if (cacti_sizeof($hosts)) { $suppressGroups = false; - $function = 'render_suppressgroups_' . get_request_var('view'); + $function = 'renderSuppressgroups' . ucfirst(get_request_var('view')); if (function_exists($function)) { $suppressGroups = $function($hosts); } - $function = 'render_header_' . get_request_var('view'); + $function = 'renderHeader' . ucfirst(get_request_var('view')); if (function_exists($function)) { // Call the custom render_header_ function @@ -1585,7 +1585,7 @@ function render_site() { FROM host AS h WHERE id IN (' . implode(',', $host_ids) . ')'); } - $maxlen = get_monitor_trim_length($maxlen); + $maxlen = getMonitorTrimLength($maxlen); $class = get_request_var('size'); $csuffix = get_request_var('view'); @@ -1612,7 +1612,7 @@ function render_site() { } } - $result .= render_host($host, true, $maxlen); + $result .= renderHost($host, true, $maxlen); if ($ctemp != $ptemp) { $ptemp = $ctemp; @@ -1623,7 +1623,7 @@ function render_site() { $result .= '
'; } - $function = 'render_footer_' . get_request_var('view'); + $function = 'renderFooter' . ucfirst(get_request_var('view')); if (function_exists($function)) { // Call the custom render_footer_ function @@ -1634,7 +1634,7 @@ function render_site() { return $result; } -function render_template() { +function renderTemplate() { global $maxchars; $result = ''; @@ -1653,7 +1653,7 @@ function render_template() { $rows = read_config_option('num_rows_table'); } - render_where_join($sql_where, $sql_join); + renderWhereJoin($sql_where, $sql_join); $sql_limit = ' LIMIT ' . ($rows * (get_request_var('page') - 1)) . ',' . $rows; @@ -1682,13 +1682,13 @@ function render_template() { if (cacti_sizeof($hosts)) { $suppressGroups = false; - $function = 'render_suppressgroups_' . get_request_var('view'); + $function = 'renderSuppressgroups' . ucfirst(get_request_var('view')); if (function_exists($function)) { $suppressGroups = $function($hosts); } - $function = 'render_header_' . get_request_var('view'); + $function = 'renderHeader' . ucfirst(get_request_var('view')); if (function_exists($function)) { // Call the custom render_header_ function @@ -1712,7 +1712,7 @@ function render_template() { FROM host AS h WHERE id IN (' . implode(',', $host_ids) . ')'); } - $maxlen = get_monitor_trim_length($maxlen); + $maxlen = getMonitorTrimLength($maxlen); $class = get_request_var('size'); $csuffix = get_request_var('view'); @@ -1739,7 +1739,7 @@ function render_template() { } } - $result .= render_host($host, true, $maxlen); + $result .= renderHost($host, true, $maxlen); if ($ctemp != $ptemp) { $ptemp = $ctemp; @@ -1750,7 +1750,7 @@ function render_template() { $result .= ''; } - $function = 'render_footer_' . get_request_var('view'); + $function = 'renderFooter' . ucfirst(get_request_var('view')); if (function_exists($function)) { // Call the custom render_footer_ function @@ -1761,7 +1761,7 @@ function render_template() { return $result; } -function render_tree() { +function renderTree() { global $maxchars; $result = ''; @@ -1780,7 +1780,7 @@ function render_tree() { $tree_list = []; } - $function = 'render_header_' . get_request_var('view'); + $function = 'renderHeader' . ucfirst(get_request_var('view')); if (function_exists($function)) { $hosts = []; @@ -1796,7 +1796,7 @@ function render_tree() { $tree_ids[$tree['id']] = $tree['id']; } - render_where_join($sql_where, $sql_join); + renderWhereJoin($sql_where, $sql_join); $branchWhost_SQL = ("SELECT DISTINCT gti.graph_tree_id, gti.parent FROM graph_tree_items AS gti @@ -1826,7 +1826,7 @@ function render_tree() { AND deleted = ''"); } - $maxlen = get_monitor_trim_length($maxlen); + $maxlen = getMonitorTrimLength($maxlen); if (cacti_sizeof($branchWhost)) { foreach ($branchWhost as $b) { @@ -1855,7 +1855,7 @@ function render_tree() { $sql_where = ''; $sql_join = ''; - render_where_join($sql_where, $sql_join); + renderWhereJoin($sql_where, $sql_join); $hosts_sql = "SELECT h.*, IFNULL(s.name,' " . __('Non-Site Device', 'monitor') . " ') AS site_name FROM host AS h @@ -1909,7 +1909,7 @@ function render_tree() { $result .= "
"; foreach ($hosts as $host) { - $result .= render_host($host, true, $maxlen); + $result .= renderHost($host, true, $maxlen); } $result .= '
'; @@ -1922,7 +1922,7 @@ function render_tree() { // begin others - lets get the monitor items that are not associated with any tree if (get_request_var('tree') < 0) { - $hosts = get_host_non_tree_array(); + $hosts = getHostNonTreeArray(); if (cacti_sizeof($hosts)) { foreach ($hosts as $index => $host) { @@ -1944,7 +1944,7 @@ function render_tree() { AND h.deleted = ''"); } } - $maxlen = get_monitor_trim_length($maxlen); + $maxlen = getMonitorTrimLength($maxlen); $result .= "
'; } } - $function = 'render_footer_' . get_request_var('view'); + $function = 'renderFooter' . ucfirst(get_request_var('view')); if (function_exists($function)) { // Call the custom render_footer_ function @@ -1971,7 +1971,7 @@ function render_tree() { return $result; } -function get_host_status($host, $real = false) { +function getHostStatus($host, $real = false) { global $thold_hosts, $iclasses; // If the host has been muted, show the muted Icon @@ -1996,7 +1996,7 @@ function get_host_status($host, $real = false) { return ($real || array_key_exists($host['status'], $iclasses)) ? $host['status'] : 0; } -function get_host_status_description($status) { +function getHostStatusDescription($status) { global $icolorsdisplay; if (array_key_exists($status, $icolorsdisplay)) { @@ -2012,7 +2012,7 @@ function get_host_status_description($status) { * @param mixed $float * @param mixed $maxlen */ -function render_host($host, $float = true, $maxlen = 10) { +function renderHost($host, $float = true, $maxlen = 10) { global $thold_hosts, $config, $icolorsdisplay, $iclasses, $classes, $maxchars, $mon_zoom_state; // throw out tree root items @@ -2031,17 +2031,17 @@ function render_host($host, $float = true, $maxlen = 10) { $host['anchor'] = $config['url_path'] . 'plugins/thold/thold_graph.php?action=thold&reset=true&status=1&host_id=' . $host['id']; } - $host['real_status'] = get_host_status($host, true); - $host['status'] = get_host_status($host); + $host['real_status'] = getHostStatus($host, true); + $host['status'] = getHostStatus($host); $host['iclass'] = $iclasses[$host['status']]; - $function = 'render_host_' . get_request_var('view'); + $function = 'renderHost' . ucfirst(get_request_var('view')); if (function_exists($function)) { // Call the custom render_host_ function $result = $function($host); } else { - $iclass = get_status_icon($host['status'], $host['monitor_icon']); + $iclass = getStatusIcon($host['status'], $host['monitor_icon']); $fclass = get_request_var('size'); $monitor_times = read_user_setting('monitor_uptime'); @@ -2071,7 +2071,7 @@ function render_host($host, $float = true, $maxlen = 10) { return $result; } -function get_status_icon($status, $icon) { +function getStatusIcon($status, $icon) { global $fa_icons; if (($status == 1 || ($status == 4 && get_request_var('status') > 0)) && read_user_setting('monitor_sound') == 'First Orders Suite.mp3') { @@ -2089,7 +2089,7 @@ function get_status_icon($status, $icon) { } } -function monitor_print_host_time($status_time, $seconds = false) { +function monitorPrintHostTime($status_time, $seconds = false) { // If the host is down, make a downtime since message $dt = ''; @@ -2116,12 +2116,12 @@ function monitor_print_host_time($status_time, $seconds = false) { return $dt; } -function ajax_status() { +function ajaxStatus() { global $thold_hosts, $config, $icolorsdisplay, $iclasses, $criticalities; $tholds = 0; - validate_request_vars(); + validateRequestVars(); if (isset_request_var('id') && get_filter_request_var('id')) { $id = get_request_var('id'); @@ -2149,8 +2149,8 @@ function ajax_status() { $host['status'] = 6; } - $host['real_status'] = get_host_status($host, true); - $host['status'] = get_host_status($host); + $host['real_status'] = getHostStatus($host, true); + $host['status'] = getHostStatus($host); if (cacti_sizeof($host)) { if (api_plugin_user_realm_auth('host.php')) { @@ -2233,7 +2233,7 @@ function ajax_status() { } $iclass = $iclasses[$host['status']]; - $sdisplay = get_host_status_description($host['real_status']); + $sdisplay = getHostStatusDescription($host['real_status']); $site = db_fetch_cell_prepared('SELECT name FROM sites WHERE id = ?', [$host['site_id']]); if ($host['location'] == '') { @@ -2297,19 +2297,19 @@ function ajax_status() { ' . ($host['snmp_version'] > 0 && ($host['status'] == 3 || $host['status'] == 2) ? ' ' . __('Agent Uptime:', 'monitor') . ' - ' . ($host['status'] == 3 || $host['status'] == 5 ? monitor_print_host_time($host['snmp_sysUpTimeInstance']) : __('N/A', 'monitor')) . " + ' . ($host['status'] == 3 || $host['status'] == 5 ? monitorPrintHostTime($host['snmp_sysUpTimeInstance']) : __('N/A', 'monitor')) . " " . __('Sys Description:', 'monitor') . ' - ' . html_escape(monitor_trim($host['snmp_sysDescr'])) . ' + ' . html_escape(monitorTrim($host['snmp_sysDescr'])) . ' ' . __('Location:', 'monitor') . ' - ' . html_escape(monitor_trim($host['snmp_sysLocation'])) . ' + ' . html_escape(monitorTrim($host['snmp_sysLocation'])) . ' ' . __('Contact:', 'monitor') . ' - ' . html_escape(monitor_trim($host['snmp_sysContact'])) . ' + ' . html_escape(monitorTrim($host['snmp_sysContact'])) . ' ' : '') . ($host['notes'] != '' ? ' ' . __('Notes:', 'monitor') . ' @@ -2322,27 +2322,27 @@ function ajax_status() { } } -function monitor_trim($string) { +function monitorTrim($string) { return trim($string, "\"'\\ \n\t\r"); } -function render_header_default($hosts) { +function renderHeaderDefault($hosts) { return "
"; } -function render_header_names($hosts) { +function renderHeaderNames($hosts) { return ""; } -function render_header_tiles($hosts) { - return render_header_default($hosts); +function renderHeaderTiles($hosts) { + return renderHeaderDefault($hosts); } -function render_header_tilesadt($hosts) { - return render_header_default($hosts); +function renderHeaderTilesadt($hosts) { + return renderHeaderDefault($hosts); } -function render_header_list($hosts, $total_rows = 0, $rows = 0) { +function renderHeaderList($hosts, $total_rows = 0, $rows = 0) { $display_text = [ 'hostname' => [ 'display' => __('Hostname', 'monitor'), @@ -2429,15 +2429,15 @@ function render_header_list($hosts, $total_rows = 0, $rows = 0) { return $output; } -function render_suppressgroups_list($hosts) { +function renderSuppressgroupsList($hosts) { return true; } -function render_footer_default($hosts) { +function renderFooterDefault($hosts) { return ''; } -function render_footer_names($hosts) { +function renderFooterNames($hosts) { $col = 7 - $_SESSION['names']; if ($col == 0) { @@ -2447,15 +2447,15 @@ function render_footer_names($hosts) { } } -function render_footer_tiles($hosts) { - return render_footer_default($hosts); +function renderFooterTiles($hosts) { + return renderFooterDefault($hosts); } -function render_footer_tilesadt($hosts) { - return render_footer_default($hosts); +function renderFooterTilesadt($hosts) { + return renderFooterDefault($hosts); } -function render_footer_list($hosts, $total_rows, $rows) { +function renderFooterList($hosts, $total_rows, $rows) { ob_start(); html_end_box(false); @@ -2473,7 +2473,7 @@ function render_footer_list($hosts, $total_rows, $rows) { return $output; } -function render_host_list($host) { +function renderHostList($host) { global $criticalities, $iclasses; if ($host['status'] < 2 || $host['status'] == 5) { @@ -2517,7 +2517,7 @@ function render_host_list($host) { $host_datefail = $host['status_fail_date']; $iclass = $iclasses[$host['status']]; - $sdisplay = get_host_status_description($host['real_status']); + $sdisplay = getHostStatusDescription($host['real_status']); $row_class = "{$iclass}Full"; @@ -2550,12 +2550,12 @@ function render_host_list($host) { return $result; } -function render_host_names($host) { +function renderHostNames($host) { $fclass = get_request_var('size'); $result = ''; - $maxlen = get_monitor_trim_length(100); + $maxlen = getMonitorTrimLength(100); $monitor_times = read_user_setting('monitor_uptime'); $monitor_time_html = ''; @@ -2579,8 +2579,8 @@ function render_host_names($host) { return $result; } -function render_host_tiles($host, $maxlen = 10) { - $class = get_status_icon($host['status'], $host['monitor_icon']); +function renderHostTiles($host, $maxlen = 10) { + $class = getStatusIcon($host['status'], $host['monitor_icon']); $fclass = get_request_var('size'); $result = "
"; @@ -2588,10 +2588,10 @@ function render_host_tiles($host, $maxlen = 10) { return $result; } -function render_host_tilesadt($host, $maxlen = 10) { +function renderHostTilesadt($host, $maxlen = 10) { $tis = ''; - $class = get_status_icon($host['status'], $host['monitor_icon']); + $class = getStatusIcon($host['status'], $host['monitor_icon']); $fclass = get_request_var('size'); if ($host['status'] < 2 || $host['status'] == 5) { @@ -2609,7 +2609,7 @@ function render_host_tilesadt($host, $maxlen = 10) { } } -function get_hosts_down_or_triggered_by_permission($prescan) { +function getHostsDownOrTriggeredByPermission($prescan) { global $render_style; $PreScanValue = 2; @@ -2635,7 +2635,7 @@ function get_hosts_down_or_triggered_by_permission($prescan) { AND graph_tree_id = ?', [get_request_var('tree')]); - render_group_concat($sql_add_where, ' OR ', 'h.id', $devices,'AND h.status < 2'); + renderGroupConcat($sql_add_where, ' OR ', 'h.id', $devices,'AND h.status < 2'); } } @@ -2644,17 +2644,17 @@ function get_hosts_down_or_triggered_by_permission($prescan) { FROM host AS h INNER JOIN thold_data AS td ON td.host_id = h.id - WHERE ' . get_thold_where() . ' + WHERE ' . getTholdWhere() . ' AND h.deleted = ""'); - render_group_concat($sql_add_where, ' OR ', 'h.id', $triggered, 'AND h.status > 1'); + renderGroupConcat($sql_add_where, ' OR ', 'h.id', $triggered, 'AND h.status > 1'); $_SESSION['monitor_triggered'] = array_rekey( db_fetch_assoc('SELECT td.host_id, COUNT(DISTINCT td.id) AS triggered FROM thold_data AS td INNER JOIN host AS h ON td.host_id = h.id - WHERE ' . get_thold_where() . ' + WHERE ' . getTholdWhere() . ' AND h.deleted = "" GROUP BY td.host_id'), 'host_id', 'triggered' @@ -2683,18 +2683,18 @@ function get_hosts_down_or_triggered_by_permission($prescan) { /* // This function is not used and contains an undefined variable -function get_host_tree_array() { +function getHostTreeArray() { return $leafs; } */ -function get_host_non_tree_array() { +function getHostNonTreeArray() { $leafs = []; $sql_where = ''; $sql_join = ''; - render_where_join($sql_where, $sql_join); + renderWhereJoin($sql_where, $sql_join); $hierarchy = db_fetch_assoc("SELECT DISTINCT h.*, gti.title, gti.host_id, gti.host_grouping_type, gti.graph_tree_id @@ -2719,7 +2719,7 @@ function get_host_non_tree_array() { return $leafs; } -function get_monitor_trim_length($fieldlen) { +function getMonitorTrimLength($fieldlen) { global $maxchars; if (get_request_var('view') == 'default' || get_request_var('view') == 'names') { diff --git a/poller_monitor.php b/poller_monitor.php index 433da8a..b2ca27f 100644 --- a/poller_monitor.php +++ b/poller_monitor.php @@ -61,12 +61,12 @@ case '--version': case '-V': case '-v': - display_version(); + displayVersion(); exit; case '--help': case '-H': case '-h': - display_help(); + displayHelp(); exit; case '--force': $force = true; @@ -78,15 +78,15 @@ break; default: print 'ERROR: Invalid Parameter ' . $parameter . PHP_EOL . PHP_EOL; - display_help(); + displayHelp(); exit; } } } -monitor_debug('Monitor Starting Checks'); +monitorDebug('Monitor Starting Checks'); -[$reboots, $recent_down] = monitor_uptime_checker(); +[$reboots, $recent_down] = monitorUptimeChecker(); $warning_criticality = read_config_option('monitor_warn_criticality'); $alert_criticality = read_config_option('monitor_alert_criticality'); @@ -98,45 +98,45 @@ $last_time = date('Y-m-d H:i:s', time() - read_config_option('monitor_resend_frequency') * 60); if ($warning_criticality > 0 || $alert_criticality > 0) { - monitor_debug('Monitor Notification Enabled for Devices'); + monitorDebug('Monitor Notification Enabled for Devices'); // Get hosts that are above threshold. Start with Alert, and then Warning if ($alert_criticality) { - get_hosts_by_list_type('alert', $alert_criticality, $global_list, $notify_list, $lists); + getHostsByListType('alert', $alert_criticality, $global_list, $notify_list, $lists); } if ($warning_criticality) { - get_hosts_by_list_type('warn', $warning_criticality, $global_list, $notify_list, $lists); + getHostsByListType('warn', $warning_criticality, $global_list, $notify_list, $lists); } - flatten_lists($global_list, $notify_list); + flattenLists($global_list, $notify_list); - monitor_debug('Lists Flattened there are ' . sizeof($global_list) . ' Global Notifications and ' . sizeof($notify_list) . ' Notification List Notifications.'); + monitorDebug('Lists Flattened there are ' . sizeof($global_list) . ' Global Notifications and ' . sizeof($notify_list) . ' Notification List Notifications.'); if (strlen(read_config_option('alert_email')) == 0) { - monitor_debug('WARNING: No Global List Defined. Please set under Settings -> Thresholds'); + monitorDebug('WARNING: No Global List Defined. Please set under Settings -> Thresholds'); cacti_log('WARNING: No Global Notification List defined. Please set under Settings -> Thresholds', false, 'MONITOR'); } if (cacti_sizeof($global_list) || sizeof($notify_list)) { // array of email[list|'g'] = true; - $notification_emails = get_emails_and_lists($lists); + $notification_emails = getEmailsAndLists($lists); // Send out emails to each emails address with all notifications in one if (cacti_sizeof($notification_emails)) { foreach ($notification_emails as $email => $lists) { - monitor_debug('Processing the email address: ' . $email); - process_email($email, $lists, $global_list, $notify_list); + monitorDebug('Processing the email address: ' . $email); + processEmail($email, $lists, $global_list, $notify_list); $notifications++; } } } } else { - monitor_debug('Both Warning and Alert Notification are Disabled.'); + monitorDebug('Both Warning and Alert Notification are Disabled.'); } -[$purge_n, $purge_r] = purge_event_records(); +[$purge_n, $purge_r] = purgeEventRecords(); $poller_end = microtime(true); @@ -152,7 +152,7 @@ exit; -function monitor_addemails(&$reboot_emails, $alert_emails, $host_id) { +function monitorAddEmails(&$reboot_emails, $alert_emails, $host_id) { if (cacti_sizeof($alert_emails)) { foreach ($alert_emails as $email) { $reboot_emails[trim(strtolower($email))][$host_id] = $host_id; @@ -160,17 +160,17 @@ function monitor_addemails(&$reboot_emails, $alert_emails, $host_id) { } } -function monitor_addnotificationlist(&$reboot_emails, $notify_list, $host_id, $notification_lists) { +function monitorAddNotificationList(&$reboot_emails, $notify_list, $host_id, $notification_lists) { if ($notify_list > 0) { if (isset($notification_lists[$notify_list])) { $emails = explode(',', $notification_lists[$notify_list]); - monitor_addemails($reboot_emails, $emails, $host_id); + monitorAddEmails($reboot_emails, $emails, $host_id); } } } -function monitor_uptime_checker() { - monitor_debug('Checking for Uptime of Devices'); +function monitorUptimeChecker() { + monitorDebug('Checking for Uptime of Devices'); $start = date('Y-m-d H:i:s'); @@ -243,7 +243,7 @@ function monitor_uptime_checker() { VALUES (?, ?)', [$host['id'], date('Y-m-d H:i:s', time() - intval($host['snmp_sysUpTimeInstance']))]); - monitor_addnotificationlist($reboot_emails, $monitor_list, $host['id'], $notification_lists); + monitorAddNotificationList($reboot_emails, $monitor_list, $host['id'], $notification_lists); if ($monitor_thold == 'on') { $notify = db_fetch_row_prepared('SELECT thold_send_email, thold_host_email @@ -256,17 +256,17 @@ function monitor_uptime_checker() { case '0': // Disabled break; case '1': // Global List - monitor_addemails($reboot_emails, $alert_emails, $host['id']); + monitorAddEmails($reboot_emails, $alert_emails, $host['id']); break; case '2': // Nofitication List - monitor_addnotificationlist($reboot_emails, $notify['thold_host_email'], + monitorAddNotificationList($reboot_emails, $notify['thold_host_email'], $host['id'], $notification_lists); break; case '3': // Both Global and Nofication list - monitor_addemails($reboot_emails, $alert_emails, $host['id']); - monitor_addnotificationlist($reboot_emails, $notify['thold_host_email'], + monitorAddEmails($reboot_emails, $alert_emails, $host['id']); + monitorAddNotificationList($reboot_emails, $notify['thold_host_email'], $host['id'], $notification_lists); break; @@ -284,17 +284,17 @@ function monitor_uptime_checker() { $to_email .= ($to_email != '' ? ',' : '') . $email; if ($monitor_send_one_email !== 'on') { - monitor_debug('Processing the Email address: ' . $email); - process_reboot_email($email, $hosts); + monitorDebug('Processing the Email address: ' . $email); + processRebootEmail($email, $hosts); } } else { - monitor_debug('Unable to process reboot notification due to empty Email address.'); + monitorDebug('Unable to process reboot notification due to empty Email address.'); } } if ($monitor_send_one_email == 'on') { - monitor_debug('Processing the Email address: ' . $to_email); - process_reboot_email($to_email, $hosts); + monitorDebug('Processing the Email address: ' . $to_email); + processRebootEmail($to_email, $hosts); } } } @@ -325,8 +325,8 @@ function monitor_uptime_checker() { return [cacti_sizeof($rebooted_hosts), $recent]; } -function process_reboot_email($email, $hosts) { - monitor_debug("Reboot Processing for $email starting"); +function processRebootEmail($email, $hosts) { + monitorDebug("Reboot Processing for $email starting"); $body_txt = ''; @@ -385,11 +385,11 @@ function process_reboot_email($email, $hosts) { $report_tag = ''; $theme = 'modern'; - monitor_debug('Loading Format File'); + monitorDebug('Loading Format File'); $format_ok = reports_load_format_file(read_config_option('monitor_format_file'), $output, $report_tag, $theme); - monitor_debug('Format File Loaded, Format is ' . ($format_ok ? 'Ok' : 'Not Ok') . ', Report Tag is ' . $report_tag); + monitorDebug('Format File Loaded, Format is ' . ($format_ok ? 'Ok' : 'Not Ok') . ', Report Tag is ' . $report_tag); if ($format_ok) { if ($report_tag) { @@ -401,7 +401,7 @@ function process_reboot_email($email, $hosts) { $output = $body; } - monitor_debug('HTML Processed'); + monitorDebug('HTML Processed'); if (defined('CACTI_VERSION')) { $version = CACTI_VERSION; @@ -413,14 +413,14 @@ function process_reboot_email($email, $hosts) { $status = 'Reboot Notifications'; - process_send_email($email, $subject, $output, $toutput, $headers, $status); + processSendEmail($email, $subject, $output, $toutput, $headers, $status); } } -function process_email($email, $lists, $global_list, $notify_list) { +function processEmail($email, $lists, $global_list, $notify_list) { global $config; - monitor_debug('Into Processing'); + monitorDebug('Into Processing'); $alert_hosts = []; $warn_hosts = []; @@ -460,24 +460,24 @@ function process_email($email, $lists, $global_list, $notify_list) { } } - monitor_debug('Lists Processed'); + monitorDebug('Lists Processed'); if (cacti_sizeof($alert_hosts)) { $alert_hosts = array_unique($alert_hosts, SORT_NUMERIC); - log_messages('alert', $alert_hosts); + logMessages('alert', $alert_hosts); } if (cacti_sizeof($warn_hosts)) { $warn_hosts = array_unique($warn_hosts, SORT_NUMERIC); - log_messages('warn', $alert_hosts); + logMessages('warn', $alert_hosts); } - monitor_debug('Found ' . sizeof($alert_hosts) . ' Alert Hosts, and ' . sizeof($warn_hosts) . ' Warn Hosts'); + monitorDebug('Found ' . sizeof($alert_hosts) . ' Alert Hosts, and ' . sizeof($warn_hosts) . ' Warn Hosts'); if (cacti_sizeof($alert_hosts) || sizeof($warn_hosts)) { - monitor_debug('Formatting Email'); + monitorDebug('Formatting Email'); $freq = read_config_option('monitor_resend_frequency'); $subject = __('Cacti Monitor Plugin Ping Threshold Notification', 'monitor'); @@ -605,11 +605,11 @@ function process_email($email, $lists, $global_list, $notify_list) { $report_tag = ''; $theme = 'modern'; - monitor_debug('Loading Format File'); + monitorDebug('Loading Format File'); $format_ok = reports_load_format_file(read_config_option('monitor_format_file'), $output, $report_tag, $theme); - monitor_debug('Format File Loaded, Format is ' . ($format_ok ? 'Ok' : 'Not Ok') . ', Report Tag is ' . $report_tag); + monitorDebug('Format File Loaded, Format is ' . ($format_ok ? 'Ok' : 'Not Ok') . ', Report Tag is ' . $report_tag); if ($format_ok) { if ($report_tag) { @@ -621,7 +621,7 @@ function process_email($email, $lists, $global_list, $notify_list) { $output = $body; } - monitor_debug('HTML Processed'); + monitorDebug('HTML Processed'); if (defined('CACTI_VERSION')) { $version = CACTI_VERSION; @@ -635,11 +635,11 @@ function process_email($email, $lists, $global_list, $notify_list) { (cacti_sizeof($warn_hosts) ? (cacti_sizeof($alert_hosts) ? ', and ' : '') . sizeof($warn_hosts) . ' Warning Notifications' : ''); - process_send_email($email, $subject, $output, $toutput, $headers, $status); + processSendEmail($email, $subject, $output, $toutput, $headers, $status); } } -function process_send_email($email, $subject, $output, $toutput, $headers, $status) { +function processSendEmail($email, $subject, $output, $toutput, $headers, $status) { $from_email = read_config_option('monitor_fromemail'); if ($from_email == '') { @@ -663,11 +663,11 @@ function process_send_email($email, $subject, $output, $toutput, $headers, $stat $html = true; if (read_config_option('thold_send_text_only') == 'on') { - $output = monitor_text($toutput); + $output = monitorText($toutput); $html = false; } - monitor_debug("Sending Email to '$email' for $status"); + monitorDebug("Sending Email to '$email' for $status"); $error = mailer( [$from_email, $from_name], @@ -677,13 +677,13 @@ function process_send_email($email, $subject, $output, $toutput, $headers, $stat '', $subject, $output, - monitor_text($toutput), + monitorText($toutput), null, $headers, $html ); - monitor_debug("The return from the mailer was '$error'"); + monitorDebug("The return from the mailer was '$error'"); if (strlen($error)) { cacti_log("WARNING: Monitor had problems sending to '$email' for $status. The error was '$error'", false, 'MONITOR'); @@ -692,7 +692,7 @@ function process_send_email($email, $subject, $output, $toutput, $headers, $stat } } -function monitor_text($output) { +function monitorText($output) { $output = explode(PHP_EOL, $output); $new_output = ''; @@ -709,7 +709,7 @@ function monitor_text($output) { return $new_output; } -function log_messages($type, $alert_hosts) { +function logMessages($type, $alert_hosts) { global $start_date; static $processed = []; @@ -738,7 +738,7 @@ function log_messages($type, $alert_hosts) { } } -function get_hosts_by_list_type($type, $criticality, &$global_list, &$notify_list, &$lists) { +function getHostsByListType($type, $criticality, &$global_list, &$notify_list, &$lists) { global $force; $last_time = date('Y-m-d H:i:s', time() - read_config_option('monitor_resend_frequency') * 60); @@ -811,7 +811,7 @@ function get_hosts_by_list_type($type, $criticality, &$global_list, &$notify_lis } } -function flatten_lists(&$global_list, &$notify_list) { +function flattenLists(&$global_list, &$notify_list) { if (cacti_sizeof($global_list)) { foreach ($global_list as $severity => $list) { foreach ($list as $item) { @@ -833,7 +833,7 @@ function flatten_lists(&$global_list, &$notify_list) { } } -function get_emails_and_lists($lists) { +function getEmailsAndLists($lists) { $notification_emails = []; $alert_email = read_config_option('alert_email'); @@ -873,7 +873,7 @@ function get_emails_and_lists($lists) { return $notification_emails; } -function purge_event_records() { +function purgeEventRecords() { // Purge old records $days = read_config_option('monitor_log_storage'); @@ -896,7 +896,7 @@ function purge_event_records() { return [$purge_n, $purge_r]; } -function monitor_debug($message) { +function monitorDebug($message) { global $debug; if ($debug) { @@ -904,14 +904,14 @@ function monitor_debug($message) { } } -function display_version() { +function displayVersion() { global $config; - if (!function_exists('plugin_monitor_version')) { + if (!function_exists('pluginMonitorVersion')) { include_once($config['base_path'] . '/plugins/monitor/setup.php'); } - $info = plugin_monitor_version(); + $info = pluginMonitorVersion(); print 'Cacti Monitor Poller, Version ' . $info['version'] . ', ' . COPYRIGHT_YEARS . PHP_EOL; } @@ -919,8 +919,8 @@ function display_version() { * display_help * displays the usage of the function */ -function display_help() { - display_version(); +function displayHelp() { + displayVersion(); print PHP_EOL; print 'usage: poller_monitor.php [--force] [--debug]' . PHP_EOL . PHP_EOL; diff --git a/setup.php b/setup.php index 8304a92..b978ee2 100644 --- a/setup.php +++ b/setup.php @@ -22,30 +22,30 @@ +-------------------------------------------------------------------------+ */ -function plugin_monitor_install() { +function pluginMonitorInstall() { // core plugin functionality - api_plugin_register_hook('monitor', 'top_header_tabs', 'monitor_show_tab', 'setup.php'); - api_plugin_register_hook('monitor', 'top_graph_header_tabs', 'monitor_show_tab', 'setup.php'); - api_plugin_register_hook('monitor', 'top_graph_refresh', 'monitor_top_graph_refresh', 'setup.php'); + api_plugin_register_hook('monitor', 'top_header_tabs', 'monitorShowTab', 'setup.php'); + api_plugin_register_hook('monitor', 'top_graph_header_tabs', 'monitorShowTab', 'setup.php'); + api_plugin_register_hook('monitor', 'top_graph_refresh', 'monitorTopGraphRefresh', 'setup.php'); - api_plugin_register_hook('monitor', 'draw_navigation_text', 'monitor_draw_navigation_text', 'setup.php'); - api_plugin_register_hook('monitor', 'config_form', 'monitor_config_form', 'setup.php'); - api_plugin_register_hook('monitor', 'config_settings', 'monitor_config_settings', 'setup.php'); - api_plugin_register_hook('monitor', 'config_arrays', 'monitor_config_arrays', 'setup.php'); - api_plugin_register_hook('monitor', 'poller_bottom', 'monitor_poller_bottom', 'setup.php'); - api_plugin_register_hook('monitor', 'page_head', 'plugin_monitor_page_head', 'setup.php'); + api_plugin_register_hook('monitor', 'draw_navigation_text', 'monitorDrawNavigationText', 'setup.php'); + api_plugin_register_hook('monitor', 'config_form', 'monitorConfigForm', 'setup.php'); + api_plugin_register_hook('monitor', 'config_settings', 'monitorConfigSettings', 'setup.php'); + api_plugin_register_hook('monitor', 'config_arrays', 'monitorConfigArrays', 'setup.php'); + api_plugin_register_hook('monitor', 'poller_bottom', 'monitorPollerBottom', 'setup.php'); + api_plugin_register_hook('monitor', 'page_head', 'pluginMonitorPageHead', 'setup.php'); // device actions and interaction - api_plugin_register_hook('monitor', 'api_device_save', 'monitor_api_device_save', 'setup.php'); - api_plugin_register_hook('monitor', 'device_action_array', 'monitor_device_action_array', 'setup.php'); - api_plugin_register_hook('monitor', 'device_action_execute', 'monitor_device_action_execute', 'setup.php'); - api_plugin_register_hook('monitor', 'device_action_prepare', 'monitor_device_action_prepare', 'setup.php'); - api_plugin_register_hook('monitor', 'device_remove', 'monitor_device_remove', 'setup.php'); + api_plugin_register_hook('monitor', 'api_device_save', 'monitorApiDeviceSave', 'setup.php'); + api_plugin_register_hook('monitor', 'device_action_array', 'monitorDeviceActionArray', 'setup.php'); + api_plugin_register_hook('monitor', 'device_action_execute', 'monitorDeviceActionExecute', 'setup.php'); + api_plugin_register_hook('monitor', 'device_action_prepare', 'monitorDeviceActionPrepare', 'setup.php'); + api_plugin_register_hook('monitor', 'device_remove', 'monitorDeviceRemove', 'setup.php'); // add new filter for device - api_plugin_register_hook('monitor', 'device_filters', 'monitor_device_filters', 'setup.php'); - api_plugin_register_hook('monitor', 'device_sql_where', 'monitor_device_sql_where', 'setup.php'); - api_plugin_register_hook('monitor', 'device_table_bottom', 'monitor_device_table_bottom', 'setup.php'); + api_plugin_register_hook('monitor', 'device_filters', 'monitorDeviceFilters', 'setup.php'); + api_plugin_register_hook('monitor', 'device_sql_where', 'monitorDeviceSqlWhere', 'setup.php'); + api_plugin_register_hook('monitor', 'device_table_bottom', 'monitorDeviceTableBottom', 'setup.php'); api_plugin_register_realm('monitor', 'monitor.php', 'View Monitoring Dashboard', 1); @@ -54,10 +54,10 @@ function plugin_monitor_install() { set_config_option('monitor_trim', '4000'); set_config_option('monitor_rows', 100); - monitor_setup_table(); + monitorSetupTable(); } -function monitor_device_filters($filters) { +function monitorDeviceFilters($filters) { $criticalities = [ '-1' => __('Any', 'monitor'), '0' => __('None', 'monitor'), @@ -80,7 +80,7 @@ function monitor_device_filters($filters) { return $filters; } -function monitor_device_sql_where($sql_where) { +function monitorDeviceSqlWhere($sql_where) { if (get_request_var('criticality') >= 0) { $sql_where .= ($sql_where != '' ? ' AND ' : 'WHERE ') . ' monitor_criticality = ' . get_request_var('criticality'); } @@ -88,7 +88,7 @@ function monitor_device_sql_where($sql_where) { return $sql_where; } -function monitor_device_table_bottom() { +function monitorDeviceTableBottom() { $criticalities = [ '-1' => __('Any', 'monitor'), '0' => __('None', 'monitor'), @@ -156,13 +156,13 @@ function monitor_device_table_bottom() { } } -function plugin_monitor_uninstall() { +function pluginMonitorUninstall() { db_execute('DROP TABLE IF EXISTS plugin_monitor_notify_history'); db_execute('DROP TABLE IF EXISTS plugin_monitor_reboot_history'); db_execute('DROP TABLE IF EXISTS plugin_monitor_uptime'); } -function plugin_monitor_page_head() { +function pluginMonitorPageHead() { global $config; print get_md5_include_css('plugins/monitor/monitor.css') . PHP_EOL; @@ -172,10 +172,10 @@ function plugin_monitor_page_head() { } } -function plugin_monitor_check_config() { +function pluginMonitorCheckConfig() { global $config; // Here we will check to ensure everything is configured - monitor_check_upgrade(); + monitorCheckUpgrade(); include_once($config['library_path'] . '/database.php'); $r = read_config_option('monitor_refresh'); @@ -187,28 +187,28 @@ function plugin_monitor_check_config() { return true; } -function plugin_monitor_upgrade() { +function pluginMonitorUpgrade() { // Here we will upgrade to the newest version - monitor_check_upgrade(); + monitorCheckUpgrade(); return false; } -function monitor_check_upgrade() { +function monitorCheckUpgrade() { $files = ['plugins.php', 'monitor.php']; if (isset($_SERVER['PHP_SELF']) && !in_array(basename($_SERVER['PHP_SELF']), $files, true)) { return; } - $info = plugin_monitor_version(); + $info = pluginMonitorVersion(); $current = $info['version']; $old = db_fetch_cell('SELECT version FROM plugin_config WHERE directory = "monitor"'); if ($current != $old) { - monitor_setup_table(); + monitorSetupTable(); - api_plugin_register_hook('monitor', 'page_head', 'plugin_monitor_page_head', 'setup.php', 1); + api_plugin_register_hook('monitor', 'page_head', 'pluginMonitorPageHead', 'setup.php', 1); db_execute('ALTER TABLE host MODIFY COLUMN monitor char(3) DEFAULT "on"'); @@ -235,14 +235,14 @@ function monitor_check_upgrade() { } } -function plugin_monitor_version() { +function pluginMonitorVersion() { global $config; $info = parse_ini_file($config['base_path'] . '/plugins/monitor/INFO', true); return $info['info']; } -function monitor_device_action_execute($action) { +function monitorDeviceActionExecute($action) { global $config, $fields_host_edit; if ($action != 'monitor_enable' && $action != 'monitor_disable' && $action != 'monitor_settings') { @@ -318,7 +318,7 @@ function monitor_device_action_execute($action) { return $action; } -function monitor_device_remove($devices) { +function monitorDeviceRemove($devices) { db_execute('DELETE FROM plugin_monitor_notify_history WHERE host_id IN(' . implode(',', $devices) . ')'); db_execute('DELETE FROM plugin_monitor_reboot_history WHERE host_id IN(' . implode(',', $devices) . ')'); db_execute('DELETE FROM plugin_monitor_uptime WHERE host_id IN(' . implode(',', $devices) . ')'); @@ -326,7 +326,7 @@ function monitor_device_remove($devices) { return $devices; } -function monitor_device_action_prepare($save) { +function monitorDeviceActionPrepare($save) { global $host_list, $fields_host_edit; if (!isset($save['drp_action'])) { @@ -395,7 +395,7 @@ function monitor_device_action_prepare($save) { } } -function monitor_device_action_array($device_action_array) { +function monitorDeviceActionArray($device_action_array) { $device_action_array['monitor_settings'] = __('Change Monitoring Options', 'monitor'); $device_action_array['monitor_enable'] = __('Enable Monitoring', 'monitor'); $device_action_array['monitor_disable'] = __('Disable Monitoring', 'monitor'); @@ -403,7 +403,7 @@ function monitor_device_action_array($device_action_array) { return $device_action_array; } -function monitor_scan_dir() { +function monitorScanDir() { global $config; $ext = ['.wav', '.mp3']; @@ -422,7 +422,7 @@ function monitor_scan_dir() { return $files; } -function monitor_config_settings() { +function monitorConfigSettings() { global $tabs, $formats, $settings, $criticalities, $page_refresh_interval, $config, $settings_user, $tabs_graphs; include_once($config['base_path'] . '/lib/reports.php'); @@ -472,7 +472,7 @@ function monitor_config_settings() { 'friendly_name' => __('Alarm Sound', 'monitor'), 'description' => __('This is the sound file that will be played when a Device goes down.', 'monitor'), 'method' => 'drop_array', - 'array' => monitor_scan_dir(), + 'array' => monitorScanDir(), 'default' => 'attn-noc.wav', ], 'monitor_sound_loop' => [ @@ -538,7 +538,7 @@ function monitor_config_settings() { 'friendly_name' => __('Alarm Sound', 'monitor'), 'description' => __('This is the sound file that will be played when a Device goes down.', 'monitor'), 'method' => 'drop_array', - 'array' => monitor_scan_dir(), + 'array' => monitorScanDir(), 'default' => 'attn-noc.wav', ], 'monitor_sound_loop' => [ @@ -711,7 +711,7 @@ function monitor_config_settings() { } } -function monitor_config_arrays() { +function monitorConfigArrays() { global $fa_icons; $fa_icons = [ @@ -790,10 +790,10 @@ function monitor_config_arrays() { $fa_icons = $nfa_icons; } - monitor_check_upgrade(); + monitorCheckUpgrade(); } -function monitor_top_graph_refresh($refresh) { +function monitorTopGraphRefresh($refresh) { if (get_current_page() != 'monitor.php') { return $refresh; } @@ -807,10 +807,10 @@ function monitor_top_graph_refresh($refresh) { return $r; } -function monitor_show_tab() { +function monitorShowTab() { global $config; - monitor_check_upgrade(); + monitorCheckUpgrade(); if (api_user_realm_auth('monitor.php')) { if (substr_count($_SERVER['REQUEST_URI'], 'monitor.php')) { @@ -821,7 +821,7 @@ function monitor_show_tab() { } } -function monitor_config_form() { +function monitorConfigForm() { global $config, $fields_host_edit, $criticalities, $fa_icons; $baselines = [ @@ -874,7 +874,7 @@ function monitor_config_form() { $host_id = get_nfilter_request_var('id'); if (empty($host_id) || !is_numeric($host_id)) { - $fields_host_edit3['monitor']['default'] = monitor_get_default($host_id); + $fields_host_edit3['monitor']['default'] = monitorGetDefault($host_id); } $fields_host_edit3['monitor_criticality'] = [ @@ -957,7 +957,7 @@ function monitor_config_form() { $fields_host_edit = $fields_host_edit3; } -function monitor_get_default($host_id) { +function monitorGetDefault($host_id) { $monitor_new_device = ''; if ($host_id <= 0) { @@ -967,10 +967,10 @@ function monitor_get_default($host_id) { return $monitor_new_device; } -function monitor_api_device_save($save) { +function monitorApiDeviceSave($save) { global $fa_icons; - $monitor_default = monitor_get_default($save['id']); + $monitor_default = monitorGetDefault($save['id']); if (isset_request_var('monitor')) { $save['monitor'] = form_input_validate(get_nfilter_request_var('monitor'), 'monitor', $monitor_default, true, 3); @@ -1033,13 +1033,13 @@ function monitor_api_device_save($save) { return $save; } -function monitor_draw_navigation_text($nav) { +function monitorDrawNavigationText($nav) { $nav['monitor.php:'] = ['title' => __('Monitoring', 'monitor'), 'mapping' => '', 'url' => 'monitor.php', 'level' => '0']; return $nav; } -function monitor_setup_table() { +function monitorSetupTable() { if (!db_table_exists('plugin_monitor_notify_history')) { db_execute("CREATE TABLE IF NOT EXISTS plugin_monitor_notify_history ( id int(10) unsigned NOT NULL AUTO_INCREMENT, @@ -1099,7 +1099,7 @@ function monitor_setup_table() { api_plugin_db_add_column('monitor', 'host', ['name' => 'monitor_icon', 'type' => 'varchar(30)', 'NULL' => false, 'default' => '', 'after' => 'monitor_alert']); } -function monitor_poller_bottom() { +function monitorPollerBottom() { global $config; if ($config['poller_id'] == 1) { From b7ebc7b622a33e4caadfc1d41a4a6e24085e3b27 Mon Sep 17 00:00:00 2001 From: Sean Mancini Date: Sun, 1 Mar 2026 18:59:00 -0500 Subject: [PATCH 02/26] PSR12 run 1 - Change tabs to spaces - add consts --- poller_monitor.php | 1430 ++++++++++++++++++++++---------------------- 1 file changed, 719 insertions(+), 711 deletions(-) diff --git a/poller_monitor.php b/poller_monitor.php index b2ca27f..89305c8 100644 --- a/poller_monitor.php +++ b/poller_monitor.php @@ -25,8 +25,8 @@ $dir = __DIR__; chdir($dir); -include('../../include/cli_check.php'); -include_once($config['base_path'] . '/lib/reports.php'); +include_once '../../include/cli_check.php'; +include_once $config['base_path'] . '/lib/reports.php'; // let PHP run just as long as it has to ini_set('max_execution_time', '0'); @@ -35,10 +35,15 @@ // record the start time $poller_start = microtime(true); -$start_date = date('Y-m-d H:i:s'); +$start_date = date(MONITOR_DATE_TIME_FORMAT); global $config, $database_default, $purged_r, $purged_n; +const MONITOR_DATE_TIME_FORMAT = 'Y-m-d H:i:s'; +const MONITOR_PING_NOTIFICATION_SUBJECT = 'Cacti Monitor Plugin Ping Threshold Notification'; +const MONITOR_ALERT_PING_LABEL = 'Alert Ping'; +const MONITOR_CURRENT_PING_LABEL = 'Current Ping'; + // process calling arguments $parms = $_SERVER['argv']; array_shift($parms); @@ -49,39 +54,39 @@ $purged_n = 0; if (cacti_sizeof($parms)) { - foreach ($parms as $parameter) { - if (strpos($parameter, '=')) { - [$arg, $value] = explode('=', $parameter); - } else { - $arg = $parameter; - $value = ''; - } - - switch ($arg) { - case '--version': - case '-V': - case '-v': - displayVersion(); - exit; - case '--help': - case '-H': - case '-h': - displayHelp(); - exit; - case '--force': - $force = true; - - break; - case '--debug': - $debug = true; - - break; - default: - print 'ERROR: Invalid Parameter ' . $parameter . PHP_EOL . PHP_EOL; - displayHelp(); - exit; - } - } + foreach ($parms as $parameter) { + if (strpos($parameter, '=')) { + [$arg, $value] = explode('=', $parameter); + } else { + $arg = $parameter; + $value = ''; + } + + switch ($arg) { + case '--version': + case '-V': + case '-v': + displayVersion(); + exit; + case '--help': + case '-H': + case '-h': + displayHelp(); + exit; + case '--force': + $force = true; + + break; + case '--debug': + $debug = true; + + break; + default: + print 'ERROR: Invalid Parameter ' . $parameter . PHP_EOL . PHP_EOL; + displayHelp(); + exit; + } + } } monitorDebug('Monitor Starting Checks'); @@ -95,45 +100,45 @@ $notifications = 0; $global_list = []; $notify_list = []; -$last_time = date('Y-m-d H:i:s', time() - read_config_option('monitor_resend_frequency') * 60); +$last_time = date(MONITOR_DATE_TIME_FORMAT, time() - read_config_option('monitor_resend_frequency') * 60); if ($warning_criticality > 0 || $alert_criticality > 0) { - monitorDebug('Monitor Notification Enabled for Devices'); + monitorDebug('Monitor Notification Enabled for Devices'); - // Get hosts that are above threshold. Start with Alert, and then Warning - if ($alert_criticality) { - getHostsByListType('alert', $alert_criticality, $global_list, $notify_list, $lists); - } + // Get hosts that are above threshold. Start with Alert, and then Warning + if ($alert_criticality) { + getHostsByListType('alert', $alert_criticality, $global_list, $notify_list, $lists); + } - if ($warning_criticality) { - getHostsByListType('warn', $warning_criticality, $global_list, $notify_list, $lists); - } + if ($warning_criticality) { + getHostsByListType('warn', $warning_criticality, $global_list, $notify_list, $lists); + } - flattenLists($global_list, $notify_list); + flattenLists($global_list, $notify_list); - monitorDebug('Lists Flattened there are ' . sizeof($global_list) . ' Global Notifications and ' . sizeof($notify_list) . ' Notification List Notifications.'); + monitorDebug('Lists Flattened there are ' . sizeof($global_list) . ' Global Notifications and ' . sizeof($notify_list) . ' Notification List Notifications.'); - if (strlen(read_config_option('alert_email')) == 0) { - monitorDebug('WARNING: No Global List Defined. Please set under Settings -> Thresholds'); - cacti_log('WARNING: No Global Notification List defined. Please set under Settings -> Thresholds', false, 'MONITOR'); - } + if (strlen(read_config_option('alert_email')) == 0) { + monitorDebug('WARNING: No Global List Defined. Please set under Settings -> Thresholds'); + cacti_log('WARNING: No Global Notification List defined. Please set under Settings -> Thresholds', false, 'MONITOR'); + } - if (cacti_sizeof($global_list) || sizeof($notify_list)) { - // array of email[list|'g'] = true; - $notification_emails = getEmailsAndLists($lists); + if (cacti_sizeof($global_list) || sizeof($notify_list)) { + // array of email[list|'g'] = true; + $notification_emails = getEmailsAndLists($lists); - // Send out emails to each emails address with all notifications in one - if (cacti_sizeof($notification_emails)) { - foreach ($notification_emails as $email => $lists) { - monitorDebug('Processing the email address: ' . $email); - processEmail($email, $lists, $global_list, $notify_list); + // Send out emails to each emails address with all notifications in one + if (cacti_sizeof($notification_emails)) { + foreach ($notification_emails as $email => $lists) { + monitorDebug('Processing the email address: ' . $email); + processEmail($email, $lists, $global_list, $notify_list); - $notifications++; - } - } - } + $notifications++; + } + } + } } else { - monitorDebug('Both Warning and Alert Notification are Disabled.'); + monitorDebug('Both Warning and Alert Notification are Disabled.'); } [$purge_n, $purge_r] = purgeEventRecords(); @@ -141,11 +146,11 @@ $poller_end = microtime(true); $stats = - 'Time:' . round($poller_end - $poller_start, 2) . - ' Reboots:' . $reboots . - ' DownDevices:' . $recent_down . - ' Notifications:' . $notifications . - ' Purges:' . ($purge_n + $purge_r); + 'Time:' . round($poller_end - $poller_start, 2) . + ' Reboots:' . $reboots . + ' DownDevices:' . $recent_down . + ' Notifications:' . $notifications . + ' Purges:' . ($purge_n + $purge_r); cacti_log('MONITOR STATS: ' . $stats, false, 'SYSTEM'); set_config_option('stats_monitor', $stats); @@ -153,766 +158,769 @@ exit; function monitorAddEmails(&$reboot_emails, $alert_emails, $host_id) { - if (cacti_sizeof($alert_emails)) { - foreach ($alert_emails as $email) { - $reboot_emails[trim(strtolower($email))][$host_id] = $host_id; - } - } + if (cacti_sizeof($alert_emails)) { + foreach ($alert_emails as $email) { + $reboot_emails[trim(strtolower($email))][$host_id] = $host_id; + } + } } function monitorAddNotificationList(&$reboot_emails, $notify_list, $host_id, $notification_lists) { - if ($notify_list > 0) { - if (isset($notification_lists[$notify_list])) { - $emails = explode(',', $notification_lists[$notify_list]); - monitorAddEmails($reboot_emails, $emails, $host_id); - } - } + if ($notify_list > 0 && isset($notification_lists[$notify_list])) { + $emails = explode(',', $notification_lists[$notify_list]); + monitorAddEmails($reboot_emails, $emails, $host_id); + } } function monitorUptimeChecker() { - monitorDebug('Checking for Uptime of Devices'); - - $start = date('Y-m-d H:i:s'); - - $reboot_emails = []; - - $alert_email = read_config_option('alert_email'); - - if ($alert_email != '') { - $alert_emails = explode(',', $alert_email); - } else { - $alert_emails = []; - } - - // Remove unneeded device records in associated tables - $removed_hosts = db_fetch_assoc('SELECT mu.host_id - FROM plugin_monitor_uptime AS mu - LEFT JOIN host AS h - ON h.id = mu.host_id - WHERE h.id IS NULL'); - - if (cacti_sizeof($removed_hosts)) { - db_execute('DELETE mu - FROM plugin_monitor_uptime AS mu - LEFT JOIN host AS h - ON h.id = mu.host_id - WHERE h.id IS NULL'); - } - - $removed_hosts = db_fetch_assoc('SELECT mu.host_id - FROM plugin_monitor_reboot_history AS mu - LEFT JOIN host AS h - ON h.id = mu.host_id - WHERE h.id IS NULL'); - - if (cacti_sizeof($removed_hosts)) { - db_execute('DELETE mu - FROM plugin_monitor_reboot_history AS mu - LEFT JOIN host AS h - ON h.id = mu.host_id - WHERE h.id IS NULL'); - } - - // Get the rebooted devices - $rebooted_hosts = db_fetch_assoc('SELECT h.id, h.description, - h.hostname, h.snmp_sysUpTimeInstance, mu.uptime - FROM host AS h - LEFT JOIN plugin_monitor_uptime AS mu - ON h.id = mu.host_id - WHERE h.snmp_version > 0 - AND status IN (2,3) - AND h.deleted = "" - AND h.monitor = "on" - AND (mu.uptime IS NULL OR mu.uptime > h.snmp_sysUpTimeInstance) - AND h.snmp_sysUpTimeInstance > 0'); - - if (cacti_sizeof($rebooted_hosts)) { - $notification_lists = array_rekey( - db_fetch_assoc('SELECT id, emails - FROM plugin_notification_lists - ORDER BY id'), - 'id', 'emails' - ); - - $monitor_list = read_config_option('monitor_list'); - $monitor_thold = read_config_option('monitor_reboot_thold'); - - foreach ($rebooted_hosts as $host) { - db_execute_prepared('INSERT INTO plugin_monitor_reboot_history - (host_id, reboot_time) - VALUES (?, ?)', - [$host['id'], date('Y-m-d H:i:s', time() - intval($host['snmp_sysUpTimeInstance']))]); - - monitorAddNotificationList($reboot_emails, $monitor_list, $host['id'], $notification_lists); - - if ($monitor_thold == 'on') { - $notify = db_fetch_row_prepared('SELECT thold_send_email, thold_host_email - FROM host - WHERE id = ?', - [$host['id']]); - - if (cacti_sizeof($notify)) { - switch($notify['thold_send_email']) { - case '0': // Disabled - break; - case '1': // Global List - monitorAddEmails($reboot_emails, $alert_emails, $host['id']); - - break; - case '2': // Nofitication List - monitorAddNotificationList($reboot_emails, $notify['thold_host_email'], - $host['id'], $notification_lists); - - break; - case '3': // Both Global and Nofication list - monitorAddEmails($reboot_emails, $alert_emails, $host['id']); - monitorAddNotificationList($reboot_emails, $notify['thold_host_email'], - $host['id'], $notification_lists); - - break; - } - } - } - } - - $monitor_send_one_email = read_config_option('monitor_send_one_email'); - $to_email = ''; - - if (cacti_sizeof($reboot_emails)) { - foreach ($reboot_emails as $email => $hosts) { - if ($email != '') { - $to_email .= ($to_email != '' ? ',' : '') . $email; - - if ($monitor_send_one_email !== 'on') { - monitorDebug('Processing the Email address: ' . $email); - processRebootEmail($email, $hosts); - } - } else { - monitorDebug('Unable to process reboot notification due to empty Email address.'); - } - } - - if ($monitor_send_one_email == 'on') { - monitorDebug('Processing the Email address: ' . $to_email); - processRebootEmail($to_email, $hosts); - } - } - } - - // Freshen the uptimes - db_execute('REPLACE INTO plugin_monitor_uptime - (host_id, uptime) - SELECT id, snmp_sysUpTimeInstance - FROM host - WHERE snmp_version > 0 - AND status IN(2,3) - AND deleted = "" - AND monitor = "on" - AND snmp_sysUpTimeInstance > 0'); - - // Log Recently Down - db_execute('INSERT IGNORE INTO plugin_monitor_notify_history - (host_id, notify_type, notification_time, notes) - SELECT h.id, "3" AS notify_type, status_fail_date AS notification_time, status_last_error AS notes - FROM host AS h - WHERE status = 1 - AND deleted = "" - AND monitor = "on" - AND status_event_count = 1'); - - $recent = db_affected_rows(); - - return [cacti_sizeof($rebooted_hosts), $recent]; + monitorDebug('Checking for Uptime of Devices'); + + $reboot_emails = []; + + $alert_email = read_config_option('alert_email'); + + if ($alert_email != '') { + $alert_emails = explode(',', $alert_email); + } else { + $alert_emails = []; + } + + // Remove unneeded device records in associated tables + $removed_hosts = db_fetch_assoc('SELECT mu.host_id + FROM plugin_monitor_uptime AS mu + LEFT JOIN host AS h + ON h.id = mu.host_id + WHERE h.id IS NULL'); + + if (cacti_sizeof($removed_hosts)) { + db_execute('DELETE mu + FROM plugin_monitor_uptime AS mu + LEFT JOIN host AS h + ON h.id = mu.host_id + WHERE h.id IS NULL'); + } + + $removed_hosts = db_fetch_assoc('SELECT mu.host_id + FROM plugin_monitor_reboot_history AS mu + LEFT JOIN host AS h + ON h.id = mu.host_id + WHERE h.id IS NULL'); + + if (cacti_sizeof($removed_hosts)) { + db_execute('DELETE mu + FROM plugin_monitor_reboot_history AS mu + LEFT JOIN host AS h + ON h.id = mu.host_id + WHERE h.id IS NULL'); + } + + // Get the rebooted devices + $rebooted_hosts = db_fetch_assoc('SELECT h.id, h.description, + h.hostname, h.snmp_sysUpTimeInstance, mu.uptime + FROM host AS h + LEFT JOIN plugin_monitor_uptime AS mu + ON h.id = mu.host_id + WHERE h.snmp_version > 0 + AND status IN (2,3) + AND h.deleted = "" + AND h.monitor = "on" + AND (mu.uptime IS NULL OR mu.uptime > h.snmp_sysUpTimeInstance) + AND h.snmp_sysUpTimeInstance > 0'); + + if (cacti_sizeof($rebooted_hosts)) { + $notification_lists = array_rekey( + db_fetch_assoc('SELECT id, emails + FROM plugin_notification_lists + ORDER BY id'), + 'id', 'emails' + ); + + $monitor_list = read_config_option('monitor_list'); + $monitor_thold = read_config_option('monitor_reboot_thold'); + + foreach ($rebooted_hosts as $host) { + db_execute_prepared('INSERT INTO plugin_monitor_reboot_history + (host_id, reboot_time) + VALUES (?, ?)', + [$host['id'], date(MONITOR_DATE_TIME_FORMAT, time() - intval($host['snmp_sysUpTimeInstance']))]); + + monitorAddNotificationList($reboot_emails, $monitor_list, $host['id'], $notification_lists); + + if ($monitor_thold == 'on') { + $notify = db_fetch_row_prepared('SELECT thold_send_email, thold_host_email + FROM host + WHERE id = ?', + [$host['id']]); + + if (cacti_sizeof($notify)) { + switch($notify['thold_send_email']) { + case '0': // Disabled + break; + case '1': // Global List + monitorAddEmails($reboot_emails, $alert_emails, $host['id']); + + break; + case '2': // Nofitication List + monitorAddNotificationList($reboot_emails, $notify['thold_host_email'], + $host['id'], $notification_lists); + + break; + case '3': // Both Global and Nofication list + monitorAddEmails($reboot_emails, $alert_emails, $host['id']); + monitorAddNotificationList($reboot_emails, $notify['thold_host_email'], + $host['id'], $notification_lists); + + break; + default: + break; + } + } + } + } + + $monitor_send_one_email = read_config_option('monitor_send_one_email'); + $to_email = ''; + + if (cacti_sizeof($reboot_emails)) { + foreach ($reboot_emails as $email => $hosts) { + if ($email != '') { + $to_email .= ($to_email != '' ? ',' : '') . $email; + + if ($monitor_send_one_email !== 'on') { + monitorDebug('Processing the Email address: ' . $email); + processRebootEmail($email, $hosts); + } + } else { + monitorDebug('Unable to process reboot notification due to empty Email address.'); + } + } + + if ($monitor_send_one_email == 'on') { + monitorDebug('Processing the Email address: ' . $to_email); + processRebootEmail($to_email, $hosts); + } + } + } + + // Freshen the uptimes + db_execute('REPLACE INTO plugin_monitor_uptime + (host_id, uptime) + SELECT id, snmp_sysUpTimeInstance + FROM host + WHERE snmp_version > 0 + AND status IN(2,3) + AND deleted = "" + AND monitor = "on" + AND snmp_sysUpTimeInstance > 0'); + + // Log Recently Down + db_execute('INSERT IGNORE INTO plugin_monitor_notify_history + (host_id, notify_type, notification_time, notes) + SELECT h.id, "3" AS notify_type, status_fail_date AS notification_time, status_last_error AS notes + FROM host AS h + WHERE status = 1 + AND deleted = "" + AND monitor = "on" + AND status_event_count = 1'); + + $recent = db_affected_rows(); + + return [cacti_sizeof($rebooted_hosts), $recent]; } function processRebootEmail($email, $hosts) { - monitorDebug("Reboot Processing for $email starting"); + monitorDebug("Reboot Processing for $email starting"); - $body_txt = ''; + $body_txt = ''; - $body = '
' . PHP_EOL; - $body .= '' . PHP_EOL; + $body = '
' . PHP_EOL; + $body .= '' . PHP_EOL; - $body .= - '' . - '' . PHP_EOL; + $body .= + '' . + '' . PHP_EOL; - $body .= '' . PHP_EOL; + $body .= '' . PHP_EOL; - foreach ($hosts as $host) { - $host = db_fetch_row_prepared('SELECT description, hostname - FROM host - WHERE id = ?', - [$host]); + foreach ($hosts as $host) { + $host = db_fetch_row_prepared('SELECT description, hostname + FROM host + WHERE id = ?', + [$host]); - if (cacti_sizeof($host)) { - $body .= '' . - '' . - '' . - '' . PHP_EOL; + if (cacti_sizeof($host)) { + $body .= '' . + '' . + '' . + '' . PHP_EOL; - $body_txt .= - __('Description: ', 'monitor') . $host['description'] . PHP_EOL . - __('Hostname: ', 'monitor') . $host['hostname'] . PHP_EOL . PHP_EOL; - } - } + $body_txt .= + __('Description: ', 'monitor') . $host['description'] . PHP_EOL . + __('Hostname: ', 'monitor') . $host['hostname'] . PHP_EOL . PHP_EOL; + } + } - $body .= '
' . __('Description', 'monitor') . '' . __('Hostname', 'monitor') . '' . __('Description', 'monitor') . '' . __('Hostname', 'monitor') . '
' . $host['description'] . '' . $host['hostname'] . '
' . $host['description'] . '' . $host['hostname'] . '
' . PHP_EOL; + $body .= '' . PHP_EOL; - $subject = read_config_option('monitor_subject'); - $monitor_send_one_email = read_config_option('monitor_send_one_email'); + $subject = read_config_option('monitor_subject'); + $monitor_send_one_email = read_config_option('monitor_send_one_email'); - if ($monitor_send_one_email == 'on') { - $subject .= ' ' . $host['description'] . ' (' . $host['hostname'] . ')'; - } else { - if (cacti_sizeof($hosts) == 1) { - $subject .= ' 1 device - ' . $host['description'] . ' (' . $host['hostname'] . ')'; - } else { - $subject .= ' ' . cacti_sizeof($hosts) . ' devices'; - } - } + if ($monitor_send_one_email == 'on') { + $subject .= ' ' . $host['description'] . ' (' . $host['hostname'] . ')'; + } else { + if (cacti_sizeof($hosts) == 1) { + $subject .= ' 1 device - ' . $host['description'] . ' (' . $host['hostname'] . ')'; + } else { + $subject .= ' ' . cacti_sizeof($hosts) . ' devices'; + } + } - $output = read_config_option('monitor_body'); - $output = str_replace('
', $body, $output) . PHP_EOL; + $output = read_config_option('monitor_body'); + $output = str_replace('
', $body, $output) . PHP_EOL; - if (strpos($output, '
') !== false) { - $toutput = str_replace('
', $body_txt, $output) . PHP_EOL; - } else { - $toutput = $body_txt; - } + if (strpos($output, '
') !== false) { + $toutput = str_replace('
', $body_txt, $output) . PHP_EOL; + } else { + $toutput = $body_txt; + } - if (read_config_option('monitor_reboot_notify') == 'on') { - $report_tag = ''; - $theme = 'modern'; + if (read_config_option('monitor_reboot_notify') == 'on') { + $report_tag = ''; + $theme = 'modern'; - monitorDebug('Loading Format File'); + monitorDebug('Loading Format File'); - $format_ok = reports_load_format_file(read_config_option('monitor_format_file'), $output, $report_tag, $theme); + $format_ok = reports_load_format_file(read_config_option('monitor_format_file'), $output, $report_tag, $theme); - monitorDebug('Format File Loaded, Format is ' . ($format_ok ? 'Ok' : 'Not Ok') . ', Report Tag is ' . $report_tag); + monitorDebug('Format File Loaded, Format is ' . ($format_ok ? 'Ok' : 'Not Ok') . ', Report Tag is ' . $report_tag); - if ($format_ok) { - if ($report_tag) { - $output = str_replace('', $body, $output); - } else { - $output = $output . PHP_EOL . $body; - } - } else { - $output = $body; - } + if ($format_ok) { + if ($report_tag) { + $output = str_replace('', $body, $output); + } else { + $output = $output . PHP_EOL . $body; + } + } else { + $output = $body; + } - monitorDebug('HTML Processed'); + monitorDebug('HTML Processed'); - if (defined('CACTI_VERSION')) { - $version = CACTI_VERSION; - } else { - $version = get_cacti_version(); - } + if (defined('CACTI_VERSION')) { + $version = CACTI_VERSION; + } else { + $version = get_cacti_version(); + } - $headers['User-Agent'] = 'Cacti-Monitor-v' . $version; + $headers['User-Agent'] = 'Cacti-Monitor-v' . $version; - $status = 'Reboot Notifications'; + $status = 'Reboot Notifications'; - processSendEmail($email, $subject, $output, $toutput, $headers, $status); - } + processSendEmail($email, $subject, $output, $toutput, $headers, $status); + } } function processEmail($email, $lists, $global_list, $notify_list) { - global $config; + global $config; + + monitorDebug('Into Processing'); + + $alert_hosts = []; + $warn_hosts = []; + + $criticalities = [ + 0 => __('Disabled', 'monnitor'), + 1 => __('Low', 'monnitor'), + 2 => __('Medium', 'monnitor'), + 3 => __('High', 'monnitor'), + 4 => __('Mission Critical', 'monnitor') + ]; + + foreach ($lists as $list) { + if ($list === 'global') { + if (isset($global_list['alert'])) { + $alert_hosts += explode(',', $global_list['alert']); + } - monitorDebug('Into Processing'); + if (isset($global_list['warn'])) { + $warn_hosts += explode(',', $global_list['warn']); + } + } else { + if (isset($notify_list[$list]['alert'])) { + $alert_hosts = explode(',', $notify_list[$list]['alert']); + } - $alert_hosts = []; - $warn_hosts = []; + if (isset($notify_list[$list]['warn'])) { + $warn_hosts = explode(',', $notify_list[$list]['warn']); + } + } + } - $criticalities = [ - 0 => __('Disabled', 'monnitor'), - 1 => __('Low', 'monnitor'), - 2 => __('Medium', 'monnitor'), - 3 => __('High', 'monnitor'), - 4 => __('Mission Critical', 'monnitor') - ]; + monitorDebug('Lists Processed'); - foreach ($lists as $list) { - switch($list) { - case 'global': - $hosts = []; + if (cacti_sizeof($alert_hosts)) { + $alert_hosts = array_unique($alert_hosts, SORT_NUMERIC); - if (isset($global_list['alert'])) { - $alert_hosts += explode(',', $global_list['alert']); - } + logMessages('alert', $alert_hosts); + } - if (isset($global_list['warn'])) { - $warn_hosts += explode(',', $global_list['warn']); - } + if (cacti_sizeof($warn_hosts)) { + $warn_hosts = array_unique($warn_hosts, SORT_NUMERIC); - break; - default: - if (isset($notify_list[$list]['alert'])) { - $alert_hosts = explode(',', $notify_list[$list]['alert']); - } + logMessages('warn', $alert_hosts); + } - if (isset($notify_list[$list]['warn'])) { - $warn_hosts = explode(',', $notify_list[$list]['warn']); - } + monitorDebug('Found ' . sizeof($alert_hosts) . ' Alert Hosts, and ' . sizeof($warn_hosts) . ' Warn Hosts'); - break; - } - } + if (cacti_sizeof($alert_hosts) || sizeof($warn_hosts)) { + monitorDebug('Formatting Email'); - monitorDebug('Lists Processed'); + $freq = read_config_option('monitor_resend_frequency'); + $subject = __(MONITOR_PING_NOTIFICATION_SUBJECT, 'monitor'); - if (cacti_sizeof($alert_hosts)) { - $alert_hosts = array_unique($alert_hosts, SORT_NUMERIC); + $body = '

' . __(MONITOR_PING_NOTIFICATION_SUBJECT, 'monitor') . '

' . PHP_EOL; + $body_txt = __(MONITOR_PING_NOTIFICATION_SUBJECT, 'monitor') . PHP_EOL; - logMessages('alert', $alert_hosts); - } + $body .= '

' . __('The following report will identify Devices that have eclipsed their ping latency thresholds. You are receiving this report since you are subscribed to a Device associated with the Cacti system located at the following URL below.') . '

' . PHP_EOL; - if (cacti_sizeof($warn_hosts)) { - $warn_hosts = array_unique($warn_hosts, SORT_NUMERIC); + $body_txt .= __('The following report will identify Devices that have eclipsed their ping latency thresholds. You are receiving this report since you are subscribed to a Device associated with the Cacti system located at the following URL below.') . PHP_EOL; - logMessages('warn', $alert_hosts); - } + $body .= '

Cacti Monitoring Site

' . PHP_EOL; - monitorDebug('Found ' . sizeof($alert_hosts) . ' Alert Hosts, and ' . sizeof($warn_hosts) . ' Warn Hosts'); + $body_txt .= __('Cacti Monitoring Site', 'monitor') . PHP_EOL; - if (cacti_sizeof($alert_hosts) || sizeof($warn_hosts)) { - monitorDebug('Formatting Email'); + if ($freq > 0) { + $body .= '

' . __('You will receive notifications every %d minutes if the Device is above its threshold.', $freq, 'monitor') . '

' . PHP_EOL; - $freq = read_config_option('monitor_resend_frequency'); - $subject = __('Cacti Monitor Plugin Ping Threshold Notification', 'monitor'); + $body_txt .= __('You will receive notifications every %d minutes if the Device is above its threshold.', $freq, 'monitor') . PHP_EOL; + } else { + $body .= '

' . __('You will receive notifications every time the Device is above its threshold.', 'monitor') . '

' . PHP_EOL; - $body = '

' . __('Cacti Monitor Plugin Ping Threshold Notification', 'monitor') . '

' . PHP_EOL; - $body_txt = __('Cacti Monitor Plugin Ping Threshold Notification', 'monitor') . PHP_EOL; + $body_txt .= __('You will receive notifications every time the Device is above its threshold.', 'monitor') . PHP_EOL; + } - $body .= '

' . __('The following report will identify Devices that have eclipsed their ping latency thresholds. You are receiving this report since you are subscribed to a Device associated with the Cacti system located at the following URL below.') . '

' . PHP_EOL; + if (cacti_sizeof($alert_hosts)) { + $body .= '

' . __('The following Devices have breached their Alert Notification Threshold.', 'monitor') . '

' . PHP_EOL; - $body_txt .= __('The following report will identify Devices that have eclipsed their ping latency thresholds. You are receiving this report since you are subscribed to a Device associated with the Cacti system located at the following URL below.') . PHP_EOL; + $body_txt .= __('The following Devices have breached their Alert Notification Threshold.', 'monitor') . PHP_EOL; - $body .= '

Cacti Monitoring Site

' . PHP_EOL; + $body .= '' . PHP_EOL; + $body .= '' . PHP_EOL; - $body_txt .= __('Cacti Monitoring Site', 'monitor') . PHP_EOL; + $body .= + '' . + '' . + '' . + '' . PHP_EOL; - if ($freq > 0) { - $body .= '

' . __('You will receive notifications every %d minutes if the Device is above its threshold.', $freq, 'monitor') . '

' . PHP_EOL; + $body_txt .= + __('Hostname', 'monitor') . "\t" . + __('Criticality', 'monitor') . "\t" . + __(MONITOR_ALERT_PING_LABEL, 'monitor') . "\t" . + __(MONITOR_CURRENT_PING_LABEL, 'monitor') . PHP_EOL; - $body_txt .= __('You will receive notifications every %d minutes if the Device is above its threshold.', $freq, 'monitor') . PHP_EOL; - } else { - $body .= '

' . __('You will receive notifications every time the Device is above its threshold.', 'monitor') . '

' . PHP_EOL; + $body .= '' . PHP_EOL; - $body_txt .= __('You will receive notifications every time the Device is above its threshold.', 'monitor') . PHP_EOL; - } + $hosts = db_fetch_assoc('SELECT * + FROM host + WHERE id IN(' . implode(',', $alert_hosts) . ') + AND deleted = ""'); - if (cacti_sizeof($alert_hosts)) { - $body .= '

' . __('The following Devices have breached their Alert Notification Threshold.', 'monitor') . '

' . PHP_EOL; + if (cacti_sizeof($hosts)) { + foreach ($hosts as $host) { + $body .= '' . PHP_EOL; + $body .= '' . PHP_EOL; - $body_txt .= __('The following Devices have breached their Alert Notification Threshold.', 'monitor') . PHP_EOL; + $body .= '' . PHP_EOL; + $body .= '' . PHP_EOL; + $body .= '' . PHP_EOL; - $body .= '
' . __('Hostname', 'monitor') . '' . __('Criticality', 'monitor') . '' . __(MONITOR_ALERT_PING_LABEL, 'monitor') . '' . __(MONITOR_CURRENT_PING_LABEL, 'monitor') . '
' . $host['description'] . '' . $criticalities[$host['monitor_criticality']] . '' . number_format_i18n($host['monitor_alert'],2) . ' ms' . number_format_i18n($host['cur_time'],2) . ' ms
' . PHP_EOL; - $body .= '' . PHP_EOL; + $body_txt .= + $host['description'] . "\t" . + $criticalities[$host['monitor_criticality']] . "\t" . + number_format_i18n($host['monitor_alert'],2) . " ms\t" . + number_format_i18n($host['cur_time'],2) . ' ms' . PHP_EOL; - $body .= - '' . - '' . - '' . - '' . PHP_EOL; + $body .= '' . PHP_EOL; + } + } - $body_txt .= - __('Hostname', 'monitor') . "\t" . - __('Criticality', 'monitor') . "\t" . - __('Alert Ping', 'monitor') . "\t" . - __('Current Ping', 'monitor') . PHP_EOL; + $body .= '
' . __('Hostname', 'monitor') . '' . __('Criticality', 'monitor') . '' . __('Alert Ping', 'monitor') . '' . __('Current Ping', 'monitor') . '
' . PHP_EOL; + } - $body .= '' . PHP_EOL; + if (cacti_sizeof($warn_hosts)) { + $body .= '

' . __('The following Devices have breached their Warning Notification Threshold.', 'monitor') . '

' . PHP_EOL; - $hosts = db_fetch_assoc('SELECT * - FROM host - WHERE id IN(' . implode(',', $alert_hosts) . ') - AND deleted = ""'); + $body_txt .= __('The following Devices have breached their Warning Notification Threshold.', 'monitor') . PHP_EOL; - if (cacti_sizeof($hosts)) { - foreach ($hosts as $host) { - $body .= '' . PHP_EOL; - $body .= '' . $host['description'] . '' . PHP_EOL; + $body .= '' . PHP_EOL; + $body .= '' . PHP_EOL; - $body .= '' . PHP_EOL; - $body .= '' . PHP_EOL; - $body .= '' . PHP_EOL; + $body .= + '' . + '' . + '' . + '' . PHP_EOL; - $body_txt .= - $host['description'] . "\t" . - $criticalities[$host['monitor_criticality']] . "\t" . - number_format_i18n($host['monitor_alert'],2) . " ms\t" . - number_format_i18n($host['cur_time'],2) . ' ms' . PHP_EOL; + $body_txt .= + __('Hostname', 'monitor') . "\t" . + __('Criticality', 'monitor') . "\t" . + __(MONITOR_ALERT_PING_LABEL, 'monitor') . "\t" . + __(MONITOR_CURRENT_PING_LABEL, 'monitor') . PHP_EOL; - $body .= '' . PHP_EOL; - } - } + $body .= '' . PHP_EOL; - $body .= '
' . $criticalities[$host['monitor_criticality']] . '' . number_format_i18n($host['monitor_alert'],2) . ' ms' . number_format_i18n($host['cur_time'],2) . ' ms' . __('Hostname', 'monitor') . '' . __('Criticality', 'monitor') . '' . __(MONITOR_ALERT_PING_LABEL, 'monitor') . '' . __(MONITOR_CURRENT_PING_LABEL, 'monitor') . '
' . PHP_EOL; - } + $hosts = db_fetch_assoc('SELECT * + FROM host + WHERE id IN(' . implode(',', $warn_hosts) . ') + AND deleted = ""'); - if (cacti_sizeof($warn_hosts)) { - $body .= '

' . __('The following Devices have breached their Warning Notification Threshold.', 'monitor') . '

' . PHP_EOL; + if (cacti_sizeof($hosts)) { + foreach ($hosts as $host) { + $body .= '' . PHP_EOL; + $body .= '' . $host['description'] . '' . PHP_EOL; - $body_txt .= __('The following Devices have breached their Warning Notification Threshold.', 'monitor') . PHP_EOL; + $body .= '' . $criticalities[$host['monitor_criticality']] . '' . PHP_EOL; + $body .= '' . number_format_i18n($host['monitor_warn'],2) . ' ms' . PHP_EOL; + $body .= '' . number_format_i18n($host['cur_time'],2) . ' ms' . PHP_EOL; - $body .= '' . PHP_EOL; - $body .= '' . PHP_EOL; + $body_txt .= + $host['description'] . "\t" . + $criticalities[$host['monitor_criticality']] . "\t" . + number_format_i18n($host['monitor_alert'],2) . " ms\t" . + number_format_i18n($host['cur_time'],2) . ' ms' . PHP_EOL; - $body .= - '' . - '' . - '' . - '' . PHP_EOL; + $body .= '' . PHP_EOL; + } + } + $body .= '
' . __('Hostname', 'monitor') . '' . __('Criticality', 'monitor') . '' . __('Alert Ping', 'monitor') . '' . __('Current Ping', 'monitor') . '
' . PHP_EOL; + } - $body_txt .= - __('Hostname', 'monitor') . "\t" . - __('Criticality', 'monitor') . "\t" . - __('Alert Ping', 'monitor') . "\t" . - __('Current Ping', 'monitor') . PHP_EOL; + $output = ''; + $toutput = $body_txt; + $report_tag = ''; + $theme = 'modern'; - $body .= '' . PHP_EOL; + monitorDebug('Loading Format File'); + + $format_ok = reports_load_format_file(read_config_option('monitor_format_file'), $output, $report_tag, $theme); + + monitorDebug('Format File Loaded, Format is ' . ($format_ok ? 'Ok' : 'Not Ok') . ', Report Tag is ' . $report_tag); + + if ($format_ok) { + if ($report_tag) { + $output = str_replace('', $body, $output); + } else { + $output = $output . PHP_EOL . $body; + } + } else { + $output = $body; + } - $hosts = db_fetch_assoc('SELECT * - FROM host - WHERE id IN(' . implode(',', $warn_hosts) . ') - AND deleted = ""'); + monitorDebug('HTML Processed'); - if (cacti_sizeof($hosts)) { - foreach ($hosts as $host) { - $body .= '' . PHP_EOL; - $body .= '' . $host['description'] . '' . PHP_EOL; + if (defined('CACTI_VERSION')) { + $version = CACTI_VERSION; + } else { + $version = get_cacti_version(); + } - $body .= '' . $criticalities[$host['monitor_criticality']] . '' . PHP_EOL; - $body .= '' . number_format_i18n($host['monitor_warn'],2) . ' ms' . PHP_EOL; - $body .= '' . number_format_i18n($host['cur_time'],2) . ' ms' . PHP_EOL; + $headers['User-Agent'] = 'Cacti-Monitor-v' . $version; + + $status = ''; - $body_txt .= - $host['description'] . "\t" . - $criticalities[$host['monitor_criticality']] . "\t" . - number_format_i18n($host['monitor_alert'],2) . " ms\t" . - number_format_i18n($host['cur_time'],2) . ' ms' . PHP_EOL; - - $body .= '' . PHP_EOL; - } - } - $body .= '' . PHP_EOL; - } + if (cacti_sizeof($alert_hosts)) { + $status = sizeof($alert_hosts) . ' Alert Notifications'; + } - $output = ''; - $toutput = $body_txt; - $report_tag = ''; - $theme = 'modern'; - - monitorDebug('Loading Format File'); - - $format_ok = reports_load_format_file(read_config_option('monitor_format_file'), $output, $report_tag, $theme); - - monitorDebug('Format File Loaded, Format is ' . ($format_ok ? 'Ok' : 'Not Ok') . ', Report Tag is ' . $report_tag); - - if ($format_ok) { - if ($report_tag) { - $output = str_replace('', $body, $output); - } else { - $output = $output . PHP_EOL . $body; - } - } else { - $output = $body; - } - - monitorDebug('HTML Processed'); + if (cacti_sizeof($warn_hosts)) { + if ($status !== '') { + $status .= ', and '; + } - if (defined('CACTI_VERSION')) { - $version = CACTI_VERSION; - } else { - $version = get_cacti_version(); - } - - $headers['User-Agent'] = 'Cacti-Monitor-v' . $version; - - $status = (cacti_sizeof($alert_hosts) ? sizeof($alert_hosts) . ' Alert Notifications' : '') . - (cacti_sizeof($warn_hosts) ? (cacti_sizeof($alert_hosts) ? ', and ' : '') . - sizeof($warn_hosts) . ' Warning Notifications' : ''); + $status .= sizeof($warn_hosts) . ' Warning Notifications'; + } - processSendEmail($email, $subject, $output, $toutput, $headers, $status); - } + processSendEmail($email, $subject, $output, $toutput, $headers, $status); + } } function processSendEmail($email, $subject, $output, $toutput, $headers, $status) { - $from_email = read_config_option('monitor_fromemail'); - - if ($from_email == '') { - $from_email = read_config_option('settings_from_email'); - - if ($from_email == '') { - $from_email = 'Cacti@cacti.net'; - } - } - - $from_name = read_config_option('monitor_fromname'); - - if ($from_name != '') { - $from_name = read_config_option('settings_from_name'); - - if ($from_name == '') { - $from_name = 'Cacti Reporting'; - } - } - - $html = true; - - if (read_config_option('thold_send_text_only') == 'on') { - $output = monitorText($toutput); - $html = false; - } - - monitorDebug("Sending Email to '$email' for $status"); - - $error = mailer( - [$from_email, $from_name], - $email, - '', - '', - '', - $subject, - $output, - monitorText($toutput), - null, - $headers, - $html - ); - - monitorDebug("The return from the mailer was '$error'"); - - if (strlen($error)) { - cacti_log("WARNING: Monitor had problems sending to '$email' for $status. The error was '$error'", false, 'MONITOR'); - } else { - cacti_log("NOTICE: Email Notification Sent to '$email' for $status.", false, 'MONITOR'); - } + $from_email = read_config_option('monitor_fromemail'); + + if ($from_email == '') { + $from_email = read_config_option('settings_from_email'); + + if ($from_email == '') { + $from_email = 'Cacti@cacti.net'; + } + } + + $from_name = read_config_option('monitor_fromname'); + + if ($from_name != '') { + $from_name = read_config_option('settings_from_name'); + + if ($from_name == '') { + $from_name = 'Cacti Reporting'; + } + } + + $html = true; + + if (read_config_option('thold_send_text_only') == 'on') { + $output = monitorText($toutput); + $html = false; + } + + monitorDebug("Sending Email to '$email' for $status"); + + $error = mailer( + [$from_email, $from_name], + $email, + '', + '', + '', + $subject, + $output, + monitorText($toutput), + null, + $headers, + $html + ); + + monitorDebug("The return from the mailer was '$error'"); + + if (strlen($error)) { + cacti_log("WARNING: Monitor had problems sending to '$email' for $status. The error was '$error'", false, 'MONITOR'); + } else { + cacti_log("NOTICE: Email Notification Sent to '$email' for $status.", false, 'MONITOR'); + } } function monitorText($output) { - $output = explode(PHP_EOL, $output); + $output = explode(PHP_EOL, $output); - $new_output = ''; + $new_output = ''; - if (cacti_sizeof($output)) { - foreach ($output as $line) { - $line = str_replace('
', PHP_EOL, $line); - $line = str_replace('
', PHP_EOL, $line); - $line = trim(strip_tags($line)); - $new_output .= $line . PHP_EOL; - } - } + if (cacti_sizeof($output)) { + foreach ($output as $line) { + $line = str_replace('
', PHP_EOL, $line); + $line = str_replace('
', PHP_EOL, $line); + $line = trim(strip_tags($line)); + $new_output .= $line . PHP_EOL; + } + } - return $new_output; + return $new_output; } function logMessages($type, $alert_hosts) { - global $start_date; - - static $processed = []; - - if ($type == 'warn') { - $type = '0'; - $column = 'monitor_warn'; - } elseif ($type == 'alert') { - $type = '1'; - $column = 'monitor_alert'; - } - - foreach ($alert_hosts as $id) { - if (!isset($processed[$id])) { - db_execute_prepared("INSERT INTO plugin_monitor_notify_history - (host_id, notify_type, ping_time, ping_threshold, notification_time) - SELECT id, '$type' AS notify_type, cur_time, $column, '$start_date' AS notification_time - FROM host - WHERE deleted = '' - AND monitor = 'on' - AND id = ?", - [$id]); - } - - $processed[$id] = true; - } + global $start_date; + + static $processed = []; + + if ($type == 'warn') { + $type = '0'; + $column = 'monitor_warn'; + } elseif ($type == 'alert') { + $type = '1'; + $column = 'monitor_alert'; + } + + foreach ($alert_hosts as $id) { + if (!isset($processed[$id])) { + db_execute_prepared("INSERT INTO plugin_monitor_notify_history + (host_id, notify_type, ping_time, ping_threshold, notification_time) + SELECT id, '$type' AS notify_type, cur_time, $column, '$start_date' AS notification_time + FROM host + WHERE deleted = '' + AND monitor = 'on' + AND id = ?", + [$id]); + } + + $processed[$id] = true; + } } function getHostsByListType($type, $criticality, &$global_list, &$notify_list, &$lists) { - global $force; - - $last_time = date('Y-m-d H:i:s', time() - read_config_option('monitor_resend_frequency') * 60); - - $hosts = db_fetch_cell_prepared("SELECT COUNT(*) - FROM host - WHERE status = 3 - AND deleted = '' - AND monitor = 'on' - AND thold_send_email > 0 - AND monitor_criticality >= ? - AND cur_time > monitor_$type", - [$criticality]); - - if ($type == 'warn') { - $htype = 1; - } else { - $htype = 0; - } - - if ($hosts > 0) { - $groups = db_fetch_assoc_prepared("SELECT - thold_send_email, thold_host_email, GROUP_CONCAT(host.id) AS id - FROM host - LEFT JOIN ( - SELECT host_id, MAX(notification_time) AS notification_time - FROM plugin_monitor_notify_history - WHERE notify_type = ? - GROUP BY host_id - ) AS nh - ON host.id=nh.host_id - WHERE status = 3 - AND deleted = '' - AND monitor = 'on' - AND thold_send_email > 0 - AND monitor_criticality >= ? - AND cur_time > monitor_$type " . ($type == 'warn' ? ' AND cur_time < monitor_alert' : '') . ' - AND (notification_time < ? OR notification_time IS NULL) - AND host.total_polls > 1 - GROUP BY thold_host_email, thold_send_email - ORDER BY thold_host_email, thold_send_email', - [$htype, $criticality, $last_time]); - - if (cacti_sizeof($groups)) { - foreach ($groups as $entry) { - switch($entry['thold_send_email']) { - case '1': // Global List - $global_list[$type][] = $entry; - - break; - case '2': // Notification List - if ($entry['thold_host_email'] > 0) { - $notify_list[$type][$entry['thold_host_email']][] = $entry; - $lists[$entry['thold_host_email']] = $entry['thold_host_email']; - } - - break; - case '3': // Both Notification and Global - $global_list[$type][] = $entry; - - if ($entry['thold_host_email'] > 0) { - $notify_list[$type][$entry['thold_host_email']][] = $entry; - $lists[$entry['thold_host_email']] = $entry['thold_host_email']; - } - - break; - } - } - } - } + global $force; + + $last_time = date(MONITOR_DATE_TIME_FORMAT, time() - read_config_option('monitor_resend_frequency') * 60); + + $hosts = db_fetch_cell_prepared("SELECT COUNT(*) + FROM host + WHERE status = 3 + AND deleted = '' + AND monitor = 'on' + AND thold_send_email > 0 + AND monitor_criticality >= ? + AND cur_time > monitor_$type", + [$criticality]); + + if ($type == 'warn') { + $htype = 1; + } else { + $htype = 0; + } + + if ($hosts > 0) { + $groups = db_fetch_assoc_prepared("SELECT + thold_send_email, thold_host_email, GROUP_CONCAT(host.id) AS id + FROM host + LEFT JOIN ( + SELECT host_id, MAX(notification_time) AS notification_time + FROM plugin_monitor_notify_history + WHERE notify_type = ? + GROUP BY host_id + ) AS nh + ON host.id=nh.host_id + WHERE status = 3 + AND deleted = '' + AND monitor = 'on' + AND thold_send_email > 0 + AND monitor_criticality >= ? + AND cur_time > monitor_$type " . ($type == 'warn' ? ' AND cur_time < monitor_alert' : '') . ' + AND (notification_time < ? OR notification_time IS NULL) + AND host.total_polls > 1 + GROUP BY thold_host_email, thold_send_email + ORDER BY thold_host_email, thold_send_email', + [$htype, $criticality, $last_time]); + + if (cacti_sizeof($groups)) { + foreach ($groups as $entry) { + switch($entry['thold_send_email']) { + case '1': // Global List + $global_list[$type][] = $entry; + + break; + case '2': // Notification List + if ($entry['thold_host_email'] > 0) { + $notify_list[$type][$entry['thold_host_email']][] = $entry; + $lists[$entry['thold_host_email']] = $entry['thold_host_email']; + } + + break; + case '3': // Both Notification and Global + $global_list[$type][] = $entry; + + if ($entry['thold_host_email'] > 0) { + $notify_list[$type][$entry['thold_host_email']][] = $entry; + $lists[$entry['thold_host_email']] = $entry['thold_host_email']; + } + + break; + default: + break; + } + } + } + } } function flattenLists(&$global_list, &$notify_list) { - if (cacti_sizeof($global_list)) { - foreach ($global_list as $severity => $list) { - foreach ($list as $item) { - $new_global[$severity] = (isset($new_global[$severity]) ? $new_global[$severity] . ',' : '') . $item['id']; - } - } - $global_list = $new_global; - } - - if (cacti_sizeof($notify_list)) { - foreach ($notify_list as $severity => $lists) { - foreach ($lists as $id => $list) { - foreach ($list as $item) { - $new_list[$severity][$id] = (isset($new_list[$severity][$id]) ? $new_list[$severity][$id] . ',' : '') . $item['id']; - } - } - } - $notify_list = $new_list; - } + if (cacti_sizeof($global_list)) { + foreach ($global_list as $severity => $list) { + foreach ($list as $item) { + $new_global[$severity] = (isset($new_global[$severity]) ? $new_global[$severity] . ',' : '') . $item['id']; + } + } + $global_list = $new_global; + } + + if (cacti_sizeof($notify_list)) { + foreach ($notify_list as $severity => $lists) { + foreach ($lists as $id => $list) { + foreach ($list as $item) { + $new_list[$severity][$id] = (isset($new_list[$severity][$id]) ? $new_list[$severity][$id] . ',' : '') . $item['id']; + } + } + } + $notify_list = $new_list; + } } function getEmailsAndLists($lists) { - $notification_emails = []; - - $alert_email = read_config_option('alert_email'); - - if ($alert_email != '') { - $global_emails = explode(',', $alert_email); - } else { - $global_emails = []; - } - - if (cacti_sizeof($global_emails)) { - foreach ($global_emails as $index => $user) { - if (trim($user) != '') { - $notification_emails[trim($user)]['global'] = true; - } - } - } - - if (cacti_sizeof($lists)) { - $list_emails = db_fetch_assoc('SELECT id, emails - FROM plugin_notification_lists - WHERE id IN (' . implode(',', $lists) . ')'); - - if (cacti_sizeof($list_emails)) { - foreach ($list_emails as $email) { - $emails = explode(',', $email['emails']); - - foreach ($emails as $user) { - if (trim($user) != '') { - $notification_emails[trim($user)][$email['id']] = true; - } - } - } - } - } - - return $notification_emails; + $notification_emails = []; + + $alert_email = read_config_option('alert_email'); + + if ($alert_email != '') { + $global_emails = explode(',', $alert_email); + } else { + $global_emails = []; + } + + if (cacti_sizeof($global_emails)) { + foreach ($global_emails as $user) { + if (trim($user) != '') { + $notification_emails[trim($user)]['global'] = true; + } + } + } + + if (cacti_sizeof($lists)) { + $list_emails = db_fetch_assoc('SELECT id, emails + FROM plugin_notification_lists + WHERE id IN (' . implode(',', $lists) . ')'); + + if (cacti_sizeof($list_emails)) { + foreach ($list_emails as $email) { + $emails = explode(',', $email['emails']); + + foreach ($emails as $user) { + if (trim($user) != '') { + $notification_emails[trim($user)][$email['id']] = true; + } + } + } + } + } + + return $notification_emails; } function purgeEventRecords() { - // Purge old records - $days = read_config_option('monitor_log_storage'); + // Purge old records + $days = read_config_option('monitor_log_storage'); - if (empty($days)) { - $days = 120; - } + if (empty($days)) { + $days = 120; + } - db_execute_prepared('DELETE FROM plugin_monitor_notify_history - WHERE notification_time < FROM_UNIXTIME(UNIX_TIMESTAMP() - (? * 86400))', - [$days]); + db_execute_prepared('DELETE FROM plugin_monitor_notify_history + WHERE notification_time < FROM_UNIXTIME(UNIX_TIMESTAMP() - (? * 86400))', + [$days]); - $purge_n = db_affected_rows(); + $purge_n = db_affected_rows(); - db_execute_prepared('DELETE FROM plugin_monitor_reboot_history - WHERE log_time < FROM_UNIXTIME(UNIX_TIMESTAMP() - (? * 86400))', - [$days]); + db_execute_prepared('DELETE FROM plugin_monitor_reboot_history + WHERE log_time < FROM_UNIXTIME(UNIX_TIMESTAMP() - (? * 86400))', + [$days]); - $purge_r = db_affected_rows(); + $purge_r = db_affected_rows(); - return [$purge_n, $purge_r]; + return [$purge_n, $purge_r]; } function monitorDebug($message) { - global $debug; + global $debug; - if ($debug) { - print trim($message) . PHP_EOL; - } + if ($debug) { + print trim($message) . PHP_EOL; + } } function displayVersion() { - global $config; + global $config; - if (!function_exists('pluginMonitorVersion')) { - include_once($config['base_path'] . '/plugins/monitor/setup.php'); - } + if (!function_exists('pluginMonitorVersion')) { + include_once $config['base_path'] . '/plugins/monitor/setup.php'; + } - $info = pluginMonitorVersion(); - print 'Cacti Monitor Poller, Version ' . $info['version'] . ', ' . COPYRIGHT_YEARS . PHP_EOL; + $info = pluginMonitorVersion(); + print 'Cacti Monitor Poller, Version ' . $info['version'] . ', ' . COPYRIGHT_YEARS . PHP_EOL; } /* @@ -920,10 +928,10 @@ function displayVersion() { * displays the usage of the function */ function displayHelp() { - displayVersion(); + displayVersion(); - print PHP_EOL; - print 'usage: poller_monitor.php [--force] [--debug]' . PHP_EOL . PHP_EOL; - print ' --force - force execution, e.g. for testing' . PHP_EOL; - print ' --debug - debug execution, e.g. for testing' . PHP_EOL . PHP_EOL; + print PHP_EOL; + print 'usage: poller_monitor.php [--force] [--debug]' . PHP_EOL . PHP_EOL; + print ' --force - force execution, e.g. for testing' . PHP_EOL; + print ' --debug - debug execution, e.g. for testing' . PHP_EOL . PHP_EOL; } From db3aff5e5448b98d35c825e3c52d0a6fef1cb39b Mon Sep 17 00:00:00 2001 From: Sean Mancini Date: Sun, 1 Mar 2026 19:06:22 -0500 Subject: [PATCH 03/26] reduce cognetive complexity scores based on PSR12 and sonar scans --- poller_monitor.php | 914 +++++++++++++++++++++++++-------------------- 1 file changed, 504 insertions(+), 410 deletions(-) diff --git a/poller_monitor.php b/poller_monitor.php index 89305c8..c1d6c42 100644 --- a/poller_monitor.php +++ b/poller_monitor.php @@ -157,6 +157,9 @@ exit; +/** + * Add host to reboot email recipients. + */ function monitorAddEmails(&$reboot_emails, $alert_emails, $host_id) { if (cacti_sizeof($alert_emails)) { foreach ($alert_emails as $email) { @@ -165,6 +168,9 @@ function monitorAddEmails(&$reboot_emails, $alert_emails, $host_id) { } } +/** + * Add host to recipients from a notification list. + */ function monitorAddNotificationList(&$reboot_emails, $notify_list, $host_id, $notification_lists) { if ($notify_list > 0 && isset($notification_lists[$notify_list])) { $emails = explode(',', $notification_lists[$notify_list]); @@ -172,50 +178,39 @@ function monitorAddNotificationList(&$reboot_emails, $notify_list, $host_id, $no } } -function monitorUptimeChecker() { - monitorDebug('Checking for Uptime of Devices'); - - $reboot_emails = []; - - $alert_email = read_config_option('alert_email'); - - if ($alert_email != '') { - $alert_emails = explode(',', $alert_email); - } else { - $alert_emails = []; - } - - // Remove unneeded device records in associated tables - $removed_hosts = db_fetch_assoc('SELECT mu.host_id - FROM plugin_monitor_uptime AS mu - LEFT JOIN host AS h - ON h.id = mu.host_id - WHERE h.id IS NULL'); +/** + * Return configured global alert emails. + */ +function getAlertEmails() { + $alert_email = read_config_option('alert_email'); - if (cacti_sizeof($removed_hosts)) { - db_execute('DELETE mu - FROM plugin_monitor_uptime AS mu - LEFT JOIN host AS h - ON h.id = mu.host_id - WHERE h.id IS NULL'); - } + return ($alert_email != '') ? explode(',', $alert_email) : []; +} - $removed_hosts = db_fetch_assoc('SELECT mu.host_id - FROM plugin_monitor_reboot_history AS mu +/** + * Remove orphan monitor rows for a monitor table. + */ +function purgeOrphanMonitorRows($table_name) { + $removed_hosts = db_fetch_assoc("SELECT mu.host_id + FROM $table_name AS mu LEFT JOIN host AS h ON h.id = mu.host_id - WHERE h.id IS NULL'); + WHERE h.id IS NULL"); if (cacti_sizeof($removed_hosts)) { - db_execute('DELETE mu - FROM plugin_monitor_reboot_history AS mu + db_execute("DELETE mu + FROM $table_name AS mu LEFT JOIN host AS h ON h.id = mu.host_id - WHERE h.id IS NULL'); + WHERE h.id IS NULL"); } +} - // Get the rebooted devices - $rebooted_hosts = db_fetch_assoc('SELECT h.id, h.description, +/** + * Return hosts detected as rebooted. + */ +function getRebootedHosts() { + return db_fetch_assoc('SELECT h.id, h.description, h.hostname, h.snmp_sysUpTimeInstance, mu.uptime FROM host AS h LEFT JOIN plugin_monitor_uptime AS mu @@ -226,82 +221,130 @@ function monitorUptimeChecker() { AND h.monitor = "on" AND (mu.uptime IS NULL OR mu.uptime > h.snmp_sysUpTimeInstance) AND h.snmp_sysUpTimeInstance > 0'); +} - if (cacti_sizeof($rebooted_hosts)) { - $notification_lists = array_rekey( - db_fetch_assoc('SELECT id, emails - FROM plugin_notification_lists - ORDER BY id'), - 'id', 'emails' - ); - - $monitor_list = read_config_option('monitor_list'); - $monitor_thold = read_config_option('monitor_reboot_thold'); - - foreach ($rebooted_hosts as $host) { - db_execute_prepared('INSERT INTO plugin_monitor_reboot_history - (host_id, reboot_time) - VALUES (?, ?)', - [$host['id'], date(MONITOR_DATE_TIME_FORMAT, time() - intval($host['snmp_sysUpTimeInstance']))]); - - monitorAddNotificationList($reboot_emails, $monitor_list, $host['id'], $notification_lists); - - if ($monitor_thold == 'on') { - $notify = db_fetch_row_prepared('SELECT thold_send_email, thold_host_email - FROM host - WHERE id = ?', - [$host['id']]); - - if (cacti_sizeof($notify)) { - switch($notify['thold_send_email']) { - case '0': // Disabled - break; - case '1': // Global List - monitorAddEmails($reboot_emails, $alert_emails, $host['id']); - - break; - case '2': // Nofitication List - monitorAddNotificationList($reboot_emails, $notify['thold_host_email'], - $host['id'], $notification_lists); - - break; - case '3': // Both Global and Nofication list - monitorAddEmails($reboot_emails, $alert_emails, $host['id']); - monitorAddNotificationList($reboot_emails, $notify['thold_host_email'], - $host['id'], $notification_lists); - - break; - default: - break; - } - } - } +/** + * Return notification list id-to-emails map. + */ +function getNotificationListsMap() { + return array_rekey( + db_fetch_assoc('SELECT id, emails + FROM plugin_notification_lists + ORDER BY id'), + 'id', 'emails' + ); +} + +/** + * Add threshold-configured recipients for rebooted host. + */ +function addTholdRebootRecipients(&$reboot_emails, $host_id, $alert_emails, $notification_lists) { + $notify = db_fetch_row_prepared('SELECT thold_send_email, thold_host_email + FROM host + WHERE id = ?', + [$host_id]); + + if (!cacti_sizeof($notify)) { + return; + } + + switch ($notify['thold_send_email']) { + case '1': + monitorAddEmails($reboot_emails, $alert_emails, $host_id); + + break; + case '2': + monitorAddNotificationList($reboot_emails, $notify['thold_host_email'], $host_id, $notification_lists); + + break; + case '3': + monitorAddEmails($reboot_emails, $alert_emails, $host_id); + monitorAddNotificationList($reboot_emails, $notify['thold_host_email'], $host_id, $notification_lists); + + break; + default: + break; + } +} + +/** + * Build reboot email recipient map for rebooted hosts. + */ +function buildRebootEmailMap($rebooted_hosts, $alert_emails) { + $reboot_emails = []; + $notification_lists = getNotificationListsMap(); + $monitor_list = read_config_option('monitor_list'); + $monitor_thold = read_config_option('monitor_reboot_thold'); + + foreach ($rebooted_hosts as $host) { + db_execute_prepared('INSERT INTO plugin_monitor_reboot_history + (host_id, reboot_time) + VALUES (?, ?)', + [$host['id'], date(MONITOR_DATE_TIME_FORMAT, time() - intval($host['snmp_sysUpTimeInstance']))]); + + monitorAddNotificationList($reboot_emails, $monitor_list, $host['id'], $notification_lists); + + if ($monitor_thold == 'on') { + addTholdRebootRecipients($reboot_emails, $host['id'], $alert_emails, $notification_lists); } + } - $monitor_send_one_email = read_config_option('monitor_send_one_email'); - $to_email = ''; - - if (cacti_sizeof($reboot_emails)) { - foreach ($reboot_emails as $email => $hosts) { - if ($email != '') { - $to_email .= ($to_email != '' ? ',' : '') . $email; - - if ($monitor_send_one_email !== 'on') { - monitorDebug('Processing the Email address: ' . $email); - processRebootEmail($email, $hosts); - } - } else { - monitorDebug('Unable to process reboot notification due to empty Email address.'); - } - } + return $reboot_emails; +} - if ($monitor_send_one_email == 'on') { - monitorDebug('Processing the Email address: ' . $to_email); - processRebootEmail($to_email, $hosts); - } +/** + * Send reboot notifications using configured delivery mode. + */ +function sendRebootNotifications($reboot_emails) { + $monitor_send_one_email = read_config_option('monitor_send_one_email'); + + if (!cacti_sizeof($reboot_emails)) { + return; + } + + $all_hosts = []; + $to_email = ''; + + foreach ($reboot_emails as $email => $hosts) { + if ($email == '') { + monitorDebug('Unable to process reboot notification due to empty Email address.'); + + continue; + } + + $to_email .= ($to_email != '' ? ',' : '') . $email; + $all_hosts = array_unique(array_merge($all_hosts, array_values($hosts))); + + if ($monitor_send_one_email !== 'on') { + monitorDebug('Processing the Email address: ' . $email); + processRebootEmail($email, $hosts); } } + if ($monitor_send_one_email == 'on' && $to_email !== '') { + monitorDebug('Processing the Email address: ' . $to_email); + processRebootEmail($to_email, $all_hosts); + } +} + +/** + * Check uptime/reboot events and process reboot notifications. + */ +function monitorUptimeChecker() { + monitorDebug('Checking for Uptime of Devices'); + + $alert_emails = getAlertEmails(); + + purgeOrphanMonitorRows('plugin_monitor_uptime'); + purgeOrphanMonitorRows('plugin_monitor_reboot_history'); + + $rebooted_hosts = getRebootedHosts(); + + if (cacti_sizeof($rebooted_hosts)) { + $reboot_emails = buildRebootEmailMap($rebooted_hosts, $alert_emails); + sendRebootNotifications($reboot_emails); + } + // Freshen the uptimes db_execute('REPLACE INTO plugin_monitor_uptime (host_id, uptime) @@ -328,114 +371,136 @@ function monitorUptimeChecker() { return [cacti_sizeof($rebooted_hosts), $recent]; } -function processRebootEmail($email, $hosts) { - monitorDebug("Reboot Processing for $email starting"); - - $body_txt = ''; +/** + * Build reboot details for both HTML and plain text mail bodies. + */ +function buildRebootDetails($hosts) { + $body_txt = ''; + $last_host = []; $body = '' . PHP_EOL; $body .= '' . PHP_EOL; - $body .= '' . '' . PHP_EOL; - $body .= '' . PHP_EOL; - foreach ($hosts as $host) { + foreach ($hosts as $host_id) { $host = db_fetch_row_prepared('SELECT description, hostname FROM host WHERE id = ?', - [$host]); + [$host_id]); - if (cacti_sizeof($host)) { - $body .= '' . - '' . - '' . - '' . PHP_EOL; - - $body_txt .= - __('Description: ', 'monitor') . $host['description'] . PHP_EOL . - __('Hostname: ', 'monitor') . $host['hostname'] . PHP_EOL . PHP_EOL; + if (!cacti_sizeof($host)) { + continue; } + + $last_host = $host; + $body .= '' . + '' . + '' . + '' . PHP_EOL; + + $body_txt .= + __('Description: ', 'monitor') . $host['description'] . PHP_EOL . + __('Hostname: ', 'monitor') . $host['hostname'] . PHP_EOL . PHP_EOL; } $body .= '
' . __('Description', 'monitor') . '' . __('Hostname', 'monitor') . '
' . $host['description'] . '' . $host['hostname'] . '
' . $host['description'] . '' . $host['hostname'] . '
' . PHP_EOL; + return [$body, $body_txt, $last_host]; +} + +/** + * Build reboot notification email subject. + */ +function buildRebootSubject($hosts, $last_host) { $subject = read_config_option('monitor_subject'); $monitor_send_one_email = read_config_option('monitor_send_one_email'); - if ($monitor_send_one_email == 'on') { - $subject .= ' ' . $host['description'] . ' (' . $host['hostname'] . ')'; - } else { - if (cacti_sizeof($hosts) == 1) { - $subject .= ' 1 device - ' . $host['description'] . ' (' . $host['hostname'] . ')'; - } else { - $subject .= ' ' . cacti_sizeof($hosts) . ' devices'; - } + if ($monitor_send_one_email == 'on' && cacti_sizeof($last_host)) { + return $subject . ' ' . $last_host['description'] . ' (' . $last_host['hostname'] . ')'; } - $output = read_config_option('monitor_body'); - $output = str_replace('
', $body, $output) . PHP_EOL; - - if (strpos($output, '
') !== false) { - $toutput = str_replace('
', $body_txt, $output) . PHP_EOL; - } else { - $toutput = $body_txt; + if (cacti_sizeof($hosts) == 1 && cacti_sizeof($last_host)) { + return $subject . ' 1 device - ' . $last_host['description'] . ' (' . $last_host['hostname'] . ')'; } - if (read_config_option('monitor_reboot_notify') == 'on') { - $report_tag = ''; - $theme = 'modern'; + return $subject . ' ' . cacti_sizeof($hosts) . ' devices'; +} - monitorDebug('Loading Format File'); +/** + * Prepare report wrapper output and headers for monitor notifications. + */ +function prepareReportOutput($body, $body_txt) { + $output = ''; - $format_ok = reports_load_format_file(read_config_option('monitor_format_file'), $output, $report_tag, $theme); + $report_tag = ''; + $theme = 'modern'; - monitorDebug('Format File Loaded, Format is ' . ($format_ok ? 'Ok' : 'Not Ok') . ', Report Tag is ' . $report_tag); + monitorDebug('Loading Format File'); - if ($format_ok) { - if ($report_tag) { - $output = str_replace('', $body, $output); - } else { - $output = $output . PHP_EOL . $body; - } - } else { - $output = $body; - } + $format_ok = reports_load_format_file(read_config_option('monitor_format_file'), $output, $report_tag, $theme); - monitorDebug('HTML Processed'); + monitorDebug('Format File Loaded, Format is ' . ($format_ok ? 'Ok' : 'Not Ok') . ', Report Tag is ' . $report_tag); - if (defined('CACTI_VERSION')) { - $version = CACTI_VERSION; + if ($format_ok) { + if ($report_tag) { + $output = str_replace('', $body, $output); } else { - $version = get_cacti_version(); + $output = $output . PHP_EOL . $body; } + } else { + $output = $body; + } - $headers['User-Agent'] = 'Cacti-Monitor-v' . $version; - - $status = 'Reboot Notifications'; + monitorDebug('HTML Processed'); - processSendEmail($email, $subject, $output, $toutput, $headers, $status); + if (defined('CACTI_VERSION')) { + $version = CACTI_VERSION; + } else { + $version = get_cacti_version(); } + + $headers = ['User-Agent' => 'Cacti-Monitor-v' . $version]; + + return [$output, $body_txt, $headers]; } -function processEmail($email, $lists, $global_list, $notify_list) { - global $config; +/** + * Process and send reboot notification email. + */ +function processRebootEmail($email, $hosts) { + monitorDebug("Reboot Processing for $email starting"); - monitorDebug('Into Processing'); + [$body, $body_txt, $last_host] = buildRebootDetails($hosts); + $subject = buildRebootSubject($hosts, $last_host); + + $template_output = read_config_option('monitor_body'); + $template_output = str_replace('
', $body, $template_output) . PHP_EOL; + if (strpos($template_output, '
') !== false) { + $toutput = str_replace('
', $body_txt, $template_output) . PHP_EOL; + } else { + $toutput = $body_txt; + } + + if (read_config_option('monitor_reboot_notify') != 'on') { + return; + } + + [$output, $toutput, $headers] = prepareReportOutput($body, $toutput); + + processSendEmail($email, $subject, $output, $toutput, $headers, 'Reboot Notifications'); +} + +/** + * Collect alert and warning host ids from requested notification lists. + */ +function collectNotificationHosts($lists, $global_list, $notify_list) { $alert_hosts = []; $warn_hosts = []; - $criticalities = [ - 0 => __('Disabled', 'monnitor'), - 1 => __('Low', 'monnitor'), - 2 => __('Medium', 'monnitor'), - 3 => __('High', 'monnitor'), - 4 => __('Mission Critical', 'monnitor') - ]; - foreach ($lists as $list) { if ($list === 'global') { if (isset($global_list['alert'])) { @@ -445,206 +510,194 @@ function processEmail($email, $lists, $global_list, $notify_list) { if (isset($global_list['warn'])) { $warn_hosts += explode(',', $global_list['warn']); } - } else { - if (isset($notify_list[$list]['alert'])) { - $alert_hosts = explode(',', $notify_list[$list]['alert']); - } - if (isset($notify_list[$list]['warn'])) { - $warn_hosts = explode(',', $notify_list[$list]['warn']); - } + continue; + } + + if (isset($notify_list[$list]['alert'])) { + $alert_hosts = explode(',', $notify_list[$list]['alert']); + } + + if (isset($notify_list[$list]['warn'])) { + $warn_hosts = explode(',', $notify_list[$list]['warn']); } } - monitorDebug('Lists Processed'); + return [$alert_hosts, $warn_hosts]; +} +/** + * Log and de-duplicate notification host ids. + */ +function normalizeAndLogNotificationHosts(&$alert_hosts, &$warn_hosts) { if (cacti_sizeof($alert_hosts)) { $alert_hosts = array_unique($alert_hosts, SORT_NUMERIC); - logMessages('alert', $alert_hosts); } if (cacti_sizeof($warn_hosts)) { $warn_hosts = array_unique($warn_hosts, SORT_NUMERIC); - - logMessages('warn', $alert_hosts); + logMessages('warn', $warn_hosts); } +} - monitorDebug('Found ' . sizeof($alert_hosts) . ' Alert Hosts, and ' . sizeof($warn_hosts) . ' Warn Hosts'); - - if (cacti_sizeof($alert_hosts) || sizeof($warn_hosts)) { - monitorDebug('Formatting Email'); - - $freq = read_config_option('monitor_resend_frequency'); - $subject = __(MONITOR_PING_NOTIFICATION_SUBJECT, 'monitor'); - - $body = '

' . __(MONITOR_PING_NOTIFICATION_SUBJECT, 'monitor') . '

' . PHP_EOL; - $body_txt = __(MONITOR_PING_NOTIFICATION_SUBJECT, 'monitor') . PHP_EOL; - - $body .= '

' . __('The following report will identify Devices that have eclipsed their ping latency thresholds. You are receiving this report since you are subscribed to a Device associated with the Cacti system located at the following URL below.') . '

' . PHP_EOL; - - $body_txt .= __('The following report will identify Devices that have eclipsed their ping latency thresholds. You are receiving this report since you are subscribed to a Device associated with the Cacti system located at the following URL below.') . PHP_EOL; +/** + * Build base intro text for ping threshold notification. + */ +function buildPingNotificationIntro($freq) { + $body = '

' . __(MONITOR_PING_NOTIFICATION_SUBJECT, 'monitor') . '

' . PHP_EOL; + $body_txt = __(MONITOR_PING_NOTIFICATION_SUBJECT, 'monitor') . PHP_EOL; - $body .= '

Cacti Monitoring Site

' . PHP_EOL; + $message = __('The following report will identify Devices that have eclipsed their ping latency thresholds. You are receiving this report since you are subscribed to a Device associated with the Cacti system located at the following URL below.'); - $body_txt .= __('Cacti Monitoring Site', 'monitor') . PHP_EOL; + $body .= '

' . $message . '

' . PHP_EOL; + $body_txt .= $message . PHP_EOL; - if ($freq > 0) { - $body .= '

' . __('You will receive notifications every %d minutes if the Device is above its threshold.', $freq, 'monitor') . '

' . PHP_EOL; + $body .= '

Cacti Monitoring Site

' . PHP_EOL; + $body_txt .= __('Cacti Monitoring Site', 'monitor') . PHP_EOL; - $body_txt .= __('You will receive notifications every %d minutes if the Device is above its threshold.', $freq, 'monitor') . PHP_EOL; - } else { - $body .= '

' . __('You will receive notifications every time the Device is above its threshold.', 'monitor') . '

' . PHP_EOL; + if ($freq > 0) { + $body .= '

' . __('You will receive notifications every %d minutes if the Device is above its threshold.', $freq, 'monitor') . '

' . PHP_EOL; + $body_txt .= __('You will receive notifications every %d minutes if the Device is above its threshold.', $freq, 'monitor') . PHP_EOL; + } else { + $body .= '

' . __('You will receive notifications every time the Device is above its threshold.', 'monitor') . '

' . PHP_EOL; + $body_txt .= __('You will receive notifications every time the Device is above its threshold.', 'monitor') . PHP_EOL; + } - $body_txt .= __('You will receive notifications every time the Device is above its threshold.', 'monitor') . PHP_EOL; - } + return [$body, $body_txt]; +} - if (cacti_sizeof($alert_hosts)) { - $body .= '

' . __('The following Devices have breached their Alert Notification Threshold.', 'monitor') . '

' . PHP_EOL; +/** + * Append one threshold breach section to notification body. + */ +function appendThresholdSection(&$body, &$body_txt, $host_ids, $criticalities, $section_text, $threshold_field) { + global $config; - $body_txt .= __('The following Devices have breached their Alert Notification Threshold.', 'monitor') . PHP_EOL; + if (!cacti_sizeof($host_ids)) { + return; + } - $body .= '' . PHP_EOL; - $body .= '' . PHP_EOL; + $body .= '

' . __($section_text, 'monitor') . '

' . PHP_EOL; + $body_txt .= __($section_text, 'monitor') . PHP_EOL; - $body .= - '' . - '' . - '' . - '' . PHP_EOL; + $body .= '
' . __('Hostname', 'monitor') . '' . __('Criticality', 'monitor') . '' . __(MONITOR_ALERT_PING_LABEL, 'monitor') . '' . __(MONITOR_CURRENT_PING_LABEL, 'monitor') . '
' . PHP_EOL; + $body .= '' . PHP_EOL; + $body .= + '' . + '' . + '' . + '' . PHP_EOL; + $body .= '' . PHP_EOL; - $body_txt .= - __('Hostname', 'monitor') . "\t" . - __('Criticality', 'monitor') . "\t" . - __(MONITOR_ALERT_PING_LABEL, 'monitor') . "\t" . - __(MONITOR_CURRENT_PING_LABEL, 'monitor') . PHP_EOL; + $body_txt .= + __('Hostname', 'monitor') . "\t" . + __('Criticality', 'monitor') . "\t" . + __(MONITOR_ALERT_PING_LABEL, 'monitor') . "\t" . + __(MONITOR_CURRENT_PING_LABEL, 'monitor') . PHP_EOL; + $hosts = db_fetch_assoc('SELECT * + FROM host + WHERE id IN(' . implode(',', $host_ids) . ') + AND deleted = ""'); + + if (cacti_sizeof($hosts)) { + foreach ($hosts as $host) { + $body .= '' . PHP_EOL; + $body .= '' . PHP_EOL; + $body .= '' . PHP_EOL; + $body .= '' . PHP_EOL; + $body .= '' . PHP_EOL; $body .= '' . PHP_EOL; - $hosts = db_fetch_assoc('SELECT * - FROM host - WHERE id IN(' . implode(',', $alert_hosts) . ') - AND deleted = ""'); - - if (cacti_sizeof($hosts)) { - foreach ($hosts as $host) { - $body .= '' . PHP_EOL; - $body .= '' . PHP_EOL; - - $body .= '' . PHP_EOL; - $body .= '' . PHP_EOL; - $body .= '' . PHP_EOL; - - $body_txt .= - $host['description'] . "\t" . - $criticalities[$host['monitor_criticality']] . "\t" . - number_format_i18n($host['monitor_alert'],2) . " ms\t" . - number_format_i18n($host['cur_time'],2) . ' ms' . PHP_EOL; - - $body .= '' . PHP_EOL; - } - } - - $body .= '
' . __('Hostname', 'monitor') . '' . __('Criticality', 'monitor') . '' . __(MONITOR_ALERT_PING_LABEL, 'monitor') . '' . __(MONITOR_CURRENT_PING_LABEL, 'monitor') . '
' . $host['description'] . '' . $criticalities[$host['monitor_criticality']] . '' . number_format_i18n($host[$threshold_field],2) . ' ms' . number_format_i18n($host['cur_time'],2) . ' ms
' . $host['description'] . '' . $criticalities[$host['monitor_criticality']] . '' . number_format_i18n($host['monitor_alert'],2) . ' ms' . number_format_i18n($host['cur_time'],2) . ' ms
' . PHP_EOL; + $body_txt .= + $host['description'] . "\t" . + $criticalities[$host['monitor_criticality']] . "\t" . + number_format_i18n($host[$threshold_field],2) . " ms\t" . + number_format_i18n($host['cur_time'],2) . ' ms' . PHP_EOL; } + } - if (cacti_sizeof($warn_hosts)) { - $body .= '

' . __('The following Devices have breached their Warning Notification Threshold.', 'monitor') . '

' . PHP_EOL; - - $body_txt .= __('The following Devices have breached their Warning Notification Threshold.', 'monitor') . PHP_EOL; - - $body .= '' . PHP_EOL; - $body .= '' . PHP_EOL; - - $body .= - '' . - '' . - '' . - '' . PHP_EOL; + $body .= '
' . __('Hostname', 'monitor') . '' . __('Criticality', 'monitor') . '' . __(MONITOR_ALERT_PING_LABEL, 'monitor') . '' . __(MONITOR_CURRENT_PING_LABEL, 'monitor') . '
' . PHP_EOL; +} - $body_txt .= - __('Hostname', 'monitor') . "\t" . - __('Criticality', 'monitor') . "\t" . - __(MONITOR_ALERT_PING_LABEL, 'monitor') . "\t" . - __(MONITOR_CURRENT_PING_LABEL, 'monitor') . PHP_EOL; +/** + * Build delivery status summary for notification logging. + */ +function buildNotificationStatus($alert_hosts, $warn_hosts) { + $status = ''; - $body .= '' . PHP_EOL; + if (cacti_sizeof($alert_hosts)) { + $status = sizeof($alert_hosts) . ' Alert Notifications'; + } - $hosts = db_fetch_assoc('SELECT * - FROM host - WHERE id IN(' . implode(',', $warn_hosts) . ') - AND deleted = ""'); - - if (cacti_sizeof($hosts)) { - foreach ($hosts as $host) { - $body .= '' . PHP_EOL; - $body .= '' . $host['description'] . '' . PHP_EOL; - - $body .= '' . $criticalities[$host['monitor_criticality']] . '' . PHP_EOL; - $body .= '' . number_format_i18n($host['monitor_warn'],2) . ' ms' . PHP_EOL; - $body .= '' . number_format_i18n($host['cur_time'],2) . ' ms' . PHP_EOL; - - $body_txt .= - $host['description'] . "\t" . - $criticalities[$host['monitor_criticality']] . "\t" . - number_format_i18n($host['monitor_alert'],2) . " ms\t" . - number_format_i18n($host['cur_time'],2) . ' ms' . PHP_EOL; - - $body .= '' . PHP_EOL; - } - } - $body .= '' . PHP_EOL; + if (cacti_sizeof($warn_hosts)) { + if ($status !== '') { + $status .= ', and '; } - $output = ''; - $toutput = $body_txt; - $report_tag = ''; - $theme = 'modern'; + $status .= sizeof($warn_hosts) . ' Warning Notifications'; + } - monitorDebug('Loading Format File'); + return $status; +} - $format_ok = reports_load_format_file(read_config_option('monitor_format_file'), $output, $report_tag, $theme); +/** + * Process and send ping threshold notification email. + */ +function processEmail($email, $lists, $global_list, $notify_list) { + monitorDebug('Into Processing'); - monitorDebug('Format File Loaded, Format is ' . ($format_ok ? 'Ok' : 'Not Ok') . ', Report Tag is ' . $report_tag); + $criticalities = [ + 0 => __('Disabled', 'monnitor'), + 1 => __('Low', 'monnitor'), + 2 => __('Medium', 'monnitor'), + 3 => __('High', 'monnitor'), + 4 => __('Mission Critical', 'monnitor') + ]; - if ($format_ok) { - if ($report_tag) { - $output = str_replace('', $body, $output); - } else { - $output = $output . PHP_EOL . $body; - } - } else { - $output = $body; - } + [$alert_hosts, $warn_hosts] = collectNotificationHosts($lists, $global_list, $notify_list); + monitorDebug('Lists Processed'); - monitorDebug('HTML Processed'); + normalizeAndLogNotificationHosts($alert_hosts, $warn_hosts); + monitorDebug('Found ' . sizeof($alert_hosts) . ' Alert Hosts, and ' . sizeof($warn_hosts) . ' Warn Hosts'); - if (defined('CACTI_VERSION')) { - $version = CACTI_VERSION; - } else { - $version = get_cacti_version(); - } + if (!cacti_sizeof($alert_hosts) && !cacti_sizeof($warn_hosts)) { + return; + } - $headers['User-Agent'] = 'Cacti-Monitor-v' . $version; + monitorDebug('Formatting Email'); - $status = ''; + $freq = read_config_option('monitor_resend_frequency'); + $subject = __(MONITOR_PING_NOTIFICATION_SUBJECT, 'monitor'); + [$body, $body_txt] = buildPingNotificationIntro($freq); - if (cacti_sizeof($alert_hosts)) { - $status = sizeof($alert_hosts) . ' Alert Notifications'; - } + appendThresholdSection( + $body, + $body_txt, + $alert_hosts, + $criticalities, + 'The following Devices have breached their Alert Notification Threshold.', + 'monitor_alert' + ); - if (cacti_sizeof($warn_hosts)) { - if ($status !== '') { - $status .= ', and '; - } + appendThresholdSection( + $body, + $body_txt, + $warn_hosts, + $criticalities, + 'The following Devices have breached their Warning Notification Threshold.', + 'monitor_warn' + ); - $status .= sizeof($warn_hosts) . ' Warning Notifications'; - } + [$output, $toutput, $headers] = prepareReportOutput($body, $body_txt); + $status = buildNotificationStatus($alert_hosts, $warn_hosts); - processSendEmail($email, $subject, $output, $toutput, $headers, $status); - } + processSendEmail($email, $subject, $output, $toutput, $headers, $status); } +/** + * Send notification email through Cacti mailer. + */ function processSendEmail($email, $subject, $output, $toutput, $headers, $status) { $from_email = read_config_option('monitor_fromemail'); @@ -698,6 +751,9 @@ function processSendEmail($email, $subject, $output, $toutput, $headers, $status } } +/** + * Convert HTML output into plain text output. + */ function monitorText($output) { $output = explode(PHP_EOL, $output); @@ -715,6 +771,9 @@ function monitorText($output) { return $new_output; } +/** + * Log alert or warning notification events. + */ function logMessages($type, $alert_hosts) { global $start_date; @@ -744,9 +803,24 @@ function logMessages($type, $alert_hosts) { } } -function getHostsByListType($type, $criticality, &$global_list, &$notify_list, &$lists) { - global $force; +/** + * Add one grouped notification entry to global/notification collections. + */ +function addGroupedNotificationEntry($type, $entry, &$global_list, &$notify_list, &$lists) { + if ($entry['thold_send_email'] == '1' || $entry['thold_send_email'] == '3') { + $global_list[$type][] = $entry; + } + if (($entry['thold_send_email'] == '2' || $entry['thold_send_email'] == '3') && $entry['thold_host_email'] > 0) { + $notify_list[$type][$entry['thold_host_email']][] = $entry; + $lists[$entry['thold_host_email']] = $entry['thold_host_email']; + } +} + +/** + * Collect threshold-breached hosts by severity and notification list type. + */ +function getHostsByListType($type, $criticality, &$global_list, &$notify_list, &$lists) { $last_time = date(MONITOR_DATE_TIME_FORMAT, time() - read_config_option('monitor_resend_frequency') * 60); $hosts = db_fetch_cell_prepared("SELECT COUNT(*) @@ -759,128 +833,142 @@ function getHostsByListType($type, $criticality, &$global_list, &$notify_list, & AND cur_time > monitor_$type", [$criticality]); - if ($type == 'warn') { - $htype = 1; - } else { - $htype = 0; + if ($hosts <= 0) { + return; } - if ($hosts > 0) { - $groups = db_fetch_assoc_prepared("SELECT - thold_send_email, thold_host_email, GROUP_CONCAT(host.id) AS id - FROM host - LEFT JOIN ( - SELECT host_id, MAX(notification_time) AS notification_time - FROM plugin_monitor_notify_history - WHERE notify_type = ? - GROUP BY host_id - ) AS nh - ON host.id=nh.host_id - WHERE status = 3 - AND deleted = '' - AND monitor = 'on' - AND thold_send_email > 0 - AND monitor_criticality >= ? - AND cur_time > monitor_$type " . ($type == 'warn' ? ' AND cur_time < monitor_alert' : '') . ' - AND (notification_time < ? OR notification_time IS NULL) - AND host.total_polls > 1 - GROUP BY thold_host_email, thold_send_email - ORDER BY thold_host_email, thold_send_email', - [$htype, $criticality, $last_time]); - - if (cacti_sizeof($groups)) { - foreach ($groups as $entry) { - switch($entry['thold_send_email']) { - case '1': // Global List - $global_list[$type][] = $entry; - - break; - case '2': // Notification List - if ($entry['thold_host_email'] > 0) { - $notify_list[$type][$entry['thold_host_email']][] = $entry; - $lists[$entry['thold_host_email']] = $entry['thold_host_email']; - } - - break; - case '3': // Both Notification and Global - $global_list[$type][] = $entry; - - if ($entry['thold_host_email'] > 0) { - $notify_list[$type][$entry['thold_host_email']][] = $entry; - $lists[$entry['thold_host_email']] = $entry['thold_host_email']; - } - - break; - default: - break; - } - } - } + $htype = ($type == 'warn') ? 1 : 0; + + $groups = db_fetch_assoc_prepared("SELECT + thold_send_email, thold_host_email, GROUP_CONCAT(host.id) AS id + FROM host + LEFT JOIN ( + SELECT host_id, MAX(notification_time) AS notification_time + FROM plugin_monitor_notify_history + WHERE notify_type = ? + GROUP BY host_id + ) AS nh + ON host.id=nh.host_id + WHERE status = 3 + AND deleted = '' + AND monitor = 'on' + AND thold_send_email > 0 + AND monitor_criticality >= ? + AND cur_time > monitor_$type " . ($type == 'warn' ? ' AND cur_time < monitor_alert' : '') . ' + AND (notification_time < ? OR notification_time IS NULL) + AND host.total_polls > 1 + GROUP BY thold_host_email, thold_send_email + ORDER BY thold_host_email, thold_send_email', + [$htype, $criticality, $last_time]); + + if (!cacti_sizeof($groups)) { + return; + } + + foreach ($groups as $entry) { + addGroupedNotificationEntry($type, $entry, $global_list, $notify_list, $lists); + } +} + +/** + * Flatten grouped list ids for one severity. + */ +function flattenGroupSeverityList($list) { + $flattened = ''; + + foreach ($list as $item) { + $flattened .= ($flattened !== '' ? ',' : '') . $item['id']; } + + return $flattened; } +/** + * Flatten grouped notification ids for each list id within a severity. + */ +function flattenNotifySeverityLists($lists) { + $flattened = []; + + foreach ($lists as $id => $list) { + $flattened[$id] = flattenGroupSeverityList($list); + } + + return $flattened; +} + +/** + * Flatten grouped notification structures into comma-separated host id strings. + */ function flattenLists(&$global_list, &$notify_list) { if (cacti_sizeof($global_list)) { + $new_global = []; + foreach ($global_list as $severity => $list) { - foreach ($list as $item) { - $new_global[$severity] = (isset($new_global[$severity]) ? $new_global[$severity] . ',' : '') . $item['id']; - } + $new_global[$severity] = flattenGroupSeverityList($list); } + $global_list = $new_global; } if (cacti_sizeof($notify_list)) { + $new_list = []; + foreach ($notify_list as $severity => $lists) { - foreach ($lists as $id => $list) { - foreach ($list as $item) { - $new_list[$severity][$id] = (isset($new_list[$severity][$id]) ? $new_list[$severity][$id] . ',' : '') . $item['id']; - } - } + $new_list[$severity] = flattenNotifySeverityLists($lists); } + $notify_list = $new_list; } } +/** + * Add email addresses to notification map under a scope key. + */ +function addEmailsToNotificationMap(&$notification_emails, $emails, $scope_key) { + foreach ($emails as $user) { + $user = trim($user); + + if ($user !== '') { + $notification_emails[$user][$scope_key] = true; + } + } +} + +/** + * Build recipient map for global and notification list subscriptions. + */ function getEmailsAndLists($lists) { $notification_emails = []; $alert_email = read_config_option('alert_email'); + $global_emails = ($alert_email != '') ? explode(',', $alert_email) : []; - if ($alert_email != '') { - $global_emails = explode(',', $alert_email); - } else { - $global_emails = []; + if (cacti_sizeof($global_emails)) { + addEmailsToNotificationMap($notification_emails, $global_emails, 'global'); } - if (cacti_sizeof($global_emails)) { - foreach ($global_emails as $user) { - if (trim($user) != '') { - $notification_emails[trim($user)]['global'] = true; - } - } + if (!cacti_sizeof($lists)) { + return $notification_emails; } - if (cacti_sizeof($lists)) { - $list_emails = db_fetch_assoc('SELECT id, emails - FROM plugin_notification_lists - WHERE id IN (' . implode(',', $lists) . ')'); + $list_emails = db_fetch_assoc('SELECT id, emails + FROM plugin_notification_lists + WHERE id IN (' . implode(',', $lists) . ')'); - if (cacti_sizeof($list_emails)) { - foreach ($list_emails as $email) { - $emails = explode(',', $email['emails']); + if (!cacti_sizeof($list_emails)) { + return $notification_emails; + } - foreach ($emails as $user) { - if (trim($user) != '') { - $notification_emails[trim($user)][$email['id']] = true; - } - } - } - } + foreach ($list_emails as $email) { + addEmailsToNotificationMap($notification_emails, explode(',', $email['emails']), $email['id']); } return $notification_emails; } +/** + * Purge old notification and reboot history rows. + */ function purgeEventRecords() { // Purge old records $days = read_config_option('monitor_log_storage'); @@ -904,6 +992,9 @@ function purgeEventRecords() { return [$purge_n, $purge_r]; } +/** + * Print debug message when debug mode is enabled. + */ function monitorDebug($message) { global $debug; @@ -912,6 +1003,9 @@ function monitorDebug($message) { } } +/** + * Display poller version information. + */ function displayVersion() { global $config; From b27c31d09666bbc811b60ab53e4fca4e96c74c12 Mon Sep 17 00:00:00 2001 From: Sean Mancini Date: Sun, 1 Mar 2026 19:11:35 -0500 Subject: [PATCH 04/26] Split poller_monitor with helper file --- poller_functions.php | 895 ++++++++++++++++++++++++++++++++++++++++++ poller_monitor.php | 905 +------------------------------------------ 2 files changed, 908 insertions(+), 892 deletions(-) create mode 100644 poller_functions.php diff --git a/poller_functions.php b/poller_functions.php new file mode 100644 index 0000000..f353138 --- /dev/null +++ b/poller_functions.php @@ -0,0 +1,895 @@ + 0 && isset($notification_lists[$notify_list])) { + $emails = explode(',', $notification_lists[$notify_list]); + monitorAddEmails($reboot_emails, $emails, $host_id); + } +} + +/** + * Return configured global alert emails. + */ +function getAlertEmails() { + $alert_email = read_config_option('alert_email'); + + return ($alert_email != '') ? explode(',', $alert_email) : []; +} + +/** + * Remove orphan monitor rows for a monitor table. + */ +function purgeOrphanMonitorRows($table_name) { + $removed_hosts = db_fetch_assoc("SELECT mu.host_id + FROM $table_name AS mu + LEFT JOIN host AS h + ON h.id = mu.host_id + WHERE h.id IS NULL"); + + if (cacti_sizeof($removed_hosts)) { + db_execute("DELETE mu + FROM $table_name AS mu + LEFT JOIN host AS h + ON h.id = mu.host_id + WHERE h.id IS NULL"); + } +} + +/** + * Return hosts detected as rebooted. + */ +function getRebootedHosts() { + return db_fetch_assoc('SELECT h.id, h.description, + h.hostname, h.snmp_sysUpTimeInstance, mu.uptime + FROM host AS h + LEFT JOIN plugin_monitor_uptime AS mu + ON h.id = mu.host_id + WHERE h.snmp_version > 0 + AND status IN (2,3) + AND h.deleted = "" + AND h.monitor = "on" + AND (mu.uptime IS NULL OR mu.uptime > h.snmp_sysUpTimeInstance) + AND h.snmp_sysUpTimeInstance > 0'); +} + +/** + * Return notification list id-to-emails map. + */ +function getNotificationListsMap() { + return array_rekey( + db_fetch_assoc('SELECT id, emails + FROM plugin_notification_lists + ORDER BY id'), + 'id', 'emails' + ); +} + +/** + * Add threshold-configured recipients for rebooted host. + */ +function addTholdRebootRecipients(&$reboot_emails, $host_id, $alert_emails, $notification_lists) { + $notify = db_fetch_row_prepared('SELECT thold_send_email, thold_host_email + FROM host + WHERE id = ?', + [$host_id]); + + if (!cacti_sizeof($notify)) { + return; + } + + switch ($notify['thold_send_email']) { + case '1': + monitorAddEmails($reboot_emails, $alert_emails, $host_id); + + break; + case '2': + monitorAddNotificationList($reboot_emails, $notify['thold_host_email'], $host_id, $notification_lists); + + break; + case '3': + monitorAddEmails($reboot_emails, $alert_emails, $host_id); + monitorAddNotificationList($reboot_emails, $notify['thold_host_email'], $host_id, $notification_lists); + + break; + default: + break; + } +} + +/** + * Build reboot email recipient map for rebooted hosts. + */ +function buildRebootEmailMap($rebooted_hosts, $alert_emails) { + $reboot_emails = []; + $notification_lists = getNotificationListsMap(); + $monitor_list = read_config_option('monitor_list'); + $monitor_thold = read_config_option('monitor_reboot_thold'); + + foreach ($rebooted_hosts as $host) { + db_execute_prepared('INSERT INTO plugin_monitor_reboot_history + (host_id, reboot_time) + VALUES (?, ?)', + [$host['id'], date(MONITOR_DATE_TIME_FORMAT, time() - intval($host['snmp_sysUpTimeInstance']))]); + + monitorAddNotificationList($reboot_emails, $monitor_list, $host['id'], $notification_lists); + + if ($monitor_thold == 'on') { + addTholdRebootRecipients($reboot_emails, $host['id'], $alert_emails, $notification_lists); + } + } + + return $reboot_emails; +} + +/** + * Send reboot notifications using configured delivery mode. + */ +function sendRebootNotifications($reboot_emails) { + $monitor_send_one_email = read_config_option('monitor_send_one_email'); + + if (!cacti_sizeof($reboot_emails)) { + return; + } + + $all_hosts = []; + $to_email = ''; + + foreach ($reboot_emails as $email => $hosts) { + if ($email == '') { + monitorDebug('Unable to process reboot notification due to empty Email address.'); + + continue; + } + + $to_email .= ($to_email != '' ? ',' : '') . $email; + $all_hosts = array_unique(array_merge($all_hosts, array_values($hosts))); + + if ($monitor_send_one_email !== 'on') { + monitorDebug('Processing the Email address: ' . $email); + processRebootEmail($email, $hosts); + } + } + + if ($monitor_send_one_email == 'on' && $to_email !== '') { + monitorDebug('Processing the Email address: ' . $to_email); + processRebootEmail($to_email, $all_hosts); + } +} + +/** + * Check uptime/reboot events and process reboot notifications. + */ +function monitorUptimeChecker() { + monitorDebug('Checking for Uptime of Devices'); + + $alert_emails = getAlertEmails(); + + purgeOrphanMonitorRows('plugin_monitor_uptime'); + purgeOrphanMonitorRows('plugin_monitor_reboot_history'); + + $rebooted_hosts = getRebootedHosts(); + + if (cacti_sizeof($rebooted_hosts)) { + $reboot_emails = buildRebootEmailMap($rebooted_hosts, $alert_emails); + sendRebootNotifications($reboot_emails); + } + + // Freshen the uptimes + db_execute('REPLACE INTO plugin_monitor_uptime + (host_id, uptime) + SELECT id, snmp_sysUpTimeInstance + FROM host + WHERE snmp_version > 0 + AND status IN(2,3) + AND deleted = "" + AND monitor = "on" + AND snmp_sysUpTimeInstance > 0'); + + // Log Recently Down + db_execute('INSERT IGNORE INTO plugin_monitor_notify_history + (host_id, notify_type, notification_time, notes) + SELECT h.id, "3" AS notify_type, status_fail_date AS notification_time, status_last_error AS notes + FROM host AS h + WHERE status = 1 + AND deleted = "" + AND monitor = "on" + AND status_event_count = 1'); + + $recent = db_affected_rows(); + + return [cacti_sizeof($rebooted_hosts), $recent]; +} + +/** + * Build reboot details for both HTML and plain text mail bodies. + */ +function buildRebootDetails($hosts) { + $body_txt = ''; + $last_host = []; + + $body = '' . PHP_EOL; + $body .= '' . PHP_EOL; + $body .= + '' . + '' . PHP_EOL; + $body .= '' . PHP_EOL; + + foreach ($hosts as $host_id) { + $host = db_fetch_row_prepared('SELECT description, hostname + FROM host + WHERE id = ?', + [$host_id]); + + if (!cacti_sizeof($host)) { + continue; + } + + $last_host = $host; + $body .= '' . + '' . + '' . + '' . PHP_EOL; + + $body_txt .= + __('Description: ', 'monitor') . $host['description'] . PHP_EOL . + __('Hostname: ', 'monitor') . $host['hostname'] . PHP_EOL . PHP_EOL; + } + + $body .= '
' . __('Description', 'monitor') . '' . __('Hostname', 'monitor') . '
' . $host['description'] . '' . $host['hostname'] . '
' . PHP_EOL; + + return [$body, $body_txt, $last_host]; +} + +/** + * Build reboot notification email subject. + */ +function buildRebootSubject($hosts, $last_host) { + $subject = read_config_option('monitor_subject'); + $monitor_send_one_email = read_config_option('monitor_send_one_email'); + + if ($monitor_send_one_email == 'on' && cacti_sizeof($last_host)) { + return $subject . ' ' . $last_host['description'] . ' (' . $last_host['hostname'] . ')'; + } + + if (cacti_sizeof($hosts) == 1 && cacti_sizeof($last_host)) { + return $subject . ' 1 device - ' . $last_host['description'] . ' (' . $last_host['hostname'] . ')'; + } + + return $subject . ' ' . cacti_sizeof($hosts) . ' devices'; +} + +/** + * Prepare report wrapper output and headers for monitor notifications. + */ +function prepareReportOutput($body, $body_txt) { + $output = ''; + + $report_tag = ''; + $theme = 'modern'; + + monitorDebug('Loading Format File'); + + $format_ok = reports_load_format_file(read_config_option('monitor_format_file'), $output, $report_tag, $theme); + + monitorDebug('Format File Loaded, Format is ' . ($format_ok ? 'Ok' : 'Not Ok') . ', Report Tag is ' . $report_tag); + + if ($format_ok) { + if ($report_tag) { + $output = str_replace('', $body, $output); + } else { + $output = $output . PHP_EOL . $body; + } + } else { + $output = $body; + } + + monitorDebug('HTML Processed'); + + if (defined('CACTI_VERSION')) { + $version = CACTI_VERSION; + } else { + $version = get_cacti_version(); + } + + $headers = ['User-Agent' => 'Cacti-Monitor-v' . $version]; + + return [$output, $body_txt, $headers]; +} + +/** + * Process and send reboot notification email. + */ +function processRebootEmail($email, $hosts) { + monitorDebug("Reboot Processing for $email starting"); + + [$body, $body_txt, $last_host] = buildRebootDetails($hosts); + $subject = buildRebootSubject($hosts, $last_host); + + $template_output = read_config_option('monitor_body'); + $template_output = str_replace('
', $body, $template_output) . PHP_EOL; + + if (strpos($template_output, '
') !== false) { + $toutput = str_replace('
', $body_txt, $template_output) . PHP_EOL; + } else { + $toutput = $body_txt; + } + + if (read_config_option('monitor_reboot_notify') != 'on') { + return; + } + + [$output, $toutput, $headers] = prepareReportOutput($body, $toutput); + + processSendEmail($email, $subject, $output, $toutput, $headers, 'Reboot Notifications'); +} + +/** + * Collect alert and warning host ids from requested notification lists. + */ +function collectNotificationHosts($lists, $global_list, $notify_list) { + $alert_hosts = []; + $warn_hosts = []; + + foreach ($lists as $list) { + if ($list === 'global') { + if (isset($global_list['alert'])) { + $alert_hosts = array_merge($alert_hosts, explode(',', $global_list['alert'])); + } + + if (isset($global_list['warn'])) { + $warn_hosts = array_merge($warn_hosts, explode(',', $global_list['warn'])); + } + + continue; + } + + if (isset($notify_list[$list]['alert'])) { + $alert_hosts = array_merge($alert_hosts, explode(',', $notify_list[$list]['alert'])); + } + + if (isset($notify_list[$list]['warn'])) { + $warn_hosts = array_merge($warn_hosts, explode(',', $notify_list[$list]['warn'])); + } + } + + return [$alert_hosts, $warn_hosts]; +} + +/** + * Log and de-duplicate notification host ids. + */ +function normalizeAndLogNotificationHosts(&$alert_hosts, &$warn_hosts) { + if (cacti_sizeof($alert_hosts)) { + $alert_hosts = array_unique($alert_hosts, SORT_NUMERIC); + logMessages('alert', $alert_hosts); + } + + if (cacti_sizeof($warn_hosts)) { + $warn_hosts = array_unique($warn_hosts, SORT_NUMERIC); + logMessages('warn', $warn_hosts); + } +} + +/** + * Build base intro text for ping threshold notification. + */ +function buildPingNotificationIntro($freq) { + $body = '

' . __(MONITOR_PING_NOTIFICATION_SUBJECT, 'monitor') . '

' . PHP_EOL; + $body_txt = __(MONITOR_PING_NOTIFICATION_SUBJECT, 'monitor') . PHP_EOL; + + $message = __('The following report will identify Devices that have eclipsed their ping latency thresholds. You are receiving this report since you are subscribed to a Device associated with the Cacti system located at the following URL below.'); + + $body .= '

' . $message . '

' . PHP_EOL; + $body_txt .= $message . PHP_EOL; + + $body .= '

Cacti Monitoring Site

' . PHP_EOL; + $body_txt .= __('Cacti Monitoring Site', 'monitor') . PHP_EOL; + + if ($freq > 0) { + $body .= '

' . __('You will receive notifications every %d minutes if the Device is above its threshold.', $freq, 'monitor') . '

' . PHP_EOL; + $body_txt .= __('You will receive notifications every %d minutes if the Device is above its threshold.', $freq, 'monitor') . PHP_EOL; + } else { + $body .= '

' . __('You will receive notifications every time the Device is above its threshold.', 'monitor') . '

' . PHP_EOL; + $body_txt .= __('You will receive notifications every time the Device is above its threshold.', 'monitor') . PHP_EOL; + } + + return [$body, $body_txt]; +} + +/** + * Append one threshold breach section to notification body. + */ +function appendThresholdSection(&$body, &$body_txt, $host_ids, $criticalities, $section_text, $threshold_field) { + global $config; + + if (!cacti_sizeof($host_ids)) { + return; + } + + $body .= '

' . __($section_text, 'monitor') . '

' . PHP_EOL; + $body_txt .= __($section_text, 'monitor') . PHP_EOL; + + $body .= '' . PHP_EOL; + $body .= '' . PHP_EOL; + $body .= + '' . + '' . + '' . + '' . PHP_EOL; + $body .= '' . PHP_EOL; + + $body_txt .= + __('Hostname', 'monitor') . "\t" . + __('Criticality', 'monitor') . "\t" . + __(MONITOR_ALERT_PING_LABEL, 'monitor') . "\t" . + __(MONITOR_CURRENT_PING_LABEL, 'monitor') . PHP_EOL; + + $hosts = db_fetch_assoc('SELECT * + FROM host + WHERE id IN(' . implode(',', $host_ids) . ') + AND deleted = ""'); + + if (cacti_sizeof($hosts)) { + foreach ($hosts as $host) { + $body .= '' . PHP_EOL; + $body .= '' . PHP_EOL; + $body .= '' . PHP_EOL; + $body .= '' . PHP_EOL; + $body .= '' . PHP_EOL; + $body .= '' . PHP_EOL; + + $body_txt .= + $host['description'] . "\t" . + $criticalities[$host['monitor_criticality']] . "\t" . + number_format_i18n($host[$threshold_field],2) . " ms\t" . + number_format_i18n($host['cur_time'],2) . ' ms' . PHP_EOL; + } + } + + $body .= '
' . __('Hostname', 'monitor') . '' . __('Criticality', 'monitor') . '' . __(MONITOR_ALERT_PING_LABEL, 'monitor') . '' . __(MONITOR_CURRENT_PING_LABEL, 'monitor') . '
' . $host['description'] . '' . $criticalities[$host['monitor_criticality']] . '' . number_format_i18n($host[$threshold_field],2) . ' ms' . number_format_i18n($host['cur_time'],2) . ' ms
' . PHP_EOL; +} + +/** + * Build delivery status summary for notification logging. + */ +function buildNotificationStatus($alert_hosts, $warn_hosts) { + $status = ''; + + if (cacti_sizeof($alert_hosts)) { + $status = sizeof($alert_hosts) . ' Alert Notifications'; + } + + if (cacti_sizeof($warn_hosts)) { + if ($status !== '') { + $status .= ', and '; + } + + $status .= sizeof($warn_hosts) . ' Warning Notifications'; + } + + return $status; +} + +/** + * Process and send ping threshold notification email. + */ +function processEmail($email, $lists, $global_list, $notify_list) { + monitorDebug('Into Processing'); + + $criticalities = [ + 0 => __('Disabled', 'monitor'), + 1 => __('Low', 'monitor'), + 2 => __('Medium', 'monitor'), + 3 => __('High', 'monitor'), + 4 => __('Mission Critical', 'monitor') + ]; + + [$alert_hosts, $warn_hosts] = collectNotificationHosts($lists, $global_list, $notify_list); + monitorDebug('Lists Processed'); + + normalizeAndLogNotificationHosts($alert_hosts, $warn_hosts); + monitorDebug('Found ' . sizeof($alert_hosts) . ' Alert Hosts, and ' . sizeof($warn_hosts) . ' Warn Hosts'); + + if (!cacti_sizeof($alert_hosts) && !cacti_sizeof($warn_hosts)) { + return; + } + + monitorDebug('Formatting Email'); + + $freq = read_config_option('monitor_resend_frequency'); + $subject = __(MONITOR_PING_NOTIFICATION_SUBJECT, 'monitor'); + [$body, $body_txt] = buildPingNotificationIntro($freq); + + appendThresholdSection( + $body, + $body_txt, + $alert_hosts, + $criticalities, + 'The following Devices have breached their Alert Notification Threshold.', + 'monitor_alert' + ); + + appendThresholdSection( + $body, + $body_txt, + $warn_hosts, + $criticalities, + 'The following Devices have breached their Warning Notification Threshold.', + 'monitor_warn' + ); + + [$output, $toutput, $headers] = prepareReportOutput($body, $body_txt); + $status = buildNotificationStatus($alert_hosts, $warn_hosts); + + processSendEmail($email, $subject, $output, $toutput, $headers, $status); +} + +/** + * Send notification email through Cacti mailer. + */ +function processSendEmail($email, $subject, $output, $toutput, $headers, $status) { + $from_email = read_config_option('monitor_fromemail'); + + if ($from_email == '') { + $from_email = read_config_option('settings_from_email'); + + if ($from_email == '') { + $from_email = 'Cacti@cacti.net'; + } + } + + $from_name = read_config_option('monitor_fromname'); + + if ($from_name == '') { + $from_name = read_config_option('settings_from_name'); + + if ($from_name == '') { + $from_name = 'Cacti Reporting'; + } + } + + $html = true; + + if (read_config_option('thold_send_text_only') == 'on') { + $output = monitorText($toutput); + $html = false; + } + + monitorDebug("Sending Email to '$email' for $status"); + + $error = mailer( + [$from_email, $from_name], + $email, + '', + '', + '', + $subject, + $output, + monitorText($toutput), + null, + $headers, + $html + ); + + monitorDebug("The return from the mailer was '$error'"); + + if (strlen($error)) { + cacti_log("WARNING: Monitor had problems sending to '$email' for $status. The error was '$error'", false, 'MONITOR'); + } else { + cacti_log("NOTICE: Email Notification Sent to '$email' for $status.", false, 'MONITOR'); + } +} + +/** + * Convert HTML output into plain text output. + */ +function monitorText($output) { + $output = explode(PHP_EOL, $output); + + $new_output = ''; + + if (cacti_sizeof($output)) { + foreach ($output as $line) { + $line = str_replace('
', PHP_EOL, $line); + $line = str_replace('
', PHP_EOL, $line); + $line = trim(strip_tags($line)); + $new_output .= $line . PHP_EOL; + } + } + + return $new_output; +} + +/** + * Log alert or warning notification events. + */ +function logMessages($type, $alert_hosts) { + global $start_date; + + static $processed = []; + + if ($type == 'warn') { + $type = '0'; + $column = 'monitor_warn'; + } elseif ($type == 'alert') { + $type = '1'; + $column = 'monitor_alert'; + } + + foreach ($alert_hosts as $id) { + if (!isset($processed[$id])) { + db_execute_prepared("INSERT INTO plugin_monitor_notify_history + (host_id, notify_type, ping_time, ping_threshold, notification_time) + SELECT id, '$type' AS notify_type, cur_time, $column, '$start_date' AS notification_time + FROM host + WHERE deleted = '' + AND monitor = 'on' + AND id = ?", + [$id]); + } + + $processed[$id] = true; + } +} + +/** + * Add one grouped notification entry to global/notification collections. + */ +function addGroupedNotificationEntry($type, $entry, &$global_list, &$notify_list, &$lists) { + if ($entry['thold_send_email'] == '1' || $entry['thold_send_email'] == '3') { + $global_list[$type][] = $entry; + } + + if (($entry['thold_send_email'] == '2' || $entry['thold_send_email'] == '3') && $entry['thold_host_email'] > 0) { + $notify_list[$type][$entry['thold_host_email']][] = $entry; + $lists[$entry['thold_host_email']] = $entry['thold_host_email']; + } +} + +/** + * Collect threshold-breached hosts by severity and notification list type. + */ +function getHostsByListType($type, $criticality, &$global_list, &$notify_list, &$lists) { + $last_time = date(MONITOR_DATE_TIME_FORMAT, time() - read_config_option('monitor_resend_frequency') * 60); + + $hosts = db_fetch_cell_prepared("SELECT COUNT(*) + FROM host + WHERE status = 3 + AND deleted = '' + AND monitor = 'on' + AND thold_send_email > 0 + AND monitor_criticality >= ? + AND cur_time > monitor_$type", + [$criticality]); + + if ($hosts <= 0) { + return; + } + + $htype = ($type == 'warn') ? 1 : 0; + + $groups = db_fetch_assoc_prepared("SELECT + thold_send_email, thold_host_email, GROUP_CONCAT(host.id) AS id + FROM host + LEFT JOIN ( + SELECT host_id, MAX(notification_time) AS notification_time + FROM plugin_monitor_notify_history + WHERE notify_type = ? + GROUP BY host_id + ) AS nh + ON host.id=nh.host_id + WHERE status = 3 + AND deleted = '' + AND monitor = 'on' + AND thold_send_email > 0 + AND monitor_criticality >= ? + AND cur_time > monitor_$type " . ($type == 'warn' ? ' AND cur_time < monitor_alert' : '') . ' + AND (notification_time < ? OR notification_time IS NULL) + AND host.total_polls > 1 + GROUP BY thold_host_email, thold_send_email + ORDER BY thold_host_email, thold_send_email', + [$htype, $criticality, $last_time]); + + if (!cacti_sizeof($groups)) { + return; + } + + foreach ($groups as $entry) { + addGroupedNotificationEntry($type, $entry, $global_list, $notify_list, $lists); + } +} + +/** + * Flatten grouped list ids for one severity. + */ +function flattenGroupSeverityList($list) { + $flattened = ''; + + foreach ($list as $item) { + $flattened .= ($flattened !== '' ? ',' : '') . $item['id']; + } + + return $flattened; +} + +/** + * Flatten grouped notification ids for each list id within a severity. + */ +function flattenNotifySeverityLists($lists) { + $flattened = []; + + foreach ($lists as $id => $list) { + $flattened[$id] = flattenGroupSeverityList($list); + } + + return $flattened; +} + +/** + * Flatten grouped notification structures into comma-separated host id strings. + */ +function flattenLists(&$global_list, &$notify_list) { + if (cacti_sizeof($global_list)) { + $new_global = []; + + foreach ($global_list as $severity => $list) { + $new_global[$severity] = flattenGroupSeverityList($list); + } + + $global_list = $new_global; + } + + if (cacti_sizeof($notify_list)) { + $new_list = []; + + foreach ($notify_list as $severity => $lists) { + $new_list[$severity] = flattenNotifySeverityLists($lists); + } + + $notify_list = $new_list; + } +} + +/** + * Add email addresses to notification map under a scope key. + */ +function addEmailsToNotificationMap(&$notification_emails, $emails, $scope_key) { + foreach ($emails as $user) { + $user = trim($user); + + if ($user !== '') { + $notification_emails[$user][$scope_key] = true; + } + } +} + +/** + * Build recipient map for global and notification list subscriptions. + */ +function getEmailsAndLists($lists) { + $notification_emails = []; + + $alert_email = read_config_option('alert_email'); + $global_emails = ($alert_email != '') ? explode(',', $alert_email) : []; + + if (cacti_sizeof($global_emails)) { + addEmailsToNotificationMap($notification_emails, $global_emails, 'global'); + } + + if (!cacti_sizeof($lists)) { + return $notification_emails; + } + + $list_emails = db_fetch_assoc('SELECT id, emails + FROM plugin_notification_lists + WHERE id IN (' . implode(',', $lists) . ')'); + + if (!cacti_sizeof($list_emails)) { + return $notification_emails; + } + + foreach ($list_emails as $email) { + addEmailsToNotificationMap($notification_emails, explode(',', $email['emails']), $email['id']); + } + + return $notification_emails; +} + +/** + * Purge old notification and reboot history rows. + */ +function purgeEventRecords() { + // Purge old records + $days = read_config_option('monitor_log_storage'); + + if (empty($days)) { + $days = 120; + } + + db_execute_prepared('DELETE FROM plugin_monitor_notify_history + WHERE notification_time < FROM_UNIXTIME(UNIX_TIMESTAMP() - (? * 86400))', + [$days]); + + $purge_n = db_affected_rows(); + + db_execute_prepared('DELETE FROM plugin_monitor_reboot_history + WHERE log_time < FROM_UNIXTIME(UNIX_TIMESTAMP() - (? * 86400))', + [$days]); + + $purge_r = db_affected_rows(); + + return [$purge_n, $purge_r]; +} + +/** + * Print debug message when debug mode is enabled. + */ +function monitorDebug($message) { + global $debug; + + if ($debug) { + print trim($message) . PHP_EOL; + } +} + +/** + * Display poller version information. + */ +function displayVersion() { + global $config; + + if (!function_exists('pluginMonitorVersion')) { + include_once $config['base_path'] . '/plugins/monitor/setup.php'; + } + + $info = pluginMonitorVersion(); + print 'Cacti Monitor Poller, Version ' . $info['version'] . ', ' . COPYRIGHT_YEARS . PHP_EOL; +} + +/* + * display_help + * displays the usage of the function + */ +function displayHelp() { + displayVersion(); + + print PHP_EOL; + print 'usage: poller_monitor.php [--debug]' . PHP_EOL . PHP_EOL; + print ' --debug - debug execution, e.g. for testing' . PHP_EOL . PHP_EOL; +} diff --git a/poller_monitor.php b/poller_monitor.php index c1d6c42..2641dc0 100644 --- a/poller_monitor.php +++ b/poller_monitor.php @@ -33,25 +33,24 @@ error_reporting(E_ALL); +const MONITOR_DATE_TIME_FORMAT = 'Y-m-d H:i:s'; +const MONITOR_PING_NOTIFICATION_SUBJECT = 'Cacti Monitor Plugin Ping Threshold Notification'; +const MONITOR_ALERT_PING_LABEL = 'Alert Ping'; +const MONITOR_CURRENT_PING_LABEL = 'Current Ping'; + // record the start time $poller_start = microtime(true); $start_date = date(MONITOR_DATE_TIME_FORMAT); -global $config, $database_default, $purged_r, $purged_n; +global $config, $database_default; -const MONITOR_DATE_TIME_FORMAT = 'Y-m-d H:i:s'; -const MONITOR_PING_NOTIFICATION_SUBJECT = 'Cacti Monitor Plugin Ping Threshold Notification'; -const MONITOR_ALERT_PING_LABEL = 'Alert Ping'; -const MONITOR_CURRENT_PING_LABEL = 'Current Ping'; +include_once __DIR__ . '/poller_functions.php'; // process calling arguments $parms = $_SERVER['argv']; array_shift($parms); -$debug = false; -$force = false; -$purged_r = 0; -$purged_n = 0; +$debug = false; if (cacti_sizeof($parms)) { foreach ($parms as $parameter) { @@ -73,10 +72,6 @@ case '-h': displayHelp(); exit; - case '--force': - $force = true; - - break; case '--debug': $debug = true; @@ -96,16 +91,15 @@ $warning_criticality = read_config_option('monitor_warn_criticality'); $alert_criticality = read_config_option('monitor_alert_criticality'); -$lists = []; -$notifications = 0; -$global_list = []; -$notify_list = []; -$last_time = date(MONITOR_DATE_TIME_FORMAT, time() - read_config_option('monitor_resend_frequency') * 60); +$lists = []; +$notifications = 0; +$global_list = []; +$notify_list = []; if ($warning_criticality > 0 || $alert_criticality > 0) { monitorDebug('Monitor Notification Enabled for Devices'); - // Get hosts that are above threshold. Start with Alert, and then Warning + // Get hosts that are above threshold. Start with Alert, and then Warning. if ($alert_criticality) { getHostsByListType('alert', $alert_criticality, $global_list, $notify_list, $lists); } @@ -156,876 +150,3 @@ set_config_option('stats_monitor', $stats); exit; - -/** - * Add host to reboot email recipients. - */ -function monitorAddEmails(&$reboot_emails, $alert_emails, $host_id) { - if (cacti_sizeof($alert_emails)) { - foreach ($alert_emails as $email) { - $reboot_emails[trim(strtolower($email))][$host_id] = $host_id; - } - } -} - -/** - * Add host to recipients from a notification list. - */ -function monitorAddNotificationList(&$reboot_emails, $notify_list, $host_id, $notification_lists) { - if ($notify_list > 0 && isset($notification_lists[$notify_list])) { - $emails = explode(',', $notification_lists[$notify_list]); - monitorAddEmails($reboot_emails, $emails, $host_id); - } -} - -/** - * Return configured global alert emails. - */ -function getAlertEmails() { - $alert_email = read_config_option('alert_email'); - - return ($alert_email != '') ? explode(',', $alert_email) : []; -} - -/** - * Remove orphan monitor rows for a monitor table. - */ -function purgeOrphanMonitorRows($table_name) { - $removed_hosts = db_fetch_assoc("SELECT mu.host_id - FROM $table_name AS mu - LEFT JOIN host AS h - ON h.id = mu.host_id - WHERE h.id IS NULL"); - - if (cacti_sizeof($removed_hosts)) { - db_execute("DELETE mu - FROM $table_name AS mu - LEFT JOIN host AS h - ON h.id = mu.host_id - WHERE h.id IS NULL"); - } -} - -/** - * Return hosts detected as rebooted. - */ -function getRebootedHosts() { - return db_fetch_assoc('SELECT h.id, h.description, - h.hostname, h.snmp_sysUpTimeInstance, mu.uptime - FROM host AS h - LEFT JOIN plugin_monitor_uptime AS mu - ON h.id = mu.host_id - WHERE h.snmp_version > 0 - AND status IN (2,3) - AND h.deleted = "" - AND h.monitor = "on" - AND (mu.uptime IS NULL OR mu.uptime > h.snmp_sysUpTimeInstance) - AND h.snmp_sysUpTimeInstance > 0'); -} - -/** - * Return notification list id-to-emails map. - */ -function getNotificationListsMap() { - return array_rekey( - db_fetch_assoc('SELECT id, emails - FROM plugin_notification_lists - ORDER BY id'), - 'id', 'emails' - ); -} - -/** - * Add threshold-configured recipients for rebooted host. - */ -function addTholdRebootRecipients(&$reboot_emails, $host_id, $alert_emails, $notification_lists) { - $notify = db_fetch_row_prepared('SELECT thold_send_email, thold_host_email - FROM host - WHERE id = ?', - [$host_id]); - - if (!cacti_sizeof($notify)) { - return; - } - - switch ($notify['thold_send_email']) { - case '1': - monitorAddEmails($reboot_emails, $alert_emails, $host_id); - - break; - case '2': - monitorAddNotificationList($reboot_emails, $notify['thold_host_email'], $host_id, $notification_lists); - - break; - case '3': - monitorAddEmails($reboot_emails, $alert_emails, $host_id); - monitorAddNotificationList($reboot_emails, $notify['thold_host_email'], $host_id, $notification_lists); - - break; - default: - break; - } -} - -/** - * Build reboot email recipient map for rebooted hosts. - */ -function buildRebootEmailMap($rebooted_hosts, $alert_emails) { - $reboot_emails = []; - $notification_lists = getNotificationListsMap(); - $monitor_list = read_config_option('monitor_list'); - $monitor_thold = read_config_option('monitor_reboot_thold'); - - foreach ($rebooted_hosts as $host) { - db_execute_prepared('INSERT INTO plugin_monitor_reboot_history - (host_id, reboot_time) - VALUES (?, ?)', - [$host['id'], date(MONITOR_DATE_TIME_FORMAT, time() - intval($host['snmp_sysUpTimeInstance']))]); - - monitorAddNotificationList($reboot_emails, $monitor_list, $host['id'], $notification_lists); - - if ($monitor_thold == 'on') { - addTholdRebootRecipients($reboot_emails, $host['id'], $alert_emails, $notification_lists); - } - } - - return $reboot_emails; -} - -/** - * Send reboot notifications using configured delivery mode. - */ -function sendRebootNotifications($reboot_emails) { - $monitor_send_one_email = read_config_option('monitor_send_one_email'); - - if (!cacti_sizeof($reboot_emails)) { - return; - } - - $all_hosts = []; - $to_email = ''; - - foreach ($reboot_emails as $email => $hosts) { - if ($email == '') { - monitorDebug('Unable to process reboot notification due to empty Email address.'); - - continue; - } - - $to_email .= ($to_email != '' ? ',' : '') . $email; - $all_hosts = array_unique(array_merge($all_hosts, array_values($hosts))); - - if ($monitor_send_one_email !== 'on') { - monitorDebug('Processing the Email address: ' . $email); - processRebootEmail($email, $hosts); - } - } - - if ($monitor_send_one_email == 'on' && $to_email !== '') { - monitorDebug('Processing the Email address: ' . $to_email); - processRebootEmail($to_email, $all_hosts); - } -} - -/** - * Check uptime/reboot events and process reboot notifications. - */ -function monitorUptimeChecker() { - monitorDebug('Checking for Uptime of Devices'); - - $alert_emails = getAlertEmails(); - - purgeOrphanMonitorRows('plugin_monitor_uptime'); - purgeOrphanMonitorRows('plugin_monitor_reboot_history'); - - $rebooted_hosts = getRebootedHosts(); - - if (cacti_sizeof($rebooted_hosts)) { - $reboot_emails = buildRebootEmailMap($rebooted_hosts, $alert_emails); - sendRebootNotifications($reboot_emails); - } - - // Freshen the uptimes - db_execute('REPLACE INTO plugin_monitor_uptime - (host_id, uptime) - SELECT id, snmp_sysUpTimeInstance - FROM host - WHERE snmp_version > 0 - AND status IN(2,3) - AND deleted = "" - AND monitor = "on" - AND snmp_sysUpTimeInstance > 0'); - - // Log Recently Down - db_execute('INSERT IGNORE INTO plugin_monitor_notify_history - (host_id, notify_type, notification_time, notes) - SELECT h.id, "3" AS notify_type, status_fail_date AS notification_time, status_last_error AS notes - FROM host AS h - WHERE status = 1 - AND deleted = "" - AND monitor = "on" - AND status_event_count = 1'); - - $recent = db_affected_rows(); - - return [cacti_sizeof($rebooted_hosts), $recent]; -} - -/** - * Build reboot details for both HTML and plain text mail bodies. - */ -function buildRebootDetails($hosts) { - $body_txt = ''; - $last_host = []; - - $body = '' . PHP_EOL; - $body .= '' . PHP_EOL; - $body .= - '' . - '' . PHP_EOL; - $body .= '' . PHP_EOL; - - foreach ($hosts as $host_id) { - $host = db_fetch_row_prepared('SELECT description, hostname - FROM host - WHERE id = ?', - [$host_id]); - - if (!cacti_sizeof($host)) { - continue; - } - - $last_host = $host; - $body .= '' . - '' . - '' . - '' . PHP_EOL; - - $body_txt .= - __('Description: ', 'monitor') . $host['description'] . PHP_EOL . - __('Hostname: ', 'monitor') . $host['hostname'] . PHP_EOL . PHP_EOL; - } - - $body .= '
' . __('Description', 'monitor') . '' . __('Hostname', 'monitor') . '
' . $host['description'] . '' . $host['hostname'] . '
' . PHP_EOL; - - return [$body, $body_txt, $last_host]; -} - -/** - * Build reboot notification email subject. - */ -function buildRebootSubject($hosts, $last_host) { - $subject = read_config_option('monitor_subject'); - $monitor_send_one_email = read_config_option('monitor_send_one_email'); - - if ($monitor_send_one_email == 'on' && cacti_sizeof($last_host)) { - return $subject . ' ' . $last_host['description'] . ' (' . $last_host['hostname'] . ')'; - } - - if (cacti_sizeof($hosts) == 1 && cacti_sizeof($last_host)) { - return $subject . ' 1 device - ' . $last_host['description'] . ' (' . $last_host['hostname'] . ')'; - } - - return $subject . ' ' . cacti_sizeof($hosts) . ' devices'; -} - -/** - * Prepare report wrapper output and headers for monitor notifications. - */ -function prepareReportOutput($body, $body_txt) { - $output = ''; - - $report_tag = ''; - $theme = 'modern'; - - monitorDebug('Loading Format File'); - - $format_ok = reports_load_format_file(read_config_option('monitor_format_file'), $output, $report_tag, $theme); - - monitorDebug('Format File Loaded, Format is ' . ($format_ok ? 'Ok' : 'Not Ok') . ', Report Tag is ' . $report_tag); - - if ($format_ok) { - if ($report_tag) { - $output = str_replace('', $body, $output); - } else { - $output = $output . PHP_EOL . $body; - } - } else { - $output = $body; - } - - monitorDebug('HTML Processed'); - - if (defined('CACTI_VERSION')) { - $version = CACTI_VERSION; - } else { - $version = get_cacti_version(); - } - - $headers = ['User-Agent' => 'Cacti-Monitor-v' . $version]; - - return [$output, $body_txt, $headers]; -} - -/** - * Process and send reboot notification email. - */ -function processRebootEmail($email, $hosts) { - monitorDebug("Reboot Processing for $email starting"); - - [$body, $body_txt, $last_host] = buildRebootDetails($hosts); - $subject = buildRebootSubject($hosts, $last_host); - - $template_output = read_config_option('monitor_body'); - $template_output = str_replace('
', $body, $template_output) . PHP_EOL; - - if (strpos($template_output, '
') !== false) { - $toutput = str_replace('
', $body_txt, $template_output) . PHP_EOL; - } else { - $toutput = $body_txt; - } - - if (read_config_option('monitor_reboot_notify') != 'on') { - return; - } - - [$output, $toutput, $headers] = prepareReportOutput($body, $toutput); - - processSendEmail($email, $subject, $output, $toutput, $headers, 'Reboot Notifications'); -} - -/** - * Collect alert and warning host ids from requested notification lists. - */ -function collectNotificationHosts($lists, $global_list, $notify_list) { - $alert_hosts = []; - $warn_hosts = []; - - foreach ($lists as $list) { - if ($list === 'global') { - if (isset($global_list['alert'])) { - $alert_hosts += explode(',', $global_list['alert']); - } - - if (isset($global_list['warn'])) { - $warn_hosts += explode(',', $global_list['warn']); - } - - continue; - } - - if (isset($notify_list[$list]['alert'])) { - $alert_hosts = explode(',', $notify_list[$list]['alert']); - } - - if (isset($notify_list[$list]['warn'])) { - $warn_hosts = explode(',', $notify_list[$list]['warn']); - } - } - - return [$alert_hosts, $warn_hosts]; -} - -/** - * Log and de-duplicate notification host ids. - */ -function normalizeAndLogNotificationHosts(&$alert_hosts, &$warn_hosts) { - if (cacti_sizeof($alert_hosts)) { - $alert_hosts = array_unique($alert_hosts, SORT_NUMERIC); - logMessages('alert', $alert_hosts); - } - - if (cacti_sizeof($warn_hosts)) { - $warn_hosts = array_unique($warn_hosts, SORT_NUMERIC); - logMessages('warn', $warn_hosts); - } -} - -/** - * Build base intro text for ping threshold notification. - */ -function buildPingNotificationIntro($freq) { - $body = '

' . __(MONITOR_PING_NOTIFICATION_SUBJECT, 'monitor') . '

' . PHP_EOL; - $body_txt = __(MONITOR_PING_NOTIFICATION_SUBJECT, 'monitor') . PHP_EOL; - - $message = __('The following report will identify Devices that have eclipsed their ping latency thresholds. You are receiving this report since you are subscribed to a Device associated with the Cacti system located at the following URL below.'); - - $body .= '

' . $message . '

' . PHP_EOL; - $body_txt .= $message . PHP_EOL; - - $body .= '

Cacti Monitoring Site

' . PHP_EOL; - $body_txt .= __('Cacti Monitoring Site', 'monitor') . PHP_EOL; - - if ($freq > 0) { - $body .= '

' . __('You will receive notifications every %d minutes if the Device is above its threshold.', $freq, 'monitor') . '

' . PHP_EOL; - $body_txt .= __('You will receive notifications every %d minutes if the Device is above its threshold.', $freq, 'monitor') . PHP_EOL; - } else { - $body .= '

' . __('You will receive notifications every time the Device is above its threshold.', 'monitor') . '

' . PHP_EOL; - $body_txt .= __('You will receive notifications every time the Device is above its threshold.', 'monitor') . PHP_EOL; - } - - return [$body, $body_txt]; -} - -/** - * Append one threshold breach section to notification body. - */ -function appendThresholdSection(&$body, &$body_txt, $host_ids, $criticalities, $section_text, $threshold_field) { - global $config; - - if (!cacti_sizeof($host_ids)) { - return; - } - - $body .= '

' . __($section_text, 'monitor') . '

' . PHP_EOL; - $body_txt .= __($section_text, 'monitor') . PHP_EOL; - - $body .= '' . PHP_EOL; - $body .= '' . PHP_EOL; - $body .= - '' . - '' . - '' . - '' . PHP_EOL; - $body .= '' . PHP_EOL; - - $body_txt .= - __('Hostname', 'monitor') . "\t" . - __('Criticality', 'monitor') . "\t" . - __(MONITOR_ALERT_PING_LABEL, 'monitor') . "\t" . - __(MONITOR_CURRENT_PING_LABEL, 'monitor') . PHP_EOL; - - $hosts = db_fetch_assoc('SELECT * - FROM host - WHERE id IN(' . implode(',', $host_ids) . ') - AND deleted = ""'); - - if (cacti_sizeof($hosts)) { - foreach ($hosts as $host) { - $body .= '' . PHP_EOL; - $body .= '' . PHP_EOL; - $body .= '' . PHP_EOL; - $body .= '' . PHP_EOL; - $body .= '' . PHP_EOL; - $body .= '' . PHP_EOL; - - $body_txt .= - $host['description'] . "\t" . - $criticalities[$host['monitor_criticality']] . "\t" . - number_format_i18n($host[$threshold_field],2) . " ms\t" . - number_format_i18n($host['cur_time'],2) . ' ms' . PHP_EOL; - } - } - - $body .= '
' . __('Hostname', 'monitor') . '' . __('Criticality', 'monitor') . '' . __(MONITOR_ALERT_PING_LABEL, 'monitor') . '' . __(MONITOR_CURRENT_PING_LABEL, 'monitor') . '
' . $host['description'] . '' . $criticalities[$host['monitor_criticality']] . '' . number_format_i18n($host[$threshold_field],2) . ' ms' . number_format_i18n($host['cur_time'],2) . ' ms
' . PHP_EOL; -} - -/** - * Build delivery status summary for notification logging. - */ -function buildNotificationStatus($alert_hosts, $warn_hosts) { - $status = ''; - - if (cacti_sizeof($alert_hosts)) { - $status = sizeof($alert_hosts) . ' Alert Notifications'; - } - - if (cacti_sizeof($warn_hosts)) { - if ($status !== '') { - $status .= ', and '; - } - - $status .= sizeof($warn_hosts) . ' Warning Notifications'; - } - - return $status; -} - -/** - * Process and send ping threshold notification email. - */ -function processEmail($email, $lists, $global_list, $notify_list) { - monitorDebug('Into Processing'); - - $criticalities = [ - 0 => __('Disabled', 'monnitor'), - 1 => __('Low', 'monnitor'), - 2 => __('Medium', 'monnitor'), - 3 => __('High', 'monnitor'), - 4 => __('Mission Critical', 'monnitor') - ]; - - [$alert_hosts, $warn_hosts] = collectNotificationHosts($lists, $global_list, $notify_list); - monitorDebug('Lists Processed'); - - normalizeAndLogNotificationHosts($alert_hosts, $warn_hosts); - monitorDebug('Found ' . sizeof($alert_hosts) . ' Alert Hosts, and ' . sizeof($warn_hosts) . ' Warn Hosts'); - - if (!cacti_sizeof($alert_hosts) && !cacti_sizeof($warn_hosts)) { - return; - } - - monitorDebug('Formatting Email'); - - $freq = read_config_option('monitor_resend_frequency'); - $subject = __(MONITOR_PING_NOTIFICATION_SUBJECT, 'monitor'); - [$body, $body_txt] = buildPingNotificationIntro($freq); - - appendThresholdSection( - $body, - $body_txt, - $alert_hosts, - $criticalities, - 'The following Devices have breached their Alert Notification Threshold.', - 'monitor_alert' - ); - - appendThresholdSection( - $body, - $body_txt, - $warn_hosts, - $criticalities, - 'The following Devices have breached their Warning Notification Threshold.', - 'monitor_warn' - ); - - [$output, $toutput, $headers] = prepareReportOutput($body, $body_txt); - $status = buildNotificationStatus($alert_hosts, $warn_hosts); - - processSendEmail($email, $subject, $output, $toutput, $headers, $status); -} - -/** - * Send notification email through Cacti mailer. - */ -function processSendEmail($email, $subject, $output, $toutput, $headers, $status) { - $from_email = read_config_option('monitor_fromemail'); - - if ($from_email == '') { - $from_email = read_config_option('settings_from_email'); - - if ($from_email == '') { - $from_email = 'Cacti@cacti.net'; - } - } - - $from_name = read_config_option('monitor_fromname'); - - if ($from_name != '') { - $from_name = read_config_option('settings_from_name'); - - if ($from_name == '') { - $from_name = 'Cacti Reporting'; - } - } - - $html = true; - - if (read_config_option('thold_send_text_only') == 'on') { - $output = monitorText($toutput); - $html = false; - } - - monitorDebug("Sending Email to '$email' for $status"); - - $error = mailer( - [$from_email, $from_name], - $email, - '', - '', - '', - $subject, - $output, - monitorText($toutput), - null, - $headers, - $html - ); - - monitorDebug("The return from the mailer was '$error'"); - - if (strlen($error)) { - cacti_log("WARNING: Monitor had problems sending to '$email' for $status. The error was '$error'", false, 'MONITOR'); - } else { - cacti_log("NOTICE: Email Notification Sent to '$email' for $status.", false, 'MONITOR'); - } -} - -/** - * Convert HTML output into plain text output. - */ -function monitorText($output) { - $output = explode(PHP_EOL, $output); - - $new_output = ''; - - if (cacti_sizeof($output)) { - foreach ($output as $line) { - $line = str_replace('
', PHP_EOL, $line); - $line = str_replace('
', PHP_EOL, $line); - $line = trim(strip_tags($line)); - $new_output .= $line . PHP_EOL; - } - } - - return $new_output; -} - -/** - * Log alert or warning notification events. - */ -function logMessages($type, $alert_hosts) { - global $start_date; - - static $processed = []; - - if ($type == 'warn') { - $type = '0'; - $column = 'monitor_warn'; - } elseif ($type == 'alert') { - $type = '1'; - $column = 'monitor_alert'; - } - - foreach ($alert_hosts as $id) { - if (!isset($processed[$id])) { - db_execute_prepared("INSERT INTO plugin_monitor_notify_history - (host_id, notify_type, ping_time, ping_threshold, notification_time) - SELECT id, '$type' AS notify_type, cur_time, $column, '$start_date' AS notification_time - FROM host - WHERE deleted = '' - AND monitor = 'on' - AND id = ?", - [$id]); - } - - $processed[$id] = true; - } -} - -/** - * Add one grouped notification entry to global/notification collections. - */ -function addGroupedNotificationEntry($type, $entry, &$global_list, &$notify_list, &$lists) { - if ($entry['thold_send_email'] == '1' || $entry['thold_send_email'] == '3') { - $global_list[$type][] = $entry; - } - - if (($entry['thold_send_email'] == '2' || $entry['thold_send_email'] == '3') && $entry['thold_host_email'] > 0) { - $notify_list[$type][$entry['thold_host_email']][] = $entry; - $lists[$entry['thold_host_email']] = $entry['thold_host_email']; - } -} - -/** - * Collect threshold-breached hosts by severity and notification list type. - */ -function getHostsByListType($type, $criticality, &$global_list, &$notify_list, &$lists) { - $last_time = date(MONITOR_DATE_TIME_FORMAT, time() - read_config_option('monitor_resend_frequency') * 60); - - $hosts = db_fetch_cell_prepared("SELECT COUNT(*) - FROM host - WHERE status = 3 - AND deleted = '' - AND monitor = 'on' - AND thold_send_email > 0 - AND monitor_criticality >= ? - AND cur_time > monitor_$type", - [$criticality]); - - if ($hosts <= 0) { - return; - } - - $htype = ($type == 'warn') ? 1 : 0; - - $groups = db_fetch_assoc_prepared("SELECT - thold_send_email, thold_host_email, GROUP_CONCAT(host.id) AS id - FROM host - LEFT JOIN ( - SELECT host_id, MAX(notification_time) AS notification_time - FROM plugin_monitor_notify_history - WHERE notify_type = ? - GROUP BY host_id - ) AS nh - ON host.id=nh.host_id - WHERE status = 3 - AND deleted = '' - AND monitor = 'on' - AND thold_send_email > 0 - AND monitor_criticality >= ? - AND cur_time > monitor_$type " . ($type == 'warn' ? ' AND cur_time < monitor_alert' : '') . ' - AND (notification_time < ? OR notification_time IS NULL) - AND host.total_polls > 1 - GROUP BY thold_host_email, thold_send_email - ORDER BY thold_host_email, thold_send_email', - [$htype, $criticality, $last_time]); - - if (!cacti_sizeof($groups)) { - return; - } - - foreach ($groups as $entry) { - addGroupedNotificationEntry($type, $entry, $global_list, $notify_list, $lists); - } -} - -/** - * Flatten grouped list ids for one severity. - */ -function flattenGroupSeverityList($list) { - $flattened = ''; - - foreach ($list as $item) { - $flattened .= ($flattened !== '' ? ',' : '') . $item['id']; - } - - return $flattened; -} - -/** - * Flatten grouped notification ids for each list id within a severity. - */ -function flattenNotifySeverityLists($lists) { - $flattened = []; - - foreach ($lists as $id => $list) { - $flattened[$id] = flattenGroupSeverityList($list); - } - - return $flattened; -} - -/** - * Flatten grouped notification structures into comma-separated host id strings. - */ -function flattenLists(&$global_list, &$notify_list) { - if (cacti_sizeof($global_list)) { - $new_global = []; - - foreach ($global_list as $severity => $list) { - $new_global[$severity] = flattenGroupSeverityList($list); - } - - $global_list = $new_global; - } - - if (cacti_sizeof($notify_list)) { - $new_list = []; - - foreach ($notify_list as $severity => $lists) { - $new_list[$severity] = flattenNotifySeverityLists($lists); - } - - $notify_list = $new_list; - } -} - -/** - * Add email addresses to notification map under a scope key. - */ -function addEmailsToNotificationMap(&$notification_emails, $emails, $scope_key) { - foreach ($emails as $user) { - $user = trim($user); - - if ($user !== '') { - $notification_emails[$user][$scope_key] = true; - } - } -} - -/** - * Build recipient map for global and notification list subscriptions. - */ -function getEmailsAndLists($lists) { - $notification_emails = []; - - $alert_email = read_config_option('alert_email'); - $global_emails = ($alert_email != '') ? explode(',', $alert_email) : []; - - if (cacti_sizeof($global_emails)) { - addEmailsToNotificationMap($notification_emails, $global_emails, 'global'); - } - - if (!cacti_sizeof($lists)) { - return $notification_emails; - } - - $list_emails = db_fetch_assoc('SELECT id, emails - FROM plugin_notification_lists - WHERE id IN (' . implode(',', $lists) . ')'); - - if (!cacti_sizeof($list_emails)) { - return $notification_emails; - } - - foreach ($list_emails as $email) { - addEmailsToNotificationMap($notification_emails, explode(',', $email['emails']), $email['id']); - } - - return $notification_emails; -} - -/** - * Purge old notification and reboot history rows. - */ -function purgeEventRecords() { - // Purge old records - $days = read_config_option('monitor_log_storage'); - - if (empty($days)) { - $days = 120; - } - - db_execute_prepared('DELETE FROM plugin_monitor_notify_history - WHERE notification_time < FROM_UNIXTIME(UNIX_TIMESTAMP() - (? * 86400))', - [$days]); - - $purge_n = db_affected_rows(); - - db_execute_prepared('DELETE FROM plugin_monitor_reboot_history - WHERE log_time < FROM_UNIXTIME(UNIX_TIMESTAMP() - (? * 86400))', - [$days]); - - $purge_r = db_affected_rows(); - - return [$purge_n, $purge_r]; -} - -/** - * Print debug message when debug mode is enabled. - */ -function monitorDebug($message) { - global $debug; - - if ($debug) { - print trim($message) . PHP_EOL; - } -} - -/** - * Display poller version information. - */ -function displayVersion() { - global $config; - - if (!function_exists('pluginMonitorVersion')) { - include_once $config['base_path'] . '/plugins/monitor/setup.php'; - } - - $info = pluginMonitorVersion(); - print 'Cacti Monitor Poller, Version ' . $info['version'] . ', ' . COPYRIGHT_YEARS . PHP_EOL; -} - -/* - * display_help - * displays the usage of the function - */ -function displayHelp() { - displayVersion(); - - print PHP_EOL; - print 'usage: poller_monitor.php [--force] [--debug]' . PHP_EOL . PHP_EOL; - print ' --force - force execution, e.g. for testing' . PHP_EOL; - print ' --debug - debug execution, e.g. for testing' . PHP_EOL . PHP_EOL; -} From 6e92d3dc2b3387d65f6cc719be3d915605d01e1d Mon Sep 17 00:00:00 2001 From: Sean Mancini Date: Sun, 1 Mar 2026 19:12:29 -0500 Subject: [PATCH 05/26] update docblocks --- poller_functions.php | 232 ++++++++++++++++++++++++++++++++++++------- 1 file changed, 197 insertions(+), 35 deletions(-) diff --git a/poller_functions.php b/poller_functions.php index f353138..37d06a5 100644 --- a/poller_functions.php +++ b/poller_functions.php @@ -23,7 +23,13 @@ */ /** - * Add host to reboot email recipients. + * Add a host id to each recipient entry in the reboot recipient map. + * + * @param array $reboot_emails Recipient map keyed by email, then host id. + * @param array $alert_emails List of raw email addresses. + * @param int $host_id Host id to associate with each recipient. + * + * @return void */ function monitorAddEmails(&$reboot_emails, $alert_emails, $host_id) { if (cacti_sizeof($alert_emails)) { @@ -34,7 +40,14 @@ function monitorAddEmails(&$reboot_emails, $alert_emails, $host_id) { } /** - * Add host to recipients from a notification list. + * Add a host id to recipients coming from a notification list id. + * + * @param array $reboot_emails Recipient map keyed by email, then host id. + * @param int $notify_list Notification list id. + * @param int $host_id Host id to add. + * @param array $notification_lists Map of list id to comma-delimited emails. + * + * @return void */ function monitorAddNotificationList(&$reboot_emails, $notify_list, $host_id, $notification_lists) { if ($notify_list > 0 && isset($notification_lists[$notify_list])) { @@ -44,7 +57,9 @@ function monitorAddNotificationList(&$reboot_emails, $notify_list, $host_id, $no } /** - * Return configured global alert emails. + * Fetch the configured global alert email list. + * + * @return array */ function getAlertEmails() { $alert_email = read_config_option('alert_email'); @@ -53,7 +68,11 @@ function getAlertEmails() { } /** - * Remove orphan monitor rows for a monitor table. + * Delete monitor table rows that reference missing hosts. + * + * @param string $table_name Monitor table to purge. + * + * @return void */ function purgeOrphanMonitorRows($table_name) { $removed_hosts = db_fetch_assoc("SELECT mu.host_id @@ -72,7 +91,9 @@ function purgeOrphanMonitorRows($table_name) { } /** - * Return hosts detected as rebooted. + * Get monitored hosts whose uptime indicates a reboot. + * + * @return array */ function getRebootedHosts() { return db_fetch_assoc('SELECT h.id, h.description, @@ -89,7 +110,9 @@ function getRebootedHosts() { } /** - * Return notification list id-to-emails map. + * Fetch notification lists and map id to email string. + * + * @return array */ function getNotificationListsMap() { return array_rekey( @@ -101,7 +124,14 @@ function getNotificationListsMap() { } /** - * Add threshold-configured recipients for rebooted host. + * Add reboot recipients based on host threshold notification settings. + * + * @param array $reboot_emails Recipient map keyed by email, then host id. + * @param int $host_id Host id being processed. + * @param array $alert_emails Global alert email list. + * @param array $notification_lists Map of notification list id to emails. + * + * @return void */ function addTholdRebootRecipients(&$reboot_emails, $host_id, $alert_emails, $notification_lists) { $notify = db_fetch_row_prepared('SELECT thold_send_email, thold_host_email @@ -133,7 +163,12 @@ function addTholdRebootRecipients(&$reboot_emails, $host_id, $alert_emails, $not } /** - * Build reboot email recipient map for rebooted hosts. + * Build reboot recipient map and persist reboot history rows. + * + * @param array $rebooted_hosts Rebooted host rows. + * @param array $alert_emails Global alert email list. + * + * @return array */ function buildRebootEmailMap($rebooted_hosts, $alert_emails) { $reboot_emails = []; @@ -158,7 +193,11 @@ function buildRebootEmailMap($rebooted_hosts, $alert_emails) { } /** - * Send reboot notifications using configured delivery mode. + * Dispatch reboot notifications per-recipient or as a single batched email. + * + * @param array $reboot_emails Recipient map keyed by email, then host id. + * + * @return void */ function sendRebootNotifications($reboot_emails) { $monitor_send_one_email = read_config_option('monitor_send_one_email'); @@ -193,7 +232,9 @@ function sendRebootNotifications($reboot_emails) { } /** - * Check uptime/reboot events and process reboot notifications. + * Process reboot detection, uptime refresh, and down-event history logging. + * + * @return array{int, int} Reboot count and recent down count. */ function monitorUptimeChecker() { monitorDebug('Checking for Uptime of Devices'); @@ -237,7 +278,11 @@ function monitorUptimeChecker() { } /** - * Build reboot details for both HTML and plain text mail bodies. + * Build reboot details table/text and capture the last resolved host row. + * + * @param array $hosts Host ids to include. + * + * @return array{string, string, array} */ function buildRebootDetails($hosts) { $body_txt = ''; @@ -277,7 +322,12 @@ function buildRebootDetails($hosts) { } /** - * Build reboot notification email subject. + * Build reboot notification subject from host count and delivery mode. + * + * @param array $hosts Host id list. + * @param array $last_host Last host row seen while building details. + * + * @return string */ function buildRebootSubject($hosts, $last_host) { $subject = read_config_option('monitor_subject'); @@ -295,7 +345,12 @@ function buildRebootSubject($hosts, $last_host) { } /** - * Prepare report wrapper output and headers for monitor notifications. + * Wrap body output with report format template and build mail headers. + * + * @param string $body HTML body content. + * @param string $body_txt Plain text body content. + * + * @return array{string, string, array} */ function prepareReportOutput($body, $body_txt) { $output = ''; @@ -333,7 +388,12 @@ function prepareReportOutput($body, $body_txt) { } /** - * Process and send reboot notification email. + * Render and send one reboot notification email payload. + * + * @param string $email Recipient email address string. + * @param array $hosts Host ids to include in the message. + * + * @return void */ function processRebootEmail($email, $hosts) { monitorDebug("Reboot Processing for $email starting"); @@ -360,7 +420,13 @@ function processRebootEmail($email, $hosts) { } /** - * Collect alert and warning host ids from requested notification lists. + * Resolve alert/warn host ids for requested global/list subscription scopes. + * + * @param array $lists Requested scopes (`global` or list ids). + * @param array $global_list Flattened global notification host ids by severity. + * @param array $notify_list Flattened list notification host ids by severity. + * + * @return array{array, array} */ function collectNotificationHosts($lists, $global_list, $notify_list) { $alert_hosts = []; @@ -392,7 +458,12 @@ function collectNotificationHosts($lists, $global_list, $notify_list) { } /** - * Log and de-duplicate notification host ids. + * De-duplicate alert/warn host ids and log notification history entries. + * + * @param array $alert_hosts Alert host ids; normalized in place. + * @param array $warn_hosts Warning host ids; normalized in place. + * + * @return void */ function normalizeAndLogNotificationHosts(&$alert_hosts, &$warn_hosts) { if (cacti_sizeof($alert_hosts)) { @@ -407,7 +478,11 @@ function normalizeAndLogNotificationHosts(&$alert_hosts, &$warn_hosts) { } /** - * Build base intro text for ping threshold notification. + * Build shared intro copy for ping threshold email and text output. + * + * @param int $freq Resend frequency in minutes. + * + * @return array{string, string} */ function buildPingNotificationIntro($freq) { $body = '

' . __(MONITOR_PING_NOTIFICATION_SUBJECT, 'monitor') . '

' . PHP_EOL; @@ -433,7 +508,16 @@ function buildPingNotificationIntro($freq) { } /** - * Append one threshold breach section to notification body. + * Append one severity section for breached host thresholds. + * + * @param string $body HTML body output buffer. + * @param string $body_txt Plain text output buffer. + * @param array $host_ids Host ids for the section. + * @param array $criticalities Criticality label map. + * @param string $section_text Section heading text. + * @param string $threshold_field Host threshold field name. + * + * @return void */ function appendThresholdSection(&$body, &$body_txt, $host_ids, $criticalities, $section_text, $threshold_field) { global $config; @@ -486,7 +570,12 @@ function appendThresholdSection(&$body, &$body_txt, $host_ids, $criticalities, $ } /** - * Build delivery status summary for notification logging. + * Build log-friendly summary text for alert/warn delivery counts. + * + * @param array $alert_hosts Alert host ids. + * @param array $warn_hosts Warning host ids. + * + * @return string */ function buildNotificationStatus($alert_hosts, $warn_hosts) { $status = ''; @@ -507,7 +596,14 @@ function buildNotificationStatus($alert_hosts, $warn_hosts) { } /** - * Process and send ping threshold notification email. + * Build and send a ping-threshold notification for one recipient. + * + * @param string $email Recipient email. + * @param array $lists Requested scopes (`global` or list ids). + * @param array $global_list Flattened global host ids by severity. + * @param array $notify_list Flattened list host ids by severity. + * + * @return void */ function processEmail($email, $lists, $global_list, $notify_list) { monitorDebug('Into Processing'); @@ -561,7 +657,16 @@ function processEmail($email, $lists, $global_list, $notify_list) { } /** - * Send notification email through Cacti mailer. + * Send an email through Cacti mailer with configured sender fallbacks. + * + * @param string $email Recipient email string. + * @param string $subject Message subject. + * @param string $output HTML output body. + * @param string $toutput Plain text output body. + * @param array $headers Extra headers passed to mailer. + * @param string $status Status text used in logs. + * + * @return void */ function processSendEmail($email, $subject, $output, $toutput, $headers, $status) { $from_email = read_config_option('monitor_fromemail'); @@ -617,7 +722,11 @@ function processSendEmail($email, $subject, $output, $toutput, $headers, $status } /** - * Convert HTML output into plain text output. + * Convert HTML-ish report content into plain text line output. + * + * @param string $output HTML or mixed output. + * + * @return string */ function monitorText($output) { $output = explode(PHP_EOL, $output); @@ -637,7 +746,12 @@ function monitorText($output) { } /** - * Log alert or warning notification events. + * Persist alert or warning notification history rows once per host. + * + * @param string $type Severity type (`alert` or `warn`). + * @param array $alert_hosts Host ids to log for the severity. + * + * @return void */ function logMessages($type, $alert_hosts) { global $start_date; @@ -669,7 +783,15 @@ function logMessages($type, $alert_hosts) { } /** - * Add one grouped notification entry to global/notification collections. + * Add grouped host ids to global/list collections by host email mode. + * + * @param string $type Severity key (`alert` or `warn`). + * @param array $entry Grouped SQL row containing mode/list/ids. + * @param array $global_list Global grouped bucket, updated in place. + * @param array $notify_list Per-list grouped bucket, updated in place. + * @param array $lists Set of list ids used for recipient lookups. + * + * @return void */ function addGroupedNotificationEntry($type, $entry, &$global_list, &$notify_list, &$lists) { if ($entry['thold_send_email'] == '1' || $entry['thold_send_email'] == '3') { @@ -683,7 +805,15 @@ function addGroupedNotificationEntry($type, $entry, &$global_list, &$notify_list } /** - * Collect threshold-breached hosts by severity and notification list type. + * Query and group threshold-breached hosts for one severity type. + * + * @param string $type Severity key (`alert` or `warn`). + * @param int $criticality Minimum criticality threshold. + * @param array $global_list Global grouped bucket, updated in place. + * @param array $notify_list Per-list grouped bucket, updated in place. + * @param array $lists Set of notification list ids, updated in place. + * + * @return void */ function getHostsByListType($type, $criticality, &$global_list, &$notify_list, &$lists) { $last_time = date(MONITOR_DATE_TIME_FORMAT, time() - read_config_option('monitor_resend_frequency') * 60); @@ -736,7 +866,11 @@ function getHostsByListType($type, $criticality, &$global_list, &$notify_list, & } /** - * Flatten grouped list ids for one severity. + * Flatten grouped host id chunks for a single severity bucket. + * + * @param array $list Grouped rows, each row containing a CSV `id` field. + * + * @return string */ function flattenGroupSeverityList($list) { $flattened = ''; @@ -749,7 +883,11 @@ function flattenGroupSeverityList($list) { } /** - * Flatten grouped notification ids for each list id within a severity. + * Flatten grouped host ids for each notification list id. + * + * @param array $lists Grouped entries keyed by notification list id. + * + * @return array */ function flattenNotifySeverityLists($lists) { $flattened = []; @@ -762,7 +900,12 @@ function flattenNotifySeverityLists($lists) { } /** - * Flatten grouped notification structures into comma-separated host id strings. + * Flatten grouped global and per-list structures into CSV host id strings. + * + * @param array $global_list Global grouped structure, updated in place. + * @param array $notify_list Per-list grouped structure, updated in place. + * + * @return void */ function flattenLists(&$global_list, &$notify_list) { if (cacti_sizeof($global_list)) { @@ -787,7 +930,13 @@ function flattenLists(&$global_list, &$notify_list) { } /** - * Add email addresses to notification map under a scope key. + * Add email addresses into the recipient scope map. + * + * @param array $notification_emails Recipient map, updated in place. + * @param array $emails Raw email values to normalize. + * @param string|int $scope_key Scope key (`global` or list id). + * + * @return void */ function addEmailsToNotificationMap(&$notification_emails, $emails, $scope_key) { foreach ($emails as $user) { @@ -801,6 +950,10 @@ function addEmailsToNotificationMap(&$notification_emails, $emails, $scope_key) /** * Build recipient map for global and notification list subscriptions. + * + * @param array $lists Notification list ids to resolve. + * + * @return array */ function getEmailsAndLists($lists) { $notification_emails = []; @@ -832,7 +985,9 @@ function getEmailsAndLists($lists) { } /** - * Purge old notification and reboot history rows. + * Purge notification and reboot history records older than configured retention. + * + * @return array{int, int} Purged notify count and purged reboot count. */ function purgeEventRecords() { // Purge old records @@ -858,7 +1013,11 @@ function purgeEventRecords() { } /** - * Print debug message when debug mode is enabled. + * Print a debug line when poller debug mode is enabled. + * + * @param string $message Debug message. + * + * @return void */ function monitorDebug($message) { global $debug; @@ -869,7 +1028,9 @@ function monitorDebug($message) { } /** - * Display poller version information. + * Print monitor poller version information. + * + * @return void */ function displayVersion() { global $config; @@ -882,9 +1043,10 @@ function displayVersion() { print 'Cacti Monitor Poller, Version ' . $info['version'] . ', ' . COPYRIGHT_YEARS . PHP_EOL; } -/* - * display_help - * displays the usage of the function +/** + * Print CLI help output for this poller entrypoint. + * + * @return void */ function displayHelp() { displayVersion(); From 8e9d3d5fff99debc85b1bae561b209ddc3ac524f Mon Sep 17 00:00:00 2001 From: Sean Mancini Date: Sun, 1 Mar 2026 19:26:27 -0500 Subject: [PATCH 06/26] code reorginization Breaking up some of the large files --- db_functions.php | 276 +++++ js/monitor.js | 360 ++++++ monitor.php | 2571 +--------------------------------------- monitor_controller.php | 992 ++++++++++++++++ monitor_render.php | 1027 ++++++++++++++++ 5 files changed, 2660 insertions(+), 2566 deletions(-) create mode 100644 db_functions.php create mode 100644 js/monitor.js create mode 100644 monitor_controller.php create mode 100644 monitor_render.php diff --git a/db_functions.php b/db_functions.php new file mode 100644 index 0000000..4cc0237 --- /dev/null +++ b/db_functions.php @@ -0,0 +1,276 @@ + 0))"; + } else { // triggered + return "(td.thold_enabled='on' + AND ((td.thold_alert != 0 AND td.thold_fail_count >= td.thold_fail_trigger) + OR (td.bl_alert > 0 AND td.bl_fail_count >= td.bl_fail_trigger)))"; + } +} + +function checkTholds() { + $thold_hosts = []; + + if (api_plugin_is_enabled('thold')) { + return array_rekey( + db_fetch_assoc('SELECT DISTINCT dl.host_id + FROM thold_data AS td + INNER JOIN data_local AS dl + ON td.local_data_id=dl.id + WHERE ' . getTholdWhere()), + 'host_id', 'host_id' + ); + } + + return $thold_hosts; +} + + +function renderGroupConcat(&$sql_where, $sql_join, $sql_field, $sql_data, $sql_suffix = '') { + // Remove empty entries if something was returned + if (!empty($sql_data)) { + $sql_data = trim(str_replace(',,',',',$sql_data), ','); + + if (!empty($sql_data)) { + $sql_where .= ($sql_where != '' ? $sql_join : '') . "($sql_field IN($sql_data) $sql_suffix)"; + } + } +} + +function renderWhereJoin(&$sql_where, &$sql_join) { + if (get_request_var('crit') > 0) { + $awhere = 'h.monitor_criticality >= ' . get_request_var('crit'); + } else { + $awhere = ''; + } + + if (get_request_var('grouping') == 'site') { + if (get_request_var('site') > 0) { + $awhere .= ($awhere == '' ? '' : ' AND ') . 'h.site_id = ' . get_request_var('site'); + } elseif (get_request_var('site') == -2) { + $awhere .= ($awhere == '' ? '' : ' AND ') . ' h.site_id = 0'; + } + } + + if (get_request_var('rfilter') != '') { + $awhere .= ($awhere == '' ? '' : ' AND ') . " h.description RLIKE '" . get_request_var('rfilter') . "'"; + } + + if (get_request_var('grouping') == 'tree') { + if (get_request_var('tree') > 0) { + $hlist = db_fetch_cell_prepared('SELECT GROUP_CONCAT(DISTINCT host_id) + FROM graph_tree_items AS gti + INNER JOIN host AS h + ON h.id = gti.host_id + WHERE host_id > 0 + AND graph_tree_id = ? + AND h.deleted = ""', + [get_request_var('tree')]); + + renderGroupConcat($awhere, ' AND ', 'h.id', $hlist); + } elseif (get_request_var('tree') == -2) { + $hlist = db_fetch_cell('SELECT GROUP_CONCAT(DISTINCT h.id) + FROM host AS h + LEFT JOIN (SELECT DISTINCT host_id FROM graph_tree_items WHERE host_id > 0) AS gti + ON h.id = gti.host_id + WHERE gti.host_id IS NULL + AND h.deleted = ""'); + + renderGroupConcat($awhere, ' AND ', 'h.id', $hlist); + } + } + + if (!empty($awhere)) { + $awhere = ' AND ' . $awhere; + } + + if (get_request_var('status') == '0') { + $sql_join = ''; + $sql_where = 'WHERE h.disabled = "" + AND h.monitor = "on" + AND h.status < 3 + AND h.deleted = "" + AND (h.availability_method > 0 + OR h.snmp_version > 0 + OR (h.cur_time >= h.monitor_warn AND monitor_warn > 0) + OR (h.cur_time >= h.monitor_alert AND h.monitor_alert > 0) + )' . $awhere; + } elseif (get_request_var('status') == '1' || get_request_var('status') == 2) { + $sql_join = 'LEFT JOIN thold_data AS td ON td.host_id=h.id'; + + $sql_where = 'WHERE h.disabled = "" + AND h.monitor = "on" + AND h.deleted = "" + AND (h.status < 3 + OR ' . getTholdWhere() . ' + OR ((h.availability_method > 0 OR h.snmp_version > 0) + AND ((h.cur_time > h.monitor_warn AND h.monitor_warn > 0) + OR (h.cur_time > h.monitor_alert AND h.monitor_alert > 0)) + ))' . $awhere; + } elseif (get_request_var('status') == -1) { + $sql_join = 'LEFT JOIN thold_data AS td ON td.host_id=h.id'; + + $sql_where = 'WHERE h.disabled = "" + AND h.monitor = "on" + AND h.deleted = "" + AND (h.availability_method > 0 OR h.snmp_version > 0 + OR ((td.thold_enabled="on" AND td.thold_alert > 0) + OR td.id IS NULL) + )' . $awhere; + } elseif (get_request_var('status') == -2) { + $sql_join = 'LEFT JOIN thold_data AS td ON td.host_id=h.id'; + + $sql_where = 'WHERE h.disabled = "" + AND h.deleted = ""' . $awhere; + } elseif (get_request_var('status') == -3) { + $sql_join = 'LEFT JOIN thold_data AS td ON td.host_id=h.id'; + + $sql_where = 'WHERE h.disabled = "" + AND h.monitor = "" + AND h.deleted = "")' . $awhere; + } else { + $sql_join = 'LEFT JOIN thold_data AS td ON td.host_id=h.id'; + + $sql_where = 'WHERE (h.disabled = "" + AND h.deleted = "" + AND td.id IS NULL)' . $awhere; + } +} + +// Render functions + +function getHostsDownOrTriggeredByPermission($prescan) { + global $render_style; + $PreScanValue = 2; + + if ($prescan) { + $PreScanValue = 3; + } + + $result = []; + + if (get_request_var('crit') > 0) { + $sql_add_where = 'monitor_criticality >= ' . get_request_var('crit'); + } else { + $sql_add_where = ''; + } + + if (get_request_var('grouping') == 'tree') { + if (get_request_var('tree') > 0) { + $devices = db_fetch_cell_prepared('SELECT GROUP_CONCAT(DISTINCT host_id) AS hosts + FROM graph_tree_items AS gti + INNER JOIN host AS h + WHERE host_id > 0 + AND h.deleted = "" + AND graph_tree_id = ?', + [get_request_var('tree')]); + + renderGroupConcat($sql_add_where, ' OR ', 'h.id', $devices,'AND h.status < 2'); + } + } + + if (get_request_var('status') > 0) { + $triggered = db_fetch_cell('SELECT GROUP_CONCAT(DISTINCT host_id) AS hosts + FROM host AS h + INNER JOIN thold_data AS td + ON td.host_id = h.id + WHERE ' . getTholdWhere() . ' + AND h.deleted = ""'); + + renderGroupConcat($sql_add_where, ' OR ', 'h.id', $triggered, 'AND h.status > 1'); + + $_SESSION['monitor_triggered'] = array_rekey( + db_fetch_assoc('SELECT td.host_id, COUNT(DISTINCT td.id) AS triggered + FROM thold_data AS td + INNER JOIN host AS h + ON td.host_id = h.id + WHERE ' . getTholdWhere() . ' + AND h.deleted = "" + GROUP BY td.host_id'), + 'host_id', 'triggered' + ); + } + + $sql_where = "h.monitor = 'on' + AND h.disabled = '' + AND h.deleted = '' + AND ((h.status < " . $PreScanValue . ' AND (h.availability_method > 0 OR h.snmp_version > 0)) ' . + ($sql_add_where != '' ? ' OR (' . $sql_add_where . '))' : ')'); + + // do a quick loop through to pull the hosts that are down + $hosts = get_allowed_devices($sql_where); + + if (cacti_sizeof($hosts)) { + foreach ($hosts as $host) { + $result[] = $host['id']; + sort($result); + } + } + + return $result; +} + +/* +// This function is not used and contains an undefined variable + +function getHostTreeArray() { + return $leafs; +} +*/ + +function getHostNonTreeArray() { + $leafs = []; + + $sql_where = ''; + $sql_join = ''; + + renderWhereJoin($sql_where, $sql_join); + + $hierarchy = db_fetch_assoc("SELECT DISTINCT + h.*, gti.title, gti.host_id, gti.host_grouping_type, gti.graph_tree_id + FROM host AS h + LEFT JOIN graph_tree_items AS gti + ON h.id=gti.host_id + $sql_join + $sql_where + AND gti.graph_tree_id IS NULL + ORDER BY h.description"); + + if (cacti_sizeof($hierarchy) > 0) { + $leafs = []; + $branchleafs = 0; + + foreach ($hierarchy as $leaf) { + $leafs[$branchleafs] = $leaf; + $branchleafs++; + } + } + + return $leafs; +} + diff --git a/js/monitor.js b/js/monitor.js new file mode 100644 index 0000000..4e15cd0 --- /dev/null +++ b/js/monitor.js @@ -0,0 +1,360 @@ +var refreshMSeconds = 99999999; +var myTimer; +var monitorCfg = window.monitorPageConfig || {}; +var mbColor = monitorCfg.mbColor || ''; +var monitorFont = monitorCfg.monitorFont || '10px'; +var dozoomRefresh = !!monitorCfg.doZoomRefresh; +var monitorMessages = monitorCfg.messages || {}; +var monitorNewForm = monitorCfg.newForm || ''; +var monitorNewTitle = monitorCfg.newTitle || ''; + +if (mbColor !== '') { + var monoe = false; + + function setZoomErrorBackgrounds() { + if (mbColor != '') { + $('.monitor_container').css('background-color', mbColor); + $('.cactiConsoleContentArea').css('background-color', mbColor); + } + } + + setZoomErrorBackgrounds(); + $('.monitor_errorzoom_title').css('font-size', monitorFont); + + function setIntervalX(callback, delay, repetitions) { + var x = 0; + var intervalID = window.setInterval(function () { + callback(); + if (++x === repetitions) { + window.clearInterval(intervalID); + setZoomErrorBackgrounds(); + } + }, delay); + } + + setIntervalX(function () { + if (monoe === false) { + setZoomErrorBackgrounds(); + + monoe = true; + } else { + if (mbColor != '') { + $('.monitor_container').css('background-color', ''); + $('.cactiConsoleContentArea').css('background-color', ''); + } + + monoe = false; + } + }, 600, 8); +} else { + $('.monitor_container').css('background-color', ''); + $('.cactiConsoleContentArea').css('background-color', ''); +} + +function timeStep() { + value = $('#timer').html() - 1; + + if (value <= 0) { + applyFilter('refresh'); + } else { + $('#timer').html(value); + // What is a second, well if you are an + // imperial storm tropper, it's just a little more than a second. + myTimer = setTimeout(timeStep, 1284); + } +} + +function muteUnmuteAudio(mute) { + if (mute) { + $('audio').each(function() { + this.pause(); + this.currentTime = 0; + }); + } else if ($('#downhosts').val() == 'true') { + $('audio').each(function() { + this.play(); + }); + } +} + +function closeTip() { + $(document).tooltip('close'); +} + +function applyFilter(action) { + if (typeof action == 'undefined') { + action = ''; + } + + clearTimeout(myTimer); + $('.mon_icon').unbind(); + + if (action != 'dashboard') { + var strURL = 'monitor.php?header=false'; + + if (action >= '') { + strURL += '&action=' + action; + } + + strURL += '&refresh=' + $('#refresh').val(); + strURL += '&grouping=' + $('#grouping').val(); + strURL += '&tree=' + $('#tree').val(); + strURL += '&site=' + $('#site').val(); + strURL += '&template=' + $('#template').val(); + strURL += '&view=' + $('#view').val(); + strURL += '&rows=' + $('#rows').val(); + strURL += '&crit=' + $('#crit').val(); + strURL += '&size=' + $('#size').val(); + strURL += '&trim=' + $('#trim').val(); + strURL += '&mute=' + $('#mute').val(); + strURL += '&rfilter=' + base64_encode($('#rfilter').val()); + strURL += '&status=' + $('#status').val(); + } else { + strURL = 'monitor.php?action=dbchange&header=false'; + strURL += '&dashboard=' + $('#dashboard').val(); + } + + loadIt(strURL); +} + +function saveFilter() { + var url = 'monitor.php?action=save&header=false'; + + var post = { + dashboard: $('#dashboard').val(), + refresh: $('#refresh').val(), + grouping: $('#grouping').val(), + tree: $('#tree').val(), + site: $('#site').val(), + template: $('#template').val(), + view: $('#view').val(), + rows: $('#rows').val(), + crit: $('#crit').val(), + rfilter: base64_encode($('#rfilter').val()), + trim: $('#trim').val(), + mute: $('#mute').val(), + size: $('#size').val(), + trim: $('#trim').val(), + status: $('#status').val(), + __csrf_magic: csrfMagicToken + }; + + $.post(url, post).done(function(data) { + $('#text').show().text(monitorMessages.filterSaved || '').fadeOut(2000); + }); +} + +function saveNewDashboard(action) { + if (action == 'new') { + var dashboard = '-1'; + } else { + var dashboard = $('#dashboard').val(); + } + + var url = 'monitor.php?header=false'; + + var post = { + action: 'saveDb', + dashboard: dashboard, + name: $('#name').val(), + refresh: $('#refresh').val(), + grouping: $('#grouping').val(), + tree: $('#tree').val(), + site: $('#site').val(), + template: $('#template').val(), + view: $('#view').val(), + rows: $('#rows').val(), + crit: $('#crit').val(), + rfilter: base64_encode($('#rfilter').val()), + trim: $('#trim').val(), + size: $('#size').val(), + mute: $('#mute').val(), + status: $('#status').val(), + __csrf_magic: csrfMagicToken + }; + + $('#newdialog').dialog('close'); + + postIt(url, post); +} + +function removeDashboard() { + url = 'monitor.php?action=remove&header=false&dashboard=' + $('#dashboard').val(); + loadIt(url); +} + +function loadIt(url) { + if (typeof loadUrl == 'undefined') { + loadPageNoHeader(url); + } else { + loadUrl({url: url}); + } +} + +function postIt(url, post, returnLocation) { + if (typeof postUrl == 'undefined') { + loadPageUsingPost(url, post); + } else { + postUrl({ + url: url, + tabId: returnLocation, + type: 'loadPageUsingPost' + }, post); + } +} + +function saveDashboard(action) { + var btnDialog = { + 'Cancel': { + text: monitorMessages.cancel || 'Cancel', + id: 'btnCancel', + click: function() { + $(this).dialog('close'); + } + }, + 'Save': { + text: monitorMessages.save || 'Save', + id: 'btnSave', + click: function() { + saveNewDashboard(action); + } + } + }; + + if ($('#newdialog').length == 0) { + $('body').append(monitorNewForm); + } + + $('#newdialog').dialog({ + title: monitorNewTitle, + minHeight: 80, + minWidth: 500, + buttons: btnDialog, + position: { at: 'center top+240px', of: window }, + open: function() { + $('#name').val($('#dashboard option:selected').text()); + $('#btnSave').addClass('ui-state-active'); + $('#name').focus(); + $('#new_dashboard').off('submit').on('submit', function(event) { + event.preventDefault(); + saveNewDashboard('new'); + }); + } + }); +} + +$(function() { + if (dozoomRefresh) { + applyFilter('refresh'); + } + + var selectmenu = ($('#grouping').selectmenu('instance') !== undefined); + + if ($('#view').val() == 'list') { + $('#grouping').prop('disabled', true); + if (selectmenu) { + $('#grouping').selectmenu('disable'); + } + } else { + $('#grouping').prop('disabled', false); + if (selectmenu) { + $('#grouping').selectmenu('enable'); + } + } + + // Clear the timeout to keep countdown accurate + clearTimeout(myTimer); + + $('#go').click(function(event) { + event.preventDefault(); + applyFilter('go'); + }); + + $('#clear').click(function(event) { + loadIt('monitor.php?clear=1&header=false'); + }); + + $('#sound').click(function() { + if ($('#mute').val() == 'false') { + $('#mute').val('true'); + muteUnmuteAudio(true); + applyFilter('ajax_mute_all'); + } else { + $('#mute').val('false'); + muteUnmuteAudio(false); + applyFilter('ajax_unmute_all'); + } + }); + + $('#refresh, #view, #rows, #trim, #crit, #grouping, #size, #status, #tree, #site, #template').change(function() { + applyFilter('change'); + }); + + $('#dashboard').change(function() { + applyFilter('dashboard'); + }); + + $('#save').click(function() { + saveFilter(); + }); + + $('#new').click(function() { + saveDashboard('new'); + }); + + $('#rename').click(function() { + saveDashboard('rename'); + }); + + $('#delete').click(function() { + removeDashboard(); + }); + + $('.monitorFilterForm').submit(function(event) { + event.preventDefault(); + applyFilter('change'); + }); + + $('.monitor_device_frame').find('i').tooltip({ + items: '.mon_icon', + open: function(event, ui) { + ajaxAnchors(); + + if (typeof(event.originalEvent) == 'undefined') { + return false; + } + + var id = $(ui.tooltip).attr('id'); + }, + close: function(event, ui) { + ui.tooltip.hover( + function () { + $(this).stop(true).fadeTo(400, 1); + }, + function() { + $(this).fadeOut('400'); + }); + }, + position: {my: 'left:15 top', at: 'right center'}, + content: function(callback) { + var id = $(this).attr('id'); + var size = $('#size').val(); + $.get('monitor.php?action=ajax_status&size=' + size + '&id=' + id, function(data) { + callback(data); + }); + } + }); + + myTimer = setTimeout(timeStep, 1000); + + $(window).resize(function() { + $(document).tooltip('option', 'position', {my: '1eft:15 top', at: 'right center'}); + }); + + if ($('#mute').val() == 'true') { + muteUnmuteAudio(true); + } else { + muteUnmuteAudio(false); + } + $('#main').css('margin-right', '15px'); +}); diff --git a/monitor.php b/monitor.php index eb2c7ba..b4de788 100644 --- a/monitor.php +++ b/monitor.php @@ -125,6 +125,11 @@ $_SESSION['monitor_muted_hosts'] = []; } + +include_once __DIR__ . '/db_functions.php'; +include_once __DIR__ . '/monitor_render.php'; +include_once __DIR__ . '/monitor_controller.php'; + validateRequestVars(); if (!db_column_exists('host', 'monitor_icon')) { @@ -172,2569 +177,3 @@ } exit; - -function loadDashboardSettings() { - $dashboard = get_filter_request_var('dashboard'); - - if ($dashboard > 0) { - $db_settings = db_fetch_cell_prepared('SELECT url - FROM plugin_monitor_dashboards - WHERE id = ?', - [$dashboard]); - - if ($db_settings != '') { - $db_settings = str_replace('monitor.php?', '', $db_settings); - $settings = explode('&', $db_settings); - - if (cacti_sizeof($settings)) { - foreach ($settings as $setting) { - [$name, $value] = explode('=', $setting); - - set_request_var($name, $value); - } - } - } - } -} - -function drawPage() { - global $config, $iclasses, $icolorsdisplay, $mon_zoom_state, $dozoomrefresh, $dozoombgndcolor, $font_sizes; - global $new_form, $new_title; - - $errored_list = getHostsDownOrTriggeredByPermission(true); - - if (cacti_sizeof($errored_list) && read_user_setting('monitor_error_zoom') == 'on') { - if ($_SESSION['monitor_zoom_state'] == 0) { - $mon_zoom_state = $_SESSION['monitor_zoom_state'] = 1; - $_SESSION['mon_zoom_hist_status'] = get_nfilter_request_var('status'); - $_SESSION['mon_zoom_hist_size'] = get_nfilter_request_var('size'); - $dozoomrefresh = true; - $dozoombgndcolor = true; - } - } elseif (isset($_SESSION['monitor_zoom_state']) && $_SESSION['monitor_zoom_state'] == 1) { - $_SESSION['monitor_zoom_state'] = 0; - $dozoomrefresh = true; - $dozoombgndcolor = false; - } - - $name = db_fetch_cell_prepared('SELECT name - FROM plugin_monitor_dashboards - WHERE id = ?', - [get_request_var('dashboard')]); - - if ($name == '') { - $name = __('New Dashboard', 'monitor'); - } - - $new_form = "
" . __('Enter the Dashboard Name and then press \'Save\' to continue, else press \'Cancel\'', 'monitor') . '
' . __('Dashboard', 'monitor') . "
"; - - $new_title = __('Create New Dashboard', 'monitor'); - - findDownHosts(); - - general_header(); - - drawFilterAndStatus(); - - print ''; - - // Default with permissions = default_by_permission - // Tree = group_by_tree - $function = 'render' . ucfirst(get_request_var('grouping')); - - if (function_exists($function) && get_request_var('view') != 'list') { - if (get_request_var('grouping') == 'default' || get_request_var('grouping') == 'site') { - html_start_box(__('Monitored Devices', 'monitor'), '100%', true, '3', 'center', ''); - } else { - html_start_box('', '100%', true, '3', 'center', ''); - } - print $function(); - } else { - print renderDefault(); - } - - print ''; - - html_end_box(); - - if (read_user_setting('monitor_legend', read_config_option('monitor_legend'))) { - print "
"; - - foreach ($iclasses as $index => $class) { - print "
" . $icolorsdisplay[$index] . '
'; - } - - print '
'; - } - - // If the host is down, we need to insert the embedded wav file - $monitor_sound = getMonitorSound(); - - if (isMonitorAudible()) { - if (read_user_setting('monitor_sound_loop', read_config_option('monitor_sound_loop'))) { - print ""; - } else { - print ""; - } - } - - print '
' . getFilterText() . '
'; - - bottom_footer(); -} - -function isMonitorAudible() { - return getMonitorSound() != ''; -} - -function getMonitorSound() { - $sound = read_user_setting('monitor_sound', read_config_option('monitor_sound')); - clearstatcache(); - $file = __DIR__ . '/sounds/' . $sound; - $exists = file_exists($file); - - return $exists ? $sound : ''; -} - -function findDownHosts() { - $dhosts = getHostsDownOrTriggeredByPermission(false); - - if (cacti_sizeof($dhosts)) { - set_request_var('downhosts', 'true'); - - if (isset($_SESSION['monitor_muted_hosts'])) { - unmute_up_non_triggered_hosts($dhosts); - - $unmuted_hosts = array_diff($dhosts, $_SESSION['monitor_muted_hosts']); - - if (cacti_sizeof($unmuted_hosts)) { - unmute_user(); - } - } else { - set_request_var('mute', 'false'); - } - } else { - unmuteAllHosts(); - set_request_var('downhosts', 'false'); - } -} - -function unmuteUpNonTriggeredHosts($dhosts) { - if (isset($_SESSION['monitor_muted_hosts'])) { - foreach ($_SESSION['monitor_muted_hosts'] as $index => $host_id) { - if (array_search($host_id, $dhosts, true) === false) { - unset($_SESSION['monitor_muted_hosts'][$index]); - } - } - } -} - -function muteAllHosts() { - $_SESSION['monitor_muted_hosts'] = getHostsDownOrTriggeredByPermission(false); - muteUser(); -} - -function unmuteAllHosts() { - $_SESSION['monitor_muted_hosts'] = []; - unmuteUser(); -} - -function muteUser() { - set_request_var('mute', 'true'); - set_user_setting('monitor_mute', 'true'); -} - -function unmuteUser() { - set_request_var('mute', 'false'); - set_user_setting('monitor_mute','false'); -} - -function getTholdWhere() { - if (get_request_var('status') == '2') { // breached - return "(td.thold_enabled = 'on' - AND (td.thold_alert != 0 OR td.bl_alert > 0))"; - } else { // triggered - return "(td.thold_enabled='on' - AND ((td.thold_alert != 0 AND td.thold_fail_count >= td.thold_fail_trigger) - OR (td.bl_alert > 0 AND td.bl_fail_count >= td.bl_fail_trigger)))"; - } -} - -function checkTholds() { - $thold_hosts = []; - - if (api_plugin_is_enabled('thold')) { - return array_rekey( - db_fetch_assoc('SELECT DISTINCT dl.host_id - FROM thold_data AS td - INNER JOIN data_local AS dl - ON td.local_data_id=dl.id - WHERE ' . getTholdWhere()), - 'host_id', 'host_id' - ); - } - - return $thold_hosts; -} - -function getFilterText() { - $filter = '
'; - - switch(get_request_var('status')) { - case '-4': - $filter .= __('Devices without Thresholds', 'monitor'); - - break; - case '-3': - $filter .= __('Not Monitored Devices', 'monitor'); - - break; - case '-2': - $filter .= __('All Devices', 'monitor'); - - break; - case '-1': - $filter .= __('All Monitored Devices', 'monitor'); - - break; - case '0': - $filter .= __('Monitored Devices either Down or Recovering', 'monitor'); - - break; - case '1': - $filter .= __('Monitored Devices either Down, Recovering, or with Triggered Thresholds', 'monitor'); - - break; - case '2': - $filter .= __('Monitored Devices either Down, Recovering, or with Breached or Triggered Thresholds', 'monitor'); - - break; - default: - $filter .= __('Unknown monitoring status (%s)', get_request_var('status'), 'monitor'); - } - - switch(get_request_var('crit')) { - case '0': - $filter .= __(', and All Criticalities', 'monitor'); - - break; - case '1': - $filter .= __(', and of Low Criticality or Higher', 'monitor'); - - break; - case '2': - $filter .= __(', and of Medium Criticality or Higher', 'monitor'); - - break; - case '3': - $filter .= __(', and of High Criticality or Higher', 'monitor'); - - break; - case '4': - $filter .= __(', and of Mission Critical Status', 'monitor'); - - break; - } - - $filter .= __('
Remember to first select eligible Devices to be Monitored from the Devices page!
', 'monitor'); - - return $filter; -} - -function drawFilterDropdown($id, $title, $settings = [], $value = null) { - if ($value == null) { - $value = get_nfilter_request_var($id); - } - - if (cacti_sizeof($settings)) { - print '' . html_escape($title) . ''; - print '' . PHP_EOL; - } else { - print "" . PHP_EOL; - } -} - -function drawFilterAndStatus() { - global $criticalities, $page_refresh_interval, $classes, $monitor_grouping; - global $monitor_view_type, $monitor_status, $monitor_trim; - global $dozoombgndcolor, $dozoomrefresh, $zoom_hist_status, $zoom_hist_size, $mon_zoom_state; - global $new_form, $new_title, $item_rows; - - $header = __('Monitor Filter [ Last Refresh: %s ]', date('g:i:s a', time()), 'monitor') . (get_request_var('refresh') < 99999 ? __(' [ Refresh Again in %d Seconds ]', get_request_var('refresh'), 'monitor') : '') . (get_request_var('view') == 'list' ? __('[ Showing only first 30 Devices ]', 'monitor') : '') . ''; - - html_start_box($header, '100%', false, '3', 'center', ''); - - print '' . PHP_EOL; - print '
' . PHP_EOL; - - // First line of filter - print '' . PHP_EOL; - print '' . PHP_EOL; - - $dashboards[0] = __('Unsaved', 'monitor'); - $dashboards += array_rekey( - db_fetch_assoc_prepared('SELECT id, name - FROM plugin_monitor_dashboards - WHERE user_id = 0 OR user_id = ? - ORDER BY name', - [$_SESSION['sess_user_id']]), - 'id', 'name' - ); - - $name = db_fetch_cell_prepared('SELECT name - FROM plugin_monitor_dashboards - WHERE id = ?', - [get_request_var('dashboard')]); - - $mon_zoom_status = null; - $mon_zoom_size = null; - - if (isset($_SESSION['monitor_zoom_state'])) { - if ($_SESSION['monitor_zoom_state'] == 1) { - $mon_zoom_status = 2; - $mon_zoom_size = 'monitor_errorzoom'; - $dozoombgndcolor = true; - } else { - if (isset($_SESSION['mon_zoom_hist_status'])) { - $mon_zoom_status = $_SESSION['mon_zoom_hist_status']; - } else { - $mon_zoom_status = null; - } - - if (isset($_SESSION['mon_zoom_hist_size'])) { - $currentddsize = get_nfilter_request_var('size'); - - if ($currentddsize != $_SESSION['mon_zoom_hist_size'] && $currentddsize != 'monitor_errorzoom') { - $_SESSION['mon_zoom_hist_size'] = $currentddsize; - } - - $mon_zoom_size = $_SESSION['mon_zoom_hist_size']; - } else { - $mon_zoom_size = null; - } - } - } - - drawFilterDropdown('dashboard', __('Layout', 'monitor'), $dashboards); - drawFilterDropdown('status', __('Status', 'monitor'), $monitor_status, $mon_zoom_status); - drawFilterDropdown('view', __('View', 'monitor'), $monitor_view_type); - drawFilterDropdown('grouping', __('Grouping', 'monitor'), $monitor_grouping); - drawFilterDropdown('rows', __('Devices', 'monitor'), $item_rows); - - // Buttons - print ''; - print ''; - print '
' . PHP_EOL; - - print '' . PHP_EOL; - - print '' . PHP_EOL; - - print '' . PHP_EOL; - - print '' . PHP_EOL; - - if (get_request_var('dashboard') > 0) { - print '' . PHP_EOL; - } - - if (get_request_var('dashboard') > 0) { - print '' . PHP_EOL; - } - - print '' . PHP_EOL; - print '' . PHP_EOL; - print '
'; - - // Second line of filter - print '' . PHP_EOL; - print '' . PHP_EOL; - print ''; - print ''; - - drawFilterDropdown('crit', __('Criticality', 'monitor'), $criticalities); - - if (get_request_var('view') != 'list') { - drawFilterDropdown('size', __('Size', 'monitor'), $classes, $mon_zoom_size); - } - - if (get_request_var('view') == 'default' || get_request_var('view') == 'names') { - drawFilterDropdown('trim', __('Trim', 'monitor'), $monitor_trim); - } - - if (get_nfilter_request_var('grouping') == 'tree') { - $trees = []; - - if (get_request_var('grouping') == 'tree') { - $trees_allowed = array_rekey(get_allowed_trees(), 'id', 'name'); - - if (cacti_sizeof($trees_allowed)) { - $trees_prefix = [-1 => __('All Trees', 'monitor')]; - $trees_suffix = [-2 => __('Non-Tree Devices', 'monitor')]; - - $trees = $trees_prefix + $trees_allowed + $trees_suffix; - } - } - - drawFilterDropdown('tree', __('Tree', 'monitor'), $trees); - } - - if (get_nfilter_request_var('grouping') == 'site') { - $sites = []; - - if (get_request_var('grouping') == 'site') { - $sites = array_rekey( - db_fetch_assoc('SELECT id, name - FROM sites - ORDER BY name'), - 'id', 'name' - ); - - if (cacti_sizeof($sites)) { - $sites_prefix = [-1 => __('All Sites', 'monitor')]; - $sites_suffix = [-2 => __('Non-Site Devices', 'monitor')]; - - $sites = $sites_prefix + $sites + $sites_suffix; - } - } - - drawFilterDropdown('site', __('Sites', 'monitor'), $sites); - } - - if (get_request_var('grouping') == 'template') { - $templates = []; - $templates_allowed = array_rekey( - db_fetch_assoc('SELECT ht.id, ht.name, COUNT(gl.id) AS graphs - FROM host_template AS ht - INNER JOIN host AS h - ON h.host_template_id = ht.id - INNER JOIN graph_local AS gl - ON h.id = gl.host_id - GROUP BY ht.id - HAVING graphs > 0'), - 'id', 'name' - ); - - if (cacti_sizeof($templates_allowed)) { - $templates_prefix = [-1 => __('All Templates', 'monitor')]; - $templates_suffix = [-2 => __('Non-Templated Devices', 'monitor')]; - - $templates = $templates_prefix + $templates_allowed + $templates_suffix; - } - - drawFilterDropdown('template', __('Template', 'monitor'), $templates); - } - - drawFilterDropdown('refresh', __('Refresh', 'monitor'), $page_refresh_interval); - - if (get_request_var('grouping') != 'tree') { - print '' . PHP_EOL; - } - - if (get_request_var('grouping') != 'site') { - print '' . PHP_EOL; - } - - if (get_request_var('grouping') != 'template') { - print '' . PHP_EOL; - } - - if (get_request_var('view') == 'list') { - print '' . PHP_EOL; - } - - if (get_request_var('view') != 'default') { - print '' . PHP_EOL; - } - - print ''; - print '
' . __('Search', 'monitor') . '
'; - print '
' . PHP_EOL; - - html_end_box(); - - if ($dozoombgndcolor) { - $mbcolora = db_fetch_row_prepared('SELECT * - FROM colors - WHERE id = ?', - [read_user_setting('monitor_error_background')]); - - $monitor_error_fontsize = read_user_setting('monitor_error_fontsize') . 'px'; - - if (cacti_sizeof($mbcolora)) { - $mbcolor = '#' . $mbcolora['hex']; - } else { - $mbcolor = 'snow'; - } - } else { - $mbcolor = ''; - $monitor_error_fontsize = '10px'; - } - - ?> - - $value) { - switch($var) { - case 'dashboard': - set_user_setting('monitor_rfilter', get_request_var('dashboard')); - - break; - case 'rfilter': - set_user_setting('monitor_rfilter', get_request_var('rfilter')); - - break; - case 'refresh': - set_user_setting('monitor_refresh', get_request_var('refresh')); - - break; - case 'grouping': - set_user_setting('monitor_grouping', get_request_var('grouping')); - - break; - case 'view': - set_user_setting('monitor_view', get_request_var('view')); - - break; - case 'rows': - set_user_setting('monitor_rows', get_request_var('rows')); - - break; - case 'crit': - set_user_setting('monitor_crit', get_request_var('crit')); - - break; - case 'mute': - set_user_setting('monitor_mute', get_request_var('mute')); - - break; - case 'size': - set_user_setting('monitor_size', get_request_var('size')); - - break; - case 'trim': - set_user_setting('monitor_trim', get_request_var('trim')); - - break; - case 'status': - set_user_setting('monitor_status', get_request_var('status')); - - break; - case 'tree': - set_user_setting('monitor_tree', get_request_var('tree')); - - break; - case 'mute': - set_user_setting('monitor_mute', get_request_var('mute')); - - break; - case 'site': - set_user_setting('monitor_site', get_request_var('site')); - - break; - } - } - } - } else { - $url = 'monitor.php' . - '?refresh=' . get_request_var('refresh') . - '&grouping=' . get_request_var('grouping') . - '&view=' . get_request_var('view') . - '&rows=' . get_request_var('rows') . - '&crit=' . get_request_var('crit') . - '&size=' . get_request_var('size') . - '&trim=' . get_request_var('trim') . - '&status=' . get_request_var('status') . - '&tree=' . get_request_var('tree') . - '&site=' . get_request_var('site'); - - if (!isset_request_var('user')) { - $user = $_SESSION['sess_user_id']; - } else { - $user = get_request_var('user'); - } - - $id = get_request_var('dashboard'); - $name = get_nfilter_request_var('name'); - - $save = []; - $save['id'] = $id; - $save['name'] = $name; - $save['user_id'] = $user; - $save['url'] = $url; - - $id = sql_save($save, 'plugin_monitor_dashboards'); - - if (!empty($id)) { - raise_message('monitorsaved', __('Dashboard \'%s\' has been Saved!', $name, 'monitor'), MESSAGE_LEVEL_INFO); - set_request_var('dashboard', $id); - } else { - raise_message('monitornotsaved', __('Dashboard \'%s\' could not be Saved!', $name, 'monitor'), MESSAGE_LEVEL_INFO); - set_request_var('dashboard', '0'); - } - } - - validateRequestVars(true); -} - -function validateRequestVars($force = false) { - // ================= input validation and session storage ================= - $filters = [ - 'refresh' => [ - 'filter' => FILTER_VALIDATE_INT, - 'default' => read_user_setting('monitor_refresh', read_config_option('monitor_refresh'), $force) - ], - 'dashboard' => [ - 'filter' => FILTER_VALIDATE_INT, - 'pageset' => true, - 'default' => read_user_setting('monitor_dashboard', '0', $force) - ], - 'rfilter' => [ - 'filter' => FILTER_VALIDATE_IS_REGEX, - 'pageset' => true, - 'default' => read_user_setting('monitor_rfilter', '', $force) - ], - 'name' => [ - 'filter' => FILTER_CALLBACK, - 'options' => ['options' => 'sanitize_search_string'], - 'default' => '' - ], - 'mute' => [ - 'filter' => FILTER_CALLBACK, - 'options' => ['options' => 'sanitize_search_string'], - 'default' => read_user_setting('monitor_mute', 'false', $force) - ], - 'grouping' => [ - 'filter' => FILTER_CALLBACK, - 'options' => ['options' => 'sanitize_search_string'], - 'pageset' => true, - 'default' => read_user_setting('monitor_grouping', read_config_option('monitor_grouping'), $force) - ], - 'view' => [ - 'filter' => FILTER_CALLBACK, - 'options' => ['options' => 'sanitize_search_string'], - 'pageset' => true, - 'default' => read_user_setting('monitor_view', read_config_option('monitor_view'), $force) - ], - 'rows' => [ - 'filter' => FILTER_VALIDATE_INT, - 'options' => ['options' => 'sanitize_search_string'], - 'default' => read_user_setting('monitor_rows', read_config_option('num_rows_table'), $force) - ], - 'size' => [ - 'filter' => FILTER_CALLBACK, - 'options' => ['options' => 'sanitize_search_string'], - 'default' => read_user_setting('monitor_size', 'monitor_medium', $force) - ], - 'trim' => [ - 'filter' => FILTER_VALIDATE_INT, - 'default' => read_user_setting('monitor_trim', read_config_option('monitor_trim'), $force) - ], - 'crit' => [ - 'filter' => FILTER_VALIDATE_INT, - 'pageset' => true, - 'default' => read_user_setting('monitor_crit', '-1', $force) - ], - 'status' => [ - 'filter' => FILTER_VALIDATE_INT, - 'pageset' => true, - 'default' => read_user_setting('monitor_status', '-1', $force) - ], - 'tree' => [ - 'filter' => FILTER_VALIDATE_INT, - 'pageset' => true, - 'default' => read_user_setting('monitor_tree', '-1', $force) - ], - 'site' => [ - 'filter' => FILTER_VALIDATE_INT, - 'pageset' => true, - 'default' => read_user_setting('monitor_site', '-1', $force) - ], - 'template' => [ - 'filter' => FILTER_VALIDATE_INT, - 'pageset' => true, - 'default' => read_user_setting('monitor_template', '-1', $force) - ], - 'id' => [ - 'filter' => FILTER_VALIDATE_INT, - 'default' => '-1' - ], - 'page' => [ - 'filter' => FILTER_VALIDATE_INT, - 'default' => '1' - ], - 'sort_column' => [ - 'filter' => FILTER_CALLBACK, - 'default' => 'status', - 'options' => ['options' => 'sanitize_search_string'] - ], - 'sort_direction' => [ - 'filter' => FILTER_CALLBACK, - 'default' => 'ASC', - 'options' => ['options' => 'sanitize_search_string'] - ] - ]; - - validate_store_request_vars($filters, 'sess_monitor'); - // ================= input validation ================= -} - -function renderGroupConcat(&$sql_where, $sql_join, $sql_field, $sql_data, $sql_suffix = '') { - // Remove empty entries if something was returned - if (!empty($sql_data)) { - $sql_data = trim(str_replace(',,',',',$sql_data), ','); - - if (!empty($sql_data)) { - $sql_where .= ($sql_where != '' ? $sql_join : '') . "($sql_field IN($sql_data) $sql_suffix)"; - } - } -} - -function renderWhereJoin(&$sql_where, &$sql_join) { - if (get_request_var('crit') > 0) { - $awhere = 'h.monitor_criticality >= ' . get_request_var('crit'); - } else { - $awhere = ''; - } - - if (get_request_var('grouping') == 'site') { - if (get_request_var('site') > 0) { - $awhere .= ($awhere == '' ? '' : ' AND ') . 'h.site_id = ' . get_request_var('site'); - } elseif (get_request_var('site') == -2) { - $awhere .= ($awhere == '' ? '' : ' AND ') . ' h.site_id = 0'; - } - } - - if (get_request_var('rfilter') != '') { - $awhere .= ($awhere == '' ? '' : ' AND ') . " h.description RLIKE '" . get_request_var('rfilter') . "'"; - } - - if (get_request_var('grouping') == 'tree') { - if (get_request_var('tree') > 0) { - $hlist = db_fetch_cell_prepared('SELECT GROUP_CONCAT(DISTINCT host_id) - FROM graph_tree_items AS gti - INNER JOIN host AS h - ON h.id = gti.host_id - WHERE host_id > 0 - AND graph_tree_id = ? - AND h.deleted = ""', - [get_request_var('tree')]); - - renderGroupConcat($awhere, ' AND ', 'h.id', $hlist); - } elseif (get_request_var('tree') == -2) { - $hlist = db_fetch_cell('SELECT GROUP_CONCAT(DISTINCT h.id) - FROM host AS h - LEFT JOIN (SELECT DISTINCT host_id FROM graph_tree_items WHERE host_id > 0) AS gti - ON h.id = gti.host_id - WHERE gti.host_id IS NULL - AND h.deleted = ""'); - - renderGroupConcat($awhere, ' AND ', 'h.id', $hlist); - } - } - - if (!empty($awhere)) { - $awhere = ' AND ' . $awhere; - } - - if (get_request_var('status') == '0') { - $sql_join = ''; - $sql_where = 'WHERE h.disabled = "" - AND h.monitor = "on" - AND h.status < 3 - AND h.deleted = "" - AND (h.availability_method > 0 - OR h.snmp_version > 0 - OR (h.cur_time >= h.monitor_warn AND monitor_warn > 0) - OR (h.cur_time >= h.monitor_alert AND h.monitor_alert > 0) - )' . $awhere; - } elseif (get_request_var('status') == '1' || get_request_var('status') == 2) { - $sql_join = 'LEFT JOIN thold_data AS td ON td.host_id=h.id'; - - $sql_where = 'WHERE h.disabled = "" - AND h.monitor = "on" - AND h.deleted = "" - AND (h.status < 3 - OR ' . getTholdWhere() . ' - OR ((h.availability_method > 0 OR h.snmp_version > 0) - AND ((h.cur_time > h.monitor_warn AND h.monitor_warn > 0) - OR (h.cur_time > h.monitor_alert AND h.monitor_alert > 0)) - ))' . $awhere; - } elseif (get_request_var('status') == -1) { - $sql_join = 'LEFT JOIN thold_data AS td ON td.host_id=h.id'; - - $sql_where = 'WHERE h.disabled = "" - AND h.monitor = "on" - AND h.deleted = "" - AND (h.availability_method > 0 OR h.snmp_version > 0 - OR ((td.thold_enabled="on" AND td.thold_alert > 0) - OR td.id IS NULL) - )' . $awhere; - } elseif (get_request_var('status') == -2) { - $sql_join = 'LEFT JOIN thold_data AS td ON td.host_id=h.id'; - - $sql_where = 'WHERE h.disabled = "" - AND h.deleted = ""' . $awhere; - } elseif (get_request_var('status') == -3) { - $sql_join = 'LEFT JOIN thold_data AS td ON td.host_id=h.id'; - - $sql_where = 'WHERE h.disabled = "" - AND h.monitor = "" - AND h.deleted = "")' . $awhere; - } else { - $sql_join = 'LEFT JOIN thold_data AS td ON td.host_id=h.id'; - - $sql_where = 'WHERE (h.disabled = "" - AND h.deleted = "" - AND td.id IS NULL)' . $awhere; - } -} - -// Render functions -function renderDefault() { - global $maxchars; - - $result = ''; - - $sql_where = ''; - $sql_join = ''; - $sql_limit = ''; - $sql_order = 'ORDER BY description'; - - $rows = get_request_var('rows'); - - if ($rows == '-1') { - $rows = read_user_setting('monitor_rows'); - } - - if (!is_numeric($rows)) { - $rows = read_config_option('num_rows_table'); - } - - if (get_request_var('view') == 'list') { - $sql_order = get_order_string(); - } - - renderWhereJoin($sql_where, $sql_join); - - $poller_interval = read_config_option('poller_interval'); - - $sql_limit = ' LIMIT ' . ($rows * (get_request_var('page') - 1)) . ',' . $rows; - - $hosts_sql = ("SELECT DISTINCT h.*, IFNULL(s.name,' " . __('Non-Site Device', 'monitor') . " ') AS site_name, - CAST(IF(availability_method = 0, '0', - IF(status_event_count > 0 AND status IN (1, 2), status_event_count*$poller_interval, - IF(UNIX_TIMESTAMP(status_rec_date) < 943916400 AND status IN (0, 3), total_polls*$poller_interval, - IF(UNIX_TIMESTAMP(status_rec_date) > 943916400, UNIX_TIMESTAMP() - UNIX_TIMESTAMP(status_rec_date), - IF(snmp_sysUptimeInstance>0 AND snmp_version > 0, snmp_sysUptimeInstance/100, UNIX_TIMESTAMP() - ))))) AS unsigned) AS instate - FROM host AS h - LEFT JOIN sites AS s - ON h.site_id = s.id - $sql_join - $sql_where - $sql_order - $sql_limit"); - - $hosts = db_fetch_assoc($hosts_sql); - - $total_rows = db_fetch_cell("SELECT COUNT(DISTINCT h.id) - FROM host AS h - LEFT JOIN sites AS s - ON h.site_id = s.id - $sql_join - $sql_where"); - - if (cacti_sizeof($hosts)) { - // Determine the correct width of the cell - $maxlen = 10; - - if (get_request_var('view') == 'default') { - $maxlen = db_fetch_cell("SELECT MAX(LENGTH(description)) - FROM host AS h - $sql_join - $sql_where"); - } - - $maxlen = getMonitorTrimLength($maxlen); - - $function = 'renderHeader' . ucfirst(get_request_var('view')); - - if (function_exists($function)) { - // Call the custom render_header_ function - $result .= $function($hosts, $total_rows, $rows); - } - - $count = 0; - - foreach ($hosts as $host) { - if (is_device_allowed($host['id'])) { - $result .= renderHost($host, true, $maxlen); - } - - $count++; - } - - $function = 'renderFooter' . ucfirst(get_request_var('view')); - - if (function_exists($function)) { - // Call the custom render_footer_ function - $result .= $function($hosts, $total_rows, $rows); - } - } - - return $result; -} - -function renderSite() { - global $maxchars; - - $result = ''; - - $sql_where = ''; - $sql_join = ''; - $sql_limit = ''; - - $rows = get_request_var('rows'); - - if ($rows == '-1') { - $rows = read_user_setting('monitor_rows'); - } - - if (!is_numeric($rows)) { - $rows = read_config_option('num_rows_table'); - } - - renderWhereJoin($sql_where, $sql_join); - - $sql_limit = ' LIMIT ' . ($rows * (get_request_var('page') - 1)) . ',' . $rows; - - $hosts_sql = ("SELECT DISTINCT h.*, IFNULL(s.name,' " . __('Non-Site Devices', 'monitor') . " ') AS site_name - FROM host AS h - LEFT JOIN sites AS s - ON s.id = h.site_id - $sql_join - $sql_where - ORDER BY site_name, description - $sql_limit"); - - $hosts = db_fetch_assoc($hosts_sql); - - $ctemp = -1; - $ptemp = -1; - - if (cacti_sizeof($hosts)) { - $suppressGroups = false; - $function = 'renderSuppressgroups' . ucfirst(get_request_var('view')); - - if (function_exists($function)) { - $suppressGroups = $function($hosts); - } - - $function = 'renderHeader' . ucfirst(get_request_var('view')); - - if (function_exists($function)) { - // Call the custom render_header_ function - $result .= $function($hosts); - $suppressGroups = true; - } - - foreach ($hosts as $index => $host) { - if (is_device_allowed($host['id'])) { - $host_ids[] = $host['id']; - } else { - unset($hosts[$index]); - } - } - - // Determine the correct width of the cell - $maxlen = 10; - - if (get_request_var('view') == 'default') { - $maxlen = db_fetch_cell('SELECT MAX(LENGTH(description)) - FROM host AS h - WHERE id IN (' . implode(',', $host_ids) . ')'); - } - $maxlen = getMonitorTrimLength($maxlen); - - $class = get_request_var('size'); - $csuffix = get_request_var('view'); - - if ($csuffix == 'default') { - $csuffix = ''; - } - - foreach ($hosts as $host) { - $ctemp = $host['site_id']; - - if (!$suppressGroups) { - if ($ctemp != $ptemp && $ptemp > 0) { - $result .= '
'; - } - - if ($ctemp != $ptemp) { - $result .= "
- -
-
"; - } - } - - $result .= renderHost($host, true, $maxlen); - - if ($ctemp != $ptemp) { - $ptemp = $ctemp; - } - } - - if ($ptemp == $ctemp && !$suppressGroups) { - $result .= '
'; - } - - $function = 'renderFooter' . ucfirst(get_request_var('view')); - - if (function_exists($function)) { - // Call the custom render_footer_ function - $result .= $function($hosts); - } - } - - return $result; -} - -function renderTemplate() { - global $maxchars; - - $result = ''; - - $sql_where = ''; - $sql_join = ''; - $sql_limit = ''; - - $rows = get_request_var('rows'); - - if ($rows == '-1') { - $rows = read_user_setting('monitor_rows'); - } - - if (!is_numeric($rows)) { - $rows = read_config_option('num_rows_table'); - } - - renderWhereJoin($sql_where, $sql_join); - - $sql_limit = ' LIMIT ' . ($rows * (get_request_var('page') - 1)) . ',' . $rows; - - if (get_request_var('template') > 0) { - $sql_where .= ($sql_where == '' ? '' : 'AND ') . 'ht.id = ' . get_request_var('template'); - } - - $sql_template = 'INNER JOIN host_template AS ht ON h.host_template_id=ht.id '; - - if (get_request_var('template') == -2) { - $sql_where .= ($sql_where == '' ? '' : 'AND ') . 'ht.id IS NULL'; - $sql_template = 'LEFT JOIN host_template AS ht ON h.host_template_id=ht.id '; - } - - $hosts = db_fetch_assoc("SELECT DISTINCT - h.*, ht.name AS host_template_name - FROM host AS h - $sql_template - $sql_join - $sql_where - ORDER BY ht.name, h.description - $sql_limit"); - - $ctemp = -1; - $ptemp = -1; - - if (cacti_sizeof($hosts)) { - $suppressGroups = false; - $function = 'renderSuppressgroups' . ucfirst(get_request_var('view')); - - if (function_exists($function)) { - $suppressGroups = $function($hosts); - } - - $function = 'renderHeader' . ucfirst(get_request_var('view')); - - if (function_exists($function)) { - // Call the custom render_header_ function - $result .= $function($hosts); - $suppressGroups = true; - } - - foreach ($hosts as $index => $host) { - if (is_device_allowed($host['id'])) { - $host_ids[] = $host['id']; - } else { - unset($hosts[$index]); - } - } - - // Determine the correct width of the cell - $maxlen = 10; - - if (get_request_var('view') == 'default') { - $maxlen = db_fetch_cell('SELECT MAX(LENGTH(description)) - FROM host AS h - WHERE id IN (' . implode(',', $host_ids) . ')'); - } - $maxlen = getMonitorTrimLength($maxlen); - - $class = get_request_var('size'); - $csuffix = get_request_var('view'); - - if ($csuffix == 'default') { - $csuffix = ''; - } - - foreach ($hosts as $host) { - $ctemp = $host['host_template_id']; - - if (!$suppressGroups) { - if ($ctemp != $ptemp && $ptemp > 0) { - $result .= ''; - } - - if ($ctemp != $ptemp) { - $result .= "
- -
-
"; - } - } - - $result .= renderHost($host, true, $maxlen); - - if ($ctemp != $ptemp) { - $ptemp = $ctemp; - } - } - - if ($ptemp == $ctemp && !$suppressGroups) { - $result .= '
'; - } - - $function = 'renderFooter' . ucfirst(get_request_var('view')); - - if (function_exists($function)) { - // Call the custom render_footer_ function - $result .= $function($hosts); - } - } - - return $result; -} - -function renderTree() { - global $maxchars; - - $result = ''; - - $leafs = []; - - if (get_request_var('tree') > 0) { - $sql_where = 'gt.id=' . get_request_var('tree'); - } else { - $sql_where = ''; - } - - if (get_request_var('tree') != -2) { - $tree_list = get_allowed_trees(false, false, $sql_where, 'sequence'); - } else { - $tree_list = []; - } - - $function = 'renderHeader' . ucfirst(get_request_var('view')); - - if (function_exists($function)) { - $hosts = []; - - // Call the custom render_header_ function - $result .= $function($hosts); - } - - if (cacti_sizeof($tree_list)) { - $ptree = ''; - - foreach ($tree_list as $tree) { - $tree_ids[$tree['id']] = $tree['id']; - } - - renderWhereJoin($sql_where, $sql_join); - - $branchWhost_SQL = ("SELECT DISTINCT gti.graph_tree_id, gti.parent - FROM graph_tree_items AS gti - INNER JOIN graph_tree AS gt - ON gt.id = gti.graph_tree_id - INNER JOIN host AS h - ON h.id = gti.host_id - $sql_join - $sql_where - AND gti.host_id > 0 - AND gti.graph_tree_id IN (" . implode(',', $tree_ids) . ') - ORDER BY gt.sequence, gti.position'); - - // cacti_log($branchWhost_SQL); - - $branchWhost = db_fetch_assoc($branchWhost_SQL); - - // Determine the correct width of the cell - $maxlen = 10; - - if (get_request_var('view') == 'default') { - $maxlen = db_fetch_cell("SELECT MAX(LENGTH(description)) - FROM host AS h - INNER JOIN graph_tree_items AS gti - ON gti.host_id = h.id - WHERE disabled = '' - AND deleted = ''"); - } - - $maxlen = getMonitorTrimLength($maxlen); - - if (cacti_sizeof($branchWhost)) { - foreach ($branchWhost as $b) { - if ($ptree != $b['graph_tree_id']) { - $titles[$b['graph_tree_id'] . ':0'] = __('Root Branch', 'monitor'); - $ptree = $b['graph_tree_id']; - } - - if ($b['parent'] > 0) { - $titles[$b['graph_tree_id'] . ':' . $b['parent']] = db_fetch_cell_prepared('SELECT title - FROM graph_tree_items - WHERE id = ? - AND graph_tree_id = ? - ORDER BY position', - [$b['parent'], $b['graph_tree_id']]); - } - } - - $ptree = ''; - - foreach ($titles as $index => $title) { - [$graph_tree_id, $parent] = explode(':', $index); - - $oid = $parent; - - $sql_where = ''; - $sql_join = ''; - - renderWhereJoin($sql_where, $sql_join); - - $hosts_sql = "SELECT h.*, IFNULL(s.name,' " . __('Non-Site Device', 'monitor') . " ') AS site_name - FROM host AS h - LEFT JOIN sites AS s - ON h.site_id = s.id - INNER JOIN graph_tree_items AS gti - ON h.id = gti.host_id - $sql_join - $sql_where - AND parent = ? - AND graph_tree_id = ? - GROUP BY h.id - ORDER BY gti.position"; - - // cacti_log($hosts_sql); - - $hosts = db_fetch_assoc_prepared($hosts_sql, [$oid, $graph_tree_id]); - - $tree_name = db_fetch_cell_prepared('SELECT name - FROM graph_tree - WHERE id = ?', - [$graph_tree_id]); - - if ($ptree != $tree_name) { - if ($ptree != '') { - $result .= ''; - } - - $result .= "
- -
-
-
"; - - $ptree = $tree_name; - } - - if (cacti_sizeof($hosts)) { - foreach ($hosts as $index => $host) { - if (is_device_allowed($host['id'])) { - $host_ids[] = $host['id']; - } else { - unset($hosts[$index]); - } - } - - $class = get_request_var('size'); - - $result .= "
"; - - foreach ($hosts as $host) { - $result .= renderHost($host, true, $maxlen); - } - - $result .= '
'; - } - } - } - - $result .= '
'; - } - - // begin others - lets get the monitor items that are not associated with any tree - if (get_request_var('tree') < 0) { - $hosts = getHostNonTreeArray(); - - if (cacti_sizeof($hosts)) { - foreach ($hosts as $index => $host) { - if (is_device_allowed($host['id'])) { - $host_ids[] = $host['id']; - } else { - unset($hosts[$index]); - } - } - - // Determine the correct width of the cell - $maxlen = 10; - - if (get_request_var('view') == 'default') { - if (cacti_sizeof($host_ids)) { - $maxlen = db_fetch_cell('SELECT MAX(LENGTH(description)) - FROM host AS h - WHERE id IN (' . implode(',', $host_ids) . ") - AND h.deleted = ''"); - } - } - $maxlen = getMonitorTrimLength($maxlen); - - $result .= "
- -
-
"; - - foreach ($hosts as $leaf) { - $result .= renderHost($leaf, true, $maxlen); - } - - $result .= '
'; - } - } - - $function = 'renderFooter' . ucfirst(get_request_var('view')); - - if (function_exists($function)) { - // Call the custom render_footer_ function - $result .= $function($hosts); - } - - return $result; -} - -function getHostStatus($host, $real = false) { - global $thold_hosts, $iclasses; - - // If the host has been muted, show the muted Icon - if ($host['status'] != 1 && in_array($host['id'], $thold_hosts, true)) { - $host['status'] = 4; - } - - if (in_array($host['id'], $_SESSION['monitor_muted_hosts'], true) && $host['status'] == 1) { - $host['status'] = 5; - } elseif (in_array($host['id'], $_SESSION['monitor_muted_hosts'], true) && $host['status'] == 4) { - $host['status'] = 9; - } elseif ($host['status'] == 3) { - if ($host['cur_time'] > $host['monitor_alert'] && !empty($host['monitor_alert'])) { - $host['status'] = 8; - } elseif ($host['cur_time'] > $host['monitor_warn'] && !empty($host['monitor_warn'])) { - $host['status'] = 7; - } - } - - // If wanting the real status, or the status is already known - // return the real status, otherwise default to unknown - return ($real || array_key_exists($host['status'], $iclasses)) ? $host['status'] : 0; -} - -function getHostStatusDescription($status) { - global $icolorsdisplay; - - if (array_key_exists($status, $icolorsdisplay)) { - return $icolorsdisplay[$status]; - } else { - return __('Unknown', 'monitor') . " ($status)"; - } -} - -/** - * render_host - Renders a host using a sub-function - * @param mixed $host - * @param mixed $float - * @param mixed $maxlen - */ -function renderHost($host, $float = true, $maxlen = 10) { - global $thold_hosts, $config, $icolorsdisplay, $iclasses, $classes, $maxchars, $mon_zoom_state; - - // throw out tree root items - if (array_key_exists('name', $host)) { - return; - } - - if ($host['id'] <= 0) { - return; - } - - $host['anchor'] = $config['url_path'] . 'graph_view.php?action=preview&reset=1&host_id=' . $host['id']; - - if ($host['status'] == 3 && array_key_exists($host['id'], $thold_hosts)) { - $host['status'] = 4; - $host['anchor'] = $config['url_path'] . 'plugins/thold/thold_graph.php?action=thold&reset=true&status=1&host_id=' . $host['id']; - } - - $host['real_status'] = getHostStatus($host, true); - $host['status'] = getHostStatus($host); - $host['iclass'] = $iclasses[$host['status']]; - - $function = 'renderHost' . ucfirst(get_request_var('view')); - - if (function_exists($function)) { - // Call the custom render_host_ function - $result = $function($host); - } else { - $iclass = getStatusIcon($host['status'], $host['monitor_icon']); - $fclass = get_request_var('size'); - - $monitor_times = read_user_setting('monitor_uptime'); - $monitor_time_html = ''; - - if ($host['status'] <= 2 || $host['status'] == 5) { - if ($mon_zoom_state) { - $fclass = 'monitor_errorzoom'; - } - $tis = get_timeinstate($host); - - if ($monitor_times == 'on') { - $monitor_time_html = "
$tis"; - } - $result = "

" . title_trim(html_escape($host['description']), $maxlen) . "$monitor_time_html
"; - } else { - $tis = get_uptime($host); - - if ($monitor_times == 'on') { - $monitor_time_html = "
$tis
"; - } - - $result = "

" . title_trim(html_escape($host['description']), $maxlen) . "$monitor_time_html
"; - } - } - - return $result; -} - -function getStatusIcon($status, $icon) { - global $fa_icons; - - if (($status == 1 || ($status == 4 && get_request_var('status') > 0)) && read_user_setting('monitor_sound') == 'First Orders Suite.mp3') { - return 'fab fa-first-order fa-spin mon_icon'; - } - - if ($icon != '' && array_key_exists($icon, $fa_icons)) { - if (isset($fa_icons[$icon]['class'])) { - return $fa_icons[$icon]['class'] . ' mon_icon'; - } else { - return "fa fa-$icon mon_icon"; - } - } else { - return 'fa fa-server' . ' mon_icon'; - } -} - -function monitorPrintHostTime($status_time, $seconds = false) { - // If the host is down, make a downtime since message - $dt = ''; - - if (is_numeric($status_time)) { - $sfd = round($status_time / 100,0); - } else { - $sfd = time() - strtotime($status_time); - } - $dt_d = floor($sfd / 86400); - $dt_h = floor(($sfd - ($dt_d * 86400)) / 3600); - $dt_m = floor(($sfd - ($dt_d * 86400) - ($dt_h * 3600)) / 60); - $dt_s = $sfd - ($dt_d * 86400) - ($dt_h * 3600) - ($dt_m * 60); - - if ($dt_d > 0) { - $dt .= $dt_d . 'd:' . $dt_h . 'h:' . $dt_m . 'm' . ($seconds ? ':' . $dt_s . 's' : ''); - } elseif ($dt_h > 0) { - $dt .= $dt_h . 'h:' . $dt_m . 'm' . ($seconds ? ':' . $dt_s . 's' : ''); - } elseif ($dt_m > 0) { - $dt .= $dt_m . 'm' . ($seconds ? ':' . $dt_s . 's' : ''); - } else { - $dt .= ($seconds ? $dt_s . 's' : __('Just Up', 'monitor')); - } - - return $dt; -} - -function ajaxStatus() { - global $thold_hosts, $config, $icolorsdisplay, $iclasses, $criticalities; - - $tholds = 0; - - validateRequestVars(); - - if (isset_request_var('id') && get_filter_request_var('id')) { - $id = get_request_var('id'); - $size = get_request_var('size'); - - $host = db_fetch_row_prepared('SELECT * - FROM host - WHERE id = ?', - [$id]); - - if (!cacti_sizeof($host)) { - cacti_log('Attempted to retrieve status for missing Device ' . $id, false, 'MONITOR', POLLER_VERBOSITY_HIGH); - - return false; - } - - $host['anchor'] = $config['url_path'] . 'graph_view.php?action=preview&reset=1&host_id=' . $host['id']; - - if ($host['status'] == 3 && array_key_exists($host['id'], $thold_hosts)) { - $host['status'] = 4; - $host['anchor'] = $config['url_path'] . 'plugins/thold/thold_graph.php?action=thold&reset=true&status=1&host_id=' . $host['id']; - } - - if ($host['availability_method'] == 0) { - $host['status'] = 6; - } - - $host['real_status'] = getHostStatus($host, true); - $host['status'] = getHostStatus($host); - - if (cacti_sizeof($host)) { - if (api_plugin_user_realm_auth('host.php')) { - $host_link = html_escape($config['url_path'] . 'host.php?action=edit&id=' . $host['id']); - } - - // Get the number of graphs - $graphs = db_fetch_cell_prepared('SELECT COUNT(*) - FROM graph_local - WHERE host_id = ?', - [$host['id']]); - - if ($graphs > 0) { - $graph_link = html_escape($config['url_path'] . 'graph_view.php?action=preview&reset=1&host_id=' . $host['id']); - } - - // Get the number of thresholds - if (api_plugin_is_enabled('thold')) { - $tholds = db_fetch_cell_prepared('SELECT count(*) - FROM thold_data - WHERE host_id = ?', - [$host['id']]); - - if ($tholds) { - $thold_link = html_escape($config['url_path'] . 'plugins/thold/thold_graph.php?action=thold&reset=true&status=1&host_id=' . $host['id']); - } - } - - // Get the number of syslogs - if (api_plugin_is_enabled('syslog') && api_plugin_user_realm_auth('syslog.php')) { - include($config['base_path'] . '/plugins/syslog/config.php'); - include_once($config['base_path'] . '/plugins/syslog/functions.php'); - - $syslog_logs = syslog_db_fetch_cell_prepared('SELECT count(*) - FROM syslog_logs - WHERE host = ?', - [$host['hostname']]); - - $syslog_host = syslog_db_fetch_cell_prepared('SELECT host_id - FROM syslog_hosts - WHERE host = ?', - [$host['hostname']]); - - if ($syslog_logs && $syslog_host) { - $syslog_log_link = html_escape($config['url_path'] . 'plugins/syslog/syslog/syslog.php?reset=1&tab=alerts&host_id=' . $syslog_host); - } - - if ($syslog_host) { - $syslog_link = html_escape($config['url_path'] . 'plugins/syslog/syslog/syslog.php?reset=1&tab=syslog&host_id=' . $syslog_host); - } - } else { - $syslog_logs = 0; - $syslog_host = 0; - } - - $links = ''; - - if (isset($host_link)) { - $links .= '
'; - } - - if (isset($graph_link)) { - $links .= '
'; - } - - if (isset($thold_link)) { - $links .= '
'; - } - - if (isset($syslog_log_link)) { - $links .= '
'; - } - - if (isset($syslog_link)) { - $links .= '
'; - } - - if (strtotime($host['status_fail_date']) < 86400) { - $host['status_fail_date'] = __('Never', 'monitor'); - } - - $iclass = $iclasses[$host['status']]; - $sdisplay = getHostStatusDescription($host['real_status']); - $site = db_fetch_cell_prepared('SELECT name FROM sites WHERE id = ?', [$host['site_id']]); - - if ($host['location'] == '') { - $host['location'] = __('Unspecified', 'monitor'); - } - - if ($site == '') { - $site = __('None', 'monitor'); - } - - print " - - - - - - - - - - - - - - ' . (isset($host['monitor_criticality']) && $host['monitor_criticality'] > 0 ? ' - - - - ' : '') . ' - - - - " . ($host['status'] < 3 || $host['status'] == 5 ? ' - - - - ' : '') . ($host['availability_method'] > 0 ? ' - - - - ' : '') . ($host['availability_method'] > 0 ? " - - - - ' : '') . (isset($host['monitor_warn']) && ($host['monitor_warn'] > 0 || $host['monitor_alert'] > 0) ? " - - - - ' : '') . ' - - - - - - - - - - - - ' . ($host['snmp_version'] > 0 && ($host['status'] == 3 || $host['status'] == 2) ? ' - - - - - - - - - - - - - - - - ' : '') . ($host['notes'] != '' ? ' - - - - ' : '') . " - - -
" . __('Device Status Information', 'monitor') . '
' . __('Device:', 'monitor') . "" . html_escape($host['description']) . '
' . __('Site:', 'monitor') . '' . html_escape($site) . '
' . __('Location:', 'monitor') . '' . html_escape($host['location']) . '
' . __('Criticality:', 'monitor') . '' . html_escape($criticalities[$host['monitor_criticality']]) . '
' . __('Status:', 'monitor') . "$sdisplay
' . __('Admin Note:', 'monitor') . "" . html_escape($host['monitor_text']) . '
' . __('IP/Hostname:', 'monitor') . '' . html_escape($host['hostname']) . '
" . __('Curr/Avg:', 'monitor') . '' . __('%d ms', $host['cur_time'], 'monitor') . ' / ' . __('%d ms', $host['avg_time'], 'monitor') . '
" . __('Warn/Alert:', 'monitor') . '' . __('%0.2d ms', $host['monitor_warn'], 'monitor') . ' / ' . __('%0.2d ms', $host['monitor_alert'], 'monitor') . '
' . __('Last Fail:', 'monitor') . '' . html_escape($host['status_fail_date']) . '
' . __('Time In State:', 'monitor') . '' . get_timeinstate($host) . '
' . __('Availability:', 'monitor') . '' . round($host['availability'],2) . ' %
' . __('Agent Uptime:', 'monitor') . '' . ($host['status'] == 3 || $host['status'] == 5 ? monitorPrintHostTime($host['snmp_sysUpTimeInstance']) : __('N/A', 'monitor')) . "
" . __('Sys Description:', 'monitor') . '' . html_escape(monitorTrim($host['snmp_sysDescr'])) . '
' . __('Location:', 'monitor') . '' . html_escape(monitorTrim($host['snmp_sysLocation'])) . '
' . __('Contact:', 'monitor') . '' . html_escape(monitorTrim($host['snmp_sysContact'])) . '
' . __('Notes:', 'monitor') . '' . html_escape($host['notes']) . '

$links
"; - } - } -} - -function monitorTrim($string) { - return trim($string, "\"'\\ \n\t\r"); -} - -function renderHeaderDefault($hosts) { - return "
"; -} - -function renderHeaderNames($hosts) { - return ""; -} - -function renderHeaderTiles($hosts) { - return renderHeaderDefault($hosts); -} - -function renderHeaderTilesadt($hosts) { - return renderHeaderDefault($hosts); -} - -function renderHeaderList($hosts, $total_rows = 0, $rows = 0) { - $display_text = [ - 'hostname' => [ - 'display' => __('Hostname', 'monitor'), - 'sort' => 'ASC', - 'align' => 'left', 'tip' => __('Hostname of device', 'monitor') - ], - 'id' => [ - 'display' => __('ID', 'monitor'), - 'sort' => 'ASC', - 'align' => 'left' - ], - 'description' => [ - 'display' => __('Description', 'monitor'), - 'sort' => 'ASC', - 'align' => 'left' - ], - 'site_name' => [ - 'display' => __('Site', 'monitor'), - 'sort' => 'ASC', - 'align' => 'left' - ], - 'monitor_criticality' => [ - 'display' => __('Criticality', 'monitor'), - 'sort' => 'ASC', - 'align' => 'left' - ], - 'status' => [ - 'display' => __('Status', 'monitor'), - 'sort' => 'DESC', - 'align' => 'center' - ], - 'instate' => [ - 'display' => __('Length in Status', 'monitor'), - 'sort' => 'ASC', - 'align' => 'center' - ], - 'avg_time' => [ - 'display' => __('Averages', 'monitor'), - 'sort' => 'DESC', - 'align' => 'left' - ], - 'monitor_warn' => [ - 'display' => __('Warning', 'monitor'), - 'sort' => 'DESC', - 'align' => 'left' - ], - 'monitor_text' => [ - 'display' => __('Admin', 'monitor'), - 'sort' => 'ASC', - 'tip' => __('Monitor Text Column represents \'Admin\'', 'monitor'), - 'align' => 'left' - ], - 'notes' => [ - 'display' => __('Notes', 'monitor'), - 'sort' => 'ASC', - 'align' => 'left' - ], - 'availability' => [ - 'display' => __('Availability', 'monitor'), - 'sort' => 'DESC', - 'align' => 'right' - ], - 'status_fail_date' => [ - 'display' => __('Last Fail', 'monitor'), - 'sort' => 'DESC', - 'align' => 'right' - ], - ]; - - ob_start(); - - $nav = html_nav_bar('monitor.php?rfilter=' . get_request_var('rfilter'), MAX_DISPLAY_PAGES, get_request_var('page'), $rows, $total_rows, 12, __('Devices'), 'page', 'main'); - - html_start_box(__('Monitored Devices', 'monitor'), '100%', false, '3', 'center', ''); - - print $nav; - - html_header_sort($display_text, get_request_var('sort_column'), get_request_var('sort_direction'), false); - - $output = ob_get_contents(); - - ob_end_clean(); - - return $output; -} - -function renderSuppressgroupsList($hosts) { - return true; -} - -function renderFooterDefault($hosts) { - return ''; -} - -function renderFooterNames($hosts) { - $col = 7 - $_SESSION['names']; - - if ($col == 0) { - return '
'; - } else { - return ''; - } -} - -function renderFooterTiles($hosts) { - return renderFooterDefault($hosts); -} - -function renderFooterTilesadt($hosts) { - return renderFooterDefault($hosts); -} - -function renderFooterList($hosts, $total_rows, $rows) { - ob_start(); - - html_end_box(false); - - if ($total_rows > 0) { - $nav = html_nav_bar('monitor.php?rfilter=' . get_request_var('rfilter'), MAX_DISPLAY_PAGES, get_request_var('page'), $rows, $total_rows, 12, __('Devices'), 'page', 'main'); - - print $nav; - } - - $output = ob_get_contents(); - - ob_end_clean(); - - return $output; -} - -function renderHostList($host) { - global $criticalities, $iclasses; - - if ($host['status'] < 2 || $host['status'] == 5) { - $dt = get_timeinstate($host); - } elseif (strtotime($host['status_rec_date']) > 192800) { - $dt = get_timeinstate($host); - } else { - $dt = __('Never', 'monitor'); - } - - if ($host['status'] < 3 || $host['status'] == 5) { - $host_admin = $host['monitor_text']; - } else { - $host_admin = ''; - } - - if (isset($host['monitor_criticality']) && $host['monitor_criticality'] > 0) { - $host_crit = $criticalities[$host['monitor_criticality']]; - } else { - $host_crit = ''; - } - - if ($host['availability_method'] > 0) { - $host_address = $host['hostname']; - $host_avg = __('%d ms', $host['cur_time'], 'monitor') . ' / ' . __('%d ms', $host['avg_time'], 'monitor'); - } else { - $host_address = ''; - $host_avg = __('N/A', 'monitor'); - } - - if (isset($host['monitor_warn']) && ($host['monitor_warn'] > 0 || $host['monitor_alert'] > 0)) { - $host_warn = __('%0.2d ms', $host['monitor_warn'], 'monitor') . ' / ' . __('%0.2d ms', $host['monitor_alert'], 'monitor'); - } else { - $host_warn = ''; - } - - if (strtotime($host['status_fail_date']) < 86400) { - $host['status_fail_date'] = __('Never', 'monitor'); - } - - $host_datefail = $host['status_fail_date']; - - $iclass = $iclasses[$host['status']]; - $sdisplay = getHostStatusDescription($host['real_status']); - - $row_class = "{$iclass}Full"; - - ob_start(); - - print ""; - - $url = $host['anchor']; - - form_selectable_cell(filter_value($host['hostname'], '', $url), $host['id'], '', 'left'); - form_selectable_cell($host['id'], $host['id'], '', 'left'); - form_selectable_cell($host['description'], $host['id'], '', 'left'); - form_selectable_cell($host['site_name'], $host['id'], '', 'left'); - form_selectable_cell($host_crit, $host['id'], '', 'left'); - form_selectable_cell($sdisplay, $host['id'], '', 'center'); - form_selectable_cell($dt, $host['id'], '', 'center'); - form_selectable_cell($host_avg, $host['id'], '', 'left'); - form_selectable_cell($host_warn, $host['id'], '', 'left'); - form_selectable_cell($host_admin, $host['id'], '', 'white-space:pre-wrap;text-align:left'); - form_selectable_cell(str_replace(["\n", "\r"], [' ', ''], $host['notes']), $host['id'], '', 'white-space:pre-wrap;text-align:left'); - form_selectable_cell(round($host['availability'],2) . ' %', $host['id'], '', 'right'); - form_selectable_cell($host_datefail, $host['id'], '', 'right'); - - form_end_row(); - - $result = ob_get_contents(); - - ob_end_clean(); - - return $result; -} - -function renderHostNames($host) { - $fclass = get_request_var('size'); - - $result = ''; - - $maxlen = getMonitorTrimLength(100); - $monitor_times = read_user_setting('monitor_uptime'); - $monitor_time_html = ''; - - if ($_SESSION['names'] == 0) { - $result .= ''; - } - - if ($host['status'] <= 2 || $host['status'] == 5) { - $result .= "" . title_trim(html_escape($host['description']), $maxlen) . ''; - } else { - $result .= "" . title_trim(html_escape($host['description']), $maxlen) . ''; - } - - $_SESSION['names']++; - - if ($_SESSION['names'] > 7) { - $result .= ''; - $_SESSION['names'] = 0; - } - - return $result; -} - -function renderHostTiles($host, $maxlen = 10) { - $class = getStatusIcon($host['status'], $host['monitor_icon']); - $fclass = get_request_var('size'); - - $result = "
"; - - return $result; -} - -function renderHostTilesadt($host, $maxlen = 10) { - $tis = ''; - - $class = getStatusIcon($host['status'], $host['monitor_icon']); - $fclass = get_request_var('size'); - - if ($host['status'] < 2 || $host['status'] == 5) { - $tis = get_timeinstate($host); - - $result = ""; - - return $result; - } else { - $tis = get_uptime($host); - - $result = ""; - - return $result; - } -} - -function getHostsDownOrTriggeredByPermission($prescan) { - global $render_style; - $PreScanValue = 2; - - if ($prescan) { - $PreScanValue = 3; - } - - $result = []; - - if (get_request_var('crit') > 0) { - $sql_add_where = 'monitor_criticality >= ' . get_request_var('crit'); - } else { - $sql_add_where = ''; - } - - if (get_request_var('grouping') == 'tree') { - if (get_request_var('tree') > 0) { - $devices = db_fetch_cell_prepared('SELECT GROUP_CONCAT(DISTINCT host_id) AS hosts - FROM graph_tree_items AS gti - INNER JOIN host AS h - WHERE host_id > 0 - AND h.deleted = "" - AND graph_tree_id = ?', - [get_request_var('tree')]); - - renderGroupConcat($sql_add_where, ' OR ', 'h.id', $devices,'AND h.status < 2'); - } - } - - if (get_request_var('status') > 0) { - $triggered = db_fetch_cell('SELECT GROUP_CONCAT(DISTINCT host_id) AS hosts - FROM host AS h - INNER JOIN thold_data AS td - ON td.host_id = h.id - WHERE ' . getTholdWhere() . ' - AND h.deleted = ""'); - - renderGroupConcat($sql_add_where, ' OR ', 'h.id', $triggered, 'AND h.status > 1'); - - $_SESSION['monitor_triggered'] = array_rekey( - db_fetch_assoc('SELECT td.host_id, COUNT(DISTINCT td.id) AS triggered - FROM thold_data AS td - INNER JOIN host AS h - ON td.host_id = h.id - WHERE ' . getTholdWhere() . ' - AND h.deleted = "" - GROUP BY td.host_id'), - 'host_id', 'triggered' - ); - } - - $sql_where = "h.monitor = 'on' - AND h.disabled = '' - AND h.deleted = '' - AND ((h.status < " . $PreScanValue . ' AND (h.availability_method > 0 OR h.snmp_version > 0)) ' . - ($sql_add_where != '' ? ' OR (' . $sql_add_where . '))' : ')'); - - // do a quick loop through to pull the hosts that are down - $hosts = get_allowed_devices($sql_where); - - if (cacti_sizeof($hosts)) { - foreach ($hosts as $host) { - $result[] = $host['id']; - sort($result); - } - } - - return $result; -} - -/* -// This function is not used and contains an undefined variable - -function getHostTreeArray() { - return $leafs; -} -*/ - -function getHostNonTreeArray() { - $leafs = []; - - $sql_where = ''; - $sql_join = ''; - - renderWhereJoin($sql_where, $sql_join); - - $hierarchy = db_fetch_assoc("SELECT DISTINCT - h.*, gti.title, gti.host_id, gti.host_grouping_type, gti.graph_tree_id - FROM host AS h - LEFT JOIN graph_tree_items AS gti - ON h.id=gti.host_id - $sql_join - $sql_where - AND gti.graph_tree_id IS NULL - ORDER BY h.description"); - - if (cacti_sizeof($hierarchy) > 0) { - $leafs = []; - $branchleafs = 0; - - foreach ($hierarchy as $leaf) { - $leafs[$branchleafs] = $leaf; - $branchleafs++; - } - } - - return $leafs; -} - -function getMonitorTrimLength($fieldlen) { - global $maxchars; - - if (get_request_var('view') == 'default' || get_request_var('view') == 'names') { - $maxlen = $maxchars; - - if (get_request_var('trim') < 0) { - $maxlen = 4000; - } elseif (get_request_var('trim') > 0) { - $maxlen = get_request_var('trim'); - } - - if ($fieldlen > $maxlen) { - $fieldlen = $maxlen; - } - } - - return $fieldlen; -} diff --git a/monitor_controller.php b/monitor_controller.php new file mode 100644 index 0000000..ec9a60b --- /dev/null +++ b/monitor_controller.php @@ -0,0 +1,992 @@ + 0) { + $db_settings = db_fetch_cell_prepared('SELECT url + FROM plugin_monitor_dashboards + WHERE id = ?', + [$dashboard]); + + if ($db_settings != '') { + $db_settings = str_replace('monitor.php?', '', $db_settings); + $settings = explode('&', $db_settings); + + if (cacti_sizeof($settings)) { + foreach ($settings as $setting) { + [$name, $value] = explode('=', $setting); + + set_request_var($name, $value); + } + } + } + } +} + +function drawPage() { + global $config, $iclasses, $icolorsdisplay, $mon_zoom_state, $dozoomrefresh, $dozoombgndcolor, $font_sizes; + global $new_form, $new_title; + + $errored_list = getHostsDownOrTriggeredByPermission(true); + + if (cacti_sizeof($errored_list) && read_user_setting('monitor_error_zoom') == 'on') { + if ($_SESSION['monitor_zoom_state'] == 0) { + $mon_zoom_state = $_SESSION['monitor_zoom_state'] = 1; + $_SESSION['mon_zoom_hist_status'] = get_nfilter_request_var('status'); + $_SESSION['mon_zoom_hist_size'] = get_nfilter_request_var('size'); + $dozoomrefresh = true; + $dozoombgndcolor = true; + } + } elseif (isset($_SESSION['monitor_zoom_state']) && $_SESSION['monitor_zoom_state'] == 1) { + $_SESSION['monitor_zoom_state'] = 0; + $dozoomrefresh = true; + $dozoombgndcolor = false; + } + + $name = db_fetch_cell_prepared('SELECT name + FROM plugin_monitor_dashboards + WHERE id = ?', + [get_request_var('dashboard')]); + + if ($name == '') { + $name = __('New Dashboard', 'monitor'); + } + + $new_form = "
" . __('Enter the Dashboard Name and then press \'Save\' to continue, else press \'Cancel\'', 'monitor') . '
' . __('Dashboard', 'monitor') . "
"; + + $new_title = __('Create New Dashboard', 'monitor'); + + findDownHosts(); + + general_header(); + + drawFilterAndStatus(); + + print ''; + + // Default with permissions = default_by_permission + // Tree = group_by_tree + $function = 'render' . ucfirst(get_request_var('grouping')); + + if (function_exists($function) && get_request_var('view') != 'list') { + if (get_request_var('grouping') == 'default' || get_request_var('grouping') == 'site') { + html_start_box(__('Monitored Devices', 'monitor'), '100%', true, '3', 'center', ''); + } else { + html_start_box('', '100%', true, '3', 'center', ''); + } + print $function(); + } else { + print renderDefault(); + } + + print ''; + + html_end_box(); + + if (read_user_setting('monitor_legend', read_config_option('monitor_legend'))) { + print "
"; + + foreach ($iclasses as $index => $class) { + print "
" . $icolorsdisplay[$index] . '
'; + } + + print '
'; + } + + // If the host is down, we need to insert the embedded wav file + $monitor_sound = getMonitorSound(); + + if (isMonitorAudible()) { + if (read_user_setting('monitor_sound_loop', read_config_option('monitor_sound_loop'))) { + print ""; + } else { + print ""; + } + } + + print '
' . getFilterText() . '
'; + + bottom_footer(); +} + +function isMonitorAudible() { + return getMonitorSound() != ''; +} + +function getMonitorSound() { + $sound = read_user_setting('monitor_sound', read_config_option('monitor_sound')); + clearstatcache(); + $file = __DIR__ . '/sounds/' . $sound; + $exists = file_exists($file); + + return $exists ? $sound : ''; +} + +function findDownHosts() { + $dhosts = getHostsDownOrTriggeredByPermission(false); + + if (cacti_sizeof($dhosts)) { + set_request_var('downhosts', 'true'); + + if (isset($_SESSION['monitor_muted_hosts'])) { + unmute_up_non_triggered_hosts($dhosts); + + $unmuted_hosts = array_diff($dhosts, $_SESSION['monitor_muted_hosts']); + + if (cacti_sizeof($unmuted_hosts)) { + unmute_user(); + } + } else { + set_request_var('mute', 'false'); + } + } else { + unmuteAllHosts(); + set_request_var('downhosts', 'false'); + } +} + +function unmuteUpNonTriggeredHosts($dhosts) { + if (isset($_SESSION['monitor_muted_hosts'])) { + foreach ($_SESSION['monitor_muted_hosts'] as $index => $host_id) { + if (array_search($host_id, $dhosts, true) === false) { + unset($_SESSION['monitor_muted_hosts'][$index]); + } + } + } +} + +function muteAllHosts() { + $_SESSION['monitor_muted_hosts'] = getHostsDownOrTriggeredByPermission(false); + muteUser(); +} + +function unmuteAllHosts() { + $_SESSION['monitor_muted_hosts'] = []; + unmuteUser(); +} + +function muteUser() { + set_request_var('mute', 'true'); + set_user_setting('monitor_mute', 'true'); +} + +function unmuteUser() { + set_request_var('mute', 'false'); + set_user_setting('monitor_mute','false'); +} + + +function getFilterText() { + $filter = '
'; + + switch(get_request_var('status')) { + case '-4': + $filter .= __('Devices without Thresholds', 'monitor'); + + break; + case '-3': + $filter .= __('Not Monitored Devices', 'monitor'); + + break; + case '-2': + $filter .= __('All Devices', 'monitor'); + + break; + case '-1': + $filter .= __('All Monitored Devices', 'monitor'); + + break; + case '0': + $filter .= __('Monitored Devices either Down or Recovering', 'monitor'); + + break; + case '1': + $filter .= __('Monitored Devices either Down, Recovering, or with Triggered Thresholds', 'monitor'); + + break; + case '2': + $filter .= __('Monitored Devices either Down, Recovering, or with Breached or Triggered Thresholds', 'monitor'); + + break; + default: + $filter .= __('Unknown monitoring status (%s)', get_request_var('status'), 'monitor'); + } + + switch(get_request_var('crit')) { + case '0': + $filter .= __(', and All Criticalities', 'monitor'); + + break; + case '1': + $filter .= __(', and of Low Criticality or Higher', 'monitor'); + + break; + case '2': + $filter .= __(', and of Medium Criticality or Higher', 'monitor'); + + break; + case '3': + $filter .= __(', and of High Criticality or Higher', 'monitor'); + + break; + case '4': + $filter .= __(', and of Mission Critical Status', 'monitor'); + + break; + } + + $filter .= __('
Remember to first select eligible Devices to be Monitored from the Devices page!
', 'monitor'); + + return $filter; +} + +function drawFilterDropdown($id, $title, $settings = [], $value = null) { + if ($value == null) { + $value = get_nfilter_request_var($id); + } + + if (cacti_sizeof($settings)) { + print '' . html_escape($title) . ''; + print '' . PHP_EOL; + } else { + print "" . PHP_EOL; + } +} + +function drawFilterAndStatus() { + global $config, $criticalities, $page_refresh_interval, $classes, $monitor_grouping; + global $monitor_view_type, $monitor_status, $monitor_trim; + global $dozoombgndcolor, $dozoomrefresh, $zoom_hist_status, $zoom_hist_size, $mon_zoom_state; + global $new_form, $new_title, $item_rows; + + $header = __('Monitor Filter [ Last Refresh: %s ]', date('g:i:s a', time()), 'monitor') . (get_request_var('refresh') < 99999 ? __(' [ Refresh Again in %d Seconds ]', get_request_var('refresh'), 'monitor') : '') . (get_request_var('view') == 'list' ? __('[ Showing only first 30 Devices ]', 'monitor') : '') . ''; + + html_start_box($header, '100%', false, '3', 'center', ''); + + print '' . PHP_EOL; + print '
' . PHP_EOL; + + // First line of filter + print '' . PHP_EOL; + print '' . PHP_EOL; + + $dashboards[0] = __('Unsaved', 'monitor'); + $dashboards += array_rekey( + db_fetch_assoc_prepared('SELECT id, name + FROM plugin_monitor_dashboards + WHERE user_id = 0 OR user_id = ? + ORDER BY name', + [$_SESSION['sess_user_id']]), + 'id', 'name' + ); + + $name = db_fetch_cell_prepared('SELECT name + FROM plugin_monitor_dashboards + WHERE id = ?', + [get_request_var('dashboard')]); + + $mon_zoom_status = null; + $mon_zoom_size = null; + + if (isset($_SESSION['monitor_zoom_state'])) { + if ($_SESSION['monitor_zoom_state'] == 1) { + $mon_zoom_status = 2; + $mon_zoom_size = 'monitor_errorzoom'; + $dozoombgndcolor = true; + } else { + if (isset($_SESSION['mon_zoom_hist_status'])) { + $mon_zoom_status = $_SESSION['mon_zoom_hist_status']; + } else { + $mon_zoom_status = null; + } + + if (isset($_SESSION['mon_zoom_hist_size'])) { + $currentddsize = get_nfilter_request_var('size'); + + if ($currentddsize != $_SESSION['mon_zoom_hist_size'] && $currentddsize != 'monitor_errorzoom') { + $_SESSION['mon_zoom_hist_size'] = $currentddsize; + } + + $mon_zoom_size = $_SESSION['mon_zoom_hist_size']; + } else { + $mon_zoom_size = null; + } + } + } + + drawFilterDropdown('dashboard', __('Layout', 'monitor'), $dashboards); + drawFilterDropdown('status', __('Status', 'monitor'), $monitor_status, $mon_zoom_status); + drawFilterDropdown('view', __('View', 'monitor'), $monitor_view_type); + drawFilterDropdown('grouping', __('Grouping', 'monitor'), $monitor_grouping); + drawFilterDropdown('rows', __('Devices', 'monitor'), $item_rows); + + // Buttons + print ''; + print ''; + print '
' . PHP_EOL; + + print '' . PHP_EOL; + + print '' . PHP_EOL; + + print '' . PHP_EOL; + + print '' . PHP_EOL; + + if (get_request_var('dashboard') > 0) { + print '' . PHP_EOL; + } + + if (get_request_var('dashboard') > 0) { + print '' . PHP_EOL; + } + + print '' . PHP_EOL; + print '' . PHP_EOL; + print '
'; + + // Second line of filter + print '' . PHP_EOL; + print '' . PHP_EOL; + print ''; + print ''; + + drawFilterDropdown('crit', __('Criticality', 'monitor'), $criticalities); + + if (get_request_var('view') != 'list') { + drawFilterDropdown('size', __('Size', 'monitor'), $classes, $mon_zoom_size); + } + + if (get_request_var('view') == 'default' || get_request_var('view') == 'names') { + drawFilterDropdown('trim', __('Trim', 'monitor'), $monitor_trim); + } + + if (get_nfilter_request_var('grouping') == 'tree') { + $trees = []; + + if (get_request_var('grouping') == 'tree') { + $trees_allowed = array_rekey(get_allowed_trees(), 'id', 'name'); + + if (cacti_sizeof($trees_allowed)) { + $trees_prefix = [-1 => __('All Trees', 'monitor')]; + $trees_suffix = [-2 => __('Non-Tree Devices', 'monitor')]; + + $trees = $trees_prefix + $trees_allowed + $trees_suffix; + } + } + + drawFilterDropdown('tree', __('Tree', 'monitor'), $trees); + } + + if (get_nfilter_request_var('grouping') == 'site') { + $sites = []; + + if (get_request_var('grouping') == 'site') { + $sites = array_rekey( + db_fetch_assoc('SELECT id, name + FROM sites + ORDER BY name'), + 'id', 'name' + ); + + if (cacti_sizeof($sites)) { + $sites_prefix = [-1 => __('All Sites', 'monitor')]; + $sites_suffix = [-2 => __('Non-Site Devices', 'monitor')]; + + $sites = $sites_prefix + $sites + $sites_suffix; + } + } + + drawFilterDropdown('site', __('Sites', 'monitor'), $sites); + } + + if (get_request_var('grouping') == 'template') { + $templates = []; + $templates_allowed = array_rekey( + db_fetch_assoc('SELECT ht.id, ht.name, COUNT(gl.id) AS graphs + FROM host_template AS ht + INNER JOIN host AS h + ON h.host_template_id = ht.id + INNER JOIN graph_local AS gl + ON h.id = gl.host_id + GROUP BY ht.id + HAVING graphs > 0'), + 'id', 'name' + ); + + if (cacti_sizeof($templates_allowed)) { + $templates_prefix = [-1 => __('All Templates', 'monitor')]; + $templates_suffix = [-2 => __('Non-Templated Devices', 'monitor')]; + + $templates = $templates_prefix + $templates_allowed + $templates_suffix; + } + + drawFilterDropdown('template', __('Template', 'monitor'), $templates); + } + + drawFilterDropdown('refresh', __('Refresh', 'monitor'), $page_refresh_interval); + + if (get_request_var('grouping') != 'tree') { + print '' . PHP_EOL; + } + + if (get_request_var('grouping') != 'site') { + print '' . PHP_EOL; + } + + if (get_request_var('grouping') != 'template') { + print '' . PHP_EOL; + } + + if (get_request_var('view') == 'list') { + print '' . PHP_EOL; + } + + if (get_request_var('view') != 'default') { + print '' . PHP_EOL; + } + + print ''; + print '
' . __('Search', 'monitor') . '
'; + print '
' . PHP_EOL; + + html_end_box(); + + if ($dozoombgndcolor) { + $mbcolora = db_fetch_row_prepared('SELECT * + FROM colors + WHERE id = ?', + [read_user_setting('monitor_error_background')]); + + $monitor_error_fontsize = read_user_setting('monitor_error_fontsize') . 'px'; + + if (cacti_sizeof($mbcolora)) { + $mbcolor = '#' . $mbcolora['hex']; + } else { + $mbcolor = 'snow'; + } + } else { + $mbcolor = ''; + $monitor_error_fontsize = '10px'; + } + + $monitor_js_config = [ + 'mbColor' => $mbcolor, + 'monitorFont' => $monitor_error_fontsize, + 'doZoomRefresh' => $dozoomrefresh, + 'newForm' => $new_form, + 'newTitle' => $new_title, + 'messages' => [ + 'filterSaved' => __(' [ Filter Settings Saved ]', 'monitor'), + 'cancel' => __('Cancel', 'monitor'), + 'save' => __('Save', 'monitor') + ] + ]; + + print ''; + print ''; + + } + +function getMuteText() { + if (isMonitorAudible()) { + return __('Mute', 'monitor'); + } else { + return __('Acknowledge', 'monitor'); + } +} + +function getUnmuteText() { + if (isMonitorAudible()) { + return __('Un-Mute', 'monitor'); + } else { + return __('Reset', 'monitor'); + } +} + +function removeDashboard() { + $dashboard = get_filter_request_var('dashboard'); + + $name = db_fetch_cell_prepared('SELECT name + FROM plugin_monitor_dashboards + WHERE id = ? + AND user_id = ?', + [$dashboard, $_SESSION['sess_user_id']]); + + if ($name != '') { + db_execute_prepared('DELETE FROM plugin_monitor_dashboards + WHERE id = ?', + [$dashboard]); + + raise_message('removed', __('Dashboard \'%s\' Removed.', $name, 'monitor'), MESSAGE_LEVEL_INFO); + } else { + $name = db_fetch_cell_prepared('SELECT name + FROM plugin_monitor_dashboards + WHERE id = ?', + [$dashboard]); + + raise_message('notremoved', __('Dashboard \'%s\' is not owned by you.', $name, 'monitor'), MESSAGE_LEVEL_ERROR); + } + + set_request_var('dashboard', '0'); +} + +function saveSettings() { + if (isset_request_var('dashboard') && get_filter_request_var('dashboard') != 0) { + $save_db = true; + } else { + $save_db = false; + } + + validateRequestVars(); + + if (!$save_db) { + if (cacti_sizeof($_REQUEST)) { + foreach ($_REQUEST as $var => $value) { + switch($var) { + case 'dashboard': + set_user_setting('monitor_rfilter', get_request_var('dashboard')); + + break; + case 'rfilter': + set_user_setting('monitor_rfilter', get_request_var('rfilter')); + + break; + case 'refresh': + set_user_setting('monitor_refresh', get_request_var('refresh')); + + break; + case 'grouping': + set_user_setting('monitor_grouping', get_request_var('grouping')); + + break; + case 'view': + set_user_setting('monitor_view', get_request_var('view')); + + break; + case 'rows': + set_user_setting('monitor_rows', get_request_var('rows')); + + break; + case 'crit': + set_user_setting('monitor_crit', get_request_var('crit')); + + break; + case 'mute': + set_user_setting('monitor_mute', get_request_var('mute')); + + break; + case 'size': + set_user_setting('monitor_size', get_request_var('size')); + + break; + case 'trim': + set_user_setting('monitor_trim', get_request_var('trim')); + + break; + case 'status': + set_user_setting('monitor_status', get_request_var('status')); + + break; + case 'tree': + set_user_setting('monitor_tree', get_request_var('tree')); + + break; + case 'mute': + set_user_setting('monitor_mute', get_request_var('mute')); + + break; + case 'site': + set_user_setting('monitor_site', get_request_var('site')); + + break; + } + } + } + } else { + $url = 'monitor.php' . + '?refresh=' . get_request_var('refresh') . + '&grouping=' . get_request_var('grouping') . + '&view=' . get_request_var('view') . + '&rows=' . get_request_var('rows') . + '&crit=' . get_request_var('crit') . + '&size=' . get_request_var('size') . + '&trim=' . get_request_var('trim') . + '&status=' . get_request_var('status') . + '&tree=' . get_request_var('tree') . + '&site=' . get_request_var('site'); + + if (!isset_request_var('user')) { + $user = $_SESSION['sess_user_id']; + } else { + $user = get_request_var('user'); + } + + $id = get_request_var('dashboard'); + $name = get_nfilter_request_var('name'); + + $save = []; + $save['id'] = $id; + $save['name'] = $name; + $save['user_id'] = $user; + $save['url'] = $url; + + $id = sql_save($save, 'plugin_monitor_dashboards'); + + if (!empty($id)) { + raise_message('monitorsaved', __('Dashboard \'%s\' has been Saved!', $name, 'monitor'), MESSAGE_LEVEL_INFO); + set_request_var('dashboard', $id); + } else { + raise_message('monitornotsaved', __('Dashboard \'%s\' could not be Saved!', $name, 'monitor'), MESSAGE_LEVEL_INFO); + set_request_var('dashboard', '0'); + } + } + + validateRequestVars(true); +} + +function validateRequestVars($force = false) { + // ================= input validation and session storage ================= + $filters = [ + 'refresh' => [ + 'filter' => FILTER_VALIDATE_INT, + 'default' => read_user_setting('monitor_refresh', read_config_option('monitor_refresh'), $force) + ], + 'dashboard' => [ + 'filter' => FILTER_VALIDATE_INT, + 'pageset' => true, + 'default' => read_user_setting('monitor_dashboard', '0', $force) + ], + 'rfilter' => [ + 'filter' => FILTER_VALIDATE_IS_REGEX, + 'pageset' => true, + 'default' => read_user_setting('monitor_rfilter', '', $force) + ], + 'name' => [ + 'filter' => FILTER_CALLBACK, + 'options' => ['options' => 'sanitize_search_string'], + 'default' => '' + ], + 'mute' => [ + 'filter' => FILTER_CALLBACK, + 'options' => ['options' => 'sanitize_search_string'], + 'default' => read_user_setting('monitor_mute', 'false', $force) + ], + 'grouping' => [ + 'filter' => FILTER_CALLBACK, + 'options' => ['options' => 'sanitize_search_string'], + 'pageset' => true, + 'default' => read_user_setting('monitor_grouping', read_config_option('monitor_grouping'), $force) + ], + 'view' => [ + 'filter' => FILTER_CALLBACK, + 'options' => ['options' => 'sanitize_search_string'], + 'pageset' => true, + 'default' => read_user_setting('monitor_view', read_config_option('monitor_view'), $force) + ], + 'rows' => [ + 'filter' => FILTER_VALIDATE_INT, + 'options' => ['options' => 'sanitize_search_string'], + 'default' => read_user_setting('monitor_rows', read_config_option('num_rows_table'), $force) + ], + 'size' => [ + 'filter' => FILTER_CALLBACK, + 'options' => ['options' => 'sanitize_search_string'], + 'default' => read_user_setting('monitor_size', 'monitor_medium', $force) + ], + 'trim' => [ + 'filter' => FILTER_VALIDATE_INT, + 'default' => read_user_setting('monitor_trim', read_config_option('monitor_trim'), $force) + ], + 'crit' => [ + 'filter' => FILTER_VALIDATE_INT, + 'pageset' => true, + 'default' => read_user_setting('monitor_crit', '-1', $force) + ], + 'status' => [ + 'filter' => FILTER_VALIDATE_INT, + 'pageset' => true, + 'default' => read_user_setting('monitor_status', '-1', $force) + ], + 'tree' => [ + 'filter' => FILTER_VALIDATE_INT, + 'pageset' => true, + 'default' => read_user_setting('monitor_tree', '-1', $force) + ], + 'site' => [ + 'filter' => FILTER_VALIDATE_INT, + 'pageset' => true, + 'default' => read_user_setting('monitor_site', '-1', $force) + ], + 'template' => [ + 'filter' => FILTER_VALIDATE_INT, + 'pageset' => true, + 'default' => read_user_setting('monitor_template', '-1', $force) + ], + 'id' => [ + 'filter' => FILTER_VALIDATE_INT, + 'default' => '-1' + ], + 'page' => [ + 'filter' => FILTER_VALIDATE_INT, + 'default' => '1' + ], + 'sort_column' => [ + 'filter' => FILTER_CALLBACK, + 'default' => 'status', + 'options' => ['options' => 'sanitize_search_string'] + ], + 'sort_direction' => [ + 'filter' => FILTER_CALLBACK, + 'default' => 'ASC', + 'options' => ['options' => 'sanitize_search_string'] + ] + ]; + + validate_store_request_vars($filters, 'sess_monitor'); + // ================= input validation ================= +} + + +function ajaxStatus() { + global $thold_hosts, $config, $icolorsdisplay, $iclasses, $criticalities; + + $tholds = 0; + + validateRequestVars(); + + if (isset_request_var('id') && get_filter_request_var('id')) { + $id = get_request_var('id'); + $size = get_request_var('size'); + + $host = db_fetch_row_prepared('SELECT * + FROM host + WHERE id = ?', + [$id]); + + if (!cacti_sizeof($host)) { + cacti_log('Attempted to retrieve status for missing Device ' . $id, false, 'MONITOR', POLLER_VERBOSITY_HIGH); + + return false; + } + + $host['anchor'] = $config['url_path'] . 'graph_view.php?action=preview&reset=1&host_id=' . $host['id']; + + if ($host['status'] == 3 && array_key_exists($host['id'], $thold_hosts)) { + $host['status'] = 4; + $host['anchor'] = $config['url_path'] . 'plugins/thold/thold_graph.php?action=thold&reset=true&status=1&host_id=' . $host['id']; + } + + if ($host['availability_method'] == 0) { + $host['status'] = 6; + } + + $host['real_status'] = getHostStatus($host, true); + $host['status'] = getHostStatus($host); + + if (cacti_sizeof($host)) { + if (api_plugin_user_realm_auth('host.php')) { + $host_link = html_escape($config['url_path'] . 'host.php?action=edit&id=' . $host['id']); + } + + // Get the number of graphs + $graphs = db_fetch_cell_prepared('SELECT COUNT(*) + FROM graph_local + WHERE host_id = ?', + [$host['id']]); + + if ($graphs > 0) { + $graph_link = html_escape($config['url_path'] . 'graph_view.php?action=preview&reset=1&host_id=' . $host['id']); + } + + // Get the number of thresholds + if (api_plugin_is_enabled('thold')) { + $tholds = db_fetch_cell_prepared('SELECT count(*) + FROM thold_data + WHERE host_id = ?', + [$host['id']]); + + if ($tholds) { + $thold_link = html_escape($config['url_path'] . 'plugins/thold/thold_graph.php?action=thold&reset=true&status=1&host_id=' . $host['id']); + } + } + + // Get the number of syslogs + if (api_plugin_is_enabled('syslog') && api_plugin_user_realm_auth('syslog.php')) { + include($config['base_path'] . '/plugins/syslog/config.php'); + include_once($config['base_path'] . '/plugins/syslog/functions.php'); + + $syslog_logs = syslog_db_fetch_cell_prepared('SELECT count(*) + FROM syslog_logs + WHERE host = ?', + [$host['hostname']]); + + $syslog_host = syslog_db_fetch_cell_prepared('SELECT host_id + FROM syslog_hosts + WHERE host = ?', + [$host['hostname']]); + + if ($syslog_logs && $syslog_host) { + $syslog_log_link = html_escape($config['url_path'] . 'plugins/syslog/syslog/syslog.php?reset=1&tab=alerts&host_id=' . $syslog_host); + } + + if ($syslog_host) { + $syslog_link = html_escape($config['url_path'] . 'plugins/syslog/syslog/syslog.php?reset=1&tab=syslog&host_id=' . $syslog_host); + } + } else { + $syslog_logs = 0; + $syslog_host = 0; + } + + $links = ''; + + if (isset($host_link)) { + $links .= '
'; + } + + if (isset($graph_link)) { + $links .= '
'; + } + + if (isset($thold_link)) { + $links .= '
'; + } + + if (isset($syslog_log_link)) { + $links .= '
'; + } + + if (isset($syslog_link)) { + $links .= '
'; + } + + if (strtotime($host['status_fail_date']) < 86400) { + $host['status_fail_date'] = __('Never', 'monitor'); + } + + $iclass = $iclasses[$host['status']]; + $sdisplay = getHostStatusDescription($host['real_status']); + $site = db_fetch_cell_prepared('SELECT name FROM sites WHERE id = ?', [$host['site_id']]); + + if ($host['location'] == '') { + $host['location'] = __('Unspecified', 'monitor'); + } + + if ($site == '') { + $site = __('None', 'monitor'); + } + + print " + + + + + + + + + + + + + + ' . (isset($host['monitor_criticality']) && $host['monitor_criticality'] > 0 ? ' + + + + ' : '') . ' + + + + " . ($host['status'] < 3 || $host['status'] == 5 ? ' + + + + ' : '') . ($host['availability_method'] > 0 ? ' + + + + ' : '') . ($host['availability_method'] > 0 ? " + + + + ' : '') . (isset($host['monitor_warn']) && ($host['monitor_warn'] > 0 || $host['monitor_alert'] > 0) ? " + + + + ' : '') . ' + + + + + + + + + + + + ' . ($host['snmp_version'] > 0 && ($host['status'] == 3 || $host['status'] == 2) ? ' + + + + + + + + + + + + + + + + ' : '') . ($host['notes'] != '' ? ' + + + + ' : '') . " + + +
" . __('Device Status Information', 'monitor') . '
' . __('Device:', 'monitor') . "" . html_escape($host['description']) . '
' . __('Site:', 'monitor') . '' . html_escape($site) . '
' . __('Location:', 'monitor') . '' . html_escape($host['location']) . '
' . __('Criticality:', 'monitor') . '' . html_escape($criticalities[$host['monitor_criticality']]) . '
' . __('Status:', 'monitor') . "$sdisplay
' . __('Admin Note:', 'monitor') . "" . html_escape($host['monitor_text']) . '
' . __('IP/Hostname:', 'monitor') . '' . html_escape($host['hostname']) . '
" . __('Curr/Avg:', 'monitor') . '' . __('%d ms', $host['cur_time'], 'monitor') . ' / ' . __('%d ms', $host['avg_time'], 'monitor') . '
" . __('Warn/Alert:', 'monitor') . '' . __('%0.2d ms', $host['monitor_warn'], 'monitor') . ' / ' . __('%0.2d ms', $host['monitor_alert'], 'monitor') . '
' . __('Last Fail:', 'monitor') . '' . html_escape($host['status_fail_date']) . '
' . __('Time In State:', 'monitor') . '' . get_timeinstate($host) . '
' . __('Availability:', 'monitor') . '' . round($host['availability'],2) . ' %
' . __('Agent Uptime:', 'monitor') . '' . ($host['status'] == 3 || $host['status'] == 5 ? monitorPrintHostTime($host['snmp_sysUpTimeInstance']) : __('N/A', 'monitor')) . "
" . __('Sys Description:', 'monitor') . '' . html_escape(monitorTrim($host['snmp_sysDescr'])) . '
' . __('Location:', 'monitor') . '' . html_escape(monitorTrim($host['snmp_sysLocation'])) . '
' . __('Contact:', 'monitor') . '' . html_escape(monitorTrim($host['snmp_sysContact'])) . '
' . __('Notes:', 'monitor') . '' . html_escape($host['notes']) . '

$links
"; + } + } +} diff --git a/monitor_render.php b/monitor_render.php new file mode 100644 index 0000000..26337f9 --- /dev/null +++ b/monitor_render.php @@ -0,0 +1,1027 @@ + 0 AND status IN (1, 2), status_event_count*$poller_interval, + IF(UNIX_TIMESTAMP(status_rec_date) < 943916400 AND status IN (0, 3), total_polls*$poller_interval, + IF(UNIX_TIMESTAMP(status_rec_date) > 943916400, UNIX_TIMESTAMP() - UNIX_TIMESTAMP(status_rec_date), + IF(snmp_sysUptimeInstance>0 AND snmp_version > 0, snmp_sysUptimeInstance/100, UNIX_TIMESTAMP() + ))))) AS unsigned) AS instate + FROM host AS h + LEFT JOIN sites AS s + ON h.site_id = s.id + $sql_join + $sql_where + $sql_order + $sql_limit"); + + $hosts = db_fetch_assoc($hosts_sql); + + $total_rows = db_fetch_cell("SELECT COUNT(DISTINCT h.id) + FROM host AS h + LEFT JOIN sites AS s + ON h.site_id = s.id + $sql_join + $sql_where"); + + if (cacti_sizeof($hosts)) { + // Determine the correct width of the cell + $maxlen = 10; + + if (get_request_var('view') == 'default') { + $maxlen = db_fetch_cell("SELECT MAX(LENGTH(description)) + FROM host AS h + $sql_join + $sql_where"); + } + + $maxlen = getMonitorTrimLength($maxlen); + + $function = 'renderHeader' . ucfirst(get_request_var('view')); + + if (function_exists($function)) { + // Call the custom render_header_ function + $result .= $function($hosts, $total_rows, $rows); + } + + $count = 0; + + foreach ($hosts as $host) { + if (is_device_allowed($host['id'])) { + $result .= renderHost($host, true, $maxlen); + } + + $count++; + } + + $function = 'renderFooter' . ucfirst(get_request_var('view')); + + if (function_exists($function)) { + // Call the custom render_footer_ function + $result .= $function($hosts, $total_rows, $rows); + } + } + + return $result; +} + +function renderSite() { + global $maxchars; + + $result = ''; + + $sql_where = ''; + $sql_join = ''; + $sql_limit = ''; + + $rows = get_request_var('rows'); + + if ($rows == '-1') { + $rows = read_user_setting('monitor_rows'); + } + + if (!is_numeric($rows)) { + $rows = read_config_option('num_rows_table'); + } + + renderWhereJoin($sql_where, $sql_join); + + $sql_limit = ' LIMIT ' . ($rows * (get_request_var('page') - 1)) . ',' . $rows; + + $hosts_sql = ("SELECT DISTINCT h.*, IFNULL(s.name,' " . __('Non-Site Devices', 'monitor') . " ') AS site_name + FROM host AS h + LEFT JOIN sites AS s + ON s.id = h.site_id + $sql_join + $sql_where + ORDER BY site_name, description + $sql_limit"); + + $hosts = db_fetch_assoc($hosts_sql); + + $ctemp = -1; + $ptemp = -1; + + if (cacti_sizeof($hosts)) { + $suppressGroups = false; + $function = 'renderSuppressgroups' . ucfirst(get_request_var('view')); + + if (function_exists($function)) { + $suppressGroups = $function($hosts); + } + + $function = 'renderHeader' . ucfirst(get_request_var('view')); + + if (function_exists($function)) { + // Call the custom render_header_ function + $result .= $function($hosts); + $suppressGroups = true; + } + + foreach ($hosts as $index => $host) { + if (is_device_allowed($host['id'])) { + $host_ids[] = $host['id']; + } else { + unset($hosts[$index]); + } + } + + // Determine the correct width of the cell + $maxlen = 10; + + if (get_request_var('view') == 'default') { + $maxlen = db_fetch_cell('SELECT MAX(LENGTH(description)) + FROM host AS h + WHERE id IN (' . implode(',', $host_ids) . ')'); + } + $maxlen = getMonitorTrimLength($maxlen); + + $class = get_request_var('size'); + $csuffix = get_request_var('view'); + + if ($csuffix == 'default') { + $csuffix = ''; + } + + foreach ($hosts as $host) { + $ctemp = $host['site_id']; + + if (!$suppressGroups) { + if ($ctemp != $ptemp && $ptemp > 0) { + $result .= ''; + } + + if ($ctemp != $ptemp) { + $result .= "
+ +
+
"; + } + } + + $result .= renderHost($host, true, $maxlen); + + if ($ctemp != $ptemp) { + $ptemp = $ctemp; + } + } + + if ($ptemp == $ctemp && !$suppressGroups) { + $result .= '
'; + } + + $function = 'renderFooter' . ucfirst(get_request_var('view')); + + if (function_exists($function)) { + // Call the custom render_footer_ function + $result .= $function($hosts); + } + } + + return $result; +} + +function renderTemplate() { + global $maxchars; + + $result = ''; + + $sql_where = ''; + $sql_join = ''; + $sql_limit = ''; + + $rows = get_request_var('rows'); + + if ($rows == '-1') { + $rows = read_user_setting('monitor_rows'); + } + + if (!is_numeric($rows)) { + $rows = read_config_option('num_rows_table'); + } + + renderWhereJoin($sql_where, $sql_join); + + $sql_limit = ' LIMIT ' . ($rows * (get_request_var('page') - 1)) . ',' . $rows; + + if (get_request_var('template') > 0) { + $sql_where .= ($sql_where == '' ? '' : 'AND ') . 'ht.id = ' . get_request_var('template'); + } + + $sql_template = 'INNER JOIN host_template AS ht ON h.host_template_id=ht.id '; + + if (get_request_var('template') == -2) { + $sql_where .= ($sql_where == '' ? '' : 'AND ') . 'ht.id IS NULL'; + $sql_template = 'LEFT JOIN host_template AS ht ON h.host_template_id=ht.id '; + } + + $hosts = db_fetch_assoc("SELECT DISTINCT + h.*, ht.name AS host_template_name + FROM host AS h + $sql_template + $sql_join + $sql_where + ORDER BY ht.name, h.description + $sql_limit"); + + $ctemp = -1; + $ptemp = -1; + + if (cacti_sizeof($hosts)) { + $suppressGroups = false; + $function = 'renderSuppressgroups' . ucfirst(get_request_var('view')); + + if (function_exists($function)) { + $suppressGroups = $function($hosts); + } + + $function = 'renderHeader' . ucfirst(get_request_var('view')); + + if (function_exists($function)) { + // Call the custom render_header_ function + $result .= $function($hosts); + $suppressGroups = true; + } + + foreach ($hosts as $index => $host) { + if (is_device_allowed($host['id'])) { + $host_ids[] = $host['id']; + } else { + unset($hosts[$index]); + } + } + + // Determine the correct width of the cell + $maxlen = 10; + + if (get_request_var('view') == 'default') { + $maxlen = db_fetch_cell('SELECT MAX(LENGTH(description)) + FROM host AS h + WHERE id IN (' . implode(',', $host_ids) . ')'); + } + $maxlen = getMonitorTrimLength($maxlen); + + $class = get_request_var('size'); + $csuffix = get_request_var('view'); + + if ($csuffix == 'default') { + $csuffix = ''; + } + + foreach ($hosts as $host) { + $ctemp = $host['host_template_id']; + + if (!$suppressGroups) { + if ($ctemp != $ptemp && $ptemp > 0) { + $result .= ''; + } + + if ($ctemp != $ptemp) { + $result .= "
+ +
+
"; + } + } + + $result .= renderHost($host, true, $maxlen); + + if ($ctemp != $ptemp) { + $ptemp = $ctemp; + } + } + + if ($ptemp == $ctemp && !$suppressGroups) { + $result .= '
'; + } + + $function = 'renderFooter' . ucfirst(get_request_var('view')); + + if (function_exists($function)) { + // Call the custom render_footer_ function + $result .= $function($hosts); + } + } + + return $result; +} + +function renderTree() { + global $maxchars; + + $result = ''; + + $leafs = []; + + if (get_request_var('tree') > 0) { + $sql_where = 'gt.id=' . get_request_var('tree'); + } else { + $sql_where = ''; + } + + if (get_request_var('tree') != -2) { + $tree_list = get_allowed_trees(false, false, $sql_where, 'sequence'); + } else { + $tree_list = []; + } + + $function = 'renderHeader' . ucfirst(get_request_var('view')); + + if (function_exists($function)) { + $hosts = []; + + // Call the custom render_header_ function + $result .= $function($hosts); + } + + if (cacti_sizeof($tree_list)) { + $ptree = ''; + + foreach ($tree_list as $tree) { + $tree_ids[$tree['id']] = $tree['id']; + } + + renderWhereJoin($sql_where, $sql_join); + + $branchWhost_SQL = ("SELECT DISTINCT gti.graph_tree_id, gti.parent + FROM graph_tree_items AS gti + INNER JOIN graph_tree AS gt + ON gt.id = gti.graph_tree_id + INNER JOIN host AS h + ON h.id = gti.host_id + $sql_join + $sql_where + AND gti.host_id > 0 + AND gti.graph_tree_id IN (" . implode(',', $tree_ids) . ') + ORDER BY gt.sequence, gti.position'); + + // cacti_log($branchWhost_SQL); + + $branchWhost = db_fetch_assoc($branchWhost_SQL); + + // Determine the correct width of the cell + $maxlen = 10; + + if (get_request_var('view') == 'default') { + $maxlen = db_fetch_cell("SELECT MAX(LENGTH(description)) + FROM host AS h + INNER JOIN graph_tree_items AS gti + ON gti.host_id = h.id + WHERE disabled = '' + AND deleted = ''"); + } + + $maxlen = getMonitorTrimLength($maxlen); + + if (cacti_sizeof($branchWhost)) { + foreach ($branchWhost as $b) { + if ($ptree != $b['graph_tree_id']) { + $titles[$b['graph_tree_id'] . ':0'] = __('Root Branch', 'monitor'); + $ptree = $b['graph_tree_id']; + } + + if ($b['parent'] > 0) { + $titles[$b['graph_tree_id'] . ':' . $b['parent']] = db_fetch_cell_prepared('SELECT title + FROM graph_tree_items + WHERE id = ? + AND graph_tree_id = ? + ORDER BY position', + [$b['parent'], $b['graph_tree_id']]); + } + } + + $ptree = ''; + + foreach ($titles as $index => $title) { + [$graph_tree_id, $parent] = explode(':', $index); + + $oid = $parent; + + $sql_where = ''; + $sql_join = ''; + + renderWhereJoin($sql_where, $sql_join); + + $hosts_sql = "SELECT h.*, IFNULL(s.name,' " . __('Non-Site Device', 'monitor') . " ') AS site_name + FROM host AS h + LEFT JOIN sites AS s + ON h.site_id = s.id + INNER JOIN graph_tree_items AS gti + ON h.id = gti.host_id + $sql_join + $sql_where + AND parent = ? + AND graph_tree_id = ? + GROUP BY h.id + ORDER BY gti.position"; + + // cacti_log($hosts_sql); + + $hosts = db_fetch_assoc_prepared($hosts_sql, [$oid, $graph_tree_id]); + + $tree_name = db_fetch_cell_prepared('SELECT name + FROM graph_tree + WHERE id = ?', + [$graph_tree_id]); + + if ($ptree != $tree_name) { + if ($ptree != '') { + $result .= ''; + } + + $result .= "
+ +
+
+
"; + + $ptree = $tree_name; + } + + if (cacti_sizeof($hosts)) { + foreach ($hosts as $index => $host) { + if (is_device_allowed($host['id'])) { + $host_ids[] = $host['id']; + } else { + unset($hosts[$index]); + } + } + + $class = get_request_var('size'); + + $result .= "
"; + + foreach ($hosts as $host) { + $result .= renderHost($host, true, $maxlen); + } + + $result .= '
'; + } + } + } + + $result .= '
'; + } + + // begin others - lets get the monitor items that are not associated with any tree + if (get_request_var('tree') < 0) { + $hosts = getHostNonTreeArray(); + + if (cacti_sizeof($hosts)) { + foreach ($hosts as $index => $host) { + if (is_device_allowed($host['id'])) { + $host_ids[] = $host['id']; + } else { + unset($hosts[$index]); + } + } + + // Determine the correct width of the cell + $maxlen = 10; + + if (get_request_var('view') == 'default') { + if (cacti_sizeof($host_ids)) { + $maxlen = db_fetch_cell('SELECT MAX(LENGTH(description)) + FROM host AS h + WHERE id IN (' . implode(',', $host_ids) . ") + AND h.deleted = ''"); + } + } + $maxlen = getMonitorTrimLength($maxlen); + + $result .= "
+ +
+
"; + + foreach ($hosts as $leaf) { + $result .= renderHost($leaf, true, $maxlen); + } + + $result .= '
'; + } + } + + $function = 'renderFooter' . ucfirst(get_request_var('view')); + + if (function_exists($function)) { + // Call the custom render_footer_ function + $result .= $function($hosts); + } + + return $result; +} + +function getHostStatus($host, $real = false) { + global $thold_hosts, $iclasses; + + // If the host has been muted, show the muted Icon + if ($host['status'] != 1 && in_array($host['id'], $thold_hosts, true)) { + $host['status'] = 4; + } + + if (in_array($host['id'], $_SESSION['monitor_muted_hosts'], true) && $host['status'] == 1) { + $host['status'] = 5; + } elseif (in_array($host['id'], $_SESSION['monitor_muted_hosts'], true) && $host['status'] == 4) { + $host['status'] = 9; + } elseif ($host['status'] == 3) { + if ($host['cur_time'] > $host['monitor_alert'] && !empty($host['monitor_alert'])) { + $host['status'] = 8; + } elseif ($host['cur_time'] > $host['monitor_warn'] && !empty($host['monitor_warn'])) { + $host['status'] = 7; + } + } + + // If wanting the real status, or the status is already known + // return the real status, otherwise default to unknown + return ($real || array_key_exists($host['status'], $iclasses)) ? $host['status'] : 0; +} + +function getHostStatusDescription($status) { + global $icolorsdisplay; + + if (array_key_exists($status, $icolorsdisplay)) { + return $icolorsdisplay[$status]; + } else { + return __('Unknown', 'monitor') . " ($status)"; + } +} + +/** + * render_host - Renders a host using a sub-function + * @param mixed $host + * @param mixed $float + * @param mixed $maxlen + */ +function renderHost($host, $float = true, $maxlen = 10) { + global $thold_hosts, $config, $icolorsdisplay, $iclasses, $classes, $maxchars, $mon_zoom_state; + + // throw out tree root items + if (array_key_exists('name', $host)) { + return; + } + + if ($host['id'] <= 0) { + return; + } + + $host['anchor'] = $config['url_path'] . 'graph_view.php?action=preview&reset=1&host_id=' . $host['id']; + + if ($host['status'] == 3 && array_key_exists($host['id'], $thold_hosts)) { + $host['status'] = 4; + $host['anchor'] = $config['url_path'] . 'plugins/thold/thold_graph.php?action=thold&reset=true&status=1&host_id=' . $host['id']; + } + + $host['real_status'] = getHostStatus($host, true); + $host['status'] = getHostStatus($host); + $host['iclass'] = $iclasses[$host['status']]; + + $function = 'renderHost' . ucfirst(get_request_var('view')); + + if (function_exists($function)) { + // Call the custom render_host_ function + $result = $function($host); + } else { + $iclass = getStatusIcon($host['status'], $host['monitor_icon']); + $fclass = get_request_var('size'); + + $monitor_times = read_user_setting('monitor_uptime'); + $monitor_time_html = ''; + + if ($host['status'] <= 2 || $host['status'] == 5) { + if ($mon_zoom_state) { + $fclass = 'monitor_errorzoom'; + } + $tis = get_timeinstate($host); + + if ($monitor_times == 'on') { + $monitor_time_html = "
$tis"; + } + $result = "

" . title_trim(html_escape($host['description']), $maxlen) . "$monitor_time_html
"; + } else { + $tis = get_uptime($host); + + if ($monitor_times == 'on') { + $monitor_time_html = "
$tis
"; + } + + $result = "

" . title_trim(html_escape($host['description']), $maxlen) . "$monitor_time_html
"; + } + } + + return $result; +} + +function getStatusIcon($status, $icon) { + global $fa_icons; + + if (($status == 1 || ($status == 4 && get_request_var('status') > 0)) && read_user_setting('monitor_sound') == 'First Orders Suite.mp3') { + return 'fab fa-first-order fa-spin mon_icon'; + } + + if ($icon != '' && array_key_exists($icon, $fa_icons)) { + if (isset($fa_icons[$icon]['class'])) { + return $fa_icons[$icon]['class'] . ' mon_icon'; + } else { + return "fa fa-$icon mon_icon"; + } + } else { + return 'fa fa-server' . ' mon_icon'; + } +} + +function monitorPrintHostTime($status_time, $seconds = false) { + // If the host is down, make a downtime since message + $dt = ''; + + if (is_numeric($status_time)) { + $sfd = round($status_time / 100,0); + } else { + $sfd = time() - strtotime($status_time); + } + $dt_d = floor($sfd / 86400); + $dt_h = floor(($sfd - ($dt_d * 86400)) / 3600); + $dt_m = floor(($sfd - ($dt_d * 86400) - ($dt_h * 3600)) / 60); + $dt_s = $sfd - ($dt_d * 86400) - ($dt_h * 3600) - ($dt_m * 60); + + if ($dt_d > 0) { + $dt .= $dt_d . 'd:' . $dt_h . 'h:' . $dt_m . 'm' . ($seconds ? ':' . $dt_s . 's' : ''); + } elseif ($dt_h > 0) { + $dt .= $dt_h . 'h:' . $dt_m . 'm' . ($seconds ? ':' . $dt_s . 's' : ''); + } elseif ($dt_m > 0) { + $dt .= $dt_m . 'm' . ($seconds ? ':' . $dt_s . 's' : ''); + } else { + $dt .= ($seconds ? $dt_s . 's' : __('Just Up', 'monitor')); + } + + return $dt; +} + + +function monitorTrim($string) { + return trim($string, "\"'\\ \n\t\r"); +} + +function renderHeaderDefault($hosts) { + return "
"; +} + +function renderHeaderNames($hosts) { + return ""; +} + +function renderHeaderTiles($hosts) { + return renderHeaderDefault($hosts); +} + +function renderHeaderTilesadt($hosts) { + return renderHeaderDefault($hosts); +} + +function renderHeaderList($hosts, $total_rows = 0, $rows = 0) { + $display_text = [ + 'hostname' => [ + 'display' => __('Hostname', 'monitor'), + 'sort' => 'ASC', + 'align' => 'left', 'tip' => __('Hostname of device', 'monitor') + ], + 'id' => [ + 'display' => __('ID', 'monitor'), + 'sort' => 'ASC', + 'align' => 'left' + ], + 'description' => [ + 'display' => __('Description', 'monitor'), + 'sort' => 'ASC', + 'align' => 'left' + ], + 'site_name' => [ + 'display' => __('Site', 'monitor'), + 'sort' => 'ASC', + 'align' => 'left' + ], + 'monitor_criticality' => [ + 'display' => __('Criticality', 'monitor'), + 'sort' => 'ASC', + 'align' => 'left' + ], + 'status' => [ + 'display' => __('Status', 'monitor'), + 'sort' => 'DESC', + 'align' => 'center' + ], + 'instate' => [ + 'display' => __('Length in Status', 'monitor'), + 'sort' => 'ASC', + 'align' => 'center' + ], + 'avg_time' => [ + 'display' => __('Averages', 'monitor'), + 'sort' => 'DESC', + 'align' => 'left' + ], + 'monitor_warn' => [ + 'display' => __('Warning', 'monitor'), + 'sort' => 'DESC', + 'align' => 'left' + ], + 'monitor_text' => [ + 'display' => __('Admin', 'monitor'), + 'sort' => 'ASC', + 'tip' => __('Monitor Text Column represents \'Admin\'', 'monitor'), + 'align' => 'left' + ], + 'notes' => [ + 'display' => __('Notes', 'monitor'), + 'sort' => 'ASC', + 'align' => 'left' + ], + 'availability' => [ + 'display' => __('Availability', 'monitor'), + 'sort' => 'DESC', + 'align' => 'right' + ], + 'status_fail_date' => [ + 'display' => __('Last Fail', 'monitor'), + 'sort' => 'DESC', + 'align' => 'right' + ], + ]; + + ob_start(); + + $nav = html_nav_bar('monitor.php?rfilter=' . get_request_var('rfilter'), MAX_DISPLAY_PAGES, get_request_var('page'), $rows, $total_rows, 12, __('Devices'), 'page', 'main'); + + html_start_box(__('Monitored Devices', 'monitor'), '100%', false, '3', 'center', ''); + + print $nav; + + html_header_sort($display_text, get_request_var('sort_column'), get_request_var('sort_direction'), false); + + $output = ob_get_contents(); + + ob_end_clean(); + + return $output; +} + +function renderSuppressgroupsList($hosts) { + return true; +} + +function renderFooterDefault($hosts) { + return ''; +} + +function renderFooterNames($hosts) { + $col = 7 - $_SESSION['names']; + + if ($col == 0) { + return '
'; + } else { + return ''; + } +} + +function renderFooterTiles($hosts) { + return renderFooterDefault($hosts); +} + +function renderFooterTilesadt($hosts) { + return renderFooterDefault($hosts); +} + +function renderFooterList($hosts, $total_rows, $rows) { + ob_start(); + + html_end_box(false); + + if ($total_rows > 0) { + $nav = html_nav_bar('monitor.php?rfilter=' . get_request_var('rfilter'), MAX_DISPLAY_PAGES, get_request_var('page'), $rows, $total_rows, 12, __('Devices'), 'page', 'main'); + + print $nav; + } + + $output = ob_get_contents(); + + ob_end_clean(); + + return $output; +} + +function renderHostList($host) { + global $criticalities, $iclasses; + + if ($host['status'] < 2 || $host['status'] == 5) { + $dt = get_timeinstate($host); + } elseif (strtotime($host['status_rec_date']) > 192800) { + $dt = get_timeinstate($host); + } else { + $dt = __('Never', 'monitor'); + } + + if ($host['status'] < 3 || $host['status'] == 5) { + $host_admin = $host['monitor_text']; + } else { + $host_admin = ''; + } + + if (isset($host['monitor_criticality']) && $host['monitor_criticality'] > 0) { + $host_crit = $criticalities[$host['monitor_criticality']]; + } else { + $host_crit = ''; + } + + if ($host['availability_method'] > 0) { + $host_address = $host['hostname']; + $host_avg = __('%d ms', $host['cur_time'], 'monitor') . ' / ' . __('%d ms', $host['avg_time'], 'monitor'); + } else { + $host_address = ''; + $host_avg = __('N/A', 'monitor'); + } + + if (isset($host['monitor_warn']) && ($host['monitor_warn'] > 0 || $host['monitor_alert'] > 0)) { + $host_warn = __('%0.2d ms', $host['monitor_warn'], 'monitor') . ' / ' . __('%0.2d ms', $host['monitor_alert'], 'monitor'); + } else { + $host_warn = ''; + } + + if (strtotime($host['status_fail_date']) < 86400) { + $host['status_fail_date'] = __('Never', 'monitor'); + } + + $host_datefail = $host['status_fail_date']; + + $iclass = $iclasses[$host['status']]; + $sdisplay = getHostStatusDescription($host['real_status']); + + $row_class = "{$iclass}Full"; + + ob_start(); + + print ""; + + $url = $host['anchor']; + + form_selectable_cell(filter_value($host['hostname'], '', $url), $host['id'], '', 'left'); + form_selectable_cell($host['id'], $host['id'], '', 'left'); + form_selectable_cell($host['description'], $host['id'], '', 'left'); + form_selectable_cell($host['site_name'], $host['id'], '', 'left'); + form_selectable_cell($host_crit, $host['id'], '', 'left'); + form_selectable_cell($sdisplay, $host['id'], '', 'center'); + form_selectable_cell($dt, $host['id'], '', 'center'); + form_selectable_cell($host_avg, $host['id'], '', 'left'); + form_selectable_cell($host_warn, $host['id'], '', 'left'); + form_selectable_cell($host_admin, $host['id'], '', 'white-space:pre-wrap;text-align:left'); + form_selectable_cell(str_replace(["\n", "\r"], [' ', ''], $host['notes']), $host['id'], '', 'white-space:pre-wrap;text-align:left'); + form_selectable_cell(round($host['availability'],2) . ' %', $host['id'], '', 'right'); + form_selectable_cell($host_datefail, $host['id'], '', 'right'); + + form_end_row(); + + $result = ob_get_contents(); + + ob_end_clean(); + + return $result; +} + +function renderHostNames($host) { + $fclass = get_request_var('size'); + + $result = ''; + + $maxlen = getMonitorTrimLength(100); + $monitor_times = read_user_setting('monitor_uptime'); + $monitor_time_html = ''; + + if ($_SESSION['names'] == 0) { + $result .= ''; + } + + if ($host['status'] <= 2 || $host['status'] == 5) { + $result .= "" . title_trim(html_escape($host['description']), $maxlen) . ''; + } else { + $result .= "" . title_trim(html_escape($host['description']), $maxlen) . ''; + } + + $_SESSION['names']++; + + if ($_SESSION['names'] > 7) { + $result .= ''; + $_SESSION['names'] = 0; + } + + return $result; +} + +function renderHostTiles($host, $maxlen = 10) { + $class = getStatusIcon($host['status'], $host['monitor_icon']); + $fclass = get_request_var('size'); + + $result = "
"; + + return $result; +} + +function renderHostTilesadt($host, $maxlen = 10) { + $tis = ''; + + $class = getStatusIcon($host['status'], $host['monitor_icon']); + $fclass = get_request_var('size'); + + if ($host['status'] < 2 || $host['status'] == 5) { + $tis = get_timeinstate($host); + + $result = ""; + + return $result; + } else { + $tis = get_uptime($host); + + $result = ""; + + return $result; + } +} + + +function getMonitorTrimLength($fieldlen) { + global $maxchars; + + if (get_request_var('view') == 'default' || get_request_var('view') == 'names') { + $maxlen = $maxchars; + + if (get_request_var('trim') < 0) { + $maxlen = 4000; + } elseif (get_request_var('trim') > 0) { + $maxlen = get_request_var('trim'); + } + + if ($fieldlen > $maxlen) { + $fieldlen = $maxlen; + } + } + + return $fieldlen; +} From 8f09edf671871c422ef261ecfdb17ed733101394 Mon Sep 17 00:00:00 2001 From: Sean Mancini Date: Sun, 1 Mar 2026 19:30:33 -0500 Subject: [PATCH 07/26] modernize js Replaced legacy var with const/let. Switched loose checks to strict (===, !==, strict typeof checks). Added default param: applyFilter(action = ''). Used template literals for URL/query string assembly. Converted many callbacks to arrow functions and shorthand methods. Removed one duplicate object key in saveFilter payload (trim was defined twice with same value). Kept existing flow, DOM selectors, action names, and endpoints unchanged. --- js/monitor.js | 244 ++++++++++++++++++++++++-------------------------- 1 file changed, 119 insertions(+), 125 deletions(-) diff --git a/js/monitor.js b/js/monitor.js index 4e15cd0..1da55e9 100644 --- a/js/monitor.js +++ b/js/monitor.js @@ -1,44 +1,44 @@ -var refreshMSeconds = 99999999; -var myTimer; -var monitorCfg = window.monitorPageConfig || {}; -var mbColor = monitorCfg.mbColor || ''; -var monitorFont = monitorCfg.monitorFont || '10px'; -var dozoomRefresh = !!monitorCfg.doZoomRefresh; -var monitorMessages = monitorCfg.messages || {}; -var monitorNewForm = monitorCfg.newForm || ''; -var monitorNewTitle = monitorCfg.newTitle || ''; - -if (mbColor !== '') { - var monoe = false; +let refreshMSeconds = 99999999; +let myTimer; + +const monitorCfg = window.monitorPageConfig || {}; +const mbColor = monitorCfg.mbColor || ''; +const monitorFont = monitorCfg.monitorFont || '10px'; +const dozoomRefresh = Boolean(monitorCfg.doZoomRefresh); +const monitorMessages = monitorCfg.messages || {}; +const monitorNewForm = monitorCfg.newForm || ''; +const monitorNewTitle = monitorCfg.newTitle || ''; + +function setZoomErrorBackgrounds() { + if (mbColor !== '') { + $('.monitor_container').css('background-color', mbColor); + $('.cactiConsoleContentArea').css('background-color', mbColor); + } +} - function setZoomErrorBackgrounds() { - if (mbColor != '') { - $('.monitor_container').css('background-color', mbColor); - $('.cactiConsoleContentArea').css('background-color', mbColor); +function setIntervalX(callback, delay, repetitions) { + let x = 0; + const intervalID = window.setInterval(() => { + callback(); + if (++x === repetitions) { + window.clearInterval(intervalID); + setZoomErrorBackgrounds(); } - } + }, delay); +} + +if (mbColor !== '') { + let monoe = false; setZoomErrorBackgrounds(); $('.monitor_errorzoom_title').css('font-size', monitorFont); - function setIntervalX(callback, delay, repetitions) { - var x = 0; - var intervalID = window.setInterval(function () { - callback(); - if (++x === repetitions) { - window.clearInterval(intervalID); - setZoomErrorBackgrounds(); - } - }, delay); - } - - setIntervalX(function () { - if (monoe === false) { + setIntervalX(() => { + if (!monoe) { setZoomErrorBackgrounds(); - monoe = true; } else { - if (mbColor != '') { + if (mbColor !== '') { $('.monitor_container').css('background-color', ''); $('.cactiConsoleContentArea').css('background-color', ''); } @@ -52,7 +52,7 @@ if (mbColor !== '') { } function timeStep() { - value = $('#timer').html() - 1; + const value = Number($('#timer').html()) - 1; if (value <= 0) { applyFilter('refresh'); @@ -70,7 +70,7 @@ function muteUnmuteAudio(mute) { this.pause(); this.currentTime = 0; }); - } else if ($('#downhosts').val() == 'true') { + } else if ($('#downhosts').val() === 'true') { $('audio').each(function() { this.play(); }); @@ -81,46 +81,43 @@ function closeTip() { $(document).tooltip('close'); } -function applyFilter(action) { - if (typeof action == 'undefined') { - action = ''; - } - +function applyFilter(action = '') { clearTimeout(myTimer); $('.mon_icon').unbind(); - if (action != 'dashboard') { - var strURL = 'monitor.php?header=false'; + let strURL; + + if (action !== 'dashboard') { + strURL = 'monitor.php?header=false'; if (action >= '') { - strURL += '&action=' + action; + strURL += `&action=${action}`; } - strURL += '&refresh=' + $('#refresh').val(); - strURL += '&grouping=' + $('#grouping').val(); - strURL += '&tree=' + $('#tree').val(); - strURL += '&site=' + $('#site').val(); - strURL += '&template=' + $('#template').val(); - strURL += '&view=' + $('#view').val(); - strURL += '&rows=' + $('#rows').val(); - strURL += '&crit=' + $('#crit').val(); - strURL += '&size=' + $('#size').val(); - strURL += '&trim=' + $('#trim').val(); - strURL += '&mute=' + $('#mute').val(); - strURL += '&rfilter=' + base64_encode($('#rfilter').val()); - strURL += '&status=' + $('#status').val(); + strURL += `&refresh=${$('#refresh').val()}`; + strURL += `&grouping=${$('#grouping').val()}`; + strURL += `&tree=${$('#tree').val()}`; + strURL += `&site=${$('#site').val()}`; + strURL += `&template=${$('#template').val()}`; + strURL += `&view=${$('#view').val()}`; + strURL += `&rows=${$('#rows').val()}`; + strURL += `&crit=${$('#crit').val()}`; + strURL += `&size=${$('#size').val()}`; + strURL += `&trim=${$('#trim').val()}`; + strURL += `&mute=${$('#mute').val()}`; + strURL += `&rfilter=${base64_encode($('#rfilter').val())}`; + strURL += `&status=${$('#status').val()}`; } else { - strURL = 'monitor.php?action=dbchange&header=false'; - strURL += '&dashboard=' + $('#dashboard').val(); + strURL = `monitor.php?action=dbchange&header=false&dashboard=${$('#dashboard').val()}`; } loadIt(strURL); } function saveFilter() { - var url = 'monitor.php?action=save&header=false'; + const url = 'monitor.php?action=save&header=false'; - var post = { + const post = { dashboard: $('#dashboard').val(), refresh: $('#refresh').val(), grouping: $('#grouping').val(), @@ -134,28 +131,22 @@ function saveFilter() { trim: $('#trim').val(), mute: $('#mute').val(), size: $('#size').val(), - trim: $('#trim').val(), status: $('#status').val(), __csrf_magic: csrfMagicToken }; - $.post(url, post).done(function(data) { + $.post(url, post).done(() => { $('#text').show().text(monitorMessages.filterSaved || '').fadeOut(2000); }); } function saveNewDashboard(action) { - if (action == 'new') { - var dashboard = '-1'; - } else { - var dashboard = $('#dashboard').val(); - } - - var url = 'monitor.php?header=false'; + const dashboard = action === 'new' ? '-1' : $('#dashboard').val(); + const url = 'monitor.php?header=false'; - var post = { + const post = { action: 'saveDb', - dashboard: dashboard, + dashboard, name: $('#name').val(), refresh: $('#refresh').val(), grouping: $('#grouping').val(), @@ -174,54 +165,56 @@ function saveNewDashboard(action) { }; $('#newdialog').dialog('close'); - postIt(url, post); } function removeDashboard() { - url = 'monitor.php?action=remove&header=false&dashboard=' + $('#dashboard').val(); + const url = `monitor.php?action=remove&header=false&dashboard=${$('#dashboard').val()}`; loadIt(url); } function loadIt(url) { - if (typeof loadUrl == 'undefined') { + if (typeof loadUrl === 'undefined') { loadPageNoHeader(url); } else { - loadUrl({url: url}); + loadUrl({ url }); } } function postIt(url, post, returnLocation) { - if (typeof postUrl == 'undefined') { + if (typeof postUrl === 'undefined') { loadPageUsingPost(url, post); } else { - postUrl({ - url: url, - tabId: returnLocation, - type: 'loadPageUsingPost' - }, post); + postUrl( + { + url, + tabId: returnLocation, + type: 'loadPageUsingPost' + }, + post + ); } } function saveDashboard(action) { - var btnDialog = { - 'Cancel': { + const btnDialog = { + Cancel: { text: monitorMessages.cancel || 'Cancel', id: 'btnCancel', - click: function() { + click() { $(this).dialog('close'); } }, - 'Save': { + Save: { text: monitorMessages.save || 'Save', id: 'btnSave', - click: function() { + click() { saveNewDashboard(action); } } }; - if ($('#newdialog').length == 0) { + if ($('#newdialog').length === 0) { $('body').append(monitorNewForm); } @@ -231,26 +224,28 @@ function saveDashboard(action) { minWidth: 500, buttons: btnDialog, position: { at: 'center top+240px', of: window }, - open: function() { + open() { $('#name').val($('#dashboard option:selected').text()); $('#btnSave').addClass('ui-state-active'); $('#name').focus(); - $('#new_dashboard').off('submit').on('submit', function(event) { - event.preventDefault(); - saveNewDashboard('new'); - }); + $('#new_dashboard') + .off('submit') + .on('submit', (event) => { + event.preventDefault(); + saveNewDashboard('new'); + }); } }); } -$(function() { +$(() => { if (dozoomRefresh) { applyFilter('refresh'); } - var selectmenu = ($('#grouping').selectmenu('instance') !== undefined); + const selectmenu = $('#grouping').selectmenu('instance') !== undefined; - if ($('#view').val() == 'list') { + if ($('#view').val() === 'list') { $('#grouping').prop('disabled', true); if (selectmenu) { $('#grouping').selectmenu('disable'); @@ -262,20 +257,19 @@ $(function() { } } - // Clear the timeout to keep countdown accurate clearTimeout(myTimer); - $('#go').click(function(event) { + $('#go').click((event) => { event.preventDefault(); applyFilter('go'); }); - $('#clear').click(function(event) { + $('#clear').click(() => { loadIt('monitor.php?clear=1&header=false'); }); - $('#sound').click(function() { - if ($('#mute').val() == 'false') { + $('#sound').click(() => { + if ($('#mute').val() === 'false') { $('#mute').val('true'); muteUnmuteAudio(true); applyFilter('ajax_mute_all'); @@ -286,60 +280,59 @@ $(function() { } }); - $('#refresh, #view, #rows, #trim, #crit, #grouping, #size, #status, #tree, #site, #template').change(function() { + $('#refresh, #view, #rows, #trim, #crit, #grouping, #size, #status, #tree, #site, #template').change(() => { applyFilter('change'); }); - $('#dashboard').change(function() { + $('#dashboard').change(() => { applyFilter('dashboard'); }); - $('#save').click(function() { + $('#save').click(() => { saveFilter(); }); - $('#new').click(function() { + $('#new').click(() => { saveDashboard('new'); }); - $('#rename').click(function() { + $('#rename').click(() => { saveDashboard('rename'); }); - $('#delete').click(function() { + $('#delete').click(() => { removeDashboard(); }); - $('.monitorFilterForm').submit(function(event) { + $('.monitorFilterForm').submit((event) => { event.preventDefault(); applyFilter('change'); }); $('.monitor_device_frame').find('i').tooltip({ items: '.mon_icon', - open: function(event, ui) { + open(event, ui) { ajaxAnchors(); - if (typeof(event.originalEvent) == 'undefined') { + if (typeof event.originalEvent === 'undefined') { return false; } - - var id = $(ui.tooltip).attr('id'); }, - close: function(event, ui) { + close(event, ui) { ui.tooltip.hover( - function () { - $(this).stop(true).fadeTo(400, 1); - }, - function() { - $(this).fadeOut('400'); - }); + function() { + $(this).stop(true).fadeTo(400, 1); + }, + function() { + $(this).fadeOut('400'); + } + ); }, - position: {my: 'left:15 top', at: 'right center'}, - content: function(callback) { - var id = $(this).attr('id'); - var size = $('#size').val(); - $.get('monitor.php?action=ajax_status&size=' + size + '&id=' + id, function(data) { + position: { my: 'left:15 top', at: 'right center' }, + content(callback) { + const id = $(this).attr('id'); + const size = $('#size').val(); + $.get(`monitor.php?action=ajax_status&size=${size}&id=${id}`, (data) => { callback(data); }); } @@ -347,14 +340,15 @@ $(function() { myTimer = setTimeout(timeStep, 1000); - $(window).resize(function() { - $(document).tooltip('option', 'position', {my: '1eft:15 top', at: 'right center'}); + $(window).resize(() => { + $(document).tooltip('option', 'position', { my: '1eft:15 top', at: 'right center' }); }); - if ($('#mute').val() == 'true') { + if ($('#mute').val() === 'true') { muteUnmuteAudio(true); } else { muteUnmuteAudio(false); } + $('#main').css('margin-right', '15px'); }); From e759aa38e543c4bcdac053a01dd051e6ddb714af Mon Sep 17 00:00:00 2001 From: Sean Mancini Date: Sun, 1 Mar 2026 19:32:28 -0500 Subject: [PATCH 08/26] Update monitor.js Applied the Sonar-requested cleanups in monitor.js: --- js/monitor.js | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/js/monitor.js b/js/monitor.js index 1da55e9..e94c614 100644 --- a/js/monitor.js +++ b/js/monitor.js @@ -1,7 +1,7 @@ let refreshMSeconds = 99999999; let myTimer; -const monitorCfg = window.monitorPageConfig || {}; +const monitorCfg = globalThis.monitorPageConfig || {}; const mbColor = monitorCfg.mbColor || ''; const monitorFont = monitorCfg.monitorFont || '10px'; const dozoomRefresh = Boolean(monitorCfg.doZoomRefresh); @@ -18,37 +18,37 @@ function setZoomErrorBackgrounds() { function setIntervalX(callback, delay, repetitions) { let x = 0; - const intervalID = window.setInterval(() => { + const intervalID = globalThis.setInterval(() => { callback(); if (++x === repetitions) { - window.clearInterval(intervalID); + globalThis.clearInterval(intervalID); setZoomErrorBackgrounds(); } }, delay); } -if (mbColor !== '') { +if (mbColor === '') { + $('.monitor_container').css('background-color', ''); + $('.cactiConsoleContentArea').css('background-color', ''); +} else { let monoe = false; setZoomErrorBackgrounds(); $('.monitor_errorzoom_title').css('font-size', monitorFont); setIntervalX(() => { - if (!monoe) { - setZoomErrorBackgrounds(); - monoe = true; - } else { + if (monoe) { if (mbColor !== '') { $('.monitor_container').css('background-color', ''); $('.cactiConsoleContentArea').css('background-color', ''); } monoe = false; + } else { + setZoomErrorBackgrounds(); + monoe = true; } }, 600, 8); -} else { - $('.monitor_container').css('background-color', ''); - $('.cactiConsoleContentArea').css('background-color', ''); } function timeStep() { @@ -87,7 +87,9 @@ function applyFilter(action = '') { let strURL; - if (action !== 'dashboard') { + if (action === 'dashboard') { + strURL = `monitor.php?action=dbchange&header=false&dashboard=${$('#dashboard').val()}`; + } else { strURL = 'monitor.php?header=false'; if (action >= '') { @@ -107,8 +109,6 @@ function applyFilter(action = '') { strURL += `&mute=${$('#mute').val()}`; strURL += `&rfilter=${base64_encode($('#rfilter').val())}`; strURL += `&status=${$('#status').val()}`; - } else { - strURL = `monitor.php?action=dbchange&header=false&dashboard=${$('#dashboard').val()}`; } loadIt(strURL); @@ -223,7 +223,7 @@ function saveDashboard(action) { minHeight: 80, minWidth: 500, buttons: btnDialog, - position: { at: 'center top+240px', of: window }, + position: { at: 'center top+240px', of: globalThis }, open() { $('#name').val($('#dashboard option:selected').text()); $('#btnSave').addClass('ui-state-active'); @@ -314,7 +314,7 @@ $(() => { open(event, ui) { ajaxAnchors(); - if (typeof event.originalEvent === 'undefined') { + if (event.originalEvent === undefined) { return false; } }, @@ -340,7 +340,7 @@ $(() => { myTimer = setTimeout(timeStep, 1000); - $(window).resize(() => { + $(globalThis).resize(() => { $(document).tooltip('option', 'position', { my: '1eft:15 top', at: 'right center' }); }); From 662a8bef20a950f2421d575badfd369c3b117b45 Mon Sep 17 00:00:00 2001 From: Sean Mancini Date: Sun, 1 Mar 2026 19:34:12 -0500 Subject: [PATCH 09/26] remove unused variables --- monitor_render.php | 20 +++++--------------- 1 file changed, 5 insertions(+), 15 deletions(-) diff --git a/monitor_render.php b/monitor_render.php index 26337f9..0f7c6c9 100644 --- a/monitor_render.php +++ b/monitor_render.php @@ -893,10 +893,8 @@ function renderHostList($host) { } if ($host['availability_method'] > 0) { - $host_address = $host['hostname']; $host_avg = __('%d ms', $host['cur_time'], 'monitor') . ' / ' . __('%d ms', $host['avg_time'], 'monitor'); } else { - $host_address = ''; $host_avg = __('N/A', 'monitor'); } @@ -952,8 +950,6 @@ function renderHostNames($host) { $result = ''; $maxlen = getMonitorTrimLength(100); - $monitor_times = read_user_setting('monitor_uptime'); - $monitor_time_html = ''; if ($_SESSION['names'] == 0) { $result .= ''; @@ -975,16 +971,14 @@ function renderHostNames($host) { return $result; } -function renderHostTiles($host, $maxlen = 10) { +function renderHostTiles($host) { $class = getStatusIcon($host['status'], $host['monitor_icon']); $fclass = get_request_var('size'); - $result = "
"; - - return $result; + return "
"; } -function renderHostTilesadt($host, $maxlen = 10) { +function renderHostTilesadt($host) { $tis = ''; $class = getStatusIcon($host['status'], $host['monitor_icon']); @@ -993,15 +987,11 @@ function renderHostTilesadt($host, $maxlen = 10) { if ($host['status'] < 2 || $host['status'] == 5) { $tis = get_timeinstate($host); - $result = ""; - - return $result; + return ""; } else { $tis = get_uptime($host); - $result = ""; - - return $result; + return ""; } } From e6cc43772390e087c860df33dcdefd85bda90e79 Mon Sep 17 00:00:00 2001 From: Sean Mancini Date: Sun, 1 Mar 2026 19:35:56 -0500 Subject: [PATCH 10/26] remove unused variables --- monitor_render.php | 50 +++++++++++++++++++++++----------------------- 1 file changed, 25 insertions(+), 25 deletions(-) diff --git a/monitor_render.php b/monitor_render.php index 0f7c6c9..a386a96 100644 --- a/monitor_render.php +++ b/monitor_render.php @@ -93,7 +93,7 @@ function renderDefault() { if (function_exists($function)) { // Call the custom render_header_ function - $result .= $function($hosts, $total_rows, $rows); + $result .= $function($total_rows, $rows); } $count = 0; @@ -110,7 +110,7 @@ function renderDefault() { if (function_exists($function)) { // Call the custom render_footer_ function - $result .= $function($hosts, $total_rows, $rows); + $result .= $function($total_rows, $rows); } } @@ -159,14 +159,14 @@ function renderSite() { $function = 'renderSuppressgroups' . ucfirst(get_request_var('view')); if (function_exists($function)) { - $suppressGroups = $function($hosts); + $suppressGroups = $function(); } $function = 'renderHeader' . ucfirst(get_request_var('view')); if (function_exists($function)) { // Call the custom render_header_ function - $result .= $function($hosts); + $result .= $function(); $suppressGroups = true; } @@ -228,7 +228,7 @@ function renderSite() { if (function_exists($function)) { // Call the custom render_footer_ function - $result .= $function($hosts); + $result .= $function(); } } @@ -286,14 +286,14 @@ function renderTemplate() { $function = 'renderSuppressgroups' . ucfirst(get_request_var('view')); if (function_exists($function)) { - $suppressGroups = $function($hosts); + $suppressGroups = $function(); } $function = 'renderHeader' . ucfirst(get_request_var('view')); if (function_exists($function)) { // Call the custom render_header_ function - $result .= $function($hosts); + $result .= $function(); $suppressGroups = true; } @@ -355,7 +355,7 @@ function renderTemplate() { if (function_exists($function)) { // Call the custom render_footer_ function - $result .= $function($hosts); + $result .= $function(); } } @@ -387,7 +387,7 @@ function renderTree() { $hosts = []; // Call the custom render_header_ function - $result .= $function($hosts); + $result .= $function(); } if (cacti_sizeof($tree_list)) { @@ -566,7 +566,7 @@ function renderTree() { if (function_exists($function)) { // Call the custom render_footer_ function - $result .= $function($hosts); + $result .= $function(); } return $result; @@ -722,23 +722,23 @@ function monitorTrim($string) { return trim($string, "\"'\\ \n\t\r"); } -function renderHeaderDefault($hosts) { +function renderHeaderDefault() { return "
"; } -function renderHeaderNames($hosts) { +function renderHeaderNames() { return ""; } -function renderHeaderTiles($hosts) { - return renderHeaderDefault($hosts); +function renderHeaderTiles() { + return renderHeaderDefault(); } -function renderHeaderTilesadt($hosts) { - return renderHeaderDefault($hosts); +function renderHeaderTilesadt() { + return renderHeaderDefault(); } -function renderHeaderList($hosts, $total_rows = 0, $rows = 0) { +function renderHeaderList($total_rows = 0, $rows = 0) { $display_text = [ 'hostname' => [ 'display' => __('Hostname', 'monitor'), @@ -825,15 +825,15 @@ function renderHeaderList($hosts, $total_rows = 0, $rows = 0) { return $output; } -function renderSuppressgroupsList($hosts) { +function renderSuppressgroupsList() { return true; } -function renderFooterDefault($hosts) { +function renderFooterDefault() { return ''; } -function renderFooterNames($hosts) { +function renderFooterNames() { $col = 7 - $_SESSION['names']; if ($col == 0) { @@ -843,15 +843,15 @@ function renderFooterNames($hosts) { } } -function renderFooterTiles($hosts) { - return renderFooterDefault($hosts); +function renderFooterTiles() { + return renderFooterDefault(); } -function renderFooterTilesadt($hosts) { - return renderFooterDefault($hosts); +function renderFooterTilesadt() { + return renderFooterDefault(); } -function renderFooterList($hosts, $total_rows, $rows) { +function renderFooterList($total_rows, $rows) { ob_start(); html_end_box(false); From 5fd26f2507e1592efc263c31d3e0db4e709ad45c Mon Sep 17 00:00:00 2001 From: Sean Mancini Date: Sun, 1 Mar 2026 21:55:53 -0500 Subject: [PATCH 11/26] Update copilot-instructions.md --- .github/copilot-instructions.md | 182 ++++++++++++-------------------- 1 file changed, 70 insertions(+), 112 deletions(-) diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index ffda458..aba0f56 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -4,153 +4,111 @@ When generating code for this repository: -1. **Version Compatibility**: Respect versions and compatibility declared by this plugin and CI. -2. **Context Files**: If `.github/copilot/*` files are added later, prioritize them first. -3. **Codebase Patterns**: When no explicit guidance exists, follow established patterns in this repository. -4. **Architectural Consistency**: Preserve the current monolithic, procedural Cacti plugin architecture. -5. **Code Quality**: Prioritize maintainability, security, performance, and testability in ways already present in this codebase. +1. **Version Compatibility First**: Honor plugin and CI version constraints before all style preferences. +2. **Repository Context Files**: Prioritize `.github/copilot/*` docs if they are added later. +3. **Agent Profiles as Secondary Context**: Reuse conventions from `.github/agents/*.md` when applicable. +4. **Pattern Matching Over Reinvention**: Mirror existing plugin patterns in the same file/flow. +5. **Architectural Consistency**: Keep the plugin procedural and Cacti-native. -## Technology Version Detection +## Verified Runtime and Compatibility -Before generating code, detect and honor exact versions from repository metadata: +Use only capabilities compatible with observed project metadata: -- **Plugin metadata**: `INFO` +- **Plugin metadata (`INFO`)** + - `name = monitor` - `version = 2.8` - - `compat = 1.2.15` (Cacti compatibility) + - `compat = 1.2.15` - `requires = thold:1.2.1` -- **CI runtime matrix**: `.github/workflows/plugin-ci-workflow.yml` +- **CI matrix (`.github/workflows/plugin-ci-workflow.yml`)** - PHP: `8.1`, `8.2`, `8.3`, `8.4` + - OS: `ubuntu-latest` - MariaDB service: `10.6` -- **Language/frameworks observed**: - - PHP plugin code (`setup.php`, `monitor.php`, `poller_monitor.php`) - - CSS themes (`monitor.css`, `themes/*/monitor.css`) - - GitHub Actions workflow YAML +- **Observed technologies** + - Procedural PHP plugin files + - CSS theme overlays in `themes/*/monitor.css` - gettext localization (`locales/po/*.po`, `locales/LC_MESSAGES/*.mo`) + - GitHub Actions integration checks -Do not introduce APIs or syntax incompatible with the supported Cacti/plugin environment and CI matrix. +Do not introduce syntax or APIs that could fail under these versions. -## Context Files +## Architecture and File Responsibilities -If present in future, prioritize `.github/copilot` files in this order: +This is a single Cacti plugin with procedural flows split by responsibility: -- `architecture.md` -- `tech-stack.md` -- `coding-standards.md` -- `folder-structure.md` -- `exemplars.md` +- `setup.php`: plugin lifecycle, hook registration, config arrays/settings, install/upgrade table management. +- `monitor.php`: web entrypoint/bootstrap, includes, session/request setup. +- `monitor_controller.php`: action flow, filter handling, page orchestration. +- `monitor_render.php`: dashboard/group rendering and view-specific output. +- `db_functions.php`: SQL filter/join helpers and status/device query utilities. +- `poller_monitor.php`: CLI poller entrypoint (`--help`, `--version`, `--debug`). +- `poller_functions.php`: poller helper logic (uptime checks, notifications, email payload building). -If these files do not exist, use repository patterns directly. +Avoid OO/framework refactors unless explicitly requested. -## Architecture and Boundaries (Observed) +## Coding Patterns to Preserve -This repository is a **single Cacti plugin** with procedural PHP entrypoints and Cacti hook integration. +### Naming and Structure -- **Plugin lifecycle and hooks**: `setup.php` - - Registration via `api_plugin_register_hook()` and `api_plugin_register_realm()`. - - Upgrade/install logic via `plugin_monitor_install()`, `plugin_monitor_upgrade()`, `monitor_check_upgrade()`. -- **Web UI controller/rendering**: `monitor.php` - - Request routing by `action` switch. - - Rendering and UI state via Cacti helper functions. -- **CLI/poller processing**: `poller_monitor.php` - - Argument parsing (`--help`, `--version`, `--force`, `--debug`). - - Notification and uptime/reboot processing. -- **Presentation assets**: `monitor.css`, `themes/*/monitor.css`, `sounds/`, `images/`. -- **Localization assets**: gettext `.po/.mo` files under `locales/`. +- Use procedural functions with **lowerCamelCase** naming, matching current core files. +- Keep plugin hook callback names exactly synchronized between definitions and `api_plugin_register_hook()` registration strings. +- Keep top-level entrypoints lightweight; place reusable logic in helper files. -Do not refactor this plugin into OO/framework patterns unless the existing code in this repository does so first. +### Cacti Integration -## Codebase Scanning Instructions +- Prefer Cacti APIs already used in this plugin: + - Config/state: `read_config_option()`, `set_config_option()`, `read_user_setting()`, `set_user_setting()` + - Request helpers: `get_request_var()`, `get_filter_request_var()`, `get_nfilter_request_var()`, `set_request_var()`, `validateRequestVars()` + - DB helpers: `db_fetch_assoc()`, `db_fetch_row_prepared()`, `db_fetch_cell_prepared()`, `db_execute_prepared()` + - Plugin hooks/realms: `api_plugin_register_hook()`, `api_plugin_register_realm()` +- Use gettext calls with the `monitor` domain for user-facing strings: `__('Text', 'monitor')`. -For any new change: +### Data and Schema Safety -1. Find similar logic in the same entrypoint type (`setup.php` for hooks/config, `monitor.php` for UI routing/rendering, `poller_monitor.php` for CLI/poller flows). -2. Match these patterns exactly: - - Function naming: `monitor_*`, `plugin_monitor_*` - - Procedural flow with top-level includes and switch routing - - Cacti helper/database APIs (`db_fetch_*`, `db_execute*`, `read_config_option`, `set_config_option`) - - Localization calls: `__('Text', 'monitor')` -3. Reuse existing request handling and sanitization helpers before adding any new input handling. -4. Prefer existing table names and schema migration style in `monitor_check_upgrade()` and related setup functions. -5. Avoid introducing new architectural abstractions not currently used. +- Keep schema evolution in existing setup/upgrade flows (table creation/alter logic in setup lifecycle functions). +- Reuse existing table names and avoid introducing parallel schema variants. +- Prefer prepared DB calls when dynamic values are present. -## Code Quality Standards (Evidence-Based) +## Quality Expectations ### Maintainability -- Keep procedural style and naming consistent with existing files. -- Keep related behavior grouped by responsibility (install/upgrade/hooks in `setup.php`; UI rendering in `monitor.php`; poller logic in `poller_monitor.php`). -- Prefer small helper functions as seen throughout the codebase. +- Keep changes localized to the appropriate responsibility file. +- Favor small helper extractions for complex branches (pattern used in `poller_functions.php`). +- Do not rename public/plugin callback functions unless all call sites and hook strings are updated. ### Security -- Follow current input-handling patterns: - - `get_request_var()`, `get_nfilter_request_var()`, `get_filter_request_var()`, `set_request_var()` - - `validate_request_vars()` where appropriate -- Escape output using existing helpers such as `html_escape()` for HTML contexts. -- Use prepared database calls where parameters are dynamic (`db_fetch_*_prepared`, `db_execute_prepared`) following existing usage. +- Continue current request-validation patterns before consuming request values. +- Escape HTML output with existing helpers (e.g., `html_escape()`). +- Avoid direct string interpolation for dynamic SQL parameters when prepared variants exist. ### Performance -- Match existing data-access style: targeted SQL queries and batched operations. -- Preserve existing poller timing/stat collection behavior in `poller_monitor.php`. -- Avoid adding expensive repeated queries inside loops when existing code already provides reusable query patterns. +- Avoid repeated expensive queries inside loops. +- Follow current query-shaping patterns (precompute lists/maps, then iterate). +- Preserve current poller stat logging behavior and timing model. -### Testability +### Documentation -- Keep logic in discrete functions so behavior can be linted, statically analyzed, and integration-tested as in CI. -- Preserve CLI flags and deterministic output patterns used by workflow checks. +- Keep function docblocks descriptive where present, especially in `poller_functions.php`. +- Keep inline comments concise and only where intent is non-obvious. +- Do not add boilerplate comments for trivial statements. -## Documentation Requirements +## Validation and CI Alignment -Documentation level in this repository is **Standard**: +Before finalizing substantial PHP changes: -- File-level header blocks are consistently present in PHP and workflow files. -- Inline comments are concise and purpose-driven. -- Follow existing style: do not over-document trivial lines. -- Update `CHANGELOG.md` style only when project maintainers require release note updates. +1. Run PHP syntax checks (`php -l`) on modified plugin files. +2. Ensure compatibility with Cacti-driven lint/style checks used in CI (`lint`, `phpcsfixer` scripts run from Cacti workspace). +3. Preserve integration behavior expected by CI: + - Plugin install/enable via Cacti CLI + - Poller execution path and monitor stats logging -## Testing Approach (Observed) +Do not add a new local unit-test framework unless requested. -This repository relies on **integration + static checks** via GitHub Actions: +## Scope Rules for Future Changes -- PHP syntax lint (`php -l` over plugin files) -- Composer-based lint/style checks from Cacti workspace (`lint`, `phpcsfixer` scripts) -- Runtime integration checks by installing Cacti + plugin and running poller -- No repository-local unit test suite is currently present - -When generating code: - -- Ensure code is syntactically valid PHP. -- Keep style and lint compatibility with current Cacti-driven CI steps. -- Do not invent a new test framework in this plugin unless requested. - -## PHP-Specific Guidelines - -- Maintain procedural PHP structure and Cacti plugin API usage. -- Keep includes, globals, and helper calls consistent with existing patterns. -- Match array formatting and control-flow style used in current files. -- Continue using gettext domain `'monitor'` for user-facing strings. -- Preserve compatibility with CI-validated PHP versions and Cacti/plugin constraints. - -## Versioning and Change Tracking - -- Follow existing changelog conventions in `CHANGELOG.md` (sectioned by release, `issue#` / `feature#` bullets). -- Treat plugin version metadata in `INFO` as the authoritative plugin version declaration. - -## General Best Practices for This Repository - -- Prioritize consistency with existing code over introducing newer external patterns. -- Reuse existing Cacti APIs and plugin hooks instead of custom abstractions. -- Keep CSS/theme changes aligned with current theme folder structure. -- Keep localization updates aligned with existing gettext files and domain usage. -- If uncertain, mirror nearby code patterns in the same file first. - -## Project-Specific Guidance - -- Scan relevant files before generating code; do not assume patterns from unrelated projects. -- Respect current architectural boundaries: - - Hook/config lifecycle in `setup.php` - - UI/rendering workflow in `monitor.php` - - Poller/notification workflow in `poller_monitor.php` -- When conflicts arise, prefer patterns that are currently active in top-level runtime paths and CI-validated flows. -- Always prioritize compatibility and consistency with this repository over external “best practice” rewrites. +- Prefer minimal, surgical updates over broad rewrites. +- Keep CSS/theme updates limited to existing theme file layout. +- Keep localization changes aligned to existing gettext workflow/files. +- If guidance conflicts, prefer behavior already validated in runtime entrypoints and CI workflow. From 34c91c4413ac1c69927d4f29fd20be6d4cee9db3 Mon Sep 17 00:00:00 2001 From: Sean Mancini Date: Sun, 1 Mar 2026 21:58:20 -0500 Subject: [PATCH 12/26] PSR12 formatting --- db_functions.php | 270 ++--- images/index.php | 1 + index.php | 1 + locales/LC_MESSAGES/index.php | 1 + locales/index.php | 1 + monitor.php | 189 ++-- monitor_controller.php | 1441 +++++++++++++------------- monitor_render.php | 1393 ++++++++++++------------- poller_functions.php | 162 ++- poller_monitor.php | 1 + setup.php | 1802 +++++++++++++++++---------------- sounds/index.php | 1 + 12 files changed, 2729 insertions(+), 2534 deletions(-) diff --git a/db_functions.php b/db_functions.php index 4cc0237..f1d8b34 100644 --- a/db_functions.php +++ b/db_functions.php @@ -1,4 +1,5 @@ 0))"; - } else { // triggered - return "(td.thold_enabled='on' + } else { // triggered + return "(td.thold_enabled='on' AND ((td.thold_alert != 0 AND td.thold_fail_count >= td.thold_fail_trigger) OR (td.bl_alert > 0 AND td.bl_fail_count >= td.bl_fail_trigger)))"; - } + } } -function checkTholds() { - $thold_hosts = []; +function checkTholds() +{ + $thold_hosts = []; - if (api_plugin_is_enabled('thold')) { - return array_rekey( - db_fetch_assoc('SELECT DISTINCT dl.host_id + if (api_plugin_is_enabled('thold')) { + return array_rekey( + db_fetch_assoc('SELECT DISTINCT dl.host_id FROM thold_data AS td INNER JOIN data_local AS dl ON td.local_data_id=dl.id WHERE ' . getTholdWhere()), - 'host_id', 'host_id' - ); - } + 'host_id', + 'host_id' + ); + } - return $thold_hosts; + return $thold_hosts; } -function renderGroupConcat(&$sql_where, $sql_join, $sql_field, $sql_data, $sql_suffix = '') { - // Remove empty entries if something was returned - if (!empty($sql_data)) { - $sql_data = trim(str_replace(',,',',',$sql_data), ','); +function renderGroupConcat(&$sql_where, $sql_join, $sql_field, $sql_data, $sql_suffix = '') +{ + // Remove empty entries if something was returned + if (!empty($sql_data)) { + $sql_data = trim(str_replace(',,', ',', $sql_data), ','); - if (!empty($sql_data)) { - $sql_where .= ($sql_where != '' ? $sql_join : '') . "($sql_field IN($sql_data) $sql_suffix)"; - } - } + if (!empty($sql_data)) { + $sql_where .= ($sql_where != '' ? $sql_join : '') . "($sql_field IN($sql_data) $sql_suffix)"; + } + } } -function renderWhereJoin(&$sql_where, &$sql_join) { - if (get_request_var('crit') > 0) { - $awhere = 'h.monitor_criticality >= ' . get_request_var('crit'); - } else { - $awhere = ''; - } - - if (get_request_var('grouping') == 'site') { - if (get_request_var('site') > 0) { - $awhere .= ($awhere == '' ? '' : ' AND ') . 'h.site_id = ' . get_request_var('site'); - } elseif (get_request_var('site') == -2) { - $awhere .= ($awhere == '' ? '' : ' AND ') . ' h.site_id = 0'; - } - } - - if (get_request_var('rfilter') != '') { - $awhere .= ($awhere == '' ? '' : ' AND ') . " h.description RLIKE '" . get_request_var('rfilter') . "'"; - } - - if (get_request_var('grouping') == 'tree') { - if (get_request_var('tree') > 0) { - $hlist = db_fetch_cell_prepared('SELECT GROUP_CONCAT(DISTINCT host_id) +function renderWhereJoin(&$sql_where, &$sql_join) +{ + if (get_request_var('crit') > 0) { + $awhere = 'h.monitor_criticality >= ' . get_request_var('crit'); + } else { + $awhere = ''; + } + + if (get_request_var('grouping') == 'site') { + if (get_request_var('site') > 0) { + $awhere .= ($awhere == '' ? '' : ' AND ') . 'h.site_id = ' . get_request_var('site'); + } elseif (get_request_var('site') == -2) { + $awhere .= ($awhere == '' ? '' : ' AND ') . ' h.site_id = 0'; + } + } + + if (get_request_var('rfilter') != '') { + $awhere .= ($awhere == '' ? '' : ' AND ') . " h.description RLIKE '" . get_request_var('rfilter') . "'"; + } + + if (get_request_var('grouping') == 'tree') { + if (get_request_var('tree') > 0) { + $hlist = db_fetch_cell_prepared( + 'SELECT GROUP_CONCAT(DISTINCT host_id) FROM graph_tree_items AS gti INNER JOIN host AS h ON h.id = gti.host_id WHERE host_id > 0 AND graph_tree_id = ? AND h.deleted = ""', - [get_request_var('tree')]); + [get_request_var('tree')] + ); - renderGroupConcat($awhere, ' AND ', 'h.id', $hlist); - } elseif (get_request_var('tree') == -2) { - $hlist = db_fetch_cell('SELECT GROUP_CONCAT(DISTINCT h.id) + renderGroupConcat($awhere, ' AND ', 'h.id', $hlist); + } elseif (get_request_var('tree') == -2) { + $hlist = db_fetch_cell('SELECT GROUP_CONCAT(DISTINCT h.id) FROM host AS h LEFT JOIN (SELECT DISTINCT host_id FROM graph_tree_items WHERE host_id > 0) AS gti ON h.id = gti.host_id WHERE gti.host_id IS NULL AND h.deleted = ""'); - renderGroupConcat($awhere, ' AND ', 'h.id', $hlist); - } - } + renderGroupConcat($awhere, ' AND ', 'h.id', $hlist); + } + } - if (!empty($awhere)) { - $awhere = ' AND ' . $awhere; - } + if (!empty($awhere)) { + $awhere = ' AND ' . $awhere; + } - if (get_request_var('status') == '0') { - $sql_join = ''; - $sql_where = 'WHERE h.disabled = "" + if (get_request_var('status') == '0') { + $sql_join = ''; + $sql_where = 'WHERE h.disabled = "" AND h.monitor = "on" AND h.status < 3 AND h.deleted = "" @@ -120,10 +128,10 @@ function renderWhereJoin(&$sql_where, &$sql_join) { OR (h.cur_time >= h.monitor_warn AND monitor_warn > 0) OR (h.cur_time >= h.monitor_alert AND h.monitor_alert > 0) )' . $awhere; - } elseif (get_request_var('status') == '1' || get_request_var('status') == 2) { - $sql_join = 'LEFT JOIN thold_data AS td ON td.host_id=h.id'; + } elseif (get_request_var('status') == '1' || get_request_var('status') == 2) { + $sql_join = 'LEFT JOIN thold_data AS td ON td.host_id=h.id'; - $sql_where = 'WHERE h.disabled = "" + $sql_where = 'WHERE h.disabled = "" AND h.monitor = "on" AND h.deleted = "" AND (h.status < 3 @@ -132,126 +140,131 @@ function renderWhereJoin(&$sql_where, &$sql_join) { AND ((h.cur_time > h.monitor_warn AND h.monitor_warn > 0) OR (h.cur_time > h.monitor_alert AND h.monitor_alert > 0)) ))' . $awhere; - } elseif (get_request_var('status') == -1) { - $sql_join = 'LEFT JOIN thold_data AS td ON td.host_id=h.id'; + } elseif (get_request_var('status') == -1) { + $sql_join = 'LEFT JOIN thold_data AS td ON td.host_id=h.id'; - $sql_where = 'WHERE h.disabled = "" + $sql_where = 'WHERE h.disabled = "" AND h.monitor = "on" AND h.deleted = "" AND (h.availability_method > 0 OR h.snmp_version > 0 OR ((td.thold_enabled="on" AND td.thold_alert > 0) OR td.id IS NULL) )' . $awhere; - } elseif (get_request_var('status') == -2) { - $sql_join = 'LEFT JOIN thold_data AS td ON td.host_id=h.id'; + } elseif (get_request_var('status') == -2) { + $sql_join = 'LEFT JOIN thold_data AS td ON td.host_id=h.id'; - $sql_where = 'WHERE h.disabled = "" + $sql_where = 'WHERE h.disabled = "" AND h.deleted = ""' . $awhere; - } elseif (get_request_var('status') == -3) { - $sql_join = 'LEFT JOIN thold_data AS td ON td.host_id=h.id'; + } elseif (get_request_var('status') == -3) { + $sql_join = 'LEFT JOIN thold_data AS td ON td.host_id=h.id'; - $sql_where = 'WHERE h.disabled = "" + $sql_where = 'WHERE h.disabled = "" AND h.monitor = "" AND h.deleted = "")' . $awhere; - } else { - $sql_join = 'LEFT JOIN thold_data AS td ON td.host_id=h.id'; + } else { + $sql_join = 'LEFT JOIN thold_data AS td ON td.host_id=h.id'; - $sql_where = 'WHERE (h.disabled = "" + $sql_where = 'WHERE (h.disabled = "" AND h.deleted = "" AND td.id IS NULL)' . $awhere; - } + } } // Render functions -function getHostsDownOrTriggeredByPermission($prescan) { - global $render_style; - $PreScanValue = 2; +function getHostsDownOrTriggeredByPermission($prescan) +{ + global $render_style; + $PreScanValue = 2; - if ($prescan) { - $PreScanValue = 3; - } + if ($prescan) { + $PreScanValue = 3; + } - $result = []; + $result = []; - if (get_request_var('crit') > 0) { - $sql_add_where = 'monitor_criticality >= ' . get_request_var('crit'); - } else { - $sql_add_where = ''; - } + if (get_request_var('crit') > 0) { + $sql_add_where = 'monitor_criticality >= ' . get_request_var('crit'); + } else { + $sql_add_where = ''; + } - if (get_request_var('grouping') == 'tree') { - if (get_request_var('tree') > 0) { - $devices = db_fetch_cell_prepared('SELECT GROUP_CONCAT(DISTINCT host_id) AS hosts + if (get_request_var('grouping') == 'tree') { + if (get_request_var('tree') > 0) { + $devices = db_fetch_cell_prepared( + 'SELECT GROUP_CONCAT(DISTINCT host_id) AS hosts FROM graph_tree_items AS gti INNER JOIN host AS h WHERE host_id > 0 AND h.deleted = "" AND graph_tree_id = ?', - [get_request_var('tree')]); + [get_request_var('tree')] + ); - renderGroupConcat($sql_add_where, ' OR ', 'h.id', $devices,'AND h.status < 2'); - } - } + renderGroupConcat($sql_add_where, ' OR ', 'h.id', $devices, 'AND h.status < 2'); + } + } - if (get_request_var('status') > 0) { - $triggered = db_fetch_cell('SELECT GROUP_CONCAT(DISTINCT host_id) AS hosts + if (get_request_var('status') > 0) { + $triggered = db_fetch_cell('SELECT GROUP_CONCAT(DISTINCT host_id) AS hosts FROM host AS h INNER JOIN thold_data AS td ON td.host_id = h.id WHERE ' . getTholdWhere() . ' AND h.deleted = ""'); - renderGroupConcat($sql_add_where, ' OR ', 'h.id', $triggered, 'AND h.status > 1'); + renderGroupConcat($sql_add_where, ' OR ', 'h.id', $triggered, 'AND h.status > 1'); - $_SESSION['monitor_triggered'] = array_rekey( - db_fetch_assoc('SELECT td.host_id, COUNT(DISTINCT td.id) AS triggered + $_SESSION['monitor_triggered'] = array_rekey( + db_fetch_assoc('SELECT td.host_id, COUNT(DISTINCT td.id) AS triggered FROM thold_data AS td INNER JOIN host AS h ON td.host_id = h.id WHERE ' . getTholdWhere() . ' AND h.deleted = "" GROUP BY td.host_id'), - 'host_id', 'triggered' - ); - } + 'host_id', + 'triggered' + ); + } - $sql_where = "h.monitor = 'on' + $sql_where = "h.monitor = 'on' AND h.disabled = '' AND h.deleted = '' AND ((h.status < " . $PreScanValue . ' AND (h.availability_method > 0 OR h.snmp_version > 0)) ' . - ($sql_add_where != '' ? ' OR (' . $sql_add_where . '))' : ')'); + ($sql_add_where != '' ? ' OR (' . $sql_add_where . '))' : ')'); - // do a quick loop through to pull the hosts that are down - $hosts = get_allowed_devices($sql_where); + // do a quick loop through to pull the hosts that are down + $hosts = get_allowed_devices($sql_where); - if (cacti_sizeof($hosts)) { - foreach ($hosts as $host) { - $result[] = $host['id']; - sort($result); - } - } + if (cacti_sizeof($hosts)) { + foreach ($hosts as $host) { + $result[] = $host['id']; + sort($result); + } + } - return $result; + return $result; } /* // This function is not used and contains an undefined variable function getHostTreeArray() { - return $leafs; + return $leafs; } */ -function getHostNonTreeArray() { - $leafs = []; +function getHostNonTreeArray() +{ + $leafs = []; - $sql_where = ''; - $sql_join = ''; + $sql_where = ''; + $sql_join = ''; - renderWhereJoin($sql_where, $sql_join); + renderWhereJoin($sql_where, $sql_join); - $hierarchy = db_fetch_assoc("SELECT DISTINCT + $hierarchy = db_fetch_assoc("SELECT DISTINCT h.*, gti.title, gti.host_id, gti.host_grouping_type, gti.graph_tree_id FROM host AS h LEFT JOIN graph_tree_items AS gti @@ -261,16 +274,15 @@ function getHostNonTreeArray() { AND gti.graph_tree_id IS NULL ORDER BY h.description"); - if (cacti_sizeof($hierarchy) > 0) { - $leafs = []; - $branchleafs = 0; + if (cacti_sizeof($hierarchy) > 0) { + $leafs = []; + $branchleafs = 0; - foreach ($hierarchy as $leaf) { - $leafs[$branchleafs] = $leaf; - $branchleafs++; - } - } + foreach ($hierarchy as $leaf) { + $leafs[$branchleafs] = $leaf; + $branchleafs++; + } + } - return $leafs; + return $leafs; } - diff --git a/images/index.php b/images/index.php index d0f1fcd..ea6f1df 100644 --- a/images/index.php +++ b/images/index.php @@ -1,4 +1,5 @@ __('Disabled', 'monitor'), - 1 => __('Low', 'monitor'), - 2 => __('Medium', 'monitor'), - 3 => __('High', 'monitor'), - 4 => __('Mission Critical', 'monitor') + 0 => __('Disabled', 'monitor'), + 1 => __('Low', 'monitor'), + 2 => __('Medium', 'monitor'), + 3 => __('High', 'monitor'), + 4 => __('Mission Critical', 'monitor') ]; $iclasses = [ - 0 => 'deviceUnknown', - 1 => 'deviceDown', - 2 => 'deviceRecovering', - 3 => 'deviceUp', - 4 => 'deviceThreshold', - 5 => 'deviceDownMuted', - 6 => 'deviceUnmonitored', - 7 => 'deviceWarning', - 8 => 'deviceAlert', - 9 => 'deviceThresholdMuted', + 0 => 'deviceUnknown', + 1 => 'deviceDown', + 2 => 'deviceRecovering', + 3 => 'deviceUp', + 4 => 'deviceThreshold', + 5 => 'deviceDownMuted', + 6 => 'deviceUnmonitored', + 7 => 'deviceWarning', + 8 => 'deviceAlert', + 9 => 'deviceThresholdMuted', ]; $icolorsdisplay = [ - 0 => __('Unknown', 'monitor'), - 1 => __('Down', 'monitor'), - 2 => __('Recovering', 'monitor'), - 3 => __('Up', 'monitor'), - 4 => __('Triggered', 'monitor'), - 9 => __('Triggered (Muted/Acked)', 'monitor'), - 5 => __('Down (Muted/Acked)', 'monitor'), - 6 => __('No Availability Check', 'monitor'), - 7 => __('Warning Ping', 'monitor'), - 8 => __('Alert Ping', 'monitor'), + 0 => __('Unknown', 'monitor'), + 1 => __('Down', 'monitor'), + 2 => __('Recovering', 'monitor'), + 3 => __('Up', 'monitor'), + 4 => __('Triggered', 'monitor'), + 9 => __('Triggered (Muted/Acked)', 'monitor'), + 5 => __('Down (Muted/Acked)', 'monitor'), + 6 => __('No Availability Check', 'monitor'), + 7 => __('Warning Ping', 'monitor'), + 8 => __('Alert Ping', 'monitor'), ]; $classes = [ - 'monitor_exsmall' => __('Extra Small', 'monitor'), - 'monitor_small' => __('Small', 'monitor'), - 'monitor_medium' => __('Medium', 'monitor'), - 'monitor_large' => __('Large', 'monitor'), - 'monitor_exlarge' => __('Extra Large', 'monitor'), - 'monitor_errorzoom' => __('Zoom', 'monitor') + 'monitor_exsmall' => __('Extra Small', 'monitor'), + 'monitor_small' => __('Small', 'monitor'), + 'monitor_medium' => __('Medium', 'monitor'), + 'monitor_large' => __('Large', 'monitor'), + 'monitor_exlarge' => __('Extra Large', 'monitor'), + 'monitor_errorzoom' => __('Zoom', 'monitor') ]; $monitor_status = [ - -2 => __('All Devices', 'monitor'), - -1 => __('All Monitored Devices', 'monitor'), - 0 => __('Not Up', 'monitor'), - 1 => __('Not Up or Triggered', 'monitor'), - 2 => __('Not Up, Triggered or Breached', 'monitor'), - -4 => __('Devices without Thresholds', 'monitor'), - -3 => __('Devices not Monitored', 'monitor'), + -2 => __('All Devices', 'monitor'), + -1 => __('All Monitored Devices', 'monitor'), + 0 => __('Not Up', 'monitor'), + 1 => __('Not Up or Triggered', 'monitor'), + 2 => __('Not Up, Triggered or Breached', 'monitor'), + -4 => __('Devices without Thresholds', 'monitor'), + -3 => __('Devices not Monitored', 'monitor'), ]; $monitor_view_type = [ - 'default' => __('Default', 'monitor'), - 'list' => __('List', 'monitor'), - 'names' => __('Names only', 'monitor'), - 'tiles' => __('Tiles', 'monitor'), - 'tilesadt' => __('Tiles & Time', 'monitor') + 'default' => __('Default', 'monitor'), + 'list' => __('List', 'monitor'), + 'names' => __('Names only', 'monitor'), + 'tiles' => __('Tiles', 'monitor'), + 'tilesadt' => __('Tiles & Time', 'monitor') ]; $monitor_grouping = [ - 'default' => __('Default', 'monitor'), - 'tree' => __('Tree', 'monitor'), - 'site' => __('Site', 'monitor'), - 'template' => __('Device Template', 'monitor') + 'default' => __('Default', 'monitor'), + 'tree' => __('Tree', 'monitor'), + 'site' => __('Site', 'monitor'), + 'template' => __('Device Template', 'monitor') ]; $monitor_trim = [ - 0 => __('Default', 'monitor'), - -1 => __('Full', 'monitor'), - 10 => __('10 Chars', 'monitor'), - 20 => __('20 Chars', 'monitor'), - 30 => __('30 Chars', 'monitor'), - 40 => __('40 Chars', 'monitor'), - 50 => __('50 Chars', 'monitor'), - 75 => __('75 Chars', 'monitor'), - 100 => __('100 Chars', 'monitor'), + 0 => __('Default', 'monitor'), + -1 => __('Full', 'monitor'), + 10 => __('10 Chars', 'monitor'), + 20 => __('20 Chars', 'monitor'), + 30 => __('30 Chars', 'monitor'), + 40 => __('40 Chars', 'monitor'), + 50 => __('50 Chars', 'monitor'), + 75 => __('75 Chars', 'monitor'), + 100 => __('100 Chars', 'monitor'), ]; global $thold_hosts, $maxchars; @@ -122,7 +123,7 @@ $_SESSION['names'] = 0; if (!isset($_SESSION['monitor_muted_hosts'])) { - $_SESSION['monitor_muted_hosts'] = []; + $_SESSION['monitor_muted_hosts'] = []; } @@ -133,47 +134,47 @@ validateRequestVars(); if (!db_column_exists('host', 'monitor_icon')) { - monitorSetupTable(); + monitorSetupTable(); } $thold_hosts = checkTholds(); -switch(get_nfilter_request_var('action')) { - case 'ajax_status': - ajaxStatus(); - - break; - case 'ajax_mute_all': - muteAllHosts(); - drawPage(); - - break; - case 'ajax_unmute_all': - unmuteAllHosts(); - drawPage(); - - break; - case 'dbchange': - loadDashboardSettings(); - drawPage(); - - break; - case 'remove': - removeDashboard(); - drawPage(); - - break; - case 'saveDb': - saveSettings(); - drawPage(); - - break; - case 'save': - saveSettings(); - - break; - default: - drawPage(); +switch (get_nfilter_request_var('action')) { + case 'ajax_status': + ajaxStatus(); + + break; + case 'ajax_mute_all': + muteAllHosts(); + drawPage(); + + break; + case 'ajax_unmute_all': + unmuteAllHosts(); + drawPage(); + + break; + case 'dbchange': + loadDashboardSettings(); + drawPage(); + + break; + case 'remove': + removeDashboard(); + drawPage(); + + break; + case 'saveDb': + saveSettings(); + drawPage(); + + break; + case 'save': + saveSettings(); + + break; + default: + drawPage(); } exit; diff --git a/monitor_controller.php b/monitor_controller.php index ec9a60b..86cac36 100644 --- a/monitor_controller.php +++ b/monitor_controller.php @@ -1,4 +1,5 @@ 0) { - $db_settings = db_fetch_cell_prepared('SELECT url + if ($dashboard > 0) { + $db_settings = db_fetch_cell_prepared( + 'SELECT url FROM plugin_monitor_dashboards WHERE id = ?', - [$dashboard]); - - if ($db_settings != '') { - $db_settings = str_replace('monitor.php?', '', $db_settings); - $settings = explode('&', $db_settings); - - if (cacti_sizeof($settings)) { - foreach ($settings as $setting) { - [$name, $value] = explode('=', $setting); - - set_request_var($name, $value); - } - } - } - } + [$dashboard] + ); + + if ($db_settings != '') { + $db_settings = str_replace('monitor.php?', '', $db_settings); + $settings = explode('&', $db_settings); + + if (cacti_sizeof($settings)) { + foreach ($settings as $setting) { + [$name, $value] = explode('=', $setting); + + set_request_var($name, $value); + } + } + } + } } -function drawPage() { - global $config, $iclasses, $icolorsdisplay, $mon_zoom_state, $dozoomrefresh, $dozoombgndcolor, $font_sizes; - global $new_form, $new_title; - - $errored_list = getHostsDownOrTriggeredByPermission(true); - - if (cacti_sizeof($errored_list) && read_user_setting('monitor_error_zoom') == 'on') { - if ($_SESSION['monitor_zoom_state'] == 0) { - $mon_zoom_state = $_SESSION['monitor_zoom_state'] = 1; - $_SESSION['mon_zoom_hist_status'] = get_nfilter_request_var('status'); - $_SESSION['mon_zoom_hist_size'] = get_nfilter_request_var('size'); - $dozoomrefresh = true; - $dozoombgndcolor = true; - } - } elseif (isset($_SESSION['monitor_zoom_state']) && $_SESSION['monitor_zoom_state'] == 1) { - $_SESSION['monitor_zoom_state'] = 0; - $dozoomrefresh = true; - $dozoombgndcolor = false; - } - - $name = db_fetch_cell_prepared('SELECT name +function drawPage() +{ + global $config, $iclasses, $icolorsdisplay, $mon_zoom_state, $dozoomrefresh, $dozoombgndcolor, $font_sizes; + global $new_form, $new_title; + + $errored_list = getHostsDownOrTriggeredByPermission(true); + + if (cacti_sizeof($errored_list) && read_user_setting('monitor_error_zoom') == 'on') { + if ($_SESSION['monitor_zoom_state'] == 0) { + $mon_zoom_state = $_SESSION['monitor_zoom_state'] = 1; + $_SESSION['mon_zoom_hist_status'] = get_nfilter_request_var('status'); + $_SESSION['mon_zoom_hist_size'] = get_nfilter_request_var('size'); + $dozoomrefresh = true; + $dozoombgndcolor = true; + } + } elseif (isset($_SESSION['monitor_zoom_state']) && $_SESSION['monitor_zoom_state'] == 1) { + $_SESSION['monitor_zoom_state'] = 0; + $dozoomrefresh = true; + $dozoombgndcolor = false; + } + + $name = db_fetch_cell_prepared( + 'SELECT name FROM plugin_monitor_dashboards WHERE id = ?', - [get_request_var('dashboard')]); + [get_request_var('dashboard')] + ); - if ($name == '') { - $name = __('New Dashboard', 'monitor'); - } + if ($name == '') { + $name = __('New Dashboard', 'monitor'); + } - $new_form = "
" . __('Enter the Dashboard Name and then press \'Save\' to continue, else press \'Cancel\'', 'monitor') . '
' . __('Dashboard', 'monitor') . "
"; + $new_form = "
" . __('Enter the Dashboard Name and then press \'Save\' to continue, else press \'Cancel\'', 'monitor') . '
' . __('Dashboard', 'monitor') . "
"; - $new_title = __('Create New Dashboard', 'monitor'); + $new_title = __('Create New Dashboard', 'monitor'); - findDownHosts(); + findDownHosts(); - general_header(); + general_header(); - drawFilterAndStatus(); + drawFilterAndStatus(); - print ''; + print ''; - // Default with permissions = default_by_permission - // Tree = group_by_tree - $function = 'render' . ucfirst(get_request_var('grouping')); + // Default with permissions = default_by_permission + // Tree = group_by_tree + $function = 'render' . ucfirst(get_request_var('grouping')); - if (function_exists($function) && get_request_var('view') != 'list') { - if (get_request_var('grouping') == 'default' || get_request_var('grouping') == 'site') { - html_start_box(__('Monitored Devices', 'monitor'), '100%', true, '3', 'center', ''); - } else { - html_start_box('', '100%', true, '3', 'center', ''); - } - print $function(); - } else { - print renderDefault(); - } + if (function_exists($function) && get_request_var('view') != 'list') { + if (get_request_var('grouping') == 'default' || get_request_var('grouping') == 'site') { + html_start_box(__('Monitored Devices', 'monitor'), '100%', true, '3', 'center', ''); + } else { + html_start_box('', '100%', true, '3', 'center', ''); + } + print $function(); + } else { + print renderDefault(); + } - print ''; + print ''; - html_end_box(); + html_end_box(); - if (read_user_setting('monitor_legend', read_config_option('monitor_legend'))) { - print "
"; + if (read_user_setting('monitor_legend', read_config_option('monitor_legend'))) { + print "
"; - foreach ($iclasses as $index => $class) { - print "
" . $icolorsdisplay[$index] . '
'; - } + foreach ($iclasses as $index => $class) { + print "
" . $icolorsdisplay[$index] . '
'; + } - print '
'; - } + print '
'; + } - // If the host is down, we need to insert the embedded wav file - $monitor_sound = getMonitorSound(); + // If the host is down, we need to insert the embedded wav file + $monitor_sound = getMonitorSound(); - if (isMonitorAudible()) { - if (read_user_setting('monitor_sound_loop', read_config_option('monitor_sound_loop'))) { - print ""; - } else { - print ""; - } - } + if (isMonitorAudible()) { + if (read_user_setting('monitor_sound_loop', read_config_option('monitor_sound_loop'))) { + print ""; + } else { + print ""; + } + } - print '
' . getFilterText() . '
'; + print '
' . getFilterText() . '
'; - bottom_footer(); + bottom_footer(); } -function isMonitorAudible() { - return getMonitorSound() != ''; +function isMonitorAudible() +{ + return getMonitorSound() != ''; } -function getMonitorSound() { - $sound = read_user_setting('monitor_sound', read_config_option('monitor_sound')); - clearstatcache(); - $file = __DIR__ . '/sounds/' . $sound; - $exists = file_exists($file); +function getMonitorSound() +{ + $sound = read_user_setting('monitor_sound', read_config_option('monitor_sound')); + clearstatcache(); + $file = __DIR__ . '/sounds/' . $sound; + $exists = file_exists($file); - return $exists ? $sound : ''; + return $exists ? $sound : ''; } -function findDownHosts() { - $dhosts = getHostsDownOrTriggeredByPermission(false); +function findDownHosts() +{ + $dhosts = getHostsDownOrTriggeredByPermission(false); - if (cacti_sizeof($dhosts)) { - set_request_var('downhosts', 'true'); + if (cacti_sizeof($dhosts)) { + set_request_var('downhosts', 'true'); - if (isset($_SESSION['monitor_muted_hosts'])) { - unmute_up_non_triggered_hosts($dhosts); + if (isset($_SESSION['monitor_muted_hosts'])) { + unmute_up_non_triggered_hosts($dhosts); - $unmuted_hosts = array_diff($dhosts, $_SESSION['monitor_muted_hosts']); + $unmuted_hosts = array_diff($dhosts, $_SESSION['monitor_muted_hosts']); - if (cacti_sizeof($unmuted_hosts)) { - unmute_user(); - } - } else { - set_request_var('mute', 'false'); - } - } else { - unmuteAllHosts(); - set_request_var('downhosts', 'false'); - } + if (cacti_sizeof($unmuted_hosts)) { + unmute_user(); + } + } else { + set_request_var('mute', 'false'); + } + } else { + unmuteAllHosts(); + set_request_var('downhosts', 'false'); + } } -function unmuteUpNonTriggeredHosts($dhosts) { - if (isset($_SESSION['monitor_muted_hosts'])) { - foreach ($_SESSION['monitor_muted_hosts'] as $index => $host_id) { - if (array_search($host_id, $dhosts, true) === false) { - unset($_SESSION['monitor_muted_hosts'][$index]); - } - } - } +function unmuteUpNonTriggeredHosts($dhosts) +{ + if (isset($_SESSION['monitor_muted_hosts'])) { + foreach ($_SESSION['monitor_muted_hosts'] as $index => $host_id) { + if (array_search($host_id, $dhosts, true) === false) { + unset($_SESSION['monitor_muted_hosts'][$index]); + } + } + } } -function muteAllHosts() { - $_SESSION['monitor_muted_hosts'] = getHostsDownOrTriggeredByPermission(false); - muteUser(); +function muteAllHosts() +{ + $_SESSION['monitor_muted_hosts'] = getHostsDownOrTriggeredByPermission(false); + muteUser(); } -function unmuteAllHosts() { - $_SESSION['monitor_muted_hosts'] = []; - unmuteUser(); +function unmuteAllHosts() +{ + $_SESSION['monitor_muted_hosts'] = []; + unmuteUser(); } -function muteUser() { - set_request_var('mute', 'true'); - set_user_setting('monitor_mute', 'true'); +function muteUser() +{ + set_request_var('mute', 'true'); + set_user_setting('monitor_mute', 'true'); } -function unmuteUser() { - set_request_var('mute', 'false'); - set_user_setting('monitor_mute','false'); +function unmuteUser() +{ + set_request_var('mute', 'false'); + set_user_setting('monitor_mute', 'false'); } -function getFilterText() { - $filter = '
'; +function getFilterText() +{ + $filter = '
'; - switch(get_request_var('status')) { - case '-4': - $filter .= __('Devices without Thresholds', 'monitor'); + switch (get_request_var('status')) { + case '-4': + $filter .= __('Devices without Thresholds', 'monitor'); - break; - case '-3': - $filter .= __('Not Monitored Devices', 'monitor'); + break; + case '-3': + $filter .= __('Not Monitored Devices', 'monitor'); - break; - case '-2': - $filter .= __('All Devices', 'monitor'); + break; + case '-2': + $filter .= __('All Devices', 'monitor'); - break; - case '-1': - $filter .= __('All Monitored Devices', 'monitor'); + break; + case '-1': + $filter .= __('All Monitored Devices', 'monitor'); - break; - case '0': - $filter .= __('Monitored Devices either Down or Recovering', 'monitor'); + break; + case '0': + $filter .= __('Monitored Devices either Down or Recovering', 'monitor'); - break; - case '1': - $filter .= __('Monitored Devices either Down, Recovering, or with Triggered Thresholds', 'monitor'); + break; + case '1': + $filter .= __('Monitored Devices either Down, Recovering, or with Triggered Thresholds', 'monitor'); - break; - case '2': - $filter .= __('Monitored Devices either Down, Recovering, or with Breached or Triggered Thresholds', 'monitor'); + break; + case '2': + $filter .= __('Monitored Devices either Down, Recovering, or with Breached or Triggered Thresholds', 'monitor'); - break; - default: - $filter .= __('Unknown monitoring status (%s)', get_request_var('status'), 'monitor'); - } + break; + default: + $filter .= __('Unknown monitoring status (%s)', get_request_var('status'), 'monitor'); + } - switch(get_request_var('crit')) { - case '0': - $filter .= __(', and All Criticalities', 'monitor'); + switch (get_request_var('crit')) { + case '0': + $filter .= __(', and All Criticalities', 'monitor'); - break; - case '1': - $filter .= __(', and of Low Criticality or Higher', 'monitor'); + break; + case '1': + $filter .= __(', and of Low Criticality or Higher', 'monitor'); - break; - case '2': - $filter .= __(', and of Medium Criticality or Higher', 'monitor'); + break; + case '2': + $filter .= __(', and of Medium Criticality or Higher', 'monitor'); - break; - case '3': - $filter .= __(', and of High Criticality or Higher', 'monitor'); + break; + case '3': + $filter .= __(', and of High Criticality or Higher', 'monitor'); - break; - case '4': - $filter .= __(', and of Mission Critical Status', 'monitor'); + break; + case '4': + $filter .= __(', and of Mission Critical Status', 'monitor'); - break; - } + break; + } - $filter .= __('
Remember to first select eligible Devices to be Monitored from the Devices page!
', 'monitor'); + $filter .= __('
Remember to first select eligible Devices to be Monitored from the Devices page!
', 'monitor'); - return $filter; + return $filter; } -function drawFilterDropdown($id, $title, $settings = [], $value = null) { - if ($value == null) { - $value = get_nfilter_request_var($id); - } +function drawFilterDropdown($id, $title, $settings = [], $value = null) +{ + if ($value == null) { + $value = get_nfilter_request_var($id); + } - if (cacti_sizeof($settings)) { - print '' . html_escape($title) . ''; - print '' . PHP_EOL; - foreach ($settings as $setting_value => $setting_name) { - if ($value == null || $value == '') { - $value = $setting_value; - } + foreach ($settings as $setting_value => $setting_name) { + if ($value == null || $value == '') { + $value = $setting_value; + } - $setting_selected = ($value == $setting_value) ? ' selected' : ''; + $setting_selected = ($value == $setting_value) ? ' selected' : ''; - print '' . PHP_EOL; - } + print '' . PHP_EOL; + } - print '' . PHP_EOL; - } else { - print "" . PHP_EOL; - } + print '' . PHP_EOL; + } else { + print "" . PHP_EOL; + } } -function drawFilterAndStatus() { - global $config, $criticalities, $page_refresh_interval, $classes, $monitor_grouping; - global $monitor_view_type, $monitor_status, $monitor_trim; - global $dozoombgndcolor, $dozoomrefresh, $zoom_hist_status, $zoom_hist_size, $mon_zoom_state; - global $new_form, $new_title, $item_rows; +function drawFilterAndStatus() +{ + global $config, $criticalities, $page_refresh_interval, $classes, $monitor_grouping; + global $monitor_view_type, $monitor_status, $monitor_trim; + global $dozoombgndcolor, $dozoomrefresh, $zoom_hist_status, $zoom_hist_size, $mon_zoom_state; + global $new_form, $new_title, $item_rows; - $header = __('Monitor Filter [ Last Refresh: %s ]', date('g:i:s a', time()), 'monitor') . (get_request_var('refresh') < 99999 ? __(' [ Refresh Again in %d Seconds ]', get_request_var('refresh'), 'monitor') : '') . (get_request_var('view') == 'list' ? __('[ Showing only first 30 Devices ]', 'monitor') : '') . ''; + $header = __('Monitor Filter [ Last Refresh: %s ]', date('g:i:s a', time()), 'monitor') . (get_request_var('refresh') < 99999 ? __(' [ Refresh Again in %d Seconds ]', get_request_var('refresh'), 'monitor') : '') . (get_request_var('view') == 'list' ? __('[ Showing only first 30 Devices ]', 'monitor') : '') . ''; - html_start_box($header, '100%', false, '3', 'center', ''); + html_start_box($header, '100%', false, '3', 'center', ''); - print '' . PHP_EOL; - print '
' . PHP_EOL; + print '' . PHP_EOL; + print '' . PHP_EOL; - // First line of filter - print '' . PHP_EOL; - print '' . PHP_EOL; + // First line of filter + print '
' . PHP_EOL; + print '' . PHP_EOL; - $dashboards[0] = __('Unsaved', 'monitor'); - $dashboards += array_rekey( - db_fetch_assoc_prepared('SELECT id, name + $dashboards[0] = __('Unsaved', 'monitor'); + $dashboards += array_rekey( + db_fetch_assoc_prepared( + 'SELECT id, name FROM plugin_monitor_dashboards WHERE user_id = 0 OR user_id = ? ORDER BY name', - [$_SESSION['sess_user_id']]), - 'id', 'name' - ); - - $name = db_fetch_cell_prepared('SELECT name + [$_SESSION['sess_user_id']] + ), + 'id', + 'name' + ); + + $name = db_fetch_cell_prepared( + 'SELECT name FROM plugin_monitor_dashboards WHERE id = ?', - [get_request_var('dashboard')]); + [get_request_var('dashboard')] + ); - $mon_zoom_status = null; - $mon_zoom_size = null; + $mon_zoom_status = null; + $mon_zoom_size = null; - if (isset($_SESSION['monitor_zoom_state'])) { - if ($_SESSION['monitor_zoom_state'] == 1) { - $mon_zoom_status = 2; - $mon_zoom_size = 'monitor_errorzoom'; - $dozoombgndcolor = true; - } else { - if (isset($_SESSION['mon_zoom_hist_status'])) { - $mon_zoom_status = $_SESSION['mon_zoom_hist_status']; - } else { - $mon_zoom_status = null; - } + if (isset($_SESSION['monitor_zoom_state'])) { + if ($_SESSION['monitor_zoom_state'] == 1) { + $mon_zoom_status = 2; + $mon_zoom_size = 'monitor_errorzoom'; + $dozoombgndcolor = true; + } else { + if (isset($_SESSION['mon_zoom_hist_status'])) { + $mon_zoom_status = $_SESSION['mon_zoom_hist_status']; + } else { + $mon_zoom_status = null; + } - if (isset($_SESSION['mon_zoom_hist_size'])) { - $currentddsize = get_nfilter_request_var('size'); + if (isset($_SESSION['mon_zoom_hist_size'])) { + $currentddsize = get_nfilter_request_var('size'); - if ($currentddsize != $_SESSION['mon_zoom_hist_size'] && $currentddsize != 'monitor_errorzoom') { - $_SESSION['mon_zoom_hist_size'] = $currentddsize; - } + if ($currentddsize != $_SESSION['mon_zoom_hist_size'] && $currentddsize != 'monitor_errorzoom') { + $_SESSION['mon_zoom_hist_size'] = $currentddsize; + } - $mon_zoom_size = $_SESSION['mon_zoom_hist_size']; - } else { - $mon_zoom_size = null; - } - } - } + $mon_zoom_size = $_SESSION['mon_zoom_hist_size']; + } else { + $mon_zoom_size = null; + } + } + } - drawFilterDropdown('dashboard', __('Layout', 'monitor'), $dashboards); - drawFilterDropdown('status', __('Status', 'monitor'), $monitor_status, $mon_zoom_status); - drawFilterDropdown('view', __('View', 'monitor'), $monitor_view_type); - drawFilterDropdown('grouping', __('Grouping', 'monitor'), $monitor_grouping); - drawFilterDropdown('rows', __('Devices', 'monitor'), $item_rows); + drawFilterDropdown('dashboard', __('Layout', 'monitor'), $dashboards); + drawFilterDropdown('status', __('Status', 'monitor'), $monitor_status, $mon_zoom_status); + drawFilterDropdown('view', __('View', 'monitor'), $monitor_view_type); + drawFilterDropdown('grouping', __('Grouping', 'monitor'), $monitor_grouping); + drawFilterDropdown('rows', __('Devices', 'monitor'), $item_rows); - // Buttons - print ''; - print ''; - print '
' . PHP_EOL; + // Buttons + print '' . PHP_EOL; - print '' . PHP_EOL; + print '' . PHP_EOL; - print '' . PHP_EOL; + print '' . PHP_EOL; - print '' . PHP_EOL; + print '' . PHP_EOL; - print '' . PHP_EOL; + print '' . PHP_EOL; - if (get_request_var('dashboard') > 0) { - print '' . PHP_EOL; - } + if (get_request_var('dashboard') > 0) { + print '' . PHP_EOL; + } - if (get_request_var('dashboard') > 0) { - print '' . PHP_EOL; - } + if (get_request_var('dashboard') > 0) { + print '' . PHP_EOL; + } - print '' . PHP_EOL; - print '' . PHP_EOL; - print '
'; + print '' . PHP_EOL; + print '' . PHP_EOL; + print ''; + print ''; + print ''; - // Second line of filter - print '' . PHP_EOL; - print '' . PHP_EOL; - print ''; - print ''; + // Second line of filter + print '
' . __('Search', 'monitor') . '
' . PHP_EOL; + print '' . PHP_EOL; + print ''; + print ''; - drawFilterDropdown('crit', __('Criticality', 'monitor'), $criticalities); + drawFilterDropdown('crit', __('Criticality', 'monitor'), $criticalities); - if (get_request_var('view') != 'list') { - drawFilterDropdown('size', __('Size', 'monitor'), $classes, $mon_zoom_size); - } + if (get_request_var('view') != 'list') { + drawFilterDropdown('size', __('Size', 'monitor'), $classes, $mon_zoom_size); + } - if (get_request_var('view') == 'default' || get_request_var('view') == 'names') { - drawFilterDropdown('trim', __('Trim', 'monitor'), $monitor_trim); - } + if (get_request_var('view') == 'default' || get_request_var('view') == 'names') { + drawFilterDropdown('trim', __('Trim', 'monitor'), $monitor_trim); + } - if (get_nfilter_request_var('grouping') == 'tree') { - $trees = []; + if (get_nfilter_request_var('grouping') == 'tree') { + $trees = []; - if (get_request_var('grouping') == 'tree') { - $trees_allowed = array_rekey(get_allowed_trees(), 'id', 'name'); + if (get_request_var('grouping') == 'tree') { + $trees_allowed = array_rekey(get_allowed_trees(), 'id', 'name'); - if (cacti_sizeof($trees_allowed)) { - $trees_prefix = [-1 => __('All Trees', 'monitor')]; - $trees_suffix = [-2 => __('Non-Tree Devices', 'monitor')]; + if (cacti_sizeof($trees_allowed)) { + $trees_prefix = [-1 => __('All Trees', 'monitor')]; + $trees_suffix = [-2 => __('Non-Tree Devices', 'monitor')]; - $trees = $trees_prefix + $trees_allowed + $trees_suffix; - } - } + $trees = $trees_prefix + $trees_allowed + $trees_suffix; + } + } - drawFilterDropdown('tree', __('Tree', 'monitor'), $trees); - } + drawFilterDropdown('tree', __('Tree', 'monitor'), $trees); + } - if (get_nfilter_request_var('grouping') == 'site') { - $sites = []; + if (get_nfilter_request_var('grouping') == 'site') { + $sites = []; - if (get_request_var('grouping') == 'site') { - $sites = array_rekey( - db_fetch_assoc('SELECT id, name + if (get_request_var('grouping') == 'site') { + $sites = array_rekey( + db_fetch_assoc('SELECT id, name FROM sites ORDER BY name'), - 'id', 'name' - ); + 'id', + 'name' + ); - if (cacti_sizeof($sites)) { - $sites_prefix = [-1 => __('All Sites', 'monitor')]; - $sites_suffix = [-2 => __('Non-Site Devices', 'monitor')]; + if (cacti_sizeof($sites)) { + $sites_prefix = [-1 => __('All Sites', 'monitor')]; + $sites_suffix = [-2 => __('Non-Site Devices', 'monitor')]; - $sites = $sites_prefix + $sites + $sites_suffix; - } - } + $sites = $sites_prefix + $sites + $sites_suffix; + } + } - drawFilterDropdown('site', __('Sites', 'monitor'), $sites); - } + drawFilterDropdown('site', __('Sites', 'monitor'), $sites); + } - if (get_request_var('grouping') == 'template') { - $templates = []; - $templates_allowed = array_rekey( - db_fetch_assoc('SELECT ht.id, ht.name, COUNT(gl.id) AS graphs + if (get_request_var('grouping') == 'template') { + $templates = []; + $templates_allowed = array_rekey( + db_fetch_assoc('SELECT ht.id, ht.name, COUNT(gl.id) AS graphs FROM host_template AS ht INNER JOIN host AS h ON h.host_template_id = ht.id @@ -446,474 +470,499 @@ function drawFilterAndStatus() { ON h.id = gl.host_id GROUP BY ht.id HAVING graphs > 0'), - 'id', 'name' - ); + 'id', + 'name' + ); - if (cacti_sizeof($templates_allowed)) { - $templates_prefix = [-1 => __('All Templates', 'monitor')]; - $templates_suffix = [-2 => __('Non-Templated Devices', 'monitor')]; + if (cacti_sizeof($templates_allowed)) { + $templates_prefix = [-1 => __('All Templates', 'monitor')]; + $templates_suffix = [-2 => __('Non-Templated Devices', 'monitor')]; - $templates = $templates_prefix + $templates_allowed + $templates_suffix; - } + $templates = $templates_prefix + $templates_allowed + $templates_suffix; + } - drawFilterDropdown('template', __('Template', 'monitor'), $templates); - } + drawFilterDropdown('template', __('Template', 'monitor'), $templates); + } - drawFilterDropdown('refresh', __('Refresh', 'monitor'), $page_refresh_interval); + drawFilterDropdown('refresh', __('Refresh', 'monitor'), $page_refresh_interval); - if (get_request_var('grouping') != 'tree') { - print '' . PHP_EOL; - } + if (get_request_var('grouping') != 'tree') { + print '' . PHP_EOL; + } - if (get_request_var('grouping') != 'site') { - print '' . PHP_EOL; - } + if (get_request_var('grouping') != 'site') { + print '' . PHP_EOL; + } - if (get_request_var('grouping') != 'template') { - print '' . PHP_EOL; - } + if (get_request_var('grouping') != 'template') { + print '' . PHP_EOL; + } - if (get_request_var('view') == 'list') { - print '' . PHP_EOL; - } + if (get_request_var('view') == 'list') { + print '' . PHP_EOL; + } - if (get_request_var('view') != 'default') { - print '' . PHP_EOL; - } + if (get_request_var('view') != 'default') { + print '' . PHP_EOL; + } - print ''; - print '
' . __('Search', 'monitor') . '
'; - print '
' . PHP_EOL; + print ''; + print ''; + print '' . PHP_EOL; - html_end_box(); + html_end_box(); - if ($dozoombgndcolor) { - $mbcolora = db_fetch_row_prepared('SELECT * + if ($dozoombgndcolor) { + $mbcolora = db_fetch_row_prepared( + 'SELECT * FROM colors WHERE id = ?', - [read_user_setting('monitor_error_background')]); - - $monitor_error_fontsize = read_user_setting('monitor_error_fontsize') . 'px'; - - if (cacti_sizeof($mbcolora)) { - $mbcolor = '#' . $mbcolora['hex']; - } else { - $mbcolor = 'snow'; - } - } else { - $mbcolor = ''; - $monitor_error_fontsize = '10px'; - } - - $monitor_js_config = [ - 'mbColor' => $mbcolor, - 'monitorFont' => $monitor_error_fontsize, - 'doZoomRefresh' => $dozoomrefresh, - 'newForm' => $new_form, - 'newTitle' => $new_title, - 'messages' => [ - 'filterSaved' => __(' [ Filter Settings Saved ]', 'monitor'), - 'cancel' => __('Cancel', 'monitor'), - 'save' => __('Save', 'monitor') - ] - ]; - - print ''; - print ''; - - } - -function getMuteText() { - if (isMonitorAudible()) { - return __('Mute', 'monitor'); - } else { - return __('Acknowledge', 'monitor'); - } + [read_user_setting('monitor_error_background')] + ); + + $monitor_error_fontsize = read_user_setting('monitor_error_fontsize') . 'px'; + + if (cacti_sizeof($mbcolora)) { + $mbcolor = '#' . $mbcolora['hex']; + } else { + $mbcolor = 'snow'; + } + } else { + $mbcolor = ''; + $monitor_error_fontsize = '10px'; + } + + $monitor_js_config = [ + 'mbColor' => $mbcolor, + 'monitorFont' => $monitor_error_fontsize, + 'doZoomRefresh' => $dozoomrefresh, + 'newForm' => $new_form, + 'newTitle' => $new_title, + 'messages' => [ + 'filterSaved' => __(' [ Filter Settings Saved ]', 'monitor'), + 'cancel' => __('Cancel', 'monitor'), + 'save' => __('Save', 'monitor') + ] + ]; + + print ''; + print ''; + +} + +function getMuteText() +{ + if (isMonitorAudible()) { + return __('Mute', 'monitor'); + } else { + return __('Acknowledge', 'monitor'); + } } -function getUnmuteText() { - if (isMonitorAudible()) { - return __('Un-Mute', 'monitor'); - } else { - return __('Reset', 'monitor'); - } +function getUnmuteText() +{ + if (isMonitorAudible()) { + return __('Un-Mute', 'monitor'); + } else { + return __('Reset', 'monitor'); + } } -function removeDashboard() { - $dashboard = get_filter_request_var('dashboard'); +function removeDashboard() +{ + $dashboard = get_filter_request_var('dashboard'); - $name = db_fetch_cell_prepared('SELECT name + $name = db_fetch_cell_prepared( + 'SELECT name FROM plugin_monitor_dashboards WHERE id = ? AND user_id = ?', - [$dashboard, $_SESSION['sess_user_id']]); + [$dashboard, $_SESSION['sess_user_id']] + ); - if ($name != '') { - db_execute_prepared('DELETE FROM plugin_monitor_dashboards + if ($name != '') { + db_execute_prepared( + 'DELETE FROM plugin_monitor_dashboards WHERE id = ?', - [$dashboard]); + [$dashboard] + ); - raise_message('removed', __('Dashboard \'%s\' Removed.', $name, 'monitor'), MESSAGE_LEVEL_INFO); - } else { - $name = db_fetch_cell_prepared('SELECT name + raise_message('removed', __('Dashboard \'%s\' Removed.', $name, 'monitor'), MESSAGE_LEVEL_INFO); + } else { + $name = db_fetch_cell_prepared( + 'SELECT name FROM plugin_monitor_dashboards WHERE id = ?', - [$dashboard]); + [$dashboard] + ); - raise_message('notremoved', __('Dashboard \'%s\' is not owned by you.', $name, 'monitor'), MESSAGE_LEVEL_ERROR); - } + raise_message('notremoved', __('Dashboard \'%s\' is not owned by you.', $name, 'monitor'), MESSAGE_LEVEL_ERROR); + } - set_request_var('dashboard', '0'); + set_request_var('dashboard', '0'); } -function saveSettings() { - if (isset_request_var('dashboard') && get_filter_request_var('dashboard') != 0) { - $save_db = true; - } else { - $save_db = false; - } - - validateRequestVars(); - - if (!$save_db) { - if (cacti_sizeof($_REQUEST)) { - foreach ($_REQUEST as $var => $value) { - switch($var) { - case 'dashboard': - set_user_setting('monitor_rfilter', get_request_var('dashboard')); - - break; - case 'rfilter': - set_user_setting('monitor_rfilter', get_request_var('rfilter')); - - break; - case 'refresh': - set_user_setting('monitor_refresh', get_request_var('refresh')); - - break; - case 'grouping': - set_user_setting('monitor_grouping', get_request_var('grouping')); - - break; - case 'view': - set_user_setting('monitor_view', get_request_var('view')); - - break; - case 'rows': - set_user_setting('monitor_rows', get_request_var('rows')); - - break; - case 'crit': - set_user_setting('monitor_crit', get_request_var('crit')); - - break; - case 'mute': - set_user_setting('monitor_mute', get_request_var('mute')); - - break; - case 'size': - set_user_setting('monitor_size', get_request_var('size')); - - break; - case 'trim': - set_user_setting('monitor_trim', get_request_var('trim')); - - break; - case 'status': - set_user_setting('monitor_status', get_request_var('status')); - - break; - case 'tree': - set_user_setting('monitor_tree', get_request_var('tree')); - - break; - case 'mute': - set_user_setting('monitor_mute', get_request_var('mute')); - - break; - case 'site': - set_user_setting('monitor_site', get_request_var('site')); - - break; - } - } - } - } else { - $url = 'monitor.php' . - '?refresh=' . get_request_var('refresh') . - '&grouping=' . get_request_var('grouping') . - '&view=' . get_request_var('view') . - '&rows=' . get_request_var('rows') . - '&crit=' . get_request_var('crit') . - '&size=' . get_request_var('size') . - '&trim=' . get_request_var('trim') . - '&status=' . get_request_var('status') . - '&tree=' . get_request_var('tree') . - '&site=' . get_request_var('site'); - - if (!isset_request_var('user')) { - $user = $_SESSION['sess_user_id']; - } else { - $user = get_request_var('user'); - } - - $id = get_request_var('dashboard'); - $name = get_nfilter_request_var('name'); - - $save = []; - $save['id'] = $id; - $save['name'] = $name; - $save['user_id'] = $user; - $save['url'] = $url; - - $id = sql_save($save, 'plugin_monitor_dashboards'); - - if (!empty($id)) { - raise_message('monitorsaved', __('Dashboard \'%s\' has been Saved!', $name, 'monitor'), MESSAGE_LEVEL_INFO); - set_request_var('dashboard', $id); - } else { - raise_message('monitornotsaved', __('Dashboard \'%s\' could not be Saved!', $name, 'monitor'), MESSAGE_LEVEL_INFO); - set_request_var('dashboard', '0'); - } - } - - validateRequestVars(true); +function saveSettings() +{ + if (isset_request_var('dashboard') && get_filter_request_var('dashboard') != 0) { + $save_db = true; + } else { + $save_db = false; + } + + validateRequestVars(); + + if (!$save_db) { + if (cacti_sizeof($_REQUEST)) { + foreach ($_REQUEST as $var => $value) { + switch ($var) { + case 'dashboard': + set_user_setting('monitor_rfilter', get_request_var('dashboard')); + + break; + case 'rfilter': + set_user_setting('monitor_rfilter', get_request_var('rfilter')); + + break; + case 'refresh': + set_user_setting('monitor_refresh', get_request_var('refresh')); + + break; + case 'grouping': + set_user_setting('monitor_grouping', get_request_var('grouping')); + + break; + case 'view': + set_user_setting('monitor_view', get_request_var('view')); + + break; + case 'rows': + set_user_setting('monitor_rows', get_request_var('rows')); + + break; + case 'crit': + set_user_setting('monitor_crit', get_request_var('crit')); + + break; + case 'mute': + set_user_setting('monitor_mute', get_request_var('mute')); + + break; + case 'size': + set_user_setting('monitor_size', get_request_var('size')); + + break; + case 'trim': + set_user_setting('monitor_trim', get_request_var('trim')); + + break; + case 'status': + set_user_setting('monitor_status', get_request_var('status')); + + break; + case 'tree': + set_user_setting('monitor_tree', get_request_var('tree')); + + break; + case 'mute': + set_user_setting('monitor_mute', get_request_var('mute')); + + break; + case 'site': + set_user_setting('monitor_site', get_request_var('site')); + + break; + } + } + } + } else { + $url = 'monitor.php' . + '?refresh=' . get_request_var('refresh') . + '&grouping=' . get_request_var('grouping') . + '&view=' . get_request_var('view') . + '&rows=' . get_request_var('rows') . + '&crit=' . get_request_var('crit') . + '&size=' . get_request_var('size') . + '&trim=' . get_request_var('trim') . + '&status=' . get_request_var('status') . + '&tree=' . get_request_var('tree') . + '&site=' . get_request_var('site'); + + if (!isset_request_var('user')) { + $user = $_SESSION['sess_user_id']; + } else { + $user = get_request_var('user'); + } + + $id = get_request_var('dashboard'); + $name = get_nfilter_request_var('name'); + + $save = []; + $save['id'] = $id; + $save['name'] = $name; + $save['user_id'] = $user; + $save['url'] = $url; + + $id = sql_save($save, 'plugin_monitor_dashboards'); + + if (!empty($id)) { + raise_message('monitorsaved', __('Dashboard \'%s\' has been Saved!', $name, 'monitor'), MESSAGE_LEVEL_INFO); + set_request_var('dashboard', $id); + } else { + raise_message('monitornotsaved', __('Dashboard \'%s\' could not be Saved!', $name, 'monitor'), MESSAGE_LEVEL_INFO); + set_request_var('dashboard', '0'); + } + } + + validateRequestVars(true); } -function validateRequestVars($force = false) { - // ================= input validation and session storage ================= - $filters = [ - 'refresh' => [ - 'filter' => FILTER_VALIDATE_INT, - 'default' => read_user_setting('monitor_refresh', read_config_option('monitor_refresh'), $force) - ], - 'dashboard' => [ - 'filter' => FILTER_VALIDATE_INT, - 'pageset' => true, - 'default' => read_user_setting('monitor_dashboard', '0', $force) - ], - 'rfilter' => [ - 'filter' => FILTER_VALIDATE_IS_REGEX, - 'pageset' => true, - 'default' => read_user_setting('monitor_rfilter', '', $force) - ], - 'name' => [ - 'filter' => FILTER_CALLBACK, - 'options' => ['options' => 'sanitize_search_string'], - 'default' => '' - ], - 'mute' => [ - 'filter' => FILTER_CALLBACK, - 'options' => ['options' => 'sanitize_search_string'], - 'default' => read_user_setting('monitor_mute', 'false', $force) - ], - 'grouping' => [ - 'filter' => FILTER_CALLBACK, - 'options' => ['options' => 'sanitize_search_string'], - 'pageset' => true, - 'default' => read_user_setting('monitor_grouping', read_config_option('monitor_grouping'), $force) - ], - 'view' => [ - 'filter' => FILTER_CALLBACK, - 'options' => ['options' => 'sanitize_search_string'], - 'pageset' => true, - 'default' => read_user_setting('monitor_view', read_config_option('monitor_view'), $force) - ], - 'rows' => [ - 'filter' => FILTER_VALIDATE_INT, - 'options' => ['options' => 'sanitize_search_string'], - 'default' => read_user_setting('monitor_rows', read_config_option('num_rows_table'), $force) - ], - 'size' => [ - 'filter' => FILTER_CALLBACK, - 'options' => ['options' => 'sanitize_search_string'], - 'default' => read_user_setting('monitor_size', 'monitor_medium', $force) - ], - 'trim' => [ - 'filter' => FILTER_VALIDATE_INT, - 'default' => read_user_setting('monitor_trim', read_config_option('monitor_trim'), $force) - ], - 'crit' => [ - 'filter' => FILTER_VALIDATE_INT, - 'pageset' => true, - 'default' => read_user_setting('monitor_crit', '-1', $force) - ], - 'status' => [ - 'filter' => FILTER_VALIDATE_INT, - 'pageset' => true, - 'default' => read_user_setting('monitor_status', '-1', $force) - ], - 'tree' => [ - 'filter' => FILTER_VALIDATE_INT, - 'pageset' => true, - 'default' => read_user_setting('monitor_tree', '-1', $force) - ], - 'site' => [ - 'filter' => FILTER_VALIDATE_INT, - 'pageset' => true, - 'default' => read_user_setting('monitor_site', '-1', $force) - ], - 'template' => [ - 'filter' => FILTER_VALIDATE_INT, - 'pageset' => true, - 'default' => read_user_setting('monitor_template', '-1', $force) - ], - 'id' => [ - 'filter' => FILTER_VALIDATE_INT, - 'default' => '-1' - ], - 'page' => [ - 'filter' => FILTER_VALIDATE_INT, - 'default' => '1' - ], - 'sort_column' => [ - 'filter' => FILTER_CALLBACK, - 'default' => 'status', - 'options' => ['options' => 'sanitize_search_string'] - ], - 'sort_direction' => [ - 'filter' => FILTER_CALLBACK, - 'default' => 'ASC', - 'options' => ['options' => 'sanitize_search_string'] - ] - ]; - - validate_store_request_vars($filters, 'sess_monitor'); - // ================= input validation ================= +function validateRequestVars($force = false) +{ + // ================= input validation and session storage ================= + $filters = [ + 'refresh' => [ + 'filter' => FILTER_VALIDATE_INT, + 'default' => read_user_setting('monitor_refresh', read_config_option('monitor_refresh'), $force) + ], + 'dashboard' => [ + 'filter' => FILTER_VALIDATE_INT, + 'pageset' => true, + 'default' => read_user_setting('monitor_dashboard', '0', $force) + ], + 'rfilter' => [ + 'filter' => FILTER_VALIDATE_IS_REGEX, + 'pageset' => true, + 'default' => read_user_setting('monitor_rfilter', '', $force) + ], + 'name' => [ + 'filter' => FILTER_CALLBACK, + 'options' => ['options' => 'sanitize_search_string'], + 'default' => '' + ], + 'mute' => [ + 'filter' => FILTER_CALLBACK, + 'options' => ['options' => 'sanitize_search_string'], + 'default' => read_user_setting('monitor_mute', 'false', $force) + ], + 'grouping' => [ + 'filter' => FILTER_CALLBACK, + 'options' => ['options' => 'sanitize_search_string'], + 'pageset' => true, + 'default' => read_user_setting('monitor_grouping', read_config_option('monitor_grouping'), $force) + ], + 'view' => [ + 'filter' => FILTER_CALLBACK, + 'options' => ['options' => 'sanitize_search_string'], + 'pageset' => true, + 'default' => read_user_setting('monitor_view', read_config_option('monitor_view'), $force) + ], + 'rows' => [ + 'filter' => FILTER_VALIDATE_INT, + 'options' => ['options' => 'sanitize_search_string'], + 'default' => read_user_setting('monitor_rows', read_config_option('num_rows_table'), $force) + ], + 'size' => [ + 'filter' => FILTER_CALLBACK, + 'options' => ['options' => 'sanitize_search_string'], + 'default' => read_user_setting('monitor_size', 'monitor_medium', $force) + ], + 'trim' => [ + 'filter' => FILTER_VALIDATE_INT, + 'default' => read_user_setting('monitor_trim', read_config_option('monitor_trim'), $force) + ], + 'crit' => [ + 'filter' => FILTER_VALIDATE_INT, + 'pageset' => true, + 'default' => read_user_setting('monitor_crit', '-1', $force) + ], + 'status' => [ + 'filter' => FILTER_VALIDATE_INT, + 'pageset' => true, + 'default' => read_user_setting('monitor_status', '-1', $force) + ], + 'tree' => [ + 'filter' => FILTER_VALIDATE_INT, + 'pageset' => true, + 'default' => read_user_setting('monitor_tree', '-1', $force) + ], + 'site' => [ + 'filter' => FILTER_VALIDATE_INT, + 'pageset' => true, + 'default' => read_user_setting('monitor_site', '-1', $force) + ], + 'template' => [ + 'filter' => FILTER_VALIDATE_INT, + 'pageset' => true, + 'default' => read_user_setting('monitor_template', '-1', $force) + ], + 'id' => [ + 'filter' => FILTER_VALIDATE_INT, + 'default' => '-1' + ], + 'page' => [ + 'filter' => FILTER_VALIDATE_INT, + 'default' => '1' + ], + 'sort_column' => [ + 'filter' => FILTER_CALLBACK, + 'default' => 'status', + 'options' => ['options' => 'sanitize_search_string'] + ], + 'sort_direction' => [ + 'filter' => FILTER_CALLBACK, + 'default' => 'ASC', + 'options' => ['options' => 'sanitize_search_string'] + ] + ]; + + validate_store_request_vars($filters, 'sess_monitor'); + // ================= input validation ================= } -function ajaxStatus() { - global $thold_hosts, $config, $icolorsdisplay, $iclasses, $criticalities; +function ajaxStatus() +{ + global $thold_hosts, $config, $icolorsdisplay, $iclasses, $criticalities; - $tholds = 0; + $tholds = 0; - validateRequestVars(); + validateRequestVars(); - if (isset_request_var('id') && get_filter_request_var('id')) { - $id = get_request_var('id'); - $size = get_request_var('size'); + if (isset_request_var('id') && get_filter_request_var('id')) { + $id = get_request_var('id'); + $size = get_request_var('size'); - $host = db_fetch_row_prepared('SELECT * + $host = db_fetch_row_prepared( + 'SELECT * FROM host WHERE id = ?', - [$id]); + [$id] + ); - if (!cacti_sizeof($host)) { - cacti_log('Attempted to retrieve status for missing Device ' . $id, false, 'MONITOR', POLLER_VERBOSITY_HIGH); + if (!cacti_sizeof($host)) { + cacti_log('Attempted to retrieve status for missing Device ' . $id, false, 'MONITOR', POLLER_VERBOSITY_HIGH); - return false; - } + return false; + } - $host['anchor'] = $config['url_path'] . 'graph_view.php?action=preview&reset=1&host_id=' . $host['id']; + $host['anchor'] = $config['url_path'] . 'graph_view.php?action=preview&reset=1&host_id=' . $host['id']; - if ($host['status'] == 3 && array_key_exists($host['id'], $thold_hosts)) { - $host['status'] = 4; - $host['anchor'] = $config['url_path'] . 'plugins/thold/thold_graph.php?action=thold&reset=true&status=1&host_id=' . $host['id']; - } + if ($host['status'] == 3 && array_key_exists($host['id'], $thold_hosts)) { + $host['status'] = 4; + $host['anchor'] = $config['url_path'] . 'plugins/thold/thold_graph.php?action=thold&reset=true&status=1&host_id=' . $host['id']; + } - if ($host['availability_method'] == 0) { - $host['status'] = 6; - } + if ($host['availability_method'] == 0) { + $host['status'] = 6; + } - $host['real_status'] = getHostStatus($host, true); - $host['status'] = getHostStatus($host); + $host['real_status'] = getHostStatus($host, true); + $host['status'] = getHostStatus($host); - if (cacti_sizeof($host)) { - if (api_plugin_user_realm_auth('host.php')) { - $host_link = html_escape($config['url_path'] . 'host.php?action=edit&id=' . $host['id']); - } + if (cacti_sizeof($host)) { + if (api_plugin_user_realm_auth('host.php')) { + $host_link = html_escape($config['url_path'] . 'host.php?action=edit&id=' . $host['id']); + } - // Get the number of graphs - $graphs = db_fetch_cell_prepared('SELECT COUNT(*) + // Get the number of graphs + $graphs = db_fetch_cell_prepared( + 'SELECT COUNT(*) FROM graph_local WHERE host_id = ?', - [$host['id']]); + [$host['id']] + ); - if ($graphs > 0) { - $graph_link = html_escape($config['url_path'] . 'graph_view.php?action=preview&reset=1&host_id=' . $host['id']); - } + if ($graphs > 0) { + $graph_link = html_escape($config['url_path'] . 'graph_view.php?action=preview&reset=1&host_id=' . $host['id']); + } - // Get the number of thresholds - if (api_plugin_is_enabled('thold')) { - $tholds = db_fetch_cell_prepared('SELECT count(*) + // Get the number of thresholds + if (api_plugin_is_enabled('thold')) { + $tholds = db_fetch_cell_prepared( + 'SELECT count(*) FROM thold_data WHERE host_id = ?', - [$host['id']]); + [$host['id']] + ); - if ($tholds) { - $thold_link = html_escape($config['url_path'] . 'plugins/thold/thold_graph.php?action=thold&reset=true&status=1&host_id=' . $host['id']); - } - } + if ($tholds) { + $thold_link = html_escape($config['url_path'] . 'plugins/thold/thold_graph.php?action=thold&reset=true&status=1&host_id=' . $host['id']); + } + } - // Get the number of syslogs - if (api_plugin_is_enabled('syslog') && api_plugin_user_realm_auth('syslog.php')) { - include($config['base_path'] . '/plugins/syslog/config.php'); - include_once($config['base_path'] . '/plugins/syslog/functions.php'); + // Get the number of syslogs + if (api_plugin_is_enabled('syslog') && api_plugin_user_realm_auth('syslog.php')) { + include($config['base_path'] . '/plugins/syslog/config.php'); + include_once($config['base_path'] . '/plugins/syslog/functions.php'); - $syslog_logs = syslog_db_fetch_cell_prepared('SELECT count(*) + $syslog_logs = syslog_db_fetch_cell_prepared( + 'SELECT count(*) FROM syslog_logs WHERE host = ?', - [$host['hostname']]); + [$host['hostname']] + ); - $syslog_host = syslog_db_fetch_cell_prepared('SELECT host_id + $syslog_host = syslog_db_fetch_cell_prepared( + 'SELECT host_id FROM syslog_hosts WHERE host = ?', - [$host['hostname']]); + [$host['hostname']] + ); - if ($syslog_logs && $syslog_host) { - $syslog_log_link = html_escape($config['url_path'] . 'plugins/syslog/syslog/syslog.php?reset=1&tab=alerts&host_id=' . $syslog_host); - } + if ($syslog_logs && $syslog_host) { + $syslog_log_link = html_escape($config['url_path'] . 'plugins/syslog/syslog/syslog.php?reset=1&tab=alerts&host_id=' . $syslog_host); + } - if ($syslog_host) { - $syslog_link = html_escape($config['url_path'] . 'plugins/syslog/syslog/syslog.php?reset=1&tab=syslog&host_id=' . $syslog_host); - } - } else { - $syslog_logs = 0; - $syslog_host = 0; - } + if ($syslog_host) { + $syslog_link = html_escape($config['url_path'] . 'plugins/syslog/syslog/syslog.php?reset=1&tab=syslog&host_id=' . $syslog_host); + } + } else { + $syslog_logs = 0; + $syslog_host = 0; + } - $links = ''; + $links = ''; - if (isset($host_link)) { - $links .= '
'; - } + if (isset($host_link)) { + $links .= '
'; + } - if (isset($graph_link)) { - $links .= '
'; - } + if (isset($graph_link)) { + $links .= '
'; + } - if (isset($thold_link)) { - $links .= '
'; - } + if (isset($thold_link)) { + $links .= '
'; + } - if (isset($syslog_log_link)) { - $links .= '
'; - } + if (isset($syslog_log_link)) { + $links .= '
'; + } - if (isset($syslog_link)) { - $links .= '
'; - } + if (isset($syslog_link)) { + $links .= '
'; + } - if (strtotime($host['status_fail_date']) < 86400) { - $host['status_fail_date'] = __('Never', 'monitor'); - } + if (strtotime($host['status_fail_date']) < 86400) { + $host['status_fail_date'] = __('Never', 'monitor'); + } - $iclass = $iclasses[$host['status']]; - $sdisplay = getHostStatusDescription($host['real_status']); - $site = db_fetch_cell_prepared('SELECT name FROM sites WHERE id = ?', [$host['site_id']]); + $iclass = $iclasses[$host['status']]; + $sdisplay = getHostStatusDescription($host['real_status']); + $site = db_fetch_cell_prepared('SELECT name FROM sites WHERE id = ?', [$host['site_id']]); - if ($host['location'] == '') { - $host['location'] = __('Unspecified', 'monitor'); - } + if ($host['location'] == '') { + $host['location'] = __('Unspecified', 'monitor'); + } - if ($site == '') { - $site = __('None', 'monitor'); - } + if ($site == '') { + $site = __('None', 'monitor'); + } - print " + print "
@@ -962,7 +1011,7 @@ function ajaxStatus() { - + ' . ($host['snmp_version'] > 0 && ($host['status'] == 3 || $host['status'] == 2) ? ' @@ -987,6 +1036,6 @@ function ajaxStatus() {
" . __('Device Status Information', 'monitor') . '
' . __('Availability:', 'monitor') . '' . round($host['availability'],2) . ' %' . round($host['availability'], 2) . ' %
' . __('Agent Uptime:', 'monitor') . '

$links
"; - } - } + } + } } diff --git a/monitor_render.php b/monitor_render.php index a386a96..01eaf3a 100644 --- a/monitor_render.php +++ b/monitor_render.php @@ -1,4 +1,5 @@ 0 AND status IN (1, 2), status_event_count*$poller_interval, IF(UNIX_TIMESTAMP(status_rec_date) < 943916400 AND status IN (0, 3), total_polls*$poller_interval, @@ -67,80 +69,81 @@ function renderDefault() { $sql_order $sql_limit"); - $hosts = db_fetch_assoc($hosts_sql); + $hosts = db_fetch_assoc($hosts_sql); - $total_rows = db_fetch_cell("SELECT COUNT(DISTINCT h.id) + $total_rows = db_fetch_cell("SELECT COUNT(DISTINCT h.id) FROM host AS h LEFT JOIN sites AS s ON h.site_id = s.id $sql_join $sql_where"); - if (cacti_sizeof($hosts)) { - // Determine the correct width of the cell - $maxlen = 10; + if (cacti_sizeof($hosts)) { + // Determine the correct width of the cell + $maxlen = 10; - if (get_request_var('view') == 'default') { - $maxlen = db_fetch_cell("SELECT MAX(LENGTH(description)) + if (get_request_var('view') == 'default') { + $maxlen = db_fetch_cell("SELECT MAX(LENGTH(description)) FROM host AS h $sql_join $sql_where"); - } + } - $maxlen = getMonitorTrimLength($maxlen); + $maxlen = getMonitorTrimLength($maxlen); - $function = 'renderHeader' . ucfirst(get_request_var('view')); + $function = 'renderHeader' . ucfirst(get_request_var('view')); - if (function_exists($function)) { - // Call the custom render_header_ function - $result .= $function($total_rows, $rows); - } + if (function_exists($function)) { + // Call the custom render_header_ function + $result .= $function($total_rows, $rows); + } - $count = 0; + $count = 0; - foreach ($hosts as $host) { - if (is_device_allowed($host['id'])) { - $result .= renderHost($host, true, $maxlen); - } + foreach ($hosts as $host) { + if (is_device_allowed($host['id'])) { + $result .= renderHost($host, true, $maxlen); + } - $count++; - } + $count++; + } - $function = 'renderFooter' . ucfirst(get_request_var('view')); + $function = 'renderFooter' . ucfirst(get_request_var('view')); - if (function_exists($function)) { - // Call the custom render_footer_ function - $result .= $function($total_rows, $rows); - } - } + if (function_exists($function)) { + // Call the custom render_footer_ function + $result .= $function($total_rows, $rows); + } + } - return $result; + return $result; } -function renderSite() { - global $maxchars; +function renderSite() +{ + global $maxchars; - $result = ''; + $result = ''; - $sql_where = ''; - $sql_join = ''; - $sql_limit = ''; + $sql_where = ''; + $sql_join = ''; + $sql_limit = ''; - $rows = get_request_var('rows'); + $rows = get_request_var('rows'); - if ($rows == '-1') { - $rows = read_user_setting('monitor_rows'); - } + if ($rows == '-1') { + $rows = read_user_setting('monitor_rows'); + } - if (!is_numeric($rows)) { - $rows = read_config_option('num_rows_table'); - } + if (!is_numeric($rows)) { + $rows = read_config_option('num_rows_table'); + } - renderWhereJoin($sql_where, $sql_join); + renderWhereJoin($sql_where, $sql_join); - $sql_limit = ' LIMIT ' . ($rows * (get_request_var('page') - 1)) . ',' . $rows; + $sql_limit = ' LIMIT ' . ($rows * (get_request_var('page') - 1)) . ',' . $rows; - $hosts_sql = ("SELECT DISTINCT h.*, IFNULL(s.name,' " . __('Non-Site Devices', 'monitor') . " ') AS site_name + $hosts_sql = ("SELECT DISTINCT h.*, IFNULL(s.name,' " . __('Non-Site Devices', 'monitor') . " ') AS site_name FROM host AS h LEFT JOIN sites AS s ON s.id = h.site_id @@ -149,127 +152,128 @@ function renderSite() { ORDER BY site_name, description $sql_limit"); - $hosts = db_fetch_assoc($hosts_sql); + $hosts = db_fetch_assoc($hosts_sql); - $ctemp = -1; - $ptemp = -1; + $ctemp = -1; + $ptemp = -1; - if (cacti_sizeof($hosts)) { - $suppressGroups = false; - $function = 'renderSuppressgroups' . ucfirst(get_request_var('view')); + if (cacti_sizeof($hosts)) { + $suppressGroups = false; + $function = 'renderSuppressgroups' . ucfirst(get_request_var('view')); - if (function_exists($function)) { - $suppressGroups = $function(); - } + if (function_exists($function)) { + $suppressGroups = $function(); + } - $function = 'renderHeader' . ucfirst(get_request_var('view')); + $function = 'renderHeader' . ucfirst(get_request_var('view')); - if (function_exists($function)) { - // Call the custom render_header_ function - $result .= $function(); - $suppressGroups = true; - } + if (function_exists($function)) { + // Call the custom render_header_ function + $result .= $function(); + $suppressGroups = true; + } - foreach ($hosts as $index => $host) { - if (is_device_allowed($host['id'])) { - $host_ids[] = $host['id']; - } else { - unset($hosts[$index]); - } - } + foreach ($hosts as $index => $host) { + if (is_device_allowed($host['id'])) { + $host_ids[] = $host['id']; + } else { + unset($hosts[$index]); + } + } - // Determine the correct width of the cell - $maxlen = 10; + // Determine the correct width of the cell + $maxlen = 10; - if (get_request_var('view') == 'default') { - $maxlen = db_fetch_cell('SELECT MAX(LENGTH(description)) + if (get_request_var('view') == 'default') { + $maxlen = db_fetch_cell('SELECT MAX(LENGTH(description)) FROM host AS h WHERE id IN (' . implode(',', $host_ids) . ')'); - } - $maxlen = getMonitorTrimLength($maxlen); + } + $maxlen = getMonitorTrimLength($maxlen); - $class = get_request_var('size'); - $csuffix = get_request_var('view'); + $class = get_request_var('size'); + $csuffix = get_request_var('view'); - if ($csuffix == 'default') { - $csuffix = ''; - } + if ($csuffix == 'default') { + $csuffix = ''; + } - foreach ($hosts as $host) { - $ctemp = $host['site_id']; + foreach ($hosts as $host) { + $ctemp = $host['site_id']; - if (!$suppressGroups) { - if ($ctemp != $ptemp && $ptemp > 0) { - $result .= ''; - } + if (!$suppressGroups) { + if ($ctemp != $ptemp && $ptemp > 0) { + $result .= ''; + } - if ($ctemp != $ptemp) { - $result .= "
+ if ($ctemp != $ptemp) { + $result .= "
"; - } - } + } + } - $result .= renderHost($host, true, $maxlen); + $result .= renderHost($host, true, $maxlen); - if ($ctemp != $ptemp) { - $ptemp = $ctemp; - } - } + if ($ctemp != $ptemp) { + $ptemp = $ctemp; + } + } - if ($ptemp == $ctemp && !$suppressGroups) { - $result .= '
'; - } + if ($ptemp == $ctemp && !$suppressGroups) { + $result .= '
'; + } - $function = 'renderFooter' . ucfirst(get_request_var('view')); + $function = 'renderFooter' . ucfirst(get_request_var('view')); - if (function_exists($function)) { - // Call the custom render_footer_ function - $result .= $function(); - } - } + if (function_exists($function)) { + // Call the custom render_footer_ function + $result .= $function(); + } + } - return $result; + return $result; } -function renderTemplate() { - global $maxchars; +function renderTemplate() +{ + global $maxchars; - $result = ''; + $result = ''; - $sql_where = ''; - $sql_join = ''; - $sql_limit = ''; + $sql_where = ''; + $sql_join = ''; + $sql_limit = ''; - $rows = get_request_var('rows'); + $rows = get_request_var('rows'); - if ($rows == '-1') { - $rows = read_user_setting('monitor_rows'); - } + if ($rows == '-1') { + $rows = read_user_setting('monitor_rows'); + } - if (!is_numeric($rows)) { - $rows = read_config_option('num_rows_table'); - } + if (!is_numeric($rows)) { + $rows = read_config_option('num_rows_table'); + } - renderWhereJoin($sql_where, $sql_join); + renderWhereJoin($sql_where, $sql_join); - $sql_limit = ' LIMIT ' . ($rows * (get_request_var('page') - 1)) . ',' . $rows; + $sql_limit = ' LIMIT ' . ($rows * (get_request_var('page') - 1)) . ',' . $rows; - if (get_request_var('template') > 0) { - $sql_where .= ($sql_where == '' ? '' : 'AND ') . 'ht.id = ' . get_request_var('template'); - } + if (get_request_var('template') > 0) { + $sql_where .= ($sql_where == '' ? '' : 'AND ') . 'ht.id = ' . get_request_var('template'); + } - $sql_template = 'INNER JOIN host_template AS ht ON h.host_template_id=ht.id '; + $sql_template = 'INNER JOIN host_template AS ht ON h.host_template_id=ht.id '; - if (get_request_var('template') == -2) { - $sql_where .= ($sql_where == '' ? '' : 'AND ') . 'ht.id IS NULL'; - $sql_template = 'LEFT JOIN host_template AS ht ON h.host_template_id=ht.id '; - } + if (get_request_var('template') == -2) { + $sql_where .= ($sql_where == '' ? '' : 'AND ') . 'ht.id IS NULL'; + $sql_template = 'LEFT JOIN host_template AS ht ON h.host_template_id=ht.id '; + } - $hosts = db_fetch_assoc("SELECT DISTINCT + $hosts = db_fetch_assoc("SELECT DISTINCT h.*, ht.name AS host_template_name FROM host AS h $sql_template @@ -278,128 +282,129 @@ function renderTemplate() { ORDER BY ht.name, h.description $sql_limit"); - $ctemp = -1; - $ptemp = -1; + $ctemp = -1; + $ptemp = -1; - if (cacti_sizeof($hosts)) { - $suppressGroups = false; - $function = 'renderSuppressgroups' . ucfirst(get_request_var('view')); + if (cacti_sizeof($hosts)) { + $suppressGroups = false; + $function = 'renderSuppressgroups' . ucfirst(get_request_var('view')); - if (function_exists($function)) { - $suppressGroups = $function(); - } + if (function_exists($function)) { + $suppressGroups = $function(); + } - $function = 'renderHeader' . ucfirst(get_request_var('view')); + $function = 'renderHeader' . ucfirst(get_request_var('view')); - if (function_exists($function)) { - // Call the custom render_header_ function - $result .= $function(); - $suppressGroups = true; - } + if (function_exists($function)) { + // Call the custom render_header_ function + $result .= $function(); + $suppressGroups = true; + } - foreach ($hosts as $index => $host) { - if (is_device_allowed($host['id'])) { - $host_ids[] = $host['id']; - } else { - unset($hosts[$index]); - } - } + foreach ($hosts as $index => $host) { + if (is_device_allowed($host['id'])) { + $host_ids[] = $host['id']; + } else { + unset($hosts[$index]); + } + } - // Determine the correct width of the cell - $maxlen = 10; + // Determine the correct width of the cell + $maxlen = 10; - if (get_request_var('view') == 'default') { - $maxlen = db_fetch_cell('SELECT MAX(LENGTH(description)) + if (get_request_var('view') == 'default') { + $maxlen = db_fetch_cell('SELECT MAX(LENGTH(description)) FROM host AS h WHERE id IN (' . implode(',', $host_ids) . ')'); - } - $maxlen = getMonitorTrimLength($maxlen); + } + $maxlen = getMonitorTrimLength($maxlen); - $class = get_request_var('size'); - $csuffix = get_request_var('view'); + $class = get_request_var('size'); + $csuffix = get_request_var('view'); - if ($csuffix == 'default') { - $csuffix = ''; - } + if ($csuffix == 'default') { + $csuffix = ''; + } - foreach ($hosts as $host) { - $ctemp = $host['host_template_id']; + foreach ($hosts as $host) { + $ctemp = $host['host_template_id']; - if (!$suppressGroups) { - if ($ctemp != $ptemp && $ptemp > 0) { - $result .= ''; - } + if (!$suppressGroups) { + if ($ctemp != $ptemp && $ptemp > 0) { + $result .= ''; + } - if ($ctemp != $ptemp) { - $result .= "
+ if ($ctemp != $ptemp) { + $result .= "
"; - } - } + } + } - $result .= renderHost($host, true, $maxlen); + $result .= renderHost($host, true, $maxlen); - if ($ctemp != $ptemp) { - $ptemp = $ctemp; - } - } + if ($ctemp != $ptemp) { + $ptemp = $ctemp; + } + } - if ($ptemp == $ctemp && !$suppressGroups) { - $result .= '
'; - } + if ($ptemp == $ctemp && !$suppressGroups) { + $result .= '
'; + } - $function = 'renderFooter' . ucfirst(get_request_var('view')); + $function = 'renderFooter' . ucfirst(get_request_var('view')); - if (function_exists($function)) { - // Call the custom render_footer_ function - $result .= $function(); - } - } + if (function_exists($function)) { + // Call the custom render_footer_ function + $result .= $function(); + } + } - return $result; + return $result; } -function renderTree() { - global $maxchars; +function renderTree() +{ + global $maxchars; - $result = ''; + $result = ''; - $leafs = []; + $leafs = []; - if (get_request_var('tree') > 0) { - $sql_where = 'gt.id=' . get_request_var('tree'); - } else { - $sql_where = ''; - } + if (get_request_var('tree') > 0) { + $sql_where = 'gt.id=' . get_request_var('tree'); + } else { + $sql_where = ''; + } - if (get_request_var('tree') != -2) { - $tree_list = get_allowed_trees(false, false, $sql_where, 'sequence'); - } else { - $tree_list = []; - } + if (get_request_var('tree') != -2) { + $tree_list = get_allowed_trees(false, false, $sql_where, 'sequence'); + } else { + $tree_list = []; + } - $function = 'renderHeader' . ucfirst(get_request_var('view')); + $function = 'renderHeader' . ucfirst(get_request_var('view')); - if (function_exists($function)) { - $hosts = []; + if (function_exists($function)) { + $hosts = []; - // Call the custom render_header_ function - $result .= $function(); - } + // Call the custom render_header_ function + $result .= $function(); + } - if (cacti_sizeof($tree_list)) { - $ptree = ''; + if (cacti_sizeof($tree_list)) { + $ptree = ''; - foreach ($tree_list as $tree) { - $tree_ids[$tree['id']] = $tree['id']; - } + foreach ($tree_list as $tree) { + $tree_ids[$tree['id']] = $tree['id']; + } - renderWhereJoin($sql_where, $sql_join); + renderWhereJoin($sql_where, $sql_join); - $branchWhost_SQL = ("SELECT DISTINCT gti.graph_tree_id, gti.parent + $branchWhost_SQL = ("SELECT DISTINCT gti.graph_tree_id, gti.parent FROM graph_tree_items AS gti INNER JOIN graph_tree AS gt ON gt.id = gti.graph_tree_id @@ -411,54 +416,56 @@ function renderTree() { AND gti.graph_tree_id IN (" . implode(',', $tree_ids) . ') ORDER BY gt.sequence, gti.position'); - // cacti_log($branchWhost_SQL); + // cacti_log($branchWhost_SQL); - $branchWhost = db_fetch_assoc($branchWhost_SQL); + $branchWhost = db_fetch_assoc($branchWhost_SQL); - // Determine the correct width of the cell - $maxlen = 10; + // Determine the correct width of the cell + $maxlen = 10; - if (get_request_var('view') == 'default') { - $maxlen = db_fetch_cell("SELECT MAX(LENGTH(description)) + if (get_request_var('view') == 'default') { + $maxlen = db_fetch_cell("SELECT MAX(LENGTH(description)) FROM host AS h INNER JOIN graph_tree_items AS gti ON gti.host_id = h.id WHERE disabled = '' AND deleted = ''"); - } + } - $maxlen = getMonitorTrimLength($maxlen); + $maxlen = getMonitorTrimLength($maxlen); - if (cacti_sizeof($branchWhost)) { - foreach ($branchWhost as $b) { - if ($ptree != $b['graph_tree_id']) { - $titles[$b['graph_tree_id'] . ':0'] = __('Root Branch', 'monitor'); - $ptree = $b['graph_tree_id']; - } + if (cacti_sizeof($branchWhost)) { + foreach ($branchWhost as $b) { + if ($ptree != $b['graph_tree_id']) { + $titles[$b['graph_tree_id'] . ':0'] = __('Root Branch', 'monitor'); + $ptree = $b['graph_tree_id']; + } - if ($b['parent'] > 0) { - $titles[$b['graph_tree_id'] . ':' . $b['parent']] = db_fetch_cell_prepared('SELECT title + if ($b['parent'] > 0) { + $titles[$b['graph_tree_id'] . ':' . $b['parent']] = db_fetch_cell_prepared( + 'SELECT title FROM graph_tree_items WHERE id = ? AND graph_tree_id = ? ORDER BY position', - [$b['parent'], $b['graph_tree_id']]); - } - } + [$b['parent'], $b['graph_tree_id']] + ); + } + } - $ptree = ''; + $ptree = ''; - foreach ($titles as $index => $title) { - [$graph_tree_id, $parent] = explode(':', $index); + foreach ($titles as $index => $title) { + [$graph_tree_id, $parent] = explode(':', $index); - $oid = $parent; + $oid = $parent; - $sql_where = ''; - $sql_join = ''; + $sql_where = ''; + $sql_join = ''; - renderWhereJoin($sql_where, $sql_join); + renderWhereJoin($sql_where, $sql_join); - $hosts_sql = "SELECT h.*, IFNULL(s.name,' " . __('Non-Site Device', 'monitor') . " ') AS site_name + $hosts_sql = "SELECT h.*, IFNULL(s.name,' " . __('Non-Site Device', 'monitor') . " ') AS site_name FROM host AS h LEFT JOIN sites AS s ON h.site_id = s.id @@ -471,21 +478,23 @@ function renderTree() { GROUP BY h.id ORDER BY gti.position"; - // cacti_log($hosts_sql); + // cacti_log($hosts_sql); - $hosts = db_fetch_assoc_prepared($hosts_sql, [$oid, $graph_tree_id]); + $hosts = db_fetch_assoc_prepared($hosts_sql, [$oid, $graph_tree_id]); - $tree_name = db_fetch_cell_prepared('SELECT name + $tree_name = db_fetch_cell_prepared( + 'SELECT name FROM graph_tree WHERE id = ?', - [$graph_tree_id]); + [$graph_tree_id] + ); - if ($ptree != $tree_name) { - if ($ptree != '') { - $result .= ''; - } + if ($ptree != $tree_name) { + if ($ptree != '') { + $result .= ''; + } - $result .= "
+ $result .= "
@@ -493,118 +502,120 @@ function renderTree() {
"; - $ptree = $tree_name; - } - - if (cacti_sizeof($hosts)) { - foreach ($hosts as $index => $host) { - if (is_device_allowed($host['id'])) { - $host_ids[] = $host['id']; - } else { - unset($hosts[$index]); - } - } - - $class = get_request_var('size'); - - $result .= "
"; - - foreach ($hosts as $host) { - $result .= renderHost($host, true, $maxlen); - } - - $result .= '
'; - } - } - } - - $result .= '
'; - } - - // begin others - lets get the monitor items that are not associated with any tree - if (get_request_var('tree') < 0) { - $hosts = getHostNonTreeArray(); - - if (cacti_sizeof($hosts)) { - foreach ($hosts as $index => $host) { - if (is_device_allowed($host['id'])) { - $host_ids[] = $host['id']; - } else { - unset($hosts[$index]); - } - } - - // Determine the correct width of the cell - $maxlen = 10; - - if (get_request_var('view') == 'default') { - if (cacti_sizeof($host_ids)) { - $maxlen = db_fetch_cell('SELECT MAX(LENGTH(description)) + $ptree = $tree_name; + } + + if (cacti_sizeof($hosts)) { + foreach ($hosts as $index => $host) { + if (is_device_allowed($host['id'])) { + $host_ids[] = $host['id']; + } else { + unset($hosts[$index]); + } + } + + $class = get_request_var('size'); + + $result .= "
"; + + foreach ($hosts as $host) { + $result .= renderHost($host, true, $maxlen); + } + + $result .= '
'; + } + } + } + + $result .= '
'; + } + + // begin others - lets get the monitor items that are not associated with any tree + if (get_request_var('tree') < 0) { + $hosts = getHostNonTreeArray(); + + if (cacti_sizeof($hosts)) { + foreach ($hosts as $index => $host) { + if (is_device_allowed($host['id'])) { + $host_ids[] = $host['id']; + } else { + unset($hosts[$index]); + } + } + + // Determine the correct width of the cell + $maxlen = 10; + + if (get_request_var('view') == 'default') { + if (cacti_sizeof($host_ids)) { + $maxlen = db_fetch_cell('SELECT MAX(LENGTH(description)) FROM host AS h WHERE id IN (' . implode(',', $host_ids) . ") AND h.deleted = ''"); - } - } - $maxlen = getMonitorTrimLength($maxlen); + } + } + $maxlen = getMonitorTrimLength($maxlen); - $result .= "
+ $result .= "
"; - foreach ($hosts as $leaf) { - $result .= renderHost($leaf, true, $maxlen); - } + foreach ($hosts as $leaf) { + $result .= renderHost($leaf, true, $maxlen); + } - $result .= '
'; - } - } + $result .= '
'; + } + } - $function = 'renderFooter' . ucfirst(get_request_var('view')); + $function = 'renderFooter' . ucfirst(get_request_var('view')); - if (function_exists($function)) { - // Call the custom render_footer_ function - $result .= $function(); - } + if (function_exists($function)) { + // Call the custom render_footer_ function + $result .= $function(); + } - return $result; + return $result; } -function getHostStatus($host, $real = false) { - global $thold_hosts, $iclasses; - - // If the host has been muted, show the muted Icon - if ($host['status'] != 1 && in_array($host['id'], $thold_hosts, true)) { - $host['status'] = 4; - } - - if (in_array($host['id'], $_SESSION['monitor_muted_hosts'], true) && $host['status'] == 1) { - $host['status'] = 5; - } elseif (in_array($host['id'], $_SESSION['monitor_muted_hosts'], true) && $host['status'] == 4) { - $host['status'] = 9; - } elseif ($host['status'] == 3) { - if ($host['cur_time'] > $host['monitor_alert'] && !empty($host['monitor_alert'])) { - $host['status'] = 8; - } elseif ($host['cur_time'] > $host['monitor_warn'] && !empty($host['monitor_warn'])) { - $host['status'] = 7; - } - } - - // If wanting the real status, or the status is already known - // return the real status, otherwise default to unknown - return ($real || array_key_exists($host['status'], $iclasses)) ? $host['status'] : 0; +function getHostStatus($host, $real = false) +{ + global $thold_hosts, $iclasses; + + // If the host has been muted, show the muted Icon + if ($host['status'] != 1 && in_array($host['id'], $thold_hosts, true)) { + $host['status'] = 4; + } + + if (in_array($host['id'], $_SESSION['monitor_muted_hosts'], true) && $host['status'] == 1) { + $host['status'] = 5; + } elseif (in_array($host['id'], $_SESSION['monitor_muted_hosts'], true) && $host['status'] == 4) { + $host['status'] = 9; + } elseif ($host['status'] == 3) { + if ($host['cur_time'] > $host['monitor_alert'] && !empty($host['monitor_alert'])) { + $host['status'] = 8; + } elseif ($host['cur_time'] > $host['monitor_warn'] && !empty($host['monitor_warn'])) { + $host['status'] = 7; + } + } + + // If wanting the real status, or the status is already known + // return the real status, otherwise default to unknown + return ($real || array_key_exists($host['status'], $iclasses)) ? $host['status'] : 0; } -function getHostStatusDescription($status) { - global $icolorsdisplay; +function getHostStatusDescription($status) +{ + global $icolorsdisplay; - if (array_key_exists($status, $icolorsdisplay)) { - return $icolorsdisplay[$status]; - } else { - return __('Unknown', 'monitor') . " ($status)"; - } + if (array_key_exists($status, $icolorsdisplay)) { + return $icolorsdisplay[$status]; + } else { + return __('Unknown', 'monitor') . " ($status)"; + } } /** @@ -613,405 +624,425 @@ function getHostStatusDescription($status) { * @param mixed $float * @param mixed $maxlen */ -function renderHost($host, $float = true, $maxlen = 10) { - global $thold_hosts, $config, $icolorsdisplay, $iclasses, $classes, $maxchars, $mon_zoom_state; - - // throw out tree root items - if (array_key_exists('name', $host)) { - return; - } - - if ($host['id'] <= 0) { - return; - } - - $host['anchor'] = $config['url_path'] . 'graph_view.php?action=preview&reset=1&host_id=' . $host['id']; - - if ($host['status'] == 3 && array_key_exists($host['id'], $thold_hosts)) { - $host['status'] = 4; - $host['anchor'] = $config['url_path'] . 'plugins/thold/thold_graph.php?action=thold&reset=true&status=1&host_id=' . $host['id']; - } - - $host['real_status'] = getHostStatus($host, true); - $host['status'] = getHostStatus($host); - $host['iclass'] = $iclasses[$host['status']]; - - $function = 'renderHost' . ucfirst(get_request_var('view')); - - if (function_exists($function)) { - // Call the custom render_host_ function - $result = $function($host); - } else { - $iclass = getStatusIcon($host['status'], $host['monitor_icon']); - $fclass = get_request_var('size'); - - $monitor_times = read_user_setting('monitor_uptime'); - $monitor_time_html = ''; - - if ($host['status'] <= 2 || $host['status'] == 5) { - if ($mon_zoom_state) { - $fclass = 'monitor_errorzoom'; - } - $tis = get_timeinstate($host); - - if ($monitor_times == 'on') { - $monitor_time_html = "
$tis"; - } - $result = "

" . title_trim(html_escape($host['description']), $maxlen) . "$monitor_time_html
"; - } else { - $tis = get_uptime($host); - - if ($monitor_times == 'on') { - $monitor_time_html = "
$tis
"; - } - - $result = "

" . title_trim(html_escape($host['description']), $maxlen) . "$monitor_time_html
"; - } - } - - return $result; +function renderHost($host, $float = true, $maxlen = 10) +{ + global $thold_hosts, $config, $icolorsdisplay, $iclasses, $classes, $maxchars, $mon_zoom_state; + + // throw out tree root items + if (array_key_exists('name', $host)) { + return; + } + + if ($host['id'] <= 0) { + return; + } + + $host['anchor'] = $config['url_path'] . 'graph_view.php?action=preview&reset=1&host_id=' . $host['id']; + + if ($host['status'] == 3 && array_key_exists($host['id'], $thold_hosts)) { + $host['status'] = 4; + $host['anchor'] = $config['url_path'] . 'plugins/thold/thold_graph.php?action=thold&reset=true&status=1&host_id=' . $host['id']; + } + + $host['real_status'] = getHostStatus($host, true); + $host['status'] = getHostStatus($host); + $host['iclass'] = $iclasses[$host['status']]; + + $function = 'renderHost' . ucfirst(get_request_var('view')); + + if (function_exists($function)) { + // Call the custom render_host_ function + $result = $function($host); + } else { + $iclass = getStatusIcon($host['status'], $host['monitor_icon']); + $fclass = get_request_var('size'); + + $monitor_times = read_user_setting('monitor_uptime'); + $monitor_time_html = ''; + + if ($host['status'] <= 2 || $host['status'] == 5) { + if ($mon_zoom_state) { + $fclass = 'monitor_errorzoom'; + } + $tis = get_timeinstate($host); + + if ($monitor_times == 'on') { + $monitor_time_html = "
$tis"; + } + $result = "

" . title_trim(html_escape($host['description']), $maxlen) . "$monitor_time_html
"; + } else { + $tis = get_uptime($host); + + if ($monitor_times == 'on') { + $monitor_time_html = "
$tis
"; + } + + $result = "

" . title_trim(html_escape($host['description']), $maxlen) . "$monitor_time_html
"; + } + } + + return $result; } -function getStatusIcon($status, $icon) { - global $fa_icons; - - if (($status == 1 || ($status == 4 && get_request_var('status') > 0)) && read_user_setting('monitor_sound') == 'First Orders Suite.mp3') { - return 'fab fa-first-order fa-spin mon_icon'; - } - - if ($icon != '' && array_key_exists($icon, $fa_icons)) { - if (isset($fa_icons[$icon]['class'])) { - return $fa_icons[$icon]['class'] . ' mon_icon'; - } else { - return "fa fa-$icon mon_icon"; - } - } else { - return 'fa fa-server' . ' mon_icon'; - } +function getStatusIcon($status, $icon) +{ + global $fa_icons; + + if (($status == 1 || ($status == 4 && get_request_var('status') > 0)) && read_user_setting('monitor_sound') == 'First Orders Suite.mp3') { + return 'fab fa-first-order fa-spin mon_icon'; + } + + if ($icon != '' && array_key_exists($icon, $fa_icons)) { + if (isset($fa_icons[$icon]['class'])) { + return $fa_icons[$icon]['class'] . ' mon_icon'; + } else { + return "fa fa-$icon mon_icon"; + } + } else { + return 'fa fa-server' . ' mon_icon'; + } } -function monitorPrintHostTime($status_time, $seconds = false) { - // If the host is down, make a downtime since message - $dt = ''; - - if (is_numeric($status_time)) { - $sfd = round($status_time / 100,0); - } else { - $sfd = time() - strtotime($status_time); - } - $dt_d = floor($sfd / 86400); - $dt_h = floor(($sfd - ($dt_d * 86400)) / 3600); - $dt_m = floor(($sfd - ($dt_d * 86400) - ($dt_h * 3600)) / 60); - $dt_s = $sfd - ($dt_d * 86400) - ($dt_h * 3600) - ($dt_m * 60); - - if ($dt_d > 0) { - $dt .= $dt_d . 'd:' . $dt_h . 'h:' . $dt_m . 'm' . ($seconds ? ':' . $dt_s . 's' : ''); - } elseif ($dt_h > 0) { - $dt .= $dt_h . 'h:' . $dt_m . 'm' . ($seconds ? ':' . $dt_s . 's' : ''); - } elseif ($dt_m > 0) { - $dt .= $dt_m . 'm' . ($seconds ? ':' . $dt_s . 's' : ''); - } else { - $dt .= ($seconds ? $dt_s . 's' : __('Just Up', 'monitor')); - } - - return $dt; +function monitorPrintHostTime($status_time, $seconds = false) +{ + // If the host is down, make a downtime since message + $dt = ''; + + if (is_numeric($status_time)) { + $sfd = round($status_time / 100, 0); + } else { + $sfd = time() - strtotime($status_time); + } + $dt_d = floor($sfd / 86400); + $dt_h = floor(($sfd - ($dt_d * 86400)) / 3600); + $dt_m = floor(($sfd - ($dt_d * 86400) - ($dt_h * 3600)) / 60); + $dt_s = $sfd - ($dt_d * 86400) - ($dt_h * 3600) - ($dt_m * 60); + + if ($dt_d > 0) { + $dt .= $dt_d . 'd:' . $dt_h . 'h:' . $dt_m . 'm' . ($seconds ? ':' . $dt_s . 's' : ''); + } elseif ($dt_h > 0) { + $dt .= $dt_h . 'h:' . $dt_m . 'm' . ($seconds ? ':' . $dt_s . 's' : ''); + } elseif ($dt_m > 0) { + $dt .= $dt_m . 'm' . ($seconds ? ':' . $dt_s . 's' : ''); + } else { + $dt .= ($seconds ? $dt_s . 's' : __('Just Up', 'monitor')); + } + + return $dt; } -function monitorTrim($string) { - return trim($string, "\"'\\ \n\t\r"); +function monitorTrim($string) +{ + return trim($string, "\"'\\ \n\t\r"); } -function renderHeaderDefault() { - return "
"; +function renderHeaderDefault() +{ + return "
"; } -function renderHeaderNames() { - return ""; +function renderHeaderNames() +{ + return "
"; } -function renderHeaderTiles() { - return renderHeaderDefault(); +function renderHeaderTiles() +{ + return renderHeaderDefault(); } -function renderHeaderTilesadt() { - return renderHeaderDefault(); +function renderHeaderTilesadt() +{ + return renderHeaderDefault(); } -function renderHeaderList($total_rows = 0, $rows = 0) { - $display_text = [ - 'hostname' => [ - 'display' => __('Hostname', 'monitor'), - 'sort' => 'ASC', - 'align' => 'left', 'tip' => __('Hostname of device', 'monitor') - ], - 'id' => [ - 'display' => __('ID', 'monitor'), - 'sort' => 'ASC', - 'align' => 'left' - ], - 'description' => [ - 'display' => __('Description', 'monitor'), - 'sort' => 'ASC', - 'align' => 'left' - ], - 'site_name' => [ - 'display' => __('Site', 'monitor'), - 'sort' => 'ASC', - 'align' => 'left' - ], - 'monitor_criticality' => [ - 'display' => __('Criticality', 'monitor'), - 'sort' => 'ASC', - 'align' => 'left' - ], - 'status' => [ - 'display' => __('Status', 'monitor'), - 'sort' => 'DESC', - 'align' => 'center' - ], - 'instate' => [ - 'display' => __('Length in Status', 'monitor'), - 'sort' => 'ASC', - 'align' => 'center' - ], - 'avg_time' => [ - 'display' => __('Averages', 'monitor'), - 'sort' => 'DESC', - 'align' => 'left' - ], - 'monitor_warn' => [ - 'display' => __('Warning', 'monitor'), - 'sort' => 'DESC', - 'align' => 'left' - ], - 'monitor_text' => [ - 'display' => __('Admin', 'monitor'), - 'sort' => 'ASC', - 'tip' => __('Monitor Text Column represents \'Admin\'', 'monitor'), - 'align' => 'left' - ], - 'notes' => [ - 'display' => __('Notes', 'monitor'), - 'sort' => 'ASC', - 'align' => 'left' - ], - 'availability' => [ - 'display' => __('Availability', 'monitor'), - 'sort' => 'DESC', - 'align' => 'right' - ], - 'status_fail_date' => [ - 'display' => __('Last Fail', 'monitor'), - 'sort' => 'DESC', - 'align' => 'right' - ], - ]; - - ob_start(); - - $nav = html_nav_bar('monitor.php?rfilter=' . get_request_var('rfilter'), MAX_DISPLAY_PAGES, get_request_var('page'), $rows, $total_rows, 12, __('Devices'), 'page', 'main'); - - html_start_box(__('Monitored Devices', 'monitor'), '100%', false, '3', 'center', ''); - - print $nav; - - html_header_sort($display_text, get_request_var('sort_column'), get_request_var('sort_direction'), false); - - $output = ob_get_contents(); - - ob_end_clean(); - - return $output; +function renderHeaderList($total_rows = 0, $rows = 0) +{ + $display_text = [ + 'hostname' => [ + 'display' => __('Hostname', 'monitor'), + 'sort' => 'ASC', + 'align' => 'left', 'tip' => __('Hostname of device', 'monitor') + ], + 'id' => [ + 'display' => __('ID', 'monitor'), + 'sort' => 'ASC', + 'align' => 'left' + ], + 'description' => [ + 'display' => __('Description', 'monitor'), + 'sort' => 'ASC', + 'align' => 'left' + ], + 'site_name' => [ + 'display' => __('Site', 'monitor'), + 'sort' => 'ASC', + 'align' => 'left' + ], + 'monitor_criticality' => [ + 'display' => __('Criticality', 'monitor'), + 'sort' => 'ASC', + 'align' => 'left' + ], + 'status' => [ + 'display' => __('Status', 'monitor'), + 'sort' => 'DESC', + 'align' => 'center' + ], + 'instate' => [ + 'display' => __('Length in Status', 'monitor'), + 'sort' => 'ASC', + 'align' => 'center' + ], + 'avg_time' => [ + 'display' => __('Averages', 'monitor'), + 'sort' => 'DESC', + 'align' => 'left' + ], + 'monitor_warn' => [ + 'display' => __('Warning', 'monitor'), + 'sort' => 'DESC', + 'align' => 'left' + ], + 'monitor_text' => [ + 'display' => __('Admin', 'monitor'), + 'sort' => 'ASC', + 'tip' => __('Monitor Text Column represents \'Admin\'', 'monitor'), + 'align' => 'left' + ], + 'notes' => [ + 'display' => __('Notes', 'monitor'), + 'sort' => 'ASC', + 'align' => 'left' + ], + 'availability' => [ + 'display' => __('Availability', 'monitor'), + 'sort' => 'DESC', + 'align' => 'right' + ], + 'status_fail_date' => [ + 'display' => __('Last Fail', 'monitor'), + 'sort' => 'DESC', + 'align' => 'right' + ], + ]; + + ob_start(); + + $nav = html_nav_bar('monitor.php?rfilter=' . get_request_var('rfilter'), MAX_DISPLAY_PAGES, get_request_var('page'), $rows, $total_rows, 12, __('Devices'), 'page', 'main'); + + html_start_box(__('Monitored Devices', 'monitor'), '100%', false, '3', 'center', ''); + + print $nav; + + html_header_sort($display_text, get_request_var('sort_column'), get_request_var('sort_direction'), false); + + $output = ob_get_contents(); + + ob_end_clean(); + + return $output; } -function renderSuppressgroupsList() { - return true; +function renderSuppressgroupsList() +{ + return true; } -function renderFooterDefault() { - return ''; +function renderFooterDefault() +{ + return ''; } -function renderFooterNames() { - $col = 7 - $_SESSION['names']; +function renderFooterNames() +{ + $col = 7 - $_SESSION['names']; - if ($col == 0) { - return '
'; - } else { - return ''; - } + if ($col == 0) { + return ''; + } else { + return ''; + } } -function renderFooterTiles() { - return renderFooterDefault(); +function renderFooterTiles() +{ + return renderFooterDefault(); } -function renderFooterTilesadt() { - return renderFooterDefault(); +function renderFooterTilesadt() +{ + return renderFooterDefault(); } -function renderFooterList($total_rows, $rows) { - ob_start(); +function renderFooterList($total_rows, $rows) +{ + ob_start(); - html_end_box(false); + html_end_box(false); - if ($total_rows > 0) { - $nav = html_nav_bar('monitor.php?rfilter=' . get_request_var('rfilter'), MAX_DISPLAY_PAGES, get_request_var('page'), $rows, $total_rows, 12, __('Devices'), 'page', 'main'); + if ($total_rows > 0) { + $nav = html_nav_bar('monitor.php?rfilter=' . get_request_var('rfilter'), MAX_DISPLAY_PAGES, get_request_var('page'), $rows, $total_rows, 12, __('Devices'), 'page', 'main'); - print $nav; - } + print $nav; + } - $output = ob_get_contents(); + $output = ob_get_contents(); - ob_end_clean(); + ob_end_clean(); - return $output; + return $output; } -function renderHostList($host) { - global $criticalities, $iclasses; +function renderHostList($host) +{ + global $criticalities, $iclasses; - if ($host['status'] < 2 || $host['status'] == 5) { - $dt = get_timeinstate($host); - } elseif (strtotime($host['status_rec_date']) > 192800) { - $dt = get_timeinstate($host); - } else { - $dt = __('Never', 'monitor'); - } + if ($host['status'] < 2 || $host['status'] == 5) { + $dt = get_timeinstate($host); + } elseif (strtotime($host['status_rec_date']) > 192800) { + $dt = get_timeinstate($host); + } else { + $dt = __('Never', 'monitor'); + } - if ($host['status'] < 3 || $host['status'] == 5) { - $host_admin = $host['monitor_text']; - } else { - $host_admin = ''; - } + if ($host['status'] < 3 || $host['status'] == 5) { + $host_admin = $host['monitor_text']; + } else { + $host_admin = ''; + } - if (isset($host['monitor_criticality']) && $host['monitor_criticality'] > 0) { - $host_crit = $criticalities[$host['monitor_criticality']]; - } else { - $host_crit = ''; - } + if (isset($host['monitor_criticality']) && $host['monitor_criticality'] > 0) { + $host_crit = $criticalities[$host['monitor_criticality']]; + } else { + $host_crit = ''; + } - if ($host['availability_method'] > 0) { - $host_avg = __('%d ms', $host['cur_time'], 'monitor') . ' / ' . __('%d ms', $host['avg_time'], 'monitor'); - } else { - $host_avg = __('N/A', 'monitor'); - } + if ($host['availability_method'] > 0) { + $host_avg = __('%d ms', $host['cur_time'], 'monitor') . ' / ' . __('%d ms', $host['avg_time'], 'monitor'); + } else { + $host_avg = __('N/A', 'monitor'); + } - if (isset($host['monitor_warn']) && ($host['monitor_warn'] > 0 || $host['monitor_alert'] > 0)) { - $host_warn = __('%0.2d ms', $host['monitor_warn'], 'monitor') . ' / ' . __('%0.2d ms', $host['monitor_alert'], 'monitor'); - } else { - $host_warn = ''; - } + if (isset($host['monitor_warn']) && ($host['monitor_warn'] > 0 || $host['monitor_alert'] > 0)) { + $host_warn = __('%0.2d ms', $host['monitor_warn'], 'monitor') . ' / ' . __('%0.2d ms', $host['monitor_alert'], 'monitor'); + } else { + $host_warn = ''; + } - if (strtotime($host['status_fail_date']) < 86400) { - $host['status_fail_date'] = __('Never', 'monitor'); - } + if (strtotime($host['status_fail_date']) < 86400) { + $host['status_fail_date'] = __('Never', 'monitor'); + } - $host_datefail = $host['status_fail_date']; + $host_datefail = $host['status_fail_date']; - $iclass = $iclasses[$host['status']]; - $sdisplay = getHostStatusDescription($host['real_status']); + $iclass = $iclasses[$host['status']]; + $sdisplay = getHostStatusDescription($host['real_status']); - $row_class = "{$iclass}Full"; + $row_class = "{$iclass}Full"; - ob_start(); + ob_start(); - print ""; + print ""; - $url = $host['anchor']; + $url = $host['anchor']; - form_selectable_cell(filter_value($host['hostname'], '', $url), $host['id'], '', 'left'); - form_selectable_cell($host['id'], $host['id'], '', 'left'); - form_selectable_cell($host['description'], $host['id'], '', 'left'); - form_selectable_cell($host['site_name'], $host['id'], '', 'left'); - form_selectable_cell($host_crit, $host['id'], '', 'left'); - form_selectable_cell($sdisplay, $host['id'], '', 'center'); - form_selectable_cell($dt, $host['id'], '', 'center'); - form_selectable_cell($host_avg, $host['id'], '', 'left'); - form_selectable_cell($host_warn, $host['id'], '', 'left'); - form_selectable_cell($host_admin, $host['id'], '', 'white-space:pre-wrap;text-align:left'); - form_selectable_cell(str_replace(["\n", "\r"], [' ', ''], $host['notes']), $host['id'], '', 'white-space:pre-wrap;text-align:left'); - form_selectable_cell(round($host['availability'],2) . ' %', $host['id'], '', 'right'); - form_selectable_cell($host_datefail, $host['id'], '', 'right'); + form_selectable_cell(filter_value($host['hostname'], '', $url), $host['id'], '', 'left'); + form_selectable_cell($host['id'], $host['id'], '', 'left'); + form_selectable_cell($host['description'], $host['id'], '', 'left'); + form_selectable_cell($host['site_name'], $host['id'], '', 'left'); + form_selectable_cell($host_crit, $host['id'], '', 'left'); + form_selectable_cell($sdisplay, $host['id'], '', 'center'); + form_selectable_cell($dt, $host['id'], '', 'center'); + form_selectable_cell($host_avg, $host['id'], '', 'left'); + form_selectable_cell($host_warn, $host['id'], '', 'left'); + form_selectable_cell($host_admin, $host['id'], '', 'white-space:pre-wrap;text-align:left'); + form_selectable_cell(str_replace(["\n", "\r"], [' ', ''], $host['notes']), $host['id'], '', 'white-space:pre-wrap;text-align:left'); + form_selectable_cell(round($host['availability'], 2) . ' %', $host['id'], '', 'right'); + form_selectable_cell($host_datefail, $host['id'], '', 'right'); - form_end_row(); + form_end_row(); - $result = ob_get_contents(); + $result = ob_get_contents(); - ob_end_clean(); + ob_end_clean(); - return $result; + return $result; } -function renderHostNames($host) { - $fclass = get_request_var('size'); +function renderHostNames($host) +{ + $fclass = get_request_var('size'); - $result = ''; + $result = ''; - $maxlen = getMonitorTrimLength(100); + $maxlen = getMonitorTrimLength(100); - if ($_SESSION['names'] == 0) { - $result .= ''; - } + if ($_SESSION['names'] == 0) { + $result .= ''; + } - if ($host['status'] <= 2 || $host['status'] == 5) { - $result .= "" . title_trim(html_escape($host['description']), $maxlen) . ''; - } else { - $result .= "" . title_trim(html_escape($host['description']), $maxlen) . ''; - } + if ($host['status'] <= 2 || $host['status'] == 5) { + $result .= "" . title_trim(html_escape($host['description']), $maxlen) . ''; + } else { + $result .= "" . title_trim(html_escape($host['description']), $maxlen) . ''; + } - $_SESSION['names']++; + $_SESSION['names']++; - if ($_SESSION['names'] > 7) { - $result .= ''; - $_SESSION['names'] = 0; - } + if ($_SESSION['names'] > 7) { + $result .= ''; + $_SESSION['names'] = 0; + } - return $result; + return $result; } -function renderHostTiles($host) { - $class = getStatusIcon($host['status'], $host['monitor_icon']); - $fclass = get_request_var('size'); +function renderHostTiles($host) +{ + $class = getStatusIcon($host['status'], $host['monitor_icon']); + $fclass = get_request_var('size'); - return "
"; + return "
"; } -function renderHostTilesadt($host) { - $tis = ''; +function renderHostTilesadt($host) +{ + $tis = ''; - $class = getStatusIcon($host['status'], $host['monitor_icon']); - $fclass = get_request_var('size'); + $class = getStatusIcon($host['status'], $host['monitor_icon']); + $fclass = get_request_var('size'); - if ($host['status'] < 2 || $host['status'] == 5) { - $tis = get_timeinstate($host); + if ($host['status'] < 2 || $host['status'] == 5) { + $tis = get_timeinstate($host); - return ""; - } else { - $tis = get_uptime($host); + return ""; + } else { + $tis = get_uptime($host); - return ""; - } + return ""; + } } -function getMonitorTrimLength($fieldlen) { - global $maxchars; +function getMonitorTrimLength($fieldlen) +{ + global $maxchars; - if (get_request_var('view') == 'default' || get_request_var('view') == 'names') { - $maxlen = $maxchars; + if (get_request_var('view') == 'default' || get_request_var('view') == 'names') { + $maxlen = $maxchars; - if (get_request_var('trim') < 0) { - $maxlen = 4000; - } elseif (get_request_var('trim') > 0) { - $maxlen = get_request_var('trim'); - } + if (get_request_var('trim') < 0) { + $maxlen = 4000; + } elseif (get_request_var('trim') > 0) { + $maxlen = get_request_var('trim'); + } - if ($fieldlen > $maxlen) { - $fieldlen = $maxlen; - } - } + if ($fieldlen > $maxlen) { + $fieldlen = $maxlen; + } + } - return $fieldlen; + return $fieldlen; } diff --git a/poller_functions.php b/poller_functions.php index 37d06a5..18d3246 100644 --- a/poller_functions.php +++ b/poller_functions.php @@ -1,4 +1,5 @@ 0 && isset($notification_lists[$notify_list])) { $emails = explode(',', $notification_lists[$notify_list]); monitorAddEmails($reboot_emails, $emails, $host_id); @@ -61,7 +64,8 @@ function monitorAddNotificationList(&$reboot_emails, $notify_list, $host_id, $no * * @return array */ -function getAlertEmails() { +function getAlertEmails() +{ $alert_email = read_config_option('alert_email'); return ($alert_email != '') ? explode(',', $alert_email) : []; @@ -74,7 +78,8 @@ function getAlertEmails() { * * @return void */ -function purgeOrphanMonitorRows($table_name) { +function purgeOrphanMonitorRows($table_name) +{ $removed_hosts = db_fetch_assoc("SELECT mu.host_id FROM $table_name AS mu LEFT JOIN host AS h @@ -95,7 +100,8 @@ function purgeOrphanMonitorRows($table_name) { * * @return array */ -function getRebootedHosts() { +function getRebootedHosts() +{ return db_fetch_assoc('SELECT h.id, h.description, h.hostname, h.snmp_sysUpTimeInstance, mu.uptime FROM host AS h @@ -114,12 +120,14 @@ function getRebootedHosts() { * * @return array */ -function getNotificationListsMap() { +function getNotificationListsMap() +{ return array_rekey( db_fetch_assoc('SELECT id, emails FROM plugin_notification_lists ORDER BY id'), - 'id', 'emails' + 'id', + 'emails' ); } @@ -133,11 +141,14 @@ function getNotificationListsMap() { * * @return void */ -function addTholdRebootRecipients(&$reboot_emails, $host_id, $alert_emails, $notification_lists) { - $notify = db_fetch_row_prepared('SELECT thold_send_email, thold_host_email +function addTholdRebootRecipients(&$reboot_emails, $host_id, $alert_emails, $notification_lists) +{ + $notify = db_fetch_row_prepared( + 'SELECT thold_send_email, thold_host_email FROM host WHERE id = ?', - [$host_id]); + [$host_id] + ); if (!cacti_sizeof($notify)) { return; @@ -170,17 +181,20 @@ function addTholdRebootRecipients(&$reboot_emails, $host_id, $alert_emails, $not * * @return array */ -function buildRebootEmailMap($rebooted_hosts, $alert_emails) { +function buildRebootEmailMap($rebooted_hosts, $alert_emails) +{ $reboot_emails = []; $notification_lists = getNotificationListsMap(); $monitor_list = read_config_option('monitor_list'); $monitor_thold = read_config_option('monitor_reboot_thold'); foreach ($rebooted_hosts as $host) { - db_execute_prepared('INSERT INTO plugin_monitor_reboot_history + db_execute_prepared( + 'INSERT INTO plugin_monitor_reboot_history (host_id, reboot_time) VALUES (?, ?)', - [$host['id'], date(MONITOR_DATE_TIME_FORMAT, time() - intval($host['snmp_sysUpTimeInstance']))]); + [$host['id'], date(MONITOR_DATE_TIME_FORMAT, time() - intval($host['snmp_sysUpTimeInstance']))] + ); monitorAddNotificationList($reboot_emails, $monitor_list, $host['id'], $notification_lists); @@ -199,7 +213,8 @@ function buildRebootEmailMap($rebooted_hosts, $alert_emails) { * * @return void */ -function sendRebootNotifications($reboot_emails) { +function sendRebootNotifications($reboot_emails) +{ $monitor_send_one_email = read_config_option('monitor_send_one_email'); if (!cacti_sizeof($reboot_emails)) { @@ -236,7 +251,8 @@ function sendRebootNotifications($reboot_emails) { * * @return array{int, int} Reboot count and recent down count. */ -function monitorUptimeChecker() { +function monitorUptimeChecker() +{ monitorDebug('Checking for Uptime of Devices'); $alert_emails = getAlertEmails(); @@ -284,7 +300,8 @@ function monitorUptimeChecker() { * * @return array{string, string, array} */ -function buildRebootDetails($hosts) { +function buildRebootDetails($hosts) +{ $body_txt = ''; $last_host = []; @@ -296,10 +313,12 @@ function buildRebootDetails($hosts) { $body .= '' . PHP_EOL; foreach ($hosts as $host_id) { - $host = db_fetch_row_prepared('SELECT description, hostname + $host = db_fetch_row_prepared( + 'SELECT description, hostname FROM host WHERE id = ?', - [$host_id]); + [$host_id] + ); if (!cacti_sizeof($host)) { continue; @@ -329,7 +348,8 @@ function buildRebootDetails($hosts) { * * @return string */ -function buildRebootSubject($hosts, $last_host) { +function buildRebootSubject($hosts, $last_host) +{ $subject = read_config_option('monitor_subject'); $monitor_send_one_email = read_config_option('monitor_send_one_email'); @@ -352,7 +372,8 @@ function buildRebootSubject($hosts, $last_host) { * * @return array{string, string, array} */ -function prepareReportOutput($body, $body_txt) { +function prepareReportOutput($body, $body_txt) +{ $output = ''; $report_tag = ''; @@ -395,7 +416,8 @@ function prepareReportOutput($body, $body_txt) { * * @return void */ -function processRebootEmail($email, $hosts) { +function processRebootEmail($email, $hosts) +{ monitorDebug("Reboot Processing for $email starting"); [$body, $body_txt, $last_host] = buildRebootDetails($hosts); @@ -428,7 +450,8 @@ function processRebootEmail($email, $hosts) { * * @return array{array, array} */ -function collectNotificationHosts($lists, $global_list, $notify_list) { +function collectNotificationHosts($lists, $global_list, $notify_list) +{ $alert_hosts = []; $warn_hosts = []; @@ -465,7 +488,8 @@ function collectNotificationHosts($lists, $global_list, $notify_list) { * * @return void */ -function normalizeAndLogNotificationHosts(&$alert_hosts, &$warn_hosts) { +function normalizeAndLogNotificationHosts(&$alert_hosts, &$warn_hosts) +{ if (cacti_sizeof($alert_hosts)) { $alert_hosts = array_unique($alert_hosts, SORT_NUMERIC); logMessages('alert', $alert_hosts); @@ -484,7 +508,8 @@ function normalizeAndLogNotificationHosts(&$alert_hosts, &$warn_hosts) { * * @return array{string, string} */ -function buildPingNotificationIntro($freq) { +function buildPingNotificationIntro($freq) +{ $body = '

' . __(MONITOR_PING_NOTIFICATION_SUBJECT, 'monitor') . '

' . PHP_EOL; $body_txt = __(MONITOR_PING_NOTIFICATION_SUBJECT, 'monitor') . PHP_EOL; @@ -519,7 +544,8 @@ function buildPingNotificationIntro($freq) { * * @return void */ -function appendThresholdSection(&$body, &$body_txt, $host_ids, $criticalities, $section_text, $threshold_field) { +function appendThresholdSection(&$body, &$body_txt, $host_ids, $criticalities, $section_text, $threshold_field) +{ global $config; if (!cacti_sizeof($host_ids)) { @@ -554,15 +580,15 @@ function appendThresholdSection(&$body, &$body_txt, $host_ids, $criticalities, $ $body .= '' . PHP_EOL; $body .= '' . $host['description'] . '' . PHP_EOL; $body .= '' . $criticalities[$host['monitor_criticality']] . '' . PHP_EOL; - $body .= '' . number_format_i18n($host[$threshold_field],2) . ' ms' . PHP_EOL; - $body .= '' . number_format_i18n($host['cur_time'],2) . ' ms' . PHP_EOL; + $body .= '' . number_format_i18n($host[$threshold_field], 2) . ' ms' . PHP_EOL; + $body .= '' . number_format_i18n($host['cur_time'], 2) . ' ms' . PHP_EOL; $body .= '' . PHP_EOL; $body_txt .= $host['description'] . "\t" . $criticalities[$host['monitor_criticality']] . "\t" . - number_format_i18n($host[$threshold_field],2) . " ms\t" . - number_format_i18n($host['cur_time'],2) . ' ms' . PHP_EOL; + number_format_i18n($host[$threshold_field], 2) . " ms\t" . + number_format_i18n($host['cur_time'], 2) . ' ms' . PHP_EOL; } } @@ -577,7 +603,8 @@ function appendThresholdSection(&$body, &$body_txt, $host_ids, $criticalities, $ * * @return string */ -function buildNotificationStatus($alert_hosts, $warn_hosts) { +function buildNotificationStatus($alert_hosts, $warn_hosts) +{ $status = ''; if (cacti_sizeof($alert_hosts)) { @@ -605,7 +632,8 @@ function buildNotificationStatus($alert_hosts, $warn_hosts) { * * @return void */ -function processEmail($email, $lists, $global_list, $notify_list) { +function processEmail($email, $lists, $global_list, $notify_list) +{ monitorDebug('Into Processing'); $criticalities = [ @@ -668,7 +696,8 @@ function processEmail($email, $lists, $global_list, $notify_list) { * * @return void */ -function processSendEmail($email, $subject, $output, $toutput, $headers, $status) { +function processSendEmail($email, $subject, $output, $toutput, $headers, $status) +{ $from_email = read_config_option('monitor_fromemail'); if ($from_email == '') { @@ -728,7 +757,8 @@ function processSendEmail($email, $subject, $output, $toutput, $headers, $status * * @return string */ -function monitorText($output) { +function monitorText($output) +{ $output = explode(PHP_EOL, $output); $new_output = ''; @@ -753,7 +783,8 @@ function monitorText($output) { * * @return void */ -function logMessages($type, $alert_hosts) { +function logMessages($type, $alert_hosts) +{ global $start_date; static $processed = []; @@ -768,14 +799,16 @@ function logMessages($type, $alert_hosts) { foreach ($alert_hosts as $id) { if (!isset($processed[$id])) { - db_execute_prepared("INSERT INTO plugin_monitor_notify_history + db_execute_prepared( + "INSERT INTO plugin_monitor_notify_history (host_id, notify_type, ping_time, ping_threshold, notification_time) SELECT id, '$type' AS notify_type, cur_time, $column, '$start_date' AS notification_time FROM host WHERE deleted = '' AND monitor = 'on' AND id = ?", - [$id]); + [$id] + ); } $processed[$id] = true; @@ -793,7 +826,8 @@ function logMessages($type, $alert_hosts) { * * @return void */ -function addGroupedNotificationEntry($type, $entry, &$global_list, &$notify_list, &$lists) { +function addGroupedNotificationEntry($type, $entry, &$global_list, &$notify_list, &$lists) +{ if ($entry['thold_send_email'] == '1' || $entry['thold_send_email'] == '3') { $global_list[$type][] = $entry; } @@ -815,10 +849,12 @@ function addGroupedNotificationEntry($type, $entry, &$global_list, &$notify_list * * @return void */ -function getHostsByListType($type, $criticality, &$global_list, &$notify_list, &$lists) { +function getHostsByListType($type, $criticality, &$global_list, &$notify_list, &$lists) +{ $last_time = date(MONITOR_DATE_TIME_FORMAT, time() - read_config_option('monitor_resend_frequency') * 60); - $hosts = db_fetch_cell_prepared("SELECT COUNT(*) + $hosts = db_fetch_cell_prepared( + "SELECT COUNT(*) FROM host WHERE status = 3 AND deleted = '' @@ -826,7 +862,8 @@ function getHostsByListType($type, $criticality, &$global_list, &$notify_list, & AND thold_send_email > 0 AND monitor_criticality >= ? AND cur_time > monitor_$type", - [$criticality]); + [$criticality] + ); if ($hosts <= 0) { return; @@ -834,7 +871,8 @@ function getHostsByListType($type, $criticality, &$global_list, &$notify_list, & $htype = ($type == 'warn') ? 1 : 0; - $groups = db_fetch_assoc_prepared("SELECT + $groups = db_fetch_assoc_prepared( + "SELECT thold_send_email, thold_host_email, GROUP_CONCAT(host.id) AS id FROM host LEFT JOIN ( @@ -854,7 +892,8 @@ function getHostsByListType($type, $criticality, &$global_list, &$notify_list, & AND host.total_polls > 1 GROUP BY thold_host_email, thold_send_email ORDER BY thold_host_email, thold_send_email', - [$htype, $criticality, $last_time]); + [$htype, $criticality, $last_time] + ); if (!cacti_sizeof($groups)) { return; @@ -872,7 +911,8 @@ function getHostsByListType($type, $criticality, &$global_list, &$notify_list, & * * @return string */ -function flattenGroupSeverityList($list) { +function flattenGroupSeverityList($list) +{ $flattened = ''; foreach ($list as $item) { @@ -889,7 +929,8 @@ function flattenGroupSeverityList($list) { * * @return array */ -function flattenNotifySeverityLists($lists) { +function flattenNotifySeverityLists($lists) +{ $flattened = []; foreach ($lists as $id => $list) { @@ -907,7 +948,8 @@ function flattenNotifySeverityLists($lists) { * * @return void */ -function flattenLists(&$global_list, &$notify_list) { +function flattenLists(&$global_list, &$notify_list) +{ if (cacti_sizeof($global_list)) { $new_global = []; @@ -938,7 +980,8 @@ function flattenLists(&$global_list, &$notify_list) { * * @return void */ -function addEmailsToNotificationMap(&$notification_emails, $emails, $scope_key) { +function addEmailsToNotificationMap(&$notification_emails, $emails, $scope_key) +{ foreach ($emails as $user) { $user = trim($user); @@ -955,7 +998,8 @@ function addEmailsToNotificationMap(&$notification_emails, $emails, $scope_key) * * @return array */ -function getEmailsAndLists($lists) { +function getEmailsAndLists($lists) +{ $notification_emails = []; $alert_email = read_config_option('alert_email'); @@ -989,7 +1033,8 @@ function getEmailsAndLists($lists) { * * @return array{int, int} Purged notify count and purged reboot count. */ -function purgeEventRecords() { +function purgeEventRecords() +{ // Purge old records $days = read_config_option('monitor_log_storage'); @@ -997,15 +1042,19 @@ function purgeEventRecords() { $days = 120; } - db_execute_prepared('DELETE FROM plugin_monitor_notify_history + db_execute_prepared( + 'DELETE FROM plugin_monitor_notify_history WHERE notification_time < FROM_UNIXTIME(UNIX_TIMESTAMP() - (? * 86400))', - [$days]); + [$days] + ); $purge_n = db_affected_rows(); - db_execute_prepared('DELETE FROM plugin_monitor_reboot_history + db_execute_prepared( + 'DELETE FROM plugin_monitor_reboot_history WHERE log_time < FROM_UNIXTIME(UNIX_TIMESTAMP() - (? * 86400))', - [$days]); + [$days] + ); $purge_r = db_affected_rows(); @@ -1019,7 +1068,8 @@ function purgeEventRecords() { * * @return void */ -function monitorDebug($message) { +function monitorDebug($message) +{ global $debug; if ($debug) { @@ -1032,7 +1082,8 @@ function monitorDebug($message) { * * @return void */ -function displayVersion() { +function displayVersion() +{ global $config; if (!function_exists('pluginMonitorVersion')) { @@ -1048,7 +1099,8 @@ function displayVersion() { * * @return void */ -function displayHelp() { +function displayHelp() +{ displayVersion(); print PHP_EOL; diff --git a/poller_monitor.php b/poller_monitor.php index 2641dc0..0554a41 100644 --- a/poller_monitor.php +++ b/poller_monitor.php @@ -1,4 +1,5 @@ __('Any', 'monitor'), - '0' => __('None', 'monitor'), - '1' => __('Low', 'monitor'), - '2' => __('Medium', 'monitor'), - '3' => __('High', 'monitor'), - '4' => __('Mission Critical', 'monitor') - ]; - - $filters['criticality'] = [ - 'friendly_name' => __('Criticality', 'monitor'), - 'method' => 'drop_array', - 'filter' => FILTER_VALIDATE_INT, - 'pageset' => true, - 'default' => '-1', - 'array' => $criticalities, - 'value' => '-1' - ]; - - return $filters; +function monitorDeviceFilters($filters) +{ + $criticalities = [ + '-1' => __('Any', 'monitor'), + '0' => __('None', 'monitor'), + '1' => __('Low', 'monitor'), + '2' => __('Medium', 'monitor'), + '3' => __('High', 'monitor'), + '4' => __('Mission Critical', 'monitor') + ]; + + $filters['criticality'] = [ + 'friendly_name' => __('Criticality', 'monitor'), + 'method' => 'drop_array', + 'filter' => FILTER_VALIDATE_INT, + 'pageset' => true, + 'default' => '-1', + 'array' => $criticalities, + 'value' => '-1' + ]; + + return $filters; } -function monitorDeviceSqlWhere($sql_where) { - if (get_request_var('criticality') >= 0) { - $sql_where .= ($sql_where != '' ? ' AND ' : 'WHERE ') . ' monitor_criticality = ' . get_request_var('criticality'); - } +function monitorDeviceSqlWhere($sql_where) +{ + if (get_request_var('criticality') >= 0) { + $sql_where .= ($sql_where != '' ? ' AND ' : 'WHERE ') . ' monitor_criticality = ' . get_request_var('criticality'); + } - return $sql_where; + return $sql_where; } -function monitorDeviceTableBottom() { - $criticalities = [ - '-1' => __('Any', 'monitor'), - '0' => __('None', 'monitor'), - '1' => __('Low', 'monitor'), - '2' => __('Medium', 'monitor'), - '3' => __('High', 'monitor'), - '4' => __('Mission Critical', 'monitor') - ]; - - if (version_compare(CACTI_VERSION, '1.3.0', '<')) { - $select = '' . __('Criticality') . ''; - - ?> +function monitorDeviceTableBottom() +{ + $criticalities = [ + '-1' => __('Any', 'monitor'), + '0' => __('None', 'monitor'), + '1' => __('Low', 'monitor'), + '2' => __('Medium', 'monitor'), + '3' => __('High', 'monitor'), + '4' => __('Mission Critical', 'monitor') + ]; + + if (version_compare(CACTI_VERSION, '1.3.0', '<')) { + $select = '' . __('Criticality') . ''; + + ?> 300) { - set_config_option('monitor_refresh', '300'); - } + if ($r == '' || $r < 1 || $r > 300) { + set_config_option('monitor_refresh', '300'); + } - return true; + return true; } -function pluginMonitorUpgrade() { - // Here we will upgrade to the newest version - monitorCheckUpgrade(); +function pluginMonitorUpgrade() +{ + // Here we will upgrade to the newest version + monitorCheckUpgrade(); - return false; + return false; } -function monitorCheckUpgrade() { - $files = ['plugins.php', 'monitor.php']; +function monitorCheckUpgrade() +{ + $files = ['plugins.php', 'monitor.php']; - if (isset($_SERVER['PHP_SELF']) && !in_array(basename($_SERVER['PHP_SELF']), $files, true)) { - return; - } + if (isset($_SERVER['PHP_SELF']) && !in_array(basename($_SERVER['PHP_SELF']), $files, true)) { + return; + } - $info = pluginMonitorVersion(); - $current = $info['version']; - $old = db_fetch_cell('SELECT version FROM plugin_config WHERE directory = "monitor"'); + $info = pluginMonitorVersion(); + $current = $info['version']; + $old = db_fetch_cell('SELECT version FROM plugin_config WHERE directory = "monitor"'); - if ($current != $old) { - monitorSetupTable(); + if ($current != $old) { + monitorSetupTable(); - api_plugin_register_hook('monitor', 'page_head', 'pluginMonitorPageHead', 'setup.php', 1); + api_plugin_register_hook('monitor', 'page_head', 'pluginMonitorPageHead', 'setup.php', 1); - db_execute('ALTER TABLE host MODIFY COLUMN monitor char(3) DEFAULT "on"'); + db_execute('ALTER TABLE host MODIFY COLUMN monitor char(3) DEFAULT "on"'); - db_execute('ALTER TABLE plugin_monitor_uptime + db_execute('ALTER TABLE plugin_monitor_uptime MODIFY COLUMN uptime BIGINT unsigned NOT NULL default "0"'); - api_plugin_db_add_column('monitor', 'host', ['name' => 'monitor_icon', 'type' => 'varchar(30)', 'NULL' => false, 'default' => '', 'after' => 'monitor_alert']); + api_plugin_db_add_column('monitor', 'host', ['name' => 'monitor_icon', 'type' => 'varchar(30)', 'NULL' => false, 'default' => '', 'after' => 'monitor_alert']); - if (function_exists('api_plugin_upgrade_register')) { - api_plugin_upgrade_register('monitor'); - } else { - db_execute_prepared('UPDATE plugin_config + if (function_exists('api_plugin_upgrade_register')) { + api_plugin_upgrade_register('monitor'); + } else { + db_execute_prepared( + 'UPDATE plugin_config SET version = ?, name = ?, author = ?, webpage = ? WHERE directory = ?', - [ - $info['version'], - $info['longname'], - $info['author'], - $info['homepage'], - $info['name'] - ] - ); - } - } + [ + $info['version'], + $info['longname'], + $info['author'], + $info['homepage'], + $info['name'] + ] + ); + } + } } -function pluginMonitorVersion() { - global $config; - $info = parse_ini_file($config['base_path'] . '/plugins/monitor/INFO', true); +function pluginMonitorVersion() +{ + global $config; + $info = parse_ini_file($config['base_path'] . '/plugins/monitor/INFO', true); - return $info['info']; + return $info['info']; } -function monitorDeviceActionExecute($action) { - global $config, $fields_host_edit; +function monitorDeviceActionExecute($action) +{ + global $config, $fields_host_edit; - if ($action != 'monitor_enable' && $action != 'monitor_disable' && $action != 'monitor_settings') { - return $action; - } + if ($action != 'monitor_enable' && $action != 'monitor_disable' && $action != 'monitor_settings') { + return $action; + } - $selected_items = sanitize_unserialize_selected_items(get_nfilter_request_var('selected_items')); + $selected_items = sanitize_unserialize_selected_items(get_nfilter_request_var('selected_items')); - if ($selected_items != false) { - if ($action == 'monitor_enable' || $action == 'monitor_disable') { - for ($i = 0; ($i < count($selected_items)); $i++) { - if ($action == 'monitor_enable') { - db_execute_prepared('UPDATE host + if ($selected_items != false) { + if ($action == 'monitor_enable' || $action == 'monitor_disable') { + for ($i = 0; ($i < count($selected_items)); $i++) { + if ($action == 'monitor_enable') { + db_execute_prepared( + 'UPDATE host SET monitor = "on" WHERE deleted = "" AND id = ?', - [$selected_items[$i]]); - } elseif ($action == 'monitor_disable') { - db_execute_prepared('UPDATE host + [$selected_items[$i]] + ); + } elseif ($action == 'monitor_disable') { + db_execute_prepared( + 'UPDATE host SET monitor = "" WHERE deleted = "" AND id = ?', - [$selected_items[$i]]); - } - } - } else { - for ($i = 0; ($i < count($selected_items)); $i++) { - reset($fields_host_edit); - - foreach ($fields_host_edit as $field_name => $field_array) { - if (isset_request_var("t_$field_name")) { - if ($field_name == 'monitor_alert_baseline') { - $cur_time = db_fetch_cell_prepared('SELECT cur_time + [$selected_items[$i]] + ); + } + } + } else { + for ($i = 0; ($i < count($selected_items)); $i++) { + reset($fields_host_edit); + + foreach ($fields_host_edit as $field_name => $field_array) { + if (isset_request_var("t_$field_name")) { + if ($field_name == 'monitor_alert_baseline') { + $cur_time = db_fetch_cell_prepared( + 'SELECT cur_time FROM host WHERE deleted = "" AND id = ?', - [$selected_items[$i]]); + [$selected_items[$i]] + ); - if ($cur_time > 0) { - db_execute_prepared('UPDATE host + if ($cur_time > 0) { + db_execute_prepared( + 'UPDATE host SET monitor_alert = CEIL(avg_time*?) WHERE deleted = "" AND id = ?', - [get_nfilter_request_var($field_name), $selected_items[$i]]); - } - } elseif ($field_name == 'monitor_warn_baseline') { - $cur_time = db_fetch_cell_prepared('SELECT cur_time + [get_nfilter_request_var($field_name), $selected_items[$i]] + ); + } + } elseif ($field_name == 'monitor_warn_baseline') { + $cur_time = db_fetch_cell_prepared( + 'SELECT cur_time FROM host WHERE deleted = "" AND id = ?', - [$selected_items[$i]]); + [$selected_items[$i]] + ); - if ($cur_time > 0) { - db_execute_prepared('UPDATE host + if ($cur_time > 0) { + db_execute_prepared( + 'UPDATE host SET monitor_warn = CEIL(avg_time*?) WHERE deleted = "" AND id = ?', - [get_nfilter_request_var($field_name), $selected_items[$i]]); - } - } else { - db_execute_prepared("UPDATE host + [get_nfilter_request_var($field_name), $selected_items[$i]] + ); + } + } else { + db_execute_prepared( + "UPDATE host SET $field_name = ? WHERE deleted='' AND id = ?", - [get_nfilter_request_var($field_name), $selected_items[$i]]); - } - } - } - } - } - } - - return $action; + [get_nfilter_request_var($field_name), $selected_items[$i]] + ); + } + } + } + } + } + } + + return $action; } -function monitorDeviceRemove($devices) { - db_execute('DELETE FROM plugin_monitor_notify_history WHERE host_id IN(' . implode(',', $devices) . ')'); - db_execute('DELETE FROM plugin_monitor_reboot_history WHERE host_id IN(' . implode(',', $devices) . ')'); - db_execute('DELETE FROM plugin_monitor_uptime WHERE host_id IN(' . implode(',', $devices) . ')'); +function monitorDeviceRemove($devices) +{ + db_execute('DELETE FROM plugin_monitor_notify_history WHERE host_id IN(' . implode(',', $devices) . ')'); + db_execute('DELETE FROM plugin_monitor_reboot_history WHERE host_id IN(' . implode(',', $devices) . ')'); + db_execute('DELETE FROM plugin_monitor_uptime WHERE host_id IN(' . implode(',', $devices) . ')'); - return $devices; + return $devices; } -function monitorDeviceActionPrepare($save) { - global $host_list, $fields_host_edit; +function monitorDeviceActionPrepare($save) +{ + global $host_list, $fields_host_edit; - if (!isset($save['drp_action'])) { - return $save; - } else { - $action = $save['drp_action']; + if (!isset($save['drp_action'])) { + return $save; + } else { + $action = $save['drp_action']; - if ($action != 'monitor_enable' && $action != 'monitor_disable' && $action != 'monitor_settings') { - return $save; - } + if ($action != 'monitor_enable' && $action != 'monitor_disable' && $action != 'monitor_settings') { + return $save; + } - if ($action == 'monitor_enable' || $action == 'monitor_disable') { - if ($action == 'monitor_enable') { - $action_description = 'enable'; - } elseif ($action == 'monitor_disable') { - $action_description = 'disable'; - } + if ($action == 'monitor_enable' || $action == 'monitor_disable') { + if ($action == 'monitor_enable') { + $action_description = 'enable'; + } elseif ($action == 'monitor_disable') { + $action_description = 'disable'; + } - print " + print "

" . __('Click \'Continue\' to %s monitoring on these Device(s)', $action_description, 'monitor') . "

    " . $save['host_list'] . '

'; - } else { - print " + } else { + print "

" . __('Click \'Continue\' to Change the Monitoring settings for the following Device(s). Remember to check \'Update this Field\' to indicate which columns to update.', 'monitor') . "

    " . $save['host_list'] . '

'; - $form_array = []; - $fields = [ - 'monitor', - 'monitor_text', - 'monitor_criticality', - 'monitor_warn', - 'monitor_alert', - 'monitor_warn_baseline', - 'monitor_alert_baseline', - 'monitor_icon' - ]; - - foreach ($fields as $field) { - $form_array += [$field => $fields_host_edit[$field]]; - - $form_array[$field]['value'] = ''; - $form_array[$field]['form_id'] = 0; - $form_array[$field]['sub_checkbox'] = [ - 'name' => 't_' . $field, - 'friendly_name' => __('Update this Field', 'monitor'), - 'value' => '' - ]; - } - - draw_edit_form( - [ - 'config' => ['no_form_tag' => true], - 'fields' => $form_array - ] - ); - } - - return $save; - } + $form_array = []; + $fields = [ + 'monitor', + 'monitor_text', + 'monitor_criticality', + 'monitor_warn', + 'monitor_alert', + 'monitor_warn_baseline', + 'monitor_alert_baseline', + 'monitor_icon' + ]; + + foreach ($fields as $field) { + $form_array += [$field => $fields_host_edit[$field]]; + + $form_array[$field]['value'] = ''; + $form_array[$field]['form_id'] = 0; + $form_array[$field]['sub_checkbox'] = [ + 'name' => 't_' . $field, + 'friendly_name' => __('Update this Field', 'monitor'), + 'value' => '' + ]; + } + + draw_edit_form( + [ + 'config' => ['no_form_tag' => true], + 'fields' => $form_array + ] + ); + } + + return $save; + } } -function monitorDeviceActionArray($device_action_array) { - $device_action_array['monitor_settings'] = __('Change Monitoring Options', 'monitor'); - $device_action_array['monitor_enable'] = __('Enable Monitoring', 'monitor'); - $device_action_array['monitor_disable'] = __('Disable Monitoring', 'monitor'); +function monitorDeviceActionArray($device_action_array) +{ + $device_action_array['monitor_settings'] = __('Change Monitoring Options', 'monitor'); + $device_action_array['monitor_enable'] = __('Enable Monitoring', 'monitor'); + $device_action_array['monitor_disable'] = __('Disable Monitoring', 'monitor'); - return $device_action_array; + return $device_action_array; } -function monitorScanDir() { - global $config; +function monitorScanDir() +{ + global $config; - $ext = ['.wav', '.mp3']; - $d = dir($config['base_path'] . '/plugins/monitor/sounds/'); - $files = []; + $ext = ['.wav', '.mp3']; + $d = dir($config['base_path'] . '/plugins/monitor/sounds/'); + $files = []; - while (false !== ($entry = $d->read())) { - if ($entry != '.' && $entry != '..' && in_array(strtolower(substr($entry,-4)),$ext, true)) { - $files[$entry] = $entry; - } - } - $d->close(); - asort($files); // sort the files - array_unshift($files, 'None'); // prepend the None option + while (false !== ($entry = $d->read())) { + if ($entry != '.' && $entry != '..' && in_array(strtolower(substr($entry, -4)), $ext, true)) { + $files[$entry] = $entry; + } + } + $d->close(); + asort($files); // sort the files + array_unshift($files, 'None'); // prepend the None option - return $files; + return $files; } -function monitorConfigSettings() { - global $tabs, $formats, $settings, $criticalities, $page_refresh_interval, $config, $settings_user, $tabs_graphs; - - include_once($config['base_path'] . '/lib/reports.php'); - - if (get_nfilter_request_var('tab') == 'monitor') { - $formats = reports_get_format_files(); - } elseif (empty($formats)) { - $formats = []; - } - - $criticalities = [ - 0 => __('Disabled', 'monitor'), - 1 => __('Low', 'monitor'), - 2 => __('Medium', 'monitor'), - 3 => __('High', 'monitor'), - 4 => __('Mission Critical', 'monitor') - ]; - - $log_retentions = [ - '-1' => __('Indefinitely', 'monitor'), - '31' => __('%d Month', 1, 'monitor'), - '62' => __('%d Months', 2, 'monitor'), - '93' => __('%d Months', 3, 'monitor'), - '124' => __('%d Months', 4, 'monitor'), - '186' => __('%d Months', 6, 'monitor'), - '365' => __('%d Year', 1, 'monitor') - ]; - - $font_sizes = [ - '20' => '20px', - '30' => '30px', - '40' => '40px', - '50' => '50px', - '60' => '60px', - '70' => '70px' - ]; - - if (function_exists('auth_augment_roles')) { - auth_augment_roles(__('Normal User'), ['monitor.php']); - } - - $tabs_graphs += ['monitor' => __('Monitor Settings', 'monitor')]; - - $settings_user += [ - 'monitor' => [ - 'monitor_sound' => [ - 'friendly_name' => __('Alarm Sound', 'monitor'), - 'description' => __('This is the sound file that will be played when a Device goes down.', 'monitor'), - 'method' => 'drop_array', - 'array' => monitorScanDir(), - 'default' => 'attn-noc.wav', - ], - 'monitor_sound_loop' => [ - 'friendly_name' => __('Loop Alarm Sound', 'monitor'), - 'description' => __('Play the above sound on a loop when a Device goes down.', 'monitor'), - 'method' => 'checkbox', - ], - 'monitor_legend' => [ - 'friendly_name' => __('Show Icon Legend', 'monitor'), - 'description' => __('Check this to show an icon legend on the Monitor display', 'monitor'), - 'method' => 'checkbox', - ], - 'monitor_uptime' => [ - 'friendly_name' => __('Show Uptime', 'monitor'), - 'description' => __('Check this to show Uptime on the Monitor display', 'monitor'), - 'method' => 'checkbox', - ], - 'monitor_error_zoom' => [ - 'friendly_name' => __('Zoom to Errors', 'monitor'), - 'description' => __('Check this to zoom to errored items on the Monitor display', 'monitor'), - 'method' => 'checkbox', - ], - 'monitor_error_background' => [ - 'friendly_name' => __('Zoom Background', 'monitor'), - 'description' => __('Background Color for Zoomed Errors on the Monitor display', 'monitor'), - 'method' => 'drop_color', - ], - 'monitor_error_fontsize' => [ - 'friendly_name' => __('Zoom Fontsize', 'monitor'), - 'description' => __('Check this to zoom to errored items on the Monitor display', 'monitor'), - 'method' => 'drop_array', - 'default' => '50', - 'array' => $font_sizes - ] - ] - ]; - - if (get_current_page() != 'settings.php') { - return; - } - - $tabs['monitor'] = __('Monitor', 'monitor'); - - $temp = [ - 'monitor_header' => [ - 'friendly_name' => __('Monitor Settings', 'monitor'), - 'method' => 'spacer', - 'collapsible' => 'true' - ], - 'monitor_new_enabled' => [ - 'friendly_name' => __('Enable on new devices', 'monitor'), - 'description' => __('Check this to automatically enable monitoring when creating new devices', 'monitor'), - 'method' => 'checkbox', - ], - 'monitor_log_storage' => [ - 'friendly_name' => __('Notification/Reboot Log Retention', 'monitor'), - 'description' => __('Keep Notification and Reboot Logs for this number of days.', 'monitor'), - 'method' => 'drop_array', - 'default' => '31', - 'array' => $log_retentions - ], - 'monitor_sound' => [ - 'friendly_name' => __('Alarm Sound', 'monitor'), - 'description' => __('This is the sound file that will be played when a Device goes down.', 'monitor'), - 'method' => 'drop_array', - 'array' => monitorScanDir(), - 'default' => 'attn-noc.wav', - ], - 'monitor_sound_loop' => [ - 'friendly_name' => __('Loop Alarm Sound', 'monitor'), - 'description' => __('Play the above sound on a loop when a Device goes down.', 'monitor'), - 'method' => 'checkbox', - ], - 'monitor_refresh' => [ - 'friendly_name' => __('Refresh Interval', 'monitor'), - 'description' => __('This is the time in seconds before the page refreshes. (1 - 300)', 'monitor'), - 'method' => 'drop_array', - 'default' => '60', - 'array' => $page_refresh_interval - ], - 'monitor_legend' => [ - 'friendly_name' => __('Show Icon Legend', 'monitor'), - 'description' => __('Check this to show an icon legend on the Monitor display', 'monitor'), - 'method' => 'checkbox', - ], - 'monitor_grouping' => [ - 'friendly_name' => __('Grouping', 'monitor'), - 'description' => __('This is how monitor will Group Devices.', 'monitor'), - 'method' => 'drop_array', - 'default' => 'default', - 'array' => [ - 'default' => __('Default', 'monitor'), - 'default_by_permissions' => __('Default with permissions', 'monitor'), - 'group_by_tree' => __('Tree', 'monitor'), - 'group_by_device_template' => __('Device Template', 'monitor'), - ] - ], - 'monitor_view' => [ - 'friendly_name' => __('View', 'monitor'), - 'description' => __('This is how monitor will render Devices.', 'monitor'), - 'method' => 'drop_array', - 'default' => 'default', - 'array' => [ - 'default' => __('Default', 'monitor'), - 'list' => __('List', 'monitor'), - 'names' => __('Names only', 'monitor'), - 'tiles' => __('Tiles', 'monitor'), - 'tilesadt' => __('Tiles & Downtime', 'monitor') - ] - ], - 'monitor_format_header' => [ - 'friendly_name' => __('Notification Report Format', 'monitor'), - 'method' => 'spacer', - 'collapsible' => 'true' - ], - 'monitor_format_file' => [ - 'friendly_name' => __('Format File to Use', 'monitor'), - 'method' => 'drop_array', - 'default' => 'default.format', - 'description' => __('Choose the custom html wrapper and CSS file to use. This file contains both html and CSS to wrap around your report. If it contains more than simply CSS, you need to place a special tag inside of the file. This format tag will be replaced by the report content. These files are located in the \'formats\' directory.', 'monitor'), - 'array' => $formats - ], - 'monitor_threshold' => [ - 'friendly_name' => __('Ping Threshold Notifications', 'monitor'), - 'method' => 'spacer', - 'collapsible' => 'true' - ], - 'monitor_warn_criticality' => [ - 'friendly_name' => __('Warning Latency Notification', 'monitor'), - 'description' => __('If a Device has a Round Trip Ping Latency above the Warning Threshold and above the Criticality below, subscribing emails to the Device will receive an email notification. Select \'Disabled\' to Disable. The Thold Plugin is required to enable this feature.', 'monitor'), - 'method' => 'drop_array', - 'default' => '0', - 'array' => $criticalities - ], - 'monitor_alert_criticality' => [ - 'friendly_name' => __('Alert Latency Notification', 'monitor'), - 'description' => __('If a Device has a Round Trip Ping Latency above the Alert Threshold and above the Criticality below, subscribing emails to the Device will receive an email notification. Select \'Disabled\' to Disable. The Thold Plugin is required to enable this feature.', 'monitor'), - 'method' => 'drop_array', - 'default' => '0', - 'array' => $criticalities - ], - 'monitor_resend_frequency' => [ - 'friendly_name' => __('How Often to Resend Emails', 'monitor'), - 'description' => __('How often should emails notifications be sent to subscribers for these Devices if they are exceeding their latency thresholds', 'monitor'), - 'method' => 'drop_array', - 'default' => '0', - 'array' => [ - '0' => __('Every Occurrence', 'monitor'), - '20' => __('Every %d Minutes', 20, 'monitor'), - '30' => __('Every %d Minutes', 30, 'monitor'), - '60' => __('Every Hour', 'monitor'), - '120' => __('Every %d Hours', 2, 'monitor'), - '240' => __('Every %d Hours', 4, 'monitor') - ] - ], - 'monitor_reboot' => [ - 'friendly_name' => __('Reboot Notifications', 'monitor'), - 'method' => 'spacer', - 'collapsible' => 'true' - ], - 'monitor_reboot_notify' => [ - 'friendly_name' => __('Send Reboot Notifications', 'monitor'), - 'method' => 'checkbox', - 'description' => __('Should Device Reboot Notifications be sent to users?', 'monitor'), - 'default' => 'on', - ], - 'monitor_send_one_email' => [ - 'friendly_name' => __('Send one Email to all addresses', 'monitor'), - 'description' => __('If checked, the system will send one Email only to all addresses.', 'monitor'), - 'method' => 'checkbox', - 'default' => 'on' - ], - 'monitor_reboot_thold' => [ - 'friendly_name' => __('Include Threshold Alert Lists', 'monitor'), - 'method' => 'checkbox', - 'description' => __('Should Threshold Alert Lists also receive Notification', 'monitor'), - 'default' => 'on', - ], - 'monitor_subject' => [ - 'friendly_name' => __('Subject', 'monitor'), - 'description' => __('Enter a Reboot message subject for the Reboot Notification.', 'monitor'), - 'method' => 'textbox', - 'default' => __('Cacti Device Reboot Notification', 'monitor'), - 'size' => 60, - 'max_length' => 60 - ], - 'monitor_body' => [ - 'friendly_name' => __('Email Body', 'monitor'), - 'description' => __('Enter an Email body to include in the Reboot Notification message. Currently, the only supported replacement tag accepted is <DETAILS>', 'monitor'), - 'method' => 'textarea', - 'textarea_rows' => 4, - 'textarea_cols' => 80, - 'default' => __('

Monitor Reboot Notification

The following Device\'s were Rebooted. See details below for additional information.


', 'monitor') - ], - 'monitor_email_header' => [ - 'friendly_name' => __('Notification Email Addresses', 'monitor'), - 'method' => 'spacer', - 'collapsible' => 'true' - ], - 'monitor_fromname' => [ - 'friendly_name' => __('From Name', 'monitor'), - 'description' => __('Enter the Email Name to send the notifications from', 'monitor'), - 'method' => 'textbox', - 'size' => '60', - 'max_length' => '255' - ], - 'monitor_fromemail' => [ - 'friendly_name' => __('From Address', 'monitor'), - 'description' => __('Enter the Email Address to send the notification from', 'monitor'), - 'method' => 'textbox', - 'size' => '60', - 'max_length' => '255' - ], - 'monitor_list' => [ - 'friendly_name' => __('Notification List', 'thold'), - 'description' => __('Select a Notification List below. All Emails subscribed to the notification list will be notified.', 'thold'), - 'method' => 'drop_sql', - 'sql' => 'SELECT id, name FROM plugin_notification_lists ORDER BY name', - 'default' => '', - 'none_value' => __('None', 'monitor') - ], - 'monitor_emails' => [ - 'friendly_name' => __('Email Addresses', 'monitor'), - 'description' => __('Enter a comma delimited list of Email addresses to inform of a reboot event.', 'monitor'), - 'method' => 'textarea', - 'textarea_rows' => 2, - 'textarea_cols' => 80, - 'default' => '' - ] - ]; - - if (isset($settings['monitor'])) { - $settings['monitor'] = array_merge($settings['monitor'], $temp); - } else { - $settings['monitor'] = $temp; - } +function monitorConfigSettings() +{ + global $tabs, $formats, $settings, $criticalities, $page_refresh_interval, $config, $settings_user, $tabs_graphs; + + include_once($config['base_path'] . '/lib/reports.php'); + + if (get_nfilter_request_var('tab') == 'monitor') { + $formats = reports_get_format_files(); + } elseif (empty($formats)) { + $formats = []; + } + + $criticalities = [ + 0 => __('Disabled', 'monitor'), + 1 => __('Low', 'monitor'), + 2 => __('Medium', 'monitor'), + 3 => __('High', 'monitor'), + 4 => __('Mission Critical', 'monitor') + ]; + + $log_retentions = [ + '-1' => __('Indefinitely', 'monitor'), + '31' => __('%d Month', 1, 'monitor'), + '62' => __('%d Months', 2, 'monitor'), + '93' => __('%d Months', 3, 'monitor'), + '124' => __('%d Months', 4, 'monitor'), + '186' => __('%d Months', 6, 'monitor'), + '365' => __('%d Year', 1, 'monitor') + ]; + + $font_sizes = [ + '20' => '20px', + '30' => '30px', + '40' => '40px', + '50' => '50px', + '60' => '60px', + '70' => '70px' + ]; + + if (function_exists('auth_augment_roles')) { + auth_augment_roles(__('Normal User'), ['monitor.php']); + } + + $tabs_graphs += ['monitor' => __('Monitor Settings', 'monitor')]; + + $settings_user += [ + 'monitor' => [ + 'monitor_sound' => [ + 'friendly_name' => __('Alarm Sound', 'monitor'), + 'description' => __('This is the sound file that will be played when a Device goes down.', 'monitor'), + 'method' => 'drop_array', + 'array' => monitorScanDir(), + 'default' => 'attn-noc.wav', + ], + 'monitor_sound_loop' => [ + 'friendly_name' => __('Loop Alarm Sound', 'monitor'), + 'description' => __('Play the above sound on a loop when a Device goes down.', 'monitor'), + 'method' => 'checkbox', + ], + 'monitor_legend' => [ + 'friendly_name' => __('Show Icon Legend', 'monitor'), + 'description' => __('Check this to show an icon legend on the Monitor display', 'monitor'), + 'method' => 'checkbox', + ], + 'monitor_uptime' => [ + 'friendly_name' => __('Show Uptime', 'monitor'), + 'description' => __('Check this to show Uptime on the Monitor display', 'monitor'), + 'method' => 'checkbox', + ], + 'monitor_error_zoom' => [ + 'friendly_name' => __('Zoom to Errors', 'monitor'), + 'description' => __('Check this to zoom to errored items on the Monitor display', 'monitor'), + 'method' => 'checkbox', + ], + 'monitor_error_background' => [ + 'friendly_name' => __('Zoom Background', 'monitor'), + 'description' => __('Background Color for Zoomed Errors on the Monitor display', 'monitor'), + 'method' => 'drop_color', + ], + 'monitor_error_fontsize' => [ + 'friendly_name' => __('Zoom Fontsize', 'monitor'), + 'description' => __('Check this to zoom to errored items on the Monitor display', 'monitor'), + 'method' => 'drop_array', + 'default' => '50', + 'array' => $font_sizes + ] + ] + ]; + + if (get_current_page() != 'settings.php') { + return; + } + + $tabs['monitor'] = __('Monitor', 'monitor'); + + $temp = [ + 'monitor_header' => [ + 'friendly_name' => __('Monitor Settings', 'monitor'), + 'method' => 'spacer', + 'collapsible' => 'true' + ], + 'monitor_new_enabled' => [ + 'friendly_name' => __('Enable on new devices', 'monitor'), + 'description' => __('Check this to automatically enable monitoring when creating new devices', 'monitor'), + 'method' => 'checkbox', + ], + 'monitor_log_storage' => [ + 'friendly_name' => __('Notification/Reboot Log Retention', 'monitor'), + 'description' => __('Keep Notification and Reboot Logs for this number of days.', 'monitor'), + 'method' => 'drop_array', + 'default' => '31', + 'array' => $log_retentions + ], + 'monitor_sound' => [ + 'friendly_name' => __('Alarm Sound', 'monitor'), + 'description' => __('This is the sound file that will be played when a Device goes down.', 'monitor'), + 'method' => 'drop_array', + 'array' => monitorScanDir(), + 'default' => 'attn-noc.wav', + ], + 'monitor_sound_loop' => [ + 'friendly_name' => __('Loop Alarm Sound', 'monitor'), + 'description' => __('Play the above sound on a loop when a Device goes down.', 'monitor'), + 'method' => 'checkbox', + ], + 'monitor_refresh' => [ + 'friendly_name' => __('Refresh Interval', 'monitor'), + 'description' => __('This is the time in seconds before the page refreshes. (1 - 300)', 'monitor'), + 'method' => 'drop_array', + 'default' => '60', + 'array' => $page_refresh_interval + ], + 'monitor_legend' => [ + 'friendly_name' => __('Show Icon Legend', 'monitor'), + 'description' => __('Check this to show an icon legend on the Monitor display', 'monitor'), + 'method' => 'checkbox', + ], + 'monitor_grouping' => [ + 'friendly_name' => __('Grouping', 'monitor'), + 'description' => __('This is how monitor will Group Devices.', 'monitor'), + 'method' => 'drop_array', + 'default' => 'default', + 'array' => [ + 'default' => __('Default', 'monitor'), + 'default_by_permissions' => __('Default with permissions', 'monitor'), + 'group_by_tree' => __('Tree', 'monitor'), + 'group_by_device_template' => __('Device Template', 'monitor'), + ] + ], + 'monitor_view' => [ + 'friendly_name' => __('View', 'monitor'), + 'description' => __('This is how monitor will render Devices.', 'monitor'), + 'method' => 'drop_array', + 'default' => 'default', + 'array' => [ + 'default' => __('Default', 'monitor'), + 'list' => __('List', 'monitor'), + 'names' => __('Names only', 'monitor'), + 'tiles' => __('Tiles', 'monitor'), + 'tilesadt' => __('Tiles & Downtime', 'monitor') + ] + ], + 'monitor_format_header' => [ + 'friendly_name' => __('Notification Report Format', 'monitor'), + 'method' => 'spacer', + 'collapsible' => 'true' + ], + 'monitor_format_file' => [ + 'friendly_name' => __('Format File to Use', 'monitor'), + 'method' => 'drop_array', + 'default' => 'default.format', + 'description' => __('Choose the custom html wrapper and CSS file to use. This file contains both html and CSS to wrap around your report. If it contains more than simply CSS, you need to place a special tag inside of the file. This format tag will be replaced by the report content. These files are located in the \'formats\' directory.', 'monitor'), + 'array' => $formats + ], + 'monitor_threshold' => [ + 'friendly_name' => __('Ping Threshold Notifications', 'monitor'), + 'method' => 'spacer', + 'collapsible' => 'true' + ], + 'monitor_warn_criticality' => [ + 'friendly_name' => __('Warning Latency Notification', 'monitor'), + 'description' => __('If a Device has a Round Trip Ping Latency above the Warning Threshold and above the Criticality below, subscribing emails to the Device will receive an email notification. Select \'Disabled\' to Disable. The Thold Plugin is required to enable this feature.', 'monitor'), + 'method' => 'drop_array', + 'default' => '0', + 'array' => $criticalities + ], + 'monitor_alert_criticality' => [ + 'friendly_name' => __('Alert Latency Notification', 'monitor'), + 'description' => __('If a Device has a Round Trip Ping Latency above the Alert Threshold and above the Criticality below, subscribing emails to the Device will receive an email notification. Select \'Disabled\' to Disable. The Thold Plugin is required to enable this feature.', 'monitor'), + 'method' => 'drop_array', + 'default' => '0', + 'array' => $criticalities + ], + 'monitor_resend_frequency' => [ + 'friendly_name' => __('How Often to Resend Emails', 'monitor'), + 'description' => __('How often should emails notifications be sent to subscribers for these Devices if they are exceeding their latency thresholds', 'monitor'), + 'method' => 'drop_array', + 'default' => '0', + 'array' => [ + '0' => __('Every Occurrence', 'monitor'), + '20' => __('Every %d Minutes', 20, 'monitor'), + '30' => __('Every %d Minutes', 30, 'monitor'), + '60' => __('Every Hour', 'monitor'), + '120' => __('Every %d Hours', 2, 'monitor'), + '240' => __('Every %d Hours', 4, 'monitor') + ] + ], + 'monitor_reboot' => [ + 'friendly_name' => __('Reboot Notifications', 'monitor'), + 'method' => 'spacer', + 'collapsible' => 'true' + ], + 'monitor_reboot_notify' => [ + 'friendly_name' => __('Send Reboot Notifications', 'monitor'), + 'method' => 'checkbox', + 'description' => __('Should Device Reboot Notifications be sent to users?', 'monitor'), + 'default' => 'on', + ], + 'monitor_send_one_email' => [ + 'friendly_name' => __('Send one Email to all addresses', 'monitor'), + 'description' => __('If checked, the system will send one Email only to all addresses.', 'monitor'), + 'method' => 'checkbox', + 'default' => 'on' + ], + 'monitor_reboot_thold' => [ + 'friendly_name' => __('Include Threshold Alert Lists', 'monitor'), + 'method' => 'checkbox', + 'description' => __('Should Threshold Alert Lists also receive Notification', 'monitor'), + 'default' => 'on', + ], + 'monitor_subject' => [ + 'friendly_name' => __('Subject', 'monitor'), + 'description' => __('Enter a Reboot message subject for the Reboot Notification.', 'monitor'), + 'method' => 'textbox', + 'default' => __('Cacti Device Reboot Notification', 'monitor'), + 'size' => 60, + 'max_length' => 60 + ], + 'monitor_body' => [ + 'friendly_name' => __('Email Body', 'monitor'), + 'description' => __('Enter an Email body to include in the Reboot Notification message. Currently, the only supported replacement tag accepted is <DETAILS>', 'monitor'), + 'method' => 'textarea', + 'textarea_rows' => 4, + 'textarea_cols' => 80, + 'default' => __('

Monitor Reboot Notification

The following Device\'s were Rebooted. See details below for additional information.


', 'monitor') + ], + 'monitor_email_header' => [ + 'friendly_name' => __('Notification Email Addresses', 'monitor'), + 'method' => 'spacer', + 'collapsible' => 'true' + ], + 'monitor_fromname' => [ + 'friendly_name' => __('From Name', 'monitor'), + 'description' => __('Enter the Email Name to send the notifications from', 'monitor'), + 'method' => 'textbox', + 'size' => '60', + 'max_length' => '255' + ], + 'monitor_fromemail' => [ + 'friendly_name' => __('From Address', 'monitor'), + 'description' => __('Enter the Email Address to send the notification from', 'monitor'), + 'method' => 'textbox', + 'size' => '60', + 'max_length' => '255' + ], + 'monitor_list' => [ + 'friendly_name' => __('Notification List', 'thold'), + 'description' => __('Select a Notification List below. All Emails subscribed to the notification list will be notified.', 'thold'), + 'method' => 'drop_sql', + 'sql' => 'SELECT id, name FROM plugin_notification_lists ORDER BY name', + 'default' => '', + 'none_value' => __('None', 'monitor') + ], + 'monitor_emails' => [ + 'friendly_name' => __('Email Addresses', 'monitor'), + 'description' => __('Enter a comma delimited list of Email addresses to inform of a reboot event.', 'monitor'), + 'method' => 'textarea', + 'textarea_rows' => 2, + 'textarea_cols' => 80, + 'default' => '' + ] + ]; + + if (isset($settings['monitor'])) { + $settings['monitor'] = array_merge($settings['monitor'], $temp); + } else { + $settings['monitor'] = $temp; + } } -function monitorConfigArrays() { - global $fa_icons; - - $fa_icons = [ - 'server' => [ - 'display' => __('Server', 'monitor'), - 'class' => 'fa fa-server deviceUp', - 'style' => '' - ], - 'print' => [ - 'display' => __('Printer', 'monitor'), - 'class' => 'fa fa-print deviceUp', - 'style' => '' - ], - 'desktop' => [ - 'display' => __('Desktop PC', 'monitor'), - 'class' => 'fa fa-desktop deviceUp', - 'style' => '' - ], - 'laptop' => [ - 'display' => __('Laptop/notebook', 'monitor'), - 'class' => 'fa fa-laptop deviceUp', - 'style' => '' - ], - 'wifi' => [ - 'display' => __('Wifi', 'monitor'), - 'class' => 'fa fa-wifi deviceUp', - 'style' => '' - ], - 'network-wired' => [ - 'display' => __('Wired network', 'monitor'), - 'class' => 'fa fa-network-wired deviceUp', - 'style' => '' - ], - 'database' => [ - 'display' => __('Database', 'monitor'), - 'class' => 'fa fa-database deviceUp', - 'style' => '' - ], - 'clock' => [ - 'display' => __('Clock', 'monitor'), - 'class' => 'fa fa-clock deviceUp', - 'style' => '' - ], - 'asterisk' => [ - 'display' => __('Asterisk', 'monitor'), - 'class' => 'fas fa-asterisk deviceUp', - 'style' => '' - ], - 'hdd' => [ - 'display' => __('Harddisk', 'monitor'), - 'class' => 'fa fa-hdd deviceUp', - 'style' => '' - ], - 'boxes' => [ - 'display' => __('Boxes', 'monitor'), - 'class' => 'fa fa-boxes deviceUp', - 'style' => '' - ], - 'phone' => [ - 'display' => __('Phone', 'monitor'), - 'class' => 'fa fa-phone deviceUp', - 'style' => '' - ], - 'cloud' => [ - 'display' => __('Cloud', 'monitor'), - 'class' => 'fa fa-cloud deviceUp', - 'style' => '' - ] - ]; - - if (!function_exists('form_dropicon')) { - foreach ($fa_icons as $key => $data) { - $nfa_icons[$key] = $data['display']; - } - - $fa_icons = $nfa_icons; - } - - monitorCheckUpgrade(); +function monitorConfigArrays() +{ + global $fa_icons; + + $fa_icons = [ + 'server' => [ + 'display' => __('Server', 'monitor'), + 'class' => 'fa fa-server deviceUp', + 'style' => '' + ], + 'print' => [ + 'display' => __('Printer', 'monitor'), + 'class' => 'fa fa-print deviceUp', + 'style' => '' + ], + 'desktop' => [ + 'display' => __('Desktop PC', 'monitor'), + 'class' => 'fa fa-desktop deviceUp', + 'style' => '' + ], + 'laptop' => [ + 'display' => __('Laptop/notebook', 'monitor'), + 'class' => 'fa fa-laptop deviceUp', + 'style' => '' + ], + 'wifi' => [ + 'display' => __('Wifi', 'monitor'), + 'class' => 'fa fa-wifi deviceUp', + 'style' => '' + ], + 'network-wired' => [ + 'display' => __('Wired network', 'monitor'), + 'class' => 'fa fa-network-wired deviceUp', + 'style' => '' + ], + 'database' => [ + 'display' => __('Database', 'monitor'), + 'class' => 'fa fa-database deviceUp', + 'style' => '' + ], + 'clock' => [ + 'display' => __('Clock', 'monitor'), + 'class' => 'fa fa-clock deviceUp', + 'style' => '' + ], + 'asterisk' => [ + 'display' => __('Asterisk', 'monitor'), + 'class' => 'fas fa-asterisk deviceUp', + 'style' => '' + ], + 'hdd' => [ + 'display' => __('Harddisk', 'monitor'), + 'class' => 'fa fa-hdd deviceUp', + 'style' => '' + ], + 'boxes' => [ + 'display' => __('Boxes', 'monitor'), + 'class' => 'fa fa-boxes deviceUp', + 'style' => '' + ], + 'phone' => [ + 'display' => __('Phone', 'monitor'), + 'class' => 'fa fa-phone deviceUp', + 'style' => '' + ], + 'cloud' => [ + 'display' => __('Cloud', 'monitor'), + 'class' => 'fa fa-cloud deviceUp', + 'style' => '' + ] + ]; + + if (!function_exists('form_dropicon')) { + foreach ($fa_icons as $key => $data) { + $nfa_icons[$key] = $data['display']; + } + + $fa_icons = $nfa_icons; + } + + monitorCheckUpgrade(); } -function monitorTopGraphRefresh($refresh) { - if (get_current_page() != 'monitor.php') { - return $refresh; - } +function monitorTopGraphRefresh($refresh) +{ + if (get_current_page() != 'monitor.php') { + return $refresh; + } - $r = read_config_option('monitor_refresh'); + $r = read_config_option('monitor_refresh'); - if ($r == '' || $r < 1) { - return $refresh; - } + if ($r == '' || $r < 1) { + return $refresh; + } - return $r; + return $r; } -function monitorShowTab() { - global $config; +function monitorShowTab() +{ + global $config; - monitorCheckUpgrade(); + monitorCheckUpgrade(); - if (api_user_realm_auth('monitor.php')) { - if (substr_count($_SERVER['REQUEST_URI'], 'monitor.php')) { - print '' . __('Monitor', 'monitor') . ''; - } else { - print '' . __('Monitor', 'monitor') . ''; - } - } + if (api_user_realm_auth('monitor.php')) { + if (substr_count($_SERVER['REQUEST_URI'], 'monitor.php')) { + print '' . __('Monitor', 'monitor') . ''; + } else { + print '' . __('Monitor', 'monitor') . ''; + } + } } -function monitorConfigForm() { - global $config, $fields_host_edit, $criticalities, $fa_icons; - - $baselines = [ - '0' => __('Do not Change', 'monitor'), - '1.20' => __('%d Percent Above Average', 20, 'monitor'), - '1.30' => __('%d Percent Above Average', 30, 'monitor'), - '1.40' => __('%d Percent Above Average', 40, 'monitor'), - '1.50' => __('%d Percent Above Average', 50, 'monitor'), - '1.60' => __('%d Percent Above Average', 60, 'monitor'), - '1.70' => __('%d Percent Above Average', 70, 'monitor'), - '1.80' => __('%d Percent Above Average', 80, 'monitor'), - '1.90' => __('%d Percent Above Average', 90, 'monitor'), - '2.00' => __('%d Percent Above Average', 100, 'monitor'), - '2.20' => __('%d Percent Above Average', 120, 'monitor'), - '2.40' => __('%d Percent Above Average', 140, 'monitor'), - '2.50' => __('%d Percent Above Average', 150, 'monitor'), - '3.00' => __('%d Percent Above Average', 200, 'monitor'), - '4.00' => __('%d Percent Above Average', 300, 'monitor'), - '5.00' => __('%d Percent Above Average', 400, 'monitor'), - '6.00' => __('%d Percent Above Average', 500, 'monitor') - ]; - - $fields_host_edit2 = $fields_host_edit; - $fields_host_edit3 = []; - - if (array_key_exists('bulk_walk_size', $fields_host_edit2)) { - $insert_field = 'bulk_walk_size'; - } else { - $insert_field = 'disabled'; - } - - foreach ($fields_host_edit2 as $f => $a) { - $fields_host_edit3[$f] = $a; - - if ($f == $insert_field) { - $fields_host_edit3['monitor_header'] = [ - 'friendly_name' => __('Device Monitoring Settings', 'monitor'), - 'method' => 'spacer', - 'collapsible' => 'true' - ]; - - $fields_host_edit3['monitor'] = [ - 'method' => 'checkbox', - 'friendly_name' => __('Monitor Device', 'monitor'), - 'description' => __('Check this box to monitor this Device on the Monitor Tab.', 'monitor'), - 'value' => '|arg1:monitor|', - 'form_id' => false - ]; - - $host_id = get_nfilter_request_var('id'); - - if (empty($host_id) || !is_numeric($host_id)) { - $fields_host_edit3['monitor']['default'] = monitorGetDefault($host_id); - } - - $fields_host_edit3['monitor_criticality'] = [ - 'friendly_name' => __('Device Criticality', 'monitor'), - 'description' => __('What is the Criticality of this Device.', 'monitor'), - 'method' => 'drop_array', - 'array' => $criticalities, - 'value' => '|arg1:monitor_criticality|', - 'default' => '0', - ]; - - $fields_host_edit3['monitor_warn'] = [ - 'friendly_name' => __('Ping Warning Threshold', 'monitor'), - 'description' => __('If the round-trip latency via any of the predefined Cacti ping methods raises above this threshold, log a warning or send email based upon the Devices Criticality and Monitor setting. The unit is in milliseconds. Setting to 0 disables. The Thold Plugin is required to leverage this functionality.', 'monitor'), - 'method' => 'textbox', - 'size' => '10', - 'max_length' => '5', - 'placeholder' => __('milliseconds', 'monitor'), - 'value' => '|arg1:monitor_warn|', - 'default' => '', - ]; - - $fields_host_edit3['monitor_alert'] = [ - 'friendly_name' => __('Ping Alert Threshold', 'monitor'), - 'description' => __('If the round-trip latency via any of the predefined Cacti ping methods raises above this threshold, log an alert or send an email based upon the Devices Criticality and Monitor setting. The unit is in milliseconds. Setting to 0 disables. The Thold Plugin is required to leverage this functionality.', 'monitor'), - 'method' => 'textbox', - 'size' => '10', - 'max_length' => '5', - 'placeholder' => __('milliseconds', 'monitor'), - 'value' => '|arg1:monitor_alert|', - 'default' => '', - ]; - - $fields_host_edit3['monitor_warn_baseline'] = [ - 'friendly_name' => __('Re-Baseline Warning', 'monitor'), - 'description' => __('The percentage above the current average ping time to consider a Warning Threshold. If updated, this will automatically adjust the Ping Warning Threshold.', 'monitor'), - 'method' => 'drop_array', - 'default' => '0', - 'value' => '0', - 'array' => $baselines - ]; - - $fields_host_edit3['monitor_alert_baseline'] = [ - 'friendly_name' => __('Re-Baseline Alert', 'monitor'), - 'description' => __('The percentage above the current average ping time to consider a Alert Threshold. If updated, this will automatically adjust the Ping Alert Threshold.', 'monitor'), - 'method' => 'drop_array', - 'default' => '0', - 'value' => '0', - 'array' => $baselines - ]; - - $fields_host_edit3['monitor_text'] = [ - 'friendly_name' => __('Down Device Message', 'monitor'), - 'description' => __('This is the message that will be displayed when this Device is reported as down.', 'monitor'), - 'method' => 'textarea', - 'max_length' => 1000, - 'textarea_rows' => 2, - 'textarea_cols' => 80, - 'value' => '|arg1:monitor_text|', - 'default' => '', - ]; - - if (function_exists('form_dropicon')) { - $method = 'drop_icon'; - } else { - $method = 'drop_array'; - } - - $fields_host_edit3['monitor_icon'] = [ - 'friendly_name' => __('Device icon', 'monitor'), - 'description' => __('You can select device icon.', 'monitor'), - 'method' => $method, - 'default' => '0', - 'value' => '|arg1:monitor_icon|', - 'array' => $fa_icons, - ]; - } - } - - $fields_host_edit = $fields_host_edit3; +function monitorConfigForm() +{ + global $config, $fields_host_edit, $criticalities, $fa_icons; + + $baselines = [ + '0' => __('Do not Change', 'monitor'), + '1.20' => __('%d Percent Above Average', 20, 'monitor'), + '1.30' => __('%d Percent Above Average', 30, 'monitor'), + '1.40' => __('%d Percent Above Average', 40, 'monitor'), + '1.50' => __('%d Percent Above Average', 50, 'monitor'), + '1.60' => __('%d Percent Above Average', 60, 'monitor'), + '1.70' => __('%d Percent Above Average', 70, 'monitor'), + '1.80' => __('%d Percent Above Average', 80, 'monitor'), + '1.90' => __('%d Percent Above Average', 90, 'monitor'), + '2.00' => __('%d Percent Above Average', 100, 'monitor'), + '2.20' => __('%d Percent Above Average', 120, 'monitor'), + '2.40' => __('%d Percent Above Average', 140, 'monitor'), + '2.50' => __('%d Percent Above Average', 150, 'monitor'), + '3.00' => __('%d Percent Above Average', 200, 'monitor'), + '4.00' => __('%d Percent Above Average', 300, 'monitor'), + '5.00' => __('%d Percent Above Average', 400, 'monitor'), + '6.00' => __('%d Percent Above Average', 500, 'monitor') + ]; + + $fields_host_edit2 = $fields_host_edit; + $fields_host_edit3 = []; + + if (array_key_exists('bulk_walk_size', $fields_host_edit2)) { + $insert_field = 'bulk_walk_size'; + } else { + $insert_field = 'disabled'; + } + + foreach ($fields_host_edit2 as $f => $a) { + $fields_host_edit3[$f] = $a; + + if ($f == $insert_field) { + $fields_host_edit3['monitor_header'] = [ + 'friendly_name' => __('Device Monitoring Settings', 'monitor'), + 'method' => 'spacer', + 'collapsible' => 'true' + ]; + + $fields_host_edit3['monitor'] = [ + 'method' => 'checkbox', + 'friendly_name' => __('Monitor Device', 'monitor'), + 'description' => __('Check this box to monitor this Device on the Monitor Tab.', 'monitor'), + 'value' => '|arg1:monitor|', + 'form_id' => false + ]; + + $host_id = get_nfilter_request_var('id'); + + if (empty($host_id) || !is_numeric($host_id)) { + $fields_host_edit3['monitor']['default'] = monitorGetDefault($host_id); + } + + $fields_host_edit3['monitor_criticality'] = [ + 'friendly_name' => __('Device Criticality', 'monitor'), + 'description' => __('What is the Criticality of this Device.', 'monitor'), + 'method' => 'drop_array', + 'array' => $criticalities, + 'value' => '|arg1:monitor_criticality|', + 'default' => '0', + ]; + + $fields_host_edit3['monitor_warn'] = [ + 'friendly_name' => __('Ping Warning Threshold', 'monitor'), + 'description' => __('If the round-trip latency via any of the predefined Cacti ping methods raises above this threshold, log a warning or send email based upon the Devices Criticality and Monitor setting. The unit is in milliseconds. Setting to 0 disables. The Thold Plugin is required to leverage this functionality.', 'monitor'), + 'method' => 'textbox', + 'size' => '10', + 'max_length' => '5', + 'placeholder' => __('milliseconds', 'monitor'), + 'value' => '|arg1:monitor_warn|', + 'default' => '', + ]; + + $fields_host_edit3['monitor_alert'] = [ + 'friendly_name' => __('Ping Alert Threshold', 'monitor'), + 'description' => __('If the round-trip latency via any of the predefined Cacti ping methods raises above this threshold, log an alert or send an email based upon the Devices Criticality and Monitor setting. The unit is in milliseconds. Setting to 0 disables. The Thold Plugin is required to leverage this functionality.', 'monitor'), + 'method' => 'textbox', + 'size' => '10', + 'max_length' => '5', + 'placeholder' => __('milliseconds', 'monitor'), + 'value' => '|arg1:monitor_alert|', + 'default' => '', + ]; + + $fields_host_edit3['monitor_warn_baseline'] = [ + 'friendly_name' => __('Re-Baseline Warning', 'monitor'), + 'description' => __('The percentage above the current average ping time to consider a Warning Threshold. If updated, this will automatically adjust the Ping Warning Threshold.', 'monitor'), + 'method' => 'drop_array', + 'default' => '0', + 'value' => '0', + 'array' => $baselines + ]; + + $fields_host_edit3['monitor_alert_baseline'] = [ + 'friendly_name' => __('Re-Baseline Alert', 'monitor'), + 'description' => __('The percentage above the current average ping time to consider a Alert Threshold. If updated, this will automatically adjust the Ping Alert Threshold.', 'monitor'), + 'method' => 'drop_array', + 'default' => '0', + 'value' => '0', + 'array' => $baselines + ]; + + $fields_host_edit3['monitor_text'] = [ + 'friendly_name' => __('Down Device Message', 'monitor'), + 'description' => __('This is the message that will be displayed when this Device is reported as down.', 'monitor'), + 'method' => 'textarea', + 'max_length' => 1000, + 'textarea_rows' => 2, + 'textarea_cols' => 80, + 'value' => '|arg1:monitor_text|', + 'default' => '', + ]; + + if (function_exists('form_dropicon')) { + $method = 'drop_icon'; + } else { + $method = 'drop_array'; + } + + $fields_host_edit3['monitor_icon'] = [ + 'friendly_name' => __('Device icon', 'monitor'), + 'description' => __('You can select device icon.', 'monitor'), + 'method' => $method, + 'default' => '0', + 'value' => '|arg1:monitor_icon|', + 'array' => $fa_icons, + ]; + } + } + + $fields_host_edit = $fields_host_edit3; } -function monitorGetDefault($host_id) { - $monitor_new_device = ''; +function monitorGetDefault($host_id) +{ + $monitor_new_device = ''; - if ($host_id <= 0) { - $monitor_new_device = read_config_option('monitor_new_enabled'); - } + if ($host_id <= 0) { + $monitor_new_device = read_config_option('monitor_new_enabled'); + } - return $monitor_new_device; + return $monitor_new_device; } -function monitorApiDeviceSave($save) { - global $fa_icons; - - $monitor_default = monitorGetDefault($save['id']); - - if (isset_request_var('monitor')) { - $save['monitor'] = form_input_validate(get_nfilter_request_var('monitor'), 'monitor', $monitor_default, true, 3); - } else { - $save['monitor'] = form_input_validate($monitor_default, 'monitor', '', true, 3); - } - - if (isset_request_var('monitor_text')) { - $save['monitor_text'] = form_input_validate(get_nfilter_request_var('monitor_text'), 'monitor_text', '', true, 3); - } else { - $save['monitor_text'] = form_input_validate('', 'monitor_text', '', true, 3); - } - - if (isset_request_var('monitor_criticality')) { - $save['monitor_criticality'] = form_input_validate(get_nfilter_request_var('monitor_criticality'), 'monitor_criticality', '^[0-9]+$', true, 3); - } else { - $save['monitor_criticality'] = form_input_validate('', 'monitor_criticality', '', true, 3); - } - - if (isset_request_var('monitor_warn')) { - $save['monitor_warn'] = form_input_validate(get_nfilter_request_var('monitor_warn'), 'monitor_warn', '^[0-9]+$', true, 3); - } else { - $save['monitor_warn'] = form_input_validate('', 'monitor_warn', '', true, 3); - } - - if (isset_request_var('monitor_alert')) { - $save['monitor_alert'] = form_input_validate(get_nfilter_request_var('monitor_alert'), 'monitor_alert', '^[0-9]+$', true, 3); - } else { - $save['monitor_alert'] = form_input_validate('', 'monitor_alert', '', true, 3); - } - - if (isset_request_var('monitor_icon') && array_key_exists(get_nfilter_request_var('monitor_icon'), $fa_icons)) { - $save['monitor_icon'] = get_nfilter_request_var('monitor_icon'); - } else { - $save['monitor_icon'] = ''; - } - - if (!isempty_request_var('monitor_alert_baseline') && !empty($save['id'])) { - $cur_time = db_fetch_cell_prepared('SELECT cur_time +function monitorApiDeviceSave($save) +{ + global $fa_icons; + + $monitor_default = monitorGetDefault($save['id']); + + if (isset_request_var('monitor')) { + $save['monitor'] = form_input_validate(get_nfilter_request_var('monitor'), 'monitor', $monitor_default, true, 3); + } else { + $save['monitor'] = form_input_validate($monitor_default, 'monitor', '', true, 3); + } + + if (isset_request_var('monitor_text')) { + $save['monitor_text'] = form_input_validate(get_nfilter_request_var('monitor_text'), 'monitor_text', '', true, 3); + } else { + $save['monitor_text'] = form_input_validate('', 'monitor_text', '', true, 3); + } + + if (isset_request_var('monitor_criticality')) { + $save['monitor_criticality'] = form_input_validate(get_nfilter_request_var('monitor_criticality'), 'monitor_criticality', '^[0-9]+$', true, 3); + } else { + $save['monitor_criticality'] = form_input_validate('', 'monitor_criticality', '', true, 3); + } + + if (isset_request_var('monitor_warn')) { + $save['monitor_warn'] = form_input_validate(get_nfilter_request_var('monitor_warn'), 'monitor_warn', '^[0-9]+$', true, 3); + } else { + $save['monitor_warn'] = form_input_validate('', 'monitor_warn', '', true, 3); + } + + if (isset_request_var('monitor_alert')) { + $save['monitor_alert'] = form_input_validate(get_nfilter_request_var('monitor_alert'), 'monitor_alert', '^[0-9]+$', true, 3); + } else { + $save['monitor_alert'] = form_input_validate('', 'monitor_alert', '', true, 3); + } + + if (isset_request_var('monitor_icon') && array_key_exists(get_nfilter_request_var('monitor_icon'), $fa_icons)) { + $save['monitor_icon'] = get_nfilter_request_var('monitor_icon'); + } else { + $save['monitor_icon'] = ''; + } + + if (!isempty_request_var('monitor_alert_baseline') && !empty($save['id'])) { + $cur_time = db_fetch_cell_prepared( + 'SELECT cur_time FROM host WHERE id = ?', - [$save['id']]); + [$save['id']] + ); - if ($cur_time > 0) { - $save['monitor_alert'] = ceil($cur_time * get_nfilter_request_var('monitor_alert_baseline')); - } - } + if ($cur_time > 0) { + $save['monitor_alert'] = ceil($cur_time * get_nfilter_request_var('monitor_alert_baseline')); + } + } - if (!isempty_request_var('monitor_warn_baseline') && !empty($save['id'])) { - $cur_time = db_fetch_cell_prepared('SELECT cur_time + if (!isempty_request_var('monitor_warn_baseline') && !empty($save['id'])) { + $cur_time = db_fetch_cell_prepared( + 'SELECT cur_time FROM host WHERE id = ?', - [$save['id']]); + [$save['id']] + ); - if ($cur_time > 0) { - $save['monitor_warn'] = ceil($cur_time * get_nfilter_request_var('monitor_alert_baseline')); - } - } + if ($cur_time > 0) { + $save['monitor_warn'] = ceil($cur_time * get_nfilter_request_var('monitor_alert_baseline')); + } + } - return $save; + return $save; } -function monitorDrawNavigationText($nav) { - $nav['monitor.php:'] = ['title' => __('Monitoring', 'monitor'), 'mapping' => '', 'url' => 'monitor.php', 'level' => '0']; +function monitorDrawNavigationText($nav) +{ + $nav['monitor.php:'] = ['title' => __('Monitoring', 'monitor'), 'mapping' => '', 'url' => 'monitor.php', 'level' => '0']; - return $nav; + return $nav; } -function monitorSetupTable() { - if (!db_table_exists('plugin_monitor_notify_history')) { - db_execute("CREATE TABLE IF NOT EXISTS plugin_monitor_notify_history ( +function monitorSetupTable() +{ + if (!db_table_exists('plugin_monitor_notify_history')) { + db_execute("CREATE TABLE IF NOT EXISTS plugin_monitor_notify_history ( id int(10) unsigned NOT NULL AUTO_INCREMENT, host_id int(10) unsigned DEFAULT NULL, notify_type tinyint(3) unsigned DEFAULT NULL, @@ -1053,10 +1096,10 @@ function monitorSetupTable() { UNIQUE KEY unique_key (host_id,notify_type,notification_time)) ENGINE=InnoDB COMMENT='Stores Notification Event History'"); - } + } - if (!db_table_exists('plugin_monitor_reboot_history')) { - db_execute("CREATE TABLE IF NOT EXISTS plugin_monitor_reboot_history ( + if (!db_table_exists('plugin_monitor_reboot_history')) { + db_execute("CREATE TABLE IF NOT EXISTS plugin_monitor_reboot_history ( id int(10) unsigned NOT NULL AUTO_INCREMENT, host_id int(10) unsigned DEFAULT NULL, reboot_time timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', @@ -1067,20 +1110,20 @@ function monitorSetupTable() { KEY reboot_time (reboot_time)) ENGINE=InnoDB COMMENT='Keeps Track of Device Reboot Times'"); - } + } - if (!db_table_exists('plugin_monitor_uptime')) { - db_execute("CREATE TABLE IF NOT EXISTS plugin_monitor_uptime ( + if (!db_table_exists('plugin_monitor_uptime')) { + db_execute("CREATE TABLE IF NOT EXISTS plugin_monitor_uptime ( host_id int(10) unsigned DEFAULT '0', uptime bigint(20) unsigned DEFAULT '0', PRIMARY KEY (host_id), KEY uptime (uptime)) ENGINE=InnoDB COMMENT='Keeps Track of the Devices last uptime to track agent restarts and reboots'"); - } + } - if (!db_table_exists('plugin_monitor_dashboards')) { - db_execute("CREATE TABLE IF NOT EXISTS plugin_monitor_dashboards ( + if (!db_table_exists('plugin_monitor_dashboards')) { + db_execute("CREATE TABLE IF NOT EXISTS plugin_monitor_dashboards ( id int(10) unsigned auto_increment, user_id int(10) unsigned DEFAULT '0', name varchar(128) DEFAULT '', @@ -1089,30 +1132,31 @@ function monitorSetupTable() { KEY user_id (user_id)) ENGINE=InnoDB COMMENT='Stores predefined dashboard information for a user or users'"); - } - - api_plugin_db_add_column('monitor', 'host', ['name' => 'monitor', 'type' => 'char(3)', 'NULL' => true, 'default' => 'on', 'after' => 'disabled']); - api_plugin_db_add_column('monitor', 'host', ['name' => 'monitor_text', 'type' => 'varchar(1024)', 'default' => '', 'NULL' => false, 'after' => 'monitor']); - api_plugin_db_add_column('monitor', 'host', ['name' => 'monitor_criticality', 'type' => 'tinyint', 'unsigned' => true, 'NULL' => false, 'default' => '0', 'after' => 'monitor_text']); - api_plugin_db_add_column('monitor', 'host', ['name' => 'monitor_warn', 'type' => 'double', 'NULL' => false, 'default' => '0', 'after' => 'monitor_criticality']); - api_plugin_db_add_column('monitor', 'host', ['name' => 'monitor_alert', 'type' => 'double', 'NULL' => false, 'default' => '0', 'after' => 'monitor_warn']); - api_plugin_db_add_column('monitor', 'host', ['name' => 'monitor_icon', 'type' => 'varchar(30)', 'NULL' => false, 'default' => '', 'after' => 'monitor_alert']); + } + + api_plugin_db_add_column('monitor', 'host', ['name' => 'monitor', 'type' => 'char(3)', 'NULL' => true, 'default' => 'on', 'after' => 'disabled']); + api_plugin_db_add_column('monitor', 'host', ['name' => 'monitor_text', 'type' => 'varchar(1024)', 'default' => '', 'NULL' => false, 'after' => 'monitor']); + api_plugin_db_add_column('monitor', 'host', ['name' => 'monitor_criticality', 'type' => 'tinyint', 'unsigned' => true, 'NULL' => false, 'default' => '0', 'after' => 'monitor_text']); + api_plugin_db_add_column('monitor', 'host', ['name' => 'monitor_warn', 'type' => 'double', 'NULL' => false, 'default' => '0', 'after' => 'monitor_criticality']); + api_plugin_db_add_column('monitor', 'host', ['name' => 'monitor_alert', 'type' => 'double', 'NULL' => false, 'default' => '0', 'after' => 'monitor_warn']); + api_plugin_db_add_column('monitor', 'host', ['name' => 'monitor_icon', 'type' => 'varchar(30)', 'NULL' => false, 'default' => '', 'after' => 'monitor_alert']); } -function monitorPollerBottom() { - global $config; +function monitorPollerBottom() +{ + global $config; - if ($config['poller_id'] == 1) { - include_once($config['library_path'] . '/poller.php'); + if ($config['poller_id'] == 1) { + include_once($config['library_path'] . '/poller.php'); - $command_string = trim(read_config_option('path_php_binary')); + $command_string = trim(read_config_option('path_php_binary')); - if (trim($command_string) == '') { - $command_string = 'php'; - } + if (trim($command_string) == '') { + $command_string = 'php'; + } - $extra_args = ' -q ' . $config['base_path'] . '/plugins/monitor/poller_monitor.php'; + $extra_args = ' -q ' . $config['base_path'] . '/plugins/monitor/poller_monitor.php'; - exec_background($command_string, $extra_args); - } + exec_background($command_string, $extra_args); + } } diff --git a/sounds/index.php b/sounds/index.php index 828ecbe..362957c 100644 --- a/sounds/index.php +++ b/sounds/index.php @@ -1,4 +1,5 @@ Date: Sun, 1 Mar 2026 22:04:55 -0500 Subject: [PATCH 13/26] Update db_functions.php --- db_functions.php | 8 -------- 1 file changed, 8 deletions(-) diff --git a/db_functions.php b/db_functions.php index f1d8b34..ae727f6 100644 --- a/db_functions.php +++ b/db_functions.php @@ -247,14 +247,6 @@ function getHostsDownOrTriggeredByPermission($prescan) return $result; } -/* -// This function is not used and contains an undefined variable - -function getHostTreeArray() { - return $leafs; -} -*/ - function getHostNonTreeArray() { $leafs = []; From 3bfd39038ef0a4725527ff026b284a795f57bc50 Mon Sep 17 00:00:00 2001 From: Sean Mancini Date: Sun, 1 Mar 2026 22:10:15 -0500 Subject: [PATCH 14/26] refactor functions Refactor rending function and Ajax call functions Lowe cognetive complexity prepare for easier testing --- monitor_controller.php | 535 +++++++++++++++++++++-------------------- monitor_render.php | 337 ++++++++++++++------------ 2 files changed, 455 insertions(+), 417 deletions(-) diff --git a/monitor_controller.php b/monitor_controller.php index 86cac36..3bcf167 100644 --- a/monitor_controller.php +++ b/monitor_controller.php @@ -305,44 +305,26 @@ function drawFilterDropdown($id, $title, $settings = [], $value = null) } } -function drawFilterAndStatus() +function monitorGetDashboardOptions() { - global $config, $criticalities, $page_refresh_interval, $classes, $monitor_grouping; - global $monitor_view_type, $monitor_status, $monitor_trim; - global $dozoombgndcolor, $dozoomrefresh, $zoom_hist_status, $zoom_hist_size, $mon_zoom_state; - global $new_form, $new_title, $item_rows; - - $header = __('Monitor Filter [ Last Refresh: %s ]', date('g:i:s a', time()), 'monitor') . (get_request_var('refresh') < 99999 ? __(' [ Refresh Again in %d Seconds ]', get_request_var('refresh'), 'monitor') : '') . (get_request_var('view') == 'list' ? __('[ Showing only first 30 Devices ]', 'monitor') : '') . ''; - - html_start_box($header, '100%', false, '3', 'center', ''); - - print '' . PHP_EOL; - print '
' . PHP_EOL; - - // First line of filter - print '' . PHP_EOL; - print '' . PHP_EOL; - - $dashboards[0] = __('Unsaved', 'monitor'); + $dashboards = [0 => __('Unsaved', 'monitor')]; $dashboards += array_rekey( db_fetch_assoc_prepared( 'SELECT id, name - FROM plugin_monitor_dashboards - WHERE user_id = 0 OR user_id = ? - ORDER BY name', + FROM plugin_monitor_dashboards + WHERE user_id = 0 OR user_id = ? + ORDER BY name', [$_SESSION['sess_user_id']] ), 'id', 'name' ); - $name = db_fetch_cell_prepared( - 'SELECT name - FROM plugin_monitor_dashboards - WHERE id = ?', - [get_request_var('dashboard')] - ); + return $dashboards; +} +function monitorGetZoomDropdownState(&$dozoombgndcolor) +{ $mon_zoom_status = null; $mon_zoom_size = null; @@ -354,8 +336,6 @@ function drawFilterAndStatus() } else { if (isset($_SESSION['mon_zoom_hist_status'])) { $mon_zoom_status = $_SESSION['mon_zoom_hist_status']; - } else { - $mon_zoom_status = null; } if (isset($_SESSION['mon_zoom_hist_size'])) { @@ -366,49 +346,39 @@ function drawFilterAndStatus() } $mon_zoom_size = $_SESSION['mon_zoom_hist_size']; - } else { - $mon_zoom_size = null; } } } + return [$mon_zoom_status, $mon_zoom_size]; +} + +function monitorRenderPrimaryFilterRow($dashboards, $monitor_status, $monitor_view_type, $monitor_grouping, $item_rows, $mon_zoom_status) +{ drawFilterDropdown('dashboard', __('Layout', 'monitor'), $dashboards); drawFilterDropdown('status', __('Status', 'monitor'), $monitor_status, $mon_zoom_status); drawFilterDropdown('view', __('View', 'monitor'), $monitor_view_type); drawFilterDropdown('grouping', __('Grouping', 'monitor'), $monitor_grouping); drawFilterDropdown('rows', __('Devices', 'monitor'), $item_rows); - // Buttons print ''; - print ''; - print '
' . PHP_EOL; - print '' . PHP_EOL; - print '' . PHP_EOL; - print '' . PHP_EOL; - print '' . PHP_EOL; if (get_request_var('dashboard') > 0) { print '' . PHP_EOL; - } - - if (get_request_var('dashboard') > 0) { print '' . PHP_EOL; } print '' . PHP_EOL; print '' . PHP_EOL; print '
'; - - // Second line of filter - print '' . PHP_EOL; - print '' . PHP_EOL; - print ''; - print ''; +} +function monitorRenderGroupingDropdowns($classes, $criticalities, $monitor_trim, $page_refresh_interval, $mon_zoom_size) +{ drawFilterDropdown('crit', __('Criticality', 'monitor'), $criticalities); if (get_request_var('view') != 'list') { @@ -428,8 +398,7 @@ function drawFilterAndStatus() if (cacti_sizeof($trees_allowed)) { $trees_prefix = [-1 => __('All Trees', 'monitor')]; $trees_suffix = [-2 => __('Non-Tree Devices', 'monitor')]; - - $trees = $trees_prefix + $trees_allowed + $trees_suffix; + $trees = $trees_prefix + $trees_allowed + $trees_suffix; } } @@ -442,8 +411,8 @@ function drawFilterAndStatus() if (get_request_var('grouping') == 'site') { $sites = array_rekey( db_fetch_assoc('SELECT id, name - FROM sites - ORDER BY name'), + FROM sites + ORDER BY name'), 'id', 'name' ); @@ -451,8 +420,7 @@ function drawFilterAndStatus() if (cacti_sizeof($sites)) { $sites_prefix = [-1 => __('All Sites', 'monitor')]; $sites_suffix = [-2 => __('Non-Site Devices', 'monitor')]; - - $sites = $sites_prefix + $sites + $sites_suffix; + $sites = $sites_prefix + $sites + $sites_suffix; } } @@ -463,13 +431,13 @@ function drawFilterAndStatus() $templates = []; $templates_allowed = array_rekey( db_fetch_assoc('SELECT ht.id, ht.name, COUNT(gl.id) AS graphs - FROM host_template AS ht - INNER JOIN host AS h - ON h.host_template_id = ht.id - INNER JOIN graph_local AS gl - ON h.id = gl.host_id - GROUP BY ht.id - HAVING graphs > 0'), + FROM host_template AS ht + INNER JOIN host AS h + ON h.host_template_id = ht.id + INNER JOIN graph_local AS gl + ON h.id = gl.host_id + GROUP BY ht.id + HAVING graphs > 0'), 'id', 'name' ); @@ -477,15 +445,17 @@ function drawFilterAndStatus() if (cacti_sizeof($templates_allowed)) { $templates_prefix = [-1 => __('All Templates', 'monitor')]; $templates_suffix = [-2 => __('Non-Templated Devices', 'monitor')]; - - $templates = $templates_prefix + $templates_allowed + $templates_suffix; + $templates = $templates_prefix + $templates_allowed + $templates_suffix; } drawFilterDropdown('template', __('Template', 'monitor'), $templates); } drawFilterDropdown('refresh', __('Refresh', 'monitor'), $page_refresh_interval); +} +function monitorRenderHiddenFilterInputs() +{ if (get_request_var('grouping') != 'tree') { print '' . PHP_EOL; } @@ -505,33 +475,30 @@ function drawFilterAndStatus() if (get_request_var('view') != 'default') { print '' . PHP_EOL; } +} - print ''; - print '
' . __('Search', 'monitor') . '
'; - print '
' . PHP_EOL; - - html_end_box(); - +function monitorGetZoomBackgroundStyle($dozoombgndcolor) +{ if ($dozoombgndcolor) { $mbcolora = db_fetch_row_prepared( 'SELECT * - FROM colors - WHERE id = ?', + FROM colors + WHERE id = ?', [read_user_setting('monitor_error_background')] ); $monitor_error_fontsize = read_user_setting('monitor_error_fontsize') . 'px'; - - if (cacti_sizeof($mbcolora)) { - $mbcolor = '#' . $mbcolora['hex']; - } else { - $mbcolor = 'snow'; - } + $mbcolor = cacti_sizeof($mbcolora) ? '#' . $mbcolora['hex'] : 'snow'; } else { $mbcolor = ''; $monitor_error_fontsize = '10px'; } + return [$mbcolor, $monitor_error_fontsize]; +} + +function monitorPrintJsBootstrap($config, $mbcolor, $monitor_error_fontsize, $dozoomrefresh, $new_form, $new_title) +{ $monitor_js_config = [ 'mbColor' => $mbcolor, 'monitorFont' => $monitor_error_fontsize, @@ -549,7 +516,52 @@ function drawFilterAndStatus() json_encode($monitor_js_config, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) . ';'; print ''; +} + +function drawFilterAndStatus() +{ + global $config, $criticalities, $page_refresh_interval, $classes, $monitor_grouping; + global $monitor_view_type, $monitor_status, $monitor_trim; + global $dozoombgndcolor, $dozoomrefresh, $zoom_hist_status, $zoom_hist_size, $mon_zoom_state; + global $new_form, $new_title, $item_rows; + + $header = __('Monitor Filter [ Last Refresh: %s ]', date('g:i:s a', time()), 'monitor') . (get_request_var('refresh') < 99999 ? __(' [ Refresh Again in %d Seconds ]', get_request_var('refresh'), 'monitor') : '') . (get_request_var('view') == 'list' ? __('[ Showing only first 30 Devices ]', 'monitor') : '') . ''; + + html_start_box($header, '100%', false, '3', 'center', ''); + print '' . PHP_EOL; + print '
' . PHP_EOL; + + print '' . PHP_EOL; + print '' . PHP_EOL; + [$mon_zoom_status, $mon_zoom_size] = monitorGetZoomDropdownState($dozoombgndcolor); + monitorRenderPrimaryFilterRow( + monitorGetDashboardOptions(), + $monitor_status, + $monitor_view_type, + $monitor_grouping, + $item_rows, + $mon_zoom_status + ); + print ''; + print '
'; + + // Second line of filter + print '' . PHP_EOL; + print '' . PHP_EOL; + print ''; + print ''; + monitorRenderGroupingDropdowns($classes, $criticalities, $monitor_trim, $page_refresh_interval, $mon_zoom_size); + monitorRenderHiddenFilterInputs(); + + print ''; + print '
' . __('Search', 'monitor') . '
'; + print '
' . PHP_EOL; + + html_end_box(); + + [$mbcolor, $monitor_error_fontsize] = monitorGetZoomBackgroundStyle($dozoombgndcolor); + monitorPrintJsBootstrap($config, $mbcolor, $monitor_error_fontsize, $dozoomrefresh, $new_form, $new_title); } function getMuteText() @@ -822,220 +834,219 @@ function validateRequestVars($force = false) // ================= input validation ================= } - -function ajaxStatus() +function monitorLoadAjaxStatusHost($id, $thold_hosts, $config) { - global $thold_hosts, $config, $icolorsdisplay, $iclasses, $criticalities; + $host = db_fetch_row_prepared( + 'SELECT * + FROM host + WHERE id = ?', + [$id] + ); - $tholds = 0; + if (!cacti_sizeof($host)) { + return []; + } - validateRequestVars(); + $host['anchor'] = $config['url_path'] . 'graph_view.php?action=preview&reset=1&host_id=' . $host['id']; - if (isset_request_var('id') && get_filter_request_var('id')) { - $id = get_request_var('id'); - $size = get_request_var('size'); + if ($host['status'] == 3 && array_key_exists($host['id'], $thold_hosts)) { + $host['status'] = 4; + $host['anchor'] = $config['url_path'] . 'plugins/thold/thold_graph.php?action=thold&reset=true&status=1&host_id=' . $host['id']; + } - $host = db_fetch_row_prepared( - 'SELECT * - FROM host - WHERE id = ?', - [$id] - ); + if ($host['availability_method'] == 0) { + $host['status'] = 6; + } - if (!cacti_sizeof($host)) { - cacti_log('Attempted to retrieve status for missing Device ' . $id, false, 'MONITOR', POLLER_VERBOSITY_HIGH); + $host['real_status'] = getHostStatus($host, true); + $host['status'] = getHostStatus($host); - return false; - } + return $host; +} - $host['anchor'] = $config['url_path'] . 'graph_view.php?action=preview&reset=1&host_id=' . $host['id']; +function monitorGetAjaxStatusLinks($host, $config) +{ + $links = ''; - if ($host['status'] == 3 && array_key_exists($host['id'], $thold_hosts)) { - $host['status'] = 4; - $host['anchor'] = $config['url_path'] . 'plugins/thold/thold_graph.php?action=thold&reset=true&status=1&host_id=' . $host['id']; - } + if (api_plugin_user_realm_auth('host.php')) { + $host_link = html_escape($config['url_path'] . 'host.php?action=edit&id=' . $host['id']); + $links .= '
'; + } + + $graphs = db_fetch_cell_prepared( + 'SELECT COUNT(*) + FROM graph_local + WHERE host_id = ?', + [$host['id']] + ); - if ($host['availability_method'] == 0) { - $host['status'] = 6; + if ($graphs > 0) { + $graph_link = html_escape($config['url_path'] . 'graph_view.php?action=preview&reset=1&host_id=' . $host['id']); + $links .= '
'; + } + + if (api_plugin_is_enabled('thold')) { + $tholds = db_fetch_cell_prepared( + 'SELECT count(*) + FROM thold_data + WHERE host_id = ?', + [$host['id']] + ); + + if ($tholds) { + $thold_link = html_escape($config['url_path'] . 'plugins/thold/thold_graph.php?action=thold&reset=true&status=1&host_id=' . $host['id']); + $links .= '
'; } + } - $host['real_status'] = getHostStatus($host, true); - $host['status'] = getHostStatus($host); + if (api_plugin_is_enabled('syslog') && api_plugin_user_realm_auth('syslog.php')) { + include($config['base_path'] . '/plugins/syslog/config.php'); + include_once($config['base_path'] . '/plugins/syslog/functions.php'); - if (cacti_sizeof($host)) { - if (api_plugin_user_realm_auth('host.php')) { - $host_link = html_escape($config['url_path'] . 'host.php?action=edit&id=' . $host['id']); - } + $syslog_logs = syslog_db_fetch_cell_prepared( + 'SELECT count(*) + FROM syslog_logs + WHERE host = ?', + [$host['hostname']] + ); - // Get the number of graphs - $graphs = db_fetch_cell_prepared( - 'SELECT COUNT(*) - FROM graph_local - WHERE host_id = ?', - [$host['id']] - ); + $syslog_host = syslog_db_fetch_cell_prepared( + 'SELECT host_id + FROM syslog_hosts + WHERE host = ?', + [$host['hostname']] + ); - if ($graphs > 0) { - $graph_link = html_escape($config['url_path'] . 'graph_view.php?action=preview&reset=1&host_id=' . $host['id']); - } + if ($syslog_logs && $syslog_host) { + $syslog_log_link = html_escape($config['url_path'] . 'plugins/syslog/syslog/syslog.php?reset=1&tab=alerts&host_id=' . $syslog_host); + $links .= '
'; + } - // Get the number of thresholds - if (api_plugin_is_enabled('thold')) { - $tholds = db_fetch_cell_prepared( - 'SELECT count(*) - FROM thold_data - WHERE host_id = ?', - [$host['id']] - ); - - if ($tholds) { - $thold_link = html_escape($config['url_path'] . 'plugins/thold/thold_graph.php?action=thold&reset=true&status=1&host_id=' . $host['id']); - } - } + if ($syslog_host) { + $syslog_link = html_escape($config['url_path'] . 'plugins/syslog/syslog/syslog.php?reset=1&tab=syslog&host_id=' . $syslog_host); + $links .= '
'; + } + } - // Get the number of syslogs - if (api_plugin_is_enabled('syslog') && api_plugin_user_realm_auth('syslog.php')) { - include($config['base_path'] . '/plugins/syslog/config.php'); - include_once($config['base_path'] . '/plugins/syslog/functions.php'); - - $syslog_logs = syslog_db_fetch_cell_prepared( - 'SELECT count(*) - FROM syslog_logs - WHERE host = ?', - [$host['hostname']] - ); - - $syslog_host = syslog_db_fetch_cell_prepared( - 'SELECT host_id - FROM syslog_hosts - WHERE host = ?', - [$host['hostname']] - ); - - if ($syslog_logs && $syslog_host) { - $syslog_log_link = html_escape($config['url_path'] . 'plugins/syslog/syslog/syslog.php?reset=1&tab=alerts&host_id=' . $syslog_host); - } + return $links; +} - if ($syslog_host) { - $syslog_link = html_escape($config['url_path'] . 'plugins/syslog/syslog/syslog.php?reset=1&tab=syslog&host_id=' . $syslog_host); - } - } else { - $syslog_logs = 0; - $syslog_host = 0; - } +function monitorRenderAjaxStatusTooltip($host, $size, $links, $site, $sdisplay, $iclass, $criticalities) +{ + return " + + + + + + + + + + + + + + ' . (isset($host['monitor_criticality']) && $host['monitor_criticality'] > 0 ? ' + + + + ' : '') . ' + + + + " . ($host['status'] < 3 || $host['status'] == 5 ? ' + + + + ' : '') . ($host['availability_method'] > 0 ? ' + + + + ' : '') . ($host['availability_method'] > 0 ? " + + + + ' : '') . (isset($host['monitor_warn']) && ($host['monitor_warn'] > 0 || $host['monitor_alert'] > 0) ? " + + + + ' : '') . ' + + + + + + + + + + + + ' . ($host['snmp_version'] > 0 && ($host['status'] == 3 || $host['status'] == 2) ? ' + + + + + + + + + + + + + + + + ' : '') . ($host['notes'] != '' ? ' + + + + ' : '') . " + + +
" . __('Device Status Information', 'monitor') . '
' . __('Device:', 'monitor') . "" . html_escape($host['description']) . '
' . __('Site:', 'monitor') . '' . html_escape($site) . '
' . __('Location:', 'monitor') . '' . html_escape($host['location']) . '
' . __('Criticality:', 'monitor') . '' . html_escape($criticalities[$host['monitor_criticality']]) . '
' . __('Status:', 'monitor') . "$sdisplay
' . __('Admin Note:', 'monitor') . "" . html_escape($host['monitor_text']) . '
' . __('IP/Hostname:', 'monitor') . '' . html_escape($host['hostname']) . '
" . __('Curr/Avg:', 'monitor') . '' . __('%d ms', $host['cur_time'], 'monitor') . ' / ' . __('%d ms', $host['avg_time'], 'monitor') . '
" . __('Warn/Alert:', 'monitor') . '' . __('%0.2d ms', $host['monitor_warn'], 'monitor') . ' / ' . __('%0.2d ms', $host['monitor_alert'], 'monitor') . '
' . __('Last Fail:', 'monitor') . '' . html_escape($host['status_fail_date']) . '
' . __('Time In State:', 'monitor') . '' . get_timeinstate($host) . '
' . __('Availability:', 'monitor') . '' . round($host['availability'], 2) . ' %
' . __('Agent Uptime:', 'monitor') . '' . ($host['status'] == 3 || $host['status'] == 5 ? monitorPrintHostTime($host['snmp_sysUpTimeInstance']) : __('N/A', 'monitor')) . "
" . __('Sys Description:', 'monitor') . '' . html_escape(monitorTrim($host['snmp_sysDescr'])) . '
' . __('Location:', 'monitor') . '' . html_escape(monitorTrim($host['snmp_sysLocation'])) . '
' . __('Contact:', 'monitor') . '' . html_escape(monitorTrim($host['snmp_sysContact'])) . '
' . __('Notes:', 'monitor') . '' . html_escape($host['notes']) . '

$links
"; +} - $links = ''; - if (isset($host_link)) { - $links .= '
'; - } +function ajaxStatus() +{ + global $thold_hosts, $config, $iclasses, $criticalities; - if (isset($graph_link)) { - $links .= '
'; - } + validateRequestVars(); - if (isset($thold_link)) { - $links .= '
'; - } + if (!isset_request_var('id') || !get_filter_request_var('id')) { + return; + } - if (isset($syslog_log_link)) { - $links .= '
'; - } + $id = get_request_var('id'); + $size = get_request_var('size'); + $host = monitorLoadAjaxStatusHost($id, $thold_hosts, $config); - if (isset($syslog_link)) { - $links .= '
'; - } + if (!cacti_sizeof($host)) { + cacti_log('Attempted to retrieve status for missing Device ' . $id, false, 'MONITOR', POLLER_VERBOSITY_HIGH); - if (strtotime($host['status_fail_date']) < 86400) { - $host['status_fail_date'] = __('Never', 'monitor'); - } + return false; + } - $iclass = $iclasses[$host['status']]; - $sdisplay = getHostStatusDescription($host['real_status']); - $site = db_fetch_cell_prepared('SELECT name FROM sites WHERE id = ?', [$host['site_id']]); + $links = monitorGetAjaxStatusLinks($host, $config); - if ($host['location'] == '') { - $host['location'] = __('Unspecified', 'monitor'); - } + if (strtotime($host['status_fail_date']) < 86400) { + $host['status_fail_date'] = __('Never', 'monitor'); + } - if ($site == '') { - $site = __('None', 'monitor'); - } + if ($host['location'] == '') { + $host['location'] = __('Unspecified', 'monitor'); + } - print " - - - - - - - - - - - - - - ' . (isset($host['monitor_criticality']) && $host['monitor_criticality'] > 0 ? ' - - - - ' : '') . ' - - - - " . ($host['status'] < 3 || $host['status'] == 5 ? ' - - - - ' : '') . ($host['availability_method'] > 0 ? ' - - - - ' : '') . ($host['availability_method'] > 0 ? " - - - - ' : '') . (isset($host['monitor_warn']) && ($host['monitor_warn'] > 0 || $host['monitor_alert'] > 0) ? " - - - - ' : '') . ' - - - - - - - - - - - - ' . ($host['snmp_version'] > 0 && ($host['status'] == 3 || $host['status'] == 2) ? ' - - - - - - - - - - - - - - - - ' : '') . ($host['notes'] != '' ? ' - - - - ' : '') . " - - -
" . __('Device Status Information', 'monitor') . '
' . __('Device:', 'monitor') . "" . html_escape($host['description']) . '
' . __('Site:', 'monitor') . '' . html_escape($site) . '
' . __('Location:', 'monitor') . '' . html_escape($host['location']) . '
' . __('Criticality:', 'monitor') . '' . html_escape($criticalities[$host['monitor_criticality']]) . '
' . __('Status:', 'monitor') . "$sdisplay
' . __('Admin Note:', 'monitor') . "" . html_escape($host['monitor_text']) . '
' . __('IP/Hostname:', 'monitor') . '' . html_escape($host['hostname']) . '
" . __('Curr/Avg:', 'monitor') . '' . __('%d ms', $host['cur_time'], 'monitor') . ' / ' . __('%d ms', $host['avg_time'], 'monitor') . '
" . __('Warn/Alert:', 'monitor') . '' . __('%0.2d ms', $host['monitor_warn'], 'monitor') . ' / ' . __('%0.2d ms', $host['monitor_alert'], 'monitor') . '
' . __('Last Fail:', 'monitor') . '' . html_escape($host['status_fail_date']) . '
' . __('Time In State:', 'monitor') . '' . get_timeinstate($host) . '
' . __('Availability:', 'monitor') . '' . round($host['availability'], 2) . ' %
' . __('Agent Uptime:', 'monitor') . '' . ($host['status'] == 3 || $host['status'] == 5 ? monitorPrintHostTime($host['snmp_sysUpTimeInstance']) : __('N/A', 'monitor')) . "
" . __('Sys Description:', 'monitor') . '' . html_escape(monitorTrim($host['snmp_sysDescr'])) . '
' . __('Location:', 'monitor') . '' . html_escape(monitorTrim($host['snmp_sysLocation'])) . '
' . __('Contact:', 'monitor') . '' . html_escape(monitorTrim($host['snmp_sysContact'])) . '
' . __('Notes:', 'monitor') . '' . html_escape($host['notes']) . '

$links
"; - } + $iclass = $iclasses[$host['status']]; + $sdisplay = getHostStatusDescription($host['real_status']); + $site = db_fetch_cell_prepared('SELECT name FROM sites WHERE id = ?', [$host['site_id']]); + + if ($site == '') { + $site = __('None', 'monitor'); } + + print monitorRenderAjaxStatusTooltip($host, $size, $links, $site, $sdisplay, $iclass, $criticalities); } diff --git a/monitor_render.php b/monitor_render.php index 01eaf3a..8c814b2 100644 --- a/monitor_render.php +++ b/monitor_render.php @@ -366,211 +366,238 @@ function renderTemplate() return $result; } -function renderTree() +function monitorFilterAllowedHosts($hosts) { - global $maxchars; + $host_ids = []; - $result = ''; + foreach ($hosts as $index => $host) { + if (is_device_allowed($host['id'])) { + $host_ids[] = $host['id']; + } else { + unset($hosts[$index]); + } + } - $leafs = []; + return [array_values($hosts), $host_ids]; +} - if (get_request_var('tree') > 0) { - $sql_where = 'gt.id=' . get_request_var('tree'); - } else { - $sql_where = ''; +function monitorGetTreeRenderMaxLength() +{ + $maxlen = 10; + + if (get_request_var('view') == 'default') { + $maxlen = db_fetch_cell("SELECT MAX(LENGTH(description)) + FROM host AS h + INNER JOIN graph_tree_items AS gti + ON gti.host_id = h.id + WHERE disabled = '' + AND deleted = ''"); } - if (get_request_var('tree') != -2) { - $tree_list = get_allowed_trees(false, false, $sql_where, 'sequence'); - } else { - $tree_list = []; - } + return getMonitorTrimLength($maxlen); +} - $function = 'renderHeader' . ucfirst(get_request_var('view')); +function monitorBuildTreeTitles($branchWhost) +{ + $titles = []; + $ptree = ''; - if (function_exists($function)) { - $hosts = []; + foreach ($branchWhost as $b) { + if ($ptree != $b['graph_tree_id']) { + $titles[$b['graph_tree_id'] . ':0'] = __('Root Branch', 'monitor'); + $ptree = $b['graph_tree_id']; + } - // Call the custom render_header_ function - $result .= $function(); + if ($b['parent'] > 0) { + $titles[$b['graph_tree_id'] . ':' . $b['parent']] = db_fetch_cell_prepared( + 'SELECT title + FROM graph_tree_items + WHERE id = ? + AND graph_tree_id = ? + ORDER BY position', + [$b['parent'], $b['graph_tree_id']] + ); + } } - if (cacti_sizeof($tree_list)) { - $ptree = ''; + return $titles; +} - foreach ($tree_list as $tree) { - $tree_ids[$tree['id']] = $tree['id']; - } +function monitorRenderTreeTitleSections($titles, $maxlen) +{ + $result = ''; + $ptree = ''; + + foreach ($titles as $index => $title) { + [$graph_tree_id, $parent] = explode(':', $index); + $oid = $parent; + $sql_where = ''; + $sql_join = ''; renderWhereJoin($sql_where, $sql_join); - $branchWhost_SQL = ("SELECT DISTINCT gti.graph_tree_id, gti.parent - FROM graph_tree_items AS gti - INNER JOIN graph_tree AS gt - ON gt.id = gti.graph_tree_id - INNER JOIN host AS h - ON h.id = gti.host_id - $sql_join - $sql_where - AND gti.host_id > 0 - AND gti.graph_tree_id IN (" . implode(',', $tree_ids) . ') - ORDER BY gt.sequence, gti.position'); + $hosts_sql = "SELECT h.*, IFNULL(s.name,' " . __('Non-Site Device', 'monitor') . " ') AS site_name + FROM host AS h + LEFT JOIN sites AS s + ON h.site_id = s.id + INNER JOIN graph_tree_items AS gti + ON h.id = gti.host_id + $sql_join + $sql_where + AND parent = ? + AND graph_tree_id = ? + GROUP BY h.id + ORDER BY gti.position"; + + $hosts = db_fetch_assoc_prepared($hosts_sql, [$oid, $graph_tree_id]); + + $tree_name = db_fetch_cell_prepared( + 'SELECT name + FROM graph_tree + WHERE id = ?', + [$graph_tree_id] + ); + + if ($ptree != $tree_name) { + if ($ptree != '') { + $result .= '
'; + } - // cacti_log($branchWhost_SQL); + $result .= "
+ +
+
+
"; + + $ptree = $tree_name; + } - $branchWhost = db_fetch_assoc($branchWhost_SQL); + if (!cacti_sizeof($hosts)) { + continue; + } - // Determine the correct width of the cell - $maxlen = 10; + [$hosts] = monitorFilterAllowedHosts($hosts); - if (get_request_var('view') == 'default') { - $maxlen = db_fetch_cell("SELECT MAX(LENGTH(description)) - FROM host AS h - INNER JOIN graph_tree_items AS gti - ON gti.host_id = h.id - WHERE disabled = '' - AND deleted = ''"); + if (!cacti_sizeof($hosts)) { + continue; } - $maxlen = getMonitorTrimLength($maxlen); - - if (cacti_sizeof($branchWhost)) { - foreach ($branchWhost as $b) { - if ($ptree != $b['graph_tree_id']) { - $titles[$b['graph_tree_id'] . ':0'] = __('Root Branch', 'monitor'); - $ptree = $b['graph_tree_id']; - } + $result .= "
"; - if ($b['parent'] > 0) { - $titles[$b['graph_tree_id'] . ':' . $b['parent']] = db_fetch_cell_prepared( - 'SELECT title - FROM graph_tree_items - WHERE id = ? - AND graph_tree_id = ? - ORDER BY position', - [$b['parent'], $b['graph_tree_id']] - ); - } - } + foreach ($hosts as $host) { + $result .= renderHost($host, true, $maxlen); + } - $ptree = ''; + $result .= '
'; + } - foreach ($titles as $index => $title) { - [$graph_tree_id, $parent] = explode(':', $index); + return $result; +} - $oid = $parent; +function monitorRenderNonTreeSection() +{ + $result = ''; - $sql_where = ''; - $sql_join = ''; + if (get_request_var('tree') >= 0) { + return $result; + } - renderWhereJoin($sql_where, $sql_join); + $hosts = getHostNonTreeArray(); - $hosts_sql = "SELECT h.*, IFNULL(s.name,' " . __('Non-Site Device', 'monitor') . " ') AS site_name - FROM host AS h - LEFT JOIN sites AS s - ON h.site_id = s.id - INNER JOIN graph_tree_items AS gti - ON h.id = gti.host_id - $sql_join - $sql_where - AND parent = ? - AND graph_tree_id = ? - GROUP BY h.id - ORDER BY gti.position"; + if (!cacti_sizeof($hosts)) { + return $result; + } - // cacti_log($hosts_sql); + [$hosts, $host_ids] = monitorFilterAllowedHosts($hosts); - $hosts = db_fetch_assoc_prepared($hosts_sql, [$oid, $graph_tree_id]); + if (!cacti_sizeof($hosts)) { + return $result; + } - $tree_name = db_fetch_cell_prepared( - 'SELECT name - FROM graph_tree - WHERE id = ?', - [$graph_tree_id] - ); + $maxlen = 10; - if ($ptree != $tree_name) { - if ($ptree != '') { - $result .= '
'; - } + if (get_request_var('view') == 'default' && cacti_sizeof($host_ids)) { + $maxlen = db_fetch_cell('SELECT MAX(LENGTH(description)) + FROM host AS h + WHERE id IN (' . implode(',', $host_ids) . ") + AND h.deleted = ''"); + } - $result .= "
- -
-
-
"; + $maxlen = getMonitorTrimLength($maxlen); - $ptree = $tree_name; - } + $result .= "
+ +
+
"; - if (cacti_sizeof($hosts)) { - foreach ($hosts as $index => $host) { - if (is_device_allowed($host['id'])) { - $host_ids[] = $host['id']; - } else { - unset($hosts[$index]); - } - } + foreach ($hosts as $leaf) { + $result .= renderHost($leaf, true, $maxlen); + } - $class = get_request_var('size'); + $result .= '
'; - $result .= "
"; + return $result; +} - foreach ($hosts as $host) { - $result .= renderHost($host, true, $maxlen); - } +function renderTree() +{ + $result = ''; - $result .= '
'; - } - } - } + if (get_request_var('tree') > 0) { + $sql_where = 'gt.id=' . get_request_var('tree'); + } else { + $sql_where = ''; + } - $result .= '
'; + if (get_request_var('tree') != -2) { + $tree_list = get_allowed_trees(false, false, $sql_where, 'sequence'); + } else { + $tree_list = []; } - // begin others - lets get the monitor items that are not associated with any tree - if (get_request_var('tree') < 0) { - $hosts = getHostNonTreeArray(); + $function = 'renderHeader' . ucfirst(get_request_var('view')); - if (cacti_sizeof($hosts)) { - foreach ($hosts as $index => $host) { - if (is_device_allowed($host['id'])) { - $host_ids[] = $host['id']; - } else { - unset($hosts[$index]); - } - } + if (function_exists($function)) { + $hosts = []; - // Determine the correct width of the cell - $maxlen = 10; + // Call the custom render_header_ function + $result .= $function(); + } - if (get_request_var('view') == 'default') { - if (cacti_sizeof($host_ids)) { - $maxlen = db_fetch_cell('SELECT MAX(LENGTH(description)) - FROM host AS h - WHERE id IN (' . implode(',', $host_ids) . ") - AND h.deleted = ''"); - } - } - $maxlen = getMonitorTrimLength($maxlen); + if (cacti_sizeof($tree_list)) { + $tree_ids = []; + foreach ($tree_list as $tree) { + $tree_ids[$tree['id']] = $tree['id']; + } - $result .= "
- -
-
"; - - foreach ($hosts as $leaf) { - $result .= renderHost($leaf, true, $maxlen); - } + renderWhereJoin($sql_where, $sql_join); + + $branchWhost = db_fetch_assoc("SELECT DISTINCT gti.graph_tree_id, gti.parent + FROM graph_tree_items AS gti + INNER JOIN graph_tree AS gt + ON gt.id = gti.graph_tree_id + INNER JOIN host AS h + ON h.id = gti.host_id + $sql_join + $sql_where + AND gti.host_id > 0 + AND gti.graph_tree_id IN (" . implode(',', $tree_ids) . ') + ORDER BY gt.sequence, gti.position'); - $result .= '
'; + if (cacti_sizeof($branchWhost)) { + $titles = monitorBuildTreeTitles($branchWhost); + $result .= monitorRenderTreeTitleSections($titles, monitorGetTreeRenderMaxLength()); } + + $result .= '
'; } + $result .= monitorRenderNonTreeSection(); + $function = 'renderFooter' . ucfirst(get_request_var('view')); if (function_exists($function)) { From f441199efeef8d34c7930181fd39b2b9d018a4b9 Mon Sep 17 00:00:00 2001 From: Sean Mancini Date: Sun, 1 Mar 2026 22:14:59 -0500 Subject: [PATCH 15/26] Add missing docblocks --- db_functions.php | 43 ++++++++- monitor_controller.php | 193 ++++++++++++++++++++++++++++++++++++++++ monitor_render.php | 197 ++++++++++++++++++++++++++++++++++++++++- setup.php | 145 ++++++++++++++++++++++++++++++ 4 files changed, 572 insertions(+), 6 deletions(-) diff --git a/db_functions.php b/db_functions.php index ae727f6..5ac7ec7 100644 --- a/db_functions.php +++ b/db_functions.php @@ -23,6 +23,11 @@ +-------------------------------------------------------------------------+ */ +/** + * Build thold SQL predicate based on selected monitor status filter. + * + * @return string + */ function getTholdWhere() { if (get_request_var('status') == '2') { // breached @@ -35,6 +40,11 @@ function getTholdWhere() } } +/** + * Get host ids currently associated with triggered/breached thresholds. + * + * @return array + */ function checkTholds() { $thold_hosts = []; @@ -55,6 +65,17 @@ function checkTholds() } +/** + * Append an IN-clause fragment to an existing SQL where string. + * + * @param string $sql_where SQL where fragment, updated in place. + * @param string $sql_join Join token used between predicates (e.g. AND/OR). + * @param string $sql_field Field name to compare with IN list. + * @param string $sql_data Comma-delimited values for the IN list. + * @param string $sql_suffix Optional suffix appended inside predicate. + * + * @return void + */ function renderGroupConcat(&$sql_where, $sql_join, $sql_field, $sql_data, $sql_suffix = '') { // Remove empty entries if something was returned @@ -67,6 +88,14 @@ function renderGroupConcat(&$sql_where, $sql_join, $sql_field, $sql_data, $sql_s } } +/** + * Build core monitor host query join/where fragments from current filters. + * + * @param string $sql_where SQL where fragment, updated in place. + * @param string $sql_join SQL join fragment, updated in place. + * + * @return void + */ function renderWhereJoin(&$sql_where, &$sql_join) { if (get_request_var('crit') > 0) { @@ -170,8 +199,13 @@ function renderWhereJoin(&$sql_where, &$sql_join) } } -// Render functions - +/** + * Return host ids that are down/triggered and visible to current user. + * + * @param bool $prescan Whether to use prescan severity threshold. + * + * @return array + */ function getHostsDownOrTriggeredByPermission($prescan) { global $render_style; @@ -247,6 +281,11 @@ function getHostsDownOrTriggeredByPermission($prescan) return $result; } +/** + * Return non-tree monitor hosts after applying current filters. + * + * @return array + */ function getHostNonTreeArray() { $leafs = []; diff --git a/monitor_controller.php b/monitor_controller.php index 3bcf167..1e1456a 100644 --- a/monitor_controller.php +++ b/monitor_controller.php @@ -23,6 +23,11 @@ +-------------------------------------------------------------------------+ */ +/** + * Load saved dashboard URL parameters into request scope. + * + * @return void + */ function loadDashboardSettings() { $dashboard = get_filter_request_var('dashboard'); @@ -50,6 +55,11 @@ function loadDashboardSettings() } } +/** + * Render monitor page including filters, host layout, legend, and audio. + * + * @return void + */ function drawPage() { global $config, $iclasses, $icolorsdisplay, $mon_zoom_state, $dozoomrefresh, $dozoombgndcolor, $font_sizes; @@ -139,11 +149,21 @@ function drawPage() bottom_footer(); } +/** + * Determine if alert audio is available and should be considered playable. + * + * @return bool + */ function isMonitorAudible() { return getMonitorSound() != ''; } +/** + * Resolve configured monitor sound file if it exists on disk. + * + * @return string + */ function getMonitorSound() { $sound = read_user_setting('monitor_sound', read_config_option('monitor_sound')); @@ -154,6 +174,11 @@ function getMonitorSound() return $exists ? $sound : ''; } +/** + * Update down-host request flags and mute state based on current host status. + * + * @return void + */ function findDownHosts() { $dhosts = getHostsDownOrTriggeredByPermission(false); @@ -178,6 +203,13 @@ function findDownHosts() } } +/** + * Remove recovered hosts from muted-host session state. + * + * @param array $dhosts Current down/triggered host id list. + * + * @return void + */ function unmuteUpNonTriggeredHosts($dhosts) { if (isset($_SESSION['monitor_muted_hosts'])) { @@ -189,24 +221,44 @@ function unmuteUpNonTriggeredHosts($dhosts) } } +/** + * Mute all currently down/triggered hosts for the active user session. + * + * @return void + */ function muteAllHosts() { $_SESSION['monitor_muted_hosts'] = getHostsDownOrTriggeredByPermission(false); muteUser(); } +/** + * Clear muted-host list and unmute monitor notifications for this user. + * + * @return void + */ function unmuteAllHosts() { $_SESSION['monitor_muted_hosts'] = []; unmuteUser(); } +/** + * Persist user mute state as enabled. + * + * @return void + */ function muteUser() { set_request_var('mute', 'true'); set_user_setting('monitor_mute', 'true'); } +/** + * Persist user mute state as disabled. + * + * @return void + */ function unmuteUser() { set_request_var('mute', 'false'); @@ -214,6 +266,11 @@ function unmuteUser() } +/** + * Build footer text describing currently active monitor filters. + * + * @return string + */ function getFilterText() { $filter = '
'; @@ -279,6 +336,16 @@ function getFilterText() return $filter; } +/** + * Render one filter dropdown (or hidden fallback input) for the monitor form. + * + * @param string $id Filter field id/name. + * @param string $title Filter display title. + * @param array $settings Option map of value => label. + * @param string|int $value Selected value override. + * + * @return void + */ function drawFilterDropdown($id, $title, $settings = [], $value = null) { if ($value == null) { @@ -305,6 +372,11 @@ function drawFilterDropdown($id, $title, $settings = [], $value = null) } } +/** + * Build dashboard dropdown option map for current user context. + * + * @return array + */ function monitorGetDashboardOptions() { $dashboards = [0 => __('Unsaved', 'monitor')]; @@ -323,6 +395,13 @@ function monitorGetDashboardOptions() return $dashboards; } +/** + * Resolve zoom override dropdown state from session values. + * + * @param bool $dozoombgndcolor Zoom background flag, updated in place. + * + * @return array{int|null, string|null} + */ function monitorGetZoomDropdownState(&$dozoombgndcolor) { $mon_zoom_status = null; @@ -353,6 +432,18 @@ function monitorGetZoomDropdownState(&$dozoombgndcolor) return [$mon_zoom_status, $mon_zoom_size]; } +/** + * Render the primary filter row (layout/status/view/grouping/actions). + * + * @param array $dashboards Dashboard option map. + * @param array $monitor_status Status filter options. + * @param array $monitor_view_type View mode options. + * @param array $monitor_grouping Grouping mode options. + * @param array $item_rows Device row count options. + * @param int|null $mon_zoom_status Zoom-driven status override. + * + * @return void + */ function monitorRenderPrimaryFilterRow($dashboards, $monitor_status, $monitor_view_type, $monitor_grouping, $item_rows, $mon_zoom_status) { drawFilterDropdown('dashboard', __('Layout', 'monitor'), $dashboards); @@ -377,6 +468,17 @@ function monitorRenderPrimaryFilterRow($dashboards, $monitor_status, $monitor_vi print ''; } +/** + * Render secondary grouping/filter controls for monitor page. + * + * @param array $classes Size class options. + * @param array $criticalities Criticality options. + * @param array $monitor_trim Trim options. + * @param array $page_refresh_interval Refresh options. + * @param string|null $mon_zoom_size Zoom-driven size override. + * + * @return void + */ function monitorRenderGroupingDropdowns($classes, $criticalities, $monitor_trim, $page_refresh_interval, $mon_zoom_size) { drawFilterDropdown('crit', __('Criticality', 'monitor'), $criticalities); @@ -454,6 +556,11 @@ function monitorRenderGroupingDropdowns($classes, $criticalities, $monitor_trim, drawFilterDropdown('refresh', __('Refresh', 'monitor'), $page_refresh_interval); } +/** + * Render hidden fallback input fields for inactive filters. + * + * @return void + */ function monitorRenderHiddenFilterInputs() { if (get_request_var('grouping') != 'tree') { @@ -477,6 +584,13 @@ function monitorRenderHiddenFilterInputs() } } +/** + * Resolve zoom background color/font style for page rendering. + * + * @param bool $dozoombgndcolor Whether zoom background styling is enabled. + * + * @return array{string, string} + */ function monitorGetZoomBackgroundStyle($dozoombgndcolor) { if ($dozoombgndcolor) { @@ -497,6 +611,18 @@ function monitorGetZoomBackgroundStyle($dozoombgndcolor) return [$mbcolor, $monitor_error_fontsize]; } +/** + * Emit JavaScript bootstrap config and monitor JS include tag. + * + * @param array $config Global Cacti config. + * @param string $mbcolor Monitor background color. + * @param string $monitor_error_fontsize Zoom mode font size. + * @param bool $dozoomrefresh Auto-refresh flag for zoom mode. + * @param string $new_form New dashboard dialog markup. + * @param string $new_title New dashboard dialog title. + * + * @return void + */ function monitorPrintJsBootstrap($config, $mbcolor, $monitor_error_fontsize, $dozoomrefresh, $new_form, $new_title) { $monitor_js_config = [ @@ -518,6 +644,11 @@ function monitorPrintJsBootstrap($config, $mbcolor, $monitor_error_fontsize, $do print ''; } +/** + * Render monitor filter area and inject page JS bootstrap config. + * + * @return void + */ function drawFilterAndStatus() { global $config, $criticalities, $page_refresh_interval, $classes, $monitor_grouping; @@ -564,6 +695,11 @@ function drawFilterAndStatus() monitorPrintJsBootstrap($config, $mbcolor, $monitor_error_fontsize, $dozoomrefresh, $new_form, $new_title); } +/** + * Get action label for mute button based on current audio capability. + * + * @return string + */ function getMuteText() { if (isMonitorAudible()) { @@ -573,6 +709,11 @@ function getMuteText() } } +/** + * Get action label for unmute/reset button based on audio capability. + * + * @return string + */ function getUnmuteText() { if (isMonitorAudible()) { @@ -582,6 +723,11 @@ function getUnmuteText() } } +/** + * Delete selected dashboard when owned by current user. + * + * @return void + */ function removeDashboard() { $dashboard = get_filter_request_var('dashboard'); @@ -616,6 +762,11 @@ function removeDashboard() set_request_var('dashboard', '0'); } +/** + * Save monitor filter settings to user prefs or selected dashboard record. + * + * @return void + */ function saveSettings() { if (isset_request_var('dashboard') && get_filter_request_var('dashboard') != 0) { @@ -731,6 +882,13 @@ function saveSettings() validateRequestVars(true); } +/** + * Validate and persist monitor request/session filter variables. + * + * @param bool $force Force reload from saved defaults. + * + * @return void + */ function validateRequestVars($force = false) { // ================= input validation and session storage ================= @@ -834,6 +992,15 @@ function validateRequestVars($force = false) // ================= input validation ================= } +/** + * Load host row and normalize status fields for AJAX tooltip rendering. + * + * @param int $id Host id. + * @param array $thold_hosts Threshold host map. + * @param array $config Global Cacti config. + * + * @return array + */ function monitorLoadAjaxStatusHost($id, $thold_hosts, $config) { $host = db_fetch_row_prepared( @@ -864,6 +1031,14 @@ function monitorLoadAjaxStatusHost($id, $thold_hosts, $config) return $host; } +/** + * Build quick-action link markup for AJAX tooltip panel. + * + * @param array $host Host row. + * @param array $config Global Cacti config. + * + * @return string + */ function monitorGetAjaxStatusLinks($host, $config) { $links = ''; @@ -931,6 +1106,19 @@ function monitorGetAjaxStatusLinks($host, $config) return $links; } +/** + * Render full hover tooltip table HTML for one host. + * + * @param array $host Host row. + * @param string $size Tooltip CSS size key. + * @param string $links Action links HTML. + * @param string $site Site display value. + * @param string $sdisplay Status display string. + * @param string $iclass Status CSS class. + * @param array $criticalities Criticality label map. + * + * @return string + */ function monitorRenderAjaxStatusTooltip($host, $size, $links, $site, $sdisplay, $iclass, $criticalities) { return " @@ -1010,6 +1198,11 @@ function monitorRenderAjaxStatusTooltip($host, $size, $links, $site, $sdisplay, } +/** + * Handle AJAX monitor status tooltip request and print response HTML. + * + * @return bool|null + */ function ajaxStatus() { global $thold_hosts, $config, $iclasses, $criticalities; diff --git a/monitor_render.php b/monitor_render.php index 8c814b2..358abda 100644 --- a/monitor_render.php +++ b/monitor_render.php @@ -23,6 +23,11 @@ +-------------------------------------------------------------------------+ */ +/** + * Render default monitor grouping output with active filters applied. + * + * @return string + */ function renderDefault() { global $maxchars; @@ -119,6 +124,11 @@ function renderDefault() return $result; } +/** + * Render host output grouped by site. + * + * @return string + */ function renderSite() { global $maxchars; @@ -238,6 +248,11 @@ function renderSite() return $result; } +/** + * Render host output grouped by host template. + * + * @return string + */ function renderTemplate() { global $maxchars; @@ -366,6 +381,13 @@ function renderTemplate() return $result; } +/** + * Filter out disallowed hosts and return normalized host/id lists. + * + * @param array $hosts Host rows. + * + * @return array{array, array} + */ function monitorFilterAllowedHosts($hosts) { $host_ids = []; @@ -381,6 +403,11 @@ function monitorFilterAllowedHosts($hosts) return [array_values($hosts), $host_ids]; } +/** + * Determine max description trim length for tree rendering context. + * + * @return int + */ function monitorGetTreeRenderMaxLength() { $maxlen = 10; @@ -397,6 +424,13 @@ function monitorGetTreeRenderMaxLength() return getMonitorTrimLength($maxlen); } +/** + * Build map of tree branch labels keyed by "tree_id:parent_id". + * + * @param array $branchWhost Tree branch/host rows. + * + * @return array + */ function monitorBuildTreeTitles($branchWhost) { $titles = []; @@ -423,6 +457,14 @@ function monitorBuildTreeTitles($branchWhost) return $titles; } +/** + * Render grouped tree title/branch sections for monitor view. + * + * @param array $titles Tree titles map keyed by "tree_id:parent_id". + * @param int $maxlen Trim length used for host title rendering. + * + * @return string + */ function monitorRenderTreeTitleSections($titles, $maxlen) { $result = ''; @@ -496,6 +538,11 @@ function monitorRenderTreeTitleSections($titles, $maxlen) return $result; } +/** + * Render section for monitored hosts that are not attached to any tree. + * + * @return string + */ function monitorRenderNonTreeSection() { $result = ''; @@ -543,6 +590,11 @@ function monitorRenderNonTreeSection() return $result; } +/** + * Render monitor tree grouping view, including tree and non-tree sections. + * + * @return string + */ function renderTree() { $result = ''; @@ -608,6 +660,14 @@ function renderTree() return $result; } +/** + * Resolve display status for a host with monitor/thold/mute overlays applied. + * + * @param array $host Host row data. + * @param bool $real Return raw computed status even if icon class is missing. + * + * @return int + */ function getHostStatus($host, $real = false) { global $thold_hosts, $iclasses; @@ -634,6 +694,13 @@ function getHostStatus($host, $real = false) return ($real || array_key_exists($host['status'], $iclasses)) ? $host['status'] : 0; } +/** + * Translate status code into localized display label. + * + * @param int $status Monitor status code. + * + * @return string + */ function getHostStatusDescription($status) { global $icolorsdisplay; @@ -646,10 +713,13 @@ function getHostStatusDescription($status) } /** - * render_host - Renders a host using a sub-function - * @param mixed $host - * @param mixed $float - * @param mixed $maxlen + * Render one host using view-specific renderer or default tile layout. + * + * @param array $host Host row data. + * @param bool $float Legacy compatibility flag (currently unused). + * @param int $maxlen Maximum host description trim length. + * + * @return string|null */ function renderHost($host, $float = true, $maxlen = 10) { @@ -711,6 +781,14 @@ function renderHost($host, $float = true, $maxlen = 10) return $result; } +/** + * Resolve icon class for host status and configured monitor icon. + * + * @param int $status Current monitor status. + * @param string $icon Configured icon key. + * + * @return string + */ function getStatusIcon($status, $icon) { global $fa_icons; @@ -730,6 +808,14 @@ function getStatusIcon($status, $icon) } } +/** + * Convert uptime/fail timestamp into compact human-readable duration text. + * + * @param string|int $status_time Timestamp string or SNMP uptime ticks. + * @param bool $seconds Include seconds in output string. + * + * @return string + */ function monitorPrintHostTime($status_time, $seconds = false) { // If the host is down, make a downtime since message @@ -759,31 +845,66 @@ function monitorPrintHostTime($status_time, $seconds = false) } +/** + * Trim monitor text fields for quote and whitespace artifacts. + * + * @param string $string Input string. + * + * @return string + */ function monitorTrim($string) { return trim($string, "\"'\\ \n\t\r"); } +/** + * Render wrapper header for default/tile monitor views. + * + * @return string + */ function renderHeaderDefault() { return "
"; } +/** + * Render wrapper header for names view table. + * + * @return string + */ function renderHeaderNames() { return "
"; } +/** + * Render wrapper header for icon tile view. + * + * @return string + */ function renderHeaderTiles() { return renderHeaderDefault(); } +/** + * Render wrapper header for advanced tile view. + * + * @return string + */ function renderHeaderTilesadt() { return renderHeaderDefault(); } +/** + * Render header and sortable column bar for list view. + * + * @param int $total_rows Total rows matching active filters. + * @param int $rows Page row limit. + * + * @return string + */ function renderHeaderList($total_rows = 0, $rows = 0) { $display_text = [ @@ -872,16 +993,31 @@ function renderHeaderList($total_rows = 0, $rows = 0) return $output; } +/** + * Indicate whether grouped section headers are suppressed for list view. + * + * @return bool + */ function renderSuppressgroupsList() { return true; } +/** + * Render wrapper footer for default/tile monitor views. + * + * @return string + */ function renderFooterDefault() { return ''; } +/** + * Render footer row for names view including trailing empty cells. + * + * @return string + */ function renderFooterNames() { $col = 7 - $_SESSION['names']; @@ -893,16 +1029,34 @@ function renderFooterNames() } } +/** + * Render wrapper footer for icon tile view. + * + * @return string + */ function renderFooterTiles() { return renderFooterDefault(); } +/** + * Render wrapper footer for advanced tile view. + * + * @return string + */ function renderFooterTilesadt() { return renderFooterDefault(); } +/** + * Render list view footer and bottom pager. + * + * @param int $total_rows Total rows matching active filters. + * @param int $rows Page row limit. + * + * @return string + */ function renderFooterList($total_rows, $rows) { ob_start(); @@ -922,6 +1076,13 @@ function renderFooterList($total_rows, $rows) return $output; } +/** + * Render one host row in list view. + * + * @param array $host Host row data. + * + * @return string + */ function renderHostList($host) { global $criticalities, $iclasses; @@ -998,6 +1159,13 @@ function renderHostList($host) return $result; } +/** + * Render one host cell in names view grid. + * + * @param array $host Host row data. + * + * @return string + */ function renderHostNames($host) { $fclass = get_request_var('size'); @@ -1026,6 +1194,13 @@ function renderHostNames($host) return $result; } +/** + * Render one host icon tile. + * + * @param array $host Host row data. + * + * @return string + */ function renderHostTiles($host) { $class = getStatusIcon($host['status'], $host['monitor_icon']); @@ -1034,6 +1209,13 @@ function renderHostTiles($host) return "
"; } +/** + * Render one advanced host tile including time-in-state/uptime text. + * + * @param array $host Host row data. + * + * @return string + */ function renderHostTilesadt($host) { $tis = ''; @@ -1053,6 +1235,13 @@ function renderHostTilesadt($host) } +/** + * Apply monitor trim setting to a computed source field length. + * + * @param int $fieldlen Initial field length. + * + * @return int + */ function getMonitorTrimLength($fieldlen) { global $maxchars; diff --git a/setup.php b/setup.php index abb2e71..96f6283 100644 --- a/setup.php +++ b/setup.php @@ -22,6 +22,11 @@ +-------------------------------------------------------------------------+ */ +/** + * Register monitor plugin hooks, realm, defaults, and schema. + * + * @return void + */ function pluginMonitorInstall() { // core plugin functionality @@ -58,6 +63,13 @@ function pluginMonitorInstall() monitorSetupTable(); } +/** + * Add monitor criticality filter definition to device filter list. + * + * @param array $filters Existing device filters. + * + * @return array + */ function monitorDeviceFilters($filters) { $criticalities = [ @@ -82,6 +94,13 @@ function monitorDeviceFilters($filters) return $filters; } +/** + * Append monitor criticality SQL predicate to host filter query. + * + * @param string $sql_where Existing WHERE fragment. + * + * @return string + */ function monitorDeviceSqlWhere($sql_where) { if (get_request_var('criticality') >= 0) { @@ -91,6 +110,11 @@ function monitorDeviceSqlWhere($sql_where) return $sql_where; } +/** + * Render legacy criticality filter control for pre-1.3 device table UI. + * + * @return void + */ function monitorDeviceTableBottom() { $criticalities = [ @@ -160,6 +184,11 @@ function monitorDeviceTableBottom() } } +/** + * Drop monitor plugin runtime/history tables during uninstall. + * + * @return void + */ function pluginMonitorUninstall() { db_execute('DROP TABLE IF EXISTS plugin_monitor_notify_history'); @@ -167,6 +196,11 @@ function pluginMonitorUninstall() db_execute('DROP TABLE IF EXISTS plugin_monitor_uptime'); } +/** + * Inject monitor CSS assets into the current page header. + * + * @return void + */ function pluginMonitorPageHead() { global $config; @@ -178,6 +212,11 @@ function pluginMonitorPageHead() } } +/** + * Validate plugin configuration values and trigger upgrade checks. + * + * @return bool + */ function pluginMonitorCheckConfig() { global $config; @@ -194,6 +233,11 @@ function pluginMonitorCheckConfig() return true; } +/** + * Execute plugin upgrade checks when plugin manager requests upgrade. + * + * @return bool + */ function pluginMonitorUpgrade() { // Here we will upgrade to the newest version @@ -202,6 +246,11 @@ function pluginMonitorUpgrade() return false; } +/** + * Apply pending monitor plugin schema/metadata upgrades. + * + * @return void + */ function monitorCheckUpgrade() { $files = ['plugins.php', 'monitor.php']; @@ -245,6 +294,11 @@ function monitorCheckUpgrade() } } +/** + * Read monitor plugin metadata from INFO file. + * + * @return array + */ function pluginMonitorVersion() { global $config; @@ -253,6 +307,13 @@ function pluginMonitorVersion() return $info['info']; } +/** + * Execute custom monitor bulk actions for selected devices. + * + * @param string $action Requested device action key. + * + * @return string + */ function monitorDeviceActionExecute($action) { global $config, $fields_host_edit; @@ -344,6 +405,13 @@ function monitorDeviceActionExecute($action) return $action; } +/** + * Remove monitor history/uptime rows for deleted devices. + * + * @param array $devices Device ids being removed. + * + * @return array + */ function monitorDeviceRemove($devices) { db_execute('DELETE FROM plugin_monitor_notify_history WHERE host_id IN(' . implode(',', $devices) . ')'); @@ -353,6 +421,13 @@ function monitorDeviceRemove($devices) return $devices; } +/** + * Render confirmation/edit UI for monitor-specific bulk device actions. + * + * @param array $save Bulk action context payload. + * + * @return array + */ function monitorDeviceActionPrepare($save) { global $host_list, $fields_host_edit; @@ -423,6 +498,13 @@ function monitorDeviceActionPrepare($save) } } +/** + * Register monitor-specific entries in device action dropdown. + * + * @param array $device_action_array Existing action map. + * + * @return array + */ function monitorDeviceActionArray($device_action_array) { $device_action_array['monitor_settings'] = __('Change Monitoring Options', 'monitor'); @@ -432,6 +514,11 @@ function monitorDeviceActionArray($device_action_array) return $device_action_array; } +/** + * Scan monitor sounds directory and return selectable alarm files. + * + * @return array + */ function monitorScanDir() { global $config; @@ -452,6 +539,11 @@ function monitorScanDir() return $files; } +/** + * Register monitor plugin settings and user preference definitions. + * + * @return void + */ function monitorConfigSettings() { global $tabs, $formats, $settings, $criticalities, $page_refresh_interval, $config, $settings_user, $tabs_graphs; @@ -742,6 +834,11 @@ function monitorConfigSettings() } } +/** + * Build monitor icon option arrays and normalize legacy format fallback. + * + * @return void + */ function monitorConfigArrays() { global $fa_icons; @@ -825,6 +922,13 @@ function monitorConfigArrays() monitorCheckUpgrade(); } +/** + * Override top-graph refresh interval when on monitor page. + * + * @param int|string $refresh Existing refresh interval. + * + * @return int|string + */ function monitorTopGraphRefresh($refresh) { if (get_current_page() != 'monitor.php') { @@ -840,6 +944,11 @@ function monitorTopGraphRefresh($refresh) return $r; } +/** + * Render monitor navigation tab icon for authorized users. + * + * @return void + */ function monitorShowTab() { global $config; @@ -855,6 +964,11 @@ function monitorShowTab() } } +/** + * Inject monitor fields into device edit form configuration. + * + * @return void + */ function monitorConfigForm() { global $config, $fields_host_edit, $criticalities, $fa_icons; @@ -992,6 +1106,13 @@ function monitorConfigForm() $fields_host_edit = $fields_host_edit3; } +/** + * Resolve default monitor enabled state for new devices. + * + * @param int|string $host_id Host identifier. + * + * @return string + */ function monitorGetDefault($host_id) { $monitor_new_device = ''; @@ -1003,6 +1124,13 @@ function monitorGetDefault($host_id) return $monitor_new_device; } +/** + * Validate and map monitor-specific host fields during device save. + * + * @param array $save Device save payload. + * + * @return array + */ function monitorApiDeviceSave($save) { global $fa_icons; @@ -1074,6 +1202,13 @@ function monitorApiDeviceSave($save) return $save; } +/** + * Add monitor page breadcrumb/nav metadata. + * + * @param array $nav Existing navigation mapping. + * + * @return array + */ function monitorDrawNavigationText($nav) { $nav['monitor.php:'] = ['title' => __('Monitoring', 'monitor'), 'mapping' => '', 'url' => 'monitor.php', 'level' => '0']; @@ -1081,6 +1216,11 @@ function monitorDrawNavigationText($nav) return $nav; } +/** + * Create/upgrade monitor plugin tables and host columns. + * + * @return void + */ function monitorSetupTable() { if (!db_table_exists('plugin_monitor_notify_history')) { @@ -1142,6 +1282,11 @@ function monitorSetupTable() api_plugin_db_add_column('monitor', 'host', ['name' => 'monitor_icon', 'type' => 'varchar(30)', 'NULL' => false, 'default' => '', 'after' => 'monitor_alert']); } +/** + * Trigger monitor poller script from primary poller process. + * + * @return void + */ function monitorPollerBottom() { global $config; From 57fca891df97011d35801dcf33ba6b8e373e3c22 Mon Sep 17 00:00:00 2001 From: Sean Mancini Date: Sun, 1 Mar 2026 22:26:38 -0500 Subject: [PATCH 16/26] Apply typing --- db_functions.php | 14 +++-- images/index.php | 2 + locales/LC_MESSAGES/index.php | 2 + monitor.php | 9 +++ monitor_controller.php | 62 ++++++++++--------- monitor_render.php | 68 ++++++++++---------- poller_functions.php | 70 +++++++++++---------- poller_monitor.php | 7 +++ setup.php | 113 ++++++++++++++++++++++++++-------- 9 files changed, 219 insertions(+), 128 deletions(-) diff --git a/db_functions.php b/db_functions.php index 5ac7ec7..8443bbc 100644 --- a/db_functions.php +++ b/db_functions.php @@ -1,5 +1,7 @@ 0) { $awhere = 'h.monitor_criticality >= ' . get_request_var('crit'); @@ -206,7 +208,7 @@ function renderWhereJoin(&$sql_where, &$sql_join) * * @return array */ -function getHostsDownOrTriggeredByPermission($prescan) +function getHostsDownOrTriggeredByPermission(bool $prescan): array { global $render_style; $PreScanValue = 2; @@ -286,7 +288,7 @@ function getHostsDownOrTriggeredByPermission($prescan) * * @return array */ -function getHostNonTreeArray() +function getHostNonTreeArray(): array { $leafs = []; diff --git a/images/index.php b/images/index.php index ea6f1df..e085c75 100644 --- a/images/index.php +++ b/images/index.php @@ -1,5 +1,7 @@ $host_id) { @@ -226,7 +228,7 @@ function unmuteUpNonTriggeredHosts($dhosts) * * @return void */ -function muteAllHosts() +function muteAllHosts(): void { $_SESSION['monitor_muted_hosts'] = getHostsDownOrTriggeredByPermission(false); muteUser(); @@ -237,7 +239,7 @@ function muteAllHosts() * * @return void */ -function unmuteAllHosts() +function unmuteAllHosts(): void { $_SESSION['monitor_muted_hosts'] = []; unmuteUser(); @@ -248,7 +250,7 @@ function unmuteAllHosts() * * @return void */ -function muteUser() +function muteUser(): void { set_request_var('mute', 'true'); set_user_setting('monitor_mute', 'true'); @@ -259,7 +261,7 @@ function muteUser() * * @return void */ -function unmuteUser() +function unmuteUser(): void { set_request_var('mute', 'false'); set_user_setting('monitor_mute', 'false'); @@ -271,7 +273,7 @@ function unmuteUser() * * @return string */ -function getFilterText() +function getFilterText(): string { $filter = '
'; @@ -346,7 +348,7 @@ function getFilterText() * * @return void */ -function drawFilterDropdown($id, $title, $settings = [], $value = null) +function drawFilterDropdown(string $id, string $title, array $settings = [], mixed $value = null): void { if ($value == null) { $value = get_nfilter_request_var($id); @@ -377,7 +379,7 @@ function drawFilterDropdown($id, $title, $settings = [], $value = null) * * @return array */ -function monitorGetDashboardOptions() +function monitorGetDashboardOptions(): array { $dashboards = [0 => __('Unsaved', 'monitor')]; $dashboards += array_rekey( @@ -402,7 +404,7 @@ function monitorGetDashboardOptions() * * @return array{int|null, string|null} */ -function monitorGetZoomDropdownState(&$dozoombgndcolor) +function monitorGetZoomDropdownState(bool &$dozoombgndcolor): array { $mon_zoom_status = null; $mon_zoom_size = null; @@ -444,7 +446,7 @@ function monitorGetZoomDropdownState(&$dozoombgndcolor) * * @return void */ -function monitorRenderPrimaryFilterRow($dashboards, $monitor_status, $monitor_view_type, $monitor_grouping, $item_rows, $mon_zoom_status) +function monitorRenderPrimaryFilterRow(array $dashboards, array $monitor_status, array $monitor_view_type, array $monitor_grouping, array $item_rows, int|null $mon_zoom_status): void { drawFilterDropdown('dashboard', __('Layout', 'monitor'), $dashboards); drawFilterDropdown('status', __('Status', 'monitor'), $monitor_status, $mon_zoom_status); @@ -479,7 +481,7 @@ function monitorRenderPrimaryFilterRow($dashboards, $monitor_status, $monitor_vi * * @return void */ -function monitorRenderGroupingDropdowns($classes, $criticalities, $monitor_trim, $page_refresh_interval, $mon_zoom_size) +function monitorRenderGroupingDropdowns(array $classes, array $criticalities, array $monitor_trim, array $page_refresh_interval, string|null $mon_zoom_size): void { drawFilterDropdown('crit', __('Criticality', 'monitor'), $criticalities); @@ -561,7 +563,7 @@ function monitorRenderGroupingDropdowns($classes, $criticalities, $monitor_trim, * * @return void */ -function monitorRenderHiddenFilterInputs() +function monitorRenderHiddenFilterInputs(): void { if (get_request_var('grouping') != 'tree') { print '
' . PHP_EOL; @@ -591,7 +593,7 @@ function monitorRenderHiddenFilterInputs() * * @return array{string, string} */ -function monitorGetZoomBackgroundStyle($dozoombgndcolor) +function monitorGetZoomBackgroundStyle(bool $dozoombgndcolor): array { if ($dozoombgndcolor) { $mbcolora = db_fetch_row_prepared( @@ -623,7 +625,7 @@ function monitorGetZoomBackgroundStyle($dozoombgndcolor) * * @return void */ -function monitorPrintJsBootstrap($config, $mbcolor, $monitor_error_fontsize, $dozoomrefresh, $new_form, $new_title) +function monitorPrintJsBootstrap(array $config, string $mbcolor, string $monitor_error_fontsize, bool $dozoomrefresh, string $new_form, string $new_title): void { $monitor_js_config = [ 'mbColor' => $mbcolor, @@ -649,7 +651,7 @@ function monitorPrintJsBootstrap($config, $mbcolor, $monitor_error_fontsize, $do * * @return void */ -function drawFilterAndStatus() +function drawFilterAndStatus(): void { global $config, $criticalities, $page_refresh_interval, $classes, $monitor_grouping; global $monitor_view_type, $monitor_status, $monitor_trim; @@ -700,7 +702,7 @@ function drawFilterAndStatus() * * @return string */ -function getMuteText() +function getMuteText(): string { if (isMonitorAudible()) { return __('Mute', 'monitor'); @@ -714,7 +716,7 @@ function getMuteText() * * @return string */ -function getUnmuteText() +function getUnmuteText(): string { if (isMonitorAudible()) { return __('Un-Mute', 'monitor'); @@ -728,7 +730,7 @@ function getUnmuteText() * * @return void */ -function removeDashboard() +function removeDashboard(): void { $dashboard = get_filter_request_var('dashboard'); @@ -767,7 +769,7 @@ function removeDashboard() * * @return void */ -function saveSettings() +function saveSettings(): void { if (isset_request_var('dashboard') && get_filter_request_var('dashboard') != 0) { $save_db = true; @@ -889,7 +891,7 @@ function saveSettings() * * @return void */ -function validateRequestVars($force = false) +function validateRequestVars(bool $force = false): void { // ================= input validation and session storage ================= $filters = [ @@ -1001,7 +1003,7 @@ function validateRequestVars($force = false) * * @return array */ -function monitorLoadAjaxStatusHost($id, $thold_hosts, $config) +function monitorLoadAjaxStatusHost(int|string $id, array $thold_hosts, array $config): array { $host = db_fetch_row_prepared( 'SELECT * @@ -1039,7 +1041,7 @@ function monitorLoadAjaxStatusHost($id, $thold_hosts, $config) * * @return string */ -function monitorGetAjaxStatusLinks($host, $config) +function monitorGetAjaxStatusLinks(array $host, array $config): string { $links = ''; @@ -1119,7 +1121,7 @@ function monitorGetAjaxStatusLinks($host, $config) * * @return string */ -function monitorRenderAjaxStatusTooltip($host, $size, $links, $site, $sdisplay, $iclass, $criticalities) +function monitorRenderAjaxStatusTooltip(array $host, string $size, string $links, string $site, string $sdisplay, string $iclass, array $criticalities): string { return "
@@ -1203,7 +1205,7 @@ function monitorRenderAjaxStatusTooltip($host, $size, $links, $site, $sdisplay, * * @return bool|null */ -function ajaxStatus() +function ajaxStatus(): void { global $thold_hosts, $config, $iclasses, $criticalities; @@ -1220,7 +1222,7 @@ function ajaxStatus() if (!cacti_sizeof($host)) { cacti_log('Attempted to retrieve status for missing Device ' . $id, false, 'MONITOR', POLLER_VERBOSITY_HIGH); - return false; + return; } $links = monitorGetAjaxStatusLinks($host, $config); diff --git a/monitor_render.php b/monitor_render.php index 358abda..5c4bfcd 100644 --- a/monitor_render.php +++ b/monitor_render.php @@ -1,5 +1,7 @@
"; } @@ -872,7 +874,7 @@ function renderHeaderDefault() * * @return string */ -function renderHeaderNames() +function renderHeaderNames(): string { return "
"; } @@ -882,7 +884,7 @@ function renderHeaderNames() * * @return string */ -function renderHeaderTiles() +function renderHeaderTiles(): string { return renderHeaderDefault(); } @@ -892,7 +894,7 @@ function renderHeaderTiles() * * @return string */ -function renderHeaderTilesadt() +function renderHeaderTilesadt(): string { return renderHeaderDefault(); } @@ -905,7 +907,7 @@ function renderHeaderTilesadt() * * @return string */ -function renderHeaderList($total_rows = 0, $rows = 0) +function renderHeaderList(int $total_rows = 0, int $rows = 0): string { $display_text = [ 'hostname' => [ @@ -998,7 +1000,7 @@ function renderHeaderList($total_rows = 0, $rows = 0) * * @return bool */ -function renderSuppressgroupsList() +function renderSuppressgroupsList(): bool { return true; } @@ -1008,7 +1010,7 @@ function renderSuppressgroupsList() * * @return string */ -function renderFooterDefault() +function renderFooterDefault(): string { return ''; } @@ -1018,7 +1020,7 @@ function renderFooterDefault() * * @return string */ -function renderFooterNames() +function renderFooterNames(): string { $col = 7 - $_SESSION['names']; @@ -1034,7 +1036,7 @@ function renderFooterNames() * * @return string */ -function renderFooterTiles() +function renderFooterTiles(): string { return renderFooterDefault(); } @@ -1044,7 +1046,7 @@ function renderFooterTiles() * * @return string */ -function renderFooterTilesadt() +function renderFooterTilesadt(): string { return renderFooterDefault(); } @@ -1057,7 +1059,7 @@ function renderFooterTilesadt() * * @return string */ -function renderFooterList($total_rows, $rows) +function renderFooterList(int $total_rows, int $rows): string { ob_start(); @@ -1083,7 +1085,7 @@ function renderFooterList($total_rows, $rows) * * @return string */ -function renderHostList($host) +function renderHostList(array $host): string { global $criticalities, $iclasses; @@ -1166,7 +1168,7 @@ function renderHostList($host) * * @return string */ -function renderHostNames($host) +function renderHostNames(array $host): string { $fclass = get_request_var('size'); @@ -1201,7 +1203,7 @@ function renderHostNames($host) * * @return string */ -function renderHostTiles($host) +function renderHostTiles(array $host): string { $class = getStatusIcon($host['status'], $host['monitor_icon']); $fclass = get_request_var('size'); @@ -1216,7 +1218,7 @@ function renderHostTiles($host) * * @return string */ -function renderHostTilesadt($host) +function renderHostTilesadt(array $host): string { $tis = ''; @@ -1242,7 +1244,7 @@ function renderHostTilesadt($host) * * @return int */ -function getMonitorTrimLength($fieldlen) +function getMonitorTrimLength(int $fieldlen): int { global $maxchars; diff --git a/poller_functions.php b/poller_functions.php index 18d3246..b05c540 100644 --- a/poller_functions.php +++ b/poller_functions.php @@ -1,5 +1,7 @@ 0 && isset($notification_lists[$notify_list])) { $emails = explode(',', $notification_lists[$notify_list]); @@ -64,7 +66,7 @@ function monitorAddNotificationList(&$reboot_emails, $notify_list, $host_id, $no * * @return array */ -function getAlertEmails() +function getAlertEmails(): array { $alert_email = read_config_option('alert_email'); @@ -78,7 +80,7 @@ function getAlertEmails() * * @return void */ -function purgeOrphanMonitorRows($table_name) +function purgeOrphanMonitorRows(string $table_name): void { $removed_hosts = db_fetch_assoc("SELECT mu.host_id FROM $table_name AS mu @@ -100,7 +102,7 @@ function purgeOrphanMonitorRows($table_name) * * @return array */ -function getRebootedHosts() +function getRebootedHosts(): array { return db_fetch_assoc('SELECT h.id, h.description, h.hostname, h.snmp_sysUpTimeInstance, mu.uptime @@ -120,7 +122,7 @@ function getRebootedHosts() * * @return array */ -function getNotificationListsMap() +function getNotificationListsMap(): array { return array_rekey( db_fetch_assoc('SELECT id, emails @@ -141,7 +143,7 @@ function getNotificationListsMap() * * @return void */ -function addTholdRebootRecipients(&$reboot_emails, $host_id, $alert_emails, $notification_lists) +function addTholdRebootRecipients(array &$reboot_emails, int|string $host_id, array $alert_emails, array $notification_lists): void { $notify = db_fetch_row_prepared( 'SELECT thold_send_email, thold_host_email @@ -181,7 +183,7 @@ function addTholdRebootRecipients(&$reboot_emails, $host_id, $alert_emails, $not * * @return array */ -function buildRebootEmailMap($rebooted_hosts, $alert_emails) +function buildRebootEmailMap(array $rebooted_hosts, array $alert_emails): array { $reboot_emails = []; $notification_lists = getNotificationListsMap(); @@ -213,7 +215,7 @@ function buildRebootEmailMap($rebooted_hosts, $alert_emails) * * @return void */ -function sendRebootNotifications($reboot_emails) +function sendRebootNotifications(array $reboot_emails): void { $monitor_send_one_email = read_config_option('monitor_send_one_email'); @@ -251,7 +253,7 @@ function sendRebootNotifications($reboot_emails) * * @return array{int, int} Reboot count and recent down count. */ -function monitorUptimeChecker() +function monitorUptimeChecker(): array { monitorDebug('Checking for Uptime of Devices'); @@ -300,7 +302,7 @@ function monitorUptimeChecker() * * @return array{string, string, array} */ -function buildRebootDetails($hosts) +function buildRebootDetails(array $hosts): array { $body_txt = ''; $last_host = []; @@ -348,7 +350,7 @@ function buildRebootDetails($hosts) * * @return string */ -function buildRebootSubject($hosts, $last_host) +function buildRebootSubject(array $hosts, array $last_host): string { $subject = read_config_option('monitor_subject'); $monitor_send_one_email = read_config_option('monitor_send_one_email'); @@ -372,7 +374,7 @@ function buildRebootSubject($hosts, $last_host) * * @return array{string, string, array} */ -function prepareReportOutput($body, $body_txt) +function prepareReportOutput(string $body, string $body_txt): array { $output = ''; @@ -416,7 +418,7 @@ function prepareReportOutput($body, $body_txt) * * @return void */ -function processRebootEmail($email, $hosts) +function processRebootEmail(string $email, array $hosts): void { monitorDebug("Reboot Processing for $email starting"); @@ -450,7 +452,7 @@ function processRebootEmail($email, $hosts) * * @return array{array, array} */ -function collectNotificationHosts($lists, $global_list, $notify_list) +function collectNotificationHosts(array $lists, array $global_list, array $notify_list): array { $alert_hosts = []; $warn_hosts = []; @@ -488,7 +490,7 @@ function collectNotificationHosts($lists, $global_list, $notify_list) * * @return void */ -function normalizeAndLogNotificationHosts(&$alert_hosts, &$warn_hosts) +function normalizeAndLogNotificationHosts(array &$alert_hosts, array &$warn_hosts): void { if (cacti_sizeof($alert_hosts)) { $alert_hosts = array_unique($alert_hosts, SORT_NUMERIC); @@ -508,7 +510,7 @@ function normalizeAndLogNotificationHosts(&$alert_hosts, &$warn_hosts) * * @return array{string, string} */ -function buildPingNotificationIntro($freq) +function buildPingNotificationIntro(int|string $freq): array { $body = '

' . __(MONITOR_PING_NOTIFICATION_SUBJECT, 'monitor') . '

' . PHP_EOL; $body_txt = __(MONITOR_PING_NOTIFICATION_SUBJECT, 'monitor') . PHP_EOL; @@ -544,7 +546,7 @@ function buildPingNotificationIntro($freq) * * @return void */ -function appendThresholdSection(&$body, &$body_txt, $host_ids, $criticalities, $section_text, $threshold_field) +function appendThresholdSection(string &$body, string &$body_txt, array $host_ids, array $criticalities, string $section_text, string $threshold_field): void { global $config; @@ -603,7 +605,7 @@ function appendThresholdSection(&$body, &$body_txt, $host_ids, $criticalities, $ * * @return string */ -function buildNotificationStatus($alert_hosts, $warn_hosts) +function buildNotificationStatus(array $alert_hosts, array $warn_hosts): string { $status = ''; @@ -632,7 +634,7 @@ function buildNotificationStatus($alert_hosts, $warn_hosts) * * @return void */ -function processEmail($email, $lists, $global_list, $notify_list) +function processEmail(string $email, array $lists, array $global_list, array $notify_list): void { monitorDebug('Into Processing'); @@ -696,7 +698,7 @@ function processEmail($email, $lists, $global_list, $notify_list) * * @return void */ -function processSendEmail($email, $subject, $output, $toutput, $headers, $status) +function processSendEmail(string $email, string $subject, string $output, string $toutput, array $headers, string $status): void { $from_email = read_config_option('monitor_fromemail'); @@ -757,7 +759,7 @@ function processSendEmail($email, $subject, $output, $toutput, $headers, $status * * @return string */ -function monitorText($output) +function monitorText(string $output): string { $output = explode(PHP_EOL, $output); @@ -783,7 +785,7 @@ function monitorText($output) * * @return void */ -function logMessages($type, $alert_hosts) +function logMessages(string $type, array $alert_hosts): void { global $start_date; @@ -826,7 +828,7 @@ function logMessages($type, $alert_hosts) * * @return void */ -function addGroupedNotificationEntry($type, $entry, &$global_list, &$notify_list, &$lists) +function addGroupedNotificationEntry(string $type, array $entry, array &$global_list, array &$notify_list, array &$lists): void { if ($entry['thold_send_email'] == '1' || $entry['thold_send_email'] == '3') { $global_list[$type][] = $entry; @@ -849,7 +851,7 @@ function addGroupedNotificationEntry($type, $entry, &$global_list, &$notify_list * * @return void */ -function getHostsByListType($type, $criticality, &$global_list, &$notify_list, &$lists) +function getHostsByListType(string $type, int|string $criticality, array &$global_list, array &$notify_list, array &$lists): void { $last_time = date(MONITOR_DATE_TIME_FORMAT, time() - read_config_option('monitor_resend_frequency') * 60); @@ -911,7 +913,7 @@ function getHostsByListType($type, $criticality, &$global_list, &$notify_list, & * * @return string */ -function flattenGroupSeverityList($list) +function flattenGroupSeverityList(array $list): string { $flattened = ''; @@ -929,7 +931,7 @@ function flattenGroupSeverityList($list) * * @return array */ -function flattenNotifySeverityLists($lists) +function flattenNotifySeverityLists(array $lists): array { $flattened = []; @@ -948,7 +950,7 @@ function flattenNotifySeverityLists($lists) * * @return void */ -function flattenLists(&$global_list, &$notify_list) +function flattenLists(array &$global_list, array &$notify_list): void { if (cacti_sizeof($global_list)) { $new_global = []; @@ -980,7 +982,7 @@ function flattenLists(&$global_list, &$notify_list) * * @return void */ -function addEmailsToNotificationMap(&$notification_emails, $emails, $scope_key) +function addEmailsToNotificationMap(array &$notification_emails, array $emails, string|int $scope_key): void { foreach ($emails as $user) { $user = trim($user); @@ -998,7 +1000,7 @@ function addEmailsToNotificationMap(&$notification_emails, $emails, $scope_key) * * @return array */ -function getEmailsAndLists($lists) +function getEmailsAndLists(array $lists): array { $notification_emails = []; @@ -1033,7 +1035,7 @@ function getEmailsAndLists($lists) * * @return array{int, int} Purged notify count and purged reboot count. */ -function purgeEventRecords() +function purgeEventRecords(): array { // Purge old records $days = read_config_option('monitor_log_storage'); @@ -1068,7 +1070,7 @@ function purgeEventRecords() * * @return void */ -function monitorDebug($message) +function monitorDebug(string $message): void { global $debug; @@ -1082,7 +1084,7 @@ function monitorDebug($message) * * @return void */ -function displayVersion() +function displayVersion(): void { global $config; @@ -1099,7 +1101,7 @@ function displayVersion() * * @return void */ -function displayHelp() +function displayHelp(): void { displayVersion(); diff --git a/poller_monitor.php b/poller_monitor.php index 0554a41..756ef64 100644 --- a/poller_monitor.php +++ b/poller_monitor.php @@ -1,5 +1,7 @@ ='); +} + +/** + * Enforce plugin minimum PHP version and optionally raise a UI message. + * + * @param bool $raise_message Whether to raise a Cacti UI error message. + * + * @return bool + */ +function monitorEnsureSupportedPhpVersion(bool $raise_message = true): bool +{ + if (monitorHasSupportedPhpVersion()) { + return true; + } + + $message = sprintf( + 'Monitor plugin requires PHP %s or newer. Current runtime: %s', + monitorGetMinimumPhpVersion(), + PHP_VERSION + ); + + cacti_log($message, false, 'MONITOR'); + + if ($raise_message) { + raise_message('monitor_php_version', $message, MESSAGE_LEVEL_ERROR); + } + + return false; +} + /** * Register monitor plugin hooks, realm, defaults, and schema. * * @return void */ -function pluginMonitorInstall() +function pluginMonitorInstall(): void { + if (!monitorEnsureSupportedPhpVersion()) { + return; + } + // core plugin functionality api_plugin_register_hook('monitor', 'top_header_tabs', 'monitorShowTab', 'setup.php'); api_plugin_register_hook('monitor', 'top_graph_header_tabs', 'monitorShowTab', 'setup.php'); @@ -70,7 +124,7 @@ function pluginMonitorInstall() * * @return array */ -function monitorDeviceFilters($filters) +function monitorDeviceFilters(array $filters): array { $criticalities = [ '-1' => __('Any', 'monitor'), @@ -101,7 +155,7 @@ function monitorDeviceFilters($filters) * * @return string */ -function monitorDeviceSqlWhere($sql_where) +function monitorDeviceSqlWhere(string $sql_where): string { if (get_request_var('criticality') >= 0) { $sql_where .= ($sql_where != '' ? ' AND ' : 'WHERE ') . ' monitor_criticality = ' . get_request_var('criticality'); @@ -115,7 +169,7 @@ function monitorDeviceSqlWhere($sql_where) * * @return void */ -function monitorDeviceTableBottom() +function monitorDeviceTableBottom(): void { $criticalities = [ '-1' => __('Any', 'monitor'), @@ -189,7 +243,7 @@ function monitorDeviceTableBottom() * * @return void */ -function pluginMonitorUninstall() +function pluginMonitorUninstall(): void { db_execute('DROP TABLE IF EXISTS plugin_monitor_notify_history'); db_execute('DROP TABLE IF EXISTS plugin_monitor_reboot_history'); @@ -201,7 +255,7 @@ function pluginMonitorUninstall() * * @return void */ -function pluginMonitorPageHead() +function pluginMonitorPageHead(): void { global $config; @@ -217,9 +271,14 @@ function pluginMonitorPageHead() * * @return bool */ -function pluginMonitorCheckConfig() +function pluginMonitorCheckConfig(): bool { global $config; + + if (!monitorEnsureSupportedPhpVersion()) { + return false; + } + // Here we will check to ensure everything is configured monitorCheckUpgrade(); @@ -238,8 +297,12 @@ function pluginMonitorCheckConfig() * * @return bool */ -function pluginMonitorUpgrade() +function pluginMonitorUpgrade(): bool { + if (!monitorEnsureSupportedPhpVersion()) { + return false; + } + // Here we will upgrade to the newest version monitorCheckUpgrade(); @@ -251,7 +314,7 @@ function pluginMonitorUpgrade() * * @return void */ -function monitorCheckUpgrade() +function monitorCheckUpgrade(): void { $files = ['plugins.php', 'monitor.php']; @@ -299,7 +362,7 @@ function monitorCheckUpgrade() * * @return array */ -function pluginMonitorVersion() +function pluginMonitorVersion(): array { global $config; $info = parse_ini_file($config['base_path'] . '/plugins/monitor/INFO', true); @@ -314,7 +377,7 @@ function pluginMonitorVersion() * * @return string */ -function monitorDeviceActionExecute($action) +function monitorDeviceActionExecute(string $action): string { global $config, $fields_host_edit; @@ -412,7 +475,7 @@ function monitorDeviceActionExecute($action) * * @return array */ -function monitorDeviceRemove($devices) +function monitorDeviceRemove(array $devices): array { db_execute('DELETE FROM plugin_monitor_notify_history WHERE host_id IN(' . implode(',', $devices) . ')'); db_execute('DELETE FROM plugin_monitor_reboot_history WHERE host_id IN(' . implode(',', $devices) . ')'); @@ -428,7 +491,7 @@ function monitorDeviceRemove($devices) * * @return array */ -function monitorDeviceActionPrepare($save) +function monitorDeviceActionPrepare(array $save): array { global $host_list, $fields_host_edit; @@ -505,7 +568,7 @@ function monitorDeviceActionPrepare($save) * * @return array */ -function monitorDeviceActionArray($device_action_array) +function monitorDeviceActionArray(array $device_action_array): array { $device_action_array['monitor_settings'] = __('Change Monitoring Options', 'monitor'); $device_action_array['monitor_enable'] = __('Enable Monitoring', 'monitor'); @@ -519,7 +582,7 @@ function monitorDeviceActionArray($device_action_array) * * @return array */ -function monitorScanDir() +function monitorScanDir(): array { global $config; @@ -544,7 +607,7 @@ function monitorScanDir() * * @return void */ -function monitorConfigSettings() +function monitorConfigSettings(): void { global $tabs, $formats, $settings, $criticalities, $page_refresh_interval, $config, $settings_user, $tabs_graphs; @@ -839,7 +902,7 @@ function monitorConfigSettings() * * @return void */ -function monitorConfigArrays() +function monitorConfigArrays(): void { global $fa_icons; @@ -929,7 +992,7 @@ function monitorConfigArrays() * * @return int|string */ -function monitorTopGraphRefresh($refresh) +function monitorTopGraphRefresh(mixed $refresh): mixed { if (get_current_page() != 'monitor.php') { return $refresh; @@ -949,7 +1012,7 @@ function monitorTopGraphRefresh($refresh) * * @return void */ -function monitorShowTab() +function monitorShowTab(): void { global $config; @@ -969,7 +1032,7 @@ function monitorShowTab() * * @return void */ -function monitorConfigForm() +function monitorConfigForm(): void { global $config, $fields_host_edit, $criticalities, $fa_icons; @@ -1113,7 +1176,7 @@ function monitorConfigForm() * * @return string */ -function monitorGetDefault($host_id) +function monitorGetDefault(int|string $host_id): string { $monitor_new_device = ''; @@ -1131,7 +1194,7 @@ function monitorGetDefault($host_id) * * @return array */ -function monitorApiDeviceSave($save) +function monitorApiDeviceSave(array $save): array { global $fa_icons; @@ -1209,7 +1272,7 @@ function monitorApiDeviceSave($save) * * @return array */ -function monitorDrawNavigationText($nav) +function monitorDrawNavigationText(array $nav): array { $nav['monitor.php:'] = ['title' => __('Monitoring', 'monitor'), 'mapping' => '', 'url' => 'monitor.php', 'level' => '0']; @@ -1221,7 +1284,7 @@ function monitorDrawNavigationText($nav) * * @return void */ -function monitorSetupTable() +function monitorSetupTable(): void { if (!db_table_exists('plugin_monitor_notify_history')) { db_execute("CREATE TABLE IF NOT EXISTS plugin_monitor_notify_history ( @@ -1287,7 +1350,7 @@ function monitorSetupTable() * * @return void */ -function monitorPollerBottom() +function monitorPollerBottom(): void { global $config; From dff312fee079b101a662a0e881a030666145a971 Mon Sep 17 00:00:00 2001 From: Sean Mancini Date: Tue, 3 Mar 2026 10:58:26 -0500 Subject: [PATCH 17/26] remove checks for min php version --- monitor.php | 7 ----- poller_functions.php | 5 ++-- poller_monitor.php | 5 ---- setup.php | 64 +++----------------------------------------- 4 files changed, 6 insertions(+), 75 deletions(-) diff --git a/monitor.php b/monitor.php index 268a662..51658e0 100644 --- a/monitor.php +++ b/monitor.php @@ -25,13 +25,6 @@ +-------------------------------------------------------------------------+ */ -if (PHP_VERSION_ID < 80100) { - $protocol = $_SERVER['SERVER_PROTOCOL'] ?? 'HTTP/1.1'; - header($protocol . ' 500 Internal Server Error', true, 500); - print 'Monitor plugin requires PHP 8.1.0 or newer. Current runtime: ' . PHP_VERSION; - exit; -} - $guest_account = true; chdir('../../'); diff --git a/poller_functions.php b/poller_functions.php index b05c540..821412d 100644 --- a/poller_functions.php +++ b/poller_functions.php @@ -1088,11 +1088,12 @@ function displayVersion(): void { global $config; - if (!function_exists('pluginMonitorVersion')) { + if (!function_exists('plugin_monitor_version')) { include_once $config['base_path'] . '/plugins/monitor/setup.php'; } - $info = pluginMonitorVersion(); + $info = plugin_monitor_version(); + print 'Cacti Monitor Poller, Version ' . $info['version'] . ', ' . COPYRIGHT_YEARS . PHP_EOL; } diff --git a/poller_monitor.php b/poller_monitor.php index 756ef64..bb71ae0 100644 --- a/poller_monitor.php +++ b/poller_monitor.php @@ -25,11 +25,6 @@ +-------------------------------------------------------------------------+ */ -if (PHP_VERSION_ID < 80100) { - fwrite(STDERR, 'Monitor plugin requires PHP 8.1.0 or newer. Current runtime: ' . PHP_VERSION . PHP_EOL); - exit(1); -} - $dir = __DIR__; chdir($dir); diff --git a/setup.php b/setup.php index f939999..21b6e70 100644 --- a/setup.php +++ b/setup.php @@ -24,54 +24,6 @@ +-------------------------------------------------------------------------+ */ -/** - * Get minimum supported PHP version for this plugin. - * - * @return string - */ -function monitorGetMinimumPhpVersion(): string -{ - return '8.1.0'; -} - -/** - * Determine whether current runtime satisfies plugin PHP requirement. - * - * @return bool - */ -function monitorHasSupportedPhpVersion(): bool -{ - return version_compare(PHP_VERSION, monitorGetMinimumPhpVersion(), '>='); -} - -/** - * Enforce plugin minimum PHP version and optionally raise a UI message. - * - * @param bool $raise_message Whether to raise a Cacti UI error message. - * - * @return bool - */ -function monitorEnsureSupportedPhpVersion(bool $raise_message = true): bool -{ - if (monitorHasSupportedPhpVersion()) { - return true; - } - - $message = sprintf( - 'Monitor plugin requires PHP %s or newer. Current runtime: %s', - monitorGetMinimumPhpVersion(), - PHP_VERSION - ); - - cacti_log($message, false, 'MONITOR'); - - if ($raise_message) { - raise_message('monitor_php_version', $message, MESSAGE_LEVEL_ERROR); - } - - return false; -} - /** * Register monitor plugin hooks, realm, defaults, and schema. * @@ -79,9 +31,7 @@ function monitorEnsureSupportedPhpVersion(bool $raise_message = true): bool */ function pluginMonitorInstall(): void { - if (!monitorEnsureSupportedPhpVersion()) { - return; - } + plugin_monitor_version(); // core plugin functionality api_plugin_register_hook('monitor', 'top_header_tabs', 'monitorShowTab', 'setup.php'); @@ -275,10 +225,6 @@ function pluginMonitorCheckConfig(): bool { global $config; - if (!monitorEnsureSupportedPhpVersion()) { - return false; - } - // Here we will check to ensure everything is configured monitorCheckUpgrade(); @@ -299,10 +245,6 @@ function pluginMonitorCheckConfig(): bool */ function pluginMonitorUpgrade(): bool { - if (!monitorEnsureSupportedPhpVersion()) { - return false; - } - // Here we will upgrade to the newest version monitorCheckUpgrade(); @@ -322,7 +264,7 @@ function monitorCheckUpgrade(): void return; } - $info = pluginMonitorVersion(); + $info = plugin_monitor_version(); $current = $info['version']; $old = db_fetch_cell('SELECT version FROM plugin_config WHERE directory = "monitor"'); @@ -362,7 +304,7 @@ function monitorCheckUpgrade(): void * * @return array */ -function pluginMonitorVersion(): array +function plugin_monitor_version(): array { global $config; $info = parse_ini_file($config['base_path'] . '/plugins/monitor/INFO', true); From 80a08aaf257e8191705dfe359ea8b63527544804 Mon Sep 17 00:00:00 2001 From: Sean Mancini Date: Tue, 3 Mar 2026 11:20:16 -0500 Subject: [PATCH 18/26] correct installation errors after PSR12 --- setup.php | 45 +++++++++++++++++++++++++++++++++------------ 1 file changed, 33 insertions(+), 12 deletions(-) diff --git a/setup.php b/setup.php index 21b6e70..fe488f9 100644 --- a/setup.php +++ b/setup.php @@ -29,7 +29,7 @@ * * @return void */ -function pluginMonitorInstall(): void +function plugin_monitor_install(): void { plugin_monitor_version(); @@ -67,6 +67,16 @@ function pluginMonitorInstall(): void monitorSetupTable(); } +/** + * Backward-compatible camelCase install entrypoint. + * + * @return void + */ +function pluginMonitorInstall(): void +{ + plugin_monitor_install(); +} + /** * Add monitor criticality filter definition to device filter list. * @@ -193,7 +203,7 @@ function monitorDeviceTableBottom(): void * * @return void */ -function pluginMonitorUninstall(): void +function plugin_monitor_uninstall(): void { db_execute('DROP TABLE IF EXISTS plugin_monitor_notify_history'); db_execute('DROP TABLE IF EXISTS plugin_monitor_reboot_history'); @@ -221,7 +231,7 @@ function pluginMonitorPageHead(): void * * @return bool */ -function pluginMonitorCheckConfig(): bool +function plugin_monitor_check_config(): bool { global $config; @@ -243,7 +253,7 @@ function pluginMonitorCheckConfig(): bool * * @return bool */ -function pluginMonitorUpgrade(): bool +function plugin_monitor_upgrade(): bool { // Here we will upgrade to the newest version monitorCheckUpgrade(); @@ -278,7 +288,7 @@ function monitorCheckUpgrade(): void db_execute('ALTER TABLE plugin_monitor_uptime MODIFY COLUMN uptime BIGINT unsigned NOT NULL default "0"'); - api_plugin_db_add_column('monitor', 'host', ['name' => 'monitor_icon', 'type' => 'varchar(30)', 'NULL' => false, 'default' => '', 'after' => 'monitor_alert']); + api_plugin_db_add_column('monitor', 'host', ['name' => 'monitor_icon', 'type' => 'varchar(30)', 'NULL' => false, 'default' => '']); if (function_exists('api_plugin_upgrade_register')) { api_plugin_upgrade_register('monitor'); @@ -1123,7 +1133,7 @@ function monitorGetDefault(int|string $host_id): string $monitor_new_device = ''; if ($host_id <= 0) { - $monitor_new_device = read_config_option('monitor_new_enabled'); + $monitor_new_device = (string) read_config_option('monitor_new_enabled'); } return $monitor_new_device; @@ -1279,12 +1289,23 @@ function monitorSetupTable(): void COMMENT='Stores predefined dashboard information for a user or users'"); } - api_plugin_db_add_column('monitor', 'host', ['name' => 'monitor', 'type' => 'char(3)', 'NULL' => true, 'default' => 'on', 'after' => 'disabled']); - api_plugin_db_add_column('monitor', 'host', ['name' => 'monitor_text', 'type' => 'varchar(1024)', 'default' => '', 'NULL' => false, 'after' => 'monitor']); - api_plugin_db_add_column('monitor', 'host', ['name' => 'monitor_criticality', 'type' => 'tinyint', 'unsigned' => true, 'NULL' => false, 'default' => '0', 'after' => 'monitor_text']); - api_plugin_db_add_column('monitor', 'host', ['name' => 'monitor_warn', 'type' => 'double', 'NULL' => false, 'default' => '0', 'after' => 'monitor_criticality']); - api_plugin_db_add_column('monitor', 'host', ['name' => 'monitor_alert', 'type' => 'double', 'NULL' => false, 'default' => '0', 'after' => 'monitor_warn']); - api_plugin_db_add_column('monitor', 'host', ['name' => 'monitor_icon', 'type' => 'varchar(30)', 'NULL' => false, 'default' => '', 'after' => 'monitor_alert']); + if (db_table_exists('host')) { + $row_format = db_fetch_cell("SELECT ROW_FORMAT + FROM information_schema.tables + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = 'host'"); + + if (strtoupper((string) $row_format) !== 'DYNAMIC') { + db_execute('ALTER TABLE host ROW_FORMAT=DYNAMIC'); + } + } + + api_plugin_db_add_column('monitor', 'host', ['name' => 'monitor', 'type' => 'char(3)', 'NULL' => true, 'default' => 'on']); + api_plugin_db_add_column('monitor', 'host', ['name' => 'monitor_text', 'type' => 'text', 'NULL' => false]); + api_plugin_db_add_column('monitor', 'host', ['name' => 'monitor_criticality', 'type' => 'tinyint', 'unsigned' => true, 'NULL' => false, 'default' => '0']); + api_plugin_db_add_column('monitor', 'host', ['name' => 'monitor_warn', 'type' => 'double', 'NULL' => false, 'default' => '0']); + api_plugin_db_add_column('monitor', 'host', ['name' => 'monitor_alert', 'type' => 'double', 'NULL' => false, 'default' => '0']); + api_plugin_db_add_column('monitor', 'host', ['name' => 'monitor_icon', 'type' => 'varchar(30)', 'NULL' => false, 'default' => '']); } /** From 1b57f4b5b56c6bdbc508d77e9dba04788b68e958 Mon Sep 17 00:00:00 2001 From: Sean Mancini Date: Tue, 3 Mar 2026 11:26:03 -0500 Subject: [PATCH 19/26] try iinstall fix one more time --- monitor_controller.php | 2 +- setup.php | 2028 ++++++++++++++++++---------------------- 2 files changed, 913 insertions(+), 1117 deletions(-) diff --git a/monitor_controller.php b/monitor_controller.php index d84cfcf..e51b6ca 100644 --- a/monitor_controller.php +++ b/monitor_controller.php @@ -168,7 +168,7 @@ function isMonitorAudible(): bool */ function getMonitorSound(): string { - $sound = read_user_setting('monitor_sound', read_config_option('monitor_sound')); + $sound = (string) read_user_setting('monitor_sound', read_config_option('monitor_sound')); clearstatcache(); $file = __DIR__ . '/sounds/' . $sound; $exists = file_exists($file); diff --git a/setup.php b/setup.php index fe488f9..043d0f7 100644 --- a/setup.php +++ b/setup.php @@ -1,6 +1,4 @@ __('Any', 'monitor'), + '0' => __('None', 'monitor'), + '1' => __('Low', 'monitor'), + '2' => __('Medium', 'monitor'), + '3' => __('High', 'monitor'), + '4' => __('Mission Critical', 'monitor') + ]; + + $filters['criticality'] = [ + 'friendly_name' => __('Criticality', 'monitor'), + 'method' => 'drop_array', + 'filter' => FILTER_VALIDATE_INT, + 'pageset' => true, + 'default' => '-1', + 'array' => $criticalities, + 'value' => '-1' + ]; + + return $filters; } -/** - * Add monitor criticality filter definition to device filter list. - * - * @param array $filters Existing device filters. - * - * @return array - */ -function monitorDeviceFilters(array $filters): array -{ - $criticalities = [ - '-1' => __('Any', 'monitor'), - '0' => __('None', 'monitor'), - '1' => __('Low', 'monitor'), - '2' => __('Medium', 'monitor'), - '3' => __('High', 'monitor'), - '4' => __('Mission Critical', 'monitor') - ]; - - $filters['criticality'] = [ - 'friendly_name' => __('Criticality', 'monitor'), - 'method' => 'drop_array', - 'filter' => FILTER_VALIDATE_INT, - 'pageset' => true, - 'default' => '-1', - 'array' => $criticalities, - 'value' => '-1' - ]; - - return $filters; -} +function monitor_device_sql_where($sql_where) { + if (get_request_var('criticality') >= 0) { + $sql_where .= ($sql_where != '' ? ' AND ' : 'WHERE ') . ' monitor_criticality = ' . get_request_var('criticality'); + } -/** - * Append monitor criticality SQL predicate to host filter query. - * - * @param string $sql_where Existing WHERE fragment. - * - * @return string - */ -function monitorDeviceSqlWhere(string $sql_where): string -{ - if (get_request_var('criticality') >= 0) { - $sql_where .= ($sql_where != '' ? ' AND ' : 'WHERE ') . ' monitor_criticality = ' . get_request_var('criticality'); - } - - return $sql_where; + return $sql_where; } -/** - * Render legacy criticality filter control for pre-1.3 device table UI. - * - * @return void - */ -function monitorDeviceTableBottom(): void -{ - $criticalities = [ - '-1' => __('Any', 'monitor'), - '0' => __('None', 'monitor'), - '1' => __('Low', 'monitor'), - '2' => __('Medium', 'monitor'), - '3' => __('High', 'monitor'), - '4' => __('Mission Critical', 'monitor') - ]; - - if (version_compare(CACTI_VERSION, '1.3.0', '<')) { - $select = ''; - - ?> +function monitor_device_table_bottom() { + $criticalities = [ + '-1' => __('Any', 'monitor'), + '0' => __('None', 'monitor'), + '1' => __('Low', 'monitor'), + '2' => __('Medium', 'monitor'), + '3' => __('High', 'monitor'), + '4' => __('Mission Critical', 'monitor') + ]; + + if (version_compare(CACTI_VERSION, '1.3.0', '<')) { + $select = ''; + + ?> 300) { - set_config_option('monitor_refresh', '300'); - } + if ($r == '' || $r < 1 || $r > 300) { + set_config_option('monitor_refresh', '300'); + } - return true; + return true; } -/** - * Execute plugin upgrade checks when plugin manager requests upgrade. - * - * @return bool - */ -function plugin_monitor_upgrade(): bool -{ - // Here we will upgrade to the newest version - monitorCheckUpgrade(); - - return false; +function plugin_monitor_upgrade() { + // Here we will upgrade to the newest version + monitor_check_upgrade(); + + return false; } -/** - * Apply pending monitor plugin schema/metadata upgrades. - * - * @return void - */ -function monitorCheckUpgrade(): void -{ - $files = ['plugins.php', 'monitor.php']; +function monitor_check_upgrade() { + $files = ['plugins.php', 'monitor.php']; - if (isset($_SERVER['PHP_SELF']) && !in_array(basename($_SERVER['PHP_SELF']), $files, true)) { - return; - } + if (isset($_SERVER['PHP_SELF']) && !in_array(basename($_SERVER['PHP_SELF']), $files, true)) { + return; + } - $info = plugin_monitor_version(); - $current = $info['version']; - $old = db_fetch_cell('SELECT version FROM plugin_config WHERE directory = "monitor"'); + $info = plugin_monitor_version(); + $current = $info['version']; + $old = db_fetch_cell('SELECT version FROM plugin_config WHERE directory = "monitor"'); - if ($current != $old) { - monitorSetupTable(); + if ($current != $old) { + monitor_setup_table(); - api_plugin_register_hook('monitor', 'page_head', 'pluginMonitorPageHead', 'setup.php', 1); + api_plugin_register_hook('monitor', 'page_head', 'plugin_monitor_page_head', 'setup.php', 1); - db_execute('ALTER TABLE host MODIFY COLUMN monitor char(3) DEFAULT "on"'); + db_execute('ALTER TABLE host MODIFY COLUMN monitor char(3) DEFAULT "on"'); - db_execute('ALTER TABLE plugin_monitor_uptime + db_execute('ALTER TABLE plugin_monitor_uptime MODIFY COLUMN uptime BIGINT unsigned NOT NULL default "0"'); - api_plugin_db_add_column('monitor', 'host', ['name' => 'monitor_icon', 'type' => 'varchar(30)', 'NULL' => false, 'default' => '']); + api_plugin_db_add_column('monitor', 'host', ['name' => 'monitor_icon', 'type' => 'varchar(30)', 'NULL' => false, 'default' => '']); - if (function_exists('api_plugin_upgrade_register')) { - api_plugin_upgrade_register('monitor'); - } else { - db_execute_prepared( - 'UPDATE plugin_config + if (function_exists('api_plugin_upgrade_register')) { + api_plugin_upgrade_register('monitor'); + } else { + db_execute_prepared('UPDATE plugin_config SET version = ?, name = ?, author = ?, webpage = ? WHERE directory = ?', - [ - $info['version'], - $info['longname'], - $info['author'], - $info['homepage'], - $info['name'] - ] - ); - } - } + [ + $info['version'], + $info['longname'], + $info['author'], + $info['homepage'], + $info['name'] + ] + ); + } + } } -/** - * Read monitor plugin metadata from INFO file. - * - * @return array - */ -function plugin_monitor_version(): array -{ - global $config; - $info = parse_ini_file($config['base_path'] . '/plugins/monitor/INFO', true); - - return $info['info']; +function plugin_monitor_version() { + global $config; + $info = parse_ini_file($config['base_path'] . '/plugins/monitor/INFO', true); + + return $info['info']; } -/** - * Execute custom monitor bulk actions for selected devices. - * - * @param string $action Requested device action key. - * - * @return string - */ -function monitorDeviceActionExecute(string $action): string -{ - global $config, $fields_host_edit; - - if ($action != 'monitor_enable' && $action != 'monitor_disable' && $action != 'monitor_settings') { - return $action; - } - - $selected_items = sanitize_unserialize_selected_items(get_nfilter_request_var('selected_items')); - - if ($selected_items != false) { - if ($action == 'monitor_enable' || $action == 'monitor_disable') { - for ($i = 0; ($i < count($selected_items)); $i++) { - if ($action == 'monitor_enable') { - db_execute_prepared( - 'UPDATE host +function monitor_device_action_execute($action) { + global $config, $fields_host_edit; + + if ($action != 'monitor_enable' && $action != 'monitor_disable' && $action != 'monitor_settings') { + return $action; + } + + $selected_items = sanitize_unserialize_selected_items(get_nfilter_request_var('selected_items')); + + if ($selected_items != false) { + if ($action == 'monitor_enable' || $action == 'monitor_disable') { + for ($i = 0; ($i < count($selected_items)); $i++) { + if ($action == 'monitor_enable') { + db_execute_prepared('UPDATE host SET monitor = "on" WHERE deleted = "" AND id = ?', - [$selected_items[$i]] - ); - } elseif ($action == 'monitor_disable') { - db_execute_prepared( - 'UPDATE host + [$selected_items[$i]]); + } elseif ($action == 'monitor_disable') { + db_execute_prepared('UPDATE host SET monitor = "" WHERE deleted = "" AND id = ?', - [$selected_items[$i]] - ); - } - } - } else { - for ($i = 0; ($i < count($selected_items)); $i++) { - reset($fields_host_edit); - - foreach ($fields_host_edit as $field_name => $field_array) { - if (isset_request_var("t_$field_name")) { - if ($field_name == 'monitor_alert_baseline') { - $cur_time = db_fetch_cell_prepared( - 'SELECT cur_time + [$selected_items[$i]]); + } + } + } else { + for ($i = 0; ($i < count($selected_items)); $i++) { + reset($fields_host_edit); + + foreach ($fields_host_edit as $field_name => $field_array) { + if (isset_request_var("t_$field_name")) { + if ($field_name == 'monitor_alert_baseline') { + $cur_time = db_fetch_cell_prepared('SELECT cur_time FROM host WHERE deleted = "" AND id = ?', - [$selected_items[$i]] - ); + [$selected_items[$i]]); - if ($cur_time > 0) { - db_execute_prepared( - 'UPDATE host + if ($cur_time > 0) { + db_execute_prepared('UPDATE host SET monitor_alert = CEIL(avg_time*?) WHERE deleted = "" AND id = ?', - [get_nfilter_request_var($field_name), $selected_items[$i]] - ); - } - } elseif ($field_name == 'monitor_warn_baseline') { - $cur_time = db_fetch_cell_prepared( - 'SELECT cur_time + [get_nfilter_request_var($field_name), $selected_items[$i]]); + } + } elseif ($field_name == 'monitor_warn_baseline') { + $cur_time = db_fetch_cell_prepared('SELECT cur_time FROM host WHERE deleted = "" AND id = ?', - [$selected_items[$i]] - ); + [$selected_items[$i]]); - if ($cur_time > 0) { - db_execute_prepared( - 'UPDATE host + if ($cur_time > 0) { + db_execute_prepared('UPDATE host SET monitor_warn = CEIL(avg_time*?) WHERE deleted = "" AND id = ?', - [get_nfilter_request_var($field_name), $selected_items[$i]] - ); - } - } else { - db_execute_prepared( - "UPDATE host + [get_nfilter_request_var($field_name), $selected_items[$i]]); + } + } else { + db_execute_prepared("UPDATE host SET $field_name = ? WHERE deleted='' AND id = ?", - [get_nfilter_request_var($field_name), $selected_items[$i]] - ); - } - } - } - } - } - } - - return $action; + [get_nfilter_request_var($field_name), $selected_items[$i]]); + } + } + } + } + } + } + + return $action; } -/** - * Remove monitor history/uptime rows for deleted devices. - * - * @param array $devices Device ids being removed. - * - * @return array - */ -function monitorDeviceRemove(array $devices): array -{ - db_execute('DELETE FROM plugin_monitor_notify_history WHERE host_id IN(' . implode(',', $devices) . ')'); - db_execute('DELETE FROM plugin_monitor_reboot_history WHERE host_id IN(' . implode(',', $devices) . ')'); - db_execute('DELETE FROM plugin_monitor_uptime WHERE host_id IN(' . implode(',', $devices) . ')'); - - return $devices; +function monitor_device_remove($devices) { + db_execute('DELETE FROM plugin_monitor_notify_history WHERE host_id IN(' . implode(',', $devices) . ')'); + db_execute('DELETE FROM plugin_monitor_reboot_history WHERE host_id IN(' . implode(',', $devices) . ')'); + db_execute('DELETE FROM plugin_monitor_uptime WHERE host_id IN(' . implode(',', $devices) . ')'); + + return $devices; } -/** - * Render confirmation/edit UI for monitor-specific bulk device actions. - * - * @param array $save Bulk action context payload. - * - * @return array - */ -function monitorDeviceActionPrepare(array $save): array -{ - global $host_list, $fields_host_edit; - - if (!isset($save['drp_action'])) { - return $save; - } else { - $action = $save['drp_action']; - - if ($action != 'monitor_enable' && $action != 'monitor_disable' && $action != 'monitor_settings') { - return $save; - } - - if ($action == 'monitor_enable' || $action == 'monitor_disable') { - if ($action == 'monitor_enable') { - $action_description = 'enable'; - } elseif ($action == 'monitor_disable') { - $action_description = 'disable'; - } - - print " +function monitor_device_action_prepare($save) { + global $host_list, $fields_host_edit; + + if (!isset($save['drp_action'])) { + return $save; + } else { + $action = $save['drp_action']; + + if ($action != 'monitor_enable' && $action != 'monitor_disable' && $action != 'monitor_settings') { + return $save; + } + + if ($action == 'monitor_enable' || $action == 'monitor_disable') { + if ($action == 'monitor_enable') { + $action_description = 'enable'; + } elseif ($action == 'monitor_disable') { + $action_description = 'disable'; + } + + print "'; - } else { - print " + } else { + print "'; - $form_array = []; - $fields = [ - 'monitor', - 'monitor_text', - 'monitor_criticality', - 'monitor_warn', - 'monitor_alert', - 'monitor_warn_baseline', - 'monitor_alert_baseline', - 'monitor_icon' - ]; - - foreach ($fields as $field) { - $form_array += [$field => $fields_host_edit[$field]]; - - $form_array[$field]['value'] = ''; - $form_array[$field]['form_id'] = 0; - $form_array[$field]['sub_checkbox'] = [ - 'name' => 't_' . $field, - 'friendly_name' => __('Update this Field', 'monitor'), - 'value' => '' - ]; - } - - draw_edit_form( - [ - 'config' => ['no_form_tag' => true], - 'fields' => $form_array - ] - ); - } - - return $save; - } + $form_array = []; + $fields = [ + 'monitor', + 'monitor_text', + 'monitor_criticality', + 'monitor_warn', + 'monitor_alert', + 'monitor_warn_baseline', + 'monitor_alert_baseline', + 'monitor_icon' + ]; + + foreach ($fields as $field) { + $form_array += [$field => $fields_host_edit[$field]]; + + $form_array[$field]['value'] = ''; + $form_array[$field]['form_id'] = 0; + $form_array[$field]['sub_checkbox'] = [ + 'name' => 't_' . $field, + 'friendly_name' => __('Update this Field', 'monitor'), + 'value' => '' + ]; + } + + draw_edit_form( + [ + 'config' => ['no_form_tag' => true], + 'fields' => $form_array + ] + ); + } + + return $save; + } } -/** - * Register monitor-specific entries in device action dropdown. - * - * @param array $device_action_array Existing action map. - * - * @return array - */ -function monitorDeviceActionArray(array $device_action_array): array -{ - $device_action_array['monitor_settings'] = __('Change Monitoring Options', 'monitor'); - $device_action_array['monitor_enable'] = __('Enable Monitoring', 'monitor'); - $device_action_array['monitor_disable'] = __('Disable Monitoring', 'monitor'); - - return $device_action_array; +function monitor_device_action_array($device_action_array) { + $device_action_array['monitor_settings'] = __('Change Monitoring Options', 'monitor'); + $device_action_array['monitor_enable'] = __('Enable Monitoring', 'monitor'); + $device_action_array['monitor_disable'] = __('Disable Monitoring', 'monitor'); + + return $device_action_array; } -/** - * Scan monitor sounds directory and return selectable alarm files. - * - * @return array - */ -function monitorScanDir(): array -{ - global $config; - - $ext = ['.wav', '.mp3']; - $d = dir($config['base_path'] . '/plugins/monitor/sounds/'); - $files = []; - - while (false !== ($entry = $d->read())) { - if ($entry != '.' && $entry != '..' && in_array(strtolower(substr($entry, -4)), $ext, true)) { - $files[$entry] = $entry; - } - } - $d->close(); - asort($files); // sort the files - array_unshift($files, 'None'); // prepend the None option - - return $files; +function monitor_scan_dir() { + global $config; + + $ext = ['.wav', '.mp3']; + $d = dir($config['base_path'] . '/plugins/monitor/sounds/'); + $files = []; + + while (false !== ($entry = $d->read())) { + if ($entry != '.' && $entry != '..' && in_array(strtolower(substr($entry,-4)),$ext, true)) { + $files[$entry] = $entry; + } + } + $d->close(); + asort($files); // sort the files + array_unshift($files, 'None'); // prepend the None option + + return $files; } -/** - * Register monitor plugin settings and user preference definitions. - * - * @return void - */ -function monitorConfigSettings(): void -{ - global $tabs, $formats, $settings, $criticalities, $page_refresh_interval, $config, $settings_user, $tabs_graphs; - - include_once($config['base_path'] . '/lib/reports.php'); - - if (get_nfilter_request_var('tab') == 'monitor') { - $formats = reports_get_format_files(); - } elseif (empty($formats)) { - $formats = []; - } - - $criticalities = [ - 0 => __('Disabled', 'monitor'), - 1 => __('Low', 'monitor'), - 2 => __('Medium', 'monitor'), - 3 => __('High', 'monitor'), - 4 => __('Mission Critical', 'monitor') - ]; - - $log_retentions = [ - '-1' => __('Indefinitely', 'monitor'), - '31' => __('%d Month', 1, 'monitor'), - '62' => __('%d Months', 2, 'monitor'), - '93' => __('%d Months', 3, 'monitor'), - '124' => __('%d Months', 4, 'monitor'), - '186' => __('%d Months', 6, 'monitor'), - '365' => __('%d Year', 1, 'monitor') - ]; - - $font_sizes = [ - '20' => '20px', - '30' => '30px', - '40' => '40px', - '50' => '50px', - '60' => '60px', - '70' => '70px' - ]; - - if (function_exists('auth_augment_roles')) { - auth_augment_roles(__('Normal User'), ['monitor.php']); - } - - $tabs_graphs += ['monitor' => __('Monitor Settings', 'monitor')]; - - $settings_user += [ - 'monitor' => [ - 'monitor_sound' => [ - 'friendly_name' => __('Alarm Sound', 'monitor'), - 'description' => __('This is the sound file that will be played when a Device goes down.', 'monitor'), - 'method' => 'drop_array', - 'array' => monitorScanDir(), - 'default' => 'attn-noc.wav', - ], - 'monitor_sound_loop' => [ - 'friendly_name' => __('Loop Alarm Sound', 'monitor'), - 'description' => __('Play the above sound on a loop when a Device goes down.', 'monitor'), - 'method' => 'checkbox', - ], - 'monitor_legend' => [ - 'friendly_name' => __('Show Icon Legend', 'monitor'), - 'description' => __('Check this to show an icon legend on the Monitor display', 'monitor'), - 'method' => 'checkbox', - ], - 'monitor_uptime' => [ - 'friendly_name' => __('Show Uptime', 'monitor'), - 'description' => __('Check this to show Uptime on the Monitor display', 'monitor'), - 'method' => 'checkbox', - ], - 'monitor_error_zoom' => [ - 'friendly_name' => __('Zoom to Errors', 'monitor'), - 'description' => __('Check this to zoom to errored items on the Monitor display', 'monitor'), - 'method' => 'checkbox', - ], - 'monitor_error_background' => [ - 'friendly_name' => __('Zoom Background', 'monitor'), - 'description' => __('Background Color for Zoomed Errors on the Monitor display', 'monitor'), - 'method' => 'drop_color', - ], - 'monitor_error_fontsize' => [ - 'friendly_name' => __('Zoom Fontsize', 'monitor'), - 'description' => __('Check this to zoom to errored items on the Monitor display', 'monitor'), - 'method' => 'drop_array', - 'default' => '50', - 'array' => $font_sizes - ] - ] - ]; - - if (get_current_page() != 'settings.php') { - return; - } - - $tabs['monitor'] = __('Monitor', 'monitor'); - - $temp = [ - 'monitor_header' => [ - 'friendly_name' => __('Monitor Settings', 'monitor'), - 'method' => 'spacer', - 'collapsible' => 'true' - ], - 'monitor_new_enabled' => [ - 'friendly_name' => __('Enable on new devices', 'monitor'), - 'description' => __('Check this to automatically enable monitoring when creating new devices', 'monitor'), - 'method' => 'checkbox', - ], - 'monitor_log_storage' => [ - 'friendly_name' => __('Notification/Reboot Log Retention', 'monitor'), - 'description' => __('Keep Notification and Reboot Logs for this number of days.', 'monitor'), - 'method' => 'drop_array', - 'default' => '31', - 'array' => $log_retentions - ], - 'monitor_sound' => [ - 'friendly_name' => __('Alarm Sound', 'monitor'), - 'description' => __('This is the sound file that will be played when a Device goes down.', 'monitor'), - 'method' => 'drop_array', - 'array' => monitorScanDir(), - 'default' => 'attn-noc.wav', - ], - 'monitor_sound_loop' => [ - 'friendly_name' => __('Loop Alarm Sound', 'monitor'), - 'description' => __('Play the above sound on a loop when a Device goes down.', 'monitor'), - 'method' => 'checkbox', - ], - 'monitor_refresh' => [ - 'friendly_name' => __('Refresh Interval', 'monitor'), - 'description' => __('This is the time in seconds before the page refreshes. (1 - 300)', 'monitor'), - 'method' => 'drop_array', - 'default' => '60', - 'array' => $page_refresh_interval - ], - 'monitor_legend' => [ - 'friendly_name' => __('Show Icon Legend', 'monitor'), - 'description' => __('Check this to show an icon legend on the Monitor display', 'monitor'), - 'method' => 'checkbox', - ], - 'monitor_grouping' => [ - 'friendly_name' => __('Grouping', 'monitor'), - 'description' => __('This is how monitor will Group Devices.', 'monitor'), - 'method' => 'drop_array', - 'default' => 'default', - 'array' => [ - 'default' => __('Default', 'monitor'), - 'default_by_permissions' => __('Default with permissions', 'monitor'), - 'group_by_tree' => __('Tree', 'monitor'), - 'group_by_device_template' => __('Device Template', 'monitor'), - ] - ], - 'monitor_view' => [ - 'friendly_name' => __('View', 'monitor'), - 'description' => __('This is how monitor will render Devices.', 'monitor'), - 'method' => 'drop_array', - 'default' => 'default', - 'array' => [ - 'default' => __('Default', 'monitor'), - 'list' => __('List', 'monitor'), - 'names' => __('Names only', 'monitor'), - 'tiles' => __('Tiles', 'monitor'), - 'tilesadt' => __('Tiles & Downtime', 'monitor') - ] - ], - 'monitor_format_header' => [ - 'friendly_name' => __('Notification Report Format', 'monitor'), - 'method' => 'spacer', - 'collapsible' => 'true' - ], - 'monitor_format_file' => [ - 'friendly_name' => __('Format File to Use', 'monitor'), - 'method' => 'drop_array', - 'default' => 'default.format', - 'description' => __('Choose the custom html wrapper and CSS file to use. This file contains both html and CSS to wrap around your report. If it contains more than simply CSS, you need to place a special tag inside of the file. This format tag will be replaced by the report content. These files are located in the \'formats\' directory.', 'monitor'), - 'array' => $formats - ], - 'monitor_threshold' => [ - 'friendly_name' => __('Ping Threshold Notifications', 'monitor'), - 'method' => 'spacer', - 'collapsible' => 'true' - ], - 'monitor_warn_criticality' => [ - 'friendly_name' => __('Warning Latency Notification', 'monitor'), - 'description' => __('If a Device has a Round Trip Ping Latency above the Warning Threshold and above the Criticality below, subscribing emails to the Device will receive an email notification. Select \'Disabled\' to Disable. The Thold Plugin is required to enable this feature.', 'monitor'), - 'method' => 'drop_array', - 'default' => '0', - 'array' => $criticalities - ], - 'monitor_alert_criticality' => [ - 'friendly_name' => __('Alert Latency Notification', 'monitor'), - 'description' => __('If a Device has a Round Trip Ping Latency above the Alert Threshold and above the Criticality below, subscribing emails to the Device will receive an email notification. Select \'Disabled\' to Disable. The Thold Plugin is required to enable this feature.', 'monitor'), - 'method' => 'drop_array', - 'default' => '0', - 'array' => $criticalities - ], - 'monitor_resend_frequency' => [ - 'friendly_name' => __('How Often to Resend Emails', 'monitor'), - 'description' => __('How often should emails notifications be sent to subscribers for these Devices if they are exceeding their latency thresholds', 'monitor'), - 'method' => 'drop_array', - 'default' => '0', - 'array' => [ - '0' => __('Every Occurrence', 'monitor'), - '20' => __('Every %d Minutes', 20, 'monitor'), - '30' => __('Every %d Minutes', 30, 'monitor'), - '60' => __('Every Hour', 'monitor'), - '120' => __('Every %d Hours', 2, 'monitor'), - '240' => __('Every %d Hours', 4, 'monitor') - ] - ], - 'monitor_reboot' => [ - 'friendly_name' => __('Reboot Notifications', 'monitor'), - 'method' => 'spacer', - 'collapsible' => 'true' - ], - 'monitor_reboot_notify' => [ - 'friendly_name' => __('Send Reboot Notifications', 'monitor'), - 'method' => 'checkbox', - 'description' => __('Should Device Reboot Notifications be sent to users?', 'monitor'), - 'default' => 'on', - ], - 'monitor_send_one_email' => [ - 'friendly_name' => __('Send one Email to all addresses', 'monitor'), - 'description' => __('If checked, the system will send one Email only to all addresses.', 'monitor'), - 'method' => 'checkbox', - 'default' => 'on' - ], - 'monitor_reboot_thold' => [ - 'friendly_name' => __('Include Threshold Alert Lists', 'monitor'), - 'method' => 'checkbox', - 'description' => __('Should Threshold Alert Lists also receive Notification', 'monitor'), - 'default' => 'on', - ], - 'monitor_subject' => [ - 'friendly_name' => __('Subject', 'monitor'), - 'description' => __('Enter a Reboot message subject for the Reboot Notification.', 'monitor'), - 'method' => 'textbox', - 'default' => __('Cacti Device Reboot Notification', 'monitor'), - 'size' => 60, - 'max_length' => 60 - ], - 'monitor_body' => [ - 'friendly_name' => __('Email Body', 'monitor'), - 'description' => __('Enter an Email body to include in the Reboot Notification message. Currently, the only supported replacement tag accepted is <DETAILS>', 'monitor'), - 'method' => 'textarea', - 'textarea_rows' => 4, - 'textarea_cols' => 80, - 'default' => __('

Monitor Reboot Notification

The following Device\'s were Rebooted. See details below for additional information.


', 'monitor') - ], - 'monitor_email_header' => [ - 'friendly_name' => __('Notification Email Addresses', 'monitor'), - 'method' => 'spacer', - 'collapsible' => 'true' - ], - 'monitor_fromname' => [ - 'friendly_name' => __('From Name', 'monitor'), - 'description' => __('Enter the Email Name to send the notifications from', 'monitor'), - 'method' => 'textbox', - 'size' => '60', - 'max_length' => '255' - ], - 'monitor_fromemail' => [ - 'friendly_name' => __('From Address', 'monitor'), - 'description' => __('Enter the Email Address to send the notification from', 'monitor'), - 'method' => 'textbox', - 'size' => '60', - 'max_length' => '255' - ], - 'monitor_list' => [ - 'friendly_name' => __('Notification List', 'thold'), - 'description' => __('Select a Notification List below. All Emails subscribed to the notification list will be notified.', 'thold'), - 'method' => 'drop_sql', - 'sql' => 'SELECT id, name FROM plugin_notification_lists ORDER BY name', - 'default' => '', - 'none_value' => __('None', 'monitor') - ], - 'monitor_emails' => [ - 'friendly_name' => __('Email Addresses', 'monitor'), - 'description' => __('Enter a comma delimited list of Email addresses to inform of a reboot event.', 'monitor'), - 'method' => 'textarea', - 'textarea_rows' => 2, - 'textarea_cols' => 80, - 'default' => '' - ] - ]; - - if (isset($settings['monitor'])) { - $settings['monitor'] = array_merge($settings['monitor'], $temp); - } else { - $settings['monitor'] = $temp; - } +function monitor_config_settings() { + global $tabs, $formats, $settings, $criticalities, $page_refresh_interval, $config, $settings_user, $tabs_graphs; + + include_once($config['base_path'] . '/lib/reports.php'); + + if (get_nfilter_request_var('tab') == 'monitor') { + $formats = reports_get_format_files(); + } elseif (empty($formats)) { + $formats = []; + } + + $criticalities = [ + 0 => __('Disabled', 'monitor'), + 1 => __('Low', 'monitor'), + 2 => __('Medium', 'monitor'), + 3 => __('High', 'monitor'), + 4 => __('Mission Critical', 'monitor') + ]; + + $log_retentions = [ + '-1' => __('Indefinitely', 'monitor'), + '31' => __('%d Month', 1, 'monitor'), + '62' => __('%d Months', 2, 'monitor'), + '93' => __('%d Months', 3, 'monitor'), + '124' => __('%d Months', 4, 'monitor'), + '186' => __('%d Months', 6, 'monitor'), + '365' => __('%d Year', 1, 'monitor') + ]; + + $font_sizes = [ + '20' => '20px', + '30' => '30px', + '40' => '40px', + '50' => '50px', + '60' => '60px', + '70' => '70px' + ]; + + if (function_exists('auth_augment_roles')) { + auth_augment_roles(__('Normal User'), ['monitor.php']); + } + + $tabs_graphs += ['monitor' => __('Monitor Settings', 'monitor')]; + + $settings_user += [ + 'monitor' => [ + 'monitor_sound' => [ + 'friendly_name' => __('Alarm Sound', 'monitor'), + 'description' => __('This is the sound file that will be played when a Device goes down.', 'monitor'), + 'method' => 'drop_array', + 'array' => monitor_scan_dir(), + 'default' => 'attn-noc.wav', + ], + 'monitor_sound_loop' => [ + 'friendly_name' => __('Loop Alarm Sound', 'monitor'), + 'description' => __('Play the above sound on a loop when a Device goes down.', 'monitor'), + 'method' => 'checkbox', + ], + 'monitor_legend' => [ + 'friendly_name' => __('Show Icon Legend', 'monitor'), + 'description' => __('Check this to show an icon legend on the Monitor display', 'monitor'), + 'method' => 'checkbox', + ], + 'monitor_uptime' => [ + 'friendly_name' => __('Show Uptime', 'monitor'), + 'description' => __('Check this to show Uptime on the Monitor display', 'monitor'), + 'method' => 'checkbox', + ], + 'monitor_error_zoom' => [ + 'friendly_name' => __('Zoom to Errors', 'monitor'), + 'description' => __('Check this to zoom to errored items on the Monitor display', 'monitor'), + 'method' => 'checkbox', + ], + 'monitor_error_background' => [ + 'friendly_name' => __('Zoom Background', 'monitor'), + 'description' => __('Background Color for Zoomed Errors on the Monitor display', 'monitor'), + 'method' => 'drop_color', + ], + 'monitor_error_fontsize' => [ + 'friendly_name' => __('Zoom Fontsize', 'monitor'), + 'description' => __('Check this to zoom to errored items on the Monitor display', 'monitor'), + 'method' => 'drop_array', + 'default' => '50', + 'array' => $font_sizes + ] + ] + ]; + + if (get_current_page() != 'settings.php') { + return; + } + + $tabs['monitor'] = __('Monitor', 'monitor'); + + $temp = [ + 'monitor_header' => [ + 'friendly_name' => __('Monitor Settings', 'monitor'), + 'method' => 'spacer', + 'collapsible' => 'true' + ], + 'monitor_new_enabled' => [ + 'friendly_name' => __('Enable on new devices', 'monitor'), + 'description' => __('Check this to automatically enable monitoring when creating new devices', 'monitor'), + 'method' => 'checkbox', + ], + 'monitor_log_storage' => [ + 'friendly_name' => __('Notification/Reboot Log Retention', 'monitor'), + 'description' => __('Keep Notification and Reboot Logs for this number of days.', 'monitor'), + 'method' => 'drop_array', + 'default' => '31', + 'array' => $log_retentions + ], + 'monitor_sound' => [ + 'friendly_name' => __('Alarm Sound', 'monitor'), + 'description' => __('This is the sound file that will be played when a Device goes down.', 'monitor'), + 'method' => 'drop_array', + 'array' => monitor_scan_dir(), + 'default' => 'attn-noc.wav', + ], + 'monitor_sound_loop' => [ + 'friendly_name' => __('Loop Alarm Sound', 'monitor'), + 'description' => __('Play the above sound on a loop when a Device goes down.', 'monitor'), + 'method' => 'checkbox', + ], + 'monitor_refresh' => [ + 'friendly_name' => __('Refresh Interval', 'monitor'), + 'description' => __('This is the time in seconds before the page refreshes. (1 - 300)', 'monitor'), + 'method' => 'drop_array', + 'default' => '60', + 'array' => $page_refresh_interval + ], + 'monitor_legend' => [ + 'friendly_name' => __('Show Icon Legend', 'monitor'), + 'description' => __('Check this to show an icon legend on the Monitor display', 'monitor'), + 'method' => 'checkbox', + ], + 'monitor_grouping' => [ + 'friendly_name' => __('Grouping', 'monitor'), + 'description' => __('This is how monitor will Group Devices.', 'monitor'), + 'method' => 'drop_array', + 'default' => 'default', + 'array' => [ + 'default' => __('Default', 'monitor'), + 'default_by_permissions' => __('Default with permissions', 'monitor'), + 'group_by_tree' => __('Tree', 'monitor'), + 'group_by_device_template' => __('Device Template', 'monitor'), + ] + ], + 'monitor_view' => [ + 'friendly_name' => __('View', 'monitor'), + 'description' => __('This is how monitor will render Devices.', 'monitor'), + 'method' => 'drop_array', + 'default' => 'default', + 'array' => [ + 'default' => __('Default', 'monitor'), + 'list' => __('List', 'monitor'), + 'names' => __('Names only', 'monitor'), + 'tiles' => __('Tiles', 'monitor'), + 'tilesadt' => __('Tiles & Downtime', 'monitor') + ] + ], + 'monitor_format_header' => [ + 'friendly_name' => __('Notification Report Format', 'monitor'), + 'method' => 'spacer', + 'collapsible' => 'true' + ], + 'monitor_format_file' => [ + 'friendly_name' => __('Format File to Use', 'monitor'), + 'method' => 'drop_array', + 'default' => 'default.format', + 'description' => __('Choose the custom html wrapper and CSS file to use. This file contains both html and CSS to wrap around your report. If it contains more than simply CSS, you need to place a special tag inside of the file. This format tag will be replaced by the report content. These files are located in the \'formats\' directory.', 'monitor'), + 'array' => $formats + ], + 'monitor_threshold' => [ + 'friendly_name' => __('Ping Threshold Notifications', 'monitor'), + 'method' => 'spacer', + 'collapsible' => 'true' + ], + 'monitor_warn_criticality' => [ + 'friendly_name' => __('Warning Latency Notification', 'monitor'), + 'description' => __('If a Device has a Round Trip Ping Latency above the Warning Threshold and above the Criticality below, subscribing emails to the Device will receive an email notification. Select \'Disabled\' to Disable. The Thold Plugin is required to enable this feature.', 'monitor'), + 'method' => 'drop_array', + 'default' => '0', + 'array' => $criticalities + ], + 'monitor_alert_criticality' => [ + 'friendly_name' => __('Alert Latency Notification', 'monitor'), + 'description' => __('If a Device has a Round Trip Ping Latency above the Alert Threshold and above the Criticality below, subscribing emails to the Device will receive an email notification. Select \'Disabled\' to Disable. The Thold Plugin is required to enable this feature.', 'monitor'), + 'method' => 'drop_array', + 'default' => '0', + 'array' => $criticalities + ], + 'monitor_resend_frequency' => [ + 'friendly_name' => __('How Often to Resend Emails', 'monitor'), + 'description' => __('How often should emails notifications be sent to subscribers for these Devices if they are exceeding their latency thresholds', 'monitor'), + 'method' => 'drop_array', + 'default' => '0', + 'array' => [ + '0' => __('Every Occurrence', 'monitor'), + '20' => __('Every %d Minutes', 20, 'monitor'), + '30' => __('Every %d Minutes', 30, 'monitor'), + '60' => __('Every Hour', 'monitor'), + '120' => __('Every %d Hours', 2, 'monitor'), + '240' => __('Every %d Hours', 4, 'monitor') + ] + ], + 'monitor_reboot' => [ + 'friendly_name' => __('Reboot Notifications', 'monitor'), + 'method' => 'spacer', + 'collapsible' => 'true' + ], + 'monitor_reboot_notify' => [ + 'friendly_name' => __('Send Reboot Notifications', 'monitor'), + 'method' => 'checkbox', + 'description' => __('Should Device Reboot Notifications be sent to users?', 'monitor'), + 'default' => 'on', + ], + 'monitor_send_one_email' => [ + 'friendly_name' => __('Send one Email to all addresses', 'monitor'), + 'description' => __('If checked, the system will send one Email only to all addresses.', 'monitor'), + 'method' => 'checkbox', + 'default' => 'on' + ], + 'monitor_reboot_thold' => [ + 'friendly_name' => __('Include Threshold Alert Lists', 'monitor'), + 'method' => 'checkbox', + 'description' => __('Should Threshold Alert Lists also receive Notification', 'monitor'), + 'default' => 'on', + ], + 'monitor_subject' => [ + 'friendly_name' => __('Subject', 'monitor'), + 'description' => __('Enter a Reboot message subject for the Reboot Notification.', 'monitor'), + 'method' => 'textbox', + 'default' => __('Cacti Device Reboot Notification', 'monitor'), + 'size' => 60, + 'max_length' => 60 + ], + 'monitor_body' => [ + 'friendly_name' => __('Email Body', 'monitor'), + 'description' => __('Enter an Email body to include in the Reboot Notification message. Currently, the only supported replacement tag accepted is <DETAILS>', 'monitor'), + 'method' => 'textarea', + 'textarea_rows' => 4, + 'textarea_cols' => 80, + 'default' => __('

Monitor Reboot Notification

The following Device\'s were Rebooted. See details below for additional information.


', 'monitor') + ], + 'monitor_email_header' => [ + 'friendly_name' => __('Notification Email Addresses', 'monitor'), + 'method' => 'spacer', + 'collapsible' => 'true' + ], + 'monitor_fromname' => [ + 'friendly_name' => __('From Name', 'monitor'), + 'description' => __('Enter the Email Name to send the notifications from', 'monitor'), + 'method' => 'textbox', + 'size' => '60', + 'max_length' => '255' + ], + 'monitor_fromemail' => [ + 'friendly_name' => __('From Address', 'monitor'), + 'description' => __('Enter the Email Address to send the notification from', 'monitor'), + 'method' => 'textbox', + 'size' => '60', + 'max_length' => '255' + ], + 'monitor_list' => [ + 'friendly_name' => __('Notification List', 'thold'), + 'description' => __('Select a Notification List below. All Emails subscribed to the notification list will be notified.', 'thold'), + 'method' => 'drop_sql', + 'sql' => 'SELECT id, name FROM plugin_notification_lists ORDER BY name', + 'default' => '', + 'none_value' => __('None', 'monitor') + ], + 'monitor_emails' => [ + 'friendly_name' => __('Email Addresses', 'monitor'), + 'description' => __('Enter a comma delimited list of Email addresses to inform of a reboot event.', 'monitor'), + 'method' => 'textarea', + 'textarea_rows' => 2, + 'textarea_cols' => 80, + 'default' => '' + ] + ]; + + if (isset($settings['monitor'])) { + $settings['monitor'] = array_merge($settings['monitor'], $temp); + } else { + $settings['monitor'] = $temp; + } } -/** - * Build monitor icon option arrays and normalize legacy format fallback. - * - * @return void - */ -function monitorConfigArrays(): void -{ - global $fa_icons; - - $fa_icons = [ - 'server' => [ - 'display' => __('Server', 'monitor'), - 'class' => 'fa fa-server deviceUp', - 'style' => '' - ], - 'print' => [ - 'display' => __('Printer', 'monitor'), - 'class' => 'fa fa-print deviceUp', - 'style' => '' - ], - 'desktop' => [ - 'display' => __('Desktop PC', 'monitor'), - 'class' => 'fa fa-desktop deviceUp', - 'style' => '' - ], - 'laptop' => [ - 'display' => __('Laptop/notebook', 'monitor'), - 'class' => 'fa fa-laptop deviceUp', - 'style' => '' - ], - 'wifi' => [ - 'display' => __('Wifi', 'monitor'), - 'class' => 'fa fa-wifi deviceUp', - 'style' => '' - ], - 'network-wired' => [ - 'display' => __('Wired network', 'monitor'), - 'class' => 'fa fa-network-wired deviceUp', - 'style' => '' - ], - 'database' => [ - 'display' => __('Database', 'monitor'), - 'class' => 'fa fa-database deviceUp', - 'style' => '' - ], - 'clock' => [ - 'display' => __('Clock', 'monitor'), - 'class' => 'fa fa-clock deviceUp', - 'style' => '' - ], - 'asterisk' => [ - 'display' => __('Asterisk', 'monitor'), - 'class' => 'fas fa-asterisk deviceUp', - 'style' => '' - ], - 'hdd' => [ - 'display' => __('Harddisk', 'monitor'), - 'class' => 'fa fa-hdd deviceUp', - 'style' => '' - ], - 'boxes' => [ - 'display' => __('Boxes', 'monitor'), - 'class' => 'fa fa-boxes deviceUp', - 'style' => '' - ], - 'phone' => [ - 'display' => __('Phone', 'monitor'), - 'class' => 'fa fa-phone deviceUp', - 'style' => '' - ], - 'cloud' => [ - 'display' => __('Cloud', 'monitor'), - 'class' => 'fa fa-cloud deviceUp', - 'style' => '' - ] - ]; - - if (!function_exists('form_dropicon')) { - foreach ($fa_icons as $key => $data) { - $nfa_icons[$key] = $data['display']; - } - - $fa_icons = $nfa_icons; - } - - monitorCheckUpgrade(); +function monitor_config_arrays() { + global $fa_icons; + + $fa_icons = [ + 'server' => [ + 'display' => __('Server', 'monitor'), + 'class' => 'fa fa-server deviceUp', + 'style' => '' + ], + 'print' => [ + 'display' => __('Printer', 'monitor'), + 'class' => 'fa fa-print deviceUp', + 'style' => '' + ], + 'desktop' => [ + 'display' => __('Desktop PC', 'monitor'), + 'class' => 'fa fa-desktop deviceUp', + 'style' => '' + ], + 'laptop' => [ + 'display' => __('Laptop/notebook', 'monitor'), + 'class' => 'fa fa-laptop deviceUp', + 'style' => '' + ], + 'wifi' => [ + 'display' => __('Wifi', 'monitor'), + 'class' => 'fa fa-wifi deviceUp', + 'style' => '' + ], + 'network-wired' => [ + 'display' => __('Wired network', 'monitor'), + 'class' => 'fa fa-network-wired deviceUp', + 'style' => '' + ], + 'database' => [ + 'display' => __('Database', 'monitor'), + 'class' => 'fa fa-database deviceUp', + 'style' => '' + ], + 'clock' => [ + 'display' => __('Clock', 'monitor'), + 'class' => 'fa fa-clock deviceUp', + 'style' => '' + ], + 'asterisk' => [ + 'display' => __('Asterisk', 'monitor'), + 'class' => 'fas fa-asterisk deviceUp', + 'style' => '' + ], + 'hdd' => [ + 'display' => __('Harddisk', 'monitor'), + 'class' => 'fa fa-hdd deviceUp', + 'style' => '' + ], + 'boxes' => [ + 'display' => __('Boxes', 'monitor'), + 'class' => 'fa fa-boxes deviceUp', + 'style' => '' + ], + 'phone' => [ + 'display' => __('Phone', 'monitor'), + 'class' => 'fa fa-phone deviceUp', + 'style' => '' + ], + 'cloud' => [ + 'display' => __('Cloud', 'monitor'), + 'class' => 'fa fa-cloud deviceUp', + 'style' => '' + ] + ]; + + if (!function_exists('form_dropicon')) { + foreach ($fa_icons as $key => $data) { + $nfa_icons[$key] = $data['display']; + } + + $fa_icons = $nfa_icons; + } + + monitor_check_upgrade(); } -/** - * Override top-graph refresh interval when on monitor page. - * - * @param int|string $refresh Existing refresh interval. - * - * @return int|string - */ -function monitorTopGraphRefresh(mixed $refresh): mixed -{ - if (get_current_page() != 'monitor.php') { - return $refresh; - } - - $r = read_config_option('monitor_refresh'); - - if ($r == '' || $r < 1) { - return $refresh; - } - - return $r; +function monitor_top_graph_refresh($refresh) { + if (get_current_page() != 'monitor.php') { + return $refresh; + } + + $r = read_config_option('monitor_refresh'); + + if ($r == '' || $r < 1) { + return $refresh; + } + + return $r; } -/** - * Render monitor navigation tab icon for authorized users. - * - * @return void - */ -function monitorShowTab(): void -{ - global $config; - - monitorCheckUpgrade(); - - if (api_user_realm_auth('monitor.php')) { - if (substr_count($_SERVER['REQUEST_URI'], 'monitor.php')) { - print '' . __('Monitor', 'monitor') . ''; - } else { - print '' . __('Monitor', 'monitor') . ''; - } - } +function monitor_show_tab() { + global $config; + + monitor_check_upgrade(); + + if (api_user_realm_auth('monitor.php')) { + if (substr_count($_SERVER['REQUEST_URI'], 'monitor.php')) { + print '' . __('Monitor', 'monitor') . ''; + } else { + print '' . __('Monitor', 'monitor') . ''; + } + } } -/** - * Inject monitor fields into device edit form configuration. - * - * @return void - */ -function monitorConfigForm(): void -{ - global $config, $fields_host_edit, $criticalities, $fa_icons; - - $baselines = [ - '0' => __('Do not Change', 'monitor'), - '1.20' => __('%d Percent Above Average', 20, 'monitor'), - '1.30' => __('%d Percent Above Average', 30, 'monitor'), - '1.40' => __('%d Percent Above Average', 40, 'monitor'), - '1.50' => __('%d Percent Above Average', 50, 'monitor'), - '1.60' => __('%d Percent Above Average', 60, 'monitor'), - '1.70' => __('%d Percent Above Average', 70, 'monitor'), - '1.80' => __('%d Percent Above Average', 80, 'monitor'), - '1.90' => __('%d Percent Above Average', 90, 'monitor'), - '2.00' => __('%d Percent Above Average', 100, 'monitor'), - '2.20' => __('%d Percent Above Average', 120, 'monitor'), - '2.40' => __('%d Percent Above Average', 140, 'monitor'), - '2.50' => __('%d Percent Above Average', 150, 'monitor'), - '3.00' => __('%d Percent Above Average', 200, 'monitor'), - '4.00' => __('%d Percent Above Average', 300, 'monitor'), - '5.00' => __('%d Percent Above Average', 400, 'monitor'), - '6.00' => __('%d Percent Above Average', 500, 'monitor') - ]; - - $fields_host_edit2 = $fields_host_edit; - $fields_host_edit3 = []; - - if (array_key_exists('bulk_walk_size', $fields_host_edit2)) { - $insert_field = 'bulk_walk_size'; - } else { - $insert_field = 'disabled'; - } - - foreach ($fields_host_edit2 as $f => $a) { - $fields_host_edit3[$f] = $a; - - if ($f == $insert_field) { - $fields_host_edit3['monitor_header'] = [ - 'friendly_name' => __('Device Monitoring Settings', 'monitor'), - 'method' => 'spacer', - 'collapsible' => 'true' - ]; - - $fields_host_edit3['monitor'] = [ - 'method' => 'checkbox', - 'friendly_name' => __('Monitor Device', 'monitor'), - 'description' => __('Check this box to monitor this Device on the Monitor Tab.', 'monitor'), - 'value' => '|arg1:monitor|', - 'form_id' => false - ]; - - $host_id = get_nfilter_request_var('id'); - - if (empty($host_id) || !is_numeric($host_id)) { - $fields_host_edit3['monitor']['default'] = monitorGetDefault($host_id); - } - - $fields_host_edit3['monitor_criticality'] = [ - 'friendly_name' => __('Device Criticality', 'monitor'), - 'description' => __('What is the Criticality of this Device.', 'monitor'), - 'method' => 'drop_array', - 'array' => $criticalities, - 'value' => '|arg1:monitor_criticality|', - 'default' => '0', - ]; - - $fields_host_edit3['monitor_warn'] = [ - 'friendly_name' => __('Ping Warning Threshold', 'monitor'), - 'description' => __('If the round-trip latency via any of the predefined Cacti ping methods raises above this threshold, log a warning or send email based upon the Devices Criticality and Monitor setting. The unit is in milliseconds. Setting to 0 disables. The Thold Plugin is required to leverage this functionality.', 'monitor'), - 'method' => 'textbox', - 'size' => '10', - 'max_length' => '5', - 'placeholder' => __('milliseconds', 'monitor'), - 'value' => '|arg1:monitor_warn|', - 'default' => '', - ]; - - $fields_host_edit3['monitor_alert'] = [ - 'friendly_name' => __('Ping Alert Threshold', 'monitor'), - 'description' => __('If the round-trip latency via any of the predefined Cacti ping methods raises above this threshold, log an alert or send an email based upon the Devices Criticality and Monitor setting. The unit is in milliseconds. Setting to 0 disables. The Thold Plugin is required to leverage this functionality.', 'monitor'), - 'method' => 'textbox', - 'size' => '10', - 'max_length' => '5', - 'placeholder' => __('milliseconds', 'monitor'), - 'value' => '|arg1:monitor_alert|', - 'default' => '', - ]; - - $fields_host_edit3['monitor_warn_baseline'] = [ - 'friendly_name' => __('Re-Baseline Warning', 'monitor'), - 'description' => __('The percentage above the current average ping time to consider a Warning Threshold. If updated, this will automatically adjust the Ping Warning Threshold.', 'monitor'), - 'method' => 'drop_array', - 'default' => '0', - 'value' => '0', - 'array' => $baselines - ]; - - $fields_host_edit3['monitor_alert_baseline'] = [ - 'friendly_name' => __('Re-Baseline Alert', 'monitor'), - 'description' => __('The percentage above the current average ping time to consider a Alert Threshold. If updated, this will automatically adjust the Ping Alert Threshold.', 'monitor'), - 'method' => 'drop_array', - 'default' => '0', - 'value' => '0', - 'array' => $baselines - ]; - - $fields_host_edit3['monitor_text'] = [ - 'friendly_name' => __('Down Device Message', 'monitor'), - 'description' => __('This is the message that will be displayed when this Device is reported as down.', 'monitor'), - 'method' => 'textarea', - 'max_length' => 1000, - 'textarea_rows' => 2, - 'textarea_cols' => 80, - 'value' => '|arg1:monitor_text|', - 'default' => '', - ]; - - if (function_exists('form_dropicon')) { - $method = 'drop_icon'; - } else { - $method = 'drop_array'; - } - - $fields_host_edit3['monitor_icon'] = [ - 'friendly_name' => __('Device icon', 'monitor'), - 'description' => __('You can select device icon.', 'monitor'), - 'method' => $method, - 'default' => '0', - 'value' => '|arg1:monitor_icon|', - 'array' => $fa_icons, - ]; - } - } - - $fields_host_edit = $fields_host_edit3; +function monitor_config_form() { + global $config, $fields_host_edit, $criticalities, $fa_icons; + + $baselines = [ + '0' => __('Do not Change', 'monitor'), + '1.20' => __('%d Percent Above Average', 20, 'monitor'), + '1.30' => __('%d Percent Above Average', 30, 'monitor'), + '1.40' => __('%d Percent Above Average', 40, 'monitor'), + '1.50' => __('%d Percent Above Average', 50, 'monitor'), + '1.60' => __('%d Percent Above Average', 60, 'monitor'), + '1.70' => __('%d Percent Above Average', 70, 'monitor'), + '1.80' => __('%d Percent Above Average', 80, 'monitor'), + '1.90' => __('%d Percent Above Average', 90, 'monitor'), + '2.00' => __('%d Percent Above Average', 100, 'monitor'), + '2.20' => __('%d Percent Above Average', 120, 'monitor'), + '2.40' => __('%d Percent Above Average', 140, 'monitor'), + '2.50' => __('%d Percent Above Average', 150, 'monitor'), + '3.00' => __('%d Percent Above Average', 200, 'monitor'), + '4.00' => __('%d Percent Above Average', 300, 'monitor'), + '5.00' => __('%d Percent Above Average', 400, 'monitor'), + '6.00' => __('%d Percent Above Average', 500, 'monitor') + ]; + + $fields_host_edit2 = $fields_host_edit; + $fields_host_edit3 = []; + + if (array_key_exists('bulk_walk_size', $fields_host_edit2)) { + $insert_field = 'bulk_walk_size'; + } else { + $insert_field = 'disabled'; + } + + foreach ($fields_host_edit2 as $f => $a) { + $fields_host_edit3[$f] = $a; + + if ($f == $insert_field) { + $fields_host_edit3['monitor_header'] = [ + 'friendly_name' => __('Device Monitoring Settings', 'monitor'), + 'method' => 'spacer', + 'collapsible' => 'true' + ]; + + $fields_host_edit3['monitor'] = [ + 'method' => 'checkbox', + 'friendly_name' => __('Monitor Device', 'monitor'), + 'description' => __('Check this box to monitor this Device on the Monitor Tab.', 'monitor'), + 'value' => '|arg1:monitor|', + 'form_id' => false + ]; + + $host_id = get_nfilter_request_var('id'); + + if (empty($host_id) || !is_numeric($host_id)) { + $fields_host_edit3['monitor']['default'] = monitor_get_default($host_id); + } + + $fields_host_edit3['monitor_criticality'] = [ + 'friendly_name' => __('Device Criticality', 'monitor'), + 'description' => __('What is the Criticality of this Device.', 'monitor'), + 'method' => 'drop_array', + 'array' => $criticalities, + 'value' => '|arg1:monitor_criticality|', + 'default' => '0', + ]; + + $fields_host_edit3['monitor_warn'] = [ + 'friendly_name' => __('Ping Warning Threshold', 'monitor'), + 'description' => __('If the round-trip latency via any of the predefined Cacti ping methods raises above this threshold, log a warning or send email based upon the Devices Criticality and Monitor setting. The unit is in milliseconds. Setting to 0 disables. The Thold Plugin is required to leverage this functionality.', 'monitor'), + 'method' => 'textbox', + 'size' => '10', + 'max_length' => '5', + 'placeholder' => __('milliseconds', 'monitor'), + 'value' => '|arg1:monitor_warn|', + 'default' => '', + ]; + + $fields_host_edit3['monitor_alert'] = [ + 'friendly_name' => __('Ping Alert Threshold', 'monitor'), + 'description' => __('If the round-trip latency via any of the predefined Cacti ping methods raises above this threshold, log an alert or send an email based upon the Devices Criticality and Monitor setting. The unit is in milliseconds. Setting to 0 disables. The Thold Plugin is required to leverage this functionality.', 'monitor'), + 'method' => 'textbox', + 'size' => '10', + 'max_length' => '5', + 'placeholder' => __('milliseconds', 'monitor'), + 'value' => '|arg1:monitor_alert|', + 'default' => '', + ]; + + $fields_host_edit3['monitor_warn_baseline'] = [ + 'friendly_name' => __('Re-Baseline Warning', 'monitor'), + 'description' => __('The percentage above the current average ping time to consider a Warning Threshold. If updated, this will automatically adjust the Ping Warning Threshold.', 'monitor'), + 'method' => 'drop_array', + 'default' => '0', + 'value' => '0', + 'array' => $baselines + ]; + + $fields_host_edit3['monitor_alert_baseline'] = [ + 'friendly_name' => __('Re-Baseline Alert', 'monitor'), + 'description' => __('The percentage above the current average ping time to consider a Alert Threshold. If updated, this will automatically adjust the Ping Alert Threshold.', 'monitor'), + 'method' => 'drop_array', + 'default' => '0', + 'value' => '0', + 'array' => $baselines + ]; + + $fields_host_edit3['monitor_text'] = [ + 'friendly_name' => __('Down Device Message', 'monitor'), + 'description' => __('This is the message that will be displayed when this Device is reported as down.', 'monitor'), + 'method' => 'textarea', + 'max_length' => 1000, + 'textarea_rows' => 2, + 'textarea_cols' => 80, + 'value' => '|arg1:monitor_text|', + 'default' => '', + ]; + + if (function_exists('form_dropicon')) { + $method = 'drop_icon'; + } else { + $method = 'drop_array'; + } + + $fields_host_edit3['monitor_icon'] = [ + 'friendly_name' => __('Device icon', 'monitor'), + 'description' => __('You can select device icon.', 'monitor'), + 'method' => $method, + 'default' => '0', + 'value' => '|arg1:monitor_icon|', + 'array' => $fa_icons, + ]; + } + } + + $fields_host_edit = $fields_host_edit3; } -/** - * Resolve default monitor enabled state for new devices. - * - * @param int|string $host_id Host identifier. - * - * @return string - */ -function monitorGetDefault(int|string $host_id): string -{ - $monitor_new_device = ''; - - if ($host_id <= 0) { - $monitor_new_device = (string) read_config_option('monitor_new_enabled'); - } - - return $monitor_new_device; +function monitor_get_default($host_id) { + $monitor_new_device = ''; + + if ($host_id <= 0) { + $monitor_new_device = read_config_option('monitor_new_enabled'); + } + + return $monitor_new_device; } -/** - * Validate and map monitor-specific host fields during device save. - * - * @param array $save Device save payload. - * - * @return array - */ -function monitorApiDeviceSave(array $save): array -{ - global $fa_icons; - - $monitor_default = monitorGetDefault($save['id']); - - if (isset_request_var('monitor')) { - $save['monitor'] = form_input_validate(get_nfilter_request_var('monitor'), 'monitor', $monitor_default, true, 3); - } else { - $save['monitor'] = form_input_validate($monitor_default, 'monitor', '', true, 3); - } - - if (isset_request_var('monitor_text')) { - $save['monitor_text'] = form_input_validate(get_nfilter_request_var('monitor_text'), 'monitor_text', '', true, 3); - } else { - $save['monitor_text'] = form_input_validate('', 'monitor_text', '', true, 3); - } - - if (isset_request_var('monitor_criticality')) { - $save['monitor_criticality'] = form_input_validate(get_nfilter_request_var('monitor_criticality'), 'monitor_criticality', '^[0-9]+$', true, 3); - } else { - $save['monitor_criticality'] = form_input_validate('', 'monitor_criticality', '', true, 3); - } - - if (isset_request_var('monitor_warn')) { - $save['monitor_warn'] = form_input_validate(get_nfilter_request_var('monitor_warn'), 'monitor_warn', '^[0-9]+$', true, 3); - } else { - $save['monitor_warn'] = form_input_validate('', 'monitor_warn', '', true, 3); - } - - if (isset_request_var('monitor_alert')) { - $save['monitor_alert'] = form_input_validate(get_nfilter_request_var('monitor_alert'), 'monitor_alert', '^[0-9]+$', true, 3); - } else { - $save['monitor_alert'] = form_input_validate('', 'monitor_alert', '', true, 3); - } - - if (isset_request_var('monitor_icon') && array_key_exists(get_nfilter_request_var('monitor_icon'), $fa_icons)) { - $save['monitor_icon'] = get_nfilter_request_var('monitor_icon'); - } else { - $save['monitor_icon'] = ''; - } - - if (!isempty_request_var('monitor_alert_baseline') && !empty($save['id'])) { - $cur_time = db_fetch_cell_prepared( - 'SELECT cur_time +function monitor_api_device_save($save) { + global $fa_icons; + + $monitor_default = monitor_get_default($save['id']); + + if (isset_request_var('monitor')) { + $save['monitor'] = form_input_validate(get_nfilter_request_var('monitor'), 'monitor', $monitor_default, true, 3); + } else { + $save['monitor'] = form_input_validate($monitor_default, 'monitor', '', true, 3); + } + + if (isset_request_var('monitor_text')) { + $save['monitor_text'] = form_input_validate(get_nfilter_request_var('monitor_text'), 'monitor_text', '', true, 3); + } else { + $save['monitor_text'] = form_input_validate('', 'monitor_text', '', true, 3); + } + + if (isset_request_var('monitor_criticality')) { + $save['monitor_criticality'] = form_input_validate(get_nfilter_request_var('monitor_criticality'), 'monitor_criticality', '^[0-9]+$', true, 3); + } else { + $save['monitor_criticality'] = form_input_validate('', 'monitor_criticality', '', true, 3); + } + + if (isset_request_var('monitor_warn')) { + $save['monitor_warn'] = form_input_validate(get_nfilter_request_var('monitor_warn'), 'monitor_warn', '^[0-9]+$', true, 3); + } else { + $save['monitor_warn'] = form_input_validate('', 'monitor_warn', '', true, 3); + } + + if (isset_request_var('monitor_alert')) { + $save['monitor_alert'] = form_input_validate(get_nfilter_request_var('monitor_alert'), 'monitor_alert', '^[0-9]+$', true, 3); + } else { + $save['monitor_alert'] = form_input_validate('', 'monitor_alert', '', true, 3); + } + + if (isset_request_var('monitor_icon') && array_key_exists(get_nfilter_request_var('monitor_icon'), $fa_icons)) { + $save['monitor_icon'] = get_nfilter_request_var('monitor_icon'); + } else { + $save['monitor_icon'] = ''; + } + + if (!isempty_request_var('monitor_alert_baseline') && !empty($save['id'])) { + $cur_time = db_fetch_cell_prepared('SELECT cur_time FROM host WHERE id = ?', - [$save['id']] - ); + [$save['id']]); - if ($cur_time > 0) { - $save['monitor_alert'] = ceil($cur_time * get_nfilter_request_var('monitor_alert_baseline')); - } - } + if ($cur_time > 0) { + $save['monitor_alert'] = ceil($cur_time * get_nfilter_request_var('monitor_alert_baseline')); + } + } - if (!isempty_request_var('monitor_warn_baseline') && !empty($save['id'])) { - $cur_time = db_fetch_cell_prepared( - 'SELECT cur_time + if (!isempty_request_var('monitor_warn_baseline') && !empty($save['id'])) { + $cur_time = db_fetch_cell_prepared('SELECT cur_time FROM host WHERE id = ?', - [$save['id']] - ); + [$save['id']]); - if ($cur_time > 0) { - $save['monitor_warn'] = ceil($cur_time * get_nfilter_request_var('monitor_alert_baseline')); - } - } + if ($cur_time > 0) { + $save['monitor_warn'] = ceil($cur_time * get_nfilter_request_var('monitor_alert_baseline')); + } + } - return $save; + return $save; } -/** - * Add monitor page breadcrumb/nav metadata. - * - * @param array $nav Existing navigation mapping. - * - * @return array - */ -function monitorDrawNavigationText(array $nav): array -{ - $nav['monitor.php:'] = ['title' => __('Monitoring', 'monitor'), 'mapping' => '', 'url' => 'monitor.php', 'level' => '0']; - - return $nav; +function monitor_draw_navigation_text($nav) { + $nav['monitor.php:'] = ['title' => __('Monitoring', 'monitor'), 'mapping' => '', 'url' => 'monitor.php', 'level' => '0']; + + return $nav; } -/** - * Create/upgrade monitor plugin tables and host columns. - * - * @return void - */ -function monitorSetupTable(): void -{ - if (!db_table_exists('plugin_monitor_notify_history')) { - db_execute("CREATE TABLE IF NOT EXISTS plugin_monitor_notify_history ( +function monitor_setup_table() { + if (!db_table_exists('plugin_monitor_notify_history')) { + db_execute("CREATE TABLE IF NOT EXISTS plugin_monitor_notify_history ( id int(10) unsigned NOT NULL AUTO_INCREMENT, host_id int(10) unsigned DEFAULT NULL, notify_type tinyint(3) unsigned DEFAULT NULL, @@ -1251,10 +1053,10 @@ function monitorSetupTable(): void UNIQUE KEY unique_key (host_id,notify_type,notification_time)) ENGINE=InnoDB COMMENT='Stores Notification Event History'"); - } + } - if (!db_table_exists('plugin_monitor_reboot_history')) { - db_execute("CREATE TABLE IF NOT EXISTS plugin_monitor_reboot_history ( + if (!db_table_exists('plugin_monitor_reboot_history')) { + db_execute("CREATE TABLE IF NOT EXISTS plugin_monitor_reboot_history ( id int(10) unsigned NOT NULL AUTO_INCREMENT, host_id int(10) unsigned DEFAULT NULL, reboot_time timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', @@ -1265,20 +1067,20 @@ function monitorSetupTable(): void KEY reboot_time (reboot_time)) ENGINE=InnoDB COMMENT='Keeps Track of Device Reboot Times'"); - } + } - if (!db_table_exists('plugin_monitor_uptime')) { - db_execute("CREATE TABLE IF NOT EXISTS plugin_monitor_uptime ( + if (!db_table_exists('plugin_monitor_uptime')) { + db_execute("CREATE TABLE IF NOT EXISTS plugin_monitor_uptime ( host_id int(10) unsigned DEFAULT '0', uptime bigint(20) unsigned DEFAULT '0', PRIMARY KEY (host_id), KEY uptime (uptime)) ENGINE=InnoDB COMMENT='Keeps Track of the Devices last uptime to track agent restarts and reboots'"); - } + } - if (!db_table_exists('plugin_monitor_dashboards')) { - db_execute("CREATE TABLE IF NOT EXISTS plugin_monitor_dashboards ( + if (!db_table_exists('plugin_monitor_dashboards')) { + db_execute("CREATE TABLE IF NOT EXISTS plugin_monitor_dashboards ( id int(10) unsigned auto_increment, user_id int(10) unsigned DEFAULT '0', name varchar(128) DEFAULT '', @@ -1287,47 +1089,41 @@ function monitorSetupTable(): void KEY user_id (user_id)) ENGINE=InnoDB COMMENT='Stores predefined dashboard information for a user or users'"); - } - - if (db_table_exists('host')) { - $row_format = db_fetch_cell("SELECT ROW_FORMAT - FROM information_schema.tables - WHERE TABLE_SCHEMA = DATABASE() - AND TABLE_NAME = 'host'"); - - if (strtoupper((string) $row_format) !== 'DYNAMIC') { - db_execute('ALTER TABLE host ROW_FORMAT=DYNAMIC'); - } - } - - api_plugin_db_add_column('monitor', 'host', ['name' => 'monitor', 'type' => 'char(3)', 'NULL' => true, 'default' => 'on']); - api_plugin_db_add_column('monitor', 'host', ['name' => 'monitor_text', 'type' => 'text', 'NULL' => false]); - api_plugin_db_add_column('monitor', 'host', ['name' => 'monitor_criticality', 'type' => 'tinyint', 'unsigned' => true, 'NULL' => false, 'default' => '0']); - api_plugin_db_add_column('monitor', 'host', ['name' => 'monitor_warn', 'type' => 'double', 'NULL' => false, 'default' => '0']); - api_plugin_db_add_column('monitor', 'host', ['name' => 'monitor_alert', 'type' => 'double', 'NULL' => false, 'default' => '0']); - api_plugin_db_add_column('monitor', 'host', ['name' => 'monitor_icon', 'type' => 'varchar(30)', 'NULL' => false, 'default' => '']); + } + + if (db_table_exists('host')) { + $row_format = db_fetch_cell("SELECT ROW_FORMAT + FROM information_schema.tables + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = 'host'"); + + if (strtoupper((string) $row_format) !== 'DYNAMIC') { + db_execute('ALTER TABLE host ROW_FORMAT=DYNAMIC'); + } + } + + api_plugin_db_add_column('monitor', 'host', ['name' => 'monitor', 'type' => 'char(3)', 'NULL' => true, 'default' => 'on']); + api_plugin_db_add_column('monitor', 'host', ['name' => 'monitor_text', 'type' => 'text', 'NULL' => false]); + api_plugin_db_add_column('monitor', 'host', ['name' => 'monitor_criticality', 'type' => 'tinyint', 'unsigned' => true, 'NULL' => false, 'default' => '0']); + api_plugin_db_add_column('monitor', 'host', ['name' => 'monitor_warn', 'type' => 'double', 'NULL' => false, 'default' => '0']); + api_plugin_db_add_column('monitor', 'host', ['name' => 'monitor_alert', 'type' => 'double', 'NULL' => false, 'default' => '0']); + api_plugin_db_add_column('monitor', 'host', ['name' => 'monitor_icon', 'type' => 'varchar(30)', 'NULL' => false, 'default' => '']); } -/** - * Trigger monitor poller script from primary poller process. - * - * @return void - */ -function monitorPollerBottom(): void -{ - global $config; +function monitor_poller_bottom() { + global $config; - if ($config['poller_id'] == 1) { - include_once($config['library_path'] . '/poller.php'); + if ($config['poller_id'] == 1) { + include_once($config['library_path'] . '/poller.php'); - $command_string = trim(read_config_option('path_php_binary')); + $command_string = trim(read_config_option('path_php_binary')); - if (trim($command_string) == '') { - $command_string = 'php'; - } + if (trim($command_string) == '') { + $command_string = 'php'; + } - $extra_args = ' -q ' . $config['base_path'] . '/plugins/monitor/poller_monitor.php'; + $extra_args = ' -q ' . $config['base_path'] . '/plugins/monitor/poller_monitor.php'; - exec_background($command_string, $extra_args); - } + exec_background($command_string, $extra_args); + } } From b78621a1663b752214e7ca42fb9d17ccd9d11134 Mon Sep 17 00:00:00 2001 From: Sean Mancini Date: Tue, 3 Mar 2026 11:40:57 -0500 Subject: [PATCH 20/26] . --- db_functions.php | 11 +++++------ monitor.php | 3 --- setup.php | 4 ++++ 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/db_functions.php b/db_functions.php index 8443bbc..2477a3d 100644 --- a/db_functions.php +++ b/db_functions.php @@ -66,7 +66,6 @@ function checkTholds(): array return $thold_hosts; } - /** * Append an IN-clause fragment to an existing SQL where string. * @@ -156,7 +155,7 @@ function renderWhereJoin(string &$sql_where, string &$sql_join): void AND h.deleted = "" AND (h.availability_method > 0 OR h.snmp_version > 0 - OR (h.cur_time >= h.monitor_warn AND monitor_warn > 0) + OR (h.cur_time >= h.monitor_warn AND h.monitor_warn > 0) OR (h.cur_time >= h.monitor_alert AND h.monitor_alert > 0) )' . $awhere; } elseif (get_request_var('status') == '1' || get_request_var('status') == 2) { @@ -169,8 +168,8 @@ function renderWhereJoin(string &$sql_where, string &$sql_join): void OR ' . getTholdWhere() . ' OR ((h.availability_method > 0 OR h.snmp_version > 0) AND ((h.cur_time > h.monitor_warn AND h.monitor_warn > 0) - OR (h.cur_time > h.monitor_alert AND h.monitor_alert > 0)) - ))' . $awhere; + OR (h.cur_time > h.monitor_alert AND h.monitor_alert > 0))) + )' . $awhere; } elseif (get_request_var('status') == -1) { $sql_join = 'LEFT JOIN thold_data AS td ON td.host_id=h.id'; @@ -191,7 +190,7 @@ function renderWhereJoin(string &$sql_where, string &$sql_join): void $sql_where = 'WHERE h.disabled = "" AND h.monitor = "" - AND h.deleted = "")' . $awhere; + AND h.deleted = ""' . $awhere; } else { $sql_join = 'LEFT JOIN thold_data AS td ON td.host_id=h.id'; @@ -264,7 +263,7 @@ function getHostsDownOrTriggeredByPermission(bool $prescan): array ); } - $sql_where = "h.monitor = 'on' + $sql_where = "h.monitor = 'on' AND h.disabled = '' AND h.deleted = '' AND ((h.status < " . $PreScanValue . ' AND (h.availability_method > 0 OR h.snmp_version > 0)) ' . diff --git a/monitor.php b/monitor.php index 51658e0..76fb245 100644 --- a/monitor.php +++ b/monitor.php @@ -135,9 +135,6 @@ validateRequestVars(); -if (!db_column_exists('host', 'monitor_icon')) { - monitorSetupTable(); -} $thold_hosts = checkTholds(); diff --git a/setup.php b/setup.php index 043d0f7..283d533 100644 --- a/setup.php +++ b/setup.php @@ -1102,12 +1102,16 @@ function monitor_setup_table() { } } + db_execute('SET SESSION innodb_strict_mode=0'); + api_plugin_db_add_column('monitor', 'host', ['name' => 'monitor', 'type' => 'char(3)', 'NULL' => true, 'default' => 'on']); api_plugin_db_add_column('monitor', 'host', ['name' => 'monitor_text', 'type' => 'text', 'NULL' => false]); api_plugin_db_add_column('monitor', 'host', ['name' => 'monitor_criticality', 'type' => 'tinyint', 'unsigned' => true, 'NULL' => false, 'default' => '0']); api_plugin_db_add_column('monitor', 'host', ['name' => 'monitor_warn', 'type' => 'double', 'NULL' => false, 'default' => '0']); api_plugin_db_add_column('monitor', 'host', ['name' => 'monitor_alert', 'type' => 'double', 'NULL' => false, 'default' => '0']); api_plugin_db_add_column('monitor', 'host', ['name' => 'monitor_icon', 'type' => 'varchar(30)', 'NULL' => false, 'default' => '']); + + db_execute('SET SESSION innodb_strict_mode=1'); } function monitor_poller_bottom() { From 702c3513ef422d276861b1c515465cd2640c9998 Mon Sep 17 00:00:00 2001 From: Sean Mancini Date: Tue, 3 Mar 2026 11:42:59 -0500 Subject: [PATCH 21/26] Update monitor_controller.php --- monitor_controller.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/monitor_controller.php b/monitor_controller.php index e51b6ca..96dc152 100644 --- a/monitor_controller.php +++ b/monitor_controller.php @@ -189,7 +189,7 @@ function findDownHosts(): void set_request_var('downhosts', 'true'); if (isset($_SESSION['monitor_muted_hosts'])) { - unmute_up_non_triggered_hosts($dhosts); + unmuteUpNonTriggeredHosts($dhosts); $unmuted_hosts = array_diff($dhosts, $_SESSION['monitor_muted_hosts']); From f764763e956a617abee75a8f4a42018abd0fb749 Mon Sep 17 00:00:00 2001 From: Sean Mancini Date: Tue, 3 Mar 2026 11:45:02 -0500 Subject: [PATCH 22/26] Update monitor_controller.php --- monitor_controller.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/monitor_controller.php b/monitor_controller.php index 96dc152..0f2bc03 100644 --- a/monitor_controller.php +++ b/monitor_controller.php @@ -194,7 +194,7 @@ function findDownHosts(): void $unmuted_hosts = array_diff($dhosts, $_SESSION['monitor_muted_hosts']); if (cacti_sizeof($unmuted_hosts)) { - unmute_user(); + unmuteUser(); } } else { set_request_var('mute', 'false'); From 258942e43dc4c35d48bfba20d5df93a25a318d1c Mon Sep 17 00:00:00 2001 From: Sean Mancini Date: Tue, 3 Mar 2026 11:49:47 -0500 Subject: [PATCH 23/26] Update monitor_render.php --- monitor_render.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/monitor_render.php b/monitor_render.php index 5c4bfcd..761460f 100644 --- a/monitor_render.php +++ b/monitor_render.php @@ -628,6 +628,8 @@ function renderTree(): string $tree_ids[$tree['id']] = $tree['id']; } + $sql_where = ''; + $sql_join = ''; renderWhereJoin($sql_where, $sql_join); $branchWhost = db_fetch_assoc("SELECT DISTINCT gti.graph_tree_id, gti.parent From 43640c8960a419e14f4c929ff4937709bacbf2cc Mon Sep 17 00:00:00 2001 From: Sean Mancini Date: Tue, 3 Mar 2026 16:56:01 -0500 Subject: [PATCH 24/26] fix typing errors --- monitor_controller.php | 2 +- poller_functions.php | 4 ++-- sonar-project.properties | 10 ++++++++++ 3 files changed, 13 insertions(+), 3 deletions(-) create mode 100644 sonar-project.properties diff --git a/monitor_controller.php b/monitor_controller.php index 0f2bc03..84a341e 100644 --- a/monitor_controller.php +++ b/monitor_controller.php @@ -1172,7 +1172,7 @@ function monitorRenderAjaxStatusTooltip(array $host, string $size, string $links
- + ' . ($host['snmp_version'] > 0 && ($host['status'] == 3 || $host['status'] == 2) ? ' diff --git a/poller_functions.php b/poller_functions.php index 821412d..b5e1929 100644 --- a/poller_functions.php +++ b/poller_functions.php @@ -53,9 +53,9 @@ function monitorAddEmails(array &$reboot_emails, array $alert_emails, int|string * * @return void */ -function monitorAddNotificationList(array &$reboot_emails, int|string $notify_list, int|string $host_id, array $notification_lists): void +function monitorAddNotificationList(array &$reboot_emails, int|string|null $notify_list, int|string $host_id, array $notification_lists): void { - if ($notify_list > 0 && isset($notification_lists[$notify_list])) { + if ($notify_list !== null && $notify_list > 0 && isset($notification_lists[$notify_list])) { $emails = explode(',', $notification_lists[$notify_list]); monitorAddEmails($reboot_emails, $emails, $host_id); } diff --git a/sonar-project.properties b/sonar-project.properties new file mode 100644 index 0000000..5ed8db9 --- /dev/null +++ b/sonar-project.properties @@ -0,0 +1,10 @@ +sonar.projectKey=plugin_monitor +sonar.sources=. +sonar.exclusions=vendor/** + +# php:S4833 - "Use namespaces instead of include/require" +# This is a Cacti plugin with a required procedural architecture. +# Namespaces cannot be used; include_once is the correct and only mechanism. +sonar.issue.ignore.multicriteria=e1 +sonar.issue.ignore.multicriteria.e1.ruleKey=php:S4833 +sonar.issue.ignore.multicriteria.e1.resourceKey=**/*.php From 365b49b4ce28f33f705790bfd92744cdb60a8e56 Mon Sep 17 00:00:00 2001 From: Sean Mancini Date: Tue, 3 Mar 2026 17:04:29 -0500 Subject: [PATCH 25/26] apply php cs-fixer updates --- db_functions.php | 284 ++++---- monitor.php | 188 +++-- monitor_controller.php | 1567 ++++++++++++++++++++-------------------- monitor_render.php | 1472 ++++++++++++++++++------------------- poller_functions.php | 1156 ++++++++++++++--------------- poller_monitor.php | 130 ++-- 6 files changed, 2346 insertions(+), 2451 deletions(-) diff --git a/db_functions.php b/db_functions.php index 2477a3d..dac37e2 100644 --- a/db_functions.php +++ b/db_functions.php @@ -1,6 +1,6 @@ 0))"; - } else { // triggered - return "(td.thold_enabled='on' + } else { // triggered + return "(td.thold_enabled='on' AND ((td.thold_alert != 0 AND td.thold_fail_count >= td.thold_fail_trigger) OR (td.bl_alert > 0 AND td.bl_fail_count >= td.bl_fail_trigger)))"; - } + } } /** @@ -47,23 +46,22 @@ function getTholdWhere(): string * * @return array */ -function checkTholds(): array -{ - $thold_hosts = []; +function checkTholds(): array { + $thold_hosts = []; - if (api_plugin_is_enabled('thold')) { - return array_rekey( - db_fetch_assoc('SELECT DISTINCT dl.host_id + if (api_plugin_is_enabled('thold')) { + return array_rekey( + db_fetch_assoc('SELECT DISTINCT dl.host_id FROM thold_data AS td INNER JOIN data_local AS dl ON td.local_data_id=dl.id WHERE ' . getTholdWhere()), - 'host_id', - 'host_id' - ); - } + 'host_id', + 'host_id' + ); + } - return $thold_hosts; + return $thold_hosts; } /** @@ -77,16 +75,15 @@ function checkTholds(): array * * @return void */ -function renderGroupConcat(string &$sql_where, string $sql_join, string $sql_field, string $sql_data, string $sql_suffix = ''): void -{ - // Remove empty entries if something was returned - if (!empty($sql_data)) { - $sql_data = trim(str_replace(',,', ',', $sql_data), ','); - - if (!empty($sql_data)) { - $sql_where .= ($sql_where != '' ? $sql_join : '') . "($sql_field IN($sql_data) $sql_suffix)"; - } - } +function renderGroupConcat(string &$sql_where, string $sql_join, string $sql_field, string $sql_data, string $sql_suffix = ''): void { + // Remove empty entries if something was returned + if (!empty($sql_data)) { + $sql_data = trim(str_replace(',,', ',', $sql_data), ','); + + if (!empty($sql_data)) { + $sql_where .= ($sql_where != '' ? $sql_join : '') . "($sql_field IN($sql_data) $sql_suffix)"; + } + } } /** @@ -97,59 +94,58 @@ function renderGroupConcat(string &$sql_where, string $sql_join, string $sql_fie * * @return void */ -function renderWhereJoin(string &$sql_where, string &$sql_join): void -{ - if (get_request_var('crit') > 0) { - $awhere = 'h.monitor_criticality >= ' . get_request_var('crit'); - } else { - $awhere = ''; - } - - if (get_request_var('grouping') == 'site') { - if (get_request_var('site') > 0) { - $awhere .= ($awhere == '' ? '' : ' AND ') . 'h.site_id = ' . get_request_var('site'); - } elseif (get_request_var('site') == -2) { - $awhere .= ($awhere == '' ? '' : ' AND ') . ' h.site_id = 0'; - } - } - - if (get_request_var('rfilter') != '') { - $awhere .= ($awhere == '' ? '' : ' AND ') . " h.description RLIKE '" . get_request_var('rfilter') . "'"; - } - - if (get_request_var('grouping') == 'tree') { - if (get_request_var('tree') > 0) { - $hlist = db_fetch_cell_prepared( - 'SELECT GROUP_CONCAT(DISTINCT host_id) +function renderWhereJoin(string &$sql_where, string &$sql_join): void { + if (get_request_var('crit') > 0) { + $awhere = 'h.monitor_criticality >= ' . get_request_var('crit'); + } else { + $awhere = ''; + } + + if (get_request_var('grouping') == 'site') { + if (get_request_var('site') > 0) { + $awhere .= ($awhere == '' ? '' : ' AND ') . 'h.site_id = ' . get_request_var('site'); + } elseif (get_request_var('site') == -2) { + $awhere .= ($awhere == '' ? '' : ' AND ') . ' h.site_id = 0'; + } + } + + if (get_request_var('rfilter') != '') { + $awhere .= ($awhere == '' ? '' : ' AND ') . " h.description RLIKE '" . get_request_var('rfilter') . "'"; + } + + if (get_request_var('grouping') == 'tree') { + if (get_request_var('tree') > 0) { + $hlist = db_fetch_cell_prepared( + 'SELECT GROUP_CONCAT(DISTINCT host_id) FROM graph_tree_items AS gti INNER JOIN host AS h ON h.id = gti.host_id WHERE host_id > 0 AND graph_tree_id = ? AND h.deleted = ""', - [get_request_var('tree')] - ); + [get_request_var('tree')] + ); - renderGroupConcat($awhere, ' AND ', 'h.id', $hlist); - } elseif (get_request_var('tree') == -2) { - $hlist = db_fetch_cell('SELECT GROUP_CONCAT(DISTINCT h.id) + renderGroupConcat($awhere, ' AND ', 'h.id', $hlist); + } elseif (get_request_var('tree') == -2) { + $hlist = db_fetch_cell('SELECT GROUP_CONCAT(DISTINCT h.id) FROM host AS h LEFT JOIN (SELECT DISTINCT host_id FROM graph_tree_items WHERE host_id > 0) AS gti ON h.id = gti.host_id WHERE gti.host_id IS NULL AND h.deleted = ""'); - renderGroupConcat($awhere, ' AND ', 'h.id', $hlist); - } - } + renderGroupConcat($awhere, ' AND ', 'h.id', $hlist); + } + } - if (!empty($awhere)) { - $awhere = ' AND ' . $awhere; - } + if (!empty($awhere)) { + $awhere = ' AND ' . $awhere; + } - if (get_request_var('status') == '0') { - $sql_join = ''; - $sql_where = 'WHERE h.disabled = "" + if (get_request_var('status') == '0') { + $sql_join = ''; + $sql_where = 'WHERE h.disabled = "" AND h.monitor = "on" AND h.status < 3 AND h.deleted = "" @@ -158,10 +154,10 @@ function renderWhereJoin(string &$sql_where, string &$sql_join): void OR (h.cur_time >= h.monitor_warn AND h.monitor_warn > 0) OR (h.cur_time >= h.monitor_alert AND h.monitor_alert > 0) )' . $awhere; - } elseif (get_request_var('status') == '1' || get_request_var('status') == 2) { - $sql_join = 'LEFT JOIN thold_data AS td ON td.host_id=h.id'; + } elseif (get_request_var('status') == '1' || get_request_var('status') == 2) { + $sql_join = 'LEFT JOIN thold_data AS td ON td.host_id=h.id'; - $sql_where = 'WHERE h.disabled = "" + $sql_where = 'WHERE h.disabled = "" AND h.monitor = "on" AND h.deleted = "" AND (h.status < 3 @@ -170,34 +166,34 @@ function renderWhereJoin(string &$sql_where, string &$sql_join): void AND ((h.cur_time > h.monitor_warn AND h.monitor_warn > 0) OR (h.cur_time > h.monitor_alert AND h.monitor_alert > 0))) )' . $awhere; - } elseif (get_request_var('status') == -1) { - $sql_join = 'LEFT JOIN thold_data AS td ON td.host_id=h.id'; + } elseif (get_request_var('status') == -1) { + $sql_join = 'LEFT JOIN thold_data AS td ON td.host_id=h.id'; - $sql_where = 'WHERE h.disabled = "" + $sql_where = 'WHERE h.disabled = "" AND h.monitor = "on" AND h.deleted = "" AND (h.availability_method > 0 OR h.snmp_version > 0 OR ((td.thold_enabled="on" AND td.thold_alert > 0) OR td.id IS NULL) )' . $awhere; - } elseif (get_request_var('status') == -2) { - $sql_join = 'LEFT JOIN thold_data AS td ON td.host_id=h.id'; + } elseif (get_request_var('status') == -2) { + $sql_join = 'LEFT JOIN thold_data AS td ON td.host_id=h.id'; - $sql_where = 'WHERE h.disabled = "" + $sql_where = 'WHERE h.disabled = "" AND h.deleted = ""' . $awhere; - } elseif (get_request_var('status') == -3) { - $sql_join = 'LEFT JOIN thold_data AS td ON td.host_id=h.id'; + } elseif (get_request_var('status') == -3) { + $sql_join = 'LEFT JOIN thold_data AS td ON td.host_id=h.id'; - $sql_where = 'WHERE h.disabled = "" + $sql_where = 'WHERE h.disabled = "" AND h.monitor = "" AND h.deleted = ""' . $awhere; - } else { - $sql_join = 'LEFT JOIN thold_data AS td ON td.host_id=h.id'; + } else { + $sql_join = 'LEFT JOIN thold_data AS td ON td.host_id=h.id'; - $sql_where = 'WHERE (h.disabled = "" + $sql_where = 'WHERE (h.disabled = "" AND h.deleted = "" AND td.id IS NULL)' . $awhere; - } + } } /** @@ -207,79 +203,78 @@ function renderWhereJoin(string &$sql_where, string &$sql_join): void * * @return array */ -function getHostsDownOrTriggeredByPermission(bool $prescan): array -{ - global $render_style; - $PreScanValue = 2; - - if ($prescan) { - $PreScanValue = 3; - } - - $result = []; - - if (get_request_var('crit') > 0) { - $sql_add_where = 'monitor_criticality >= ' . get_request_var('crit'); - } else { - $sql_add_where = ''; - } - - if (get_request_var('grouping') == 'tree') { - if (get_request_var('tree') > 0) { - $devices = db_fetch_cell_prepared( - 'SELECT GROUP_CONCAT(DISTINCT host_id) AS hosts +function getHostsDownOrTriggeredByPermission(bool $prescan): array { + global $render_style; + $PreScanValue = 2; + + if ($prescan) { + $PreScanValue = 3; + } + + $result = []; + + if (get_request_var('crit') > 0) { + $sql_add_where = 'monitor_criticality >= ' . get_request_var('crit'); + } else { + $sql_add_where = ''; + } + + if (get_request_var('grouping') == 'tree') { + if (get_request_var('tree') > 0) { + $devices = db_fetch_cell_prepared( + 'SELECT GROUP_CONCAT(DISTINCT host_id) AS hosts FROM graph_tree_items AS gti INNER JOIN host AS h WHERE host_id > 0 AND h.deleted = "" AND graph_tree_id = ?', - [get_request_var('tree')] - ); + [get_request_var('tree')] + ); - renderGroupConcat($sql_add_where, ' OR ', 'h.id', $devices, 'AND h.status < 2'); - } - } + renderGroupConcat($sql_add_where, ' OR ', 'h.id', $devices, 'AND h.status < 2'); + } + } - if (get_request_var('status') > 0) { - $triggered = db_fetch_cell('SELECT GROUP_CONCAT(DISTINCT host_id) AS hosts + if (get_request_var('status') > 0) { + $triggered = db_fetch_cell('SELECT GROUP_CONCAT(DISTINCT host_id) AS hosts FROM host AS h INNER JOIN thold_data AS td ON td.host_id = h.id WHERE ' . getTholdWhere() . ' AND h.deleted = ""'); - renderGroupConcat($sql_add_where, ' OR ', 'h.id', $triggered, 'AND h.status > 1'); + renderGroupConcat($sql_add_where, ' OR ', 'h.id', $triggered, 'AND h.status > 1'); - $_SESSION['monitor_triggered'] = array_rekey( - db_fetch_assoc('SELECT td.host_id, COUNT(DISTINCT td.id) AS triggered + $_SESSION['monitor_triggered'] = array_rekey( + db_fetch_assoc('SELECT td.host_id, COUNT(DISTINCT td.id) AS triggered FROM thold_data AS td INNER JOIN host AS h ON td.host_id = h.id WHERE ' . getTholdWhere() . ' AND h.deleted = "" GROUP BY td.host_id'), - 'host_id', - 'triggered' - ); - } + 'host_id', + 'triggered' + ); + } - $sql_where = "h.monitor = 'on' + $sql_where = "h.monitor = 'on' AND h.disabled = '' AND h.deleted = '' AND ((h.status < " . $PreScanValue . ' AND (h.availability_method > 0 OR h.snmp_version > 0)) ' . - ($sql_add_where != '' ? ' OR (' . $sql_add_where . '))' : ')'); + ($sql_add_where != '' ? ' OR (' . $sql_add_where . '))' : ')'); - // do a quick loop through to pull the hosts that are down - $hosts = get_allowed_devices($sql_where); + // do a quick loop through to pull the hosts that are down + $hosts = get_allowed_devices($sql_where); - if (cacti_sizeof($hosts)) { - foreach ($hosts as $host) { - $result[] = $host['id']; - sort($result); - } - } + if (cacti_sizeof($hosts)) { + foreach ($hosts as $host) { + $result[] = $host['id']; + sort($result); + } + } - return $result; + return $result; } /** @@ -287,16 +282,15 @@ function getHostsDownOrTriggeredByPermission(bool $prescan): array * * @return array */ -function getHostNonTreeArray(): array -{ - $leafs = []; +function getHostNonTreeArray(): array { + $leafs = []; - $sql_where = ''; - $sql_join = ''; + $sql_where = ''; + $sql_join = ''; - renderWhereJoin($sql_where, $sql_join); + renderWhereJoin($sql_where, $sql_join); - $hierarchy = db_fetch_assoc("SELECT DISTINCT + $hierarchy = db_fetch_assoc("SELECT DISTINCT h.*, gti.title, gti.host_id, gti.host_grouping_type, gti.graph_tree_id FROM host AS h LEFT JOIN graph_tree_items AS gti @@ -306,15 +300,15 @@ function getHostNonTreeArray(): array AND gti.graph_tree_id IS NULL ORDER BY h.description"); - if (cacti_sizeof($hierarchy) > 0) { - $leafs = []; - $branchleafs = 0; + if (cacti_sizeof($hierarchy) > 0) { + $leafs = []; + $branchleafs = 0; - foreach ($hierarchy as $leaf) { - $leafs[$branchleafs] = $leaf; - $branchleafs++; - } - } + foreach ($hierarchy as $leaf) { + $leafs[$branchleafs] = $leaf; + $branchleafs++; + } + } - return $leafs; + return $leafs; } diff --git a/monitor.php b/monitor.php index 76fb245..9445f2b 100644 --- a/monitor.php +++ b/monitor.php @@ -1,6 +1,6 @@ __('Disabled', 'monitor'), - 1 => __('Low', 'monitor'), - 2 => __('Medium', 'monitor'), - 3 => __('High', 'monitor'), - 4 => __('Mission Critical', 'monitor') + 0 => __('Disabled', 'monitor'), + 1 => __('Low', 'monitor'), + 2 => __('Medium', 'monitor'), + 3 => __('High', 'monitor'), + 4 => __('Mission Critical', 'monitor') ]; $iclasses = [ - 0 => 'deviceUnknown', - 1 => 'deviceDown', - 2 => 'deviceRecovering', - 3 => 'deviceUp', - 4 => 'deviceThreshold', - 5 => 'deviceDownMuted', - 6 => 'deviceUnmonitored', - 7 => 'deviceWarning', - 8 => 'deviceAlert', - 9 => 'deviceThresholdMuted', + 0 => 'deviceUnknown', + 1 => 'deviceDown', + 2 => 'deviceRecovering', + 3 => 'deviceUp', + 4 => 'deviceThreshold', + 5 => 'deviceDownMuted', + 6 => 'deviceUnmonitored', + 7 => 'deviceWarning', + 8 => 'deviceAlert', + 9 => 'deviceThresholdMuted', ]; $icolorsdisplay = [ - 0 => __('Unknown', 'monitor'), - 1 => __('Down', 'monitor'), - 2 => __('Recovering', 'monitor'), - 3 => __('Up', 'monitor'), - 4 => __('Triggered', 'monitor'), - 9 => __('Triggered (Muted/Acked)', 'monitor'), - 5 => __('Down (Muted/Acked)', 'monitor'), - 6 => __('No Availability Check', 'monitor'), - 7 => __('Warning Ping', 'monitor'), - 8 => __('Alert Ping', 'monitor'), + 0 => __('Unknown', 'monitor'), + 1 => __('Down', 'monitor'), + 2 => __('Recovering', 'monitor'), + 3 => __('Up', 'monitor'), + 4 => __('Triggered', 'monitor'), + 9 => __('Triggered (Muted/Acked)', 'monitor'), + 5 => __('Down (Muted/Acked)', 'monitor'), + 6 => __('No Availability Check', 'monitor'), + 7 => __('Warning Ping', 'monitor'), + 8 => __('Alert Ping', 'monitor'), ]; $classes = [ - 'monitor_exsmall' => __('Extra Small', 'monitor'), - 'monitor_small' => __('Small', 'monitor'), - 'monitor_medium' => __('Medium', 'monitor'), - 'monitor_large' => __('Large', 'monitor'), - 'monitor_exlarge' => __('Extra Large', 'monitor'), - 'monitor_errorzoom' => __('Zoom', 'monitor') + 'monitor_exsmall' => __('Extra Small', 'monitor'), + 'monitor_small' => __('Small', 'monitor'), + 'monitor_medium' => __('Medium', 'monitor'), + 'monitor_large' => __('Large', 'monitor'), + 'monitor_exlarge' => __('Extra Large', 'monitor'), + 'monitor_errorzoom' => __('Zoom', 'monitor') ]; $monitor_status = [ - -2 => __('All Devices', 'monitor'), - -1 => __('All Monitored Devices', 'monitor'), - 0 => __('Not Up', 'monitor'), - 1 => __('Not Up or Triggered', 'monitor'), - 2 => __('Not Up, Triggered or Breached', 'monitor'), - -4 => __('Devices without Thresholds', 'monitor'), - -3 => __('Devices not Monitored', 'monitor'), + -2 => __('All Devices', 'monitor'), + -1 => __('All Monitored Devices', 'monitor'), + 0 => __('Not Up', 'monitor'), + 1 => __('Not Up or Triggered', 'monitor'), + 2 => __('Not Up, Triggered or Breached', 'monitor'), + -4 => __('Devices without Thresholds', 'monitor'), + -3 => __('Devices not Monitored', 'monitor'), ]; $monitor_view_type = [ - 'default' => __('Default', 'monitor'), - 'list' => __('List', 'monitor'), - 'names' => __('Names only', 'monitor'), - 'tiles' => __('Tiles', 'monitor'), - 'tilesadt' => __('Tiles & Time', 'monitor') + 'default' => __('Default', 'monitor'), + 'list' => __('List', 'monitor'), + 'names' => __('Names only', 'monitor'), + 'tiles' => __('Tiles', 'monitor'), + 'tilesadt' => __('Tiles & Time', 'monitor') ]; $monitor_grouping = [ - 'default' => __('Default', 'monitor'), - 'tree' => __('Tree', 'monitor'), - 'site' => __('Site', 'monitor'), - 'template' => __('Device Template', 'monitor') + 'default' => __('Default', 'monitor'), + 'tree' => __('Tree', 'monitor'), + 'site' => __('Site', 'monitor'), + 'template' => __('Device Template', 'monitor') ]; $monitor_trim = [ - 0 => __('Default', 'monitor'), - -1 => __('Full', 'monitor'), - 10 => __('10 Chars', 'monitor'), - 20 => __('20 Chars', 'monitor'), - 30 => __('30 Chars', 'monitor'), - 40 => __('40 Chars', 'monitor'), - 50 => __('50 Chars', 'monitor'), - 75 => __('75 Chars', 'monitor'), - 100 => __('100 Chars', 'monitor'), + 0 => __('Default', 'monitor'), + -1 => __('Full', 'monitor'), + 10 => __('10 Chars', 'monitor'), + 20 => __('20 Chars', 'monitor'), + 30 => __('30 Chars', 'monitor'), + 40 => __('40 Chars', 'monitor'), + 50 => __('50 Chars', 'monitor'), + 75 => __('75 Chars', 'monitor'), + 100 => __('100 Chars', 'monitor'), ]; global $thold_hosts, $maxchars; @@ -125,55 +125,53 @@ $_SESSION['names'] = 0; if (!isset($_SESSION['monitor_muted_hosts'])) { - $_SESSION['monitor_muted_hosts'] = []; + $_SESSION['monitor_muted_hosts'] = []; } - include_once __DIR__ . '/db_functions.php'; include_once __DIR__ . '/monitor_render.php'; include_once __DIR__ . '/monitor_controller.php'; validateRequestVars(); - $thold_hosts = checkTholds(); switch (get_nfilter_request_var('action')) { - case 'ajax_status': - ajaxStatus(); - - break; - case 'ajax_mute_all': - muteAllHosts(); - drawPage(); - - break; - case 'ajax_unmute_all': - unmuteAllHosts(); - drawPage(); - - break; - case 'dbchange': - loadDashboardSettings(); - drawPage(); - - break; - case 'remove': - removeDashboard(); - drawPage(); - - break; - case 'saveDb': - saveSettings(); - drawPage(); - - break; - case 'save': - saveSettings(); - - break; - default: - drawPage(); + case 'ajax_status': + ajaxStatus(); + + break; + case 'ajax_mute_all': + muteAllHosts(); + drawPage(); + + break; + case 'ajax_unmute_all': + unmuteAllHosts(); + drawPage(); + + break; + case 'dbchange': + loadDashboardSettings(); + drawPage(); + + break; + case 'remove': + removeDashboard(); + drawPage(); + + break; + case 'saveDb': + saveSettings(); + drawPage(); + + break; + case 'save': + saveSettings(); + + break; + default: + drawPage(); } exit; diff --git a/monitor_controller.php b/monitor_controller.php index 84a341e..ff1e7c8 100644 --- a/monitor_controller.php +++ b/monitor_controller.php @@ -1,6 +1,6 @@ 0) { - $db_settings = db_fetch_cell_prepared( - 'SELECT url + if ($dashboard > 0) { + $db_settings = db_fetch_cell_prepared( + 'SELECT url FROM plugin_monitor_dashboards WHERE id = ?', - [$dashboard] - ); - - if ($db_settings != '') { - $db_settings = str_replace('monitor.php?', '', $db_settings); - $settings = explode('&', $db_settings); - - if (cacti_sizeof($settings)) { - foreach ($settings as $setting) { - [$name, $value] = explode('=', $setting); - - set_request_var($name, $value); - } - } - } - } + [$dashboard] + ); + + if ($db_settings != '') { + $db_settings = str_replace('monitor.php?', '', $db_settings); + $settings = explode('&', $db_settings); + + if (cacti_sizeof($settings)) { + foreach ($settings as $setting) { + [$name, $value] = explode('=', $setting); + + set_request_var($name, $value); + } + } + } + } } /** @@ -62,93 +61,92 @@ function loadDashboardSettings(): void * * @return void */ -function drawPage(): void -{ - global $config, $iclasses, $icolorsdisplay, $mon_zoom_state, $dozoomrefresh, $dozoombgndcolor, $font_sizes; - global $new_form, $new_title; - - $errored_list = getHostsDownOrTriggeredByPermission(true); - - if (cacti_sizeof($errored_list) && read_user_setting('monitor_error_zoom') == 'on') { - if ($_SESSION['monitor_zoom_state'] == 0) { - $mon_zoom_state = $_SESSION['monitor_zoom_state'] = 1; - $_SESSION['mon_zoom_hist_status'] = get_nfilter_request_var('status'); - $_SESSION['mon_zoom_hist_size'] = get_nfilter_request_var('size'); - $dozoomrefresh = true; - $dozoombgndcolor = true; - } - } elseif (isset($_SESSION['monitor_zoom_state']) && $_SESSION['monitor_zoom_state'] == 1) { - $_SESSION['monitor_zoom_state'] = 0; - $dozoomrefresh = true; - $dozoombgndcolor = false; - } - - $name = db_fetch_cell_prepared( - 'SELECT name +function drawPage(): void { + global $config, $iclasses, $icolorsdisplay, $mon_zoom_state, $dozoomrefresh, $dozoombgndcolor, $font_sizes; + global $new_form, $new_title; + + $errored_list = getHostsDownOrTriggeredByPermission(true); + + if (cacti_sizeof($errored_list) && read_user_setting('monitor_error_zoom') == 'on') { + if ($_SESSION['monitor_zoom_state'] == 0) { + $mon_zoom_state = $_SESSION['monitor_zoom_state'] = 1; + $_SESSION['mon_zoom_hist_status'] = get_nfilter_request_var('status'); + $_SESSION['mon_zoom_hist_size'] = get_nfilter_request_var('size'); + $dozoomrefresh = true; + $dozoombgndcolor = true; + } + } elseif (isset($_SESSION['monitor_zoom_state']) && $_SESSION['monitor_zoom_state'] == 1) { + $_SESSION['monitor_zoom_state'] = 0; + $dozoomrefresh = true; + $dozoombgndcolor = false; + } + + $name = db_fetch_cell_prepared( + 'SELECT name FROM plugin_monitor_dashboards WHERE id = ?', - [get_request_var('dashboard')] - ); + [get_request_var('dashboard')] + ); - if ($name == '') { - $name = __('New Dashboard', 'monitor'); - } + if ($name == '') { + $name = __('New Dashboard', 'monitor'); + } - $new_form = "
' . __('Criticality') . '' . __('Criticality') . '

" . __('Click \'Continue\' to %s monitoring on these Device(s)', $action_description, 'monitor') . "

    " . $save['host_list'] . '

" . __('Click \'Continue\' to Change the Monitoring settings for the following Device(s). Remember to check \'Update this Field\' to indicate which columns to update.', 'monitor') . "

    " . $save['host_list'] . '

' . __('Availability:', 'monitor') . '' . round($host['availability'], 2) . ' %' . round((float) $host['availability'], 2) . ' %
' . __('Agent Uptime:', 'monitor') . '
" . __('Enter the Dashboard Name and then press \'Save\' to continue, else press \'Cancel\'', 'monitor') . '
' . __('Dashboard', 'monitor') . "
"; + $new_form = "
" . __('Enter the Dashboard Name and then press \'Save\' to continue, else press \'Cancel\'', 'monitor') . '
' . __('Dashboard', 'monitor') . "
"; - $new_title = __('Create New Dashboard', 'monitor'); + $new_title = __('Create New Dashboard', 'monitor'); - findDownHosts(); + findDownHosts(); - general_header(); + general_header(); - drawFilterAndStatus(); + drawFilterAndStatus(); - print ''; + print ''; - // Default with permissions = default_by_permission - // Tree = group_by_tree - $function = 'render' . ucfirst(get_request_var('grouping')); + // Default with permissions = default_by_permission + // Tree = group_by_tree + $function = 'render' . ucfirst(get_request_var('grouping')); - if (function_exists($function) && get_request_var('view') != 'list') { - if (get_request_var('grouping') == 'default' || get_request_var('grouping') == 'site') { - html_start_box(__('Monitored Devices', 'monitor'), '100%', true, '3', 'center', ''); - } else { - html_start_box('', '100%', true, '3', 'center', ''); - } - print $function(); - } else { - print renderDefault(); - } + if (function_exists($function) && get_request_var('view') != 'list') { + if (get_request_var('grouping') == 'default' || get_request_var('grouping') == 'site') { + html_start_box(__('Monitored Devices', 'monitor'), '100%', true, '3', 'center', ''); + } else { + html_start_box('', '100%', true, '3', 'center', ''); + } + print $function(); + } else { + print renderDefault(); + } - print ''; + print ''; - html_end_box(); + html_end_box(); - if (read_user_setting('monitor_legend', read_config_option('monitor_legend'))) { - print "
"; + if (read_user_setting('monitor_legend', read_config_option('monitor_legend'))) { + print "
"; - foreach ($iclasses as $index => $class) { - print "
" . $icolorsdisplay[$index] . '
'; - } + foreach ($iclasses as $index => $class) { + print "
" . $icolorsdisplay[$index] . '
'; + } - print '
'; - } + print '
'; + } - // If the host is down, we need to insert the embedded wav file - $monitor_sound = getMonitorSound(); + // If the host is down, we need to insert the embedded wav file + $monitor_sound = getMonitorSound(); - if (isMonitorAudible()) { - if (read_user_setting('monitor_sound_loop', read_config_option('monitor_sound_loop'))) { - print ""; - } else { - print ""; - } - } + if (isMonitorAudible()) { + if (read_user_setting('monitor_sound_loop', read_config_option('monitor_sound_loop'))) { + print ""; + } else { + print ""; + } + } - print '
' . getFilterText() . '
'; + print '
' . getFilterText() . '
'; - bottom_footer(); + bottom_footer(); } /** @@ -156,9 +154,8 @@ function drawPage(): void * * @return bool */ -function isMonitorAudible(): bool -{ - return getMonitorSound() != ''; +function isMonitorAudible(): bool { + return getMonitorSound() != ''; } /** @@ -166,14 +163,13 @@ function isMonitorAudible(): bool * * @return string */ -function getMonitorSound(): string -{ - $sound = (string) read_user_setting('monitor_sound', read_config_option('monitor_sound')); - clearstatcache(); - $file = __DIR__ . '/sounds/' . $sound; - $exists = file_exists($file); - - return $exists ? $sound : ''; +function getMonitorSound(): string { + $sound = (string) read_user_setting('monitor_sound', read_config_option('monitor_sound')); + clearstatcache(); + $file = __DIR__ . '/sounds/' . $sound; + $exists = file_exists($file); + + return $exists ? $sound : ''; } /** @@ -181,28 +177,27 @@ function getMonitorSound(): string * * @return void */ -function findDownHosts(): void -{ - $dhosts = getHostsDownOrTriggeredByPermission(false); - - if (cacti_sizeof($dhosts)) { - set_request_var('downhosts', 'true'); - - if (isset($_SESSION['monitor_muted_hosts'])) { - unmuteUpNonTriggeredHosts($dhosts); - - $unmuted_hosts = array_diff($dhosts, $_SESSION['monitor_muted_hosts']); - - if (cacti_sizeof($unmuted_hosts)) { - unmuteUser(); - } - } else { - set_request_var('mute', 'false'); - } - } else { - unmuteAllHosts(); - set_request_var('downhosts', 'false'); - } +function findDownHosts(): void { + $dhosts = getHostsDownOrTriggeredByPermission(false); + + if (cacti_sizeof($dhosts)) { + set_request_var('downhosts', 'true'); + + if (isset($_SESSION['monitor_muted_hosts'])) { + unmuteUpNonTriggeredHosts($dhosts); + + $unmuted_hosts = array_diff($dhosts, $_SESSION['monitor_muted_hosts']); + + if (cacti_sizeof($unmuted_hosts)) { + unmuteUser(); + } + } else { + set_request_var('mute', 'false'); + } + } else { + unmuteAllHosts(); + set_request_var('downhosts', 'false'); + } } /** @@ -212,15 +207,14 @@ function findDownHosts(): void * * @return void */ -function unmuteUpNonTriggeredHosts(array $dhosts): void -{ - if (isset($_SESSION['monitor_muted_hosts'])) { - foreach ($_SESSION['monitor_muted_hosts'] as $index => $host_id) { - if (array_search($host_id, $dhosts, true) === false) { - unset($_SESSION['monitor_muted_hosts'][$index]); - } - } - } +function unmuteUpNonTriggeredHosts(array $dhosts): void { + if (isset($_SESSION['monitor_muted_hosts'])) { + foreach ($_SESSION['monitor_muted_hosts'] as $index => $host_id) { + if (array_search($host_id, $dhosts, true) === false) { + unset($_SESSION['monitor_muted_hosts'][$index]); + } + } + } } /** @@ -228,10 +222,9 @@ function unmuteUpNonTriggeredHosts(array $dhosts): void * * @return void */ -function muteAllHosts(): void -{ - $_SESSION['monitor_muted_hosts'] = getHostsDownOrTriggeredByPermission(false); - muteUser(); +function muteAllHosts(): void { + $_SESSION['monitor_muted_hosts'] = getHostsDownOrTriggeredByPermission(false); + muteUser(); } /** @@ -239,10 +232,9 @@ function muteAllHosts(): void * * @return void */ -function unmuteAllHosts(): void -{ - $_SESSION['monitor_muted_hosts'] = []; - unmuteUser(); +function unmuteAllHosts(): void { + $_SESSION['monitor_muted_hosts'] = []; + unmuteUser(); } /** @@ -250,10 +242,9 @@ function unmuteAllHosts(): void * * @return void */ -function muteUser(): void -{ - set_request_var('mute', 'true'); - set_user_setting('monitor_mute', 'true'); +function muteUser(): void { + set_request_var('mute', 'true'); + set_user_setting('monitor_mute', 'true'); } /** @@ -261,81 +252,78 @@ function muteUser(): void * * @return void */ -function unmuteUser(): void -{ - set_request_var('mute', 'false'); - set_user_setting('monitor_mute', 'false'); +function unmuteUser(): void { + set_request_var('mute', 'false'); + set_user_setting('monitor_mute', 'false'); } - /** * Build footer text describing currently active monitor filters. * * @return string */ -function getFilterText(): string -{ - $filter = '
'; +function getFilterText(): string { + $filter = '
'; - switch (get_request_var('status')) { - case '-4': - $filter .= __('Devices without Thresholds', 'monitor'); + switch (get_request_var('status')) { + case '-4': + $filter .= __('Devices without Thresholds', 'monitor'); - break; - case '-3': - $filter .= __('Not Monitored Devices', 'monitor'); + break; + case '-3': + $filter .= __('Not Monitored Devices', 'monitor'); - break; - case '-2': - $filter .= __('All Devices', 'monitor'); + break; + case '-2': + $filter .= __('All Devices', 'monitor'); - break; - case '-1': - $filter .= __('All Monitored Devices', 'monitor'); + break; + case '-1': + $filter .= __('All Monitored Devices', 'monitor'); - break; - case '0': - $filter .= __('Monitored Devices either Down or Recovering', 'monitor'); + break; + case '0': + $filter .= __('Monitored Devices either Down or Recovering', 'monitor'); - break; - case '1': - $filter .= __('Monitored Devices either Down, Recovering, or with Triggered Thresholds', 'monitor'); + break; + case '1': + $filter .= __('Monitored Devices either Down, Recovering, or with Triggered Thresholds', 'monitor'); - break; - case '2': - $filter .= __('Monitored Devices either Down, Recovering, or with Breached or Triggered Thresholds', 'monitor'); + break; + case '2': + $filter .= __('Monitored Devices either Down, Recovering, or with Breached or Triggered Thresholds', 'monitor'); - break; - default: - $filter .= __('Unknown monitoring status (%s)', get_request_var('status'), 'monitor'); - } + break; + default: + $filter .= __('Unknown monitoring status (%s)', get_request_var('status'), 'monitor'); + } - switch (get_request_var('crit')) { - case '0': - $filter .= __(', and All Criticalities', 'monitor'); + switch (get_request_var('crit')) { + case '0': + $filter .= __(', and All Criticalities', 'monitor'); - break; - case '1': - $filter .= __(', and of Low Criticality or Higher', 'monitor'); + break; + case '1': + $filter .= __(', and of Low Criticality or Higher', 'monitor'); - break; - case '2': - $filter .= __(', and of Medium Criticality or Higher', 'monitor'); + break; + case '2': + $filter .= __(', and of Medium Criticality or Higher', 'monitor'); - break; - case '3': - $filter .= __(', and of High Criticality or Higher', 'monitor'); + break; + case '3': + $filter .= __(', and of High Criticality or Higher', 'monitor'); - break; - case '4': - $filter .= __(', and of Mission Critical Status', 'monitor'); + break; + case '4': + $filter .= __(', and of Mission Critical Status', 'monitor'); - break; - } + break; + } - $filter .= __('
Remember to first select eligible Devices to be Monitored from the Devices page!
', 'monitor'); + $filter .= __('
Remember to first select eligible Devices to be Monitored from the Devices page!
', 'monitor'); - return $filter; + return $filter; } /** @@ -348,30 +336,29 @@ function getFilterText(): string * * @return void */ -function drawFilterDropdown(string $id, string $title, array $settings = [], mixed $value = null): void -{ - if ($value == null) { - $value = get_nfilter_request_var($id); - } - - if (cacti_sizeof($settings)) { - print '' . html_escape($title) . ''; - print '' . PHP_EOL; - } else { - print "" . PHP_EOL; - } +function drawFilterDropdown(string $id, string $title, array $settings = [], mixed $value = null): void { + if ($value == null) { + $value = get_nfilter_request_var($id); + } + + if (cacti_sizeof($settings)) { + print '' . html_escape($title) . ''; + print '' . PHP_EOL; + } else { + print "" . PHP_EOL; + } } /** @@ -379,22 +366,21 @@ function drawFilterDropdown(string $id, string $title, array $settings = [], mix * * @return array */ -function monitorGetDashboardOptions(): array -{ - $dashboards = [0 => __('Unsaved', 'monitor')]; - $dashboards += array_rekey( - db_fetch_assoc_prepared( - 'SELECT id, name +function monitorGetDashboardOptions(): array { + $dashboards = [0 => __('Unsaved', 'monitor')]; + $dashboards += array_rekey( + db_fetch_assoc_prepared( + 'SELECT id, name FROM plugin_monitor_dashboards WHERE user_id = 0 OR user_id = ? ORDER BY name', - [$_SESSION['sess_user_id']] - ), - 'id', - 'name' - ); + [$_SESSION['sess_user_id']] + ), + 'id', + 'name' + ); - return $dashboards; + return $dashboards; } /** @@ -404,137 +390,134 @@ function monitorGetDashboardOptions(): array * * @return array{int|null, string|null} */ -function monitorGetZoomDropdownState(bool &$dozoombgndcolor): array -{ - $mon_zoom_status = null; - $mon_zoom_size = null; - - if (isset($_SESSION['monitor_zoom_state'])) { - if ($_SESSION['monitor_zoom_state'] == 1) { - $mon_zoom_status = 2; - $mon_zoom_size = 'monitor_errorzoom'; - $dozoombgndcolor = true; - } else { - if (isset($_SESSION['mon_zoom_hist_status'])) { - $mon_zoom_status = $_SESSION['mon_zoom_hist_status']; - } - - if (isset($_SESSION['mon_zoom_hist_size'])) { - $currentddsize = get_nfilter_request_var('size'); - - if ($currentddsize != $_SESSION['mon_zoom_hist_size'] && $currentddsize != 'monitor_errorzoom') { - $_SESSION['mon_zoom_hist_size'] = $currentddsize; - } - - $mon_zoom_size = $_SESSION['mon_zoom_hist_size']; - } - } - } - - return [$mon_zoom_status, $mon_zoom_size]; +function monitorGetZoomDropdownState(bool &$dozoombgndcolor): array { + $mon_zoom_status = null; + $mon_zoom_size = null; + + if (isset($_SESSION['monitor_zoom_state'])) { + if ($_SESSION['monitor_zoom_state'] == 1) { + $mon_zoom_status = 2; + $mon_zoom_size = 'monitor_errorzoom'; + $dozoombgndcolor = true; + } else { + if (isset($_SESSION['mon_zoom_hist_status'])) { + $mon_zoom_status = $_SESSION['mon_zoom_hist_status']; + } + + if (isset($_SESSION['mon_zoom_hist_size'])) { + $currentddsize = get_nfilter_request_var('size'); + + if ($currentddsize != $_SESSION['mon_zoom_hist_size'] && $currentddsize != 'monitor_errorzoom') { + $_SESSION['mon_zoom_hist_size'] = $currentddsize; + } + + $mon_zoom_size = $_SESSION['mon_zoom_hist_size']; + } + } + } + + return [$mon_zoom_status, $mon_zoom_size]; } /** * Render the primary filter row (layout/status/view/grouping/actions). * - * @param array $dashboards Dashboard option map. - * @param array $monitor_status Status filter options. - * @param array $monitor_view_type View mode options. - * @param array $monitor_grouping Grouping mode options. - * @param array $item_rows Device row count options. - * @param int|null $mon_zoom_status Zoom-driven status override. + * @param array $dashboards Dashboard option map. + * @param array $monitor_status Status filter options. + * @param array $monitor_view_type View mode options. + * @param array $monitor_grouping Grouping mode options. + * @param array $item_rows Device row count options. + * @param int|null $mon_zoom_status Zoom-driven status override. * * @return void */ -function monitorRenderPrimaryFilterRow(array $dashboards, array $monitor_status, array $monitor_view_type, array $monitor_grouping, array $item_rows, int|null $mon_zoom_status): void -{ - drawFilterDropdown('dashboard', __('Layout', 'monitor'), $dashboards); - drawFilterDropdown('status', __('Status', 'monitor'), $monitor_status, $mon_zoom_status); - drawFilterDropdown('view', __('View', 'monitor'), $monitor_view_type); - drawFilterDropdown('grouping', __('Grouping', 'monitor'), $monitor_grouping); - drawFilterDropdown('rows', __('Devices', 'monitor'), $item_rows); - - print '' . PHP_EOL; - print '' . PHP_EOL; - print '' . PHP_EOL; - print '' . PHP_EOL; - print '' . PHP_EOL; - - if (get_request_var('dashboard') > 0) { - print '' . PHP_EOL; - print '' . PHP_EOL; - } - - print '' . PHP_EOL; - print '' . PHP_EOL; - print ''; +function monitorRenderPrimaryFilterRow(array $dashboards, array $monitor_status, array $monitor_view_type, array $monitor_grouping, array $item_rows, int|null $mon_zoom_status): void { + drawFilterDropdown('dashboard', __('Layout', 'monitor'), $dashboards); + drawFilterDropdown('status', __('Status', 'monitor'), $monitor_status, $mon_zoom_status); + drawFilterDropdown('view', __('View', 'monitor'), $monitor_view_type); + drawFilterDropdown('grouping', __('Grouping', 'monitor'), $monitor_grouping); + drawFilterDropdown('rows', __('Devices', 'monitor'), $item_rows); + + print '' . PHP_EOL; + print '' . PHP_EOL; + print '' . PHP_EOL; + print '' . PHP_EOL; + print '' . PHP_EOL; + + if (get_request_var('dashboard') > 0) { + print '' . PHP_EOL; + print '' . PHP_EOL; + } + + print '' . PHP_EOL; + print '' . PHP_EOL; + print ''; } /** * Render secondary grouping/filter controls for monitor page. * - * @param array $classes Size class options. - * @param array $criticalities Criticality options. - * @param array $monitor_trim Trim options. - * @param array $page_refresh_interval Refresh options. - * @param string|null $mon_zoom_size Zoom-driven size override. + * @param array $classes Size class options. + * @param array $criticalities Criticality options. + * @param array $monitor_trim Trim options. + * @param array $page_refresh_interval Refresh options. + * @param string|null $mon_zoom_size Zoom-driven size override. * * @return void */ -function monitorRenderGroupingDropdowns(array $classes, array $criticalities, array $monitor_trim, array $page_refresh_interval, string|null $mon_zoom_size): void -{ - drawFilterDropdown('crit', __('Criticality', 'monitor'), $criticalities); +function monitorRenderGroupingDropdowns(array $classes, array $criticalities, array $monitor_trim, array $page_refresh_interval, string|null $mon_zoom_size): void { + drawFilterDropdown('crit', __('Criticality', 'monitor'), $criticalities); - if (get_request_var('view') != 'list') { - drawFilterDropdown('size', __('Size', 'monitor'), $classes, $mon_zoom_size); - } + if (get_request_var('view') != 'list') { + drawFilterDropdown('size', __('Size', 'monitor'), $classes, $mon_zoom_size); + } - if (get_request_var('view') == 'default' || get_request_var('view') == 'names') { - drawFilterDropdown('trim', __('Trim', 'monitor'), $monitor_trim); - } + if (get_request_var('view') == 'default' || get_request_var('view') == 'names') { + drawFilterDropdown('trim', __('Trim', 'monitor'), $monitor_trim); + } - if (get_nfilter_request_var('grouping') == 'tree') { - $trees = []; + if (get_nfilter_request_var('grouping') == 'tree') { + $trees = []; - if (get_request_var('grouping') == 'tree') { - $trees_allowed = array_rekey(get_allowed_trees(), 'id', 'name'); + if (get_request_var('grouping') == 'tree') { + $trees_allowed = array_rekey(get_allowed_trees(), 'id', 'name'); - if (cacti_sizeof($trees_allowed)) { - $trees_prefix = [-1 => __('All Trees', 'monitor')]; - $trees_suffix = [-2 => __('Non-Tree Devices', 'monitor')]; - $trees = $trees_prefix + $trees_allowed + $trees_suffix; - } - } + if (cacti_sizeof($trees_allowed)) { + $trees_prefix = [-1 => __('All Trees', 'monitor')]; + $trees_suffix = [-2 => __('Non-Tree Devices', 'monitor')]; + $trees = $trees_prefix + $trees_allowed + $trees_suffix; + } + } - drawFilterDropdown('tree', __('Tree', 'monitor'), $trees); - } + drawFilterDropdown('tree', __('Tree', 'monitor'), $trees); + } - if (get_nfilter_request_var('grouping') == 'site') { - $sites = []; + if (get_nfilter_request_var('grouping') == 'site') { + $sites = []; - if (get_request_var('grouping') == 'site') { - $sites = array_rekey( - db_fetch_assoc('SELECT id, name + if (get_request_var('grouping') == 'site') { + $sites = array_rekey( + db_fetch_assoc('SELECT id, name FROM sites ORDER BY name'), - 'id', - 'name' - ); - - if (cacti_sizeof($sites)) { - $sites_prefix = [-1 => __('All Sites', 'monitor')]; - $sites_suffix = [-2 => __('Non-Site Devices', 'monitor')]; - $sites = $sites_prefix + $sites + $sites_suffix; - } - } - - drawFilterDropdown('site', __('Sites', 'monitor'), $sites); - } - - if (get_request_var('grouping') == 'template') { - $templates = []; - $templates_allowed = array_rekey( - db_fetch_assoc('SELECT ht.id, ht.name, COUNT(gl.id) AS graphs + 'id', + 'name' + ); + + if (cacti_sizeof($sites)) { + $sites_prefix = [-1 => __('All Sites', 'monitor')]; + $sites_suffix = [-2 => __('Non-Site Devices', 'monitor')]; + $sites = $sites_prefix + $sites + $sites_suffix; + } + } + + drawFilterDropdown('site', __('Sites', 'monitor'), $sites); + } + + if (get_request_var('grouping') == 'template') { + $templates = []; + $templates_allowed = array_rekey( + db_fetch_assoc('SELECT ht.id, ht.name, COUNT(gl.id) AS graphs FROM host_template AS ht INNER JOIN host AS h ON h.host_template_id = ht.id @@ -542,20 +525,20 @@ function monitorRenderGroupingDropdowns(array $classes, array $criticalities, ar ON h.id = gl.host_id GROUP BY ht.id HAVING graphs > 0'), - 'id', - 'name' - ); + 'id', + 'name' + ); - if (cacti_sizeof($templates_allowed)) { - $templates_prefix = [-1 => __('All Templates', 'monitor')]; - $templates_suffix = [-2 => __('Non-Templated Devices', 'monitor')]; - $templates = $templates_prefix + $templates_allowed + $templates_suffix; - } + if (cacti_sizeof($templates_allowed)) { + $templates_prefix = [-1 => __('All Templates', 'monitor')]; + $templates_suffix = [-2 => __('Non-Templated Devices', 'monitor')]; + $templates = $templates_prefix + $templates_allowed + $templates_suffix; + } - drawFilterDropdown('template', __('Template', 'monitor'), $templates); - } + drawFilterDropdown('template', __('Template', 'monitor'), $templates); + } - drawFilterDropdown('refresh', __('Refresh', 'monitor'), $page_refresh_interval); + drawFilterDropdown('refresh', __('Refresh', 'monitor'), $page_refresh_interval); } /** @@ -563,27 +546,26 @@ function monitorRenderGroupingDropdowns(array $classes, array $criticalities, ar * * @return void */ -function monitorRenderHiddenFilterInputs(): void -{ - if (get_request_var('grouping') != 'tree') { - print '' . PHP_EOL; - } - - if (get_request_var('grouping') != 'site') { - print '' . PHP_EOL; - } - - if (get_request_var('grouping') != 'template') { - print '' . PHP_EOL; - } - - if (get_request_var('view') == 'list') { - print '' . PHP_EOL; - } - - if (get_request_var('view') != 'default') { - print '' . PHP_EOL; - } +function monitorRenderHiddenFilterInputs(): void { + if (get_request_var('grouping') != 'tree') { + print '' . PHP_EOL; + } + + if (get_request_var('grouping') != 'site') { + print '' . PHP_EOL; + } + + if (get_request_var('grouping') != 'template') { + print '' . PHP_EOL; + } + + if (get_request_var('view') == 'list') { + print '' . PHP_EOL; + } + + if (get_request_var('view') != 'default') { + print '' . PHP_EOL; + } } /** @@ -593,24 +575,23 @@ function monitorRenderHiddenFilterInputs(): void * * @return array{string, string} */ -function monitorGetZoomBackgroundStyle(bool $dozoombgndcolor): array -{ - if ($dozoombgndcolor) { - $mbcolora = db_fetch_row_prepared( - 'SELECT * +function monitorGetZoomBackgroundStyle(bool $dozoombgndcolor): array { + if ($dozoombgndcolor) { + $mbcolora = db_fetch_row_prepared( + 'SELECT * FROM colors WHERE id = ?', - [read_user_setting('monitor_error_background')] - ); + [read_user_setting('monitor_error_background')] + ); - $monitor_error_fontsize = read_user_setting('monitor_error_fontsize') . 'px'; - $mbcolor = cacti_sizeof($mbcolora) ? '#' . $mbcolora['hex'] : 'snow'; - } else { - $mbcolor = ''; - $monitor_error_fontsize = '10px'; - } + $monitor_error_fontsize = read_user_setting('monitor_error_fontsize') . 'px'; + $mbcolor = cacti_sizeof($mbcolora) ? '#' . $mbcolora['hex'] : 'snow'; + } else { + $mbcolor = ''; + $monitor_error_fontsize = '10px'; + } - return [$mbcolor, $monitor_error_fontsize]; + return [$mbcolor, $monitor_error_fontsize]; } /** @@ -625,25 +606,24 @@ function monitorGetZoomBackgroundStyle(bool $dozoombgndcolor): array * * @return void */ -function monitorPrintJsBootstrap(array $config, string $mbcolor, string $monitor_error_fontsize, bool $dozoomrefresh, string $new_form, string $new_title): void -{ - $monitor_js_config = [ - 'mbColor' => $mbcolor, - 'monitorFont' => $monitor_error_fontsize, - 'doZoomRefresh' => $dozoomrefresh, - 'newForm' => $new_form, - 'newTitle' => $new_title, - 'messages' => [ - 'filterSaved' => __(' [ Filter Settings Saved ]', 'monitor'), - 'cancel' => __('Cancel', 'monitor'), - 'save' => __('Save', 'monitor') - ] - ]; - - print ''; - print ''; +function monitorPrintJsBootstrap(array $config, string $mbcolor, string $monitor_error_fontsize, bool $dozoomrefresh, string $new_form, string $new_title): void { + $monitor_js_config = [ + 'mbColor' => $mbcolor, + 'monitorFont' => $monitor_error_fontsize, + 'doZoomRefresh' => $dozoomrefresh, + 'newForm' => $new_form, + 'newTitle' => $new_title, + 'messages' => [ + 'filterSaved' => __(' [ Filter Settings Saved ]', 'monitor'), + 'cancel' => __('Cancel', 'monitor'), + 'save' => __('Save', 'monitor') + ] + ]; + + print ''; + print ''; } /** @@ -651,50 +631,49 @@ function monitorPrintJsBootstrap(array $config, string $mbcolor, string $monitor * * @return void */ -function drawFilterAndStatus(): void -{ - global $config, $criticalities, $page_refresh_interval, $classes, $monitor_grouping; - global $monitor_view_type, $monitor_status, $monitor_trim; - global $dozoombgndcolor, $dozoomrefresh, $zoom_hist_status, $zoom_hist_size, $mon_zoom_state; - global $new_form, $new_title, $item_rows; - - $header = __('Monitor Filter [ Last Refresh: %s ]', date('g:i:s a', time()), 'monitor') . (get_request_var('refresh') < 99999 ? __(' [ Refresh Again in %d Seconds ]', get_request_var('refresh'), 'monitor') : '') . (get_request_var('view') == 'list' ? __('[ Showing only first 30 Devices ]', 'monitor') : '') . ''; - - html_start_box($header, '100%', false, '3', 'center', ''); - - print '' . PHP_EOL; - print '
' . PHP_EOL; - - print '' . PHP_EOL; - print '' . PHP_EOL; - [$mon_zoom_status, $mon_zoom_size] = monitorGetZoomDropdownState($dozoombgndcolor); - monitorRenderPrimaryFilterRow( - monitorGetDashboardOptions(), - $monitor_status, - $monitor_view_type, - $monitor_grouping, - $item_rows, - $mon_zoom_status - ); - print ''; - print '
'; - - // Second line of filter - print '' . PHP_EOL; - print '' . PHP_EOL; - print ''; - print ''; - monitorRenderGroupingDropdowns($classes, $criticalities, $monitor_trim, $page_refresh_interval, $mon_zoom_size); - monitorRenderHiddenFilterInputs(); - - print ''; - print '
' . __('Search', 'monitor') . '
'; - print '
' . PHP_EOL; - - html_end_box(); - - [$mbcolor, $monitor_error_fontsize] = monitorGetZoomBackgroundStyle($dozoombgndcolor); - monitorPrintJsBootstrap($config, $mbcolor, $monitor_error_fontsize, $dozoomrefresh, $new_form, $new_title); +function drawFilterAndStatus(): void { + global $config, $criticalities, $page_refresh_interval, $classes, $monitor_grouping; + global $monitor_view_type, $monitor_status, $monitor_trim; + global $dozoombgndcolor, $dozoomrefresh, $zoom_hist_status, $zoom_hist_size, $mon_zoom_state; + global $new_form, $new_title, $item_rows; + + $header = __('Monitor Filter [ Last Refresh: %s ]', date('g:i:s a', time()), 'monitor') . (get_request_var('refresh') < 99999 ? __(' [ Refresh Again in %d Seconds ]', get_request_var('refresh'), 'monitor') : '') . (get_request_var('view') == 'list' ? __('[ Showing only first 30 Devices ]', 'monitor') : '') . ''; + + html_start_box($header, '100%', false, '3', 'center', ''); + + print '' . PHP_EOL; + print '
' . PHP_EOL; + + print '' . PHP_EOL; + print '' . PHP_EOL; + [$mon_zoom_status, $mon_zoom_size] = monitorGetZoomDropdownState($dozoombgndcolor); + monitorRenderPrimaryFilterRow( + monitorGetDashboardOptions(), + $monitor_status, + $monitor_view_type, + $monitor_grouping, + $item_rows, + $mon_zoom_status + ); + print ''; + print '
'; + + // Second line of filter + print '' . PHP_EOL; + print '' . PHP_EOL; + print ''; + print ''; + monitorRenderGroupingDropdowns($classes, $criticalities, $monitor_trim, $page_refresh_interval, $mon_zoom_size); + monitorRenderHiddenFilterInputs(); + + print ''; + print '
' . __('Search', 'monitor') . '
'; + print '
' . PHP_EOL; + + html_end_box(); + + [$mbcolor, $monitor_error_fontsize] = monitorGetZoomBackgroundStyle($dozoombgndcolor); + monitorPrintJsBootstrap($config, $mbcolor, $monitor_error_fontsize, $dozoomrefresh, $new_form, $new_title); } /** @@ -702,13 +681,12 @@ function drawFilterAndStatus(): void * * @return string */ -function getMuteText(): string -{ - if (isMonitorAudible()) { - return __('Mute', 'monitor'); - } else { - return __('Acknowledge', 'monitor'); - } +function getMuteText(): string { + if (isMonitorAudible()) { + return __('Mute', 'monitor'); + } else { + return __('Acknowledge', 'monitor'); + } } /** @@ -716,13 +694,12 @@ function getMuteText(): string * * @return string */ -function getUnmuteText(): string -{ - if (isMonitorAudible()) { - return __('Un-Mute', 'monitor'); - } else { - return __('Reset', 'monitor'); - } +function getUnmuteText(): string { + if (isMonitorAudible()) { + return __('Un-Mute', 'monitor'); + } else { + return __('Reset', 'monitor'); + } } /** @@ -730,38 +707,37 @@ function getUnmuteText(): string * * @return void */ -function removeDashboard(): void -{ - $dashboard = get_filter_request_var('dashboard'); +function removeDashboard(): void { + $dashboard = get_filter_request_var('dashboard'); - $name = db_fetch_cell_prepared( - 'SELECT name + $name = db_fetch_cell_prepared( + 'SELECT name FROM plugin_monitor_dashboards WHERE id = ? AND user_id = ?', - [$dashboard, $_SESSION['sess_user_id']] - ); + [$dashboard, $_SESSION['sess_user_id']] + ); - if ($name != '') { - db_execute_prepared( - 'DELETE FROM plugin_monitor_dashboards + if ($name != '') { + db_execute_prepared( + 'DELETE FROM plugin_monitor_dashboards WHERE id = ?', - [$dashboard] - ); + [$dashboard] + ); - raise_message('removed', __('Dashboard \'%s\' Removed.', $name, 'monitor'), MESSAGE_LEVEL_INFO); - } else { - $name = db_fetch_cell_prepared( - 'SELECT name + raise_message('removed', __('Dashboard \'%s\' Removed.', $name, 'monitor'), MESSAGE_LEVEL_INFO); + } else { + $name = db_fetch_cell_prepared( + 'SELECT name FROM plugin_monitor_dashboards WHERE id = ?', - [$dashboard] - ); + [$dashboard] + ); - raise_message('notremoved', __('Dashboard \'%s\' is not owned by you.', $name, 'monitor'), MESSAGE_LEVEL_ERROR); - } + raise_message('notremoved', __('Dashboard \'%s\' is not owned by you.', $name, 'monitor'), MESSAGE_LEVEL_ERROR); + } - set_request_var('dashboard', '0'); + set_request_var('dashboard', '0'); } /** @@ -769,119 +745,118 @@ function removeDashboard(): void * * @return void */ -function saveSettings(): void -{ - if (isset_request_var('dashboard') && get_filter_request_var('dashboard') != 0) { - $save_db = true; - } else { - $save_db = false; - } - - validateRequestVars(); - - if (!$save_db) { - if (cacti_sizeof($_REQUEST)) { - foreach ($_REQUEST as $var => $value) { - switch ($var) { - case 'dashboard': - set_user_setting('monitor_rfilter', get_request_var('dashboard')); - - break; - case 'rfilter': - set_user_setting('monitor_rfilter', get_request_var('rfilter')); - - break; - case 'refresh': - set_user_setting('monitor_refresh', get_request_var('refresh')); - - break; - case 'grouping': - set_user_setting('monitor_grouping', get_request_var('grouping')); - - break; - case 'view': - set_user_setting('monitor_view', get_request_var('view')); - - break; - case 'rows': - set_user_setting('monitor_rows', get_request_var('rows')); - - break; - case 'crit': - set_user_setting('monitor_crit', get_request_var('crit')); - - break; - case 'mute': - set_user_setting('monitor_mute', get_request_var('mute')); - - break; - case 'size': - set_user_setting('monitor_size', get_request_var('size')); - - break; - case 'trim': - set_user_setting('monitor_trim', get_request_var('trim')); - - break; - case 'status': - set_user_setting('monitor_status', get_request_var('status')); - - break; - case 'tree': - set_user_setting('monitor_tree', get_request_var('tree')); - - break; - case 'mute': - set_user_setting('monitor_mute', get_request_var('mute')); - - break; - case 'site': - set_user_setting('monitor_site', get_request_var('site')); - - break; - } - } - } - } else { - $url = 'monitor.php' . - '?refresh=' . get_request_var('refresh') . - '&grouping=' . get_request_var('grouping') . - '&view=' . get_request_var('view') . - '&rows=' . get_request_var('rows') . - '&crit=' . get_request_var('crit') . - '&size=' . get_request_var('size') . - '&trim=' . get_request_var('trim') . - '&status=' . get_request_var('status') . - '&tree=' . get_request_var('tree') . - '&site=' . get_request_var('site'); - - if (!isset_request_var('user')) { - $user = $_SESSION['sess_user_id']; - } else { - $user = get_request_var('user'); - } - - $id = get_request_var('dashboard'); - $name = get_nfilter_request_var('name'); - - $save = []; - $save['id'] = $id; - $save['name'] = $name; - $save['user_id'] = $user; - $save['url'] = $url; - - $id = sql_save($save, 'plugin_monitor_dashboards'); - - if (!empty($id)) { - raise_message('monitorsaved', __('Dashboard \'%s\' has been Saved!', $name, 'monitor'), MESSAGE_LEVEL_INFO); - set_request_var('dashboard', $id); - } else { - raise_message('monitornotsaved', __('Dashboard \'%s\' could not be Saved!', $name, 'monitor'), MESSAGE_LEVEL_INFO); - set_request_var('dashboard', '0'); - } - } - - validateRequestVars(true); +function saveSettings(): void { + if (isset_request_var('dashboard') && get_filter_request_var('dashboard') != 0) { + $save_db = true; + } else { + $save_db = false; + } + + validateRequestVars(); + + if (!$save_db) { + if (cacti_sizeof($_REQUEST)) { + foreach ($_REQUEST as $var => $value) { + switch ($var) { + case 'dashboard': + set_user_setting('monitor_rfilter', get_request_var('dashboard')); + + break; + case 'rfilter': + set_user_setting('monitor_rfilter', get_request_var('rfilter')); + + break; + case 'refresh': + set_user_setting('monitor_refresh', get_request_var('refresh')); + + break; + case 'grouping': + set_user_setting('monitor_grouping', get_request_var('grouping')); + + break; + case 'view': + set_user_setting('monitor_view', get_request_var('view')); + + break; + case 'rows': + set_user_setting('monitor_rows', get_request_var('rows')); + + break; + case 'crit': + set_user_setting('monitor_crit', get_request_var('crit')); + + break; + case 'mute': + set_user_setting('monitor_mute', get_request_var('mute')); + + break; + case 'size': + set_user_setting('monitor_size', get_request_var('size')); + + break; + case 'trim': + set_user_setting('monitor_trim', get_request_var('trim')); + + break; + case 'status': + set_user_setting('monitor_status', get_request_var('status')); + + break; + case 'tree': + set_user_setting('monitor_tree', get_request_var('tree')); + + break; + case 'mute': + set_user_setting('monitor_mute', get_request_var('mute')); + + break; + case 'site': + set_user_setting('monitor_site', get_request_var('site')); + + break; + } + } + } + } else { + $url = 'monitor.php' . + '?refresh=' . get_request_var('refresh') . + '&grouping=' . get_request_var('grouping') . + '&view=' . get_request_var('view') . + '&rows=' . get_request_var('rows') . + '&crit=' . get_request_var('crit') . + '&size=' . get_request_var('size') . + '&trim=' . get_request_var('trim') . + '&status=' . get_request_var('status') . + '&tree=' . get_request_var('tree') . + '&site=' . get_request_var('site'); + + if (!isset_request_var('user')) { + $user = $_SESSION['sess_user_id']; + } else { + $user = get_request_var('user'); + } + + $id = get_request_var('dashboard'); + $name = get_nfilter_request_var('name'); + + $save = []; + $save['id'] = $id; + $save['name'] = $name; + $save['user_id'] = $user; + $save['url'] = $url; + + $id = sql_save($save, 'plugin_monitor_dashboards'); + + if (!empty($id)) { + raise_message('monitorsaved', __('Dashboard \'%s\' has been Saved!', $name, 'monitor'), MESSAGE_LEVEL_INFO); + set_request_var('dashboard', $id); + } else { + raise_message('monitornotsaved', __('Dashboard \'%s\' could not be Saved!', $name, 'monitor'), MESSAGE_LEVEL_INFO); + set_request_var('dashboard', '0'); + } + } + + validateRequestVars(true); } /** @@ -891,107 +866,106 @@ function saveSettings(): void * * @return void */ -function validateRequestVars(bool $force = false): void -{ - // ================= input validation and session storage ================= - $filters = [ - 'refresh' => [ - 'filter' => FILTER_VALIDATE_INT, - 'default' => read_user_setting('monitor_refresh', read_config_option('monitor_refresh'), $force) - ], - 'dashboard' => [ - 'filter' => FILTER_VALIDATE_INT, - 'pageset' => true, - 'default' => read_user_setting('monitor_dashboard', '0', $force) - ], - 'rfilter' => [ - 'filter' => FILTER_VALIDATE_IS_REGEX, - 'pageset' => true, - 'default' => read_user_setting('monitor_rfilter', '', $force) - ], - 'name' => [ - 'filter' => FILTER_CALLBACK, - 'options' => ['options' => 'sanitize_search_string'], - 'default' => '' - ], - 'mute' => [ - 'filter' => FILTER_CALLBACK, - 'options' => ['options' => 'sanitize_search_string'], - 'default' => read_user_setting('monitor_mute', 'false', $force) - ], - 'grouping' => [ - 'filter' => FILTER_CALLBACK, - 'options' => ['options' => 'sanitize_search_string'], - 'pageset' => true, - 'default' => read_user_setting('monitor_grouping', read_config_option('monitor_grouping'), $force) - ], - 'view' => [ - 'filter' => FILTER_CALLBACK, - 'options' => ['options' => 'sanitize_search_string'], - 'pageset' => true, - 'default' => read_user_setting('monitor_view', read_config_option('monitor_view'), $force) - ], - 'rows' => [ - 'filter' => FILTER_VALIDATE_INT, - 'options' => ['options' => 'sanitize_search_string'], - 'default' => read_user_setting('monitor_rows', read_config_option('num_rows_table'), $force) - ], - 'size' => [ - 'filter' => FILTER_CALLBACK, - 'options' => ['options' => 'sanitize_search_string'], - 'default' => read_user_setting('monitor_size', 'monitor_medium', $force) - ], - 'trim' => [ - 'filter' => FILTER_VALIDATE_INT, - 'default' => read_user_setting('monitor_trim', read_config_option('monitor_trim'), $force) - ], - 'crit' => [ - 'filter' => FILTER_VALIDATE_INT, - 'pageset' => true, - 'default' => read_user_setting('monitor_crit', '-1', $force) - ], - 'status' => [ - 'filter' => FILTER_VALIDATE_INT, - 'pageset' => true, - 'default' => read_user_setting('monitor_status', '-1', $force) - ], - 'tree' => [ - 'filter' => FILTER_VALIDATE_INT, - 'pageset' => true, - 'default' => read_user_setting('monitor_tree', '-1', $force) - ], - 'site' => [ - 'filter' => FILTER_VALIDATE_INT, - 'pageset' => true, - 'default' => read_user_setting('monitor_site', '-1', $force) - ], - 'template' => [ - 'filter' => FILTER_VALIDATE_INT, - 'pageset' => true, - 'default' => read_user_setting('monitor_template', '-1', $force) - ], - 'id' => [ - 'filter' => FILTER_VALIDATE_INT, - 'default' => '-1' - ], - 'page' => [ - 'filter' => FILTER_VALIDATE_INT, - 'default' => '1' - ], - 'sort_column' => [ - 'filter' => FILTER_CALLBACK, - 'default' => 'status', - 'options' => ['options' => 'sanitize_search_string'] - ], - 'sort_direction' => [ - 'filter' => FILTER_CALLBACK, - 'default' => 'ASC', - 'options' => ['options' => 'sanitize_search_string'] - ] - ]; - - validate_store_request_vars($filters, 'sess_monitor'); - // ================= input validation ================= +function validateRequestVars(bool $force = false): void { + // ================= input validation and session storage ================= + $filters = [ + 'refresh' => [ + 'filter' => FILTER_VALIDATE_INT, + 'default' => read_user_setting('monitor_refresh', read_config_option('monitor_refresh'), $force) + ], + 'dashboard' => [ + 'filter' => FILTER_VALIDATE_INT, + 'pageset' => true, + 'default' => read_user_setting('monitor_dashboard', '0', $force) + ], + 'rfilter' => [ + 'filter' => FILTER_VALIDATE_IS_REGEX, + 'pageset' => true, + 'default' => read_user_setting('monitor_rfilter', '', $force) + ], + 'name' => [ + 'filter' => FILTER_CALLBACK, + 'options' => ['options' => 'sanitize_search_string'], + 'default' => '' + ], + 'mute' => [ + 'filter' => FILTER_CALLBACK, + 'options' => ['options' => 'sanitize_search_string'], + 'default' => read_user_setting('monitor_mute', 'false', $force) + ], + 'grouping' => [ + 'filter' => FILTER_CALLBACK, + 'options' => ['options' => 'sanitize_search_string'], + 'pageset' => true, + 'default' => read_user_setting('monitor_grouping', read_config_option('monitor_grouping'), $force) + ], + 'view' => [ + 'filter' => FILTER_CALLBACK, + 'options' => ['options' => 'sanitize_search_string'], + 'pageset' => true, + 'default' => read_user_setting('monitor_view', read_config_option('monitor_view'), $force) + ], + 'rows' => [ + 'filter' => FILTER_VALIDATE_INT, + 'options' => ['options' => 'sanitize_search_string'], + 'default' => read_user_setting('monitor_rows', read_config_option('num_rows_table'), $force) + ], + 'size' => [ + 'filter' => FILTER_CALLBACK, + 'options' => ['options' => 'sanitize_search_string'], + 'default' => read_user_setting('monitor_size', 'monitor_medium', $force) + ], + 'trim' => [ + 'filter' => FILTER_VALIDATE_INT, + 'default' => read_user_setting('monitor_trim', read_config_option('monitor_trim'), $force) + ], + 'crit' => [ + 'filter' => FILTER_VALIDATE_INT, + 'pageset' => true, + 'default' => read_user_setting('monitor_crit', '-1', $force) + ], + 'status' => [ + 'filter' => FILTER_VALIDATE_INT, + 'pageset' => true, + 'default' => read_user_setting('monitor_status', '-1', $force) + ], + 'tree' => [ + 'filter' => FILTER_VALIDATE_INT, + 'pageset' => true, + 'default' => read_user_setting('monitor_tree', '-1', $force) + ], + 'site' => [ + 'filter' => FILTER_VALIDATE_INT, + 'pageset' => true, + 'default' => read_user_setting('monitor_site', '-1', $force) + ], + 'template' => [ + 'filter' => FILTER_VALIDATE_INT, + 'pageset' => true, + 'default' => read_user_setting('monitor_template', '-1', $force) + ], + 'id' => [ + 'filter' => FILTER_VALIDATE_INT, + 'default' => '-1' + ], + 'page' => [ + 'filter' => FILTER_VALIDATE_INT, + 'default' => '1' + ], + 'sort_column' => [ + 'filter' => FILTER_CALLBACK, + 'default' => 'status', + 'options' => ['options' => 'sanitize_search_string'] + ], + 'sort_direction' => [ + 'filter' => FILTER_CALLBACK, + 'default' => 'ASC', + 'options' => ['options' => 'sanitize_search_string'] + ] + ]; + + validate_store_request_vars($filters, 'sess_monitor'); + // ================= input validation ================= } /** @@ -1003,34 +977,33 @@ function validateRequestVars(bool $force = false): void * * @return array */ -function monitorLoadAjaxStatusHost(int|string $id, array $thold_hosts, array $config): array -{ - $host = db_fetch_row_prepared( - 'SELECT * +function monitorLoadAjaxStatusHost(int|string $id, array $thold_hosts, array $config): array { + $host = db_fetch_row_prepared( + 'SELECT * FROM host WHERE id = ?', - [$id] - ); + [$id] + ); - if (!cacti_sizeof($host)) { - return []; - } + if (!cacti_sizeof($host)) { + return []; + } - $host['anchor'] = $config['url_path'] . 'graph_view.php?action=preview&reset=1&host_id=' . $host['id']; + $host['anchor'] = $config['url_path'] . 'graph_view.php?action=preview&reset=1&host_id=' . $host['id']; - if ($host['status'] == 3 && array_key_exists($host['id'], $thold_hosts)) { - $host['status'] = 4; - $host['anchor'] = $config['url_path'] . 'plugins/thold/thold_graph.php?action=thold&reset=true&status=1&host_id=' . $host['id']; - } + if ($host['status'] == 3 && array_key_exists($host['id'], $thold_hosts)) { + $host['status'] = 4; + $host['anchor'] = $config['url_path'] . 'plugins/thold/thold_graph.php?action=thold&reset=true&status=1&host_id=' . $host['id']; + } - if ($host['availability_method'] == 0) { - $host['status'] = 6; - } + if ($host['availability_method'] == 0) { + $host['status'] = 6; + } - $host['real_status'] = getHostStatus($host, true); - $host['status'] = getHostStatus($host); + $host['real_status'] = getHostStatus($host, true); + $host['status'] = getHostStatus($host); - return $host; + return $host; } /** @@ -1041,89 +1014,87 @@ function monitorLoadAjaxStatusHost(int|string $id, array $thold_hosts, array $co * * @return string */ -function monitorGetAjaxStatusLinks(array $host, array $config): string -{ - $links = ''; +function monitorGetAjaxStatusLinks(array $host, array $config): string { + $links = ''; - if (api_plugin_user_realm_auth('host.php')) { - $host_link = html_escape($config['url_path'] . 'host.php?action=edit&id=' . $host['id']); - $links .= '
'; - } + if (api_plugin_user_realm_auth('host.php')) { + $host_link = html_escape($config['url_path'] . 'host.php?action=edit&id=' . $host['id']); + $links .= '
'; + } - $graphs = db_fetch_cell_prepared( - 'SELECT COUNT(*) + $graphs = db_fetch_cell_prepared( + 'SELECT COUNT(*) FROM graph_local WHERE host_id = ?', - [$host['id']] - ); + [$host['id']] + ); - if ($graphs > 0) { - $graph_link = html_escape($config['url_path'] . 'graph_view.php?action=preview&reset=1&host_id=' . $host['id']); - $links .= '
'; - } + if ($graphs > 0) { + $graph_link = html_escape($config['url_path'] . 'graph_view.php?action=preview&reset=1&host_id=' . $host['id']); + $links .= '
'; + } - if (api_plugin_is_enabled('thold')) { - $tholds = db_fetch_cell_prepared( - 'SELECT count(*) + if (api_plugin_is_enabled('thold')) { + $tholds = db_fetch_cell_prepared( + 'SELECT count(*) FROM thold_data WHERE host_id = ?', - [$host['id']] - ); + [$host['id']] + ); - if ($tholds) { - $thold_link = html_escape($config['url_path'] . 'plugins/thold/thold_graph.php?action=thold&reset=true&status=1&host_id=' . $host['id']); - $links .= '
'; - } - } + if ($tholds) { + $thold_link = html_escape($config['url_path'] . 'plugins/thold/thold_graph.php?action=thold&reset=true&status=1&host_id=' . $host['id']); + $links .= '
'; + } + } - if (api_plugin_is_enabled('syslog') && api_plugin_user_realm_auth('syslog.php')) { - include($config['base_path'] . '/plugins/syslog/config.php'); - include_once($config['base_path'] . '/plugins/syslog/functions.php'); + if (api_plugin_is_enabled('syslog') && api_plugin_user_realm_auth('syslog.php')) { + include($config['base_path'] . '/plugins/syslog/config.php'); + include_once($config['base_path'] . '/plugins/syslog/functions.php'); - $syslog_logs = syslog_db_fetch_cell_prepared( - 'SELECT count(*) + $syslog_logs = syslog_db_fetch_cell_prepared( + 'SELECT count(*) FROM syslog_logs WHERE host = ?', - [$host['hostname']] - ); + [$host['hostname']] + ); - $syslog_host = syslog_db_fetch_cell_prepared( - 'SELECT host_id + $syslog_host = syslog_db_fetch_cell_prepared( + 'SELECT host_id FROM syslog_hosts WHERE host = ?', - [$host['hostname']] - ); + [$host['hostname']] + ); - if ($syslog_logs && $syslog_host) { - $syslog_log_link = html_escape($config['url_path'] . 'plugins/syslog/syslog/syslog.php?reset=1&tab=alerts&host_id=' . $syslog_host); - $links .= '
'; - } + if ($syslog_logs && $syslog_host) { + $syslog_log_link = html_escape($config['url_path'] . 'plugins/syslog/syslog/syslog.php?reset=1&tab=alerts&host_id=' . $syslog_host); + $links .= '
'; + } - if ($syslog_host) { - $syslog_link = html_escape($config['url_path'] . 'plugins/syslog/syslog/syslog.php?reset=1&tab=syslog&host_id=' . $syslog_host); - $links .= '
'; - } - } + if ($syslog_host) { + $syslog_link = html_escape($config['url_path'] . 'plugins/syslog/syslog/syslog.php?reset=1&tab=syslog&host_id=' . $syslog_host); + $links .= '
'; + } + } - return $links; + return $links; } /** * Render full hover tooltip table HTML for one host. * - * @param array $host Host row. - * @param string $size Tooltip CSS size key. - * @param string $links Action links HTML. - * @param string $site Site display value. - * @param string $sdisplay Status display string. - * @param string $iclass Status CSS class. + * @param array $host Host row. + * @param string $size Tooltip CSS size key. + * @param string $links Action links HTML. + * @param string $site Site display value. + * @param string $sdisplay Status display string. + * @param string $iclass Status CSS class. * @param array $criticalities Criticality label map. * * @return string */ -function monitorRenderAjaxStatusTooltip(array $host, string $size, string $links, string $site, string $sdisplay, string $iclass, array $criticalities): string -{ - return " +function monitorRenderAjaxStatusTooltip(array $host, string $size, string $links, string $site, string $sdisplay, string $iclass, array $criticalities): string { + return "
@@ -1199,49 +1170,47 @@ function monitorRenderAjaxStatusTooltip(array $host, string $size, string $links
" . __('Device Status Information', 'monitor') . '
"; } - /** * Handle AJAX monitor status tooltip request and print response HTML. * * @return bool|null */ -function ajaxStatus(): void -{ - global $thold_hosts, $config, $iclasses, $criticalities; +function ajaxStatus(): void { + global $thold_hosts, $config, $iclasses, $criticalities; - validateRequestVars(); + validateRequestVars(); - if (!isset_request_var('id') || !get_filter_request_var('id')) { - return; - } + if (!isset_request_var('id') || !get_filter_request_var('id')) { + return; + } - $id = get_request_var('id'); - $size = get_request_var('size'); - $host = monitorLoadAjaxStatusHost($id, $thold_hosts, $config); + $id = get_request_var('id'); + $size = get_request_var('size'); + $host = monitorLoadAjaxStatusHost($id, $thold_hosts, $config); - if (!cacti_sizeof($host)) { - cacti_log('Attempted to retrieve status for missing Device ' . $id, false, 'MONITOR', POLLER_VERBOSITY_HIGH); + if (!cacti_sizeof($host)) { + cacti_log('Attempted to retrieve status for missing Device ' . $id, false, 'MONITOR', POLLER_VERBOSITY_HIGH); - return; - } + return; + } - $links = monitorGetAjaxStatusLinks($host, $config); + $links = monitorGetAjaxStatusLinks($host, $config); - if (strtotime($host['status_fail_date']) < 86400) { - $host['status_fail_date'] = __('Never', 'monitor'); - } + if (strtotime($host['status_fail_date']) < 86400) { + $host['status_fail_date'] = __('Never', 'monitor'); + } - if ($host['location'] == '') { - $host['location'] = __('Unspecified', 'monitor'); - } + if ($host['location'] == '') { + $host['location'] = __('Unspecified', 'monitor'); + } - $iclass = $iclasses[$host['status']]; - $sdisplay = getHostStatusDescription($host['real_status']); - $site = db_fetch_cell_prepared('SELECT name FROM sites WHERE id = ?', [$host['site_id']]); + $iclass = $iclasses[$host['status']]; + $sdisplay = getHostStatusDescription($host['real_status']); + $site = db_fetch_cell_prepared('SELECT name FROM sites WHERE id = ?', [$host['site_id']]); - if ($site == '') { - $site = __('None', 'monitor'); - } + if ($site == '') { + $site = __('None', 'monitor'); + } - print monitorRenderAjaxStatusTooltip($host, $size, $links, $site, $sdisplay, $iclass, $criticalities); + print monitorRenderAjaxStatusTooltip($host, $size, $links, $site, $sdisplay, $iclass, $criticalities); } diff --git a/monitor_render.php b/monitor_render.php index 761460f..b2bc208 100644 --- a/monitor_render.php +++ b/monitor_render.php @@ -1,6 +1,6 @@ 0 AND status IN (1, 2), status_event_count*$poller_interval, IF(UNIX_TIMESTAMP(status_rec_date) < 943916400 AND status IN (0, 3), total_polls*$poller_interval, @@ -76,54 +75,54 @@ function renderDefault(): string $sql_order $sql_limit"); - $hosts = db_fetch_assoc($hosts_sql); + $hosts = db_fetch_assoc($hosts_sql); - $total_rows = db_fetch_cell("SELECT COUNT(DISTINCT h.id) + $total_rows = db_fetch_cell("SELECT COUNT(DISTINCT h.id) FROM host AS h LEFT JOIN sites AS s ON h.site_id = s.id $sql_join $sql_where"); - if (cacti_sizeof($hosts)) { - // Determine the correct width of the cell - $maxlen = 10; + if (cacti_sizeof($hosts)) { + // Determine the correct width of the cell + $maxlen = 10; - if (get_request_var('view') == 'default') { - $maxlen = db_fetch_cell("SELECT MAX(LENGTH(description)) + if (get_request_var('view') == 'default') { + $maxlen = db_fetch_cell("SELECT MAX(LENGTH(description)) FROM host AS h $sql_join $sql_where"); - } + } - $maxlen = getMonitorTrimLength($maxlen); + $maxlen = getMonitorTrimLength($maxlen); - $function = 'renderHeader' . ucfirst(get_request_var('view')); + $function = 'renderHeader' . ucfirst(get_request_var('view')); - if (function_exists($function)) { - // Call the custom render_header_ function - $result .= $function($total_rows, $rows); - } + if (function_exists($function)) { + // Call the custom render_header_ function + $result .= $function($total_rows, $rows); + } - $count = 0; + $count = 0; - foreach ($hosts as $host) { - if (is_device_allowed($host['id'])) { - $result .= renderHost($host, true, $maxlen); - } + foreach ($hosts as $host) { + if (is_device_allowed($host['id'])) { + $result .= renderHost($host, true, $maxlen); + } - $count++; - } + $count++; + } - $function = 'renderFooter' . ucfirst(get_request_var('view')); + $function = 'renderFooter' . ucfirst(get_request_var('view')); - if (function_exists($function)) { - // Call the custom render_footer_ function - $result .= $function($total_rows, $rows); - } - } + if (function_exists($function)) { + // Call the custom render_footer_ function + $result .= $function($total_rows, $rows); + } + } - return $result; + return $result; } /** @@ -131,31 +130,30 @@ function renderDefault(): string * * @return string */ -function renderSite(): string -{ - global $maxchars; +function renderSite(): string { + global $maxchars; - $result = ''; + $result = ''; - $sql_where = ''; - $sql_join = ''; - $sql_limit = ''; + $sql_where = ''; + $sql_join = ''; + $sql_limit = ''; - $rows = get_request_var('rows'); + $rows = get_request_var('rows'); - if ($rows == '-1') { - $rows = read_user_setting('monitor_rows'); - } + if ($rows == '-1') { + $rows = read_user_setting('monitor_rows'); + } - if (!is_numeric($rows)) { - $rows = read_config_option('num_rows_table'); - } + if (!is_numeric($rows)) { + $rows = read_config_option('num_rows_table'); + } - renderWhereJoin($sql_where, $sql_join); + renderWhereJoin($sql_where, $sql_join); - $sql_limit = ' LIMIT ' . ($rows * (get_request_var('page') - 1)) . ',' . $rows; + $sql_limit = ' LIMIT ' . ($rows * (get_request_var('page') - 1)) . ',' . $rows; - $hosts_sql = ("SELECT DISTINCT h.*, IFNULL(s.name,' " . __('Non-Site Devices', 'monitor') . " ') AS site_name + $hosts_sql = ("SELECT DISTINCT h.*, IFNULL(s.name,' " . __('Non-Site Devices', 'monitor') . " ') AS site_name FROM host AS h LEFT JOIN sites AS s ON s.id = h.site_id @@ -164,90 +162,90 @@ function renderSite(): string ORDER BY site_name, description $sql_limit"); - $hosts = db_fetch_assoc($hosts_sql); + $hosts = db_fetch_assoc($hosts_sql); - $ctemp = -1; - $ptemp = -1; + $ctemp = -1; + $ptemp = -1; - if (cacti_sizeof($hosts)) { - $suppressGroups = false; - $function = 'renderSuppressgroups' . ucfirst(get_request_var('view')); + if (cacti_sizeof($hosts)) { + $suppressGroups = false; + $function = 'renderSuppressgroups' . ucfirst(get_request_var('view')); - if (function_exists($function)) { - $suppressGroups = $function(); - } + if (function_exists($function)) { + $suppressGroups = $function(); + } - $function = 'renderHeader' . ucfirst(get_request_var('view')); + $function = 'renderHeader' . ucfirst(get_request_var('view')); - if (function_exists($function)) { - // Call the custom render_header_ function - $result .= $function(); - $suppressGroups = true; - } + if (function_exists($function)) { + // Call the custom render_header_ function + $result .= $function(); + $suppressGroups = true; + } - foreach ($hosts as $index => $host) { - if (is_device_allowed($host['id'])) { - $host_ids[] = $host['id']; - } else { - unset($hosts[$index]); - } - } + foreach ($hosts as $index => $host) { + if (is_device_allowed($host['id'])) { + $host_ids[] = $host['id']; + } else { + unset($hosts[$index]); + } + } - // Determine the correct width of the cell - $maxlen = 10; + // Determine the correct width of the cell + $maxlen = 10; - if (get_request_var('view') == 'default') { - $maxlen = db_fetch_cell('SELECT MAX(LENGTH(description)) + if (get_request_var('view') == 'default') { + $maxlen = db_fetch_cell('SELECT MAX(LENGTH(description)) FROM host AS h WHERE id IN (' . implode(',', $host_ids) . ')'); - } - $maxlen = getMonitorTrimLength($maxlen); + } + $maxlen = getMonitorTrimLength($maxlen); - $class = get_request_var('size'); - $csuffix = get_request_var('view'); + $class = get_request_var('size'); + $csuffix = get_request_var('view'); - if ($csuffix == 'default') { - $csuffix = ''; - } + if ($csuffix == 'default') { + $csuffix = ''; + } - foreach ($hosts as $host) { - $ctemp = $host['site_id']; + foreach ($hosts as $host) { + $ctemp = $host['site_id']; - if (!$suppressGroups) { - if ($ctemp != $ptemp && $ptemp > 0) { - $result .= ''; - } + if (!$suppressGroups) { + if ($ctemp != $ptemp && $ptemp > 0) { + $result .= ''; + } - if ($ctemp != $ptemp) { - $result .= "
+ if ($ctemp != $ptemp) { + $result .= "
"; - } - } + } + } - $result .= renderHost($host, true, $maxlen); + $result .= renderHost($host, true, $maxlen); - if ($ctemp != $ptemp) { - $ptemp = $ctemp; - } - } + if ($ctemp != $ptemp) { + $ptemp = $ctemp; + } + } - if ($ptemp == $ctemp && !$suppressGroups) { - $result .= '
'; - } + if ($ptemp == $ctemp && !$suppressGroups) { + $result .= '
'; + } - $function = 'renderFooter' . ucfirst(get_request_var('view')); + $function = 'renderFooter' . ucfirst(get_request_var('view')); - if (function_exists($function)) { - // Call the custom render_footer_ function - $result .= $function(); - } - } + if (function_exists($function)) { + // Call the custom render_footer_ function + $result .= $function(); + } + } - return $result; + return $result; } /** @@ -255,42 +253,41 @@ function renderSite(): string * * @return string */ -function renderTemplate(): string -{ - global $maxchars; +function renderTemplate(): string { + global $maxchars; - $result = ''; + $result = ''; - $sql_where = ''; - $sql_join = ''; - $sql_limit = ''; + $sql_where = ''; + $sql_join = ''; + $sql_limit = ''; - $rows = get_request_var('rows'); + $rows = get_request_var('rows'); - if ($rows == '-1') { - $rows = read_user_setting('monitor_rows'); - } + if ($rows == '-1') { + $rows = read_user_setting('monitor_rows'); + } - if (!is_numeric($rows)) { - $rows = read_config_option('num_rows_table'); - } + if (!is_numeric($rows)) { + $rows = read_config_option('num_rows_table'); + } - renderWhereJoin($sql_where, $sql_join); + renderWhereJoin($sql_where, $sql_join); - $sql_limit = ' LIMIT ' . ($rows * (get_request_var('page') - 1)) . ',' . $rows; + $sql_limit = ' LIMIT ' . ($rows * (get_request_var('page') - 1)) . ',' . $rows; - if (get_request_var('template') > 0) { - $sql_where .= ($sql_where == '' ? '' : 'AND ') . 'ht.id = ' . get_request_var('template'); - } + if (get_request_var('template') > 0) { + $sql_where .= ($sql_where == '' ? '' : 'AND ') . 'ht.id = ' . get_request_var('template'); + } - $sql_template = 'INNER JOIN host_template AS ht ON h.host_template_id=ht.id '; + $sql_template = 'INNER JOIN host_template AS ht ON h.host_template_id=ht.id '; - if (get_request_var('template') == -2) { - $sql_where .= ($sql_where == '' ? '' : 'AND ') . 'ht.id IS NULL'; - $sql_template = 'LEFT JOIN host_template AS ht ON h.host_template_id=ht.id '; - } + if (get_request_var('template') == -2) { + $sql_where .= ($sql_where == '' ? '' : 'AND ') . 'ht.id IS NULL'; + $sql_template = 'LEFT JOIN host_template AS ht ON h.host_template_id=ht.id '; + } - $hosts = db_fetch_assoc("SELECT DISTINCT + $hosts = db_fetch_assoc("SELECT DISTINCT h.*, ht.name AS host_template_name FROM host AS h $sql_template @@ -299,88 +296,88 @@ function renderTemplate(): string ORDER BY ht.name, h.description $sql_limit"); - $ctemp = -1; - $ptemp = -1; + $ctemp = -1; + $ptemp = -1; - if (cacti_sizeof($hosts)) { - $suppressGroups = false; - $function = 'renderSuppressgroups' . ucfirst(get_request_var('view')); + if (cacti_sizeof($hosts)) { + $suppressGroups = false; + $function = 'renderSuppressgroups' . ucfirst(get_request_var('view')); - if (function_exists($function)) { - $suppressGroups = $function(); - } + if (function_exists($function)) { + $suppressGroups = $function(); + } - $function = 'renderHeader' . ucfirst(get_request_var('view')); + $function = 'renderHeader' . ucfirst(get_request_var('view')); - if (function_exists($function)) { - // Call the custom render_header_ function - $result .= $function(); - $suppressGroups = true; - } + if (function_exists($function)) { + // Call the custom render_header_ function + $result .= $function(); + $suppressGroups = true; + } - foreach ($hosts as $index => $host) { - if (is_device_allowed($host['id'])) { - $host_ids[] = $host['id']; - } else { - unset($hosts[$index]); - } - } + foreach ($hosts as $index => $host) { + if (is_device_allowed($host['id'])) { + $host_ids[] = $host['id']; + } else { + unset($hosts[$index]); + } + } - // Determine the correct width of the cell - $maxlen = 10; + // Determine the correct width of the cell + $maxlen = 10; - if (get_request_var('view') == 'default') { - $maxlen = db_fetch_cell('SELECT MAX(LENGTH(description)) + if (get_request_var('view') == 'default') { + $maxlen = db_fetch_cell('SELECT MAX(LENGTH(description)) FROM host AS h WHERE id IN (' . implode(',', $host_ids) . ')'); - } - $maxlen = getMonitorTrimLength($maxlen); + } + $maxlen = getMonitorTrimLength($maxlen); - $class = get_request_var('size'); - $csuffix = get_request_var('view'); + $class = get_request_var('size'); + $csuffix = get_request_var('view'); - if ($csuffix == 'default') { - $csuffix = ''; - } + if ($csuffix == 'default') { + $csuffix = ''; + } - foreach ($hosts as $host) { - $ctemp = $host['host_template_id']; + foreach ($hosts as $host) { + $ctemp = $host['host_template_id']; - if (!$suppressGroups) { - if ($ctemp != $ptemp && $ptemp > 0) { - $result .= ''; - } + if (!$suppressGroups) { + if ($ctemp != $ptemp && $ptemp > 0) { + $result .= ''; + } - if ($ctemp != $ptemp) { - $result .= "
+ if ($ctemp != $ptemp) { + $result .= "
"; - } - } + } + } - $result .= renderHost($host, true, $maxlen); + $result .= renderHost($host, true, $maxlen); - if ($ctemp != $ptemp) { - $ptemp = $ctemp; - } - } + if ($ctemp != $ptemp) { + $ptemp = $ctemp; + } + } - if ($ptemp == $ctemp && !$suppressGroups) { - $result .= '
'; - } + if ($ptemp == $ctemp && !$suppressGroups) { + $result .= '
'; + } - $function = 'renderFooter' . ucfirst(get_request_var('view')); + $function = 'renderFooter' . ucfirst(get_request_var('view')); - if (function_exists($function)) { - // Call the custom render_footer_ function - $result .= $function(); - } - } + if (function_exists($function)) { + // Call the custom render_footer_ function + $result .= $function(); + } + } - return $result; + return $result; } /** @@ -390,19 +387,18 @@ function renderTemplate(): string * * @return array{array, array} */ -function monitorFilterAllowedHosts(array $hosts): array -{ - $host_ids = []; - - foreach ($hosts as $index => $host) { - if (is_device_allowed($host['id'])) { - $host_ids[] = $host['id']; - } else { - unset($hosts[$index]); - } - } - - return [array_values($hosts), $host_ids]; +function monitorFilterAllowedHosts(array $hosts): array { + $host_ids = []; + + foreach ($hosts as $index => $host) { + if (is_device_allowed($host['id'])) { + $host_ids[] = $host['id']; + } else { + unset($hosts[$index]); + } + } + + return [array_values($hosts), $host_ids]; } /** @@ -410,20 +406,19 @@ function monitorFilterAllowedHosts(array $hosts): array * * @return int */ -function monitorGetTreeRenderMaxLength(): int -{ - $maxlen = 10; +function monitorGetTreeRenderMaxLength(): int { + $maxlen = 10; - if (get_request_var('view') == 'default') { - $maxlen = db_fetch_cell("SELECT MAX(LENGTH(description)) + if (get_request_var('view') == 'default') { + $maxlen = db_fetch_cell("SELECT MAX(LENGTH(description)) FROM host AS h INNER JOIN graph_tree_items AS gti ON gti.host_id = h.id WHERE disabled = '' AND deleted = ''"); - } + } - return getMonitorTrimLength($maxlen); + return getMonitorTrimLength($maxlen); } /** @@ -433,30 +428,29 @@ function monitorGetTreeRenderMaxLength(): int * * @return array */ -function monitorBuildTreeTitles(array $branchWhost): array -{ - $titles = []; - $ptree = ''; - - foreach ($branchWhost as $b) { - if ($ptree != $b['graph_tree_id']) { - $titles[$b['graph_tree_id'] . ':0'] = __('Root Branch', 'monitor'); - $ptree = $b['graph_tree_id']; - } - - if ($b['parent'] > 0) { - $titles[$b['graph_tree_id'] . ':' . $b['parent']] = db_fetch_cell_prepared( - 'SELECT title +function monitorBuildTreeTitles(array $branchWhost): array { + $titles = []; + $ptree = ''; + + foreach ($branchWhost as $b) { + if ($ptree != $b['graph_tree_id']) { + $titles[$b['graph_tree_id'] . ':0'] = __('Root Branch', 'monitor'); + $ptree = $b['graph_tree_id']; + } + + if ($b['parent'] > 0) { + $titles[$b['graph_tree_id'] . ':' . $b['parent']] = db_fetch_cell_prepared( + 'SELECT title FROM graph_tree_items WHERE id = ? AND graph_tree_id = ? ORDER BY position', - [$b['parent'], $b['graph_tree_id']] - ); - } - } + [$b['parent'], $b['graph_tree_id']] + ); + } + } - return $titles; + return $titles; } /** @@ -467,20 +461,19 @@ function monitorBuildTreeTitles(array $branchWhost): array * * @return string */ -function monitorRenderTreeTitleSections(array $titles, int $maxlen): string -{ - $result = ''; - $ptree = ''; +function monitorRenderTreeTitleSections(array $titles, int $maxlen): string { + $result = ''; + $ptree = ''; - foreach ($titles as $index => $title) { - [$graph_tree_id, $parent] = explode(':', $index); - $oid = $parent; + foreach ($titles as $index => $title) { + [$graph_tree_id, $parent] = explode(':', $index); + $oid = $parent; - $sql_where = ''; - $sql_join = ''; - renderWhereJoin($sql_where, $sql_join); + $sql_where = ''; + $sql_join = ''; + renderWhereJoin($sql_where, $sql_join); - $hosts_sql = "SELECT h.*, IFNULL(s.name,' " . __('Non-Site Device', 'monitor') . " ') AS site_name + $hosts_sql = "SELECT h.*, IFNULL(s.name,' " . __('Non-Site Device', 'monitor') . " ') AS site_name FROM host AS h LEFT JOIN sites AS s ON h.site_id = s.id @@ -493,21 +486,21 @@ function monitorRenderTreeTitleSections(array $titles, int $maxlen): string GROUP BY h.id ORDER BY gti.position"; - $hosts = db_fetch_assoc_prepared($hosts_sql, [$oid, $graph_tree_id]); + $hosts = db_fetch_assoc_prepared($hosts_sql, [$oid, $graph_tree_id]); - $tree_name = db_fetch_cell_prepared( - 'SELECT name + $tree_name = db_fetch_cell_prepared( + 'SELECT name FROM graph_tree WHERE id = ?', - [$graph_tree_id] - ); + [$graph_tree_id] + ); - if ($ptree != $tree_name) { - if ($ptree != '') { - $result .= ''; - } + if ($ptree != $tree_name) { + if ($ptree != '') { + $result .= ''; + } - $result .= "
+ $result .= "
@@ -515,29 +508,29 @@ function monitorRenderTreeTitleSections(array $titles, int $maxlen): string
"; - $ptree = $tree_name; - } + $ptree = $tree_name; + } - if (!cacti_sizeof($hosts)) { - continue; - } + if (!cacti_sizeof($hosts)) { + continue; + } - [$hosts] = monitorFilterAllowedHosts($hosts); + [$hosts] = monitorFilterAllowedHosts($hosts); - if (!cacti_sizeof($hosts)) { - continue; - } + if (!cacti_sizeof($hosts)) { + continue; + } - $result .= "
"; + $result .= "
"; - foreach ($hosts as $host) { - $result .= renderHost($host, true, $maxlen); - } + foreach ($hosts as $host) { + $result .= renderHost($host, true, $maxlen); + } - $result .= '
'; - } + $result .= '
'; + } - return $result; + return $result; } /** @@ -545,51 +538,50 @@ function monitorRenderTreeTitleSections(array $titles, int $maxlen): string * * @return string */ -function monitorRenderNonTreeSection(): string -{ - $result = ''; +function monitorRenderNonTreeSection(): string { + $result = ''; - if (get_request_var('tree') >= 0) { - return $result; - } + if (get_request_var('tree') >= 0) { + return $result; + } - $hosts = getHostNonTreeArray(); + $hosts = getHostNonTreeArray(); - if (!cacti_sizeof($hosts)) { - return $result; - } + if (!cacti_sizeof($hosts)) { + return $result; + } - [$hosts, $host_ids] = monitorFilterAllowedHosts($hosts); + [$hosts, $host_ids] = monitorFilterAllowedHosts($hosts); - if (!cacti_sizeof($hosts)) { - return $result; - } + if (!cacti_sizeof($hosts)) { + return $result; + } - $maxlen = 10; + $maxlen = 10; - if (get_request_var('view') == 'default' && cacti_sizeof($host_ids)) { - $maxlen = db_fetch_cell('SELECT MAX(LENGTH(description)) + if (get_request_var('view') == 'default' && cacti_sizeof($host_ids)) { + $maxlen = db_fetch_cell('SELECT MAX(LENGTH(description)) FROM host AS h WHERE id IN (' . implode(',', $host_ids) . ") AND h.deleted = ''"); - } + } - $maxlen = getMonitorTrimLength($maxlen); + $maxlen = getMonitorTrimLength($maxlen); - $result .= "
+ $result .= "
"; - foreach ($hosts as $leaf) { - $result .= renderHost($leaf, true, $maxlen); - } + foreach ($hosts as $leaf) { + $result .= renderHost($leaf, true, $maxlen); + } - $result .= '
'; + $result .= '
'; - return $result; + return $result; } /** @@ -597,42 +589,42 @@ function monitorRenderNonTreeSection(): string * * @return string */ -function renderTree(): string -{ - $result = ''; - - if (get_request_var('tree') > 0) { - $sql_where = 'gt.id=' . get_request_var('tree'); - } else { - $sql_where = ''; - } - - if (get_request_var('tree') != -2) { - $tree_list = get_allowed_trees(false, false, $sql_where, 'sequence'); - } else { - $tree_list = []; - } - - $function = 'renderHeader' . ucfirst(get_request_var('view')); - - if (function_exists($function)) { - $hosts = []; - - // Call the custom render_header_ function - $result .= $function(); - } - - if (cacti_sizeof($tree_list)) { - $tree_ids = []; - foreach ($tree_list as $tree) { - $tree_ids[$tree['id']] = $tree['id']; - } - - $sql_where = ''; - $sql_join = ''; - renderWhereJoin($sql_where, $sql_join); - - $branchWhost = db_fetch_assoc("SELECT DISTINCT gti.graph_tree_id, gti.parent +function renderTree(): string { + $result = ''; + + if (get_request_var('tree') > 0) { + $sql_where = 'gt.id=' . get_request_var('tree'); + } else { + $sql_where = ''; + } + + if (get_request_var('tree') != -2) { + $tree_list = get_allowed_trees(false, false, $sql_where, 'sequence'); + } else { + $tree_list = []; + } + + $function = 'renderHeader' . ucfirst(get_request_var('view')); + + if (function_exists($function)) { + $hosts = []; + + // Call the custom render_header_ function + $result .= $function(); + } + + if (cacti_sizeof($tree_list)) { + $tree_ids = []; + + foreach ($tree_list as $tree) { + $tree_ids[$tree['id']] = $tree['id']; + } + + $sql_where = ''; + $sql_join = ''; + renderWhereJoin($sql_where, $sql_join); + + $branchWhost = db_fetch_assoc("SELECT DISTINCT gti.graph_tree_id, gti.parent FROM graph_tree_items AS gti INNER JOIN graph_tree AS gt ON gt.id = gti.graph_tree_id @@ -644,24 +636,24 @@ function renderTree(): string AND gti.graph_tree_id IN (" . implode(',', $tree_ids) . ') ORDER BY gt.sequence, gti.position'); - if (cacti_sizeof($branchWhost)) { - $titles = monitorBuildTreeTitles($branchWhost); - $result .= monitorRenderTreeTitleSections($titles, monitorGetTreeRenderMaxLength()); - } + if (cacti_sizeof($branchWhost)) { + $titles = monitorBuildTreeTitles($branchWhost); + $result .= monitorRenderTreeTitleSections($titles, monitorGetTreeRenderMaxLength()); + } - $result .= '
'; - } + $result .= '
'; + } - $result .= monitorRenderNonTreeSection(); + $result .= monitorRenderNonTreeSection(); - $function = 'renderFooter' . ucfirst(get_request_var('view')); + $function = 'renderFooter' . ucfirst(get_request_var('view')); - if (function_exists($function)) { - // Call the custom render_footer_ function - $result .= $function(); - } + if (function_exists($function)) { + // Call the custom render_footer_ function + $result .= $function(); + } - return $result; + return $result; } /** @@ -672,30 +664,29 @@ function renderTree(): string * * @return int */ -function getHostStatus(array $host, bool $real = false): int -{ - global $thold_hosts, $iclasses; - - // If the host has been muted, show the muted Icon - if ($host['status'] != 1 && in_array($host['id'], $thold_hosts, true)) { - $host['status'] = 4; - } - - if (in_array($host['id'], $_SESSION['monitor_muted_hosts'], true) && $host['status'] == 1) { - $host['status'] = 5; - } elseif (in_array($host['id'], $_SESSION['monitor_muted_hosts'], true) && $host['status'] == 4) { - $host['status'] = 9; - } elseif ($host['status'] == 3) { - if ($host['cur_time'] > $host['monitor_alert'] && !empty($host['monitor_alert'])) { - $host['status'] = 8; - } elseif ($host['cur_time'] > $host['monitor_warn'] && !empty($host['monitor_warn'])) { - $host['status'] = 7; - } - } - - // If wanting the real status, or the status is already known - // return the real status, otherwise default to unknown - return ($real || array_key_exists($host['status'], $iclasses)) ? $host['status'] : 0; +function getHostStatus(array $host, bool $real = false): int { + global $thold_hosts, $iclasses; + + // If the host has been muted, show the muted Icon + if ($host['status'] != 1 && in_array($host['id'], $thold_hosts, true)) { + $host['status'] = 4; + } + + if (in_array($host['id'], $_SESSION['monitor_muted_hosts'], true) && $host['status'] == 1) { + $host['status'] = 5; + } elseif (in_array($host['id'], $_SESSION['monitor_muted_hosts'], true) && $host['status'] == 4) { + $host['status'] = 9; + } elseif ($host['status'] == 3) { + if ($host['cur_time'] > $host['monitor_alert'] && !empty($host['monitor_alert'])) { + $host['status'] = 8; + } elseif ($host['cur_time'] > $host['monitor_warn'] && !empty($host['monitor_warn'])) { + $host['status'] = 7; + } + } + + // If wanting the real status, or the status is already known + // return the real status, otherwise default to unknown + return ($real || array_key_exists($host['status'], $iclasses)) ? $host['status'] : 0; } /** @@ -705,15 +696,14 @@ function getHostStatus(array $host, bool $real = false): int * * @return string */ -function getHostStatusDescription(int|string $status): string -{ - global $icolorsdisplay; - - if (array_key_exists($status, $icolorsdisplay)) { - return $icolorsdisplay[$status]; - } else { - return __('Unknown', 'monitor') . " ($status)"; - } +function getHostStatusDescription(int|string $status): string { + global $icolorsdisplay; + + if (array_key_exists($status, $icolorsdisplay)) { + return $icolorsdisplay[$status]; + } else { + return __('Unknown', 'monitor') . " ($status)"; + } } /** @@ -725,64 +715,63 @@ function getHostStatusDescription(int|string $status): string * * @return string|null */ -function renderHost(array $host, bool $float = true, int $maxlen = 10): ?string -{ - global $thold_hosts, $config, $icolorsdisplay, $iclasses, $classes, $maxchars, $mon_zoom_state; - - // throw out tree root items - if (array_key_exists('name', $host)) { - return null; - } - - if ($host['id'] <= 0) { - return null; - } - - $host['anchor'] = $config['url_path'] . 'graph_view.php?action=preview&reset=1&host_id=' . $host['id']; - - if ($host['status'] == 3 && array_key_exists($host['id'], $thold_hosts)) { - $host['status'] = 4; - $host['anchor'] = $config['url_path'] . 'plugins/thold/thold_graph.php?action=thold&reset=true&status=1&host_id=' . $host['id']; - } - - $host['real_status'] = getHostStatus($host, true); - $host['status'] = getHostStatus($host); - $host['iclass'] = $iclasses[$host['status']]; - - $function = 'renderHost' . ucfirst(get_request_var('view')); - - if (function_exists($function)) { - // Call the custom render_host_ function - $result = $function($host); - } else { - $iclass = getStatusIcon($host['status'], $host['monitor_icon']); - $fclass = get_request_var('size'); - - $monitor_times = read_user_setting('monitor_uptime'); - $monitor_time_html = ''; - - if ($host['status'] <= 2 || $host['status'] == 5) { - if ($mon_zoom_state) { - $fclass = 'monitor_errorzoom'; - } - $tis = get_timeinstate($host); - - if ($monitor_times == 'on') { - $monitor_time_html = "
$tis"; - } - $result = "

" . title_trim(html_escape($host['description']), $maxlen) . "$monitor_time_html
"; - } else { - $tis = get_uptime($host); - - if ($monitor_times == 'on') { - $monitor_time_html = "
$tis
"; - } - - $result = "

" . title_trim(html_escape($host['description']), $maxlen) . "$monitor_time_html
"; - } - } - - return $result; +function renderHost(array $host, bool $float = true, int $maxlen = 10): ?string { + global $thold_hosts, $config, $icolorsdisplay, $iclasses, $classes, $maxchars, $mon_zoom_state; + + // throw out tree root items + if (array_key_exists('name', $host)) { + return null; + } + + if ($host['id'] <= 0) { + return null; + } + + $host['anchor'] = $config['url_path'] . 'graph_view.php?action=preview&reset=1&host_id=' . $host['id']; + + if ($host['status'] == 3 && array_key_exists($host['id'], $thold_hosts)) { + $host['status'] = 4; + $host['anchor'] = $config['url_path'] . 'plugins/thold/thold_graph.php?action=thold&reset=true&status=1&host_id=' . $host['id']; + } + + $host['real_status'] = getHostStatus($host, true); + $host['status'] = getHostStatus($host); + $host['iclass'] = $iclasses[$host['status']]; + + $function = 'renderHost' . ucfirst(get_request_var('view')); + + if (function_exists($function)) { + // Call the custom render_host_ function + $result = $function($host); + } else { + $iclass = getStatusIcon($host['status'], $host['monitor_icon']); + $fclass = get_request_var('size'); + + $monitor_times = read_user_setting('monitor_uptime'); + $monitor_time_html = ''; + + if ($host['status'] <= 2 || $host['status'] == 5) { + if ($mon_zoom_state) { + $fclass = 'monitor_errorzoom'; + } + $tis = get_timeinstate($host); + + if ($monitor_times == 'on') { + $monitor_time_html = "
$tis"; + } + $result = "

" . title_trim(html_escape($host['description']), $maxlen) . "$monitor_time_html
"; + } else { + $tis = get_uptime($host); + + if ($monitor_times == 'on') { + $monitor_time_html = "
$tis
"; + } + + $result = "

" . title_trim(html_escape($host['description']), $maxlen) . "$monitor_time_html
"; + } + } + + return $result; } /** @@ -793,23 +782,22 @@ function renderHost(array $host, bool $float = true, int $maxlen = 10): ?string * * @return string */ -function getStatusIcon(int $status, string $icon): string -{ - global $fa_icons; - - if (($status == 1 || ($status == 4 && get_request_var('status') > 0)) && read_user_setting('monitor_sound') == 'First Orders Suite.mp3') { - return 'fab fa-first-order fa-spin mon_icon'; - } - - if ($icon != '' && array_key_exists($icon, $fa_icons)) { - if (isset($fa_icons[$icon]['class'])) { - return $fa_icons[$icon]['class'] . ' mon_icon'; - } else { - return "fa fa-$icon mon_icon"; - } - } else { - return 'fa fa-server' . ' mon_icon'; - } +function getStatusIcon(int $status, string $icon): string { + global $fa_icons; + + if (($status == 1 || ($status == 4 && get_request_var('status') > 0)) && read_user_setting('monitor_sound') == 'First Orders Suite.mp3') { + return 'fab fa-first-order fa-spin mon_icon'; + } + + if ($icon != '' && array_key_exists($icon, $fa_icons)) { + if (isset($fa_icons[$icon]['class'])) { + return $fa_icons[$icon]['class'] . ' mon_icon'; + } else { + return "fa fa-$icon mon_icon"; + } + } else { + return 'fa fa-server' . ' mon_icon'; + } } /** @@ -820,35 +808,33 @@ function getStatusIcon(int $status, string $icon): string * * @return string */ -function monitorPrintHostTime(int|string $status_time, bool $seconds = false): string -{ - // If the host is down, make a downtime since message - $dt = ''; - - if (is_numeric($status_time)) { - $sfd = round($status_time / 100, 0); - } else { - $sfd = time() - strtotime($status_time); - } - $dt_d = floor($sfd / 86400); - $dt_h = floor(($sfd - ($dt_d * 86400)) / 3600); - $dt_m = floor(($sfd - ($dt_d * 86400) - ($dt_h * 3600)) / 60); - $dt_s = $sfd - ($dt_d * 86400) - ($dt_h * 3600) - ($dt_m * 60); - - if ($dt_d > 0) { - $dt .= $dt_d . 'd:' . $dt_h . 'h:' . $dt_m . 'm' . ($seconds ? ':' . $dt_s . 's' : ''); - } elseif ($dt_h > 0) { - $dt .= $dt_h . 'h:' . $dt_m . 'm' . ($seconds ? ':' . $dt_s . 's' : ''); - } elseif ($dt_m > 0) { - $dt .= $dt_m . 'm' . ($seconds ? ':' . $dt_s . 's' : ''); - } else { - $dt .= ($seconds ? $dt_s . 's' : __('Just Up', 'monitor')); - } - - return $dt; +function monitorPrintHostTime(int|string $status_time, bool $seconds = false): string { + // If the host is down, make a downtime since message + $dt = ''; + + if (is_numeric($status_time)) { + $sfd = round($status_time / 100, 0); + } else { + $sfd = time() - strtotime($status_time); + } + $dt_d = floor($sfd / 86400); + $dt_h = floor(($sfd - ($dt_d * 86400)) / 3600); + $dt_m = floor(($sfd - ($dt_d * 86400) - ($dt_h * 3600)) / 60); + $dt_s = $sfd - ($dt_d * 86400) - ($dt_h * 3600) - ($dt_m * 60); + + if ($dt_d > 0) { + $dt .= $dt_d . 'd:' . $dt_h . 'h:' . $dt_m . 'm' . ($seconds ? ':' . $dt_s . 's' : ''); + } elseif ($dt_h > 0) { + $dt .= $dt_h . 'h:' . $dt_m . 'm' . ($seconds ? ':' . $dt_s . 's' : ''); + } elseif ($dt_m > 0) { + $dt .= $dt_m . 'm' . ($seconds ? ':' . $dt_s . 's' : ''); + } else { + $dt .= ($seconds ? $dt_s . 's' : __('Just Up', 'monitor')); + } + + return $dt; } - /** * Trim monitor text fields for quote and whitespace artifacts. * @@ -856,9 +842,8 @@ function monitorPrintHostTime(int|string $status_time, bool $seconds = false): s * * @return string */ -function monitorTrim(string $string): string -{ - return trim($string, "\"'\\ \n\t\r"); +function monitorTrim(string $string): string { + return trim($string, "\"'\\ \n\t\r"); } /** @@ -866,9 +851,8 @@ function monitorTrim(string $string): string * * @return string */ -function renderHeaderDefault(): string -{ - return "
"; +function renderHeaderDefault(): string { + return "
"; } /** @@ -876,9 +860,8 @@ function renderHeaderDefault(): string * * @return string */ -function renderHeaderNames(): string -{ - return ""; +function renderHeaderNames(): string { + return "
"; } /** @@ -886,9 +869,8 @@ function renderHeaderNames(): string * * @return string */ -function renderHeaderTiles(): string -{ - return renderHeaderDefault(); +function renderHeaderTiles(): string { + return renderHeaderDefault(); } /** @@ -896,9 +878,8 @@ function renderHeaderTiles(): string * * @return string */ -function renderHeaderTilesadt(): string -{ - return renderHeaderDefault(); +function renderHeaderTilesadt(): string { + return renderHeaderDefault(); } /** @@ -909,92 +890,91 @@ function renderHeaderTilesadt(): string * * @return string */ -function renderHeaderList(int $total_rows = 0, int $rows = 0): string -{ - $display_text = [ - 'hostname' => [ - 'display' => __('Hostname', 'monitor'), - 'sort' => 'ASC', - 'align' => 'left', 'tip' => __('Hostname of device', 'monitor') - ], - 'id' => [ - 'display' => __('ID', 'monitor'), - 'sort' => 'ASC', - 'align' => 'left' - ], - 'description' => [ - 'display' => __('Description', 'monitor'), - 'sort' => 'ASC', - 'align' => 'left' - ], - 'site_name' => [ - 'display' => __('Site', 'monitor'), - 'sort' => 'ASC', - 'align' => 'left' - ], - 'monitor_criticality' => [ - 'display' => __('Criticality', 'monitor'), - 'sort' => 'ASC', - 'align' => 'left' - ], - 'status' => [ - 'display' => __('Status', 'monitor'), - 'sort' => 'DESC', - 'align' => 'center' - ], - 'instate' => [ - 'display' => __('Length in Status', 'monitor'), - 'sort' => 'ASC', - 'align' => 'center' - ], - 'avg_time' => [ - 'display' => __('Averages', 'monitor'), - 'sort' => 'DESC', - 'align' => 'left' - ], - 'monitor_warn' => [ - 'display' => __('Warning', 'monitor'), - 'sort' => 'DESC', - 'align' => 'left' - ], - 'monitor_text' => [ - 'display' => __('Admin', 'monitor'), - 'sort' => 'ASC', - 'tip' => __('Monitor Text Column represents \'Admin\'', 'monitor'), - 'align' => 'left' - ], - 'notes' => [ - 'display' => __('Notes', 'monitor'), - 'sort' => 'ASC', - 'align' => 'left' - ], - 'availability' => [ - 'display' => __('Availability', 'monitor'), - 'sort' => 'DESC', - 'align' => 'right' - ], - 'status_fail_date' => [ - 'display' => __('Last Fail', 'monitor'), - 'sort' => 'DESC', - 'align' => 'right' - ], - ]; - - ob_start(); - - $nav = html_nav_bar('monitor.php?rfilter=' . get_request_var('rfilter'), MAX_DISPLAY_PAGES, get_request_var('page'), $rows, $total_rows, 12, __('Devices'), 'page', 'main'); - - html_start_box(__('Monitored Devices', 'monitor'), '100%', false, '3', 'center', ''); - - print $nav; - - html_header_sort($display_text, get_request_var('sort_column'), get_request_var('sort_direction'), false); - - $output = ob_get_contents(); - - ob_end_clean(); - - return $output; +function renderHeaderList(int $total_rows = 0, int $rows = 0): string { + $display_text = [ + 'hostname' => [ + 'display' => __('Hostname', 'monitor'), + 'sort' => 'ASC', + 'align' => 'left', 'tip' => __('Hostname of device', 'monitor') + ], + 'id' => [ + 'display' => __('ID', 'monitor'), + 'sort' => 'ASC', + 'align' => 'left' + ], + 'description' => [ + 'display' => __('Description', 'monitor'), + 'sort' => 'ASC', + 'align' => 'left' + ], + 'site_name' => [ + 'display' => __('Site', 'monitor'), + 'sort' => 'ASC', + 'align' => 'left' + ], + 'monitor_criticality' => [ + 'display' => __('Criticality', 'monitor'), + 'sort' => 'ASC', + 'align' => 'left' + ], + 'status' => [ + 'display' => __('Status', 'monitor'), + 'sort' => 'DESC', + 'align' => 'center' + ], + 'instate' => [ + 'display' => __('Length in Status', 'monitor'), + 'sort' => 'ASC', + 'align' => 'center' + ], + 'avg_time' => [ + 'display' => __('Averages', 'monitor'), + 'sort' => 'DESC', + 'align' => 'left' + ], + 'monitor_warn' => [ + 'display' => __('Warning', 'monitor'), + 'sort' => 'DESC', + 'align' => 'left' + ], + 'monitor_text' => [ + 'display' => __('Admin', 'monitor'), + 'sort' => 'ASC', + 'tip' => __('Monitor Text Column represents \'Admin\'', 'monitor'), + 'align' => 'left' + ], + 'notes' => [ + 'display' => __('Notes', 'monitor'), + 'sort' => 'ASC', + 'align' => 'left' + ], + 'availability' => [ + 'display' => __('Availability', 'monitor'), + 'sort' => 'DESC', + 'align' => 'right' + ], + 'status_fail_date' => [ + 'display' => __('Last Fail', 'monitor'), + 'sort' => 'DESC', + 'align' => 'right' + ], + ]; + + ob_start(); + + $nav = html_nav_bar('monitor.php?rfilter=' . get_request_var('rfilter'), MAX_DISPLAY_PAGES, get_request_var('page'), $rows, $total_rows, 12, __('Devices'), 'page', 'main'); + + html_start_box(__('Monitored Devices', 'monitor'), '100%', false, '3', 'center', ''); + + print $nav; + + html_header_sort($display_text, get_request_var('sort_column'), get_request_var('sort_direction'), false); + + $output = ob_get_contents(); + + ob_end_clean(); + + return $output; } /** @@ -1002,9 +982,8 @@ function renderHeaderList(int $total_rows = 0, int $rows = 0): string * * @return bool */ -function renderSuppressgroupsList(): bool -{ - return true; +function renderSuppressgroupsList(): bool { + return true; } /** @@ -1012,9 +991,8 @@ function renderSuppressgroupsList(): bool * * @return string */ -function renderFooterDefault(): string -{ - return ''; +function renderFooterDefault(): string { + return ''; } /** @@ -1022,15 +1000,14 @@ function renderFooterDefault(): string * * @return string */ -function renderFooterNames(): string -{ - $col = 7 - $_SESSION['names']; - - if ($col == 0) { - return '
'; - } else { - return ''; - } +function renderFooterNames(): string { + $col = 7 - $_SESSION['names']; + + if ($col == 0) { + return ''; + } else { + return ''; + } } /** @@ -1038,9 +1015,8 @@ function renderFooterNames(): string * * @return string */ -function renderFooterTiles(): string -{ - return renderFooterDefault(); +function renderFooterTiles(): string { + return renderFooterDefault(); } /** @@ -1048,9 +1024,8 @@ function renderFooterTiles(): string * * @return string */ -function renderFooterTilesadt(): string -{ - return renderFooterDefault(); +function renderFooterTilesadt(): string { + return renderFooterDefault(); } /** @@ -1061,23 +1036,22 @@ function renderFooterTilesadt(): string * * @return string */ -function renderFooterList(int $total_rows, int $rows): string -{ - ob_start(); +function renderFooterList(int $total_rows, int $rows): string { + ob_start(); - html_end_box(false); + html_end_box(false); - if ($total_rows > 0) { - $nav = html_nav_bar('monitor.php?rfilter=' . get_request_var('rfilter'), MAX_DISPLAY_PAGES, get_request_var('page'), $rows, $total_rows, 12, __('Devices'), 'page', 'main'); + if ($total_rows > 0) { + $nav = html_nav_bar('monitor.php?rfilter=' . get_request_var('rfilter'), MAX_DISPLAY_PAGES, get_request_var('page'), $rows, $total_rows, 12, __('Devices'), 'page', 'main'); - print $nav; - } + print $nav; + } - $output = ob_get_contents(); + $output = ob_get_contents(); - ob_end_clean(); + ob_end_clean(); - return $output; + return $output; } /** @@ -1087,80 +1061,79 @@ function renderFooterList(int $total_rows, int $rows): string * * @return string */ -function renderHostList(array $host): string -{ - global $criticalities, $iclasses; - - if ($host['status'] < 2 || $host['status'] == 5) { - $dt = get_timeinstate($host); - } elseif (strtotime($host['status_rec_date']) > 192800) { - $dt = get_timeinstate($host); - } else { - $dt = __('Never', 'monitor'); - } - - if ($host['status'] < 3 || $host['status'] == 5) { - $host_admin = $host['monitor_text']; - } else { - $host_admin = ''; - } - - if (isset($host['monitor_criticality']) && $host['monitor_criticality'] > 0) { - $host_crit = $criticalities[$host['monitor_criticality']]; - } else { - $host_crit = ''; - } - - if ($host['availability_method'] > 0) { - $host_avg = __('%d ms', $host['cur_time'], 'monitor') . ' / ' . __('%d ms', $host['avg_time'], 'monitor'); - } else { - $host_avg = __('N/A', 'monitor'); - } - - if (isset($host['monitor_warn']) && ($host['monitor_warn'] > 0 || $host['monitor_alert'] > 0)) { - $host_warn = __('%0.2d ms', $host['monitor_warn'], 'monitor') . ' / ' . __('%0.2d ms', $host['monitor_alert'], 'monitor'); - } else { - $host_warn = ''; - } - - if (strtotime($host['status_fail_date']) < 86400) { - $host['status_fail_date'] = __('Never', 'monitor'); - } - - $host_datefail = $host['status_fail_date']; - - $iclass = $iclasses[$host['status']]; - $sdisplay = getHostStatusDescription($host['real_status']); - - $row_class = "{$iclass}Full"; - - ob_start(); - - print ""; - - $url = $host['anchor']; - - form_selectable_cell(filter_value($host['hostname'], '', $url), $host['id'], '', 'left'); - form_selectable_cell($host['id'], $host['id'], '', 'left'); - form_selectable_cell($host['description'], $host['id'], '', 'left'); - form_selectable_cell($host['site_name'], $host['id'], '', 'left'); - form_selectable_cell($host_crit, $host['id'], '', 'left'); - form_selectable_cell($sdisplay, $host['id'], '', 'center'); - form_selectable_cell($dt, $host['id'], '', 'center'); - form_selectable_cell($host_avg, $host['id'], '', 'left'); - form_selectable_cell($host_warn, $host['id'], '', 'left'); - form_selectable_cell($host_admin, $host['id'], '', 'white-space:pre-wrap;text-align:left'); - form_selectable_cell(str_replace(["\n", "\r"], [' ', ''], $host['notes']), $host['id'], '', 'white-space:pre-wrap;text-align:left'); - form_selectable_cell(round($host['availability'], 2) . ' %', $host['id'], '', 'right'); - form_selectable_cell($host_datefail, $host['id'], '', 'right'); - - form_end_row(); - - $result = ob_get_contents(); - - ob_end_clean(); - - return $result; +function renderHostList(array $host): string { + global $criticalities, $iclasses; + + if ($host['status'] < 2 || $host['status'] == 5) { + $dt = get_timeinstate($host); + } elseif (strtotime($host['status_rec_date']) > 192800) { + $dt = get_timeinstate($host); + } else { + $dt = __('Never', 'monitor'); + } + + if ($host['status'] < 3 || $host['status'] == 5) { + $host_admin = $host['monitor_text']; + } else { + $host_admin = ''; + } + + if (isset($host['monitor_criticality']) && $host['monitor_criticality'] > 0) { + $host_crit = $criticalities[$host['monitor_criticality']]; + } else { + $host_crit = ''; + } + + if ($host['availability_method'] > 0) { + $host_avg = __('%d ms', $host['cur_time'], 'monitor') . ' / ' . __('%d ms', $host['avg_time'], 'monitor'); + } else { + $host_avg = __('N/A', 'monitor'); + } + + if (isset($host['monitor_warn']) && ($host['monitor_warn'] > 0 || $host['monitor_alert'] > 0)) { + $host_warn = __('%0.2d ms', $host['monitor_warn'], 'monitor') . ' / ' . __('%0.2d ms', $host['monitor_alert'], 'monitor'); + } else { + $host_warn = ''; + } + + if (strtotime($host['status_fail_date']) < 86400) { + $host['status_fail_date'] = __('Never', 'monitor'); + } + + $host_datefail = $host['status_fail_date']; + + $iclass = $iclasses[$host['status']]; + $sdisplay = getHostStatusDescription($host['real_status']); + + $row_class = "{$iclass}Full"; + + ob_start(); + + print ""; + + $url = $host['anchor']; + + form_selectable_cell(filter_value($host['hostname'], '', $url), $host['id'], '', 'left'); + form_selectable_cell($host['id'], $host['id'], '', 'left'); + form_selectable_cell($host['description'], $host['id'], '', 'left'); + form_selectable_cell($host['site_name'], $host['id'], '', 'left'); + form_selectable_cell($host_crit, $host['id'], '', 'left'); + form_selectable_cell($sdisplay, $host['id'], '', 'center'); + form_selectable_cell($dt, $host['id'], '', 'center'); + form_selectable_cell($host_avg, $host['id'], '', 'left'); + form_selectable_cell($host_warn, $host['id'], '', 'left'); + form_selectable_cell($host_admin, $host['id'], '', 'white-space:pre-wrap;text-align:left'); + form_selectable_cell(str_replace(["\n", "\r"], [' ', ''], $host['notes']), $host['id'], '', 'white-space:pre-wrap;text-align:left'); + form_selectable_cell(round($host['availability'], 2) . ' %', $host['id'], '', 'right'); + form_selectable_cell($host_datefail, $host['id'], '', 'right'); + + form_end_row(); + + $result = ob_get_contents(); + + ob_end_clean(); + + return $result; } /** @@ -1170,32 +1143,31 @@ function renderHostList(array $host): string * * @return string */ -function renderHostNames(array $host): string -{ - $fclass = get_request_var('size'); +function renderHostNames(array $host): string { + $fclass = get_request_var('size'); - $result = ''; + $result = ''; - $maxlen = getMonitorTrimLength(100); + $maxlen = getMonitorTrimLength(100); - if ($_SESSION['names'] == 0) { - $result .= ''; - } + if ($_SESSION['names'] == 0) { + $result .= ''; + } - if ($host['status'] <= 2 || $host['status'] == 5) { - $result .= "" . title_trim(html_escape($host['description']), $maxlen) . ''; - } else { - $result .= "" . title_trim(html_escape($host['description']), $maxlen) . ''; - } + if ($host['status'] <= 2 || $host['status'] == 5) { + $result .= "" . title_trim(html_escape($host['description']), $maxlen) . ''; + } else { + $result .= "" . title_trim(html_escape($host['description']), $maxlen) . ''; + } - $_SESSION['names']++; + $_SESSION['names']++; - if ($_SESSION['names'] > 7) { - $result .= ''; - $_SESSION['names'] = 0; - } + if ($_SESSION['names'] > 7) { + $result .= ''; + $_SESSION['names'] = 0; + } - return $result; + return $result; } /** @@ -1205,12 +1177,11 @@ function renderHostNames(array $host): string * * @return string */ -function renderHostTiles(array $host): string -{ - $class = getStatusIcon($host['status'], $host['monitor_icon']); - $fclass = get_request_var('size'); +function renderHostTiles(array $host): string { + $class = getStatusIcon($host['status'], $host['monitor_icon']); + $fclass = get_request_var('size'); - return "
"; + return "
"; } /** @@ -1220,25 +1191,23 @@ function renderHostTiles(array $host): string * * @return string */ -function renderHostTilesadt(array $host): string -{ - $tis = ''; +function renderHostTilesadt(array $host): string { + $tis = ''; - $class = getStatusIcon($host['status'], $host['monitor_icon']); - $fclass = get_request_var('size'); + $class = getStatusIcon($host['status'], $host['monitor_icon']); + $fclass = get_request_var('size'); - if ($host['status'] < 2 || $host['status'] == 5) { - $tis = get_timeinstate($host); + if ($host['status'] < 2 || $host['status'] == 5) { + $tis = get_timeinstate($host); - return ""; - } else { - $tis = get_uptime($host); + return ""; + } else { + $tis = get_uptime($host); - return ""; - } + return ""; + } } - /** * Apply monitor trim setting to a computed source field length. * @@ -1246,23 +1215,22 @@ function renderHostTilesadt(array $host): string * * @return int */ -function getMonitorTrimLength(int $fieldlen): int -{ - global $maxchars; +function getMonitorTrimLength(int $fieldlen): int { + global $maxchars; - if (get_request_var('view') == 'default' || get_request_var('view') == 'names') { - $maxlen = $maxchars; + if (get_request_var('view') == 'default' || get_request_var('view') == 'names') { + $maxlen = $maxchars; - if (get_request_var('trim') < 0) { - $maxlen = 4000; - } elseif (get_request_var('trim') > 0) { - $maxlen = get_request_var('trim'); - } + if (get_request_var('trim') < 0) { + $maxlen = 4000; + } elseif (get_request_var('trim') > 0) { + $maxlen = get_request_var('trim'); + } - if ($fieldlen > $maxlen) { - $fieldlen = $maxlen; - } - } + if ($fieldlen > $maxlen) { + $fieldlen = $maxlen; + } + } - return $fieldlen; + return $fieldlen; } diff --git a/poller_functions.php b/poller_functions.php index b5e1929..ddb8568 100644 --- a/poller_functions.php +++ b/poller_functions.php @@ -1,6 +1,6 @@ 0 && isset($notification_lists[$notify_list])) { - $emails = explode(',', $notification_lists[$notify_list]); - monitorAddEmails($reboot_emails, $emails, $host_id); - } +function monitorAddNotificationList(array &$reboot_emails, int|string|null $notify_list, int|string $host_id, array $notification_lists): void { + if ($notify_list !== null && $notify_list > 0 && isset($notification_lists[$notify_list])) { + $emails = explode(',', $notification_lists[$notify_list]); + monitorAddEmails($reboot_emails, $emails, $host_id); + } } /** @@ -66,11 +64,10 @@ function monitorAddNotificationList(array &$reboot_emails, int|string|null $noti * * @return array */ -function getAlertEmails(): array -{ - $alert_email = read_config_option('alert_email'); +function getAlertEmails(): array { + $alert_email = read_config_option('alert_email'); - return ($alert_email != '') ? explode(',', $alert_email) : []; + return ($alert_email != '') ? explode(',', $alert_email) : []; } /** @@ -80,21 +77,20 @@ function getAlertEmails(): array * * @return void */ -function purgeOrphanMonitorRows(string $table_name): void -{ - $removed_hosts = db_fetch_assoc("SELECT mu.host_id +function purgeOrphanMonitorRows(string $table_name): void { + $removed_hosts = db_fetch_assoc("SELECT mu.host_id FROM $table_name AS mu LEFT JOIN host AS h ON h.id = mu.host_id WHERE h.id IS NULL"); - if (cacti_sizeof($removed_hosts)) { - db_execute("DELETE mu + if (cacti_sizeof($removed_hosts)) { + db_execute("DELETE mu FROM $table_name AS mu LEFT JOIN host AS h ON h.id = mu.host_id WHERE h.id IS NULL"); - } + } } /** @@ -102,9 +98,8 @@ function purgeOrphanMonitorRows(string $table_name): void * * @return array */ -function getRebootedHosts(): array -{ - return db_fetch_assoc('SELECT h.id, h.description, +function getRebootedHosts(): array { + return db_fetch_assoc('SELECT h.id, h.description, h.hostname, h.snmp_sysUpTimeInstance, mu.uptime FROM host AS h LEFT JOIN plugin_monitor_uptime AS mu @@ -122,15 +117,14 @@ function getRebootedHosts(): array * * @return array */ -function getNotificationListsMap(): array -{ - return array_rekey( - db_fetch_assoc('SELECT id, emails +function getNotificationListsMap(): array { + return array_rekey( + db_fetch_assoc('SELECT id, emails FROM plugin_notification_lists ORDER BY id'), - 'id', - 'emails' - ); + 'id', + 'emails' + ); } /** @@ -143,36 +137,35 @@ function getNotificationListsMap(): array * * @return void */ -function addTholdRebootRecipients(array &$reboot_emails, int|string $host_id, array $alert_emails, array $notification_lists): void -{ - $notify = db_fetch_row_prepared( - 'SELECT thold_send_email, thold_host_email +function addTholdRebootRecipients(array &$reboot_emails, int|string $host_id, array $alert_emails, array $notification_lists): void { + $notify = db_fetch_row_prepared( + 'SELECT thold_send_email, thold_host_email FROM host WHERE id = ?', - [$host_id] - ); - - if (!cacti_sizeof($notify)) { - return; - } - - switch ($notify['thold_send_email']) { - case '1': - monitorAddEmails($reboot_emails, $alert_emails, $host_id); - - break; - case '2': - monitorAddNotificationList($reboot_emails, $notify['thold_host_email'], $host_id, $notification_lists); - - break; - case '3': - monitorAddEmails($reboot_emails, $alert_emails, $host_id); - monitorAddNotificationList($reboot_emails, $notify['thold_host_email'], $host_id, $notification_lists); - - break; - default: - break; - } + [$host_id] + ); + + if (!cacti_sizeof($notify)) { + return; + } + + switch ($notify['thold_send_email']) { + case '1': + monitorAddEmails($reboot_emails, $alert_emails, $host_id); + + break; + case '2': + monitorAddNotificationList($reboot_emails, $notify['thold_host_email'], $host_id, $notification_lists); + + break; + case '3': + monitorAddEmails($reboot_emails, $alert_emails, $host_id); + monitorAddNotificationList($reboot_emails, $notify['thold_host_email'], $host_id, $notification_lists); + + break; + default: + break; + } } /** @@ -183,29 +176,28 @@ function addTholdRebootRecipients(array &$reboot_emails, int|string $host_id, ar * * @return array */ -function buildRebootEmailMap(array $rebooted_hosts, array $alert_emails): array -{ - $reboot_emails = []; - $notification_lists = getNotificationListsMap(); - $monitor_list = read_config_option('monitor_list'); - $monitor_thold = read_config_option('monitor_reboot_thold'); - - foreach ($rebooted_hosts as $host) { - db_execute_prepared( - 'INSERT INTO plugin_monitor_reboot_history +function buildRebootEmailMap(array $rebooted_hosts, array $alert_emails): array { + $reboot_emails = []; + $notification_lists = getNotificationListsMap(); + $monitor_list = read_config_option('monitor_list'); + $monitor_thold = read_config_option('monitor_reboot_thold'); + + foreach ($rebooted_hosts as $host) { + db_execute_prepared( + 'INSERT INTO plugin_monitor_reboot_history (host_id, reboot_time) VALUES (?, ?)', - [$host['id'], date(MONITOR_DATE_TIME_FORMAT, time() - intval($host['snmp_sysUpTimeInstance']))] - ); + [$host['id'], date(MONITOR_DATE_TIME_FORMAT, time() - intval($host['snmp_sysUpTimeInstance']))] + ); - monitorAddNotificationList($reboot_emails, $monitor_list, $host['id'], $notification_lists); + monitorAddNotificationList($reboot_emails, $monitor_list, $host['id'], $notification_lists); - if ($monitor_thold == 'on') { - addTholdRebootRecipients($reboot_emails, $host['id'], $alert_emails, $notification_lists); - } - } + if ($monitor_thold == 'on') { + addTholdRebootRecipients($reboot_emails, $host['id'], $alert_emails, $notification_lists); + } + } - return $reboot_emails; + return $reboot_emails; } /** @@ -215,37 +207,36 @@ function buildRebootEmailMap(array $rebooted_hosts, array $alert_emails): array * * @return void */ -function sendRebootNotifications(array $reboot_emails): void -{ - $monitor_send_one_email = read_config_option('monitor_send_one_email'); +function sendRebootNotifications(array $reboot_emails): void { + $monitor_send_one_email = read_config_option('monitor_send_one_email'); - if (!cacti_sizeof($reboot_emails)) { - return; - } + if (!cacti_sizeof($reboot_emails)) { + return; + } - $all_hosts = []; - $to_email = ''; + $all_hosts = []; + $to_email = ''; - foreach ($reboot_emails as $email => $hosts) { - if ($email == '') { - monitorDebug('Unable to process reboot notification due to empty Email address.'); + foreach ($reboot_emails as $email => $hosts) { + if ($email == '') { + monitorDebug('Unable to process reboot notification due to empty Email address.'); - continue; - } + continue; + } - $to_email .= ($to_email != '' ? ',' : '') . $email; - $all_hosts = array_unique(array_merge($all_hosts, array_values($hosts))); + $to_email .= ($to_email != '' ? ',' : '') . $email; + $all_hosts = array_unique(array_merge($all_hosts, array_values($hosts))); - if ($monitor_send_one_email !== 'on') { - monitorDebug('Processing the Email address: ' . $email); - processRebootEmail($email, $hosts); - } - } + if ($monitor_send_one_email !== 'on') { + monitorDebug('Processing the Email address: ' . $email); + processRebootEmail($email, $hosts); + } + } - if ($monitor_send_one_email == 'on' && $to_email !== '') { - monitorDebug('Processing the Email address: ' . $to_email); - processRebootEmail($to_email, $all_hosts); - } + if ($monitor_send_one_email == 'on' && $to_email !== '') { + monitorDebug('Processing the Email address: ' . $to_email); + processRebootEmail($to_email, $all_hosts); + } } /** @@ -253,24 +244,23 @@ function sendRebootNotifications(array $reboot_emails): void * * @return array{int, int} Reboot count and recent down count. */ -function monitorUptimeChecker(): array -{ - monitorDebug('Checking for Uptime of Devices'); +function monitorUptimeChecker(): array { + monitorDebug('Checking for Uptime of Devices'); - $alert_emails = getAlertEmails(); + $alert_emails = getAlertEmails(); - purgeOrphanMonitorRows('plugin_monitor_uptime'); - purgeOrphanMonitorRows('plugin_monitor_reboot_history'); + purgeOrphanMonitorRows('plugin_monitor_uptime'); + purgeOrphanMonitorRows('plugin_monitor_reboot_history'); - $rebooted_hosts = getRebootedHosts(); + $rebooted_hosts = getRebootedHosts(); - if (cacti_sizeof($rebooted_hosts)) { - $reboot_emails = buildRebootEmailMap($rebooted_hosts, $alert_emails); - sendRebootNotifications($reboot_emails); - } + if (cacti_sizeof($rebooted_hosts)) { + $reboot_emails = buildRebootEmailMap($rebooted_hosts, $alert_emails); + sendRebootNotifications($reboot_emails); + } - // Freshen the uptimes - db_execute('REPLACE INTO plugin_monitor_uptime + // Freshen the uptimes + db_execute('REPLACE INTO plugin_monitor_uptime (host_id, uptime) SELECT id, snmp_sysUpTimeInstance FROM host @@ -280,8 +270,8 @@ function monitorUptimeChecker(): array AND monitor = "on" AND snmp_sysUpTimeInstance > 0'); - // Log Recently Down - db_execute('INSERT IGNORE INTO plugin_monitor_notify_history + // Log Recently Down + db_execute('INSERT IGNORE INTO plugin_monitor_notify_history (host_id, notify_type, notification_time, notes) SELECT h.id, "3" AS notify_type, status_fail_date AS notification_time, status_last_error AS notes FROM host AS h @@ -290,9 +280,9 @@ function monitorUptimeChecker(): array AND monitor = "on" AND status_event_count = 1'); - $recent = db_affected_rows(); + $recent = db_affected_rows(); - return [cacti_sizeof($rebooted_hosts), $recent]; + return [cacti_sizeof($rebooted_hosts), $recent]; } /** @@ -302,44 +292,43 @@ function monitorUptimeChecker(): array * * @return array{string, string, array} */ -function buildRebootDetails(array $hosts): array -{ - $body_txt = ''; - $last_host = []; - - $body = '' . PHP_EOL; - $body .= '' . PHP_EOL; - $body .= - '' . - '' . PHP_EOL; - $body .= '' . PHP_EOL; - - foreach ($hosts as $host_id) { - $host = db_fetch_row_prepared( - 'SELECT description, hostname +function buildRebootDetails(array $hosts): array { + $body_txt = ''; + $last_host = []; + + $body = '
' . __('Description', 'monitor') . '' . __('Hostname', 'monitor') . '
' . PHP_EOL; + $body .= '' . PHP_EOL; + $body .= + '' . + '' . PHP_EOL; + $body .= '' . PHP_EOL; + + foreach ($hosts as $host_id) { + $host = db_fetch_row_prepared( + 'SELECT description, hostname FROM host WHERE id = ?', - [$host_id] - ); + [$host_id] + ); - if (!cacti_sizeof($host)) { - continue; - } + if (!cacti_sizeof($host)) { + continue; + } - $last_host = $host; - $body .= '' . - '' . - '' . - '' . PHP_EOL; + $last_host = $host; + $body .= '' . + '' . + '' . + '' . PHP_EOL; - $body_txt .= - __('Description: ', 'monitor') . $host['description'] . PHP_EOL . - __('Hostname: ', 'monitor') . $host['hostname'] . PHP_EOL . PHP_EOL; - } + $body_txt .= + __('Description: ', 'monitor') . $host['description'] . PHP_EOL . + __('Hostname: ', 'monitor') . $host['hostname'] . PHP_EOL . PHP_EOL; + } - $body .= '
' . __('Description', 'monitor') . '' . __('Hostname', 'monitor') . '
' . $host['description'] . '' . $host['hostname'] . '
' . $host['description'] . '' . $host['hostname'] . '
' . PHP_EOL; + $body .= '' . PHP_EOL; - return [$body, $body_txt, $last_host]; + return [$body, $body_txt, $last_host]; } /** @@ -350,20 +339,19 @@ function buildRebootDetails(array $hosts): array * * @return string */ -function buildRebootSubject(array $hosts, array $last_host): string -{ - $subject = read_config_option('monitor_subject'); - $monitor_send_one_email = read_config_option('monitor_send_one_email'); +function buildRebootSubject(array $hosts, array $last_host): string { + $subject = read_config_option('monitor_subject'); + $monitor_send_one_email = read_config_option('monitor_send_one_email'); - if ($monitor_send_one_email == 'on' && cacti_sizeof($last_host)) { - return $subject . ' ' . $last_host['description'] . ' (' . $last_host['hostname'] . ')'; - } + if ($monitor_send_one_email == 'on' && cacti_sizeof($last_host)) { + return $subject . ' ' . $last_host['description'] . ' (' . $last_host['hostname'] . ')'; + } - if (cacti_sizeof($hosts) == 1 && cacti_sizeof($last_host)) { - return $subject . ' 1 device - ' . $last_host['description'] . ' (' . $last_host['hostname'] . ')'; - } + if (cacti_sizeof($hosts) == 1 && cacti_sizeof($last_host)) { + return $subject . ' 1 device - ' . $last_host['description'] . ' (' . $last_host['hostname'] . ')'; + } - return $subject . ' ' . cacti_sizeof($hosts) . ' devices'; + return $subject . ' ' . cacti_sizeof($hosts) . ' devices'; } /** @@ -374,40 +362,39 @@ function buildRebootSubject(array $hosts, array $last_host): string * * @return array{string, string, array} */ -function prepareReportOutput(string $body, string $body_txt): array -{ - $output = ''; +function prepareReportOutput(string $body, string $body_txt): array { + $output = ''; - $report_tag = ''; - $theme = 'modern'; + $report_tag = ''; + $theme = 'modern'; - monitorDebug('Loading Format File'); + monitorDebug('Loading Format File'); - $format_ok = reports_load_format_file(read_config_option('monitor_format_file'), $output, $report_tag, $theme); + $format_ok = reports_load_format_file(read_config_option('monitor_format_file'), $output, $report_tag, $theme); - monitorDebug('Format File Loaded, Format is ' . ($format_ok ? 'Ok' : 'Not Ok') . ', Report Tag is ' . $report_tag); + monitorDebug('Format File Loaded, Format is ' . ($format_ok ? 'Ok' : 'Not Ok') . ', Report Tag is ' . $report_tag); - if ($format_ok) { - if ($report_tag) { - $output = str_replace('', $body, $output); - } else { - $output = $output . PHP_EOL . $body; - } - } else { - $output = $body; - } + if ($format_ok) { + if ($report_tag) { + $output = str_replace('', $body, $output); + } else { + $output = $output . PHP_EOL . $body; + } + } else { + $output = $body; + } - monitorDebug('HTML Processed'); + monitorDebug('HTML Processed'); - if (defined('CACTI_VERSION')) { - $version = CACTI_VERSION; - } else { - $version = get_cacti_version(); - } + if (defined('CACTI_VERSION')) { + $version = CACTI_VERSION; + } else { + $version = get_cacti_version(); + } - $headers = ['User-Agent' => 'Cacti-Monitor-v' . $version]; + $headers = ['User-Agent' => 'Cacti-Monitor-v' . $version]; - return [$output, $body_txt, $headers]; + return [$output, $body_txt, $headers]; } /** @@ -418,29 +405,28 @@ function prepareReportOutput(string $body, string $body_txt): array * * @return void */ -function processRebootEmail(string $email, array $hosts): void -{ - monitorDebug("Reboot Processing for $email starting"); +function processRebootEmail(string $email, array $hosts): void { + monitorDebug("Reboot Processing for $email starting"); - [$body, $body_txt, $last_host] = buildRebootDetails($hosts); - $subject = buildRebootSubject($hosts, $last_host); + [$body, $body_txt, $last_host] = buildRebootDetails($hosts); + $subject = buildRebootSubject($hosts, $last_host); - $template_output = read_config_option('monitor_body'); - $template_output = str_replace('
', $body, $template_output) . PHP_EOL; + $template_output = read_config_option('monitor_body'); + $template_output = str_replace('
', $body, $template_output) . PHP_EOL; - if (strpos($template_output, '
') !== false) { - $toutput = str_replace('
', $body_txt, $template_output) . PHP_EOL; - } else { - $toutput = $body_txt; - } + if (strpos($template_output, '
') !== false) { + $toutput = str_replace('
', $body_txt, $template_output) . PHP_EOL; + } else { + $toutput = $body_txt; + } - if (read_config_option('monitor_reboot_notify') != 'on') { - return; - } + if (read_config_option('monitor_reboot_notify') != 'on') { + return; + } - [$output, $toutput, $headers] = prepareReportOutput($body, $toutput); + [$output, $toutput, $headers] = prepareReportOutput($body, $toutput); - processSendEmail($email, $subject, $output, $toutput, $headers, 'Reboot Notifications'); + processSendEmail($email, $subject, $output, $toutput, $headers, 'Reboot Notifications'); } /** @@ -452,34 +438,33 @@ function processRebootEmail(string $email, array $hosts): void * * @return array{array, array} */ -function collectNotificationHosts(array $lists, array $global_list, array $notify_list): array -{ - $alert_hosts = []; - $warn_hosts = []; - - foreach ($lists as $list) { - if ($list === 'global') { - if (isset($global_list['alert'])) { - $alert_hosts = array_merge($alert_hosts, explode(',', $global_list['alert'])); - } - - if (isset($global_list['warn'])) { - $warn_hosts = array_merge($warn_hosts, explode(',', $global_list['warn'])); - } - - continue; - } - - if (isset($notify_list[$list]['alert'])) { - $alert_hosts = array_merge($alert_hosts, explode(',', $notify_list[$list]['alert'])); - } - - if (isset($notify_list[$list]['warn'])) { - $warn_hosts = array_merge($warn_hosts, explode(',', $notify_list[$list]['warn'])); - } - } - - return [$alert_hosts, $warn_hosts]; +function collectNotificationHosts(array $lists, array $global_list, array $notify_list): array { + $alert_hosts = []; + $warn_hosts = []; + + foreach ($lists as $list) { + if ($list === 'global') { + if (isset($global_list['alert'])) { + $alert_hosts = array_merge($alert_hosts, explode(',', $global_list['alert'])); + } + + if (isset($global_list['warn'])) { + $warn_hosts = array_merge($warn_hosts, explode(',', $global_list['warn'])); + } + + continue; + } + + if (isset($notify_list[$list]['alert'])) { + $alert_hosts = array_merge($alert_hosts, explode(',', $notify_list[$list]['alert'])); + } + + if (isset($notify_list[$list]['warn'])) { + $warn_hosts = array_merge($warn_hosts, explode(',', $notify_list[$list]['warn'])); + } + } + + return [$alert_hosts, $warn_hosts]; } /** @@ -490,17 +475,16 @@ function collectNotificationHosts(array $lists, array $global_list, array $notif * * @return void */ -function normalizeAndLogNotificationHosts(array &$alert_hosts, array &$warn_hosts): void -{ - if (cacti_sizeof($alert_hosts)) { - $alert_hosts = array_unique($alert_hosts, SORT_NUMERIC); - logMessages('alert', $alert_hosts); - } - - if (cacti_sizeof($warn_hosts)) { - $warn_hosts = array_unique($warn_hosts, SORT_NUMERIC); - logMessages('warn', $warn_hosts); - } +function normalizeAndLogNotificationHosts(array &$alert_hosts, array &$warn_hosts): void { + if (cacti_sizeof($alert_hosts)) { + $alert_hosts = array_unique($alert_hosts, SORT_NUMERIC); + logMessages('alert', $alert_hosts); + } + + if (cacti_sizeof($warn_hosts)) { + $warn_hosts = array_unique($warn_hosts, SORT_NUMERIC); + logMessages('warn', $warn_hosts); + } } /** @@ -510,91 +494,89 @@ function normalizeAndLogNotificationHosts(array &$alert_hosts, array &$warn_host * * @return array{string, string} */ -function buildPingNotificationIntro(int|string $freq): array -{ - $body = '

' . __(MONITOR_PING_NOTIFICATION_SUBJECT, 'monitor') . '

' . PHP_EOL; - $body_txt = __(MONITOR_PING_NOTIFICATION_SUBJECT, 'monitor') . PHP_EOL; +function buildPingNotificationIntro(int|string $freq): array { + $body = '

' . __(MONITOR_PING_NOTIFICATION_SUBJECT, 'monitor') . '

' . PHP_EOL; + $body_txt = __(MONITOR_PING_NOTIFICATION_SUBJECT, 'monitor') . PHP_EOL; - $message = __('The following report will identify Devices that have eclipsed their ping latency thresholds. You are receiving this report since you are subscribed to a Device associated with the Cacti system located at the following URL below.'); + $message = __('The following report will identify Devices that have eclipsed their ping latency thresholds. You are receiving this report since you are subscribed to a Device associated with the Cacti system located at the following URL below.'); - $body .= '

' . $message . '

' . PHP_EOL; - $body_txt .= $message . PHP_EOL; + $body .= '

' . $message . '

' . PHP_EOL; + $body_txt .= $message . PHP_EOL; - $body .= '

Cacti Monitoring Site

' . PHP_EOL; - $body_txt .= __('Cacti Monitoring Site', 'monitor') . PHP_EOL; + $body .= '

Cacti Monitoring Site

' . PHP_EOL; + $body_txt .= __('Cacti Monitoring Site', 'monitor') . PHP_EOL; - if ($freq > 0) { - $body .= '

' . __('You will receive notifications every %d minutes if the Device is above its threshold.', $freq, 'monitor') . '

' . PHP_EOL; - $body_txt .= __('You will receive notifications every %d minutes if the Device is above its threshold.', $freq, 'monitor') . PHP_EOL; - } else { - $body .= '

' . __('You will receive notifications every time the Device is above its threshold.', 'monitor') . '

' . PHP_EOL; - $body_txt .= __('You will receive notifications every time the Device is above its threshold.', 'monitor') . PHP_EOL; - } + if ($freq > 0) { + $body .= '

' . __('You will receive notifications every %d minutes if the Device is above its threshold.', $freq, 'monitor') . '

' . PHP_EOL; + $body_txt .= __('You will receive notifications every %d minutes if the Device is above its threshold.', $freq, 'monitor') . PHP_EOL; + } else { + $body .= '

' . __('You will receive notifications every time the Device is above its threshold.', 'monitor') . '

' . PHP_EOL; + $body_txt .= __('You will receive notifications every time the Device is above its threshold.', 'monitor') . PHP_EOL; + } - return [$body, $body_txt]; + return [$body, $body_txt]; } /** * Append one severity section for breached host thresholds. * - * @param string $body HTML body output buffer. - * @param string $body_txt Plain text output buffer. - * @param array $host_ids Host ids for the section. - * @param array $criticalities Criticality label map. - * @param string $section_text Section heading text. + * @param string $body HTML body output buffer. + * @param string $body_txt Plain text output buffer. + * @param array $host_ids Host ids for the section. + * @param array $criticalities Criticality label map. + * @param string $section_text Section heading text. * @param string $threshold_field Host threshold field name. * * @return void */ -function appendThresholdSection(string &$body, string &$body_txt, array $host_ids, array $criticalities, string $section_text, string $threshold_field): void -{ - global $config; - - if (!cacti_sizeof($host_ids)) { - return; - } - - $body .= '

' . __($section_text, 'monitor') . '

' . PHP_EOL; - $body_txt .= __($section_text, 'monitor') . PHP_EOL; - - $body .= '' . PHP_EOL; - $body .= '' . PHP_EOL; - $body .= - '' . - '' . - '' . - '' . PHP_EOL; - $body .= '' . PHP_EOL; - - $body_txt .= - __('Hostname', 'monitor') . "\t" . - __('Criticality', 'monitor') . "\t" . - __(MONITOR_ALERT_PING_LABEL, 'monitor') . "\t" . - __(MONITOR_CURRENT_PING_LABEL, 'monitor') . PHP_EOL; - - $hosts = db_fetch_assoc('SELECT * +function appendThresholdSection(string &$body, string &$body_txt, array $host_ids, array $criticalities, string $section_text, string $threshold_field): void { + global $config; + + if (!cacti_sizeof($host_ids)) { + return; + } + + $body .= '

' . __($section_text, 'monitor') . '

' . PHP_EOL; + $body_txt .= __($section_text, 'monitor') . PHP_EOL; + + $body .= '
' . __('Hostname', 'monitor') . '' . __('Criticality', 'monitor') . '' . __(MONITOR_ALERT_PING_LABEL, 'monitor') . '' . __(MONITOR_CURRENT_PING_LABEL, 'monitor') . '
' . PHP_EOL; + $body .= '' . PHP_EOL; + $body .= + '' . + '' . + '' . + '' . PHP_EOL; + $body .= '' . PHP_EOL; + + $body_txt .= + __('Hostname', 'monitor') . "\t" . + __('Criticality', 'monitor') . "\t" . + __(MONITOR_ALERT_PING_LABEL, 'monitor') . "\t" . + __(MONITOR_CURRENT_PING_LABEL, 'monitor') . PHP_EOL; + + $hosts = db_fetch_assoc('SELECT * FROM host WHERE id IN(' . implode(',', $host_ids) . ') AND deleted = ""'); - if (cacti_sizeof($hosts)) { - foreach ($hosts as $host) { - $body .= '' . PHP_EOL; - $body .= '' . PHP_EOL; - $body .= '' . PHP_EOL; - $body .= '' . PHP_EOL; - $body .= '' . PHP_EOL; - $body .= '' . PHP_EOL; - - $body_txt .= - $host['description'] . "\t" . - $criticalities[$host['monitor_criticality']] . "\t" . - number_format_i18n($host[$threshold_field], 2) . " ms\t" . - number_format_i18n($host['cur_time'], 2) . ' ms' . PHP_EOL; - } - } - - $body .= '
' . __('Hostname', 'monitor') . '' . __('Criticality', 'monitor') . '' . __(MONITOR_ALERT_PING_LABEL, 'monitor') . '' . __(MONITOR_CURRENT_PING_LABEL, 'monitor') . '
' . $host['description'] . '' . $criticalities[$host['monitor_criticality']] . '' . number_format_i18n($host[$threshold_field], 2) . ' ms' . number_format_i18n($host['cur_time'], 2) . ' ms
' . PHP_EOL; + if (cacti_sizeof($hosts)) { + foreach ($hosts as $host) { + $body .= '' . PHP_EOL; + $body .= '' . $host['description'] . '' . PHP_EOL; + $body .= '' . $criticalities[$host['monitor_criticality']] . '' . PHP_EOL; + $body .= '' . number_format_i18n($host[$threshold_field], 2) . ' ms' . PHP_EOL; + $body .= '' . number_format_i18n($host['cur_time'], 2) . ' ms' . PHP_EOL; + $body .= '' . PHP_EOL; + + $body_txt .= + $host['description'] . "\t" . + $criticalities[$host['monitor_criticality']] . "\t" . + number_format_i18n($host[$threshold_field], 2) . " ms\t" . + number_format_i18n($host['cur_time'], 2) . ' ms' . PHP_EOL; + } + } + + $body .= '' . PHP_EOL; } /** @@ -605,23 +587,22 @@ function appendThresholdSection(string &$body, string &$body_txt, array $host_id * * @return string */ -function buildNotificationStatus(array $alert_hosts, array $warn_hosts): string -{ - $status = ''; +function buildNotificationStatus(array $alert_hosts, array $warn_hosts): string { + $status = ''; - if (cacti_sizeof($alert_hosts)) { - $status = sizeof($alert_hosts) . ' Alert Notifications'; - } + if (cacti_sizeof($alert_hosts)) { + $status = sizeof($alert_hosts) . ' Alert Notifications'; + } - if (cacti_sizeof($warn_hosts)) { - if ($status !== '') { - $status .= ', and '; - } + if (cacti_sizeof($warn_hosts)) { + if ($status !== '') { + $status .= ', and '; + } - $status .= sizeof($warn_hosts) . ' Warning Notifications'; - } + $status .= sizeof($warn_hosts) . ' Warning Notifications'; + } - return $status; + return $status; } /** @@ -634,56 +615,55 @@ function buildNotificationStatus(array $alert_hosts, array $warn_hosts): string * * @return void */ -function processEmail(string $email, array $lists, array $global_list, array $notify_list): void -{ - monitorDebug('Into Processing'); - - $criticalities = [ - 0 => __('Disabled', 'monitor'), - 1 => __('Low', 'monitor'), - 2 => __('Medium', 'monitor'), - 3 => __('High', 'monitor'), - 4 => __('Mission Critical', 'monitor') - ]; - - [$alert_hosts, $warn_hosts] = collectNotificationHosts($lists, $global_list, $notify_list); - monitorDebug('Lists Processed'); - - normalizeAndLogNotificationHosts($alert_hosts, $warn_hosts); - monitorDebug('Found ' . sizeof($alert_hosts) . ' Alert Hosts, and ' . sizeof($warn_hosts) . ' Warn Hosts'); - - if (!cacti_sizeof($alert_hosts) && !cacti_sizeof($warn_hosts)) { - return; - } - - monitorDebug('Formatting Email'); - - $freq = read_config_option('monitor_resend_frequency'); - $subject = __(MONITOR_PING_NOTIFICATION_SUBJECT, 'monitor'); - [$body, $body_txt] = buildPingNotificationIntro($freq); - - appendThresholdSection( - $body, - $body_txt, - $alert_hosts, - $criticalities, - 'The following Devices have breached their Alert Notification Threshold.', - 'monitor_alert' - ); - - appendThresholdSection( - $body, - $body_txt, - $warn_hosts, - $criticalities, - 'The following Devices have breached their Warning Notification Threshold.', - 'monitor_warn' - ); - - [$output, $toutput, $headers] = prepareReportOutput($body, $body_txt); - $status = buildNotificationStatus($alert_hosts, $warn_hosts); - - processSendEmail($email, $subject, $output, $toutput, $headers, $status); +function processEmail(string $email, array $lists, array $global_list, array $notify_list): void { + monitorDebug('Into Processing'); + + $criticalities = [ + 0 => __('Disabled', 'monitor'), + 1 => __('Low', 'monitor'), + 2 => __('Medium', 'monitor'), + 3 => __('High', 'monitor'), + 4 => __('Mission Critical', 'monitor') + ]; + + [$alert_hosts, $warn_hosts] = collectNotificationHosts($lists, $global_list, $notify_list); + monitorDebug('Lists Processed'); + + normalizeAndLogNotificationHosts($alert_hosts, $warn_hosts); + monitorDebug('Found ' . sizeof($alert_hosts) . ' Alert Hosts, and ' . sizeof($warn_hosts) . ' Warn Hosts'); + + if (!cacti_sizeof($alert_hosts) && !cacti_sizeof($warn_hosts)) { + return; + } + + monitorDebug('Formatting Email'); + + $freq = read_config_option('monitor_resend_frequency'); + $subject = __(MONITOR_PING_NOTIFICATION_SUBJECT, 'monitor'); + [$body, $body_txt] = buildPingNotificationIntro($freq); + + appendThresholdSection( + $body, + $body_txt, + $alert_hosts, + $criticalities, + 'The following Devices have breached their Alert Notification Threshold.', + 'monitor_alert' + ); + + appendThresholdSection( + $body, + $body_txt, + $warn_hosts, + $criticalities, + 'The following Devices have breached their Warning Notification Threshold.', + 'monitor_warn' + ); + + [$output, $toutput, $headers] = prepareReportOutput($body, $body_txt); + $status = buildNotificationStatus($alert_hosts, $warn_hosts); + + processSendEmail($email, $subject, $output, $toutput, $headers, $status); } /** @@ -698,58 +678,57 @@ function processEmail(string $email, array $lists, array $global_list, array $no * * @return void */ -function processSendEmail(string $email, string $subject, string $output, string $toutput, array $headers, string $status): void -{ - $from_email = read_config_option('monitor_fromemail'); - - if ($from_email == '') { - $from_email = read_config_option('settings_from_email'); - - if ($from_email == '') { - $from_email = 'Cacti@cacti.net'; - } - } - - $from_name = read_config_option('monitor_fromname'); - - if ($from_name == '') { - $from_name = read_config_option('settings_from_name'); - - if ($from_name == '') { - $from_name = 'Cacti Reporting'; - } - } - - $html = true; - - if (read_config_option('thold_send_text_only') == 'on') { - $output = monitorText($toutput); - $html = false; - } - - monitorDebug("Sending Email to '$email' for $status"); - - $error = mailer( - [$from_email, $from_name], - $email, - '', - '', - '', - $subject, - $output, - monitorText($toutput), - null, - $headers, - $html - ); - - monitorDebug("The return from the mailer was '$error'"); - - if (strlen($error)) { - cacti_log("WARNING: Monitor had problems sending to '$email' for $status. The error was '$error'", false, 'MONITOR'); - } else { - cacti_log("NOTICE: Email Notification Sent to '$email' for $status.", false, 'MONITOR'); - } +function processSendEmail(string $email, string $subject, string $output, string $toutput, array $headers, string $status): void { + $from_email = read_config_option('monitor_fromemail'); + + if ($from_email == '') { + $from_email = read_config_option('settings_from_email'); + + if ($from_email == '') { + $from_email = 'Cacti@cacti.net'; + } + } + + $from_name = read_config_option('monitor_fromname'); + + if ($from_name == '') { + $from_name = read_config_option('settings_from_name'); + + if ($from_name == '') { + $from_name = 'Cacti Reporting'; + } + } + + $html = true; + + if (read_config_option('thold_send_text_only') == 'on') { + $output = monitorText($toutput); + $html = false; + } + + monitorDebug("Sending Email to '$email' for $status"); + + $error = mailer( + [$from_email, $from_name], + $email, + '', + '', + '', + $subject, + $output, + monitorText($toutput), + null, + $headers, + $html + ); + + monitorDebug("The return from the mailer was '$error'"); + + if (strlen($error)) { + cacti_log("WARNING: Monitor had problems sending to '$email' for $status. The error was '$error'", false, 'MONITOR'); + } else { + cacti_log("NOTICE: Email Notification Sent to '$email' for $status.", false, 'MONITOR'); + } } /** @@ -759,22 +738,21 @@ function processSendEmail(string $email, string $subject, string $output, string * * @return string */ -function monitorText(string $output): string -{ - $output = explode(PHP_EOL, $output); - - $new_output = ''; - - if (cacti_sizeof($output)) { - foreach ($output as $line) { - $line = str_replace('
', PHP_EOL, $line); - $line = str_replace('
', PHP_EOL, $line); - $line = trim(strip_tags($line)); - $new_output .= $line . PHP_EOL; - } - } - - return $new_output; +function monitorText(string $output): string { + $output = explode(PHP_EOL, $output); + + $new_output = ''; + + if (cacti_sizeof($output)) { + foreach ($output as $line) { + $line = str_replace('
', PHP_EOL, $line); + $line = str_replace('
', PHP_EOL, $line); + $line = trim(strip_tags($line)); + $new_output .= $line . PHP_EOL; + } + } + + return $new_output; } /** @@ -785,36 +763,35 @@ function monitorText(string $output): string * * @return void */ -function logMessages(string $type, array $alert_hosts): void -{ - global $start_date; - - static $processed = []; - - if ($type == 'warn') { - $type = '0'; - $column = 'monitor_warn'; - } elseif ($type == 'alert') { - $type = '1'; - $column = 'monitor_alert'; - } - - foreach ($alert_hosts as $id) { - if (!isset($processed[$id])) { - db_execute_prepared( - "INSERT INTO plugin_monitor_notify_history +function logMessages(string $type, array $alert_hosts): void { + global $start_date; + + static $processed = []; + + if ($type == 'warn') { + $type = '0'; + $column = 'monitor_warn'; + } elseif ($type == 'alert') { + $type = '1'; + $column = 'monitor_alert'; + } + + foreach ($alert_hosts as $id) { + if (!isset($processed[$id])) { + db_execute_prepared( + "INSERT INTO plugin_monitor_notify_history (host_id, notify_type, ping_time, ping_threshold, notification_time) SELECT id, '$type' AS notify_type, cur_time, $column, '$start_date' AS notification_time FROM host WHERE deleted = '' AND monitor = 'on' AND id = ?", - [$id] - ); - } + [$id] + ); + } - $processed[$id] = true; - } + $processed[$id] = true; + } } /** @@ -828,16 +805,15 @@ function logMessages(string $type, array $alert_hosts): void * * @return void */ -function addGroupedNotificationEntry(string $type, array $entry, array &$global_list, array &$notify_list, array &$lists): void -{ - if ($entry['thold_send_email'] == '1' || $entry['thold_send_email'] == '3') { - $global_list[$type][] = $entry; - } - - if (($entry['thold_send_email'] == '2' || $entry['thold_send_email'] == '3') && $entry['thold_host_email'] > 0) { - $notify_list[$type][$entry['thold_host_email']][] = $entry; - $lists[$entry['thold_host_email']] = $entry['thold_host_email']; - } +function addGroupedNotificationEntry(string $type, array $entry, array &$global_list, array &$notify_list, array &$lists): void { + if ($entry['thold_send_email'] == '1' || $entry['thold_send_email'] == '3') { + $global_list[$type][] = $entry; + } + + if (($entry['thold_send_email'] == '2' || $entry['thold_send_email'] == '3') && $entry['thold_host_email'] > 0) { + $notify_list[$type][$entry['thold_host_email']][] = $entry; + $lists[$entry['thold_host_email']] = $entry['thold_host_email']; + } } /** @@ -851,12 +827,11 @@ function addGroupedNotificationEntry(string $type, array $entry, array &$global_ * * @return void */ -function getHostsByListType(string $type, int|string $criticality, array &$global_list, array &$notify_list, array &$lists): void -{ - $last_time = date(MONITOR_DATE_TIME_FORMAT, time() - read_config_option('monitor_resend_frequency') * 60); +function getHostsByListType(string $type, int|string $criticality, array &$global_list, array &$notify_list, array &$lists): void { + $last_time = date(MONITOR_DATE_TIME_FORMAT, time() - read_config_option('monitor_resend_frequency') * 60); - $hosts = db_fetch_cell_prepared( - "SELECT COUNT(*) + $hosts = db_fetch_cell_prepared( + "SELECT COUNT(*) FROM host WHERE status = 3 AND deleted = '' @@ -864,17 +839,17 @@ function getHostsByListType(string $type, int|string $criticality, array &$globa AND thold_send_email > 0 AND monitor_criticality >= ? AND cur_time > monitor_$type", - [$criticality] - ); + [$criticality] + ); - if ($hosts <= 0) { - return; - } + if ($hosts <= 0) { + return; + } - $htype = ($type == 'warn') ? 1 : 0; + $htype = ($type == 'warn') ? 1 : 0; - $groups = db_fetch_assoc_prepared( - "SELECT + $groups = db_fetch_assoc_prepared( + "SELECT thold_send_email, thold_host_email, GROUP_CONCAT(host.id) AS id FROM host LEFT JOIN ( @@ -894,16 +869,16 @@ function getHostsByListType(string $type, int|string $criticality, array &$globa AND host.total_polls > 1 GROUP BY thold_host_email, thold_send_email ORDER BY thold_host_email, thold_send_email', - [$htype, $criticality, $last_time] - ); + [$htype, $criticality, $last_time] + ); - if (!cacti_sizeof($groups)) { - return; - } + if (!cacti_sizeof($groups)) { + return; + } - foreach ($groups as $entry) { - addGroupedNotificationEntry($type, $entry, $global_list, $notify_list, $lists); - } + foreach ($groups as $entry) { + addGroupedNotificationEntry($type, $entry, $global_list, $notify_list, $lists); + } } /** @@ -913,15 +888,14 @@ function getHostsByListType(string $type, int|string $criticality, array &$globa * * @return string */ -function flattenGroupSeverityList(array $list): string -{ - $flattened = ''; +function flattenGroupSeverityList(array $list): string { + $flattened = ''; - foreach ($list as $item) { - $flattened .= ($flattened !== '' ? ',' : '') . $item['id']; - } + foreach ($list as $item) { + $flattened .= ($flattened !== '' ? ',' : '') . $item['id']; + } - return $flattened; + return $flattened; } /** @@ -931,15 +905,14 @@ function flattenGroupSeverityList(array $list): string * * @return array */ -function flattenNotifySeverityLists(array $lists): array -{ - $flattened = []; +function flattenNotifySeverityLists(array $lists): array { + $flattened = []; - foreach ($lists as $id => $list) { - $flattened[$id] = flattenGroupSeverityList($list); - } + foreach ($lists as $id => $list) { + $flattened[$id] = flattenGroupSeverityList($list); + } - return $flattened; + return $flattened; } /** @@ -950,47 +923,45 @@ function flattenNotifySeverityLists(array $lists): array * * @return void */ -function flattenLists(array &$global_list, array &$notify_list): void -{ - if (cacti_sizeof($global_list)) { - $new_global = []; +function flattenLists(array &$global_list, array &$notify_list): void { + if (cacti_sizeof($global_list)) { + $new_global = []; - foreach ($global_list as $severity => $list) { - $new_global[$severity] = flattenGroupSeverityList($list); - } + foreach ($global_list as $severity => $list) { + $new_global[$severity] = flattenGroupSeverityList($list); + } - $global_list = $new_global; - } + $global_list = $new_global; + } - if (cacti_sizeof($notify_list)) { - $new_list = []; + if (cacti_sizeof($notify_list)) { + $new_list = []; - foreach ($notify_list as $severity => $lists) { - $new_list[$severity] = flattenNotifySeverityLists($lists); - } + foreach ($notify_list as $severity => $lists) { + $new_list[$severity] = flattenNotifySeverityLists($lists); + } - $notify_list = $new_list; - } + $notify_list = $new_list; + } } /** * Add email addresses into the recipient scope map. * - * @param array $notification_emails Recipient map, updated in place. - * @param array $emails Raw email values to normalize. - * @param string|int $scope_key Scope key (`global` or list id). + * @param array $notification_emails Recipient map, updated in place. + * @param array $emails Raw email values to normalize. + * @param string|int $scope_key Scope key (`global` or list id). * * @return void */ -function addEmailsToNotificationMap(array &$notification_emails, array $emails, string|int $scope_key): void -{ - foreach ($emails as $user) { - $user = trim($user); - - if ($user !== '') { - $notification_emails[$user][$scope_key] = true; - } - } +function addEmailsToNotificationMap(array &$notification_emails, array $emails, string|int $scope_key): void { + foreach ($emails as $user) { + $user = trim($user); + + if ($user !== '') { + $notification_emails[$user][$scope_key] = true; + } + } } /** @@ -1000,34 +971,33 @@ function addEmailsToNotificationMap(array &$notification_emails, array $emails, * * @return array */ -function getEmailsAndLists(array $lists): array -{ - $notification_emails = []; +function getEmailsAndLists(array $lists): array { + $notification_emails = []; - $alert_email = read_config_option('alert_email'); - $global_emails = ($alert_email != '') ? explode(',', $alert_email) : []; + $alert_email = read_config_option('alert_email'); + $global_emails = ($alert_email != '') ? explode(',', $alert_email) : []; - if (cacti_sizeof($global_emails)) { - addEmailsToNotificationMap($notification_emails, $global_emails, 'global'); - } + if (cacti_sizeof($global_emails)) { + addEmailsToNotificationMap($notification_emails, $global_emails, 'global'); + } - if (!cacti_sizeof($lists)) { - return $notification_emails; - } + if (!cacti_sizeof($lists)) { + return $notification_emails; + } - $list_emails = db_fetch_assoc('SELECT id, emails + $list_emails = db_fetch_assoc('SELECT id, emails FROM plugin_notification_lists WHERE id IN (' . implode(',', $lists) . ')'); - if (!cacti_sizeof($list_emails)) { - return $notification_emails; - } + if (!cacti_sizeof($list_emails)) { + return $notification_emails; + } - foreach ($list_emails as $email) { - addEmailsToNotificationMap($notification_emails, explode(',', $email['emails']), $email['id']); - } + foreach ($list_emails as $email) { + addEmailsToNotificationMap($notification_emails, explode(',', $email['emails']), $email['id']); + } - return $notification_emails; + return $notification_emails; } /** @@ -1035,32 +1005,31 @@ function getEmailsAndLists(array $lists): array * * @return array{int, int} Purged notify count and purged reboot count. */ -function purgeEventRecords(): array -{ - // Purge old records - $days = read_config_option('monitor_log_storage'); +function purgeEventRecords(): array { + // Purge old records + $days = read_config_option('monitor_log_storage'); - if (empty($days)) { - $days = 120; - } + if (empty($days)) { + $days = 120; + } - db_execute_prepared( - 'DELETE FROM plugin_monitor_notify_history + db_execute_prepared( + 'DELETE FROM plugin_monitor_notify_history WHERE notification_time < FROM_UNIXTIME(UNIX_TIMESTAMP() - (? * 86400))', - [$days] - ); + [$days] + ); - $purge_n = db_affected_rows(); + $purge_n = db_affected_rows(); - db_execute_prepared( - 'DELETE FROM plugin_monitor_reboot_history + db_execute_prepared( + 'DELETE FROM plugin_monitor_reboot_history WHERE log_time < FROM_UNIXTIME(UNIX_TIMESTAMP() - (? * 86400))', - [$days] - ); + [$days] + ); - $purge_r = db_affected_rows(); + $purge_r = db_affected_rows(); - return [$purge_n, $purge_r]; + return [$purge_n, $purge_r]; } /** @@ -1070,13 +1039,12 @@ function purgeEventRecords(): array * * @return void */ -function monitorDebug(string $message): void -{ - global $debug; +function monitorDebug(string $message): void { + global $debug; - if ($debug) { - print trim($message) . PHP_EOL; - } + if ($debug) { + print trim($message) . PHP_EOL; + } } /** @@ -1084,17 +1052,16 @@ function monitorDebug(string $message): void * * @return void */ -function displayVersion(): void -{ - global $config; +function displayVersion(): void { + global $config; - if (!function_exists('plugin_monitor_version')) { - include_once $config['base_path'] . '/plugins/monitor/setup.php'; - } + if (!function_exists('plugin_monitor_version')) { + include_once $config['base_path'] . '/plugins/monitor/setup.php'; + } - $info = plugin_monitor_version(); + $info = plugin_monitor_version(); - print 'Cacti Monitor Poller, Version ' . $info['version'] . ', ' . COPYRIGHT_YEARS . PHP_EOL; + print 'Cacti Monitor Poller, Version ' . $info['version'] . ', ' . COPYRIGHT_YEARS . PHP_EOL; } /** @@ -1102,11 +1069,10 @@ function displayVersion(): void * * @return void */ -function displayHelp(): void -{ - displayVersion(); +function displayHelp(): void { + displayVersion(); - print PHP_EOL; - print 'usage: poller_monitor.php [--debug]' . PHP_EOL . PHP_EOL; - print ' --debug - debug execution, e.g. for testing' . PHP_EOL . PHP_EOL; + print PHP_EOL; + print 'usage: poller_monitor.php [--debug]' . PHP_EOL . PHP_EOL; + print ' --debug - debug execution, e.g. for testing' . PHP_EOL . PHP_EOL; } diff --git a/poller_monitor.php b/poller_monitor.php index bb71ae0..0a7ba3c 100644 --- a/poller_monitor.php +++ b/poller_monitor.php @@ -1,6 +1,6 @@ 0 || $alert_criticality > 0) { - monitorDebug('Monitor Notification Enabled for Devices'); + monitorDebug('Monitor Notification Enabled for Devices'); - // Get hosts that are above threshold. Start with Alert, and then Warning. - if ($alert_criticality) { - getHostsByListType('alert', $alert_criticality, $global_list, $notify_list, $lists); - } + // Get hosts that are above threshold. Start with Alert, and then Warning. + if ($alert_criticality) { + getHostsByListType('alert', $alert_criticality, $global_list, $notify_list, $lists); + } - if ($warning_criticality) { - getHostsByListType('warn', $warning_criticality, $global_list, $notify_list, $lists); - } + if ($warning_criticality) { + getHostsByListType('warn', $warning_criticality, $global_list, $notify_list, $lists); + } - flattenLists($global_list, $notify_list); + flattenLists($global_list, $notify_list); - monitorDebug('Lists Flattened there are ' . sizeof($global_list) . ' Global Notifications and ' . sizeof($notify_list) . ' Notification List Notifications.'); + monitorDebug('Lists Flattened there are ' . sizeof($global_list) . ' Global Notifications and ' . sizeof($notify_list) . ' Notification List Notifications.'); - if (strlen(read_config_option('alert_email')) == 0) { - monitorDebug('WARNING: No Global List Defined. Please set under Settings -> Thresholds'); - cacti_log('WARNING: No Global Notification List defined. Please set under Settings -> Thresholds', false, 'MONITOR'); - } + if (strlen(read_config_option('alert_email')) == 0) { + monitorDebug('WARNING: No Global List Defined. Please set under Settings -> Thresholds'); + cacti_log('WARNING: No Global Notification List defined. Please set under Settings -> Thresholds', false, 'MONITOR'); + } - if (cacti_sizeof($global_list) || sizeof($notify_list)) { - // array of email[list|'g'] = true; - $notification_emails = getEmailsAndLists($lists); + if (cacti_sizeof($global_list) || sizeof($notify_list)) { + // array of email[list|'g'] = true; + $notification_emails = getEmailsAndLists($lists); - // Send out emails to each emails address with all notifications in one - if (cacti_sizeof($notification_emails)) { - foreach ($notification_emails as $email => $lists) { - monitorDebug('Processing the email address: ' . $email); - processEmail($email, $lists, $global_list, $notify_list); + // Send out emails to each emails address with all notifications in one + if (cacti_sizeof($notification_emails)) { + foreach ($notification_emails as $email => $lists) { + monitorDebug('Processing the email address: ' . $email); + processEmail($email, $lists, $global_list, $notify_list); - $notifications++; - } - } - } + $notifications++; + } + } + } } else { - monitorDebug('Both Warning and Alert Notification are Disabled.'); + monitorDebug('Both Warning and Alert Notification are Disabled.'); } [$purge_n, $purge_r] = purgeEventRecords(); @@ -143,11 +143,11 @@ $poller_end = microtime(true); $stats = - 'Time:' . round($poller_end - $poller_start, 2) . - ' Reboots:' . $reboots . - ' DownDevices:' . $recent_down . - ' Notifications:' . $notifications . - ' Purges:' . ($purge_n + $purge_r); + 'Time:' . round($poller_end - $poller_start, 2) . + ' Reboots:' . $reboots . + ' DownDevices:' . $recent_down . + ' Notifications:' . $notifications . + ' Purges:' . ($purge_n + $purge_r); cacti_log('MONITOR STATS: ' . $stats, false, 'SYSTEM'); set_config_option('stats_monitor', $stats); From abbbec81ac77d284b8e8f4a951658b8e3b1df550 Mon Sep 17 00:00:00 2001 From: Sean Mancini Date: Tue, 3 Mar 2026 17:08:03 -0500 Subject: [PATCH 26/26] missed 2 commits --- images/index.php | 2 +- locales/LC_MESSAGES/index.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/images/index.php b/images/index.php index e085c75..b8c7e48 100644 --- a/images/index.php +++ b/images/index.php @@ -1,6 +1,6 @@