This commit is contained in:
laf
2015-07-15 20:52:43 +01:00
743 changed files with 37585 additions and 34072 deletions

View File

@ -10,17 +10,16 @@
* @subpackage cli
* @author Adam Armstrong <adama@memetic.org>
* @copyright (C) 2006 - 2012 Adam Armstrong
*
*/
chdir(dirname($argv[0]));
include("includes/defaults.inc.php");
include("config.php");
include("includes/definitions.inc.php");
include("includes/functions.php");
require 'includes/defaults.inc.php';
require 'config.php';
require 'includes/definitions.inc.php';
require 'includes/functions.php';
$options = getopt("g:f::");
$options = getopt('g:f::');
if (isset($options['g']) && $options['g'] >= 0) {
$cmd = array_shift($argv);
@ -28,7 +27,8 @@ if (isset($options['g']) && $options['g'] >= 0) {
array_shift($argv);
array_unshift($argv, $cmd);
$poller_group = $options['g'];
} elseif ($config['distributed_poller'] === TRUE) {
}
else if ($config['distributed_poller'] === true) {
$poller_group = $config['distributed_poller_group'];
}
@ -39,8 +39,7 @@ if (isset($options['f']) && $options['f'] == 0) {
$force_add = 1;
}
if (!empty($argv[1]))
{
if (!empty($argv[1])) {
$host = strtolower($argv[1]);
$community = $argv[2];
$snmpver = strtolower($argv[3]);
@ -48,186 +47,161 @@ if (!empty($argv[1]))
$port = 161;
$transport = 'udp';
if ($snmpver === "v3")
{
if ($snmpver === 'v3') {
$seclevel = $community;
// These values are the same as in defaults.inc.php
$v3 = array(
'authlevel' => "noAuthNoPriv",
'authname' => "root",
'authpass' => "",
'authalgo' => "MD5",
'cryptopass' => "",
'cryptoalgo' => "AES"
'authlevel' => 'noAuthNoPriv',
'authname' => 'root',
'authpass' => '',
'authalgo' => 'MD5',
'cryptopass' => '',
'cryptoalgo' => 'AES',
);
if ($seclevel === "nanp" or $seclevel === "any" or $seclevel === "noAuthNoPriv")
{
$v3['authlevel'] = "noAuthNoPriv";
if ($seclevel === 'nanp' or $seclevel === 'any' or $seclevel === 'noAuthNoPriv') {
$v3['authlevel'] = 'noAuthNoPriv';
$v3args = array_slice($argv, 4);
while ($arg = array_shift($v3args))
{
while ($arg = array_shift($v3args)) {
// parse all remaining args
if (is_numeric($arg))
{
if (is_numeric($arg)) {
$port = $arg;
}
elseif (preg_match ('/^(' . implode("|",$config['snmp']['transports']) . ')$/', $arg))
{
else if (preg_match('/^('.implode('|', $config['snmp']['transports']).')$/', $arg)) {
$transport = $arg;
}
else
{
else {
// should add a sanity check of chars allowed in user
$user = $arg;
}
}
if ($seclevel === "nanp")
{ array_push($config['snmp']['v3'], $v3); }
if ($seclevel === 'nanp') {
array_push($config['snmp']['v3'], $v3);
}
$device_id = addHost($host, $snmpver, $port, $transport, 0, $poller_group, $force_add);
}
elseif ($seclevel === "anp" or $seclevel === "authNoPriv")
{
$v3['authlevel'] = "authNoPriv";
else if ($seclevel === 'anp' or $seclevel === 'authNoPriv') {
$v3['authlevel'] = 'authNoPriv';
$v3args = array_slice($argv, 4);
$v3['authname'] = array_shift($v3args);
$v3['authpass'] = array_shift($v3args);
while ($arg = array_shift($v3args))
{
while ($arg = array_shift($v3args)) {
// parse all remaining args
if (is_numeric($arg))
{
if (is_numeric($arg)) {
$port = $arg;
}
elseif (preg_match ('/^(' . implode("|",$config['snmp']['transports']) . ')$/i', $arg))
{
else if (preg_match('/^('.implode('|', $config['snmp']['transports']).')$/i', $arg)) {
$transport = $arg;
}
elseif (preg_match ('/^(sha|md5)$/i', $arg))
{
else if (preg_match('/^(sha|md5)$/i', $arg)) {
$v3['authalgo'] = $arg;
} else {
echo "Invalid argument: " . $arg . "\n" ;
}
else {
echo 'Invalid argument: '.$arg."\n";
return;
}
}
array_push($config['snmp']['v3'], $v3);
$device_id = addHost($host, $snmpver, $port, $transport, 0, $poller_group, $force_add);
}
elseif ($seclevel === "ap" or $seclevel === "authPriv")
{
$v3['authlevel'] = "authPriv";
else if ($seclevel === 'ap' or $seclevel === 'authPriv') {
$v3['authlevel'] = 'authPriv';
$v3args = array_slice($argv, 4);
$v3['authname'] = array_shift($v3args);
$v3['authpass'] = array_shift($v3args);
$v3['cryptopass'] = array_shift($v3args);
while ($arg = array_shift($v3args))
{
while ($arg = array_shift($v3args)) {
// parse all remaining args
if (is_numeric($arg))
{
if (is_numeric($arg)) {
$port = $arg;
}
elseif (preg_match ('/^(' . implode("|",$config['snmp']['transports']) . ')$/i', $arg))
{
else if (preg_match('/^('.implode('|', $config['snmp']['transports']).')$/i', $arg)) {
$transport = $arg;
}
elseif (preg_match ('/^(sha|md5)$/i', $arg))
{
else if (preg_match('/^(sha|md5)$/i', $arg)) {
$v3['authalgo'] = $arg;
}
elseif (preg_match ('/^(aes|des)$/i', $arg))
{
else if (preg_match('/^(aes|des)$/i', $arg)) {
$v3['cryptoalgo'] = $arg;
} else {
echo "Invalid argument: " . $arg . "\n" ;
}
else {
echo 'Invalid argument: '.$arg."\n";
return;
}
}
}//end while
array_push($config['snmp']['v3'], $v3);
$device_id = addHost($host, $snmpver, $port, $transport, 0, $poller_group, $force_add);
}
else
{
else {
// Error or do nothing ?
}//end if
}
}
else // v1 or v2c
{
else {
$v2args = array_slice($argv, 2);
while ($arg = array_shift($v2args))
{
while ($arg = array_shift($v2args)) {
// parse all remaining args
if (is_numeric($arg))
{
if (is_numeric($arg)) {
$port = $arg;
}
elseif (preg_match ('/(' . implode("|",$config['snmp']['transports']) . ')/i', $arg))
{
else if (preg_match('/('.implode('|', $config['snmp']['transports']).')/i', $arg)) {
$transport = $arg;
}
elseif (preg_match ('/^(v1|v2c)$/i', $arg))
{
else if (preg_match('/^(v1|v2c)$/i', $arg)) {
$snmpver = $arg;
}
}
if ($community)
{
if ($community) {
$config['snmp']['community'] = array($community);
}
$device_id = addHost($host, $snmpver, $port, $transport, 0, $poller_group, $force_add);
}
}//end if
if ($snmpver)
{
if ($snmpver) {
$snmpversions[] = $snmpver;
}
else
{
$snmpversions = array('v2c', 'v3', 'v1');
else {
$snmpversions = array(
'v2c',
'v3',
'v1',
);
}
while (!$device_id && count($snmpversions))
{
while (!$device_id && count($snmpversions)) {
$snmpver = array_shift($snmpversions);
$device_id = addHost($host, $snmpver, $port, $transport, 0, $poller_group, $force_add);
}
if ($device_id)
{
if ($device_id) {
$device = device_by_id_cache($device_id);
echo("Added device ".$device['hostname']." (".$device_id.")\n");
echo 'Added device '.$device['hostname'].' ('.$device_id.")\n";
exit;
}
}
}//end if
print $console_color->convert("\n" . $config['project_name_version']." Add Host Tool
print $console_color->convert(
"\n".$config['project_name_version'].' Add Host Tool
Usage (SNMPv1/2c): ./addhost.php [-g <poller group>] [-f] <%Whostname%n> [community] [v1|v2c] [port] ['.implode('|', $config['snmp']['transports']).']
Usage (SNMPv3) : Config Defaults : ./addhost.php [-g <poller group>] [-f]<%Whostname%n> any v3 [user] [port] ['.implode('|', $config['snmp']['transports']).']
No Auth, No Priv : ./addhost.php [-g <poller group>] [-f]<%Whostname%n> nanp v3 [user] [port] ['.implode('|', $config['snmp']['transports']).']
Auth, No Priv : ./addhost.php [-g <poller group>] [-f]<%Whostname%n> anp v3 <user> <password> [md5|sha] [port] ['.implode('|', $config['snmp']['transports']).']
Auth, Priv : ./addhost.php [-g <poller group>] [-f]<%Whostname%n> ap v3 <user> <password> <enckey> [md5|sha] [aes|dsa] [port] ['.implode('|', $config['snmp']['transports']).']
Usage (SNMPv1/2c): ./addhost.php [-g <poller group>] [-f] <%Whostname%n> [community] [v1|v2c] [port] [" . implode("|",$config['snmp']['transports']) . "]
Usage (SNMPv3) : Config Defaults : ./addhost.php [-g <poller group>] [-f]<%Whostname%n> any v3 [user] [port] [" . implode("|",$config['snmp']['transports']) . "]
No Auth, No Priv : ./addhost.php [-g <poller group>] [-f]<%Whostname%n> nanp v3 [user] [port] [" . implode("|",$config['snmp']['transports']) . "]
Auth, No Priv : ./addhost.php [-g <poller group>] [-f]<%Whostname%n> anp v3 <user> <password> [md5|sha] [port] [" . implode("|",$config['snmp']['transports']) . "]
Auth, Priv : ./addhost.php [-g <poller group>] [-f]<%Whostname%n> ap v3 <user> <password> <enckey> [md5|sha] [aes|dsa] [port] [" . implode("|",$config['snmp']['transports']) . "]
-g <poller group> allows you to add a device to be pinned to a specific poller when using distributed polling. X can be any number associated with a poller group
-f forces the device to be added by skipping the icmp and snmp check against the host.
%rRemember to run discovery for the host afterwards.%n
");
?>
'
);

View File

@ -1,7 +1,7 @@
#!/usr/bin/env php
<?php
/**
/*
* Observium
*
* This file is part of Observium.
@ -15,46 +15,35 @@
chdir(dirname($argv[0]));
include("includes/defaults.inc.php");
include("config.php");
include("includes/definitions.inc.php");
include("includes/functions.php");
require("html/includes/PasswordHash.php");
require 'includes/defaults.inc.php';
require 'config.php';
require 'includes/definitions.inc.php';
require 'includes/functions.php';
require 'html/includes/PasswordHash.php';
if (file_exists('html/includes/authentication/' . $config['auth_mechanism'] . '.inc.php'))
{
include('html/includes/authentication/' . $config['auth_mechanism'] . '.inc.php');
if (file_exists('html/includes/authentication/'.$config['auth_mechanism'].'.inc.php')) {
include 'html/includes/authentication/'.$config['auth_mechanism'].'.inc.php';
}
else
{
echo("ERROR: no valid auth_mechanism defined.\n");
else {
echo "ERROR: no valid auth_mechanism defined.\n";
exit();
}
if (auth_usermanagement())
{
if (isset($argv[1]) && isset($argv[2]) && isset($argv[3]))
{
if (!user_exists($argv[1]))
{
if (adduser($argv[1],$argv[2],$argv[3],@$argv[4]))
{
echo("User ".$argv[1]." added successfully\n");
if (auth_usermanagement()) {
if (isset($argv[1]) && isset($argv[2]) && isset($argv[3])) {
if (!user_exists($argv[1])) {
if (adduser($argv[1], $argv[2], $argv[3], @$argv[4])) {
echo 'User '.$argv[1]." added successfully\n";
}
}
else
{
echo("User ".$argv[1]." already exists!\n");
else {
echo 'User '.$argv[1]." already exists!\n";
}
}
else
{
echo("Add User Tool\nUsage: ./adduser.php <username> <password> <level 1-10> [email]\n");
else {
echo "Add User Tool\nUsage: ./adduser.php <username> <password> <level 1-10> [email]\n";
}
}
else
{
echo("Auth module does not allow adding users!\n");
}
?>
else {
echo "Auth module does not allow adding users!\n";
}//end if

View File

@ -1,6 +1,7 @@
#!/usr/bin/env php
<?php
/* Copyright (C) 2014 Daniel Preussker <f0o@devilcode.org>
/*
* Copyright (C) 2014 Daniel Preussker <f0o@devilcode.org>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
@ -12,7 +13,8 @@
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. */
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Alerts Cronjob
@ -23,13 +25,13 @@
* @subpackage Alerts
*/
include_once("includes/defaults.inc.php");
include_once("config.php");
require_once 'includes/defaults.inc.php';
require_once 'config.php';
$lock = false;
if( file_exists($config['install_dir']."/.alerts.lock") ) {
if (file_exists($config['install_dir'].'/.alerts.lock')) {
$pids = explode("\n", trim(`ps -e | grep php | awk '{print $1}'`));
$lpid = trim(file_get_contents($config['install_dir']."/.alerts.lock"));
$lpid = trim(file_get_contents($config['install_dir'].'/.alerts.lock'));
if (in_array($lpid, $pids)) {
$lock = true;
}
@ -37,31 +39,33 @@ if( file_exists($config['install_dir']."/.alerts.lock") ) {
if ($lock === true) {
exit(1);
} else {
file_put_contents($config['install_dir']."/.alerts.lock", getmypid());
}
else {
file_put_contents($config['install_dir'].'/.alerts.lock', getmypid());
}
include_once($config['install_dir']."/includes/definitions.inc.php");
include_once($config['install_dir']."/includes/functions.php");
include_once($config['install_dir']."/includes/alerts.inc.php");
require_once $config['install_dir'].'/includes/definitions.inc.php';
require_once $config['install_dir'].'/includes/functions.php';
require_once $config['install_dir'].'/includes/alerts.inc.php';
if( !defined("TEST") ) {
echo "Start: ".date('r')."\r\n";
if (!defined('TEST')) {
echo 'Start: '.date('r')."\r\n";
echo "RunFollowUp():\r\n";
RunFollowUp();
echo "RunAlerts():\r\n";
RunAlerts();
echo "RunAcks():\r\n";
RunAcks();
echo "End : ".date('r')."\r\n";
echo 'End : '.date('r')."\r\n";
}
unlink($config['install_dir']."/.alerts.lock");
unlink($config['install_dir'].'/.alerts.lock');
/**
* Re-Validate Rule-Mappings
* @param int $device Device-ID
* @param int $rule Rule-ID
* @param integer $device Device-ID
* @param integer $rule Rule-ID
* @return boolean
*/
function IsRuleValid($device, $rule) {
@ -71,11 +75,15 @@ function IsRuleValid($device,$rule) {
$rulescache[$device][$chk['id']] = true;
}
}
if ($rulescache[$device][$rule] === true) {
return true;
}
return false;
}
}//end IsRuleValid()
/**
* Issue Alert-Object
@ -84,52 +92,67 @@ function IsRuleValid($device,$rule) {
*/
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" ) {
if (dbFetchCell('SELECT attrib_value FROM devices_attribs WHERE attrib_type = "disable_notify" && device_id = ?', array($alert['device_id'])) == '1') {
return true;
}
$default_tpl = "%title\r\nSeverity: %severity\r\n{if %state == 0}Time elapsed: %elapsed\r\n{/if}Timestamp: %timestamp\r\nUnique-ID: %uid\r\nRule: {if %name}%name{else}%rule{/if}\r\n{if %faults}Faults:\r\n{foreach %faults} #%key: %value.string\r\n{/foreach}{/if}Alert sent to: {foreach %contacts}%value <%key> {/foreach}"; //FIXME: Put somewhere else?
$default_tpl = "%title\r\nSeverity: %severity\r\n{if %state == 0}Time elapsed: %elapsed\r\n{/if}Timestamp: %timestamp\r\nUnique-ID: %uid\r\nRule: {if %name}%name{else}%rule{/if}\r\n{if %faults}Faults:\r\n{foreach %faults} #%key: %value.string\r\n{/foreach}{/if}Alert sent to: {foreach %contacts}%value <%key> {/foreach}";
// FIXME: Put somewhere else?
if ($config['alert']['fixed-contacts'] == false) {
$alert['details']['contacts'] = GetContacts($alert['details']['rule']);
}
$obj = DescribeAlert($alert);
if (is_array($obj)) {
$tpl = dbFetchRow("SELECT `template` FROM `alert_templates` JOIN `alert_template_map` ON `alert_template_map`.`alert_templates_id`=`alert_templates`.`id` WHERE `alert_template_map`.`alert_rule_id`=?", array($alert['rule_id']));
$tpl = dbFetchRow('SELECT `template` FROM `alert_templates` JOIN `alert_template_map` ON `alert_template_map`.`alert_templates_id`=`alert_templates`.`id` WHERE `alert_template_map`.`alert_rule_id`=?', array($alert['rule_id']));
if (isset($tpl['template'])) {
$tpl = $tpl['template'];
} else {
}
else {
$tpl = $default_tpl;
}
echo "Issuing Alert-UID #".$alert['id']."/".$alert['state'].": ";
echo 'Issuing Alert-UID #'.$alert['id'].'/'.$alert['state'].': ';
$msg = FormatAlertTpl($tpl, $obj);
$obj['msg'] = $msg;
if (!empty($config['alert']['transports'])) {
ExtTransports($obj);
}
echo "\r\n";
}
return true;
}
}//end IssueAlert()
/**
* Issue ACK notification
* @return void
*/
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'],$alert['device_id']);
$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 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['device_id'],$alert['rule_id']));
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'],
$alert['device_id'],
);
$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 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['device_id'], $alert['rule_id']));
if (empty($alert['rule']) || !IsRuleValid($tmp[1], $tmp[0])) {
// Alert-Rule does not exist anymore, let's remove the alert-state.
echo "Stale-Rule: #".$tmp[0]."/".$tmp[1]."\r\n";
echo 'Stale-Rule: #'.$tmp[0].'/'.$tmp[1]."\r\n";
dbDelete('alerts', 'rule_id = ? && device_id = ?', array($tmp[0], $tmp[1]));
continue;
}
$alert['details'] = json_decode(gzuncompress($alert['details']), true);
$alert['state'] = 2;
IssueAlert($alert);
dbUpdate(array('open' => 0), 'alerts', 'rule_id = ? && device_id = ?', array($alert['rule_id'], $alert['device_id']));
}
}
}//end RunAcks()
/**
* Run Follow-Up alerts
@ -137,41 +160,51 @@ function RunAcks() {
*/
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($alert['rule_id'],$alert['device_id']);
$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 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['device_id'],$alert['rule_id']));
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(
$alert['rule_id'],
$alert['device_id'],
);
$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 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['device_id'], $alert['rule_id']));
if (empty($alert['rule']) || !IsRuleValid($tmp[1], $tmp[0])) {
// Alert-Rule does not exist anymore, let's remove the alert-state.
echo "Stale-Rule: #".$tmp[0]."/".$tmp[1]."\r\n";
echo 'Stale-Rule: #'.$tmp[0].'/'.$tmp[1]."\r\n";
dbDelete('alerts', 'rule_id = ? && device_id = ?', array($tmp[0], $tmp[1]));
continue;
}
$alert['details'] = json_decode(gzuncompress($alert['details']), true);
$rextra = json_decode($alert['extra'], true);
if ($rextra['invert']) {
continue;
}
$chk = dbFetchRows(GenSQL($alert['rule']), array($alert['device_id']));
$o = sizeof($alert['details']['rule']);
$n = sizeof($chk);
$ret = "Alert #".$alert['id'];
$ret = 'Alert #'.$alert['id'];
$state = 0;
if ($n > $o) {
$ret .= " Worsens";
$ret .= ' Worsens';
$state = 3;
} elseif( $n < $o ) {
$ret .= " Betters";
}
else if ($n < $o) {
$ret .= ' Betters';
$state = 4;
}
if ($state > 0) {
$alert['details']['rule'] = $chk;
if (dbInsert(array('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']));
}
echo $ret." (".$o."/".$n.")\r\n";
}
}
echo $ret.' ('.$o.'/'.$n.")\r\n";
}
}//end foreach
}//end RunFollowUp()
/**
* Run all alerts
@ -179,15 +212,19 @@ function RunFollowUp() {
*/
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($alert['rule_id'],$alert['device_id']);
$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 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['device_id'],$alert['rule_id']));
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'],
$alert['device_id'],
);
$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 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['device_id'], $alert['rule_id']));
if (empty($alert['rule_id']) || !IsRuleValid($tmp[1], $tmp[0])) {
echo "Stale-Rule: #".$tmp[0]."/".$tmp[1]."\r\n";
echo 'Stale-Rule: #'.$tmp[0].'/'.$tmp[1]."\r\n";
// Alert-Rule does not exist anymore, let's remove the alert-state.
dbDelete('alerts', 'rule_id = ? && device_id = ?', array($tmp[0], $tmp[1]));
continue;
}
$alert['details'] = json_decode(gzuncompress($alert['details']), true);
$noiss = false;
$noacc = false;
@ -197,71 +234,85 @@ function RunAlerts() {
if ($chk['alerted'] == $alert['state']) {
$noiss = true;
}
if (!empty($rextra['count']) && empty($rextra['interval'])) {
// This check below is for compat-reasons
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;
}
}
if ($alert['state'] == 1 && !empty($rextra['count']) && ($rextra['count'] == -1 || $alert['details']['count']++ < $rextra['count'])) {
if ($alert['details']['count'] < $rextra['count']) {
$noacc = true;
}
$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;
}
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;
}
}
if ($alert['state'] == 1 && !empty($rextra['count']) && ($rextra['count'] == -1 || $alert['details']['count']++ < $rextra['count'])) {
if ($alert['details']['count'] < $rextra['count']) {
$noacc = true;
}
$updet = true;
$noiss = false;
}
}
}//end if
if ($chk['ignore'] == 1 || $chk['disabled'] == 1) {
$noiss = true;
$updet = false;
$noacc = false;
}
if (IsMaintenance($alert['device_id']) > 0) {
$noiss = true;
$noacc = true;
}
if ($updet) {
dbUpdate(array('details' => gzcompress(json_encode($alert['details']), 9)), 'alert_log', 'id = ?', array($alert['id']));
}
if (!empty($rextra['mute'])) {
echo "Muted Alert-UID #".$alert['id']."\r\n";
echo 'Muted Alert-UID #'.$alert['id']."\r\n";
$noiss = true;
}
if (!$noiss) {
IssueAlert($alert);
dbUpdate(array('alerted' => $alert['state']), 'alerts', 'rule_id = ? && device_id = ?', array($alert['rule_id'], $alert['device_id']));
}
if (!$noacc) {
dbUpdate(array('open' => 0), 'alerts', 'rule_id = ? && device_id = ?', array($alert['rule_id'], $alert['device_id']));
}
}
}
}//end foreach
}//end RunAlerts()
/**
* Run external transports
@ -270,24 +321,29 @@ function RunAlerts() {
*/
function ExtTransports($obj) {
global $config;
$tmp = false; //To keep scrutinizer from naging because it doesnt understand eval
$tmp = false;
// To keep scrutinizer from naging because it doesnt understand eval
foreach ($config['alert']['transports'] as $transport => $opts) {
if( ($opts === true || !empty($opts)) && $opts != false && file_exists($config['install_dir']."/includes/alerts/transport.".$transport.".php") ) {
echo $transport." => ";
eval('$tmp = function($obj,$opts) { global $config; '.file_get_contents($config['install_dir']."/includes/alerts/transport.".$transport.".php").' };');
if (($opts === true || !empty($opts)) && $opts != false && file_exists($config['install_dir'].'/includes/alerts/transport.'.$transport.'.php')) {
echo $transport.' => ';
eval('$tmp = function($obj,$opts) { global $config; '.file_get_contents($config['install_dir'].'/includes/alerts/transport.'.$transport.'.php').' };');
$tmp = $tmp($obj,$opts);
if ($tmp) {
echo "OK";
log_event("Issued ".$obj['severity']." alert for rule '".$obj['name']."' to transport '".$transport."'",$obj['device_id']);
} else {
echo "ERROR";
log_event("Could not issue ".$obj['severity']." alert for rule '".$obj['name']."' to transport '".$transport."'",$obj['device_id']);
echo 'OK';
log_event('Issued '.$obj['severity']." alert for rule '".$obj['name']."' to transport '".$transport."'", $obj['device_id']);
}
else {
echo 'ERROR';
log_event('Could not issue '.$obj['severity']." alert for rule '".$obj['name']."' to transport '".$transport."'", $obj['device_id']);
}
}
echo "; ";
}
echo '; ';
}
}//end ExtTransports()
/**
* Format Alert
* @param string $tpl Template
@ -295,51 +351,68 @@ function ExtTransports($obj) {
* @return string
*/
function FormatAlertTpl($tpl, $obj) {
$msg = '$ret .= "'.str_replace(array("{else}","{/if}","{/foreach}"),array('"; } else { $ret .= "','"; } $ret .= "','"; } $ret .= "'),addslashes($tpl)).'";';
$msg = '$ret .= "'.str_replace(array('{else}', '{/if}', '{/foreach}'), array('"; } else { $ret .= "', '"; } $ret .= "', '"; } $ret .= "'), addslashes($tpl)).'";';
$parsed = $msg;
$s = strlen($msg);
$x = $pos = -1;
$buff = "";
$buff = '';
$if = $for = false;
while (++$x < $s) {
if( $msg[$x] == "{" && $buff == "" ) {
$buff .= $msg[$x];
} elseif( $buff == "{ " ) {
$buff = "";
} elseif( $buff != "" ) {
if ($msg[$x] == '{' && $buff == '') {
$buff .= $msg[$x];
}
if( $buff == "{if" ) {
else if ($buff == '{ ') {
$buff = '';
}
else if ($buff != '') {
$buff .= $msg[$x];
}
if ($buff == '{if') {
$pos = $x;
$if = true;
} elseif( $buff == "{foreach" ) {
}
else if ($buff == '{foreach') {
$pos = $x;
$for = true;
}
if( $pos != -1 && $msg[$x] == "}" ) {
if ($pos != -1 && $msg[$x] == '}') {
$orig = $buff;
$buff = "";
$buff = '';
$pos = -1;
if ($if) {
$if = false;
$o = 3;
$native = array('"; if( ',' ) { $ret .= "');
} elseif( $for ) {
$native = array(
'"; if( ',
' ) { $ret .= "',
);
}
else if ($for) {
$for = false;
$o = 8;
$native = array('"; foreach( ',' as $key=>$value) { $ret .= "');
} else {
$native = array(
'"; foreach( ',
' as $key=>$value) { $ret .= "',
);
}
else {
continue;
}
$cond = trim(populate(substr($orig, $o, -1), false));
$native = $native[0].$cond.$native[1];
$parsed = str_replace($orig, $native, $parsed);
unset($cond, $o, $orig, $native);
}
}
}//end if
}//end while
$parsed = populate($parsed);
return RunJail($parsed, $obj);
}
}//end FormatAlertTpl()
/**
* Describe Alert
@ -349,41 +422,47 @@ function FormatAlertTpl($tpl,$obj) {
function DescribeAlert($alert) {
$obj = array();
$i = 0;
$device = dbFetchRow("SELECT hostname FROM devices WHERE device_id = ?",array($alert['device_id']));
$device = dbFetchRow('SELECT hostname FROM devices WHERE device_id = ?', array($alert['device_id']));
$obj['hostname'] = $device['hostname'];
$obj['device_id'] = $alert['device_id'];
$extra = $alert['details'];
if ($alert['state'] >= 1) {
$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 ) {
$obj['title'] .= " got worse";
} elseif( $alert['state'] == 4 ) {
$obj['title'] .= " got better";
$obj['title'] .= ' got acknowledged';
}
else if ($alert['state'] == 3) {
$obj['title'] .= ' got worse';
}
else if ($alert['state'] == 4) {
$obj['title'] .= ' got better';
}
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."; ";
$obj['faults'][$i]['string'] .= $k.' => '.$v.'; ';
}
}
}
} 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']));
}
else if ($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;
}
$extra = json_decode(gzuncompress($id['details']), true);
$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 {
return "Unknown State";
}
else {
return 'Unknown State';
}//end if
$obj['uid'] = $alert['id'];
$obj['severity'] = $alert['severity'];
$obj['rule'] = $alert['rule'];
@ -392,11 +471,13 @@ function DescribeAlert($alert) {
$obj['contacts'] = $extra['contacts'];
$obj['state'] = $alert['state'];
return $obj;
}
}//end DescribeAlert()
/**
* Format Elapsed Time
* @param int $secs Seconds elapsed
* @param integer $secs Seconds elapsed
* @return string
*/
function TimeFormat($secs) {
@ -406,7 +487,7 @@ function TimeFormat($secs){
'd' => $secs / 86400 % 7,
'h' => $secs / 3600 % 24,
'm' => $secs / 60 % 60,
's' => $secs % 60
's' => $secs % 60,
);
$ret = array();
foreach ($bit as $k => $v) {
@ -414,11 +495,15 @@ function TimeFormat($secs){
$ret[] = $v.$k;
}
}
if (empty($ret)) {
return "none";
return 'none';
}
return join(' ', $ret);
}
}//end TimeFormat()
/**
* "Safely" run eval
@ -427,15 +512,17 @@ function TimeFormat($secs){
* @return string|mixed
*/
function RunJail($code, $obj) {
$ret = "";
$ret = '';
eval($code);
return $ret;
}
}//end RunJail()
/**
* Populate variables
* @param string $txt Text with variables
* @param bool $wrap Wrap variable for text-usage (default: true)
* @param boolean $wrap Wrap variable for text-usage (default: true)
* @return string
*/
function populate($txt, $wrap=true) {
@ -443,23 +530,28 @@ function populate($txt,$wrap=true) {
foreach ($m[1] as $tmp) {
$orig = $tmp;
$rep = false;
if( $tmp == "key" || $tmp == "value" ) {
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';
}
$rep = $pre."['".str_replace('.', "']['", $tmp)."']";
if ($wrap) {
$rep = "{".$rep."}";
$rep = '{'.$rep.'}';
}
}
$txt = str_replace("%".$orig,$rep,$txt);
}
$txt = str_replace('%'.$orig, $rep, $txt);
}//end foreach
return $txt;
}
?>
}//end populate()

View File

@ -10,27 +10,27 @@
* @subpackage billing
* @author Adam Armstrong <adama@memetic.org>
* @copyright (C) 2006 - 2012 Adam Armstrong
*
*/
chdir(dirname($argv[0]));
include("includes/defaults.inc.php");
include("config.php");
include("includes/definitions.inc.php");
include("includes/functions.php");
require 'includes/defaults.inc.php';
require 'config.php';
require 'includes/definitions.inc.php';
require 'includes/functions.php';
$options = getopt("r");
$options = getopt('r');
if (isset($options['r'])) { echo("Clearing history table.\n"); dbQuery("TRUNCATE TABLE `bill_history`"); }
if (isset($options['r'])) {
echo "Clearing history table.\n";
dbQuery('TRUNCATE TABLE `bill_history`');
}
foreach (dbFetchRows("SELECT * FROM `bills` ORDER BY `bill_id`") as $bill)
{
echo(str_pad($bill['bill_id']." ".$bill['bill_name'], 30)." \n");
foreach (dbFetchRows('SELECT * FROM `bills` ORDER BY `bill_id`') as $bill) {
echo str_pad($bill['bill_id'].' '.$bill['bill_name'], 30)." \n";
$i = 0;
while ($i <= 24)
{
while ($i <= 24) {
unset($class);
unset($rate_data);
$day_data = getDates($bill['bill_day'], $i);
@ -38,46 +38,45 @@ foreach (dbFetchRows("SELECT * FROM `bills` ORDER BY `bill_id`") as $bill)
$datefrom = $day_data['0'];
$dateto = $day_data['1'];
$check = dbFetchRow("SELECT * FROM `bill_history` WHERE bill_id = ? AND bill_datefrom = ? AND bill_dateto = ? LIMIT 1", array($bill['bill_id'], $datefrom, $dateto));
$check = dbFetchRow('SELECT * FROM `bill_history` WHERE bill_id = ? AND bill_datefrom = ? AND bill_dateto = ? LIMIT 1', array($bill['bill_id'], $datefrom, $dateto));
$period = getPeriod($bill['bill_id'], $datefrom, $dateto);
$date_updated = str_replace("-", "", str_replace(":", "", str_replace(" ", "", $check['updated'])));
$date_updated = str_replace('-', '', str_replace(':', '', str_replace(' ', '', $check['updated'])));
if ($period > 0 && $dateto > $date_updated)
{
if ($period > 0 && $dateto > $date_updated) {
$rate_data = getRates($bill['bill_id'], $datefrom, $dateto);
$rate_95th = $rate_data['rate_95th'];
$dir_95th = $rate_data['dir_95th'];
$total_data = $rate_data['total_data'];
$rate_average = $rate_data['rate_average'];
if ($bill['bill_type'] == "cdr")
{
$type = "CDR";
if ($bill['bill_type'] == 'cdr') {
$type = 'CDR';
$allowed = $bill['bill_cdr'];
$used = $rate_data['rate_95th'];
$allowed_text = format_si($allowed)."bps";
$used_text = format_si($used)."bps";
$overuse = $used - $allowed;
$overuse = (($overuse <= 0) ? "0" : $overuse);
$percent = round(($rate_data['rate_95th'] / $bill['bill_cdr']) * 100,2);
} elseif ($bill['bill_type'] == "quota") {
$type = "Quota";
$allowed_text = format_si($allowed).'bps';
$used_text = format_si($used).'bps';
$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') {
$type = 'Quota';
$allowed = $bill['bill_quota'];
$used = $rate_data['total_data'];
$allowed_text = format_bytes_billing($allowed);
$used_text = format_bytes_billing($used);
$overuse = $used - $allowed;
$overuse = (($overuse <= 0) ? "0" : $overuse);
$percent = round(($rate_data['total_data'] / $bill['bill_quota']) * 100,2);
$overuse = ($used - $allowed);
$overuse = (($overuse <= 0) ? '0' : $overuse);
$percent = round((($rate_data['total_data'] / $bill['bill_quota']) * 100), 2);
}
echo(strftime("%x @ %X", strtotime($datefrom))." to ".strftime("%x @ %X", strtotime($dateto))." ".str_pad($type,8)." ".str_pad($allowed_text,10)." ".str_pad($used_text,10)." ".$percent."%");
echo strftime('%x @ %X', strtotime($datefrom)).' to '.strftime('%x @ %X', strtotime($dateto)).' '.str_pad($type, 8).' '.str_pad($allowed_text, 10).' '.str_pad($used_text, 10).' '.$percent.'%';
if ($i == '0')
{
$update = array('rate_95th' => $rate_data['rate_95th'],
if ($i == '0') {
$update = array(
'rate_95th' => $rate_data['rate_95th'],
'rate_95th_in' => $rate_data['rate_95th_in'],
'rate_95th_out' => $rate_data['rate_95th_out'],
'dir_95th' => $rate_data['dir_95th'],
@ -87,15 +86,16 @@ foreach (dbFetchRows("SELECT * FROM `bills` ORDER BY `bill_id`") as $bill)
'rate_average' => $rate_data['rate_average'],
'rate_average_in' => $rate_data['rate_average_in'],
'rate_average_out' => $rate_data['rate_average_out'],
'bill_last_calc' => array('NOW()') );
'bill_last_calc' => array('NOW()'),
);
dbUpdate($update, 'bills', '`bill_id` = ?', array($bill['bill_id']));
echo(" Updated! ");
echo ' Updated! ';
}
if ($check['bill_id'] == $bill['bill_id'])
{
$update = array('rate_95th' => $rate_data['rate_95th'],
if ($check['bill_id'] == $bill['bill_id']) {
$update = array(
'rate_95th' => $rate_data['rate_95th'],
'rate_95th_in' => $rate_data['rate_95th_in'],
'rate_95th_out' => $rate_data['rate_95th_out'],
'dir_95th' => $rate_data['dir_95th'],
@ -108,12 +108,15 @@ foreach (dbFetchRows("SELECT * FROM `bills` ORDER BY `bill_id`") as $bill)
'bill_used' => $used,
'bill_overuse' => $overuse,
'bill_percent' => $percent,
'updated' => array('NOW()'));
'updated' => array('NOW()'),
);
dbUpdate($update, 'bill_history', '`bill_hist_id` = ?', array($check['bill_hist_id']));
echo(" Updated history! ");
} else {
$update = array('rate_95th' => $rate_data['rate_95th'],
echo ' Updated history! ';
}
else {
$update = array(
'rate_95th' => $rate_data['rate_95th'],
'rate_95th_in' => $rate_data['rate_95th_in'],
'rate_95th_out' => $rate_data['rate_95th_out'],
'dir_95th' => $rate_data['dir_95th'],
@ -132,14 +135,14 @@ foreach (dbFetchRows("SELECT * FROM `bills` ORDER BY `bill_id`") as $bill)
'bill_percent' => $percent,
'bill_datefrom' => $datefrom,
'bill_dateto' => $dateto,
'bill_id' => $bill['bill_id'] );
'bill_id' => $bill['bill_id'],
);
dbInsert($update, 'bill_history');
echo(" Generated history! ");
}
echo("\n\n");
}
$i++;
}
}
echo ' Generated history! ';
}//end if
echo "\n\n";
}//end if
?>
$i++;
}//end while
}//end foreach

View File

@ -2,43 +2,40 @@
// MYSQL Check - FIXME
// 1 UNKNOWN
include( "config.php" );
require 'config.php';
if (!isset($sql_file)) {
$sql_file = 'build.sql';
}
$sql_fh = fopen($sql_file, 'r');
if ($sql_fh === FALSE) {
echo( "ERROR: Cannot open SQL build script " . $sql_file . "\n" );
if ($sql_fh === false) {
echo 'ERROR: Cannot open SQL build script '.$sql_file."\n";
exit(1);
}
$connection = mysql_connect($config['db_host'], $config['db_user'], $config['db_pass']);
if ($connection === FALSE) {
echo( "ERROR: Cannot connect to database: " . mysql_error() . "\n" );
if ($connection === false) {
echo 'ERROR: Cannot connect to database: '.mysql_error()."\n";
exit(1);
}
$select = mysql_select_db($config['db_name']);
if ($select === FALSE) {
echo( "ERROR: Cannot select database: " . mysql_error() . "\n" );
if ($select === false) {
echo 'ERROR: Cannot select database: '.mysql_error()."\n";
exit(1);
}
while (!feof($sql_fh)) {
$line = fgetss($sql_fh);
if(!empty($line))
{
if (!empty($line)) {
$creation = mysql_query($line);
if (!$creation) {
echo( "WARNING: Cannot execute query (" . $line . "): " . mysql_error() . "\n" );
echo 'WARNING: Cannot execute query ('.$line.'): '.mysql_error()."\n";
}
}
}
fclose($sql_fh);
include("includes/sql-schema/update.php");
?>
require 'includes/sql-schema/update.php';

View File

@ -14,10 +14,10 @@
$enabled = dbFetchCell("SELECT `value` FROM `callback` WHERE `name` = 'enabled'");
if ($enabled == 1) {
if (dbFetchCell("SELECT `value` FROM `callback` WHERE `name` = 'uuid'") == '') {
dbInsert(array('name' => 'uuid', 'value' => guidv4(openssl_random_pseudo_bytes(16))), 'callback');
}
$uuid = dbFetchCell("SELECT `value` FROM `callback` WHERE `name` = 'uuid'");
$queries = array(
@ -61,14 +61,19 @@ if ($enabled == 1) {
'vminfo' => 'SELECT COUNT(`id`) AS `total`,`vm_type` FROM `vminfo` GROUP BY `vm_type`',
'vmware' => 'SELECT COUNT(`id`) AS `total` FROM `vmware_vminfo`',
'vrfs' => 'SELECT COUNT(`vrf_id`) AS `total` FROM `vrfs`',
'mysql_version'=>'SELECT 1 AS `total`, @@version AS `version`',);
'mysql_version' => 'SELECT 1 AS `total`, @@version AS `version`',
);
foreach ($queries as $name => $query) {
$data = dbFetchRows($query);
$response[$name] = $data;
}
$output = array('uuid'=>$uuid,'data'=>$response);
$output = array(
'uuid' => $uuid,
'data' => $response,
);
$data = json_encode($output);
$submit = array('data' => $data);
@ -76,6 +81,7 @@ if ($enabled == 1) {
foreach ($submit as $key => $value) {
$fields .= $key.'='.$value.'&';
}
rtrim($fields, '&');
$post = curl_init();
@ -85,8 +91,8 @@ if ($enabled == 1) {
curl_setopt($post, CURLOPT_POSTFIELDS, $fields);
curl_setopt($post, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($post);
} elseif ($enabled == 2) {
}
else if ($enabled == 2) {
$uuid = dbFetchCell("SELECT `value` FROM `callback` WHERE `name` = 'uuid'");
$fields = "uuid=$uuid";
@ -100,5 +106,3 @@ if ($enabled == 1) {
dbDelete('callback', '`name`="uuid"', array());
dbUpdate(array('value' => '0'), 'callback', '`name` = "enabled"', array());
}
?>

View File

@ -12,8 +12,7 @@ $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;
}

View File

@ -1,7 +1,7 @@
#!/usr/bin/env php
<?php
/**
/*
* Observium
*
* This file is part of Observium.
@ -10,33 +10,29 @@
* @subpackage discovery
* @author Adam Armstrong <adama@memetic.org>
* @copyright (C) 2006 - 2012 Adam Armstrong
*
*/
include("includes/defaults.inc.php");
include("config.php");
include("includes/definitions.inc.php");
include("includes/functions.php");
require 'includes/defaults.inc.php';
require 'config.php';
require 'includes/definitions.inc.php';
require 'includes/functions.php';
$handle = fopen("ips.txt", "w");
$handle = fopen('ips.txt', 'w');
foreach (dbFetchRows("SELECT * FROM `ipv4_networks`") as $data)
{
foreach (dbFetchRows('SELECT * FROM `ipv4_networks`') as $data) {
$cidr = $data['ipv4_network'];
list ($network, $bits) = explode("/", $cidr);
if ($bits != '32' && $bits != '32' && $bits > '22')
{
list ($network, $bits) = explode('/', $cidr);
if ($bits != '32' && $bits != '32' && $bits > '22') {
$addr = Net_IPv4::parseAddress($cidr);
$broadcast = $addr->broadcast;
$ip = ip2long($network) + '1';
$end = ip2long($broadcast);
while ($ip < $end)
{
while ($ip < $end) {
$ipdotted = long2ip($ip);
if (dbFetchCell("SELECT COUNT(ipv4_address_id) FROM `ipv4_addresses` WHERE `ipv4_address` = ?", array($ipdotted)) == '0' && match_network($config['nets'], $ipdotted))
{
if (dbFetchCell('SELECT COUNT(ipv4_address_id) FROM `ipv4_addresses` WHERE `ipv4_address` = ?', array($ipdotted)) == '0' && match_network($config['nets'], $ipdotted)) {
fputs($handle, $ipdotted."\n");
}
$ip++;
}
}
@ -44,6 +40,4 @@ foreach (dbFetchRows("SELECT * FROM `ipv4_networks`") as $data)
fclose($handle);
shell_exec("fping -t 100 -f ips.txt > ips-scanned.txt");
?>
shell_exec('fping -t 100 -f ips.txt > ips-scanned.txt');

View File

@ -5,12 +5,12 @@
* (c) 2013 LibreNMS Contributors
*/
include('includes/defaults.inc.php');
include('config.php');
include_once("includes/definitions.inc.php");
include("includes/functions.php");
require 'includes/defaults.inc.php';
require 'config.php';
require_once 'includes/definitions.inc.php';
require 'includes/functions.php';
$options = getopt("f:");
$options = getopt('f:');
if ($options['f'] === 'update') {
echo $config['update'];
@ -18,53 +18,58 @@ if ($options['f'] === 'update') {
if ($options['f'] === 'syslog') {
if (is_numeric($config['syslog_purge'])) {
$rows = dbFetchRow("SELECT MIN(seq) FROM syslog");
while(TRUE) {
$limit = dbFetchRow("SELECT seq FROM syslog WHERE seq >= ? ORDER BY seq LIMIT 1000,1", array($rows));
$rows = dbFetchRow('SELECT MIN(seq) FROM syslog');
while (true) {
$limit = dbFetchRow('SELECT seq FROM syslog WHERE seq >= ? ORDER BY seq LIMIT 1000,1', array($rows));
if (empty($limit)) {
break;
}
if (dbDelete('syslog', "seq >= ? AND seq < ? AND timestamp < DATE_SUB(NOW(), INTERVAL ? DAY)", array($rows,$limit,$config['syslog_purge'])) > 0) {
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;
}
}
dbDelete('syslog', "seq >= ? AND timestamp < DATE_SUB(NOW(), INTERVAL ? DAY)", array($rows,$config['syslog_purge']));
dbDelete('syslog', 'seq >= ? AND timestamp < DATE_SUB(NOW(), INTERVAL ? DAY)', array($rows, $config['syslog_purge']));
}
}
if ($options['f'] === 'eventlog') {
if (is_numeric($config['eventlog_purge'])) {
if (dbDelete('eventlog', "datetime < DATE_SUB(NOW(), INTERVAL ? DAY)", array($config['eventlog_purge'])) ) {
if (dbDelete('eventlog', 'datetime < DATE_SUB(NOW(), INTERVAL ? DAY)', array($config['eventlog_purge']))) {
echo 'Eventlog cleared for entries over '.$config['eventlog_purge']." days\n";
}
}
}
if ($options['f'] === 'authlog') {
if (is_numeric($config['authlog_purge'])) {
if (dbDelete('authlog', "datetime < DATE_SUB(NOW(), INTERVAL ? DAY)", array($config['authlog_purge'])) ) {
if (dbDelete('authlog', 'datetime < DATE_SUB(NOW(), INTERVAL ? DAY)', array($config['authlog_purge']))) {
echo 'Authlog cleared for entries over '.$config['authlog_purge']." days\n";
}
}
}
if ($options['f'] === 'perf_times') {
if (is_numeric($config['perf_times_purge'])) {
if (dbDelete('perf_times', "start < UNIX_TIMESTAMP(DATE_SUB(NOW(),INTERVAL ? DAY))", array($config['perf_times_purge'])) ) {
if (dbDelete('perf_times', 'start < UNIX_TIMESTAMP(DATE_SUB(NOW(),INTERVAL ? DAY))', array($config['perf_times_purge']))) {
echo 'Performance poller times cleared for entries over '.$config['perf_times_purge']." days\n";
}
}
}
if ($options['f'] === 'callback') {
require_once "callback.php";
include_once 'callback.php';
}
if ($options['f'] === 'device_perf') {
if (is_numeric($config['device_perf_purge'])) {
if (dbDelete('device_perf', "timestamp < UNIX_TIMESTAMP(DATE_SUB(NOW(),INTERVAL ? DAY))", array($config['device_perf_purge'])) ) {
if (dbDelete('device_perf', 'timestamp < UNIX_TIMESTAMP(DATE_SUB(NOW(),INTERVAL ? DAY))', array($config['device_perf_purge']))) {
echo 'Device performance times cleared for entries over '.$config['device_perf_purge']." days\n";
}
}
}
?>

View File

@ -10,30 +10,26 @@
* @subpackage cli
* @author Adam Armstrong <adama@memetic.org>
* @copyright (C) 2006 - 2012 Adam Armstrong
*
*/
chdir(dirname($argv[0]));
include("includes/defaults.inc.php");
include("config.php");
include("includes/definitions.inc.php");
include("includes/functions.php");
require 'includes/defaults.inc.php';
require 'config.php';
require 'includes/definitions.inc.php';
require 'includes/functions.php';
# Remove a host and all related data from the system
if ($argv[1])
{
// Remove a host and all related data from the system
if ($argv[1]) {
$host = strtolower($argv[1]);
$id = getidbyname($host);
if ($id)
{
echo(delete_device($id)."\n");
} else {
echo("Host doesn't exist!\n");
if ($id) {
echo delete_device($id)."\n";
}
} else {
echo("Host Removal Tool\nUsage: ./delhost.php <hostname>\n");
else {
echo "Host doesn't exist!\n";
}
}
else {
echo "Host Removal Tool\nUsage: ./delhost.php <hostname>\n";
}
?>

View File

@ -10,129 +10,125 @@
* @subpackage discovery
* @author Adam Armstrong <adama@memetic.org>
* @copyright (C) 2006 - 2012 Adam Armstrong
*
*/
chdir(dirname($argv[0]));
include("includes/defaults.inc.php");
include("config.php");
include("includes/definitions.inc.php");
include("includes/functions.php");
include("includes/discovery/functions.inc.php");
require 'includes/defaults.inc.php';
require 'config.php';
require 'includes/definitions.inc.php';
require 'includes/functions.php';
require 'includes/discovery/functions.inc.php';
$start = utime();
$runtime_stats = array();
// Observium Device Discovery
$options = getopt('h:m:i:n:d::a::q');
$options = getopt("h:m:i:n:d::a::q");
if (!isset($options['q']))
{
echo($config['project_name_version']." Discovery\n\n");
if (!isset($options['q'])) {
echo $config['project_name_version']." Discovery\n\n";
}
if (isset($options['h']))
{
if ($options['h'] == "odd") { $options['n'] = "1"; $options['i'] = "2"; }
elseif ($options['h'] == "even") { $options['n'] = "0"; $options['i'] = "2"; }
elseif ($options['h'] == "all") { $where = " "; $doing = "all"; }
elseif ($options['h'] == "new") { $where = "AND `last_discovered` IS NULL"; $doing = "new"; }
elseif ($options['h'])
{
if (is_numeric($options['h']))
{
if (isset($options['h'])) {
if ($options['h'] == 'odd') {
$options['n'] = '1';
$options['i'] = '2';
}
else if ($options['h'] == 'even') {
$options['n'] = '0';
$options['i'] = '2';
}
else if ($options['h'] == 'all') {
$where = ' ';
$doing = 'all';
}
else if ($options['h'] == 'new') {
$where = 'AND `last_discovered` IS NULL';
$doing = 'new';
}
else if ($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'];
}
}
}//end if
}//end if
if (isset($options['i']) && $options['i'] && isset($options['n'])) {
$where = 'AND MOD(device_id,'.$options['i'].") = '".$options['n']."'";
$doing = $options['n'].'/'.$options['i'];
}
if (isset($options['i']) && $options['i'] && isset($options['n']))
{
$where = "AND MOD(device_id,".$options['i'].") = '" . $options['n'] . "'";
$doing = $options['n'] ."/".$options['i'];
}
if (isset($options['d']))
{
echo("DEBUG!\n");
$debug = TRUE;
if (isset($options['d'])) {
echo "DEBUG!\n";
$debug = true;
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
ini_set('log_errors', 1);
ini_set('error_reporting', 1);
} else {
$debug = FALSE;
# ini_set('display_errors', 0);
}
else {
$debug = false;
// ini_set('display_errors', 0);
ini_set('display_startup_errors', 0);
ini_set('log_errors', 0);
# ini_set('error_reporting', 0);
// ini_set('error_reporting', 0);
}
if (!$where)
{
echo("-h <device id> | <device hostname wildcard> Poll single device\n");
echo("-h odd Poll odd numbered devices (same as -i 2 -n 0)\n");
echo("-h even Poll even numbered devices (same as -i 2 -n 1)\n");
echo("-h all Poll all devices\n");
echo("-h new Poll all devices that have not had a discovery run before\n\n");
echo("-i <instances> -n <number> Poll as instance <number> of <instances>\n");
echo(" Instances start at 0. 0-3 for -n 4\n\n");
echo("\n");
echo("Debugging and testing options:\n");
echo("-d Enable debugging output\n");
echo("-m Specify single module to be run\n");
echo("\n");
echo("Invalid arguments!\n");
if (!$where) {
echo "-h <device id> | <device hostname wildcard> Poll single device\n";
echo "-h odd Poll odd numbered devices (same as -i 2 -n 0)\n";
echo "-h even Poll even numbered devices (same as -i 2 -n 1)\n";
echo "-h all Poll all devices\n";
echo "-h new Poll all devices that have not had a discovery run before\n\n";
echo "-i <instances> -n <number> Poll as instance <number> of <instances>\n";
echo " Instances start at 0. 0-3 for -n 4\n\n";
echo "\n";
echo "Debugging and testing options:\n";
echo "-d Enable debugging output\n";
echo "-m Specify single module to be run\n";
echo "\n";
echo "Invalid arguments!\n";
exit;
}
include("includes/sql-schema/update.php");
require 'includes/sql-schema/update.php';
$discovered_devices = 0;
if ($config['distributed_poller'] === TRUE) {
$where .= " AND poller_group IN(".$config['distributed_poller_group'].")";
if ($config['distributed_poller'] === true) {
$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") as $device)
{
foreach (dbFetch("SELECT * FROM `devices` WHERE status = 1 AND disabled = 0 $where ORDER BY device_id DESC") as $device) {
discover_device($device, $options);
}
$end = utime(); $run = $end - $start;
$end = utime();
$run = ($end - $start);
$proctime = substr($run, 0, 5);
if ($discovered_devices)
{
if ($discovered_devices) {
dbInsert(array('type' => 'discover', 'doing' => $doing, 'start' => $start, 'duration' => $proctime, 'devices' => $discovered_devices), 'perf_times');
}
$string = $argv[0]." $doing ".date($config['dateformat']['compact'])." - $discovered_devices devices discovered in $proctime secs";
if ($debug) echo("$string\n");
if($options['h'] != "new" && $config['version_check']) {
include("includes/versioncheck.inc.php");
if ($debug) {
echo "$string\n";
}
if (!isset($options['q']))
{
echo('MySQL: Cell['.($db_stats['fetchcell']+0).'/'.round($db_stats['fetchcell_sec']+0,2).'s]'.
' Row['.($db_stats['fetchrow']+0). '/'.round($db_stats['fetchrow_sec']+0,2).'s]'.
' Rows['.($db_stats['fetchrows']+0).'/'.round($db_stats['fetchrows_sec']+0,2).'s]'.
' Column['.($db_stats['fetchcol']+0). '/'.round($db_stats['fetchcol_sec']+0,2).'s]'.
' Update['.($db_stats['update']+0).'/'.round($db_stats['update_sec']+0,2).'s]'.
' Insert['.($db_stats['insert']+0). '/'.round($db_stats['insert_sec']+0,2).'s]'.
' Delete['.($db_stats['delete']+0). '/'.round($db_stats['delete_sec']+0,2).'s]');
echo("\n");
if ($options['h'] != 'new' && $config['version_check']) {
include 'includes/versioncheck.inc.php';
}
if (!isset($options['q'])) {
echo ('MySQL: Cell['.($db_stats['fetchcell'] + 0).'/'.round(($db_stats['fetchcell_sec'] + 0), 2).'s]'.' Row['.($db_stats['fetchrow'] + 0).'/'.round(($db_stats['fetchrow_sec'] + 0), 2).'s]'.' Rows['.($db_stats['fetchrows'] + 0).'/'.round(($db_stats['fetchrows_sec'] + 0), 2).'s]'.' Column['.($db_stats['fetchcol'] + 0).'/'.round(($db_stats['fetchcol_sec'] + 0), 2).'s]'.' Update['.($db_stats['update'] + 0).'/'.round(($db_stats['update_sec'] + 0), 2).'s]'.' Insert['.($db_stats['insert'] + 0).'/'.round(($db_stats['insert_sec'] + 0), 2).'s]'.' Delete['.($db_stats['delete'] + 0).'/'.round(($db_stats['delete_sec'] + 0), 2).'s]');
echo "\n";
}
logfile($string);
?>

View File

@ -15,49 +15,55 @@
chdir(dirname($argv[0]));
include("includes/defaults.inc.php");
include("config.php");
include("includes/definitions.inc.php");
include("includes/functions.php");
include("includes/polling/functions.inc.php");
include("includes/alerts.inc.php");
include('includes/console_table.php');
require 'includes/defaults.inc.php';
require 'config.php';
require 'includes/definitions.inc.php';
require 'includes/functions.php';
require 'includes/polling/functions.inc.php';
require 'includes/alerts.inc.php';
require 'includes/console_table.php';
$options = getopt("l:u:r::");
$options = getopt('l:u:r::');
if (isset($options['l'])) {
if ($options['l'] == 'pollers') {
$tbl = new Console_Table();
$tbl->setHeaders(array('ID', 'Poller Name', 'Last Polled', '# Devices', 'Poll Time'));
foreach (dbFetchRows("SELECT * FROM `pollers`") as $poller) {
foreach (dbFetchRows('SELECT * FROM `pollers`') as $poller) {
$tbl->addRow(array($poller['id'], $poller['poller_name'], $poller['last_polled'], $poller['devices'], $poller['time_taken']));
}
echo $tbl->getTable();
} elseif ($options['l'] == 'groups') {
}
else if ($options['l'] == 'groups') {
$tbl = new Console_Table();
$tbl->setHeaders(array('ID', 'Group Name', 'Description'));
foreach (dbFetchRows("SELECT * FROM `poller_groups`") as $groups) {
foreach (dbFetchRows('SELECT * FROM `poller_groups`') as $groups) {
$tbl->addRow(array($groups['id'], $groups['group_name'], $groups['descr']));
}
echo $tbl->getTable();
}
} elseif (isset($options['u']) && !empty($options['u'])) {
}
else if (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";
echo 'Poller '.$options['u']." has been removed\n";
}
} elseif (isset($options['r'])) {
}
else if (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";
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";
}
?>
}//end if

View File

@ -13,9 +13,7 @@
*/
// FUA
if (isset($_REQUEST['debug']))
{
if (isset($_REQUEST['debug'])) {
ini_set('display_errors', 1);
ini_set('display_startup_errors', 0);
ini_set('log_errors', 0);
@ -23,22 +21,20 @@ if (isset($_REQUEST['debug']))
ini_set('error_reporting', E_ALL);
}
include_once("../includes/defaults.inc.php");
include_once("../config.php");
include_once("../includes/definitions.inc.php");
include_once("includes/functions.inc.php");
include_once("../includes/functions.php");
include_once("includes/authenticate.inc.php");
require_once '../includes/defaults.inc.php';
require_once '../config.php';
require_once '../includes/definitions.inc.php';
require_once 'includes/functions.inc.php';
require_once '../includes/functions.php';
require_once 'includes/authenticate.inc.php';
if (!$_SESSION['authenticated']) { echo("unauthenticated"); exit; }
if(preg_match("/^[a-zA-Z0-9\-]+$/", $_POST['type']) == 1) {
if(file_exists('forms/'.$_POST['type'].'.inc.php'))
{
include_once('forms/'.$_POST['type'].'.inc.php');
if (!$_SESSION['authenticated']) {
echo 'unauthenticated';
exit;
}
if (preg_match('/^[a-zA-Z0-9\-]+$/', $_POST['type']) == 1) {
if (file_exists('forms/'.$_POST['type'].'.inc.php')) {
include_once 'forms/'.$_POST['type'].'.inc.php';
}
}
?>

View File

@ -9,11 +9,9 @@
* @subpackage ajax
* @author Adam Armstrong <adama@memetic.org>
* @copyright (C) 2006 - 2012 Adam Armstrong
*
*/
if (isset($_GET['debug']))
{
if (isset($_GET['debug'])) {
ini_set('display_errors', 1);
ini_set('display_startup_errors', 0);
ini_set('log_errors', 0);
@ -21,27 +19,26 @@ if (isset($_GET['debug']))
ini_set('error_reporting', E_ALL);
}
include_once("../includes/defaults.inc.php");
include_once("../config.php");
include_once("../includes/definitions.inc.php");
include_once("includes/functions.inc.php");
include_once("../includes/dbFacile.php");
include_once("../includes/common.php");
require_once '../includes/defaults.inc.php';
require_once '../config.php';
require_once '../includes/definitions.inc.php';
require_once 'includes/functions.inc.php';
require_once '../includes/dbFacile.php';
require_once '../includes/common.php';
include_once("../includes/rewrites.php");
include_once("includes/authenticate.inc.php");
require_once '../includes/rewrites.php';
require_once 'includes/authenticate.inc.php';
if (!$_SESSION['authenticated']) { echo("unauthenticated"); exit; }
if (!$_SESSION['authenticated']) {
echo 'unauthenticated';
exit;
}
if (is_numeric($_GET['device_id']))
{
foreach (dbFetch("SELECT * FROM ports WHERE device_id = ?", array($_GET['device_id'])) as $interface)
{
if (is_numeric($_GET['device_id'])) {
foreach (dbFetch('SELECT * FROM ports WHERE device_id = ?', array($_GET['device_id'])) as $interface) {
$interface = ifNameDescr($interface);
$string = mres($interface['label']." - ".$interface['ifAlias']);
echo("obj.options[obj.options.length] = new Option('".$string."','".$interface['port_id']."');\n");
#echo("obj.options[obj.options.length] = new Option('".$interface['ifDescr']." - ".$interface['ifAlias']."','".$interface['port_id']."');\n");
$string = mres($interface['label'].' - '.$interface['ifAlias']);
echo "obj.options[obj.options.length] = new Option('".$string."','".$interface['port_id']."');\n";
// echo("obj.options[obj.options.length] = new Option('".$interface['ifDescr']." - ".$interface['ifAlias']."','".$interface['port_id']."');\n");
}
}
?>

View File

@ -1,5 +1,6 @@
<?php
/* Copyright (C) 2014 Daniel Preussker <f0o@devilcode.org>
/*
* Copyright (C) 2014 Daniel Preussker <f0o@devilcode.org>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
@ -11,9 +12,10 @@
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. */
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
/*
* Rule Suggestion-AJAX
* @author Daniel Preussker <f0o@devilcode.org>
* @copyright 2014 f0o, LibreNMS
@ -23,13 +25,14 @@
session_start();
if (!isset($_SESSION['authenticated'])) {
die("Unauthorized.");
die('Unauthorized.');
}
require_once("../includes/defaults.inc.php");
require_once("../config.php");
require_once("../includes/definitions.inc.php");
require_once("../includes/functions.php");
require_once '../includes/defaults.inc.php';
require_once '../config.php';
require_once '../includes/definitions.inc.php';
require_once '../includes/functions.php';
/**
* Levenshtein Sort
@ -43,17 +46,22 @@ function levsort($base, $obj) {
$lev = levenshtein($base, $elem, 1, 10, 10);
if ($lev == 0) {
return array(array('name' => $elem));
} else {
}
else {
while (isset($ret["$lev"])) {
$lev += 0.1;
}
$ret["$lev"] = array('name' => $elem);
}
}
ksort($ret);
return $ret;
}
$obj = array(array('name' => 'Error: No suggestions found.'));
$term = array();
$current = false;
@ -61,17 +69,19 @@ if( isset($_GET['term'],$_GET['device_id']) ) {
$chk = array();
$_GET['term'] = mres($_GET['term']);
$_GET['device_id'] = mres($_GET['device_id']);
if( strstr($_GET['term'],".") ) {
$term = explode(".",$_GET['term']);
if (strstr($_GET['term'], '.')) {
$term = explode('.', $_GET['term']);
if ($config['memcached']['enable']) {
$chk = $memcache->get('rule-suggest_'.$term[0]);
}
if (!(sizeof($chk) > 0) || $chk === false) {
if( $term[0] == "macros" ) {
if ($term[0] == 'macros') {
foreach ($config['alert']['macros']['rule'] as $macro => $v) {
$chk[] = "macros.".$macro;
$chk[] = 'macros.'.$macro;
}
} else {
}
else {
$tmp = dbFetchRows('SHOW COLUMNS FROM '.$term[0]);
foreach ($tmp as $tst) {
if (isset($tst['Field'])) {
@ -80,24 +90,30 @@ if( isset($_GET['term'],$_GET['device_id']) ) {
}
}
}
$current = true;
} else {
}
else {
if ($config['memcached']['enable']) {
$chk = $memcache->get('rule-suggest-toplvl');
}
if (!(sizeof($chk) > 0) || $chk === false) {
$tmp = dbFetchRows("SELECT TABLE_NAME FROM information_schema.COLUMNS WHERE COLUMN_NAME = 'device_id'");
foreach ($tmp as $tst) {
$chk[] = $tst['TABLE_NAME'].'.';
}
$chk[] = 'macros.';
$chk[] = 'bills.';
}
}
if (sizeof($chk) > 0) {
if ($config['memcached']['enable']) {
$memcache->set('rule-suggest-'.$oterm,$chk,86400); //Cache for 24h
$memcache->set('rule-suggest-'.$oterm, $chk, 86400);
// Cache for 24h
}
$obj = levsort($_GET['term'], $chk);
$obj = array_chunk($obj, 20, true);
$obj = $obj[0];
@ -106,19 +122,25 @@ if( isset($_GET['term'],$_GET['device_id']) ) {
foreach ($obj as $fld) {
$flds[] = $fld['name'];
}
$qry = dbFetchRows("SELECT ".implode(", ",$flds)." FROM ".$term[0]." WHERE device_id = ?", array($_GET['device_id']));
$qry = dbFetchRows('SELECT '.implode(', ', $flds).' FROM '.$term[0].' WHERE device_id = ?', array($_GET['device_id']));
$ret = array();
foreach ($obj as $lev => $fld) {
list($tbl, $chk) = explode(".",$fld['name']);
list($tbl, $chk) = explode('.', $fld['name']);
$val = array();
foreach ($qry as $row) {
$val[] = $row[$chk];
}
$ret[$lev] = array('name'=>$fld['name'],'current'=>$val);
$ret[$lev] = array(
'name' => $fld['name'],
'current' => $val,
);
}
$obj = $ret;
}
}
}
die(json_encode($obj));
?>

View File

@ -1,7 +1,6 @@
<?php
if (isset($_REQUEST['debug']))
{
if (isset($_REQUEST['debug'])) {
ini_set('display_errors', 1);
ini_set('display_startup_errors', 0);
ini_set('log_errors', 0);
@ -9,79 +8,87 @@ if (isset($_REQUEST['debug']))
ini_set('error_reporting', E_ALL);
}
include_once("../includes/defaults.inc.php");
include_once("../config.php");
include_once("../includes/definitions.inc.php");
include_once("includes/functions.inc.php");
include_once("../includes/functions.php");
include_once("includes/authenticate.inc.php");
require_once '../includes/defaults.inc.php';
require_once '../config.php';
require_once '../includes/definitions.inc.php';
require_once 'includes/functions.inc.php';
require_once '../includes/functions.php';
require_once 'includes/authenticate.inc.php';
if (!$_SESSION['authenticated']) { echo("unauthenticated"); exit; }
if (!$_SESSION['authenticated']) {
echo 'unauthenticated';
exit;
}
$device = Array();
$ports = Array();
$device = array();
$ports = array();
if (isset($_REQUEST['search']))
{
if (isset($_REQUEST['search'])) {
$search = mres($_REQUEST['search']);
if (strlen($search) >0)
{
if (strlen($search) > 0) {
$found = 0;
if ($_REQUEST['type'] == 'group') {
include_once('../includes/device-groups.inc.php');
include_once '../includes/device-groups.inc.php';
foreach (dbFetchRows("SELECT id,name FROM device_groups WHERE name LIKE '%".$search."%'") as $group) {
if ($_REQUEST['map']) {
$results[] = array('name'=>'g:'.$group['name'],'group_id'=>$group['id']);
} else {
$results[] = array(
'name' => 'g:'.$group['name'],
'group_id' => $group['id'],
);
}
else {
$results[] = array('name' => $group['name']);
}
}
die(json_encode($results));
} elseif( $_REQUEST['type'] == 'alert-rules' ) {
}
else if ($_REQUEST['type'] == 'alert-rules') {
foreach (dbFetchRows("SELECT name FROM alert_rules WHERE name LIKE '%".$search."%'") as $rules) {
$results[] = array('name' => $rules['name']);
}
die(json_encode($results));
} elseif($_REQUEST['type'] == 'device') {
die(json_encode($results));
}
else if ($_REQUEST['type'] == 'device') {
// Device search
if (is_admin() === TRUE || is_read() === TRUE) {
if (is_admin() === true || is_read() === true) {
$results = dbFetchRows("SELECT * FROM `devices` WHERE `hostname` LIKE '%".$search."%' OR `location` LIKE '%".$search."%' ORDER BY hostname LIMIT 8");
} else {
}
else {
$results = dbFetchRows("SELECT * FROM `devices` AS `D`, `devices_perms` AS `P` WHERE `P`.`user_id` = ? AND `P`.`device_id` = `D`.`device_id` AND (`hostname` LIKE '%".$search."%' OR `location` LIKE '%".$search."%') ORDER BY hostname LIMIT 8", array($_SESSION['user_id']));
}
if (count($results))
{
if (count($results)) {
$found = 1;
$devices = count($results);
foreach ($results as $result)
{
foreach ($results as $result) {
$name = $result['hostname'];
if($result['disabled'] == 1)
{
if ($result['disabled'] == 1) {
$highlight_colour = '#808080';
}
elseif($result['ignored'] == 1 && $result['disabled'] == 0)
{
else if ($result['ignored'] == 1 && $result['disabled'] == 0) {
$highlight_colour = '#000000';
}
elseif($result['status'] == 0 && $result['ignore'] == 0 && $result['disabled'] == 0)
{
else if ($result['status'] == 0 && $result['ignore'] == 0 && $result['disabled'] == 0) {
$highlight_colour = '#ff0000';
}
elseif($result['status'] == 1 && $result['ignore'] == 0 && $result['disabled'] == 0)
{
else if ($result['status'] == 1 && $result['ignore'] == 0 && $result['disabled'] == 0) {
$highlight_colour = '#008000';
}
if (is_admin() === TRUE || is_read() === TRUE) {
$num_ports = dbFetchCell("SELECT COUNT(*) FROM `ports` WHERE device_id = ?", array($result['device_id']));
} else {
$num_ports = dbFetchCell("SELECT COUNT(*) FROM `ports` AS `I`, `devices` AS `D`, `devices_perms` AS `P` WHERE `P`.`user_id` = ? AND `P`.`device_id` = `D`.`device_id` AND `I`.`device_id` = `D`.`device_id` AND device_id = ?", array($_SESSION['user_id'],$result['device_id']));
if (is_admin() === true || is_read() === true) {
$num_ports = dbFetchCell('SELECT COUNT(*) FROM `ports` WHERE device_id = ?', array($result['device_id']));
}
$device[]=array('name'=>$name,
else {
$num_ports = dbFetchCell('SELECT COUNT(*) FROM `ports` AS `I`, `devices` AS `D`, `devices_perms` AS `P` WHERE `P`.`user_id` = ? AND `P`.`device_id` = `D`.`device_id` AND `I`.`device_id` = `D`.`device_id` AND device_id = ?', array($_SESSION['user_id'], $result['device_id']));
}
$device[] = array(
'name' => $name,
'device_id' => $result['device_id'],
'url' => generate_device_url($result),
'colours' => $highlight_colour,
@ -90,108 +97,107 @@ if (isset($_REQUEST['search']))
'device_hardware' => $result['hardware'],
'device_os' => $config['os'][$result['os']]['text'],
'version' => $result['version'],
'location'=>$result['location']);
}
}
'location' => $result['location'],
);
}//end foreach
}//end if
$json = json_encode($device);
print_r($json);
exit;
} elseif($_REQUEST['type'] == 'ports') {
}
else if ($_REQUEST['type'] == 'ports') {
// Search ports
if (is_admin() === TRUE || is_read() === TRUE) {
if (is_admin() === true || is_read() === true) {
$results = dbFetchRows("SELECT `ports`.*,`devices`.* FROM `ports` LEFT JOIN `devices` ON `ports`.`device_id` = `devices`.`device_id` WHERE `ifAlias` LIKE '%".$search."%' OR `ifDescr` LIKE '%".$search."%' ORDER BY ifDescr LIMIT 8");
} else {
}
else {
$results = dbFetchRows("SELECT DISTINCT(`I`.`port_id`), `I`.*, `D`.`hostname` FROM `ports` AS `I`, `devices` AS `D`, `devices_perms` AS `P`, `ports_perms` AS `PP` WHERE ((`P`.`user_id` = ? AND `P`.`device_id` = `D`.`device_id`) OR (`PP`.`user_id` = ? AND `PP`.`port_id` = `I`.`port_id` AND `I`.`device_id` = `D`.`device_id`)) AND `D`.`device_id` = `I`.`device_id` AND (`ifAlias` LIKE '%".$search."%' OR `ifDescr` LIKE '%".$search."%') ORDER BY ifDescr LIMIT 8", array($_SESSION['user_id'], $_SESSION['user_id']));
}
if (count($results))
{
if (count($results)) {
$found = 1;
foreach ($results as $result)
{
foreach ($results as $result) {
$name = $result['ifDescr'];
$description = $result['ifAlias'];
if($result['deleted'] == 0 && ($result['ignore'] == 0 || $result['ignore'] == 0) && ($result['ifInErrors_delta'] > 0 || $result['ifOutErrors_delta'] > 0))
{
if ($result['deleted'] == 0 && ($result['ignore'] == 0 || $result['ignore'] == 0) && ($result['ifInErrors_delta'] > 0 || $result['ifOutErrors_delta'] > 0)) {
// Errored ports
$port_colour = '#ffa500';
}
elseif($result['deleted'] == 0 && ($result['ignore'] == 1 || $result['ignore'] == 1))
{
else if ($result['deleted'] == 0 && ($result['ignore'] == 1 || $result['ignore'] == 1)) {
// Ignored ports
$port_colour = '#000000';
}
elseif($result['deleted'] == 0 && $result['ifAdminStatus'] == 'down' && $result['ignore'] == 0 && $result['ignore'] == 0)
{
else if ($result['deleted'] == 0 && $result['ifAdminStatus'] == 'down' && $result['ignore'] == 0 && $result['ignore'] == 0) {
// Shutdown ports
$port_colour = '#808080';
}
elseif($result['deleted'] == 0 && $result['ifOperStatus'] == 'down' && $result['ifAdminStatus'] == 'up' && $result['ignore'] == 0 && $result['ignore'] == 0)
{
else if ($result['deleted'] == 0 && $result['ifOperStatus'] == 'down' && $result['ifAdminStatus'] == 'up' && $result['ignore'] == 0 && $result['ignore'] == 0) {
// Down ports
$port_colour = '#ff0000';
}
elseif($result['deleted'] == 0 && $result['ifOperStatus'] == 'up' && $result['ignore'] == 0 && $result['ignore'] == 0)
{
else if ($result['deleted'] == 0 && $result['ifOperStatus'] == 'up' && $result['ignore'] == 0 && $result['ignore'] == 0) {
// Up ports
$port_colour = '#008000';
}
}//end if
$ports[]=array('count'=>count($results),
$ports[] = array(
'count' => count($results),
'url' => generate_port_url($result),
'name' => $name,
'description' => $description,
'colours' => $highlight_colour,
'hostname'=>$result['hostname']);
'hostname' => $result['hostname'],
);
}//end foreach
}//end if
}
}
$json = json_encode($ports);
print_r($json);
exit;
} elseif($_REQUEST['type'] == 'bgp') {
}
else if ($_REQUEST['type'] == 'bgp') {
// Search bgp peers
if (is_admin() === TRUE || is_read() === TRUE) {
if (is_admin() === true || is_read() === true) {
$results = dbFetchRows("SELECT `bgpPeers`.*,`devices`.* FROM `bgpPeers` LEFT JOIN `devices` ON `bgpPeers`.`device_id` = `devices`.`device_id` WHERE `astext` LIKE '%".$search."%' OR `bgpPeerIdentifier` LIKE '%".$search."%' OR `bgpPeerRemoteAs` LIKE '%".$search."%' ORDER BY `astext` LIMIT 8");
} else {
}
else {
$results = dbFetchRows("SELECT `bgpPeers`.*,`D`.* FROM `bgpPeers`, `devices` AS `D`, `devices_perms` AS `P` WHERE `P`.`user_id` = ? AND `P`.`device_id` = `D`.`device_id` AND `bgpPeers`.`device_id`=`D`.`device_id` AND (`astext` LIKE '%".$search."%' OR `bgpPeerIdentifier` LIKE '%".$search."%' OR `bgpPeerRemoteAs` LIKE '%".$search."%') ORDER BY `astext` LIMIT 8", array($_SESSION['user_id']));
}
if (count($results))
{
if (count($results)) {
$found = 1;
foreach ($results as $result)
{
foreach ($results as $result) {
$name = $result['bgpPeerIdentifier'];
$description = $result['astext'];
$remoteas = $result['bgpPeerRemoteAs'];
$localas = $result['bgpLocalAs'];
if($result['bgpPeerAdminStatus'] == 'start' && $result['bgpPeerState'] != 'established')
{
if ($result['bgpPeerAdminStatus'] == 'start' && $result['bgpPeerState'] != 'established') {
// Session active but errored
$port_colour = '#ffa500';
}
elseif($result['bgpPeerAdminStatus'] != 'start')
{
else if ($result['bgpPeerAdminStatus'] != 'start') {
// Session inactive
$port_colour = '#000000';
}
elseif($result['bgpPeerAdminStatus'] == 'start' && $result['bgpPeerState'] == 'established')
{
else if ($result['bgpPeerAdminStatus'] == 'start' && $result['bgpPeerState'] == 'established') {
// Session Up
$port_colour = '#008000';
}
if ($result['bgpPeerRemoteAs'] == $result['bgpLocalAs']) { $bgp_image = "images/16/brick_link.png"; } else { $bgp_image = "images/16/world_link.png"; }
if ($result['bgpPeerRemoteAs'] == $result['bgpLocalAs']) {
$bgp_image = 'images/16/brick_link.png';
}
else {
$bgp_image = 'images/16/world_link.png';
}
$bgp[]=array('count'=>count($results),
$bgp[] = array(
'count' => count($results),
'url' => generate_peer_url($result),
'name' => $name,
'description' => $description,
@ -199,14 +205,14 @@ if (isset($_REQUEST['search']))
'bgp_image' => $bgp_image,
'remoteas' => $remoteas,
'colours' => $port_colour,
'hostname'=>$result['hostname']);
'hostname' => $result['hostname'],
);
}//end foreach
}//end if
}
}
$json = json_encode($bgp);
print_r($json);
exit;
}
}
}
?>
}//end if
}//end if
}//end if

View File

@ -12,8 +12,7 @@
* the source code distribution for details.
*/
if (isset($_REQUEST['debug']))
{
if (isset($_REQUEST['debug'])) {
ini_set('display_errors', 1);
ini_set('display_startup_errors', 0);
ini_set('log_errors', 0);
@ -21,30 +20,29 @@ if (isset($_REQUEST['debug']))
ini_set('error_reporting', E_ALL);
}
include_once("../includes/defaults.inc.php");
include_once("../config.php");
include_once("../includes/definitions.inc.php");
include_once("includes/functions.inc.php");
include_once("../includes/functions.php");
include_once("includes/authenticate.inc.php");
require_once '../includes/defaults.inc.php';
require_once '../config.php';
require_once '../includes/definitions.inc.php';
require_once 'includes/functions.inc.php';
require_once '../includes/functions.php';
require_once 'includes/authenticate.inc.php';
$current = $_POST['current'];
settype($current,"integer");
settype($current, 'integer');
$rowCount = $_POST['rowCount'];
settype($rowCount,"integer");
settype($rowCount, 'integer');
if (isset($_POST['sort']) && is_array($_POST['sort'])) {
foreach ($_POST['sort'] as $k => $v) {
$sort .= " $k $v";
}
}
$searchPhrase = mres($_POST['searchPhrase']);
$id = mres($_POST['id']);
$response = array();
if (isset($id)) {
if (file_exists("includes/table/$id.inc.php")) {
require_once "includes/table/$id.inc.php";
include_once "includes/table/$id.inc.php";
}
}
?>

View File

@ -12,67 +12,111 @@
* the source code distribution for details.
*/
include_once("../includes/defaults.inc.php");
include_once("../config.php");
include_once("../includes/definitions.inc.php");
include_once("../includes/common.php");
include_once("../includes/dbFacile.php");
include_once("../includes/rewrites.php");
include_once("includes/functions.inc.php");
include_once("../includes/rrdtool.inc.php");
require_once '../includes/defaults.inc.php';
require_once '../config.php';
require_once '../includes/definitions.inc.php';
require_once '../includes/common.php';
require_once '../includes/dbFacile.php';
require_once '../includes/rewrites.php';
require_once 'includes/functions.inc.php';
require_once '../includes/rrdtool.inc.php';
require 'includes/Slim/Slim.php';
\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim();
require_once("includes/api_functions.inc.php");
require_once 'includes/api_functions.inc.php';
$app->setName('api');
$app->group('/api', function() use ($app) {
$app->group('/v0', function() use ($app) {
$app->get('/bgp', 'authToken', 'list_bgp')->name('list_bgp');//api/v0/bgp
$app->group(
'/api',
function () use ($app) {
$app->group(
'/v0',
function () use ($app) {
$app->get('/bgp', 'authToken', 'list_bgp')->name('list_bgp');
// api/v0/bgp
$app->get('/oxidized', 'authToken', 'list_oxidized')->name('list_oxidized');
$app->group('/devices', function() use ($app) {
$app->delete('/:hostname', 'authToken', 'del_device')->name('del_device');//api/v0/devices/$hostname
$app->get('/:hostname', 'authToken', 'get_device')->name('get_device');//api/v0/devices/$hostname
$app->get('/:hostname/vlans', 'authToken', 'get_vlans')->name('get_vlans');//api/v0/devices/$hostname/vlans
$app->get('/:hostname/graphs', 'authToken', 'get_graphs')->name('get_graphs');//api/v0/devices/$hostname/graphs
$app->get('/:hostname/ports', 'authToken', 'get_port_graphs')->name('get_port_graphs');//api/v0/devices/$hostname/ports
$app->get('/:hostname/:type', 'authToken', 'get_graph_generic_by_hostname')->name('get_graph_generic_by_hostname');//api/v0/devices/$hostname/$type
$app->get('/:hostname/ports/:ifname', 'authToken', 'get_port_stats_by_port_hostname')->name('get_port_stats_by_port_hostname');//api/v0/devices/$hostname/ports/$ifName
$app->get('/:hostname/ports/:ifname/:type', 'authToken', 'get_graph_by_port_hostname')->name('get_graph_by_port_hostname');//api/v0/devices/$hostname/ports/$ifName/$type
});
$app->get('/devices', 'authToken', 'list_devices')->name('list_devices');//api/v0/devices
$app->post('/devices', 'authToken', 'add_device')->name('add_device');//api/v0/devices (json data needs to be passed)
$app->group('/portgroups', function() use ($app) {
$app->get('/:group', 'authToken', 'get_graph_by_portgroup')->name('get_graph_by_portgroup');//api/v0/portgroups/$group
});
$app->group('/bills', function() use ($app) {
$app->get('/:bill_id', 'authToken', 'list_bills')->name('get_bill');//api/v0/bills/$bill_id
});
$app->get('/bills', 'authToken', 'list_bills')->name('list_bills');//api/v0/bills
$app->group(
'/devices',
function () use ($app) {
$app->delete('/:hostname', 'authToken', 'del_device')->name('del_device');
// api/v0/devices/$hostname
$app->get('/:hostname', 'authToken', 'get_device')->name('get_device');
// api/v0/devices/$hostname
$app->get('/:hostname/vlans', 'authToken', 'get_vlans')->name('get_vlans');
// api/v0/devices/$hostname/vlans
$app->get('/:hostname/graphs', 'authToken', 'get_graphs')->name('get_graphs');
// api/v0/devices/$hostname/graphs
$app->get('/:hostname/ports', 'authToken', 'get_port_graphs')->name('get_port_graphs');
// api/v0/devices/$hostname/ports
$app->get('/:hostname/:type', 'authToken', 'get_graph_generic_by_hostname')->name('get_graph_generic_by_hostname');
// api/v0/devices/$hostname/$type
$app->get('/:hostname/ports/:ifname', 'authToken', 'get_port_stats_by_port_hostname')->name('get_port_stats_by_port_hostname');
// api/v0/devices/$hostname/ports/$ifName
$app->get('/:hostname/ports/:ifname/:type', 'authToken', 'get_graph_by_port_hostname')->name('get_graph_by_port_hostname');
// api/v0/devices/$hostname/ports/$ifName/$type
}
);
$app->get('/devices', 'authToken', 'list_devices')->name('list_devices');
// api/v0/devices
$app->post('/devices', 'authToken', 'add_device')->name('add_device');
// api/v0/devices (json data needs to be passed)
$app->group(
'/portgroups',
function () use ($app) {
$app->get('/:group', 'authToken', 'get_graph_by_portgroup')->name('get_graph_by_portgroup');
// api/v0/portgroups/$group
}
);
$app->group(
'/bills',
function () use ($app) {
$app->get('/:bill_id', 'authToken', 'list_bills')->name('get_bill');
// api/v0/bills/$bill_id
}
);
$app->get('/bills', 'authToken', 'list_bills')->name('list_bills');
// api/v0/bills
// /api/v0/alerts
$app->group('/alerts', function() use ($app) {
$app->get('/:id', 'authToken', 'list_alerts')->name('get_alert');//api/v0/alerts
$app->put('/:id', 'authToken', 'ack_alert')->name('ack_alert');//api/v0/alerts/$id (PUT)
});
$app->get('/alerts', 'authToken', 'list_alerts')->name('list_alerts');//api/v0/alerts
$app->group(
'/alerts',
function () use ($app) {
$app->get('/:id', 'authToken', 'list_alerts')->name('get_alert');
// api/v0/alerts
$app->put('/:id', 'authToken', 'ack_alert')->name('ack_alert');
// api/v0/alerts/$id (PUT)
}
);
$app->get('/alerts', 'authToken', 'list_alerts')->name('list_alerts');
// api/v0/alerts
// /api/v0/rules
$app->group('/rules', function() use ($app) {
$app->get('/:id', 'authToken', 'list_alert_rules')->name('get_alert_rule');//api/v0/rules/$id
$app->delete('/:id', 'authToken', 'delete_rule')->name('delete_rule');//api/v0/rules/$id (DELETE)
});
$app->get('/rules', 'authToken', 'list_alert_rules')->name('list_alert_rules');//api/v0/rules
$app->post('/rules', 'authToken', 'add_edit_rule')->name('add_rule');//api/v0/rules (json data needs to be passed)
$app->put('/rules', 'authToken', 'add_edit_rule')->name('edit_rule');//api/v0/rules (json data needs to be passed)
$app->group(
'/rules',
function () use ($app) {
$app->get('/:id', 'authToken', 'list_alert_rules')->name('get_alert_rule');
// api/v0/rules/$id
$app->delete('/:id', 'authToken', 'delete_rule')->name('delete_rule');
// api/v0/rules/$id (DELETE)
}
);
$app->get('/rules', 'authToken', 'list_alert_rules')->name('list_alert_rules');
// api/v0/rules
$app->post('/rules', 'authToken', 'add_edit_rule')->name('add_rule');
// api/v0/rules (json data needs to be passed)
$app->put('/rules', 'authToken', 'add_edit_rule')->name('edit_rule');
// api/v0/rules (json data needs to be passed)
// Inventory section
$app->group('/inventory', function() use ($app) {
$app->group(
'/inventory',
function () use ($app) {
$app->get('/:hostname', 'authToken', 'get_inventory')->name('get_inventory');
});// End Inventory
});
$app->get('/v0', 'authToken', 'show_endpoints');//api/v0
});
}
);
// End Inventory
}
);
$app->get('/v0', 'authToken', 'show_endpoints');
// api/v0
}
);
$app->run();
?>

View File

@ -9,72 +9,77 @@
* @subpackage webinterface
* @author Adam Armstrong <adama@memetic.org>
* @copyright (C) 2006 - 2012 Adam Armstrong
*
*/
ini_set('allow_url_fopen', 0);
ini_set('display_errors', 0);
if (strpos($_SERVER['REQUEST_URI'], "debug"))
{
$debug = "1";
if (strpos($_SERVER['REQUEST_URI'], 'debug')) {
$debug = '1';
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
ini_set('log_errors', 1);
ini_set('error_reporting', E_ALL);
} else {
$debug = FALSE;
}
else {
$debug = false;
ini_set('display_errors', 0);
ini_set('display_startup_errors', 0);
ini_set('log_errors', 0);
ini_set('error_reporting', 0);
}
include("../includes/defaults.inc.php");
include("../config.php");
include("../includes/definitions.inc.php");
include("../includes/functions.php");
include("includes/functions.inc.php");
include("includes/authenticate.inc.php");
require '../includes/defaults.inc.php';
require '../config.php';
require '../includes/definitions.inc.php';
require '../includes/functions.php';
require 'includes/functions.inc.php';
require 'includes/authenticate.inc.php';
if (get_client_ip() != $_SERVER['SERVER_ADDR']) { if (!$_SESSION['authenticated']) { echo("unauthenticated"); exit; } }
require_once("includes/jpgraph/src/jpgraph.php");
require_once("includes/jpgraph/src/jpgraph_line.php");
require_once("includes/jpgraph/src/jpgraph_bar.php");
require_once("includes/jpgraph/src/jpgraph_utils.inc.php");
require_once("includes/jpgraph/src/jpgraph_date.php");
if (is_numeric($_GET['bill_id']))
{
if (get_client_ip() != $_SERVER['SERVER_ADDR'])
{
if (bill_permitted($_GET['bill_id']))
{
$bill_id = $_GET['bill_id'];
} else {
echo("Unauthorised Access Prohibited.");
if (get_client_ip() != $_SERVER['SERVER_ADDR']) {
if (!$_SESSION['authenticated']) {
echo 'unauthenticated';
exit;
}
} else {
}
require_once 'includes/jpgraph/src/jpgraph.php';
require_once 'includes/jpgraph/src/jpgraph_line.php';
require_once 'includes/jpgraph/src/jpgraph_bar.php';
require_once 'includes/jpgraph/src/jpgraph_utils.inc.php';
require_once 'includes/jpgraph/src/jpgraph_date.php';
if (is_numeric($_GET['bill_id'])) {
if (get_client_ip() != $_SERVER['SERVER_ADDR']) {
if (bill_permitted($_GET['bill_id'])) {
$bill_id = $_GET['bill_id'];
}
} else {
echo("Unauthorised Access Prohibited.");
else {
echo 'Unauthorised Access Prohibited.';
exit;
}
}
else {
$bill_id = $_GET['bill_id'];
}
}
else {
echo 'Unauthorised Access Prohibited.';
exit;
}
$start = $_GET['from'];
$end = $_GET['to'];
$xsize = (is_numeric($_GET['x']) ? $_GET['x'] : "800" );
$ysize = (is_numeric($_GET['y']) ? $_GET['y'] : "250" );
$xsize = (is_numeric($_GET['x']) ? $_GET['x'] : '800' );
$ysize = (is_numeric($_GET['y']) ? $_GET['y'] : '250' );
// $count = (is_numeric($_GET['count']) ? $_GET['count'] : "0" );
// $type = (isset($_GET['type']) ? $_GET['type'] : "date" );
// $dur = $end - $start;
// $datefrom = date('Ymthis', $start);
// $dateto = date('Ymthis', $end);
$imgtype = (isset($_GET['type']) ? $_GET['type'] : "historical" );
$imgtype = (isset($_GET['type']) ? $_GET['type'] : 'historical' );
$imgbill = (isset($_GET['imgbill']) ? $_GET['imgbill'] : false);
$yaxistitle = "Bytes";
$yaxistitle = 'Bytes';
$in_data = array();
$out_data = array();
@ -84,26 +89,24 @@ $ave_data = array();
$overuse_data = array();
$ticklabels = array();
if ($imgtype == "historical")
{
$i = "0";
if ($imgtype == 'historical') {
$i = '0';
foreach (dbFetchRows("SELECT * FROM `bill_history` WHERE `bill_id` = ? ORDER BY `bill_datefrom` DESC LIMIT 12", array($bill_id)) as $data)
{
$datefrom = strftime("%e %b %Y", strtotime($data['bill_datefrom']));
$dateto = strftime("%e %b %Y", strtotime($data['bill_dateto']));
foreach (dbFetchRows('SELECT * FROM `bill_history` WHERE `bill_id` = ? ORDER BY `bill_datefrom` DESC LIMIT 12', array($bill_id)) as $data) {
$datefrom = strftime('%e %b %Y', strtotime($data['bill_datefrom']));
$dateto = strftime('%e %b %Y', strtotime($data['bill_dateto']));
$datelabel = $datefrom."\n".$dateto;
$traf['in'] = $data['traf_in'];
$traf['out'] = $data['traf_out'];
$traf['total'] = $data['traf_total'];
if ($data['bill_type'] == "Quota")
{
if ($data['bill_type'] == 'Quota') {
$traf['allowed'] = $data['bill_allowed'];
$traf['overuse'] = $data['bill_overuse'];
} else {
$traf['allowed'] = "0";
$traf['overuse'] = "0";
}
else {
$traf['allowed'] = '0';
$traf['overuse'] = '0';
}
array_push($ticklabels, $datelabel);
@ -114,31 +117,29 @@ if ($imgtype == "historical")
array_push($overuse_data, $traf['overuse']);
$i++;
// print_r($data);
}//end foreach
if ($i < 12) {
$y = (12 - $i);
for ($x = 0; $x < $y; $x++) {
$allowed = (($x == '0') ? $traf['allowed'] : '0' );
array_push($in_data, '0');
array_push($out_data, '0');
array_push($tot_data, '0');
array_push($allow_data, $allowed);
array_push($overuse_data, '0');
array_push($ticklabels, '');
}
}
if ($i < 12)
{
$y = 12 - $i;
for ($x=0;$x<$y;$x++)
{
$allowed = (($x == "0") ? $traf['allowed'] : "0" );
array_push($in_data, "0");
array_push($out_data, "0");
array_push($tot_data, "0");
array_push($allow_data, $allowed);
array_push($overuse_data, "0");
array_push($ticklabels, "");
$yaxistitle = 'Gigabytes';
$graph_name = 'Historical bandwidth over the last 12 billing periods';
}
}
$yaxistitle = "Gigabytes";
$graph_name = "Historical bandwidth over the last 12 billing periods";
} else {
else {
$data = array();
$average = 0;
if ($imgtype == "day")
{
foreach (dbFetch("SELECT DISTINCT UNIX_TIMESTAMP(timestamp) as timestamp, SUM(delta) as traf_total, SUM(in_delta) as traf_in, SUM(out_delta) as traf_out FROM bill_data WHERE `bill_id` = ? AND `timestamp` >= FROM_UNIXTIME(?) AND `timestamp` <= FROM_UNIXTIME(?) GROUP BY DATE(timestamp) ORDER BY timestamp ASC", array($bill_id, $start, $end)) as $data)
{
if ($imgtype == 'day') {
foreach (dbFetch('SELECT DISTINCT UNIX_TIMESTAMP(timestamp) as timestamp, SUM(delta) as traf_total, SUM(in_delta) as traf_in, SUM(out_delta) as traf_out FROM bill_data WHERE `bill_id` = ? AND `timestamp` >= FROM_UNIXTIME(?) AND `timestamp` <= FROM_UNIXTIME(?) GROUP BY DATE(timestamp) ORDER BY timestamp ASC', array($bill_id, $start, $end)) as $data) {
$traf['in'] = (isset($data['traf_in']) ? $data['traf_in'] : 0);
$traf['out'] = (isset($data['traf_out']) ? $data['traf_out'] : 0);
$traf['total'] = (isset($data['traf_total']) ? $data['traf_total'] : 0);
@ -149,59 +150,57 @@ if ($imgtype == "historical")
array_push($tot_data, $traf['total']);
$average += $data['traf_total'];
}
$ave_count = count($tot_data);
if ($imgbill != false)
{
$days = strftime("%e", date($end - $start)) - $ave_count - 1;
for ($x=0;$x<$days;$x++)
{
array_push($ticklabels, "");
if ($imgbill != false) {
$days = (strftime('%e', date($end - $start)) - $ave_count - 1);
for ($x = 0; $x < $days; $x++) {
array_push($ticklabels, '');
array_push($in_data, 0);
array_push($out_data, 0);
array_push($tot_data, 0);
}
}
} elseif ($imgtype == "hour")
{
foreach (dbFetch("SELECT DISTINCT UNIX_TIMESTAMP(timestamp) as timestamp, SUM(delta) as traf_total, SUM(in_delta) as traf_in, SUM(out_delta) as traf_out FROM bill_data WHERE `bill_id` = ? AND `timestamp` >= FROM_UNIXTIME(?) AND `timestamp` <= FROM_UNIXTIME(?) GROUP BY HOUR(timestamp) ORDER BY timestamp ASC", array($bill_id, $start, $end)) as $data)
{
}
else if ($imgtype == 'hour') {
foreach (dbFetch('SELECT DISTINCT UNIX_TIMESTAMP(timestamp) as timestamp, SUM(delta) as traf_total, SUM(in_delta) as traf_in, SUM(out_delta) as traf_out FROM bill_data WHERE `bill_id` = ? AND `timestamp` >= FROM_UNIXTIME(?) AND `timestamp` <= FROM_UNIXTIME(?) GROUP BY HOUR(timestamp) ORDER BY timestamp ASC', array($bill_id, $start, $end)) as $data) {
$traf['in'] = (isset($data['traf_in']) ? $data['traf_in'] : 0);
$traf['out'] = (isset($data['traf_out']) ? $data['traf_out'] : 0);
$traf['total'] = (isset($data['traf_total']) ? $data['traf_total'] : 0);
$datelabel = strftime("%H:%M", $data['timestamp']);
$datelabel = strftime('%H:%M', $data['timestamp']);
array_push($ticklabels, $datelabel);
array_push($in_data, $traf['in']);
array_push($out_data, $traf['out']);
array_push($tot_data, $traf['total']);
$average += $data['traf_total'];
}
$ave_count = count($tot_data);
}
}//end if
$decimal = 0;
$average = $average / $ave_count;
for ($x=0;$x<=count($tot_data);$x++)
{
$average = ($average / $ave_count);
for ($x = 0; $x <= count($tot_data); $x++) {
array_push($ave_data, $average);
}
$graph_name = date('M j g:ia', $start)." - ".date('M j g:ia', $end);
}
$graph_name = date('M j g:ia', $start).' - '.date('M j g:ia', $end);
}//end if
// Create the graph. These two calls are always required
$graph = new Graph($xsize, $ysize, $graph_name);
$graph->img->SetImgFormat("png");
$graph->img->SetImgFormat('png');
#$graph->SetScale("textlin",0,0,$start,$end);
$graph->SetScale("textlin");
#$graph->title->Set("$graph_name");
// $graph->SetScale("textlin",0,0,$start,$end);
$graph->SetScale('textlin');
// $graph->title->Set("$graph_name");
$graph->title->SetFont(FF_FONT2, FS_BOLD, 10);
$graph->SetMarginColor("white");
$graph->SetMarginColor('white');
$graph->SetFrame(false);
$graph->SetMargin("75", "30", "30", "65");
$graph->SetMargin('75', '30', '30', '65');
$graph->legend->SetFont(FF_FONT1, FS_NORMAL);
$graph->legend->SetLayout(LEGEND_HOR);
$graph->legend->Pos("0.52", "0.91", "center");
$graph->legend->Pos('0.52', '0.91', 'center');
$graph->xaxis->SetFont(FF_FONT1, FS_BOLD);
$graph->xaxis->SetPos('min');
@ -213,58 +212,56 @@ $graph->xgrid->SetColor('#e0e0e0','#efefef');
$graph->yaxis->SetFont(FF_FONT1);
$graph->yaxis->SetTitleMargin(50);
$graph->yaxis->title->SetFont(FF_FONT1, FS_NORMAL, 10);
$graph->yaxis->title->Set("Bytes Transferred");
$graph->yaxis->title->Set('Bytes Transferred');
$graph->yaxis->SetLabelFormatCallback('format_bytes_billing');
$graph->ygrid->SetFill(true, '#EFEFEF@0.5', '#FFFFFF@0.5');
// Create the bar plots
$barplot_tot = new BarPlot($tot_data);
$barplot_tot->SetLegend("Traffic total");
$barplot_tot->SetLegend('Traffic total');
$barplot_tot->SetColor('darkgray');
$barplot_tot->SetFillColor('lightgray@0.4');
$barplot_tot->value->Show();
$barplot_tot->value->SetFormatCallback('format_bytes_billing_short');
$barplot_in = new BarPlot($in_data);
$barplot_in->SetLegend("Traffic In");
$barplot_in->SetLegend('Traffic In');
$barplot_in->SetColor('darkgreen');
$barplot_in->SetFillColor('lightgreen@0.4');
$barplot_in->SetWeight(1);
$barplot_out = new BarPlot($out_data);
$barplot_out->SetLegend("Traffic Out");
$barplot_out->SetLegend('Traffic Out');
$barplot_out->SetColor('darkblue');
$barplot_out->SetFillColor('lightblue@0.4');
$barplot_out->SetWeight(1);
if ($imgtype == "historical")
{
if ($imgtype == 'historical') {
$barplot_over = new BarPlot($overuse_data);
$barplot_over->SetLegend("Traffic Overusage");
$barplot_over->SetLegend('Traffic Overusage');
$barplot_over->SetColor('darkred');
$barplot_over->SetFillColor('lightred@0.4');
$barplot_over->SetWeight(1);
$lineplot_allow = new LinePlot($allow_data);
$lineplot_allow->SetLegend("Traffic Allowed");
$lineplot_allow->SetLegend('Traffic Allowed');
$lineplot_allow->SetColor('black');
$lineplot_allow->SetWeight(1);
$gbplot = new GroupBarPlot(array($barplot_in, $barplot_tot, $barplot_out, $barplot_over));
} else {
}
else {
$lineplot_allow = new LinePlot($ave_data);
// $lineplot_allow->SetLegend("Average per ".$imgtype);
$lineplot_allow->SetLegend("Average");
$lineplot_allow->SetLegend('Average');
$lineplot_allow->SetColor('black');
$lineplot_allow->SetWeight(1);
$gbplot = new GroupBarPlot(array($barplot_in, $barplot_tot, $barplot_out));
}
}//end if
$graph->Add($gbplot);
$graph->Add($lineplot_allow);
// Display the graph
$graph->Stroke();
?>

View File

@ -1,6 +1,6 @@
<?php
/**
/*
* Observium
*
* This file is part of Observium.
@ -9,56 +9,61 @@
* @subpackage billing
* @author Adam Armstrong <adama@memetic.org>
* @copyright (C) 2006 - 2012 Adam Armstrong
*
*/
ini_set('allow_url_fopen', 0);
ini_set('display_errors', 0);
if (strpos($_SERVER['REQUEST_URI'], "debug"))
{
$debug = "1";
if (strpos($_SERVER['REQUEST_URI'], 'debug')) {
$debug = '1';
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
ini_set('log_errors', 1);
ini_set('error_reporting', E_ALL);
} else {
$debug = FALSE;
}
else {
$debug = false;
ini_set('display_errors', 0);
ini_set('display_startup_errors', 0);
ini_set('log_errors', 0);
ini_set('error_reporting', 0);
}
include("../includes/defaults.inc.php");
include("../config.php");
include("../includes/definitions.inc.php");
include("../includes/functions.php");
include("includes/functions.inc.php");
include("includes/authenticate.inc.php");
require '../includes/defaults.inc.php';
require '../config.php';
require '../includes/definitions.inc.php';
require '../includes/functions.php';
require 'includes/functions.inc.php';
require 'includes/authenticate.inc.php';
if (get_client_ip() != $_SERVER['SERVER_ADDR']) { if (!$_SESSION['authenticated']) { echo("unauthenticated"); exit; } }
require("includes/jpgraph/src/jpgraph.php");
include("includes/jpgraph/src/jpgraph_line.php");
include("includes/jpgraph/src/jpgraph_utils.inc.php");
include("includes/jpgraph/src/jpgraph_date.php");
if (is_numeric($_GET['bill_id']))
{
if (get_client_ip() != $_SERVER['SERVER_ADDR'])
{
if (bill_permitted($_GET['bill_id']))
{
$bill_id = $_GET['bill_id'];
} else {
echo("Unauthorised Access Prohibited.");
if (get_client_ip() != $_SERVER['SERVER_ADDR']) {
if (!$_SESSION['authenticated']) {
echo 'unauthenticated';
exit;
}
} else {
}
require 'includes/jpgraph/src/jpgraph.php';
require 'includes/jpgraph/src/jpgraph_line.php';
require 'includes/jpgraph/src/jpgraph_utils.inc.php';
require 'includes/jpgraph/src/jpgraph_date.php';
if (is_numeric($_GET['bill_id'])) {
if (get_client_ip() != $_SERVER['SERVER_ADDR']) {
if (bill_permitted($_GET['bill_id'])) {
$bill_id = $_GET['bill_id'];
}
} else {
echo("Unauthorised Access Prohibited.");
else {
echo 'Unauthorised Access Prohibited.';
exit;
}
}
else {
$bill_id = $_GET['bill_id'];
}
}
else {
echo 'Unauthorised Access Prohibited.';
exit;
}
@ -67,50 +72,57 @@ $end = $_GET[to];
$xsize = $_GET[x];
$ysize = $_GET[y];
$count = $_GET[count];
$count = $count + 0;
$count = ($count + 0);
$iter = 1;
if ($_GET[type]) { $type = $_GET[type]; } else { $type = "date"; }
if ($_GET[type]) {
$type = $_GET[type];
}
else {
$type = 'date';
}
$dur = $end - $start;
$dur = ($end - $start);
$datefrom = date('Ymthis', $start);
$dateto = date('Ymthis', $end);
#$rate_data = getRates($bill_id,$datefrom,$dateto);
$rate_data = dbFetchRow("SELECT * from `bills` WHERE `bill_id`= ? LIMIT 1", array($bill_id));
// $rate_data = getRates($bill_id,$datefrom,$dateto);
$rate_data = dbFetchRow('SELECT * from `bills` WHERE `bill_id`= ? LIMIT 1', array($bill_id));
$rate_95th = $rate_data['rate_95th'];
$rate_average = $rate_data['rate_average'];
#$bi_a = dbFetchRow("SELECT * FROM bills WHERE bill_id = ?", array($bill_id));
#$bill_name = $bi_a['bill_name'];
// $bi_a = dbFetchRow("SELECT * FROM bills WHERE bill_id = ?", array($bill_id));
// $bill_name = $bi_a['bill_name'];
$bill_name = $rate_data['bill_name'];
$dur = $end - $start;
$dur = ($end - $start);
$counttot = dbFetchCell("SELECT count(`delta`) FROM `bill_data` WHERE `bill_id` = ? AND `timestamp` >= FROM_UNIXTIME( ? ) AND `timestamp` <= FROM_UNIXTIME( ? )", array($bill_id, $start, $end));
$counttot = dbFetchCell('SELECT count(`delta`) FROM `bill_data` WHERE `bill_id` = ? AND `timestamp` >= FROM_UNIXTIME( ? ) AND `timestamp` <= FROM_UNIXTIME( ? )', array($bill_id, $start, $end));
$count = round($dur / 300 / (($ysize - 100) * 3), 0);
if ($count <= 1) { $count = 2; }
#$count = round($counttot / 260, 0);
#if ($count <= 1) { $count = 2; }
#$max = dbFetchCell("SELECT delta FROM bill_data WHERE bill_id = ? AND `timestamp` >= FROM_UNIXTIME( ? ) AND `timestamp` <= FROM_UNIXTIME( ? ) ORDER BY delta DESC LIMIT 0,1", array($bill_id, $start, $end));
#if ($max > 1000000) { $div = "1000000"; $yaxis = "Mbit/sec"; } else { $div = "1000"; $yaxis = "Kbit/sec"; }
$count = round(($dur / 300 / (($ysize - 100) * 3)), 0);
if ($count <= 1) {
$count = 2;
}
// $count = round($counttot / 260, 0);
// if ($count <= 1) { $count = 2; }
// $max = dbFetchCell("SELECT delta FROM bill_data WHERE bill_id = ? AND `timestamp` >= FROM_UNIXTIME( ? ) AND `timestamp` <= FROM_UNIXTIME( ? ) ORDER BY delta DESC LIMIT 0,1", array($bill_id, $start, $end));
// if ($max > 1000000) { $div = "1000000"; $yaxis = "Mbit/sec"; } else { $div = "1000"; $yaxis = "Kbit/sec"; }
$i = '0';
foreach (dbFetch("SELECT *, UNIX_TIMESTAMP(timestamp) AS formatted_date FROM bill_data WHERE bill_id = ? AND `timestamp` >= FROM_UNIXTIME( ? ) AND `timestamp` <= FROM_UNIXTIME( ? ) ORDER BY timestamp ASC", array($bill_id, $start, $end)) as $row)
{
foreach (dbFetch('SELECT *, UNIX_TIMESTAMP(timestamp) AS formatted_date FROM bill_data WHERE bill_id = ? AND `timestamp` >= FROM_UNIXTIME( ? ) AND `timestamp` <= FROM_UNIXTIME( ? ) ORDER BY timestamp ASC', array($bill_id, $start, $end)) as $row) {
@$timestamp = $row['formatted_date'];
if (!$first) { $first = $timestamp; }
if (!$first) {
$first = $timestamp;
}
$delta = $row['delta'];
$period = $row['period'];
$in_delta = $row['in_delta'];
$out_delta = $row['out_delta'];
$in_value = round($in_delta * 8 / $period, 2);
$out_value = round($out_delta * 8 / $period, 2);
$in_value = round(($in_delta * 8 / $period), 2);
$out_value = round(($out_delta * 8 / $period), 2);
$last = $timestamp;
@ -118,48 +130,49 @@ foreach (dbFetch("SELECT *, UNIX_TIMESTAMP(timestamp) AS formatted_date FROM bil
$iter_out += $out_delta;
$iter_period += $period;
if ($iter == $count)
{
$out_data[$i] = round($iter_out * 8 / $iter_period, 2);
$out_data_inv[$i] = $out_data[$i] * -1;
$in_data[$i] = round($iter_in * 8 / $iter_period, 2);
$tot_data[$i] = $out_data[$i] + $in_data[$i];
$tot_data_inv[$i] = $tot_data[$i] * -1;
if ($iter == $count) {
$out_data[$i] = round(($iter_out * 8 / $iter_period), 2);
$out_data_inv[$i] = ($out_data[$i] * -1);
$in_data[$i] = round(($iter_in * 8 / $iter_period), 2);
$tot_data[$i] = ($out_data[$i] + $in_data[$i]);
$tot_data_inv[$i] = ($tot_data[$i] * -1);
if ($tot_data[$i] > $max_value) { $max_value = $tot_data[$i]; }
if ($tot_data[$i] > $max_value) {
$max_value = $tot_data[$i];
}
$ticks[$i] = $timestamp;
$per_data[$i] = $rate_95th;
$ave_data[$i] = $rate_average;
$iter = "1";
$iter = '1';
$i++;
unset($iter_out, $iter_in, $iter_period);
}
$iter++;
}
}//end foreach
$graph_name = date('M j g:ia', $start) . " - " . date('M j g:ia', $last);
$graph_name = date('M j g:ia', $start).' - '.date('M j g:ia', $last);
$n = count($ticks);
$xmin = $ticks[0];
$xmax = $ticks[$n-1];
$xmax = $ticks[($n - 1)];
$graph_name = date('M j g:ia', $xmin) . " - " . date('M j g:ia', $xmax);
$graph_name = date('M j g:ia', $xmin).' - '.date('M j g:ia', $xmax);
$graph = new Graph($xsize, $ysize, $graph_name);
$graph->img->SetImgFormat("png");
$graph->img->SetImgFormat('png');
$graph->SetScale('datlin', 0, 0, $start, $end);
#$graph->title->Set("$graph_name");
// $graph->title->Set("$graph_name");
$graph->title->SetFont(FF_FONT2, FS_BOLD, 10);
$graph->xaxis->SetFont(FF_FONT1, FS_BOLD);
$graph->xaxis->SetTextLabelInterval(2);
$graph->xaxis->SetPos('min');
#$graph->xaxis->SetLabelAngle(15);
// $graph->xaxis->SetLabelAngle(15);
$graph->yaxis->HideZeroLabel(1);
$graph->yaxis->SetFont(FF_FONT1);
$graph->yaxis->SetLabelAngle(0);
@ -167,25 +180,29 @@ $graph->xaxis->title->SetFont(FF_FONT1,FS_NORMAL,10);
$graph->yaxis->title->SetFont(FF_FONT1, FS_NORMAL, 10);
$graph->yaxis->SetTitleMargin(50);
$graph->xaxis->SetTitleMargin(30);
#$graph->xaxis->HideLastTickLabel();
#$graph->xaxis->HideFirstTickLabel();
#$graph->yaxis->scale->SetAutoMin(1);
// $graph->xaxis->HideLastTickLabel();
// $graph->xaxis->HideFirstTickLabel();
// $graph->yaxis->scale->SetAutoMin(1);
$graph->xaxis->title->Set($type);
$graph->yaxis->title->Set("Bits per second");
$graph->yaxis->SetLabelFormatCallback("format_si");
$graph->yaxis->title->Set('Bits per second');
$graph->yaxis->SetLabelFormatCallback('format_si');
function TimeCallback($aVal) {
global $dur;
if ($dur < 172800)
{
return Date('H:i',$aVal);
} elseif ($dur < 604800) {
return Date('D',$aVal);
} else {
return Date('j M',$aVal);
if ($dur < 172800) {
return date('H:i', $aVal);
}
else if ($dur < 604800) {
return date('D', $aVal);
}
else {
return date('j M', $aVal);
}
}//end TimeCallback()
$graph->xaxis->SetLabelFormatCallback('TimeCallBack');
@ -198,58 +215,50 @@ $graph->SetMargin(75,30,30,45);
$graph->legend->SetFont(FF_FONT1, FS_NORMAL);
$lineplot = new LinePlot($tot_data, $ticks);
$lineplot->SetLegend("Traffic total");
$lineplot->SetColor("#d5d5d5");
$lineplot->SetFillColor("#d5d5d5@0.5");
#$lineplot2 = new LinePlot($tot_data_inv, $ticks);
#$lineplot2->SetColor("#d5d5d5");
#$lineplot2->SetFillColor("#d5d5d5@0.5");
$lineplot->SetLegend('Traffic total');
$lineplot->SetColor('#d5d5d5');
$lineplot->SetFillColor('#d5d5d5@0.5');
// $lineplot2 = new LinePlot($tot_data_inv, $ticks);
// $lineplot2->SetColor("#d5d5d5");
// $lineplot2->SetFillColor("#d5d5d5@0.5");
$lineplot_in = new LinePlot($in_data, $ticks);
$lineplot_in->SetLegend("Traffic In");
$lineplot_in->SetLegend('Traffic In');
$lineplot_in->SetColor('darkgreen');
$lineplot_in->SetFillColor('lightgreen@0.4');
$lineplot_in->SetWeight(1);
$lineplot_out = new LinePlot($out_data_inv, $ticks);
$lineplot_out->SetLegend("Traffic Out");
$lineplot_out->SetLegend('Traffic Out');
$lineplot_out->SetColor('darkblue');
$lineplot_out->SetFillColor('lightblue@0.4');
$lineplot_out->SetWeight(1);
if ($_GET['95th'])
{
if ($_GET['95th']) {
$lineplot_95th = new LinePlot($per_data, $ticks);
$lineplot_95th ->SetColor("red");
$lineplot_95th->SetColor('red');
}
if ($_GET['ave'])
{
if ($_GET['ave']) {
$lineplot_ave = new LinePlot($ave_data, $ticks);
$lineplot_ave ->SetColor("red");
$lineplot_ave->SetColor('red');
}
$graph->legend->SetLayout(LEGEND_HOR);
$graph->legend->Pos(0.52, 0.90, 'center');
$graph->Add($lineplot);
#$graph->Add($lineplot2);
// $graph->Add($lineplot2);
$graph->Add($lineplot_in);
$graph->Add($lineplot_out);
if ($_GET['95th'])
{
if ($_GET['95th']) {
$graph->Add($lineplot_95th);
}
if ($_GET['ave'])
{
if ($_GET['ave']) {
$graph->Add($lineplot_ave);
}
$graph->stroke();
?>

View File

@ -1588,7 +1588,7 @@ tr.search:nth-child(odd) {
}
#visualization {
width: 90%;
width: 100%;
min-height: 600px;
}

View File

@ -12,41 +12,42 @@
* the source code distribution for details.
*/
if (strpos($_SERVER['PATH_INFO'], "debug"))
{
$debug = "1";
if (strpos($_SERVER['PATH_INFO'], 'debug')) {
$debug = '1';
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
ini_set('log_errors', 1);
ini_set('error_reporting', E_ALL);
} else {
$debug = FALSE;
}
else {
$debug = false;
ini_set('display_errors', 0);
ini_set('display_startup_errors', 0);
ini_set('log_errors', 0);
ini_set('error_reporting', 0);
}
include "../includes/defaults.inc.php";
include "../config.php";
include_once "../includes/definitions.inc.php";
include "../includes/functions.php";
include "includes/functions.inc.php";
include "includes/vars.inc.php";
include "includes/authenticate.inc.php";
require '../includes/defaults.inc.php';
require '../config.php';
require_once '../includes/definitions.inc.php';
require '../includes/functions.php';
require 'includes/functions.inc.php';
require 'includes/vars.inc.php';
require 'includes/authenticate.inc.php';
$report = mres($vars['report']);
if (!empty($report) && file_exists("includes/reports/$report.csv.inc.php")) {
if ($debug == false) {
header("Content-Type: text/csv");
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="'.$report.'-'.date('Ymd').'.csv"');
}
$csv = array();
include_once "includes/reports/$report.csv.inc.php";
foreach ($csv as $line) {
echo implode(',', $line)."\n";
}
} else {
}
else {
echo "Report not found.\n";
}
?>

View File

@ -9,44 +9,38 @@
* @subpackage webinterface
* @author Adam Armstrong <adama@memetic.org>
* @copyright (C) 2006 - 2012 Adam Armstrong
*
*/
// FIXME - fewer includes!
require_once '../includes/defaults.inc.php';
require_once '../config.php';
require_once '../includes/definitions.inc.php';
require_once '../includes/common.php';
require_once '../includes/dbFacile.php';
require_once '../includes/rewrites.php';
require_once 'includes/functions.inc.php';
require_once 'includes/authenticate.inc.php';
include_once("../includes/defaults.inc.php");
include_once("../config.php");
include_once("../includes/definitions.inc.php");
include_once("../includes/common.php");
include_once("../includes/dbFacile.php");
include_once("../includes/rewrites.php");
include_once("includes/functions.inc.php");
include_once("includes/authenticate.inc.php");
require_once '../includes/snmp.inc.php';
include_once("../includes/snmp.inc.php");
if (is_numeric($_GET['id']) && ($config['allow_unauth_graphs'] || port_permitted($_GET['id'])))
{
if (is_numeric($_GET['id']) && ($config['allow_unauth_graphs'] || port_permitted($_GET['id']))) {
$port = get_port_by_id($_GET['id']);
$device = device_by_id_cache($port['device_id']);
$title = generate_device_link($device);
$title .= " :: Port ".generate_port_link($port);
$auth = TRUE;
$title .= ' :: Port '.generate_port_link($port);
$auth = true;
}
$in = snmp_get($device, "ifInOctets.".$port['ifIndex'], "-OUqnv", "IF-MIB");
$out = snmp_get($device, "ifOutOctets.".$port['ifIndex'], "-OUqnv", "IF-MIB");
if(empty($in))
{
$in = snmp_get($device, "ifHCInOctets.".$port['ifIndex'], "-OUqnv", "IF-MIB");
$in = snmp_get($device, 'ifInOctets.'.$port['ifIndex'], '-OUqnv', 'IF-MIB');
$out = snmp_get($device, 'ifOutOctets.'.$port['ifIndex'], '-OUqnv', 'IF-MIB');
if (empty($in)) {
$in = snmp_get($device, 'ifHCInOctets.'.$port['ifIndex'], '-OUqnv', 'IF-MIB');
}
if(empty($out))
{
$out = snmp_get($device, "ifHCOutOctets.".$port['ifIndex'], "-OUqnv", "IF-MIB");
if (empty($out)) {
$out = snmp_get($device, 'ifHCOutOctets.'.$port['ifIndex'], '-OUqnv', 'IF-MIB');
}
$time = time();
printf("%lf|%s|%s\n", time(), $in, $out);
?>

View File

@ -14,86 +14,75 @@
enable_debug();
include_once("../includes/defaults.inc.php");
include_once("../config.php");
include_once("../includes/definitions.inc.php");
include_once("includes/functions.inc.php");
include_once("../includes/functions.php");
include_once("includes/authenticate.inc.php");
require_once '../includes/defaults.inc.php';
require_once '../config.php';
require_once '../includes/definitions.inc.php';
require_once 'includes/functions.inc.php';
require_once '../includes/functions.php';
require_once 'includes/authenticate.inc.php';
if (!$_SESSION['authenticated']) { echo("unauthenticated"); exit; }
if (!$_SESSION['authenticated']) {
echo 'unauthenticated';
exit;
}
$new_conf_type = $_POST['new_conf_type'];
$new_conf_name = $_POST['new_conf_name'];
$new_conf_desc = $_POST['new_conf_desc'];
if(empty($new_conf_name))
{
echo("You haven't specified a config name");
if (empty($new_conf_name)) {
echo "You haven't specified a config name";
exit;
}
elseif(empty($new_conf_desc))
{
echo("You haven't specified a config description");
else if (empty($new_conf_desc)) {
echo "You haven't specified a config description";
exit;
}
elseif(empty($_POST['new_conf_single_value']) && empty($_POST['new_conf_multi_value']))
{
echo("You haven't specified a config value");
else if (empty($_POST['new_conf_single_value']) && empty($_POST['new_conf_multi_value'])) {
echo "You haven't specified a config value";
exit;
}
$db_inserted = '0';
if($new_conf_type == 'Single')
{
if ($new_conf_type == 'Single') {
$new_conf_type = 'single';
$new_conf_value = $_POST['new_conf_single_value'];
$db_inserted = add_config_item($new_conf_name, $new_conf_value, $new_conf_type, $new_conf_desc);
}
elseif($new_conf_type == 'Single Array')
{
else if ($new_conf_type == 'Single Array') {
$new_conf_type = 'single-array';
$new_conf_value = $_POST['new_conf_single_value'];
$db_inserted = add_config_item($new_conf_name, $new_conf_value, $new_conf_type, $new_conf_desc);
}
elseif($new_conf_type == 'Standard Array' || $new_conf_type == 'Multi Array')
{
if($new_conf_type == 'Standard Array')
{
else if ($new_conf_type == 'Standard Array' || $new_conf_type == 'Multi Array') {
if ($new_conf_type == 'Standard Array') {
$new_conf_type = 'array';
}
elseif($new_conf_type == 'Multi Array')
{
else if ($new_conf_type == 'Multi Array') {
$new_conf_type = 'multi-array';
}
else
{
# $new_conf_type is invalid so clear values so we don't create any config
else {
// $new_conf_type is invalid so clear values so we don't create any config
$new_conf_value = '';
}
$new_conf_value = nl2br($_POST['new_conf_multi_value']);
$values = explode('<br />', $new_conf_value);
foreach ($values as $item)
{
foreach ($values as $item) {
$new_conf_value = trim($item);
$db_inserted = add_config_item($new_conf_name, $new_conf_value, $new_conf_type, $new_conf_desc);
}
}
else
{
echo('Bad config type!');
else {
echo 'Bad config type!';
$db_inserted = 0;
exit;
}
}//end if
if($db_inserted == 1)
{
echo('Your new config item has been added');
if ($db_inserted == 1) {
echo 'Your new config item has been added';
}
else
{
echo('An error occurred adding your config item to the database');
else {
echo 'An error occurred adding your config item to the database';
}
?>

View File

@ -15,23 +15,27 @@
$alert_id = mres($_POST['alert_id']);
$state = mres($_POST['state']);
if (!is_numeric($alert_id)) {
echo('ERROR: No alert selected');
echo 'ERROR: No alert selected';
exit;
} elseif(!is_numeric($state)) {
echo('ERROR: No state passed');
}
else if (!is_numeric($state)) {
echo 'ERROR: No state passed';
exit;
} else {
}
else {
if ($state == 2) {
$state = dbFetchCell('SELECT alerted FROM alerts WHERE id = ?', array($alert_id));
} elseif($state >= 1) {
}
else if ($state >= 1) {
$state = 2;
}
if(dbUpdate(array('state' => $state), 'alerts', 'id=?',array($alert_id)) >= 0) {
echo('Alert acknowledged status changed.');
exit;
} else {
echo('ERROR: Alert has not been acknowledged.');
exit;
}
}
if (dbUpdate(array('state' => $state), 'alerts', 'id=?', array($alert_id)) >= 0) {
echo 'Alert acknowledged status changed.';
exit;
}
else {
echo 'ERROR: Alert has not been acknowledged.';
exit;
}
}//end if

View File

@ -44,35 +44,43 @@ if(!empty($name)) {
}
if(dbUpdate(array('rule_id' => mres($_REQUEST['rule_id']), 'name' => $name), "alert_templates", "id = ?", array($_REQUEST['template_id']))) {
$ok = "Updated template and rule id mapping";
} else {
}
else {
$error ="Failed to update the template and rule id mapping";
}
} elseif( $_REQUEST['template'] && is_numeric($_REQUEST['template_id']) ) {
}
elseif( $_REQUEST['template'] && is_numeric($_REQUEST['template_id']) ) {
//Update template-text
if($ret = dbUpdate(array('template' => $_REQUEST['template'], 'name' => $name), "alert_templates", "id = ?", array($_REQUEST['template_id']))) {
$ok = "Updated template";
} else {
}
else {
$error = "Failed to update the template";
}
} elseif( $_REQUEST['template'] ) {
}
elseif( $_REQUEST['template'] ) {
//Create new template
if(dbInsert(array('template' => $_REQUEST['template'], 'name' => $name), "alert_templates")) {
$ok = "Alert template has been created.";
} else {
}
else {
$error = "Could not create alert template";
}
} else {
}
else {
$error = "We could not work out what you wanted to do!";
}
} else {
}
else {
$error = "You haven't given your template a name, it feels sad :( - $name";
}
if(!empty( $ok )) {
die("$ok");
} else {
}
else {
die("ERROR: $error");
}
?>

View File

@ -17,25 +17,27 @@ if(is_admin() === false) {
}
if (!is_numeric($_POST['template_id'])) {
echo('ERROR: No template selected');
echo 'ERROR: No template selected';
exit;
} else {
$rules = preg_split("/,/",mres($_POST['rule_id']));
$success = FALSE;
}
else {
$rules = preg_split('/,/', mres($_POST['rule_id']));
$success = false;
foreach ($rules as $rule_id) {
$db_id = dbInsert(array('alert_rule_id' => $rule_id, 'alert_templates_id' => mres($_POST['template_id'])), 'alert_template_map');
if ($db_id > 0) {
$success = TRUE;
$success = true;
$ids[] = $db_id;
} else {
echo('ERROR: Alert rules have not been attached to this template.');
exit;
}
}
if ($success === TRUE) {
dbDelete('alert_template_map',"id NOT IN (".implode(',',$ids).")");
echo "Alert rules have been attached to this template. $template_map_ids";
else {
echo 'ERROR: Alert rules have not been attached to this template.';
exit;
}
}
if ($success === true) {
dbDelete('alert_template_map', 'id NOT IN ('.implode(',', $ids).')');
echo "Alert rules have been attached to this template. $template_map_ids";
exit;
}
}//end if

View File

@ -14,9 +14,11 @@
if ($_POST['state'] == 'true') {
$state = 1;
} elseif ($_POST['state'] == 'false') {
}
elseif ($_POST['state'] == 'false') {
$state = 0;
} else {
}
else {
$state = 0;
}

View File

@ -13,36 +13,28 @@
*/
// FUA
if(!is_numeric($_POST['config_id']))
{
echo('error with data');
if (!is_numeric($_POST['config_id'])) {
echo 'error with data';
exit;
}
else
{
if($_POST['state'] == 'true')
{
else {
if ($_POST['state'] == 'true') {
$state = 1;
}
elseif($_POST['state'] == 'false')
{
else if ($_POST['state'] == 'false') {
$state = 0;
}
else
{
else {
$state = 0;
}
$update = dbUpdate(array('config_disabled' => $state), 'config', '`config_id` = ?', array($_POST['config_id']));
if(!empty($update) || $update == '0')
{
echo('success');
exit;
}
else
{
echo('error');
exit;
}
}
$update = dbUpdate(array('config_disabled' => $state), 'config', '`config_id` = ?', array($_POST['config_id']));
if (!empty($update) || $update == '0') {
echo 'success';
exit;
}
else {
echo 'error';
exit;
}
}//end if

View File

@ -13,25 +13,19 @@
*/
// FUA
if(!is_numeric($_POST['config_id']) || empty($_POST['data']))
{
echo('error with data');
if (!is_numeric($_POST['config_id']) || empty($_POST['data'])) {
echo 'error with data';
exit;
}
else
{
else {
$data = mres($_POST['data']);
$update = dbUpdate(array('config_value' => "$data"), 'config', '`config_id` = ?', array($_POST['config_id']));
if(!empty($update) || $update == '0')
{
echo('success');
if (!empty($update) || $update == '0') {
echo 'success';
exit;
}
else
{
echo('error');
else {
echo 'error';
exit;
}
}

View File

@ -13,7 +13,10 @@
*/
if (is_admin() === false) {
$response = array('status'=>'error','message'=>'Need to be admin');
$response = array(
'status' => 'error',
'message' => 'Need to be admin',
);
echo _json_encode($response);
exit;
}
@ -34,25 +37,32 @@ if ($action == 'remove' || $action == 'remove-slack' || $action == 'remove-hipch
$config_id = mres($_POST['config_id']);
if (empty($config_id)) {
$message = 'No config id passed';
} else {
}
else {
if (dbDelete('config', '`config_id`=?', array($config_id))) {
if ($action == 'remove-slack') {
dbDelete('config', "`config_name` LIKE 'alert.transports.slack.$config_id.%'");
} elseif ($action == 'remove-hipchat') {
}
else if ($action == 'remove-hipchat') {
dbDelete('config', "`config_name` LIKE 'alert.transports.hipchat.$config_id.%'");
} elseif ($action == 'remove-pushover') {
}
else if ($action == 'remove-pushover') {
dbDelete('config', "`config_name` LIKE 'alert.transports.pushover.$config_id.%'");
}
$status = 'ok';
$message = 'Config item removed';
} else {
}
else {
$message = 'General error, could not remove config';
}
}
} elseif ($action == 'add-slack') {
}
else if ($action == 'add-slack') {
if (empty($config_value)) {
$message = 'No Slack url provided';
} else {
}
else {
$config_id = dbInsert(array('config_name' => 'alert.transports.slack.', 'config_value' => $config_value, 'config_group' => $config_group, 'config_sub_group' => $config_sub_group, 'config_default' => $config_value, 'config_descr' => 'Slack Transport'), 'config');
if ($config_id > 0) {
dbUpdate(array('config_name' => 'alert.transports.slack.'.$config_id.'.url'), 'config', 'config_id=?', array($config_id));
@ -60,19 +70,22 @@ if ($action == 'remove' || $action == 'remove-slack' || $action == 'remove-hipch
$message = 'Config item created';
$extras = explode('\n', $config_extra);
foreach ($extras as $option) {
list($k,$v) = explode("=", $option,2);
list($k,$v) = explode('=', $option, 2);
if (!empty($k) || !empty($v)) {
dbInsert(array('config_name' => 'alert.transports.slack.'.$config_id.'.'.$k, 'config_value' => $v, 'config_group' => $config_group, 'config_sub_group' => $config_sub_group, 'config_default' => $v, 'config_descr' => 'Slack Transport'), 'config');
}
}
} else {
}
else {
$message = 'Could not create config item';
}
}
} elseif ($action == 'add-hipchat') {
}
else if ($action == 'add-hipchat') {
if (empty($config_value) || empty($config_room_id) || empty($config_from)) {
$message = 'No hipchat url, room id or from provided';
} else {
}
else {
$config_id = dbInsert(array('config_name' => 'alert.transports.hipchat.', 'config_value' => $config_value, 'config_group' => $config_group, 'config_sub_group' => $config_sub_group, 'config_default' => $config_value, 'config_descr' => 'Hipchat Transport'), 'config');
if ($config_id > 0) {
dbUpdate(array('config_name' => 'alert.transports.hipchat.'.$config_id.'.url'), 'config', 'config_id=?', array($config_id));
@ -82,19 +95,22 @@ if ($action == 'remove' || $action == 'remove-slack' || $action == 'remove-hipch
$message = 'Config item created';
$extras = explode('\n', $config_extra);
foreach ($extras as $option) {
list($k,$v) = explode("=", $option,2);
list($k,$v) = explode('=', $option, 2);
if (!empty($k) || !empty($v)) {
dbInsert(array('config_name' => 'alert.transports.hipchat.'.$config_id.'.'.$k, 'config_value' => $v, 'config_group' => $config_group, 'config_sub_group' => $config_sub_group, 'config_default' => $v, 'config_descr' => 'Hipchat '.$v), 'config');
}
}
} else {
}
else {
$message = 'Could not create config item';
}
}//end if
}
} elseif ($action == 'add-pushover') {
else if ($action == 'add-pushover') {
if (empty($config_value) || empty($config_userkey)) {
$message = 'No pushover appkey or userkey provided';
} else {
}
else {
$config_id = dbInsert(array('config_name' => 'alert.transports.pushover.', 'config_value' => $config_value, 'config_group' => $config_group, 'config_sub_group' => $config_sub_group, 'config_default' => $config_value, 'config_descr' => 'Pushover Transport'), 'config');
if ($config_id > 0) {
dbUpdate(array('config_name' => 'alert.transports.pushover.'.$config_id.'.appkey'), 'config', 'config_id=?', array($config_id));
@ -103,30 +119,38 @@ if ($action == 'remove' || $action == 'remove-slack' || $action == 'remove-hipch
$message = 'Config item created';
$extras = explode('\n', $config_extra);
foreach ($extras as $option) {
list($k,$v) = explode("=", $option,2);
list($k,$v) = explode('=', $option, 2);
if (!empty($k) || !empty($v)) {
dbInsert(array('config_name' => 'alert.transports.pushover.'.$config_id.'.'.$k, 'config_value' => $v, 'config_group' => $config_group, 'config_sub_group' => $config_sub_group, 'config_default' => $v, 'config_descr' => 'Pushover '.$v), 'config');
}
}
} else {
}
else {
$message = 'Could not create config item';
}
}
} else {
}
else {
if (empty($config_group) || empty($config_sub_group) || empty($config_name) || empty($config_value)) {
$message = 'Missing config name or value';
} else {
}
else {
$config_id = dbInsert(array('config_name' => $config_name, 'config_value' => $config_value, 'config_group' => $config_group, 'config_sub_group' => $config_sub_group, 'config_default' => $config_value, 'config_descr' => 'API Transport'), 'config');
if ($config_id > 0) {
dbUpdate(array('config_name' => $config_name.$config_id), 'config', 'config_id=?', array($config_id));
$status = 'ok';
$message = 'Config item created';
} else {
}
else {
$message = 'Could not create config item';
}
}
}
}//end if
$response = array('status'=>$status,'message'=>$message, 'config_id'=>$config_id, 'additional_id'=>$additional_id);
$response = array(
'status' => $status,
'message' => $message,
'config_id' => $config_id,
'additional_id' => $additional_id,
);
echo _json_encode($response);

View File

@ -16,7 +16,7 @@ if(is_admin() === false) {
die('ERROR: You need to be admin');
}
$rule = implode(" ", $_POST['rules']);
$rule = implode(' ', $_POST['rules']);
$rule = rtrim($rule, '&&');
$rule = rtrim($rule, '||');
$alert_id = $_POST['alert_id'];
@ -28,36 +28,51 @@ $invert = mres($_POST['invert']);
$name = mres($_POST['name']);
if (empty($rule)) {
$update_message = "ERROR: No rule was generated - did you forget to click and / or?";
} elseif(validate_device_id($_POST['device_id']) || $_POST['device_id'] == '-1' || $_POST['device_id'][0] == ':') {
$update_message = 'ERROR: No rule was generated - did you forget to click and / or?';
}
else if (validate_device_id($_POST['device_id']) || $_POST['device_id'] == '-1' || $_POST['device_id'][0] == ':') {
$device_id = $_POST['device_id'];
if (!is_numeric($count)) {
$count = '-1';
}
$delay_sec = convert_delay($delay);
$interval_sec = convert_delay($interval);
if ($mute == 'on') {
$mute = true;
} else {
}
else {
$mute = false;
}
if ($invert == 'on') {
$invert = true;
} else {
}
else {
$invert = false;
}
$extra = array('mute'=>$mute,'count'=>$count,'delay'=>$delay_sec,'invert'=>$invert,'interval'=>$interval_sec);
$extra = array(
'mute' => $mute,
'count' => $count,
'delay' => $delay_sec,
'invert' => $invert,
'interval' => $interval_sec,
);
$extra_json = json_encode($extra);
if (is_numeric($alert_id) && $alert_id > 0) {
if (dbUpdate(array('rule' => $rule, 'severity' => mres($_POST['severity']), 'extra' => $extra_json, 'name' => $name), 'alert_rules', 'id=?', array($alert_id)) >= 0) {
$update_message = "Edited Rule: <i>$name: $rule</i>";
} else {
$update_message = "ERROR: Failed to edit Rule: <i>".$rule."</i>";
}
} else {
else {
$update_message = 'ERROR: Failed to edit Rule: <i>'.$rule.'</i>';
}
}
else {
if (is_array($_POST['maps'])) {
$device_id = ':'.$device_id;
}
if (dbInsert(array('device_id' => $device_id, 'rule' => $rule, 'severity' => mres($_POST['severity']), 'extra' => $extra_json, 'name' => $name), 'alert_rules')) {
$update_message = "Added Rule: <i>$name: $rule</i>";
if (is_array($_POST['maps'])) {
@ -65,15 +80,17 @@ if(empty($rule)) {
$_POST['rule'] = $name;
$_POST['target'] = $target;
$_POST['map_id'] = '';
include('forms/create-map-item.inc.php');
include 'forms/create-map-item.inc.php';
unset($ret,$target,$raw,$rule,$msg,$map_id);
}
}
} else {
$update_message = "ERROR: Failed to add Rule: <i>".$rule."</i>";
}
else {
$update_message = 'ERROR: Failed to add Rule: <i>'.$rule.'</i>';
}
} else {
$update_message = "ERROR: invalid device ID or not a global alert";
}//end if
}
else {
$update_message = 'ERROR: invalid device ID or not a global alert';
}//end if
echo $update_message;

View File

@ -22,29 +22,36 @@ $name = mres($_POST['name']);
$desc = mres($_POST['desc']);
if (is_array($pattern)) {
$pattern = implode(" ", $pattern);
} elseif( !empty($_POST['pattern']) && !empty($_POST['condition']) && !empty($_POST['value']) ) {
$pattern = implode(' ', $pattern);
}
else if (!empty($_POST['pattern']) && !empty($_POST['condition']) && !empty($_POST['value'])) {
$pattern = '%'.$_POST['pattern'].' '.$_POST['condition'].' ';
if (is_numeric($_POST['value'])) {
$pattern .= $_POST['value'];
} else {
}
else {
$pattern .= '"'.$_POST['value'].'"';
}
}
if (empty($pattern)) {
$update_message = "ERROR: No group was generated";
} elseif(is_numeric($group_id) && $group_id > 0) {
$update_message = 'ERROR: No group was generated';
}
else if (is_numeric($group_id) && $group_id > 0) {
if (dbUpdate(array('pattern' => $pattern, 'name' => $name, 'desc' => $desc), 'device_groups', 'id=?', array($group_id)) >= 0) {
$update_message = "Edited Group: <i>$name: $pattern</i>";
} else {
$update_message = "ERROR: Failed to edit Group: <i>".$pattern."</i>";
}
} else {
else {
$update_message = 'ERROR: Failed to edit Group: <i>'.$pattern.'</i>';
}
}
else {
if (dbInsert(array('pattern' => $pattern, 'name' => $name, 'desc' => $desc), 'device_groups')) {
$update_message = "Added Group: <i>$name: $pattern</i>";
} else {
$update_message = "ERROR: Failed to add Group: <i>".$pattern."</i>";
}
else {
$update_message = 'ERROR: Failed to add Group: <i>'.$pattern.'</i>';
}
}
echo $update_message;

View File

@ -22,45 +22,55 @@ $map_id = mres($_POST['map_id']);
$ret = array();
if (empty($rule) || empty($target)) {
$ret[] = "ERROR: No map was generated";
} else {
$ret[] = 'ERROR: No map was generated';
}
else {
$raw = $rule;
$rule = dbFetchCell('SELECT id FROM alert_rules WHERE name = ?', array($rule));
if (!is_numeric($rule)) {
array_unshift($ret, "ERROR: Could not find rule for '".$raw."'");
} else {
}
else {
$raw = $target;
if( $target[0].$target[1] == "g:" ) {
$target = "g".dbFetchCell('SELECT id FROM device_groups WHERE name = ?',array(substr($target,2)));
} else {
if ($target[0].$target[1] == 'g:') {
$target = 'g'.dbFetchCell('SELECT id FROM device_groups WHERE name = ?', array(substr($target, 2)));
}
else {
$target = dbFetchCell('SELECT device_id FROM devices WHERE hostname = ?', array($target));
}
if (!is_numeric(str_replace('g', '', $target))) {
array_unshift($ret, "ERROR: Could not find entry for '".$raw."'");
} else {
}
else {
if (is_numeric($map_id) && $map_id > 0) {
if (dbUpdate(array('rule' => $rule, 'target' => $target), 'alert_map', 'id=?', array($map_id)) >= 0) {
$ret[] = "Edited Map: <i>".$map_id.": ".$rule." = ".$target."</i>";
} else {
array_unshift($ret,"ERROR: Failed to edit Map: <i>".$map_id.": ".$rule." = ".$target."</i>");
$ret[] = 'Edited Map: <i>'.$map_id.': '.$rule.' = '.$target.'</i>';
}
} else {
else {
array_unshift($ret, 'ERROR: Failed to edit Map: <i>'.$map_id.': '.$rule.' = '.$target.'</i>');
}
}
else {
if (dbInsert(array('rule' => $rule, 'target' => $target), 'alert_map')) {
$ret[] = "Added Map: <i>".$rule." = ".$target."</i>";
} else {
array_unshift($ret,"ERROR: Failed to add Map: <i>".$rule." = ".$target."</i>");
$ret[] = 'Added Map: <i>'.$rule.' = '.$target.'</i>';
}
else {
array_unshift($ret, 'ERROR: Failed to add Map: <i>'.$rule.' = '.$target.'</i>');
}
}
if( ($tmp=dbFetchCell('SELECT device_id FROM alert_rules WHERE id = ?',array($rule))) && $tmp[0] != ":" ) {
if (($tmp = dbFetchCell('SELECT device_id FROM alert_rules WHERE id = ?', array($rule))) && $tmp[0] != ':') {
if (dbUpdate(array('device_id' => ':'.$tmp), 'alert_rules', 'id=?', array($rule)) >= 0) {
$ret[] = "Edited Rule: <i>".$rule." device_id = ':".$tmp."'</i>";
} else {
array_unshift($ret,"ERROR: Failed to edit Rule: <i>".$rule.": device_id = ':".$tmp."'</i>");
}
}
}
$ret[] = 'Edited Rule: <i>'.$rule." device_id = ':".$tmp."'</i>";
}
else {
array_unshift($ret, 'ERROR: Failed to edit Rule: <i>'.$rule.": device_id = ':".$tmp."'</i>");
}
}
}//end if
}//end if
}//end if
foreach ($ret as $msg) {
echo $msg."<br/>";
echo $msg.'<br/>';
}

View File

@ -15,27 +15,33 @@
if (is_admin() === false) {
die('ERROR: You need to be admin');
}
$ret = array();
$brk = false;
if (!is_numeric($_POST['map_id'])) {
array_unshift($ret, 'ERROR: No map selected');
} else {
}
else {
if (dbFetchCell('SELECT COUNT(B.id) FROM alert_map,alert_map AS B WHERE alert_map.rule=B.rule && alert_map.id = ?', array($_POST['map_id'])) <= 1) {
$rule = dbFetchRow('SELECT alert_rules.id,alert_rules.device_id FROM alert_map,alert_rules WHERE alert_map.rule=alert_rules.id && alert_map.id = ?', array($_POST['map_id']));
$rule['device_id'] = str_replace(":",'',$rule['device_id']);
$rule['device_id'] = str_replace(':', '', $rule['device_id']);
if (dbUpdate(array('device_id' => $rule['device_id']), 'alert_rules', 'id = ?', array($rule['id'])) >= 0) {
$ret[] = "Restored Rule: <i>".$rule['id'].": device_id = '".$rule['device_id']."'</i>";
} else {
$ret[] = 'Restored Rule: <i>'.$rule['id'].": device_id = '".$rule['device_id']."'</i>";
}
else {
array_unshift($ret, 'ERROR: Rule '.$rule['id'].' has not been restored.');
$brk = true;
}
}
if( $brk === false && dbDelete('alert_map', "`id` = ?", array($_POST['map_id'])) ) {
if ($brk === false && dbDelete('alert_map', '`id` = ?', array($_POST['map_id']))) {
$ret[] = 'Map has been deleted.';
} else {
}
else {
array_unshift($ret, 'ERROR: Map has not been deleted.');
}
}
foreach ($ret as $msg) {
echo $msg."<br/>";
echo $msg.'<br/>';
}

View File

@ -17,20 +17,23 @@ if(is_admin() === false) {
}
if (!is_numeric($_POST['alert_id'])) {
echo('ERROR: No alert selected');
exit;
} else {
if(dbDelete('alert_rules', "`id` = ?", array($_POST['alert_id']))) {
if(dbDelete('alert_map', "rule = ?", array($_POST['alert_id'])) || dbFetchCell('COUNT(id) FROM alert_map WHERE rule = ?',array($_POST['alert_id'])) == 0) {
echo('Maps has been deleted.');
} else {
echo('WARNING: Maps could not be deleted.');
}
echo('Alert rule has been deleted.');
exit;
} else {
echo('ERROR: Alert rule has not been deleted.');
echo 'ERROR: No alert selected';
exit;
}
else {
if (dbDelete('alert_rules', '`id` = ?', array($_POST['alert_id']))) {
if (dbDelete('alert_map', 'rule = ?', array($_POST['alert_id'])) || dbFetchCell('COUNT(id) FROM alert_map WHERE rule = ?', array($_POST['alert_id'])) == 0) {
echo 'Maps has been deleted.';
}
else {
echo 'WARNING: Maps could not be deleted.';
}
echo 'Alert rule has been deleted.';
exit;
}
else {
echo 'ERROR: Alert rule has not been deleted.';
exit;
}
}

View File

@ -17,15 +17,16 @@ if(is_admin() === false) {
}
if (!is_numeric($_POST['template_id'])) {
echo('ERROR: No template selected');
echo 'ERROR: No template selected';
exit;
} else {
if(dbDelete('alert_templates', "`id` = ?", array($_POST['template_id']))) {
echo('Alert template has been deleted.');
}
else {
if (dbDelete('alert_templates', '`id` = ?', array($_POST['template_id']))) {
echo 'Alert template has been deleted.';
exit;
} else {
echo('ERROR: Alert template has not been deleted.');
}
else {
echo 'ERROR: Alert template has not been deleted.';
exit;
}
}

View File

@ -17,21 +17,23 @@ if(is_admin() === false) {
}
if (!is_numeric($_POST['group_id'])) {
echo('ERROR: No group selected');
echo 'ERROR: No group selected';
exit;
} else {
if(dbDelete('device_groups', "`id` = ?", array($_POST['group_id']))) {
}
else {
if (dbDelete('device_groups', '`id` = ?', array($_POST['group_id']))) {
if (dbFetchCell('SELECT COUNT(id) FROM alert_map WHERE target = ?', array('g'.$_POST['group_id'])) >= 1) {
foreach (dbFetchRows('SELECT id FROM alert_map WHERE target = ?', array('g'.$_POST['group_id'])) as $map) {
$_POST['map_id'] = $map['id'];
include('forms/delete-alert-map.inc.php');
}
}
echo('Group has been deleted.');
exit;
} else {
echo('ERROR: Group has not been deleted.');
exit;
include 'forms/delete-alert-map.inc.php';
}
}
echo 'Group has been deleted.';
exit;
}
else {
echo 'ERROR: Group has not been deleted.';
exit;
}
}

View File

@ -1,37 +1,28 @@
<?php
// FUA
$device['device_id'] = $_POST['device_id'];
$module = 'discover_'.$_POST['discovery_module'];
if(!isset($module) && validate_device_id($device['device_id']) === false)
{
echo('error with data');
if (!isset($module) && validate_device_id($device['device_id']) === false) {
echo 'error with data';
exit;
}
else
{
if($_POST['state'] == 'true')
{
else {
if ($_POST['state'] == 'true') {
$state = 1;
}
elseif($_POST['state'] == 'false')
{
else if ($_POST['state'] == 'false') {
$state = 0;
}
else
{
else {
$state = 0;
}
if(isset($attribs['discover_'.$module]) && $attribs['discover_'.$module] != $config['discover_modules'][$module])
{
if (isset($attribs['discover_'.$module]) && $attribs['discover_'.$module] != $config['discover_modules'][$module]) {
del_dev_attrib($device, $module);
}
else
{
else {
set_dev_attrib($device, $module, $state);
}
}

View File

@ -13,24 +13,18 @@
*/
// FUA
if(!is_numeric($_POST['device_id']) || !is_numeric($_POST['sensor_id']) || (empty($_POST['data']) || !isset($_POST['data'])))
{
echo('error with data');
if (!is_numeric($_POST['device_id']) || !is_numeric($_POST['sensor_id']) || (empty($_POST['data']) || !isset($_POST['data']))) {
echo 'error with data';
exit;
}
else
{
else {
$update = dbUpdate(array($_POST['value_type'] => $_POST['data'], 'sensor_custom' => 'Yes'), 'sensors', '`sensor_id` = ? AND `device_id` = ?', array($_POST['sensor_id'], $_POST['device_id']));
if(!empty($update) || $update == '0')
{
echo('success');
if (!empty($update) || $update == '0') {
echo 'success';
exit;
}
else
{
echo('error');
else {
echo 'error';
exit;
}
}

View File

@ -19,12 +19,17 @@ if(is_admin() === false) {
$map_id = $_POST['map_id'];
if (is_numeric($map_id) && $map_id > 0) {
$map = dbFetchRow("SELECT alert_rules.name,alert_map.target FROM alert_map,alert_rules WHERE alert_map.rule=alert_rules.id && alert_map.id = ?",array($map_id));
if( $map['target'][0] == "g" ) {
$map['target'] = 'g:'.dbFetchCell("SELECT name FROM device_groups WHERE id = ?",array(substr($map['target'],1)));
} else {
$map['target'] = dbFetchCell("SELECT hostname FROM devices WHERE device_id = ?",array($map['target']));
$map = dbFetchRow('SELECT alert_rules.name,alert_map.target FROM alert_map,alert_rules WHERE alert_map.rule=alert_rules.id && alert_map.id = ?', array($map_id));
if ($map['target'][0] == 'g') {
$map['target'] = 'g:'.dbFetchCell('SELECT name FROM device_groups WHERE id = ?', array(substr($map['target'], 1)));
}
$output = array('rule'=>$map['name'],'target'=>$map['target']);
else {
$map['target'] = dbFetchCell('SELECT hostname FROM devices WHERE device_id = ?', array($map['target']));
}
$output = array(
'rule' => $map['name'],
'target' => $map['target'],
);
echo _json_encode($output);
}

View File

@ -19,10 +19,15 @@ if(is_admin() === false) {
$alert_id = $_POST['alert_id'];
if (is_numeric($alert_id) && $alert_id > 0) {
$rule = dbFetchRow("SELECT * FROM `alert_rules` WHERE `id` = ? LIMIT 1",array($alert_id));
$rule_split = preg_split('/([a-zA-Z0-9_\-\.\=\%\<\>\ \"\'\!\~\(\)\*\/\@]+[&&\|\|]+)/',$rule['rule'], -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
$count = count($rule_split) - 1;
$rule = dbFetchRow('SELECT * FROM `alert_rules` WHERE `id` = ? LIMIT 1', array($alert_id));
$rule_split = preg_split('/([a-zA-Z0-9_\-\.\=\%\<\>\ \"\'\!\~\(\)\*\/\@]+[&&\|\|]+)/', $rule['rule'], -1, (PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY));
$count = (count($rule_split) - 1);
$rule_split[$count] = $rule_split[$count].' &&';
$output = array('severity'=>$rule['severity'],'extra'=>$rule['extra'],'name'=>$rule['name'],'rules'=>$rule_split);
$output = array(
'severity' => $rule['severity'],
'extra' => $rule['extra'],
'name' => $rule['name'],
'rules' => $rule_split,
);
echo _json_encode($output);
}

View File

@ -19,7 +19,10 @@ if(is_admin() === false) {
$template_id = ($_POST['template_id']);
if (is_numeric($template_id) && $template_id > 0) {
$template = dbFetchRow("SELECT * FROM `alert_templates` WHERE `id` = ? LIMIT 1",array($template_id));
$output = array('template'=>$template['template'],'name'=>$template['name']);
$template = dbFetchRow('SELECT * FROM `alert_templates` WHERE `id` = ? LIMIT 1', array($template_id));
$output = array(
'template' => $template['template'],
'name' => $template['name'],
);
echo _json_encode($output);
}

View File

@ -19,14 +19,20 @@ if(is_admin() === false) {
$group_id = $_POST['group_id'];
if (is_numeric($group_id) && $group_id > 0) {
$group = dbFetchRow("SELECT * FROM `device_groups` WHERE `id` = ? LIMIT 1",array($group_id));
$group_split = preg_split('/([a-zA-Z0-9_\-\.\=\%\<\>\ \"\'\!\~\(\)\*\/\@\[\]]+[&&\|\|]+)/',$group['pattern'], -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
$count = count($group_split) - 1;
if (preg_match("/\&\&$/",$group_split[$count]) == 1 || preg_match("/\|\|$/", $group_split[$count]) == 1) {
$group = dbFetchRow('SELECT * FROM `device_groups` WHERE `id` = ? LIMIT 1', array($group_id));
$group_split = preg_split('/([a-zA-Z0-9_\-\.\=\%\<\>\ \"\'\!\~\(\)\*\/\@\[\]]+[&&\|\|]+)/', $group['pattern'], -1, (PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY));
$count = (count($group_split) - 1);
if (preg_match('/\&\&$/', $group_split[$count]) == 1 || preg_match('/\|\|$/', $group_split[$count]) == 1) {
$group_split[$count] = $group_split[$count];
} else {
}
else {
$group_split[$count] = $group_split[$count].' &&';
}
$output = array('name'=>$group['name'],'desc'=>$group['desc'],'pattern'=>$group_split);
$output = array(
'name' => $group['name'],
'desc' => $group['desc'],
'pattern' => $group_split,
);
echo _json_encode($output);
}

View File

@ -19,7 +19,10 @@ if(is_admin() === false) {
$group_id = ($_POST['group_id']);
if (is_numeric($group_id) && $group_id > 0) {
$group = dbFetchRow("SELECT * FROM `poller_groups` WHERE `id` = ? LIMIT 1",array($group_id));
$output = array('group_name'=>$group['group_name'],'descr'=>$group['descr']);
$group = dbFetchRow('SELECT * FROM `poller_groups` WHERE `id` = ? LIMIT 1', array($group_id));
$output = array(
'group_name' => $group['group_name'],
'descr' => $group['descr'],
);
echo _json_encode($output);
}

View File

@ -19,9 +19,10 @@ if(is_admin() === false) {
$template_id = ($_POST['template_id']);
if (is_numeric($template_id) && $template_id > 0) {
foreach (dbFetchRows("SELECT `alert_rule_id` FROM `alert_template_map` WHERE `alert_templates_id` = ?",array($template_id)) as $rule) {
foreach (dbFetchRows('SELECT `alert_rule_id` FROM `alert_template_map` WHERE `alert_templates_id` = ?', array($template_id)) as $rule) {
$rules[] = $rule['alert_rule_id'];
}
$output = array('rule_id' => $rules);
echo _json_encode($output);
}

View File

@ -13,17 +13,18 @@
*/
if (!is_numeric($_POST['group_id'])) {
echo('error with data');
echo 'error with data';
exit;
} else {
if($_POST['confirm'] == 'yes')
{
}
else {
if ($_POST['confirm'] == 'yes') {
$delete = dbDelete('poller_groups', '`id` = ?', array($_POST['group_id']));
if ($delete > '0') {
echo('Poller group has been removed');
echo 'Poller group has been removed';
exit;
} else {
echo('An error occurred removing the Poller group');
}
else {
echo 'An error occurred removing the Poller group';
exit;
}
}

View File

@ -23,25 +23,29 @@ $group_name = mres($_POST['group_name']);
$descr = mres($_POST['descr']);
if (!empty($group_name)) {
if (is_numeric($group_id)) {
if (dbUpdate(array('group_name' => $group_name, 'descr' => $descr), "poller_groups", "id = ?", array($group_id))) {
$ok = "Updated poller group";
} else {
$error = "Failed to update the poller group";
if (dbUpdate(array('group_name' => $group_name, 'descr' => $descr), 'poller_groups', 'id = ?', array($group_id))) {
$ok = 'Updated poller group';
}
} else {
else {
$error = 'Failed to update the poller group';
}
}
else {
if (dbInsert(array('group_name' => $group_name, 'descr' => $descr), 'poller_groups') >= 0) {
$ok = "Added new poller group";
} else {
$error = "Failed to create new poller group";
$ok = 'Added new poller group';
}
else {
$error = 'Failed to create new poller group';
}
}
} else {
}
else {
$error = "You haven't given your poller group a name, it feels sad :( - $group_name";
}
if (!empty($ok)) {
die("$ok");
} else {
}
else {
die("ERROR: $error");
}
?>

View File

@ -1,37 +1,28 @@
<?php
// FUA
$device['device_id'] = $_POST['device_id'];
$module = 'poll_'.$_POST['poller_module'];
if(!isset($module) && validate_device_id($device['device_id']) === false)
{
echo('error with data');
if (!isset($module) && validate_device_id($device['device_id']) === false) {
echo 'error with data';
exit;
}
else
{
if($_POST['state'] == 'true')
{
else {
if ($_POST['state'] == 'true') {
$state = 1;
}
elseif($_POST['state'] == 'false')
{
else if ($_POST['state'] == 'false') {
$state = 0;
}
else
{
else {
$state = 0;
}
if(isset($attribs['poll_'.$module]) && $attribs['poll_'.$module] != $config['poller_modules'][$module])
{
if (isset($attribs['poll_'.$module]) && $attribs['poll_'.$module] != $config['poller_modules'][$module]) {
del_dev_attrib($device, $module);
}
else
{
else {
set_dev_attrib($device, $module, $state);
}
}

View File

@ -13,20 +13,26 @@
*/
// FIXME: Make this part of the API instead of a standalone function
if (!is_numeric($_POST['device_id'])) {
$status = "error";
$message = "Invalid device id";
} else {
$status = 'error';
$message = 'Invalid device id';
}
else {
$update = dbUpdate(array('last_discovered' => array('NULL')), 'devices', '`device_id` = ?', array($_POST['device_id']));
if (!empty($update) || $update == '0') {
$status = "ok";
$message = "Device will be rediscovered";
} else {
$status = "error";
$message = "Error rediscovering device";
$status = 'ok';
$message = 'Device will be rediscovered';
}
else {
$status = 'error';
$message = 'Error rediscovering device';
}
}
$output = array("status" => $status, "message" => $message);
header("Content-type: application/json");
$output = array(
'status' => $status,
'message' => $message,
);
header('Content-type: application/json');
echo _json_encode($output);

View File

@ -19,7 +19,6 @@ if(is_admin() === false) {
$sub_type = $_POST['sub_type'];
if ($sub_type == 'new-maintenance') {
// Defaults
$status = 'error';
$update = 0;
@ -28,6 +27,7 @@ if ($sub_type == 'new-maintenance') {
if ($schedule_id > 0) {
$update = 1;
}
$title = mres($_POST['title']);
$notes = mres($_POST['notes']);
$start = mres($_POST['start']);
@ -35,24 +35,29 @@ if ($sub_type == 'new-maintenance') {
$maps = mres($_POST['maps']);
if (empty($title)) {
$message = "Missing title<br />";
$message = 'Missing title<br />';
}
if (empty($start)) {
$message .= "Missing start date<br />";
$message .= 'Missing start date<br />';
}
if (empty($end)) {
$message .= "Missing end date<br />";
$message .= 'Missing end date<br />';
}
if (!is_array($_POST['maps'])) {
$message .= "Not mapped to any groups or devices<br />";
$message .= 'Not mapped to any groups or devices<br />';
}
if (empty($message)) {
if (empty($schedule_id)) {
$schedule_id = dbInsert(array('start' => $start, 'end' => $end, 'title' => $title, 'notes' => $notes), 'alert_schedule');
} else {
}
else {
dbUpdate(array('start' => $start, 'end' => $end, 'title' => $title, 'notes' => $notes), 'alert_schedule', '`schedule_id`=?', array($schedule_id));
}
if ($schedule_id > 0) {
$items = array();
$fail = 0;
@ -66,44 +71,62 @@ if ($sub_type == 'new-maintenance') {
$item = dbInsert(array('schedule_id' => $schedule_id, 'target' => $target), 'alert_schedule_items');
if ($item > 0) {
array_push($items, $item);
} else {
}
else {
$fail = 1;
}
}
if ($fail == 1 && $update == 0) {
foreach ($items as $item) {
dbDelete('alert_schedule_items', '`item_id`=?', array($item));
}
dbDelete('alert_schedule', '`schedule_id`=?', array($schedule_id));
$message = 'Issue scheduling maintenance';
} else {
}
else {
$status = 'ok';
$message = 'Scheduling maintenance ok';
}
} else {
$message = "Issue scheduling maintenance";
}
else {
$message = 'Issue scheduling maintenance';
}//end if
}//end if
$response = array(
'status' => $status,
'message' => $message,
);
}
$response = array('status'=>$status,'message'=>$message);
} elseif ($sub_type == 'parse-maintenance') {
else if ($sub_type == 'parse-maintenance') {
$schedule_id = mres($_POST['schedule_id']);
$schedule = dbFetchRow("SELECT * FROM `alert_schedule` WHERE `schedule_id`=?",array($schedule_id));
$schedule = dbFetchRow('SELECT * FROM `alert_schedule` WHERE `schedule_id`=?', array($schedule_id));
$items = array();
foreach (dbFetchRows("SELECT `target` FROM `alert_schedule_items` WHERE `schedule_id`=?",array($schedule_id)) as $targets) {
foreach (dbFetchRows('SELECT `target` FROM `alert_schedule_items` WHERE `schedule_id`=?', array($schedule_id)) as $targets) {
$targets = id_to_target($targets['target']);
array_push($items, $targets);
}
$response = array('start'=>$schedule['start'],'end'=>$schedule['end'],'title'=>$schedule['title'],'notes'=>$schedule['notes'],'targets'=>$items);
} elseif ($sub_type == 'del-maintenance') {
$response = array(
'start' => $schedule['start'],
'end' => $schedule['end'],
'title' => $schedule['title'],
'notes' => $schedule['notes'],
'targets' => $items,
);
}
else if ($sub_type == 'del-maintenance') {
$schedule_id = mres($_POST['del_schedule_id']);
dbDelete('alert_schedule_items', '`schedule_id`=?', array($schedule_id));
dbDelete('alert_schedule', '`schedule_id`=?', array($schedule_id));
$status = 'ok';
$message = 'Maintenance schedule has been removed';
$response = array('status'=>$status,'message'=>$message);
}
$response = array(
'status' => $status,
'message' => $message,
);
}//end if
echo _json_encode($response);

View File

@ -13,9 +13,6 @@
*/
// FUA
for($x=0;$x<count($_POST['sensor_id']);$x++)
{
for ($x = 0; $x < count($_POST['sensor_id']); $x++) {
dbUpdate(array('sensor_limit' => $_POST['sensor_limit'][$x], 'sensor_limit_low' => $_POST['sensor_limit_low'][$x], 'sensor_alert' => $_POST['sensor_alert'][$x]), 'sensors', '`sensor_id` = ?', array($_POST['sensor_id'][$x]));
}

View File

@ -13,41 +13,33 @@
*/
// FUA
if (isset($_POST['sub_type']) && !empty($_POST['sub_type'])) {
dbUpdate(array('sensor_custom' => 'No'), 'sensors', '`sensor_id` = ?', array($_POST['sensor_id']));
} else {
if(!is_numeric($_POST['device_id']) || !is_numeric($_POST['sensor_id']))
{
echo('error with data');
}
else {
if (!is_numeric($_POST['device_id']) || !is_numeric($_POST['sensor_id'])) {
echo 'error with data';
exit;
}
else
{
if($_POST['state'] == 'true')
{
else {
if ($_POST['state'] == 'true') {
$state = 1;
}
elseif($_POST['state'] == 'false')
{
else if ($_POST['state'] == 'false') {
$state = 0;
}
else
{
else {
$state = 0;
}
$update = dbUpdate(array('sensor_alert' => $state), 'sensors', '`sensor_id` = ? AND `device_id` = ?', array($_POST['sensor_id'],$_POST['device_id']));
if(!empty($update) || $update == '0')
{
echo('success');
exit;
}
else
{
echo('error');
exit;
}
}
}
$update = dbUpdate(array('sensor_alert' => $state), 'sensors', '`sensor_id` = ? AND `device_id` = ?', array($_POST['sensor_id'], $_POST['device_id']));
if (!empty($update) || $update == '0') {
echo 'success';
exit;
}
else {
echo 'error';
exit;
}
}
}

View File

@ -12,33 +12,27 @@
* the source code distribution for details.
*/
if(!is_numeric($_POST['user_id']) || !isset($_POST['token']))
{
echo('ERROR: error with data, please ensure a valid user and token have been specified.');
if (!is_numeric($_POST['user_id']) || !isset($_POST['token'])) {
echo 'ERROR: error with data, please ensure a valid user and token have been specified.';
exit;
}
elseif(strlen($_POST['token']) > 32)
{
echo('ERROR: The token is more than 32 characters');
else if (strlen($_POST['token']) > 32) {
echo 'ERROR: The token is more than 32 characters';
exit;
}
elseif(strlen($_POST['token']) < 16)
{
echo('ERROR: The token is less than 16 characters');
else if (strlen($_POST['token']) < 16) {
echo 'ERROR: The token is less than 16 characters';
exit;
}
else
{
else {
$create = dbInsert(array('user_id' => $_POST['user_id'], 'token_hash' => $_POST['token'], 'description' => $_POST['description']), 'api_tokens');
if($create > '0')
{
echo('API token has been created');
$_SESSION['api_token'] = TRUE;
if ($create > '0') {
echo 'API token has been created';
$_SESSION['api_token'] = true;
exit;
}
else
{
echo('ERROR: An error occurred creating the API token');
else {
echo 'ERROR: An error occurred creating the API token';
exit;
}
}
}//end if

View File

@ -12,34 +12,28 @@
* the source code distribution for details.
*/
if(!is_numeric($_POST['token_id']))
{
echo('error with data');
if (!is_numeric($_POST['token_id'])) {
echo 'error with data';
exit;
}
else
{
if($_POST['state'] == 'true')
{
else {
if ($_POST['state'] == 'true') {
$state = 1;
}
elseif($_POST['state'] == 'false')
{
else if ($_POST['state'] == 'false') {
$state = 0;
}
else
{
else {
$state = 0;
}
$update = dbUpdate(array('disabled' => $state), 'api_tokens', '`id` = ?', array($_POST['token_id']));
if(!empty($update) || $update == '0')
{
echo('success');
if (!empty($update) || $update == '0') {
echo 'success';
exit;
}
else
{
echo('error');
else {
echo 'error';
exit;
}
}
}//end if

View File

@ -12,25 +12,20 @@
* the source code distribution for details.
*/
if(!is_numeric($_POST['token_id']))
{
echo('error with data');
if (!is_numeric($_POST['token_id'])) {
echo 'error with data';
exit;
}
else
{
if($_POST['confirm'] == 'yes')
{
else {
if ($_POST['confirm'] == 'yes') {
$delete = dbDelete('api_tokens', '`id` = ?', array($_POST['token_id']));
if($delete > '0')
{
echo('API token has been removed');
if ($delete > '0') {
echo 'API token has been removed';
exit;
}
else
{
echo('An error occurred removing the API token');
else {
echo 'An error occurred removing the API token';
exit;
}
}
}
}//end if

View File

@ -16,35 +16,28 @@ if(is_admin() === false) {
die('ERROR: You need to be admin');
}
if(!is_numeric($_POST['alert_id']))
{
echo('ERROR: No alert selected');
if (!is_numeric($_POST['alert_id'])) {
echo 'ERROR: No alert selected';
exit;
}
else
{
if($_POST['state'] == 'true')
{
else {
if ($_POST['state'] == 'true') {
$state = 0;
}
elseif($_POST['state'] == 'false')
{
else if ($_POST['state'] == 'false') {
$state = 1;
}
else
{
else {
$state = 1;
}
$update = dbUpdate(array('disabled' => $state), 'alert_rules', '`id`=?', array($_POST['alert_id']));
if(!empty($update) || $update == '0')
{
echo('Alert rule has been updated.');
exit;
}
else
{
echo('ERROR: Alert rule has not been updated.');
exit;
}
}
$update = dbUpdate(array('disabled' => $state), 'alert_rules', '`id`=?', array($_POST['alert_id']));
if (!empty($update) || $update == '0') {
echo 'Alert rule has been updated.';
exit;
}
else {
echo 'ERROR: Alert rule has not been updated.';
exit;
}
}

View File

@ -24,46 +24,58 @@ $status = 'error';
if (!is_numeric($config_id)) {
$message = 'ERROR: No alert selected';
} elseif ($action == 'update-textarea') {
}
else if ($action == 'update-textarea') {
$extras = explode(PHP_EOL, $_POST['config_value']);
foreach ($extras as $option) {
list($k,$v) = explode("=", $option,2);
list($k,$v) = explode('=', $option, 2);
if (!empty($k) || !empty($v)) {
if ($config_type == 'slack') {
$db_id[] = dbInsert(array('config_name' => 'alert.transports.slack.'.$config_id.'.'.$k, 'config_value' => $v, 'config_group' => 'alerting', 'config_sub_group' => 'transports', 'config_default' => $v, 'config_descr' => 'Slack Transport'), 'config');
} elseif ($config_type == 'hipchat') {
}
else if ($config_type == 'hipchat') {
$db_id[] = dbInsert(array('config_name' => 'alert.transports.hipchat.'.$config_id.'.'.$k, 'config_value' => $v, 'config_group' => 'alerting', 'config_sub_group' => 'transports', 'config_default' => $v, 'config_descr' => 'Hipchat Transport'), 'config');
} elseif ($config_type == 'pushover') {
}
else if ($config_type == 'pushover') {
$db_id[] = dbInsert(array('config_name' => 'alert.transports.pushover.'.$config_id.'.'.$k, 'config_value' => $v, 'config_group' => 'alerting', 'config_sub_group' => 'transports', 'config_default' => $v, 'config_descr' => 'Pushover Transport'), 'config');
}
}
}
$db_inserts = implode(",",$db_id);
$db_inserts = implode(',', $db_id);
if (!empty($db_inserts) || empty($_POST['config_value'])) {
if (empty($_POST['config_value'])) {
$db_inserts = 0;
}
if ($config_type == 'slack') {
dbDelete('config', "(`config_name` LIKE 'alert.transports.slack.$config_id.%' AND `config_name` != 'alert.transports.slack.$config_id.url' AND `config_id` NOT IN ($db_inserts))");
} elseif ($config_type == 'hipchat') {
}
else if ($config_type == 'hipchat') {
dbDelete('config', "(`config_name` LIKE 'alert.transports.hipchat.$config_id.%' AND (`config_name` != 'alert.transports.hipchat.$config_id.url' AND `config_name` != 'alert.transports.hipchat.$config_id.room_id' AND `config_name` != 'alert.transports.hipchat.$config_id.from') AND `config_id` NOT IN ($db_inserts))");
} elseif ($config_type == 'pushover') {
}
else if ($config_type == 'pushover') {
dbDelete('config', "(`config_name` LIKE 'alert.transports.pushover.$config_id.%' AND (`config_name` != 'alert.transports.pushover.$config_id.appkey' AND `config_name` != 'alert.transports.pushover.$config_id.userkey') AND `config_id` NOT IN ($db_inserts))");
}
}
$message = 'Config item has been updated:';
$status = 'ok';
} else {
}
else {
$state = mres($_POST['config_value']);
$update = dbUpdate(array('config_value' => $state), 'config', '`config_id`=?', array($config_id));
if(!empty($update) || $update == '0')
{
if (!empty($update) || $update == '0') {
$message = 'Alert rule has been updated.';
$status = 'ok';
} else {
}
else {
$message = 'ERROR: Alert rule has not been updated.';
}
}
}//end if
$response = array('status'=>$status,'message'=>$message);
$response = array(
'status' => $status,
'message' => $message,
);
echo _json_encode($response);

View File

@ -13,30 +13,28 @@
*
*/
include_once("../includes/defaults.inc.php");
include_once("../config.php");
include_once("../includes/definitions.inc.php");
require_once '../includes/defaults.inc.php';
require_once '../config.php';
require_once '../includes/definitions.inc.php';
include_once("../includes/common.php");
include_once("../includes/dbFacile.php");
include_once("../includes/rewrites.php");
include_once("includes/functions.inc.php");
include_once("includes/authenticate.inc.php");
require_once '../includes/common.php';
require_once '../includes/dbFacile.php';
require_once '../includes/rewrites.php';
require_once 'includes/functions.inc.php';
require_once 'includes/authenticate.inc.php';
include_once("../includes/snmp.inc.php");
require_once '../includes/snmp.inc.php';
if (is_numeric($_GET['id']) && ($config['allow_unauth_graphs'] || port_permitted($_GET['id'])))
{
if (is_numeric($_GET['id']) && ($config['allow_unauth_graphs'] || port_permitted($_GET['id']))) {
$port = get_port_by_id($_GET['id']);
$device = device_by_id_cache($port['device_id']);
$title = generate_device_link($device);
$title .= " :: Port ".generate_port_link($port);
$auth = TRUE;
} else {
}
else {
echo("Unauthenticad");
die;
}
header("Content-type: image/svg+xml");
@ -47,7 +45,9 @@ $ifname=ifLabel($port);
$ifname=$ifname['label']; //Interface name that will be showed on top right of graph
$hostname=shorthost($device['hostname']);
if($_GET['title']) { $ifname = $_GET['title']; }
if($_GET['title']) {
$ifname = $_GET['title'];
}
/********* Other conf *******/
$scale_type="follow"; //Autoscale default setup : "up" = only increase scale; "follow" = increase and decrease scale according to current graphed datas
@ -55,7 +55,8 @@ $nb_plot=240; //NB plot in graph
if(is_numeric($_GET['interval'])) {
$time_interval=$_GET['interval'];
} else {
}
else {
$time_interval=1; //Refresh time Interval
}

View File

@ -9,62 +9,57 @@
* @subpackage graphing
* @author Adam Armstrong <adama@memetic.org>
* @copyright (C) 2006 - 2012 Adam Armstrong
*
*/
function utime()
{
$time = explode(" ", microtime());
function utime() {
$time = explode(' ', microtime());
$usec = (double) $time[0];
$sec = (double) $time[1];
return $sec + $usec;
return ($sec + $usec);
}
$start = utime();
include_once("Net/IPv4.php");
require_once 'Net/IPv4.php';
if (isset($_GET['debug']))
{
$debug = TRUE;
if (isset($_GET['debug'])) {
$debug = true;
ini_set('display_errors', 1);
ini_set('display_startup_errors', 0);
ini_set('log_errors', 0);
ini_set('error_reporting', E_ALL);
}
else
{
$debug = FALSE;
else {
$debug = false;
ini_set('display_errors', 0);
ini_set('display_startup_errors', 0);
ini_set('log_errors', 0);
ini_set('error_reporting', 0);
}
include_once("../includes/defaults.inc.php");
include_once("../config.php");
include_once("../includes/definitions.inc.php");
include_once("../includes/common.php");
include_once("../includes/console_colour.php");
include_once("../includes/dbFacile.php");
include_once("../includes/rewrites.php");
include_once("includes/functions.inc.php");
include_once("../includes/rrdtool.inc.php");
include_once("includes/authenticate.inc.php");
require_once '../includes/defaults.inc.php';
require_once '../config.php';
require_once '../includes/definitions.inc.php';
require_once '../includes/common.php';
require_once '../includes/console_colour.php';
require_once '../includes/dbFacile.php';
require_once '../includes/rewrites.php';
require_once 'includes/functions.inc.php';
require_once '../includes/rrdtool.inc.php';
require_once 'includes/authenticate.inc.php';
include("includes/graphs/graph.inc.php");
require 'includes/graphs/graph.inc.php';
$console_color = new Console_Color2();
$end = utime(); $run = $end - $start;;
$end = utime();
$run = ($end - $start);
if($debug) { echo("<br />Runtime ".$run." secs");
echo('<br />MySQL: Cell '.($db_stats['fetchcell']+0).'/'.round($db_stats['fetchcell_sec']+0,3).'s'.
' Row '.($db_stats['fetchrow']+0). '/'.round($db_stats['fetchrow_sec']+0,3).'s'.
' Rows '.($db_stats['fetchrows']+0).'/'.round($db_stats['fetchrows_sec']+0,3).'s'.
' Column '.($db_stats['fetchcol']+0). '/'.round($db_stats['fetchcol_sec']+0,3).'s');
if ($debug) {
echo '<br />Runtime '.$run.' secs';
echo ('<br />MySQL: Cell '.($db_stats['fetchcell'] + 0).'/'.round(($db_stats['fetchcell_sec'] + 0), 3).'s'.' Row '.($db_stats['fetchrow'] + 0).'/'.round(($db_stats['fetchrow_sec'] + 0), 3).'s'.' Rows '.($db_stats['fetchrows'] + 0).'/'.round(($db_stats['fetchrows_sec'] + 0), 3).'s'.' Column '.($db_stats['fetchcol'] + 0).'/'.round(($db_stats['fetchcol_sec'] + 0), 3).'s');
}
?>

BIN
html/images/os/mellanox.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

View File

@ -12,40 +12,40 @@
* the source code distribution for details.
*/
require_once("../includes/functions.php");
require_once '../includes/functions.php';
function authToken(\Slim\Route $route)
{
function authToken(\Slim\Route $route) {
$app = \Slim\Slim::getInstance();
$token = $app->request->headers->get('X-Auth-Token');
if(isset($token) && !empty($token))
{
$username = dbFetchCell("SELECT `U`.`username` FROM `api_tokens` AS AT JOIN `users` AS U ON `AT`.`user_id`=`U`.`user_id` WHERE `AT`.`token_hash`=?", array($token));
if(!empty($username))
{
if (isset($token) && !empty($token)) {
$username = dbFetchCell('SELECT `U`.`username` FROM `api_tokens` AS AT JOIN `users` AS U ON `AT`.`user_id`=`U`.`user_id` WHERE `AT`.`token_hash`=?', array($token));
if (!empty($username)) {
$authenticated = true;
}
else
{
else {
$authenticated = false;
}
}
else
{
else {
$authenticated = false;
}
if($authenticated === false)
{
if ($authenticated === false) {
$app->response->setStatus(401);
$output = array("status" => "error", "message" => "API Token is missing or invalid; please supply a valid token");
$output = array(
'status' => 'error',
'message' => 'API Token is missing or invalid; please supply a valid token',
);
echo _json_encode($output);
$app->stop();
}
}
function get_graph_by_port_hostname()
{
function get_graph_by_port_hostname() {
// This will return a graph for a given port by the ifName
global $config;
$app = \Slim\Slim::getInstance();
@ -54,24 +54,25 @@ function get_graph_by_port_hostname()
$vars = array();
$vars['port'] = urldecode($router['ifname']);
$vars['type'] = $router['type'] ?: 'port_bits';
if(!empty($_GET['from']))
{
if (!empty($_GET['from'])) {
$vars['from'] = $_GET['from'];
}
if(!empty($_GET['to']))
{
if (!empty($_GET['to'])) {
$vars['to'] = $_GET['to'];
}
$vars['width'] = $_GET['width'] ?: 1075;
$vars['height'] = $_GET['height'] ?: 300;
$auth = "1";
$vars['id'] = dbFetchCell("SELECT `P`.`port_id` FROM `ports` AS `P` JOIN `devices` AS `D` ON `P`.`device_id` = `D`.`device_id` WHERE `D`.`hostname`=? AND `P`.`ifName`=?", array($hostname,$vars['port']));
$auth = '1';
$vars['id'] = dbFetchCell('SELECT `P`.`port_id` FROM `ports` AS `P` JOIN `devices` AS `D` ON `P`.`device_id` = `D`.`device_id` WHERE `D`.`hostname`=? AND `P`.`ifName`=?', array($hostname, $vars['port']));
$app->response->headers->set('Content-Type', 'image/png');
require("includes/graphs/graph.inc.php");
include 'includes/graphs/graph.inc.php';
}
function get_port_stats_by_port_hostname()
{
function get_port_stats_by_port_hostname() {
// This will return port stats based on a devices hostname and ifName
global $config;
$app = \Slim\Slim::getInstance();
@ -79,14 +80,18 @@ function get_port_stats_by_port_hostname()
$hostname = $router['hostname'];
$device_id = ctype_digit($hostname) ? $hostname : getidbyname($hostname);
$ifName = urldecode($router['ifname']);
$stats = dbFetchRow("SELECT * FROM `ports` WHERE `device_id`=? AND `ifName`=?", array($device_id,$ifName));
$output = array("status" => "ok", "port" => $stats);
$stats = dbFetchRow('SELECT * FROM `ports` WHERE `device_id`=? AND `ifName`=?', array($device_id, $ifName));
$output = array(
'status' => 'ok',
'port' => $stats,
);
$app->response->headers->set('Content-Type', 'application/json');
echo _json_encode($output);
}
function get_graph_generic_by_hostname()
{
function get_graph_generic_by_hostname() {
// This will return a graph type given a device id.
global $config;
$app = \Slim\Slim::getInstance();
@ -94,24 +99,25 @@ function get_graph_generic_by_hostname()
$hostname = $router['hostname'];
$vars = array();
$vars['type'] = $router['type'] ?: 'device_uptime';
if(!empty($_GET['from']))
{
if (!empty($_GET['from'])) {
$vars['from'] = $_GET['from'];
}
if(!empty($_GET['to']))
{
if (!empty($_GET['to'])) {
$vars['to'] = $_GET['to'];
}
$vars['width'] = $_GET['width'] ?: 1075;
$vars['height'] = $_GET['height'] ?: 300;
$auth = "1";
$vars['device'] = dbFetchCell("SELECT `D`.`device_id` FROM `devices` AS `D` WHERE `D`.`hostname`=?", array($hostname));
$auth = '1';
$vars['device'] = dbFetchCell('SELECT `D`.`device_id` FROM `devices` AS `D` WHERE `D`.`hostname`=?', array($hostname));
$app->response->headers->set('Content-Type', 'image/png');
require("includes/graphs/graph.inc.php");
include 'includes/graphs/graph.inc.php';
}
function get_device()
{
function get_device() {
// return details of a single device
$app = \Slim\Slim::getInstance();
$app->response->headers->set('Content-Type', 'application/json');
@ -125,100 +131,103 @@ function get_device()
$device = device_by_id_cache($device_id);
if (!$device) {
$app->response->setStatus(404);
$output = array("status" => "error", "message" => "Device $hostname does not exist");
$output = array(
'status' => 'error',
'message' => "Device $hostname does not exist",
);
echo _json_encode($output);
$app->stop();
}
else {
$output = array("status" => "ok", "devices" => array($device));
$output = array(
'status' => 'ok',
'devices' => array($device),
);
echo _json_encode($output);
}
}
function list_devices()
{
function list_devices() {
// This will return a list of devices
global $config;
$app = \Slim\Slim::getInstance();
$order = $_GET['order'];
$type = $_GET['type'];
if(empty($order))
{
$order = "hostname";
}
if(stristr($order,' desc') === FALSE && stristr($order, ' asc') === FALSE)
{
$order .= ' ASC';
}
if($type == 'all' || empty($type))
{
$sql = "1";
}
elseif($type == 'ignored')
{
$sql = "ignore='1' AND disabled='0'";
}
elseif($type == 'up')
{
$sql = "status='1' AND ignore='0' AND disabled='0'";
}
elseif($type == 'down')
{
$sql = "status='0' AND ignore='0' AND disabled='0'";
}
elseif($type == 'disabled')
{
$sql = "disabled='1'";
}
else
{
$sql = "1";
}
$devices = array();
foreach (dbFetchRows("SELECT * FROM `devices` WHERE $sql ORDER by $order") as $device)
{
$devices[] = $device;
}
$output = array("status" => "ok", "devices" => $devices);
$app->response->headers->set('Content-Type', 'application/json');
echo _json_encode($output);
if (empty($order)) {
$order = 'hostname';
}
function add_device()
{
if (stristr($order, ' desc') === false && stristr($order, ' asc') === false) {
$order .= ' ASC';
}
if ($type == 'all' || empty($type)) {
$sql = '1';
}
else if ($type == 'ignored') {
$sql = "ignore='1' AND disabled='0'";
}
else if ($type == 'up') {
$sql = "status='1' AND ignore='0' AND disabled='0'";
}
else if ($type == 'down') {
$sql = "status='0' AND ignore='0' AND disabled='0'";
}
else if ($type == 'disabled') {
$sql = "disabled='1'";
}
else {
$sql = '1';
}
$devices = array();
foreach (dbFetchRows("SELECT * FROM `devices` WHERE $sql ORDER by $order") as $device) {
$devices[] = $device;
}
$output = array(
'status' => 'ok',
'devices' => $devices,
);
$app->response->headers->set('Content-Type', 'application/json');
echo _json_encode($output);
}
function add_device() {
// This will add a device using the data passed encoded with json
// FIXME: Execution flow through this function could be improved
global $config;
$app = \Slim\Slim::getInstance();
$data = json_decode(file_get_contents('php://input'), true);
// Default status & code to error and change it if we need to.
$status = "error";
$status = 'error';
$code = 500;
// keep scrutinizer from complaining about snmpver not being set for all execution paths
$snmpver = "v2c";
if(empty($data))
{
$message = "No information has been provided to add this new device";
$snmpver = 'v2c';
if (empty($data)) {
$message = 'No information has been provided to add this new device';
}
elseif(empty($data["hostname"]))
{
$message = "Missing the device hostname";
else if (empty($data['hostname'])) {
$message = 'Missing the device hostname';
}
$hostname = $data['hostname'];
$port = $data['port'] ? mres($data['port']) : $config['snmp']['port'];
$transport = $data['transport'] ? mres($data['transport']) : "udp";
$transport = $data['transport'] ? mres($data['transport']) : 'udp';
$poller_group = $data['poller_group'] ? mres($data['poller_group']) : 0;
$force_add = $data['force_add'] ? mres($data['force_add']) : 0;
if($data['version'] == "v1" || $data['version'] == "v2c")
{
if ($data['community'])
{
if ($data['version'] == 'v1' || $data['version'] == 'v2c') {
if ($data['community']) {
$config['snmp']['community'] = array($data['community']);
}
$snmpver = mres($data['version']);
}
elseif($data['version'] == 'v3')
{
else if ($data['version'] == 'v3') {
$v3 = array(
'authlevel' => mres($data['authlevel']),
'authname' => mres($data['authname']),
@ -229,57 +238,58 @@ function add_device()
);
array_push($config['snmp']['v3'], $v3);
$snmpver = "v3";
$snmpver = 'v3';
}
else
{
else {
$code = 400;
$status = "error";
$status = 'error';
$message = "You haven't specified an SNMP version to use";
}
if(empty($message))
{
if (empty($message)) {
$result = addHost($hostname, $snmpver, $port, $transport, 1, $poller_group, $force_add);
if($result)
{
if ($result) {
$code = 201;
$status = "ok";
$status = 'ok';
$message = "Device $hostname has been added successfully";
}
else
{
else {
$message = "Failed adding $hostname";
}
}
$app->response->setStatus($code);
$output = array("status" => $status, "message" => $message);
$output = array(
'status' => $status,
'message' => $message,
);
$app->response->headers->set('Content-Type', 'application/json');
echo _json_encode($output);
}
function del_device()
{
function del_device() {
// This will add a device using the data passed encoded with json
global $config;
$app = \Slim\Slim::getInstance();
$router = $app->router()->getCurrentRoute()->getParams();
$hostname = $router['hostname'];
// Default status to error and change it if we need to.
$status = "error";
$status = 'error';
$code = 500;
if(empty($hostname) || $config['api_demo'] == 1)
{
$message = "No hostname has been provided to delete";
if (empty($hostname) || $config['api_demo'] == 1) {
$message = 'No hostname has been provided to delete';
if ($config['api_demo'] == 1) {
$message = "This feature isn\'t available in the demo";
}
$output = array("status" => $status, "message" => $message);
}
else
{
$output = array(
'status' => $status,
'message' => $message,
);
}
else {
// allow deleting by device_id or hostname
$device_id = ctype_digit($hostname) ? $hostname : getidbyname($hostname);
$device = null;
@ -287,31 +297,44 @@ function del_device()
// save the current details for returning to the client on successful delete
$device = device_by_id_cache($device_id);
}
if ($device) {
$response = delete_device($device_id);
if (empty($response)) {
// FIXME: Need to provide better diagnostics out of delete_device
$output = array("status" => $status, "message" => "Device deletion failed");
$output = array(
'status' => $status,
'message' => 'Device deletion failed',
);
}
else {
// deletion succeeded - include old device details in response
$code = 200;
$status = "ok";
$output = array("status" => $status, "message" => $response, "devices" => array($device));
$status = 'ok';
$output = array(
'status' => $status,
'message' => $response,
'devices' => array($device),
);
}
}
else {
// no device matching the name
$code = 404;
$output = array("status" => $status, "message" => "Device $hostname not found");
$output = array(
'status' => $status,
'message' => "Device $hostname not found",
);
}
}
$app->response->setStatus($code);
$app->response->headers->set('Content-Type', 'application/json');
echo _json_encode($output);
}
function get_vlans() {
// This will list all vlans for a given device
global $config;
@ -320,30 +343,46 @@ function get_vlans() {
$hostname = $router['hostname'];
$code = 500;
if (empty($hostname)) {
$output = $output = array("status" => "error", "message" => "No hostname has been provided");
} else {
require_once("../includes/functions.php");
$output = $output = array(
'status' => 'error',
'message' => 'No hostname has been provided',
);
}
else {
include_once '../includes/functions.php';
$device_id = ctype_digit($hostname) ? $hostname : getidbyname($hostname);
$device = null;
if ($device_id) {
// save the current details for returning to the client on successful delete
$device = device_by_id_cache($device_id);
}
if ($device) {
$vlans = dbFetchRows("SELECT vlan_vlan,vlan_domain,vlan_name,vlan_type,vlan_mtu FROM vlans WHERE `device_id` = ?", array($device_id));
$vlans = dbFetchRows('SELECT vlan_vlan,vlan_domain,vlan_name,vlan_type,vlan_mtu FROM vlans WHERE `device_id` = ?', array($device_id));
$total_vlans = count($vlans);
$code = 200;
$output = array("status" => "ok", "count" => $total_vlans, "vlans" => $vlans);
} else {
$output = array(
'status' => 'ok',
'count' => $total_vlans,
'vlans' => $vlans,
);
}
else {
$code = 404;
$output = array("status" => "error", "Device $hostname not found");
$output = array(
'status' => 'error', "Device $hostname not found"
);
}
}
$app->response->setStatus($code);
$app->response->headers->set('Content-Type', 'application/json');
echo _json_encode($output);
}
function show_endpoints() {
global $config;
$app = \Slim\Slim::getInstance();
@ -352,11 +391,14 @@ function show_endpoints() {
foreach ($routes as $route) {
$output[$route->getName()] = $config['base_url'].$route->getPattern();
}
$app->response->setStatus('200');
$app->response->headers->set('Content-Type', 'application/json');
echo _json_encode($output);
}
function list_bgp() {
global $config;
$app = \Slim\Slim::getInstance();
@ -368,9 +410,10 @@ function list_bgp() {
$hostname = $_GET['hostname'];
$device_id = ctype_digit($hostname) ? $hostname : getidbyname($hostname);
if (is_numeric($device_id)) {
$sql = " AND `device_id`=?";
$sql = ' AND `device_id`=?';
$sql_params = array($device_id);
}
$bgp_sessions = dbFetchRows("SELECT * FROM bgpPeers WHERE `bgpPeerState` IS NOT NULL AND `bgpPeerState` != '' $sql", $sql_params);
$total_bgp_sessions = count($bgp_sessions);
if (is_numeric($total_bgp_sessions)) {
@ -378,55 +421,64 @@ function list_bgp() {
$status = 'ok';
$message = '';
}
$output = array("status" => "$status", "err-msg" => $message, "count" => $total_bgp_sessions, "bgp_sessions" => $bgp_sessions);
$output = array(
'status' => "$status",
'err-msg' => $message,
'count' => $total_bgp_sessions,
'bgp_sessions' => $bgp_sessions,
);
$app->response->setStatus($code);
$app->response->headers->set('Content-Type', 'application/json');
echo _json_encode($output);
}
function get_graph_by_portgroup() {
global $config;
$app = \Slim\Slim::getInstance();
$router = $app->router()->getCurrentRoute()->getParams();
$group = $router['group'];
$vars = array();
if(!empty($_GET['from']))
{
if (!empty($_GET['from'])) {
$vars['from'] = $_GET['from'];
}
if(!empty($_GET['to']))
{
if (!empty($_GET['to'])) {
$vars['to'] = $_GET['to'];
}
$vars['width'] = $_GET['width'] ?: 1075;
$vars['height'] = $_GET['height'] ?: 300;
$auth = "1";
$type_where = " (";
$auth = '1';
$type_where = ' (';
$or = '';
$type_param = array();
foreach (explode(",", $group) as $type)
{
foreach (explode(',', $group) as $type) {
$type_where .= " $or `port_descr_type` = ?";
$or = "OR";
$or = 'OR';
$type_param[] = $type;
}
$type_where .= ") ";
$type_where .= ') ';
$if_list = '';
$seperator = '';
$ports = dbFetchRows("SELECT * FROM `ports` as I, `devices` AS D WHERE $type_where AND I.device_id = D.device_id ORDER BY I.ifAlias", $type_param);
foreach ($ports as $port)
{
foreach ($ports as $port) {
$if_list .= $seperator.$port['port_id'];
$seperator = ",";
$seperator = ',';
}
unset($seperator);
$vars['type'] = "multiport_bits_separate";
$vars['type'] = 'multiport_bits_separate';
$vars['id'] = $if_list;
$app->response->headers->set('Content-Type', 'image/png');
require("includes/graphs/graph.inc.php");
include 'includes/graphs/graph.inc.php';
}
function get_graphs() {
global $config;
$code = 200;
@ -440,19 +492,36 @@ function get_graphs() {
// use hostname as device_id if it's all digits
$device_id = ctype_digit($hostname) ? $hostname : getidbyname($hostname);
$graphs = array();
$graphs[] = array('desc' => 'Poller Time', 'name' => 'device_poller_perf');
$graphs[] = array('desc' => 'Ping Response', 'name' => 'device_ping_perf');
foreach (dbFetchRows("SELECT * FROM device_graphs WHERE device_id = ? ORDER BY graph", array($device_id)) as $graph) {
$graphs[] = array(
'desc' => 'Poller Time',
'name' => 'device_poller_perf',
);
$graphs[] = array(
'desc' => 'Ping Response',
'name' => 'device_ping_perf',
);
foreach (dbFetchRows('SELECT * FROM device_graphs WHERE device_id = ? ORDER BY graph', array($device_id)) as $graph) {
$desc = $config['graph_types']['device'][$graph['graph']]['descr'];
$graphs[] = array('desc' => $desc, 'name' => 'device_'.$graph['graph']);
$graphs[] = array(
'desc' => $desc,
'name' => 'device_'.$graph['graph'],
);
}
$total_graphs = count($graphs);
$output = array("status" => "$status", "err-msg" => $message, "count" => $total_graphs, "graphs" => $graphs);
$output = array(
'status' => "$status",
'err-msg' => $message,
'count' => $total_graphs,
'graphs' => $graphs,
);
$app->response->setStatus($code);
$app->response->headers->set('Content-Type', 'application/json');
echo _json_encode($output);
}
function get_port_graphs() {
global $config;
$app = \Slim\Slim::getInstance();
@ -460,7 +529,8 @@ function get_port_graphs() {
$hostname = $router['hostname'];
if (isset($_GET['columns'])) {
$columns = $_GET['columns'];
} else {
}
else {
$columns = 'ifName';
}
@ -468,41 +538,61 @@ function get_port_graphs() {
$device_id = ctype_digit($hostname) ? $hostname : getidbyname($hostname);
$ports = dbFetchRows("SELECT $columns FROM `ports` WHERE `device_id` = ? AND `deleted` = '0' ORDER BY `ifIndex` ASC", array($device_id));
$total_ports = count($ports);
$output = array("status" => "ok", "err-msg" => '', "count" => $total_ports, "ports" => $ports);
$output = array(
'status' => 'ok',
'err-msg' => '',
'count' => $total_ports,
'ports' => $ports,
);
$app->response->setStatus('200');
$app->response->headers->set('Content-Type', 'application/json');
echo _json_encode($output);
}
function list_bills() {
global $config;
$app = \Slim\Slim::getInstance();
$router = $app->router()->getCurrentRoute()->getParams();
$bill_id = $router['bill_id'];
if (isset($_GET['custid'])) {
$sql = "`bill_custid` = ?";
$sql = '`bill_custid` = ?';
$param = array($_GET['custid']);
} elseif(isset($_GET['ref'])) {
$sql = "`bill_ref` = ?";
}
else if (isset($_GET['ref'])) {
$sql = '`bill_ref` = ?';
$param = array($_GET['ref']);
} elseif(is_numeric($bill_id)) {
$sql = "`bill_id` = ?";
}
else if (is_numeric($bill_id)) {
$sql = '`bill_id` = ?';
$param = array($bill_id);
} else {
$sql = "";
}
else {
$sql = '';
$param = array();
}
if (count($param) >= 1) {
$sql = "WHERE $sql";
}
$bills = dbFetchRows("SELECT * FROM `bills` $sql", $param);
$total_bills = count($bills);
$output = array("status" => "ok", "err-msg" => '', "count" => $total_bills, "bills" => $bills);
$output = array(
'status' => 'ok',
'err-msg' => '',
'count' => $total_bills,
'bills' => $bills,
);
$app->response->setStatus('200');
$app->response->headers->set('Content-Type', 'application/json');
echo _json_encode($output);
}
function list_alert_rules() {
global $config;
$app = \Slim\Slim::getInstance();
@ -511,40 +601,58 @@ function list_alert_rules() {
$param = array();
if (isset($router['id']) && $router['id'] > 0) {
$rule_id = mres($router['id']);
$sql = "WHERE id=?";
$sql = 'WHERE id=?';
$param = array($rule_id);
}
$rules = dbFetchRows("SELECT * FROM `alert_rules` $sql", $param);
$total_rules = count($rules);
$output = array("status" => "ok", "err-msg" => '', "count" => $total_rules, "rules" => $rules);
$output = array(
'status' => 'ok',
'err-msg' => '',
'count' => $total_rules,
'rules' => $rules,
);
$app->response->setStatus('200');
$app->response->headers->set('Content-Type', 'application/json');
echo _json_encode($output);
}
function list_alerts() {
global $config;
$app = \Slim\Slim::getInstance();
$router = $app->router()->getCurrentRoute()->getParams();
if (isset($_POST['state'])) {
$param = array(mres($_POST['state']));
} else {
}
else {
$param = array('1');
}
$sql = '';
if (isset($router['id']) && $router['id'] > 0) {
$alert_id = mres($router['id']);
$sql = "AND id=?";
$sql = 'AND id=?';
array_push($param, $alert_id);
}
$alerts = dbFetchRows("SELECT `D`.`hostname`, `A`.* FROM `alerts` AS `A`, `devices` AS `D` WHERE `D`.`device_id` = `A`.`device_id` AND `A`.`state` IN (?) $sql", $param);
$total_alerts = count($alerts);
$output = array("status" => "ok", "err-msg" => '', "count" => $total_alerts, "alerts" => $alerts);
$output = array(
'status' => 'ok',
'err-msg' => '',
'count' => $total_alerts,
'alerts' => $alerts,
);
$app->response->setStatus('200');
$app->response->headers->set('Content-Type', 'application/json');
echo _json_encode($output);
}
function add_edit_rule() {
global $config;
$app = \Slim\Slim::getInstance();
@ -559,7 +667,8 @@ function add_edit_rule() {
$device_id = mres($data['device_id']);
if (empty($device_id) && !isset($rule_id)) {
$message = 'Missing the device id or global device id (-1)';
} elseif($device_id == 0) {
}
else if ($device_id == 0) {
$device_id = '-1';
}
@ -567,15 +676,22 @@ function add_edit_rule() {
if (empty($rule)) {
$message = 'Missing the alert rule';
}
$name = mres($data['name']);
if (empty($name)) {
$message = 'Missing the alert rule name';
}
$severity = mres($data['severity']);
$sevs = array("ok","warning","critical");
$sevs = array(
'ok',
'warning',
'critical',
);
if (!in_array($severity, $sevs)) {
$message = 'Missing the severity';
}
$disabled = mres($data['disabled']);
if ($disabled != '0' && $disabled != '1') {
$disabled = 0;
@ -587,14 +703,19 @@ function add_edit_rule() {
$delay_sec = convert_delay($delay);
if ($mute == 1) {
$mute = true;
} else {
}
else {
$mute = false;
}
$extra = array('mute'=>$mute,'count'=>$count,'delay'=>$delay_sec);
$extra = array(
'mute' => $mute,
'count' => $count,
'delay' => $delay_sec,
);
$extra_json = json_encode($extra);
if (dbFetchCell("SELECT `name` FROM `alert_rules` WHERE `name`=?",array($name)) == $name) {
if (dbFetchCell('SELECT `name` FROM `alert_rules` WHERE `name`=?', array($name)) == $name) {
$message = 'Name has already been used';
}
@ -603,22 +724,32 @@ function add_edit_rule() {
if (dbUpdate(array('name' => $name, 'rule' => $rule, 'severity' => $severity, 'disabled' => $disabled, 'extra' => $extra_json), 'alert_rules', 'id=?', array($rule_id)) >= 0) {
$status = 'ok';
$code = 200;
} else {
}
else {
$message = 'Failed to update existing alert rule';
}
} elseif( dbInsert(array('name' => $name, 'device_id'=>$device_id,'rule'=>$rule,'severity'=>$severity,'disabled'=>$disabled,'extra'=>$extra_json),'alert_rules') ) {
}
else if (dbInsert(array('name' => $name, 'device_id' => $device_id, 'rule' => $rule, 'severity' => $severity, 'disabled' => $disabled, 'extra' => $extra_json), 'alert_rules')) {
$status = 'ok';
$code = 200;
} else {
}
else {
$message = 'Failed to create new alert rule';
}
}
$output = array("status" => $status, "err-msg" => $message);
$output = array(
'status' => $status,
'err-msg' => $message,
);
$app->response->setStatus($code);
$app->response->headers->set('Content-Type', 'application/json');
echo _json_encode($output);
}
function delete_rule() {
global $config;
$app = \Slim\Slim::getInstance();
@ -631,20 +762,30 @@ function delete_rule() {
if (is_numeric($rule_id)) {
$status = 'ok';
$code = 200;
if(dbDelete('alert_rules', "`id` = ? LIMIT 1", array($rule_id))) {
if (dbDelete('alert_rules', '`id` = ? LIMIT 1', array($rule_id))) {
$message = 'Alert rule has been removed';
} else {
}
else {
$message = 'No alert rule by that ID';
}
} else {
}
else {
$err_msg = 'Invalid rule id has been provided';
}
$output = array("status" => $status, "err-msg" => $err_msg, "message" => $message);
$output = array(
'status' => $status,
'err-msg' => $err_msg,
'message' => $message,
);
$app->response->setStatus($code);
$app->response->headers->set('Content-Type', 'application/json');
echo _json_encode($output);
}
function ack_alert() {
global $config;
$app = \Slim\Slim::getInstance();
@ -657,20 +798,29 @@ function ack_alert() {
if (is_numeric($alert_id)) {
$status = 'ok';
$code = 200;
if(dbUpdate(array("state" => 2), 'alerts', '`id` = ? LIMIT 1', array($alert_id))) {
if (dbUpdate(array('state' => 2), 'alerts', '`id` = ? LIMIT 1', array($alert_id))) {
$message = 'Alert has been ackgnowledged';
} else {
}
else {
$message = 'No alert by that ID';
}
} else {
}
else {
$err_msg = 'Invalid alert has been provided';
}
$output = array("status" => $status, "err-msg" => $err_msg, "message" => $message);
$output = array(
'status' => $status,
'err-msg' => $err_msg,
'message' => $message,
);
$app->response->setStatus($code);
$app->response->headers->set('Content-Type', 'application/json');
echo _json_encode($output);
}
function get_inventory() {
global $config;
$app = \Slim\Slim::getInstance();
@ -687,28 +837,41 @@ function get_inventory() {
$sql .= ' AND entPhysicalClass=?';
$params[] = mres($_GET['entPhysicalClass']);
}
if (isset($_GET['entPhysicalContainedIn']) && !empty($_GET['entPhysicalContainedIn'])) {
$sql .= ' AND entPhysicalContainedIn=?';
$params[] = mres($_GET['entPhysicalContainedIn']);
} else {
}
else {
$sql .= ' AND entPhysicalContainedIn="0"';
}
if (!is_numeric($device_id)) {
$err_msg = 'Invalid device provided';
$total_inv = 0;
$inventory = array();
} else {
}
else {
$inventory = dbFetchRows("SELECT * FROM `entPhysical` WHERE 1 $sql", $params);
$code = 200;
$status = 'ok';
$total_inv = count($inventory);
}
$output = array("status" => $status, "err-msg" => $err_msg, "count" => $total_inv, "inventory" => $inventory);
$output = array(
'status' => $status,
'err-msg' => $err_msg,
'count' => $total_inv,
'inventory' => $inventory,
);
$app->response->setStatus($code);
$app->response->headers->set('Content-Type', 'application/json');
echo _json_encode($output);
}
function list_oxidized() {
// return details of a single device
$app = \Slim\Slim::getInstance();
@ -718,6 +881,7 @@ function list_oxidized() {
foreach (dbFetchRows("SELECT hostname,os FROM `devices` WHERE `status`='1'") as $device) {
$devices[] = $device;
}
$app->response->headers->set('Content-Type', 'application/json');
echo _json_encode($devices);

View File

@ -1,42 +1,38 @@
<?php
@ini_set("session.gc_maxlifetime","0");
@ini_set('session.gc_maxlifetime', '0');
@ini_set('session.use_only_cookies', 1);
@ini_set('session.cookie_httponly', 1);
require('includes/PasswordHash.php');
require 'includes/PasswordHash.php';
session_start();
// Preflight checks
if (!is_dir($config['rrd_dir']))
{
echo("<div class='errorbox'>RRD Log Directory is missing ({$config['rrd_dir']}). Graphing may fail.</div>");
if (!is_dir($config['rrd_dir'])) {
echo "<div class='errorbox'>RRD Log Directory is missing ({$config['rrd_dir']}). Graphing may fail.</div>";
}
if (!is_dir($config['temp_dir']))
{
echo("<div class='errorbox'>Temp Directory is missing ({$config['temp_dir']}). Graphing may fail.</div>");
if (!is_dir($config['temp_dir'])) {
echo "<div class='errorbox'>Temp Directory is missing ({$config['temp_dir']}). Graphing may fail.</div>";
}
if (!is_writable($config['temp_dir']))
{
echo("<div class='errorbox'>Temp Directory is not writable ({$config['tmp_dir']}). Graphing may fail.</div>");
if (!is_writable($config['temp_dir'])) {
echo "<div class='errorbox'>Temp Directory is not writable ({$config['tmp_dir']}). Graphing may fail.</div>";
}
// Clear up any old sessions
dbDelete('session', "`session_expiry` < ?", array(time()));
dbDelete('session', '`session_expiry` < ?', array(time()));
if ($vars['page'] == "logout" && $_SESSION['authenticated'])
{
if ($vars['page'] == 'logout' && $_SESSION['authenticated']) {
dbInsert(array('user' => $_SESSION['username'], 'address' => get_client_ip(), 'result' => 'Logged Out'), 'authlog');
dbDelete('session', "`session_username` = ? AND session_value = ?", array($_SESSION['username'],$_COOKIE['sess_id']));
dbDelete('session', '`session_username` = ? AND session_value = ?', array($_SESSION['username'], $_COOKIE['sess_id']));
unset($_SESSION);
unset($_COOKIE);
setcookie ("sess_id", "", time() - 60*60*24*$config['auth_remember'], "/");
setcookie ("token", "", time() - 60*60*24*$config['auth_remember'], "/");
setcookie ("auth", "", time() - 60*60*24*$config['auth_remember'], "/");
setcookie('sess_id', '', (time() - 60 * 60 * 24 * $config['auth_remember']), '/');
setcookie('token', '', (time() - 60 * 60 * 24 * $config['auth_remember']), '/');
setcookie('auth', '', (time() - 60 * 60 * 24 * $config['auth_remember']), '/');
session_destroy();
$auth_message = "Logged Out";
$auth_message = 'Logged Out';
header('Location: /');
exit;
}
@ -45,79 +41,74 @@ if ($vars['page'] == "logout" && $_SESSION['authenticated'])
if (isset($_POST['username']) && isset($_POST['password'])) {
$_SESSION['username'] = mres($_POST['username']);
$_SESSION['password'] = $_POST['password'];
} elseif(isset($_GET['username']) && isset($_GET['password'])) {
}
else if (isset($_GET['username']) && isset($_GET['password'])) {
$_SESSION['username'] = mres($_GET['username']);
$_SESSION['password'] = $_GET['password'];
}
if (!isset($config['auth_mechanism']))
{
$config['auth_mechanism'] = "mysql";
if (!isset($config['auth_mechanism'])) {
$config['auth_mechanism'] = 'mysql';
}
if (file_exists('includes/authentication/' . $config['auth_mechanism'] . '.inc.php'))
{
include_once('includes/authentication/' . $config['auth_mechanism'] . '.inc.php');
if (file_exists('includes/authentication/'.$config['auth_mechanism'].'.inc.php')) {
include_once 'includes/authentication/'.$config['auth_mechanism'].'.inc.php';
}
else
{
else {
print_error('ERROR: no valid auth_mechanism defined!');
exit();
}
$auth_success = 0;
if ((isset($_SESSION['username'])) || (isset($_COOKIE['sess_id'],$_COOKIE['token'])))
{
if ((authenticate($_SESSION['username'],$_SESSION['password'])) || (reauthenticate($_COOKIE['sess_id'],$_COOKIE['token'])))
{
if ((isset($_SESSION['username'])) || (isset($_COOKIE['sess_id'],$_COOKIE['token']))) {
if ((authenticate($_SESSION['username'], $_SESSION['password'])) || (reauthenticate($_COOKIE['sess_id'], $_COOKIE['token']))) {
$_SESSION['userlevel'] = get_userlevel($_SESSION['username']);
$_SESSION['user_id'] = get_userid($_SESSION['username']);
if (!$_SESSION['authenticated'])
{
if (!$_SESSION['authenticated']) {
if ($config['twofactor'] === true && !isset($_SESSION['twofactor'])) {
require_once($config['install_dir'].'/html/includes/authentication/twofactor.lib.php');
include_once $config['install_dir'].'/html/includes/authentication/twofactor.lib.php';
twofactor_auth();
}
if (!$config['twofactor'] || $_SESSION['twofactor']) {
$_SESSION['authenticated'] = true;
dbInsert(array('user' => $_SESSION['username'], 'address' => get_client_ip(), 'result' => 'Logged In'), 'authlog');
}
}
if (isset($_POST['remember']))
{
if (isset($_POST['remember'])) {
$sess_id = session_id();
$hasher = new PasswordHash(8, FALSE);
$hasher = new PasswordHash(8, false);
$token = strgen();
$auth = strgen();
$hasher = new PasswordHash(8, FALSE);
$hasher = new PasswordHash(8, false);
$token_id = $_SESSION['username'].'|'.$hasher->HashPassword($_SESSION['username'].$token);
// If we have been asked to remember the user then set the relevant cookies and create a session in the DB.
setcookie("sess_id", $sess_id, time()+60*60*24*$config['auth_remember'], "/", null, false, true);
setcookie("token", $token_id, time()+60*60*24*$config['auth_remember'], "/", null, false, true);
setcookie("auth", $auth, time()+60*60*24*$config['auth_remember'], "/", null, false, true);
setcookie('sess_id', $sess_id, (time() + 60 * 60 * 24 * $config['auth_remember']), '/', null, false, true);
setcookie('token', $token_id, (time() + 60 * 60 * 24 * $config['auth_remember']), '/', null, false, true);
setcookie('auth', $auth, (time() + 60 * 60 * 24 * $config['auth_remember']), '/', null, false, true);
dbInsert(array('session_username' => $_SESSION['username'], 'session_value' => $sess_id, 'session_token' => $token, 'session_auth' => $auth, 'session_expiry' => time() + 60 * 60 * 24 * $config['auth_remember']), 'session');
}
if (isset($_COOKIE['sess_id'],$_COOKIE['token'],$_COOKIE['auth']))
{
if (isset($_COOKIE['sess_id'],$_COOKIE['token'],$_COOKIE['auth'])) {
// If we have the remember me cookies set then update session expiry times to keep us logged in.
$sess_id = session_id();
dbUpdate(array('session_value' => $sess_id, 'session_expiry' => time() + 60 * 60 * 24 * $config['auth_remember']), 'session', 'session_auth=?', array($_COOKIE['auth']));
setcookie("sess_id", $sess_id, time()+60*60*24*$config['auth_remember'], "/", null, false, true);
setcookie("token", $_COOKIE['token'], time()+60*60*24*$config['auth_remember'], "/", null, false, true);
setcookie("auth", $_COOKIE['auth'], time()+60*60*24*$config['auth_remember'], "/", null, false, true);
setcookie('sess_id', $sess_id, (time() + 60 * 60 * 24 * $config['auth_remember']), '/', null, false, true);
setcookie('token', $_COOKIE['token'], (time() + 60 * 60 * 24 * $config['auth_remember']), '/', null, false, true);
setcookie('auth', $_COOKIE['auth'], (time() + 60 * 60 * 24 * $config['auth_remember']), '/', null, false, true);
}
$permissions = permissions_cache($_SESSION['user_id']);
if (isset($_POST['username'])) {
header('Location: '.$_SERVER['REQUEST_URI'],TRUE,303);
header('Location: '.$_SERVER['REQUEST_URI'], true, 303);
exit;
}
}
elseif (isset($_SESSION['username']))
{
$auth_message = "Authentication Failed";
else if (isset($_SESSION['username'])) {
$auth_message = 'Authentication Failed';
unset($_SESSION['authenticated']);
dbInsert(array('user' => $_SESSION['username'], 'address' => get_client_ip(), 'result' => 'Authentication Failure'), 'authlog');
}
}
?>

View File

@ -1,25 +1,21 @@
<?php
if (!isset($_SESSION['username']))
{
if (!isset($_SESSION['username'])) {
$_SESSION['username'] = '';
}
function authenticate($username,$password)
{
function authenticate($username, $password) {
global $config;
if (isset($_SERVER['REMOTE_USER']))
{
if (isset($_SERVER['REMOTE_USER'])) {
$_SESSION['username'] = mres($_SERVER['REMOTE_USER']);
$row = @dbFetchRow("SELECT username FROM `users` WHERE `username`=?", array($_SESSION['username']));
if (isset($row['username']) && $row['username'] == $_SESSION['username'])
{
$row = @dbFetchRow('SELECT username FROM `users` WHERE `username`=?', array($_SESSION['username']));
if (isset($row['username']) && $row['username'] == $_SESSION['username']) {
return 1;
}
else
{
else {
$_SESSION['username'] = $config['http_auth_guest'];
return 1;
}
@ -27,78 +23,77 @@ function authenticate($username,$password)
return 0;
}
function reauthenticate($sess_id = "",$token = "")
{
function reauthenticate($sess_id='', $token='') {
return 0;
}
function passwordscanchange($username = "")
{
function passwordscanchange($username='') {
return 0;
}
function changepassword($username,$newpassword)
{
# Not supported
function changepassword($username, $newpassword) {
// Not supported
}
function auth_usermanagement()
{
function auth_usermanagement() {
return 1;
}
function adduser($username, $password, $level, $email = "", $realname = "", $can_modify_passwd = '1')
{
function adduser($username, $password, $level, $email='', $realname='', $can_modify_passwd='1') {
if (!user_exists($username)) {
$hasher = new PasswordHash(8, FALSE);
$hasher = new PasswordHash(8, false);
$encrypted = $hasher->HashPassword($password);
return dbInsert(array('username' => $username, 'password' => $encrypted, 'level' => $level, 'email' => $email, 'realname' => $realname), 'users');
} else {
return FALSE;
}
else {
return false;
}
}
function user_exists($username)
{
function user_exists($username) {
// FIXME this doesn't seem right? (adama)
return dbFetchCell("SELECT * FROM `users` WHERE `username` = ?", array($username));
return dbFetchCell('SELECT * FROM `users` WHERE `username` = ?', array($username));
}
function get_userlevel($username)
{
return dbFetchCell("SELECT `level` FROM `users` WHERE `username`= ?", array($username));
function get_userlevel($username) {
return dbFetchCell('SELECT `level` FROM `users` WHERE `username`= ?', array($username));
}
function get_userid($username)
{
return dbFetchCell("SELECT `user_id` FROM `users` WHERE `username`= ?", array($username));
function get_userid($username) {
return dbFetchCell('SELECT `user_id` FROM `users` WHERE `username`= ?', array($username));
}
function deluser($username)
{
# Not supported
function deluser($username) {
// Not supported
return 0;
}
function get_userlist()
{
return dbFetchRows("SELECT * FROM `users`");
function get_userlist() {
return dbFetchRows('SELECT * FROM `users`');
}
function can_update_users()
{
# supported so return 1
function can_update_users() {
// supported so return 1
return 1;
}
function get_user($user_id)
{
return dbFetchRow("SELECT * FROM `users` WHERE `user_id` = ?", array($user_id));
function get_user($user_id) {
return dbFetchRow('SELECT * FROM `users` WHERE `user_id` = ?', array($user_id));
}
function update_user($user_id,$realname,$level,$can_modify_passwd,$email)
{
function update_user($user_id, $realname, $level, $can_modify_passwd, $email) {
dbUpdate(array('realname' => $realname, 'level' => $level, 'can_modify_passwd' => $can_modify_passwd, 'email' => $email), 'users', '`user_id` = ?', array($user_id));
}
?>

View File

@ -2,148 +2,148 @@
$ds = @ldap_connect($config['auth_ldap_server'], $config['auth_ldap_port']);
if ($config['auth_ldap_starttls'] && ($config['auth_ldap_starttls'] == 'optional' || $config['auth_ldap_starttls'] == 'require'))
{
if ($config['auth_ldap_starttls'] && ($config['auth_ldap_starttls'] == 'optional' || $config['auth_ldap_starttls'] == 'require')) {
$tls = ldap_start_tls($ds);
if ($config['auth_ldap_starttls'] == 'require' && $tls == FALSE)
{
echo("<h2>Fatal error: LDAP TLS required but not successfully negotiated:" . ldap_error($ds) . "</h2>");
if ($config['auth_ldap_starttls'] == 'require' && $tls == false) {
echo '<h2>Fatal error: LDAP TLS required but not successfully negotiated:'.ldap_error($ds).'</h2>';
exit;
}
}
function authenticate($username,$password)
{
function authenticate($username, $password) {
global $config, $ds;
if ($username && $ds)
{
if ($config['auth_ldap_version'])
{
if ($username && $ds) {
if ($config['auth_ldap_version']) {
ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, $config['auth_ldap_version']);
}
if (ldap_bind($ds, $config['auth_ldap_prefix'] . $username . $config['auth_ldap_suffix'], $password))
{
if (!$config['auth_ldap_group'])
{
if (ldap_bind($ds, $config['auth_ldap_prefix'].$username.$config['auth_ldap_suffix'], $password)) {
if (!$config['auth_ldap_group']) {
return 1;
}
else
{
else {
$ldap_groups = get_group_list();
foreach ($ldap_groups as $ldap_group) {
$ldap_comparison = ldap_compare($ds,
$ldap_comparison = ldap_compare(
$ds,
$ldap_group,
$config['auth_ldap_groupmemberattr'],
get_membername($username));
get_membername($username)
);
if ($ldap_comparison === true) {
return 1;
}
}
}
}
else
{
echo(ldap_error($ds));
else {
echo ldap_error($ds);
}
}
else
{
else {
// FIXME return a warning that LDAP couldn't connect?
}
return 0;
}
function reauthenticate($sess_id,$token)
{
function reauthenticate($sess_id, $token) {
return 0;
}
function passwordscanchange($username = "")
{
function passwordscanchange($username='') {
return 0;
}
function changepassword($username,$newpassword)
{
# Not supported (for now)
function changepassword($username, $newpassword) {
// Not supported (for now)
}
function auth_usermanagement()
{
function auth_usermanagement() {
return 0;
}
function adduser($username, $password, $level, $email = "", $realname = "", $can_modify_passwd = '1')
{
# Not supported
function adduser($username, $password, $level, $email='', $realname='', $can_modify_passwd='1') {
// Not supported
return 0;
}
function user_exists($username)
{
function user_exists($username) {
global $config, $ds;
$filter = "(" . $config['auth_ldap_prefix'] . $username . ")";
$filter = '('.$config['auth_ldap_prefix'].$username.')';
$search = ldap_search($ds, trim($config['auth_ldap_suffix'], ','), $filter);
$entries = ldap_get_entries($ds, $search);
if ($entries['count'])
{
if ($entries['count']) {
return 1;
}
return 0;
}
function get_userlevel($username)
{
function get_userlevel($username) {
global $config, $ds;
$userlevel = 0;
# Find all defined groups $username is in
$filter = "(&(|(cn=" . join(")(cn=", array_keys($config['auth_ldap_groups'])) . "))(". $config['auth_ldap_groupmemberattr']. "=" . get_membername($username) . "))";
// Find all defined groups $username is in
$filter = '(&(|(cn='.join(')(cn=', array_keys($config['auth_ldap_groups'])).'))('.$config['auth_ldap_groupmemberattr'].'='.get_membername($username).'))';
$search = ldap_search($ds, $config['auth_ldap_groupbase'], $filter);
$entries = ldap_get_entries($ds, $search);
# Loop the list and find the highest level
foreach ($entries as $entry)
{
// Loop the list and find the highest level
foreach ($entries as $entry) {
$groupname = $entry['cn'][0];
if ($config['auth_ldap_groups'][$groupname]['level'] > $userlevel)
{
if ($config['auth_ldap_groups'][$groupname]['level'] > $userlevel) {
$userlevel = $config['auth_ldap_groups'][$groupname]['level'];
}
}
return $userlevel;
}
function get_userid($username)
{
function get_userid($username) {
global $config, $ds;
$filter = "(" . $config['auth_ldap_prefix'] . $username . ")";
$filter = '('.$config['auth_ldap_prefix'].$username.')';
$search = ldap_search($ds, trim($config['auth_ldap_suffix'], ','), $filter);
$entries = ldap_get_entries($ds, $search);
if ($entries['count'])
{
if ($entries['count']) {
return $entries[0]['uidnumber'][0];
}
return -1;
}
function deluser($username)
{
# Not supported
function deluser($username) {
// Not supported
return 0;
}
function get_userlist()
{
function get_userlist() {
global $config, $ds;
$userlist = array();
@ -152,62 +152,70 @@ function get_userlist()
$search = ldap_search($ds, trim($config['auth_ldap_suffix'], ','), $filter);
$entries = ldap_get_entries($ds, $search);
if ($entries['count'])
{
foreach ($entries as $entry)
{
if ($entries['count']) {
foreach ($entries as $entry) {
$username = $entry['uid'][0];
$realname = $entry['cn'][0];
$user_id = $entry['uidnumber'][0];
$email = $entry[$config['auth_ldap_emailattr']][0];
$ldap_groups = get_group_list();
foreach ($ldap_groups as $ldap_group) {
$ldap_comparison = ldap_compare($ds,
$ldap_comparison = ldap_compare(
$ds,
$ldap_group,
$config['auth_ldap_groupmemberattr'],
get_membername($username));
get_membername($username)
);
if (!isset($config['auth_ldap_group']) || $ldap_comparison === true) {
$userlist[] = array('username' => $username, 'realname' => $realname, 'user_id' => $user_id, 'email' => $email);
$userlist[] = array(
'username' => $username,
'realname' => $realname,
'user_id' => $user_id,
'email' => $email,
);
}
}
}
}
return $userlist;
}
function can_update_users()
{
# not supported so return 0
function can_update_users() {
// not supported so return 0
return 0;
}
function get_user($user_id)
{
# not supported
function get_user($user_id) {
// not supported
return 0;
}
function update_user($user_id,$realname,$level,$can_modify_passwd,$email)
{
# not supported
function update_user($user_id, $realname, $level, $can_modify_passwd, $email) {
// not supported
return 0;
}
function get_membername ($username)
{
function get_membername($username) {
global $config;
if ($config['auth_ldap_groupmembertype'] == "fulldn")
{
if ($config['auth_ldap_groupmembertype'] == 'fulldn') {
$membername = $config['auth_ldap_prefix'].$username.$config['auth_ldap_suffix'];
}
else
{
else {
$membername = $username;
}
return $membername;
}
function get_group_list() {
global $config;
@ -218,11 +226,12 @@ function get_group_list() {
$ldap_groups[] = $config['auth_ldap_group'];
}
}
foreach ($config['auth_ldap_groups'] as $key => $value) {
$dn = "cn=$key,".$config['auth_ldap_groupbase'];
$ldap_groups[] = $dn;
}
return $ldap_groups;
}
?>
return $ldap_groups;
}

View File

@ -1,72 +1,70 @@
<?php
function authenticate($username,$password)
{
function authenticate($username, $password) {
$encrypted_old = md5($password);
$row = dbFetchRow("SELECT username,password FROM `users` WHERE `username`= ?", array($username));
if ($row['username'] && $row['username'] == $username)
{
$row = dbFetchRow('SELECT username,password FROM `users` WHERE `username`= ?', array($username));
if ($row['username'] && $row['username'] == $username) {
// Migrate from old, unhashed password
if ($row['password'] == $encrypted_old)
{
$row_type = dbFetchRow("DESCRIBE users password");
if ($row_type['Type'] == 'varchar(34)')
{
if ($row['password'] == $encrypted_old) {
$row_type = dbFetchRow('DESCRIBE users password');
if ($row_type['Type'] == 'varchar(34)') {
changepassword($username, $password);
}
return 1;
}
elseif(substr($row['password'],0,3) == '$1$')
{
$row_type = dbFetchRow("DESCRIBE users password");
if ($row_type['Type'] == 'varchar(60)')
{
if ($row['password'] == crypt($password,$row['password']))
{
changepassword($username,$password);
}
}
}
$hasher = new PasswordHash(8, FALSE);
if($hasher->CheckPassword($password, $row['password']))
{
return 1;
}
}
return 0;
}
function reauthenticate($sess_id,$token)
{
list($uname,$hash) = explode("|",$token);
return 1;
}
else if (substr($row['password'], 0, 3) == '$1$') {
$row_type = dbFetchRow('DESCRIBE users password');
if ($row_type['Type'] == 'varchar(60)') {
if ($row['password'] == crypt($password, $row['password'])) {
changepassword($username, $password);
}
}
}
$hasher = new PasswordHash(8, false);
if ($hasher->CheckPassword($password, $row['password'])) {
return 1;
}
}//end if
return 0;
}//end authenticate()
function reauthenticate($sess_id, $token) {
list($uname,$hash) = explode('|', $token);
$session = dbFetchRow("SELECT * FROM `session` WHERE `session_username` = '$uname' AND session_value='$sess_id'");
$hasher = new PasswordHash(8, FALSE);
if($hasher->CheckPassword($uname.$session['session_token'],$hash))
{
$hasher = new PasswordHash(8, false);
if ($hasher->CheckPassword($uname.$session['session_token'], $hash)) {
$_SESSION['username'] = $uname;
return 1;
}
else
{
else {
return 0;
}
}
function passwordscanchange($username = "")
{
}//end reauthenticate()
function passwordscanchange($username='') {
/*
* By default allow the password to be modified, unless the existing
* user is explicitly prohibited to do so.
*/
if (empty($username) || !user_exists($username))
{
if (empty($username) || !user_exists($username)) {
return 1;
} else {
return dbFetchCell("SELECT can_modify_passwd FROM users WHERE username = ?", array($username));
}
else {
return dbFetchCell('SELECT can_modify_passwd FROM users WHERE username = ?', array($username));
}
}//end passwordscanchange()
/**
* From: http://code.activestate.com/recipes/576894-generate-a-salt/
* This function generates a password salt as a string of x (default = 15) characters
@ -74,92 +72,98 @@ function passwordscanchange($username = "")
* @param $max integer The number of characters in the string
* @author AfroSoft <scripts@afrosoft.co.cc>
*/
function generateSalt($max = 15)
{
$characterList = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
function generateSalt($max=15) {
$characterList = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$i = 0;
$salt = "";
do
{
$salt = '';
do {
$salt .= $characterList{mt_rand(0, strlen($characterList))};
$i++;
} while ($i <= $max);
return $salt;
}
function changepassword($username,$password)
{
$hasher = new PasswordHash(8, FALSE);
}//end generateSalt()
function changepassword($username, $password) {
$hasher = new PasswordHash(8, false);
$encrypted = $hasher->HashPassword($password);
return dbUpdate(array('password' => $encrypted), 'users', '`username` = ?', array($username));
}
function auth_usermanagement()
{
}//end changepassword()
function auth_usermanagement() {
return 1;
}
function adduser($username, $password, $level, $email = "", $realname = "", $can_modify_passwd=1, $description ="", $twofactor=0)
{
if (!user_exists($username))
{
$hasher = new PasswordHash(8, FALSE);
}//end auth_usermanagement()
function adduser($username, $password, $level, $email='', $realname='', $can_modify_passwd=1, $description='', $twofactor=0) {
if (!user_exists($username)) {
$hasher = new PasswordHash(8, false);
$encrypted = $hasher->HashPassword($password);
return dbInsert(array('username' => $username, 'password' => $encrypted, 'level' => $level, 'email' => $email, 'realname' => $realname, 'can_modify_passwd' => $can_modify_passwd, 'descr' => $description, 'twofactor' => $twofactor), 'users');
} else {
return FALSE;
}
else {
return false;
}
function user_exists($username)
{
$return = @dbFetchCell("SELECT COUNT(*) FROM users WHERE username = ?", array($username));
}//end adduser()
function user_exists($username) {
$return = @dbFetchCell('SELECT COUNT(*) FROM users WHERE username = ?', array($username));
return $return;
}
function get_userlevel($username)
{
return dbFetchCell("SELECT `level` FROM `users` WHERE `username` = ?", array($username));
}
}//end user_exists()
function get_userid($username)
{
return dbFetchCell("SELECT `user_id` FROM `users` WHERE `username` = ?", array($username));
}
function deluser($username)
{
function get_userlevel($username) {
return dbFetchCell('SELECT `level` FROM `users` WHERE `username` = ?', array($username));
dbDelete('bill_perms', "`user_name` = ?", array($username));
dbDelete('devices_perms', "`user_name` = ?", array($username));
dbDelete('ports_perms', "`user_name` = ?", array($username));
dbDelete('users_prefs', "`user_name` = ?", array($username));
dbDelete('users', "`user_name` = ?", array($username));
}//end get_userlevel()
return dbDelete('users', "`username` = ?", array($username));
}
function get_userid($username) {
return dbFetchCell('SELECT `user_id` FROM `users` WHERE `username` = ?', array($username));
function get_userlist()
{
return dbFetchRows("SELECT * FROM `users`");
}
}//end get_userid()
function can_update_users()
{
# supported so return 1
function deluser($username) {
dbDelete('bill_perms', '`user_name` = ?', array($username));
dbDelete('devices_perms', '`user_name` = ?', array($username));
dbDelete('ports_perms', '`user_name` = ?', array($username));
dbDelete('users_prefs', '`user_name` = ?', array($username));
dbDelete('users', '`user_name` = ?', array($username));
return dbDelete('users', '`username` = ?', array($username));
}//end deluser()
function get_userlist() {
return dbFetchRows('SELECT * FROM `users`');
}//end get_userlist()
function can_update_users() {
// supported so return 1
return 1;
}
function get_user($user_id)
{
return dbFetchRow("SELECT * FROM `users` WHERE `user_id` = ?", array($user_id));
}
}//end can_update_users()
function update_user($user_id,$realname,$level,$can_modify_passwd,$email)
{
function get_user($user_id) {
return dbFetchRow('SELECT * FROM `users` WHERE `user_id` = ?', array($user_id));
}//end get_user()
function update_user($user_id, $realname, $level, $can_modify_passwd, $email) {
dbUpdate(array('realname' => $realname, 'level' => $level, 'can_modify_passwd' => $can_modify_passwd, 'email' => $email), 'users', '`user_id` = ?', array($user_id));
}
?>
}//end update_user()

View File

@ -11,7 +11,8 @@
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. */
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Two-Factor Authentication Library
@ -128,14 +129,16 @@ function oath_hotp($key, $counter=false) {
function verify_hotp($key,$otp,$counter=false) {
if( oath_hotp($key,$counter) == $otp ) {
return true;
} else {
}
else {
if( $counter === false ) {
//TimeBased HOTP requires lookbehind and lookahead.
$counter = floor(microtime(true)/keyInterval);
$initcount = $counter-((otpWindow+1)*keyInterval);
$endcount = $counter+(otpWindow*keyInterval);
$totp = true;
} else {
}
else {
//Counter based HOTP only has lookahead, not lookbehind.
$initcount = $counter-1;
$endcount = $counter+otpWindow;
@ -145,7 +148,8 @@ function verify_hotp($key,$otp,$counter=false) {
if( oath_hotp($key,$initcount) == $otp ) {
if( !$totp ) {
return $initcount;
} else {
}
else {
return true;
}
}
@ -200,23 +204,28 @@ function twofactor_auth() {
$twofactor = dbFetchRow('SELECT twofactor FROM users WHERE username = ?', array($_SESSION['username']));
if( empty($twofactor['twofactor']) ) {
$_SESSION['twofactor'] = true;
} else {
}
else {
$twofactor = json_decode($twofactor['twofactor'],true);
if( $twofactor['fails'] >= 3 && (!$config['twofactor_lock'] || (time()-$twofactor['last']) < $config['twofactor_lock']) ) {
$auth_message = "Too many failures, please ".($config['twofactor_lock'] ? "wait ".$config['twofactor_lock']." seconds" : "contact administrator").".";
} else {
}
else {
if( !$_POST['twofactor'] ) {
$twofactorform = true;
} else {
}
else {
if( ($server_c = verify_hotp($twofactor['key'],$_POST['twofactor'],$twofactor['counter'])) === false ) {
$twofactor['fails']++;
$twofactor['last'] = time();
$auth_message = "Wrong Two-Factor Token.";
} else {
}
else {
if( $twofactor['counter'] !== false ) {
if( $server_c !== true && $server_c !== $twofactor['counter'] ) {
$twofactor['counter'] = $server_c+1;
} else {
}
else {
$twofactor['counter']++;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,89 +1,87 @@
<?php
echo('<div class="container-fluid">');
echo("<div class='row'>
echo '<div class="container-fluid">';
echo "<div class='row'>
<div class='col-md-12'>
<div class='panel panel-default panel-condensed'>
<div class='panel-heading'>");
<div class='panel-heading'>";
if ($config['overview_show_sysDescr'])
{
echo('<strong>' . $device['sysDescr'] . "</strong>");
if ($config['overview_show_sysDescr']) {
echo '<strong>'.$device['sysDescr'].'</strong>';
}
echo('</div>
<table class="table table-hover table-condensed table-striped">');
echo '</div>
<table class="table table-hover table-condensed table-striped">';
$uptime = $device['uptime'];
if ($device['os'] == "ios") { formatCiscoHardware($device); }
if ($device['features']) { $device['features'] = "(".$device['features'].")"; }
if ($device['os'] == 'ios') {
formatCiscoHardware($device);
}
if ($device['features']) {
$device['features'] = '('.$device['features'].')';
}
$device['os_text'] = $config['os'][$device['os']]['text'];
if ($device['hardware'])
{
echo('<tr>
if ($device['hardware']) {
echo '<tr>
<td>Hardware</td>
<td>'.$device['hardware'].'</td>
</tr>');
</tr>';
}
echo('<tr>
echo '<tr>
<td>Operating System</td>
<td>'.$device['os_text'].' '.$device['version'].' '.$device['features'].' </td>
</tr>');
</tr>';
if ($device['serial'])
{
echo('<tr>
if ($device['serial']) {
echo '<tr>
<td>Serial</td>
<td>'.$device['serial'].'</td>
</tr>');
</tr>';
}
if ($device['sysContact'])
{
echo('<tr>
<td>Contact</td>');
if (get_dev_attrib($device,'override_sysContact_bool'))
{
echo('
if ($device['sysContact']) {
echo '<tr>
<td>Contact</td>';
if (get_dev_attrib($device, 'override_sysContact_bool')) {
echo '
<td>'.htmlspecialchars(get_dev_attrib($device, 'override_sysContact_string')).'</td>
</tr>
<tr>
<td>SNMP Contact</td>');
}
echo('
<td>' . htmlspecialchars($device['sysContact']). '</td>
</tr>');
<td>SNMP Contact</td>';
}
if ($device['location'])
{
echo('<tr>
echo '
<td>'.htmlspecialchars($device['sysContact']).'</td>
</tr>';
}
if ($device['location']) {
echo '<tr>
<td>Location</td>
<td>'.$device['location'].'</td>
</tr>');
if (get_dev_attrib($device,'override_sysLocation_bool') && !empty($device['real_location']))
{
echo('<tr>
</tr>';
if (get_dev_attrib($device, 'override_sysLocation_bool') && !empty($device['real_location'])) {
echo '<tr>
<td>SNMP Location</td>
<td>'.$device['real_location'].'</td>
</tr>');
</tr>';
}
}
if ($uptime)
{
echo('<tr>
if ($uptime) {
echo '<tr>
<td>Uptime</td>
<td>'.formatUptime($uptime).'</td>
</tr>');
</tr>';
}
echo('</table>
echo '</table>
</div>
</div>
</div>
</div>');
?>
</div>';

View File

@ -1,73 +1,70 @@
<?php
if ($device['status'] == '0') { $class = "alert-danger"; } else { $class = ""; }
if ($device['ignore'] == '1')
{
$class = "div-ignore-alert";
if ($device['status'] == '1')
{
$class = "alert-warning";
if ($device['status'] == '0') {
$class = 'alert-danger';
}
else {
$class = '';
}
if ($device['ignore'] == '1') {
$class = 'div-ignore-alert';
if ($device['status'] == '1') {
$class = 'alert-warning';
}
}
if ($device['disabled'] == '1')
{
$class = "alert-info";
if ($device['disabled'] == '1') {
$class = 'alert-info';
}
$type = strtolower($device['os']);
$image = getImage($device);
echo('
echo '
<tr bgcolor="'.$device_colour.'" class="alert '.$class.'">
<td width="40" align=center valign=middle style="padding: 21px;">'.$image.'</td>
<td valign=middle style="padding: 0 15px;"><span style="font-size: 20px;">'.generate_device_link($device).'</span>
<br />'.$device['location'].'</td>
<td>');
<td>';
if (isset($config['os'][$device['os']]['over']))
{
if (isset($config['os'][$device['os']]['over'])) {
$graphs = $config['os'][$device['os']]['over'];
}
elseif (isset($device['os_group']) && isset($config['os'][$device['os_group']]['over']))
{
else if (isset($device['os_group']) && isset($config['os'][$device['os_group']]['over'])) {
$graphs = $config['os'][$device['os_group']]['over'];
}
else
{
else {
$graphs = $config['os']['default']['over'];
}
$graph_array = array();
$graph_array['height'] = "100";
$graph_array['width'] = "310";
$graph_array['height'] = '100';
$graph_array['width'] = '310';
$graph_array['to'] = $config['time']['now'];
$graph_array['device'] = $device['device_id'];
$graph_array['type'] = "device_bits";
$graph_array['type'] = 'device_bits';
$graph_array['from'] = $config['time']['day'];
$graph_array['legend'] = "no";
$graph_array['legend'] = 'no';
$graph_array['popup_title'] = $descr;
$graph_array['height'] = "45";
$graph_array['width'] = "150";
$graph_array['bg'] = "FFFFFF00";
$graph_array['height'] = '45';
$graph_array['width'] = '150';
$graph_array['bg'] = 'FFFFFF00';
foreach ($graphs as $entry)
{
if ($entry['graph'])
{
foreach ($graphs as $entry) {
if ($entry['graph']) {
$graph_array['type'] = $entry['graph'];
echo("<div style='float: right; text-align: center; padding: 1px 5px; margin: 0 1px; ' class='rounded-5px'>");
echo "<div style='float: right; text-align: center; padding: 1px 5px; margin: 0 1px; ' class='rounded-5px'>";
print_graph_popup($graph_array);
echo("<div style='font-weight: bold; font-size: 7pt; margin: -3px;'>".$entry['text']."</div>");
echo("</div>");
echo "<div style='font-weight: bold; font-size: 7pt; margin: -3px;'>".$entry['text'].'</div>';
echo '</div>';
}
}
unset($graph_array);
echo('</td>
</tr>');
?>
echo '</td>
</tr>';

View File

@ -1,5 +1,5 @@
<?php
include_once("includes/object-cache.inc.php");
require_once 'includes/object-cache.inc.php';
?>
<div class="panel panel-default panel-condensed table-responsive">
<table class="table table-hover table-condensed table-striped">

View File

@ -1,5 +1,5 @@
<?php
include_once("includes/object-cache.inc.php");
require_once 'includes/object-cache.inc.php';
?>
<div class="panel panel-default panel-condensed table-responsive">
<table class="table table-hover table-condensed table-striped">

View File

@ -16,5 +16,3 @@ echo("
</tr></table>");
print_optionbar_end();
echo("</div>");
?>

View File

@ -11,31 +11,23 @@
* option) any later version. Please see LICENSE.txt at the top level of
* the source code distribution for details.
*/
?>
<?php
echo('
echo '
<div class="cycle-slideshow"
data-cycle-fx="fade"
data-cycle-timeout="10000"
data-cycle-slides="> div"
style="clear: both">
');
';
foreach (get_matching_files($config['html_dir']."/includes/front/", "/^top_.*\.php$/") as $file)
{
if(($file == 'top_ports.inc.php' && $config['top_ports'] == 0) || ($file == 'top_device_bits.inc.php' && $config['top_devices'] == 0))
{
foreach (get_matching_files($config['html_dir'].'/includes/front/', '/^top_.*\.php$/') as $file) {
if (($file == 'top_ports.inc.php' && $config['top_ports'] == 0) || ($file == 'top_device_bits.inc.php' && $config['top_devices'] == 0)) {
}
else
{
echo("<div class=box>\n");
include_once($file);
echo("</div>\n");
else {
echo "<div class=box>\n";
include_once $file;
echo "</div>\n";
}
}
echo("</div>\n");
?>
echo "</div>\n";

View File

@ -14,9 +14,9 @@
*/
$minutes = 15;
$seconds = $minutes * 60;
$seconds = ($minutes * 60);
$top = $config['front_page_settings']['top']['devices'];
if (is_admin() === TRUE || is_read() === TRUE) {
if (is_admin() === true || is_read() === true) {
$query = "
SELECT *, sum(p.ifInOctets_rate + p.ifOutOctets_rate) as total
FROM ports as p, devices as d
@ -28,7 +28,8 @@ if (is_admin() === TRUE || is_read() === TRUE) {
ORDER BY total desc
LIMIT $top
";
} else {
}
else {
$query = "
SELECT *, sum(p.ifInOctets_rate + p.ifOutOctets_rate) as total
FROM ports as p, devices as d, `devices_perms` AS `P`
@ -42,17 +43,19 @@ if (is_admin() === TRUE || is_read() === TRUE) {
LIMIT $top
";
$param[] = array($_SESSION['user_id']);
}
}//end if
echo("<strong>Top $top devices (last $minutes minutes)</strong>\n");
echo("<table class='simple'>\n");
echo "<strong>Top $top devices (last $minutes minutes)</strong>\n";
echo "<table class='simple'>\n";
foreach (dbFetchRows($query, $param) as $result) {
echo("<tr class=top10>".
"<td class=top10>".generate_device_link($result, shorthost($result['hostname']))."</td>".
"<td class=top10>".generate_device_link($result,
generate_minigraph_image($result, $config['time']['day'], $config['time']['now'], "device_bits", "no", 150, 21, '&', "top10"), array(), 0, 0, 0)."</td>".
"</tr>\n");
echo '<tr class=top10>'.'<td class=top10>'.generate_device_link($result, shorthost($result['hostname'])).'</td>'.'<td class=top10>'.generate_device_link(
$result,
generate_minigraph_image($result, $config['time']['day'], $config['time']['now'], 'device_bits', 'no', 150, 21, '&', 'top10'),
array(),
0,
0,
0
).'</td>'."</tr>\n";
}
echo("</table>\n");
?>
echo "</table>\n";

View File

@ -14,9 +14,9 @@
*/
$minutes = 15;
$seconds = $minutes * 60;
$seconds = ($minutes * 60);
$top = $config['front_page_settings']['top']['ports'];
if (is_admin() === TRUE || is_read() === TRUE) {
if (is_admin() === true || is_read() === true) {
$query = "
SELECT *, p.ifInOctets_rate + p.ifOutOctets_rate as total
FROM ports as p, devices as d
@ -27,7 +27,8 @@ if (is_admin() === TRUE || is_read() === TRUE) {
ORDER BY total desc
LIMIT $top
";
} else {
}
else {
$query = "
SELECT *, I.ifInOctets_rate + I.ifOutOctets_rate as total
FROM ports as I, devices as d,
@ -40,18 +41,16 @@ if (is_admin() === TRUE || is_read() === TRUE) {
ORDER BY total desc
LIMIT $top
";
$param[] = array($_SESSION['user_id'],$_SESSION['user_id']);
}
$param[] = array(
$_SESSION['user_id'],
$_SESSION['user_id'],
);
}//end if
echo("<strong>Top $top ports (last $minutes minutes)</strong>\n");
echo("<table class='simple'>\n");
echo "<strong>Top $top ports (last $minutes minutes)</strong>\n";
echo "<table class='simple'>\n";
foreach (dbFetchRows($query, $param) as $result) {
echo("<tr class=top10>".
"<td class=top10>".generate_device_link($result, shorthost($result['hostname']))."</td>".
"<td class=top10>".generate_port_link($result)."</td>".
"<td class=top10>".generate_port_link($result, generate_port_thumbnail($result))."</td>".
"</tr>\n");
echo '<tr class=top10>'.'<td class=top10>'.generate_device_link($result, shorthost($result['hostname'])).'</td>'.'<td class=top10>'.generate_port_link($result).'</td>'.'<td class=top10>'.generate_port_link($result, generate_port_thumbnail($result)).'</td>'."</tr>\n";
}
echo("</table>\n");
?>
echo "</table>\n";

File diff suppressed because it is too large Load Diff

View File

@ -2,7 +2,6 @@
$language_data = array(
'LANG_NAME' => 'IOS',
'COMMENT_SINGLE' => array(1 => '!'),
'CASE_KEYWORDS' => GESHI_CAPS_LOWER,
@ -10,32 +9,33 @@ $language_data = array (
'NUMBERS' => GESHI_NUMBER_OCT_PREFIX | GESHI_NUMBER_HEX_PREFIX,
'KEYWORDS' => array(
1 => array(
'no', 'shutdown'
'no',
'shutdown',
),
# 2 => array(
# 'router', 'interface', 'service', 'config-register', 'upgrade', 'version', 'hostname', 'boot-start-marker', 'boot', 'boot-end-marker', 'enable', 'aaa', 'clock', 'ip',
# 'logging', 'access-list', 'route-map', 'snmp-server', 'mpls', 'speed', 'media-type', 'negotiation', 'timestamps', 'prefix-list', 'network', 'mask', 'unsuppress-map',
# 'neighbor', 'remote-as', 'ebgp-multihop', 'update-source', 'description', 'peer-group', 'policy-map', 'class-map', 'class', 'match', 'access-group', 'bandwidth', 'username',
# 'password', 'send-community', 'next-hop-self', 'route-reflector-client', 'ldp', 'discovery', 'advertise-labels', 'label', 'protocol', 'login', 'debug', 'log', 'duplex', 'router-id',
# 'authentication', 'mode', 'maximum-paths', 'address-family', 'set', 'local-preference', 'community', 'trap-source', 'location', 'host', 'tacacs-server', 'session-id',
# 'flow-export', 'destination', 'source', 'in', 'out', 'permit', 'deny', 'control-plane', 'line', 'con' ,'aux', 'vty', 'access-class', 'ntp', 'server', 'end', 'source-interface',
# 'key', 'chain', 'key-string', 'redundancy', 'match-any', 'queue-limit', 'encapsulation', 'pvc', 'vbr-nrt', 'address', 'bundle-enable', 'atm', 'sonet', 'clns', 'route-cache',
# 'default-information', 'redistribute', 'log-adjacency-changes', 'metric', 'spf-interval', 'prc-interval', 'lsp-refresh-interval', 'max-lsp-lifetime', 'set-overload-bit',
# 'on-startup', 'wait-for-bgp', 'system', 'flash', 'timezone', 'subnet-zero', 'cef', 'flow-cache', 'timeout', 'active', 'domain', 'lookup', 'dhcp', 'use', 'vrf', 'hello', 'interval',
# 'priority', 'ilmi-keepalive', 'buffered', 'debugging', 'fpd', 'secret', 'accounting', 'exec', 'group', 'local', 'recurring', 'source-route', 'call', 'rsvp-sync', 'scripting',
# 'mtu', 'passive-interface', 'area' , 'distribute-list', 'metric-style', 'is-type', 'originate', 'activate', 'both', 'auto-summary', 'synchronization', 'aggregate-address', 'le', 'ge',
# 'bgp-community', 'route', 'exit-address-family', 'standard', 'file', 'verify', 'domain-name', 'domain-lookup', 'route-target', 'export', 'import', 'map', 'rd', 'mfib', 'vtp', 'mls',
# 'hardware-switching', 'replication-mode', 'ingress', 'flow', 'error', 'action', 'slb', 'purge', 'share-global', 'routing', 'traffic-eng', 'tunnels', 'propagate-ttl', 'switchport', 'vlan',
# 'portfast', 'counters', 'max', 'age', 'ethernet', 'evc', 'uni', 'count', 'oam', 'lmi', 'gmt', 'netflow', 'pseudowire-class', 'spanning-tree', 'name', 'circuit-type'
# ),
# 3 => array(
# 'isis', 'ospf', 'eigrp', 'rip', 'igrp', 'bgp', 'ipv4', 'unicast', 'multicast', 'ipv6', 'connected', 'static', 'subnets', 'tcl'
# ),
# 4 => array(
# 'point-to-point', 'aal5snap', 'rj45', 'auto', 'full', 'half', 'precedence', 'percent', 'datetime', 'msec', 'locatime', 'summer-time', 'md5', 'wait-for-bgp', 'wide',
# 'level-1', 'level-2', 'log-neighbor-changes', 'directed-request', 'password-encryption', 'common', 'origin-as', 'bgp-nexthop', 'random-detect', 'localtime', 'sso', 'stm-1',
# 'dot1q', 'isl', 'new-model', 'always', 'summary-only', 'freeze', 'global', 'forwarded', 'access', 'trunk', 'edge', 'transparent'
# ),
// 2 => array(
// 'router', 'interface', 'service', 'config-register', 'upgrade', 'version', 'hostname', 'boot-start-marker', 'boot', 'boot-end-marker', 'enable', 'aaa', 'clock', 'ip',
// 'logging', 'access-list', 'route-map', 'snmp-server', 'mpls', 'speed', 'media-type', 'negotiation', 'timestamps', 'prefix-list', 'network', 'mask', 'unsuppress-map',
// 'neighbor', 'remote-as', 'ebgp-multihop', 'update-source', 'description', 'peer-group', 'policy-map', 'class-map', 'class', 'match', 'access-group', 'bandwidth', 'username',
// 'password', 'send-community', 'next-hop-self', 'route-reflector-client', 'ldp', 'discovery', 'advertise-labels', 'label', 'protocol', 'login', 'debug', 'log', 'duplex', 'router-id',
// 'authentication', 'mode', 'maximum-paths', 'address-family', 'set', 'local-preference', 'community', 'trap-source', 'location', 'host', 'tacacs-server', 'session-id',
// 'flow-export', 'destination', 'source', 'in', 'out', 'permit', 'deny', 'control-plane', 'line', 'con' ,'aux', 'vty', 'access-class', 'ntp', 'server', 'end', 'source-interface',
// 'key', 'chain', 'key-string', 'redundancy', 'match-any', 'queue-limit', 'encapsulation', 'pvc', 'vbr-nrt', 'address', 'bundle-enable', 'atm', 'sonet', 'clns', 'route-cache',
// 'default-information', 'redistribute', 'log-adjacency-changes', 'metric', 'spf-interval', 'prc-interval', 'lsp-refresh-interval', 'max-lsp-lifetime', 'set-overload-bit',
// 'on-startup', 'wait-for-bgp', 'system', 'flash', 'timezone', 'subnet-zero', 'cef', 'flow-cache', 'timeout', 'active', 'domain', 'lookup', 'dhcp', 'use', 'vrf', 'hello', 'interval',
// 'priority', 'ilmi-keepalive', 'buffered', 'debugging', 'fpd', 'secret', 'accounting', 'exec', 'group', 'local', 'recurring', 'source-route', 'call', 'rsvp-sync', 'scripting',
// 'mtu', 'passive-interface', 'area' , 'distribute-list', 'metric-style', 'is-type', 'originate', 'activate', 'both', 'auto-summary', 'synchronization', 'aggregate-address', 'le', 'ge',
// 'bgp-community', 'route', 'exit-address-family', 'standard', 'file', 'verify', 'domain-name', 'domain-lookup', 'route-target', 'export', 'import', 'map', 'rd', 'mfib', 'vtp', 'mls',
// 'hardware-switching', 'replication-mode', 'ingress', 'flow', 'error', 'action', 'slb', 'purge', 'share-global', 'routing', 'traffic-eng', 'tunnels', 'propagate-ttl', 'switchport', 'vlan',
// 'portfast', 'counters', 'max', 'age', 'ethernet', 'evc', 'uni', 'count', 'oam', 'lmi', 'gmt', 'netflow', 'pseudowire-class', 'spanning-tree', 'name', 'circuit-type'
// ),
// 3 => array(
// 'isis', 'ospf', 'eigrp', 'rip', 'igrp', 'bgp', 'ipv4', 'unicast', 'multicast', 'ipv6', 'connected', 'static', 'subnets', 'tcl'
// ),
// 4 => array(
// 'point-to-point', 'aal5snap', 'rj45', 'auto', 'full', 'half', 'precedence', 'percent', 'datetime', 'msec', 'locatime', 'summer-time', 'md5', 'wait-for-bgp', 'wide',
// 'level-1', 'level-2', 'log-neighbor-changes', 'directed-request', 'password-encryption', 'common', 'origin-as', 'bgp-nexthop', 'random-detect', 'localtime', 'sso', 'stm-1',
// 'dot1q', 'isl', 'new-model', 'always', 'summary-only', 'freeze', 'global', 'forwarded', 'access', 'trunk', 'edge', 'transparent'
// ),
),
'REGEXPS' => array(
@ -86,27 +86,27 @@ $language_data = array (
10 => array(
GESHI_SEARCH => '(boot) ([a-z]+) (.+)',
GESHI_REPLACE => '\\3',
GESHI_BEFORE => '\\1 \\2 '
GESHI_BEFORE => '\\1 \\2 ',
),
11 => array(
GESHI_SEARCH => '(net) ([0-9a-z\.]+)',
GESHI_REPLACE => '\\2',
GESHI_BEFORE => '\\1 '
GESHI_BEFORE => '\\1 ',
),
12 => array(
GESHI_SEARCH => '(access-list|RO|RW) ([0-9]+)',
GESHI_REPLACE => '\\2',
GESHI_BEFORE => '\\1 '
GESHI_BEFORE => '\\1 ',
),
13 => array(
GESHI_SEARCH => '(vlan) ([0-9]+)',
GESHI_REPLACE => '\\2',
GESHI_BEFORE => '\\1 '
GESHI_BEFORE => '\\1 ',
),
14 => array(
GESHI_SEARCH => '(encapsulation|speed|duplex|mtu|metric|media-type|negotiation|transport\ input|bgp-community|set\ as-path\ prepend|maximum-prefix|version|local-preference|continue|redistribute|cluster-id|vtp\ mode|label\ protocol|spanning-tree\ mode) (.+)',
GESHI_REPLACE => '\\2',
GESHI_BEFORE => '\\1 '
GESHI_BEFORE => '\\1 ',
),
),
@ -114,59 +114,57 @@ $language_data = array (
'STYLES' => array(
'REGEXPS' => array(
0 => 'color: #ff0000;',
1 => 'color: #0000cc;', # x.x.x.x
2 => 'color: #000099; font-style: italic', # 255.x.x.x
3 => 'color: #000000; font-weight: bold; font-style: italic;', # interface xxx
4 => 'color: #ff0000;', # neighbor x.x.x.x
5 => 'color: #000099;', # variable names
1 => 'color: #0000cc;',
// x.x.x.x
2 => 'color: #000099; font-style: italic',
// 255.x.x.x
3 => 'color: #000000; font-weight: bold; font-style: italic;',
// interface xxx
4 => 'color: #ff0000;',
// neighbor x.x.x.x
5 => 'color: #000099;',
// variable names
6 => 'color: #cc0000;',
7 => 'color: #cc0000;', # passwords
8 => 'color: #555555;', # description
9 => 'color: #990099;', # communities
10 => 'color: #cc0000; font-style: italic;', # no/shut
11 => 'color: #000099;', # net numbers
12 => 'color: #000099;', # acls
13 => 'color: #000099;', # acls
14 => 'color: #990099;', # warnings
7 => 'color: #cc0000;',
// passwords
8 => 'color: #555555;',
// description
9 => 'color: #990099;',
// communities
10 => 'color: #cc0000; font-style: italic;',
// no/shut
11 => 'color: #000099;',
// net numbers
12 => 'color: #000099;',
// acls
13 => 'color: #000099;',
// acls
14 => 'color: #990099;',
// warnings
),
'KEYWORDS' => array(
1 => 'color: #cc0000; font-weight: bold;', # no/shut
2 => 'color: #000000;', # commands
3 => 'color: #000000; font-weight: bold;', # proto/service
4 => 'color: #000000;', # options
5 => 'color: #ff0000;'
),
'COMMENTS' => array(
1 => 'color: #808080; font-style: italic;'
),
'ESCAPE_CHAR' => array(
0 => 'color: #000099; font-weight: bold;'
),
'BRACKETS' => array(
0 => 'color: #66cc66;'
),
'STRINGS' => array(
0 => 'color: #ff0000;'
),
'NUMBERS' => array(
0 => 'color: #cc0000;'
),
'METHODS' => array(
0 => 'color: #006600;'
),
'SYMBOLS' => array(
0 => 'color: #66cc66;'
1 => 'color: #cc0000; font-weight: bold;',
// no/shut
2 => 'color: #000000;',
// commands
3 => 'color: #000000; font-weight: bold;',
// proto/service
4 => 'color: #000000;',
// options
5 => 'color: #ff0000;',
),
'COMMENTS' => array(1 => 'color: #808080; font-style: italic;'),
'ESCAPE_CHAR' => array(0 => 'color: #000099; font-weight: bold;'),
'BRACKETS' => array(0 => 'color: #66cc66;'),
'STRINGS' => array(0 => 'color: #ff0000;'),
'NUMBERS' => array(0 => 'color: #cc0000;'),
'METHODS' => array(0 => 'color: #006600;'),
'SYMBOLS' => array(0 => 'color: #66cc66;'),
'SCRIPT' => array(
0 => '',
1 => '',
2 => '',
3 => ''
)
)
3 => '',
),
),
);
?>

View File

@ -1,25 +1,21 @@
<?php
$rrd_filename = $config['rrd_dir'] . "/" . $device['hostname'] ."/".
safename("arubaap-$ap[name].$ap[radio_number].rrd");
$rrd_filename = $config['rrd_dir'].'/'.$device['hostname'].'/'.safename("arubaap-$ap[name].$ap[radio_number].rrd");
$rrd_list[0]['filename'] = $rrd_filename;
$rrd_list[0]['descr'] = "Channel";
$rrd_list[0]['ds'] = "channel";
$rrd_list[0]['descr'] = 'Channel';
$rrd_list[0]['ds'] = 'channel';
$unit_text = "Channel";
$unit_text = 'Channel';
$units = '';
$total_units = '';
$colours = 'mixed';
$scale_min = "0";
$scale_min = '0';
$nototal = 1;
if ($rrd_list)
{
include("includes/graphs/generic_multi_line.inc.php");
if ($rrd_list) {
include 'includes/graphs/generic_multi_line.inc.php';
}
?>

View File

@ -2,27 +2,24 @@
$scale_min = 0;
include("includes/graphs/common.inc.php");
require 'includes/graphs/common.inc.php';
$apache_rrd = $config['rrd_dir'] . "/" . $device['hostname'] . "/app-apache-".$app['app_id'].".rrd";
$apache_rrd = $config['rrd_dir'].'/'.$device['hostname'].'/app-apache-'.$app['app_id'].'.rrd';
if (is_file($apache_rrd))
{
if (is_file($apache_rrd)) {
$rrd_filename = $apache_rrd;
}
$ds = "kbyte";
$ds = 'kbyte';
$colour_area = "CDEB8B";
$colour_line = "006600";
$colour_area = 'CDEB8B';
$colour_line = '006600';
$colour_area_max = "FFEE99";
$colour_area_max = 'FFEE99';
$graph_max = 1;
$multiplier = 8;
$unit_text = "Kbps";
$unit_text = 'Kbps';
include("includes/graphs/generic_simplex.inc.php");
?>
require 'includes/graphs/generic_simplex.inc.php';

View File

@ -2,26 +2,23 @@
$scale_min = 0;
include("includes/graphs/common.inc.php");
require 'includes/graphs/common.inc.php';
$apache_rrd = $config['rrd_dir'] . "/" . $device['hostname'] . "/app-apache-".$app['app_id'].".rrd";
$apache_rrd = $config['rrd_dir'].'/'.$device['hostname'].'/app-apache-'.$app['app_id'].'.rrd';
if (is_file($apache_rrd))
{
if (is_file($apache_rrd)) {
$rrd_filename = $apache_rrd;
}
$ds = "cpu";
$ds = 'cpu';
$colour_area = "F0E68C";
$colour_line = "FF4500";
$colour_area = 'F0E68C';
$colour_line = 'FF4500';
$colour_area_max = "FFEE99";
$colour_area_max = 'FFEE99';
$graph_max = 1;
$unit_text = "% Used";
$unit_text = '% Used';
include("includes/graphs/generic_simplex.inc.php");
?>
require 'includes/graphs/generic_simplex.inc.php';

View File

@ -2,26 +2,23 @@
$scale_min = 0;
include("includes/graphs/common.inc.php");
require 'includes/graphs/common.inc.php';
$apache_rrd = $config['rrd_dir'] . "/" . $device['hostname'] . "/app-apache-".$app['app_id'].".rrd";
$apache_rrd = $config['rrd_dir'].'/'.$device['hostname'].'/app-apache-'.$app['app_id'].'.rrd';
if (is_file($apache_rrd))
{
if (is_file($apache_rrd)) {
$rrd_filename = $apache_rrd;
}
$ds = "access";
$ds = 'access';
$colour_area = "B0C4DE";
$colour_line = "191970";
$colour_area = 'B0C4DE';
$colour_line = '191970';
$colour_area_max = "FFEE99";
$colour_area_max = 'FFEE99';
$graph_max = 1;
$unit_text = "Hits/sec";
$unit_text = 'Hits/sec';
include("includes/graphs/generic_simplex.inc.php");
?>
require 'includes/graphs/generic_simplex.inc.php';

View File

@ -2,39 +2,69 @@
$scale_min = 0;
include("includes/graphs/common.inc.php");
require 'includes/graphs/common.inc.php';
$rrd_filename = $config['rrd_dir'] . "/" . $device['hostname'] . "/app-apache-".$app['app_id'].".rrd";
$rrd_filename = $config['rrd_dir'].'/'.$device['hostname'].'/app-apache-'.$app['app_id'].'.rrd';
$array = array('sb_reading' => array('descr' => 'Reading', 'colour' => '750F7DFF'),
'sb_writing' => array('descr' => 'Writing', 'colour' => '00FF00FF'),
'sb_wait' => array('descr' => 'Waiting', 'colour' => '4444FFFF'),
'sb_start' => array('descr' => 'Starting', 'colour' => '157419FF'),
'sb_keepalive' => array('descr' => 'Keepalive', 'colour' => 'FF0000FF'),
'sb_dns' => array('descr' => 'DNS', 'colour' => '6DC8FEFF'),
'sb_closing' => array('descr' => 'Closing', 'colour' => 'FFAB00FF'),
'sb_logging' => array('descr' => 'Logging', 'colour' => 'FFFF00FF'),
'sb_graceful' => array('descr' => 'Graceful', 'colour' => 'FF5576FF'),
'sb_idle' => array('descr' => 'Idle', 'colour' => 'FF4105FF'),
$array = array(
'sb_reading' => array(
'descr' => 'Reading',
'colour' => '750F7DFF',
),
'sb_writing' => array(
'descr' => 'Writing',
'colour' => '00FF00FF',
),
'sb_wait' => array(
'descr' => 'Waiting',
'colour' => '4444FFFF',
),
'sb_start' => array(
'descr' => 'Starting',
'colour' => '157419FF',
),
'sb_keepalive' => array(
'descr' => 'Keepalive',
'colour' => 'FF0000FF',
),
'sb_dns' => array(
'descr' => 'DNS',
'colour' => '6DC8FEFF',
),
'sb_closing' => array(
'descr' => 'Closing',
'colour' => 'FFAB00FF',
),
'sb_logging' => array(
'descr' => 'Logging',
'colour' => 'FFFF00FF',
),
'sb_graceful' => array(
'descr' => 'Graceful',
'colour' => 'FF5576FF',
),
'sb_idle' => array(
'descr' => 'Idle',
'colour' => 'FF4105FF',
),
);
$i = 0;
if (is_file($rrd_filename))
{
foreach ($array as $ds => $vars)
{
if (is_file($rrd_filename)) {
foreach ($array as $ds => $vars) {
$rrd_list[$i]['filename'] = $rrd_filename;
$rrd_list[$i]['descr'] = $vars['descr'];
$rrd_list[$i]['ds'] = $ds;
$rrd_list[$i]['colour'] = $vars['colour'];
$i++;
}
} else { echo("file missing: $file"); }
}
else {
echo "file missing: $file";
}
$colours = "mixed";
$colours = 'mixed';
$nototal = 1;
$unit_text = "Workers";
$unit_text = 'Workers';
include("includes/graphs/generic_multi_simplex_seperated.inc.php");
?>
require 'includes/graphs/generic_multi_simplex_seperated.inc.php';

View File

@ -1,5 +1,6 @@
<?php
/* Copyright (C) 2015 Daniel Preussker <f0o@devilcode.org>
/*
* Copyright (C) 2015 Daniel Preussker <f0o@devilcode.org>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
@ -11,9 +12,10 @@
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. */
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
/*
* Bind9 Query Graph
* @author Daniel Preussker <f0o@devilcode.org>
* @copyright 2015 f0o, LibreNMS
@ -22,15 +24,26 @@
* @subpackage Graphs
*/
include("includes/graphs/common.inc.php");
require 'includes/graphs/common.inc.php';
$i = 0;
$scale_min = 0;
$nototal = 1;
$unit_text = "Query/sec";
$rrd_filename = $config['rrd_dir'] . "/" . $device['hostname'] . "/app-bind-".$app['app_id'].".rrd";
$array = array( 'any', 'a', 'aaaa', 'cname', 'mx', 'ns', 'ptr', 'soa', 'srv', 'spf' );
$colours = "merged";
$unit_text = 'Query/sec';
$rrd_filename = $config['rrd_dir'].'/'.$device['hostname'].'/app-bind-'.$app['app_id'].'.rrd';
$array = array(
'any',
'a',
'aaaa',
'cname',
'mx',
'ns',
'ptr',
'soa',
'srv',
'spf',
);
$colours = 'merged';
$rrd_list = array();
$config['graph_colours']['merged'] = array_merge($config['graph_colours']['greens'], $config['graph_colours']['blues']);
@ -42,9 +55,9 @@ if( is_file($rrd_filename) ) {
$rrd_list[$i]['ds'] = $ds;
$i++;
}
} else {
}
else {
echo "file missing: $file";
}
include("includes/graphs/generic_multi_simplex_seperated.inc.php");
?>
require 'includes/graphs/generic_multi_simplex_seperated.inc.php';

View File

@ -2,21 +2,18 @@
$scale_min = 0;
include("includes/graphs/common.inc.php");
require 'includes/graphs/common.inc.php';
$drbd_rrd = $config['rrd_dir'] . "/" . $device['hostname'] . "/app-drbd-".$app['app_instance'].".rrd";
$drbd_rrd = $config['rrd_dir'].'/'.$device['hostname'].'/app-drbd-'.$app['app_instance'].'.rrd';
if (is_file($drbd_rrd))
{
if (is_file($drbd_rrd)) {
$rrd_filename = $drbd_rrd;
}
$ds_in = "dr";
$ds_out = "dw";
$ds_in = 'dr';
$ds_out = 'dw';
$multiplier = "8";
$format = "bytes";
$multiplier = '8';
$format = 'bytes';
include("includes/graphs/generic_data.inc.php");
?>
require 'includes/graphs/generic_data.inc.php';

View File

@ -2,20 +2,17 @@
$scale_min = 0;
include("includes/graphs/common.inc.php");
require 'includes/graphs/common.inc.php';
$drbd_rrd = $config['rrd_dir'] . "/" . $device['hostname'] . "/app-drbd-".$app['app_instance'].".rrd";
$drbd_rrd = $config['rrd_dir'].'/'.$device['hostname'].'/app-drbd-'.$app['app_instance'].'.rrd';
if (is_file($drbd_rrd))
{
if (is_file($drbd_rrd)) {
$rrd_filename = $drbd_rrd;
}
$ds_in = "nr";
$ds_out = "ns";
$ds_in = 'nr';
$ds_out = 'ns';
$multiplier = "8";
$multiplier = '8';
include("includes/graphs/generic_data.inc.php");
?>
require 'includes/graphs/generic_data.inc.php';

View File

@ -2,27 +2,24 @@
$scale_min = 0;
include("includes/graphs/common.inc.php");
require 'includes/graphs/common.inc.php';
$drbd_rrd = $config['rrd_dir'] . "/" . $device['hostname'] . "/app-drbd-".$app['app_instance'].".rrd";
$drbd_rrd = $config['rrd_dir'].'/'.$device['hostname'].'/app-drbd-'.$app['app_instance'].'.rrd';
if (is_file($drbd_rrd))
{
if (is_file($drbd_rrd)) {
$rrd_filename = $drbd_rrd;
}
$ds = "oos";
$ds = 'oos';
$colour_area = "CDEB8B";
$colour_line = "006600";
$colour_area = 'CDEB8B';
$colour_line = '006600';
$colour_area_max = "FFEE99";
$colour_area_max = 'FFEE99';
$graph_max = 1;
$multiplier = 8;
$unit_text = "Bytes";
$unit_text = 'Bytes';
include("includes/graphs/generic_simplex.inc.php");
?>
require 'includes/graphs/generic_simplex.inc.php';

View File

@ -1,13 +1,11 @@
<?php
include("memcached.inc.php");
include("includes/graphs/common.inc.php");
require 'memcached.inc.php';
require 'includes/graphs/common.inc.php';
$multiplier = 8;
$ds_in = "bytes_read";
$ds_out = "bytes_written";
$ds_in = 'bytes_read';
$ds_out = 'bytes_written';
include("includes/graphs/generic_data.inc.php");
?>
require 'includes/graphs/generic_data.inc.php';

View File

@ -52,7 +52,8 @@ if (is_file($rrd_filename)) {
// $rrd_list[$i]['colour'] = $vars['colour'];
$i++;
}
} else {
}
else {
echo "file missing: $file";
}

View File

@ -25,8 +25,7 @@ $files = array();
$i = 0;
if ($handle = opendir($rrddir)) {
while (false !== ($file = readdir($handle)))
{
while (false !== ($file = readdir($handle))) {
if ($file != '.' && $file != '..') {
if (eregi('app-shoutcast-'.$app['app_id'], $file)) {
array_push($files, $file);

View File

@ -13,8 +13,7 @@ $i = 0;
$x = 0;
if ($handle = opendir($rrddir)) {
while (false !== ($file = readdir($handle)))
{
while (false !== ($file = readdir($handle))) {
if ($file != '.' && $file != '..') {
if (eregi('app-shoutcast-'.$app['app_id'], $file)) {
array_push($files, $file);

View File

@ -1,5 +1,6 @@
<?php
/* Copyright (C) 2015 Daniel Preussker <f0o@devilcode.org>
/*
* Copyright (C) 2015 Daniel Preussker <f0o@devilcode.org>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
@ -11,9 +12,10 @@
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. */
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
/*
* TinyDNS DNSSec Graph
* @author Daniel Preussker <f0o@devilcode.org>
* @copyright 2015 f0o, LibreNMS
@ -22,16 +24,19 @@
* @subpackage Graphs
*/
include("includes/graphs/common.inc.php");
require 'includes/graphs/common.inc.php';
$i = 0;
$scale_min = 0;
$nototal = 1;
$unit_text = "Query/sec";
$rrd_filename = $config['rrd_dir'] . "/" . $device['hostname'] . "/app-tinydns-".$app['app_id'].".rrd";
$unit_text = 'Query/sec';
$rrd_filename = $config['rrd_dir'].'/'.$device['hostname'].'/app-tinydns-'.$app['app_id'].'.rrd';
// $array = explode(":","hinfo:rp:sig:key:axfr:total");
$array = array( "key", "sig" );
$colours = "mixed";
$array = array(
'key',
'sig',
);
$colours = 'mixed';
$rrd_list = array();
if (is_file($rrd_filename)) {
@ -41,9 +46,9 @@ if( is_file($rrd_filename) ) {
$rrd_list[$i]['ds'] = $ds;
$i++;
}
} else {
}
else {
echo "file missing: $file";
}
include("includes/graphs/generic_multi_simplex_seperated.inc.php");
?>
require 'includes/graphs/generic_multi_simplex_seperated.inc.php';

View File

@ -1,5 +1,6 @@
<?php
/* Copyright (C) 2015 Daniel Preussker <f0o@devilcode.org>
/*
Copyright (C) 2015 Daniel Preussker <f0o@devilcode.org>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
@ -11,9 +12,10 @@
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. */
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
/*
* TinyDNS Error Graph
* @author Daniel Preussker <f0o@devilcode.org>
* @copyright 2015 f0o, LibreNMS
@ -22,15 +24,20 @@
* @subpackage Graphs
*/
include("includes/graphs/common.inc.php");
require 'includes/graphs/common.inc.php';
$i = 0;
$scale_min = 0;
$nototal = 1;
$unit_text = "Query/sec";
$rrd_filename = $config['rrd_dir'] . "/" . $device['hostname'] . "/app-tinydns-".$app['app_id'].".rrd";
$array = array( "notauth", "notimpl", "badclass", "noquery" );
$colours = "oranges";
$unit_text = 'Query/sec';
$rrd_filename = $config['rrd_dir'].'/'.$device['hostname'].'/app-tinydns-'.$app['app_id'].'.rrd';
$array = array(
'notauth',
'notimpl',
'badclass',
'noquery',
);
$colours = 'oranges';
$rrd_list = array();
if (is_file($rrd_filename)) {
@ -40,9 +47,9 @@ if( is_file($rrd_filename) ) {
$rrd_list[$i]['ds'] = $ds;
$i++;
}
} else {
}
else {
echo "file missing: $file";
}
include("includes/graphs/generic_multi_simplex_seperated.inc.php");
?>
require 'includes/graphs/generic_multi_simplex_seperated.inc.php';

View File

@ -1,5 +1,6 @@
<?php
/* Copyright (C) 2015 Daniel Preussker <f0o@devilcode.org>
/*
Copyright (C) 2015 Daniel Preussker <f0o@devilcode.org>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
@ -11,9 +12,10 @@
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. */
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
/*
* TinyDNS Other Graph
* @author Daniel Preussker <f0o@devilcode.org>
* @copyright 2015 f0o, LibreNMS
@ -22,15 +24,20 @@
* @subpackage Graphs
*/
include("includes/graphs/common.inc.php");
require 'includes/graphs/common.inc.php';
$i = 0;
$scale_min = 0;
$nototal = 1;
$unit_text = "Query/sec";
$rrd_filename = $config['rrd_dir'] . "/" . $device['hostname'] . "/app-tinydns-".$app['app_id'].".rrd";
$array = array( "other", "hinfo", "rp", "axfr" );
$colours = "mixed";
$unit_text = 'Query/sec';
$rrd_filename = $config['rrd_dir'].'/'.$device['hostname'].'/app-tinydns-'.$app['app_id'].'.rrd';
$array = array(
'other',
'hinfo',
'rp',
'axfr',
);
$colours = 'mixed';
$rrd_list = array();
if (is_file($rrd_filename)) {
@ -40,9 +47,9 @@ if( is_file($rrd_filename) ) {
$rrd_list[$i]['ds'] = $ds;
$i++;
}
} else {
}
else {
echo "file missing: $file";
}
include("includes/graphs/generic_multi_simplex_seperated.inc.php");
?>
require 'includes/graphs/generic_multi_simplex_seperated.inc.php';

View File

@ -1,5 +1,6 @@
<?php
/* Copyright (C) 2015 Daniel Preussker <f0o@devilcode.org>
/*
* Copyright (C) 2015 Daniel Preussker <f0o@devilcode.org>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
@ -11,9 +12,10 @@
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. */
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
/*
* TinyDNS Query Graph
* @author Daniel Preussker <f0o@devilcode.org>
* @copyright 2015 f0o, LibreNMS
@ -22,16 +24,26 @@
* @subpackage Graphs
*/
include("includes/graphs/common.inc.php");
require 'includes/graphs/common.inc.php';
$i = 0;
$scale_min = 0;
$nototal = 1;
$unit_text = "Query/sec";
$rrd_filename = $config['rrd_dir'] . "/" . $device['hostname'] . "/app-tinydns-".$app['app_id'].".rrd";
$unit_text = 'Query/sec';
$rrd_filename = $config['rrd_dir'].'/'.$device['hostname'].'/app-tinydns-'.$app['app_id'].'.rrd';
// $array = explode(":","hinfo:rp:sig:key:axfr:total");
$array = array( "any", "a", "aaaa", "cname", "mx", "ns", "ptr", "soa", "txt" );
$colours = "merged";
$array = array(
'any',
'a',
'aaaa',
'cname',
'mx',
'ns',
'ptr',
'soa',
'txt',
);
$colours = 'merged';
$rrd_list = array();
$config['graph_colours']['merged'] = array_merge($config['graph_colours']['greens'], $config['graph_colours']['blues']);
@ -43,9 +55,9 @@ if( is_file($rrd_filename) ) {
$rrd_list[$i]['ds'] = $ds;
$i++;
}
} else {
}
else {
echo "file missing: $file";
}
include("includes/graphs/generic_multi_simplex_seperated.inc.php");
?>
require 'includes/graphs/generic_multi_simplex_seperated.inc.php';

View File

@ -1,34 +1,105 @@
<?php
if ($_GET['from']) { $from = mres($_GET['from']); }
if ($_GET['to']) { $to = mres($_GET['to']); }
if ($_GET['width']) { $width = mres($_GET['width']); }
if ($config['trim_tobias']) { $width+=12; }
if ($_GET['height']) { $height = mres($_GET['height']); }
if ($_GET['inverse']) { $in = 'out'; $out = 'in'; $inverse=TRUE; } else { $in = 'in'; $out = 'out'; }
if ($_GET['legend'] == "no") { $rrd_options .= " -g"; }
if (isset($_GET['nototal'])) { $nototal = ((bool) $_GET['nototal']); } else { $nototal=true; }
if (isset($_GET['nodetails'])) { $nodetails = ((bool) $_GET['nodetails']); } else { $nodetails=false; }
if (isset($_GET['noagg'])) { $noagg = ((bool) $_GET['noagg']); } else { $noagg=true; }
if ($_GET['title'] == "yes") { $rrd_options .= " --title='".$graph_title."' "; }
if (isset($_GET['graph_title'])) { $rrd_options .= " --title='".$_GET['graph_title']."' "; }
if ($_GET['from']) {
$from = mres($_GET['from']);
}
if (!isset($scale_min) && !isset($scale_max)) { $rrd_options .= " --alt-autoscale-max"; }
if (!isset($scale_min) && !isset($scale_max) && !isset($norigid)) { $rrd_options .= " --rigid"; }
if (isset($scale_min)) { $rrd_options .= " -l $scale_min"; }
if (isset($scale_max)) { $rrd_options .= " -u $scale_max"; }
if (isset($scale_rigid)) { $rrd_options .= " -r"; }
if ($_GET['to']) {
$to = mres($_GET['to']);
}
$rrd_options .= " -E --start ".$from." --end " . $to . " --width ".$width." --height ".$height." ";
if ($_GET['width']) {
$width = mres($_GET['width']);
}
if ($config['trim_tobias']) {
$width += 12;
}
if ($_GET['height']) {
$height = mres($_GET['height']);
}
if ($_GET['inverse']) {
$in = 'out';
$out = 'in';
$inverse = true;
}
else {
$in = 'in';
$out = 'out';
}
if ($_GET['legend'] == 'no') {
$rrd_options .= ' -g';
}
if (isset($_GET['nototal'])) {
$nototal = ((bool) $_GET['nototal']);
}
else {
$nototal = true;
}
if (isset($_GET['nodetails'])) {
$nodetails = ((bool) $_GET['nodetails']);
}
else {
$nodetails = false;
}
if (isset($_GET['noagg'])) {
$noagg = ((bool) $_GET['noagg']);
}
else {
$noagg = true;
}
if ($_GET['title'] == 'yes') {
$rrd_options .= " --title='".$graph_title."' ";
}
if (isset($_GET['graph_title'])) {
$rrd_options .= " --title='".$_GET['graph_title']."' ";
}
if (!isset($scale_min) && !isset($scale_max)) {
$rrd_options .= ' --alt-autoscale-max';
}
if (!isset($scale_min) && !isset($scale_max) && !isset($norigid)) {
$rrd_options .= ' --rigid';
}
if (isset($scale_min)) {
$rrd_options .= " -l $scale_min";
}
if (isset($scale_max)) {
$rrd_options .= " -u $scale_max";
}
if (isset($scale_rigid)) {
$rrd_options .= ' -r';
}
$rrd_options .= ' -E --start '.$from.' --end '.$to.' --width '.$width.' --height '.$height.' ';
$rrd_options .= $config['rrdgraph_def_text'];
if ($_GET['bg']) { $rrd_options .= " -c CANVAS#" . mres($_GET['bg']) . " "; }
if ($_GET['bg']) {
$rrd_options .= ' -c CANVAS#'.mres($_GET['bg']).' ';
}
#$rrd_options .= " -c BACK#FFFFFF";
// $rrd_options .= " -c BACK#FFFFFF";
if ($height < '99') {
$rrd_options .= ' --only-graph';
}
if ($height < "99") { $rrd_options .= " --only-graph"; }
if ($width <= '300') {
$rrd_options .= ' --font LEGEND:7:'.$config['mono_font'].' --font AXIS:6:'.$config['mono_font'];
}
else {
$rrd_options .= ' --font LEGEND:8:'.$config['mono_font'].' --font AXIS:7:'.$config['mono_font'];
}
if ($width <= "300") { $rrd_options .= " --font LEGEND:7:" . $config['mono_font'] . " --font AXIS:6:" . $config['mono_font']; }
else { $rrd_options .= " --font LEGEND:8:" . $config['mono_font'] . " --font AXIS:7:" . $config['mono_font']; }
$rrd_options .= " --font-render-mode normal";
$rrd_options .= ' --font-render-mode normal';

View File

@ -1,12 +1,8 @@
<?php
// FIXME - wtfbbq
if ($_SESSION['userlevel'] >= "5" || $auth)
{
if ($_SESSION['userlevel'] >= '5' || $auth) {
$id = mres($vars['id']);
$title = generate_device_link($device);
$auth = TRUE;
$auth = true;
}
?>

View File

@ -6,34 +6,30 @@ $i=0;
if (!is_array($config['customers_descr'])) {
$config['customers_descr'] = array($config['customers_descr']);
}
$descr_type = "'".implode("', '", $config['customers_descr'])."'";
foreach (dbFetchRows("SELECT * FROM `ports` AS I, `devices` AS D WHERE `port_descr_type` IN (?) AND `port_descr_descr` = ? AND D.device_id = I.device_id", array(array($descr_type),$vars['id'])) as $port)
{
if (is_file($config['rrd_dir'] . "/" . $port['hostname'] . "/port-" . safename($port['ifIndex'] . ".rrd")))
{
$rrd_filename = $config['rrd_dir'] . "/" . $port['hostname'] . "/port-" . safename($port['ifIndex'] . ".rrd");
foreach (dbFetchRows('SELECT * FROM `ports` AS I, `devices` AS D WHERE `port_descr_type` IN (?) AND `port_descr_descr` = ? AND D.device_id = I.device_id', array(array($descr_type), $vars['id'])) as $port) {
if (is_file($config['rrd_dir'].'/'.$port['hostname'].'/port-'.safename($port['ifIndex'].'.rrd'))) {
$rrd_filename = $config['rrd_dir'].'/'.$port['hostname'].'/port-'.safename($port['ifIndex'].'.rrd');
$rrd_list[$i]['filename'] = $rrd_filename;
$rrd_list[$i]['descr'] = $port['hostname'] ."-". $port['ifDescr'];
$rrd_list[$i]['descr'] = $port['hostname'].'-'.$port['ifDescr'];
$rrd_list[$i]['descr_in'] = shorthost($port['hostname']);
$rrd_list[$i]['descr_out'] = makeshortif($port['ifDescr']);
$i++;
}
}
#echo($config['rrd_dir'] . "/" . $port['hostname'] . "/port-" . safename($port['ifIndex'] . ".rrd"));
// echo($config['rrd_dir'] . "/" . $port['hostname'] . "/port-" . safename($port['ifIndex'] . ".rrd"));
$units = 'bps';
$total_units = 'B';
$colours_in = 'greens';
$multiplier = "8";
$multiplier = '8';
$colours_out = 'blues';
$nototal = 1;
$ds_in = "INOCTETS";
$ds_out = "OUTOCTETS";
$ds_in = 'INOCTETS';
$ds_out = 'OUTOCTETS';
include("includes/graphs/generic_multi_bits_separated.inc.php");
?>
require 'includes/graphs/generic_multi_bits_separated.inc.php';

View File

@ -12,21 +12,18 @@
* the source code distribution for details.
*/
$scale_min = "0";
$scale_min = '0';
include("includes/graphs/common.inc.php");
require 'includes/graphs/common.inc.php';
$rrd_filename = $config['rrd_dir'] . "/" . $device['hostname'] . "/asa_conns.rrd";
$rrd_filename = $config['rrd_dir'].'/'.$device['hostname'].'/asa_conns.rrd';
$rrd_options .= " DEF:connections=$rrd_filename:connections:AVERAGE";
$rrd_options .= " DEF:connections_max=$rrd_filename:connections:MAX";
$rrd_options .= " DEF:connections_min=$rrd_filename:connections:MIN";
$rrd_options .= " AREA:connections_min";
$rrd_options .= ' AREA:connections_min';
$rrd_options .= " LINE1.5:connections#cc0000:'".rrdtool_escape('Current connections')."'";
$rrd_options .= " GPRINT:connections_min:MIN:%4.0lf";
$rrd_options .= " GPRINT:connections:LAST:%4.0lf";
$rrd_options .= " GPRINT:connections_max:MAX:%4.0lf\\\\l";
?>
$rrd_options .= ' GPRINT:connections_min:MIN:%4.0lf';
$rrd_options .= ' GPRINT:connections:LAST:%4.0lf';
$rrd_options .= ' GPRINT:connections_max:MAX:%4.0lf\\\\l';

View File

@ -1,10 +1,7 @@
<?php
if ($auth || device_permitted($device['device_id']))
{
if ($auth || device_permitted($device['device_id'])) {
$title = generate_device_link($device);
$graph_title = $device['hostname'];
$auth = true;
}
?>

Some files were not shown because too many files have changed in this diff Show More