This commit is contained in:
laf 2015-07-15 20:46:04 +01:00
commit 7eed295897
1241 changed files with 114233 additions and 73305 deletions

View File

@ -38,6 +38,7 @@ Contributors to LibreNMS:
- Tony Ditchfield <tony.ditchfield@gmail.com> (arnoldthebat)
- Travis Hegner <travis.hegner@gmail.com> (travishegner)
- Will Jones <email@willjones.eu> (willjones)
- Job Snijders <job@instituut.net> (job)
[1]: http://observium.org/ "Observium web site"

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,195 +39,169 @@ if (isset($options['f']) && $options['f'] == 0) {
$force_add = 1;
}
if (!empty($argv[1]))
{
$host = strtolower($argv[1]);
$community = $argv[2];
$snmpver = strtolower($argv[3]);
if (!empty($argv[1])) {
$host = strtolower($argv[1]);
$community = $argv[2];
$snmpver = strtolower($argv[3]);
$port = 161;
$transport = 'udp';
$port = 161;
$transport = 'udp';
if ($snmpver === "v3")
{
$seclevel = $community;
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"
);
// These values are the same as in defaults.inc.php
$v3 = array(
'authlevel' => 'noAuthNoPriv',
'authname' => 'root',
'authpass' => '',
'authalgo' => 'MD5',
'cryptopass' => '',
'cryptoalgo' => 'AES',
);
if ($seclevel === "nanp" or $seclevel === "any" or $seclevel === "noAuthNoPriv")
{
$v3['authlevel'] = "noAuthNoPriv";
$v3args = array_slice($argv, 4);
if ($seclevel === 'nanp' or $seclevel === 'any' or $seclevel === 'noAuthNoPriv') {
$v3['authlevel'] = 'noAuthNoPriv';
$v3args = array_slice($argv, 4);
while ($arg = array_shift($v3args))
{
// parse all remaining args
if (is_numeric($arg))
{
$port = $arg;
while ($arg = array_shift($v3args)) {
// parse all remaining args
if (is_numeric($arg)) {
$port = $arg;
}
else if (preg_match('/^('.implode('|', $config['snmp']['transports']).')$/', $arg)) {
$transport = $arg;
}
else {
// should add a sanity check of chars allowed in user
$user = $arg;
}
}
if ($seclevel === 'nanp') {
array_push($config['snmp']['v3'], $v3);
}
$device_id = addHost($host, $snmpver, $port, $transport, 0, $poller_group, $force_add);
}
elseif (preg_match ('/^(' . implode("|",$config['snmp']['transports']) . ')$/', $arg))
{
$transport = $arg;
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)) {
// parse all remaining args
if (is_numeric($arg)) {
$port = $arg;
}
else if (preg_match('/^('.implode('|', $config['snmp']['transports']).')$/i', $arg)) {
$transport = $arg;
}
else if (preg_match('/^(sha|md5)$/i', $arg)) {
$v3['authalgo'] = $arg;
}
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);
}
else
{
// should add a sanity check of chars allowed in user
$user = $arg;
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)) {
// parse all remaining args
if (is_numeric($arg)) {
$port = $arg;
}
else if (preg_match('/^('.implode('|', $config['snmp']['transports']).')$/i', $arg)) {
$transport = $arg;
}
else if (preg_match('/^(sha|md5)$/i', $arg)) {
$v3['authalgo'] = $arg;
}
else if (preg_match('/^(aes|des)$/i', $arg)) {
$v3['cryptoalgo'] = $arg;
}
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);
}
}
if ($seclevel === "nanp")
{ array_push($config['snmp']['v3'], $v3); }
$device_id = addHost($host, $snmpver, $port, $transport,0,$poller_group,$force_add);
else {
// Error or do nothing ?
}//end if
}
elseif ($seclevel === "anp" or $seclevel === "authNoPriv")
{
else {
$v2args = array_slice($argv, 2);
$v3['authlevel'] = "authNoPriv";
$v3args = array_slice($argv, 4);
$v3['authname'] = array_shift($v3args);
$v3['authpass'] = array_shift($v3args);
while ($arg = array_shift($v3args))
{
// parse all remaining args
if (is_numeric($arg))
{
$port = $arg;
while ($arg = array_shift($v2args)) {
// parse all remaining args
if (is_numeric($arg)) {
$port = $arg;
}
else if (preg_match('/('.implode('|', $config['snmp']['transports']).')/i', $arg)) {
$transport = $arg;
}
else if (preg_match('/^(v1|v2c)$/i', $arg)) {
$snmpver = $arg;
}
}
elseif (preg_match ('/^(' . implode("|",$config['snmp']['transports']) . ')$/i', $arg))
{
$transport = $arg;
}
elseif (preg_match ('/^(sha|md5)$/i', $arg))
{
$v3['authalgo'] = $arg;
} 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);
if ($community) {
$config['snmp']['community'] = array($community);
}
$device_id = addHost($host, $snmpver, $port, $transport, 0, $poller_group, $force_add);
}//end if
if ($snmpver) {
$snmpversions[] = $snmpver;
}
elseif ($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))
{
// parse all remaining args
if (is_numeric($arg))
{
$port = $arg;
}
elseif (preg_match ('/^(' . implode("|",$config['snmp']['transports']) . ')$/i', $arg))
{
$transport = $arg;
}
elseif (preg_match ('/^(sha|md5)$/i', $arg))
{
$v3['authalgo'] = $arg;
}
elseif (preg_match ('/^(aes|des)$/i', $arg))
{
$v3['cryptoalgo'] = $arg;
} 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);
}
else
{
// Error or do nothing ?
}
}
else // v1 or v2c
{
$v2args = array_slice($argv, 2);
while ($arg = array_shift($v2args))
{
// parse all remaining args
if (is_numeric($arg))
{
$port = $arg;
}
elseif (preg_match ('/(' . implode("|",$config['snmp']['transports']) . ')/i', $arg))
{
$transport = $arg;
}
elseif (preg_match ('/^(v1|v2c)$/i', $arg))
{
$snmpver = $arg;
}
else {
$snmpversions = array(
'v2c',
'v3',
'v1',
);
}
if ($community)
{
$config['snmp']['community'] = array($community);
while (!$device_id && count($snmpversions)) {
$snmpver = array_shift($snmpversions);
$device_id = addHost($host, $snmpver, $port, $transport, 0, $poller_group, $force_add);
}
$device_id = addHost($host, $snmpver, $port, $transport,0,$poller_group,$force_add);
}
if ($device_id) {
$device = device_by_id_cache($device_id);
echo 'Added device '.$device['hostname'].' ('.$device_id.")\n";
exit;
}
}//end if
if ($snmpver)
{
$snmpversions[] = $snmpver;
}
else
{
$snmpversions = array('v2c', 'v3', 'v1');
}
print $console_color->convert(
"\n".$config['project_name_version'].' Add Host Tool
while (!$device_id && count($snmpversions))
{
$snmpver = array_shift($snmpversions);
$device_id = addHost($host, $snmpver, $port, $transport,0,$poller_group,$force_add);
}
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']).']
if ($device_id)
{
$device = device_by_id_cache($device_id);
echo("Added device ".$device['hostname']." (".$device_id.")\n");
exit;
}
}
-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.
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']) . "]
-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
");
?>
%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");
exit();
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,18 +1,20 @@
#!/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
* (at your option) any later version.
*
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the
* 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,59 +25,65 @@
* @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") ) {
$pids = explode("\n", trim(`ps -e | grep php | awk '{print $1}'`));
$lpid = trim(file_get_contents($config['install_dir']."/.alerts.lock"));
if( in_array($lpid,$pids) ) {
$lock = true;
}
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'));
if (in_array($lpid, $pids)) {
$lock = true;
}
}
if( $lock === true ) {
exit(1);
} else {
file_put_contents($config['install_dir']."/.alerts.lock", getmypid());
if ($lock === true) {
exit(1);
}
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";
echo "RunFollowUp():\r\n";
RunFollowUp();
echo "RunAlerts():\r\n";
RunAlerts();
echo "RunAcks():\r\n";
RunAcks();
echo "End : ".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";
}
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) {
global $rulescache;
if( empty($rulescache[$device]) || !isset($rulescache[$device]) ) {
foreach( GetRules($device) as $chk ) {
$rulescache[$device][$chk['id']] = true;
}
}
if( $rulescache[$device][$rule] === true ) {
return true;
}
return false;
}
function IsRuleValid($device, $rule) {
global $rulescache;
if (empty($rulescache[$device]) || !isset($rulescache[$device])) {
foreach (GetRules($device) as $chk) {
$rulescache[$device][$chk['id']] = true;
}
}
if ($rulescache[$device][$rule] === true) {
return true;
}
return false;
}//end IsRuleValid()
/**
* Issue Alert-Object
@ -83,185 +91,228 @@ function IsRuleValid($device,$rule) {
* @return boolean
*/
function IssueAlert($alert) {
global $config;
if( dbFetchCell('SELECT attrib_value FROM devices_attribs WHERE attrib_type = "disable_notify" && device_id = ?',array($alert['device_id'])) == "1" ) {
return true;
}
$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']));
if( isset($tpl['template']) ) {
$tpl = $tpl['template'];
} else {
$tpl = $default_tpl;
}
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;
}
global $config;
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?
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']));
if (isset($tpl['template'])) {
$tpl = $tpl['template'];
}
else {
$tpl = $default_tpl;
}
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']));
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";
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']));
}
}
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";
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
* @return void
*/
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']));
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";
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'];
$state = 0;
if( $n > $o ) {
$ret .= " Worsens";
$state = 3;
} elseif( $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";
}
}
}
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']));
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";
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'];
$state = 0;
if ($n > $o) {
$ret .= ' Worsens';
$state = 3;
}
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";
}
}//end foreach
}//end RunFollowUp()
/**
* Run all alerts
* @return void
*/
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']));
if( empty($alert['rule_id']) || !IsRuleValid($tmp[1],$tmp[0]) ) {
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;
$updet = false;
$rextra = json_decode($alert['extra'],true);
$chk = dbFetchRow('SELECT alerts.alerted,devices.ignore,devices.disabled FROM alerts,devices WHERE alerts.device_id = ? && devices.device_id = alerts.device_id && alerts.rule_id = ?',array($alert['device_id'],$alert['rule_id']));
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 {
$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;
}
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']));
if (empty($alert['rule_id']) || !IsRuleValid($tmp[1], $tmp[0])) {
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;
}
} 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 {
$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;
}
$alert['details'] = json_decode(gzuncompress($alert['details']), true);
$noiss = false;
$noacc = false;
$updet = false;
$rextra = json_decode($alert['extra'], true);
$chk = dbFetchRow('SELECT alerts.alerted,devices.ignore,devices.disabled FROM alerts,devices WHERE alerts.device_id = ? && devices.device_id = alerts.device_id && alerts.rule_id = ?', array($alert['device_id'], $alert['rule_id']));
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 {
$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 {
// 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 {
$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";
$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()
}
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";
$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']));
}
}
}
/**
* Run external transports
@ -269,24 +320,29 @@ function RunAlerts() {
* @return void
*/
function ExtTransports($obj) {
global $config;
$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").' };');
$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 "; ";
}
}
global $config;
$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').' };');
$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 '; ';
}
}//end ExtTransports()
/**
* Format Alert
@ -294,52 +350,69 @@ function ExtTransports($obj) {
* @param array $obj Alert-Array
* @return string
*/
function FormatAlertTpl($tpl,$obj) {
$msg = '$ret .= "'.str_replace(array("{else}","{/if}","{/foreach}"),array('"; } else { $ret .= "','"; } $ret .= "','"; } $ret .= "'),addslashes($tpl)).'";';
$parsed = $msg;
$s = strlen($msg);
$x = $pos = -1;
$buff = "";
$if = $for = false;
while( ++$x < $s ) {
if( $msg[$x] == "{" && $buff == "" ) {
$buff .= $msg[$x];
} elseif( $buff == "{ " ) {
$buff = "";
} elseif( $buff != "" ) {
$buff .= $msg[$x];
}
if( $buff == "{if" ) {
$pos = $x;
$if = true;
} elseif( $buff == "{foreach" ) {
$pos = $x;
$for = true;
}
if( $pos != -1 && $msg[$x] == "}" ) {
$orig = $buff;
$buff = "";
$pos = -1;
if( $if ) {
$if = false;
$o = 3;
$native = array('"; if( ',' ) { $ret .= "');
} elseif( $for ) {
$for = false;
$o = 8;
$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);
}
}
$parsed = populate($parsed);
return RunJail($parsed,$obj);
}
function FormatAlertTpl($tpl, $obj) {
$msg = '$ret .= "'.str_replace(array('{else}', '{/if}', '{/foreach}'), array('"; } else { $ret .= "', '"; } $ret .= "', '"; } $ret .= "'), addslashes($tpl)).'";';
$parsed = $msg;
$s = strlen($msg);
$x = $pos = -1;
$buff = '';
$if = $for = false;
while (++$x < $s) {
if ($msg[$x] == '{' && $buff == '') {
$buff .= $msg[$x];
}
else if ($buff == '{ ') {
$buff = '';
}
else if ($buff != '') {
$buff .= $msg[$x];
}
if ($buff == '{if') {
$pos = $x;
$if = true;
}
else if ($buff == '{foreach') {
$pos = $x;
$for = true;
}
if ($pos != -1 && $msg[$x] == '}') {
$orig = $buff;
$buff = '';
$pos = -1;
if ($if) {
$if = false;
$o = 3;
$native = array(
'"; if( ',
' ) { $ret .= "',
);
}
else if ($for) {
$for = false;
$o = 8;
$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
@ -347,119 +420,138 @@ function FormatAlertTpl($tpl,$obj) {
* @return array
*/
function DescribeAlert($alert) {
$obj = array();
$i = 0;
$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";
}
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."; ";
}
}
}
} elseif( $alert['state'] == 0 ) {
$id = dbFetchRow("SELECT alert_log.id,alert_log.time_logged,alert_log.details FROM alert_log WHERE alert_log.state != 2 && alert_log.state != 0 && alert_log.rule_id = ? && alert_log.device_id = ? && alert_log.id < ? ORDER BY id DESC LIMIT 1", array($alert['rule_id'],$alert['device_id'],$alert['id']));
if( empty($id['id']) ) {
return false;
}
$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";
}
$obj['uid'] = $alert['id'];
$obj['severity'] = $alert['severity'];
$obj['rule'] = $alert['rule'];
$obj['name'] = $alert['name'];
$obj['timestamp'] = $alert['time_logged'];
$obj['contacts'] = $extra['contacts'];
$obj['state'] = $alert['state'];
return $obj;
}
$obj = array();
$i = 0;
$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';
}
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.'; ';
}
}
}
}
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';
}//end if
$obj['uid'] = $alert['id'];
$obj['severity'] = $alert['severity'];
$obj['rule'] = $alert['rule'];
$obj['name'] = $alert['name'];
$obj['timestamp'] = $alert['time_logged'];
$obj['contacts'] = $extra['contacts'];
$obj['state'] = $alert['state'];
return $obj;
}//end DescribeAlert()
/**
* Format Elapsed Time
* @param int $secs Seconds elapsed
* @param integer $secs Seconds elapsed
* @return string
*/
function TimeFormat($secs){
$bit = array(
'y' => $secs / 31556926 % 12,
'w' => $secs / 604800 % 52,
'd' => $secs / 86400 % 7,
'h' => $secs / 3600 % 24,
'm' => $secs / 60 % 60,
's' => $secs % 60
);
$ret = array();
foreach($bit as $k => $v){
if($v > 0) {
$ret[] = $v . $k;
}
}
if( empty($ret) ) {
return "none";
}
return join(' ', $ret);
}
function TimeFormat($secs) {
$bit = array(
'y' => $secs / 31556926 % 12,
'w' => $secs / 604800 % 52,
'd' => $secs / 86400 % 7,
'h' => $secs / 3600 % 24,
'm' => $secs / 60 % 60,
's' => $secs % 60,
);
$ret = array();
foreach ($bit as $k => $v) {
if ($v > 0) {
$ret[] = $v.$k;
}
}
if (empty($ret)) {
return 'none';
}
return join(' ', $ret);
}//end TimeFormat()
/**
* "Safely" run eval
* @param string $code Code to run
* @param array $obj Object with variables
* @param array $obj Object with variables
* @return string|mixed
*/
function RunJail($code,$obj) {
$ret = "";
eval($code);
return $ret;
}
function RunJail($code, $obj) {
$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 string $txt Text with variables
* @param boolean $wrap Wrap variable for text-usage (default: true)
* @return string
*/
function populate($txt,$wrap=true) {
preg_match_all('/%([\w\.]+)/', $txt, $m);
foreach( $m[1] as $tmp ) {
$orig = $tmp;
$rep = false;
if( $tmp == "key" || $tmp == "value" ) {
$rep = '$'.$tmp;
} else {
if( strstr($tmp,'.') ) {
$tmp = explode('.',$tmp,2);
$pre = '$'.$tmp[0];
$tmp = $tmp[1];
} else {
$pre = '$obj';
}
$rep = $pre."['".str_replace('.',"']['",$tmp)."']";
if( $wrap ) {
$rep = "{".$rep."}";
}
}
$txt = str_replace("%".$orig,$rep,$txt);
}
return $txt;
}
?>
function populate($txt, $wrap=true) {
preg_match_all('/%([\w\.]+)/', $txt, $m);
foreach ($m[1] as $tmp) {
$orig = $tmp;
$rep = false;
if ($tmp == 'key' || $tmp == 'value') {
$rep = '$'.$tmp;
}
else {
if (strstr($tmp, '.')) {
$tmp = explode('.', $tmp, 2);
$pre = '$'.$tmp[0];
$tmp = $tmp[1];
}
else {
$pre = '$obj';
}
$rep = $pre."['".str_replace('.', "']['", $tmp)."']";
if ($wrap) {
$rep = '{'.$rep.'}';
}
}
$txt = str_replace('%'.$orig, $rep, $txt);
}//end foreach
return $txt;
}//end populate()

View File

@ -10,136 +10,139 @@
* @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`"); }
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)
{
unset($class);
unset($rate_data);
$day_data = getDates($bill['bill_day'], $i);
$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));
$period = getPeriod($bill['bill_id'],$datefrom,$dateto);
$date_updated = str_replace("-", "", str_replace(":", "", str_replace(" ", "", $check['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";
$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 = $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);
}
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'],
'rate_95th_in' => $rate_data['rate_95th_in'],
'rate_95th_out' => $rate_data['rate_95th_out'],
'dir_95th' => $rate_data['dir_95th'],
'total_data' => $rate_data['total_data'],
'total_data_in' => $rate_data['total_data_in'],
'total_data_out' => $rate_data['total_data_out'],
'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()') );
dbUpdate($update, 'bills', '`bill_id` = ?', array($bill['bill_id']));
echo(" Updated! ");
}
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'],
'rate_average' => $rate_data['rate_average'],
'rate_average_in' => $rate_data['rate_average_in'],
'rate_average_out' => $rate_data['rate_average_out'],
'traf_total' => $rate_data['total_data'],
'traf_in' => $rate_data['total_data_in'],
'traf_out' => $rate_data['total_data_out'],
'bill_used' => $used,
'bill_overuse' => $overuse,
'bill_percent' => $percent,
'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'],
'rate_95th_in' => $rate_data['rate_95th_in'],
'rate_95th_out' => $rate_data['rate_95th_out'],
'dir_95th' => $rate_data['dir_95th'],
'rate_average' => $rate_data['rate_average'],
'rate_average_in' => $rate_data['rate_average_in'],
'rate_average_out' => $rate_data['rate_average_out'],
'traf_total' => $rate_data['total_data'],
'traf_in' => $rate_data['total_data_in'],
'traf_out' => $rate_data['total_data_out'],
'bill_datefrom' => $datefrom,
'bill_dateto' => $dateto,
'bill_type' => $type,
'bill_allowed' => $allowed,
'bill_used' => $used,
'bill_overuse' => $overuse,
'bill_percent' => $percent,
'bill_datefrom' => $datefrom,
'bill_dateto' => $dateto,
'bill_id' => $bill['bill_id'] );
dbInsert($update, 'bill_history');
echo(" Generated history! ");
}
echo("\n\n");
}
$i++;
}
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";
$i = 0;
while ($i <= 24) {
unset($class);
unset($rate_data);
$day_data = getDates($bill['bill_day'], $i);
$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));
$period = getPeriod($bill['bill_id'], $datefrom, $dateto);
$date_updated = str_replace('-', '', str_replace(':', '', str_replace(' ', '', $check['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';
$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);
}
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);
}
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'],
'rate_95th_in' => $rate_data['rate_95th_in'],
'rate_95th_out' => $rate_data['rate_95th_out'],
'dir_95th' => $rate_data['dir_95th'],
'total_data' => $rate_data['total_data'],
'total_data_in' => $rate_data['total_data_in'],
'total_data_out' => $rate_data['total_data_out'],
'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()'),
);
dbUpdate($update, 'bills', '`bill_id` = ?', array($bill['bill_id']));
echo ' Updated! ';
}
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'],
'rate_average' => $rate_data['rate_average'],
'rate_average_in' => $rate_data['rate_average_in'],
'rate_average_out' => $rate_data['rate_average_out'],
'traf_total' => $rate_data['total_data'],
'traf_in' => $rate_data['total_data_in'],
'traf_out' => $rate_data['total_data_out'],
'bill_used' => $used,
'bill_overuse' => $overuse,
'bill_percent' => $percent,
'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'],
'rate_95th_in' => $rate_data['rate_95th_in'],
'rate_95th_out' => $rate_data['rate_95th_out'],
'dir_95th' => $rate_data['dir_95th'],
'rate_average' => $rate_data['rate_average'],
'rate_average_in' => $rate_data['rate_average_in'],
'rate_average_out' => $rate_data['rate_average_out'],
'traf_total' => $rate_data['total_data'],
'traf_in' => $rate_data['total_data_in'],
'traf_out' => $rate_data['total_data_out'],
'bill_datefrom' => $datefrom,
'bill_dateto' => $dateto,
'bill_type' => $type,
'bill_allowed' => $allowed,
'bill_used' => $used,
'bill_overuse' => $overuse,
'bill_percent' => $percent,
'bill_datefrom' => $datefrom,
'bill_dateto' => $dateto,
'bill_id' => $bill['bill_id'],
);
dbInsert($update, 'bill_history');
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" );
exit(1);
$sql_file = 'build.sql';
}
$connection = mysql_connect( $config['db_host'], $config['db_user'], $config['db_pass'] );
if ($connection === FALSE) {
echo( "ERROR: Cannot connect to database: " . mysql_error() . "\n" );
exit(1);
$sql_fh = fopen($sql_file, 'r');
if ($sql_fh === false) {
echo 'ERROR: Cannot open SQL build script '.$sql_file."\n";
exit(1);
}
$select = mysql_select_db( $config['db_name'] );
if ($select === FALSE) {
echo( "ERROR: Cannot select database: " . mysql_error() . "\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";
exit(1);
}
while( !feof( $sql_fh ) ) {
$line = fgetss( $sql_fh );
if(!empty($line))
{
$creation = mysql_query( $line );
if( !$creation ) {
echo( "WARNING: Cannot execute query (" . $line . "): " . mysql_error() . "\n" );
$select = mysql_select_db($config['db_name']);
if ($select === false) {
echo 'ERROR: Cannot select database: '.mysql_error()."\n";
exit(1);
}
while (!feof($sql_fh)) {
$line = fgetss($sql_fh);
if (!empty($line)) {
$creation = mysql_query($line);
if (!$creation) {
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,68 +14,74 @@
$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');
dbInsert(array('name' => 'uuid', 'value' => guidv4(openssl_random_pseudo_bytes(16))), 'callback');
}
$uuid = dbFetchCell("SELECT `value` FROM `callback` WHERE `name` = 'uuid'");
$queries = array(
'alert_rules'=>'SELECT COUNT(`severity`) AS `total`,`severity` FROM `alert_rules` WHERE `disabled`=0 GROUP BY `severity`',
'alert_templates'=>'SELECT COUNT(`id`) AS `total` FROM `alert_templates`',
'api_tokens'=>'SELECT COUNT(`id`) AS `total` FROM `api_tokens` WHERE `disabled`=0',
'applications'=>'SELECT COUNT(`app_type`) AS `total`,`app_type` FROM `applications` GROUP BY `app_type`',
'bgppeer_state'=>'SELECT COUNT(`bgpPeerState`) AS `total`,`bgpPeerState` FROM `bgpPeers` GROUP BY `bgpPeerState`',
'bgppeer_status'=>'SELECT COUNT(`bgpPeerAdminStatus`) AS `total`,`bgpPeerAdminStatus` FROM `bgpPeers` GROUP BY `bgpPeerAdminStatus`',
'bills'=>'SELECT COUNT(`bill_type`) AS `total`,`bill_type` FROM `bills` GROUP BY `bill_type`',
'cef'=>'SELECT COUNT(`device_id`) AS `total` FROM `cef_switching`',
'cisco_asa'=>'SELECT COUNT(`oid`) AS `total`,`oid` FROM `ciscoASA` WHERE `disabled` = 0 GROUP BY `oid`',
'mempool'=>'SELECT COUNT(`cmpName`) AS `total`,`cmpName` FROM `cmpMemPool` GROUP BY `cmpName`',
'current'=>'SELECT COUNT(`current_type`) AS `total`,`current_type` FROM `current` GROUP BY `current_type`',
'dbschema'=>'SELECT COUNT(`version`) AS `total`, `version` FROM `dbSchema`',
'snmp_version'=>'SELECT COUNT(`snmpver`) AS `total`,`snmpver` FROM `devices` GROUP BY `snmpver`',
'os'=>'SELECT COUNT(`os`) AS `total`,`os` FROM `devices` GROUP BY `os`',
'type'=>'SELECT COUNT(`type`) AS `total`,`type` FROM `devices` GROUP BY `type`',
'hardware'=>'SELECT COUNT(`device_id`) AS `total`, `hardware` FROM `devices` GROUP BY `hardware`',
'ipsec'=>'SELECT COUNT(`device_id`) AS `total` FROM `ipsec_tunnels`',
'ipv4_addresses'=>'SELECT COUNT(`ipv4_address_id`) AS `total` FROM `ipv4_addresses`',
'ipv4_macaddress'=>'SELECT COUNT(`port_id`) AS `total` FROM ipv4_mac',
'ipv4_networks'=>'SELECT COUNT(`ipv4_network_id`) AS `total` FROM ipv4_networks',
'ipv6_addresses'=>'SELECT COUNT(`ipv6_address_id`) AS `total` FROM `ipv6_addresses`',
'ipv6_networks'=>'SELECT COUNT(`ipv6_network_id`) AS `total` FROM `ipv6_networks`',
'xdp'=>'SELECT COUNT(`id`) AS `total`,`protocol` FROM `links` GROUP BY `protocol`',
'ospf'=>'SELECT COUNT(`device_id`) AS `total`,`ospfVersionNumber` FROM `ospf_instances` GROUP BY `ospfVersionNumber`',
'ospf_links'=>'SELECT COUNT(`device_id`) AS `total`,`ospfIfType` FROM `ospf_ports` GROUP BY `ospfIfType`',
'arch'=>'SELECT COUNT(`pkg_id`) AS `total`,`arch` FROM `packages` GROUP BY `arch`',
'pollers'=>'SELECT COUNT(`id`) AS `total` FROM `pollers`',
'port_type'=>'SELECT COUNT(`port_id`) AS `total`,`ifType` FROM `ports` GROUP BY `ifType`',
'port_ifspeed'=>'SELECT COUNT(`ifSpeed`) AS `total`,ROUND(`ifSpeed`/1000/1000) FROM `ports` GROUP BY `ifSpeed`',
'port_vlans'=>'SELECT COUNT(`device_id`) AS `total`,`state` FROM `ports_vlans` GROUP BY `state`',
'processes'=>'SELECT COUNT(`device_id`) AS `total` FROM `processes`',
'processors'=>'SELECT COUNT(`processor_id`) AS `total`,`processor_type` FROM `processors` GROUP BY `processor_type`',
'pseudowires'=>'SELECT COUNT(`pseudowire_id`) AS `total` FROM `pseudowires`',
'sensors'=>'SELECT COUNT(`sensor_id`) AS `total`,`sensor_class` FROM `sensors` GROUP BY `sensor_class`',
'storage'=>'SELECT COUNT(`storage_id`) AS `total`,`storage_type` FROM `storage` GROUP BY `storage_type`',
'toner'=>'SELECT COUNT(`toner_id`) AS `total`,`toner_type` FROM `toner` GROUP BY `toner_type`',
'vlans'=>'SELECT COUNT(`vlan_id`) AS `total`,`vlan_type` FROM `vlans` GROUP BY `vlan_type`',
'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`',);
'alert_rules' => 'SELECT COUNT(`severity`) AS `total`,`severity` FROM `alert_rules` WHERE `disabled`=0 GROUP BY `severity`',
'alert_templates' => 'SELECT COUNT(`id`) AS `total` FROM `alert_templates`',
'api_tokens' => 'SELECT COUNT(`id`) AS `total` FROM `api_tokens` WHERE `disabled`=0',
'applications' => 'SELECT COUNT(`app_type`) AS `total`,`app_type` FROM `applications` GROUP BY `app_type`',
'bgppeer_state' => 'SELECT COUNT(`bgpPeerState`) AS `total`,`bgpPeerState` FROM `bgpPeers` GROUP BY `bgpPeerState`',
'bgppeer_status' => 'SELECT COUNT(`bgpPeerAdminStatus`) AS `total`,`bgpPeerAdminStatus` FROM `bgpPeers` GROUP BY `bgpPeerAdminStatus`',
'bills' => 'SELECT COUNT(`bill_type`) AS `total`,`bill_type` FROM `bills` GROUP BY `bill_type`',
'cef' => 'SELECT COUNT(`device_id`) AS `total` FROM `cef_switching`',
'cisco_asa' => 'SELECT COUNT(`oid`) AS `total`,`oid` FROM `ciscoASA` WHERE `disabled` = 0 GROUP BY `oid`',
'mempool' => 'SELECT COUNT(`cmpName`) AS `total`,`cmpName` FROM `cmpMemPool` GROUP BY `cmpName`',
'current' => 'SELECT COUNT(`current_type`) AS `total`,`current_type` FROM `current` GROUP BY `current_type`',
'dbschema' => 'SELECT COUNT(`version`) AS `total`, `version` FROM `dbSchema`',
'snmp_version' => 'SELECT COUNT(`snmpver`) AS `total`,`snmpver` FROM `devices` GROUP BY `snmpver`',
'os' => 'SELECT COUNT(`os`) AS `total`,`os` FROM `devices` GROUP BY `os`',
'type' => 'SELECT COUNT(`type`) AS `total`,`type` FROM `devices` GROUP BY `type`',
'hardware' => 'SELECT COUNT(`device_id`) AS `total`, `hardware` FROM `devices` GROUP BY `hardware`',
'ipsec' => 'SELECT COUNT(`device_id`) AS `total` FROM `ipsec_tunnels`',
'ipv4_addresses' => 'SELECT COUNT(`ipv4_address_id`) AS `total` FROM `ipv4_addresses`',
'ipv4_macaddress' => 'SELECT COUNT(`port_id`) AS `total` FROM ipv4_mac',
'ipv4_networks' => 'SELECT COUNT(`ipv4_network_id`) AS `total` FROM ipv4_networks',
'ipv6_addresses' => 'SELECT COUNT(`ipv6_address_id`) AS `total` FROM `ipv6_addresses`',
'ipv6_networks' => 'SELECT COUNT(`ipv6_network_id`) AS `total` FROM `ipv6_networks`',
'xdp' => 'SELECT COUNT(`id`) AS `total`,`protocol` FROM `links` GROUP BY `protocol`',
'ospf' => 'SELECT COUNT(`device_id`) AS `total`,`ospfVersionNumber` FROM `ospf_instances` GROUP BY `ospfVersionNumber`',
'ospf_links' => 'SELECT COUNT(`device_id`) AS `total`,`ospfIfType` FROM `ospf_ports` GROUP BY `ospfIfType`',
'arch' => 'SELECT COUNT(`pkg_id`) AS `total`,`arch` FROM `packages` GROUP BY `arch`',
'pollers' => 'SELECT COUNT(`id`) AS `total` FROM `pollers`',
'port_type' => 'SELECT COUNT(`port_id`) AS `total`,`ifType` FROM `ports` GROUP BY `ifType`',
'port_ifspeed' => 'SELECT COUNT(`ifSpeed`) AS `total`,ROUND(`ifSpeed`/1000/1000) FROM `ports` GROUP BY `ifSpeed`',
'port_vlans' => 'SELECT COUNT(`device_id`) AS `total`,`state` FROM `ports_vlans` GROUP BY `state`',
'processes' => 'SELECT COUNT(`device_id`) AS `total` FROM `processes`',
'processors' => 'SELECT COUNT(`processor_id`) AS `total`,`processor_type` FROM `processors` GROUP BY `processor_type`',
'pseudowires' => 'SELECT COUNT(`pseudowire_id`) AS `total` FROM `pseudowires`',
'sensors' => 'SELECT COUNT(`sensor_id`) AS `total`,`sensor_class` FROM `sensors` GROUP BY `sensor_class`',
'storage' => 'SELECT COUNT(`storage_id`) AS `total`,`storage_type` FROM `storage` GROUP BY `storage_type`',
'toner' => 'SELECT COUNT(`toner_id`) AS `total`,`toner_type` FROM `toner` GROUP BY `toner_type`',
'vlans' => 'SELECT COUNT(`vlan_id`) AS `total`,`vlan_type` FROM `vlans` GROUP BY `vlan_type`',
'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`',
);
foreach ($queries as $name => $query) {
$data = dbFetchRows($query);
$data = dbFetchRows($query);
$response[$name] = $data;
}
$output = array('uuid'=>$uuid,'data'=>$response);
$data = json_encode($output);
$submit = array('data'=>$data);
$output = array(
'uuid' => $uuid,
'data' => $response,
);
$data = json_encode($output);
$submit = array('data' => $data);
$fields = '';
foreach ($submit as $key => $value) {
$fields .= $key . '=' . $value . '&';
$fields .= $key.'='.$value.'&';
}
rtrim($fields, '&');
$post = curl_init();
@ -85,9 +91,9 @@ if ($enabled == 1) {
curl_setopt($post, CURLOPT_POSTFIELDS, $fields);
curl_setopt($post, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($post);
} elseif ($enabled == 2) {
$uuid = dbFetchCell("SELECT `value` FROM `callback` WHERE `name` = 'uuid'");
}
else if ($enabled == 2) {
$uuid = dbFetchCell("SELECT `value` FROM `callback` WHERE `name` = 'uuid'");
$fields = "uuid=$uuid";
$clear = curl_init();
@ -100,5 +106,3 @@ if ($enabled == 1) {
dbDelete('callback', '`name`="uuid"', array());
dbUpdate(array('value' => '0'), 'callback', '`name` = "enabled"', array());
}
?>

View File

@ -10,51 +10,50 @@
* @subpackage alerts
* @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("html/includes/functions.inc.php");
require 'includes/defaults.inc.php';
require 'config.php';
require 'includes/definitions.inc.php';
require 'includes/functions.php';
require 'html/includes/functions.inc.php';
// Check all of our interface RRD files for errors
if ($argv[1]) {
$where = 'AND `port_id` = ?';
$params = array($argv[1]);
}
if ($argv[1]) { $where = "AND `port_id` = ?"; $params = array($argv[1]); }
$i = 0;
$i = 0;
$errored = 0;
foreach (dbFetchRows("SELECT * FROM `ports` AS I, `devices` AS D WHERE I.device_id = D.device_id $where", $params) as $interface)
{
$errors = $interface['ifInErrors_delta'] + $interface['ifOutErrors_delta'];
if ($errors > '1')
{
$errored[] = generate_device_link($interface, $interface['hostname'] . " - " . $interface['ifDescr'] . " - " . $interface['ifAlias'] . " - " . $interface['ifInErrors_delta'] . " - " . $interface['ifOutErrors_delta']);
$errored++;
}
$i++;
}
foreach (dbFetchRows("SELECT * FROM `ports` AS I, `devices` AS D WHERE I.device_id = D.device_id $where", $params) as $interface) {
$errors = ($interface['ifInErrors_delta'] + $interface['ifOutErrors_delta']);
if ($errors > '1') {
$errored[] = generate_device_link($interface, $interface['hostname'].' - '.$interface['ifDescr'].' - '.$interface['ifAlias'].' - '.$interface['ifInErrors_delta'].' - '.$interface['ifOutErrors_delta']);
$errored++;
}
echo("Checked $i interfaces\n");
if (is_array($errored))
{ // If there are errored ports
$i = 0;
$msg = "Interfaces with errors : \n\n";
foreach ($errored as $int)
{
$msg .= "$int\n"; // Add a line to the report email warning about them
$i++;
}
// Send the alert email
notify($device, $config['project_name'] . " detected errors on $i interface" . ($i != 1 ? 's' : ''), $msg);
}
echo("$errored interfaces with errors over the past 5 minutes.\n");
echo "Checked $i interfaces\n";
?>
if (is_array($errored)) {
// If there are errored ports
$i = 0;
$msg = "Interfaces with errors : \n\n";
foreach ($errored as $int) {
$msg .= "$int\n";
// Add a line to the report email warning about them
$i++;
}
// Send the alert email
notify($device, $config['project_name']." detected errors on $i interface".($i != 1 ? 's' : ''), $msg);
}
echo "$errored interfaces with errors over the past 5 minutes.\n";

View File

@ -1,7 +1,7 @@
#!/usr/bin/env php
<?php
/**
/*
* Observium
*
* This file is part of Observium.
@ -10,76 +10,74 @@
* @subpackage services
* @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';
foreach (dbFetchRows("SELECT * FROM `devices` AS D, `services` AS S WHERE S.device_id = D.device_id ORDER by D.device_id DESC") as $service)
{
if ($service['status'] = "1")
{
unset($check, $service_status, $time, $status);
$service_status = $service['service_status'];
$service_type = strtolower($service['service_type']);
$service_param = $service['service_param'];
$checker_script = $config['install_dir'] . "/includes/services/" . $service_type . "/check.inc";
foreach (dbFetchRows('SELECT * FROM `devices` AS D, `services` AS S WHERE S.device_id = D.device_id ORDER by D.device_id DESC') as $service) {
if ($service['status'] = '1') {
unset($check, $service_status, $time, $status);
$service_status = $service['service_status'];
$service_type = strtolower($service['service_type']);
$service_param = $service['service_param'];
$checker_script = $config['install_dir'].'/includes/services/'.$service_type.'/check.inc';
if (is_file($checker_script))
{
include($checker_script);
if (is_file($checker_script)) {
include $checker_script;
}
else {
$status = '2';
$check = "Error : Script not found ($checker_script)";
}
$update = array();
if ($service_status != $status) {
$update['service_changed'] = time();
if ($service['sysContact']) {
$email = $service['sysContact'];
}
else {
$email = $config['email_default'];
}
if ($status == '1') {
$msg = 'Service Up: '.$service['service_type'].' on '.$service['hostname'];
notify($device, 'Service Up: '.$service['service_type'].' on '.$service['hostname'], $msg);
}
else if ($status == '0') {
$msg = 'Service Down: '.$service['service_type'].' on '.$service['hostname'];
notify($device, 'Service Down: '.$service['service_type'].' on '.$service['hostname'], $msg);
}
}
else {
unset($updated);
}
$update = array_merge(array('service_status' => $status, 'service_message' => $check, 'service_checked' => time()), $update);
dbUpdate($update, 'services', '`service_id` = ?', array($service['service_id']));
unset($update);
}
else
{
$status = "2";
$check = "Error : Script not found ($checker_script)";
else {
$status = '0';
}//end if
$rrd = $config['rrd_dir'].'/'.$service['hostname'].'/'.safename('service-'.$service['service_type'].'-'.$service['service_id'].'.rrd');
if (!is_file($rrd)) {
rrdtool_create($rrd, 'DS:status:GAUGE:600:0:1 '.$config['rrd_rra']);
}
$update = array();
if ($service_status != $status)
{
$update['service_changed'] = time();
if ($service['sysContact']) { $email = $service['sysContact']; } else { $email = $config['email_default']; }
if ($status == "1")
{
$msg = "Service Up: " . $service['service_type'] . " on " . $service['hostname'];
notify($device, "Service Up: " . $service['service_type'] . " on " . $service['hostname'], $msg);
}
elseif ($status == "0")
{
$msg = "Service Down: " . $service['service_type'] . " on " . $service['hostname'];
notify($device, "Service Down: " . $service['service_type'] . " on " . $service['hostname'], $msg);
}
} else { unset($updated); }
$update = array_merge(array('service_status' => $status, 'service_message' => $check, 'service_checked' => time()), $update);
dbUpdate($update, 'services', '`service_id` = ?', array($service['service_id']));
unset($update);
} else {
$status = "0";
}
$rrd = $config['rrd_dir'] . "/" . $service['hostname'] . "/" . safename("service-" . $service['service_type'] . "-" . $service['service_id'] . ".rrd");
if (!is_file($rrd))
{
rrdtool_create ($rrd, "DS:status:GAUGE:600:0:1 ".$config['rrd_rra']);
}
if ($status == "1" || $status == "0")
{
rrdtool_update($rrd,"N:".$status);
} else {
rrdtool_update($rrd,"N:U");
}
} # while
?>
if ($status == '1' || $status == '0') {
rrdtool_update($rrd, 'N:'.$status);
}
else {
rrdtool_update($rrd, 'N:U');
}
} //end foreach

View File

@ -1,33 +1,30 @@
<?php
/*
Configuration to JSON converter
Written by Job Snijders <job.snijders@atrato.com>
*/
* Configuration to JSON converter
* Written by Job Snijders <job@instituut.net>
*
*/
$defaults_file = 'includes/defaults.inc.php';
$config_file = 'config.php';
$config_file = 'config.php';
// move to install dir
chdir(dirname($argv[0]));
function iscli() {
if(php_sapi_name() == 'cli' && empty($_SERVER['REMOTE_ADDR'])) {
return true;
} else {
return false;
}
if (php_sapi_name() == 'cli' && empty($_SERVER['REMOTE_ADDR'])) {
return true;
}
else {
return false;
}
}
// check if we are running throw the CLI, otherwise abort
if ( iscli() ) {
require_once($defaults_file);
require_once($config_file);
print(json_encode($config));
if (iscli()) {
include_once $defaults_file;
include_once $config_file;
print (json_encode($config));
}
?>

View File

@ -1,7 +1,7 @@
#!/usr/bin/env php
<?php
/**
/*
* Observium
*
* This file is part of Observium.
@ -10,40 +10,34 @@
* @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)
{
$cidr = $data['ipv4_network'];
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)
{
$ipdotted = long2ip($ip);
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++;
foreach (dbFetchRows('SELECT * FROM `ipv4_networks`') as $data) {
$cidr = $data['ipv4_network'];
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) {
$ipdotted = long2ip($ip);
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++;
}
}
}
}
fclose($handle);
shell_exec("fping -t 100 -f ips.txt > ips-scanned.txt");
?>
shell_exec('fping -t 100 -f ips.txt > ips-scanned.txt');

48
cronic Executable file
View File

@ -0,0 +1,48 @@
#!/bin/bash
# Cronic v2 - cron job report wrapper
# Copyright 2007 Chuck Houpt. No rights reserved, whatsoever.
# Public Domain CC0: http://creativecommons.org/publicdomain/zero/1.0/
set -eu
OUT=/tmp/cronic.out.$$
ERR=/tmp/cronic.err.$$
TRACE=/tmp/cronic.trace.$$
set +e
"$@" >$OUT 2>$TRACE
RESULT=$?
set -e
PATTERN="^${PS4:0:1}\\+${PS4:1}"
if grep -aq "$PATTERN" $TRACE
then
! grep -av "$PATTERN" $TRACE > $ERR
else
ERR=$TRACE
fi
if [ $RESULT -ne 0 -o -s "$ERR" ]
then
echo "Cronic detected failure or error output for the command:"
echo "$@"
echo
echo "RESULT CODE: $RESULT"
echo
echo "ERROR OUTPUT:"
cat "$ERR"
echo
echo "STANDARD OUTPUT:"
cat "$OUT"
if [ $TRACE != $ERR ]
then
echo
echo "TRACE-ERROR OUTPUT:"
cat "$TRACE"
fi
fi
rm -f "$OUT"
rm -f "$ERR"
rm -f "$TRACE"

View File

@ -5,66 +5,71 @@
* (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'];
}
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));
if(empty($limit)) {
break;
}
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 {
break;
}
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));
if (empty($limit)) {
break;
}
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 {
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'])) ) {
echo 'Eventlog cleared for entries over ' . $config['eventlog_purge'] . " days\n";
if (is_numeric($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'])) ) {
echo 'Authlog cleared for entries over ' . $config['authlog_purge'] . " days\n";
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'])) ) {
echo 'Performance poller times cleared for entries over ' . $config['perf_times_purge'] . " days\n";
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'])) ) {
echo 'Device performance times cleared for entries over ' . $config['device_perf_purge'] . " days\n";
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])
{
$host = strtolower($argv[1]);
$id = getidbyname($host);
if ($id)
{
echo(delete_device($id)."\n");
} else {
echo("Host doesn't exist!\n");
}
} else {
echo("Host Removal Tool\nUsage: ./delhost.php <hostname>\n");
// 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";
}
}
else {
echo "Host Removal Tool\nUsage: ./delhost.php <hostname>\n";
}
?>

View File

@ -10,130 +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();
$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']))
{
$where = "AND `device_id` = '".$options['h']."'";
$doing = $options['h'];
if (isset($options['h'])) {
if ($options['h'] == 'odd') {
$options['n'] = '1';
$options['i'] = '2';
}
else
{
$where = "AND `hostname` LIKE '".str_replace('*','%',mres($options['h']))."'";
$doing = $options['h'];
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 {
$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;
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);
ini_set('display_startup_errors', 0);
ini_set('log_errors', 0);
// ini_set('error_reporting', 0);
}
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);
ini_set('display_startup_errors', 0);
ini_set('log_errors', 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";
exit;
}
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(?)";
$params = array($config['distributed_poller_group']);
}
foreach (dbFetch("SELECT * FROM `devices` WHERE status = 1 AND disabled = 0 $where ORDER BY device_id DESC",$params) as $device)
{
discover_device($device, $options);
if ($config['distributed_poller'] === true) {
$where .= ' AND poller_group IN('.$config['distributed_poller_group'].')';
}
$end = utime(); $run = $end - $start;
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);
$proctime = substr($run, 0, 5);
if ($discovered_devices)
{
dbInsert(array('type' => 'discover', 'doing' => $doing, 'start' => $start, 'duration' => $proctime, 'devices' => $discovered_devices), 'perf_times');
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");
$string = $argv[0]." $doing ".date($config['dateformat']['compact'])." - $discovered_devices devices discovered in $proctime secs";
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) {
$tbl->addRow(array($poller['id'],$poller['poller_name'],$poller['last_polled'],$poller['devices'],$poller['time_taken']));
}
echo $tbl->getTable();
} elseif ($options['l'] == 'groups') {
$tbl = new Console_Table();
$tbl->setHeaders(array('ID','Group Name','Description'));
foreach (dbFetchRows("SELECT * FROM `poller_groups`") as $groups) {
$tbl->addRow(array($groups['id'],$groups['group_name'],$groups['descr']));
$tbl->setHeaders(array('ID', 'Poller Name', 'Last Polled', '# Devices', 'Poll Time'));
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 (isset($options['u']) && !empty($options['u'])) {
else if ($options['l'] == 'groups') {
$tbl = new Console_Table();
$tbl->setHeaders(array('ID', 'Group Name', 'Description'));
foreach (dbFetchRows('SELECT * FROM `poller_groups`') as $groups) {
$tbl->addRow(array($groups['id'], $groups['group_name'], $groups['descr']));
}
echo $tbl->getTable();
}
}
else if (isset($options['u']) && !empty($options['u'])) {
if (is_numeric($options['u'])) {
$db_column = 'id';
} else {
$db_column = 'id';
}
else {
$db_column = 'poller_name';
}
if (dbDelete('pollers',"`$db_column` = ?", array($options['u'])) >= 0) {
echo "Poller " . $options['u'] . " has been removed\n";
if (dbDelete('pollers', "`$db_column` = ?", array($options['u'])) >= 0) {
echo 'Poller '.$options['u']." has been removed\n";
}
} elseif (isset($options['r'])) {
if(dbInsert(array('poller_name' => $config['distributed_poller_name'], 'last_polled' => '0000-00-00 00:00:00', 'devices' => 0, 'time_taken' => 0), 'pollers') >= 0) {
echo "Poller " . $config['distributed_poller_name'] . " has been registered\n";
}
else 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";
}
} 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

@ -37,6 +37,21 @@ if ($foo == 5) {
}
```
Start else and elsif on new lines, e.g.
```php
if ($foo == 5) {
echo 'foo is 5';
}
elsif ($foo == 4) {
echo 'foo is 4';
}
else {
echo 'foo is something else';
}
```
This makes diffs much cleaner when moving around blocks of code.
### Including files
Using parenthesis around file includes isn't required, instead just place the file in between ''
```php

View File

@ -3,7 +3,7 @@
MIB-based polling is experimental. It might overload your LibreNMS server,
destroy your data, set your routers on fire, and kick your cat. It has been
tested against a very limited set of devices (namely Ruckus ZD1000 wireless
controllers, and Net-SNMP on Linux). It may fail badly on other hardware.
controllers, and `net-snmp` on Linux). It may fail badly on other hardware.
The approach taken is fairly basic and I claim no special expertise in
understanding MIBs. Most of my understanding of SNMP comes from reading
@ -18,7 +18,7 @@ Paul Gear <paul@librenms.org>
MIB-based polling is disabled by default; you must set
`$config['poller_modules']['mib'] = 1;`
in config.php to enable it.
in `config.php` to enable it.
The components involved in of MIB-based support are:
@ -41,7 +41,7 @@ The components involved in of MIB-based support are:
- updates/adds graph definitions in the previously-unused graph_types
database table
- Individual OSes (`includes/polling/os/*.inc.php`) can poll extra MIBs
for a given OS by calling poll_mib(). At the moment, this actually
for a given OS by calling `poll_mib()`. At the moment, this actually
happens before the general MIB polling.
- Devices may be excluded from MIB polling by changing the setting in the
device edit screen (`/device/device=ID/tab=edit/section=modules/`)
@ -73,17 +73,16 @@ gather the data you want.
3. Check that `snmptranslate -Td -On -M mibs -m MODULE MODULE::mibName`
produces a parsed description of the OID values. An example can be
found in the comments for `snmp_mib_parse()` in `includes/snmp.inc.php`.
4. Get the `sysObjectID` from a device, for example:```
snmpget -v2c -c public -OUsb -m SNMPv2-MIB -M /opt/librenms/mibs -t 30 hostname sysObjectID.0
```
4. Get the `sysObjectID` from a device, for example:
```snmpget -v2c -c public -OUsb -m SNMPv2-MIB -M /opt/librenms/mibs -t 30 hostname sysObjectID.0```
5. Ensure `snmptranslate -m all -M /opt/librenms/mibs OID 2>/dev/null`
(where OID is the value returned for sysObjectID above) results in a
valid name for the MIB. See the comments for `snmp_translate()` in
`includes/snmp.inc.php` for an example. If this step fails, it means
there is something wrong with the MIB and net-snmp cannot parse it.
there is something wrong with the MIB and `net-snmp` cannot parse it.
6. Add any additional MIBs you wish to poll for specific device types to
`includes/polling/os/OSNAME.inc.php` by calling `poll_mibs()` with the
MIB module and name. See includes/polling/os/ruckuswireless.inc.php for
MIB module and name. See `includes/polling/os/ruckuswireless.inc.php` for
an example.
7. That should be all you need to see MIB graphs!
@ -99,4 +98,3 @@ snmpget -v2c -c public -OUsb -m SNMPv2-MIB -M /opt/librenms/mibs -t 30 hostname
- Combine multiple MIB values into graphs automatically on a predefined or
user-defined basis.
- Include MIB types in stats submissions.

View File

@ -7,8 +7,8 @@ NOTE: These instructions assume you are the root user. If you are not, prepend
yum install net-snmp mysql-server
service snmpd start
service mysqld start
chkconfig --levels 235 mysqld on
chkconfig --levels 235 snmpd on
chkconfig mysqld on
chkconfig snmpd on
mysql_secure_installation
mysql -uroot -p
@ -46,7 +46,7 @@ Install necessary software. The packages listed below are an all-inclusive list
Note if not using HTTPd (Apache): RHEL requires `httpd` to be installed regardless of of `nginx`'s (or any other web-server's) presence.
rpm -Uvh http://download.fedoraproject.org/pub/epel/6/i386/epel-release-6-8.noarch.rpm
yum install epel-release
yum install php php-cli php-gd php-mysql php-snmp php-pear php-curl httpd net-snmp graphviz graphviz-php mysql ImageMagick jwhois nmap mtr rrdtool MySQL-python net-snmp-utils vixie-cron php-mcrypt fping git
pear install Net_IPv4-1.3.4
pear install Net_IPv6-1.2.2b2
@ -87,8 +87,8 @@ If the file `/etc/httpd/conf.d/welcome.conf` exists, you might want to remove th
Install necessary extra software and let it start on system boot.
yum install nginx php-fpm
chkconfig --levels 235 nginx on
chkconfig --levels 235 php-fpm on
chkconfig nginx on
chkconfig php-fpm on
Modify permissions and configuration for `php-fpm` to use nginx credentials.

View File

@ -13,32 +13,28 @@
*/
// FUA
if (isset($_REQUEST['debug']))
{
ini_set('display_errors', 1);
ini_set('display_startup_errors', 0);
ini_set('log_errors', 0);
ini_set('allow_url_fopen', 0);
ini_set('error_reporting', E_ALL);
if (isset($_REQUEST['debug'])) {
ini_set('display_errors', 1);
ini_set('display_startup_errors', 0);
ini_set('log_errors', 0);
ini_set('allow_url_fopen', 0);
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");
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');
}
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';
}
}

View File

@ -9,39 +9,36 @@
* @subpackage ajax
* @author Adam Armstrong <adama@memetic.org>
* @copyright (C) 2006 - 2012 Adam Armstrong
*
*/
if (isset($_GET['debug']))
{
ini_set('display_errors', 1);
ini_set('display_startup_errors', 0);
ini_set('log_errors', 0);
ini_set('allow_url_fopen', 0);
ini_set('error_reporting', E_ALL);
if (isset($_GET['debug'])) {
ini_set('display_errors', 1);
ini_set('display_startup_errors', 0);
ini_set('log_errors', 0);
ini_set('allow_url_fopen', 0);
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 (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");
}
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) {
$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");
}
}

View File

@ -1,19 +1,21 @@
<?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
* (at your option) any later version.
*
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the
* 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
@ -22,103 +24,123 @@
*/
session_start();
if( !isset($_SESSION['authenticated']) ) {
die("Unauthorized.");
if (!isset($_SESSION['authenticated'])) {
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
* @param string $base Comparisson basis
* @param array $obj Object to sort
* @param array $obj Object to sort
* @return array
*/
function levsort($base, $obj) {
$ret = array();
foreach( $obj as $elem ) {
$lev = levenshtein($base, $elem, 1, 10, 10);
if( $lev == 0 ) {
return array(array('name'=>$elem));
} else {
while( isset($ret["$lev"]) ) {
$lev += 0.1;
}
$ret["$lev"] = array('name'=>$elem);
}
}
ksort($ret);
return $ret;
$ret = array();
foreach ($obj as $elem) {
$lev = levenshtein($base, $elem, 1, 10, 10);
if ($lev == 0) {
return array(array('name' => $elem));
}
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();
$obj = array(array('name' => 'Error: No suggestions found.'));
$term = array();
$current = false;
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( $config['memcached']['enable'] ) {
$chk = $memcache->get('rule-suggest_'.$term[0]);
}
if( !(sizeof($chk) > 0) || $chk === false ) {
if( $term[0] == "macros" ) {
foreach( $config['alert']['macros']['rule'] as $macro=>$v ) {
$chk[] = "macros.".$macro;
}
} else {
$tmp = dbFetchRows('SHOW COLUMNS FROM '.$term[0]);
foreach( $tmp as $tst ) {
if( isset($tst['Field']) ) {
$chk[] = $term[0].'.'.$tst['Field'];
}
}
}
}
$current = true;
} 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
}
$obj = levsort($_GET['term'],$chk);
$obj = array_chunk($obj,20,true);
$obj = $obj[0];
$flds = array();
if( $current == true ) {
foreach( $obj as $fld ) {
$flds[] = $fld['name'];
}
$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']);
$val = array();
foreach( $qry as $row ) {
$val[] = $row[$chk];
}
$ret[$lev] = array('name'=>$fld['name'],'current'=>$val);
}
$obj = $ret;
}
}
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 ($config['memcached']['enable']) {
$chk = $memcache->get('rule-suggest_'.$term[0]);
}
if (!(sizeof($chk) > 0) || $chk === false) {
if ($term[0] == 'macros') {
foreach ($config['alert']['macros']['rule'] as $macro => $v) {
$chk[] = 'macros.'.$macro;
}
}
else {
$tmp = dbFetchRows('SHOW COLUMNS FROM '.$term[0]);
foreach ($tmp as $tst) {
if (isset($tst['Field'])) {
$chk[] = $term[0].'.'.$tst['Field'];
}
}
}
}
$current = true;
}
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
}
$obj = levsort($_GET['term'], $chk);
$obj = array_chunk($obj, 20, true);
$obj = $obj[0];
$flds = array();
if ($current == true) {
foreach ($obj as $fld) {
$flds[] = $fld['name'];
}
$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']);
$val = array();
foreach ($qry as $row) {
$val[] = $row[$chk];
}
$ret[$lev] = array(
'name' => $fld['name'],
'current' => $val,
);
}
$obj = $ret;
}
}
}
die(json_encode($obj));
?>

View File

@ -1,212 +1,218 @@
<?php
if (isset($_REQUEST['debug']))
{
ini_set('display_errors', 1);
ini_set('display_startup_errors', 0);
ini_set('log_errors', 0);
ini_set('allow_url_fopen', 0);
ini_set('error_reporting', E_ALL);
if (isset($_REQUEST['debug'])) {
ini_set('display_errors', 1);
ini_set('display_startup_errors', 0);
ini_set('log_errors', 0);
ini_set('allow_url_fopen', 0);
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; }
$device = Array();
$ports = Array();
if (isset($_REQUEST['search']))
{
$search = mres($_REQUEST['search']);
if (strlen($search) >0)
{
$found = 0;
if( $_REQUEST['type'] == 'group' ) {
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'=>$group['name']);
}
}
die(json_encode($results));
} elseif( $_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') {
// Device search
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 {
$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))
{
$found = 1;
$devices = count($results);
foreach ($results as $result)
{
$name = $result['hostname'];
if($result['disabled'] == 1)
{
$highlight_colour = '#808080';
}
elseif($result['ignored'] == 1 && $result['disabled'] == 0)
{
$highlight_colour = '#000000';
}
elseif($result['status'] == 0 && $result['ignore'] == 0 && $result['disabled'] == 0)
{
$highlight_colour = '#ff0000';
}
elseif($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']));
}
$device[]=array('name'=>$name,
'device_id'=>$result['device_id'],
'url'=> generate_device_url($result),
'colours'=>$highlight_colour,
'device_ports'=>$num_ports,
'device_image'=>getImageSrc($result),
'device_hardware'=>$result['hardware'],
'device_os'=>$config['os'][$result['os']]['text'],
'version'=>$result['version'],
'location'=>$result['location']);
}
}
$json = json_encode($device);
print_r($json);
exit;
} elseif($_REQUEST['type'] == 'ports') {
// Search ports
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 {
$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))
{
$found = 1;
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))
{
// Errored ports
$port_colour = '#ffa500';
}
elseif($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)
{
// Shutdown ports
$port_colour = '#808080';
}
elseif($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)
{
// Up ports
$port_colour = '#008000';
}
$ports[]=array('count'=>count($results),
'url'=>generate_port_url($result),
'name'=>$name,
'description'=>$description,
'colours'=>$highlight_colour,
'hostname'=>$result['hostname']);
}
}
$json = json_encode($ports);
print_r($json);
exit;
} elseif($_REQUEST['type'] == 'bgp') {
// Search bgp peers
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 {
$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))
{
$found = 1;
foreach ($results as $result)
{
$name = $result['bgpPeerIdentifier'];
$description = $result['astext'];
$remoteas = $result['bgpPeerRemoteAs'];
$localas = $result['bgpLocalAs'];
if($result['bgpPeerAdminStatus'] == 'start' && $result['bgpPeerState'] != 'established')
{
// Session active but errored
$port_colour = '#ffa500';
}
elseif($result['bgpPeerAdminStatus'] != 'start')
{
// Session inactive
$port_colour = '#000000';
}
elseif($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"; }
$bgp[]=array('count'=>count($results),
'url'=>generate_peer_url($result),
'name'=>$name,
'description'=>$description,
'localas'=>$localas,
'bgp_image'=>$bgp_image,
'remoteas'=>$remoteas,
'colours'=>$port_colour,
'hostname'=>$result['hostname']);
}
}
$json = json_encode($bgp);
print_r($json);
exit;
}
}
if (!$_SESSION['authenticated']) {
echo 'unauthenticated';
exit;
}
?>
$device = array();
$ports = array();
if (isset($_REQUEST['search'])) {
$search = mres($_REQUEST['search']);
if (strlen($search) > 0) {
$found = 0;
if ($_REQUEST['type'] == 'group') {
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' => $group['name']);
}
}
die(json_encode($results));
}
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));
}
else if ($_REQUEST['type'] == 'device') {
// Device search
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 {
$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)) {
$found = 1;
$devices = count($results);
foreach ($results as $result) {
$name = $result['hostname'];
if ($result['disabled'] == 1) {
$highlight_colour = '#808080';
}
else if ($result['ignored'] == 1 && $result['disabled'] == 0) {
$highlight_colour = '#000000';
}
else if ($result['status'] == 0 && $result['ignore'] == 0 && $result['disabled'] == 0) {
$highlight_colour = '#ff0000';
}
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']));
}
$device[] = array(
'name' => $name,
'device_id' => $result['device_id'],
'url' => generate_device_url($result),
'colours' => $highlight_colour,
'device_ports' => $num_ports,
'device_image' => getImageSrc($result),
'device_hardware' => $result['hardware'],
'device_os' => $config['os'][$result['os']]['text'],
'version' => $result['version'],
'location' => $result['location'],
);
}//end foreach
}//end if
$json = json_encode($device);
print_r($json);
exit;
}
else if ($_REQUEST['type'] == 'ports') {
// Search ports
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 {
$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)) {
$found = 1;
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)) {
// Errored ports
$port_colour = '#ffa500';
}
else if ($result['deleted'] == 0 && ($result['ignore'] == 1 || $result['ignore'] == 1)) {
// Ignored ports
$port_colour = '#000000';
}
else if ($result['deleted'] == 0 && $result['ifAdminStatus'] == 'down' && $result['ignore'] == 0 && $result['ignore'] == 0) {
// Shutdown ports
$port_colour = '#808080';
}
else if ($result['deleted'] == 0 && $result['ifOperStatus'] == 'down' && $result['ifAdminStatus'] == 'up' && $result['ignore'] == 0 && $result['ignore'] == 0) {
// Down ports
$port_colour = '#ff0000';
}
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),
'url' => generate_port_url($result),
'name' => $name,
'description' => $description,
'colours' => $highlight_colour,
'hostname' => $result['hostname'],
);
}//end foreach
}//end if
$json = json_encode($ports);
print_r($json);
exit;
}
else if ($_REQUEST['type'] == 'bgp') {
// Search bgp peers
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 {
$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)) {
$found = 1;
foreach ($results as $result) {
$name = $result['bgpPeerIdentifier'];
$description = $result['astext'];
$remoteas = $result['bgpPeerRemoteAs'];
$localas = $result['bgpLocalAs'];
if ($result['bgpPeerAdminStatus'] == 'start' && $result['bgpPeerState'] != 'established') {
// Session active but errored
$port_colour = '#ffa500';
}
else if ($result['bgpPeerAdminStatus'] != 'start') {
// Session inactive
$port_colour = '#000000';
}
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';
}
$bgp[] = array(
'count' => count($results),
'url' => generate_peer_url($result),
'name' => $name,
'description' => $description,
'localas' => $localas,
'bgp_image' => $bgp_image,
'remoteas' => $remoteas,
'colours' => $port_colour,
'hostname' => $result['hostname'],
);
}//end foreach
}//end if
$json = json_encode($bgp);
print_r($json);
exit;
}//end if
}//end if
}//end if

View File

@ -12,39 +12,37 @@
* the source code distribution for details.
*/
if (isset($_REQUEST['debug']))
{
ini_set('display_errors', 1);
ini_set('display_startup_errors', 0);
ini_set('log_errors', 0);
ini_set('allow_url_fopen', 0);
ini_set('error_reporting', E_ALL);
if (isset($_REQUEST['debug'])) {
ini_set('display_errors', 1);
ini_set('display_startup_errors', 0);
ini_set('log_errors', 0);
ini_set('allow_url_fopen', 0);
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) {
foreach ($_POST['sort'] as $k => $v) {
$sort .= " $k $v";
}
}
$searchPhrase = mres($_POST['searchPhrase']);
$id = mres($_POST['id']);
$response = array();
$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->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
// /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)
// Inventory section
$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
});
$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
// /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)
// Inventory section
$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
}
);
$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";
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;
ini_set('display_errors', 0);
ini_set('display_startup_errors', 0);
ini_set('log_errors', 0);
ini_set('error_reporting', 0);
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;
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.");
exit;
if (get_client_ip() != $_SERVER['SERVER_ADDR']) {
if (!$_SESSION['authenticated']) {
echo 'unauthenticated';
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" );
//$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" );
$imgbill = (isset($_GET['imgbill']) ? $_GET['imgbill'] : false);
$yaxistitle = "Bytes";
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.';
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' );
// $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' );
$imgbill = (isset($_GET['imgbill']) ? $_GET['imgbill'] : false);
$yaxistitle = 'Bytes';
$in_data = array();
$out_data = array();
@ -84,187 +89,179 @@ $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']));
$datelabel = $datefrom."\n".$dateto;
$traf['in'] = $data['traf_in'];
$traf['out'] = $data['traf_out'];
$traf['total'] = $data['traf_total'];
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")
{
$traf['allowed'] = $data['bill_allowed'];
$traf['overuse'] = $data['bill_overuse'];
} else {
$traf['allowed'] = "0";
$traf['overuse'] = "0";
if ($data['bill_type'] == 'Quota') {
$traf['allowed'] = $data['bill_allowed'];
$traf['overuse'] = $data['bill_overuse'];
}
else {
$traf['allowed'] = '0';
$traf['overuse'] = '0';
}
array_push($ticklabels, $datelabel);
array_push($in_data, $traf['in']);
array_push($out_data, $traf['out']);
array_push($tot_data, $traf['total']);
array_push($allow_data, $traf['allowed']);
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, '');
}
}
array_push($ticklabels, $datelabel);
array_push($in_data, $traf['in']);
array_push($out_data, $traf['out']);
array_push($tot_data, $traf['total']);
array_push($allow_data, $traf['allowed']);
array_push($overuse_data, $traf['overuse']);
$i++;
//print_r($data);
}
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";
} 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)
{
$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("%e\n%b", $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);
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)
{
$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']);
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);
}
$decimal = 0;
$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);
$yaxistitle = 'Gigabytes';
$graph_name = 'Historical bandwidth over the last 12 billing periods';
}
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) {
$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("%e\n%b", $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);
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);
}
}
}
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']);
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++) {
array_push($ave_data, $average);
}
$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');
$graph->xaxis->SetTitleMargin(30);
$graph->xaxis->SetTickLabels($ticklabels);
$graph->xgrid->Show(true,true);
$graph->xgrid->SetColor('#e0e0e0','#efefef');
$graph->xgrid->Show(true, true);
$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');
$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")
{
$barplot_over = new BarPlot($overuse_data);
$barplot_over->SetLegend("Traffic Overusage");
$barplot_over->SetColor('darkred');
$barplot_over->SetFillColor('lightred@0.4');
$barplot_over->SetWeight(1);
if ($imgtype == 'historical') {
$barplot_over = new BarPlot($overuse_data);
$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->SetColor('black');
$lineplot_allow->SetWeight(1);
$lineplot_allow = new LinePlot($allow_data);
$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 {
$lineplot_allow = new LinePlot($ave_data);
//$lineplot_allow->SetLegend("Average per ".$imgtype);
$lineplot_allow->SetLegend("Average");
$lineplot_allow->SetColor('black');
$lineplot_allow->SetWeight(1);
$gbplot = new GroupBarPlot(array($barplot_in, $barplot_tot, $barplot_out));
$gbplot = new GroupBarPlot(array($barplot_in, $barplot_tot, $barplot_out, $barplot_over));
}
else {
$lineplot_allow = new LinePlot($ave_data);
// $lineplot_allow->SetLegend("Average per ".$imgtype);
$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,247 +9,256 @@
* @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";
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;
ini_set('display_errors', 0);
ini_set('display_startup_errors', 0);
ini_set('log_errors', 0);
ini_set('error_reporting', 0);
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;
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.");
exit;
if (get_client_ip() != $_SERVER['SERVER_ADDR']) {
if (!$_SESSION['authenticated']) {
echo 'unauthenticated';
exit;
}
} else {
$bill_id = $_GET['bill_id'];
}
} else {
echo("Unauthorised Access Prohibited.");
exit;
}
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.';
exit;
}
}
else {
$bill_id = $_GET['bill_id'];
}
}
else {
echo 'Unauthorised Access Prohibited.';
exit;
}
$start = $_GET[from];
$end = $_GET[to];
$end = $_GET[to];
$xsize = $_GET[x];
$ysize = $_GET[y];
$count = $_GET[count];
$count = $count + 0;
$iter = 1;
$count = ($count + 0);
$iter = 1;
if ($_GET[type]) { $type = $_GET[type]; } else { $type = "date"; }
$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_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'];
$bill_name = $rate_data['bill_name'];
$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));
$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)
{
@$timestamp = $row['formatted_date'];
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);
$last = $timestamp;
$iter_in += $in_delta;
$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 ($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";
$i++;
unset($iter_out, $iter_in, $iter_period);
}
$iter++;
if ($_GET[type]) {
$type = $_GET[type];
}
else {
$type = 'date';
}
$graph_name = date('M j g:ia', $start) . " - " . date('M j g:ia', $last);
$dur = ($end - $start);
$n = count($ticks);
$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_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'];
$bill_name = $rate_data['bill_name'];
$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));
$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) {
@$timestamp = $row['formatted_date'];
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);
$last = $timestamp;
$iter_in += $in_delta;
$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 ($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';
$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);
$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->SetScale('datlin', 0, 0, $start, $end);
#$graph->title->Set("$graph_name");
$graph->title->SetFont(FF_FONT2,FS_BOLD,10);
$graph->xaxis->SetFont(FF_FONT1,FS_BOLD);
// $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);
$graph->xaxis->title->SetFont(FF_FONT1,FS_NORMAL,10);
$graph->yaxis->title->SetFont(FF_FONT1,FS_NORMAL,10);
$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');
$graph->ygrid->SetFill(true,'#EFEFEF@0.5','#FFFFFF@0.5');
$graph->xgrid->Show(true,true);
$graph->xgrid->SetColor('#e0e0e0','#efefef');
$graph->ygrid->SetFill(true, '#EFEFEF@0.5', '#FFFFFF@0.5');
$graph->xgrid->Show(true, true);
$graph->xgrid->SetColor('#e0e0e0', '#efefef');
$graph->SetMarginColor('white');
$graph->SetFrame(false);
$graph->SetMargin(75,30,30,45);
$graph->legend->SetFont(FF_FONT1,FS_NORMAL);
$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'])
{
$lineplot_95th = new LinePlot($per_data, $ticks);
$lineplot_95th ->SetColor("red");
if ($_GET['95th']) {
$lineplot_95th = new LinePlot($per_data, $ticks);
$lineplot_95th->SetColor('red');
}
if ($_GET['ave'])
{
$lineplot_ave = new LinePlot($ave_data, $ticks);
$lineplot_ave ->SetColor("red");
if ($_GET['ave']) {
$lineplot_ave = new LinePlot($ave_data, $ticks);
$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'])
{
$graph->Add($lineplot_95th);
if ($_GET['95th']) {
$graph->Add($lineplot_95th);
}
if ($_GET['ave'])
{
$graph->Add($lineplot_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";
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;
ini_set('display_errors', 0);
ini_set('display_startup_errors', 0);
ini_set('log_errors', 0);
ini_set('error_reporting', 0);
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;
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-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 {
echo "Report not found.\n";
if (!empty($report) && file_exists("includes/reports/$report.csv.inc.php")) {
if ($debug == false) {
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 {
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'])))
{
$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;
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;
}
$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");
exit;
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");
exit;
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");
exit;
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')
{
$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);
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')
{
$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')
{
$new_conf_type = 'array';
}
elseif($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
$new_conf_value = '';
}
$new_conf_value = nl2br($_POST['new_conf_multi_value']);
$values = explode('<br />',$new_conf_value);
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!');
$db_inserted = 0;
exit;
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);
}
else if ($new_conf_type == 'Standard Array' || $new_conf_type == 'Multi Array') {
if ($new_conf_type == 'Standard Array') {
$new_conf_type = '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
$new_conf_value = '';
}
if($db_inserted == 1)
{
echo('Your new config item has been added');
}
else
{
echo('An error occurred adding your config item to the database');
$new_conf_value = nl2br($_POST['new_conf_multi_value']);
$values = explode('<br />', $new_conf_value);
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!';
$db_inserted = 0;
exit;
}//end if
?>
if ($db_inserted == 1) {
echo 'Your new config item has been added';
}
else {
echo 'An error occurred adding your config item to the database';
}

View File

@ -13,25 +13,29 @@
*/
$alert_id = mres($_POST['alert_id']);
$state = mres($_POST['state']);
if(!is_numeric($alert_id)) {
echo('ERROR: No alert selected');
$state = mres($_POST['state']);
if (!is_numeric($alert_id)) {
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 {
if($state == 2) {
$state = dbFetchCell('SELECT alerted FROM alerts WHERE id = ?',array($alert_id));
} elseif($state >= 1) {
}
else {
if ($state == 2) {
$state = dbFetchCell('SELECT alerted FROM alerts WHERE id = ?', array($alert_id));
}
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

@ -4,12 +4,12 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the
* 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/>. */
@ -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

@ -12,30 +12,32 @@
* the source code distribution for details.
*/
if(is_admin() === false) {
if (is_admin() === false) {
die('ERROR: You need to be admin');
}
if(!is_numeric($_POST['template_id'])) {
echo('ERROR: No template selected');
if (!is_numeric($_POST['template_id'])) {
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;
$ids[] = $db_id;
} else {
echo('ERROR: Alert rules have not been attached to this template.');
$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).")");
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');
exit;
}
else
{
if($_POST['state'] == 'true')
{
$state = 1;
}
elseif($_POST['state'] == 'false')
{
$state = 0;
}
else
{
$state = 0;
}
$update = dbUpdate(array('config_disabled' => $state), 'config', '`config_id` = ?', array($_POST['config_id']));
if(!empty($update) || $update == '0')
{
echo('success');
if (!is_numeric($_POST['config_id'])) {
echo 'error with data';
exit;
}
else
{
echo('error');
exit;
}
}
else {
if ($_POST['state'] == 'true') {
$state = 1;
}
else if ($_POST['state'] == 'false') {
$state = 0;
}
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;
}
}//end if

View File

@ -13,25 +13,19 @@
*/
// FUA
if(!is_numeric($_POST['config_id']) || empty($_POST['data']))
{
echo('error with data');
exit;
}
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 (!is_numeric($_POST['config_id']) || empty($_POST['data'])) {
echo 'error with data';
exit;
}
else
{
echo('error');
exit;
}
}
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';
exit;
}
else {
echo 'error';
exit;
}
}

View File

@ -12,121 +12,145 @@
* the source code distribution for details.
*/
if(is_admin() === false) {
$response = array('status'=>'error','message'=>'Need to be admin');
if (is_admin() === false) {
$response = array(
'status' => 'error',
'message' => 'Need to be admin',
);
echo _json_encode($response);
exit;
}
$action = mres($_POST['action']);
$config_group = mres($_POST['config_group']);
$action = mres($_POST['action']);
$config_group = mres($_POST['config_group']);
$config_sub_group = mres($_POST['config_sub_group']);
$config_name = mres($_POST['config_name']);
$config_value = mres($_POST['config_value']);
$config_extra = mres($_POST['config_extra']);
$config_room_id = mres($_POST['config_room_id']);
$config_from = mres($_POST['config_from']);
$config_userkey = mres($_POST['config_userkey']);
$status = 'error';
$message = 'Error with config';
$config_name = mres($_POST['config_name']);
$config_value = mres($_POST['config_value']);
$config_extra = mres($_POST['config_extra']);
$config_room_id = mres($_POST['config_room_id']);
$config_from = mres($_POST['config_from']);
$config_userkey = mres($_POST['config_userkey']);
$status = 'error';
$message = 'Error with config';
if ($action == 'remove' || $action == 'remove-slack' || $action == 'remove-hipchat' || $action == 'remove-pushover') {
$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';
$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 {
$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');
}
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));
$status = 'ok';
$status = 'ok';
$message = 'Config item created';
$extras = explode('\n',$config_extra);
$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');
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 {
$message = 'Could not create config item';
}
}
} elseif ($action == 'add-hipchat') {
if (empty($config_value) || empty($config_room_id) || empty($config_from)) {
$message = 'No hipchat url, room id or from provided';
} 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));
$additional_id['room_id'] = dbInsert(array('config_name' => 'alert.transports.hipchat.'.$config_id.'.room_id', 'config_value' => $config_room_id, 'config_group' => $config_group, 'config_sub_group' => $config_sub_group, 'config_default'=>$config_room_id, 'config_descr'=>'Hipchat URL'), 'config');
$additional_id['from'] = dbInsert(array('config_name' => 'alert.transports.hipchat.'.$config_id.'.from', 'config_value' => $config_from, 'config_group' => $config_group, 'config_sub_group' => $config_sub_group, 'config_default'=>$config_from, 'config_descr'=>'Hipchat From'), 'config');
$status = 'ok';
$message = 'Config item created';
$extras = explode('\n',$config_extra);
foreach ($extras as $option) {
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 {
$message = 'Could not create config item';
}
}
} elseif ($action == 'add-pushover') {
if (empty($config_value) || empty($config_userkey)) {
$message = 'No pushover appkey or userkey provided';
} 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));
$additional_id['userkey'] = dbInsert(array('config_name' => 'alert.transports.pushover.'.$config_id.'.userkey', 'config_value' => $config_userkey, 'config_group' => $config_group, 'config_sub_group' => $config_sub_group, 'config_default'=>$config_userkey, 'config_descr'=>'Pushver Userkey'), 'config');
$status = 'ok';
$message = 'Config item created';
$extras = explode('\n',$config_extra);
foreach ($extras as $option) {
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 {
$message = 'Could not create config item';
}
}
} else {
if (empty($config_group) || empty($config_sub_group) || empty($config_name) || empty($config_value)) {
$message = 'Missing config name or value';
} 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';
}
}
}
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 {
$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));
$additional_id['room_id'] = dbInsert(array('config_name' => 'alert.transports.hipchat.'.$config_id.'.room_id', 'config_value' => $config_room_id, 'config_group' => $config_group, 'config_sub_group' => $config_sub_group, 'config_default' => $config_room_id, 'config_descr' => 'Hipchat URL'), 'config');
$additional_id['from'] = dbInsert(array('config_name' => 'alert.transports.hipchat.'.$config_id.'.from', 'config_value' => $config_from, 'config_group' => $config_group, 'config_sub_group' => $config_sub_group, 'config_default' => $config_from, 'config_descr' => 'Hipchat From'), 'config');
$status = 'ok';
$message = 'Config item created';
$extras = explode('\n', $config_extra);
foreach ($extras as $option) {
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 {
$message = 'Could not create config item';
}
}//end if
}
else if ($action == 'add-pushover') {
if (empty($config_value) || empty($config_userkey)) {
$message = 'No pushover appkey or userkey provided';
}
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));
$additional_id['userkey'] = dbInsert(array('config_name' => 'alert.transports.pushover.'.$config_id.'.userkey', 'config_value' => $config_userkey, 'config_group' => $config_group, 'config_sub_group' => $config_sub_group, 'config_default' => $config_userkey, 'config_descr' => 'Pushver Userkey'), 'config');
$status = 'ok';
$message = 'Config item created';
$extras = explode('\n', $config_extra);
foreach ($extras as $option) {
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 {
$message = 'Could not create config item';
}
}
}
else {
if (empty($config_group) || empty($config_sub_group) || empty($config_name) || empty($config_value)) {
$message = 'Missing config name or value';
}
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 {
$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

@ -12,68 +12,85 @@
* the source code distribution for details.
*/
if(is_admin() === false) {
if (is_admin() === false) {
die('ERROR: You need to be admin');
}
$rule = implode(" ", $_POST['rules']);
$rule = rtrim($rule,'&&');
$rule = rtrim($rule,'||');
$rule = implode(' ', $_POST['rules']);
$rule = rtrim($rule, '&&');
$rule = rtrim($rule, '||');
$alert_id = $_POST['alert_id'];
$count = mres($_POST['count']);
$delay = mres($_POST['delay']);
$count = mres($_POST['count']);
$delay = mres($_POST['delay']);
$interval = mres($_POST['interval']);
$mute = mres($_POST['mute']);
$invert = mres($_POST['invert']);
$name = mres($_POST['name']);
$mute = mres($_POST['mute']);
$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] == ':') {
if (empty($rule)) {
$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';
if (!is_numeric($count)) {
$count = '-1';
}
$delay_sec = convert_delay($delay);
$delay_sec = convert_delay($delay);
$interval_sec = convert_delay($interval);
if($mute == 'on') {
if ($mute == 'on') {
$mute = true;
} else {
}
else {
$mute = false;
}
if($invert == 'on') {
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) {
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 {
if( is_array($_POST['maps']) ) {
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') ) {
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']) ) {
foreach( $_POST['maps'] as $target ) {
$_POST['rule'] = $name;
if (is_array($_POST['maps'])) {
foreach ($_POST['maps'] as $target) {
$_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: invalid device ID or not a global alert";
else {
$update_message = 'ERROR: Failed to add Rule: <i>'.$rule.'</i>';
}
}//end if
}
else {
$update_message = 'ERROR: invalid device ID or not a global alert';
}//end if
echo $update_message;

View File

@ -12,41 +12,46 @@
* the source code distribution for details.
*/
if(is_admin() === false) {
if (is_admin() === false) {
die('ERROR: You need to be admin');
}
$pattern = $_POST['patterns'];
$pattern = $_POST['patterns'];
$group_id = $_POST['group_id'];
$name = mres($_POST['name']);
$desc = mres($_POST['desc']);
$name = mres($_POST['name']);
$desc = mres($_POST['desc']);
if( is_array($pattern) ) {
$pattern = implode(" ", $pattern);
$pattern = rtrim($pattern,'&&');
$pattern = rtrim($pattern,'||');
} elseif( !empty($_POST['pattern']) && !empty($_POST['condition']) && !empty($_POST['value']) ) {
$pattern = '%'.$_POST['pattern'].' '.$_POST['condition'].' ';
if( is_numeric($_POST['value']) ) {
$pattern .= $_POST['value'];
} else {
$pattern .= '"'.$_POST['value'].'"';
}
if (is_array($pattern)) {
$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 {
$pattern .= '"'.$_POST['value'].'"';
}
}
if(empty($pattern)) {
$update_message = "ERROR: No group was generated";
} elseif(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>";
if (empty($pattern)) {
$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 {
if( dbInsert(array('pattern'=>$pattern,'name'=>$name,'desc'=>$desc),'device_groups') ) {
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

@ -12,7 +12,7 @@
* the source code distribution for details.
*/
if(is_admin() === false) {
if (is_admin() === false) {
die('ERROR: You need to be admin');
}
@ -21,46 +21,56 @@ $target = mres($_POST['target']);
$map_id = mres($_POST['map_id']);
$ret = array();
if( empty($rule) || empty($target) ) {
$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 {
$raw = $target;
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 {
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>");
}
} 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>");
}
}
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>");
}
}
}
}
if (empty($rule) || empty($target)) {
$ret[] = 'ERROR: No map was generated';
}
foreach( $ret as $msg ) {
echo $msg."<br/>";
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 {
$raw = $target;
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 {
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>');
}
}
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>');
}
}
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>");
}
}
}//end if
}//end if
}//end if
foreach ($ret as $msg) {
echo $msg.'<br/>';
}

View File

@ -12,30 +12,36 @@
* the source code distribution for details.
*/
if(is_admin() === false) {
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 {
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']);
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 {
array_unshift($ret, 'ERROR: Rule '.$rule['id'].' has not been restored.');
$brk = true;
}
}
if( $brk === false && dbDelete('alert_map', "`id` = ?", array($_POST['map_id'])) ) {
$ret[] = 'Map has been deleted.';
} else {
array_unshift($ret, 'ERROR: Map has not been deleted.');
}
if (!is_numeric($_POST['map_id'])) {
array_unshift($ret, 'ERROR: No map selected');
}
foreach( $ret as $msg ) {
echo $msg."<br/>";
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']);
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 {
array_unshift($ret, 'ERROR: Rule '.$rule['id'].' has not been restored.');
$brk = true;
}
}
if ($brk === false && dbDelete('alert_map', '`id` = ?', array($_POST['map_id']))) {
$ret[] = 'Map has been deleted.';
}
else {
array_unshift($ret, 'ERROR: Map has not been deleted.');
}
}
foreach ($ret as $msg) {
echo $msg.'<br/>';
}

View File

@ -12,25 +12,28 @@
* the source code distribution for details.
*/
if(is_admin() === false) {
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(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;
}
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

@ -12,20 +12,21 @@
* the source code distribution for details.
*/
if(is_admin() === false) {
if (is_admin() === false) {
die('ERROR: You need to be admin');
}
if(!is_numeric($_POST['template_id'])) {
echo('ERROR: No template selected');
if (!is_numeric($_POST['template_id'])) {
echo 'ERROR: No template selected';
exit;
} 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.');
exit;
}
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.';
exit;
}
}

View File

@ -12,26 +12,28 @@
* the source code distribution for details.
*/
if(is_admin() === false) {
if (is_admin() === false) {
die('ERROR: You need to be admin');
}
if(!is_numeric($_POST['group_id'])) {
echo('ERROR: No group selected');
if (!is_numeric($_POST['group_id'])) {
echo 'ERROR: No group selected';
exit;
} 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');
}
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;
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'];
$module = 'discover_'.$_POST['discovery_module'];
if(!isset($module) && validate_device_id($device['device_id']) === false)
{
echo('error with data');
exit;
if (!isset($module) && validate_device_id($device['device_id']) === false) {
echo 'error with data';
exit;
}
else
{
if($_POST['state'] == 'true')
{
$state = 1;
}
elseif($_POST['state'] == 'false')
{
$state = 0;
}
else
{
$state = 0;
}
else {
if ($_POST['state'] == 'true') {
$state = 1;
}
else if ($_POST['state'] == 'false') {
$state = 0;
}
else {
$state = 0;
}
if(isset($attribs['discover_'.$module]) && $attribs['discover_'.$module] != $config['discover_modules'][$module])
{
del_dev_attrib($device, $module);
}
else
{
set_dev_attrib($device, $module, $state);
}
if (isset($attribs['discover_'.$module]) && $attribs['discover_'.$module] != $config['discover_modules'][$module]) {
del_dev_attrib($device, $module);
}
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');
exit;
}
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 (!is_numeric($_POST['device_id']) || !is_numeric($_POST['sensor_id']) || (empty($_POST['data']) || !isset($_POST['data']))) {
echo 'error with data';
exit;
}
else
{
echo('error');
exit;
}
}
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';
exit;
}
else {
echo 'error';
exit;
}
}

View File

@ -12,19 +12,24 @@
* the source code distribution for details.
*/
if(is_admin() === false) {
if (is_admin() === false) {
die('ERROR: You need to be admin');
}
$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']));
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)));
}
$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

@ -12,17 +12,22 @@
* the source code distribution for details.
*/
if(is_admin() === false) {
if (is_admin() === false) {
die('ERROR: You need to be admin');
}
$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;
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_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

@ -12,14 +12,17 @@
* the source code distribution for details.
*/
if(is_admin() === false) {
if (is_admin() === false) {
die('ERROR: You need to be admin');
}
$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']);
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'],
);
echo _json_encode($output);
}

View File

@ -12,17 +12,27 @@
* the source code distribution for details.
*/
if(is_admin() === false) {
if (is_admin() === false) {
die('ERROR: You need to be admin');
}
$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;
$group_split[$count] = $group_split[$count].' &&';
$output = array('name'=>$group['name'],'desc'=>$group['desc'],'pattern'=>$group_split);
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_split[$count] = $group_split[$count];
}
else {
$group_split[$count] = $group_split[$count].' &&';
}
$output = array(
'name' => $group['name'],
'desc' => $group['desc'],
'pattern' => $group_split,
);
echo _json_encode($output);
}

View File

@ -12,14 +12,17 @@
* the source code distribution for details.
*/
if(is_admin() === false) {
if (is_admin() === false) {
die('ERROR: You need to be admin');
}
$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']);
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'],
);
echo _json_encode($output);
}

View File

@ -12,16 +12,17 @@
* the source code distribution for details.
*/
if(is_admin() === false) {
if (is_admin() === false) {
die('ERROR: You need to be admin');
}
$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) {
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) {
$rules[] = $rule['alert_rule_id'];
}
$output = array('rule_id'=>$rules);
$output = array('rule_id' => $rules);
echo _json_encode($output);
}

View File

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

View File

@ -12,36 +12,40 @@
* the source code distribution for details.
*/
if(is_admin() === false) {
if (is_admin() === false) {
die('ERROR: You need to be admin');
}
$ok = '';
$error = '';
$group_id = $_POST['group_id'];
$ok = '';
$error = '';
$group_id = $_POST['group_id'];
$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";
$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 {
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";
else {
$error = 'Failed to update the poller group';
}
}
} else {
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';
}
}
}
else {
$error = "You haven't given your poller group a name, it feels sad :( - $group_name";
}
if(!empty( $ok )) {
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'];
$module = 'poll_'.$_POST['poller_module'];
if(!isset($module) && validate_device_id($device['device_id']) === false)
{
echo('error with data');
exit;
if (!isset($module) && validate_device_id($device['device_id']) === false) {
echo 'error with data';
exit;
}
else
{
if($_POST['state'] == 'true')
{
$state = 1;
}
elseif($_POST['state'] == 'false')
{
$state = 0;
}
else
{
$state = 0;
}
else {
if ($_POST['state'] == 'true') {
$state = 1;
}
else if ($_POST['state'] == 'false') {
$state = 0;
}
else {
$state = 0;
}
if(isset($attribs['poll_'.$module]) && $attribs['poll_'.$module] != $config['poller_modules'][$module])
{
del_dev_attrib($device, $module);
}
else
{
set_dev_attrib($device, $module, $state);
}
if (isset($attribs['poll_'.$module]) && $attribs['poll_'.$module] != $config['poller_modules'][$module]) {
del_dev_attrib($device, $module);
}
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 {
if (!is_numeric($_POST['device_id'])) {
$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";
if (!empty($update) || $update == '0') {
$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

@ -12,14 +12,13 @@
* the source code distribution for details.
*/
if(is_admin() === false) {
if (is_admin() === false) {
die('ERROR: You need to be admin');
}
$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,75 +35,98 @@ 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 />";
if (!is_array($_POST['maps'])) {
$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 {
dbUpdate(array('start'=>$start,'end'=>$end,'title'=>$title,'notes'=>$notes),'alert_schedule','`schedule_id`=?',array($schedule_id));
$schedule_id = dbInsert(array('start' => $start, 'end' => $end, 'title' => $title, 'notes' => $notes), 'alert_schedule');
}
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;
$fail = 0;
if ($update == 1) {
dbDelete('alert_schedule_items', '`schedule_id`=?', array($schedule_id));
}
foreach( $_POST['maps'] as $target ) {
foreach ($_POST['maps'] as $target) {
$target = target_to_id($target);
$item = dbInsert(array('schedule_id'=>$schedule_id,'target'=>$target),'alert_schedule_items');
$item = dbInsert(array('schedule_id' => $schedule_id, 'target' => $target), 'alert_schedule_items');
if ($item > 0) {
array_push($items,$item);
} else {
array_push($items, $item);
}
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 {
$status = 'ok';
}
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);
} elseif ($sub_type == 'parse-maintenance') {
$schedule_id = mres($_POST['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) {
$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') {
$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,
);
}
else if ($sub_type == 'parse-maintenance') {
$schedule_id = mres($_POST['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) {
$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,
);
}
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,
);
}//end if
echo _json_encode($response);

View File

@ -13,9 +13,6 @@
*/
// FUA
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]));
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 {
}
else {
if (!is_numeric($_POST['device_id']) || !is_numeric($_POST['sensor_id'])) {
echo 'error with data';
exit;
}
else {
if ($_POST['state'] == 'true') {
$state = 1;
}
else if ($_POST['state'] == 'false') {
$state = 0;
}
else {
$state = 0;
}
if(!is_numeric($_POST['device_id']) || !is_numeric($_POST['sensor_id']))
{
echo('error with data');
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;
}
}
}
else
{
if($_POST['state'] == 'true')
{
$state = 1;
}
elseif($_POST['state'] == 'false')
{
$state = 0;
}
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;
}
}
}

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.');
exit;
}
elseif(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');
exit;
}
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 (!is_numeric($_POST['user_id']) || !isset($_POST['token'])) {
echo 'ERROR: error with data, please ensure a valid user and token have been specified.';
exit;
}
else
{
echo('ERROR: An error occurred creating the API token');
exit;
}
}
else if (strlen($_POST['token']) > 32) {
echo 'ERROR: The token is more than 32 characters';
exit;
}
else if (strlen($_POST['token']) < 16) {
echo 'ERROR: The token is less than 16 characters';
exit;
}
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;
exit;
}
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');
exit;
}
else
{
if($_POST['state'] == 'true')
{
$state = 1;
}
elseif($_POST['state'] == 'false')
{
$state = 0;
}
else
{
$state = 0;
}
$update = dbUpdate(array('disabled' => $state), 'api_tokens', '`id` = ?', array($_POST['token_id']));
if(!empty($update) || $update == '0')
{
echo('success');
if (!is_numeric($_POST['token_id'])) {
echo 'error with data';
exit;
}
else
{
echo('error');
exit;
}
}
else {
if ($_POST['state'] == 'true') {
$state = 1;
}
else if ($_POST['state'] == 'false') {
$state = 0;
}
else {
$state = 0;
}
$update = dbUpdate(array('disabled' => $state), 'api_tokens', '`id` = ?', array($_POST['token_id']));
if (!empty($update) || $update == '0') {
echo 'success';
exit;
}
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');
exit;
if (!is_numeric($_POST['token_id'])) {
echo 'error with data';
exit;
}
else
{
if($_POST['confirm'] == 'yes')
{
$delete = dbDelete('api_tokens', '`id` = ?', array($_POST['token_id']));
if($delete > '0')
{
echo('API token has been removed');
exit;
else {
if ($_POST['confirm'] == 'yes') {
$delete = dbDelete('api_tokens', '`id` = ?', array($_POST['token_id']));
if ($delete > '0') {
echo 'API token has been removed';
exit;
}
else {
echo 'An error occurred removing the API token';
exit;
}
}
else
{
echo('An error occurred removing the API token');
exit;
}
}
}
}//end if

View File

@ -12,39 +12,32 @@
* the source code distribution for details.
*/
if(is_admin() === false) {
if (is_admin() === false) {
die('ERROR: You need to be admin');
}
if(!is_numeric($_POST['alert_id']))
{
echo('ERROR: No alert selected');
exit;
}
else
{
if($_POST['state'] == 'true')
{
$state = 0;
}
elseif($_POST['state'] == 'false')
{
$state = 1;
}
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.');
if (!is_numeric($_POST['alert_id'])) {
echo 'ERROR: No alert selected';
exit;
}
else
{
echo('ERROR: Alert rule has not been updated.');
exit;
}
}
else {
if ($_POST['state'] == 'true') {
$state = 0;
}
else if ($_POST['state'] == 'false') {
$state = 1;
}
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;
}
}

View File

@ -12,58 +12,70 @@
* the source code distribution for details.
*/
if(is_admin() === false) {
if (is_admin() === false) {
die('ERROR: You need to be admin');
}
$config_id = mres($_POST['config_id']);
$action = mres($_POST['action']);
$config_id = mres($_POST['config_id']);
$action = mres($_POST['action']);
$config_type = mres($_POST['config_type']);
$status = 'error';
if (!is_numeric($config_id)) {
$message = 'ERROR: No alert selected';
} elseif ($action == 'update-textarea') {
$extras = explode(PHP_EOL,$_POST['config_value']);
}
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') {
$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') {
$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_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');
}
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');
}
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') {
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') {
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))");
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))");
}
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))");
}
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 {
$state = mres($_POST['config_value']);
$status = 'ok';
}
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 {
$status = 'ok';
}
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");
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 {
echo("Unauthenticad");
die;
require_once '../includes/snmp.inc.php';
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 {
echo("Unauthenticad");
die;
}
header("Content-type: image/svg+xml");
@ -47,16 +45,19 @@ $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
$nb_plot=240; //NB plot in graph
if(is_numeric($_GET['interval'])) {
$time_interval=$_GET['interval'];
} else {
$time_interval=1; //Refresh time Interval
$time_interval=$_GET['interval'];
}
else {
$time_interval=1; //Refresh time Interval
}
$fetch_link = "data.php?id=".$_GET[id];
@ -225,24 +226,24 @@ function plot_data(obj) {
last_ifout = ifout;
switch (plot_in.length) {
case 0:
SVGDoc.getElementById("collect_initial").setAttributeNS(null, 'visibility', 'visible');
plot_in[0] = diff_ifin / diff_ugmt;
plot_out[0] = diff_ifout / diff_ugmt;
setTimeout('fetch_data()',<?php echo(1000*$time_interval) ?>);
return;
case 1:
SVGDoc.getElementById("collect_initial").setAttributeNS(null, 'visibility', 'hidden');
break;
case 0:
SVGDoc.getElementById("collect_initial").setAttributeNS(null, 'visibility', 'visible');
plot_in[0] = diff_ifin / diff_ugmt;
plot_out[0] = diff_ifout / diff_ugmt;
setTimeout('fetch_data()',<?php echo(1000*$time_interval) ?>);
return;
case 1:
SVGDoc.getElementById("collect_initial").setAttributeNS(null, 'visibility', 'hidden');
break;
case max_num_points:
// shift plot to left if the maximum number of plot points has been reached
var i = 0;
while (i < max_num_points) {
plot_in[i] = plot_in[i+1];
plot_out[i] = plot_out[++i];
}
plot_in.length--;
plot_out.length--;
// shift plot to left if the maximum number of plot points has been reached
var i = 0;
while (i < max_num_points) {
plot_in[i] = plot_in[i+1];
plot_out[i] = plot_out[++i];
}
plot_in.length--;
plot_out.length--;
}
plot_in[plot_in.length] = diff_ifin / diff_ugmt;

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());
$usec = (double)$time[0];
$sec = (double)$time[1];
return $sec + $usec;
function utime() {
$time = explode(' ', microtime());
$usec = (double) $time[0];
$sec = (double) $time[1];
return ($sec + $usec);
}
$start = utime();
include_once("Net/IPv4.php");
require_once 'Net/IPv4.php';
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);
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;
ini_set('display_errors', 0);
ini_set('display_startup_errors', 0);
ini_set('log_errors', 0);
ini_set('error_reporting', 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);
}
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

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

File diff suppressed because it is too large Load Diff

View File

@ -1,123 +1,114 @@
<?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'])
{
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']));
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'], "/");
session_destroy();
$auth_message = "Logged Out";
header('Location: /');
exit;
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']));
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']), '/');
session_destroy();
$auth_message = 'Logged Out';
header('Location: /');
exit;
}
// We are only interested in login details passed via POST.
if (isset($_POST['username']) && isset($_POST['password'])) {
$_SESSION['username'] = mres($_POST['username']);
$_SESSION['password'] = $_POST['password'];
} elseif(isset($_GET['username']) && isset($_GET['password'])) {
$_SESSION['username'] = mres($_GET['username']);
$_SESSION['password'] = $_GET['password'];
$_SESSION['username'] = mres($_POST['username']);
$_SESSION['password'] = $_POST['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
{
print_error('ERROR: no valid auth_mechanism defined!');
exit();
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'])))
{
$_SESSION['userlevel'] = get_userlevel($_SESSION['username']);
$_SESSION['user_id'] = get_userid($_SESSION['username']);
if (!$_SESSION['authenticated'])
{
if( $config['twofactor'] === true && !isset($_SESSION['twofactor']) ) {
require_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($_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 ($config['twofactor'] === true && !isset($_SESSION['twofactor'])) {
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'])) {
$sess_id = session_id();
$hasher = new PasswordHash(8, false);
$token = strgen();
$auth = strgen();
$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);
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 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);
}
$permissions = permissions_cache($_SESSION['user_id']);
if (isset($_POST['username'])) {
header('Location: '.$_SERVER['REQUEST_URI'], true, 303);
exit;
}
}
if (isset($_POST['remember']))
{
$sess_id = session_id();
$hasher = new PasswordHash(8, FALSE);
$token = strgen();
$auth = strgen();
$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);
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');
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');
}
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);
}
$permissions = permissions_cache($_SESSION['user_id']);
if (isset($_POST['username'])) {
header('Location: '.$_SERVER['REQUEST_URI'],TRUE,303);
exit;
}
}
elseif (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,104 +1,99 @@
<?php
if (!isset($_SESSION['username']))
{
$_SESSION['username'] = '';
if (!isset($_SESSION['username'])) {
$_SESSION['username'] = '';
}
function authenticate($username,$password)
{
global $config;
if (isset($_SERVER['REMOTE_USER']))
{
$_SESSION['username'] = mres($_SERVER['REMOTE_USER']);
function authenticate($username, $password) {
global $config;
$row = @dbFetchRow("SELECT username FROM `users` WHERE `username`=?", array($_SESSION['username']));
if (isset($row['username']) && $row['username'] == $_SESSION['username'])
{
return 1;
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']) {
return 1;
}
else {
$_SESSION['username'] = $config['http_auth_guest'];
return 1;
}
}
else
{
$_SESSION['username'] = $config['http_auth_guest'];
return 1;
}
}
return 0;
return 0;
}
function reauthenticate($sess_id = "",$token = "")
{
return 0;
function reauthenticate($sess_id='', $token='') {
return 0;
}
function passwordscanchange($username = "")
{
return 0;
function passwordscanchange($username='') {
return 0;
}
function changepassword($username,$newpassword)
{
# Not supported
function changepassword($username, $newpassword) {
// Not supported
}
function auth_usermanagement()
{
return 1;
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)
{
// FIXME this doesn't seem right? (adama)
return dbFetchCell("SELECT * FROM `users` WHERE `username` = ?", array($username));
function user_exists($username) {
// FIXME this doesn't seem right? (adama)
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
return 0;
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
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)
{
dbUpdate(array('realname' => $realname, 'level' => $level, 'can_modify_passwd' => $can_modify_passwd, 'email' => $email), 'users', '`user_id` = ?', array($user_id));
}
?>
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

@ -1,228 +1,237 @@
<?php
$ds = @ldap_connect($config['auth_ldap_server'],$config['auth_ldap_port']);
$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'))
{
$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>");
exit;
}
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>';
exit;
}
}
function authenticate($username,$password)
{
global $config, $ds;
if ($username && $ds)
{
if ($config['auth_ldap_version'])
{
ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, $config['auth_ldap_version']);
function authenticate($username, $password) {
global $config, $ds;
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']) {
return 1;
}
else {
$ldap_groups = get_group_list();
foreach ($ldap_groups as $ldap_group) {
$ldap_comparison = ldap_compare(
$ds,
$ldap_group,
$config['auth_ldap_groupmemberattr'],
get_membername($username)
);
if ($ldap_comparison === true) {
return 1;
}
}
}
}
else {
echo ldap_error($ds);
}
}
if (ldap_bind($ds, $config['auth_ldap_prefix'] . $username . $config['auth_ldap_suffix'], $password))
{
if (!$config['auth_ldap_group'])
{
else {
// FIXME return a warning that LDAP couldn't connect?
}
return 0;
}
function reauthenticate($sess_id, $token) {
return 0;
}
function passwordscanchange($username='') {
return 0;
}
function changepassword($username, $newpassword) {
// Not supported (for now)
}
function auth_usermanagement() {
return 0;
}
function adduser($username, $password, $level, $email='', $realname='', $can_modify_passwd='1') {
// Not supported
return 0;
}
function user_exists($username) {
global $config, $ds;
$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']) {
return 1;
}
else
{
$ldap_groups = get_group_list();
foreach($ldap_groups as $ldap_group) {
$ldap_comparison = ldap_compare($ds,
$ldap_group,
$config['auth_ldap_groupmemberattr'],
get_membername($username));
if($ldap_comparison === true) {
return 1;
}
}
return 0;
}
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).'))';
$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) {
$groupname = $entry['cn'][0];
if ($config['auth_ldap_groups'][$groupname]['level'] > $userlevel) {
$userlevel = $config['auth_ldap_groups'][$groupname]['level'];
}
}
}
else
{
echo(ldap_error($ds));
return $userlevel;
}
function get_userid($username) {
global $config, $ds;
$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']) {
return $entries[0]['uidnumber'][0];
}
}
else
{
// FIXME return a warning that LDAP couldn't connect?
}
return 0;
return -1;
}
function reauthenticate($sess_id,$token)
{
return 0;
function deluser($username) {
// Not supported
return 0;
}
function passwordscanchange($username = "")
{
return 0;
}
function changepassword($username,$newpassword)
{
# Not supported (for now)
}
function get_userlist() {
global $config, $ds;
$userlist = array();
function auth_usermanagement()
{
return 0;
}
$filter = '('.$config['auth_ldap_prefix'].'*)';
function adduser($username, $password, $level, $email = "", $realname = "", $can_modify_passwd = '1')
{
# Not supported
return 0;
}
$search = ldap_search($ds, trim($config['auth_ldap_suffix'], ','), $filter);
$entries = ldap_get_entries($ds, $search);
function user_exists($username)
{
global $config, $ds;
$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'])
{
return 1;
}
return 0;
}
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) . "))";
$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)
{
$groupname = $entry['cn'][0];
if ($config['auth_ldap_groups'][$groupname]['level'] > $userlevel)
{
$userlevel = $config['auth_ldap_groups'][$groupname]['level'];
}
}
return $userlevel;
}
function get_userid($username)
{
global $config, $ds;
$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'])
{
return $entries[0]['uidnumber'][0];
}
return -1;
}
function deluser($username)
{
# Not supported
return 0;
}
function get_userlist()
{
global $config, $ds;
$userlist = array();
$filter = '(' . $config['auth_ldap_prefix'] . '*)';
$search = ldap_search($ds, trim($config['auth_ldap_suffix'],','), $filter);
$entries = ldap_get_entries($ds, $search);
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_group,
$config['auth_ldap_groupmemberattr'],
get_membername($username));
if (!isset($config['auth_ldap_group']) || $ldap_comparison === true) {
$userlist[] = array('username' => $username, 'realname' => $realname, 'user_id' => $user_id, 'email' => $email);
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_group,
$config['auth_ldap_groupmemberattr'],
get_membername($username)
);
if (!isset($config['auth_ldap_group']) || $ldap_comparison === true) {
$userlist[] = array(
'username' => $username,
'realname' => $realname,
'user_id' => $user_id,
'email' => $email,
);
}
}
}
}
}
}
return $userlist;
return $userlist;
}
function can_update_users()
{
# not supported so return 0
return 0;
function can_update_users() {
// not supported so return 0
return 0;
}
function get_user($user_id)
{
# not supported
return 0;
function get_user($user_id) {
// not supported
return 0;
}
function update_user($user_id,$realname,$level,$can_modify_passwd,$email)
{
# not supported
return 0;
function update_user($user_id, $realname, $level, $can_modify_passwd, $email) {
// not supported
return 0;
}
function get_membername ($username)
{
global $config;
if ($config['auth_ldap_groupmembertype'] == "fulldn")
{
$membername = $config['auth_ldap_prefix'] . $username . $config['auth_ldap_suffix'];
}
else
{
$membername = $username;
}
return $membername;
function get_membername($username) {
global $config;
if ($config['auth_ldap_groupmembertype'] == 'fulldn') {
$membername = $config['auth_ldap_prefix'].$username.$config['auth_ldap_suffix'];
}
else {
$membername = $username;
}
return $membername;
}
function get_group_list() {
global $config;
global $config;
$ldap_groups = array();
$default_group = 'cn=groupname,ou=groups,dc=example,dc=com';
if(isset($config['auth_ldap_group'])) {
if($config['auth_ldap_group'] !== $default_group) {
$ldap_groups[] = $config['auth_ldap_group'];
$ldap_groups = array();
$default_group = 'cn=groupname,ou=groups,dc=example,dc=com';
if (isset($config['auth_ldap_group'])) {
if ($config['auth_ldap_group'] !== $default_group) {
$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;
}
?>
foreach ($config['auth_ldap_groups'] as $key => $value) {
$dn = "cn=$key,".$config['auth_ldap_groupbase'];
$ldap_groups[] = $dn;
}
return $ldap_groups;
}

View File

@ -1,71 +1,69 @@
<?php
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)
{
// Migrate from old, unhashed password
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);
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) {
// Migrate from old, unhashed password
if ($row['password'] == $encrypted_old) {
$row_type = dbFetchRow('DESCRIBE users password');
if ($row_type['Type'] == 'varchar(34)') {
changepassword($username, $password);
}
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;
}
}
return 0;
}
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))
{
$_SESSION['username'] = $uname;
return 1;
}
else
{
$hasher = new PasswordHash(8, false);
if ($hasher->CheckPassword($password, $row['password'])) {
return 1;
}
}//end if
return 0;
}
}
function passwordscanchange($username = "")
{
/*
* By default allow the password to be modified, unless the existing
* user is explicitly prohibited to do so.
*/
}//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)) {
$_SESSION['username'] = $uname;
return 1;
}
else {
return 0;
}
}//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)) {
return 1;
}
else {
return dbFetchCell('SELECT can_modify_passwd FROM users WHERE username = ?', array($username));
}
}//end passwordscanchange()
if (empty($username) || !user_exists($username))
{
return 1;
} else {
return dbFetchCell("SELECT can_modify_passwd FROM users WHERE username = ?", array($username));
}
}
/**
* From: http://code.activestate.com/recipes/576894-generate-a-salt/
@ -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";
$i = 0;
$salt = "";
do
{
$salt .= $characterList{mt_rand(0,strlen($characterList))};
$i++;
} while ($i <= $max);
function generateSalt($max=15) {
$characterList = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$i = 0;
$salt = '';
do {
$salt .= $characterList{mt_rand(0, strlen($characterList))};
$i++;
} while ($i <= $max);
return $salt;
}
return $salt;
function changepassword($username,$password)
{
$hasher = new PasswordHash(8, FALSE);
$encrypted = $hasher->HashPassword($password);
return dbUpdate(array('password' => $encrypted), 'users', '`username` = ?', array($username));
}
}//end generateSalt()
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);
function changepassword($username, $password) {
$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;
}
}
return dbUpdate(array('password' => $encrypted), 'users', '`username` = ?', array($username));
function user_exists($username)
{
$return = @dbFetchCell("SELECT COUNT(*) FROM users WHERE username = ?", array($username));
return $return;
}
}//end changepassword()
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 auth_usermanagement() {
return 1;
function deluser($username)
{
}//end auth_usermanagement()
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));
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;
}
}
}//end adduser()
function get_userlist()
{
return dbFetchRows("SELECT * FROM `users`");
}
function can_update_users()
{
# supported so return 1
return 1;
}
function user_exists($username) {
$return = @dbFetchCell('SELECT COUNT(*) FROM users WHERE username = ?', array($username));
return $return;
function get_user($user_id)
{
return dbFetchRow("SELECT * FROM `users` WHERE `user_id` = ?", array($user_id));
}
}//end user_exists()
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));
}
?>
function get_userlevel($username) {
return dbFetchCell('SELECT `level` FROM `users` WHERE `username` = ?', array($username));
}//end get_userlevel()
function get_userid($username) {
return dbFetchCell('SELECT `user_id` FROM `users` WHERE `username` = ?', array($username));
}//end get_userid()
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;
}//end can_update_users()
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

@ -4,14 +4,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the
* 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
@ -44,14 +45,14 @@ const otpWindow = 4;
* Base32 Decoding dictionary
*/
$base32 = array(
"A" => 0, "B" => 1, "C" => 2, "D" => 3,
"E" => 4, "F" => 5, "G" => 6, "H" => 7,
"I" => 8, "J" => 9, "K" => 10, "L" => 11,
"M" => 12, "N" => 13, "O" => 14, "P" => 15,
"Q" => 16, "R" => 17, "S" => 18, "T" => 19,
"U" => 20, "V" => 21, "W" => 22, "X" => 23,
"Y" => 24, "Z" => 25, "2" => 26, "3" => 27,
"4" => 28, "5" => 29, "6" => 30, "7" => 31
"A" => 0, "B" => 1, "C" => 2, "D" => 3,
"E" => 4, "F" => 5, "G" => 6, "H" => 7,
"I" => 8, "J" => 9, "K" => 10, "L" => 11,
"M" => 12, "N" => 13, "O" => 14, "P" => 15,
"Q" => 16, "R" => 17, "S" => 18, "T" => 19,
"U" => 20, "V" => 21, "W" => 22, "X" => 23,
"Y" => 24, "Z" => 25, "2" => 26, "3" => 27,
"4" => 28, "5" => 29, "6" => 30, "7" => 31
);
/**
@ -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']++;
}
}

View File

@ -1,53 +1,91 @@
<?php // vim:fenc=utf-8:filetype=php:ts=4
<?php
/**
* Configuration file for Collectd graph browser
*/
// Array of paths when collectd's rrdtool plugin writes RRDs
$config['datadirs'] = array($config['collectd_dir']);
$config['datadirs'] = array($config['collectd_dir']);
// Width of graph to be generated by rrdgraph
if(isset($_GET['width'])) {
$config['rrd_width'] = $_GET['width'];
} else {
$config['rrd_width'] = 270;
if (isset($_GET['width'])) {
$config['rrd_width'] = $_GET['width'];
}
else {
$config['rrd_width'] = 270;
}
// Height of graph to be generated by rrdgraph
if(isset($_GET['height'])) {
$config['rrd_height'] = $_GET['height'];
} else {
$config['rrd_height'] = 120;
if (isset($_GET['height'])) {
$config['rrd_height'] = $_GET['height'];
}
else {
$config['rrd_height'] = 120;
}
// List of supported timespans (used for period drop-down list)
$config['timespan'] = array(
array('name'=>'hour', 'label'=>'past hour', 'seconds'=>3600),
array('name'=>'day', 'label'=>'past day', 'seconds'=>86400),
array('name'=>'week', 'label'=>'past week', 'seconds'=>604800),
array('name'=>'month', 'label'=>'past month', 'seconds'=>2678400),
array('name'=>'year', 'label'=>'past year', 'seconds'=>31622400));
$config['timespan'] = array(
array(
'name' => 'hour',
'label' => 'past hour',
'seconds' => 3600,
),
array(
'name' => 'day',
'label' => 'past day',
'seconds' => 86400,
),
array(
'name' => 'week',
'label' => 'past week',
'seconds' => 604800,
),
array(
'name' => 'month',
'label' => 'past month',
'seconds' => 2678400,
),
array(
'name' => 'year',
'label' => 'past year',
'seconds' => 31622400,
),
);
// Interval at which values are collectd (currently ignored)
$config['rrd_interval'] = 10;
$config['rrd_interval'] = 10;
// Average rows/rra (currently ignored)
$config['rrd_rows'] = 2400;
$config['rrd_rows'] = 2400;
// Additional options to pass to rrdgraph
#$config['rrd_opts'] = (isset($config['rrdgraph_defaults']) ? $config['rrdgraph_defaults'] : '');
#$config['rrd_opts'] = array('-E', "-c", "SHADEA#a5a5a5", "-c", "SHADEB#a5a5a5", "-c", "FONT#000000", "-c", "CANVAS#FFFFFF", "-c", "GRID#aaaaaa",
# "-c", "MGRID#FFAAAA", "-c", "FRAME#3e3e3e", "-c", "ARROW#5e5e5e", "-R", "normal");
// $config['rrd_opts'] = (isset($config['rrdgraph_defaults']) ? $config['rrdgraph_defaults'] : '');
// $config['rrd_opts'] = array('-E', "-c", "SHADEA#a5a5a5", "-c", "SHADEB#a5a5a5", "-c", "FONT#000000", "-c", "CANVAS#FFFFFF", "-c", "GRID#aaaaaa",
// "-c", "MGRID#FFAAAA", "-c", "FRAME#3e3e3e", "-c", "ARROW#5e5e5e", "-R", "normal");
// Predefined set of colors for use by collectd_draw_rrd()
$config['rrd_colors'] = array(
'h_1'=>'F7B7B7', 'f_1'=>'FF0000', // Red
'h_2'=>'B7EFB7', 'f_2'=>'00E000', // Green
'h_3'=>'B7B7F7', 'f_3'=>'0000FF', // Blue
'h_4'=>'F3DFB7', 'f_4'=>'F0A000', // Yellow
'h_5'=>'B7DFF7', 'f_5'=>'00A0FF', // Cyan
'h_6'=>'DFB7F7', 'f_6'=>'A000FF', // Magenta
'h_7'=>'FFC782', 'f_7'=>'FF8C00', // Orange
'h_8'=>'DCFF96', 'f_8'=>'AAFF00', // Lime
'h_9'=>'83FFCD', 'f_9'=>'00FF99',
'h_10'=>'81D9FF', 'f_10'=>'00B2FF',
'h_11'=>'FF89F5', 'f_11'=>'FF00EA',
'h_12'=>'FF89AE', 'f_12'=>'FF0051',
'h_13'=>'BBBBBB', 'f_13'=>'555555',
);
$config['rrd_colors'] = array(
'h_1' => 'F7B7B7',
'f_1' => 'FF0000', // Red
'h_2' => 'B7EFB7',
'f_2' => '00E000', // Green
'h_3' => 'B7B7F7',
'f_3' => '0000FF', // Blue
'h_4' => 'F3DFB7',
'f_4' => 'F0A000', // Yellow
'h_5' => 'B7DFF7',
'f_5' => '00A0FF', // Cyan
'h_6' => 'DFB7F7',
'f_6' => 'A000FF', // Magenta
'h_7' => 'FFC782',
'f_7' => 'FF8C00', // Orange
'h_8' => 'DCFF96',
'f_8' => 'AAFF00', // Lime
'h_9' => '83FFCD',
'f_9' => '00FF99',
'h_10' => '81D9FF',
'f_10' => '00B2FF',
'h_11' => 'FF89F5',
'f_11' => 'FF00EA',
'h_12' => 'FF89AE',
'f_12' => 'FF0051',
'h_13' => 'BBBBBB',
'f_13' => '555555',
);
/*
* URL to collectd's unix socket (unixsock plugin)
* enabled: 'unix:///var/run/collectd/collectd-unixsock'
@ -58,11 +96,9 @@ $config['collectd_sock'] = null;
* Path to TTF font file to use in error images
* (fallback when file does not exist is GD fixed font)
*/
$config['error_font'] = '/usr/share/fonts/corefonts/arial.ttf';
$config['error_font'] = '/usr/share/fonts/corefonts/arial.ttf';
/*
* Constant defining full path to rrdtool
*/
define('RRDTOOL', $config['rrdtool']);
?>

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>');
<td>'.$device['hardware'].'</td>
</tr>';
}
echo('<tr>
echo '<tr>
<td>Operating System</td>
<td>' . $device['os_text'] . ' ' . $device['version'] . ' ' . $device['features'] . ' </td>
</tr>');
<td>'.$device['os_text'].' '.$device['version'].' '.$device['features'].' </td>
</tr>';
if ($device['serial'])
{
echo('<tr>
if ($device['serial']) {
echo '<tr>
<td>Serial</td>
<td>' . $device['serial']. '</td>
</tr>');
<td>'.$device['serial'].'</td>
</tr>';
}
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>
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>';
}
echo '
<td>'.htmlspecialchars($device['sysContact']).'</td>
</tr>';
}
if ($device['location'])
{
echo('<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>
<td>'.$device['location'].'</td>
</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>');
}
<td>'.$device['real_location'].'</td>
</tr>';
}
}
if ($uptime)
{
echo('<tr>
if ($uptime) {
echo '<tr>
<td>Uptime</td>
<td>' . formatUptime($uptime) . '</td>
</tr>');
<td>'.formatUptime($uptime).'</td>
</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';
}
if ($device['disabled'] == '1')
{
$class = "alert-info";
else {
$class = '';
}
if ($device['ignore'] == '1') {
$class = 'div-ignore-alert';
if ($device['status'] == '1') {
$class = 'alert-warning';
}
}
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 valign=middle style="padding: 0 15px;"><span style="font-size: 20px;">'.generate_device_link($device).'</span>
<br />'.$device['location'].'</td>
<td>';
if (isset($config['os'][$device['os']]['over']))
{
$graphs = $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']))
{
$graphs = $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
{
$graphs = $config['os']['default']['over'];
else {
$graphs = $config['os']['default']['over'];
}
$graph_array = array();
$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['from'] = $config['time']['day'];
$graph_array['legend'] = "no";
$graph_array = array();
$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['from'] = $config['time']['day'];
$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'])
{
$graph_array['type'] = $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'>");
print_graph_popup($graph_array);
echo("<div style='font-weight: bold; font-size: 7pt; margin: -3px;'>".$entry['text']."</div>");
echo("</div>");
}
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>';
}
}
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">
');
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))
{
}
else
{
echo("<div class=box>\n");
include_once($file);
echo("</div>\n");
}
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";
}
}
echo("</div>\n");
?>
echo "</div>\n";

View File

@ -14,9 +14,9 @@
*/
$minutes = 15;
$seconds = $minutes * 60;
$top = $config['front_page_settings']['top']['devices'];
if (is_admin() === TRUE || is_read() === TRUE) {
$seconds = ($minutes * 60);
$top = $config['front_page_settings']['top']['devices'];
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
@ -27,9 +27,10 @@ if (is_admin() === TRUE || is_read() === TRUE) {
GROUP BY d.device_id
ORDER BY total desc
LIMIT $top
";
} else {
$query = "
";
}
else {
$query = "
SELECT *, sum(p.ifInOctets_rate + p.ifOutOctets_rate) as total
FROM ports as p, devices as d, `devices_perms` AS `P`
WHERE `P`.`user_id` = ? AND `P`.`device_id` = `d`.`device_id` AND
@ -40,19 +41,21 @@ if (is_admin() === TRUE || is_read() === TRUE) {
GROUP BY d.device_id
ORDER BY total desc
LIMIT $top
";
";
$param[] = array($_SESSION['user_id']);
}//end if
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("<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("</table>\n");
?>
echo "</table>\n";

View File

@ -14,9 +14,9 @@
*/
$minutes = 15;
$seconds = $minutes * 60;
$top = $config['front_page_settings']['top']['ports'];
if (is_admin() === TRUE || is_read() === TRUE) {
$seconds = ($minutes * 60);
$top = $config['front_page_settings']['top']['ports'];
if (is_admin() === true || is_read() === true) {
$query = "
SELECT *, p.ifInOctets_rate + p.ifOutOctets_rate as total
FROM ports as p, devices as d
@ -26,9 +26,10 @@ if (is_admin() === TRUE || is_read() === TRUE) {
OR p.ifOutOctets_rate > 0 )
ORDER BY total desc
LIMIT $top
";
} else {
$query = "
";
}
else {
$query = "
SELECT *, I.ifInOctets_rate + I.ifOutOctets_rate as total
FROM ports as I, devices as d,
`devices_perms` AS `P`, `ports_perms` AS `PP`
@ -39,19 +40,17 @@ if (is_admin() === TRUE || is_read() === TRUE) {
OR I.ifOutOctets_rate > 0 )
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";
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("<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("</table>\n");
?>
echo "</table>\n";

File diff suppressed because it is too large Load Diff

View File

@ -1,172 +1,170 @@
<?php
$language_data = array (
'LANG_NAME' => 'IOS',
'COMMENT_SINGLE' => array(1 => '!'),
'CASE_KEYWORDS' => GESHI_CAPS_LOWER,
'OOLANG' => false,
'NUMBERS' => GESHI_NUMBER_OCT_PREFIX | GESHI_NUMBER_HEX_PREFIX,
'KEYWORDS' => array(
1 => array(
'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'
# ),
),
'REGEXPS' => array (
1 => array(
GESHI_SEARCH => '(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})',
GESHI_REPLACE => '\\1',
GESHI_BEFORE => '',
),
2 => array(
GESHI_SEARCH => '(255\.\d{1,3}\.\d{1,3}\.\d{1,3})',
GESHI_REPLACE => '\\1',
GESHI_BEFORE => '',
),
3 => array(
GESHI_SEARCH => '(source|interface|update-source|router-id) ([A-Za-z0-9\/\:\-\.]+)',
GESHI_REPLACE => '\\2',
GESHI_BEFORE => '\\1 ',
),
4 => array(
GESHI_SEARCH => '(neighbor) ([\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}]+|[a-zA-Z0-9\-\_]+)',
GESHI_REPLACE => '\\2',
GESHI_BEFORE => '\\1 ',
),
5 => array(
GESHI_SEARCH => '(distribute-map|access-group|policy-map|class-map\ match-any|ip\ access-list\ extended|match\ community|community-list\ standard|community-list\ expanded|ip\ access-list\ standard|router\ bgp|remote-as|key\ chain|service-policy\ input|service-policy\ output|class|login\ authentication|authentication\ key-chain|username|import\ map|export\ map|domain-name|hostname|route-map|access-class|ip\ vrf\ forwarding|ip\ vrf|vtp\ domain|name|pseudowire-class|pw-class|prefix-list|vrf) ([A-Za-z0-9\-\_\.]+)',
GESHI_REPLACE => '\\2',
GESHI_BEFORE => '\\1 ',
),
6 => array(
GESHI_SEARCH => '(password|key-string|key) ([0-9]) (.+)',
GESHI_REPLACE => '\\2 \\3',
GESHI_BEFORE => '\\1 ',
),
7 => array(
GESHI_SEARCH => '(enable) ([a-z]+) ([0-9]) (.+)',
GESHI_REPLACE => '\\3 \\4',
GESHI_BEFORE => '\\1 \\2 ',
),
8 => array(
GESHI_SEARCH => '(description|location|contact|remark) (.+)',
GESHI_REPLACE => '\\2',
GESHI_BEFORE => '\\1 ',
),
9 => array(
GESHI_SEARCH => '([0-9\.\_\*]+\:[0-9\.\_\*]+)',
GESHI_REPLACE => '\\1',
),
10 => array(
GESHI_SEARCH => '(boot) ([a-z]+) (.+)',
GESHI_REPLACE => '\\3',
GESHI_BEFORE => '\\1 \\2 '
),
11 => array(
GESHI_SEARCH => '(net) ([0-9a-z\.]+)',
GESHI_REPLACE => '\\2',
GESHI_BEFORE => '\\1 '
),
12 => array(
GESHI_SEARCH => '(access-list|RO|RW) ([0-9]+)',
GESHI_REPLACE => '\\2',
GESHI_BEFORE => '\\1 '
),
13 => array(
GESHI_SEARCH => '(vlan) ([0-9]+)',
GESHI_REPLACE => '\\2',
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 '
$language_data = array(
'LANG_NAME' => 'IOS',
'COMMENT_SINGLE' => array(1 => '!'),
'CASE_KEYWORDS' => GESHI_CAPS_LOWER,
'OOLANG' => false,
'NUMBERS' => GESHI_NUMBER_OCT_PREFIX | GESHI_NUMBER_HEX_PREFIX,
'KEYWORDS' => array(
1 => array(
'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'
// ),
),
),
'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
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
),
'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;'
),
'SCRIPT' => array(
0 => '',
1 => '',
2 => '',
3 => ''
)
)
'REGEXPS' => array(
1 => array(
GESHI_SEARCH => '(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})',
GESHI_REPLACE => '\\1',
GESHI_BEFORE => '',
),
2 => array(
GESHI_SEARCH => '(255\.\d{1,3}\.\d{1,3}\.\d{1,3})',
GESHI_REPLACE => '\\1',
GESHI_BEFORE => '',
),
3 => array(
GESHI_SEARCH => '(source|interface|update-source|router-id) ([A-Za-z0-9\/\:\-\.]+)',
GESHI_REPLACE => '\\2',
GESHI_BEFORE => '\\1 ',
),
4 => array(
GESHI_SEARCH => '(neighbor) ([\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}]+|[a-zA-Z0-9\-\_]+)',
GESHI_REPLACE => '\\2',
GESHI_BEFORE => '\\1 ',
),
5 => array(
GESHI_SEARCH => '(distribute-map|access-group|policy-map|class-map\ match-any|ip\ access-list\ extended|match\ community|community-list\ standard|community-list\ expanded|ip\ access-list\ standard|router\ bgp|remote-as|key\ chain|service-policy\ input|service-policy\ output|class|login\ authentication|authentication\ key-chain|username|import\ map|export\ map|domain-name|hostname|route-map|access-class|ip\ vrf\ forwarding|ip\ vrf|vtp\ domain|name|pseudowire-class|pw-class|prefix-list|vrf) ([A-Za-z0-9\-\_\.]+)',
GESHI_REPLACE => '\\2',
GESHI_BEFORE => '\\1 ',
),
6 => array(
GESHI_SEARCH => '(password|key-string|key) ([0-9]) (.+)',
GESHI_REPLACE => '\\2 \\3',
GESHI_BEFORE => '\\1 ',
),
7 => array(
GESHI_SEARCH => '(enable) ([a-z]+) ([0-9]) (.+)',
GESHI_REPLACE => '\\3 \\4',
GESHI_BEFORE => '\\1 \\2 ',
),
8 => array(
GESHI_SEARCH => '(description|location|contact|remark) (.+)',
GESHI_REPLACE => '\\2',
GESHI_BEFORE => '\\1 ',
),
9 => array(
GESHI_SEARCH => '([0-9\.\_\*]+\:[0-9\.\_\*]+)',
GESHI_REPLACE => '\\1',
),
10 => array(
GESHI_SEARCH => '(boot) ([a-z]+) (.+)',
GESHI_REPLACE => '\\3',
GESHI_BEFORE => '\\1 \\2 ',
),
11 => array(
GESHI_SEARCH => '(net) ([0-9a-z\.]+)',
GESHI_REPLACE => '\\2',
GESHI_BEFORE => '\\1 ',
),
12 => array(
GESHI_SEARCH => '(access-list|RO|RW) ([0-9]+)',
GESHI_REPLACE => '\\2',
GESHI_BEFORE => '\\1 ',
),
13 => array(
GESHI_SEARCH => '(vlan) ([0-9]+)',
GESHI_REPLACE => '\\2',
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 ',
),
),
'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
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
),
'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;'),
'SCRIPT' => array(
0 => '',
1 => '',
2 => '',
3 => '',
),
),
);
?>

View File

@ -1,12 +1,12 @@
<?php
include("includes/graphs/common.inc.php");
require 'includes/graphs/common.inc.php';
$device = device_by_id_cache($id);
$rrd_filename = $config['rrd_dir'] . "/" . $device['hostname'] . "/mem.rrd";
$rrd_filename = $config['rrd_dir'].'/'.$device['hostname'].'/mem.rrd';
$rrd_options .= " -b 1024";
$rrd_options .= ' -b 1024';
$rrd_options .= " DEF:atotalswap=$rrd_filename:totalswap:AVERAGE";
$rrd_options .= " DEF:aavailswap=$rrd_filename:availswap:AVERAGE";
@ -16,51 +16,49 @@ $rrd_options .= " DEF:atotalfree=$rrd_filename:totalfree:AVERAGE";
$rrd_options .= " DEF:ashared=$rrd_filename:shared:AVERAGE";
$rrd_options .= " DEF:abuffered=$rrd_filename:buffered:AVERAGE";
$rrd_options .= " DEF:acached=$rrd_filename:cached:AVERAGE";
$rrd_options .= " CDEF:totalswap=atotalswap,1024,*";
$rrd_options .= " CDEF:availswap=aavailswap,1024,*";
$rrd_options .= " CDEF:totalreal=atotalreal,1024,*";
$rrd_options .= " CDEF:availreal=aavailreal,1024,*";
$rrd_options .= " CDEF:totalfree=atotalfree,1024,*";
$rrd_options .= " CDEF:shared=ashared,1024,*";
$rrd_options .= " CDEF:buffered=abuffered,1024,*";
$rrd_options .= " CDEF:cached=acached,1024,*";
$rrd_options .= " CDEF:usedreal=totalreal,availreal,-";
$rrd_options .= " CDEF:usedswap=totalswap,availswap,-";
$rrd_options .= " CDEF:cusedswap=usedswap,-1,*";
$rrd_options .= " CDEF:cdeftot=availreal,shared,buffered,usedreal,cached,usedswap,+,+,+,+,+";
$rrd_options .= ' CDEF:totalswap=atotalswap,1024,*';
$rrd_options .= ' CDEF:availswap=aavailswap,1024,*';
$rrd_options .= ' CDEF:totalreal=atotalreal,1024,*';
$rrd_options .= ' CDEF:availreal=aavailreal,1024,*';
$rrd_options .= ' CDEF:totalfree=atotalfree,1024,*';
$rrd_options .= ' CDEF:shared=ashared,1024,*';
$rrd_options .= ' CDEF:buffered=abuffered,1024,*';
$rrd_options .= ' CDEF:cached=acached,1024,*';
$rrd_options .= ' CDEF:usedreal=totalreal,availreal,-';
$rrd_options .= ' CDEF:usedswap=totalswap,availswap,-';
$rrd_options .= ' CDEF:cusedswap=usedswap,-1,*';
$rrd_options .= ' CDEF:cdeftot=availreal,shared,buffered,usedreal,cached,usedswap,+,+,+,+,+';
$rrd_options .= " COMMENT:'Bytes Current Average Maximum\\n'";
$rrd_options .= " LINE1:usedreal#d0b080:";
$rrd_options .= " AREA:usedreal#f0e0a0:used";
$rrd_options .= " GPRINT:usedreal:LAST:\ \ \ %7.2lf%sB";
$rrd_options .= " GPRINT:usedreal:AVERAGE:%7.2lf%sB";
$rrd_options .= ' LINE1:usedreal#d0b080:';
$rrd_options .= ' AREA:usedreal#f0e0a0:used';
$rrd_options .= ' GPRINT:usedreal:LAST:\ \ \ %7.2lf%sB';
$rrd_options .= ' GPRINT:usedreal:AVERAGE:%7.2lf%sB';
$rrd_options .= " GPRINT:usedreal:MAX:%7.2lf%sB\\\\n";
$rrd_options .= " STACK:availreal#e5e5e5:free";
$rrd_options .= " GPRINT:availreal:LAST:\ \ \ %7.2lf%sB";
$rrd_options .= " GPRINT:availreal:AVERAGE:%7.2lf%sB";
$rrd_options .= ' STACK:availreal#e5e5e5:free';
$rrd_options .= ' GPRINT:availreal:LAST:\ \ \ %7.2lf%sB';
$rrd_options .= ' GPRINT:availreal:AVERAGE:%7.2lf%sB';
$rrd_options .= " GPRINT:availreal:MAX:%7.2lf%sB\\\\n";
$rrd_options .= " LINE1:usedreal#d0b080:";
$rrd_options .= " AREA:shared#afeced::";
$rrd_options .= " AREA:buffered#cc0000::STACK";
$rrd_options .= " AREA:cached#ffaa66::STACK";
$rrd_options .= " LINE1.25:shared#008fea:shared";
$rrd_options .= " GPRINT:shared:LAST:\ %7.2lf%sB";
$rrd_options .= " GPRINT:shared:AVERAGE:%7.2lf%sB";
$rrd_options .= ' LINE1:usedreal#d0b080:';
$rrd_options .= ' AREA:shared#afeced::';
$rrd_options .= ' AREA:buffered#cc0000::STACK';
$rrd_options .= ' AREA:cached#ffaa66::STACK';
$rrd_options .= ' LINE1.25:shared#008fea:shared';
$rrd_options .= ' GPRINT:shared:LAST:\ %7.2lf%sB';
$rrd_options .= ' GPRINT:shared:AVERAGE:%7.2lf%sB';
$rrd_options .= " GPRINT:shared:MAX:%7.2lf%sB\\\\n";
$rrd_options .= " LINE1.25:buffered#ff1a00:buffers:STACK";
$rrd_options .= " GPRINT:buffered:LAST:%7.2lf%sB";
$rrd_options .= " GPRINT:buffered:AVERAGE:%7.2lf%sB";
$rrd_options .= ' LINE1.25:buffered#ff1a00:buffers:STACK';
$rrd_options .= ' GPRINT:buffered:LAST:%7.2lf%sB';
$rrd_options .= ' GPRINT:buffered:AVERAGE:%7.2lf%sB';
$rrd_options .= " GPRINT:buffered:MAX:%7.2lf%sB\\\\n";
$rrd_options .= " LINE1.25:cached#ea8f00:cached:STACK";
$rrd_options .= " GPRINT:cached:LAST:\ %7.2lf%sB";
$rrd_options .= " GPRINT:cached:AVERAGE:%7.2lf%sB";
$rrd_options .= ' LINE1.25:cached#ea8f00:cached:STACK';
$rrd_options .= ' GPRINT:cached:LAST:\ %7.2lf%sB';
$rrd_options .= ' GPRINT:cached:AVERAGE:%7.2lf%sB';
$rrd_options .= " GPRINT:cached:MAX:%7.2lf%sB\\\\n";
$rrd_options .= " LINE1:totalreal#050505:";
$rrd_options .= " AREA:cusedswap#C3D9FF:swap";
$rrd_options .= " LINE1.25:cusedswap#356AA0:";
$rrd_options .= " GPRINT:usedswap:LAST:\ \ \ %7.2lf%sB";
$rrd_options .= " GPRINT:usedswap:AVERAGE:%7.2lf%sB";
$rrd_options .= ' LINE1:totalreal#050505:';
$rrd_options .= ' AREA:cusedswap#C3D9FF:swap';
$rrd_options .= ' LINE1.25:cusedswap#356AA0:';
$rrd_options .= ' GPRINT:usedswap:LAST:\ \ \ %7.2lf%sB';
$rrd_options .= ' GPRINT:usedswap:AVERAGE:%7.2lf%sB';
$rrd_options .= " GPRINT:usedswap:MAX:%7.2lf%sB\\\\n";
$rrd_options .= " LINE1:totalreal#050505:total";
$rrd_options .= " GPRINT:totalreal:AVERAGE:\ \ %7.2lf%sB";
?>
$rrd_options .= ' LINE1:totalreal#050505:total';
$rrd_options .= ' GPRINT:totalreal:AVERAGE:\ \ %7.2lf%sB';

View File

@ -1,17 +1,13 @@
<?php
if (is_numeric($vars['id']))
{
$ap = accesspoint_by_id($vars['id']);
if (is_numeric($vars['id'])) {
$ap = accesspoint_by_id($vars['id']);
if (is_numeric($ap['device_id']) && ($auth || device_permitted($ap['device_id'])))
{
$device = device_by_id_cache($ap['device_id']);
if (is_numeric($ap['device_id']) && ($auth || device_permitted($ap['device_id']))) {
$device = device_by_id_cache($ap['device_id']);
$title = generate_device_link($device);
$title .= " :: AP :: " . htmlentities($ap['name']);
$auth = TRUE;
}
$title = generate_device_link($device);
$title .= ' :: AP :: '.htmlentities($ap['name']);
$auth = true;
}
}
?>

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';
$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

@ -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'] = "Interference";
$rrd_list[0]['ds'] = "interference";
$rrd_list[0]['descr'] = 'Interference';
$rrd_list[0]['ds'] = 'interference';
$unit_text = "Int";
$unit_text = 'Int';
$units='';
$total_units='';
$colours='mixed';
$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

@ -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'] = "Num Clients";
$rrd_list[0]['ds'] = "numasoclients";
$rrd_list[0]['descr'] = 'Num Clients';
$rrd_list[0]['ds'] = 'numasoclients';
$unit_text = "Clients";
$unit_text = 'Clients';
$units='';
$total_units='';
$colours='mixed';
$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

@ -1,26 +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'] = "MonBSSIDs";
$rrd_list[0]['ds'] = "nummonbssid";
$rrd_list[0]['descr'] = 'MonBSSIDs';
$rrd_list[0]['ds'] = 'nummonbssid';
$unit_text = "BSSIDs";
$unit_text = 'BSSIDs';
$units='';
$total_units='';
$colours='mixed';
$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

@ -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'] = "Mon Clients";
$rrd_list[0]['ds'] = "nummonclients";
$rrd_list[0]['descr'] = 'Mon Clients';
$rrd_list[0]['ds'] = 'nummonclients';
$unit_text = "Clients";
$unit_text = 'Clients';
$units='';
$total_units='';
$colours='mixed';
$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

@ -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'] = "radioutil";
$rrd_list[0]['ds'] = "radioutil";
$rrd_list[0]['descr'] = 'radioutil';
$rrd_list[0]['ds'] = 'radioutil';
$unit_text = "Percent";
$unit_text = 'Percent';
$units='';
$total_units='';
$colours='mixed';
$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

@ -1,26 +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'] = "txpow";
$rrd_list[0]['ds'] = "txpow";
$rrd_list[0]['descr'] = 'txpow';
$rrd_list[0]['ds'] = 'txpow';
$unit_text = "dBm";
$unit_text = 'dBm';
$units='';
$total_units='';
$colours='mixed';
$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

@ -1,33 +1,31 @@
<?php
$scale_min = "0";
$scale_min = '0';
include("includes/graphs/common.inc.php");
require 'includes/graphs/common.inc.php';
$device = device_by_id_cache($id);
$rrd_filename = $config['rrd_dir'] . "/" . $device['hostname'] . "/altiga-ssl.rrd.rrd";
$rrd_filename = $config['rrd_dir'].'/'.$device['hostname'].'/altiga-ssl.rrd.rrd';
$rrd_options .= " DEF:TotalSessions=$rrd_filename:TotalSessions:AVERAGE";
$rrd_options .= " DEF:ActiveSessions=$rrd_filename:ActiveSessions:AVERAGE";
$rrd_options .= " DEF:MaxSessions=$rrd_filename:MaxSessions:AVERAGE";
$rrd_options .= " CDEF:a=1min,100,/";
$rrd_options .= " CDEF:b=5min,100,/";
$rrd_options .= " CDEF:c=15min,100,/";
$rrd_options .= " CDEF:cdefd=a,b,c,+,+";
$rrd_options .= ' CDEF:a=1min,100,/';
$rrd_options .= ' CDEF:b=5min,100,/';
$rrd_options .= ' CDEF:c=15min,100,/';
$rrd_options .= ' CDEF:cdefd=a,b,c,+,+';
$rrd_options .= " COMMENT:Load\ Average\ \ Current\ \ \ \ Average\ \ \ \ Maximum\\\\n";
$rrd_options .= " AREA:a#ffeeaa:1\ Min:";
$rrd_options .= " LINE1:a#c5aa00:";
$rrd_options .= " GPRINT:a:LAST:\ \ \ \ %7.2lf";
$rrd_options .= " GPRINT:a:AVERAGE:\ \ %7.2lf";
$rrd_options .= ' AREA:a#ffeeaa:1\ Min:';
$rrd_options .= ' LINE1:a#c5aa00:';
$rrd_options .= ' GPRINT:a:LAST:\ \ \ \ %7.2lf';
$rrd_options .= ' GPRINT:a:AVERAGE:\ \ %7.2lf';
$rrd_options .= " GPRINT:a:MAX:\ \ %7.2lf\\\\n";
$rrd_options .= " LINE1.25:b#ea8f00:5\ Min:";
$rrd_options .= " GPRINT:b:LAST:\ \ \ \ %7.2lf";
$rrd_options .= " GPRINT:b:AVERAGE:\ \ %7.2lf";
$rrd_options .= ' LINE1.25:b#ea8f00:5\ Min:';
$rrd_options .= ' GPRINT:b:LAST:\ \ \ \ %7.2lf';
$rrd_options .= ' GPRINT:b:AVERAGE:\ \ %7.2lf';
$rrd_options .= " GPRINT:b:MAX:\ \ %7.2lf\\\\n";
$rrd_options .= " LINE1.25:c#cc0000:15\ Min";
$rrd_options .= " GPRINT:c:LAST:\ \ \ %7.2lf";
$rrd_options .= " GPRINT:c:AVERAGE:\ \ %7.2lf";
$rrd_options .= ' LINE1.25:c#cc0000:15\ Min';
$rrd_options .= ' GPRINT:c:LAST:\ \ \ %7.2lf';
$rrd_options .= ' GPRINT:c:AVERAGE:\ \ %7.2lf';
$rrd_options .= " GPRINT:c:MAX:\ \ %7.2lf\\\\n";
?>

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))
{
$rrd_filename = $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;
$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))
{
$rrd_filename = $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))
{
$rrd_filename = $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';

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