Skip to content

Commit

Permalink
Apply fixes from StyleCI (librenms#12117)
Browse files Browse the repository at this point in the history
* Apply fixes from StyleCI

* Disable style check
  • Loading branch information
Jellyfrog committed Sep 21, 2020
1 parent 8ec9183 commit 77c5315
Show file tree
Hide file tree
Showing 752 changed files with 6,226 additions and 5,821 deletions.
32 changes: 16 additions & 16 deletions LibreNMS/Alert/AlertDB.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@

class AlertDB
{

/**
* @param $rule
* @param $query_builder
Expand All @@ -56,7 +55,7 @@ public static function genSQL($rule, $query_builder = false)
/**
* Generate SQL from Rule
* @param string $rule Rule to generate SQL for
* @return string|boolean
* @return string|bool
*/
public static function genSQLOld($rule)
{
Expand All @@ -66,29 +65,29 @@ public static function genSQLOld($rule)
return false;
}
//Pretty-print rule to dissect easier
$pretty = array('&&' => ' && ', '||' => ' || ');
$pretty = ['&&' => ' && ', '||' => ' || '];
$rule = str_replace(array_keys($pretty), $pretty, $rule);
$tmp = explode(" ", $rule);
$tables = array();
$tables = [];
foreach ($tmp as $opt) {
if (strstr($opt, '%') && strstr($opt, '.')) {
$tmpp = explode(".", $opt, 2);
$tmpp[0] = str_replace("%", "", $tmpp[0]);
$tables[] = mres(str_replace("(", "", $tmpp[0]));
$rule = str_replace($opt, $tmpp[0].'.'.$tmpp[1], $rule);
$rule = str_replace($opt, $tmpp[0] . '.' . $tmpp[1], $rule);
}
}
$tables = array_keys(array_flip($tables));
if (dbFetchCell('SELECT 1 FROM information_schema.COLUMNS WHERE TABLE_NAME = ? && COLUMN_NAME = ?', array($tables[0],'device_id')) != 1) {
if (dbFetchCell('SELECT 1 FROM information_schema.COLUMNS WHERE TABLE_NAME = ? && COLUMN_NAME = ?', [$tables[0], 'device_id']) != 1) {
//Our first table has no valid glue, append the 'devices' table to it!
array_unshift($tables, 'devices');
}
$x = sizeof($tables)-1;
$x = sizeof($tables) - 1;
$i = 0;
$join = "";
while ($i < $x) {
if (isset($tables[$i+1])) {
$gtmp = ResolveGlues(array($tables[$i+1]), 'device_id');
if (isset($tables[$i + 1])) {
$gtmp = ResolveGlues([$tables[$i + 1]], 'device_id');
if ($gtmp === false) {
//Cannot resolve glue-chain. Rule is invalid.
return false;
Expand All @@ -97,22 +96,23 @@ public static function genSQLOld($rule)
$qry = "";
foreach ($gtmp as $glue) {
if (empty($last)) {
list($tmp,$last) = explode('.', $glue);
$qry .= $glue.' = ';
[$tmp,$last] = explode('.', $glue);
$qry .= $glue . ' = ';
} else {
list($tmp,$new) = explode('.', $glue);
$qry .= $tmp.'.'.$last.' && '.$tmp.'.'.$new.' = ';
[$tmp,$new] = explode('.', $glue);
$qry .= $tmp . '.' . $last . ' && ' . $tmp . '.' . $new . ' = ';
$last = $new;
}
if (!in_array($tmp, $tables)) {
if (! in_array($tmp, $tables)) {
$tables[] = $tmp;
}
}
$join .= "( ".$qry.$tables[0].".device_id ) && ";
$join .= "( " . $qry . $tables[0] . ".device_id ) && ";
}
$i++;
}
$sql = "SELECT * FROM ".implode(",", $tables)." WHERE (".$join."".str_replace("(", "", $tables[0]).".device_id = ?) && (".str_replace(array("%","@","!~","~"), array("",".*","NOT REGEXP","REGEXP"), $rule).")";
$sql = "SELECT * FROM " . implode(",", $tables) . " WHERE (" . $join . "" . str_replace("(", "", $tables[0]) . ".device_id = ?) && (" . str_replace(["%", "@", "!~", "~"], ["", ".*", "NOT REGEXP", "REGEXP"], $rule) . ")";

return $sql;
}
}
1 change: 1 addition & 0 deletions LibreNMS/Alert/AlertData.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ public function __get($name)
if ($this->has($name)) {
return $this->get($name);
}

return "$name is not a valid \$alert data name";
}
}
28 changes: 15 additions & 13 deletions LibreNMS/Alert/AlertRules.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,8 @@

use App\Models\Device;
use Carbon\Carbon;
use LibreNMS\Alert\AlertUtil;
use LibreNMS\Alert\AlertDB;
use LibreNMS\Alert\AlertUtil;
use LibreNMS\Enum\AlertState;

class AlertRules
Expand All @@ -47,6 +47,7 @@ public function runRules($device_id)
//Check to see if under maintenance
if (AlertUtil::isMaintenance($device_id) > 0) {
echo "Under Maintenance, skipping alert rules check.\r\n";

return false;
}
//Check to see if disable alerting is set
Expand All @@ -55,12 +56,13 @@ public function runRules($device_id)
$device_alert['state'] = AlertState::CLEAR;
$device_alert['alerted'] = 0;
$device_alert['open'] = 0;
dbUpdate($device_alert, 'alerts', '`device_id` = ?', array($device_id));
dbUpdate($device_alert, 'alerts', '`device_id` = ?', [$device_id]);

return false;
}
//Checks each rule.
foreach (AlertUtil::getRules($device_id) as $rule) {
c_echo('Rule %p#'.$rule['id'].' (' . $rule['name'] . '):%n ');
c_echo('Rule %p#' . $rule['id'] . ' (' . $rule['name'] . '):%n ');
$extra = json_decode($rule['extra'], true);
if (isset($extra['invert'])) {
$inv = (bool) $extra['invert'];
Expand All @@ -72,7 +74,7 @@ public function runRules($device_id)
$rule['query'] = AlertDB::genSQL($rule['rule'], $rule['builder']);
}
$sql = $rule['query'];
$qry = dbFetchRows($sql, array($device_id));
$qry = dbFetchRows($sql, [$device_id]);
$cnt = count($qry);
for ($i = 0; $i < $cnt; $i++) {
if (isset($qry[$i]['ip'])) {
Expand All @@ -99,28 +101,28 @@ public function runRules($device_id)
// NOCHG here doesn't mean no change full stop. It means no change to the alert state
// So we update the details column with any fresh changes to the alert output we might have.
$alert_log = dbFetchRow('SELECT alert_log.id, alert_log.details FROM alert_log,alert_rules WHERE alert_log.rule_id = alert_rules.id && alert_log.device_id = ? && alert_log.rule_id = ? && alert_rules.disabled = 0
ORDER BY alert_log.id DESC LIMIT 1', array($device_id, $rule['id']));
ORDER BY alert_log.id DESC LIMIT 1', [$device_id, $rule['id']]);
$details = [];
if (!empty($alert_log['details'])) {
$details = json_decode(gzuncompress($alert_log['details']), true);
if (! empty($alert_log['details'])) {
$details = json_decode(gzuncompress($alert_log['details']), true);
}
$details['contacts'] = AlertUtil::getContacts($qry);
$details['rule'] = $qry;
$details = gzcompress(json_encode($details), 9);
dbUpdate(array('details' => $details), 'alert_log', 'id = ?', array($alert_log['id']));
$details['rule'] = $qry;
$details = gzcompress(json_encode($details), 9);
dbUpdate(['details' => $details], 'alert_log', 'id = ?', [$alert_log['id']]);
} else {
$extra = gzcompress(json_encode(array('contacts' => AlertUtil::getContacts($qry), 'rule'=>$qry)), 9);
$extra = gzcompress(json_encode(['contacts' => AlertUtil::getContacts($qry), 'rule'=>$qry]), 9);
if (dbInsert(['state' => AlertState::ACTIVE, 'device_id' => $device_id, 'rule_id' => $rule['id'], 'details' => $extra], 'alert_log')) {
if (is_null($current_state)) {
dbInsert(array('state' => AlertState::ACTIVE, 'device_id' => $device_id, 'rule_id' => $rule['id'], 'open' => 1,'alerted' => 0), 'alerts');
dbInsert(['state' => AlertState::ACTIVE, 'device_id' => $device_id, 'rule_id' => $rule['id'], 'open' => 1, 'alerted' => 0], 'alerts');
} else {
dbUpdate(['state' => AlertState::ACTIVE, 'open' => 1, 'timestamp' => Carbon::now()], 'alerts', 'device_id = ? && rule_id = ?', [$device_id, $rule['id']]);
}
c_echo(PHP_EOL . 'Status: %rALERT');
}
}
} else {
if (!is_null($current_state) && $current_state == AlertState::RECOVERED) {
if (! is_null($current_state) && $current_state == AlertState::RECOVERED) {
c_echo('Status: %bNOCHG');
} else {
if (dbInsert(['state' => AlertState::RECOVERED, 'device_id' => $device_id, 'rule_id' => $rule['id']], 'alert_log')) {
Expand Down
54 changes: 29 additions & 25 deletions LibreNMS/Alert/AlertUtil.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@
class AlertUtil
{
/**
*
* Get the rule_id for a specific alert
*
* @param $alert_id
Expand All @@ -43,11 +42,11 @@ class AlertUtil
private static function getRuleId($alert_id)
{
$query = "SELECT `rule_id` FROM `alerts` WHERE `id`=?";

return dbFetchCell($query, [$alert_id]);
}

/**
*
* Get the transport for a given alert_id
*
* @param $alert_id
Expand All @@ -57,22 +56,23 @@ public static function getAlertTransports($alert_id)
{
$query = "SELECT b.transport_id, b.transport_type, b.transport_name FROM alert_transport_map AS a LEFT JOIN alert_transports AS b ON b.transport_id=a.transport_or_group_id WHERE a.target_type='single' AND a.rule_id=? UNION DISTINCT SELECT d.transport_id, d.transport_type, d.transport_name FROM alert_transport_map AS a LEFT JOIN alert_transport_groups AS b ON a.transport_or_group_id=b.transport_group_id LEFT JOIN transport_group_transport AS c ON b.transport_group_id=c.transport_group_id LEFT JOIN alert_transports AS d ON c.transport_id=d.transport_id WHERE a.target_type='group' AND a.rule_id=?";
$rule_id = self::getRuleId($alert_id);

return dbFetchRows($query, [$rule_id, $rule_id]);
}

/**
*
* Returns the default transports
*
* @return array
*/
public static function getDefaultAlertTransports()
{
$query = "SELECT transport_id, transport_type, transport_name FROM alert_transports WHERE is_default=true";

return dbFetchRows($query);
}

/**
/**
* Find contacts for alert
* @param array $results Rule-Result
* @return array
Expand All @@ -84,37 +84,38 @@ public static function getContacts($results)
}
if (Config::get('alert.default_only') === true || Config::get('alerts.email.default_only') === true) {
$email = Config::get('alert.default_mail', Config::get('alerts.email.default'));

return $email ? [$email => ''] : [];
}
$users = User::query()->thisAuth()->get();
$contacts = array();
$uids = array();
$contacts = [];
$uids = [];
foreach ($results as $result) {
$tmp = null;
$tmp = null;
if (is_numeric($result["bill_id"])) {
$tmpa = dbFetchRows("SELECT user_id FROM bill_perms WHERE bill_id = ?", array($result["bill_id"]));
$tmpa = dbFetchRows("SELECT user_id FROM bill_perms WHERE bill_id = ?", [$result["bill_id"]]);
foreach ($tmpa as $tmp) {
$uids[$tmp['user_id']] = $tmp['user_id'];
}
}
if (is_numeric($result["port_id"])) {
$tmpa = dbFetchRows("SELECT user_id FROM ports_perms WHERE port_id = ?", array($result["port_id"]));
$tmpa = dbFetchRows("SELECT user_id FROM ports_perms WHERE port_id = ?", [$result["port_id"]]);
foreach ($tmpa as $tmp) {
$uids[$tmp['user_id']] = $tmp['user_id'];
}
}
if (is_numeric($result["device_id"])) {
if (Config::get('alert.syscontact') == true) {
if (dbFetchCell("SELECT attrib_value FROM devices_attribs WHERE attrib_type = 'override_sysContact_bool' AND device_id = ?", [$result["device_id"]])) {
$tmpa = dbFetchCell("SELECT attrib_value FROM devices_attribs WHERE attrib_type = 'override_sysContact_string' AND device_id = ?", array($result["device_id"]));
$tmpa = dbFetchCell("SELECT attrib_value FROM devices_attribs WHERE attrib_type = 'override_sysContact_string' AND device_id = ?", [$result["device_id"]]);
} else {
$tmpa = dbFetchCell("SELECT sysContact FROM devices WHERE device_id = ?", array($result["device_id"]));
$tmpa = dbFetchCell("SELECT sysContact FROM devices WHERE device_id = ?", [$result["device_id"]]);
}
if (!empty($tmpa)) {
if (! empty($tmpa)) {
$contacts[$tmpa] = '';
}
}
$tmpa = dbFetchRows("SELECT user_id FROM devices_perms WHERE device_id = ?", array($result["device_id"]));
$tmpa = dbFetchRows("SELECT user_id FROM devices_perms WHERE device_id = ?", [$result["device_id"]]);
foreach ($tmpa as $tmp) {
$uids[$tmp['user_id']] = $tmp['user_id'];
}
Expand All @@ -127,21 +128,21 @@ public static function getContacts($results)
if (empty($user['realname'])) {
$user['realname'] = $user['username'];
}
if (Config::get('alert.globals') && ( $user['level'] >= 5 && $user['level'] < 10 )) {
$contacts[$user['email']] = $user['realname'];
if (Config::get('alert.globals') && ($user['level'] >= 5 && $user['level'] < 10)) {
$contacts[$user['email']] = $user['realname'];
} elseif (Config::get('alert.admins') && $user['level'] == 10) {
$contacts[$user['email']] = $user['realname'];
} elseif (Config::get('alert.users') == true && in_array($user['user_id'], $uids)) {
$contacts[$user['email']] = $user['realname'];
}
}

$tmp_contacts = array();
$tmp_contacts = [];
foreach ($contacts as $email => $name) {
if (strstr($email, ',')) {
$split_contacts = preg_split('/[,\s]+/', $email);
foreach ($split_contacts as $split_email) {
if (!empty($split_email)) {
if (! empty($split_email)) {
$tmp_contacts[$split_email] = $name;
}
}
Expand All @@ -150,7 +151,7 @@ public static function getContacts($results)
}
}

if (!empty($tmp_contacts)) {
if (! empty($tmp_contacts)) {
// Validate contacts so we can fall back to default if configured.
$mail = new PHPMailer();
foreach ($tmp_contacts as $tmp_email => $tmp_name) {
Expand All @@ -160,12 +161,12 @@ public static function getContacts($results)
}
}

# Copy all email alerts to default contact if configured.
// Copy all email alerts to default contact if configured.
$default_mail = Config::get('alert.default_mail');
if (!isset($tmp_contacts[$default_mail]) && Config::get('alert.default_copy')) {
if (! isset($tmp_contacts[$default_mail]) && Config::get('alert.default_copy')) {
$tmp_contacts[$default_mail] = '';
}
# Send email to default contact if no other contact found
// Send email to default contact if no other contact found
if (empty($tmp_contacts) && Config::get('alert.default_if_none') && $default_mail) {
$tmp_contacts[$default_mail] = '';
}
Expand All @@ -187,6 +188,7 @@ public static function getRules($device_id)
)";

$params = [$device_id, $device_id, $device_id, $device_id, $device_id, $device_id, $device_id, $device_id];

return dbFetchRows($query, $params);
}

Expand All @@ -208,22 +210,23 @@ public static function isMaintenance($device_id)
public static function hasDisableNotify($device_id)
{
$device = Device::find($device_id);
return !is_null($device) && $device->disable_notify;

return ! is_null($device) && $device->disable_notify;
}

/**
* Process Macros
* @param string $rule Rule to process
* @param int $x Recursion-Anchor
* @return string|boolean
* @return string|bool
*/
public static function runMacros($rule, $x = 1)
{
$macros = Config::get('alert.macros.rule', []) .
krsort($macros);
foreach ($macros as $macro => $value) {
if (!strstr($macro, " ")) {
$rule = str_replace('%macros.'.$macro, '('.$value.')', $rule);
if (! strstr($macro, " ")) {
$rule = str_replace('%macros.' . $macro, '(' . $value . ')', $rule);
}
}
if (strstr($rule, "%macros.")) {
Expand All @@ -233,6 +236,7 @@ public static function runMacros($rule, $x = 1)
return false;
}
}

return $rule;
}
}
Loading

0 comments on commit 77c5315

Please sign in to comment.