diff --git a/LibreNMS/Alert/AlertDB.php b/LibreNMS/Alert/AlertDB.php index 50e9ea5264..12e3e8f4b8 100644 --- a/LibreNMS/Alert/AlertDB.php +++ b/LibreNMS/Alert/AlertDB.php @@ -38,7 +38,6 @@ use LibreNMS\Alerting\QueryBuilderParser; class AlertDB { - /** * @param $rule * @param $query_builder @@ -56,7 +55,7 @@ class AlertDB /** * Generate SQL from Rule * @param string $rule Rule to generate SQL for - * @return string|boolean + * @return string|bool */ public static function genSQLOld($rule) { @@ -66,29 +65,29 @@ class AlertDB 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; @@ -97,22 +96,23 @@ class AlertDB $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; } } diff --git a/LibreNMS/Alert/AlertData.php b/LibreNMS/Alert/AlertData.php index 928ded3181..9acc4eb35d 100644 --- a/LibreNMS/Alert/AlertData.php +++ b/LibreNMS/Alert/AlertData.php @@ -32,6 +32,7 @@ class AlertData extends \Illuminate\Support\Collection if ($this->has($name)) { return $this->get($name); } + return "$name is not a valid \$alert data name"; } } diff --git a/LibreNMS/Alert/AlertRules.php b/LibreNMS/Alert/AlertRules.php index 0bc3f01779..5e2068c666 100644 --- a/LibreNMS/Alert/AlertRules.php +++ b/LibreNMS/Alert/AlertRules.php @@ -35,8 +35,8 @@ namespace LibreNMS\Alert; 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 @@ -47,6 +47,7 @@ class AlertRules //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 @@ -55,12 +56,13 @@ class AlertRules $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']; @@ -72,7 +74,7 @@ class AlertRules $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'])) { @@ -99,20 +101,20 @@ class AlertRules // 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']]); } @@ -120,7 +122,7 @@ class AlertRules } } } 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')) { diff --git a/LibreNMS/Alert/AlertUtil.php b/LibreNMS/Alert/AlertUtil.php index 6ca72bf8b7..3d50ef5d7b 100644 --- a/LibreNMS/Alert/AlertUtil.php +++ b/LibreNMS/Alert/AlertUtil.php @@ -34,7 +34,6 @@ use PHPMailer\PHPMailer\PHPMailer; class AlertUtil { /** - * * Get the rule_id for a specific alert * * @param $alert_id @@ -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 @@ -57,11 +56,11 @@ class AlertUtil { $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 @@ -69,10 +68,11 @@ class AlertUtil 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 @@ -84,21 +84,22 @@ class AlertUtil } 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']; } @@ -106,15 +107,15 @@ class AlertUtil 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']; } @@ -127,8 +128,8 @@ class AlertUtil 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)) { @@ -136,12 +137,12 @@ class AlertUtil } } - $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; } } @@ -150,7 +151,7 @@ class AlertUtil } } - 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) { @@ -160,12 +161,12 @@ class AlertUtil } } - # 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] = ''; } @@ -187,6 +188,7 @@ class AlertUtil )"; $params = [$device_id, $device_id, $device_id, $device_id, $device_id, $device_id, $device_id, $device_id]; + return dbFetchRows($query, $params); } @@ -208,22 +210,23 @@ class AlertUtil 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.")) { @@ -233,6 +236,7 @@ class AlertUtil return false; } } + return $rule; } } diff --git a/LibreNMS/Alert/RunAlerts.php b/LibreNMS/Alert/RunAlerts.php index d925e01518..e583b4aaa8 100644 --- a/LibreNMS/Alert/RunAlerts.php +++ b/LibreNMS/Alert/RunAlerts.php @@ -32,18 +32,17 @@ namespace LibreNMS\Alert; use App\Models\DevicePerf; use LibreNMS\Config; -use LibreNMS\Util\Time; use LibreNMS\Enum\Alert; use LibreNMS\Enum\AlertState; +use LibreNMS\Util\Time; use Log; class RunAlerts { - /** * Populate variables * @param string $txt Text with variables - * @param boolean $wrap Wrap variable for text-usage (default: true) + * @param bool $wrap Wrap variable for text-usage (default: true) * @return string */ public function populate($txt, $wrap = true) @@ -51,81 +50,82 @@ class RunAlerts preg_match_all('/%([\w\.]+)/', $txt, $m); foreach ($m[1] as $tmp) { $orig = $tmp; - $rep = false; + $rep = false; if ($tmp == 'key' || $tmp == 'value') { - $rep = '$'.$tmp; + $rep = '$' . $tmp; } else { if (strstr($tmp, '.')) { $tmp = explode('.', $tmp, 2); - $pre = '$'.$tmp[0]; + $pre = '$' . $tmp[0]; $tmp = $tmp[1]; } else { $pre = '$obj'; } - $rep = $pre."['".str_replace('.', "']['", $tmp)."']"; + $rep = $pre . "['" . str_replace('.', "']['", $tmp) . "']"; if ($wrap) { - $rep = '{'.$rep.'}'; + $rep = '{' . $rep . '}'; } } - $txt = str_replace('%'.$orig, $rep, $txt); + $txt = str_replace('%' . $orig, $rep, $txt); } + return $txt; } /** * Describe Alert * @param array $alert Alert-Result from DB - * @return array|boolean + * @return array|bool */ public function describeAlert($alert) { - $obj = array(); - $i = 0; - $device = dbFetchRow('SELECT hostname, sysName, sysDescr, sysContact, os, type, ip, hardware, version, purpose, notes, uptime, status, status_reason, locations.location FROM devices LEFT JOIN locations ON locations.id = devices.location_id WHERE device_id = ?', array($alert['device_id'])); - $attribs = get_dev_attribs($alert['device_id']); + $obj = []; + $i = 0; + $device = dbFetchRow('SELECT hostname, sysName, sysDescr, sysContact, os, type, ip, hardware, version, purpose, notes, uptime, status, status_reason, locations.location FROM devices LEFT JOIN locations ON locations.id = devices.location_id WHERE device_id = ?', [$alert['device_id']]); + $attribs = get_dev_attribs($alert['device_id']); - $obj['hostname'] = $device['hostname']; - $obj['sysName'] = $device['sysName']; - $obj['sysDescr'] = $device['sysDescr']; - $obj['sysContact'] = $device['sysContact']; - $obj['os'] = $device['os']; - $obj['type'] = $device['type']; - $obj['ip'] = inet6_ntop($device['ip']); - $obj['hardware'] = $device['hardware']; - $obj['version'] = $device['version']; - $obj['serial'] = $device['serial']; - $obj['features'] = $device['features']; - $obj['location'] = $device['location']; - $obj['uptime'] = $device['uptime']; - $obj['uptime_short'] = Time::formatInterval($device['uptime'], 'short'); - $obj['uptime_long'] = Time::formatInterval($device['uptime']); - $obj['description'] = $device['purpose']; - $obj['notes'] = $device['notes']; - $obj['alert_notes'] = $alert['note']; - $obj['device_id'] = $alert['device_id']; - $obj['rule_id'] = $alert['rule_id']; - $obj['id'] = $alert['id']; - $obj['proc'] = $alert['proc']; - $obj['status'] = $device['status']; + $obj['hostname'] = $device['hostname']; + $obj['sysName'] = $device['sysName']; + $obj['sysDescr'] = $device['sysDescr']; + $obj['sysContact'] = $device['sysContact']; + $obj['os'] = $device['os']; + $obj['type'] = $device['type']; + $obj['ip'] = inet6_ntop($device['ip']); + $obj['hardware'] = $device['hardware']; + $obj['version'] = $device['version']; + $obj['serial'] = $device['serial']; + $obj['features'] = $device['features']; + $obj['location'] = $device['location']; + $obj['uptime'] = $device['uptime']; + $obj['uptime_short'] = Time::formatInterval($device['uptime'], 'short'); + $obj['uptime_long'] = Time::formatInterval($device['uptime']); + $obj['description'] = $device['purpose']; + $obj['notes'] = $device['notes']; + $obj['alert_notes'] = $alert['note']; + $obj['device_id'] = $alert['device_id']; + $obj['rule_id'] = $alert['rule_id']; + $obj['id'] = $alert['id']; + $obj['proc'] = $alert['proc']; + $obj['status'] = $device['status']; $obj['status_reason'] = $device['status_reason']; if (can_ping_device($attribs)) { $ping_stats = DevicePerf::where('device_id', $alert['device_id'])->latest('timestamp')->first(); $obj['ping_timestamp'] = $ping_stats->template; - $obj['ping_loss'] = $ping_stats->loss; - $obj['ping_min'] = $ping_stats->min; - $obj['ping_max'] = $ping_stats->max; - $obj['ping_avg'] = $ping_stats->avg; - $obj['debug'] = json_decode($ping_stats->debug, true); + $obj['ping_loss'] = $ping_stats->loss; + $obj['ping_min'] = $ping_stats->min; + $obj['ping_max'] = $ping_stats->max; + $obj['ping_avg'] = $ping_stats->avg; + $obj['debug'] = json_decode($ping_stats->debug, true); } - $extra = $alert['details']; + $extra = $alert['details']; - $tpl = new Template; - $template = $tpl->getTemplate($obj); + $tpl = new Template; + $template = $tpl->getTemplate($obj); if ($alert['state'] >= AlertState::ACTIVE) { - $obj['title'] = $template->title ?: 'Alert for device '.$device['hostname'].' - '.($alert['name'] ? $alert['name'] : $alert['rule']); + $obj['title'] = $template->title ?: 'Alert for device ' . $device['hostname'] . ' - ' . ($alert['name'] ? $alert['name'] : $alert['rule']); if ($alert['state'] == AlertState::ACKNOWLEDGED) { $obj['title'] .= ' got acknowledged'; } elseif ($alert['state'] == AlertState::WORSE) { @@ -139,79 +139,80 @@ class RunAlerts $obj['faults'][$i] = $incident; $obj['faults'][$i]['string'] = null; foreach ($incident as $k => $v) { - if (!empty($v) && $k != 'device_id' && (stristr($k, 'id') || stristr($k, 'desc') || stristr($k, 'msg')) && substr_count($k, '_') <= 1) { - $obj['faults'][$i]['string'] .= $k.' = '.$v.'; '; + if (! empty($v) && $k != 'device_id' && (stristr($k, 'id') || stristr($k, 'desc') || stristr($k, 'msg')) && substr_count($k, '_') <= 1) { + $obj['faults'][$i]['string'] .= $k . ' = ' . $v . '; '; } } } $obj['elapsed'] = $this->timeFormat(time() - strtotime($alert['time_logged'])); - if (!empty($extra['diff'])) { + if (! empty($extra['diff'])) { $obj['diff'] = $extra['diff']; } } elseif ($alert['state'] == AlertState::RECOVERED) { // Alert is now cleared - $id = dbFetchRow('SELECT alert_log.id,alert_log.time_logged,alert_log.details FROM alert_log WHERE alert_log.state != ? && alert_log.state != ? && alert_log.rule_id = ? && alert_log.device_id = ? && alert_log.id < ? ORDER BY id DESC LIMIT 1', array(AlertState::ACKNOWLEDGED, AlertState::RECOVERED, $alert['rule_id'], $alert['device_id'], $alert['id'])); + $id = dbFetchRow('SELECT alert_log.id,alert_log.time_logged,alert_log.details FROM alert_log WHERE alert_log.state != ? && alert_log.state != ? && alert_log.rule_id = ? && alert_log.device_id = ? && alert_log.id < ? ORDER BY id DESC LIMIT 1', [AlertState::ACKNOWLEDGED, AlertState::RECOVERED, $alert['rule_id'], $alert['device_id'], $alert['id']]); if (empty($id['id'])) { return false; } $extra = []; - if (!empty($id['details'])) { + if (! empty($id['details'])) { $extra = json_decode(gzuncompress($id['details']), true); } // Reset count to 0 so alerts will continue $extra['count'] = 0; - dbUpdate(array('details' => gzcompress(json_encode($id['details']), 9)), 'alert_log', 'id = ?', array($alert['id'])); + dbUpdate(['details' => gzcompress(json_encode($id['details']), 9)], 'alert_log', 'id = ?', [$alert['id']]); - $obj['title'] = $template->title_rec ?: 'Device '.$device['hostname'].' recovered from '.($alert['name'] ? $alert['name'] : $alert['rule']); + $obj['title'] = $template->title_rec ?: 'Device ' . $device['hostname'] . ' recovered from ' . ($alert['name'] ? $alert['name'] : $alert['rule']); $obj['elapsed'] = $this->timeFormat(strtotime($alert['time_logged']) - strtotime($id['time_logged'])); - $obj['id'] = $id['id']; + $obj['id'] = $id['id']; foreach ($extra['rule'] as $incident) { $i++; $obj['faults'][$i] = $incident; foreach ($incident as $k => $v) { - if (!empty($v) && $k != 'device_id' && (stristr($k, 'id') || stristr($k, 'desc') || stristr($k, 'msg')) && substr_count($k, '_') <= 1) { - $obj['faults'][$i]['string'] .= $k.' => '.$v.'; '; + if (! empty($v) && $k != 'device_id' && (stristr($k, 'id') || stristr($k, 'desc') || stristr($k, 'msg')) && substr_count($k, '_') <= 1) { + $obj['faults'][$i]['string'] .= $k . ' => ' . $v . '; '; } } } } else { return 'Unknown State'; }//end if - $obj['builder'] = $alert['builder']; - $obj['uid'] = $alert['id']; - $obj['alert_id'] = $alert['alert_id']; - $obj['severity'] = $alert['severity']; - $obj['rule'] = $alert['rule']; - $obj['name'] = $alert['name']; + $obj['builder'] = $alert['builder']; + $obj['uid'] = $alert['id']; + $obj['alert_id'] = $alert['alert_id']; + $obj['severity'] = $alert['severity']; + $obj['rule'] = $alert['rule']; + $obj['name'] = $alert['name']; $obj['timestamp'] = $alert['time_logged']; - $obj['contacts'] = $extra['contacts']; - $obj['state'] = $alert['state']; - $obj['alerted'] = $alert['alerted']; - $obj['template'] = $template; + $obj['contacts'] = $extra['contacts']; + $obj['state'] = $alert['state']; + $obj['alerted'] = $alert['alerted']; + $obj['template'] = $template; + return $obj; } /** * Format Elapsed Time - * @param integer $secs Seconds elapsed + * @param int $secs Seconds elapsed * @return string */ public function timeFormat($secs) { - $bit = array( + $bit = [ 'y' => $secs / 31556926 % 12, 'w' => $secs / 604800 % 52, 'd' => $secs / 86400 % 7, 'h' => $secs / 3600 % 24, 'm' => $secs / 60 % 60, 's' => $secs % 60, - ); - $ret = array(); + ]; + $ret = []; foreach ($bit as $k => $v) { if ($v > 0) { - $ret[] = $v.$k; + $ret[] = $v . $k; } } @@ -224,10 +225,10 @@ class RunAlerts public function clearStaleAlerts() { - $sql = "SELECT `alerts`.`id` AS `alert_id`, `devices`.`hostname` AS `hostname` FROM `alerts` LEFT JOIN `devices` ON `alerts`.`device_id`=`devices`.`device_id` RIGHT JOIN `alert_rules` ON `alerts`.`rule_id`=`alert_rules`.`id` WHERE `alerts`.`state`!=".AlertState::CLEAR." AND `devices`.`hostname` IS NULL"; + $sql = "SELECT `alerts`.`id` AS `alert_id`, `devices`.`hostname` AS `hostname` FROM `alerts` LEFT JOIN `devices` ON `alerts`.`device_id`=`devices`.`device_id` RIGHT JOIN `alert_rules` ON `alerts`.`rule_id`=`alert_rules`.`id` WHERE `alerts`.`state`!=" . AlertState::CLEAR . " AND `devices`.`hostname` IS NULL"; foreach (dbFetchRows($sql) as $alert) { if (empty($alert['hostname']) && isset($alert['alert_id'])) { - dbDelete('alerts', '`id` = ?', array($alert['alert_id'])); + dbDelete('alerts', '`id` = ?', [$alert['alert_id']]); echo "Stale-alert: #{$alert['alert_id']}" . PHP_EOL; } } @@ -235,14 +236,14 @@ class RunAlerts /** * Re-Validate Rule-Mappings - * @param integer $device_id Device-ID - * @param integer $rule Rule-ID - * @return boolean + * @param int $device_id Device-ID + * @param int $rule Rule-ID + * @return bool */ public function isRuleValid($device_id, $rule) { global $rulescache; - if (empty($rulescache[$device_id]) || !isset($rulescache[$device_id])) { + if (empty($rulescache[$device_id]) || ! isset($rulescache[$device_id])) { foreach (AlertUtil::getRules($device_id) as $chk) { $rulescache[$device_id][$chk['id']] = true; } @@ -255,11 +256,10 @@ class RunAlerts return false; } - /** * Issue Alert-Object * @param array $alert - * @return boolean + * @return bool */ public function issueAlert($alert) { @@ -268,13 +268,13 @@ class RunAlerts $alert['query'] = AlertDB::genSQL($alert['rule'], $alert['builder']); } $sql = $alert['query']; - $qry = dbFetchRows($sql, array($alert['device_id'])); + $qry = dbFetchRows($sql, [$alert['device_id']]); $alert['details']['contacts'] = AlertUtil::getContacts($qry); } $obj = $this->describeAlert($alert); if (is_array($obj)) { - echo 'Issuing Alert-UID #'.$alert['id'].'/'.$alert['state'].':' . PHP_EOL; + echo 'Issuing Alert-UID #' . $alert['id'] . '/' . $alert['state'] . ':' . PHP_EOL; $this->extTransports($obj); echo "\r\n"; @@ -283,17 +283,15 @@ class RunAlerts return true; } - /** * Issue ACK notification * @return void */ public function runAcks() { - - foreach ($this->loadAlerts('alerts.state = '.AlertState::ACKNOWLEDGED.' && alerts.open = '.AlertState::ACTIVE) as $alert) { + foreach ($this->loadAlerts('alerts.state = ' . AlertState::ACKNOWLEDGED . ' && alerts.open = ' . AlertState::ACTIVE) as $alert) { $this->issueAlert($alert); - dbUpdate(array('open' => AlertState::CLEAR), 'alerts', 'rule_id = ? && device_id = ?', array($alert['rule_id'], $alert['device_id'])); + dbUpdate(['open' => AlertState::CLEAR], 'alerts', 'rule_id = ? && device_id = ?', [$alert['rule_id'], $alert['device_id']]); } } @@ -303,7 +301,7 @@ class RunAlerts */ public function runFollowUp() { - foreach ($this->loadAlerts('alerts.state > '.AlertState::CLEAR.' && alerts.open = 0') as $alert) { + foreach ($this->loadAlerts('alerts.state > ' . AlertState::CLEAR . ' && alerts.open = 0') as $alert) { if ($alert['state'] != AlertState::ACKNOWLEDGED || ($alert['info']['until_clear'] === false)) { $rextra = json_decode($alert['extra'], true); if ($rextra['invert']) { @@ -313,7 +311,7 @@ class RunAlerts if (empty($alert['query'])) { $alert['query'] = AlertDB::genSQL($alert['rule'], $alert['builder']); } - $chk = dbFetchRows($alert['query'], array($alert['device_id'])); + $chk = dbFetchRows($alert['query'], [$alert['device_id']]); //make sure we can json_encode all the datas later $cnt = count($chk); for ($i = 0; $i < $cnt; $i++) { @@ -337,13 +335,13 @@ class RunAlerts if ($state > AlertState::CLEAR && $n > 0) { $alert['details']['rule'] = $chk; - if (dbInsert(array( + if (dbInsert([ 'state' => $state, 'device_id' => $alert['device_id'], 'rule_id' => $alert['rule_id'], - 'details' => gzcompress(json_encode($alert['details']), 9) - ), 'alert_log')) { - dbUpdate(array('state' => $state, 'open' => 1, 'alerted' => 1), 'alerts', 'rule_id = ? && device_id = ?', array($alert['rule_id'], $alert['device_id'])); + 'details' => gzcompress(json_encode($alert['details']), 9), + ], 'alert_log')) { + dbUpdate(['state' => $state, 'open' => 1, 'alerted' => 1], 'alerts', 'rule_id = ? && device_id = ?', [$alert['rule_id'], $alert['device_id']]); } echo $ret . ' (' . $o . '/' . $n . ")\r\n"; @@ -358,10 +356,10 @@ class RunAlerts foreach (dbFetchRows("SELECT alerts.id, alerts.alerted, alerts.device_id, alerts.rule_id, alerts.state, alerts.note, alerts.info FROM alerts WHERE $where") as $alert_status) { $alert = dbFetchRow( 'SELECT alert_log.id,alert_log.rule_id,alert_log.device_id,alert_log.state,alert_log.details,alert_log.time_logged,alert_rules.rule,alert_rules.severity,alert_rules.extra,alert_rules.name,alert_rules.query,alert_rules.builder,alert_rules.proc 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($alert_status['device_id'], $alert_status['rule_id']) + [$alert_status['device_id'], $alert_status['rule_id']] ); - if (empty($alert['rule_id']) || !$this->isRuleValid($alert_status['device_id'], $alert_status['rule_id'])) { + if (empty($alert['rule_id']) || ! $this->isRuleValid($alert_status['device_id'], $alert_status['rule_id'])) { echo 'Stale-Rule: #' . $alert_status['rule_id'] . '/' . $alert_status['device_id'] . "\r\n"; // Alert-Rule does not exist anymore, let's remove the alert-state. dbDelete('alerts', 'rule_id = ? && device_id = ?', [$alert_status['rule_id'], $alert_status['device_id']]); @@ -370,7 +368,7 @@ class RunAlerts $alert['state'] = $alert_status['state']; $alert['alerted'] = $alert_status['alerted']; $alert['note'] = $alert_status['note']; - if (!empty($alert['details'])) { + if (! empty($alert['details'])) { $alert['details'] = json_decode(gzuncompress($alert['details']), true); } $alert['info'] = json_decode($alert_status['info'], true); @@ -387,27 +385,27 @@ class RunAlerts */ public function runAlerts() { - foreach ($this->loadAlerts('alerts.state != '.AlertState::ACKNOWLEDGED.' && alerts.open = 1') as $alert) { - $noiss = false; - $noacc = false; - $updet = false; - $rextra = json_decode($alert['extra'], true); - if (!isset($rextra['recovery'])) { + foreach ($this->loadAlerts('alerts.state != ' . AlertState::ACKNOWLEDGED . ' && alerts.open = 1') as $alert) { + $noiss = false; + $noacc = false; + $updet = false; + $rextra = json_decode($alert['extra'], true); + if (! isset($rextra['recovery'])) { // backwards compatibility check $rextra['recovery'] = true; } - $chk = dbFetchRow('SELECT alerts.alerted,devices.ignore,devices.disabled FROM alerts,devices WHERE alerts.device_id = ? && devices.device_id = alerts.device_id && alerts.rule_id = ?', array($alert['device_id'], $alert['rule_id'])); + $chk = dbFetchRow('SELECT alerts.alerted,devices.ignore,devices.disabled FROM alerts,devices WHERE alerts.device_id = ? && devices.device_id = alerts.device_id && alerts.rule_id = ?', [$alert['device_id'], $alert['rule_id']]); if ($chk['alerted'] == $alert['state']) { $noiss = true; } $tolerence_window = Config::get('alert.tolerance_window'); - if (!empty($rextra['count']) && empty($rextra['interval'])) { + if (! empty($rextra['count']) && empty($rextra['interval'])) { // This check below is for compat-reasons - if (!empty($rextra['delay']) && $alert['state'] != AlertState::RECOVERED) { - if ((time() - strtotime($alert['time_logged']) + $tolerence_window) < $rextra['delay'] || (!empty($alert['details']['delay']) && (time() - $alert['details']['delay'] + $tolerence_window) < $rextra['delay'])) { + if (! empty($rextra['delay']) && $alert['state'] != AlertState::RECOVERED) { + if ((time() - strtotime($alert['time_logged']) + $tolerence_window) < $rextra['delay'] || (! empty($alert['details']['delay']) && (time() - $alert['details']['delay'] + $tolerence_window) < $rextra['delay'])) { continue; } else { $alert['details']['delay'] = time(); @@ -415,7 +413,7 @@ class RunAlerts } } - if ($alert['state'] == AlertState::ACTIVE && !empty($rextra['count']) && ($rextra['count'] == -1 || $alert['details']['count']++ < $rextra['count'])) { + if ($alert['state'] == AlertState::ACTIVE && ! empty($rextra['count']) && ($rextra['count'] == -1 || $alert['details']['count']++ < $rextra['count'])) { if ($alert['details']['count'] < $rextra['count']) { $noacc = true; } @@ -425,12 +423,12 @@ class RunAlerts } } else { // This is the new way - if (!empty($rextra['delay']) && (time() - strtotime($alert['time_logged']) + $tolerence_window) < $rextra['delay'] && $alert['state'] != AlertState::RECOVERED) { + if (! empty($rextra['delay']) && (time() - strtotime($alert['time_logged']) + $tolerence_window) < $rextra['delay'] && $alert['state'] != AlertState::RECOVERED) { continue; } - if (!empty($rextra['interval'])) { - if (!empty($alert['details']['interval']) && (time() - $alert['details']['interval'] + $tolerence_window) < $rextra['interval']) { + if (! empty($rextra['interval'])) { + if (! empty($alert['details']['interval']) && (time() - $alert['details']['interval'] + $tolerence_window) < $rextra['interval']) { continue; } else { $alert['details']['interval'] = time(); @@ -438,7 +436,7 @@ class RunAlerts } } - if (in_array($alert['state'], [AlertState::ACTIVE, AlertState::WORSE, AlertState::BETTER]) && !empty($rextra['count']) && ($rextra['count'] == -1 || $alert['details']['count']++ < $rextra['count'])) { + if (in_array($alert['state'], [AlertState::ACTIVE, AlertState::WORSE, AlertState::BETTER]) && ! empty($rextra['count']) && ($rextra['count'] == -1 || $alert['details']['count']++ < $rextra['count'])) { if ($alert['details']['count'] < $rextra['count']) { $noacc = true; } @@ -459,11 +457,11 @@ class RunAlerts } if ($updet) { - dbUpdate(array('details' => gzcompress(json_encode($alert['details']), 9)), 'alert_log', 'id = ?', array($alert['id'])); + dbUpdate(['details' => gzcompress(json_encode($alert['details']), 9)], 'alert_log', 'id = ?', [$alert['id']]); } - if (!empty($rextra['mute'])) { - echo 'Muted Alert-UID #'.$alert['id']."\r\n"; + if (! empty($rextra['mute'])) { + echo 'Muted Alert-UID #' . $alert['id'] . "\r\n"; $noiss = true; } @@ -477,18 +475,17 @@ class RunAlerts $noiss = true; } - if (!$noiss) { + if (! $noiss) { $this->issueAlert($alert); - dbUpdate(array('alerted' => $alert['state']), 'alerts', 'rule_id = ? && device_id = ?', array($alert['rule_id'], $alert['device_id'])); + dbUpdate(['alerted' => $alert['state']], 'alerts', 'rule_id = ? && device_id = ?', [$alert['rule_id'], $alert['device_id']]); } - if (!$noacc) { - dbUpdate(array('open' => 0), 'alerts', 'rule_id = ? && device_id = ?', array($alert['rule_id'], $alert['device_id'])); + if (! $noacc) { + dbUpdate(['open' => 0], 'alerts', 'rule_id = ? && device_id = ?', [$alert['rule_id'], $alert['device_id']]); } } } - /** * Run external transports * @param array $obj Alert-Array @@ -496,17 +493,17 @@ class RunAlerts */ public function extTransports($obj) { - $type = new Template; + $type = new Template; // If alert transport mapping exists, override the default transports $transport_maps = AlertUtil::getAlertTransports($obj['alert_id']); - if (!$transport_maps) { + if (! $transport_maps) { $transport_maps = AlertUtil::getDefaultAlertTransports(); } // alerting for default contacts, etc - if (Config::get('alert.transports.mail') === true && !empty($obj['contacts'])) { + if (Config::get('alert.transports.mail') === true && ! empty($obj['contacts'])) { $transport_maps[] = [ 'transport_id' => null, 'transport_type' => 'mail', @@ -515,16 +512,16 @@ class RunAlerts } foreach ($transport_maps as $item) { - $class = 'LibreNMS\\Alert\\Transport\\'.ucfirst($item['transport_type']); + $class = 'LibreNMS\\Alert\\Transport\\' . ucfirst($item['transport_type']); if (class_exists($class)) { //FIXME remove Deprecated transport $transport_title = "Transport {$item['transport_type']}"; $obj['transport'] = $item['transport_type']; $obj['transport_name'] = $item['transport_name']; - $obj['alert'] = new AlertData($obj); - $obj['title'] = $type->getTitle($obj); + $obj['alert'] = new AlertData($obj); + $obj['title'] = $type->getTitle($obj); $obj['alert']['title'] = $obj['title']; - $obj['msg'] = $type->getBody($obj); + $obj['msg'] = $type->getBody($obj); c_echo(" :: $transport_title => "); try { $instance = new $class($item['transport_id']); @@ -548,8 +545,8 @@ class RunAlerts { $prefix = [ AlertState::RECOVERED => "recovery", - AlertState::ACTIVE => $obj['severity']." alert", - AlertState::ACKNOWLEDGED => "acknowledgment" + AlertState::ACTIVE => $obj['severity'] . " alert", + AlertState::ACKNOWLEDGED => "acknowledgment", ]; $prefix[3] = &$prefix[0]; $prefix[4] = &$prefix[0]; @@ -557,7 +554,7 @@ class RunAlerts if ($obj['state'] == AlertState::RECOVERED) { $severity = Alert::OK; } elseif ($obj['state'] == AlertState::ACTIVE) { - $severity = Alert::SEVERITIES[$obj['severity']] ?? Alert::UNKNOWN; + $severity = Alert::SEVERITIES[$obj['severity']] ?? Alert::UNKNOWN; } elseif ($obj['state'] == AlertState::ACKNOWLEDGED) { $severity = Alert::NOTICE; } else { @@ -574,7 +571,6 @@ class RunAlerts echo "ERROR: $result\r\n"; Log::event('Could not issue ' . $prefix[$obj['state']] . " for rule '" . $obj['name'] . "' to transport '" . $transport . "' Error: " . $result, $obj['device_id'], 'error', Alert::ERROR); } - return; } /** @@ -585,13 +581,12 @@ class RunAlerts */ public function isParentDown($device) { - $parent_count = dbFetchCell("SELECT count(*) from `device_relationships` WHERE `child_device_id` = ?", array($device)); - if (!$parent_count) { + $parent_count = dbFetchCell("SELECT count(*) from `device_relationships` WHERE `child_device_id` = ?", [$device]); + if (! $parent_count) { return false; } - - $down_parent_count = dbFetchCell("SELECT count(*) from devices as d LEFT JOIN devices_attribs as a ON d.device_id=a.device_id LEFT JOIN device_relationships as r ON d.device_id=r.parent_device_id WHERE d.status=0 AND d.ignore=0 AND d.disabled=0 AND r.child_device_id=? AND (d.status_reason='icmp' OR (a.attrib_type='override_icmp_disable' AND a.attrib_value=true))", array($device)); + $down_parent_count = dbFetchCell("SELECT count(*) from devices as d LEFT JOIN devices_attribs as a ON d.device_id=a.device_id LEFT JOIN device_relationships as r ON d.device_id=r.parent_device_id WHERE d.status=0 AND d.ignore=0 AND d.disabled=0 AND r.child_device_id=? AND (d.status_reason='icmp' OR (a.attrib_type='override_icmp_disable' AND a.attrib_value=true))", [$device]); if ($down_parent_count == $parent_count) { return true; } diff --git a/LibreNMS/Alert/Template.php b/LibreNMS/Alert/Template.php index 247726e6f4..df11894489 100644 --- a/LibreNMS/Alert/Template.php +++ b/LibreNMS/Alert/Template.php @@ -33,7 +33,6 @@ class Template public $template; /** - * * Get the template details * * @param null $obj @@ -48,9 +47,10 @@ class Template $this->template = AlertTemplate::whereHas('map', function ($query) use ($obj) { $query->where('alert_rule_id', '=', $obj['rule_id']); })->first(); - if (!$this->template) { + if (! $this->template) { $this->template = AlertTemplate::where('name', '=', 'Default Alert Template')->first(); } + return $this->template; } @@ -65,7 +65,6 @@ class Template } /** - * * Parse Blade body * * @param $data @@ -82,7 +81,6 @@ class Template } /** - * * Parse Blade title * * @param $data @@ -99,7 +97,6 @@ class Template } /** - * * Get the default template * * @return string @@ -108,7 +105,7 @@ class Template { return '{{ $alert->title }}' . PHP_EOL . 'Severity: {{ $alert->severity }}' . PHP_EOL . - '@if ($alert->state == '.AlertState::RECOVERED.')Time elapsed: {{ $alert->elapsed }} @endif ' . PHP_EOL . + '@if ($alert->state == ' . AlertState::RECOVERED . ')Time elapsed: {{ $alert->elapsed }} @endif ' . PHP_EOL . 'Timestamp: {{ $alert->timestamp }}' . PHP_EOL . 'Unique-ID: {{ $alert->uid }}' . PHP_EOL . 'Rule: @if ($alert->name) {{ $alert->name }} @else {{ $alert->rule }} @endif ' . PHP_EOL . diff --git a/LibreNMS/Alert/Transport.php b/LibreNMS/Alert/Transport.php index 04f9083b71..fce28b488e 100644 --- a/LibreNMS/Alert/Transport.php +++ b/LibreNMS/Alert/Transport.php @@ -3,9 +3,9 @@ namespace LibreNMS\Alert; use Illuminate\Support\Str; -use LibreNMS\Interfaces\Alert\Transport as TransportInterface; use LibreNMS\Config; use LibreNMS\Enum\AlertState; +use LibreNMS\Interfaces\Alert\Transport as TransportInterface; abstract class Transport implements TransportInterface { @@ -17,7 +17,7 @@ abstract class Transport implements TransportInterface */ public function __construct($transport_id = null) { - if (!empty($transport_id)) { + if (! empty($transport_id)) { $sql = "SELECT `transport_config` FROM `alert_transports` WHERE `transport_id`=?"; $this->config = json_decode(dbFetchCell($sql, [$transport_id]), true); } @@ -34,27 +34,28 @@ abstract class Transport implements TransportInterface $options = []; foreach (explode(PHP_EOL, $input) as $option) { if (Str::contains($option, '=')) { - list($k,$v) = explode('=', $option, 2); + [$k,$v] = explode('=', $option, 2); $options[$k] = trim($v); } } + return $options; } - /** + /** * Get the hex color string for a particular state - * @param integer $state State code from alert + * @param int $state State code from alert * @return string Hex color, default to #337AB7 blue if state unrecognised */ public static function getColorForState($state) { - $colors = array( + $colors = [ AlertState::CLEAR => Config::get('alert_colour.ok'), AlertState::ACTIVE => Config::get('alert_colour.bad'), AlertState::ACKNOWLEDGED => Config::get('alert_colour.acknowledged'), AlertState::WORSE => Config::get('alert_colour.worse'), AlertState::BETTER => Config::get('alert_colour.better'), - ); + ]; return isset($colors[$state]) ? $colors[$state] : '#337AB7'; } diff --git a/LibreNMS/Alert/Transport/Alerta.php b/LibreNMS/Alert/Transport/Alerta.php index ab4fe3d6e8..fcbe7f9388 100644 --- a/LibreNMS/Alert/Transport/Alerta.php +++ b/LibreNMS/Alert/Transport/Alerta.php @@ -5,7 +5,7 @@ * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. Please see LICENSE.txt at the top level of * the source code distribution for details. */ - /** +/** * API Transport * @author GitStoph * @copyright 2019 GitStoph @@ -13,11 +13,12 @@ * @package LibreNMS * @subpackage Alerts */ + namespace LibreNMS\Alert\Transport; use LibreNMS\Alert\Transport; -use LibreNMS\Enum\AlertState; use LibreNMS\Config; +use LibreNMS\Enum\AlertState; class Alerta extends Transport { @@ -28,8 +29,10 @@ class Alerta extends Transport $opts['apikey'] = $this->config['apikey']; $opts['alertstate'] = $this->config['alertstate']; $opts['recoverstate'] = $this->config['recoverstate']; + return $this->contactAlerta($obj, $opts); } + public function contactAlerta($obj, $opts) { $host = $opts['url']; @@ -55,30 +58,33 @@ class Alerta extends Transport 'type' => $obj['type'], 'ip' => $obj['ip'], 'uptime' => $obj['uptime_long'], - 'moreInfo' => ''.$devicehostname.'', + 'moreInfo' => '' . $devicehostname . '', ], 'origin' => $obj['rule'], 'type' => $obj['title'], ]; $alert_message = json_encode($data); set_curl_proxy($curl); - $headers = array('Content-Type: application/json', 'Authorization: Key ' . $opts['apikey']); + $headers = ['Content-Type: application/json', 'Authorization: Key ' . $opts['apikey']]; curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); curl_setopt($curl, CURLOPT_URL, $host); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, $alert_message); - $ret = curl_exec($curl); + $ret = curl_exec($curl); $code = curl_getinfo($curl, CURLINFO_HTTP_CODE); if ($code != 201) { var_dump("API '$host' returned Error"); var_dump("Params: " . $alert_message); var_dump("Return: " . $ret); var_dump("Headers: " . $headers); + return 'HTTP Status code ' . $code; } + return true; } + public static function configTemplate() { return [ @@ -112,12 +118,12 @@ class Alerta extends Transport 'name' => 'recoverstate', 'descr' => 'What severity you want Alerta to reflect when rule unmatches/recovers.', 'type' => 'text', - ] + ], ], 'validation' => [ 'alerta-url' => 'required|url', 'apikey' => 'required|string', - ] + ], ]; } } diff --git a/LibreNMS/Alert/Transport/Alertmanager.php b/LibreNMS/Alert/Transport/Alertmanager.php index bc19cce960..7983988793 100644 --- a/LibreNMS/Alert/Transport/Alertmanager.php +++ b/LibreNMS/Alert/Transport/Alertmanager.php @@ -20,11 +20,12 @@ * @package LibreNMS * @subpackage Alerts */ + namespace LibreNMS\Alert\Transport; use LibreNMS\Alert\Transport; -use LibreNMS\Enum\AlertState; use LibreNMS\Config; +use LibreNMS\Enum\AlertState; class Alertmanager extends Transport { @@ -43,11 +44,11 @@ class Alertmanager extends Transport } else { $alertmanager_status = 'startsAt'; } - $gen_url = (Config::get('base_url') . 'device/device=' . $obj['device_id']); - $host = ($api['url'] . '/api/v2/alerts'); - $curl = curl_init(); + $gen_url = (Config::get('base_url') . 'device/device=' . $obj['device_id']); + $host = ($api['url'] . '/api/v2/alerts'); + $curl = curl_init(); $alertmanager_msg = strip_tags($obj['msg']); - $data = [[ + $data = [[ $alertmanager_status => date("c"), 'generatorURL' => $gen_url, 'annotations' => [ @@ -56,16 +57,16 @@ class Alertmanager extends Transport 'description' => $alertmanager_msg, ], 'labels' => [ - 'alertname' => $obj['name'], - 'severity' => $obj['severity'], - 'instance' => $obj['hostname'], - ], + 'alertname' => $obj['name'], + 'severity' => $obj['severity'], + 'instance' => $obj['hostname'], + ], ]]; unset($api['url']); foreach ($api as $label => $value) { $data[0]['labels'][$label] = $value; - }; + } $alert_message = json_encode($data); curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: application/json']); @@ -75,11 +76,12 @@ class Alertmanager extends Transport curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, $alert_message); - $ret = curl_exec($curl); + $ret = curl_exec($curl); $code = curl_getinfo($curl, CURLINFO_HTTP_CODE); if ($code != 200) { return 'HTTP Status code ' . $code; } + return true; } @@ -98,11 +100,11 @@ class Alertmanager extends Transport 'name' => 'alertmanager-options', 'descr' => 'Alertmanager Options', 'type' => 'textarea', - ] + ], ], 'validation' => [ 'alertmanager-url' => 'required|url', - ] + ], ]; } } diff --git a/LibreNMS/Alert/Transport/Api.php b/LibreNMS/Alert/Transport/Api.php index 17384ec8ff..8f9858ae0a 100644 --- a/LibreNMS/Alert/Transport/Api.php +++ b/LibreNMS/Alert/Transport/Api.php @@ -25,9 +25,9 @@ namespace LibreNMS\Alert\Transport; +use GuzzleHttp\Client; use LibreNMS\Alert\Transport; use LibreNMS\Enum\AlertState; -use GuzzleHttp\Client; class Api extends Transport { @@ -39,6 +39,7 @@ class Api extends Transport $body = $this->config['api-body']; $method = $this->config['api-method']; $auth = [$this->config['api-auth-username'], $this->config['api-auth-password']]; + return $this->contactAPI($obj, $url, $options, $method, $auth, $headers, $body); } @@ -53,7 +54,7 @@ class Api extends Transport //get each line of key-values and process the variables for Headers; foreach (preg_split("/\\r\\n|\\r|\\n/", $headers, -1, PREG_SPLIT_NO_EMPTY) as $current_line) { - list($u_key, $u_val) = explode('=', $current_line, 2); + [$u_key, $u_val] = explode('=', $current_line, 2); foreach ($obj as $p_key => $p_val) { $u_val = str_replace("{{ $" . $p_key . ' }}', $p_val, $u_val); } @@ -62,7 +63,7 @@ class Api extends Transport } //get each line of key-values and process the variables for Options; foreach (preg_split("/\\r\\n|\\r|\\n/", $options, -1, PREG_SPLIT_NO_EMPTY) as $current_line) { - list($u_key, $u_val) = explode('=', $current_line, 2); + [$u_key, $u_val] = explode('=', $current_line, 2); // Replace the values foreach ($obj as $p_key => $p_val) { $u_val = str_replace("{{ $" . $p_key . ' }}', $p_val, $u_val); @@ -73,7 +74,7 @@ class Api extends Transport $client = new \GuzzleHttp\Client(); $request_opts['proxy'] = get_guzzle_proxy(); - if (isset($auth) && !empty($auth[0])) { + if (isset($auth) && ! empty($auth[0])) { $request_opts['auth'] = $auth; } if (count($request_heads) > 0) { @@ -98,9 +99,11 @@ class Api extends Transport var_dump($query); var_dump("Response headers:"); var_dump($res->getHeaders()); - var_dump("Return: ".$res->getReasonPhrase()); - return 'HTTP Status code '.$code; + var_dump("Return: " . $res->getReasonPhrase()); + + return 'HTTP Status code ' . $code; } + return true; } @@ -116,8 +119,8 @@ class Api extends Transport 'options' => [ 'GET' => 'GET', 'POST' => 'POST', - 'PUT' => 'PUT' - ] + 'PUT' => 'PUT', + ], ], [ 'title' => 'API URL', @@ -154,12 +157,12 @@ class Api extends Transport 'name' => 'api-auth-password', 'descr' => 'Auth Password', 'type' => 'password', - ] + ], ], 'validation' => [ 'api-method' => 'in:GET,POST,PUT', - 'api-url' => 'required|url' - ] + 'api-url' => 'required|url', + ], ]; } } diff --git a/LibreNMS/Alert/Transport/Boxcar.php b/LibreNMS/Alert/Transport/Boxcar.php index 9e68ffc206..3705547480 100644 --- a/LibreNMS/Alert/Transport/Boxcar.php +++ b/LibreNMS/Alert/Transport/Boxcar.php @@ -39,8 +39,8 @@ namespace LibreNMS\Alert\Transport; use LibreNMS\Alert\Transport; -use LibreNMS\Enum\AlertState; use LibreNMS\Config; +use LibreNMS\Enum\AlertState; class Boxcar extends Transport { @@ -54,19 +54,19 @@ class Boxcar extends Transport public static function contactBoxcar($obj, $api) { - $data = []; - $data['user_credentials'] = $api['access_token']; + $data = []; + $data['user_credentials'] = $api['access_token']; $data['notification[source_name]'] = Config::get('project_id', 'librenms'); switch ($obj['severity']) { case "critical": $severity = "Critical"; - if (!empty($api['sound_critical'])) { + if (! empty($api['sound_critical'])) { $data['notification[sound]'] = $api['sound_critical']; } break; case "warning": $severity = "Warning"; - if (!empty($api['sound_warning'])) { + if (! empty($api['sound_warning'])) { $data['notification[sound]'] = $api['sound_warning']; } break; @@ -74,7 +74,7 @@ class Boxcar extends Transport switch ($obj['state']) { case AlertState::RECOVERED: $title_text = "OK"; - if (!empty($api['sound_ok'])) { + if (! empty($api['sound_ok'])) { $data['notification[sound]'] = $api['sound_ok']; } break; @@ -86,15 +86,15 @@ class Boxcar extends Transport break; } $data['notification[title]'] = $title_text . " - " . $obj['hostname'] . " - " . $obj['name']; - $message_text = "Timestamp: " . $obj['timestamp']; - if (!empty($obj['faults'])) { + $message_text = "Timestamp: " . $obj['timestamp']; + if (! empty($obj['faults'])) { $message_text .= "\n\nFaults:\n"; foreach ($obj['faults'] as $k => $faults) { $message_text .= "#" . $k . " " . $faults['string'] . "\n"; } } $data['notification[long_message]'] = $message_text; - $curl = curl_init(); + $curl = curl_init(); set_curl_proxy($curl); curl_setopt($curl, CURLOPT_URL, 'https://new.boxcar.io/api/notifications'); curl_setopt($curl, CURLOPT_SAFE_UPLOAD, true); @@ -104,6 +104,7 @@ class Boxcar extends Transport $code = curl_getinfo($curl, CURLINFO_HTTP_CODE); if ($code != 201) { var_dump("Boxcar returned error"); //FIXME: proper debugging + return false; } @@ -125,11 +126,11 @@ class Boxcar extends Transport 'name' => 'boxcar-options', 'descr' => 'Boxcar Options', 'type' => 'textarea', - ] + ], ], 'validation' => [ 'boxcar-token' => 'required', - ] + ], ]; } } diff --git a/LibreNMS/Alert/Transport/Canopsis.php b/LibreNMS/Alert/Transport/Canopsis.php index 3410c3b27f..052ec33cfe 100644 --- a/LibreNMS/Alert/Transport/Canopsis.php +++ b/LibreNMS/Alert/Transport/Canopsis.php @@ -1,36 +1,38 @@ config)) { + if (! empty($this->config)) { $opts['host'] = $this->config['canopsis-host']; $opts['port'] = $this->config['canopsis-port']; $opts['user'] = $this->config['canopsis-user']; $opts['pass'] = $this->config['canopsis-pass']; $opts['vhost'] = $this->config['canopsis-vhost']; } + return $this->contactCanopsis($obj, $opts); } public function contactCanopsis($obj, $opts) { // Configurations - $host = $opts["host"]; - $port = $opts["port"]; - $user = $opts["user"]; - $pass = $opts["pass"]; - $vhost = $opts["vhost"]; + $host = $opts["host"]; + $port = $opts["port"]; + $user = $opts["user"]; + $pass = $opts["pass"]; + $vhost = $opts["vhost"]; $exchange = "canopsis.events"; // Connection $conn = new \PhpAmqpLib\Connection\AMQPConnection($host, $port, $user, $pass, $vhost); - $ch = $conn->channel(); + $ch = $conn->channel(); // Declare exchange (if not exist) // exchange_declare($exchange, $type, $passive=false, $durable=false, $auto_delete=true, $internal=false, $nowait=false, $arguments=null, $ticket=null) @@ -50,7 +52,7 @@ class Canopsis extends Transport default: $state = 0; } - $msg_body = array( + $msg_body = [ "timestamp" => time(), "connector" => "librenms", "connector_name" => "LibreNMS1", @@ -60,9 +62,9 @@ class Canopsis extends Transport "resource" => $obj['name'], "state" => $state, "output" => $obj['msg'], - "display_name" => "librenms" - ); - $msg_raw = json_encode($msg_body); + "display_name" => "librenms", + ]; + $msg_raw = json_encode($msg_body); // Build routing key if ($msg_body['source_type'] == "resource") { @@ -72,12 +74,13 @@ class Canopsis extends Transport } // Publish Event - $msg = new \PhpAmqpLib\Message\AMQPMessage($msg_raw, array('content_type' => 'application/json', 'delivery_mode' => 2)); + $msg = new \PhpAmqpLib\Message\AMQPMessage($msg_raw, ['content_type' => 'application/json', 'delivery_mode' => 2]); $ch->basic_publish($msg, $exchange, $msg_rk); // Close connection $ch->close(); $conn->close(); + return true; } @@ -89,31 +92,31 @@ class Canopsis extends Transport 'title' => 'Hostname', 'name' => 'canopsis-host', 'descr' => 'Canopsis Hostname', - 'type' => 'text' + 'type' => 'text', ], [ 'title' => 'Port Number', 'name' => 'canopsis-port', 'descr' => 'Canopsis Port Number', - 'type' => 'text' + 'type' => 'text', ], [ 'title' => 'User', 'name' => 'canopsis-user', 'descr' => 'Canopsis User', - 'type' => 'text' + 'type' => 'text', ], [ 'title' => 'Password', 'name' => 'canopsis-pass', 'descr' => 'Canopsis Password', - 'type' => 'text' + 'type' => 'text', ], [ 'title' => 'Vhost', 'name' => 'canopsis-vhost', 'descr' => 'Canopsis Vhost', - 'type' => 'text' + 'type' => 'text', ], ], 'validation' => [ @@ -122,7 +125,7 @@ class Canopsis extends Transport 'canopsis-user' => 'required|string', 'canopsis-pass' => 'required|string', 'canopsis-vhost' => 'required|string', - ] + ], ]; } } diff --git a/LibreNMS/Alert/Transport/Ciscospark.php b/LibreNMS/Alert/Transport/Ciscospark.php index 791b10fc73..2aa3cb252b 100644 --- a/LibreNMS/Alert/Transport/Ciscospark.php +++ b/LibreNMS/Alert/Transport/Ciscospark.php @@ -9,10 +9,11 @@ * option) any later version. Please see LICENSE.txt at the top level of * the source code distribution for details. */ + namespace LibreNMS\Alert\Transport; -use LibreNMS\Enum\AlertState; use LibreNMS\Alert\Transport; +use LibreNMS\Enum\AlertState; class Ciscospark extends Transport { @@ -25,15 +26,16 @@ class Ciscospark extends Transport $room_id = $this->config['room-id']; $token = $this->config['api-token']; } + return $this->contactCiscospark($obj, $room_id, $token); } public function contactCiscospark($obj, $room_id, $token) { $text = null; - $data = array ( - 'roomId' => $room_id - ); + $data = [ + 'roomId' => $room_id, + ]; $akey = 'text'; if ($this->config['use-markdown'] === 'on') { @@ -55,23 +57,25 @@ class Ciscospark extends Transport } $data[$akey] = $text; - $curl = curl_init(); + $curl = curl_init(); set_curl_proxy($curl); curl_setopt($curl, CURLOPT_URL, 'https://api.ciscospark.com/v1/messages'); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); - curl_setopt($curl, CURLOPT_HTTPHEADER, array( + curl_setopt($curl, CURLOPT_HTTPHEADER, [ 'Content-type' => 'application/json', 'Expect:', - 'Authorization: Bearer ' . $token - )); + 'Authorization: Bearer ' . $token, + ]); curl_setopt($curl, CURLOPT_POSTFIELDS, $data); - $ret = curl_exec($curl); + $ret = curl_exec($curl); $code = curl_getinfo($curl, CURLINFO_HTTP_CODE); if ($code != 200) { - echo("Cisco Spark returned Error, retry later\r\n"); + echo "Cisco Spark returned Error, retry later\r\n"; + return false; } + return true; } @@ -97,12 +101,12 @@ class Ciscospark extends Transport 'descr' => 'Use Markdown when sending the alert', 'type' => 'checkbox', 'default' => false, - ] + ], ], 'validation' => [ 'api-token' => 'required|string', - 'room-id' => 'required|string' - ] + 'room-id' => 'required|string', + ], ]; } } diff --git a/LibreNMS/Alert/Transport/Clickatell.php b/LibreNMS/Alert/Transport/Clickatell.php index 3fb0156c55..8018f8edb0 100644 --- a/LibreNMS/Alert/Transport/Clickatell.php +++ b/LibreNMS/Alert/Transport/Clickatell.php @@ -21,10 +21,11 @@ * @package LibreNMS * @subpackage Alerts */ + namespace LibreNMS\Alert\Transport; -use LibreNMS\Enum\AlertState; use LibreNMS\Alert\Transport; +use LibreNMS\Enum\AlertState; class Clickatell extends Transport { @@ -32,6 +33,7 @@ class Clickatell extends Transport { $clickatell_opts['token'] = $this->config['clickatell-token']; $clickatell_opts['to'] = preg_split('/([,\r\n]+)/', $this->config['clickatell-numbers']); + return $this->contactClickatell($obj, $clickatell_opts); } @@ -44,11 +46,12 @@ class Clickatell extends Transport curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "GET"); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); - $ret = curl_exec($curl); + $ret = curl_exec($curl); $code = curl_getinfo($curl, CURLINFO_HTTP_CODE); if ($code > 200) { return var_dump($ret); } + return true; } @@ -67,12 +70,12 @@ class Clickatell extends Transport 'name' => 'clickatell-numbers', 'descr' => 'Enter mobile numbers, can be new line or comma separated', 'type' => 'textarea', - ] + ], ], 'validation' => [ 'clickatell-token' => 'required|string', 'clickatell-numbers' => 'required|string', - ] + ], ]; } } diff --git a/LibreNMS/Alert/Transport/Discord.php b/LibreNMS/Alert/Transport/Discord.php index 76a2535a6a..44f57bdc77 100644 --- a/LibreNMS/Alert/Transport/Discord.php +++ b/LibreNMS/Alert/Transport/Discord.php @@ -28,8 +28,8 @@ namespace LibreNMS\Alert\Transport; -use LibreNMS\Enum\AlertState; use LibreNMS\Alert\Transport; +use LibreNMS\Enum\AlertState; class Discord extends Transport { @@ -38,7 +38,7 @@ class Discord extends Transport 'severity' => 'Severity', 'hostname' => 'Hostname', 'name' => 'Rule Name', - 'rule' => 'Rule' + 'rule' => 'Rule', ]; public function deliverAlert($obj, $opts) @@ -53,16 +53,16 @@ class Discord extends Transport public function contactDiscord($obj, $discord_opts) { - $host = $discord_opts['url']; - $curl = curl_init(); - $discord_title = '#' . $obj['uid'] . ' ' . $obj['title']; - $discord_msg = strip_tags($obj['msg']); - $color = self::getColorForState($obj['state']); + $host = $discord_opts['url']; + $curl = curl_init(); + $discord_title = '#' . $obj['uid'] . ' ' . $obj['title']; + $discord_msg = strip_tags($obj['msg']); + $color = self::getColorForState($obj['state']); // Special handling for the elapsed text in the footer if the elapsed is not set. $footer_text = $obj['elapsed'] ? 'alert took ' . $obj['elapsed'] : ''; - $data = [ + $data = [ 'embeds' => [ [ 'title' => $discord_title, @@ -70,31 +70,33 @@ class Discord extends Transport 'description' => $discord_msg, 'fields' => $this->createDiscordFields($obj, $discord_opts), 'footer' => [ - 'text' => $footer_text - ] - ] - ] + 'text' => $footer_text, + ], + ], + ], ]; - if (!empty($discord_opts['options'])) { + if (! empty($discord_opts['options'])) { $data = array_merge($data, $discord_opts['options']); } $alert_message = json_encode($data); - curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); + curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: application/json']); set_curl_proxy($curl); curl_setopt($curl, CURLOPT_URL, $host); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, $alert_message); - $ret = curl_exec($curl); + $ret = curl_exec($curl); $code = curl_getinfo($curl, CURLINFO_HTTP_CODE); if ($code != 204) { var_dump("API '$host' returned Error"); //FIXME: propper debuging var_dump("Params: " . $alert_message); //FIXME: propper debuging var_dump("Return: " . $ret); //FIXME: propper debuging + return 'HTTP Status code ' . $code; } + return true; } @@ -104,7 +106,7 @@ class Discord extends Transport foreach (self::ALERT_FIELDS_TO_DISCORD_FIELDS as $objKey => $discordKey) { // Skip over keys that do not exist so Discord does not give us a 400. - if (!$obj[$objKey]) { + if (! $obj[$objKey]) { continue; } @@ -132,11 +134,11 @@ class Discord extends Transport 'name' => 'options', 'descr' => 'Enter the config options (format: option=value separated by new lines)', 'type' => 'textarea', - ] + ], ], 'validation' => [ 'url' => 'required|url', - ] + ], ]; } } diff --git a/LibreNMS/Alert/Transport/Dummy.php b/LibreNMS/Alert/Transport/Dummy.php index 8c1dc7866c..0a0623236a 100644 --- a/LibreNMS/Alert/Transport/Dummy.php +++ b/LibreNMS/Alert/Transport/Dummy.php @@ -21,16 +21,18 @@ * @package LibreNMS * @subpackage Alerts */ + namespace LibreNMS\Alert\Transport; -use LibreNMS\Enum\AlertState; use LibreNMS\Alert\Transport; +use LibreNMS\Enum\AlertState; class Dummy extends Transport { public function deliverAlert($obj, $opts) { var_dump($obj); + return true; } diff --git a/LibreNMS/Alert/Transport/Elasticsearch.php b/LibreNMS/Alert/Transport/Elasticsearch.php index e39a2038d5..5669b1d9e9 100644 --- a/LibreNMS/Alert/Transport/Elasticsearch.php +++ b/LibreNMS/Alert/Transport/Elasticsearch.php @@ -14,20 +14,21 @@ * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ + namespace LibreNMS\Alert\Transport; -use LibreNMS\Enum\AlertState; use LibreNMS\Alert\Transport; +use LibreNMS\Enum\AlertState; class Elasticsearch extends Transport { public function deliverAlert($obj, $opts) { - if (!empty($this->config)) { + if (! empty($this->config)) { $opts['es_host'] = $this->config['es-host']; $opts['es_port'] = $this->config['es-port']; $opts['es_index'] = $this->config['es-pattern']; - $opts['es_proxy'] = $this-> config['es-proxy']; + $opts['es_proxy'] = $this->config['es-proxy']; } return $this->contactElasticsearch($obj, $opts); @@ -35,14 +36,14 @@ class Elasticsearch extends Transport public function contactElasticsearch($obj, $opts) { - $es_host = '127.0.0.1'; - $es_port = 9200; - $index = strftime("librenms-%Y.%m.%d"); - $type = 'alert'; + $es_host = '127.0.0.1'; + $es_port = 9200; + $index = strftime("librenms-%Y.%m.%d"); + $type = 'alert'; $severity = $obj['severity']; - $device = device_by_id_cache($obj['device_id']); // for event logging + $device = device_by_id_cache($obj['device_id']); // for event logging - if (!empty($opts['es_host'])) { + if (! empty($opts['es_host'])) { if (preg_match("/[a-zA-Z]/", $opts['es_host'])) { $es_host = gethostbyname($opts['es_host']); if ($es_host === $opts['es_host']) { @@ -55,11 +56,11 @@ class Elasticsearch extends Transport } } - if (!empty($opts['es_port']) && preg_match("/^\d+$/", $opts['es_port'])) { + if (! empty($opts['es_port']) && preg_match("/^\d+$/", $opts['es_port'])) { $es_port = $opts['es_port']; } - if (!empty($opts['es_index'])) { + if (! empty($opts['es_index'])) { $index = strftime($opts['es_index']); } @@ -83,7 +84,7 @@ class Elasticsearch extends Transport break; } - $data = array( + $data = [ '@timestamp' => date('c'), "host" => gethostname(), "location" => $obj['location'], @@ -101,60 +102,60 @@ class Elasticsearch extends Transport "entity_id" => $obj['device_id'], "entity_name" => $obj['hostname'], "entity_descr" => $obj['sysDescr'], - ); + ]; - if (!empty($obj['faults'])) { + if (! empty($obj['faults'])) { foreach ($obj['faults'] as $k => $v) { - $curl = curl_init(); + $curl = curl_init(); $data['message'] = $v['string']; switch (true) { - case (array_key_exists('port_id', $v)): - $data['entity_type'] = 'port'; - $data['entity_tab'] = 'port'; - $data['entity_id'] = $v['port_id']; - $data['entity_name'] = $v['ifName']; + case array_key_exists('port_id', $v): + $data['entity_type'] = 'port'; + $data['entity_tab'] = 'port'; + $data['entity_id'] = $v['port_id']; + $data['entity_name'] = $v['ifName']; $data['entity_descr'] = $v['ifAlias']; break; - case (array_key_exists('sensor_id', $v)): - $data['entity_type'] = $v['sensor_class']; - $data['entity_tab'] = 'health'; - $data['entity_id'] = $v['sensor_id']; - $data['entity_name'] = $v['sensor_descr']; + case array_key_exists('sensor_id', $v): + $data['entity_type'] = $v['sensor_class']; + $data['entity_tab'] = 'health'; + $data['entity_id'] = $v['sensor_id']; + $data['entity_name'] = $v['sensor_descr']; $data['entity_descr'] = $v['sensor_type']; break; - case (array_key_exists('mempool_id', $v)): - $data['entity_type'] = 'mempool'; - $data['entity_tab'] = 'health'; - $data['entity_id'] = $v['mempool_id']; - $data['entity_name'] = $v['mempool_index']; + case array_key_exists('mempool_id', $v): + $data['entity_type'] = 'mempool'; + $data['entity_tab'] = 'health'; + $data['entity_id'] = $v['mempool_id']; + $data['entity_name'] = $v['mempool_index']; $data['entity_descr'] = $v['mempool_descr']; break; - case (array_key_exists('storage_id', $v)): - $data['entity_type'] = 'storage'; - $data['entity_tab'] = 'health'; - $data['entity_id'] = $v['storage_id']; - $data['entity_name'] = $v['storage_index']; + case array_key_exists('storage_id', $v): + $data['entity_type'] = 'storage'; + $data['entity_tab'] = 'health'; + $data['entity_id'] = $v['storage_id']; + $data['entity_name'] = $v['storage_index']; $data['entity_descr'] = $v['storage_descr']; break; - case (array_key_exists('processor_id', $v)): - $data['entity_type'] = 'processor'; - $data['entity_tab'] = 'health'; - $data['entity_id'] = $v['processor_id']; - $data['entity_name'] = $v['processor_type']; + case array_key_exists('processor_id', $v): + $data['entity_type'] = 'processor'; + $data['entity_tab'] = 'health'; + $data['entity_id'] = $v['processor_id']; + $data['entity_name'] = $v['processor_type']; $data['entity_descr'] = $v['processor_descr']; break; - case (array_key_exists('bgpPeer_id', $v)): - $data['entity_type'] = 'bgp'; - $data['entity_tab'] = 'routing'; - $data['entity_id'] = $v['bgpPeer_id']; - $data['entity_name'] = 'local: ' . $v['bgpPeerLocalAddr'] . ' - AS' . $obj['bgpLocalAs']; + case array_key_exists('bgpPeer_id', $v): + $data['entity_type'] = 'bgp'; + $data['entity_tab'] = 'routing'; + $data['entity_id'] = $v['bgpPeer_id']; + $data['entity_name'] = 'local: ' . $v['bgpPeerLocalAddr'] . ' - AS' . $obj['bgpLocalAs']; $data['entity_descr'] = 'remote: ' . $v['bgpPeerIdentifier'] . ' - AS' . $v['bgpPeerRemoteAs']; break; - case (array_key_exists('tunnel_id', $v)): - $data['entity_type'] = 'ipsec_tunnel'; - $data['entity_tab'] = 'routing'; - $data['entity_id'] = $v['tunnel_id']; - $data['entity_name'] = $v['tunnel_name']; + case array_key_exists('tunnel_id', $v): + $data['entity_type'] = 'ipsec_tunnel'; + $data['entity_tab'] = 'routing'; + $data['entity_id'] = $v['tunnel_id']; + $data['entity_name'] = $v['tunnel_name']; $data['entity_descr'] = 'local: ' . $v['local_addr'] . ':' . $v['local_port'] . ', remote: ' . $v['peer_addr'] . ':' . $v['peer_port']; break; default: @@ -162,7 +163,7 @@ class Elasticsearch extends Transport break; } $alert_message = json_encode($data); - curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); + curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: application/json']); if ($opts['es_proxy'] === true) { set_curl_proxy($curl); } @@ -171,16 +172,16 @@ class Elasticsearch extends Transport curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, $alert_message); - $ret = curl_exec($curl); + $ret = curl_exec($curl); $code = curl_getinfo($curl, CURLINFO_HTTP_CODE); if ($code != 200 && $code != 201) { return $host . ' returned HTTP Status code ' . $code . ' for ' . $alert_message; } } } else { - $curl = curl_init(); + $curl = curl_init(); $alert_message = json_encode($data); - curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); + curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: application/json']); if ($opts['es_proxy'] === true) { set_curl_proxy($curl); } @@ -189,12 +190,13 @@ class Elasticsearch extends Transport curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, $alert_message); - $ret = curl_exec($curl); + $ret = curl_exec($curl); $code = curl_getinfo($curl, CURLINFO_HTTP_CODE); if ($code != 200 && $code != 201) { return $host . ' returned HTTP Status code ' . $code . ' for ' . $alert_message; } } + return true; } @@ -225,14 +227,14 @@ class Elasticsearch extends Transport 'name' => 'es-proxy', 'descr' => 'Elasticsearch Proxy', 'type' => 'checkbox', - 'default' => false - ] + 'default' => false, + ], ], 'validation' => [ 'es-host' => 'required|string', 'es-port' => 'required|string', - 'es-pattern' => 'required|string' - ] + 'es-pattern' => 'required|string', + ], ]; } } diff --git a/LibreNMS/Alert/Transport/Gitlab.php b/LibreNMS/Alert/Transport/Gitlab.php index 35d302424a..c660930155 100644 --- a/LibreNMS/Alert/Transport/Gitlab.php +++ b/LibreNMS/Alert/Transport/Gitlab.php @@ -21,20 +21,22 @@ * @package LibreNMS * @subpackage Alerts */ + namespace LibreNMS\Alert\Transport; -use LibreNMS\Enum\AlertState; use LibreNMS\Alert\Transport; +use LibreNMS\Enum\AlertState; class Gitlab extends Transport { public function deliverAlert($obj, $opts) { - if (!empty($this->config)) { + if (! empty($this->config)) { $opts['project-id'] = $this->config['gitlab-id']; $opts['key'] = $this->config['gitlab-key']; $opts['host'] = $this->config['gitlab-host']; } + return $this->contactGitlab($obj, $opts); } @@ -44,24 +46,24 @@ class Gitlab extends Transport if ($obj['state'] != AlertState::CLEAR) { $device = device_by_id_cache($obj['device_id']); // for event logging - $project_id = $opts['project-id']; + $project_id = $opts['project-id']; $project_key = $opts['key']; - $details = "Librenms alert for: " . $obj['hostname']; + $details = "Librenms alert for: " . $obj['hostname']; $description = $obj['msg']; - $title = urlencode($details); - $desc = urlencode($description); - $url = $opts['host'] . "/api/v4/projects/$project_id/issues?title=$title&description=$desc"; - $curl = curl_init(); + $title = urlencode($details); + $desc = urlencode($description); + $url = $opts['host'] . "/api/v4/projects/$project_id/issues?title=$title&description=$desc"; + $curl = curl_init(); - $data = array("title" => $details, - "description" => $description - ); - $postdata = array("fields" => $data); + $data = ["title" => $details, + "description" => $description, + ]; + $postdata = ["fields" => $data]; $datastring = json_encode($postdata); set_curl_proxy($curl); - $headers = array('Accept: application/json', 'Content-Type: application/json', 'PRIVATE-TOKEN: '.$project_key); + $headers = ['Accept: application/json', 'Content-Type: application/json', 'PRIVATE-TOKEN: ' . $project_key]; curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); @@ -70,14 +72,16 @@ class Gitlab extends Transport curl_setopt($curl, CURLOPT_VERBOSE, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, $datastring); - $ret = curl_exec($curl); + $ret = curl_exec($curl); $code = curl_getinfo($curl, CURLINFO_HTTP_CODE); if ($code == 200) { $gitlabout = json_decode($ret, true); d_echo("Created Gitlab issue " . $gitlabout['key'] . " for " . $device); + return true; } else { d_echo("Gitlab connection error: " . serialize($ret)); + return false; } } @@ -104,13 +108,13 @@ class Gitlab extends Transport 'name' => 'gitlab-key', 'descr' => 'Personal Access Token', 'type' => 'text', - ] + ], ], 'validation' => [ 'gitlab-host' => 'required|string', 'gitlab-id' => 'required|string', - 'gitlab-key' => 'required|string' - ] + 'gitlab-key' => 'required|string', + ], ]; } } diff --git a/LibreNMS/Alert/Transport/Hipchat.php b/LibreNMS/Alert/Transport/Hipchat.php index 18e49bc4a8..f92e792d68 100644 --- a/LibreNMS/Alert/Transport/Hipchat.php +++ b/LibreNMS/Alert/Transport/Hipchat.php @@ -21,10 +21,11 @@ * @package LibreNMS * @subpackage Alerts */ + namespace LibreNMS\Alert\Transport; -use LibreNMS\Enum\AlertState; use LibreNMS\Alert\Transport; +use LibreNMS\Enum\AlertState; class Hipchat extends Transport { @@ -92,9 +93,9 @@ class Hipchat extends Transport curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, $data); - curl_setopt($curl, CURLOPT_HTTPHEADER, array( + curl_setopt($curl, CURLOPT_HTTPHEADER, [ 'Content-Type: application/x-www-form-urlencoded', - )); + ]); $ret = curl_exec($curl); $code = curl_getinfo($curl, CURLINFO_HTTP_CODE); @@ -102,6 +103,7 @@ class Hipchat extends Transport var_dump("API '$url' returned Error"); var_dump("Params: " . $message); var_dump("Return: " . $ret); + return 'HTTP Status code ' . $code; } @@ -140,7 +142,7 @@ class Hipchat extends Transport 'validation' => [ 'hipchat-url' => 'required|url', 'hipchat-room-id' => 'required|numeric', - ] + ], ]; } } diff --git a/LibreNMS/Alert/Transport/Hue.php b/LibreNMS/Alert/Transport/Hue.php index 1728dc7dc0..b1ebbecc6a 100644 --- a/LibreNMS/Alert/Transport/Hue.php +++ b/LibreNMS/Alert/Transport/Hue.php @@ -21,10 +21,11 @@ * @package LibreNMS * @subpackage Alerts */ + namespace LibreNMS\Alert\Transport; -use LibreNMS\Enum\AlertState; use LibreNMS\Alert\Transport; +use LibreNMS\Enum\AlertState; /** * The Hue API currently is fairly limited for alerts. @@ -35,7 +36,7 @@ class Hue extends Transport { public function deliverAlert($obj, $opts) { - if (!empty($this->config)) { + if (! empty($this->config)) { $opts['user'] = $this->config['hue-user']; $opts['bridge'] = $this->config['hue-host']; $opts['duration'] = $this->config['hue-duration']; @@ -51,16 +52,16 @@ class Hue extends Transport return true; } else { $device = device_by_id_cache($obj['device_id']); // for event logging - $hue_user = $opts['user']; - $url = $opts['bridge'] . "/api/$hue_user/groups/0/action"; - $curl = curl_init(); - $duration = $opts['duration']; - $data = array("alert" => $duration); + $hue_user = $opts['user']; + $url = $opts['bridge'] . "/api/$hue_user/groups/0/action"; + $curl = curl_init(); + $duration = $opts['duration']; + $data = ["alert" => $duration]; $datastring = json_encode($data); set_curl_proxy($curl); - $headers = array('Accept: application/json', 'Content-Type: application/json'); + $headers = ['Accept: application/json', 'Content-Type: application/json']; curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); @@ -69,13 +70,15 @@ class Hue extends Transport curl_setopt($curl, CURLOPT_VERBOSE, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, $datastring); - $ret = curl_exec($curl); + $ret = curl_exec($curl); $code = curl_getinfo($curl, CURLINFO_HTTP_CODE); if ($code == 200) { d_echo("Sent alert to Phillips Hue Bridge " . $opts['host'] . " for " . $device); + return true; } else { d_echo("Hue bridge connection error: " . serialize($ret)); + return false; } } @@ -86,33 +89,33 @@ class Hue extends Transport return [ 'config'=>[ [ - 'title'=> 'Host', - 'name' => 'hue-host', - 'descr' => 'Hue Host', - 'type' => 'text', + 'title'=> 'Host', + 'name' => 'hue-host', + 'descr' => 'Hue Host', + 'type' => 'text', ], [ - 'title'=> 'Hue User', - 'name' => 'hue-user', - 'descr' => 'Phillips Hue Host', - 'type' => 'text', + 'title'=> 'Hue User', + 'name' => 'hue-user', + 'descr' => 'Phillips Hue Host', + 'type' => 'text', ], [ - 'title'=> 'Duration', - 'name' => 'hue-duration', - 'descr' => 'Phillips Hue Duration', - 'type' => 'select', - 'options' => [ - '1 Second' => 'select', - '15 Seconds' => 'lselect' - ] - ] + 'title'=> 'Duration', + 'name' => 'hue-duration', + 'descr' => 'Phillips Hue Duration', + 'type' => 'select', + 'options' => [ + '1 Second' => 'select', + '15 Seconds' => 'lselect', + ], + ], ], 'validation' => [ 'hue-host' => 'required|string', 'hue-user' => 'required|string', - 'hue-duration' => 'required|string' - ] + 'hue-duration' => 'required|string', + ], ]; } } diff --git a/LibreNMS/Alert/Transport/Irc.php b/LibreNMS/Alert/Transport/Irc.php index 5d58881f62..7a47904b86 100644 --- a/LibreNMS/Alert/Transport/Irc.php +++ b/LibreNMS/Alert/Transport/Irc.php @@ -21,11 +21,12 @@ * @package LibreNMS * @subpackage Alerts */ + namespace LibreNMS\Alert\Transport; -use LibreNMS\Enum\AlertState; use LibreNMS\Alert\Transport; use LibreNMS\Config; +use LibreNMS\Enum\AlertState; class Irc extends Transport { @@ -61,11 +62,11 @@ class Irc extends Transport 'descr' => 'Enable IRC alerts', 'type' => 'checkbox', 'default' => true, - ] + ], ], 'validation' => [ - 'irc' => 'required' - ] + 'irc' => 'required', + ], ]; } } diff --git a/LibreNMS/Alert/Transport/Jira.php b/LibreNMS/Alert/Transport/Jira.php index 8737cf6832..83a61c4f5a 100644 --- a/LibreNMS/Alert/Transport/Jira.php +++ b/LibreNMS/Alert/Transport/Jira.php @@ -21,22 +21,24 @@ * @package LibreNMS * @subpackage Alerts */ + namespace LibreNMS\Alert\Transport; -use LibreNMS\Enum\AlertState; use LibreNMS\Alert\Transport; +use LibreNMS\Enum\AlertState; class Jira extends Transport { public function deliverAlert($obj, $opts) { - if (!empty($this->config)) { + if (! empty($this->config)) { $opts['username'] = $this->config['jira-username']; $opts['password'] = $this->config['jira-password']; $opts['prjkey'] = $this->config['jira-key']; $opts['issuetype'] = $this->config['jira-type']; $opts['url'] = $this->config['jira-url']; } + return $this->contactJira($obj, $opts); } @@ -49,25 +51,25 @@ class Jira extends Transport $device = device_by_id_cache($obj['device_id']); // for event logging - $username = $opts['username']; - $password = $opts['password']; - $prjkey = $opts['prjkey']; - $issuetype = $opts['issuetype']; - $details = "Librenms alert for: " . $obj['hostname']; + $username = $opts['username']; + $password = $opts['password']; + $prjkey = $opts['prjkey']; + $issuetype = $opts['issuetype']; + $details = "Librenms alert for: " . $obj['hostname']; $description = $obj['msg']; - $url = $opts['url'] . '/rest/api/latest/issue'; - $curl = curl_init(); + $url = $opts['url'] . '/rest/api/latest/issue'; + $curl = curl_init(); - $data = array("project" => array("key" => $prjkey), - "summary" => $details, - "description" => $description, - "issuetype" => array("name" => $issuetype)); - $postdata = array("fields" => $data); + $data = ["project" => ["key" => $prjkey], + "summary" => $details, + "description" => $description, + "issuetype" => ["name" => $issuetype], ]; + $postdata = ["fields" => $data]; $datastring = json_encode($postdata); set_curl_proxy($curl); - $headers = array('Accept: application/json', 'Content-Type: application/json'); + $headers = ['Accept: application/json', 'Content-Type: application/json']; curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); @@ -77,18 +79,20 @@ class Jira extends Transport curl_setopt($curl, CURLOPT_VERBOSE, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, $datastring); - $ret = curl_exec($curl); + $ret = curl_exec($curl); $code = curl_getinfo($curl, CURLINFO_HTTP_CODE); if ($code == 200) { $jiraout = json_decode($ret, true); d_echo("Created jira issue " . $jiraout['key'] . " for " . $device); + return true; } else { d_echo("Jira connection error: " . serialize($ret)); + return false; } } - + public static function configTemplate() { return [ @@ -97,31 +101,31 @@ class Jira extends Transport 'title' => 'URL', 'name' => 'jira-url', 'descr' => 'Jira URL', - 'type' => 'text' + 'type' => 'text', ], [ 'title' => 'Project Key', 'name' => 'jira-key', 'descr' => 'Jira Project Key', - 'type' => 'text' + 'type' => 'text', ], [ 'title' => 'Issue Type', 'name' => 'jira-type', 'descr' => 'Jira Issue Type', - 'type' => 'text' + 'type' => 'text', ], [ 'title' => 'Jira Username', 'name' => 'jira-username', 'descr' => 'Jira Username', - 'type' => 'text' + 'type' => 'text', ], [ 'title' => 'Jira Password', 'name' => 'jira-password', 'descr' => 'Jira Password', - 'type' => 'text' + 'type' => 'text', ], ], 'validation' => [ @@ -130,7 +134,7 @@ class Jira extends Transport 'jira-type' => 'required|string', 'jira-username' => 'required|string', 'jira-password' => 'required|string', - ] + ], ]; } } diff --git a/LibreNMS/Alert/Transport/Kayako.php b/LibreNMS/Alert/Transport/Kayako.php index f3c4bfc10d..358e51c474 100644 --- a/LibreNMS/Alert/Transport/Kayako.php +++ b/LibreNMS/Alert/Transport/Kayako.php @@ -9,39 +9,41 @@ * option) any later version. Please see LICENSE.txt at the top level of * the source code distribution for details. */ + namespace LibreNMS\Alert\Transport; -use LibreNMS\Enum\AlertState; use LibreNMS\Alert\Transport; use LibreNMS\Config; +use LibreNMS\Enum\AlertState; class Kayako extends Transport { public function deliverAlert($host, $kayako) { - if (!empty($this->config)) { + if (! empty($this->config)) { $kayako['url'] = $this->config['kayako-url']; $kayako['key'] = $this->config['kayako-key']; $kayako['secret'] = $this->config['kayako-secret']; $kayako['department'] = $this->config['kayako-department']; } + return $this->contactKayako($host, $kayako); } public function contactKayako($host, $kayako) { - $url = $kayako['url']."/Tickets/Ticket"; + $url = $kayako['url'] . "/Tickets/Ticket"; $key = $kayako['key']; $secret = $kayako['secret']; $user = Config::get('email_from'); $department = $kayako['department']; - $ticket_type= 1; + $ticket_type = 1; $ticket_status = 1; $ticket_prio = 1; $salt = mt_rand(); $signature = base64_encode(hash_hmac('sha256', $salt, $secret, true)); - $protocol = array( + $protocol = [ 'subject' => ($host['name'] ? $host['name'] . ' on ' . $host['hostname'] : $host['title']), 'fullname' => 'LibreNMS Alert', 'email' => $user, @@ -54,11 +56,11 @@ class Kayako extends Transport 'ignoreautoresponder' => true, 'apikey' => $key, 'salt' => $salt, - 'signature' => $signature - ); + 'signature' => $signature, + ]; $post_data = http_build_query($protocol, '', '&'); - $curl = curl_init(); + $curl = curl_init(); curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); @@ -68,6 +70,7 @@ class Kayako extends Transport $code = curl_getinfo($curl, CURLINFO_HTTP_CODE); if ($code != 200) { var_dump("Kayako returned Error, retry later"); + return false; } @@ -82,33 +85,33 @@ class Kayako extends Transport 'title' => 'Kayako URL', 'name' => 'kayako-url', 'descr' => 'ServiceDesk API URL', - 'type' => 'text' + 'type' => 'text', ], [ 'title' => 'Kayako API Key', 'name' => 'kayako-key', 'descr' => 'ServiceDesk API Key', - 'type' => 'text' + 'type' => 'text', ], [ 'title' => 'Kayako API Secret', 'name' => 'kayako-secret', 'descr' => 'ServiceDesk API Secret Key', - 'type' => 'text' + 'type' => 'text', ], [ 'title' => 'Kayako Department', 'name' => 'kayako-department', 'descr' => 'Department to post a ticket', - 'type' => 'text' - ] + 'type' => 'text', + ], ], 'validation' => [ 'kayako-url' => 'required|url', 'kayako-key' => 'required|string', 'kayako-secret' => 'required|string', - 'kayako-department' => 'required|string' - ] + 'kayako-department' => 'required|string', + ], ]; } } diff --git a/LibreNMS/Alert/Transport/Linenotify.php b/LibreNMS/Alert/Transport/Linenotify.php index e551876304..e3108a615a 100644 --- a/LibreNMS/Alert/Transport/Linenotify.php +++ b/LibreNMS/Alert/Transport/Linenotify.php @@ -4,16 +4,18 @@ * @package LibreNMS * @subpackage Alerts */ + namespace LibreNMS\Alert\Transport; -use LibreNMS\Enum\AlertState; use LibreNMS\Alert\Transport; +use LibreNMS\Enum\AlertState; class Linenotify extends Transport { public function deliverAlert($obj, $opts) { $opts['line-notify-access-token'] = $this->config['line-notify-access-token']; + return $this->contactLineNotify($obj, $opts); } @@ -36,6 +38,7 @@ class Linenotify extends Transport if ($code != 200) { return 'HTTP Status code ' . $code; } + return true; } @@ -47,12 +50,12 @@ class Linenotify extends Transport 'title' => 'Token', 'name' => 'line-notify-access-token', 'descr' => 'LINE Notify Token', - 'type' => 'text' - ] + 'type' => 'text', + ], ], 'validation' => [ 'line-notify-access-token' => 'required|string', - ] + ], ]; } } diff --git a/LibreNMS/Alert/Transport/Mail.php b/LibreNMS/Alert/Transport/Mail.php index d9a5df1b9b..84c2897ddb 100644 --- a/LibreNMS/Alert/Transport/Mail.php +++ b/LibreNMS/Alert/Transport/Mail.php @@ -21,11 +21,12 @@ * @package LibreNMS * @subpackage Alerts */ + namespace LibreNMS\Alert\Transport; -use LibreNMS\Enum\AlertState; use LibreNMS\Alert\Transport; use LibreNMS\Config; +use LibreNMS\Enum\AlertState; class Mail extends Transport { @@ -51,11 +52,11 @@ class Mail extends Transport 'name' => 'email', 'descr' => 'Email address of contact', 'type' => 'text', - ] + ], ], 'validation' => [ - 'email' => 'required|email' - ] + 'email' => 'required|email', + ], ]; } } diff --git a/LibreNMS/Alert/Transport/Matrix.php b/LibreNMS/Alert/Transport/Matrix.php index 2fea77c0a6..15a636077b 100644 --- a/LibreNMS/Alert/Transport/Matrix.php +++ b/LibreNMS/Alert/Transport/Matrix.php @@ -24,18 +24,19 @@ namespace LibreNMS\Alert\Transport; +use GuzzleHttp\Client; use LibreNMS\Alert\Transport; use LibreNMS\Enum\AlertState; -use GuzzleHttp\Client; class Matrix extends Transport { public function deliverAlert($obj, $opts) { - $server = $this->config['matrix-server']; - $room = $this->config['matrix-room']; + $server = $this->config['matrix-server']; + $room = $this->config['matrix-room']; $authtoken = $this->config['matrix-authtoken']; - $message = $this->config['matrix-message']; + $message = $this->config['matrix-message']; + return $this->contactMatrix($obj, $server, $room, $authtoken, $message); } @@ -46,7 +47,7 @@ class Matrix extends Transport $txnid = rand(1111, 9999) . time(); $server = preg_replace('/\/$/', '', $server); - $host = $server."/_matrix/client/r0/rooms/".urlencode($room)."/send/m.room.message/".$txnid; + $host = $server . "/_matrix/client/r0/rooms/" . urlencode($room) . "/send/m.room.message/" . $txnid; $request_heads['Authorization'] = "Bearer $authtoken"; $request_heads['Content-Type'] = "application/json"; @@ -56,7 +57,7 @@ class Matrix extends Transport $message = str_replace("{{ $" . $p_key . ' }}', $p_val, $message); } - $body = array('body'=>$message, 'msgtype'=>'m.text'); + $body = ['body'=>$message, 'msgtype'=>'m.text']; $client = new \GuzzleHttp\Client(); $request_opts['proxy'] = get_guzzle_proxy(); @@ -70,9 +71,11 @@ class Matrix extends Transport var_dump("Params:"); var_dump("Response headers:"); var_dump($res->getHeaders()); - var_dump("Return: ".$res->getReasonPhrase()); - return 'HTTP Status code '.$code; + var_dump("Return: " . $res->getReasonPhrase()); + + return 'HTTP Status code ' . $code; } + return true; } @@ -103,13 +106,13 @@ class Matrix extends Transport 'name' => 'matrix-message', 'descr' => 'Enter the message', 'type' => 'textarea', - ] + ], ], 'validation' => [ 'matrix-server' => 'required', 'matrix-room' => 'required', - 'matrix-authtoken' => 'required' - ] + 'matrix-authtoken' => 'required', + ], ]; } } diff --git a/LibreNMS/Alert/Transport/Mattermost.php b/LibreNMS/Alert/Transport/Mattermost.php index 11b65272c3..7f27ec37b5 100755 --- a/LibreNMS/Alert/Transport/Mattermost.php +++ b/LibreNMS/Alert/Transport/Mattermost.php @@ -21,10 +21,11 @@ * @package LibreNMS * @subpackage Alerts */ + namespace LibreNMS\Alert\Transport; -use LibreNMS\Enum\AlertState; use LibreNMS\Alert\Transport; +use LibreNMS\Enum\AlertState; class Mattermost extends Transport { @@ -67,7 +68,7 @@ class Mattermost extends Transport set_curl_proxy($curl); - $httpheaders = array('Accept: application/json', 'Content-Type: application/json'); + $httpheaders = ['Accept: application/json', 'Content-Type: application/json']; $alert_payload = json_encode($data); curl_setopt($curl, CURLOPT_HTTPHEADER, $httpheaders); @@ -80,9 +81,11 @@ class Mattermost extends Transport $code = curl_getinfo($curl, CURLINFO_HTTP_CODE); if ($code != 200) { d_echo("Mattermost Connection Error: " . $ret); + return 'HTTP Status code ' . $code; } else { d_echo("Mattermost message sent for " . $device); + return true; } } diff --git a/LibreNMS/Alert/Transport/Msteams.php b/LibreNMS/Alert/Transport/Msteams.php index 0193d574cd..9405ba7f8c 100644 --- a/LibreNMS/Alert/Transport/Msteams.php +++ b/LibreNMS/Alert/Transport/Msteams.php @@ -9,16 +9,17 @@ * option) any later version. Please see LICENSE.txt at the top level of * the source code distribution for details. */ + namespace LibreNMS\Alert\Transport; -use LibreNMS\Enum\AlertState; use LibreNMS\Alert\Transport; +use LibreNMS\Enum\AlertState; class Msteams extends Transport { public function deliverAlert($obj, $opts) { - if (!empty($this->config)) { + if (! empty($this->config)) { $opts['url'] = $this->config['msteam-url']; } @@ -27,30 +28,32 @@ class Msteams extends Transport public function contactMsteams($obj, $opts) { - $url = $opts['url']; - $data = array( + $url = $opts['url']; + $data = [ 'title' => $obj['title'], 'themeColor' => self::getColorForState($obj['state']), - 'text' => strip_tags($obj['msg'], '