PSR-2 Final cleanup (#4247)

refactor: Final PSR2 cleanup
This commit is contained in:
Tony Murray
2016-08-28 17:32:55 -05:00
committed by Neil Lathwood
parent aadd627863
commit abc6a5b799
41 changed files with 1339 additions and 1397 deletions

View File

@@ -25,7 +25,6 @@
namespace LibreNMS;
/**
* Class ClassLoader
* @package LibreNMS
@@ -63,7 +62,7 @@ class ClassLoader
$file = str_replace(array('\\', '_'), DIRECTORY_SEPARATOR, $name) . '.php';
$fullFile = realpath(__DIR__ . '/..') . DIRECTORY_SEPARATOR . $file;
if($vdebug) {
if ($vdebug) {
echo __CLASS__ . " [[ $name > $fullFile ]]\n";
}
@@ -84,7 +83,7 @@ class ClassLoader
if (isset($this->classMap[$name])) {
$file = $this->classMap[$name];
if($vdebug) {
if ($vdebug) {
echo __CLASS__ . " (( $name > $file ))\n";
}
@@ -99,7 +98,7 @@ class ClassLoader
foreach (array_keys($this->dirMap[$namespace]) as $dir) {
$file = $dir . DIRECTORY_SEPARATOR . $class . '.php';
if($vdebug) {
if ($vdebug) {
echo __CLASS__ . " (( $name > $file ))\n";
}
@@ -180,7 +179,8 @@ class ClassLoader
* @param string $class the full class name to split
* @return array of the split class [namespace, classname]
*/
private function splitNamespace($class) {
private function splitNamespace($class)
{
$parts = explode('\\', $class);
$last = array_pop($parts);
return array(implode('\\', $parts), $last);

View File

@@ -25,7 +25,8 @@
namespace LibreNMS;
class Component {
class Component
{
/*
* These fields are used in the component table. They are returned in the array
* so that they can be modified but they can not be set as user attributes. We
@@ -40,12 +41,12 @@ class Component {
'error' => '',
);
public function getComponentType($TYPE=null) {
public function getComponentType($TYPE = null)
{
if (is_null($TYPE)) {
$SQL = "SELECT DISTINCT `type` as `name` FROM `component` ORDER BY `name`";
$row = dbFetchRow($SQL, array());
}
else {
} else {
$SQL = "SELECT DISTINCT `type` as `name` FROM `component` WHERE `type` = ? ORDER BY `name`";
$row = dbFetchRow($SQL, array($TYPE));
}
@@ -53,14 +54,14 @@ class Component {
if (!isset($row)) {
// We didn't find any component types
return false;
}
else {
} else {
// We found some..
return $row;
}
}
public function getComponents($device_id=null,$options=array()) {
public function getComponents($device_id = null, $options = array())
{
// Define our results array, this will be set even if no rows are returned.
$RESULT = array();
$PARAM = array();
@@ -87,25 +88,24 @@ class Component {
$SQL .= " ( ";
foreach ($options['filter'] as $field => $array) {
// Only add valid fields to the query
if (in_array($field,$validFields)) {
if (in_array($field, $validFields)) {
if ($array[0] == 'LIKE') {
$SQL .= "`".$field."` LIKE ? AND ";
$array[1] = "%".$array[1]."%";
}
else {
} else {
// Equals operator is the default
$SQL .= "`".$field."` = ? AND ";
}
array_push($PARAM,$array[1]);
array_push($PARAM, $array[1]);
}
}
// Strip the last " AND " before closing the bracket.
$SQL = substr($SQL,0,-5)." )";
$SQL = substr($SQL, 0, -5)." )";
}
if ($COUNT == 0) {
// Strip the " WHERE " that we didn't use.
$SQL = substr($SQL,0,-7);
$SQL = substr($SQL, 0, -7);
}
// sort column direction
@@ -149,7 +149,7 @@ class Component {
foreach ($RESULT as $k => $v) {
// k1 = component id, v1 = component array
foreach ($v as $k1 => $v1) {
if ( ($COUNT >= $options['limit'][0]) && ($COUNT < $options['limit'][0]+$options['limit'][1])) {
if (($COUNT >= $options['limit'][0]) && ($COUNT < $options['limit'][0]+$options['limit'][1])) {
$TEMP[$k][$k1] = $v1;
}
// We are counting components.
@@ -162,7 +162,8 @@ class Component {
return $RESULT;
}
public function getComponentStatus($device=null) {
public function getComponentStatus($device = null)
{
$sql_query = "SELECT status, count(status) as count FROM component WHERE";
$sql_param = array();
$add = 0;
@@ -191,12 +192,13 @@ class Component {
$count[$v['status']] = $v['count'];
}
d_echo("Component Count by Status: ".print_r($count,TRUE)."\n");
d_echo("Component Count by Status: ".print_r($count, true)."\n");
return $count;
}
public function getComponentStatusLog($component=null,$start=null,$end=null) {
if ( ($component == null) || ($start == null) || ($end == null) ) {
public function getComponentStatusLog($component = null, $start = null, $end = null)
{
if (($component == null) || ($start == null) || ($end == null)) {
// Error...
d_echo("Required arguments are missing. Component: ".$component.", Start: ".$start.", End: ".$end."\n");
return false;
@@ -211,8 +213,7 @@ class Component {
$result = dbFetchRow($sql_query, $sql_param);
if ($result == false) {
$return['initial'] = false;
}
else {
} else {
$return['initial'] = $result['status'];
}
@@ -221,11 +222,12 @@ class Component {
$sql_param = array($component,$start,$end);
$return['data'] = dbFetchRows($sql_query, $sql_param);
d_echo("Status Log Data: ".print_r($return,TRUE)."\n");
d_echo("Status Log Data: ".print_r($return, true)."\n");
return $return;
}
public function createComponent ($device_id,$TYPE) {
public function createComponent($device_id, $TYPE)
{
// Prepare our default values to be inserted.
$DATA = $this->reserved;
@@ -237,16 +239,17 @@ class Component {
$id = dbInsert($DATA, 'component');
// Add a default status log entry - we always start ok.
$this->createStatusLogEntry($id,0,'Component Created');
$this->createStatusLogEntry($id, 0, 'Component Created');
// Create a default component array based on what was inserted.
$ARRAY = array();
$ARRAY[$id] = $DATA;
unset ($ARRAY[$id]['device_id']); // This doesn't belong here.
unset($ARRAY[$id]['device_id']); // This doesn't belong here.
return $ARRAY;
}
public function createStatusLogEntry($component,$status,$message) {
public function createStatusLogEntry($component, $status, $message)
{
// Add an entry to the statuslog table for a particular component.
$DATA = array(
'component' => $component,
@@ -257,18 +260,19 @@ class Component {
return dbInsert($DATA, 'component_statuslog');
}
public function deleteComponent ($id) {
public function deleteComponent($id)
{
// Delete a component from the database.
return dbDelete('component', "`id` = ?",array($id));
return dbDelete('component', "`id` = ?", array($id));
}
public function setComponentPrefs ($device_id,$ARRAY) {
public function setComponentPrefs($device_id, $ARRAY)
{
// Compare the arrays. Update/Insert where necessary.
$OLD = $this->getComponents($device_id);
// Loop over each component.
foreach ($ARRAY as $COMPONENT => $AVP) {
// Make sure the component already exists.
if (!isset($OLD[$device_id][$COMPONENT])) {
// Error. Component doesn't exist in the database.
@@ -281,7 +285,7 @@ class Component {
// If the Status has changed we need to add a log entry
if ($AVP['status'] != $OLD[$device_id][$COMPONENT]['status']) {
d_echo("Status Changed - Old: ".$OLD[$device_id][$COMPONENT]['status'].", New: ".$AVP['status']."\n");
$this->createStatusLogEntry($COMPONENT,$AVP['status'],$AVP['error']);
$this->createStatusLogEntry($COMPONENT, $AVP['status'], $AVP['error']);
}
// Process our reserved components first.
@@ -289,7 +293,6 @@ class Component {
foreach ($this->reserved as $k => $v) {
// does the reserved field exist, if not skip.
if (isset($AVP[$k])) {
// Has the value changed?
if ($AVP[$k] != $OLD[$device_id][$COMPONENT][$k]) {
// The value has been modified, add it to our update array.
@@ -311,8 +314,8 @@ class Component {
foreach ($UPDATE as $k => $v) {
$MSG .= $k." => ".$v.",";
}
$MSG = substr($MSG,0,-1);
log_event($MSG,$device_id,'component',$COMPONENT);
$MSG = substr($MSG, 0, -1);
log_event($MSG, $device_id, 'component', $COMPONENT);
}
// Process our AVP Adds and Updates
@@ -325,32 +328,28 @@ class Component {
dbInsert($DATA, 'component_prefs');
// Log the addition to the Eventlog.
log_event ("Component: " . $AVP[$COMPONENT]['type'] . "(" . $COMPONENT . "). Attribute: " . $ATTR . ", was added with value: " . $VALUE, $device_id, 'component', $COMPONENT);
}
elseif ($OLD[$device_id][$COMPONENT][$ATTR] != $VALUE) {
log_event("Component: " . $AVP[$COMPONENT]['type'] . "(" . $COMPONENT . "). Attribute: " . $ATTR . ", was added with value: " . $VALUE, $device_id, 'component', $COMPONENT);
} elseif ($OLD[$device_id][$COMPONENT][$ATTR] != $VALUE) {
// Attribute exists but the value is different, need to update
$DATA = array('value'=>$VALUE);
dbUpdate($DATA, 'component_prefs', '`component` = ? AND `attribute` = ?', array($COMPONENT, $ATTR));
// Add the modification to the Eventlog.
log_event("Component: ".$AVP[$COMPONENT]['type']."(".$COMPONENT."). Attribute: ".$ATTR.", was modified from: ".$OLD[$COMPONENT][$ATTR].", to: ".$VALUE,$device_id,'component',$COMPONENT);
log_event("Component: ".$AVP[$COMPONENT]['type']."(".$COMPONENT."). Attribute: ".$ATTR.", was modified from: ".$OLD[$COMPONENT][$ATTR].", to: ".$VALUE, $device_id, 'component', $COMPONENT);
}
} // End Foreach AVP
// Process our Deletes.
$DELETE = array_diff_key($OLD[$device_id][$COMPONENT], $AVP);
foreach ($DELETE as $KEY => $VALUE) {
// As the Attribute has been removed from the array, we should remove it from the database.
dbDelete('component_prefs', "`component` = ? AND `attribute` = ?",array($COMPONENT,$KEY));
dbDelete('component_prefs', "`component` = ? AND `attribute` = ?", array($COMPONENT,$KEY));
// Log the addition to the Eventlog.
log_event ("Component: " . $AVP[$COMPONENT]['type'] . "(" . $COMPONENT . "). Attribute: " . $KEY . ", was deleted.", $COMPONENT);
log_event("Component: " . $AVP[$COMPONENT]['type'] . "(" . $COMPONENT . "). Attribute: " . $KEY . ", was deleted.", $COMPONENT);
}
}
return true;
}
}

View File

@@ -25,7 +25,6 @@
namespace LibreNMS\Exceptions;
class FileExistsException extends \Exception
{

View File

@@ -25,7 +25,6 @@
namespace LibreNMS\Exceptions;
class HostExistsException extends \Exception
{

View File

@@ -25,7 +25,6 @@
namespace LibreNMS\Exceptions;
class HostIpExistsException extends HostExistsException
{

View File

@@ -25,7 +25,6 @@
namespace LibreNMS\Exceptions;
class HostUnreachableException extends \Exception
{
protected $reasons = array();

View File

@@ -25,7 +25,6 @@
namespace LibreNMS\Exceptions;
class HostUnreachablePingException extends HostUnreachableException
{

View File

@@ -25,7 +25,6 @@
namespace LibreNMS\Exceptions;
class HostUnreachableSnmpException extends HostUnreachableException
{

View File

@@ -25,7 +25,6 @@
namespace LibreNMS\Exceptions;
class InvalidPortAssocModeException extends \Exception
{

View File

@@ -25,7 +25,6 @@
namespace LibreNMS\Exceptions;
class SnmpVersionUnsupportedException extends \Exception
{

View File

@@ -20,7 +20,8 @@
namespace LibreNMS;
class IRCBot {
class IRCBot
{
private $last_activity = '';
@@ -62,7 +63,8 @@ class IRCBot {
private $tick = 62500;
public function __construct() {
public function __construct()
{
global $config, $database_link;
$this->log('Setting up IRC-Bot..');
if (is_resource($database_link)) {
@@ -77,8 +79,7 @@ class IRCBot {
if ($this->config['irc_port'][0] == '+') {
$this->ssl = true;
$this->port = substr($this->config['irc_port'], 1);
}
else {
} else {
$this->port = $this->config['irc_port'];
}
@@ -89,11 +90,9 @@ class IRCBot {
if ($this->config['irc_chan']) {
if (is_array($this->config['irc_chan'])) {
$this->chan = $this->config['irc_chan'];
}
else if (strstr($this->config['irc_chan'], ',')) {
} elseif (strstr($this->config['irc_chan'], ',')) {
$this->chan = explode(',', $this->config['irc_chan']);
}
else {
} else {
$this->chan = array($this->config['irc_chan']);
}
}
@@ -101,8 +100,7 @@ class IRCBot {
if ($this->config['irc_alert_chan']) {
if (strstr($this->config['irc_alert_chan'], ',')) {
$this->config['irc_alert_chan'] = explode(',', $this->config['irc_alert_chan']);
}
else {
} else {
$this->config['irc_alert_chan'] = array($this->config['irc_alert_chan']);
}
}
@@ -111,14 +109,14 @@ class IRCBot {
$this->pass = $this->config['irc_pass'];
}
$this->load_external();
$this->loadExternal();
$this->log('Starting IRC-Bot..');
$this->init();
}//end __construct()
private function load_external() {
private function loadExternal()
{
if (!$this->config['irc_external']) {
return true;
}
@@ -135,13 +133,13 @@ class IRCBot {
}
return $this->log('Cached '.sizeof($this->external).' commands.');
}//end load_external()
private function init() {
private function init()
{
if ($this->config['irc_alert']) {
$this->connect_alert();
$this->connectAlert();
}
$this->last_activity = time();
@@ -182,11 +180,11 @@ class IRCBot {
}
return $this->init();
}//end init()
private function connect_alert() {
private function connectAlert()
{
$f = $this->config['install_dir'].'/.ircbot.alert';
if (( file_exists($f) && filetype($f) != 'fifo' && !unlink($f) ) || ( !file_exists($f) && !shell_exec("mkfifo $f && echo 1") )) {
$this->log('Error - Cannot create Alert-File');
@@ -201,11 +199,11 @@ class IRCBot {
$this->log('Error - Cannot open Alert-File');
return false;
}//end connect_alert()
private function read($buff) {
private function read($buff)
{
$r = fread($this->socket[$buff], 64);
$this->buff[$buff] .= $r;
$r = strlen($r);
@@ -224,21 +222,26 @@ class IRCBot {
}
return false;
}//end read()
private function alertData() {
private function alertData()
{
if (($alert = $this->read('alert')) !== false) {
$alert = json_decode($alert, true);
if (!is_array($alert)) {
return false;
}
switch ($alert['state']):
case 3: $severity_extended = '+'; break;
case 4: $severity_extended = '-'; break;
default: $severity_extended = '';
switch ($alert['state']) :
case 3:
$severity_extended = '+';
break;
case 4:
$severity_extended = '-';
break;
default:
$severity_extended = '';
endswitch;
$severity = str_replace(array('warning', 'critical'), array(chr(3).'8Warning', chr(3).'4Critical'), $alert['severity']).$severity_extended.chr(3).' ';
@@ -248,18 +251,17 @@ class IRCBot {
if ($this->config['irc_alert_chan']) {
foreach ($this->config['irc_alert_chan'] as $chan) {
$this->irc_raw('PRIVMSG '.$chan.' :'.$severity.trim($alert['title']).' - Rule: '.trim($alert['name'] ? $alert['name'] : $alert['rule']).(sizeof($alert['faults']) > 0 ? ' - Faults:' : ''));
$this->ircRaw('PRIVMSG '.$chan.' :'.$severity.trim($alert['title']).' - Rule: '.trim($alert['name'] ? $alert['name'] : $alert['rule']).(sizeof($alert['faults']) > 0 ? ' - Faults:' : ''));
foreach ($alert['faults'] as $k => $v) {
$this->irc_raw('PRIVMSG '.$chan.' :#'.$k.' '.$v['string']);
$this->ircRaw('PRIVMSG '.$chan.' :#'.$k.' '.$v['string']);
}
}
}
else {
} else {
foreach ($this->authd as $nick => $data) {
if ($data['expire'] >= time()) {
$this->irc_raw('PRIVMSG '.$nick.' :'.$severity.trim($alert['title']).' - Rule: '.trim($alert['name'] ? $alert['name'] : $alert['rule']).(sizeof($alert['faults']) > 0 ? ' - Faults'.(sizeof($alert['faults']) > 3 ? ' (showing first 3 out of '.sizeof($alert['faults']).' )' : '' ).':' : ''));
$this->ircRaw('PRIVMSG '.$nick.' :'.$severity.trim($alert['title']).' - Rule: '.trim($alert['name'] ? $alert['name'] : $alert['rule']).(sizeof($alert['faults']) > 0 ? ' - Faults'.(sizeof($alert['faults']) > 3 ? ' (showing first 3 out of '.sizeof($alert['faults']).' )' : '' ).':' : ''));
foreach ($alert['faults'] as $k => $v) {
$this->irc_raw('PRIVMSG '.$nick.' :#'.$k.' '.$v['string']);
$this->ircRaw('PRIVMSG '.$nick.' :#'.$k.' '.$v['string']);
if ($k >= 3) {
break;
}
@@ -268,17 +270,17 @@ class IRCBot {
}
}
}//end if
}//end alertData()
private function getData() {
private function getData()
{
if (($data = $this->read('irc')) !== false) {
$this->last_activity = time();
$this->data = $data;
$ex = explode(' ', $this->data);
if ($ex[0] == 'PING') {
return $this->irc_raw('PONG '.$ex[1]);
return $this->ircRaw('PONG '.$ex[1]);
}
if ($ex[1] == 376 || $ex[1] == 422 || ($ex[1] == 'MODE' && $ex[2] == $this->nick)) {
@@ -293,79 +295,78 @@ class IRCBot {
$this->handleCommand();
}
}
}//end getData()
private function joinChan($chan=false) {
private function joinChan($chan = false)
{
if ($chan) {
$this->chan[] = $chan;
}
foreach ($this->chan as $chan) {
$this->irc_raw('JOIN '.$chan);
$this->ircRaw('JOIN '.$chan);
}
return true;
}//end joinChan()
private function handleCommand() {
private function handleCommand()
{
$this->command = str_replace(':.', '', $this->command);
$tmp = explode(':.'.$this->command.' ', $this->data);
$this->user = $this->get_user();
$this->user = $this->getAuthdUser();
if ($this->isAuthd() || trim($this->command) == 'auth') {
$this->proceedCommand(str_replace("\n", '', trim($this->command)), trim($tmp[1]));
}
$this->authd[$this->getUser($this->data)] = $this->user;
return false;
}//end handleCommand()
private function proceedCommand($command, $params) {
private function proceedCommand($command, $params)
{
$command = strtolower($command);
if (in_array($command, $this->commands)) {
$this->chkdb();
$this->log($command." ( '".$params."' )");
return $this->{'_'.$command}($params);
}
else if ($this->external[$command]) {
} elseif ($this->external[$command]) {
$this->chkdb();
$this->log($command." ( '".$params."' ) [Ext]");
return eval($this->external[$command]);
}
return false;
}//end proceedCommand()
private function respond($msg) {
private function respond($msg)
{
$chan = $this->getChan($this->data);
return $this->sendMessage($msg, strstr($chan, '#') ? $chan : $this->getUser($this->data));
}//end respond()
private function getChan($param) {
private function getChan($param)
{
$data = explode('PRIVMSG ', $this->data, 3);
$data = explode(' ', $data[1], 2);
return $data[0];
}//end getChan()
private function getUser($param) {
private function getUser($param)
{
$arrData = explode('!', $param, 2);
return str_replace(':', '', $arrData[0]);
}//end getUser()
private function connect($try) {
private function connect($try)
{
if ($try > $this->max_retry) {
$this->log('Failed too many connection attempts, aborting');
return die();
@@ -378,8 +379,7 @@ class IRCBot {
if ($this->ssl) {
$server = 'ssl://'.$this->server;
}
else {
} else {
$server = $this->server;
}
@@ -387,91 +387,86 @@ class IRCBot {
$ssl_context_params = array('ssl'=>array('allow_self_signed'=> true, 'verify_peer' => false, 'verify_peer_name' => false ));
$ssl_context = stream_context_create($ssl_context_params);
$this->socket['irc'] = stream_socket_client($server.':'.$this->port, $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $ssl_context);
}
else {
} else {
$this->socket['irc'] = fsockopen($server, $this->port);
}
if (!is_resource($this->socket['irc'])) {
return $this->connect($try + 1);
}
else {
} else {
stream_set_blocking($this->socket['irc'], false);
return true;
}
}//end connect()
private function doAuth() {
if ($this->irc_raw('USER '.$this->nick.' 0 '.$this->nick.' :'.$this->nick) && $this->irc_raw('NICK '.$this->nick)) {
private function doAuth()
{
if ($this->ircRaw('USER '.$this->nick.' 0 '.$this->nick.' :'.$this->nick) && $this->ircRaw('NICK '.$this->nick)) {
return true;
}
return false;
}//end doAuth()
private function sendMessage($message, $chan) {
private function sendMessage($message, $chan)
{
if ($this->debug) {
$this->log("Sending 'PRIVMSG ".trim($chan).' :'.trim($message)."'");
}
return $this->irc_raw('PRIVMSG '.trim($chan).' :'.trim($message));
return $this->ircRaw('PRIVMSG '.trim($chan).' :'.trim($message));
}//end sendMessage()
private function log($msg) {
private function log($msg)
{
echo '['.date('r').'] '.trim($msg)."\n";
return true;
}//end log()
private function chkdb() {
private function chkdb()
{
if (!is_resource($this->sql)) {
if (($this->sql = mysqli_connect($this->config['db_host'], $this->config['db_user'], $this->config['db_pass'])) != false && mysqli_select_db($this->sql, $this->config['db_name'])) {
return true;
}
else {
} else {
$this->log('Cannot connect to MySQL');
return die();
}
}
else {
} else {
return true;
}
}//end chkdb()
private function isAuthd() {
private function isAuthd()
{
if ($this->user['expire'] >= time()) {
$this->user['expire'] = (time() + ($this->config['irc_authtime'] * 3600));
return true;
}
else {
} else {
return false;
}
}//end isAuthd()
private function get_user() {
private function getAuthdUser()
{
return $this->authd[$this->getUser($this->data)];
}//end get_user()
private function irc_raw($params) {
private function ircRaw($params)
{
return fputs($this->socket['irc'], $params."\r\n");
}//end irc_raw()
private function _auth($params) {
private function _auth($params)
{
$params = explode(' ', $params, 2);
if (strlen($params[0]) == 64) {
if ($this->tokens[$this->getUser($this->data)] == $params[0]) {
@@ -489,12 +484,10 @@ class IRCBot {
}
return $this->respond('Authenticated.');
}
else {
} else {
return $this->respond('Nope.');
}
}
else {
} else {
$user = dbFetchRow('SELECT `user_id`,`username`,`email` FROM `users` WHERE `username` = ?', array(mres($params[0])));
if ($user['email'] && $user['username'] == $params[0]) {
$token = hash('gost', openssl_random_pseudo_bytes(1024));
@@ -507,21 +500,19 @@ class IRCBot {
if (send_mail($user['email'], 'LibreNMS IRC-Bot Authtoken', "Your Authtoken for the IRC-Bot:\r\n\r\n".$token."\r\n\r\n") === true) {
return $this->respond('Token sent!');
}
else {
} else {
return $this->respond('Sorry, seems like mail doesnt like us.');
}
}
else {
} else {
return $this->respond('Who are you again?');
}
}//end if
return false;
}//end _auth()
private function _reload() {
private function _reload()
{
if ($this->user['level'] == 10) {
global $config;
$config = array();
@@ -532,54 +523,51 @@ class IRCBot {
if ($config != $this->config) {
return $this->__construct();
}
}
else {
} else {
return $this->respond('Permission denied.');
}
}//end _reload()
private function _join($params) {
private function _join($params)
{
if ($this->user['level'] == 10) {
return $this->joinChan($params);
}
else {
} else {
return $this->respond('Permission denied.');
}
}//end _join()
private function _quit($params) {
private function _quit($params)
{
if ($this->user['level'] == 10) {
return die();
}
else {
} else {
return $this->respond('Permission denied.');
}
}//end _quit()
private function _help($params) {
private function _help($params)
{
foreach ($this->commands as $cmd) {
$msg .= ', '.$cmd;
}
$msg = substr($msg, 2);
return $this->respond("Available commands: $msg");
}//end _help()
private function _version($params) {
private function _version($params)
{
return $this->respond($this->config['project_name_version'].', PHP: '.PHP_VERSION);
}//end _version()
private function _log($params) {
private function _log($params)
{
$num = 1;
if ($params > 1) {
$num = $params;
@@ -587,8 +575,7 @@ class IRCBot {
if ($this->user['level'] < 5) {
$tmp = dbFetchRows('SELECT `event_id`,`host`,`datetime`,`message`,`type` FROM `eventlog` WHERE `host` IN ('.implode(',', $this->user['devices']).') ORDER BY `event_id` DESC LIMIT '.mres($num));
}
else {
} else {
$tmp = dbFetchRows('SELECT `event_id`,`host`,`datetime`,`message`,`type` FROM `eventlog` ORDER BY `event_id` DESC LIMIT '.mres($num));
}
@@ -602,15 +589,14 @@ class IRCBot {
}
return true;
}//end _log()
private function _down($params) {
private function _down($params)
{
if ($this->user['level'] < 5) {
$tmp = dbFetchRows('SELECT `hostname` FROM `devices` WHERE status=0 AND `device_id` IN ('.implode(',', $this->user['devices']).')');
}
else {
} else {
$tmp = dbFetchRows('SELECT `hostname` FROM `devices` WHERE status=0');
}
@@ -623,11 +609,11 @@ class IRCBot {
$msg = substr($msg, 2);
$msg = $msg ? $msg : 'Nothing to show :)';
return $this->respond($msg);
}//end _down()
private function _device($params) {
private function _device($params)
{
$params = explode(' ', $params);
$hostname = $params[0];
$device = dbFetchRow('SELECT * FROM `devices` WHERE `hostname` = ?', array($hostname));
@@ -643,11 +629,11 @@ class IRCBot {
$status .= $device['ignore'] ? '*Ignored*' : '';
$status .= $device['disabled'] ? '*Disabled*' : '';
return $this->respond($device['os'].' '.$device['version'].' '.$device['features'].' '.$status);
}//end _device()
private function _port($params) {
private function _port($params)
{
$params = explode(' ', $params);
$hostname = $params[0];
$ifname = $params[1];
@@ -666,15 +652,14 @@ class IRCBot {
$pps_in = format_bi($port['ifInUcastPkts_rate']);
$pps_out = format_bi($port['ifOutUcastPkts_rate']);
return $this->respond($port['ifAdminStatus'].'/'.$port['ifOperStatus'].' '.$bps_in.' > bps > '.$bps_out.' | '.$pps_in.'pps > PPS > '.$pps_out.'pps');
}//end _port()
private function _listdevices($params) {
private function _listdevices($params)
{
if ($this->user['level'] < 5) {
$tmp = dbFetchRows('SELECT `hostname` FROM `devices` WHERE `device_id` IN ('.implode(',', $this->user['devices']).')');
}
else {
} else {
$tmp = dbFetchRows('SELECT `hostname` FROM `devices`');
}
@@ -685,11 +670,11 @@ class IRCBot {
$msg = substr($msg, 2);
$msg = $msg ? $msg : 'Nothing to show..?';
return $this->respond($msg);
}//end _listdevices()
private function _status($params) {
private function _status($params)
{
$params = explode(' ', $params);
$statustype = $params[0];
if ($this->user['level'] < 5) {
@@ -700,48 +685,45 @@ class IRCBot {
}
switch ($statustype) {
case 'devices':
case 'device':
case 'dev':
$devcount = array_pop(dbFetchRow('SELECT count(*) FROM devices'.$d_w));
$devup = array_pop(dbFetchRow("SELECT count(*) FROM devices WHERE status = '1' AND `ignore` = '0'".$d_a));
$devdown = array_pop(dbFetchRow("SELECT count(*) FROM devices WHERE status = '0' AND `ignore` = '0'".$d_a));
$devign = array_pop(dbFetchRow("SELECT count(*) FROM devices WHERE `ignore` = '1'".$d_a));
$devdis = array_pop(dbFetchRow("SELECT count(*) FROM devices WHERE `disabled` = '1'".$d_a));
$msg = 'Devices: '.$devcount.' ('.$devup.' up, '.$devdown.' down, '.$devign.' ignored, '.$devdis.' disabled'.')';
break;
case 'devices':
case 'device':
case 'dev':
$devcount = array_pop(dbFetchRow('SELECT count(*) FROM devices'.$d_w));
$devup = array_pop(dbFetchRow("SELECT count(*) FROM devices WHERE status = '1' AND `ignore` = '0'".$d_a));
$devdown = array_pop(dbFetchRow("SELECT count(*) FROM devices WHERE status = '0' AND `ignore` = '0'".$d_a));
$devign = array_pop(dbFetchRow("SELECT count(*) FROM devices WHERE `ignore` = '1'".$d_a));
$devdis = array_pop(dbFetchRow("SELECT count(*) FROM devices WHERE `disabled` = '1'".$d_a));
$msg = 'Devices: '.$devcount.' ('.$devup.' up, '.$devdown.' down, '.$devign.' ignored, '.$devdis.' disabled'.')';
break;
case 'ports':
case 'port':
case 'prt':
$prtcount = array_pop(dbFetchRow('SELECT count(*) FROM ports'.$p_w));
$prtup = array_pop(dbFetchRow("SELECT count(*) FROM ports AS I, devices AS D WHERE I.ifOperStatus = 'up' AND I.ignore = '0' AND I.device_id = D.device_id AND D.ignore = '0'".$p_a));
$prtdown = array_pop(dbFetchRow("SELECT count(*) FROM ports AS I, devices AS D WHERE I.ifOperStatus = 'down' AND I.ifAdminStatus = 'up' AND I.ignore = '0' AND D.device_id = I.device_id AND D.ignore = '0'".$p_a));
$prtsht = array_pop(dbFetchRow("SELECT count(*) FROM ports AS I, devices AS D WHERE I.ifAdminStatus = 'down' AND I.ignore = '0' AND D.device_id = I.device_id AND D.ignore = '0'".$p_a));
$prtign = array_pop(dbFetchRow("SELECT count(*) FROM ports AS I, devices AS D WHERE D.device_id = I.device_id AND (I.ignore = '1' OR D.ignore = '1')".$p_a));
$prterr = array_pop(dbFetchRow("SELECT count(*) FROM ports AS I, devices AS D WHERE D.device_id = I.device_id AND (I.ignore = '0' OR D.ignore = '0') AND (I.ifInErrors_delta > '0' OR I.ifOutErrors_delta > '0')".$p_a));
$msg = 'Ports: '.$prtcount.' ('.$prtup.' up, '.$prtdown.' down, '.$prtign.' ignored, '.$prtsht.' shutdown'.')';
break;
case 'ports':
case 'port':
case 'prt':
$prtcount = array_pop(dbFetchRow('SELECT count(*) FROM ports'.$p_w));
$prtup = array_pop(dbFetchRow("SELECT count(*) FROM ports AS I, devices AS D WHERE I.ifOperStatus = 'up' AND I.ignore = '0' AND I.device_id = D.device_id AND D.ignore = '0'".$p_a));
$prtdown = array_pop(dbFetchRow("SELECT count(*) FROM ports AS I, devices AS D WHERE I.ifOperStatus = 'down' AND I.ifAdminStatus = 'up' AND I.ignore = '0' AND D.device_id = I.device_id AND D.ignore = '0'".$p_a));
$prtsht = array_pop(dbFetchRow("SELECT count(*) FROM ports AS I, devices AS D WHERE I.ifAdminStatus = 'down' AND I.ignore = '0' AND D.device_id = I.device_id AND D.ignore = '0'".$p_a));
$prtign = array_pop(dbFetchRow("SELECT count(*) FROM ports AS I, devices AS D WHERE D.device_id = I.device_id AND (I.ignore = '1' OR D.ignore = '1')".$p_a));
$prterr = array_pop(dbFetchRow("SELECT count(*) FROM ports AS I, devices AS D WHERE D.device_id = I.device_id AND (I.ignore = '0' OR D.ignore = '0') AND (I.ifInErrors_delta > '0' OR I.ifOutErrors_delta > '0')".$p_a));
$msg = 'Ports: '.$prtcount.' ('.$prtup.' up, '.$prtdown.' down, '.$prtign.' ignored, '.$prtsht.' shutdown'.')';
break;
case 'services':
case 'service':
case 'srv':
$srvcount = array_pop(dbFetchRow('SELECT count(service_id) FROM services'.$d_w));
$srvup = array_pop(dbFetchRow("SELECT count(service_id) FROM services WHERE service_status = '1' AND service_ignore ='0'".$d_a));
$srvdown = array_pop(dbFetchRow("SELECT count(service_id) FROM services WHERE service_status = '0' AND service_ignore = '0'".$d_a));
$srvign = array_pop(dbFetchRow("SELECT count(service_id) FROM services WHERE service_ignore = '1'".$d_a));
$srvdis = array_pop(dbFetchRow("SELECT count(service_id) FROM services WHERE service_disabled = '1'".$d_a));
$msg = 'Services: '.$srvcount.' ('.$srvup.' up, '.$srvdown.' down, '.$srvign.' ignored, '.$srvdis.' disabled'.')';
break;
case 'services':
case 'service':
case 'srv':
$srvcount = array_pop(dbFetchRow('SELECT count(service_id) FROM services'.$d_w));
$srvup = array_pop(dbFetchRow("SELECT count(service_id) FROM services WHERE service_status = '1' AND service_ignore ='0'".$d_a));
$srvdown = array_pop(dbFetchRow("SELECT count(service_id) FROM services WHERE service_status = '0' AND service_ignore = '0'".$d_a));
$srvign = array_pop(dbFetchRow("SELECT count(service_id) FROM services WHERE service_ignore = '1'".$d_a));
$srvdis = array_pop(dbFetchRow("SELECT count(service_id) FROM services WHERE service_disabled = '1'".$d_a));
$msg = 'Services: '.$srvcount.' ('.$srvup.' up, '.$srvdown.' down, '.$srvign.' ignored, '.$srvdis.' disabled'.')';
break;
default:
$msg = 'Error: STATUS requires one of the following: <devices|device|dev>|<ports|port|prt>|<services|service|src>';
break;
default:
$msg = 'Error: STATUS requires one of the following: <devices|device|dev>|<ports|port|prt>|<services|service|src>';
break;
}//end switch
return $this->respond($msg);
}//end _status()
}//end class

View File

@@ -28,7 +28,8 @@ namespace LibreNMS;
use ArrayAccess;
class ObjectCache implements ArrayAccess {
class ObjectCache implements ArrayAccess
{
private $data = array();
@@ -39,13 +40,13 @@ class ObjectCache implements ArrayAccess {
* Initialize ObjectCache
* @param string $obj Name of Object
*/
public function __construct($obj) {
public function __construct($obj)
{
global $config;
$this->obj = $obj;
if (isset($GLOBALS['_ObjCache'][$obj])) {
$this->data = $GLOBALS['_ObjCacheSkell'][$obj];
}
else {
} else {
if (!is_array($GLOBALS['_ObjCacheSkell'])) {
$GLOBALS['_ObjCacheSkell'] = array();
}
@@ -64,7 +65,6 @@ class ObjectCache implements ArrayAccess {
}
}
}//end if
}//end __construct()
@@ -73,13 +73,13 @@ class ObjectCache implements ArrayAccess {
* @param string $obj Name of Data-Object
* @return boolean
*/
public function offsetExists($obj) {
public function offsetExists($obj)
{
if (isset($this->data[$obj])) {
return true;
}
return false;
}//end offsetExists()
@@ -88,15 +88,14 @@ class ObjectCache implements ArrayAccess {
* @param string $obj Name of Data-Object
* @return mixed
*/
public function offsetGet($obj) {
public function offsetGet($obj)
{
if (isset($this->data[$obj])) {
if (isset($this->data[$obj]['value'])) {
return $this->data[$obj]['value'];
}
else if (isset($GLOBALS['_ObjCache'][$this->obj][$obj]['value'])) {
} elseif (isset($GLOBALS['_ObjCache'][$this->obj][$obj]['value'])) {
return $GLOBALS['_ObjCache'][$this->obj][$obj]['value'];
}
else {
} else {
$GLOBALS['_ObjCache'][$this->obj][$obj]['value'] = dbFetchRows($this->data[$obj]['query'], $this->data[$obj]['params']);
if (sizeof($GLOBALS['_ObjCache'][$this->obj][$obj]['value']) == 1 && sizeof($GLOBALS['_ObjCache'][$this->obj][$obj]['value'][0]) == 1) {
$GLOBALS['_ObjCache'][$this->obj][$obj]['value'] = current($GLOBALS['_ObjCache'][$this->obj][$obj]['value'][0]);
@@ -104,7 +103,6 @@ class ObjectCache implements ArrayAccess {
return $GLOBALS['_ObjCache'][$this->obj][$obj]['value'];
}
}
}//end offsetGet()
@@ -114,14 +112,14 @@ class ObjectCache implements ArrayAccess {
* @param mixed $value Value
* @return boolean
*/
public function offsetSet($obj, $value) {
public function offsetSet($obj, $value)
{
if (!is_array($this->data[$obj])) {
$this->data[$obj] = array();
}
$this->data[$obj]['value'] = $value;
return $this->data[$obj]['value'];
}//end offsetSet()
@@ -130,11 +128,9 @@ class ObjectCache implements ArrayAccess {
* @param string $obj Name of Data-Object
* @return mixed
*/
public function offsetUnset($obj) {
public function offsetUnset($obj)
{
unset($this->data[$obj]['value']);
return true;
}//end offsetUnset()
}//end class

View File

@@ -207,7 +207,7 @@ class Proc
*/
public function isRunning()
{
if(!is_resource($this->_process)) {
if (!is_resource($this->_process)) {
return false;
}
$st = $this->getStatus();

View File

@@ -31,9 +31,11 @@ namespace LibreNMS;
* @method boolean isDir()
*
**/
class RRDRecursiveFilterIterator extends \RecursiveFilterIterator {
class RRDRecursiveFilterIterator extends \RecursiveFilterIterator
{
public function accept() {
public function accept()
{
$filename = $this->current()->getFilename();
if ($filename[0] === '.') {
// Ignore hidden files and directories

View File

@@ -45,12 +45,12 @@ if (isset($options['f']) && $options['f'] == 0) {
}
$port_assoc_mode = $config['default_port_association_mode'];
$valid_assoc_modes = get_port_assoc_modes ();
if (isset ($options['p'])) {
$valid_assoc_modes = get_port_assoc_modes();
if (isset($options['p'])) {
$port_assoc_mode = $options['p'];
if (! in_array ($port_assoc_mode, $valid_assoc_modes)) {
if (! in_array($port_assoc_mode, $valid_assoc_modes)) {
echo "Invalid port association mode '" . $port_assoc_mode . "'\n";
echo 'Valid modes: ' . join (', ', $valid_assoc_modes) . "\n";
echo 'Valid modes: ' . join(', ', $valid_assoc_modes) . "\n";
exit(1);
}
@@ -178,14 +178,13 @@ if (!empty($argv[1])) {
echo " $reason\n";
}
exit(2);
} catch (Exception $e){
} catch (Exception $e) {
print_error($e->getMessage());
exit(3);
}
} else {
c_echo(
"\n".$config['project_name_version'].' Add Host Tool
"\n".$config['project_name_version'].' Add Host Tool
Usage (SNMPv1/2c): ./addhost.php [-g <poller group>] [-f] [-p <port assoc mode>] <%Whostname%n> [community] [v1|v2c] [port] ['.implode('|', $config['snmp']['transports']).']
Usage (SNMPv3) : Config Defaults : ./addhost.php [-g <poller group>] [-f] [-p <port assoc mode>] <%Whostname%n> any v3 [user] [port] ['.implode('|', $config['snmp']['transports']).']
@@ -198,7 +197,7 @@ if (!empty($argv[1])) {
-p <port assoc mode> allow you to set a port association mode for this device. By default ports are associated by \'ifIndex\'.
For Linux/Unix based devices \'ifName\' or \'ifDescr\' might be useful for a stable iface mapping.
The default for this installation is \'' . $config['default_port_association_mode'] . '\'
Valid port assoc modes are: ' . join (', ', $valid_assoc_modes) . '
Valid port assoc modes are: ' . join(', ', $valid_assoc_modes) . '
%rRemember to run discovery for the host afterwards.%n
'

View File

@@ -22,8 +22,7 @@ require 'includes/functions.php';
if (file_exists('html/includes/authentication/'.$config['auth_mechanism'].'.inc.php')) {
include 'html/includes/authentication/'.$config['auth_mechanism'].'.inc.php';
}
else {
} else {
echo "ERROR: no valid auth_mechanism defined.\n";
exit();
}
@@ -34,15 +33,12 @@ if (auth_usermanagement()) {
if (adduser($argv[1], $argv[2], $argv[3], @$argv[4])) {
echo 'User '.$argv[1]." added successfully\n";
}
}
else {
} else {
echo 'User '.$argv[1]." already exists!\n";
}
}
else {
} else {
echo "Add User Tool\nUsage: ./adduser.php <username> <password> <level 1-10> [email]\n";
}
}
else {
} else {
echo "Auth module does not allow adding users!\n";
}//end if

View File

@@ -41,8 +41,7 @@ if (file_exists($config['install_dir'].'/.alerts.lock')) {
if ($lock === true) {
exit(1);
}
else {
} else {
file_put_contents($config['install_dir'].'/.alerts.lock', getmypid());
}
@@ -57,8 +56,7 @@ if (isset($options['d'])) {
ini_set('display_startup_errors', 1);
ini_set('log_errors', 1);
ini_set('error_reporting', 1);
}
else {
} else {
$debug = false;
// ini_set('display_errors', 0);
ini_set('display_startup_errors', 0);
@@ -86,7 +84,8 @@ unlink($config['install_dir'].'/.alerts.lock');
* @param integer $rule Rule-ID
* @return boolean
*/
function IsRuleValid($device, $rule) {
function IsRuleValid($device, $rule)
{
global $rulescache;
if (empty($rulescache[$device]) || !isset($rulescache[$device])) {
foreach (GetRules($device) as $chk) {
@@ -99,7 +98,6 @@ function IsRuleValid($device, $rule) {
}
return false;
}//end IsRuleValid()
@@ -108,7 +106,8 @@ function IsRuleValid($device, $rule) {
* @param array $alert
* @return boolean
*/
function IssueAlert($alert) {
function IssueAlert($alert)
{
global $config;
if (dbFetchCell('SELECT attrib_value FROM devices_attribs WHERE attrib_type = "disable_notify" && device_id = ?', array($alert['device_id'])) == '1') {
return true;
@@ -129,7 +128,6 @@ function IssueAlert($alert) {
}
return true;
}//end IssueAlert()
@@ -137,7 +135,8 @@ function IssueAlert($alert) {
* Issue ACK notification
* @return void
*/
function RunAcks() {
function RunAcks()
{
foreach (dbFetchRows('SELECT alerts.device_id, alerts.rule_id, alerts.state FROM alerts WHERE alerts.state = 2 && alerts.open = 1') as $alert) {
$tmp = array(
$alert['rule_id'],
@@ -156,7 +155,6 @@ function RunAcks() {
IssueAlert($alert);
dbUpdate(array('open' => 0), 'alerts', 'rule_id = ? && device_id = ?', array($alert['rule_id'], $alert['device_id']));
}
}//end RunAcks()
@@ -164,7 +162,8 @@ function RunAcks() {
* Run Follow-Up alerts
* @return void
*/
function RunFollowUp() {
function RunFollowUp()
{
global $config;
foreach (dbFetchRows('SELECT alerts.device_id, alerts.rule_id, alerts.state FROM alerts WHERE alerts.state != 2 && alerts.state > 0 && alerts.open = 0') as $alert) {
$tmp = array(
@@ -193,12 +192,11 @@ function RunFollowUp() {
if ($n > $o) {
$ret .= ' Worsens';
$state = 3;
$alert['details']['diff'] = array_diff($chk,$alert['details']['rule']);
}
elseif ($n < $o) {
$alert['details']['diff'] = array_diff($chk, $alert['details']['rule']);
} elseif ($n < $o) {
$ret .= ' Betters';
$state = 4;
$alert['details']['diff'] = array_diff($alert['details']['rule'],$chk);
$alert['details']['diff'] = array_diff($alert['details']['rule'], $chk);
}
if ($state > 0 && $n > 0) {
@@ -210,7 +208,6 @@ function RunFollowUp() {
echo $ret.' ('.$o.'/'.$n.")\r\n";
}
}//end foreach
}//end RunFollowUp()
@@ -218,7 +215,8 @@ function RunFollowUp() {
* Run all alerts
* @return void
*/
function RunAlerts() {
function RunAlerts()
{
global $config;
foreach (dbFetchRows('SELECT alerts.device_id, alerts.rule_id, alerts.state FROM alerts WHERE alerts.state != 2 && alerts.open = 1') as $alert) {
$tmp = array(
@@ -248,8 +246,7 @@ function RunAlerts() {
if (!empty($rextra['delay'])) {
if ((time() - strtotime($alert['time_logged']) + $config['alert']['tolerance_window']) < $rextra['delay'] || (!empty($alert['details']['delay']) && (time() - $alert['details']['delay'] + $config['alert']['tolerance_window']) < $rextra['delay'])) {
continue;
}
else {
} else {
$alert['details']['delay'] = time();
$updet = true;
}
@@ -263,8 +260,7 @@ function RunAlerts() {
$updet = true;
$noiss = false;
}
}
else {
} else {
// This is the new way
if (!empty($rextra['delay']) && (time() - strtotime($alert['time_logged']) + $config['alert']['tolerance_window']) < $rextra['delay']) {
continue;
@@ -273,8 +269,7 @@ function RunAlerts() {
if (!empty($rextra['interval'])) {
if (!empty($alert['details']['interval']) && (time() - $alert['details']['interval'] + $config['alert']['tolerance_window']) < $rextra['interval']) {
continue;
}
else {
} else {
$alert['details']['interval'] = time();
$updet = true;
}
@@ -318,7 +313,6 @@ function RunAlerts() {
dbUpdate(array('open' => 0), 'alerts', 'rule_id = ? && device_id = ?', array($alert['rule_id'], $alert['device_id']));
}
}//end foreach
}//end RunAlerts()
@@ -327,7 +321,8 @@ function RunAlerts() {
* @param array $obj Alert-Array
* @return void
*/
function ExtTransports($obj) {
function ExtTransports($obj)
{
global $config;
$tmp = false;
// To keep scrutinizer from naging because it doesnt understand eval
@@ -348,12 +343,10 @@ function ExtTransports($obj) {
if ($tmp === true) {
echo 'OK';
log_event('Issued '.$prefix[$obj['state']]." for rule '".$obj['name']."' to transport '".$transport."'", $obj['device_id']);
}
elseif ($tmp === false) {
} elseif ($tmp === false) {
echo 'ERROR';
log_event('Could not issue '.$prefix[$obj['state']]." for rule '".$obj['name']."' to transport '".$transport."'", $obj['device_id']);
}
else {
} else {
echo 'ERROR: '.$tmp."\r\n";
log_event('Could not issue '.$prefix[$obj['state']]." for rule '".$obj['name']."' to transport '".$transport."' Error: ".$tmp, $obj['device_id']);
}
@@ -361,7 +354,6 @@ function ExtTransports($obj) {
echo '; ';
}
}//end ExtTransports()
@@ -370,7 +362,8 @@ function ExtTransports($obj) {
* @param array $obj Alert-Array
* @return string
*/
function FormatAlertTpl($obj) {
function FormatAlertTpl($obj)
{
$tpl = $obj["template"];
$msg = '$ret .= "'.str_replace(array('{else}', '{/if}', '{/foreach}'), array('"; } else { $ret .= "', '"; } $ret .= "', '"; } $ret .= "'), addslashes($tpl)).'";';
$parsed = $msg;
@@ -381,23 +374,19 @@ function FormatAlertTpl($obj) {
while (++$x < $s) {
if ($msg[$x] == '{' && $buff == '') {
$buff .= $msg[$x];
}
elseif ($buff == '{ ') {
} elseif ($buff == '{ ') {
$buff = '';
}
elseif ($buff != '') {
} elseif ($buff != '') {
$buff .= $msg[$x];
}
if ($buff == '{if') {
$pos = $x;
$if = true;
}
elseif ($buff == '{foreach') {
} elseif ($buff == '{foreach') {
$pos = $x;
$for = true;
}
elseif ($buff == '{calc') {
} elseif ($buff == '{calc') {
$pos = $x;
$calc = true;
}
@@ -413,24 +402,21 @@ function FormatAlertTpl($obj) {
'"; if( ',
' ) { $ret .= "',
);
}
elseif ($for) {
} elseif ($for) {
$for = false;
$o = 8;
$native = array(
'"; foreach( ',
' as $key=>$value) { $ret .= "',
);
}
elseif ($calc) {
} elseif ($calc) {
$calc = false;
$o = 5;
$native = array(
'"; $ret .= (float) (0+(',
')); $ret .= "',
);
}
else {
} else {
continue;
}
@@ -443,7 +429,6 @@ function FormatAlertTpl($obj) {
$parsed = populate($parsed);
return RunJail($parsed, $obj);
}//end FormatAlertTpl()
@@ -452,7 +437,8 @@ function FormatAlertTpl($obj) {
* @param array $alert Alert-Result from DB
* @return array
*/
function DescribeAlert($alert) {
function DescribeAlert($alert)
{
$obj = array();
$i = 0;
$device = dbFetchRow('SELECT hostname, sysName, location, uptime FROM devices WHERE device_id = ?', array($alert['device_id']));
@@ -472,17 +458,14 @@ function DescribeAlert($alert) {
if ($alert['state'] >= 1) {
if (!empty($tpl['title'])) {
$obj['title'] = $tpl['title'];
}
else {
} else {
$obj['title'] = 'Alert for device '.$device['hostname'].' - '.($alert['name'] ? $alert['name'] : $alert['rule']);
}
if ($alert['state'] == 2) {
$obj['title'] .= ' got acknowledged';
}
elseif ($alert['state'] == 3) {
} elseif ($alert['state'] == 3) {
$obj['title'] .= ' got worse';
}
elseif ($alert['state'] == 4) {
} elseif ($alert['state'] == 4) {
$obj['title'] .= ' got better';
}
@@ -496,11 +479,10 @@ function DescribeAlert($alert) {
}
}
$obj['elapsed'] = TimeFormat(time() - strtotime($alert['time_logged']));
if( !empty($extra['diff']) ) {
if (!empty($extra['diff'])) {
$obj['diff'] = $extra['diff'];
}
}
elseif ($alert['state'] == 0) {
} elseif ($alert['state'] == 0) {
$id = dbFetchRow('SELECT alert_log.id,alert_log.time_logged,alert_log.details FROM alert_log WHERE alert_log.state != 2 && alert_log.state != 0 && alert_log.rule_id = ? && alert_log.device_id = ? && alert_log.id < ? ORDER BY id DESC LIMIT 1', array($alert['rule_id'], $alert['device_id'], $alert['id']));
if (empty($id['id'])) {
return false;
@@ -509,15 +491,13 @@ function DescribeAlert($alert) {
$extra = json_decode(gzuncompress($id['details']), true);
if (!empty($tpl['title_rec'])) {
$obj['title'] = $tpl['title_rec'];
}
else {
} else {
$obj['title'] = 'Device '.$device['hostname'].' recovered from '.($alert['name'] ? $alert['name'] : $alert['rule']);
}
$obj['elapsed'] = TimeFormat(strtotime($alert['time_logged']) - strtotime($id['time_logged']));
$obj['id'] = $id['id'];
$obj['faults'] = false;
}
else {
} else {
return 'Unknown State';
}//end if
$obj['uid'] = $alert['id'];
@@ -527,11 +507,10 @@ function DescribeAlert($alert) {
$obj['timestamp'] = $alert['time_logged'];
$obj['contacts'] = $extra['contacts'];
$obj['state'] = $alert['state'];
if (strstr($obj['title'],'%')) {
if (strstr($obj['title'], '%')) {
$obj['title'] = RunJail('$ret = "'.populate(addslashes($obj['title'])).'";', $obj);
}
return $obj;
}//end DescribeAlert()
@@ -540,7 +519,8 @@ function DescribeAlert($alert) {
* @param integer $secs Seconds elapsed
* @return string
*/
function TimeFormat($secs) {
function TimeFormat($secs)
{
$bit = array(
'y' => $secs / 31556926 % 12,
'w' => $secs / 604800 % 52,
@@ -561,7 +541,6 @@ function TimeFormat($secs) {
}
return join(' ', $ret);
}//end TimeFormat()
@@ -571,11 +550,11 @@ function TimeFormat($secs) {
* @param array $obj Object with variables
* @return string|mixed
*/
function RunJail($code, $obj) {
function RunJail($code, $obj)
{
$ret = '';
eval($code);
return $ret;
}//end RunJail()
@@ -585,21 +564,20 @@ function RunJail($code, $obj) {
* @param boolean $wrap Wrap variable for text-usage (default: true)
* @return string
*/
function populate($txt, $wrap=true) {
function populate($txt, $wrap = true)
{
preg_match_all('/%([\w\.]+)/', $txt, $m);
foreach ($m[1] as $tmp) {
$orig = $tmp;
$rep = false;
if ($tmp == 'key' || $tmp == 'value') {
$rep = '$'.$tmp;
}
else {
} else {
if (strstr($tmp, '.')) {
$tmp = explode('.', $tmp, 2);
$pre = '$'.$tmp[0];
$tmp = $tmp[1];
}
else {
} else {
$pre = '$obj';
}
@@ -613,5 +591,4 @@ function populate($txt, $wrap=true) {
}//end foreach
return $txt;
}//end populate()

View File

@@ -60,8 +60,7 @@ foreach (dbFetchRows('SELECT * FROM `bills` ORDER BY `bill_id`') as $bill) {
$overuse = ($used - $allowed);
$overuse = (($overuse <= 0) ? '0' : $overuse);
$percent = round((($rate_data['rate_95th'] / $bill['bill_cdr']) * 100), 2);
}
else if ($bill['bill_type'] == 'quota') {
} elseif ($bill['bill_type'] == 'quota') {
$type = 'Quota';
$allowed = $bill['bill_quota'];
$used = $rate_data['total_data'];
@@ -113,8 +112,7 @@ foreach (dbFetchRows('SELECT * FROM `bills` ORDER BY `bill_id`') as $bill) {
dbUpdate($update, 'bill_history', '`bill_hist_id` = ?', array($check['bill_hist_id']));
echo ' Updated history! ';
}
else {
} else {
$update = array(
'rate_95th' => $rate_data['rate_95th'],
'rate_95th_in' => $rate_data['rate_95th_in'],

View File

@@ -29,12 +29,11 @@ if ($select === false) {
$limit = 0;
while (!feof($sql_fh)) {
$line = fgetss($sql_fh);
if (isset($_SESSION['stage']) ) {
if (isset($_SESSION['stage'])) {
$limit++;
if (isset($_SESSION['offset']) && $limit < $_REQUEST['offset']) {
continue;
}
elseif ( time()-$_SESSION['last'] > 45 ) {
} elseif (time()-$_SESSION['last'] > 45) {
$_SESSION['offset'] = $limit;
$GLOBALS['refresh'] = '<b>Installing, please wait..</b><sub>'.date('r').'</sub><script>window.location.href = "install.php?offset='.$limit.'";</script>';
return;

View File

@@ -51,6 +51,5 @@ rrdtool_initialize();
foreach (dbFetchRows('SELECT * FROM `devices` AS D, `services` AS S WHERE S.device_id = D.device_id ORDER by D.device_id DESC') as $service) {
// Run the polling function
poll_service($service);
} //end foreach
rrdtool_close();

View File

@@ -12,14 +12,13 @@ $config_file = 'config.php';
// move to install dir
chdir(dirname($argv[0]));
function iscli() {
function iscli()
{
if (php_sapi_name() == 'cli' && empty($_SERVER['REMOTE_ADDR'])) {
return true;
}
else {
} else {
return false;
}
}
// check if we are running through the CLI, otherwise abort

View File

@@ -24,8 +24,7 @@ if ($options['f'] === 'update') {
if ($config['update_channel'] == 'master') {
exit(1);
}
elseif ($config['update_channel'] == 'release') {
} elseif ($config['update_channel'] == 'release') {
exit(3);
}
exit(0);
@@ -54,8 +53,7 @@ if ($options['f'] === 'syslog') {
if (dbDelete('syslog', 'seq >= ? AND seq < ? AND timestamp < DATE_SUB(NOW(), INTERVAL ? DAY)', array($rows, $limit, $config['syslog_purge'])) > 0) {
$rows = $limit;
echo 'Syslog cleared for entries over '.$config['syslog_purge']." days 1000 limit\n";
}
else {
} else {
break;
}
}
@@ -145,8 +143,8 @@ if ($options['f'] === 'purgeusers') {
foreach (dbFetchRows("SELECT DISTINCT(`user`) FROM `authlog` WHERE `datetime` >= DATE_SUB(NOW(), INTERVAL ? DAY)", array($purge)) as $user) {
$users[] = $user['user'];
}
$del_users = '"'.implode('","',$users).'"';
if (dbDelete('users', "username NOT IN ($del_users)",array($del_users))) {
$del_users = '"'.implode('","', $users).'"';
if (dbDelete('users', "username NOT IN ($del_users)", array($del_users))) {
echo "Removed users that haven't logged in for $purge days";
}
}

View File

@@ -25,11 +25,9 @@ if ($argv[1]) {
$id = getidbyname($host);
if ($id) {
echo delete_device($id)."\n";
}
else {
} else {
echo "Host doesn't exist!\n";
}
}
else {
} else {
echo "Host Removal Tool\nUsage: ./delhost.php <hostname>\n";
}

View File

@@ -23,7 +23,7 @@ require 'includes/discovery/functions.inc.php';
$start = microtime(true);
$runtime_stats = array();
$sqlparams = array();
$options = getopt('h:m:i:n:d::v::a::q',array('os:','type:'));
$options = getopt('h:m:i:n:d::v::a::q', array('os:','type:'));
if (!isset($options['q'])) {
echo $config['project_name_version']." Discovery\n";
@@ -42,25 +42,20 @@ if (isset($options['h'])) {
if ($options['h'] == 'odd') {
$options['n'] = '1';
$options['i'] = '2';
}
else if ($options['h'] == 'even') {
} elseif ($options['h'] == 'even') {
$options['n'] = '0';
$options['i'] = '2';
}
else if ($options['h'] == 'all') {
} elseif ($options['h'] == 'all') {
$where = ' ';
$doing = 'all';
}
else if ($options['h'] == 'new') {
} elseif ($options['h'] == 'new') {
$where = 'AND `last_discovered` IS NULL';
$doing = 'new';
}
else if ($options['h']) {
} elseif ($options['h']) {
if (is_numeric($options['h'])) {
$where = "AND `device_id` = '".$options['h']."'";
$doing = $options['h'];
}
else {
} else {
$where = "AND `hostname` LIKE '".str_replace('*', '%', mres($options['h']))."'";
$doing = $options['h'];
}
@@ -92,8 +87,7 @@ if (isset($options['d']) || isset($options['v'])) {
ini_set('display_startup_errors', 1);
ini_set('log_errors', 1);
ini_set('error_reporting', 1);
}
else {
} else {
$debug = false;
// ini_set('display_errors', 0);
ini_set('display_startup_errors', 0);
@@ -129,7 +123,7 @@ if (!empty($config['distributed_poller_group'])) {
$where .= ' AND poller_group IN('.$config['distributed_poller_group'].')';
}
foreach (dbFetch("SELECT * FROM `devices` WHERE status = 1 AND disabled = 0 $where ORDER BY device_id DESC",$sqlparams) as $device) {
foreach (dbFetch("SELECT * FROM `devices` WHERE status = 1 AND disabled = 0 $where ORDER BY device_id DESC", $sqlparams) as $device) {
discover_device($device, $options);
}

View File

@@ -33,8 +33,7 @@ if (isset($options['l'])) {
}
echo $tbl->getTable();
}
else if ($options['l'] == 'groups') {
} elseif ($options['l'] == 'groups') {
$tbl = new Console_Table();
$tbl->setHeaders(array('ID', 'Group Name', 'Description'));
foreach (dbFetchRows('SELECT * FROM `poller_groups`') as $groups) {
@@ -43,25 +42,21 @@ if (isset($options['l'])) {
echo $tbl->getTable();
}
}
else if (isset($options['u']) && !empty($options['u'])) {
} elseif (isset($options['u']) && !empty($options['u'])) {
if (is_numeric($options['u'])) {
$db_column = 'id';
}
else {
} else {
$db_column = 'poller_name';
}
if (dbDelete('pollers', "`$db_column` = ?", array($options['u'])) >= 0) {
echo 'Poller '.$options['u']." has been removed\n";
}
}
else if (isset($options['r'])) {
} elseif (isset($options['r'])) {
if (dbInsert(array('poller_name' => $config['distributed_poller_name'], 'last_polled' => '0000-00-00 00:00:00', 'devices' => 0, 'time_taken' => 0), 'pollers') >= 0) {
echo 'Poller '.$config['distributed_poller_name']." has been registered\n";
}
}
else {
} else {
echo "-l pollers | groups List registered pollers or poller groups\n";
echo "-u <id> | <poller name> Unregister a poller\n";
echo "-r Register this install as a poller\n";

View File

@@ -49,7 +49,8 @@ foreach (dbFetchRows('SELECT * FROM `bills`') as $bill_data) {
}
function CollectData($bill_id) {
function CollectData($bill_id)
{
$port_list = dbFetchRows('SELECT * FROM `bill_ports` as P, `ports` as I, `devices` as D WHERE P.bill_id=? AND I.port_id = P.port_id AND D.device_id = I.device_id', array($bill_id));
$now = dbFetchCell('SELECT NOW()');
@@ -77,25 +78,20 @@ function CollectData($bill_id) {
if ($port_data['ifSpeed'] > 0 && (delta_to_bits($port_data['in_measurement'], $tmp_period)-delta_to_bits($port_data['last_in_measurement'], $tmp_period)) > $port_data['ifSpeed']) {
$port_data['in_delta'] = $port_data['last_in_delta'];
}
elseif ($port_data['in_measurement'] >= $port_data['last_in_measurement']) {
} elseif ($port_data['in_measurement'] >= $port_data['last_in_measurement']) {
$port_data['in_delta'] = ($port_data['in_measurement'] - $port_data['last_in_measurement']);
}
else {
} else {
$port_data['in_delta'] = $port_data['last_in_delta'];
}
if ($port_data['ifSpeed'] > 0 && (delta_to_bits($port_data['out_measurement'], $tmp_period)-delta_to_bits($port_data['last_out_measurement'], $tmp_period)) > $port_data['ifSpeed']) {
$port_data['out_delta'] = $port_data['last_out_delta'];
}
elseif ($port_data['out_measurement'] >= $port_data['last_out_measurement']) {
} elseif ($port_data['out_measurement'] >= $port_data['last_out_measurement']) {
$port_data['out_delta'] = ($port_data['out_measurement'] - $port_data['last_out_measurement']);
}
else {
} else {
$port_data['out_delta'] = $port_data['last_out_delta'];
}
}
else {
} else {
$port_data['in_delta'] = '0';
$port_data['out_delta'] = '0';
}
@@ -120,8 +116,7 @@ function CollectData($bill_id) {
$prev_out_delta = $last_data[out_delta];
$prev_timestamp = $last_data[timestamp];
$period = dbFetchCell("SELECT UNIX_TIMESTAMP(CURRENT_TIMESTAMP()) - UNIX_TIMESTAMP('".mres($prev_timestamp)."')");
}
else {
} else {
$prev_delta = '0';
$period = '0';
$prev_in_delta = '0';
@@ -136,11 +131,9 @@ function CollectData($bill_id) {
if (!empty($period) && $period < '0') {
logfile("BILLING: negative period! id:$bill_id period:$period delta:$delta in_delta:$in_delta out_delta:$out_delta");
}
else {
} else {
dbInsert(array('bill_id' => $bill_id, 'timestamp' => $now, 'period' => $period, 'delta' => $delta, 'in_delta' => $in_delta, 'out_delta' => $out_delta), 'bill_data');
}
}//end CollectData()

View File

@@ -39,21 +39,17 @@ $options = getopt('h:m:i:n:r::d::v::a::f::');
if ($options['h'] == 'odd') {
$options['n'] = '1';
$options['i'] = '2';
}
else if ($options['h'] == 'even') {
} elseif ($options['h'] == 'even') {
$options['n'] = '0';
$options['i'] = '2';
}
else if ($options['h'] == 'all') {
} elseif ($options['h'] == 'all') {
$where = ' ';
$doing = 'all';
}
else if ($options['h']) {
} elseif ($options['h']) {
if (is_numeric($options['h'])) {
$where = "AND `device_id` = '".$options['h']."'";
$doing = $options['h'];
}
else {
} else {
$where = "AND `hostname` LIKE '".str_replace('*', '%', mres($options['h']))."'";
$doing = $options['h'];
}
@@ -101,8 +97,7 @@ if (isset($options['d']) || isset($options['v'])) {
ini_set('display_startup_errors', 1);
ini_set('log_errors', 1);
ini_set('error_reporting', 1);
}
else {
} else {
$debug = false;
// ini_set('display_errors', 0);
ini_set('display_startup_errors', 0);
@@ -120,8 +115,7 @@ if (isset($options['f'])) {
if ($config['noinfluxdb'] !== true && $config['influxdb']['enable'] === true) {
$influxdb = influxdb_connect();
}
else {
} else {
$influxdb = false;
}

View File

@@ -28,16 +28,13 @@ if ($argv[1] && $argv[2]) {
$toid = getidbyname($tohost);
if ($toid) {
echo "NOT renamed. New hostname $tohost already exists.\n";
}
else {
} else {
renamehost($id, $tohost, 'console');
echo "Renamed $host\n";
}
}
else {
} else {
echo "Host doesn't exist!\n";
}
}
else {
} else {
echo "Host Rename Tool\nUsage: ./renamehost.php <old hostname> <new hostname>\n";
}

View File

@@ -20,7 +20,6 @@ while ($end == 0) {
passthru('clear');
$tbl = new Console_Table(CONSOLE_TABLE_ALIGN_RIGHT);
foreach (dbFetchRows('SELECT * FROM `devices` ORDER BY `hostname`') as $device) {
$devices['count']++;
$cache['devices']['hostname'][$device['hostname']] = $device['device_id'];
@@ -51,8 +50,7 @@ while ($end == 0) {
}
echo $tbl->getTable();
}
else if ($options['l'] == 'syslog') {
} elseif ($options['l'] == 'syslog') {
$tbl = new Console_Table();
$tbl->setHeaders(array('Date time', 'Host', 'Program', 'Message', 'Level', 'Facility'));
if (is_numeric($options['d'])) {
@@ -65,8 +63,7 @@ while ($end == 0) {
}
echo $tbl->getTable();
}
else if ($options['list'] == 'devices') {
} elseif ($options['list'] == 'devices') {
$tbl = new Console_Table();
$tbl->setHeaders(array('Device ID', 'Device Hostname'));
$query = 'SELECT device_id,hostname FROM `devices` ORDER BY hostname';
@@ -76,8 +73,7 @@ while ($end == 0) {
echo $tbl->getTable();
exit;
}
else if (isset($options['device-stats'])) {
} elseif (isset($options['device-stats'])) {
$tbl = new Console_Table();
$tbl->setHeaders(array('Port name', 'Status', 'IPv4 Address', 'Speed In', 'Speed Out', 'Packets In', 'Packets Out', 'Speed', 'Duplex', 'Type', 'MAC Address', 'MTU'));
foreach (dbFetchRows('SELECT * FROM `ports` WHERE `device_id` = ?', array($options['d'])) as $port) {
@@ -108,8 +104,7 @@ while ($end == 0) {
}//end foreach
echo $tbl->getTable();
}
else {
} else {
echo $options['list'];
echo "Usage of console-ui.php:

View File

@@ -28,7 +28,7 @@ foreach (dbFetchRows("SELECT `type` FROM `devices` WHERE `ignore` = 0 AND `disab
echo 'title = ' . $groups['type'] . PHP_EOL;
foreach (dbFetchRows("SELECT `hostname` FROM `devices` WHERE `type` = ? AND `ignore` = 0 AND `disabled` = 0", array($groups['type'])) as $devices) {
//Dot needs to be replaced, since smokeping doesn't accept it at this level
echo '++ ' . str_replace(".","_",$devices['hostname']) . PHP_EOL;
echo '++ ' . str_replace(".", "_", $devices['hostname']) . PHP_EOL;
echo 'menu = ' . $devices['hostname'] . PHP_EOL;
echo 'title = ' . $devices['hostname'] . PHP_EOL;
echo 'host = ' . $devices['hostname'] . PHP_EOL . PHP_EOL;

View File

@@ -120,7 +120,7 @@ function check_style($passthru = false, $command_only = false)
);
$cs_exclude = build_excludes('--ignore=', $cs_excludes);
$cs_cmd = "./vendor/bin/phpcs -n -p --colors --extensions=php --standard=PSR2 $cs_exclude ./html ./includes";
$cs_cmd = "./vendor/bin/phpcs -n -p --colors --extensions=php --standard=PSR2 $cs_exclude ./";
if ($command_only) {
echo $cs_cmd . PHP_EOL;

View File

File diff suppressed because it is too large Load Diff

View File

@@ -13,19 +13,16 @@ $hosts = str_replace('*', '%', mres($options['h']));
$ports = str_replace('*', '%', mres($options['p']));
if (empty($hosts) && empty($ports)) {
echo "-h <device hostname wildcard> Device(s) to match\n";
echo "-p <ifName widcard> Port(s) to match using ifName\n";
echo "\n";
}
foreach (dbFetchRows("SELECT `device_id`,`hostname` FROM `devices` WHERE `hostname` LIKE ?", array('%'.$hosts.'%')) as $device) {
echo "Found hostname " . $device['hostname'].".......\n";
foreach (dbFetchRows("SELECT `port_id`,`ifIndex`,`ifName`,`ifSpeed` FROM `ports` WHERE `ifName` LIKE ? AND `device_id` = ?", array('%'.$ports.'%',$device['device_id'])) as $port) {
echo "Tuning port " . $port['ifName'].".......\n";
$rrdfile = get_port_rrdfile_path ($device['hostname'], $port['port_id']);
rrdtool_tune('port',$rrdfile,$port['ifSpeed']);
$rrdfile = get_port_rrdfile_path($device['hostname'], $port['port_id']);
rrdtool_tune('port', $rrdfile, $port['ifSpeed']);
}
}

View File

@@ -17,7 +17,6 @@ if ($fd = @fopen($argv[1], 'r')) {
// FIXME check query success?
echo "$line \n";
}
}
else {
} else {
echo "ERROR: Could not open file \"$argv[1]\".\n";
}

View File

@@ -44,7 +44,8 @@ if ($config['autodiscovery']['snmpscan'] == false) {
exit(2);
}
function perform_snmp_scan($net) {
function perform_snmp_scan($net)
{
global $stats, $config, $debug, $vdebug;
echo 'Range: '.$net->network.'/'.$net->bitmask.PHP_EOL;
$config['snmp']['timeout'] = 1;
@@ -141,7 +142,7 @@ if (isset($opts['r'])) {
if (!is_array($config['nets'])) {
$config['nets'] = array( $config['nets'] );
}
foreach( $config['nets'] as $subnet ) {
foreach ($config['nets'] as $subnet) {
$net = Net_IPv4::parseAddress($subnet);
perform_snmp_scan($net);
}
@@ -151,4 +152,3 @@ if (isset($opts['r'])) {
echo 'Please either add a range argument with \'-r <CIDR_RANGE>\' or define $config[\'nets\'] in your config.php'.PHP_EOL;
exit(2);
}

View File

@@ -40,7 +40,6 @@ if (!$device['device_id']) {
$file = $config['install_dir'].'/includes/snmptrap/'.$entry['1'].'.inc.php';
if (is_file($file)) {
include "$file";
}
else {
} else {
echo "unknown trap ($file)";
}

View File

@@ -23,7 +23,7 @@ require_once 'includes/functions.php';
$i = "1";
$s = fopen('php://stdin','r');
$s = fopen('php://stdin', 'r');
while ($line = fgets($s)) {
#logfile($line);
list($entry['host'],$entry['facility'],$entry['priority'], $entry['level'], $entry['tag'], $entry['timestamp'], $entry['msg'], $entry['program']) = explode("||", trim($line));

View File

@@ -84,7 +84,6 @@ class RrdtoolTest extends \PHPUnit_Framework_TestCase
$cmd = rrdtool_build_command('update', '/opt/librenms/rrd/f', 'o');
$this->assertEquals('update f o --daemon server:42217', $cmd);
}
public function testBuildCommandException()
@@ -97,5 +96,4 @@ class RrdtoolTest extends \PHPUnit_Framework_TestCase
// use this file, since it is guaranteed to exist
rrdtool_build_command('create', __FILE__, 'o');
}
}

View File

@@ -32,13 +32,15 @@ class SyslogTest extends \PHPUnit_Framework_TestCase
// $SOURCEIP||$FACILITY||$PRIORITY||$LEVEL||$TAG||$YEAR-$MONTH-$DAY $HOUR:$MIN:$SEC||$MSG||$PROGRAM
// There add an IP for each OS you want to test and use that in the input file
private function fillLine($line) {
private function fillLine($line)
{
$entry = array();
list($entry['host'],$entry['facility'],$entry['priority'], $entry['level'], $entry['tag'], $entry['timestamp'], $entry['msg'], $entry['program']) = explode("||", trim($line));
return $entry;
}
private function createData($line, $resultDelta) {
private function createData($line, $resultDelta)
{
$entry = $this->fillLine($line);
$data = array();
$data['input'] = $entry;
@@ -54,7 +56,8 @@ class SyslogTest extends \PHPUnit_Framework_TestCase
* @param string $inputline The line from the syslog daemon including the ||'s
* @param array $modified of the modified fields, most likely containging the keys program and msg
*/
private function checkSyslog($inputline, $modified) {
private function checkSyslog($inputline, $modified)
{
$data = $this->createData($inputline, $modified);
$res = process_syslog($data['input'], 0);
$this->assertEquals($data['result'], $res);
@@ -126,18 +129,18 @@ class SyslogTest extends \PHPUnit_Framework_TestCase
);
// With program from syslog
$this->checkSyslog(
$this->checkSyslog(
"1.1.1.1||local7||notice||notice||bd||2016-04-04 15:18:43||Apr 4 13:18:42.670: %LINEPROTO-5-UPDOWN: Line protocol on Interface GigabitEthernet0/32, changed state to up||345735",
array('device_id'=>1, 'program'=>'%LINEPROTO-5-UPDOWN', 'msg'=>'Line protocol on Interface GigabitEthernet0/32, changed state to up')
);
// Incorrect time
$this->checkSyslog(
$this->checkSyslog(
"1.1.1.1||user||info||info||0e||2016-04-06 15:20:35||*Apr 4 21:26:41.778 UTC: %LWAPP-3-REPLAY_ERR: 1 wcm: Received replay error on slot 1, WLAN ID 1, count 1 from AP xxxx.xxxx.xxxx||",
array('device_id'=>1, 'program'=>'%LWAPP-3-REPLAY_ERR', 'msg'=>'1 wcm: Received replay error on slot 1, WLAN ID 1, count 1 from AP xxxx.xxxx.xxxx')
);
$this->checkSyslog(
$this->checkSyslog(
"1.1.1.1||user||info||info||0e||2016-04-06 15:20:35||.Apr 4 21:26:41.778 UTC: %LWAPP-3-REPLAY_ERR: 1 wcm: Received replay error on slot 1, WLAN ID 1, count 1 from AP xxxx.xxxx.xxxx||",
array('device_id'=>1, 'program'=>'%LWAPP-3-REPLAY_ERR', 'msg'=>'1 wcm: Received replay error on slot 1, WLAN ID 1, count 1 from AP xxxx.xxxx.xxxx')
);
@@ -232,4 +235,3 @@ class SyslogTest extends \PHPUnit_Framework_TestCase
);
}
}

View File

@@ -32,4 +32,3 @@ $classLoader->registerDir($install_dir . '/tests', 'LibreNMS\Tests');
require_once $install_dir . '/includes/rrdtool.inc.php';
require_once $install_dir . '/includes/syslog.php';

View File

@@ -16,7 +16,7 @@
$options = getopt('m:h::');
if (isset($options['h'])) {
echo
echo
"\n Validate setup tool
Usage: ./validate.php [-m <module>] [-h]
@@ -38,15 +38,12 @@ if (strstr(`php -ln config.php`, 'No syntax errors detected')) {
$last_lines = explode(PHP_EOL, `tail -n2 config.php`);
if (substr($first_line, 0, 5) !== '<?php') {
print_fail("config.php doesn't start with a <?php - please fix this ($first_line)");
}
else if ($last_lines[0] == '?>' && $last_lines[1] == '') {
} elseif ($last_lines[0] == '?>' && $last_lines[1] == '') {
print_fail('config.php contains a new line at the end, please remove any whitespace at the end of the file and also remove ?>');
}
else if ($last_lines[1] == '?>') {
} elseif ($last_lines[1] == '?>') {
print_warn("It looks like you have ?> at the end of config.php, it is suggested you remove this");
}
}
else {
} else {
print_fail('Syntax error in config.php');
}
@@ -61,7 +58,7 @@ require_once 'includes/defaults.inc.php';
require_once 'config.php';
// make sure install_dir is set correctly, or the next includes will fail
if(!file_exists($config['install_dir'].'/config.php')) {
if (!file_exists($config['install_dir'].'/config.php')) {
print_fail('$config[\'install_dir\'] is not set correctly. It should probably be set to: ' . getcwd());
exit;
}
@@ -79,21 +76,20 @@ $cur_sha = $versions['local_sha'];
if ($config['update_channel'] == 'master' && $cur_sha != $versions['github']['sha']) {
$commit_date = new DateTime('@'.$versions['local_date'], new DateTimeZone(date_default_timezone_get()));
print_warn("Your install is out of date: $cur_sha " . $commit_date->format('(r)'));
}
else {
} else {
echo "Commit SHA: $cur_sha\n";
}
if($versions['local_branch'] != 'master') {
if ($versions['local_branch'] != 'master') {
print_warn("Your local git branch is not master, this will prevent automatic updates.");
}
// check for modified files
$modifiedcmd = 'git diff --name-only --exit-code';
if($username === 'root') {
if ($username === 'root') {
$modifiedcmd = 'su '.$config['user'].' -c "'.$modifiedcmd.'"';
}
exec($modifiedcmd, $cmdoutput, $code);
if($code !== 0 && !empty($cmdoutput)) {
if ($code !== 0 && !empty($cmdoutput)) {
print_warn("Your local git contains modified files, this could prevent automatic updates.\nModified files:");
echo(' ' . implode("\n ", $cmdoutput) . "\n");
}
@@ -142,8 +138,7 @@ if (isset($config['user'])) {
echo "\n";
}
}
}
else {
} else {
print_warn('You don\'t have $config["user"] set, this most likely needs to be set to librenms');
}
@@ -151,14 +146,13 @@ else {
$test_db = @mysqli_connect($config['db_host'], $config['db_user'], $config['db_pass'], $config['db_name']);
if (mysqli_connect_error()) {
print_fail('Error connecting to your database '.mysqli_connect_error());
}
else {
} else {
print_ok('Database connection successful');
}
// Test for MySQL Strict mode
$strict_mode = dbFetchCell("SELECT @@global.sql_mode");
if(strstr($strict_mode, 'STRICT_TRANS_TABLES')) {
if (strstr($strict_mode, 'STRICT_TRANS_TABLES')) {
print_fail('You have MySQL STRICT_TRANS_TABLES enabled, please disable this until full support has been added: https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html');
}
@@ -229,101 +223,89 @@ if (!function_exists('openssl_random_pseudo_bytes')) {
$modules = explode(',', $options['m']);
foreach ($modules as $module) {
switch ($module) {
case 'mail':
if ($config['alert']['transports']['mail'] === true) {
$run_test = 1;
if (empty($config['alert']['default_mail'])) {
print_fail('default_mail config option needs to be specified to test email');
$run_test = 0;
}
else if ($config['email_backend'] == 'sendmail') {
if (empty($config['email_sendmail_path'])) {
print_fail("You have selected sendmail but not configured email_sendmail_path");
$run_test = 0;
}
elseif (!file_exists($config['email_sendmail_path'])) {
print_fail("The configured email_sendmail_path is not valid");
$run_test = 0;
}
}
else if ($config['email_backend'] == 'smtp') {
if (empty($config['email_smtp_host'])) {
print_fail('You have selected SMTP but not configured an SMTP host');
$run_test = 0;
}
if (empty($config['email_smtp_port'])) {
print_fail('You have selected SMTP but not configured an SMTP port');
$run_test = 0;
}
if (($config['email_smtp_auth'] === true) && (empty($config['email_smtp_username']) || empty($config['email_smtp_password']))) {
print_fail('You have selected SMTP auth but have not configured both username and password');
case 'mail':
if ($config['alert']['transports']['mail'] === true) {
$run_test = 1;
if (empty($config['alert']['default_mail'])) {
print_fail('default_mail config option needs to be specified to test email');
$run_test = 0;
} elseif ($config['email_backend'] == 'sendmail') {
if (empty($config['email_sendmail_path'])) {
print_fail("You have selected sendmail but not configured email_sendmail_path");
$run_test = 0;
} elseif (!file_exists($config['email_sendmail_path'])) {
print_fail("The configured email_sendmail_path is not valid");
$run_test = 0;
}
} elseif ($config['email_backend'] == 'smtp') {
if (empty($config['email_smtp_host'])) {
print_fail('You have selected SMTP but not configured an SMTP host');
$run_test = 0;
}
if (empty($config['email_smtp_port'])) {
print_fail('You have selected SMTP but not configured an SMTP port');
$run_test = 0;
}
if (($config['email_smtp_auth'] === true) && (empty($config['email_smtp_username']) || empty($config['email_smtp_password']))) {
print_fail('You have selected SMTP auth but have not configured both username and password');
$run_test = 0;
}
}//end if
if ($run_test == 1) {
if ($err = send_mail($config['alert']['default_mail'], 'Test email', 'Testing email from NMS')) {
print_ok('Email has been sent');
} else {
print_fail('Issue sending email to '.$config['alert']['default_mail'].' with error '.$err);
}
}
}//end if
if ($run_test == 1) {
if ($err = send_mail($config['alert']['default_mail'], 'Test email', 'Testing email from NMS')) {
print_ok('Email has been sent');
break;
case 'dist-poller':
if ($config['distributed_poller'] !== true) {
print_fail('You have not enabled distributed_poller');
} else {
if (empty($config['distributed_poller_memcached_host'])) {
print_fail('You have not configured $config[\'distributed_poller_memcached_host\']');
} elseif (empty($config['distributed_poller_memcached_port'])) {
print_fail('You have not configured $config[\'distributed_poller_memcached_port\']');
} else {
$connection = @fsockopen($config['distributed_poller_memcached_host'], $config['distributed_poller_memcached_port']);
if (!is_resource($connection)) {
print_fail('We could not get memcached stats, it is possible that we cannot connect to your memcached server, please check');
} else {
fclose($connection);
print_ok('Connection to memcached is ok');
}
}
else {
print_fail('Issue sending email to '.$config['alert']['default_mail'].' with error '.$err);
if (empty($config['rrdcached'])) {
print_fail('You have not configured $config[\'rrdcached\']');
} elseif (empty($config['rrd_dir'])) {
print_fail('You have not configured $config[\'rrd_dir\']');
} else {
check_rrdcached();
}
}
}//end if
break;
case 'dist-poller':
if ($config['distributed_poller'] !== true) {
print_fail('You have not enabled distributed_poller');
}
else {
if (empty($config['distributed_poller_memcached_host'])) {
print_fail('You have not configured $config[\'distributed_poller_memcached_host\']');
}
elseif (empty($config['distributed_poller_memcached_port'])) {
print_fail('You have not configured $config[\'distributed_poller_memcached_port\']');
}
else {
$connection = @fsockopen($config['distributed_poller_memcached_host'], $config['distributed_poller_memcached_port']);
if (!is_resource($connection)) {
print_fail('We could not get memcached stats, it is possible that we cannot connect to your memcached server, please check');
}
else {
fclose($connection);
print_ok('Connection to memcached is ok');
}
}
if (empty($config['rrdcached'])) {
print_fail('You have not configured $config[\'rrdcached\']');
}
elseif (empty($config['rrd_dir'])) {
print_fail('You have not configured $config[\'rrd_dir\']');
}
else {
check_rrdcached();
}
}
break;
case 'rrdcheck':
break;
case 'rrdcheck':
// Loop through the rrd_dir
$rrd_directory = new RecursiveDirectoryIterator($config['rrd_dir']);
// Filter out any non rrd files
$rrd_directory_filter = new LibreNMS\RRDRecursiveFilterIterator($rrd_directory);
$rrd_iterator = new RecursiveIteratorIterator($rrd_directory_filter);
$rrd_total = iterator_count($rrd_iterator);
$rrd_iterator->rewind(); // Rewind iterator in case iterator_count left iterator in unknown state
// Loop through the rrd_dir
$rrd_directory = new RecursiveDirectoryIterator($config['rrd_dir']);
// Filter out any non rrd files
$rrd_directory_filter = new LibreNMS\RRDRecursiveFilterIterator($rrd_directory);
$rrd_iterator = new RecursiveIteratorIterator($rrd_directory_filter);
$rrd_total = iterator_count($rrd_iterator);
$rrd_iterator->rewind(); // Rewind iterator in case iterator_count left iterator in unknown state
echo "\nScanning ".$rrd_total." rrd files in ".$config['rrd_dir']."...\n";
echo "\nScanning ".$rrd_total." rrd files in ".$config['rrd_dir']."...\n";
// Count loops so we can push status to the user
$loopcount = 0;
$screenpad = 0;
foreach ($rrd_iterator as $filename => $file) {
// Count loops so we can push status to the user
$loopcount = 0;
$screenpad = 0;
foreach ($rrd_iterator as $filename => $file) {
$rrd_test_result = rrdtest($filename, $output, $error);
$loopcount++;
if (($loopcount % 50) == 0 ) {
if (($loopcount % 50) == 0) {
//This lets us update the previous status update without spamming in most consoles
echo "\033[".$screenpad."D";
$test_status = 'Status: '.$loopcount.'/'.$rrd_total;
@@ -332,51 +314,53 @@ foreach ($modules as $module) {
}
// A non zero result means there was some kind of error
if ($rrd_test_result > 0) {
if ($rrd_test_result > 0) {
echo "\033[".$screenpad."D";
print_fail('Error parsing "'.$filename.'" RRD '.trim($error));
$screenpad = 0;
}
}
echo "\033[".$screenpad."D";
echo "Status: ".$loopcount."/".$rrd_total." - Complete\n";
}
echo "\033[".$screenpad."D";
echo "Status: ".$loopcount."/".$rrd_total." - Complete\n";
break;
break;
}//end switch
}//end foreach
// End
function print_ok($msg) {
function print_ok($msg)
{
echo "[OK] $msg\n";
}//end print_ok()
function print_fail($msg) {
function print_fail($msg)
{
echo "[FAIL] $msg\n";
}//end print_fail()
function print_warn($msg) {
function print_warn($msg)
{
echo "[WARN] $msg\n";
}//end print_warn()
function check_rrdcached() {
function check_rrdcached()
{
global $config;
list($host,$port) = explode(':',$config['rrdcached']);
list($host,$port) = explode(':', $config['rrdcached']);
if ($host == 'unix') {
// Using socket, check that file exists
if (!file_exists($port)) {
print_fail("$port doesn't appear to exist, rrdcached test failed");
}
}
else {
} else {
$connection = @fsockopen($host, $port);
if (is_resource($connection)) {
fclose($connection);
}
else {
} else {
print_fail('Cannot connect to rrdcached instance');
}
}