diff --git a/doc/IRC-Bot-Extensions.md b/doc/IRC-Bot-Extensions.md
new file mode 100644
index 0000000000..0debac3807
--- /dev/null
+++ b/doc/IRC-Bot-Extensions.md
@@ -0,0 +1,80 @@
+# Quick Guide
+
+Okay this is a very quick walk-through in writing own `commands` for the IRC-Bot.
+
+First of all, create a file in `includes/ircbot`, the file-name should be in this format: `command.inc.php`.
+
+When editing the file, do not open nor close PHP-tags.
+Any variable you assign will be discarded as soon as your command returns.
+Some variables, specially all listed under `$this->`, have special meanings or effects.
+Before a command is executed, the IRC-Bot ensures that the MySQL-Socket is working, that `$this->user` points to the right user and that the user is authenticated.
+Below you will find a table with related functions and attributes.
+You can chain-load any built-in command by calling `$this->_command("My Parameters")`.
+You cannot chain-load external commands.
+
+To enable your command, edit your `config.php` and add something like this:
+```php
+ ...
+ $config['irc_external'][] = "mycommand";
+ ...
+```
+
+See: [Example](#example)
+
+# Functions and Attributes
+... that are accessible from within an extension
+
+### Functions
+
+Function( (Type) $Variable [= Default] [,...] ) | Returns | Description
+--- | --- | ---
+`$this->getChan( )` | `String` | Returns `channel` of current event.
+`$this->getData( (boolean) $Block = false )` | `String/Boolean` | Returns a `line` from the IRC-Buffer if it's not matched against any other `command`. If `$Block` is `true`, wait until a suitable line is returned.
+`$this->getUser( )` | `String` | Returns `nick` of current user. Not to confuse with `$this->user`!
+`$this->get_user( )` | `Array` | See `$this->user` in Attributes.
+`$this->irc_raw( (string) $Protocol )` | `Boolean` | Sends raw IRC-Protocol.
+`$this->isAuthd( )` | `Boolean` | `true` if the user is authenticated.
+`$this->joinChan( (string) $Channel )` | `Boolean` | Joins given `$Channel`.
+`$this->log( (string) $Message )` | `Boolean` | Logs given `$Message` into `STDOUT`.
+`$this->read( (string) $Buffer )` | `String/Boolean` | Returns a `line` from given `$Buffer` or `false` if there's nothing suitable inside the Buffer. Please use `$this->getData()` for handler-safe data retrieval.
+`$this->respond( (string) $Message )` | `Boolean` | Responds to the `request` auto-detecting channel or private message.
+
+### Attributes
+Attribute | Type | Description
+--- | --- | ---
+`$params` | `String` | Contains all arguments that are passed to the `.command`.
+`$this->chan` | `Array` | Channels that are configured.
+`$this->commands` | `Array` | Contains accessible `commands`.
+`$this->config` | `Array` | Contains `$config` from `config.php`.
+`$this->data` | `String` | Contains raw IRC-Protocol.
+`$this->debug` | `Boolean` | Debug-Flag.
+`$this->external` | `Array` | Contains loaded extra `commands`.
+`$this->nick` | `String` | Bot's `nick` on the IRC.
+`$this->pass` | `String` | IRC-Server's passphrase.
+`$this->port` | `Int` | IRC-Sever's port-number.
+`$this->server` | `String` | IRC-Server's hostname.
+`$this->ssl` | `Boolean` | SSL-Flag.
+`$this->tick` | `Int` | Interval to check buffers in microseconds.
+`$this->user` | `Array` | Array containing details about the `user` that sent the `request`.
+
+# Example!
+
+`includes/ircbot/join-ng.inc.php`
+```php
+ if( $this->user['level'] != 10 ) {
+ return $this->respond("Sorry only admins can make me join.");
+ }
+ if( $this->getChan() == "#noc") {
+ $this->respond("Joining $params");
+ $this->joinChan($params);
+ } else {
+ $this->respond("Sorry, only people from #noc can make join.");
+ }
+```
+
+`config.php`
+```php
+ ...
+ $config['irc_external'][] = "join-ng";
+ ...
+```
\ No newline at end of file
diff --git a/doc/IRC-Bot.md b/doc/IRC-Bot.md
new file mode 100644
index 0000000000..2352ae0af6
--- /dev/null
+++ b/doc/IRC-Bot.md
@@ -0,0 +1,130 @@
+Table of Content:
+- [About](#about)
+ - [Configuration](#config)
+ - [Commands](#commands)
+- [Examples](#examples)
+- [Extensions](#extensions)
+
+
+# About
+
+LibreNMS has an easy to use IRC-Interface for basic tasks like viewing last log-entry, current device/port status and such.
+
+By default the IRC-Bot will not start when executed and will return an error until at least `$config['irc_host']` and `$config['irc_port']` has been specified inside `config.php`.
+
+If no channel has been specified with `$config['irc_chan']`, `##librenms` will be used.
+The default Nick for the bot is `LibreNMS`.
+
+The Bot will reply the same way it's being called. If you send it the commands via Query, it will respond in the Query. If you send the commands via a Channel, then it will respond in the Channel.
+
+### Configuration & Defaults
+
+Option | Default-Value | Notes
+--- | --- | ---
+`$config['irc_alert']` | `false` | Optional; Enables Alerting-Socket. `EXPERIMENTAL`
+`$config['irc_authtime']` | `3` | Optional; Defines how long in Hours an auth-session is valid.
+`$config['irc_chan']` | `##librenms` | Optional; Multiple channels can be defined as Array or delimited with `,`
+`$config['irc_debug']` | `false` | Optional; Enables debug output (Wall of text)
+`$config['irc_external']` | | Optional; Array or `,` delimited string with commands to include from `includes/ircbot/*.inc.php`
+`$config['irc_host']` | | Required; Domain or IP to connect. If it's an IPv6 Address, embed it in `[]`. (Example: `[::1]`)
+`$config['irc_maxretry]` | `5` | Optional; How many connection attempts should be made before giving up
+`$config['irc_nick']` | `LibreNMS` | Optional;
+`$config['irc_pass']` | | Optional; This sends the IRC-PASS Sequence to IRC-Servers that require Password on Connect
+`$config['irc_port]` | `6667` | Required; To enable SSL append a `+` before the Port. (Example: `+6697`)
+
+### IRC-Commands
+
+Command | Description
+--- | ---
+`.auth ` | If ``: Request an Auth-Token. If ``: Authenticate session.
+`.device ` | Prints basic information about given `hostname`.
+`.down` | List hostnames that are down, if any.
+`.help` | List available commands.
+`.join ` | Joins `` if user has admin-level.
+`.listdevices` | Lists the hostnames of all known devices.
+`.log []` | Prints `N` lines or last line of the eventlog.
+`.port ` | Prints Port-related informations from `ifname` on given `hostname`.
+`.quit` | Disconnect from IRC and exit.
+`.reload` | Reload configuration.
+`.status ` | Prints status informations for given `type`. Type can be `devices`, `services`, `ports`. Shorthands are: `dev`,`srv`,`prt`
+`.version` | Prints `$this->config['project_name_version']`.
+
+( __/!\__ All commands are case-_insensitive_ but their arguments are case-_sensitive_)
+
+# Examples
+
+### Server examples:
+
+Unencrypted Connection to `irc.freenode.org`:
+
+```php
+ ...
+ $config['irc_host'] = "irc.freenode.org";
+ $config['irc_port'] = 6667;
+ ...
+```
+
+SSL-Encrypted Connection to `irc.freenode.org`:
+
+```php
+ ...
+ $config['irc_host'] = "irc.freenode.org";
+ $config['irc_port'] = "+6697";
+ ...
+```
+
+SSL-Encrypted Connection to `irc.localdomain` with Server-Password and odd port:
+
+```php
+ ...
+ $config['irc_host'] = "irc.localdomain";
+ $config['irc_port'] = "+12345";
+ $config['irc_pass'] = "Super Secret Passphrase123";
+ ...
+```
+
+### Channel notations:
+
+Channels can be defined using Array-Notation like:
+```php
+ ...
+ $config['irc_chan'][] = "#librenms";
+ $config['irc_chan'][] = "#otherchan";
+ $config['irc_chan'][] = "#noc";
+ ...
+```
+Or using a single string using `,` as delimiter between various channels:
+```php
+ ...
+ $config['irc_chan'] = "#librenms,#otherchan,#noc";
+ ...
+```
+
+# Extensions?!
+
+The bot is coded in a unified way.
+This makes writing extensions by far less painfull.
+Simply add your `command` to the `$config['irc_external']` directive and create a file called `includes/ircbot/command.inc.php` containing your code.
+The string behind the call of `.command` is passed as `$params`.
+The user who requested something is accessable via `$this->user`.
+Send your reply/ies via `$this->respond($string)`.
+
+A more detailed documentation of the functions and variables available for extensions can be found at [IRC-Bot Extensions](IRC-Bot-Extensions);
+
+Confused? Here an Echo-Example:
+
+File: config.php
+```php
+ ...
+ $config['irc_external'][] = "echo";
+ ...
+```
+File: includes/ircbot/echo.inc.php
+```php
+ //Prefix everything with `You said: '...'` and return what was sent.
+ if( $this->user['name'] != "root" ) {
+ return $this->respond("You said: '".$params."'");
+ } else {
+ return $this->respond("root shouldn't be online so late!");
+ }
+```
\ No newline at end of file
diff --git a/includes/defaults.inc.php b/includes/defaults.inc.php
index 1f095dd100..167ea17bc3 100644
--- a/includes/defaults.inc.php
+++ b/includes/defaults.inc.php
@@ -378,10 +378,16 @@ $config['device_traffic_descr'][] = '/dummy/';
// IRC Bot configuration
-$config['irc_host'] = "irc.freenode.net";
-$config['irc_port'] = 6667;
-$config['irc_nick'] = $config['project_id'];
-$config['irc_chan'][] = "##" . $config['project_id'];
+$config['irc_host'] = "";
+$config['irc_port'] = "";
+$config['irc_maxretry'] = 3;
+$config['irc_nick'] = "LibreNMS";
+$config['irc_chan'][] = "##librenms";
+$config['irc_pass'] = "";
+$config['irc_external'] = "";
+$config['irc_authtime'] = 3;
+$config['irc_debug'] = false;
+$config['irc_alert'] = false;
// Authentication
diff --git a/irc.php b/irc.php
index 09a9a3ed92..dcd715428f 100755
--- a/irc.php
+++ b/irc.php
@@ -1,265 +1,519 @@
#!/usr/bin/env php
- * @copyright (C) 2006 - 2012 Adam Armstrong
- *
- */
+/* Copyright (C) 2014
+ * Modified and Relicensed by under the expressed
+ * permission by the Copyright-Holder .
+ *
+ * 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 . */
chdir(dirname($argv[0]));
+require_once("includes/defaults.inc.php");
+require_once("config.php");
+require_once("includes/definitions.inc.php");
+require_once("includes/functions.php");
+require_once("includes/discovery/functions.inc.php");
+error_reporting(E_ERROR);
-# Disable annoying messages... well... all messages actually :)
-error_reporting(0);
-
-include_once("includes/defaults.inc.php");
-include_once("config.php");
-include("includes/definitions.inc.php");
-include_once("includes/functions.php");
-include_once("includes/discovery/functions.inc.php");
-include_once('Net/SmartIRC.php');
-
-mysql_close();
-
-# Redirect to /dev/null or logfile if you aren't using screen to keep tabs
-echo $config['project_name'] . "IRC bot starting ...\n";
-echo "\n";
-echo "Timestamp Command\n";
-echo "----------------- ------- \n";
-
-class ircbot
-{
-
-///
-# HELP Function
-///
- function help_info(&$irc, &$data)
- {
- global $config;
-
- $irc->message(SMARTIRC_TYPE_CHANNEL, $data->channel, "Commands: .help, .log, .status, .version, .down, .port, .device, .listdevices");
-
- echo date("m-d-y H:i:s ");
- echo "HELP\n";
-
- mysql_close();
- }
-
-///
-# VERSION Function
-///
- function version_info(&$irc, &$data)
- {
- global $config;
-
- $irc->message(SMARTIRC_TYPE_CHANNEL, $data->channel, $config['project_name_version']);
-
- echo date("m-d-y H:i:s ");
- echo "VERSION\t\t". $config['version'] . "\n";
-
- mysql_close();
- }
-
-///
-# LOG Function
-///
- function log_info(&$irc, &$data)
- {
- global $config;
-
- mysql_connect($config['db_host'],$config['db_user'],$config['db_pass']);
- mysql_select_db($config['db_name']);
-
- $device = dbFetchRow("SELECT `event_id`,`host`,`datetime`,`message`,`type` FROM `eventlog` ORDER BY `event_id` DESC LIMIT 1");
- $host = $device['host'];
- $hostid = dbFetchRow("SELECT `hostname` FROM `devices` WHERE `device_id` = $host");
-
- $irc->message(SMARTIRC_TYPE_CHANNEL, $data->channel, $device['event_id'] ." ". $hostid['hostname'] ." ". $device['datetime'] ." ". $device['message'] ." ". $device['type']);
-
- echo date("m-d-y H:i:s ");
- echo "LOG\n";
-
- mysql_close();
- }
-
-///
-# DOWN Function
-///
- function down_info(&$irc, &$data)
- {
- global $config;
-
- mysql_connect($config['db_host'],$config['db_user'],$config['db_pass']);
- mysql_select_db($config['db_name']);
-
- foreach (dbFetchRows("SELECT * FROM `devices` where status=0") as $device)
- {
- $message .= $sep . $device['hostname'];
- $sep = ", ";
- }
- $irc->message(SMARTIRC_TYPE_CHANNEL, $data->channel, $message);
-
- mysql_close();
-
- echo date("m-d-y H:i:s ");
- echo "DOWN\n";
- }
-
-///
-# DEVICE Function
-///
- function device_info(&$irc, &$data)
- {
- global $config;
-
- $hostname = $data->messageex[1];
-
- mysql_connect($config['db_host'],$config['db_user'],$config['db_pass']);
- mysql_select_db($config['db_name']);
-
- $device = dbFetchRow("SELECT * FROM `devices` WHERE `hostname` = ?",array($hostname));
-
- mysql_close();
-
-if (!$device) {
- $irc->message(SMARTIRC_TYPE_CHANNEL, $data->channel, "Error: Bad or Missing hostname, use .listdevices to show all devices."); } else {
-
- if ($device['status'] == 1) { $status = "Up " . formatUptime($device['uptime'] . " "); } else { $status = "Down "; }
- if ($device['ignore']) { $status = "*Ignored*"; }
- if ($device['disabled']) { $status = "*Disabled*"; }
-
- $irc->message(SMARTIRC_TYPE_CHANNEL, $data->channel, $device['os'] . " " . $device['version'] . " " .
- $device['features'] . " " . $status);
-
- echo date("m-d-y H:i:s ");
- echo "DEVICE\t\t". $device['hostname']."\n";
- }
+class ircbot {
+ private $debug = false;
+ private $server = "";
+ private $port = "";
+ private $ssl = false;
+ private $pass = "";
+ private $nick = "LibreNMS";
+ private $chan = array();
+ private $commands = array("auth", "quit", "listdevices", "device", "port", "down", "version", "status", "log", "help", "reload", "join");
+ private $external = array();
+ private $tick = 62500;
+
+ public function __construct() {
+ global $config;
+ $this->log("Setting up IRC-Bot..");
+ $this->j = 2;
+ $this->config = $config;
+ $this->debug = $this->config['irc_debug'];
+ $this->config['irc_authtime'] = $this->config['irc_authtime'] ? $this->config['irc_authtime'] : 3;
+ $this->max_retry = $this->config['irc_maxretry'];
+ $this->server = $this->config['irc_host'];
+ if($this->config['irc_port'][0] == "+") {
+ $this->ssl = true;
+ $this->port = substr($this->config['irc_port'], 1);
+ } else {
+ $this->port = $this->config['irc_port'];
+ }
+ if($this->config['irc_nick']) {
+ $this->nick = $this->config['irc_nick'];
+ }
+ if($this->config['irc_chan']) {
+ if(is_array($this->config['irc_chan'])) {
+ $this->chan = $this->config['irc_chan'];
+ } elseif(strstr($this->config['irc_chan'],",")) {
+ $this->chan = explode(",",$this->config['irc_chan']);
+ } else {
+ $this->chan = array($this->config['irc_chan']);
+ }
+ }
+ if($this->config['irc_pass']) {
+ $this->pass = $this->config['irc_pass'];
+ }
+ $this->load_external();
+ $this->log("Starting IRC-Bot..");
+ $this->init();
+ }
+
+ private function load_external() {
+ if(!$this->config['irc_external']) {
+ return true;
+ }
+ $this->log("Caching external commands...");
+ if(!is_array($this->config['irc_external'])) {
+ $this->config['irc_external'] = explode(",",$this->config['irc_external']);
+ }
+ foreach( $this->config['irc_external'] as $ext ) {
+ if( ($this->external[$ext] = file_get_contents("includes/ircbot/".$ext.".inc.php")) == "" ) {
+ unset($this->external[$ext]);
+ }
+ }
+ return $this->log("Cached ".sizeof($this->external)." commands.");
+ }
+
+ private function init() {
+ if($this->config['irc_alert']) {
+ $this->connect_alert();
+ }
+ $this->connect();
+ $this->log("Connected");
+ if($this->pass) {
+ fwrite($this->socket['irc'], "PASS ".$this->pass."\n\r");
+ }
+ $this->doAuth();
+ while( true ) {
+ foreach($this->socket as $n=>$socket) {
+ if(!is_resource($socket)) {
+ $this->log("Socket '$n' closed. Restarting.");
+ break 2;
+ }
+ }
+ $this->getData();
+ if($this->config['irc_alert']) {
+ $this->alertData();
+ }
+ usleep($this->tick);
+ }
+ return $this->init();
+ }
+
+ private function connect_alert() {
+ $f = $this->config['install_dir']."/.ircbot.alert";
+ if( (file_exists($f) || !touch($f)) && (!unlink($f) || !touch($f)) ) {
+ $this->log("Error - Cannot create Alert-File");
+ return false;
+ }
+ if( ($this->socket['alert'] = fopen($f,'r')) ) {
+ $this->log("Opened Alert-File");
+ stream_set_blocking($this->socket['alert'], false);
+ return true;
+ }
+ $this->log("Error - Cannot open Alert-File");
+ return false;
+ }
+
+ private function read($buff) {
+ $r = fread($this->socket[$buff],64);
+ $this->buff[$buff] .= $r;
+ $r = strlen($r);
+ if(strstr($this->buff[$buff],"\n")) {
+ $tmp = explode("\n",$this->buff[$buff],2);
+ $this->buff[$buff] = substr($this->buff[$buff], strlen($tmp[0])+2);
+ if( $this->debug ) {
+ $this->log("Returning buffer '$buff': '".trim($tmp[0])."'");
+ }
+ return $tmp[0];
+ }
+ if( $this->debug && $r > 0 ) {
+ $this->log("Expanding buffer '$buff' = '".trim($this->buff[$buff])."'");
+ }
+ return false;
+ }
+
+ private function alertData() {
+ if( ($tmp = $this->read("alert")) !== false ) {
+ foreach( $tmp as $data ) {
+ $this->data = $data;
+ echo $this->data;
+ //dostuff
+ }
+ }
+ }
+
+ private function getData() {
+ if( ($data = $this->read("irc")) !== false ) {
+ $this->data = $data;
+ $ex = explode(' ', $this->data);
+ if($ex[0] == "PING") {
+ return $this->irc_raw("PONG ".$ex[1]);
+ }
+ if( $ex[1] == 376 || ($ex[1] == "MODE" && $ex[2] == $this->nick) ) {
+ if($this->j == 2) {
+ $this->joinChan();
+ $this->j=0;
+ }
+ }
+ $this->command = str_replace(array(chr(10), chr(13)), '', $ex[3]);
+ if(strstr($this->command,":.")) {
+ $this->handleCommand();
+ }
+ }
+ }
+
+ private function joinChan($chan=false) {
+ if( $chan ) {
+ $this->chan[] = $chan;
+ }
+ foreach($this->chan as $chan) {
+ $this->irc_raw("JOIN ".$chan);
+ }
+ return true;
+ }
+
+ private function handleCommand() {
+ $this->command = str_replace(":.","",$this->command);
+ $tmp=explode(":.".$this->command." ",$this->data);
+ $this->user = $this->get_user();
+ if( $this->isAuthd() || trim($this->command) == "auth" ) {
+ $this->proceedCommand(str_replace("\n","",trim($this->command)),trim($tmp[1]));
+ }
+ $this->authd[$this->getUser($this->data)] = $this->user;
+ return false;
+ }
+
+ private function proceedCommand($command,$params) {
+ $command = strtolower($command);
+ if(in_array($command,$this->commands)) {
+ $this->chkdb();
+ $this->log($command." ( '".$params."' )");
+ return $this->{"_".$command}($params);
+ } elseif($this->external[$command]) {
+ $this->chkdb();
+ $this->log($command." ( '".$params."' ) [Ext]");
+ return eval($this->external[$command]);
+ }
+ return false;
+ }
+
+ private function respond($msg) {
+ $chan = $this->getChan($this->data);
+ return $this->sendMessage($msg,strstr($chan,"#") ? $chan : $this->getUser($this->data));
+ }
+
+ private function getChan($param){
+ $data = explode("PRIVMSG ",$this->data,3);
+ $data = explode(" ",$data[1],2);
+ return $data[0];
+ }
+
+ private function getUser($param) {
+ $arrData = explode("!",$param,2);
+ return str_replace(":","",$arrData[0]);
+ }
+
+ private function connect($try) {
+ if($try > $this->max_retry){
+ $this->log("Failed too many connection attempts, aborting");
+ return die();
+ }
+ $this->log("Trying to connect to ".$this->server.":".$this->port.($this->ssl?" (SSL)":""));
+ if($this->socket['irc']) {
+ fclose($this->socket['irc']);
+ }
+ if($this->ssl) {
+ $server = 'ssl://'.$this->server;
+ } else {
+ $server = $this->server;
+ }
+ $this->socket['irc'] = fsockopen($server, $this->port);
+ if(!is_resource($this->socket['irc'])) {
+ return $this->connect($try+1);
+ } else {
+ stream_set_blocking($this->socket['irc'], false);
+ return true;
+ }
+ }
+
+ private function doAuth() {
+ if( $this->irc_raw("USER ".$this->nick." 0 ".$this->nick." :".$this->nick) && $this->irc_raw("NICK ".$this->nick) ) {
+ return true;
+ }
+ return false;
+ }
+
+ private function sendMessage($message,$chan) {
+ if( $this->debug ) {
+ $this->log("Sending 'PRIVMSG ".trim($chan)." :".trim($message)."'");
+ }
+ return $this->irc_raw("PRIVMSG ".trim($chan)." :".trim($message));
+ }
+
+ private function log($msg) {
+ echo "[".date("r")."] ".trim($msg)."\n";
+ return true;
+ }
+
+ private function chkdb() {
+ if( !is_resource($this->sql) ) {
+ if( ($this->sql = mysql_connect($this->config['db_host'],$this->config['db_user'],$this->config['db_pass'])) != false && mysql_select_db($this->config['db_name'])) {
+ return true;
+ } else {
+ $this->log("Cannot connect to MySQL");
+ return die();
+ }
+ } else {
+ return true;
+ }
+ }
+
+ private function isAuthd() {
+ if( $this->user['expire'] >= time() ) {
+ $this->user['expire'] = time()+($this->config['irc_authtime']*3600);
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ private function get_user() {
+ return $this->authd[$this->getUser($this->data)];
+ }
+
+ private function irc_raw($params) {
+ return fputs($this->socket['irc'],$params."\r\n");
+ }
+
+ private function _auth($params) {
+ $params = explode(" ",$params,2);
+ if( strlen($params[0]) == 64 ) {
+ if( $this->tokens[$this->getUser($this->data)] == $params[0] ) {
+ $this->user['expire'] = time()+($this->config['irc_authtime']*3600);
+ $tmp = dbFetchRow("SELECT level FROM users WHERE user_id = ?", array($this->user['id']));
+ $this->user['level'] = $tmp['level'];
+ if( $this->user['level'] < 5 ) {
+ foreach( dbFetchRows("SELECT device_id FROM devices_perms WHERE user_id = ?", array($this->user['id'])) as $tmp ) {
+ $this->user['devices'][] = $tmp['device_id'];
+ }
+ foreach( dbFetchRows("SELECT port_id FROM ports_perms WHERE user_id = ?", array($this->user['id'])) as $tmp ) {
+ $this->user['ports'][] = $tmp['port_id'];
+ }
+ }
+ return $this->respond("Authenticated.");
+ } else {
+ return $this->respond("Nope.");
+ }
+ } else {
+ $user = dbFetchRow("SELECT `user_id`,`username`,`email` FROM `users` WHERE `username` = ?", array(mres($params[0])));
+ if($user['email'] && $user['username'] == $params[0]) {
+ $token = hash("gost",openssl_random_pseudo_bytes(1024));
+ $this->tokens[$this->getUser($this->data)] = $token;
+ $this->user['name'] = $params[0];
+ $this->user['id'] = $user['user_id'];
+ if( $this->debug ) {
+ $this->log("Auth for '".$params[0]."', ID: '".$user['user_id']."', Token: '".$token."', Mail: '".$user['email']."'");
+ }
+ if(send_mail($user['email'], "LibreNMS IRC-Bot Authtoken", "Your Authtoken for the IRC-Bot:\r\n\r\n".$token."\r\n\r\n") === true) {
+ return $this->respond("Token sent!");
+ } else {
+ return $this->respond("Sorry, seems like mail doesnt like us.");
+ }
+ } else {
+ return $this->respond("Who are you again?");
+ }
+ }
+ return false;
+ }
+
+ private function _reload() {
+ if( $this->user['level'] == 10 ) {
+ global $config;
+ include("includes/defaults.inc.php");
+ include("config.php");
+ $this->respond("Reloading configuration & defaults");
+ if( $config != $this->config ) {
+ return $this->__construct();
+ }
+ } else {
+ return $this->respond("Permission denied.");
+ }
+ }
+
+ private function _join($params) {
+ if( $this->user['level'] == 10 ) {
+ return $this->joinChan($params);
+ } else {
+ return $this->respond("Permission denied.");
+ }
+ }
+
+ private function _quit($params) {
+ if( $this->user['level'] == 10 ) {
+ return die();
+ } else {
+ return $this->respond("Permission denied.");
+ }
+ }
+
+ private function _help($params) {
+ foreach($this->commands as $cmd) {
+ $msg .= ", ".$cmd;
+ }
+ $msg = substr($msg,2);
+ return $this->respond("Available commands: $msg");
+ }
+
+ private function _version($params) {
+ return $this->respond($this->config['project_name_version'].", PHP: ".PHP_VERSION);
+ }
+
+ private function _log($params) {
+ $num = 1;
+ if( $params > 1 ) {
+ $num = $params;
+ }
+ if( $this->user['level'] < 5 ) {
+ $tmp = dbFetchRows("SELECT `event_id`,`host`,`datetime`,`message`,`type` FROM `eventlog` WHERE `host` IN (".implode(",",$this->user['devices']).") ORDER BY `event_id` DESC LIMIT ".mres($num));
+ } else
+ $tmp = dbFetchRows("SELECT `event_id`,`host`,`datetime`,`message`,`type` FROM `eventlog` ORDER BY `event_id` DESC LIMIT ".mres($num));
+ foreach( $tmp as $device) {
+ $hostid = dbFetchRow("SELECT `hostname` FROM `devices` WHERE `device_id` = ".$device['host']);
+ $this->respond($device['event_id'] ." ". $hostid['hostname'] ." ". $device['datetime'] ." ". $device['message'] ." ". $device['type']);
+ }
+ if(!$hostid) {
+ $this->respond("Nothing to see, maybe a bug?");
+ }
+ return true;
+ }
+
+ private function _down($params) {
+ if( $this->user['level'] < 5 ) {
+ $tmp = dbFetchRows("SELECT `hostname` FROM `devices` WHERE status=0 AND `device_id` IN (".implode(",",$this->user['devices']).")");
+ } else {
+ $tmp = dbFetchRows("SELECT `hostname` FROM `devices` WHERE status=0");
+ }
+ foreach( $tmp as $db ) {
+ if($db['hostname']) {
+ $msg .= ", ".$db['hostname'];
+ }
+ }
+ $msg = substr($msg,2);
+ $msg = $msg ? $msg : "Nothing to show :)";
+ return $this->respond($msg);
+ }
+
+ private function _device($params) {
+ $params = explode(" ",$params);
+ $hostname = $params[0];
+ $device = dbFetchRow("SELECT * FROM `devices` WHERE `hostname` = ?",array($hostname));
+ if(!$device) {
+ return $this->respond("Error: Bad or Missing hostname, use .listdevices to show all devices.");
+ }
+ if($this->user['level'] < 5 && !in_array($device['device_id'],$this->user['devices'])) {
+ return $this->respond("Error: Permission denied.");
+ }
+ $status = $device['status'] ? "Up ".formatUptime($device['uptime']) : "Down";
+ $status .= $device['ignore'] ? "*Ignored*" : "";
+ $status .= $device['disabled'] ? "*Disabled*" : "";
+ return $this->respond($device['os']." ".$device['version']." ".$device['features']." ".$status);
+ }
+
+ private function _port($params) {
+ $params = explode(" ",$params);
+ $hostname = $params[0];
+ $ifname = $params[1];
+ if( !$hostname || !$ifname ) {
+ return $this->respond("Error: Missing hostname or ifname.");
+ }
+ $device = dbFetchRow("SELECT * FROM `devices` WHERE `hostname` = ?",array($hostname));
+ $port = dbFetchRow("SELECT * FROM `ports` WHERE `ifName` = ? OR `ifDescr` = ? AND device_id = ?", array($ifname, $ifname, $device['device_id']));
+ if($this->user['level'] < 5 && !in_array($port['port_id'],$this->user['ports']) && !in_array($device['device_id'],$this->user['devices'])) {
+ return $this->respond("Error: Permission denied.");
+ }
+ $bps_in = formatRates($port['ifInOctets_rate']);
+ $bps_out = formatRates($port['ifOutOctets_rate']);
+ $pps_in = format_bi($port['ifInUcastPkts_rate']);
+ $pps_out = format_bi($port['ifOutUcastPkts_rate']);
+ return $this->respond($port['ifAdminStatus']."/".$port['ifOperStatus']." ".$bps_in. " > bps > ".$bps_out." | ".$pps_in."pps > PPS > ".$pps_out."pps");
+ }
+
+ private function _listdevices($params) {
+ if( $this->user['level'] < 5 ) {
+ $tmp = dbFetchRows("SELECT `hostname` FROM `devices` WHERE `device_id` IN (".implode(",",$this->user['devices']).")");
+ } else {
+ $tmp = dbFetchRows("SELECT `hostname` FROM `devices`");
+ }
+ foreach( $tmp as $device ) {
+ $msg .= ", ".$device['hostname'];
+ }
+ $msg = substr($msg,2);
+ $msg = $msg ? $msg : "Nothing to show..?";
+ return $this->respond($msg);
+ }
+
+ private function _status($params) {
+ $params = explode(" ",$params);
+ $statustype = $params[0];
+ if( $this->user['level'] < 5 ) {
+ $d_w = " WHERE device_id IN (".implode(",",$this->user['devices']).")";
+ $d_a = " AND device_id IN (".implode(",",$this->user['devices']).")";
+ $p_w = " WHERE port_id IN (".implode(",",$this->user['ports']).") OR device_id IN (".implode(",",$this->user['devices']).")";
+ $p_a = " AND (I.port_id IN (".implode(",",$this->user['ports']).") OR I.device_id IN (".implode(",",$this->user['devices'])."))";
+ }
+ switch($statustype) {
+ case "devices":
+ case "device":
+ case "dev":
+ $devcount = array_pop(dbFetchRow("SELECT count(*) FROM devices".$d_w));
+ $devup = array_pop(dbFetchRow("SELECT count(*) FROM devices WHERE status = '1' AND `ignore` = '0'".$d_a));
+ $devdown = array_pop(dbFetchRow("SELECT count(*) FROM devices WHERE status = '0' AND `ignore` = '0'".$d_a));
+ $devign = array_pop(dbFetchRow("SELECT count(*) FROM devices WHERE `ignore` = '1'".$d_a));
+ $devdis = array_pop(dbFetchRow("SELECT count(*) FROM devices WHERE `disabled` = '1'".$d_a));
+ $msg = "Devices: " .$devcount . " (" .$devup . " up, " .$devdown . " down, " .$devign . " ignored, " .$devdis . " disabled" . ")";
+ break;
+ case "ports":
+ case "port":
+ case "prt":
+ $prtcount = array_pop(dbFetchRow("SELECT count(*) FROM ports".$p_w));
+ $prtup = array_pop(dbFetchRow("SELECT count(*) FROM ports AS I, devices AS D WHERE I.ifOperStatus = 'up' AND I.ignore = '0' AND I.device_id = D.device_id AND D.ignore = '0'".$p_a));
+ $prtdown = array_pop(dbFetchRow("SELECT count(*) FROM ports AS I, devices AS D WHERE I.ifOperStatus = 'down' AND I.ifAdminStatus = 'up' AND I.ignore = '0' AND D.device_id = I.device_id AND D.ignore = '0'".$p_a));
+ $prtsht = array_pop(dbFetchRow("SELECT count(*) FROM ports AS I, devices AS D WHERE I.ifAdminStatus = 'down' AND I.ignore = '0' AND D.device_id = I.device_id AND D.ignore = '0'".$p_a));
+ $prtign = array_pop(dbFetchRow("SELECT count(*) FROM ports AS I, devices AS D WHERE D.device_id = I.device_id AND (I.ignore = '1' OR D.ignore = '1')".$p_a));
+ $prterr = array_pop(dbFetchRow("SELECT count(*) FROM ports AS I, devices AS D WHERE D.device_id = I.device_id AND (I.ignore = '0' OR D.ignore = '0') AND (I.ifInErrors_delta > '0' OR I.ifOutErrors_delta > '0')".$p_a));
+ $msg = "Ports: " .$prtcount . " (" .$prtup . " up, " .$prtdown . " down, " .$prtign . " ignored, " .$prtsht . " shutdown" . ")";
+ break;
+ case "services":
+ case "service":
+ case "srv":
+ $srvcount = array_pop(dbFetchRow("SELECT count(service_id) FROM services".$d_w));
+ $srvup = array_pop(dbFetchRow("SELECT count(service_id) FROM services WHERE service_status = '1' AND service_ignore ='0'".$d_a));
+ $srvdown = array_pop(dbFetchRow("SELECT count(service_id) FROM services WHERE service_status = '0' AND service_ignore = '0'".$d_a));
+ $srvign = array_pop(dbFetchRow("SELECT count(service_id) FROM services WHERE service_ignore = '1'".$d_a));
+ $srvdis = array_pop(dbFetchRow("SELECT count(service_id) FROM services WHERE service_disabled = '1'".$d_a));
+ $msg = "Services: " .$srvcount . " (" .$srvup . " up, " .$srvdown . " down, " .$srvign . " ignored, " .$srvdis . " disabled" . ")";
+ break;
+ default:
+ $msg = "Error: STATUS requires one of the following: ||";
+ break;
+ }
+ return $this->respond($msg);
+ }
}
-///
-# PORT Function
-///
- function port_info(&$irc, &$data)
- {
- global $config;
-
- $hostname = $data->messageex[1];
- $ifname = $data->messageex[2];
-
- mysql_connect($config['db_host'],$config['db_user'],$config['db_pass']);
- mysql_select_db($config['db_name']);
-
- $device = dbFetchRow("SELECT * FROM `devices` WHERE `hostname` = ?",array($hostname));
- $port = dbFetchRow("SELECT * FROM `ports` WHERE `ifName` = ? OR `ifDescr` = ? AND device_id = ?", array($ifname, $ifname, $device['device_id']));
-
- mysql_close();
-
- $bps_in = formatRates($port['ifInOctets_rate']);
- $bps_out = formatRates($port['ifOutOctets_rate']);
- $pps_in = format_bi($port['ifInUcastPkts_rate']);
- $pps_out = format_bi($port['ifOutUcastPkts_rate']);
-
- $irc->message(SMARTIRC_TYPE_CHANNEL, $data->channel, $port['ifAdminStatus'] . "/" . $port['ifOperStatus'] . " " .
- $bps_in. " > bps > " . $bps_out . " | " . $pps_in. "pps > PPS > " . $pps_out ."pps");
-
- echo date("m-d-y H:i:s ");
- echo "PORT\t\t\t" . $hostname . "\t". $ifname . "\n";
- }
-
-///
-# LISTDEVICES Function
-///
- function list_devices(&$irc, &$data)
- {
- global $config;
-
- unset ($message);
-
- mysql_connect($config['db_host'],$config['db_user'],$config['db_pass']);
- mysql_select_db($config['db_name']);
-
- foreach (dbFetchRows("SELECT `hostname` FROM `devices`") as $device)
- {
- $message .= $sep . $device['hostname'];
- $sep = ", ";
- }
-
- mysql_close();
-
- $irc->message(SMARTIRC_TYPE_CHANNEL, $data->channel, $message);
- unset($sep);
-
- echo date("m-d-y H:i:s ");
- echo "LISTDEVICES\n";
- }
-
-///
-# STATUS Function
-///
- function status_info(&$irc, &$data)
- {
- global $config;
-
- $statustype = $data->messageex[1];
-
- mysql_connect($config['db_host'],$config['db_user'],$config['db_pass']);
- mysql_select_db($config['db_name']);
-
- if ($statustype == "dev")
- {
- $devcount = array_pop(dbFetchRow("SELECT count(*) FROM devices"));
- $devup = array_pop(dbFetchRow("SELECT count(*) FROM devices WHERE status = '1' AND `ignore` = '0'"));
- $devdown = array_pop(dbFetchRow("SELECT count(*) FROM devices WHERE status = '0' AND `ignore` = '0'"));
- $devign = array_pop(dbFetchRow("SELECT count(*) FROM devices WHERE `ignore` = '1'"));
- $devdis = array_pop(dbFetchRow("SELECT count(*) FROM devices WHERE `disabled` = '1'"));
- $irc->message(SMARTIRC_TYPE_CHANNEL, $data->channel, "Devices: " .$devcount . " (" .$devup . " up, " .$devdown . " down, " .$devign . " ignored, " .$devdis . " disabled" . ")");
- } else if ($statustype == "prt") {
- $prtcount = array_pop(dbFetchRow("SELECT count(*) FROM ports"));
- $prtup = array_pop(dbFetchRow("SELECT count(*) FROM ports AS I, devices AS D WHERE I.ifOperStatus = 'up' AND I.ignore = '0' AND I.device_id = D.device_id AND D.ignore = '0'"));
- $prtdown = array_pop(dbFetchRow("SELECT count(*) FROM ports AS I, devices AS D WHERE I.ifOperStatus = 'down' AND I.ifAdminStatus = 'up' AND I.ignore = '0' AND D.device_id = I.device_id AND D.ignore = '0'"));
- $prtsht = array_pop(dbFetchRow("SELECT count(*) FROM ports AS I, devices AS D WHERE I.ifAdminStatus = 'down' AND I.ignore = '0' AND D.device_id = I.device_id AND D.ignore = '0'"));
- $prtign = array_pop(dbFetchRow("SELECT count(*) FROM ports AS I, devices AS D WHERE D.device_id = I.device_id AND (I.ignore = '1' OR D.ignore = '1')"));
- $prterr = array_pop(dbFetchRow("SELECT count(*) FROM ports AS I, devices AS D WHERE D.device_id = I.device_id AND (I.ignore = '0' OR D.ignore = '0') AND (I.ifInErrors_delta > '0' OR I.ifOutErrors_delta > '0')"));
- $irc->message(SMARTIRC_TYPE_CHANNEL, $data->channel, "Ports: " .$prtcount . " (" .$prtup . " up, " .$prtdown . " down, " .$prtign . " ignored, " .$prtsht . " shutdown" . ")");
- } else if ($statustype == "srv") {
- $srvcount = array_pop(dbFetchRow("SELECT count(service_id) FROM services"));
- $srvup = array_pop(dbFetchRow("SELECT count(service_id) FROM services WHERE service_status = '1' AND service_ignore ='0'"));
- $srvdown = array_pop(dbFetchRow("SELECT count(service_id) FROM services WHERE service_status = '0' AND service_ignore = '0'"));
- $srvign = array_pop(dbFetchRow("SELECT count(service_id) FROM services WHERE service_ignore = '1'"));
- $srvdis = array_pop(dbFetchRow("SELECT count(service_id) FROM services WHERE service_disabled = '1'"));
- $irc->message(SMARTIRC_TYPE_CHANNEL, $data->channel, "Services: " .$srvcount . " (" .$srvup . " up, " .$srvdown . " down, " .$srvign . " ignored, " .$srvdis . " disabled" . ")");
- } else {
- $irc->message(SMARTIRC_TYPE_CHANNEL, $data->channel, "Error: STATUS requires one of the following "); }
-
- mysql_close();
-
- echo date("m-d-y H:i:s ");
- echo "STATUS\t\t$statustype\n";
- }
-}
-
-$bot = &new ircbot();
-$irc = &new Net_SmartIRC();
-$irc->setUseSockets(TRUE);
-
-$irc->registerActionhandler(SMARTIRC_TYPE_CHANNEL, '.listdevices', $bot, 'list_devices');
-$irc->registerActionhandler(SMARTIRC_TYPE_CHANNEL, '.device', $bot, 'device_info');
-$irc->registerActionhandler(SMARTIRC_TYPE_CHANNEL, '.port', $bot, 'port_info');
-$irc->registerActionhandler(SMARTIRC_TYPE_CHANNEL, '.down', $bot, 'down_info');
-$irc->registerActionhandler(SMARTIRC_TYPE_CHANNEL, '.version', $bot, 'version_info');
-$irc->registerActionhandler(SMARTIRC_TYPE_CHANNEL, '.status', $bot, 'status_info');
-$irc->registerActionhandler(SMARTIRC_TYPE_CHANNEL, '.log', $bot, 'log_info');
-$irc->registerActionhandler(SMARTIRC_TYPE_CHANNEL, '.help', $bot, 'help_info');
-
-$irc->connect($config['irc_host'], $config['irc_port']);
-$irc->login($config['irc_nick'], $config['project_name'] . ' Bot', 0, $config['irc_nick']);
-$irc->join($config['irc_chan']);
-$irc->listen();
-$irc->disconnect();
-
-?>
+$irc = new ircbot();
+?>
\ No newline at end of file