From 8f03e2b9e322dfa20eca2266fc64fe3b80051646 Mon Sep 17 00:00:00 2001 From: TheWitness Date: Thu, 9 Apr 2026 22:57:01 -0400 Subject: [PATCH 01/10] fix: PSR, PHPDoc, Prepared Statements, More Timespan * PSR including short array syntax * PHPDoc Block Repairs * PHPCSFixit Using Cacti Ruleset * Convert to prepared statements where possible * More Timespan Changes --- database.php | 167 +-- functions.php | 850 ++++++------ images/index.php | 1 - index.php | 1 - locales/LC_MESSAGES/index.php | 1 - locales/index.php | 1 - locales/po/index.php | 1 - setup.php | 754 ++++++----- syslog.php | 1178 +++++++++-------- syslog_alerts.php | 668 +++++----- syslog_batch_transfer.php | 46 +- syslog_counter.php | 19 +- syslog_process.php | 24 +- syslog_removal.php | 512 +++---- syslog_reports.php | 558 ++++---- template/index.php | 1 - .../issue253_alert_sql_placeholder_test.php | 18 +- .../issue254_partition_table_locking_test.php | 51 +- .../issue258_replication_create_sql_test.php | 30 +- ...issue269_import_text_branch_logic_test.php | 8 +- .../issue269_import_text_trim_check_test.php | 13 +- ...ue276_bulk_action_dispatch_helper_test.php | 5 +- .../issue277_import_payload_loader_test.php | 5 +- ...sue278_command_execution_refactor_test.php | 20 +- 24 files changed, 2601 insertions(+), 2331 deletions(-) diff --git a/database.php b/database.php index 29beeef..1b6e711 100644 --- a/database.php +++ b/database.php @@ -24,20 +24,22 @@ /** * syslog_db_connect_real - makes a connection to the database server - * @param $host - the hostname of the database server, 'localhost' if the database server is running - * on this machine - * - * @param $user - the username to connect to the database server as - * @param $pass - the password to connect to the database server with - * @param $db_name - the name of the database to connect to - * @param $db_type - the type of database server to connect to, only 'mysql' is currently supported - * @param $retries - the number a time the server should attempt to connect before failing - * @param $db_ssl - true or false, is the database using ssl - * @param $db_ssl_key - the path to the ssl key file - * @param $db_ssl_cert - the path to the ssl cert file - * @param $db_ssl_ca - the path to the ssl ca file - * - * @return (object) connection_id for success, (bool) '0' for error + * + * @param string $host The hostname of the database server, + * 'localhost' if the database server is running + * on this machine + * @param string $user The username to connect to the database server as + * @param string $pass The password to connect to the database server with + * @param string $db_name The name of the database to connect to + * @param string $db_type The type of database server to connect to, only 'mysql' is currently supported + * @param int $port The database port. Defaults to 3306 + * @param int $retries The number a time the server should attempt to connect before failing + * @param bool $db_ssl true or false, is the database using ssl + * @param string $db_ssl_key The path to the ssl key file + * @param string $db_ssl_cert The path to the ssl cert file + * @param string $db_ssl_ca The path to the ssl ca file + * + * @return object|bool connection_id for success, or bool false for error */ function syslog_db_connect_real($host, $user, $pass, $db_name, $db_type, $port = '3306', $retries = 20, $db_ssl = '', $db_ssl_key = '', $db_ssl_cert = '', $db_ssl_ca = '') { @@ -47,9 +49,9 @@ function syslog_db_connect_real($host, $user, $pass, $db_name, $db_type, $port = /** * syslog_db_close - closes the open connection * - * @param $syslog_cnn - the connection object to connect to + * @param object $syslog_cnn The connection object to connect to * - * @return the result of the close command + * @return bool the result of the close command */ function syslog_db_close($syslog_cnn) { return db_close($syslog_cnn); @@ -58,193 +60,210 @@ function syslog_db_close($syslog_cnn) { /** * syslog_db_execute - run an sql query and do not return any output * - * @param $syslog_cnn - the connection object to connect to - * @param $sql - the sql query to execute - * @param $log - whether to log error messages, defaults to true + * @param string $sql The sql query to execute + * @param bool $log Whether to log error messages, defaults to true * - * @return '1' for success, '0' for error + * @return int 1 for success, 0 for error */ -function syslog_db_execute($sql, $log = TRUE) { +function syslog_db_execute($sql, $log = true) { global $syslog_cnn; + return db_execute($sql, $log, $syslog_cnn); } /** * syslog_db_execute_prepared - run an sql query and do not return any output * - * @param $sql - the sql query to execute - * @param $log - whether to log error messages, defaults to true + * @param string $sql The sql query to execute + * @param array $parms The sql params for the prepare + * @param bool $log Whether to log error messages, defaults to true * * @return '1' for success, '0' for error */ -function syslog_db_execute_prepared($sql, $parms = array(), $log = TRUE) { +function syslog_db_execute_prepared($sql, $parms = [], $log = true) { global $syslog_cnn; + return db_execute_prepared($sql, $parms, $log, $syslog_cnn); } /** * syslog_db_fetch_cell - run a 'select' sql query and return the first column of the - * first row found + * first row found * - * @param $sql - the sql query to execute - * @param $log - whether to log error messages, defaults to true - * @param $col_name - use this column name instead of the first one + * @param string $sql The sql query to execute + * @param string $col_name Use this column name instead of the first one + * @param bool $log Whether to log error messages, defaults to true * - * @return (bool) the output of the sql query as a single variable + * @return bool the output of the sql query as a single variable */ -function syslog_db_fetch_cell($sql, $col_name = '', $log = TRUE) { +function syslog_db_fetch_cell($sql, $col_name = '', $log = true) { global $syslog_cnn; + return db_fetch_cell($sql, $col_name, $log, $syslog_cnn); } /** * syslog_db_fetch_cell_prepared - run a 'select' sql query and return the first column of the - * first row found + * first row found * - * @param $sql - the sql query to execute - * @param $params - an array of parameters - * @param $col_name - use this column name instead of the first one - * @param $log - whether to log error messages, defaults to true + * @param string $sql The sql query to execute + * @param array $params An array of parameters + * @param string $col_name Use this column name instead of the first one + * @param bool $log Whether to log error messages, defaults to true * - * @return (bool) the output of the sql query as a single variable + * @return bool The output of the sql query as a single variable */ -function syslog_db_fetch_cell_prepared($sql, $params = array(), $col_name = '', $log = TRUE) { +function syslog_db_fetch_cell_prepared($sql, $params = [], $col_name = '', $log = true) { global $syslog_cnn; + return db_fetch_cell_prepared($sql, $params, $col_name, $log, $syslog_cnn); } /** * syslog_db_fetch_row - run a 'select' sql query and return the first row found * - * @param $sql - the sql query to execute - * @param $log - whether to log error messages, defaults to true + * @param string $sql The sql query to execute + * @param bool $log Whether to log error messages, defaults to true * - * @return the first row of the result as a hash + * @return array|bool The first row of the result as a hash */ -function syslog_db_fetch_row($sql, $log = TRUE) { +function syslog_db_fetch_row($sql, $log = true) { global $syslog_cnn; + return db_fetch_row($sql, $log, $syslog_cnn); } /** * syslog_db_fetch_row_prepared - run a 'select' sql query and return the first row found * - * @param $sql - the sql query to execute - * @param $params - an array of parameters - * @param $log - whether to log error messages, defaults to true + * @param string $sql The sql query to execute + * @param array $params An array of parameters + * @param bool $log Whether to log error messages, defaults to true * - * @return the first row of the result as a hash + * @return array|bool The first row of the result as a hash */ -function syslog_db_fetch_row_prepared($sql, $params = array(), $log = TRUE) { +function syslog_db_fetch_row_prepared($sql, $params = [], $log = true) { global $syslog_cnn; + return db_fetch_row_prepared($sql, $params, $log, $syslog_cnn); } /** * syslog_db_fetch_assoc - run a 'select' sql query and return all rows found * - * @param $sql - the sql query to execute - * @param $log - whether to log error messages, defaults to true + * @param string $sql The sql query to execute + * @param bool $log Whether to log error messages, defaults to true * - * @return the entire result set as a multi-dimensional hash + * @return array|bool The entire result set as a multi-dimensional hash */ -function syslog_db_fetch_assoc($sql, $log = TRUE) { +function syslog_db_fetch_assoc($sql, $log = true) { global $syslog_cnn; + return db_fetch_assoc($sql, $log, $syslog_cnn); } /** * syslog_db_fetch_assoc_prepared - run a 'select' sql query and return all rows found * - * @param $sql - the sql query to execute - * @param $params - an array of parameters - * @param $log - whether to log error messages, defaults to true + * @param string $sql The sql query to execute + * @param array $params An array of parameters + * @param bool $log Whether to log error messages, defaults to true * - * @return the entire result set as a multi-dimensional hash + * @return array|bool The entire result set as a multi-dimensional hash */ -function syslog_db_fetch_assoc_prepared($sql, $params = array(), $log = TRUE) { +function syslog_db_fetch_assoc_prepared($sql, $params = [], $log = true) { global $syslog_cnn; + return db_fetch_assoc_prepared($sql, $params, $log, $syslog_cnn); } /** * syslog_db_fetch_insert_id - get the last insert_id or auto incriment * - * @param $syslog_cnn - the connection object to connect to + * @param object $syslog_cnn The connection object to connect to * - * @return the id of the last auto incriment row that was created + * @return int The id of the last auto incriment row that was created */ function syslog_db_fetch_insert_id() { global $syslog_cnn; - return db_fetch_insert_id($syslog_cnn); + + return db_fetch_insert_id($syslog_cnn); } /** * syslog_db_replace - replaces the data contained in a particular row * - * @param $table_name - the name of the table to make the replacement in - * @param $array_items - an array containing each column -> value mapping in the row - * @param $keyCols - the name of the column containing the primary key - * @param $autoQuote - whether to use intelligent quoting or not + * @param string $table_name The name of the table to make the replacement in + * @param array $array_items An array containing each column -> value mapping in the row + * @param mixed $keyCols The name of the column containing the primary key + * @param bool $autoQuote Whether to use intelligent quoting or not * - * @return the auto incriment id column (if applicable) + * @return bool The auto incriment id column (if applicable) */ function syslog_db_replace($table_name, $array_items, $keyCols) { global $syslog_cnn; + return db_replace($table_name, $array_items, $keyCols, $syslog_cnn); } /** * syslog_sql_save - saves data to an sql table * - * @param $array_items - an array containing each column -> value mapping in the row - * @param $table_name - the name of the table to make the replacement in - * @param $key_cols - the primary key(s) + * @param array $array_items An array containing each column -> value mapping in the row + * @param string $table_name The name of the table to make the replacement in + * @param mixed $key_cols The primary key(s) + * @param bool $autoinc Is the primary key autoinc * - * @return the auto incriment id column (if applicable) + * @return int The auto incriment id column (if applicable) */ function syslog_sql_save($array_items, $table_name, $key_cols = 'id', $autoinc = true) { global $syslog_cnn; + return sql_save($array_items, $table_name, $key_cols, $autoinc, $syslog_cnn); } /** * syslog_db_table_exists - checks whether a table exists * - * @param $table - the name of the table - * @param $log - whether to log error messages, defaults to true + * @param string $table The name of the table + * @param bool $log Whether to log error messages, defaults to true * - * @return (bool) the output of the sql query as a single variable + * @return bool The output of the sql query as a single variable */ function syslog_db_table_exists($table, $log = true) { global $syslog_cnn; preg_match("/([`]{0,1}(?[\w_]+)[`]{0,1}\.){0,1}[`]{0,1}(?[\w_]+)[`]{0,1}/", $table, $matches); + if ($matches !== false && array_key_exists('table', $matches)) { $sql = 'SHOW TABLES LIKE \'' . $matches['table'] . '\''; + return (db_fetch_cell($sql, '', $log, $syslog_cnn) ? true : false); } + return false; } function syslog_db_column_exists($table, $column, $log = true) { global $syslog_cnn; + return db_column_exists($table, $column, $log, $syslog_cnn); } function syslog_db_add_column($table, $column, $log = true) { global $syslog_cnn; + return db_add_column($table, $column, $log, $syslog_cnn); } /** * syslog_db_affected_rows - return the number of rows affected by the last transaction * - * @return (bool|int) The number of rows affected by the last transaction, - * or false on error + * @return bool|int The number of rows affected by the last transaction, + * or false on error */ function syslog_db_affected_rows() { global $syslog_cnn; - return db_affected_rows($syslog_cnn);; -} + return db_affected_rows($syslog_cnn); +} diff --git a/functions.php b/functions.php index 777959c..5a6c3bb 100644 --- a/functions.php +++ b/functions.php @@ -28,7 +28,7 @@ function syslog_apply_selected_items_action($selected_items, $drp_action, $actio $action_function = $action_map[$drp_action]; if (function_exists($action_function)) { - foreach($selected_items as $selected_item) { + foreach ($selected_items as $selected_item) { $action_function($selected_item); } } else { @@ -43,7 +43,7 @@ function syslog_apply_selected_items_action($selected_items, $drp_action, $actio function syslog_include_js() { global $config; ?> - + 0) { $retention = date('Y-m-d', time() - (86400 * read_config_option('syslog_retention'))); } else { @@ -216,13 +217,13 @@ function syslog_traditional_manage() { set_config_option('syslog_retention', '30'); } - /* delete from the main syslog table first */ - syslog_db_execute("DELETE FROM `" . $syslogdb_default . "`.`syslog` WHERE logtime < '$retention'"); + // delete from the main syslog table first + syslog_db_execute('DELETE FROM `' . $syslogdb_default . "`.`syslog` WHERE logtime < '$retention'"); $syslog_deleted = db_affected_rows($syslog_cnn); - /* now delete from the syslog removed table */ - syslog_db_execute("DELETE FROM `" . $syslogdb_default . "`.`syslog_removed` WHERE logtime < '$retention'"); + // now delete from the syslog removed table + syslog_db_execute('DELETE FROM `' . $syslogdb_default . "`.`syslog_removed` WHERE logtime < '$retention'"); $syslog_deleted += db_affected_rows($syslog_cnn); @@ -256,13 +257,15 @@ function syslog_partition_manage() { * Any value added to the allowlist MUST match ^[a-z_]+$ so it is safe * for identifier interpolation in DDL statements (MySQL does not support * parameter binding for identifiers). + * + * @param mixed $table */ function syslog_partition_table_allowed($table) { - if (!in_array($table, array('syslog', 'syslog_removed'), true)) { + if (!in_array($table, ['syslog', 'syslog_removed'], true)) { return false; } - /* Defense-in-depth: reject values unsafe for identifier interpolation. */ + // Defense-in-depth: reject values unsafe for identifier interpolation. if (!preg_match('/^[a-z_]+$/', $table)) { return false; } @@ -273,6 +276,8 @@ function syslog_partition_table_allowed($table) { /** * Create a new partition for the specified table. * + * @param mixed $table + * * @return bool true on success, false on lock failure or disallowed table. */ function syslog_partition_create($table) { @@ -282,7 +287,7 @@ function syslog_partition_create($table) { return false; } - /* Hash to guarantee the lock name stays within MySQL's 64-byte limit. */ + // Hash to guarantee the lock name stays within MySQL's 64-byte limit. $lock_name = substr(hash('sha256', $syslogdb_default . '.syslog_partition_create.' . $table), 0, 60); /* @@ -290,32 +295,34 @@ function syslog_partition_create($table) { * poller cycle (typically 5 minutes), so sustained contention is not * expected. A failure is logged so monitoring can detect repeated misses. */ - $locked = syslog_db_fetch_cell_prepared('SELECT GET_LOCK(?, 10)', array($lock_name)); + $locked = syslog_db_fetch_cell_prepared('SELECT GET_LOCK(?, 10)', [$lock_name]); if ($locked === null) { - /* NULL means the GET_LOCK call itself failed, not just contention. */ + // NULL means the GET_LOCK call itself failed, not just contention. cacti_log("SYSLOG: GET_LOCK call failed for partition create on '$table'", false, 'SYSTEM'); + return false; } if ((int)$locked !== 1) { cacti_log("SYSLOG: Unable to acquire partition create lock for '$table'", false, 'SYSTEM'); + return false; } try { - /* determine the format of the table name */ + // determine the format of the table name $time = time(); $cformat = 'd' . date('Ymd', $time); - $lnow = date('Y-m-d', $time+86400); + $lnow = date('Y-m-d', $time + 86400); - $exists = syslog_db_fetch_row_prepared("SELECT * + $exists = syslog_db_fetch_row_prepared('SELECT * FROM `information_schema`.`partitions` WHERE table_schema = ? AND partition_name = ? AND table_name = ? - ORDER BY partition_ordinal_position", - array($syslogdb_default, $cformat, $table)); + ORDER BY partition_ordinal_position', + [$syslogdb_default, $cformat, $table]); if (!cacti_sizeof($exists)) { cacti_log("SYSLOG: Creating new partition '$cformat'", false, 'SYSTEM'); @@ -329,12 +336,12 @@ function syslog_partition_create($table) { * regex guard). $cformat and $lnow derive from date() and * contain only digits, hyphens, and the letter 'd'. */ - syslog_db_execute("ALTER TABLE `" . $syslogdb_default . "`.`$table` REORGANIZE PARTITION dMaxValue INTO ( + syslog_db_execute('ALTER TABLE `' . $syslogdb_default . "`.`$table` REORGANIZE PARTITION dMaxValue INTO ( PARTITION $cformat VALUES LESS THAN (TO_DAYS('$lnow')), PARTITION dMaxValue VALUES LESS THAN MAXVALUE)"); } } finally { - syslog_db_fetch_cell_prepared('SELECT RELEASE_LOCK(?)', array($lock_name)); + syslog_db_fetch_cell_prepared('SELECT RELEASE_LOCK(?)', [$lock_name]); } return true; @@ -342,37 +349,42 @@ function syslog_partition_create($table) { /** * Remove old partitions for the specified table. + * + * @param mixed $table */ function syslog_partition_remove($table) { global $syslogdb_default; if (!syslog_partition_table_allowed($table)) { cacti_log("SYSLOG: partition_remove called with disallowed table '$table'", false, 'SYSTEM'); + return 0; } $lock_name = substr(hash('sha256', $syslogdb_default . '.syslog_partition_remove.' . $table), 0, 60); - $locked = syslog_db_fetch_cell_prepared('SELECT GET_LOCK(?, 10)', array($lock_name)); + $locked = syslog_db_fetch_cell_prepared('SELECT GET_LOCK(?, 10)', [$lock_name]); if ($locked === null) { cacti_log("SYSLOG: GET_LOCK call failed for partition remove on '$table'", false, 'SYSTEM'); + return 0; } if ((int)$locked !== 1) { cacti_log("SYSLOG: Unable to acquire partition remove lock for '$table'", false, 'SYSTEM'); + return 0; } $syslog_deleted = 0; try { - $number_of_partitions = syslog_db_fetch_assoc_prepared("SELECT * + $number_of_partitions = syslog_db_fetch_assoc_prepared('SELECT * FROM `information_schema`.`partitions` WHERE table_schema = ? AND table_name = ? - ORDER BY partition_ordinal_position", - array($syslogdb_default, $table)); + ORDER BY partition_ordinal_position', + [$syslogdb_default, $table]); $days = read_config_option('syslog_retention'); @@ -380,8 +392,10 @@ function syslog_partition_remove($table) { if ($days > 0) { $user_partitions = sizeof($number_of_partitions) - 1; + if ($user_partitions >= $days) { $i = 0; + while ($user_partitions > $days) { $oldest = $number_of_partitions[$i]; @@ -389,7 +403,7 @@ function syslog_partition_remove($table) { syslog_debug("Removing partition '" . $oldest['PARTITION_NAME'] . "'"); - syslog_db_execute("ALTER TABLE `" . $syslogdb_default . "`.`$table` DROP PARTITION " . $oldest['PARTITION_NAME']); + syslog_db_execute('ALTER TABLE `' . $syslogdb_default . "`.`$table` DROP PARTITION " . $oldest['PARTITION_NAME']); $i++; $user_partitions--; @@ -398,7 +412,7 @@ function syslog_partition_remove($table) { } } } finally { - syslog_db_fetch_cell_prepared('SELECT RELEASE_LOCK(?)', array($lock_name)); + syslog_db_fetch_cell_prepared('SELECT RELEASE_LOCK(?)', [$lock_name]); } return $syslog_deleted; @@ -422,13 +436,13 @@ function syslog_partition_check($table) { include(SYSLOG_CONFIG); } - /* find date of last partition */ - $last_part = syslog_db_fetch_cell_prepared("SELECT PARTITION_NAME + // find date of last partition + $last_part = syslog_db_fetch_cell_prepared('SELECT PARTITION_NAME FROM `information_schema`.`partitions` WHERE table_schema = ? AND table_name = ? ORDER BY partition_ordinal_position DESC - LIMIT 1,1", - array($syslogdb_default, $table)); + LIMIT 1,1', + [$syslogdb_default, $table]); $lformat = str_replace('d', '', $last_part); $cformat = date('Ymd'); @@ -456,8 +470,8 @@ function syslog_remove_items($table, $max_seq) { syslog_debug('Processing Removal Rules...'); if ($table == 'syslog') { - $rows = syslog_db_fetch_assoc("SELECT * - FROM `" . $syslogdb_default . "`.`syslog_remove` + $rows = syslog_db_fetch_assoc('SELECT * + FROM `' . $syslogdb_default . "`.`syslog_remove` WHERE enabled = 'on'"); } else { $rows = syslog_db_fetch_assoc('SELECT * @@ -475,15 +489,15 @@ function syslog_remove_items($table, $max_seq) { FROM `' . $syslogdb_default . '`.`syslog_incoming` WHERE `status` = 1 AND `seq` <= ?', - array($max_seq)); + [$max_seq]); } else { $total = 0; } if (cacti_sizeof($rows)) { - foreach($rows as $remove) { + foreach ($rows as $remove) { $sql_where = ''; - $params = array(); + $params = []; if ($remove['type'] == 'facility') { if ($table == 'syslog_incoming') { @@ -496,14 +510,14 @@ function syslog_remove_items($table, $max_seq) { } else { $facility_id = syslog_db_fetch_cell_prepared('SELECT facility_id FROM `' . $syslogdb_default . '`.`syslog_facilities` - WHERE facility = ?', array($remove['message'])); + WHERE facility = ?', [$remove['message']]); if (!empty($facility_id)) { $sql_where = 'WHERE facility_id = ?'; $params[] = $facility_id; } } - } else if ($remove['type'] == 'program') { + } elseif ($remove['type'] == 'program') { if ($table == 'syslog_incoming') { $sql_where = 'WHERE `program` = ? AND `status` = 1 @@ -514,7 +528,7 @@ function syslog_remove_items($table, $max_seq) { } else { $program_id = syslog_db_fetch_cell_prepared('SELECT program_id FROM `' . $syslogdb_default . '`.`syslog_programs` - WHERE program = ?', array($remove['message'])); + WHERE program = ?', [$remove['message']]); if (!empty($program_id)) { $sql_where = 'WHERE program_id = ?'; @@ -532,7 +546,7 @@ function syslog_remove_items($table, $max_seq) { } else { $host_id = syslog_db_fetch_cell_prepared('SELECT host_id FROM `' . $syslogdb_default . '`.`syslog_hosts` - WHERE host = ?', array($remove['message'])); + WHERE host = ?', [$remove['message']]); if (!empty($host_id)) { $sql_where = 'WHERE host_id = ?'; @@ -622,65 +636,85 @@ function syslog_remove_items($table, $max_seq) { syslog_debug(sprintf('Removed %5s - Record(s) from ' . $table, $removed)); syslog_debug(sprintf('Xferred %5s - Record(s) to the syslog_removed table', $xferred)); - return array('removed' => $removed, 'xferred' => $xferred); + return ['removed' => $removed, 'xferred' => $xferred]; } -/** function syslog_log_row_color() - * This function set's the CSS for each row of the syslog table as it is displayed - * it supports both the legacy as well as the new approach to controlling these - * colors. -*/ +/** + * function syslog_log_row_color() + * This function set's the CSS for each row of the syslog table as it is displayed + * it supports both the legacy as well as the new approach to controlling these + * colors. + * + * @param mixed $severity + * @param mixed $tip_title + */ function syslog_log_row_color($severity, $tip_title) { switch($severity) { - case '': - case '0': - $class = 'logInfo'; - break; - case '1': - $class = 'logWarning'; - break; - case '2': - $class = 'logAlert'; - break; + case '': + case '0': + $class = 'logInfo'; + + break; + case '1': + $class = 'logWarning'; + + break; + case '2': + $class = 'logAlert'; + + break; } print "\n"; } -/** function syslog_row_color() - * This function set's the CSS for each row of the syslog table as it is displayed - * it supports both the legacy as well as the new approach to controlling these - * colors. -*/ +/** + * function syslog_row_color() + * This function set's the CSS for each row of the syslog table as it is displayed + * it supports both the legacy as well as the new approach to controlling these + * colors. + * + * @param mixed $priority + * @param mixed $message + */ function syslog_row_color($priority, $message) { switch($priority) { - case '0': - $class = 'logEmergency'; - break; - case '1': - $class = 'logAlert'; - break; - case '2': - $class = 'logCritical'; - break; - case '3': - $class = 'logError'; - break; - case '4': - $class = 'logWarning'; - break; - case '5': - $class = 'logNotice'; - break; - case '6': - $class = 'logInfo'; - break; - case '7': - $class = 'logDebug'; - break; + case '0': + $class = 'logEmergency'; + + break; + case '1': + $class = 'logAlert'; + + break; + case '2': + $class = 'logCritical'; + + break; + case '3': + $class = 'logError'; + + break; + case '4': + $class = 'logWarning'; + + break; + case '5': + $class = 'logNotice'; + + break; + case '6': + $class = 'logInfo'; + + break; + case '7': + $class = 'logDebug'; + + break; } print ""; + return $class; } @@ -690,19 +724,20 @@ function sql_hosts_where($tab) { $hostfilter = ''; $hostfilter_log = ''; - $hosts_array = array(); + $hosts_array = []; if (!isempty_request_var('host') && get_nfilter_request_var('host') != 'null') { $hostarray = explode(',', trim(get_nfilter_request_var('host'))); + if ($hostarray[0] != '0') { - foreach($hostarray as $host_id) { + foreach ($hostarray as $host_id) { input_validate_input_number($host_id); if ($host_id > 0) { $log_host = syslog_db_fetch_cell_prepared('SELECT host FROM `' . $syslogdb_default . '`.`syslog_hosts` WHERE host_id = ?', - array($host_id)); + [$host_id]); if (!empty($log_host)) { $hosts_array[] = db_qstr($log_host); @@ -714,7 +749,7 @@ function sql_hosts_where($tab) { $hostfilter_log = ' host IN(' . implode(',', $hosts_array) . ')'; } - $hostfilter .= ($hostfilter != '' ? ' AND ':'') . ' host_id IN(' . implode(',', $hostarray) . ')'; + $hostfilter .= ($hostfilter != '' ? ' AND ' : '') . ' host_id IN(' . implode(',', $hostarray) . ')'; } } } @@ -786,14 +821,13 @@ function syslog_export($tab) { $host = 'Unknown'; } - print - '"' . - $host . '","' . - ucfirst($facility) . '","' . - ucfirst($priority) . '","' . - ucfirst($program) . '","' . - $message['logtime'] . '","' . - $message[$syslog_incoming_config['textField']] . '"' . "\r\n"; + print '"' . + $host . '","' . + ucfirst($facility) . '","' . + ucfirst($priority) . '","' . + ucfirst($program) . '","' . + $message['logtime'] . '","' . + $message[$syslog_incoming_config['textField']] . '"' . "\r\n"; } } } else { @@ -813,16 +847,15 @@ function syslog_export($tab) { $severity = 'Unknown'; } - print - '"' . - $message['name'] . '","' . - $severity . '","' . - $message['logtime'] . '","' . - $message['logmsg'] . '","' . - $message['host'] . '","' . - ucfirst($message['facility']) . '","' . - ucfirst($message['priority']) . '","' . - $message['count'] . '"' . "\r\n"; + print '"' . + $message['name'] . '","' . + $severity . '","' . + $message['logtime'] . '","' . + $message['logmsg'] . '","' . + $message['host'] . '","' . + ucfirst($message['facility']) . '","' . + ucfirst($message['priority']) . '","' . + $message['count'] . '"' . "\r\n"; } } } @@ -836,7 +869,7 @@ function syslog_debug($message) { } } -function syslog_log_alert($alert_id, $alert_name, $severity, $msg, $count = 1, $html = '', $hosts = array()) { +function syslog_log_alert($alert_id, $alert_name, $severity, $msg, $count = 1, $html = '', $hosts = []) { global $config, $severities; global $syslogdb_default; @@ -881,7 +914,7 @@ function syslog_log_alert($alert_id, $alert_name, $severity, $msg, $count = 1, $ $save['alert_name'] = $alert_name; if (cacti_sizeof($hosts)) { - foreach($hosts as $host) { + foreach ($hosts as $host) { $save['host'] = $host; api_plugin_hook_function('syslog_update_hostsalarm', $save); } @@ -897,7 +930,7 @@ function syslog_manage_items($from_table, $to_table) { global $config, $syslog_cnn, $syslog_incoming_config; global $syslogdb_default; - /* Select filters to work on */ + // Select filters to work on $rows = syslog_db_fetch_assoc('SELECT * FROM `' . $syslogdb_default . "`.`syslog_remove` WHERE enabled='on'"); syslog_debug(sprintf('Found %5s - Removal Rule(s) to process', cacti_sizeof($rows))); @@ -907,7 +940,7 @@ function syslog_manage_items($from_table, $to_table) { $total = 0; if (cacti_sizeof($rows)) { - foreach($rows as $remove) { + foreach ($rows as $remove) { syslog_debug('Processing Rule - ' . $remove['message']); $sql_sel = ''; @@ -915,93 +948,93 @@ function syslog_manage_items($from_table, $to_table) { if ($remove['type'] == 'facility') { if ($remove['method'] != 'del') { - $sql_sel = "SELECT seq FROM `" . $syslogdb_default . "`. $from_table + $sql_sel = 'SELECT seq FROM `' . $syslogdb_default . "`. $from_table WHERE facility_id IN - (SELECT distinct facility_id FROM `". $syslogdb_default . "`syslog_facilities - WHERE facility ='". $remove['message']."')"; + (SELECT distinct facility_id FROM `" . $syslogdb_default . "`syslog_facilities + WHERE facility ='" . $remove['message'] . "')"; } else { - $sql_dlt = "DELETE FROM `" . $syslogdb_default . "`. $from_table + $sql_dlt = 'DELETE FROM `' . $syslogdb_default . "`. $from_table WHERE facility_id IN - (SELECT distinct facility_id FROM `". $syslogdb_default . "`syslog_facilities - WHERE facility ='". $remove['message']."')"; + (SELECT distinct facility_id FROM `" . $syslogdb_default . "`syslog_facilities + WHERE facility ='" . $remove['message'] . "')"; } - } elseif ($remove['type'] == 'host') { if ($remove['method'] != 'del') { - $sql_sel = "SELECT seq - FROM `" . $syslogdb_default . "`. $from_table + $sql_sel = 'SELECT seq + FROM `' . $syslogdb_default . "`. $from_table WHERE host_id in - (SELECT distinct host_id FROM `". $syslogdb_default . "`syslog_hosts - WHERE host ='". $remove['message']."')"; + (SELECT distinct host_id FROM `" . $syslogdb_default . "`syslog_hosts + WHERE host ='" . $remove['message'] . "')"; } else { - $sql_dlt = "DELETE FROM `" . $syslogdb_default . "`. $from_table + $sql_dlt = 'DELETE FROM `' . $syslogdb_default . "`. $from_table WHERE host_id in - (SELECT distinct host_id FROM `". $syslogdb_default . "`syslog_hosts - WHERE host ='". $remove['message']."')"; + (SELECT distinct host_id FROM `" . $syslogdb_default . "`syslog_hosts + WHERE host ='" . $remove['message'] . "')"; } } elseif ($remove['type'] == 'messageb') { if ($remove['method'] != 'del') { - $sql_sel = "SELECT seq FROM `" . $syslogdb_default . "`. $from_table + $sql_sel = 'SELECT seq FROM `' . $syslogdb_default . "`. $from_table WHERE message LIKE '" . $remove['message'] . "%' "; } else { - $sql_dlt = "DELETE FROM `" . $syslogdb_default . "`. $from_table + $sql_dlt = 'DELETE FROM `' . $syslogdb_default . "`. $from_table WHERE message LIKE '" . $remove['message'] . "%' "; } - } elseif ($remove['type'] == 'messagec') { if ($remove['method'] != 'del') { - $sql_sel = "SELECT seq FROM `" . $syslogdb_default . "`. $from_table + $sql_sel = 'SELECT seq FROM `' . $syslogdb_default . "`. $from_table WHERE message LIKE '%" . $remove['message'] . "%' "; } else { - $sql_dlt = "DELETE FROM `" . $syslogdb_default . "`. $from_table + $sql_dlt = 'DELETE FROM `' . $syslogdb_default . "`. $from_table WHERE message LIKE '%" . $remove['message'] . "%' "; } } elseif ($remove['type'] == 'messagee') { if ($remove['method'] != 'del') { - $sql_sel = "SELECT seq FROM `" . $syslogdb_default . "`. $from_table + $sql_sel = 'SELECT seq FROM `' . $syslogdb_default . "`. $from_table WHERE message LIKE '%" . $remove['message'] . "' "; } else { - $sql_dlt = "DELETE FROM `" . $syslogdb_default . "`. $from_table + $sql_dlt = 'DELETE FROM `' . $syslogdb_default . "`. $from_table WHERE message LIKE '%" . $remove['message'] . "' "; } } elseif ($remove['type'] == 'sql') { if ($remove['method'] != 'del') { - $sql_sel = "SELECT seq FROM `" . $syslogdb_default . "`. $from_table - WHERE message (" . $remove['message'] . ") "; + $sql_sel = 'SELECT seq FROM `' . $syslogdb_default . "`. $from_table + WHERE message (" . $remove['message'] . ') '; } else { - $sql_dlt = "DELETE FROM `" . $syslogdb_default . "`. $from_table - WHERE message (" . $remove['message'] . ") "; + $sql_dlt = 'DELETE FROM `' . $syslogdb_default . "`. $from_table + WHERE message (" . $remove['message'] . ') '; } } if ($sql_sel != '' || $sql_dlt != '') { $debugm = ''; - /* process the removal rule first */ + + // process the removal rule first if ($sql_sel != '') { $move_count = 0; - /* first insert, then delete */ + // first insert, then delete $move_records = syslog_db_fetch_assoc($sql_sel); syslog_debug(sprintf('Found %5s - Message(s)', cacti_sizeof($move_records))); if (cacti_sizeof($move_records)) { - $all_seq = ''; + $all_seq = ''; $messages_moved = 0; - foreach($move_records as $move_record) { - $all_seq = $all_seq . ", " . $move_record['seq']; + + foreach ($move_records as $move_record) { + $all_seq = $all_seq . ', ' . $move_record['seq']; } $all_seq = preg_replace('/^,/i', '', $all_seq); - syslog_db_execute("INSERT INTO `". $syslogdb_default . "`.`". $to_table ."` + syslog_db_execute('INSERT INTO `' . $syslogdb_default . '`.`' . $to_table . '` (facility_id, priority_id, host_id, logtime, message) (SELECT facility_id, priority_id, host_id, logtime, message - FROM `". $syslogdb_default . "`.". $from_table ." - WHERE seq IN (" . $all_seq ."))"); + FROM `' . $syslogdb_default . '`.' . $from_table . ' + WHERE seq IN (' . $all_seq . '))'); $messages_moved = db_affected_rows($syslog_cnn); if ($messages_moved > 0) { - syslog_db_execute("DELETE FROM `". $syslogdb_default . "`.`" . $from_table ."` - WHERE seq IN (" . $all_seq .")" ); + syslog_db_execute('DELETE FROM `' . $syslogdb_default . '`.`' . $from_table . '` + WHERE seq IN (' . $all_seq . ')'); } $xferred += $messages_moved; @@ -1012,7 +1045,7 @@ function syslog_manage_items($from_table, $to_table) { } if ($sql_dlt != '') { - /* now delete the remainder that match */ + // now delete the remainder that match syslog_db_execute($sql_dlt); $removed += db_affected_rows($syslog_cnn); $debugm = sprintf('Deleted %5s Message(s)', $removed); @@ -1023,25 +1056,32 @@ function syslog_manage_items($from_table, $to_table) { } } - return array('removed' => $removed, 'xferred' => $xferred); + return ['removed' => $removed, 'xferred' => $xferred]; } -/* get_hash_syslog - returns the current unique hash for an alert - @arg $id - (int) the ID of the syslog item to return a hash for - @returns - a 128-bit, hexadecimal hash */ +/** + * get_hash_syslog - returns the current unique hash for an alert + * + * @param mixed $id + * @param mixed $table + * + * @return string 128-bit hexadecimal hash + */ function get_hash_syslog($id, $table) { - $hash = syslog_db_fetch_cell_prepared('SELECT hash + $hash = syslog_db_fetch_cell_prepared('SELECT hash FROM ' . $table . ' WHERE id = ?', - array($id)); + [$id]); if (empty($hash)) { - return generate_hash(); - } elseif (preg_match('/[a-fA-F0-9]{32}/', $hash)) { - return $hash; - } else { - return generate_hash(); - } + return generate_hash(); + } + + if (preg_match('/[a-fA-F0-9]{32}/', $hash)) { + return $hash; + } else { + return generate_hash(); + } } function syslog_ia2xml($array) { @@ -1073,9 +1113,9 @@ function syslog_array2xml($array, $tag = 'template') { /** * syslog_execute_ticket_command - run the configured ticketing command for an alert * - * @param array $alert The alert row from syslog_alert table - * @param array $hostlist Hostnames matched by the alert - * @param string $error_message sprintf template used if exec() returns non-zero + * @param array $alert The alert row from syslog_alert table + * @param array $hostlist Hostnames matched by the alert + * @param string $error_message sprintf template used if exec() returns non-zero * * @return void */ @@ -1087,18 +1127,18 @@ function syslog_execute_ticket_command($alert, $hostlist, $error_message) { } if ($alert['open_ticket'] == 'on' && $command != '') { - /* trim surrounding quotes so paths like "/usr/bin/cmd" resolve correctly */ + // trim surrounding quotes so paths like "/usr/bin/cmd" resolve correctly $cparts = preg_split('/\s+/', trim($command)); $executable = trim($cparts[0], '"\''); if (cacti_sizeof($cparts) && is_executable($executable)) { $command = $command . ' --alert-name=' . cacti_escapeshellarg(clean_up_name($alert['name'])) . - ' --severity=' . cacti_escapeshellarg($alert['severity']) . - ' --hostlist=' . cacti_escapeshellarg(implode(',', $hostlist)) . - ' --message=' . cacti_escapeshellarg($alert['message']); + ' --severity=' . cacti_escapeshellarg($alert['severity']) . + ' --hostlist=' . cacti_escapeshellarg(implode(',', $hostlist)) . + ' --message=' . cacti_escapeshellarg($alert['message']); - $output = array(); + $output = []; $return = 0; exec($command, $output, $return); @@ -1118,9 +1158,9 @@ function syslog_execute_ticket_command($alert, $hostlist, $error_message) { /** * syslog_execute_alert_command - run the per-alert shell command for a matched result * - * @param array $alert The alert row from syslog_alert table - * @param array $results The matched syslog result row - * @param string $hostname Resolved hostname for the source device + * @param array $alert The alert row from syslog_alert table + * @param array $results The matched syslog result row + * @param string $hostname Resolved hostname for the source device * * @return void */ @@ -1132,11 +1172,11 @@ function syslog_execute_alert_command($alert, $results, $hostname) { * Do not introduce additional substitution paths that bypass this escaping. */ $command = alert_replace_variables($alert, $results, $hostname); - /* trim surrounding quotes so paths like "/usr/bin/cmd" resolve correctly */ + // trim surrounding quotes so paths like "/usr/bin/cmd" resolve correctly $cparts = preg_split('/\s+/', trim($command)); $executable = trim($cparts[0], '"\''); - $output = array(); + $output = []; $return = 0; if (cacti_sizeof($cparts) && is_executable($executable)) { @@ -1173,9 +1213,9 @@ function syslog_execute_alert_command($alert, $results, $hostname) { * and more importantly, to be able to have a separate re-alert cycles for that very same message as there can be similar messages * happening all the time at the system level, so it's hard to target a single host for re-alert rules. * - * @param (int) The max_seq to process + * @param int $max_seq The max_seq to process * - * @return (array) An array of the number of alerts processed and the number of alerts generated + * @return array An array of the number of alerts processed and the number of alerts generated */ function syslog_process_alerts($max_seq) { global $syslogdb_default; @@ -1183,7 +1223,7 @@ function syslog_process_alerts($max_seq) { $syslog_alarms = 0; $syslog_alerts = 0; - /* send out the alerts */ + // send out the alerts $alerts = syslog_db_fetch_assoc('SELECT * FROM `' . $syslogdb_default . "`.`syslog_alert` WHERE enabled='on'"); @@ -1199,11 +1239,11 @@ function syslog_process_alerts($max_seq) { syslog_debug(sprintf('Found %5s - Alert Rule(s) to process', $syslog_alerts)); if (cacti_sizeof($alerts)) { - foreach($alerts as $alert) { + foreach ($alerts as $alert) { $sql = ''; - $params = array(); + $params = []; - /* we roll up statistics depending on the level */ + // we roll up statistics depending on the level if ($alert['level'] == 1) { $groupBy = ' GROUP BY host'; } else { @@ -1214,6 +1254,7 @@ function syslog_process_alerts($max_seq) { if (!cacti_sizeof($sql_data)) { syslog_debug(sprintf('Error - Unable to determine SQL for Alert \'%s\'', $alert['name'])); + continue; } @@ -1226,7 +1267,7 @@ function syslog_process_alerts($max_seq) { $results = syslog_db_fetch_assoc_prepared($th_sql . $groupBy, $params); if (cacti_sizeof($results)) { - foreach($results as $result) { + foreach ($results as $result) { $aparams = $params; $aparams[] = $result['host']; @@ -1247,21 +1288,21 @@ function syslog_process_alerts($max_seq) { } } - return array('syslog_alerts' => $syslog_alerts, 'syslog_alarms' => $syslog_alarms); + return ['syslog_alerts' => $syslog_alerts, 'syslog_alarms' => $syslog_alarms]; } /** * syslog_process_alert - Process the Alert and generate notifications, execute commands, etc. * - * @param (array) The alert to process - * @param (string) The SQL to search for the Alert - * @param (array) The SQL parameters to be prepared into the SQL - * @param (int) In the case of a threshold alert, the number of occurrents - * of hosts with occurrences that were encountered through - * pre-processing the message - * @param (string) The hostname that this alert rule is for + * @param array $alert The alert to process + * @param string $sql The SQL to search for the Alert + * @param array $params The SQL parameters to be prepared into the SQL + * @param int $count In the case of a threshold alert, the number of occurrents + * of hosts with occurrences that were encountered through + * pre-processing the message + * @param string $hostname The hostname that this alert rule is for * - * @return (int) '1' if the alert triggered, else '0' + * @return int 1 if the alert triggered, else 0 */ function syslog_process_alert($alert, $sql, $params, $count, $hostname = '') { global $config, $severities, $syslog_levels; @@ -1273,7 +1314,7 @@ function syslog_process_alert($alert, $sql, $params, $count, $hostname = '') { $alert_count = 0; $syslog_alarms = 0; - $hostlist = array(); + $hostlist = []; $max_alerts = read_config_option('syslog_maxrecords'); $report_tag = false; $theme = false; @@ -1283,10 +1324,10 @@ function syslog_process_alert($alert, $sql, $params, $count, $hostname = '') { syslog_debug(sprintf('Processing - %s', $alert['name'])); if (read_config_option('syslog_html') == 'on') { - $html = true; + $html = true; $format_ok = reports_load_format_file(read_config_option('syslog_format_file'), $output, $report_tag, $theme); - syslog_debug('Format/CSS ' . ($format_ok ? 'Ok':'Not Ok') . ' - Report Tag ' . ($report_tag ? 'included':'missing')); + syslog_debug('Format/CSS ' . ($format_ok ? 'Ok' : 'Not Ok') . ' - Report Tag ' . ($report_tag ? 'included' : 'missing')); } else { $html = false; } @@ -1295,26 +1336,29 @@ function syslog_process_alert($alert, $sql, $params, $count, $hostname = '') { * format the from Email address */ $from_email = read_config_option('settings_from_email'); + if ($from_email == '') { $from_email = 'Cacti@cacti.net'; } $from_name = read_config_option('settings_from_name'); + if ($from_name == '') { $from_name = 'Cacti Reporting'; } - $from = array($from_email, $from_name); + $from = [$from_email, $from_name]; /** * format the destination Email addresses */ $alert['email'] = trim($alert['email'], ', '); + if ($alert['notify'] > 0) { $additional = db_fetch_cell_prepared('SELECT emails FROM plugin_notification_lists WHERE id = ?', - array($alert['notify'])); + [$alert['notify']]); if ($additional != '') { $alert['email'] .= ', ' . trim($additional, ' ,'); @@ -1344,7 +1388,7 @@ function syslog_process_alert($alert, $sql, $params, $count, $hostname = '') { /** * A list of all messages from the alert */ - $results = array(); + $results = []; syslog_debug(sprintf('Found %5s - Matching Records.', cacti_sizeof($at))); @@ -1359,16 +1403,16 @@ function syslog_process_alert($alert, $sql, $params, $count, $hostname = '') { if ($alert['method'] == '1') { if ($alert['body'] == '') { if ($hostname != '') { - $message .= '

' . __esc('Cacti Syslog Threshold Alert \'%s\' for Host \'%s\'', $alert['name'], $hostname, 'syslog') . '

'; + $message .= '

' . __esc('Cacti Syslog Threshold Alert \'%s\' for Host \'%s\'', $alert['name'], $hostname, 'syslog') . '

'; } else { - $message .= '

' . __esc('Cacti Syslog Threshold Alert \'%s\'', $alert['name'], 'syslog') . '

'; + $message .= '

' . __esc('Cacti Syslog Threshold Alert \'%s\'', $alert['name'], 'syslog') . '

'; } } else { $message .= '
' . $alert['body'] . '
'; } - $message .= ''; - $message .= ' + $message .= '
'; + $message .= ' @@ -1376,11 +1420,11 @@ function syslog_process_alert($alert, $sql, $params, $count, $hostname = '') { '; - $message .= ''; - $message .= ''; - $message .= ''; - $message .= ''; - $message .= '
' . __('Alert Name', 'syslog') . ' ' . __('Severity', 'syslog') . ' ' . __('Threshold', 'syslog') . '' . __('Match String', 'syslog') . '
' . html_escape($alert['name']) . '' . $severities[$alert['severity']] . '' . $alert['num'] . '' . sizeof($at) . '' . html_escape($alert['message']) . '

'; + $message .= '' . html_escape($alert['name']) . ''; + $message .= '' . $severities[$alert['severity']] . ''; + $message .= '' . $alert['num'] . ''; + $message .= '' . sizeof($at) . ''; + $message .= '' . html_escape($alert['message']) . '
'; } else { if ($alert['body'] == '') { if ($hostname != '') { @@ -1396,15 +1440,16 @@ function syslog_process_alert($alert, $sql, $params, $count, $hostname = '') { $message .= ''; $message .= ' - + - - + + '; } else { if ($alert['method'] == '1') { if ($alert['body'] == '') { $message .= '---------------------------------------------------------------------' . PHP_EOL . PHP_EOL; + if ($hostname != '') { $message .= __('WARNING: A Syslog Threshold Alert has Been Triggered for Host \'%s\'', $hostname, 'syslog') . PHP_EOL . PHP_EOL; } else { @@ -1415,11 +1460,11 @@ function syslog_process_alert($alert, $sql, $params, $count, $hostname = '') { $message .= $alert['body'] . PHP_EOL; } - $message .= __('Name:', 'syslog') . ' ' . html_escape($alert['name']) . PHP_EOL; - $message .= __('Severity:', 'syslog') . ' ' . $severities[$alert['severity']] . PHP_EOL; - $message .= __('Threshold:', 'syslog') . ' ' . $alert['num'] . PHP_EOL; - $message .= __('Count:', 'syslog') . ' ' . sizeof($at) . PHP_EOL; - $message .= __('Message String:', 'syslog') . ' ' . html_escape($alert['message']) . PHP_EOL; + $message .= __('Name:', 'syslog') . ' ' . html_escape($alert['name']) . PHP_EOL; + $message .= __('Severity:', 'syslog') . ' ' . $severities[$alert['severity']] . PHP_EOL; + $message .= __('Threshold:', 'syslog') . ' ' . $alert['num'] . PHP_EOL; + $message .= __('Count:', 'syslog') . ' ' . sizeof($at) . PHP_EOL; + $message .= __('Message String:', 'syslog') . ' ' . html_escape($alert['message']) . PHP_EOL; } else { if ($alert['body'] == '') { if ($hostname != '') { @@ -1438,9 +1483,9 @@ function syslog_process_alert($alert, $sql, $params, $count, $hostname = '') { $plogged = false; $flogged = false; - foreach($at as $a) { - $hostlist[] = $a['host']; - $results['message'] = (isset($results['message']) ? $results['message'] . ', ':'') . $a['message']; + foreach ($at as $a) { + $hostlist[] = $a['host']; + $results['message'] = (isset($results['message']) ? $results['message'] . ', ' : '') . $a['message']; if (isset($results['priority_id']) && $results['priority_id'] != $a['priority_id'] && !$plogged) { cacti_log(sprintf('Alert \'%s\' has more than one priority id, last one experienced will be leveraged', $alert['name']), false, 'SYSLOG'); @@ -1461,20 +1506,20 @@ function syslog_process_alert($alert, $sql, $params, $count, $hostname = '') { } if ($html) { - $message .= ' - - - + $message .= ' + + + - + '; } else { $message .= '---------------------------------------------------------------------' . PHP_EOL . PHP_EOL; - $message .= __('Hostname:', 'syslog') . ' ' . html_escape($a['host']) . PHP_EOL; - $message .= __('Date:', 'syslog') . ' ' . $a['logtime'] . PHP_EOL; - $message .= __('Severity:', 'syslog') . ' ' . $severities[$alert['severity']] . PHP_EOL . PHP_EOL; - $message .= __('Level:', 'syslog') . ' ' . $syslog_levels[$a['priority_id']] . PHP_EOL . PHP_EOL; - $message .= __('Message:', 'syslog') . ' ' . PHP_EOL . $a['message'] . PHP_EOL; + $message .= __('Hostname:', 'syslog') . ' ' . html_escape($a['host']) . PHP_EOL; + $message .= __('Date:', 'syslog') . ' ' . $a['logtime'] . PHP_EOL; + $message .= __('Severity:', 'syslog') . ' ' . $severities[$alert['severity']] . PHP_EOL . PHP_EOL; + $message .= __('Level:', 'syslog') . ' ' . $syslog_levels[$a['priority_id']] . PHP_EOL . PHP_EOL; + $message .= __('Message:', 'syslog') . ' ' . PHP_EOL . $a['message'] . PHP_EOL; } } } @@ -1498,14 +1543,14 @@ function syslog_process_alert($alert, $sql, $params, $count, $hostname = '') { WHERE alert_id = ? AND logtime > ? AND host = ?', - array($alert['id'], $date, $hostname)); + [$alert['id'], $date, $hostname]); } else { $found = syslog_db_fetch_cell_prepared('SELECT COUNT(*) FROM syslog_logs WHERE alert_id = ? AND logtime > ? AND host = "system"', - array($alert['id'], $date)); + [$alert['id'], $date]); } } @@ -1514,7 +1559,7 @@ function syslog_process_alert($alert, $sql, $params, $count, $hostname = '') { } if ($html) { - $message .= '
' . __('Hostname', 'syslog') . '' . __('Date', 'syslog') . '' . __('Date', 'syslog') . ' ' . __('Severity', 'syslog') . '' . __('Level', 'syslog') . '' . __('Message', 'syslog') . '' . __('Level', 'syslog') . '' . __('Message', 'syslog') . '
' . html_escape($a['host']) . '' . $a['logtime'] . '' . $severities[$alert['severity']] . '
' . html_escape($a['host']) . '' . $a['logtime'] . '' . $severities[$alert['severity']] . ' ' . $syslog_levels[$a['priority_id']] . '' . html_escape($a['message']) . '' . html_escape($a['message']) . '
'; + $message .= ''; } else { $message .= '---------------------------------------------------------------------' . PHP_EOL . PHP_EOL; } @@ -1558,7 +1603,6 @@ function syslog_process_alert($alert, $sql, $params, $count, $hostname = '') { if (trim($alert['command']) != '' && !$found) { syslog_execute_alert_command($alert, $results, $hostname); } - } } elseif ($alert['method'] == 1) { if ($send) { @@ -1591,11 +1635,12 @@ function syslog_process_alert($alert, $sql, $params, $count, $hostname = '') { /** * syslog_get_alert_sql - Get the SQL and params for the alert to - * checi. + * checi. * - * @param (array) The alert attributes to process + * @param array $alert The alert attributes to process + * @param int $max_seq The max sequence * - * @return (array) The SQL and the prepared array for the SQL + * @return array The SQL and the prepared array for the SQL */ function syslog_get_alert_sql(&$alert, $max_seq) { global $syslogdb_default, $syslog_incoming_config; @@ -1608,7 +1653,7 @@ function syslog_get_alert_sql(&$alert, $max_seq) { $syslog_incoming_config['programField'] = 'program'; } - $params = array(); + $params = []; $sql = ''; if ($alert['type'] == 'facility') { @@ -1675,17 +1720,17 @@ function syslog_get_alert_sql(&$alert, $max_seq) { $params[] = $max_seq; } - return array('sql' => $sql, 'params' => $params); + return ['sql' => $sql, 'params' => $params]; } /** * syslog_preprocess_incoming_records - Generate a max_seq to allow moving of - * records to done table and mark incoming records with the max_seq and - * then if syslog is configured to strip domains, perform that first. + * records to done table and mark incoming records with the max_seq and + * then if syslog is configured to strip domains, perform that first. * - * @return (int) Unique id to allow syslog messages that come in randomly to - * be differentiate between messages to process and messages - * to be left till then ext polling cycle. + * @return int Unique id to allow syslog messages that come in randomly to + * be differentiate between messages to process and messages + * to be left till then ext polling cycle. */ function syslog_preprocess_incoming_records() { global $syslogdb_default; @@ -1693,12 +1738,12 @@ function syslog_preprocess_incoming_records() { $max_seq = syslog_db_fetch_cell('SELECT MAX(seq) FROM `' . $syslogdb_default . '`.`syslog_incoming` WHERE status = 0'); if ($max_seq > 0) { - /* flag all records with the status = 1 prior to moving */ + // flag all records with the status = 1 prior to moving syslog_db_execute_prepared('UPDATE `' . $syslogdb_default . '`.`syslog_incoming` SET `status` = 1 WHERE `status` = 0 AND `seq` <= ?', - array($max_seq)); + [$max_seq]); syslog_debug('Max Sequence ID = ' . $max_seq); syslog_debug('-------------------------------------------------------------------------------------'); @@ -1707,28 +1752,28 @@ function syslog_preprocess_incoming_records() { FROM `' . $syslogdb_default . '`.`syslog_incoming` WHERE `status` = 1 AND `seq` <= ?', - array($max_seq)); + [$max_seq]); syslog_debug(sprintf('Found %5s - New Message(s) to process', $syslog_incoming)); - /* strip domains if we have requested to do so */ + // strip domains if we have requested to do so syslog_strip_incoming_domains($max_seq); api_plugin_hook('plugin_syslog_before_processing'); - return array('max_seq' => $max_seq, 'incoming' => $syslog_incoming); + return ['max_seq' => $max_seq, 'incoming' => $syslog_incoming]; } - return array('max_seq' => 0, 'incoming' => 0); + return ['max_seq' => 0, 'incoming' => 0]; } /** * syslog_strip_incoming_domains - If syslog is setup to strip DNS domain name suffixes do that - * prior to processing the records. + * prior to processing the records. * - * @param (string) The max_seq records to process + * @param int $max_seq The max_seq records to process * - * @return (void) + * @return void */ function syslog_strip_incoming_domains($max_seq) { global $syslogdb_default; @@ -1738,13 +1783,13 @@ function syslog_strip_incoming_domains($max_seq) { if ($syslog_domains != '') { $domains = explode(',', trim($syslog_domains)); - foreach($domains as $domain) { + foreach ($domains as $domain) { syslog_db_execute_prepared('UPDATE `' . $syslogdb_default . '`.`syslog_incoming` SET host = SUBSTRING_INDEX(host, \'.\', 1) WHERE host LIKE ? AND `status` = 1 AND `seq` <= ?', - array('%' . $domain, $max_seq)); + ['%' . $domain, $max_seq]); } } } @@ -1753,13 +1798,12 @@ function syslog_strip_incoming_domains($max_seq) { * Check if the hostname is in the cacti hosts table * Some devices only send IP addresses in syslog messages, and may not be in the DNS * however they may be in the cacti hosts table as monitored devices. - * - * @param (string) The hostname to check - * @param (int) The max_seq for syslog_incoming messages to process - * - * @return (bool) True if the host exists in the Cacti database, false otherwise + * + * @param string $host The hostname to check + * @param int $max_seq The max_seq for syslog_incoming messages to process + * + * @return bool True if the host exists in the Cacti database, false otherwise */ - function syslog_check_cacti_hosts($host, $max_seq) { global $syslogdb_default; @@ -1772,7 +1816,7 @@ function syslog_check_cacti_hosts($host, $max_seq) { FROM host WHERE hostname = ? LIMIT 1', - array($host)); + [$host]); if (cacti_sizeof($cacti_host) && !empty($cacti_host['description'])) { syslog_db_execute_prepared('UPDATE `' . $syslogdb_default . '`.`syslog_incoming` @@ -1780,25 +1824,26 @@ function syslog_check_cacti_hosts($host, $max_seq) { WHERE host = ? AND `status` = 1 AND `seq` <= ?', - array($cacti_host['description'], $host, $max_seq)); - + [$cacti_host['description'], $host, $max_seq]); + return true; } - + return false; } + /** * syslog_update_reference_tables - There are many values in the syslog plugin - * that for the purposes of reducing the size of the syslog table are normalized - * the columns includes the facility, the priority, and the hostname. + * that for the purposes of reducing the size of the syslog table are normalized + * the columns includes the facility, the priority, and the hostname. * - * This function will add those new hostnames to the various reference tables - * and assign an id to each of them. This way the syslog table can be optimized - * for size as much as possible. + * This function will add those new hostnames to the various reference tables + * and assign an id to each of them. This way the syslog table can be optimized + * for size as much as possible. * - * @param (int) The max_seq for syslog_incoming messages to process + * @param int $max_seq The max_seq for syslog_incoming messages to process * - * @return (void) + * @return void */ function syslog_update_reference_tables($max_seq) { global $syslogdb_default; @@ -1806,47 +1851,47 @@ function syslog_update_reference_tables($max_seq) { syslog_debug('-------------------------------------------------------------------------------------'); syslog_debug('Updating Reference Tables from New Syslog Records'); - /* Validate and resolve hostnames - check DNS first, then Cacti, then mark invalid */ - if (read_config_option('syslog_resolve_hostname') == 'on') { - $hosts = syslog_db_fetch_assoc_prepared('SELECT DISTINCT host + // Validate and resolve hostnames - check DNS first, then Cacti, then mark invalid + if (read_config_option('syslog_resolve_hostname') == 'on') { + $hosts = syslog_db_fetch_assoc_prepared('SELECT DISTINCT host FROM `' . $syslogdb_default . '`.`syslog_incoming` WHERE `status` = 1 AND `seq` <= ?', - array($max_seq)); - - foreach($hosts as $host) { - if (!isset($host['host']) || empty($host['host'])) { - continue; - } - - $resolved = false; - - // Check if hostname resolves via DNS (only if DNS is enabled) - if (read_config_option('syslog_no_dns') != 'on') { - if ($host['host'] != gethostbyname($host['host'])) { - // DNS resolved successfully - $resolved = true; - } - } - - // Check if hostname exists in Cacti hosts table (only if not already resolved via DNS) - if (!$resolved) { - $resolved = syslog_check_cacti_hosts($host['host'], $max_seq); - } - - // If not resolved via DNS or found in Cacti, prefix the hostname - if (!$resolved) { - $unresolved_host = 'unresolved-' . $host['host']; - cacti_log("SYSLOG WARNING: Hostname '" . $host['host'] . "' could not be resolved via DNS or found in Cacti hosts table, marking as '" . $unresolved_host . "'", false, 'SYSLOG'); - syslog_db_execute_prepared('UPDATE `' . $syslogdb_default . "`.`syslog_incoming` + [$max_seq]); + + foreach ($hosts as $host) { + if (!isset($host['host']) || empty($host['host'])) { + continue; + } + + $resolved = false; + + // Check if hostname resolves via DNS (only if DNS is enabled) + if (read_config_option('syslog_no_dns') != 'on') { + if ($host['host'] != gethostbyname($host['host'])) { + // DNS resolved successfully + $resolved = true; + } + } + + // Check if hostname exists in Cacti hosts table (only if not already resolved via DNS) + if (!$resolved) { + $resolved = syslog_check_cacti_hosts($host['host'], $max_seq); + } + + // If not resolved via DNS or found in Cacti, prefix the hostname + if (!$resolved) { + $unresolved_host = 'unresolved-' . $host['host']; + cacti_log("SYSLOG WARNING: Hostname '" . $host['host'] . "' could not be resolved via DNS or found in Cacti hosts table, marking as '" . $unresolved_host . "'", false, 'SYSLOG'); + syslog_db_execute_prepared('UPDATE `' . $syslogdb_default . '`.`syslog_incoming` SET host = ? WHERE host = ? AND `status` = 1 - AND `seq` <= ?", - array($unresolved_host, $host['host'], $max_seq)); - } - } - } + AND `seq` <= ?', + [$unresolved_host, $host['host'], $max_seq]); + } + } + } syslog_db_execute_prepared('INSERT INTO `' . $syslogdb_default . '`.`syslog_programs` (program, last_updated) @@ -1857,7 +1902,7 @@ function syslog_update_reference_tables($max_seq) { ON DUPLICATE KEY UPDATE program=VALUES(program), last_updated=VALUES(last_updated)', - array($max_seq)); + [$max_seq]); syslog_db_execute_prepared('INSERT INTO `' . $syslogdb_default . '`.`syslog_hosts` (host, last_updated) @@ -1868,7 +1913,7 @@ function syslog_update_reference_tables($max_seq) { ON DUPLICATE KEY UPDATE host=VALUES(host), last_updated=NOW()', - array($max_seq)); + [$max_seq]); syslog_db_execute_prepared('INSERT INTO `' . $syslogdb_default . '`.`syslog_host_facilities` (host_id, facility_id) @@ -1876,26 +1921,26 @@ function syslog_update_reference_tables($max_seq) { FROM ( ( SELECT DISTINCT host, facility_id - FROM `' . $syslogdb_default . "`.`syslog_incoming` + FROM `' . $syslogdb_default . '`.`syslog_incoming` WHERE `status` = 1 AND `seq` <= ? ) AS s - INNER JOIN `" . $syslogdb_default . '`.`syslog_hosts` AS sh + INNER JOIN `' . $syslogdb_default . '`.`syslog_hosts` AS sh ON s.host = sh.host ) ON DUPLICATE KEY UPDATE host_id=VALUES(host_id), last_updated=NOW()', - array($max_seq)); + [$max_seq]); } /** * syslog_update_statistics - Insert new statistics rows into the syslog statistics - * table for post review + * table for post review * - * @param (int) The max_seq for all syslog incoming records to be processed + * @param int $max_seq The max_seq for all syslog incoming records to be processed * - * @return (void) + * @return void */ function syslog_update_statistics($max_seq) { global $syslogdb_default, $syslog_cnn; @@ -1914,7 +1959,7 @@ function syslog_update_statistics($max_seq) { AND si.`seq` <= ? GROUP BY host_id, priority_id, facility_id, program_id) AS merge GROUP BY host_id, priority_id, facility_id, program_id', - array($max_seq)); + [$max_seq]); $stats = db_affected_rows($syslog_cnn); @@ -1929,9 +1974,9 @@ function syslog_update_statistics($max_seq) { * the syslog table, and then after which we can perform various * removal rules against them. * - * @param (int) The max_seq for rows in the syslog table + * @param int $max_seq The max_seq for rows in the syslog table * - * @return (int) The number of rows moved to the syslog table + * @return int The number of rows moved to the syslog table */ function syslog_incoming_to_syslog($max_seq) { global $syslogdb_default, $syslog_cnn; @@ -1949,7 +1994,7 @@ function syslog_incoming_to_syslog($max_seq) { WHERE si.`status` = 1 AND si.`seq` <= ? ) AS merge', - array($max_seq)); + [$max_seq]); $moved = db_affected_rows($syslog_cnn); @@ -1961,7 +2006,7 @@ function syslog_incoming_to_syslog($max_seq) { syslog_db_execute_prepared('DELETE FROM `' . $syslogdb_default . '`.`syslog_incoming` WHERE `status` = 1 AND `seq` <= ?', - array($max_seq)); + [$max_seq]); syslog_debug(sprintf('Deleted %5s - Already Processed Message(s) from incoming', db_affected_rows($syslog_cnn))); @@ -1971,14 +2016,14 @@ function syslog_incoming_to_syslog($max_seq) { syslog_debug(sprintf('Deleted %5s - Stale Message(s) from incoming', $stale)); - return array('moved' => $moved, 'stale' => $stale); + return ['moved' => $moved, 'stale' => $stale]; } /** * syslog_postprocess_tables - Remove stale records and optimize tables after - * message processing has been completed. + * message processing has been completed. * - * @return (void) + * @return void */ function syslog_postprocess_tables() { global $syslogdb_default, $syslog_cnn; @@ -1987,14 +2032,14 @@ function syslog_postprocess_tables() { syslog_debug('Post Processing/Maintenance of Syslog Tables'); syslog_debug('-------------------------------------------------------------------------------------'); - $delete_date = date('Y-m-d H:i:s', time() - (read_config_option('syslog_retention')*86400)); + $delete_date = date('Y-m-d H:i:s', time() - (read_config_option('syslog_retention') * 86400)); - /* remove stats messages */ + // remove stats messages if (read_config_option('syslog_statistics') == 'on') { if (read_config_option('syslog_retention') > 0) { syslog_db_execute_prepared('DELETE FROM `' . $syslogdb_default . '`.`syslog_statistics` WHERE insert_time < ?', - array($delete_date)); + [$delete_date]); syslog_debug(sprintf('Deleted %5s - Syslog Statistics Record(s)', db_affected_rows($syslog_cnn))); } @@ -2002,38 +2047,39 @@ function syslog_postprocess_tables() { syslog_db_execute('TRUNCATE `' . $syslogdb_default . '`.`syslog_statistics`'); } - /* remove alert log messages */ + // remove alert log messages if (read_config_option('syslog_alert_retention') > 0) { api_plugin_hook_function('syslog_delete_hostsalarm', $delete_date); syslog_db_execute_prepared('DELETE FROM `' . $syslogdb_default . '`.`syslog_logs` WHERE logtime < ?', - array($delete_date)); + [$delete_date]); syslog_debug(sprintf('Deleted %5s - Syslog alarm log Record(s)', db_affected_rows($syslog_cnn))); syslog_db_execute_prepared('DELETE FROM `' . $syslogdb_default . '`.`syslog_hosts` WHERE last_updated < ?', - array($delete_date)); + [$delete_date]); syslog_debug(sprintf('Deleted %5s - Syslog Host Record(s)', db_affected_rows($syslog_cnn))); syslog_db_execute_prepared('DELETE FROM `' . $syslogdb_default . '`.`syslog_programs` WHERE last_updated < ?', - array($delete_date)); + [$delete_date]); syslog_debug(sprintf('Deleted %5s - Old programs from programs table', db_affected_rows($syslog_cnn))); syslog_db_execute_prepared('DELETE FROM `' . $syslogdb_default . '`.`syslog_host_facilities` WHERE last_updated < ?', - array($delete_date)); + [$delete_date]); syslog_debug(sprintf('Deleted %5s - Syslog Host/Facility Record(s)', db_affected_rows($syslog_cnn))); } - /* OPTIMIZE THE TABLES ONCE A DAY, JUST TO HELP CLEANUP */ + // OPTIMIZE THE TABLES ONCE A DAY, JUST TO HELP CLEANUP if (date('G') == 0 && date('i') < 5) { syslog_debug('Optimizing Tables'); + if (!syslog_is_partitioned()) { syslog_db_execute('OPTIMIZE TABLE `' . $syslogdb_default . '`.`syslog_incoming`, @@ -2053,7 +2099,7 @@ function syslog_postprocess_tables() { /** * syslog_process_reports - Processes all syslog reports scheduled to run * - * @return (array) An array of total and sent reports + * @return array An array of total and sent reports */ function syslog_process_reports() { global $config, $syslogdb_default, $syslog_cnn, $forcer; @@ -2069,15 +2115,15 @@ function syslog_process_reports() { $format_ok = false; if (read_config_option('syslog_html') == 'on') { - $html = true; + $html = true; $format_ok = reports_load_format_file(read_config_option('syslog_format_file'), $output, $report_tag, $theme); - syslog_debug('Format/CSS ' . ($format_ok ? 'Ok':'Not Ok') . ' - Report Tag ' . ($report_tag ? 'included':'missing')); + syslog_debug('Format/CSS ' . ($format_ok ? 'Ok' : 'Not Ok') . ' - Report Tag ' . ($report_tag ? 'included' : 'missing')); } else { $html = false; } - /* Lets run the reports */ + // Lets run the reports $reports = syslog_db_fetch_assoc('SELECT * FROM `' . $syslogdb_default . "`.`syslog_reports` WHERE enabled='on'"); @@ -2089,7 +2135,8 @@ function syslog_process_reports() { if (cacti_sizeof($reports)) { $total_reports = cacti_sizeof($reports); - foreach($reports as $report) { + + foreach ($reports as $report) { syslog_debug('-------------------------------------------------------------------------------------'); syslog_debug(sprintf('Processing - %s', $report['name'])); @@ -2104,11 +2151,11 @@ function syslog_process_reports() { $start = strtotime(date('Y-m-d 00:00', $current_time)) + $base_start_time; if ($current_time > $start) { - /* if timer expired within a polling interval, then poll */ + // if timer expired within a polling interval, then poll if (($current_time - $seconds_offset) < $start) { $next_run_time = $start; } else { - $next_run_time = $start+ 3600*24; + $next_run_time = $start + 3600 * 24; } } else { $next_run_time = $start; @@ -2123,7 +2170,7 @@ function syslog_process_reports() { syslog_db_execute_prepared('UPDATE `' . $syslogdb_default . '`.`syslog_reports` SET lastsent = ? WHERE id = ?', - array(time(), $report['id'])); + [time(), $report['id']]); syslog_debug('Next Send - Now'); syslog_debug('Creating Report...'); @@ -2135,22 +2182,23 @@ function syslog_process_reports() { if ($sql != '') { $date2 = date('Y-m-d H:i:s', $current_time); $date1 = date('Y-m-d H:i:s', $current_time - $time_span); - $sql .= " AND logtime BETWEEN ". db_qstr($date1) . " AND " . db_qstr($date2); - $sql .= ' ORDER BY logtime DESC'; - $items = syslog_db_fetch_assoc($sql); + $sql .= ' AND logtime BETWEEN ? AND ?'; + $sql .= ' ORDER BY logtime DESC'; + $items = syslog_db_fetch_assoc_prepared($sql, [$data1, $date2]); syslog_debug('We have ' . db_affected_rows($syslog_cnn) . ' items for the Report'); - $classes = array('even', 'odd'); + $classes = ['even', 'odd']; if (cacti_sizeof($items)) { $i = 0; - foreach($items as $item) { + + foreach ($items as $item) { $class = $classes[$i % 2]; $reptext .= ' - ' . html_escape($item['host']) . ' - ' . $item['logtime'] . ' + ' . html_escape($item['host']) . ' + ' . $item['logtime'] . ' ' . html_escape($item['message']) . ' '; @@ -2173,8 +2221,8 @@ function syslog_process_reports() { $message .= ''; $message .= ' - - + + '; @@ -2207,15 +2255,15 @@ function syslog_process_reports() { } } - return array('total_reports' => $total_reports, 'sent_reports' => $sent_reports); + return ['total_reports' => $total_reports, 'sent_reports' => $sent_reports]; } /** * syslog_get_report_sql - Return the SQL syntax for the report query * - * @param (array) The report to process + * @param array $report The report to process * - * @return (string) The unprepared SQL + * @return string The unprepared SQL */ function syslog_get_report_sql(&$report) { global $syslogdb_default; @@ -2279,34 +2327,34 @@ function syslog_get_report_sql(&$report) { /** * generate a Cacti log message and save settings in the settings table for use - * by various graph templates + * by various graph templates * - * @param (string) The start time of the polling process - * @param (int) The number of syslog messages deleted - * @param (int) The number of syslog incoming messages - * @param (int) The number of syslog messages removed - * @param (int) The number of syslog messages transferred - * @param (int) The number of alerts processed - * @param (int) The number of alerts triggered - * @param (int) The number of reports sent + * @param string $start_time The start time of the polling process + * @param int $deleted The number of syslog messages deleted + * @param int $incoming The number of syslog incoming messages + * @param int $removed The number of syslog messages removed + * @param int $xferred The number of syslog messages transferred + * @param int $alerts The number of alerts processed + * @param int $alarms The number of alerts triggered + * @param int $reports The number of reports sent * - * @return (void) + * @return void */ function syslog_process_log($start_time, $deleted, $incoming, $removed, $xferred, $alerts, $alarms, $reports) { global $database_default, $debug; - /* record the end time */ + // record the end time $end_time = microtime(true); $stats = - ' Time:' . round($end_time-$start_time,2) . - ' Deletes:' . $deleted . + ' Time:' . round($end_time - $start_time,2) . + ' Deletes:' . $deleted . ' Incoming:' . $incoming . - ' Removes:' . $removed . - ' XFers:' . $xferred . - ' Alerts:' . $alerts . - ' Alarms:' . $alarms . - ' Reports:' . $reports; + ' Removes:' . $removed . + ' XFers:' . $xferred . + ' Alerts:' . $alerts . + ' Alarms:' . $alarms . + ' Reports:' . $reports; cacti_log('SYSLOG STATS:' . $stats, false, 'SYSTEM'); @@ -2319,29 +2367,29 @@ function syslog_process_log($start_time, $deleted, $incoming, $removed, $xferred } set_config_option('syslog_stats', - 'time:' . round($end_time-$start_time,2) . - ' deletes:' . $deleted . + 'time:' . round($end_time - $start_time,2) . + ' deletes:' . $deleted . ' incoming:' . $incoming . - ' removes:' . $removed . - ' xfers:' . $xferred . - ' alerts:' . $alerts . - ' alarms:' . $alarms . - ' reports:' . $reports + ' removes:' . $removed . + ' xfers:' . $xferred . + ' alerts:' . $alerts . + ' alarms:' . $alarms . + ' reports:' . $reports ); } /** * syslog_init_variables - initialize key variables on first pass of a run - * of the syslog plugin. This function should not have to run more than - * once during the syslog plugins lifecycle. + * of the syslog plugin. This function should not have to run more than + * once during the syslog plugins lifecycle. * - * @return (void) + * @return void */ function syslog_init_variables() { $syslog_retention = read_config_option('syslog_retention'); $alert_retention = read_config_option('syslog_alert_retention'); - if ($syslog_retention == '' or $syslog_retention < 0 or $syslog_retention > 365) { + if ($syslog_retention == '' || $syslog_retention < 0 || $syslog_retention > 365) { set_config_option('syslog_retention', '30'); } @@ -2363,41 +2411,41 @@ function syslog_init_variables() { /** * alert_setup_environment - set's up the environment for a syslog alert * - * @param (array) The alert definition - * @param (string) A comma delimited list of syslog messages - * @param (array) The list of hosts that match for the alert - * @param (string) The hostname in the case of a host level alert + * @param array $alert The alert definition + * @param string $results A comma delimited list of syslog messages + * @param array $hostlist The list of hosts that match for the alert + * @param string $hostname The hostname in the case of a host level alert * - * @return (void) + * @return void */ -function alert_setup_environment(&$alert, $results, $hostlist = array(), $hostname = '') { +function alert_setup_environment(&$alert, $results, $hostlist = [], $hostname = '') { global $severities, $syslog_levels, $syslog_facilities; - putenv('ALERT_ALERTID=' . cacti_escapeshellarg($alert['id'])); - putenv('ALERT_NAME=' . cacti_escapeshellarg(clean_up_name($alert['name']))); - putenv('ALERT_MESSAGE=' . cacti_escapeshellarg($alert['message'])); + putenv('ALERT_ALERTID=' . cacti_escapeshellarg($alert['id'])); + putenv('ALERT_NAME=' . cacti_escapeshellarg(clean_up_name($alert['name']))); + putenv('ALERT_MESSAGE=' . cacti_escapeshellarg($alert['message'])); - putenv('ALERT_SEVERITY=' . cacti_escapeshellarg($alert['severity'])); + putenv('ALERT_SEVERITY=' . cacti_escapeshellarg($alert['severity'])); putenv('ALERT_SEVERITY_TEXT=' . cacti_escapeshellarg($severities[$alert['severity']])); - putenv('ALERT_PRIORITY=' . cacti_escapeshellarg($syslog_levels[$results['priority_id']])); - putenv('ALERT_FACILITY=' . cacti_escapeshellarg($syslog_facilities[$results['facility_id']])); + putenv('ALERT_PRIORITY=' . cacti_escapeshellarg($syslog_levels[$results['priority_id']])); + putenv('ALERT_FACILITY=' . cacti_escapeshellarg($syslog_facilities[$results['facility_id']])); - putenv('ALERT_HOSTLIST=' . cacti_escapeshellarg(implode(',', $hostlist))); - putenv('ALERT_HOSTNAME=' . cacti_escapeshellarg($hostname)); + putenv('ALERT_HOSTLIST=' . cacti_escapeshellarg(implode(',', $hostlist))); + putenv('ALERT_HOSTNAME=' . cacti_escapeshellarg($hostname)); - putenv('ALERT_MESSAGES=' . cacti_escapeshellarg(trim(str_replace("\0", ' ', $results['message'])))); + putenv('ALERT_MESSAGES=' . cacti_escapeshellarg(trim(str_replace("\0", ' ', $results['message'])))); } /** * alert_replace_variables - add command line parameter to the syslog command * or ticket opening script * - * @param (array) The alert definition - * @param (string) A comma delimited list of syslog messages - * @param (string) The hostname in the case of a host level alert + * @param array $alert The alert definition + * @param string $results A comma delimited list of syslog messages + * @param string $hostname The hostname in the case of a host level alert * - * @return (string) The command and it'a arguments escaped + * @return string The command and it'a arguments escaped */ function alert_replace_variables($alert, $results, $hostname = '') { global $severities, $syslog_levels, $syslog_facilities; diff --git a/images/index.php b/images/index.php index e6bad33..828ecbe 100644 --- a/images/index.php +++ b/images/index.php @@ -23,4 +23,3 @@ */ header('Location:../index.php'); - diff --git a/index.php b/index.php index e6bad33..828ecbe 100644 --- a/index.php +++ b/index.php @@ -23,4 +23,3 @@ */ header('Location:../index.php'); - diff --git a/locales/LC_MESSAGES/index.php b/locales/LC_MESSAGES/index.php index e6bad33..828ecbe 100644 --- a/locales/LC_MESSAGES/index.php +++ b/locales/LC_MESSAGES/index.php @@ -23,4 +23,3 @@ */ header('Location:../index.php'); - diff --git a/locales/index.php b/locales/index.php index e6bad33..828ecbe 100644 --- a/locales/index.php +++ b/locales/index.php @@ -23,4 +23,3 @@ */ header('Location:../index.php'); - diff --git a/locales/po/index.php b/locales/po/index.php index e6bad33..828ecbe 100644 --- a/locales/po/index.php +++ b/locales/po/index.php @@ -23,4 +23,3 @@ */ header('Location:../index.php'); - diff --git a/setup.php b/setup.php index 0dc5f91..d012390 100644 --- a/setup.php +++ b/setup.php @@ -32,6 +32,7 @@ function plugin_syslog_install() { include(SYSLOG_CONFIG); } else { raise_message('syslog_info', __('Please rename either your config.php.dist or config_local.php.dist files in the syslog directory, and change setup your database before installing.', 'syslog'), MESSAGE_LEVEL_ERROR); + return false; } @@ -39,9 +40,9 @@ function plugin_syslog_install() { $syslog_exists = sizeof(syslog_db_fetch_row('SHOW TABLES FROM `' . $syslogdb_default . "` LIKE 'syslog'")); - /* ================= input validation ================= */ + // ================= input validation ================= get_filter_request_var('days'); - /* ==================================================== */ + // ==================================================== api_plugin_register_hook('syslog', 'config_arrays', 'syslog_config_arrays', 'setup.php'); api_plugin_register_hook('syslog', 'draw_navigation_text', 'syslog_draw_navigation_text', 'setup.php'); @@ -55,7 +56,7 @@ function plugin_syslog_install() { api_plugin_register_hook('syslog', 'utilities_list', 'syslog_utilities_list', 'setup.php'); api_plugin_register_hook('syslog', 'utilities_action', 'syslog_utilities_action', 'setup.php'); - /* hook for table replication */ + // hook for table replication api_plugin_register_hook('syslog', 'replicate_out', 'syslog_replicate_out', 'setup.php'); api_plugin_register_realm('syslog', 'syslog.php', 'Syslog User', 1); @@ -69,7 +70,7 @@ function plugin_syslog_install() { return true; } } elseif (isset($syslog_install_options) && cacti_sizeof($syslog_install_options)) { - /* hack for syslog so IBM Spectrum LSF RTM can install syslog without user interaction with preset defaults */ + // hack for syslog so IBM Spectrum LSF RTM can install syslog without user interaction with preset defaults if (!$bg_inprocess) { syslog_execute_update($syslog_exists, $syslog_install_options); $bg_inprocess = true; @@ -89,7 +90,9 @@ function syslog_execute_update($syslog_exists, $options) { if (isset($options['cancel'])) { header('Location:' . $config['url_path'] . 'plugins.php?mode=uninstall&id=syslog&uninstall&uninstall_method=all'); exit; - } elseif (isset($options['return'])) { + } + + if (isset($options['return'])) { db_execute('DELETE FROM plugin_config WHERE directory="syslog"'); db_execute('DELETE FROM plugin_realms WHERE plugin="syslog"'); db_execute('DELETE FROM plugin_db_changes WHERE plugin="syslog"'); @@ -114,13 +117,15 @@ function plugin_syslog_uninstall() { if (isset_request_var('cancel') || isset_request_var('return')) { header('Location:' . $config['url_path'] . 'plugins.php?header=false'); exit; - } elseif (isset_request_var('uninstall_method')) { + } + + if (isset_request_var('uninstall_method')) { if (get_nfilter_request_var('uninstall_method') == 'all') { - /* do the big tables first */ + // do the big tables first syslog_db_execute('DROP TABLE IF EXISTS `' . $syslogdb_default . '`.`syslog`'); syslog_db_execute('DROP TABLE IF EXISTS `' . $syslogdb_default . '`.`syslog_removed`'); - /* do the settings tables last */ + // do the settings tables last syslog_db_execute('DROP TABLE IF EXISTS `' . $syslogdb_default . '`.`syslog_incoming`'); syslog_db_execute('DROP TABLE IF EXISTS `' . $syslogdb_default . '`.`syslog_alert`'); syslog_db_execute('DROP TABLE IF EXISTS `' . $syslogdb_default . '`.`syslog_remove`'); @@ -142,23 +147,24 @@ function plugin_syslog_uninstall() { } function plugin_syslog_check_config() { - /* Here we will check to ensure everything is configured */ - if (!file_exists(dirname(__FILE__) . '/config_local.php') && !file_exists(dirname(__FILE__) . '/config.php')) { - raise_message('syslog_info', __('Please rename either your config.php.dist or config_local.php.dist files in the syslog directory, and change setup your database before installing.', 'syslog'), MESSAGE_LEVEL_ERROR); + // Here we will check to ensure everything is configured + if (!file_exists(__DIR__ . '/config_local.php') && !file_exists(__DIR__ . '/config.php')) { + raise_message('syslog_info', __('Please rename either your config.php.dist or config_local.php.dist files in the syslog directory, and change setup your database before installing.', 'syslog'), MESSAGE_LEVEL_ERROR); - return false; - } + return false; + } - if (api_plugin_installed('flowview')) { - syslog_check_upgrade(); - } + if (api_plugin_installed('flowview')) { + syslog_check_upgrade(); + } return true; } function plugin_syslog_upgrade() { - /* Here we will upgrade to the newest version */ + // Here we will upgrade to the newest version syslog_check_upgrade(); + return false; } @@ -172,32 +178,32 @@ function syslog_connect() { include(SYSLOG_CONFIG); } - include_once(dirname(__FILE__) . '/functions.php'); - include_once(dirname(__FILE__) . '/database.php'); + include_once(__DIR__ . '/functions.php'); + include_once(__DIR__ . '/database.php'); $connect_remote = false; $connected = true; - /* Connect to the Syslog Database */ + // Connect to the Syslog Database if (empty($syslog_cnn)) { if ($config['poller_id'] == 1) { if ($use_cacti_db == true) { $syslog_cnn = $local_db_cnn_id; - $connected = true; + $connected = true; } else { $connect_remote = true; } } elseif (isset($config['syslog_remote_db'])) { if ($use_cacti_db == true) { $syslog_cnn = $local_db_cnn_id; - $connected = true; + $connected = true; } else { $connect_remote = true; } } else { if ($use_cacti_db == true) { $syslog_cnn = $remote_db_cnn_id; - $connected = true; + $connected = true; } else { $connect_remote = true; } @@ -213,19 +219,19 @@ function syslog_connect() { } if (!isset($syslogdb_ssl)) { - $syslogdb_ssl = false; + $syslogdb_ssl = false; } if (!isset($syslogdb_ssl_key)) { - $syslogdb_ssl_key = ''; + $syslogdb_ssl_key = ''; } if (!isset($syslogdb_ssl_cert)) { - $syslogdb_ssl_cert = ''; + $syslogdb_ssl_cert = ''; } if (!isset($syslogdb_ssl_ca)) { - $syslogdb_ssl_ca = ''; + $syslogdb_ssl_ca = ''; } $syslog_cnn = syslog_db_connect_real($syslogdb_hostname, $syslogdb_username, $syslogdb_password, $syslogdb_default, $syslogdb_type, $syslogdb_port, $syslogdb_retries, $syslogdb_ssl, $syslogdb_ssl_key, $syslogdb_ssl_cert, $syslogdb_ssl_ca); @@ -240,7 +246,7 @@ function syslog_connect() { cacti_log('Setting Up Database Tables Since they do not exist', false, 'SYSLOG'); if (!isset($syslog_install_options)) { - $syslog_install_options = array(); + $syslog_install_options = []; } syslog_setup_table_new($syslog_install_options); @@ -256,12 +262,13 @@ function syslog_check_upgrade() { syslog_connect(); // Let's only run this check if we are on a page that actually needs the data - $files = array('plugins.php', 'syslog.php', 'syslog_removal.php', 'syslog_alerts.php', 'syslog_reports.php'); - if (substr($_SERVER['SCRIPT_FILENAME'], -18) != 'syslog_process.php' && !in_array(get_current_page(), $files)) { + $files = ['plugins.php', 'syslog.php', 'syslog_removal.php', 'syslog_alerts.php', 'syslog_reports.php']; + + if (substr($_SERVER['SCRIPT_FILENAME'], -18) != 'syslog_process.php' && !in_array(get_current_page(), $files, true)) { return; } - /* don't let this script timeout */ + // don't let this script timeout ini_set('max_execution_time', 0); if (function_exists('api_plugin_upgrade_register')) { @@ -277,16 +284,16 @@ function syslog_check_upgrade() { if ($current != $old) { api_plugin_register_hook('syslog', 'replicate_out', 'syslog_replicate_out', 'setup.php', 1); - db_execute_prepared("UPDATE plugin_config SET + db_execute_prepared('UPDATE plugin_config SET version = ?, name = ?, author = ?, webpage = ? - WHERE directory = ?", - array( + WHERE directory = ?', + [ $version['version'], $version['longname'], $version['author'], $version['homepage'], $version['name'] - ) + ] ); } else { // No upgrade required @@ -303,28 +310,28 @@ function syslog_check_upgrade() { } if (!syslog_db_column_exists('syslog_alert', 'hash')) { - syslog_db_add_column('syslog_alert', array( + syslog_db_add_column('syslog_alert', [ 'name' => 'hash', 'type' => 'varchar(32)', 'NULL' => false, 'default' => '', - 'after' => 'id') + 'after' => 'id'] ); - syslog_db_add_column('syslog_remove', array( + syslog_db_add_column('syslog_remove', [ 'name' => 'hash', 'type' => 'varchar(32)', 'NULL' => false, 'default' => '', - 'after' => 'id') + 'after' => 'id'] ); - syslog_db_add_column('syslog_reports', array( + syslog_db_add_column('syslog_reports', [ 'name' => 'hash', 'type' => 'varchar(32)', 'NULL' => false, 'default' => '', - 'after' => 'id') + 'after' => 'id'] ); } @@ -339,12 +346,12 @@ function syslog_check_upgrade() { WHERE hash IS NULL OR hash = ""'); if (cacti_sizeof($alerts)) { - foreach($alerts as $a) { + foreach ($alerts as $a) { $hash = get_hash_syslog($a['id'], 'syslog_alert'); syslog_db_execute_prepared('UPDATE syslog_alert SET hash = ? WHERE id = ?', - array($hash, $a['id'])); + [$hash, $a['id']]); } } @@ -353,12 +360,12 @@ function syslog_check_upgrade() { WHERE hash IS NULL OR hash = ""'); if (cacti_sizeof($removes)) { - foreach($removes as $r) { + foreach ($removes as $r) { $hash = get_hash_syslog($r['id'], 'syslog_remove'); syslog_db_execute_prepared('UPDATE syslog_remove SET hash = ? WHERE id = ?', - array($hash, $r['id'])); + [$hash, $r['id']]); } } @@ -367,55 +374,55 @@ function syslog_check_upgrade() { WHERE hash IS NULL OR hash = ""'); if (cacti_sizeof($reports)) { - foreach($reports as $r) { + foreach ($reports as $r) { $hash = get_hash_syslog($r['id'], 'syslog_reports'); syslog_db_execute_prepared('UPDATE syslog_reports SET hash = ? WHERE id = ?', - array($hash, $r['id'])); + [$hash, $r['id']]); } } if (!syslog_db_column_exists('syslog_alert', 'level')) { - syslog_db_add_column('syslog_alert', array( + syslog_db_add_column('syslog_alert', [ 'name' => 'level', 'type' => 'int(10)', 'unsigned' => true, 'NULL' => false, 'default' => '0', - 'after' => 'method') + 'after' => 'method'] ); } if (!syslog_db_column_exists('syslog_alert', 'notify')) { - syslog_db_add_column('syslog_alert', array( + syslog_db_add_column('syslog_alert', [ 'name' => 'notify', 'type' => 'int(10)', 'unsigned' => true, 'NULL' => false, 'default' => '0', - 'after' => 'email') + 'after' => 'email'] ); } if (!syslog_db_column_exists('syslog_alert', 'body')) { - syslog_db_add_column('syslog_alert', array( + syslog_db_add_column('syslog_alert', [ 'name' => 'body', 'type' => 'varchar(8192)', 'NULL' => false, 'default' => '', - 'after' => 'message') + 'after' => 'message'] ); } if (!syslog_db_column_exists('syslog_reports', 'notify')) { - syslog_db_add_column('syslog_reports', array( + syslog_db_add_column('syslog_reports', [ 'name' => 'notify', 'type' => 'int(10)', 'unsigned' => true, 'NULL' => false, 'default' => '0', - 'after' => 'email') + 'after' => 'email'] ); } @@ -433,7 +440,7 @@ function syslog_create_partitioned_syslog_table($engine = 'InnoDB', $days = 30) $row_format = 'ROW_FORMAT=Dynamic'; } - $sql = "CREATE TABLE IF NOT EXISTS `" . $syslogdb_default . "`.`syslog` ( + $sql = 'CREATE TABLE IF NOT EXISTS `' . $syslogdb_default . "`.`syslog` ( facility_id int(10) unsigned default NULL, priority_id int(10) unsigned default NULL, program_id int(10) unsigned default NULL, @@ -455,11 +462,12 @@ function syslog_create_partitioned_syslog_table($engine = 'InnoDB', $days = 30) $now = time(); $parts = ''; - for($i = $days; $i >= -1; $i--) { + + for ($i = $days; $i >= -1; $i--) { $timestamp = $now - ($i * 86400); - $date = date('Y-m-d', $timestamp); - $format = date('Ymd', $timestamp - 86400); - $parts .= ($parts != '' ? ",\n":"(") . " PARTITION d" . $format . " VALUES LESS THAN (TO_DAYS('" . $date . "'))"; + $date = date('Y-m-d', $timestamp); + $format = date('Ymd', $timestamp - 86400); + $parts .= ($parts != '' ? ",\n" : '(') . ' PARTITION d' . $format . " VALUES LESS THAN (TO_DAYS('" . $date . "'))"; } $parts .= ",\nPARTITION dMaxValue VALUES LESS THAN MAXVALUE);"; @@ -471,9 +479,9 @@ function syslog_setup_table_new($options) { syslog_connect(); - $tables = array(); + $tables = []; - $syslog_levels = array( + $syslog_levels = [ 0 => 'emerg', 1 => 'crit', 2 => 'alert', @@ -483,7 +491,7 @@ function syslog_setup_table_new($options) { 6 => 'info', 7 => 'debug', 8 => 'other' - ); + ]; // Set default if they are not set. if (!cacti_sizeof($options)) { @@ -509,20 +517,20 @@ function syslog_setup_table_new($options) { } } - /* validate some simple information */ - $truncate = isset($options['upgrade_type']) && $options['upgrade_type'] == 'truncate' ? true:false; - $engine = isset($options['engine']) && $options['engine'] == 'innodb' ? 'InnoDB':$options['engine']; - $partitioned = isset($options['db_type']) && $options['db_type'] == 'part' ? true:false; - $syslogexists = sizeof(syslog_db_fetch_row("SHOW TABLES FROM `" . $syslogdb_default . "` LIKE 'syslog'")); + // validate some simple information + $truncate = isset($options['upgrade_type']) && $options['upgrade_type'] == 'truncate' ? true : false; + $engine = isset($options['engine']) && $options['engine'] == 'innodb' ? 'InnoDB' : $options['engine']; + $partitioned = isset($options['db_type']) && $options['db_type'] == 'part' ? true : false; + $syslogexists = sizeof(syslog_db_fetch_row('SHOW TABLES FROM `' . $syslogdb_default . "` LIKE 'syslog'")); - /* set table construction settings for the remote pollers */ - set_config_option('syslog_install_upgrade_type', empty($options['upgrade_type'])?'':$options['upgrade_type'], true); - set_config_option('syslog_install_engine', empty($options['engine']) ?'':$options['engine'], true); - set_config_option('syslog_install_db_type', empty($options['db_type']) ?'':$options['db_type'], true); - set_config_option('syslog_install_days', empty($options['days']) ?'':$options['days'], true); + // set table construction settings for the remote pollers + set_config_option('syslog_install_upgrade_type', empty($options['upgrade_type']) ? '' : $options['upgrade_type'], true); + set_config_option('syslog_install_engine', empty($options['engine']) ? '' : $options['engine'], true); + set_config_option('syslog_install_db_type', empty($options['db_type']) ? '' : $options['db_type'], true); + set_config_option('syslog_install_days', empty($options['days']) ? '' : $options['days'], true); if ($truncate) { - syslog_db_execute("DROP TABLE IF EXISTS `" . $syslogdb_default . "`.`syslog`"); + syslog_db_execute('DROP TABLE IF EXISTS `' . $syslogdb_default . '`.`syslog`'); } if (stripos($engine, 'aria') !== false) { @@ -532,7 +540,7 @@ function syslog_setup_table_new($options) { } if (!$partitioned) { - syslog_db_execute("CREATE TABLE IF NOT EXISTS `" . $syslogdb_default . "`.`syslog` ( + syslog_db_execute('CREATE TABLE IF NOT EXISTS `' . $syslogdb_default . "`.`syslog` ( facility_id int(10) unsigned default NULL, priority_id int(10) unsigned default NULL, program_id int(10) unsigned default NULL, @@ -554,10 +562,10 @@ function syslog_setup_table_new($options) { } if ($truncate) { - syslog_db_execute("DROP TABLE IF EXISTS `" . $syslogdb_default . "`.`syslog_alert`"); + syslog_db_execute('DROP TABLE IF EXISTS `' . $syslogdb_default . '`.`syslog_alert`'); } - syslog_db_execute("CREATE TABLE IF NOT EXISTS `" . $syslogdb_default . "`.`syslog_alert` ( + syslog_db_execute('CREATE TABLE IF NOT EXISTS `' . $syslogdb_default . "`.`syslog_alert` ( `id` int(10) NOT NULL auto_increment, `hash` varchar(32) NOT NULL default '', `name` varchar(255) NOT NULL default '', @@ -581,10 +589,10 @@ function syslog_setup_table_new($options) { ENGINE=InnoDB"); if ($truncate) { - syslog_db_execute("DROP TABLE IF EXISTS `" . $syslogdb_default . "`.`syslog_incoming`"); + syslog_db_execute('DROP TABLE IF EXISTS `' . $syslogdb_default . '`.`syslog_incoming`'); } - syslog_db_execute("CREATE TABLE IF NOT EXISTS `" . $syslogdb_default . "`.`syslog_incoming` ( + syslog_db_execute('CREATE TABLE IF NOT EXISTS `' . $syslogdb_default . "`.`syslog_incoming` ( facility_id int(10) unsigned default NULL, priority_id int(10) unsigned default NULL, program varchar(40) default NULL, @@ -600,10 +608,10 @@ function syslog_setup_table_new($options) { ROW_FORMAT=Dynamic"); if ($truncate) { - syslog_db_execute("DROP TABLE IF EXISTS `" . $syslogdb_default . "`.`syslog_remove`"); + syslog_db_execute('DROP TABLE IF EXISTS `' . $syslogdb_default . '`.`syslog_remove`'); } - syslog_db_execute("CREATE TABLE IF NOT EXISTS `" . $syslogdb_default . "`.`syslog_remove` ( + syslog_db_execute('CREATE TABLE IF NOT EXISTS `' . $syslogdb_default . "`.`syslog_remove` ( id int(10) NOT NULL auto_increment, `hash` varchar(32) NOT NULL default '', name varchar(255) NOT NULL default '', @@ -618,19 +626,19 @@ function syslog_setup_table_new($options) { ENGINE=$engine $row_format"); - $present = syslog_db_fetch_row("SHOW TABLES FROM `" . $syslogdb_default . "` LIKE 'syslog_reports'"); + $present = syslog_db_fetch_row('SHOW TABLES FROM `' . $syslogdb_default . "` LIKE 'syslog_reports'"); if (cacti_sizeof($present)) { - $newreport = sizeof(syslog_db_fetch_row("SHOW COLUMNS FROM `" . $syslogdb_default . "`.`syslog_reports` LIKE 'body'")); + $newreport = sizeof(syslog_db_fetch_row('SHOW COLUMNS FROM `' . $syslogdb_default . "`.`syslog_reports` LIKE 'body'")); } else { $newreport = true; } if ($truncate || !$newreport) { - syslog_db_execute("DROP TABLE IF EXISTS `" . $syslogdb_default . "`.`syslog_reports`"); + syslog_db_execute('DROP TABLE IF EXISTS `' . $syslogdb_default . '`.`syslog_reports`'); } - syslog_db_execute("CREATE TABLE IF NOT EXISTS `" . $syslogdb_default . "`.`syslog_reports` ( + syslog_db_execute('CREATE TABLE IF NOT EXISTS `' . $syslogdb_default . "`.`syslog_reports` ( id int(10) NOT NULL auto_increment, `hash` varchar(32) NOT NULL default '', name varchar(255) NOT NULL default '', @@ -651,10 +659,10 @@ function syslog_setup_table_new($options) { ROW_FORMAT=Dynamic"); if ($truncate) { - syslog_db_execute("DROP TABLE IF EXISTS `" . $syslogdb_default . "`.`syslog_hosts`"); + syslog_db_execute('DROP TABLE IF EXISTS `' . $syslogdb_default . '`.`syslog_hosts`'); } - syslog_db_execute("CREATE TABLE IF NOT EXISTS `" . $syslogdb_default . "`.`syslog_programs` ( + syslog_db_execute('CREATE TABLE IF NOT EXISTS `' . $syslogdb_default . "`.`syslog_programs` ( `program_id` int(10) unsigned NOT NULL auto_increment, `program` VARCHAR(40) NOT NULL, `last_updated` TIMESTAMP NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP, @@ -665,7 +673,7 @@ function syslog_setup_table_new($options) { ROW_FORMAT=Dynamic COMMENT='Contains all programs currently in the syslog table'"); - syslog_db_execute("CREATE TABLE IF NOT EXISTS `" . $syslogdb_default . "`.`syslog_hosts` ( + syslog_db_execute('CREATE TABLE IF NOT EXISTS `' . $syslogdb_default . "`.`syslog_hosts` ( `host_id` int(10) unsigned NOT NULL auto_increment, `host` VARCHAR(64) NOT NULL, `last_updated` TIMESTAMP NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP, @@ -676,52 +684,52 @@ function syslog_setup_table_new($options) { ROW_FORMAT=Dynamic COMMENT='Contains all hosts currently in the syslog table'"); - syslog_db_execute("DROP TABLE IF EXISTS `" . $syslogdb_default . "`.`syslog_facilities`"); + syslog_db_execute('DROP TABLE IF EXISTS `' . $syslogdb_default . '`.`syslog_facilities`'); - syslog_db_execute("CREATE TABLE IF NOT EXISTS `". $syslogdb_default . "`.`syslog_facilities` ( + syslog_db_execute('CREATE TABLE IF NOT EXISTS `' . $syslogdb_default . '`.`syslog_facilities` ( `facility_id` int(10) unsigned NOT NULL, `facility` varchar(10) NOT NULL, `last_updated` TIMESTAMP NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP, PRIMARY KEY (`facility_id`), INDEX last_updated (`last_updated`)) ENGINE=InnoDB - ROW_FORMAT=Dynamic"); + ROW_FORMAT=Dynamic'); - syslog_db_execute("INSERT INTO `" . $syslogdb_default . "`.`syslog_facilities` (facility_id, facility) VALUES + syslog_db_execute('INSERT INTO `' . $syslogdb_default . "`.`syslog_facilities` (facility_id, facility) VALUES (0,'kern'), (1,'user'), (2,'mail'), (3,'daemon'), (4,'auth'), (5,'syslog'), (6,'lpd'), (7,'news'), (8,'uucp'), (9,'crond'), (10,'authpriv'), (11,'ftpd'), (12,'ntpd'), (13,'logaudit'), (14,'logalert'), (15,'crond'), (16,'local0'), (17,'local1'), (18,'local2'), (19,'local3'), (20,'local4'), (21,'local5'), (22,'local6'), (23,'local7');"); - syslog_db_execute("DROP TABLE IF EXISTS `" . $syslogdb_default . "`.`syslog_priorities`"); + syslog_db_execute('DROP TABLE IF EXISTS `' . $syslogdb_default . '`.`syslog_priorities`'); - syslog_db_execute("CREATE TABLE IF NOT EXISTS `". $syslogdb_default . "`.`syslog_priorities` ( + syslog_db_execute('CREATE TABLE IF NOT EXISTS `' . $syslogdb_default . '`.`syslog_priorities` ( `priority_id` int(10) unsigned NOT NULL, `priority` varchar(10) NOT NULL, `last_updated` TIMESTAMP NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP, PRIMARY KEY (`priority_id`), INDEX last_updated (`last_updated`)) ENGINE=InnoDB - ROW_FORMAT=Dynamic"); + ROW_FORMAT=Dynamic'); - syslog_db_execute("INSERT INTO `" . $syslogdb_default . "`.`syslog_priorities` (priority_id, priority) VALUES + syslog_db_execute('INSERT INTO `' . $syslogdb_default . "`.`syslog_priorities` (priority_id, priority) VALUES (0,'emerg'), (1,'alert'), (2,'crit'), (3,'err'), (4,'warning'), (5,'notice'), (6,'info'), (7,'debug'), (8,'other');"); - syslog_db_execute("CREATE TABLE IF NOT EXISTS `". $syslogdb_default . "`.`syslog_host_facilities` ( + syslog_db_execute('CREATE TABLE IF NOT EXISTS `' . $syslogdb_default . '`.`syslog_host_facilities` ( `host_id` int(10) unsigned NOT NULL, `facility_id` int(10) unsigned NOT NULL, `last_updated` TIMESTAMP NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP, PRIMARY KEY (`host_id`,`facility_id`)) ENGINE=InnoDB - ROW_FORMAT=Dynamic"); + ROW_FORMAT=Dynamic'); if ($truncate) { - syslog_db_execute("DROP TABLE IF EXISTS `" . $syslogdb_default . "`.`syslog_removed`"); + syslog_db_execute('DROP TABLE IF EXISTS `' . $syslogdb_default . '`.`syslog_removed`'); } - syslog_db_execute("CREATE TABLE IF NOT EXISTS `" . $syslogdb_default . "`.`syslog_removed` LIKE `" . $syslogdb_default . "`.`syslog`"); + syslog_db_execute('CREATE TABLE IF NOT EXISTS `' . $syslogdb_default . '`.`syslog_removed` LIKE `' . $syslogdb_default . '`.`syslog`'); - syslog_db_execute("CREATE TABLE IF NOT EXISTS `" . $syslogdb_default . "`.`syslog_logs` ( + syslog_db_execute('CREATE TABLE IF NOT EXISTS `' . $syslogdb_default . "`.`syslog_logs` ( alert_id int(10) unsigned not null default '0', logseq bigint unsigned NOT NULL, logtime TIMESTAMP NOT NULL default '0000-00-00 00:00:00', @@ -744,7 +752,7 @@ function syslog_setup_table_new($options) { ENGINE=InnoDB ROW_FORMAT=Dynamic"); - syslog_db_execute("CREATE TABLE IF NOT EXISTS `" . $syslogdb_default . "`.`syslog_statistics` ( + syslog_db_execute('CREATE TABLE IF NOT EXISTS `' . $syslogdb_default . "`.`syslog_statistics` ( `id` bigint UNSIGNED auto_increment, `host_id` int(10) UNSIGNED NOT NULL, `facility_id` int(10) UNSIGNED NOT NULL, @@ -767,7 +775,7 @@ function syslog_setup_table_new($options) { syslog_config_settings(); } - foreach($settings['syslog'] AS $name => $values) { + foreach ($settings['syslog'] as $name => $values) { if (isset($values['default'])) { set_config_option($name, $values['default']); } @@ -814,12 +822,13 @@ function syslog_replicate_in() { function syslog_replace_data($table, &$data) { if (cacti_sizeof($data)) { - $sqlData = array(); - $sqlQuery = array(); - $columns = array_keys($data[0]); + $sqlData = []; + $sqlQuery = []; + $columns = array_keys($data[0]); $create_sql = ''; $create = db_fetch_row('SHOW CREATE TABLE ' . $table); + if (isset($create["CREATE TABLE `$table`"]) || isset($create['Create Table'])) { if (isset($create["CREATE TABLE `$table`"])) { $create_sql = $create["CREATE TABLE `$table`"]; @@ -831,6 +840,7 @@ function syslog_replace_data($table, &$data) { if (!syslog_db_table_exists($table)) { if ($create_sql == '') { cacti_log('WARNING: Unable to derive CREATE TABLE SQL for `' . $table . '` during Syslog replication.', false, 'REPLICATE'); + return; } @@ -843,16 +853,17 @@ function syslog_replace_data($table, &$data) { // Make the suffix $sql_suffix = ' ON DUPLICATE KEY UPDATE '; - foreach($columns as $c) { + + foreach ($columns as $c) { $sql_suffix .= " $c = VALUES($c),"; } $sql_suffix = trim($sql_suffix, ','); // Construct the prepared statement - foreach($data as $row) { + foreach ($data as $row) { $sqlQuery[] = '(' . trim(str_repeat('?, ', cacti_sizeof($columns)), ', ') . ')'; - foreach($row as $col) { + foreach ($row as $col) { $sqlData[] = $col; } } @@ -866,6 +877,7 @@ function syslog_replace_data($table, &$data) { function plugin_syslog_version() { global $config; $info = parse_ini_file($config['base_path'] . '/plugins/syslog/INFO', true); + return $info['info']; } @@ -878,7 +890,7 @@ function syslog_poller_bottom() { if (syslog_config_safe()) { $command_string = read_config_option('path_php_binary'); - $extra_args = ' -q ' . $config['base_path'] . '/plugins/syslog/syslog_process.php'; + $extra_args = ' -q ' . $config['base_path'] . '/plugins/syslog/syslog_process.php'; exec_background($command_string, $extra_args); } else { cacti_log('WARNING: You have installed the Syslog plugin, but you have not properly set a config.php or config_local.php', false, 'POLLER'); @@ -892,73 +904,73 @@ function syslog_install_advisor($syslog_exists) { syslog_config_arrays(); - $fields_syslog_update = array( - 'upgrade_type' => array( - 'method' => 'drop_array', + $fields_syslog_update = [ + 'upgrade_type' => [ + 'method' => 'drop_array', 'friendly_name' => __('What upgrade/install type do you wish to use', 'syslog'), - 'description' => __('When you have very large tables, performing a Truncate will be much quicker. If you are concerned about archive data, you can choose either Inline, which will freeze your browser for the period of this upgrade, or background, which will create a background process to bring your old syslog data from a backup table to the new syslog format. Again this process can take several hours.', 'syslog'), - 'value' => 'truncate', - 'array' => array( - 'truncate' => __('Truncate Syslog Table', 'syslog'), - 'inline' => __('Inline Upgrade', 'syslog'), + 'description' => __('When you have very large tables, performing a Truncate will be much quicker. If you are concerned about archive data, you can choose either Inline, which will freeze your browser for the period of this upgrade, or background, which will create a background process to bring your old syslog data from a backup table to the new syslog format. Again this process can take several hours.', 'syslog'), + 'value' => 'truncate', + 'array' => [ + 'truncate' => __('Truncate Syslog Table', 'syslog'), + 'inline' => __('Inline Upgrade', 'syslog'), 'background' => __('Background Upgrade', 'syslog') - ) - ), - 'engine' => array( - 'method' => 'drop_array', + ] + ], + 'engine' => [ + 'method' => 'drop_array', 'friendly_name' => __('Database Storage Engine', 'syslog'), - 'description' => __('You have the option to make this a partitioned table by days.', 'syslog'), - 'value' => 'innodb', - 'array' => array( + 'description' => __('You have the option to make this a partitioned table by days.', 'syslog'), + 'value' => 'innodb', + 'array' => [ 'myisam' => __('MyISAM Storage', 'syslog'), 'innodb' => __('InnoDB Storage', 'syslog'), 'aria' => __('Aria Storage', 'syslog') - ) - ), - 'db_type' => array( - 'method' => 'drop_array', + ] + ], + 'db_type' => [ + 'method' => 'drop_array', 'friendly_name' => __('Database Architecture', 'syslog'), - 'description' => __('You have the option to make this a partitioned table by days. You can create multiple partitions per day.', 'syslog'), - 'value' => 'part', - 'array' => array( + 'description' => __('You have the option to make this a partitioned table by days. You can create multiple partitions per day.', 'syslog'), + 'value' => 'part', + 'array' => [ 'trad' => __('Traditional Table', 'syslog'), 'part' => __('Partitioned Table', 'syslog') - ) - ), - 'days' => array( - 'method' => 'drop_array', + ] + ], + 'days' => [ + 'method' => 'drop_array', 'friendly_name' => __('Retention Policy', 'syslog'), - 'description' => __('Choose how many days of Syslog values you wish to maintain in the database.', 'syslog'), - 'value' => '30', - 'array' => $syslog_retentions - ), - 'mode' => array( + 'description' => __('Choose how many days of Syslog values you wish to maintain in the database.', 'syslog'), + 'value' => '30', + 'array' => $syslog_retentions + ], + 'mode' => [ 'method' => 'hidden', - 'value' => 'install' - ), - 'install' => array( + 'value' => 'install' + ], + 'install' => [ 'method' => 'hidden', - 'value' => 'true' - ), - 'id' => array( + 'value' => 'true' + ], + 'id' => [ 'method' => 'hidden', - 'value' => 'syslog' - ) - ); + 'value' => 'syslog' + ] + ]; - $fields_syslog_update['dayparts'] = array( - 'method' => 'drop_array', + $fields_syslog_update['dayparts'] = [ + 'method' => 'drop_array', 'friendly_name' => __('Partitions per Day', 'syslog'), - 'description' => __('Select the number of partitions per day that you wish to create.', 'syslog'), - 'value' => '1', - 'array' => array( + 'description' => __('Select the number of partitions per day that you wish to create.', 'syslog'), + 'value' => '1', + 'array' => [ '1' => __('%d Per Day', 1, 'syslog'), '2' => __('%d Per Day', 2, 'syslog'), '4' => __('%d Per Day', 4, 'syslog'), '6' => __('%d Per Day', 6, 'syslog'), '12' => __('%d Per Day', 12, 'syslog') - ) - ); + ] + ]; if ($syslog_exists) { $type = __('Upgrade', 'syslog'); @@ -969,7 +981,7 @@ function syslog_install_advisor($syslog_exists) { syslog_connect(); $database = syslog_db_fetch_row('SHOW GLOBAL VARIABLES LIKE "version"'); - /* remove Aria as a storage engine if this is mysql */ + // remove Aria as a storage engine if this is mysql if (stripos($database['Value'], 'mariadb') === false) { unset($fields_syslog_update['engine']['array']['aria']); } else { @@ -978,14 +990,14 @@ function syslog_install_advisor($syslog_exists) { print "
' . __('Host', 'syslog') . '' . __('Date', 'syslog') . '' . __('Host', 'syslog') . '' . __('Date', 'syslog') . ' ' . __('Message', 'syslog') . '
"; + print "

" . __('WARNING: Syslog Upgrade is Time Consuming!!!', 'syslog') . '

'; + print '

' . __('The upgrade of the \'main\' syslog table can be a very time consuming process. As such, it is recommended that you either reduce the size of your syslog table prior to upgrading, or choose the background option

If you choose the background option, your legacy syslog table will be renamed, and a new syslog table will be created. Then, an upgrade process will be launched in the background. Again, this background process can quite a bit of time to complete. However, your data will be preserved

Regardless of your choice, all existing removal and alert rules will be maintained during the upgrade process.

Press \'Upgrade\' to proceed with the upgrade, or \'Cancel\' to return to the Plugins menu.', 'syslog') . '

'; } else { unset($fields_syslog_update['upgrade_type']); - print "

" . __('You have several options to choose from when installing Syslog. The first is the Database Architecture. You should elect to utilize Table Partitioning to prevent the size of the tables from becoming excessive thus slowing queries.', 'syslog') . '

' . __('You can also set the MySQL storage engine for the analytical tables syslog and syslog_remove. If you have not tuned you system for InnoDB storage properties and using MySQL, it is strongly recommended that you utilize the MyISAM storage engine. If using MariaDB, we recommend the Aria Storage Engine as it\'s designed for analytical queries', 'syslog') . '

' . __('You can also select the retention duration. Please keep in mind that if you have several hosts logging to syslog, this table can become quite large. So, if not using partitioning, you might want to keep the size smaller.', 'syslog') . "

"; + print '

' . __('You have several options to choose from when installing Syslog. The first is the Database Architecture. You should elect to utilize Table Partitioning to prevent the size of the tables from becoming excessive thus slowing queries.', 'syslog') . '

' . __('You can also set the MySQL storage engine for the analytical tables syslog and syslog_remove. If you have not tuned you system for InnoDB storage properties and using MySQL, it is strongly recommended that you utilize the MyISAM storage engine. If using MariaDB, we recommend the Aria Storage Engine as it\'s designed for analytical queries', 'syslog') . '

' . __('You can also select the retention duration. Please keep in mind that if you have several hosts logging to syslog, this table can become quite large. So, if not using partitioning, you might want to keep the size smaller.', 'syslog') . '

'; } html_end_box(); @@ -993,14 +1005,14 @@ function syslog_install_advisor($syslog_exists) { html_start_box(__('Syslog %s Settings', $type, 'syslog'), '100%', '', '3', 'center', ''); - draw_edit_form(array( - 'config' => array(), - 'fields' => inject_form_variables($fields_syslog_update, array())) + draw_edit_form([ + 'config' => [], + 'fields' => inject_form_variables($fields_syslog_update, [])] ); html_end_box(); syslog_confirm_button('install', 'plugins.php', $syslog_exists); - print "
"; html_start_box(__('Syslog %s Advisor', $type, 'syslog') . '<', '100%', '', '3', 'center', ''); - print "
"; + print '
'; if ($syslog_exists) { - print "

" . __('WARNING: Syslog Upgrade is Time Consuming!!!', 'syslog') . "

"; - print "

" . __('The upgrade of the \'main\' syslog table can be a very time consuming process. As such, it is recommended that you either reduce the size of your syslog table prior to upgrading, or choose the background option

If you choose the background option, your legacy syslog table will be renamed, and a new syslog table will be created. Then, an upgrade process will be launched in the background. Again, this background process can quite a bit of time to complete. However, your data will be preserved

Regardless of your choice, all existing removal and alert rules will be maintained during the upgrade process.

Press \'Upgrade\' to proceed with the upgrade, or \'Cancel\' to return to the Plugins menu.', 'syslog') . "

"; + print ''; bottom_footer(); exit; @@ -1015,27 +1027,27 @@ function syslog_uninstall_advisor() { top_header(); - $fields_syslog_update = array( - 'uninstall_method' => array( - 'method' => 'drop_array', + $fields_syslog_update = [ + 'uninstall_method' => [ + 'method' => 'drop_array', 'friendly_name' => __('What uninstall method do you want to use?', 'syslog'), - 'description' => __('When uninstalling syslog, you can remove everything, or only components, just in case you plan on re-installing in the future.', 'syslog'), - 'value' => 'all', - 'array' => array('all' => __('Remove Everything (Logs, Tables, Settings)', 'syslog'), 'syslog' => __('Syslog Data Only', 'syslog')), - ), - 'mode' => array( + 'description' => __('When uninstalling syslog, you can remove everything, or only components, just in case you plan on re-installing in the future.', 'syslog'), + 'value' => 'all', + 'array' => ['all' => __('Remove Everything (Logs, Tables, Settings)', 'syslog'), 'syslog' => __('Syslog Data Only', 'syslog')], + ], + 'mode' => [ 'method' => 'hidden', - 'value' => 'uninstall' - ), - 'uninstall' => array( + 'value' => 'uninstall' + ], + 'uninstall' => [ 'method' => 'hidden', - 'value' => 'true' - ), - 'id' => array( + 'value' => 'true' + ], + 'id' => [ 'method' => 'hidden', - 'value' => 'syslog' - ) - ); + 'value' => 'syslog' + ] + ]; form_start('plugins.php'); @@ -1043,23 +1055,23 @@ function syslog_uninstall_advisor() { html_start_box(__('Syslog Uninstall Preferences', 'syslog'), '100%', '', '3', 'center', ''); - draw_edit_form(array( - 'config' => array(), - 'fields' => inject_form_variables($fields_syslog_update, array())) + draw_edit_form([ + 'config' => [], + 'fields' => inject_form_variables($fields_syslog_update, [])] ); html_end_box(); syslog_confirm_button('uninstall', 'plugins.php', $syslog_exists); - print ""; + print ''; bottom_footer(); exit; } function syslog_confirm_button($action, $cancel_url, $syslog_exists) { - if ($action == 'install' ) { + if ($action == 'install') { if ($syslog_exists) { $value = __('Upgrade', 'syslog'); } else { @@ -1073,8 +1085,8 @@ function syslog_confirm_button($action, $cancel_url, $syslog_exists) { @@ -561,45 +586,45 @@ function syslog_removal() { global $syslog_actions, $message_types, $config; global $syslogdb_default; - /* ================= input validation and session storage ================= */ - $filters = array( - 'rows' => array( - 'filter' => FILTER_VALIDATE_INT, - 'pageset' => true, - 'default' => '-1', - ), - 'page' => array( - 'filter' => FILTER_VALIDATE_INT, - 'default' => '1' - ), - 'id' => array( - 'filter' => FILTER_VALIDATE_INT, - 'default' => '1' - ), - 'enabled' => array( - 'filter' => FILTER_VALIDATE_INT, + // ================= input validation and session storage ================= + $filters = [ + 'rows' => [ + 'filter' => FILTER_VALIDATE_INT, 'pageset' => true, - 'default' => '-1' - ), - 'filter' => array( - 'filter' => FILTER_DEFAULT, - 'pageset' => true, - 'default' => '' - ), - 'sort_column' => array( - 'filter' => FILTER_CALLBACK, - 'default' => 'name', - 'options' => array('options' => 'sanitize_search_string') - ), - 'sort_direction' => array( - 'filter' => FILTER_CALLBACK, - 'default' => 'ASC', - 'options' => array('options' => 'sanitize_search_string') - ) - ); - - validate_store_request_vars($filters, 'sess_syslogr'); - /* ================= input validation ================= */ + 'default' => '-1', + ], + 'page' => [ + 'filter' => FILTER_VALIDATE_INT, + 'default' => '1' + ], + 'id' => [ + 'filter' => FILTER_VALIDATE_INT, + 'default' => '1' + ], + 'enabled' => [ + 'filter' => FILTER_VALIDATE_INT, + 'pageset' => true, + 'default' => '-1' + ], + 'filter' => [ + 'filter' => FILTER_DEFAULT, + 'pageset' => true, + 'default' => '' + ], + 'sort_column' => [ + 'filter' => FILTER_CALLBACK, + 'default' => 'name', + 'options' => ['options' => 'sanitize_search_string'] + ], + 'sort_direction' => [ + 'filter' => FILTER_CALLBACK, + 'default' => 'ASC', + 'options' => ['options' => 'sanitize_search_string'] + ] + ]; + + validate_store_request_vars($filters, 'sess_syslogr'); + // ================= input validation ================= if (syslog_allow_edits()) { $url = 'syslog_removal.php?action=edit&type=1'; @@ -613,7 +638,8 @@ function syslog_removal() { html_end_box(); - $sql_where = ''; + $sql_where = ''; + $sql_params = []; if (get_request_var('rows') == -1) { $rows = read_config_option('num_rows_table'); @@ -623,23 +649,23 @@ function syslog_removal() { $rows = get_request_var('rows'); } - $removals = syslog_get_removal_records($sql_where, $rows); + $removals = syslog_get_removal_records($sql_where, $sql_params, $rows); - $rows_query_string = "SELECT COUNT(*) - FROM `" . $syslogdb_default . "`.`syslog_remove` + $rows_query_string = 'SELECT COUNT(*) + FROM `' . $syslogdb_default . "`.`syslog_remove` $sql_where"; - $total_rows = syslog_db_fetch_cell($rows_query_string); + $total_rows = syslog_db_fetch_cell_prepared($rows_query_string, $sql_params); - $display_text = array( - 'name' => array(__('Removal Name', 'syslog'), 'ASC'), - 'enabled' => array(__('Enabled', 'syslog'), 'ASC'), - 'type' => array(__('Match Type', 'syslog'), 'ASC'), - 'message' => array(__('Search String', 'syslog'), 'ASC'), - 'method' => array(__('Method', 'syslog'), 'DESC'), - 'date' => array(__('Last Modified', 'syslog'), 'ASC'), - 'user' => array(__('By User', 'syslog'), 'DESC') - ); + $display_text = [ + 'name' => [__('Removal Name', 'syslog'), 'ASC'], + 'enabled' => [__('Enabled', 'syslog'), 'ASC'], + 'type' => [__('Match Type', 'syslog'), 'ASC'], + 'message' => [__('Search String', 'syslog'), 'ASC'], + 'method' => [__('Method', 'syslog'), 'DESC'], + 'date' => [__('Last Modified', 'syslog'), 'ASC'], + 'user' => [__('By User', 'syslog'), 'DESC'] + ]; form_start('syslog_removal.php', 'chk'); @@ -655,17 +681,17 @@ function syslog_removal() { foreach ($removals as $removal) { form_alternate_row('line' . $removal['id'], true); form_selectable_cell(filter_value(title_trim($removal['name'], read_config_option('max_title_length')), get_request_var('filter'), $config['url_path'] . 'plugins/syslog/syslog_removal.php?action=edit&id=' . $removal['id']), $removal['id']); - form_selectable_cell((($removal['enabled'] == 'on') ? __('Yes', 'syslog'):__('No', 'syslog')), $removal['id']); + form_selectable_cell((($removal['enabled'] == 'on') ? __('Yes', 'syslog') : __('No', 'syslog')), $removal['id']); form_selectable_cell($message_types[$removal['type']], $removal['id']); form_selectable_ecell($removal['message'], $removal['id']); - form_selectable_cell((($removal['method'] == 'del') ? __('Deletion', 'syslog'): __('Transfer', 'syslog')), $removal['id']); + form_selectable_cell((($removal['method'] == 'del') ? __('Deletion', 'syslog') : __('Transfer', 'syslog')), $removal['id']); form_selectable_cell(date('Y-m-d H:i:s', $removal['date']), $removal['id']); form_selectable_cell($removal['user'], $removal['id']); form_checkbox_cell($removal['name'], $removal['id']); form_end_row(); } } else { - print ""; + print "'; } html_end_box(false); @@ -690,37 +716,37 @@ function syslog_removal() { kill_session_var('exporter'); exit; - } + } } function import() { - $form_data = array( - 'import_file' => array( + $form_data = [ + 'import_file' => [ 'friendly_name' => __('Import Removal Rule from Local File', 'syslog'), - 'description' => __('If the XML file containing the Removal Rule definition data is located on your local machine, select it here.', 'syslog'), - 'method' => 'file' - ), - 'import_text' => array( - 'method' => 'textarea', + 'description' => __('If the XML file containing the Removal Rule definition data is located on your local machine, select it here.', 'syslog'), + 'method' => 'file' + ], + 'import_text' => [ + 'method' => 'textarea', 'friendly_name' => __('Import Removal Rule from Text', 'syslog'), - 'description' => __('If you have the XML file containing the Removal Rule definition data as text, you can paste it into this box to import it.', 'syslog'), - 'value' => '', - 'default' => '', + 'description' => __('If you have the XML file containing the Removal Rule definition data as text, you can paste it into this box to import it.', 'syslog'), + 'value' => '', + 'default' => '', 'textarea_rows' => '10', 'textarea_cols' => '80', - 'class' => 'textAreaNotes' - ) - ); + 'class' => 'textAreaNotes' + ] + ]; print ""; html_start_box(__('Import Removal Rule', 'syslog'), '100%', false, '3', 'center', ''); draw_edit_form( - array( - 'config' => array('no_form_tag' => true), + [ + 'config' => ['no_form_tag' => true], 'fields' => $form_data - ) + ] ); html_end_box(); @@ -733,46 +759,46 @@ function import() { function removal_import() { $xml_data = syslog_get_import_xml_payload('syslog_removal.php?header=false'); - /* obtain debug information if it's set */ + // obtain debug information if it's set $xml_array = xml2array($xml_data); - $debug_data = array(); + $debug_data = []; if (cacti_sizeof($xml_array)) { foreach ($xml_array as $template => $contents) { $error = false; - $save = array(); + $save = []; if (cacti_sizeof($contents)) { foreach ($contents as $name => $value) { switch($name) { - case 'hash': - // See if the hash exists, if it does, update the alert - $found = syslog_db_fetch_cell_prepared('SELECT id - FROM syslog_remove - WHERE hash = ?', - array($value)); - - if (!empty($found)) { - $save['hash'] = $value; - $save['id'] = $found; - } else { - $save['hash'] = $value; - $save['id'] = 0; - } - - break; - case 'name': - $tname = $value; - $save['name'] = $value; - - break; - default: - if (syslog_db_column_exists('syslog_remove', $name)) { - $save[$name] = $value; - } - - break; + case 'hash': + // See if the hash exists, if it does, update the alert + $found = syslog_db_fetch_cell_prepared('SELECT id + FROM syslog_remove + WHERE hash = ?', + [$value]); + + if (!empty($found)) { + $save['hash'] = $value; + $save['id'] = $found; + } else { + $save['hash'] = $value; + $save['id'] = 0; + } + + break; + case 'name': + $tname = $value; + $save['name'] = $value; + + break; + default: + if (syslog_db_column_exists('syslog_remove', $name)) { + $save[$name] = $value; + } + + break; } } } @@ -781,9 +807,9 @@ function removal_import() { $id = sql_save($save, 'syslog_remove'); if ($id) { - raise_message('syslog_info' . $id, __('NOTE: Removal Rule \'%s\' %s!', $tname, ($save['id'] > 0 ? __('Updated', 'syslog'):__('Imported', 'syslog')), 'syslog'), MESSAGE_LEVEL_INFO); + raise_message('syslog_info' . $id, __('NOTE: Removal Rule \'%s\' %s!', $tname, ($save['id'] > 0 ? __('Updated', 'syslog') : __('Imported', 'syslog')), 'syslog'), MESSAGE_LEVEL_INFO); } else { - raise_message('syslog_info' . $id, __('ERROR: Removal Rule \'%s\' %s Failed!', $tname, ($save['id'] > 0 ? __('Update', 'syslog'):__('Import', 'syslog')), 'syslog'), MESSAGE_LEVEL_ERROR); + raise_message('syslog_info' . $id, __('ERROR: Removal Rule \'%s\' %s Failed!', $tname, ($save['id'] > 0 ? __('Update', 'syslog') : __('Import', 'syslog')), 'syslog'), MESSAGE_LEVEL_ERROR); } } } diff --git a/syslog_reports.php b/syslog_reports.php index 1a97b3a..914f166 100644 --- a/syslog_reports.php +++ b/syslog_reports.php @@ -67,6 +67,7 @@ syslog_action_edit(); bottom_footer(); + break; default: top_header(); @@ -75,13 +76,10 @@ syslog_report(); bottom_footer(); + break; } -/* -------------------------- - The Save Function - -------------------------- */ - function form_save() { if ((isset_request_var('save_component_report')) && (isempty_request_var('add_dq_y'))) { $reportid = api_syslog_report_save(get_filter_request_var('id'), get_nfilter_request_var('name'), @@ -99,18 +97,14 @@ function form_save() { } } -/* ------------------------ - The 'actions' function - ------------------------ */ - function form_actions() { global $config, $syslog_actions, $fields_syslog_action_edit; global $syslogdb_default; get_filter_request_var('drp_action', FILTER_VALIDATE_REGEXP, - array('options' => array('regexp' => '/^([a-zA-Z0-9_]+)$/'))); + ['options' => ['regexp' => '/^([a-zA-Z0-9_]+)$/']]); - /* if we are to save this form, instead of display it */ + // if we are to save this form, instead of display it if (isset_request_var('selected_items')) { $selected_items = sanitize_unserialize_selected_items(get_nfilter_request_var('selected_items')); $drp_action = get_request_var('drp_action'); @@ -118,11 +112,11 @@ function form_actions() { syslog_apply_selected_items_action( $selected_items, $drp_action, - array( + [ '1' => 'api_syslog_report_remove', '2' => 'api_syslog_report_disable', '3' => 'api_syslog_report_enable' - ), + ], '4', get_nfilter_request_var('selected_items') ); @@ -138,62 +132,64 @@ function form_actions() { html_start_box($syslog_actions[get_request_var('drp_action')], '60%', '', '3', 'center', ''); - /* setup some variables */ - $report_array = array(); $report_list = ''; + // setup some variables + $report_array = []; + $report_list = ''; - /* loop through each of the clusters selected on the previous page and get more info about them */ + // loop through each of the clusters selected on the previous page and get more info about them foreach ($_POST as $var => $val) { if (preg_match('/^chk_([0-9]+)$/', $var, $matches)) { - /* ================= input validation ================= */ + // ================= input validation ================= input_validate_input_number($matches[1]); - /* ==================================================== */ + // ==================================================== - $report_info = syslog_db_fetch_cell('SELECT name + $report_info = syslog_db_fetch_cell_prepared('SELECT name FROM `' . $syslogdb_default . '`.`syslog_reports` - WHERE id=' . $matches[1]); + WHERE id = ?', + [$matches[1]]); - $report_list .= '
  • ' . $report_info . '
  • '; + $report_list .= '
  • ' . $report_info . '
  • '; $report_array[] = $matches[1]; } } if (cacti_sizeof($report_array)) { - if (get_request_var('drp_action') == '1') { /* delete */ + if (get_request_var('drp_action') == '1') { // delete print " + print "\n"; $title = __esc('Delete Syslog Report(s)', 'syslog'); - } elseif (get_request_var('drp_action') == '2') { /* disable */ + } elseif (get_request_var('drp_action') == '2') { // disable print " + print "\n"; $title = __esc('Disable Syslog Report(s)', 'syslog'); - } elseif (get_request_var('drp_action') == '3') { /* enable */ + } elseif (get_request_var('drp_action') == '3') { // enable print " + print "\n"; $title = __esc('Enable Syslog Report(s)', 'syslog'); - } elseif (get_request_var('drp_action') == '4') { /* export */ + } elseif (get_request_var('drp_action') == '4') { // export print " + print "\n"; @@ -223,18 +219,19 @@ function form_actions() { } function report_export() { - /* if we are to save this form, instead of display it */ + // if we are to save this form, instead of display it if (isset_request_var('selected_items')) { $selected_items = sanitize_unserialize_selected_items(get_nfilter_request_var('selected_items')); if ($selected_items != false) { $output = '' . PHP_EOL; + foreach ($selected_items as $id) { if ($id > 0) { $data = db_fetch_row_prepared('SELECT * FROM syslog_reports WHERE id = ?', - array($id)); + [$id]); if (cacti_sizeof($data)) { unset($data['id']); @@ -255,8 +252,10 @@ function api_syslog_report_save($id, $name, $type, $message, $timespan, $timepar $email, $notes, $enabled, $notify = 0) { global $config, $syslogdb_default; - /* get the username */ - $username = db_fetch_cell('SELECT username FROM user_auth WHERE id=' . $_SESSION['sess_user_id']); + // get the username + $username = db_fetch_cell_prepared('SELECT username + FROM user_auth WHERE id = ?', + [$_SESSION['sess_user_id']]); if ($id) { $save['id'] = $id; @@ -276,18 +275,19 @@ function api_syslog_report_save($id, $name, $type, $message, $timespan, $timepar $save['body'] = form_input_validate($body, 'body', '', true, 3); $save['email'] = form_input_validate($email, 'email', '', true, 3); $save['notes'] = form_input_validate($notes, 'notes', '', true, 3); - $save['enabled'] = ($enabled == 'on' ? 'on':''); + $save['enabled'] = ($enabled == 'on' ? 'on' : ''); $save['date'] = time(); $save['user'] = $username; $save['notify'] = $notify; $id = 0; + if (!is_error_message()) { $sql = syslog_get_alert_sql($save, 100); if (cacti_sizeof($sql)) { - $db_sql = str_replace('%', '|||||', $sql['sql']); - $db_sql = str_replace('?', '%s', $db_sql); + $db_sql = str_replace('%', '|||||', $sql['sql']); + $db_sql = str_replace('?', '%s', $db_sql); $approx_sql = vsprintf($db_sql, $sql['params']); $approx_sql = str_replace('|||||', '%', $approx_sql); @@ -328,33 +328,29 @@ function api_syslog_report_enable($id) { syslog_db_execute('UPDATE `' . $syslogdb_default . "`.`syslog_reports` SET enabled='on' WHERE id=" . $id); } -/* --------------------- - Reports Functions - --------------------- */ - -function syslog_get_report_records(&$sql_where, $rows) { +function syslog_get_report_records(&$sql_where, &$sql_params, $rows) { global $syslogdb_default; if (get_request_var('filter') != '') { - $sql_where .= (strlen($sql_where) ? ' AND ':'WHERE ') . - '(message LIKE ' . db_qstr('%' . get_request_var('filter') . '%') . ' - OR email LIKE ' . db_qstr('%' . get_request_var('filter') . '%') . ' - OR notes LIKE ' . db_qstr('%' . get_request_var('filter') . '%') . ' - OR name LIKE ' . db_qstr('%' . get_request_var('filter') . '%') . ')'; + $sql_where .= (strlen($sql_where) ? ' AND ' : 'WHERE ') . + '(message LIKE ? OR email LIKE ? OR notes LIKE ? OR name LIKE ?)'; + + $sql_params[] = '%' . get_request_var('filter') . '%'; + $sql_params[] = '%' . get_request_var('filter') . '%'; + $sql_params[] = '%' . get_request_var('filter') . '%'; + $sql_params[] = '%' . get_request_var('filter') . '%'; } - if (get_request_var('enabled') == '-1') { - // Display all status' - }elseif (get_request_var('enabled') == '1') { - $sql_where .= (strlen($sql_where) ? ' AND ':'WHERE ') . - "enabled='on'"; - } else { - $sql_where .= (strlen($sql_where) ? ' AND ':'WHERE ') . - "enabled=''"; + if (get_request_var('enabled') != '-1') { + if (get_request_var('enabled') == '1') { + $sql_where .= (strlen($sql_where) ? ' AND ' : 'WHERE ') . "enabled='on'"; + } else { + $sql_where .= (strlen($sql_where) ? ' AND ' : 'WHERE ') . "enabled=''"; + } } $sql_order = get_order_string(); - $sql_limit = ' LIMIT ' . ($rows*(get_request_var('page')-1)) . ',' . $rows; + $sql_limit = ' LIMIT ' . ($rows * (get_request_var('page') - 1)) . ',' . $rows; $query_string = 'SELECT * FROM `' . $syslogdb_default . "`.`syslog_reports` @@ -362,22 +358,23 @@ function syslog_get_report_records(&$sql_where, $rows) { $sql_order $sql_limit"; - return syslog_db_fetch_assoc($query_string); + return syslog_db_fetch_assoc_prepared($query_string, $sql_params); } function syslog_action_edit() { global $message_types, $syslog_freqs, $syslog_times; global $syslogdb_default; - /* ================= input validation ================= */ + // ================= input validation ================= get_filter_request_var('id'); get_filter_request_var('type'); - /* ==================================================== */ + // ==================================================== if (isset_request_var('id')) { - $report = syslog_db_fetch_row('SELECT * + $report = syslog_db_fetch_row_prepared('SELECT * FROM `' . $syslogdb_default . '`.`syslog_reports` - WHERE id=' . get_request_var('id')); + WHERE id =?', + [get_request_var('id')]); if (cacti_sizeof($report)) { $header_label = __esc('Report Edit [edit: %s]', $report['name'], 'syslog'); @@ -400,135 +397,135 @@ function syslog_action_edit() { 'id', 'name' ); } else { - $lists = array('0' => __('N/A', 'syslog')); + $lists = ['0' => __('N/A', 'syslog')]; } - $fields_syslog_report_edit = array( - 'spacer0' => array( - 'method' => 'spacer', + $fields_syslog_report_edit = [ + 'spacer0' => [ + 'method' => 'spacer', 'friendly_name' => __('Details', 'syslog') - ), - 'name' => array( - 'method' => 'textbox', + ], + 'name' => [ + 'method' => 'textbox', 'friendly_name' => __('Name', 'syslog'), - 'description' => __('Please describe this Report.', 'syslog'), - 'value' => '|arg1:name|', - 'max_length' => '250' - ), - 'enabled' => array( - 'method' => 'drop_array', + 'description' => __('Please describe this Report.', 'syslog'), + 'value' => '|arg1:name|', + 'max_length' => '250' + ], + 'enabled' => [ + 'method' => 'drop_array', 'friendly_name' => __('Enabled?', 'syslog'), - 'description' => __('Is this Report Enabled?', 'syslog'), - 'value' => '|arg1:enabled|', - 'array' => array('on' => __('Enabled', 'syslog'), '' => __('Disabled', 'syslog')), - 'default' => 'on' - ), - 'type' => array( - 'method' => 'drop_array', + 'description' => __('Is this Report Enabled?', 'syslog'), + 'value' => '|arg1:enabled|', + 'array' => ['on' => __('Enabled', 'syslog'), '' => __('Disabled', 'syslog')], + 'default' => 'on' + ], + 'type' => [ + 'method' => 'drop_array', 'friendly_name' => __('String Match Type', 'syslog'), - 'description' => __('Define how you would like this string matched.', 'syslog'), - 'value' => '|arg1:type|', - 'array' => $message_types, - 'default' => 'matchesc' - ), - 'message' => array( - 'method' => 'textbox', + 'description' => __('Define how you would like this string matched.', 'syslog'), + 'value' => '|arg1:type|', + 'array' => $message_types, + 'default' => 'matchesc' + ], + 'message' => [ + 'method' => 'textbox', 'friendly_name' => __('Message Match String', 'syslog'), - 'description' => __('The matching component of the syslog message.', 'syslog'), - 'value' => '|arg1:message|', - 'default' => '', - 'max_length' => '255' - ), - 'timespan' => array( - 'method' => 'drop_array', + 'description' => __('The matching component of the syslog message.', 'syslog'), + 'value' => '|arg1:message|', + 'default' => '', + 'max_length' => '255' + ], + 'timespan' => [ + 'method' => 'drop_array', 'friendly_name' => __('Frequency', 'syslog'), - 'description' => __('How often should this Report be sent to the distribution list?', 'syslog'), - 'value' => '|arg1:timespan|', - 'array' => $syslog_freqs, - 'default' => 'del' - ), - 'timepart' => array( - 'method' => 'drop_array', + 'description' => __('How often should this Report be sent to the distribution list?', 'syslog'), + 'value' => '|arg1:timespan|', + 'array' => $syslog_freqs, + 'default' => 'del' + ], + 'timepart' => [ + 'method' => 'drop_array', 'friendly_name' => __('Send Time', 'syslog'), - 'description' => __('What time of day should this report be sent?', 'syslog'), - 'value' => '|arg1:timepart|', - 'array' => $syslog_times, - 'default' => 'del' - ), - 'spacer1' => array( - 'method' => 'spacer', + 'description' => __('What time of day should this report be sent?', 'syslog'), + 'value' => '|arg1:timepart|', + 'array' => $syslog_times, + 'default' => 'del' + ], + 'spacer1' => [ + 'method' => 'spacer', 'friendly_name' => __('Report Format', 'syslog') - ), - 'message' => array( + ], + 'message' => [ 'friendly_name' => __('Message Match String', 'syslog'), - 'description' => __('The matching component of the syslog message.', 'syslog'), - 'method' => 'textbox', - 'max_length' => '255', - 'value' => '|arg1:message|', - 'default' => '', - ), - 'body' => array( + 'description' => __('The matching component of the syslog message.', 'syslog'), + 'method' => 'textbox', + 'max_length' => '255', + 'value' => '|arg1:message|', + 'default' => '', + ], + 'body' => [ 'friendly_name' => __('Email Body Text', 'syslog'), 'textarea_rows' => '6', 'textarea_cols' => '80', - 'description' => __('The information that will be contained in the body of the Report.', 'syslog'), - 'method' => 'textarea', - 'class' => 'textAreaNotes', - 'value' => '|arg1:body|', - 'default' => '', - ), - 'notify' => array( - 'method' => 'drop_array', + 'description' => __('The information that will be contained in the body of the Report.', 'syslog'), + 'method' => 'textarea', + 'class' => 'textAreaNotes', + 'value' => '|arg1:body|', + 'default' => '', + ], + 'notify' => [ + 'method' => 'drop_array', 'friendly_name' => __('Notification List', 'syslog'), - 'description' => __('Use the contents of this Notification List to dictate who should be notified and how.', 'syslog'), - 'value' => '|arg1:notify|', - 'array' => $lists, - 'none_value' => __('None', 'syslog'), - 'default' => '0' - ), - 'email' => array( + 'description' => __('Use the contents of this Notification List to dictate who should be notified and how.', 'syslog'), + 'value' => '|arg1:notify|', + 'array' => $lists, + 'none_value' => __('None', 'syslog'), + 'default' => '0' + ], + 'email' => [ 'friendly_name' => __('Email Addresses', 'syslog'), 'textarea_rows' => '3', 'textarea_cols' => '60', - 'description' => __('Comma delimited list of Email addresses to send the report to.', 'syslog'), - 'method' => 'textarea', - 'class' => 'textAreaNotes', - 'value' => '|arg1:email|', - 'default' => '', - ), - 'notes' => array( + 'description' => __('Comma delimited list of Email addresses to send the report to.', 'syslog'), + 'method' => 'textarea', + 'class' => 'textAreaNotes', + 'value' => '|arg1:email|', + 'default' => '', + ], + 'notes' => [ 'friendly_name' => __('Notes', 'syslog'), 'textarea_rows' => '3', 'textarea_cols' => '60', - 'description' => __('Space for Notes on the Report', 'syslog'), - 'method' => 'textarea', - 'class' => 'textAreaNotes', - 'value' => '|arg1:notes|', - 'default' => '', - ), - 'id' => array( + 'description' => __('Space for Notes on the Report', 'syslog'), + 'method' => 'textarea', + 'class' => 'textAreaNotes', + 'value' => '|arg1:notes|', + 'default' => '', + ], + 'id' => [ 'method' => 'hidden_zero', - 'value' => '|arg1:id|' - ), - '_id' => array( + 'value' => '|arg1:id|' + ], + '_id' => [ 'method' => 'hidden_zero', - 'value' => '|arg1:id|' - ), - 'save_component_report' => array( + 'value' => '|arg1:id|' + ], + 'save_component_report' => [ 'method' => 'hidden', - 'value' => '1' - ) - ); + 'value' => '1' + ] + ]; form_start('syslog_reports.php', 'syslog_edit'); html_start_box($header_label, '100%', '', '3', 'center', ''); draw_edit_form( - array( - 'config' => array('no_form_tag' => true), - 'fields' => inject_form_variables($fields_syslog_report_edit, (isset($report) ? $report : array())) - ) + [ + 'config' => ['no_form_tag' => true], + 'fields' => inject_form_variables($fields_syslog_report_edit, (isset($report) ? $report : [])) + ] ); html_end_box(); @@ -538,8 +535,8 @@ function syslog_action_edit() { ?>
    - ' type='button' value=''> - + ' type='button' value=''> + + html_start_box(__('Syslog Message Filter %s', $filter_text, 'syslog'), '100%', '', '3', 'center', ''); ?>
    @@ -1248,13 +1319,13 @@ function syslog_filter($sql_where, $tab) {
    - + - + '> - ' class='calendar fa fa-calendar-alt' id='startDate'> + ' class='calendar fa fa-calendar-alt' id='startDate'> - + '> - ' class='calendar fa fa-calendar-alt' id='endDate'> + ' class='calendar fa fa-calendar-alt' id='endDate'> - ' onclick='timeshiftFilterLeft()' class='shiftArrow fa fa-backward'> + ' onclick='timeshiftFilterLeft()' class='shiftArrow fa fa-backward'> - '> ' . title_trim($graph_timeshifts[$shift_value], 40) . ''; - } - } - ?> + $start_val = 1; + $end_val = sizeof($graph_timeshifts) + 1; + + if (cacti_sizeof($graph_timeshifts)) { + for ($shift_value = $start_val; $shift_value < $end_val; $shift_value++) { + print "'; + } + } + ?> - ' onclick='timeshiftFilterRight()' class='shiftArrow fa fa-forward'> + ' onclick='timeshiftFilterRight()' class='shiftArrow fa fa-forward'> - '> - ' title=''> - ' title=''> - ' title=''> + '> + ' title=''> + ' title=''> + ' title=''> - ' title=''> - ' title=''> - ' title=''> + ' title=''> + ' title=''> + ' title=''>
    - + - ' onChange='applyFilter()'> + ' onChange='applyFilter()'> - + - + - '> + $display_text) { - print "'; + foreach ($item_rows as $rows => $display_text) { + print "'; } ?> - + - '> $display_text) { - print ""; + foreach ($trimvals as $seconds => $display_text) { + print "'; } ?> - + @@ -1411,61 +1502,70 @@ function syslog_filter($sql_where, $tab) {
    - - + + @@ -1473,12 +1573,12 @@ function syslog_filter($sql_where, $tab) { @@ -1498,15 +1598,19 @@ function syslog_filter($sql_where, $tab) { * Simple function to strip the domain for a hostname * * @param string hostname + * @param mixed $hostname */ function syslog_strip_domain($hostname) { if (strpos($hostname, '.') === false) { return $hostname; - } elseif (filter_var($hostname, FILTER_VALIDATE_IP)) { + } + + if (filter_var($hostname, FILTER_VALIDATE_IP)) { return $hostname; } else { $parts = explode('.', $hostname); - foreach($parts as $part) { + + foreach ($parts as $part) { if (is_numeric($part)) { return $hostname; } @@ -1520,44 +1624,48 @@ function syslog_strip_domain($hostname) { * function syslog_syslog_legend() * * This function displays the foreground and background colors for the syslog syslog legend -*/ + */ function syslog_syslog_legend() { global $disabled_color, $notmon_color, $database_default; html_start_box('', '100%', '', '3', 'center', ''); print ''; print "'; - print "'; - print "'; - print "'; - print "'; - print "'; - print "'; - print "'; + print "'; + print "'; + print "'; + print "'; + print "'; + print "'; + print "'; print ''; html_end_box(false); } -/** function syslog_log_legend() - * This function displays the foreground and background colors for the syslog log legend -*/ +/** + * function syslog_log_legend() + * This function displays the foreground and background colors for the syslog log legend + */ function syslog_log_legend() { global $disabled_color, $notmon_color, $database_default; html_start_box('', '100%', '', '3', 'center', ''); print ''; - print "'; - print "'; - print "'; - print "'; + print "'; + print "'; + print "'; + print "'; print ''; html_end_box(false); } -/** function syslog_messages() - * This is the main page display function in Syslog. Displays all the - * syslog messages that are relevant to Syslog. -*/ +/** + * function syslog_messages() + * This is the main page display function in Syslog. Displays all the + * syslog messages that are relevant to Syslog. + * + * @param mixed $tab + */ function syslog_messages($tab = 'syslog') { global $sql_where, $hostfilter, $severities; global $config, $syslog_incoming_config, $reset_multi, $syslog_levels; @@ -1569,10 +1677,10 @@ function syslog_messages($tab = 'syslog') { include('./include/global_arrays.php'); - /* force the initial timespan to be 30 minutes for performance reasons */ + // force the initial timespan to be 30 minutes for performance reasons if (!isset($_SESSION['sess_syslog_init'])) { $_SESSION['sess_current_timespan'] = 1; - $_SESSION['sess_syslog_init'] = 1; + $_SESSION['sess_syslog_init'] = 1; } $url_curr_page = get_browser_query_string(); @@ -1620,10 +1728,10 @@ function syslog_messages($tab = 'syslog') { } else { // Original non-grouped row counting if (get_request_var('removal') == 1) { - $total_rows = syslog_db_fetch_cell("SELECT SUM(totals) + $total_rows = syslog_db_fetch_cell('SELECT SUM(totals) FROM ( SELECT count(*) AS totals - FROM `" . $syslogdb_default . "`.`syslog` AS syslog + FROM `' . $syslogdb_default . "`.`syslog` AS syslog $sql_where UNION SELECT count(*) AS totals @@ -1631,26 +1739,26 @@ function syslog_messages($tab = 'syslog') { $sql_where ) AS rowcount"); } elseif (get_request_var('removal') == -1) { - $total_rows = syslog_db_fetch_cell("SELECT count(*) - FROM `" . $syslogdb_default . "`.`syslog` AS syslog + $total_rows = syslog_db_fetch_cell('SELECT count(*) + FROM `' . $syslogdb_default . "`.`syslog` AS syslog $sql_where"); } else { - $total_rows = syslog_db_fetch_cell("SELECT count(*) - FROM `" . $syslogdb_default . "`.`syslog_removed` AS syslog + $total_rows = syslog_db_fetch_cell('SELECT count(*) + FROM `' . $syslogdb_default . "`.`syslog_removed` AS syslog $sql_where"); } } } else { - $total_rows = syslog_db_fetch_cell("SELECT count(*) - FROM `" . $syslogdb_default . "`.`syslog_logs` AS syslog - LEFT JOIN `" . $syslogdb_default . "`.`syslog_facilities` AS sf + $total_rows = syslog_db_fetch_cell('SELECT count(*) + FROM `' . $syslogdb_default . '`.`syslog_logs` AS syslog + LEFT JOIN `' . $syslogdb_default . '`.`syslog_facilities` AS sf ON syslog.facility_id=sf.facility_id - LEFT JOIN `" . $syslogdb_default . "`.`syslog_priorities` AS sp + LEFT JOIN `' . $syslogdb_default . '`.`syslog_priorities` AS sp ON syslog.priority_id=sp.priority_id - LEFT JOIN `" . $syslogdb_default . "`.`syslog_alert` AS sa + LEFT JOIN `' . $syslogdb_default . '`.`syslog_alert` AS sa ON syslog.alert_id=sa.id - LEFT JOIN `" . $syslogdb_default . "`.`syslog_programs` AS spr - ON syslog.program_id=spr.program_id " . + LEFT JOIN `' . $syslogdb_default . '`.`syslog_programs` AS spr + ON syslog.program_id=spr.program_id ' . $sql_where); } @@ -1659,31 +1767,31 @@ function syslog_messages($tab = 'syslog') { $grouping_enabled = isset_request_var('grouping') && get_request_var('grouping') == '1'; if (api_plugin_user_realm_auth('syslog_alerts.php')) { - $display_text = array( - 'nosortt' => array(__('Actions', 'syslog'), 'ASC'), - 'logtime' => array(__('Date', 'syslog'), 'ASC'), - 'host_id' => array(__('Device', 'syslog'), 'ASC'), - 'program' => array(__('Program', 'syslog'), 'ASC'), - 'message' => array(__('Message', 'syslog'), 'ASC'), - 'facility_id' => array(__('Facility', 'syslog'), 'ASC'), - 'priority_id' => array(__('Priority', 'syslog'), 'ASC')); + $display_text = [ + 'nosortt' => [__('Actions', 'syslog'), 'ASC'], + 'logtime' => [__('Date', 'syslog'), 'ASC'], + 'host_id' => [__('Device', 'syslog'), 'ASC'], + 'program' => [__('Program', 'syslog'), 'ASC'], + 'message' => [__('Message', 'syslog'), 'ASC'], + 'facility_id' => [__('Facility', 'syslog'), 'ASC'], + 'priority_id' => [__('Priority', 'syslog'), 'ASC']]; // Add count column if grouping is enabled if ($grouping_enabled) { - $display_text['occurrence_count'] = array(__('Count', 'syslog'), 'DESC'); + $display_text['occurrence_count'] = [__('Count', 'syslog'), 'DESC']; } } else { - $display_text = array( - 'logtime' => array(__('Date', 'syslog'), 'ASC'), - 'host_id' => array(__('Device', 'syslog'), 'ASC'), - 'program' => array(__('Program', 'syslog'), 'ASC'), - 'message' => array(__('Message', 'syslog'), 'ASC'), - 'facility_id' => array(__('Facility', 'syslog'), 'ASC'), - 'priority_id' => array(__('Priority', 'syslog'), 'ASC')); + $display_text = [ + 'logtime' => [__('Date', 'syslog'), 'ASC'], + 'host_id' => [__('Device', 'syslog'), 'ASC'], + 'program' => [__('Program', 'syslog'), 'ASC'], + 'message' => [__('Message', 'syslog'), 'ASC'], + 'facility_id' => [__('Facility', 'syslog'), 'ASC'], + 'priority_id' => [__('Priority', 'syslog'), 'ASC']]; // Add count column if grouping is enabled if ($grouping_enabled) { - $display_text['occurrence_count'] = array(__('Count', 'syslog'), 'DESC'); + $display_text['occurrence_count'] = [__('Count', 'syslog'), 'DESC']; } } @@ -1715,7 +1823,6 @@ function syslog_messages($tab = 'syslog') { if (cacti_sizeof($syslog_messages)) { foreach ($syslog_messages as $sm) { - if (is_null($sm[$syslog_incoming_config['textField']])) { $sm[$syslog_incoming_config['textField']] = __('Empty message', 'syslog'); } @@ -1726,6 +1833,7 @@ function syslog_messages($tab = 'syslog') { if (api_plugin_user_realm_auth('syslog_alerts.php')) { $url = ''; + if ($sm['mtype'] == 'main') { $url .= ""; $url .= ""; @@ -1743,11 +1851,11 @@ function syslog_messages($tab = 'syslog') { form_selectable_cell($sm['logtime'], $sm['seq'], '', 'left'); } - form_selectable_cell(isset($hosts[$sm['host_id']]) ? $hosts[$sm['host_id']]:__('Unknown', 'syslog'), $sm['seq'], '', 'left'); + form_selectable_cell(isset($hosts[$sm['host_id']]) ? $hosts[$sm['host_id']] : __('Unknown', 'syslog'), $sm['seq'], '', 'left'); form_selectable_cell($sm['program'], $sm['seq'], '', 'left'); form_selectable_cell(filter_value(title_trim($sm[$syslog_incoming_config['textField']], get_request_var_request('trimval')), get_request_var('rfilter')), $sm['seq'], '', 'left syslogMessage'); - form_selectable_cell(isset($facilities[$sm['facility_id']]) ? $facilities[$sm['facility_id']]:__('Unknown', 'syslog'), $sm['seq'], '', 'left'); - form_selectable_cell(isset($priorities[$sm['priority_id']]) ? $priorities[$sm['priority_id']]:__('Unknown', 'syslog'), $sm['seq'], '', 'left'); + form_selectable_cell(isset($facilities[$sm['facility_id']]) ? $facilities[$sm['facility_id']] : __('Unknown', 'syslog'), $sm['seq'], '', 'left'); + form_selectable_cell(isset($priorities[$sm['priority_id']]) ? $priorities[$sm['priority_id']] : __('Unknown', 'syslog'), $sm['seq'], '', 'left'); // Add occurrence count if grouping is enabled if ($grouping_enabled) { @@ -1761,44 +1869,46 @@ function syslog_messages($tab = 'syslog') { $seq_array = explode(',', $sm['seq_list']); // Get individual messages for this group - $detail_messages = syslog_db_fetch_assoc("SELECT syslog.*, syslog_programs.program - FROM `" . $syslogdb_default . "`.`" . (($sm['mtype'] == 'main') ? 'syslog' : 'syslog_removed') . "` AS syslog - LEFT JOIN `" . $syslogdb_default . "`.`syslog_programs` + $detail_messages = syslog_db_fetch_assoc('SELECT syslog.*, syslog_programs.program + FROM `' . $syslogdb_default . '`.`' . (($sm['mtype'] == 'main') ? 'syslog' : 'syslog_removed') . '` AS syslog + LEFT JOIN `' . $syslogdb_default . '`.`syslog_programs` ON syslog.program_id=syslog_programs.program_id - WHERE syslog.seq IN (" . implode(',', array_map('intval', $seq_array)) . ") - ORDER BY syslog.logtime DESC"); + WHERE syslog.seq IN (' . implode(',', array_map('intval', $seq_array)) . ') + ORDER BY syslog.logtime DESC'); if (cacti_sizeof($detail_messages)) { foreach ($detail_messages as $dm) { $severity_class = syslog_row_color($dm['priority_id'], $dm['message']); - print ""; + print ""; + if (api_plugin_user_realm_auth('syslog_alerts.php')) { $url = ''; + if ($sm['mtype'] == 'main') { $url .= ""; $url .= ""; } - print ""; + print "'; } - print ""; - print ""; - print ""; - print ""; - print ""; - print ""; + print "'; + print "'; + print "'; + print "'; + print "'; + print "'; if ($grouping_enabled) { print ""; } - print ""; + print ''; } } } } } else { - print ""; + print "'; } html_end_box(false); @@ -1815,16 +1925,16 @@ function syslog_messages($tab = 'syslog') { array('display' => __('Alert Name', 'syslog'), 'sort' => 'ASC', 'align' => 'left'), - 'severity' => array('display' => __('Severity', 'syslog'), 'sort' => 'ASC', 'align' => 'left'), - 'logtime' => array('display' => __('Date', 'syslog'), 'sort' => 'ASC', 'align' => 'left'), - 'logmsg' => array('display' => __('Message', 'syslog'), 'sort' => 'ASC', 'align' => 'left'), - 'count' => array('display' => __('Count', 'syslog'), 'sort' => 'ASC', 'align' => 'right'), - 'host' => array('display' => __('Device', 'syslog'), 'sort' => 'ASC', 'align' => 'right'), - 'facility_id' => array('display' => __('Facility', 'syslog'), 'sort' => 'ASC', 'align' => 'right'), - 'priority_id' => array('display' => __('Priority', 'syslog'), 'sort' => 'ASC', 'align' => 'right') - ); + $display_text = [ + 'name' => ['display' => __('Alert Name', 'syslog'), 'sort' => 'ASC', 'align' => 'left'], + 'severity' => ['display' => __('Severity', 'syslog'), 'sort' => 'ASC', 'align' => 'left'], + 'logtime' => ['display' => __('Date', 'syslog'), 'sort' => 'ASC', 'align' => 'left'], + 'logmsg' => ['display' => __('Message', 'syslog'), 'sort' => 'ASC', 'align' => 'left'], + 'count' => ['display' => __('Count', 'syslog'), 'sort' => 'ASC', 'align' => 'right'], + 'host' => ['display' => __('Device', 'syslog'), 'sort' => 'ASC', 'align' => 'right'], + 'facility_id' => ['display' => __('Facility', 'syslog'), 'sort' => 'ASC', 'align' => 'right'], + 'priority_id' => ['display' => __('Priority', 'syslog'), 'sort' => 'ASC', 'align' => 'right'] + ]; $nav = html_nav_bar("syslog.php?tab=$tab", MAX_DISPLAY_PAGES, get_request_var_request('page'), $rows, $total_rows, cacti_sizeof($display_text), __('Alert Log Rows', 'syslog'), 'page', 'main'); @@ -1840,9 +1950,9 @@ function syslog_messages($tab = 'syslog') { syslog_log_row_color($log['severity'], $title); - form_selectable_cell(filter_value($log['name'] != '' ? $log['name']:__('Alert Removed', 'syslog'), get_request_var('rfilter'), $config['url_path'] . 'plugins/syslog/syslog.php?id=' . $log['seq'] . '&tab=current'), $log['seq'], '', 'left'); + form_selectable_cell(filter_value($log['name'] != '' ? $log['name'] : __('Alert Removed', 'syslog'), get_request_var('rfilter'), $config['url_path'] . 'plugins/syslog/syslog.php?id=' . $log['seq'] . '&tab=current'), $log['seq'], '', 'left'); - form_selectable_cell(isset($severities[$log['severity']]) ? $severities[$log['severity']]:__('Unknown', 'syslog'), $log['seq'], '', 'left'); + form_selectable_cell(isset($severities[$log['severity']]) ? $severities[$log['severity']] : __('Unknown', 'syslog'), $log['seq'], '', 'left'); form_selectable_cell($log['logtime'], $log['seq'], '', 'left'); form_selectable_cell(filter_value(title_trim($log['logmsg'], get_request_var_request('trimval')), get_request_var('rfilter')), $log['seq'], '', 'syslogMessage left'); @@ -1854,7 +1964,7 @@ function syslog_messages($tab = 'syslog') { form_end_row(); } } else { - print ""; + print "'; } html_end_box(false); @@ -1872,7 +1982,7 @@ function save_settings() { // syslog_request_validation($current_tab); - $variables = array( + $variables = [ 'rows', 'refresh', 'removal', @@ -1883,9 +1993,9 @@ function save_settings() { 'grouping', 'predefined_timespan', 'predefined_timeshift', - ); + ]; - foreach($variables as $v) { + foreach ($variables as $v) { if (isset_request_var($v)) { // Accommodate predefined if (strpos($v, 'predefined') !== false) { @@ -1906,9 +2016,10 @@ function html_program_filter($program_id = '-1', $none_entry = '', $action = 'aj } if ($program_id > 0) { - $program = syslog_db_fetch_cell("SELECT program + $program = syslog_db_fetch_cell_prepared('SELECT program FROM syslog_programs - WHERE program_id = $program_id"); + WHERE program_id = ?', + [$program_id]); } elseif ($program_id == -2) { $program = __('None', 'syslog'); } else { @@ -1944,44 +2055,47 @@ function html_program_filter($program_id = '-1', $none_entry = '', $action = 'aj } function get_ajax_programs($include_any = true, $include_none = false, $sql_where = '') { - $return = array(); + $return = []; + $sql_params = []; + + $term = get_filter_request_var('term', FILTER_CALLBACK, ['options' => 'sanitize_search_string']); - $term = get_filter_request_var('term', FILTER_CALLBACK, array('options' => 'sanitize_search_string')); if ($term != '') { - $sql_where .= ($sql_where != '' ? ' AND ' : 'WHERE ') . "program LIKE '%$term%'"; + $sql_where .= ($sql_where != '' ? ' AND ' : 'WHERE ') . 'program LIKE ?'; + $sql_params[] = '%' . $term . '%'; } if (get_request_var('term') == '') { if ($include_any) { - $return[] = array( + $return[] = [ 'label' => __('All Programs', 'syslog'), 'value' => __('All Programs', 'syslog'), - 'id' => '-1' - ); + 'id' => '-1' + ]; } if ($include_none) { - $return[] = array( + $return[] = [ 'label' => __('None', 'syslog'), 'value' => __('None', 'syslog'), - 'id' => '-2' - ); + 'id' => '-2' + ]; } } - $programs = syslog_db_fetch_assoc("SELECT program_id, program + $programs = syslog_db_fetch_assoc_prepared("SELECT program_id, program FROM syslog_programs $sql_where ORDER BY program - LIMIT 20"); + LIMIT 20", $sql_params); if (cacti_sizeof($programs)) { - foreach($programs as $program) { - $return[] = array( + foreach ($programs as $program) { + $return[] = [ 'label' => $program['program'], 'value' => $program['program'], - 'id' => $program['program_id'] - ); + 'id' => $program['program_id'] + ]; } } @@ -1995,7 +2109,7 @@ function syslog_form_callback($form_name, $classic_sql, $column_display, $column if (isset($_SESSION['sess_error_fields'])) { if (!empty($_SESSION['sess_error_fields'][$form_name])) { - $class .= ($class != '' ? ' ':'') . 'txtErrorTextBox'; + $class .= ($class != '' ? ' ' : '') . 'txtErrorTextBox'; unset($_SESSION['sess_error_fields'][$form_name]); } } @@ -2011,8 +2125,9 @@ function syslog_form_callback($form_name, $classic_sql, $column_display, $column } $theme = get_selected_theme(); + if ($theme == 'classic' || read_config_option('autocomplete') > 0) { - print "'; if (!empty($none_entry)) { print ""; @@ -2032,13 +2147,13 @@ function syslog_form_callback($form_name, $classic_sql, $column_display, $column print ""; print ""; print ""; - print ""; + print ''; if (!empty($none_entry) && empty($previous_value)) { $previous_value = $none_entry; } - print ""; + print ''; print ""; ?> array('regexp' => '/^([a-zA-Z0-9_]+)$/'))); + ['options' => ['regexp' => '/^([a-zA-Z0-9_]+)$/']]); - /* if we are to save this form, instead of display it */ + // if we are to save this form, instead of display it if (isset_request_var('selected_items')) { $selected_items = sanitize_unserialize_selected_items(get_request_var('selected_items')); $drp_action = get_request_var('drp_action'); @@ -121,11 +115,11 @@ function form_actions() { syslog_apply_selected_items_action( $selected_items, $drp_action, - array( + [ '1' => 'api_syslog_alert_remove', '2' => 'api_syslog_alert_disable', '3' => 'api_syslog_alert_enable' - ), + ], '4', get_nfilter_request_var('selected_items') ); @@ -141,59 +135,64 @@ function form_actions() { html_start_box($syslog_actions[get_request_var('drp_action')], '60%', '', '3', 'center', ''); - /* setup some variables */ - $alert_array = array(); $alert_list = ''; + // setup some variables + $alert_array = []; + $alert_list = ''; - /* loop through each of the clusters selected on the previous page and get more info about them */ + // loop through each of the clusters selected on the previous page and get more info about them foreach ($_POST as $var => $val) { if (preg_match('/^chk_([0-9]+)$/', $var, $matches)) { - /* ================= input validation ================= */ + // ================= input validation ================= input_validate_input_number($matches[1]); - /* ==================================================== */ + // ==================================================== + + $alert_info = syslog_db_fetch_cell_prepared('SELECT name + FROM `' . $syslogdb_default . '`.`syslog_alert` + WHERE id = ?', + [$matches[1]]); - $alert_info = syslog_db_fetch_cell('SELECT name FROM `' . $syslogdb_default . '`.`syslog_alert` WHERE id=' . $matches[1]); $alert_list .= '
  • ' . html_escape($alert_info) . '
  • '; $alert_array[] = $matches[1]; } } if (cacti_sizeof($alert_array)) { - if (get_request_var('drp_action') == '1') { /* delete */ + if (get_request_var('drp_action') == '1') { // delete print "
    + print " \n"; $title = __esc('Delete Syslog Alert Rule(s)', 'syslog'); - } elseif (get_request_var('drp_action') == '2') { /* disable */ + } elseif (get_request_var('drp_action') == '2') { // disable print " + print " \n"; $title = __esc('Disable Syslog Alert Rule(s)', 'syslog'); - } elseif (get_request_var('drp_action') == '3') { /* enable */ + } elseif (get_request_var('drp_action') == '3') { // enable print " + print " \n"; $title = __esc('Enable Syslog Alert Rule(s)', 'syslog'); - } elseif (get_request_var('drp_action') == '4') { /* export */ + } elseif (get_request_var('drp_action') == '4') { // export print " + print " \n"; @@ -226,18 +225,19 @@ function form_actions() { function alert_export() { global $syslogdb_default; - /* if we are to save this form, instead of display it */ + // if we are to save this form, instead of display it if (isset_request_var('selected_items')) { $selected_items = sanitize_unserialize_selected_items(get_nfilter_request_var('selected_items')); if ($selected_items != false) { $output = '' . PHP_EOL; + foreach ($selected_items as $id) { if ($id > 0) { $data = syslog_db_fetch_row_prepared('SELECT * FROM `' . $syslogdb_default . '`.`syslog_alert` WHERE id = ?', - array($id)); + [$id]); if (cacti_sizeof($data)) { unset($data['id']); @@ -258,7 +258,7 @@ function api_syslog_alert_save($id, $name, $method, $level, $num, $type, $messag $enabled, $severity, $command, $repeat_alert, $open_ticket, $notify = 0, $body = '') { global $syslogdb_default; - /* get the username */ + // get the username $username = db_fetch_cell('SELECT username FROM user_auth WHERE id=' . $_SESSION['sess_user_id']); if ($id) { @@ -276,9 +276,9 @@ function api_syslog_alert_save($id, $name, $method, $level, $num, $type, $messag $save['email'] = form_input_validate(trim($email), 'email', '', true, 3); $save['command'] = form_input_validate($command, 'command', '', true, 3); $save['notes'] = form_input_validate($notes, 'notes', '', true, 3); - $save['enabled'] = ($enabled == 'on' ? 'on':''); + $save['enabled'] = ($enabled == 'on' ? 'on' : ''); $save['repeat_alert'] = form_input_validate($repeat_alert, 'repeat_alert', '', true, 3); - $save['open_ticket'] = ($open_ticket == 'on' ? 'on':''); + $save['open_ticket'] = ($open_ticket == 'on' ? 'on' : ''); $save['type'] = $type; $save['severity'] = $severity; $save['method'] = $method; @@ -288,12 +288,13 @@ function api_syslog_alert_save($id, $name, $method, $level, $num, $type, $messag $save['date'] = time(); $id = 0; + if (!is_error_message()) { $sql = syslog_get_alert_sql($save, 100); if (cacti_sizeof($sql)) { - $db_sql = str_replace('%', '|||||', $sql['sql']); - $db_sql = str_replace('?', '%s', $db_sql); + $db_sql = str_replace('%', '|||||', $sql['sql']); + $db_sql = str_replace('?', '%s', $db_sql); $approx_sql = vsprintf($db_sql, $sql['params']); $approx_sql = str_replace('|||||', '%', $approx_sql); @@ -321,54 +322,50 @@ function api_syslog_alert_save($id, $name, $method, $level, $num, $type, $messag function api_syslog_alert_remove($id) { global $syslogdb_default; - syslog_db_execute("DELETE FROM `" . $syslogdb_default . "`.`syslog_alert` WHERE id='" . $id . "'"); + syslog_db_execute('DELETE FROM `' . $syslogdb_default . "`.`syslog_alert` WHERE id='" . $id . "'"); } function api_syslog_alert_disable($id) { global $syslogdb_default; - syslog_db_execute("UPDATE `" . $syslogdb_default . "`.`syslog_alert` SET enabled='' WHERE id='" . $id . "'"); + syslog_db_execute('UPDATE `' . $syslogdb_default . "`.`syslog_alert` SET enabled='' WHERE id='" . $id . "'"); } function api_syslog_alert_enable($id) { global $syslogdb_default; - syslog_db_execute("UPDATE `" . $syslogdb_default . "`.`syslog_alert` SET enabled='on' WHERE id='" . $id . "'"); + syslog_db_execute('UPDATE `' . $syslogdb_default . "`.`syslog_alert` SET enabled='on' WHERE id='" . $id . "'"); } -/* --------------------- - Alert Functions - --------------------- */ - -function syslog_get_alert_records(&$sql_where, $rows) { +function syslog_get_alert_records(&$sql_where, &$sql_params, $rows) { global $syslogdb_default; if (get_request_var('filter') != '') { - $sql_where .= (strlen($sql_where) ? ' AND ':'WHERE ') . - '(message LIKE ' . db_qstr('%' . get_request_var('filter') . '%') . ' - OR email LIKE ' . db_qstr('%' . get_request_var('filter') . '%') . ' - OR notes LIKE ' . db_qstr('%' . get_request_var('filter') . '%') . ' - OR name LIKE ' . db_qstr('%' . get_request_var('filter') . '%') . ')'; + $sql_where .= (strlen($sql_where) ? ' AND ' : 'WHERE ') . + '(message LIKE ? OR email LIKE ? OR notes LIKE ? OR name LIKE ?)'; + + $sql_params[] = '%' . get_request_var('filter') . '%'; + $sql_params[] = '%' . get_request_var('filter') . '%'; + $sql_params[] = '%' . get_request_var('filter') . '%'; + $sql_params[] = '%' . get_request_var('filter') . '%'; } - if (get_request_var('enabled') == '-1') { - // Display all status' - }elseif (get_request_var('enabled') == '1') { - $sql_where .= (strlen($sql_where) ? ' AND ':'WHERE ') . - "enabled='on'"; - } else { - $sql_where .= (strlen($sql_where) ? ' AND ':'WHERE ') . - "enabled=''"; + if (get_request_var('enabled') != '-1') { + if (get_request_var('enabled') == '1') { + $sql_where .= (strlen($sql_where) ? ' AND ' : 'WHERE ') . "enabled='on'"; + } else { + $sql_where .= (strlen($sql_where) ? ' AND ' : 'WHERE ') . "enabled=''"; + } } $sql_order = get_order_string(); - $sql_limit = ' LIMIT ' . ($rows*(get_request_var('page')-1)) . ',' . $rows; + $sql_limit = ' LIMIT ' . ($rows * (get_request_var('page') - 1)) . ',' . $rows; - $query_string = "SELECT * - FROM `" . $syslogdb_default . "`.`syslog_alert` + $query_string = 'SELECT * + FROM `' . $syslogdb_default . "`.`syslog_alert` $sql_where $sql_order $sql_limit"; - return syslog_db_fetch_assoc($query_string); + return syslog_db_fetch_assoc_prepared($query_string, $sql_params); } function get_repeat_array() { @@ -376,17 +373,17 @@ function get_repeat_array() { $multiplier = 300 / $poller_interval; - $repeatarray = array( + $repeatarray = [ $multiplier * 0 => __('Not Set', 'syslog'), - ); + ]; if ($multiplier > 1) { - $repeatarray += array( + $repeatarray += [ round($multiplier / 5,0) => __('1 Minute', 'syslog'), - ); + ]; } - $repeatarray += array( + $repeatarray += [ $multiplier * 1 => __('%d Minutes', 5, 'syslog'), $multiplier * 2 => __('%d Minutes', 10, 'syslog'), $multiplier * 3 => __('%d Minutes', 15, 'syslog'), @@ -405,9 +402,10 @@ function get_repeat_array() { $multiplier * 2016 => __('%d Week', 1, 'syslog'), $multiplier * 4032 => __('%d Weeks', 2, 'syslog'), $multiplier * 8640 => __('1 Month', 'syslog') - ); + ]; $alert_retention = read_config_option('syslog_alert_retention'); + if ($alert_retention != '' && $alert_retention > 0 && $alert_retention < 365) { $repeat_end = ($alert_retention * 24 * 60 * $multiplier) / 5; } @@ -427,16 +425,17 @@ function syslog_action_edit() { global $message_types, $severities; global $syslogdb_default; - /* ================= input validation ================= */ + // ================= input validation ================= get_filter_request_var('id'); get_filter_request_var('type'); get_filter_request_var('date'); - /* ==================================================== */ + // ==================================================== if (!isempty_request_var('id') && get_nfilter_request_var('action') == 'edit') { - $alert = syslog_db_fetch_row('SELECT * + $alert = syslog_db_fetch_row_prepared('SELECT * FROM `' . $syslogdb_default . '`.`syslog_alert` - WHERE id=' . get_request_var('id')); + WHERE id = ?', + [get_request_var('id')]); if (cacti_sizeof($alert)) { $header_label = __esc('Alert Edit [edit: %s]', $alert['name'], 'syslog'); @@ -444,11 +443,21 @@ function syslog_action_edit() { $header_label = __('Alert Edit [new]', 'syslog'); } } elseif (isset_request_var('id') && get_nfilter_request_var('action') == 'newedit') { - $syslog_rec = syslog_db_fetch_row("SELECT * - FROM `" . $syslogdb_default . "`.`syslog` - WHERE seq=" . get_request_var("id") . (isset_request_var('date') ? " AND logtime='" . get_request_var("date") . "'":"")); + $sql_where = 'WHERE seq = ?'; + $sql_params[] = get_request_var('id'); + + if (isset_request_var('date')) { + $sql_where .= ' AND logtime = ?'; + $sql_params[] = get_request_var('date'); + } + + $syslog_rec = syslog_db_fetch_row_prepared("SELECT * + FROM `$syslogdb_default`.`syslog` + $sql_where", + $sql_params); $header_label = __('Alert Edit [new]', 'syslog'); + if (cacti_sizeof($syslog_rec)) { $alert['message'] = $syslog_rec['message']; } @@ -468,180 +477,180 @@ function syslog_action_edit() { 'id', 'name' ); } else { - $lists = array('0' => __('N/A', 'syslog')); + $lists = ['0' => __('N/A', 'syslog')]; } $repeatarray = get_repeat_array(); - $fields_syslog_alert_edit = array( - 'spacer0' => array( - 'method' => 'spacer', + $fields_syslog_alert_edit = [ + 'spacer0' => [ + 'method' => 'spacer', 'friendly_name' => __('Details', 'syslog') - ), - 'name' => array( - 'method' => 'textbox', + ], + 'name' => [ + 'method' => 'textbox', 'friendly_name' => __('Name', 'syslog'), - 'description' => __('Please describe this Alert.', 'syslog'), - 'value' => '|arg1:name|', - 'max_length' => '250', - 'size' => 80 - ), - 'severity' => array( - 'method' => 'drop_array', + 'description' => __('Please describe this Alert.', 'syslog'), + 'value' => '|arg1:name|', + 'max_length' => '250', + 'size' => 80 + ], + 'severity' => [ + 'method' => 'drop_array', 'friendly_name' => __('Severity', 'syslog'), - 'description' => __('What is the Severity Level of this Alert?', 'syslog'), - 'value' => '|arg1:severity|', - 'array' => $severities, - 'default' => '1' - ), - 'level' => array( - 'method' => 'drop_array', + 'description' => __('What is the Severity Level of this Alert?', 'syslog'), + 'value' => '|arg1:severity|', + 'array' => $severities, + 'default' => '1' + ], + 'level' => [ + 'method' => 'drop_array', 'friendly_name' => __('Reporting Level', 'syslog'), - 'description' => __('For recording Re-Alert Cycles, should the Alert be tracked at the System or Device level.', 'syslog'), - 'value' => '|arg1:level|', - 'array' => array('0' => __('System', 'syslog'), '1' => __('Device', 'syslog')), - 'default' => '0' - ), - 'report_method' => array( - 'method' => 'drop_array', + 'description' => __('For recording Re-Alert Cycles, should the Alert be tracked at the System or Device level.', 'syslog'), + 'value' => '|arg1:level|', + 'array' => ['0' => __('System', 'syslog'), '1' => __('Device', 'syslog')], + 'default' => '0' + ], + 'report_method' => [ + 'method' => 'drop_array', 'friendly_name' => __('Reporting Method', 'syslog'), - 'description' => __('Define how to Alert on the syslog messages.', 'syslog'), - 'value' => '|arg1:method|', - 'array' => array('0' => __('Individual', 'syslog'), '1' => __('Threshold', 'syslog')), - 'default' => '0' - ), - 'num' => array( - 'method' => 'textbox', + 'description' => __('Define how to Alert on the syslog messages.', 'syslog'), + 'value' => '|arg1:method|', + 'array' => ['0' => __('Individual', 'syslog'), '1' => __('Threshold', 'syslog')], + 'default' => '0' + ], + 'num' => [ + 'method' => 'textbox', 'friendly_name' => __('Threshold', 'syslog'), - 'description' => __('For the \'Threshold\' method, If the number seen is above this value an Alert will be triggered.', 'syslog'), - 'value' => '|arg1:num|', - 'size' => '4', - 'max_length' => '10', - 'default' => '1' - ), - 'type' => array( - 'method' => 'drop_array', + 'description' => __('For the \'Threshold\' method, If the number seen is above this value an Alert will be triggered.', 'syslog'), + 'value' => '|arg1:num|', + 'size' => '4', + 'max_length' => '10', + 'default' => '1' + ], + 'type' => [ + 'method' => 'drop_array', 'friendly_name' => __('Match Type', 'syslog'), - 'description' => __('Define how you would like this string matched. If using the SQL Expression type you may use any valid SQL expression to generate the alarm. Available fields include \'message\', \'facility\', \'priority\', and \'host\'.', 'syslog'), - 'value' => '|arg1:type|', - 'array' => $message_types, - 'on_change' => 'changeTypes()', - 'default' => 'matchesc' - ), - 'message' => array( + 'description' => __('Define how you would like this string matched. If using the SQL Expression type you may use any valid SQL expression to generate the alarm. Available fields include \'message\', \'facility\', \'priority\', and \'host\'.', 'syslog'), + 'value' => '|arg1:type|', + 'array' => $message_types, + 'on_change' => 'changeTypes()', + 'default' => 'matchesc' + ], + 'message' => [ 'friendly_name' => __('Message Match String', 'syslog'), - 'description' => __('Enter the matching component of the syslog message, the facility or host name, or the SQL where clause if using the SQL Expression Match Type.', 'syslog'), + 'description' => __('Enter the matching component of the syslog message, the facility or host name, or the SQL where clause if using the SQL Expression Match Type.', 'syslog'), 'textarea_rows' => '2', 'textarea_cols' => '70', - 'method' => 'textarea', - 'class' => 'textAreaNotes', - 'value' => '|arg1:message|', - 'default' => '' - ), - 'enabled' => array( - 'method' => 'drop_array', + 'method' => 'textarea', + 'class' => 'textAreaNotes', + 'value' => '|arg1:message|', + 'default' => '' + ], + 'enabled' => [ + 'method' => 'drop_array', 'friendly_name' => __('Enabled', 'syslog'), - 'description' => __('Is this Alert Enabled?', 'syslog'), - 'value' => '|arg1:enabled|', - 'array' => array('on' => __('Enabled', 'syslog'), '' => __('Disabled', 'syslog')), - 'default' => 'on' - ), - 'repeat_alert' => array( + 'description' => __('Is this Alert Enabled?', 'syslog'), + 'value' => '|arg1:enabled|', + 'array' => ['on' => __('Enabled', 'syslog'), '' => __('Disabled', 'syslog')], + 'default' => 'on' + ], + 'repeat_alert' => [ 'friendly_name' => __('Re-Alert Cycle', 'syslog'), - 'method' => 'drop_array', - 'array' => $repeatarray, - 'default' => '0', - 'description' => __('Do not resend this alert again for the same host, until this amount of time has elapsed. For threshold based alarms, this applies to all hosts.', 'syslog'), - 'value' => '|arg1:repeat_alert|' - ), - 'notes' => array( + 'method' => 'drop_array', + 'array' => $repeatarray, + 'default' => '0', + 'description' => __('Do not resend this alert again for the same host, until this amount of time has elapsed. For threshold based alarms, this applies to all hosts.', 'syslog'), + 'value' => '|arg1:repeat_alert|' + ], + 'notes' => [ 'friendly_name' => __('Notes', 'syslog'), 'textarea_rows' => '5', 'textarea_cols' => '70', - 'description' => __('Space for Notes on the Alert', 'syslog'), - 'method' => 'textarea', - 'class' => 'textAreaNotes', - 'value' => '|arg1:notes|', - 'default' => '', - ), - 'header_email' => array( - 'method' => 'spacer', + 'description' => __('Space for Notes on the Alert', 'syslog'), + 'method' => 'textarea', + 'class' => 'textAreaNotes', + 'value' => '|arg1:notes|', + 'default' => '', + ], + 'header_email' => [ + 'method' => 'spacer', 'friendly_name' => __('Email Options', 'syslog') - ), - 'notify' => array( - 'method' => 'drop_array', + ], + 'notify' => [ + 'method' => 'drop_array', 'friendly_name' => __('Notification List', 'syslog'), - 'description' => __('Use the contents of this Notification List to dictate who should be notified and how.', 'syslog'), - 'value' => '|arg1:notify|', - 'array' => $lists, - 'none_value' => __('None', 'syslog'), - 'default' => '0' - ), - 'email' => array( - 'method' => 'textarea', + 'description' => __('Use the contents of this Notification List to dictate who should be notified and how.', 'syslog'), + 'value' => '|arg1:notify|', + 'array' => $lists, + 'none_value' => __('None', 'syslog'), + 'default' => '0' + ], + 'email' => [ + 'method' => 'textarea', 'friendly_name' => __('Emails to Notify', 'syslog'), 'textarea_rows' => '5', 'textarea_cols' => '70', - 'description' => __('Please enter a comma delimited list of Email addresses to inform. If you wish to send out Email to a recipient in SMS format, please prefix that recipient\'s Email address with \'sms@\'. For example, if the recipients SMS address is \'2485551212@mycarrier.net\', you would enter it as \'sms@2485551212@mycarrier.net\' and it will be formatted as an SMS message.', 'syslog'), - 'class' => 'textAreaNotes', - 'value' => '|arg1:email|', - 'max_length' => '255' - ), - 'body' => array( + 'description' => __('Please enter a comma delimited list of Email addresses to inform. If you wish to send out Email to a recipient in SMS format, please prefix that recipient\'s Email address with \'sms@\'. For example, if the recipients SMS address is \'2485551212@mycarrier.net\', you would enter it as \'sms@2485551212@mycarrier.net\' and it will be formatted as an SMS message.', 'syslog'), + 'class' => 'textAreaNotes', + 'value' => '|arg1:email|', + 'max_length' => '255' + ], + 'body' => [ 'friendly_name' => __('Email Body Text', 'syslog'), 'textarea_rows' => '6', 'textarea_cols' => '80', - 'description' => __('This information will appear in the body of the Alert just before the Alert details.', 'syslog'), - 'method' => 'textarea', - 'class' => 'textAreaNotes', - 'value' => '|arg1:body|', - 'default' => '', - ), - 'spacer1' => array( - 'method' => 'spacer', + 'description' => __('This information will appear in the body of the Alert just before the Alert details.', 'syslog'), + 'method' => 'textarea', + 'class' => 'textAreaNotes', + 'value' => '|arg1:body|', + 'default' => '', + ], + 'spacer1' => [ + 'method' => 'spacer', 'friendly_name' => __('Actions', 'syslog') - ), - 'open_ticket' => array( - 'method' => 'drop_array', + ], + 'open_ticket' => [ + 'method' => 'drop_array', 'friendly_name' => __('Open Ticket', 'syslog'), - 'description' => __('Should a Help Desk Ticket be opened for this Alert. NOTE: The Ticket command script will be populated with several \'ALERT_\' environment variables for convenience.', 'syslog'), - 'value' => '|arg1:open_ticket|', - 'array' => array('on' => __('Yes', 'syslog'), '' => __('No', 'syslog')), - 'default' => '' - ), - 'command' => array( + 'description' => __('Should a Help Desk Ticket be opened for this Alert. NOTE: The Ticket command script will be populated with several \'ALERT_\' environment variables for convenience.', 'syslog'), + 'value' => '|arg1:open_ticket|', + 'array' => ['on' => __('Yes', 'syslog'), '' => __('No', 'syslog')], + 'default' => '' + ], + 'command' => [ 'friendly_name' => __('Command', 'syslog'), 'textarea_rows' => '5', 'textarea_cols' => '70', - 'description' => __('When an Alert is triggered, run the following command. The following replacement variables are available \'<HOSTNAME>\', \'<ALERTID>\', \'<MESSAGE>\', \'<FACILITY>\', \'<PRIORITY>\', \'<SEVERITY>\'. Please note that \'<HOSTNAME>\' is only available on individual thresholds. These replacement values can appear on the command line, or be gathered from the environment of the script. When used from the environment, those variables will be prefixed with \'ALERT_\'.', 'syslog'), - 'method' => 'textarea', - 'class' => 'textAreaNotes', - 'value' => '|arg1:command|', - 'default' => '', - ), - 'id' => array( + 'description' => __('When an Alert is triggered, run the following command. The following replacement variables are available \'<HOSTNAME>\', \'<ALERTID>\', \'<MESSAGE>\', \'<FACILITY>\', \'<PRIORITY>\', \'<SEVERITY>\'. Please note that \'<HOSTNAME>\' is only available on individual thresholds. These replacement values can appear on the command line, or be gathered from the environment of the script. When used from the environment, those variables will be prefixed with \'ALERT_\'.', 'syslog'), + 'method' => 'textarea', + 'class' => 'textAreaNotes', + 'value' => '|arg1:command|', + 'default' => '', + ], + 'id' => [ 'method' => 'hidden_zero', - 'value' => '|arg1:id|' - ), - '_id' => array( + 'value' => '|arg1:id|' + ], + '_id' => [ 'method' => 'hidden_zero', - 'value' => '|arg1:id|' - ), - 'save_component_alert' => array( + 'value' => '|arg1:id|' + ], + 'save_component_alert' => [ 'method' => 'hidden', - 'value' => '1' - ) - ); + 'value' => '1' + ] + ]; form_start('syslog_alerts.php', 'syslog_edit'); html_start_box($header_label, '100%', '', '3', 'center', ''); draw_edit_form( - array( - 'config' => array('no_form_tag' => true), - 'fields' => inject_form_variables($fields_syslog_alert_edit, (cacti_sizeof($alert) ? $alert : array())) - ) + [ + 'config' => ['no_form_tag' => true], + 'fields' => inject_form_variables($fields_syslog_alert_edit, (cacti_sizeof($alert) ? $alert : [])) + ] ); html_end_box(); @@ -651,8 +660,8 @@ function syslog_action_edit() { ?>
    - + - '> + ' . ucfirst($efacility['facility']) . ''; + print "'; } } ?> - + - '> + + + + + + + + + + + + + + + - + - '> + + + - + - '> + +
    " . __('Emergency', 'syslog') . '" . __('Critical', 'syslog') . '" . __('Alert', 'syslog') . '" . __('Error', 'syslog') . '" . __('Warning', 'syslog') . '" . __('Notice', 'syslog') . '" . __('Info', 'syslog') . '" . __('Debug', 'syslog') . '" . __('Critical', 'syslog') . '" . __('Alert', 'syslog') . '" . __('Error', 'syslog') . '" . __('Warning', 'syslog') . '" . __('Notice', 'syslog') . '" . __('Info', 'syslog') . '" . __('Debug', 'syslog') . '
    " . __('Critical', 'syslog') . '" . __('Warning', 'syslog') . '" . __('Notice', 'syslog') . '" . __('Informational', 'syslog') . '" . __('Critical', 'syslog') . '" . __('Warning', 'syslog') . '" . __('Notice', 'syslog') . '" . __('Informational', 'syslog') . '
    " . __('No Syslog Messages', 'syslog') . "
    " . __('No Syslog Messages', 'syslog') . '
    " . __('No Alert Log Messages', 'syslog') . "
    " . __('No Alert Log Messages', 'syslog') . '

    " . __('Click \'Continue\' to Delete the following Syslog Alert Rule(s).', 'syslog') . "

      $alert_list
    "; - print "

    " . __('Click \'Continue\' to Disable the following Syslog Alert Rule(s).', 'syslog') . "

      $alert_list
    "; - print "

    " . __('Click \'Continue\' to Enable the following Syslog Alert Rule(s).', 'syslog') . "

      $alert_list
    "; - print "

    " . __('Click \'Continue\' to Export the following Syslog Alert Rule(s).', 'syslog') . "

      $alert_list
    "; - print "
    - + - '> + '> - + - + - '> - '> - '> + '> + '> + '>
    - '> + '>
    " . __('No Syslog Removal Rules Defined', 'syslog'). "
    " . __('No Syslog Removal Rules Defined', 'syslog') . '

    " . __('Click \'Continue\' to Delete the following Syslog Report(s).', 'syslog') . "

      $report_list
    "; - print "

    " . __('Click \'Continue\' to Disable the following Syslog Report(s).', 'syslog') . "

      $report_list
    "; - print "

    " . __('Click \'Continue\' to Enable the following Syslog Report(s).', 'syslog') . "

      $report_list
    "; - print "

    " . __('Click \'Continue\' to Export the following Syslog Report Rule(s).', 'syslog') . "

      $report_list
    "; - print "