Ejemplo n.º 1
0
/**
 * Generate SQL from Group-Pattern
 * @param string $pattern Pattern to generate SQL for
 * @param string $search What to searchid for
 * @return string
 */
function GenGroupSQL($pattern, $search = '')
{
    $tmp = explode(" ", $pattern);
    $tables = array();
    foreach ($tmp as $opt) {
        if (strstr($opt, '%') && strstr($opt, '.')) {
            $tmpp = explode(".", $opt, 2);
            $tmpp[0] = str_replace("%", "", $tmpp[0]);
            $tables[] = mres(str_replace("(", "", $tmpp[0]));
            $pattern = str_replace($opt, $tmpp[0] . '.' . $tmpp[1], $pattern);
        }
    }
    $tables = array_keys(array_flip($tables));
    $x = sizeof($tables);
    $i = 0;
    $join = "";
    while ($i < $x) {
        if (isset($tables[$i + 1])) {
            $join .= $tables[$i] . ".device_id = " . $tables[$i + 1] . ".device_id && ";
        }
        $i++;
    }
    if (!empty($search)) {
        $search .= " &&";
    }
    $sql = "SELECT DISTINCT(" . str_replace("(", "", $tables[0]) . ".device_id) FROM " . implode(",", $tables) . " WHERE " . $search . " (" . str_replace(array("%", "@", "!~", "~"), array("", "%", "NOT LIKE", "LIKE"), $pattern) . ")";
    return $sql;
}
Ejemplo n.º 2
0
/**
 * Generate SQL from Group-Pattern
 * @param string $pattern Pattern to generate SQL for
 * @param string $search  What to searchid for
 * @return string
 */
function GenGroupSQL($pattern, $search = '')
{
    $pattern = RunGroupMacros($pattern);
    if ($pattern === false) {
        return false;
    }
    $tmp = explode(' ', $pattern);
    $tables = array();
    foreach ($tmp as $opt) {
        if (strstr($opt, '%') && strstr($opt, '.')) {
            $tmpp = explode('.', $opt, 2);
            $tmpp[0] = str_replace('%', '', $tmpp[0]);
            $tables[] = mres(str_replace('(', '', $tmpp[0]));
            $pattern = str_replace($opt, $tmpp[0] . '.' . $tmpp[1], $pattern);
        }
    }
    $tables = array_keys(array_flip($tables));
    $x = sizeof($tables);
    $i = 0;
    $join = '';
    while ($i < $x) {
        if (isset($tables[$i + 1])) {
            $join .= $tables[$i] . '.device_id = ' . $tables[$i + 1] . '.device_id && ';
        }
        $i++;
    }
    if (!empty($search)) {
        $search .= ' &&';
    }
    $sql = 'SELECT DISTINCT(' . str_replace('(', '', $tables[0]) . '.device_id) FROM ' . implode(',', $tables) . ' WHERE ' . $search . ' (' . str_replace(array('%', '@', '!~', '~'), array('', '.*', 'NOT REGEXP', 'REGEXP'), $pattern) . ')';
    return $sql;
}
Ejemplo n.º 3
0
function get_userid($username)
{
    # FIXME should come from LDAP
    $sql = "SELECT user_id FROM `users` WHERE `username`='" . mres($username) . "'";
    $row = mysql_fetch_array(mysql_query($sql));
    return $row['user_id'];
}
Ejemplo n.º 4
0
/**
 * Generate SQL from Rule
 * @param string $rule Rule to generate SQL for
 * @return string
 */
function GenSQL($rule)
{
    $tmp = explode(" ", $rule);
    $tables = array();
    foreach ($tmp as $opt) {
        if (strstr($opt, '%') && strstr($opt, '.')) {
            $tmpp = explode(".", $opt, 2);
            $tmpp[0] = str_replace("%", "", $tmpp[0]);
            $tables[] = mres(str_replace("(", "", $tmpp[0]));
            $rule = str_replace($opt, $tmpp[0] . '.' . $tmpp[1], $rule);
        }
    }
    $tables = array_unique($tables);
    $x = sizeof($tables);
    $i = 0;
    $join = "";
    while ($i < $x) {
        if (isset($tables[$i + 1])) {
            $join .= $tables[$i] . ".device_id = " . $tables[$i + 1] . ".device_id && ";
        }
        $i++;
    }
    $sql = "SELECT * FROM " . implode(",", $tables) . " WHERE (" . $join . "" . str_replace("(", "", $tables[0]) . ".device_id = ?) && (" . str_replace(array("%", "@", "!~", "~"), array("", "%", "NOT LIKE", "LIKE"), $rule) . ")";
    return $sql;
}
Ejemplo n.º 5
0
function postbug($username, $body)
{
    global $DB_HOST, $DB_USERNAME, $DB_PASSWORD, $DB_WEBSITE;
    $connection = connect($DB_HOST, $DB_USERNAME, $DB_PASSWORD);
    $date = date('Y-m-d H:i:s');
    $sql = "INSERT INTO " . $DB_WEBSITE . ".`bugtracker` ( `body`, `autor`, `solved`, `date`, `so_date`) VALUES ( '" . mres($body) . "', '" . $username . "', 0, '" . $date . "', '" . $date . "')";
    mysqli_query($connection, $sql);
}
Ejemplo n.º 6
0
/**
 * Generate SQL from Rule
 * @param string $rule Rule to generate SQL for
 * @return string|boolean
 */
function GenSQL($rule)
{
    $rule = htmlspecialchars_decode($rule);
    $rule = RunMacros($rule);
    if (empty($rule)) {
        //Cannot resolve Macros due to recursion. Rule is invalid.
        return false;
    }
    //Pretty-print rule to dissect easier
    $pretty = array('*' => ' * ', '(' => ' ( ', ')' => ' ) ', '/' => ' / ', '&&' => ' && ', '||' => ' || ', 'DATE_SUB ( NOW (  )' => 'DATE_SUB( NOW()');
    $rule = str_replace(array_keys($pretty), $pretty, $rule);
    $tmp = explode(" ", $rule);
    $tables = array();
    foreach ($tmp as $opt) {
        if (strstr($opt, '%') && strstr($opt, '.')) {
            $tmpp = explode(".", $opt, 2);
            $tmpp[0] = str_replace("%", "", $tmpp[0]);
            $tables[] = mres(str_replace("(", "", $tmpp[0]));
            $rule = str_replace($opt, $tmpp[0] . '.' . $tmpp[1], $rule);
        }
    }
    $tables = array_keys(array_flip($tables));
    if (dbFetchCell('SELECT 1 FROM information_schema.COLUMNS WHERE TABLE_NAME = ? && COLUMN_NAME = ?', array($tables[0], 'device_id')) != 1) {
        //Our first table has no valid glue, append the 'devices' table to it!
        array_unshift($tables, 'devices');
    }
    $x = sizeof($tables) - 1;
    $i = 0;
    $join = "";
    while ($i < $x) {
        if (isset($tables[$i + 1])) {
            $gtmp = ResolveGlues(array($tables[$i + 1]), 'device_id');
            if ($gtmp === false) {
                //Cannot resolve glue-chain. Rule is invalid.
                return false;
            }
            $last = "";
            $qry = "";
            foreach ($gtmp as $glue) {
                if (empty($last)) {
                    list($tmp, $last) = explode('.', $glue);
                    $qry .= $glue . ' = ';
                } else {
                    list($tmp, $new) = explode('.', $glue);
                    $qry .= $tmp . '.' . $last . ' && ' . $tmp . '.' . $new . ' = ';
                    $last = $new;
                }
                if (!in_array($tmp, $tables)) {
                    $tables[] = $tmp;
                }
            }
            $join .= "( " . $qry . $tables[0] . ".device_id ) && ";
        }
        $i++;
    }
    $sql = "SELECT * FROM " . implode(",", $tables) . " WHERE (" . $join . "" . str_replace("(", "", $tables[0]) . ".device_id = ?) && (" . str_replace(array("%", "@", "!~", "~"), array("", ".*", "NOT REGEXP", "REGEXP"), $rule) . ")";
    return $sql;
}
Ejemplo n.º 7
0
function discover_service($device, $service)
{
    if (!dbFetchCell('SELECT COUNT(service_id) FROM `services` WHERE `service_type`= ? AND `device_id` = ?', array($service, $device['device_id']))) {
        add_service($device, $service, "(Auto discovered) {$service}");
        log_event('Autodiscovered service: type ' . mres($service), $device, 'service');
        echo '+';
    }
    echo "{$service} ";
}
Ejemplo n.º 8
0
function mres($q)
{
    if (is_array($q)) {
        foreach ($q as $k => $v) {
            $q[$k] = mres($v);
        }
    } elseif (is_string($q)) {
        $q = mysql_real_escape_string($q);
    }
    return $q;
}
Ejemplo n.º 9
0
function authenticate($username, $password)
{
    global $config;
    if (isset($_SERVER['REMOTE_USER'])) {
        $_SESSION['username'] = mres($_SERVER['REMOTE_USER']);
        if (user_exists($_SESSION['username'])) {
            return 1;
        }
        $_SESSION['username'] = $config['http_auth_guest'];
        return 1;
    }
    return 0;
}
Ejemplo n.º 10
0
function authenticate($username, $password)
{
    global $config;
    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;
        }
    }
    return 0;
}
Ejemplo n.º 11
0
 /**
  * generic clean up from db_quoteStr() clone
  *
  * @param string $string
  *
  * @return string
  */
 public static function db_sanitize($string = '')
 {
     function mres($string = '')
     {
         $search = array("\\", "", "\n", "\r", "'", '"', "");
         $replace = array("\\\\", "\\0", "\\n", "\\r", "\\'", '\\"', "\\Z");
         return str_replace($search, $replace, $string);
     }
     if (empty($string)) {
         return '';
     }
     // remove only double empty single quotes
     $string = (string) preg_replace("/[']{2}/", "'", $string);
     $string = (string) str_replace("\\n", "\n", $string);
     $string = (string) str_replace("\\r", "\r", $string);
     $string = (string) str_replace("\\\\", "\\", $string);
     $string = (string) mres($string);
     return $string;
 }
Ejemplo n.º 12
0
foreach (dbFetchRows('SELECT DISTINCT `program` FROM `syslog` ORDER BY `program`') as $data) {
    echo '"<option value="' . mres($data['program']) . '"';
    if ($data['program'] == $vars['program']) {
        echo ' selected';
    }
    echo '>' . $data['program'] . '</option>';
}
?>
                        </select>
                    </div>
                    <div class="form-group">
                        <select name="priority" id="priority" class="form-control input-sm">
                            <option value="">All Priorities</option>
                                <?php 
foreach (dbFetchRows('SELECT DISTINCT `priority` FROM `syslog` ORDER BY `level`') as $data) {
    echo '"<option value="' . mres($data['priority']) . '"';
    if ($data['priority'] == $vars['priority']) {
        echo ' selected';
    }
    echo '>' . $data['priority'] . '</option>';
}
?>
                        </select>
                    </div>
                    <div class="form-group">
                        <input name="from" type="text" class="form-control input-sm" id="dtpickerfrom" maxlength="16" value="<?php 
echo $vars['from'];
?>
" placeholder="From" data-date-format="YYYY-MM-DD HH:mm">
                    </div>
                    <div class="form-group">
Ejemplo n.º 13
0
 * 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.  Please see LICENSE.txt at the top level of
 * the source code distribution for details.
 */
header('Content-type: application/json');
if (is_admin() === false) {
    $response = array('status' => 'error', 'message' => 'Need to be admin');
    echo _json_encode($response);
    exit;
}
$status = 'error';
$message = 'Error updating storage information';
$device_id = mres($_POST['device_id']);
$storage_id = mres($_POST['storage_id']);
$data = mres($_POST['data']);
if (!is_numeric($device_id)) {
    $message = 'Missing device id';
} elseif (!is_numeric($storage_id)) {
    $message = 'Missing storage id';
} elseif (!is_numeric($data)) {
    $message = 'Missing value';
} else {
    if (dbUpdate(array('storage_perc_warn' => $data), 'storage', '`storage_id`=? AND `device_id`=?', array($storage_id, $device_id))) {
        $message = 'Storage information updated';
        $status = 'ok';
    } else {
        $message = 'Could not update storage information';
    }
}
$response = array('status' => $status, 'message' => $message, 'extra' => $extra);
Ejemplo n.º 14
0
<?php

/*
 * LibreNMS
 *
 * Copyright (c) 2015 Søren Friis Rosiak <*****@*****.**>
 * 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.  Please see LICENSE.txt at the top level of
 * the source code distribution for details.
 */
header('Content-type: application/json');
$status = 'error';
$message = 'unknown error';
$device_id = mres($_POST['device_id']);
$port_id_notes = mres($_POST['port_id_notes']);
$attrib_value = $_POST['notes'];
if (isset($attrib_value) && set_dev_attrib(array('device_id' => $device_id), $port_id_notes, $attrib_value)) {
    $status = 'ok';
    $message = 'Updated';
} else {
    $status = 'error';
    $message = 'ERROR: Could not update';
}
die(json_encode(array('status' => $status, 'message' => $message, 'attrib_type' => $port_id_notes, 'attrib_value' => $attrib_value, 'device_id' => $device_id)));
Ejemplo n.º 15
0
    echo _json_encode($response);
    exit;
}
$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';
if ($action == 'remove' || $action == 'remove-slack' || $action == 'remove-hipchat' || $action == 'remove-pushover' || $action == 'remove-boxcar') {
    $config_id = mres($_POST['config_id']);
    if (empty($config_id)) {
        $message = 'No config id passed';
    } else {
        if (dbDelete('config', '`config_id`=?', array($config_id))) {
            if ($action == 'remove-slack') {
                dbDelete('config', "`config_name` LIKE 'alert.transports.slack.{$config_id}.%'");
            } else {
                if ($action == 'remove-hipchat') {
                    dbDelete('config', "`config_name` LIKE 'alert.transports.hipchat.{$config_id}.%'");
                } else {
                    if ($action == 'remove-pushover') {
                        dbDelete('config', "`config_name` LIKE 'alert.transports.pushover.{$config_id}.%'");
                    } elseif ($action == 'remove-boxcar') {
                        dbDelete('config', "`config_name` LIKE 'alert.transports.boxcar.{$config_id}.%'");
                    }
Ejemplo n.º 16
0
function generate_device_link($device, $text = null, $vars = array(), $start = 0, $end = 0, $escape_text = 1, $overlib = 1)
{
    global $config;
    if (!$start) {
        $start = $config['time']['day'];
    }
    if (!$end) {
        $end = $config['time']['now'];
    }
    $class = devclass($device);
    if (!$text) {
        $text = $device['hostname'];
    }
    if (isset($config['os'][$device['os']]['over'])) {
        $graphs = $config['os'][$device['os']]['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'];
        }
    }
    $url = generate_device_url($device, $vars);
    // beginning of overlib box contains large hostname followed by hardware & OS details
    $contents = '<div><span class="list-large">' . $device['hostname'] . '</span>';
    if ($device['hardware']) {
        $contents .= ' - ' . $device['hardware'];
    }
    if ($device['os']) {
        $contents .= ' - ' . mres($config['os'][$device['os']]['text']);
    }
    if ($device['version']) {
        $contents .= ' ' . mres($device['version']);
    }
    if ($device['features']) {
        $contents .= ' (' . mres($device['features']) . ')';
    }
    if (isset($device['location'])) {
        $contents .= ' - ' . htmlentities($device['location']);
    }
    $contents .= '</div>';
    foreach ($graphs as $entry) {
        $graph = $entry['graph'];
        $graphhead = $entry['text'];
        $contents .= '<div class="overlib-box">';
        $contents .= '<span class="overlib-title">' . $graphhead . '</span><br />';
        $contents .= generate_minigraph_image($device, $start, $end, $graph);
        $contents .= generate_minigraph_image($device, $config['time']['week'], $end, $graph);
        $contents .= '</div>';
    }
    if ($escape_text) {
        $text = htmlentities($text);
    }
    if ($overlib == 0) {
        $link = $contents;
    } else {
        $link = overlib_link($url, $text, escape_quotes($contents), $class);
    }
    if (device_permitted($device['device_id'])) {
        return $link;
    } else {
        return $device['hostname'];
    }
}
Ejemplo n.º 17
0
function dbBulkInsert($data, $table)
{
    global $db_stats;
    // the following block swaps the parameters if they were given in the wrong order.
    // it allows the method to work for those that would rather it (or expect it to)
    // follow closer with SQL convention:
    // insert into the TABLE this DATA
    if (is_string($data) && is_array($table)) {
        $tmp = $data;
        $data = $table;
        $table = $tmp;
    }
    if (count($data) === 0) {
        return false;
    }
    if (count($data[0]) === 0) {
        return false;
    }
    $sql = 'INSERT INTO `' . $table . '` (`' . implode('`,`', array_keys($data[0])) . '`)  VALUES ';
    $values = '';
    foreach ($data as $row) {
        if ($values != '') {
            $values .= ',';
        }
        $rowvalues = '';
        foreach ($row as $key => $value) {
            if ($rowvalues != '') {
                $rowvalues .= ',';
            }
            $rowvalues .= "'" . mres($value) . "'";
        }
        $values .= "(" . $rowvalues . ")";
    }
    $time_start = microtime(true);
    $result = dbQuery($sql . $values);
    // logfile($fullSql);
    $time_end = microtime(true);
    $db_stats['insert_sec'] += number_format($time_end - $time_start, 8);
    $db_stats['insert']++;
    return $result;
}
Ejemplo n.º 18
0
<?php

if ($_POST['editing']) {
    if ($_SESSION['userlevel'] > '7') {
        $community = mres($_POST['community']);
        $snmpver = mres($_POST['snmpver']);
        $transport = $_POST['transport'] ? mres($_POST['transport']) : ($transport = 'udp');
        $port = $_POST['port'] ? mres($_POST['port']) : $config['snmp']['port'];
        $timeout = mres($_POST['timeout']);
        $retries = mres($_POST['retries']);
        $poller_group = mres($_POST['poller_group']);
        $port_assoc_mode = mres($_POST['port_assoc_mode']);
        $max_repeaters = mres($_POST['max_repeaters']);
        $v3 = array('authlevel' => mres($_POST['authlevel']), 'authname' => mres($_POST['authname']), 'authpass' => mres($_POST['authpass']), 'authalgo' => mres($_POST['authalgo']), 'cryptopass' => mres($_POST['cryptopass']), 'cryptoalgo' => mres($_POST['cryptoalgo']));
        // FIXME needs better feedback
        $update = array('community' => $community, 'snmpver' => $snmpver, 'port' => $port, 'transport' => $transport, 'poller_group' => $poller_group, 'port_association_mode' => $port_assoc_mode);
        if ($_POST['timeout']) {
            $update['timeout'] = $timeout;
        } else {
            $update['timeout'] = array('NULL');
        }
        if ($_POST['retries']) {
            $update['retries'] = $retries;
        } else {
            $update['retries'] = array('NULL');
        }
        $update = array_merge($update, $v3);
        $device_tmp = deviceArray($device['hostname'], $community, $snmpver, $port, $transport, $v3, $port_assoc_mode);
        if (isSNMPable($device_tmp)) {
            $rows_updated = dbUpdate($update, 'devices', '`device_id` = ?', array($device['device_id']));
            $max_repeaters_set = false;
Ejemplo n.º 19
0
 *
 * 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.  Please see LICENSE.txt at the top level of
 * the source code distribution for details.
 */
require_once '../includes/defaults.inc.php';
set_debug($_REQUEST['debug']);
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;
}
$type = mres($_POST['type']);
if ($type == 'placeholder') {
    $output = 'Please add a Widget to get started';
    $status = 'ok';
} elseif (is_file('includes/common/' . $type . '.inc.php')) {
    $results_limit = 10;
    $no_form = true;
    include 'includes/common/' . $type . '.inc.php';
    $output = implode('', $common_output);
    $status = 'ok';
}
$response = array('status' => $status, 'html' => $output);
echo _json_encode($response);
Ejemplo n.º 20
0
    }
}
if (is_numeric($from)) {
    if ($to - $from <= 172800) {
        $graph_max = 0;
    }
    // Do not graph MAX areas for intervals less then 48 hours
} elseif (preg_match('/\\d(d(ay)?s?|h(our)?s?)$/', $from)) {
    $graph_max = 0;
    // Also for RRD style from (6h, 2day)
}
$rrd_options .= '  --start ' . $from . ' --end ' . $to . ' --width ' . $width . ' --height ' . $height . ' ';
$rrd_options .= $config['rrdgraph_def_text'];
# FIXME mres? that's not for fixing commandline injection... we don't pass this on commandline, luckily... :-)
if ($vars['bg']) {
    $rrd_options .= ' -c CANVAS#' . mres($vars['bg']) . ' ';
}
#$rrd_options .= ' -c BACK#FFFFFF';
if ($height < '99' && $vars['draw_all'] != 'yes') {
    $rrd_options .= ' --only-graph';
}
if ($width <= '350') {
    $rrd_options .= " --font LEGEND:7:'" . $config['mono_font'] . "' --font AXIS:6:'" . $config['mono_font'] . "'";
} else {
    $rrd_options .= " --font LEGEND:8:'" . $config['mono_font'] . "' --font AXIS:7:'" . $config['mono_font'] . "'";
}
//$rrd_options .= ' --font-render-mode normal --dynamic-labels'; // dynamic-labels not supported in rrdtool < 1.4
$rrd_options .= ' --font-render-mode normal';
if ($step != TRUE) {
    $rrd_options .= ' -E';
}
Ejemplo n.º 21
0
    ?>
      </div>
    </div>
  </div>
</nav>
<?php 
}
if (dbFetchCell("SELECT COUNT(`device_id`) FROM `devices` WHERE `last_polled` <= DATE_ADD(NOW(), INTERVAL - 15 minute) AND `ignore` = 0 AND `disabled` = 0 AND status = 1", array()) > 0) {
    $msg_box[] = array('type' => 'warning', 'message' => "<a href=\"poll-log/filter=unpolled/\">It appears as though you have some devices that haven't completed polling within the last 15 minutes, you may want to check that out :)</a>", 'title' => 'Devices unpolled');
}
if (is_array($msg_box)) {
    echo "<script>\n        toastr.options.timeout = 10;\n        toastr.options.extendedTimeOut = 20;\n    ";
    foreach ($msg_box as $message) {
        $message['type'] = mres($message['type']);
        $message['message'] = mres($message['message']);
        $message['title'] = mres($message['title']);
        echo "toastr." . $message['type'] . "('" . $message['message'] . "','" . $message['title'] . "');\n";
    }
    echo "</script>";
}
if (is_array($sql_debug) && is_array($php_debug) && $_SESSION['authenticated'] === true) {
    require_once "includes/print-debug.php";
}
if ($no_refresh !== true && $config['page_refresh'] != 0) {
    $refresh = $config['page_refresh'] * 1000;
    echo '<script type="text/javascript">
        $(document).ready(function() {

           $("#countdown_timer_status").html("<i class=\\"fa fa-pause fa-fw\\"></i> Pause");
           var Countdown = {
               sec: ' . $config['page_refresh'] . ',
Ejemplo n.º 22
0
#!/usr/bin/env php
<?php 
require 'includes/defaults.inc.php';
require 'config.php';
require 'includes/definitions.inc.php';
require 'includes/functions.php';
rrdtool_pipe_open($rrd_process, $rrd_pipes);
$options = getopt('h:p:');
$hosts = str_replace('*', '%', mres($options['h']));
$ports = str_replace('*', '%', mres($options['p']));
if (empty($hosts) && empty($ports)) {
    echo "-h <device hostname wildcard>    Device(s) to match\n";
    echo "-p <ifName widcard>              Port(s) to match using ifName\n";
    echo "\n";
}
foreach (dbFetchRows("SELECT `device_id`,`hostname` FROM `devices` WHERE `hostname` LIKE ?", array('%' . $hosts . '%')) as $device) {
    echo "Found hostname " . $device['hostname'] . ".......\n";
    foreach (dbFetchRows("SELECT `port_id`,`ifIndex`,`ifName`,`ifSpeed` FROM `ports` WHERE `ifName` LIKE ? AND `device_id` = ?", array('%' . $ports . '%', $device['device_id'])) as $port) {
        echo "Tuning port " . $port['ifName'] . ".......\n";
        $rrdfile = get_port_rrdfile_path($device['hostname'], $port['port_id']);
        rrdtool_tune('port', $rrdfile, $port['ifSpeed']);
    }
}
Ejemplo n.º 23
0
function list_bills()
{
    global $config;
    $app = \Slim\Slim::getInstance();
    $router = $app->router()->getCurrentRoute()->getParams();
    $status = 'ok';
    $err_msg = '';
    $message = '';
    $code = 200;
    $bills = array();
    $bill_id = mres($router['bill_id']);
    $bill_ref = mres($_GET['ref']);
    $bill_custid = mres($_GET['custid']);
    if (!empty($bill_custid)) {
        $sql = '`bill_custid` = ?';
        $param = array($bill_custid);
    } elseif (!empty($bill_ref)) {
        $sql = '`bill_ref` = ?';
        $param = array($bill_ref);
    } elseif (is_numeric($bill_id)) {
        $sql = '`bill_id` = ?';
        $param = array($bill_id);
    } else {
        $sql = '';
        $param = array();
    }
    if (count($param) >= 1) {
        $sql = "WHERE {$sql}";
    }
    foreach (dbFetchRows("SELECT `bills`.*,COUNT(port_id) AS `ports_total` FROM `bills` LEFT JOIN `bill_ports` ON `bill_ports`.`bill_id`=`bills`.`bill_id` {$sql} GROUP BY `bill_name`,`bill_ref` ORDER BY `bill_name`", $param) as $bill) {
        $rate_data = $bill;
        $allowed = '';
        $used = '';
        $percent = '';
        $overuse = '';
        if ($bill['bill_type'] == "cdr") {
            $allowed = format_si($bill['bill_cdr']) . "bps";
            $used = format_si($rate_data['rate_95th']) . "bps";
            $percent = round($rate_data['rate_95th'] / $bill['bill_cdr'] * 100, 2);
            $overuse = $rate_data['rate_95th'] - $bill['bill_cdr'];
            $overuse = $overuse <= 0 ? "-" : format_si($overuse);
        } elseif ($bill['bill_type'] == "quota") {
            $allowed = format_bytes_billing($bill['bill_quota']);
            $used = format_bytes_billing($rate_data['total_data']);
            $percent = round($rate_data['total_data'] / $bill['bill_quota'] * 100, 2);
            $overuse = $rate_data['total_data'] - $bill['bill_quota'];
            $overuse = $overuse <= 0 ? "-" : format_bytes_billing($overuse);
        }
        $bill['allowed'] = $allowed;
        $bill['used'] = $used;
        $bill['percent'] = $percent;
        $bill['overuse'] = $overuse;
        $bills[] = $bill;
    }
    $count = count($bills);
    $output = array('status' => $status, 'message' => $message, 'err-msg' => $err_msg, 'count' => $count, 'bills' => $bills);
    $app->response->setStatus($code);
    $app->response->headers->set('Content-Type', 'application/json');
    echo _json_encode($output);
}
Ejemplo n.º 24
0
<?php

if ($_POST['editing']) {
    if ($_SESSION['userlevel'] > "7") {
        $updated = 0;
        $override_sysLocation_bool = mres($_POST['override_sysLocation']);
        if (isset($_POST['sysLocation'])) {
            $override_sysLocation_string = mres($_POST['sysLocation']);
        }
        if ($device['override_sysLocation'] != $override_sysLocation_bool || $device['location'] != $override_sysLocation_string) {
            $updated = 1;
        }
        if ($override_sysLocation_bool) {
            $override_sysLocation = 1;
        } else {
            $override_sysLocation = 0;
        }
        dbUpdate(array('override_sysLocation' => $override_sysLocation), 'devices', '`device_id`=?', array($device['device_id']));
        if (isset($override_sysLocation_string)) {
            dbUpdate(array('location' => $override_sysLocation_string), 'devices', '`device_id`=?', array($device['device_id']));
        }
        #FIXME needs more sanity checking! and better feedback
        $param = array('purpose' => $_POST['descr'], 'type' => $_POST['type'], 'ignore' => $_POST['ignore'], 'disabled' => $_POST['disabled']);
        $rows_updated = dbUpdate($param, 'devices', '`device_id` = ?', array($device['device_id']));
        if ($rows_updated > 0 || $updated) {
            $update_message = "Device record updated.";
            $updated = 1;
            $device = dbFetchRow("SELECT * FROM `devices` WHERE `device_id` = ?", array($device['device_id']));
        } elseif ($rows_updated = '-1') {
            $update_message = "Device record unchanged. No update necessary.";
            $updated = -1;
Ejemplo n.º 25
0
<?php

if ($_POST['editing']) {
    if ($_SESSION['userlevel'] > '7') {
        $ipmi_hostname = mres($_POST['ipmi_hostname']);
        $ipmi_username = mres($_POST['ipmi_username']);
        $ipmi_password = mres($_POST['ipmi_password']);
        if ($ipmi_hostname != '') {
            set_dev_attrib($device, 'ipmi_hostname', $ipmi_hostname);
        } else {
            del_dev_attrib($device, 'ipmi_hostname');
        }
        if ($ipmi_username != '') {
            set_dev_attrib($device, 'ipmi_username', $ipmi_username);
        } else {
            del_dev_attrib($device, 'ipmi_username');
        }
        if ($ipmi_password != '') {
            set_dev_attrib($device, 'ipmi_password', $ipmi_password);
        } else {
            del_dev_attrib($device, 'ipmi_password');
        }
        $update_message = 'Device IPMI data updated.';
        $updated = 1;
    } else {
        include 'includes/error-no-perm.inc.php';
    }
    //end if
}
//end if
if ($updated && $update_message) {
Ejemplo n.º 26
0
            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}))");
            } 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']);
        $update = dbUpdate(array('config_value' => $state), 'config', '`config_id`=?', array($config_id));
        if (!empty($update) || $update == '0') {
            $message = 'Alert rule has been updated.';
            $status = 'ok';
        } else {
            $message = 'ERROR: Alert rule has not been updated.';
        }
    }
}
//end if
$response = array('status' => $status, 'message' => $message);
echo _json_encode($response);
Ejemplo n.º 27
0
require_once 'includes/functions.inc.php';
require_once '../includes/functions.php';
require_once 'includes/authenticate.inc.php';
if (!$_SESSION['authenticated']) {
    echo 'unauthenticated';
    exit;
}
$type = mres($_POST['type']);
if ($type == 'placeholder') {
    $output = "<span style='text-align:left;'><br><h3>Click on the Edit Dashboard button (next to the list of dashboards) to add widgets</h3><br><h4><strong>Remember:</strong> You can only move & resize widgets when you're in <strong>Edit Mode</strong>.</h4><span>";
    $status = 'ok';
    $title = 'Placeholder';
} elseif (is_file('includes/common/' . $type . '.inc.php')) {
    $results_limit = 10;
    $no_form = true;
    $title = ucfirst($type);
    $unique_id = str_replace(array("-", "."), "_", uniqid($type, true));
    $widget_id = mres($_POST['id']);
    $widget_settings = json_decode(dbFetchCell('select settings from users_widgets where user_widget_id = ?', array($widget_id)), true);
    $widget_dimensions = $_POST['dimensions'];
    if (!empty($_POST['settings'])) {
        define('show_settings', true);
    }
    include 'includes/common/' . $type . '.inc.php';
    $output = implode('', $common_output);
    $status = 'ok';
    $title = $widget_settings['title'] ?: $title;
}
$response = array('status' => $status, 'html' => $output, 'title' => $title);
header('Content-type: application/json');
echo _json_encode($response);
Ejemplo n.º 28
0
function update_device()
{
    global $config;
    $app = \Slim\Slim::getInstance();
    $router = $app->router()->getCurrentRoute()->getParams();
    $status = 'error';
    $code = 500;
    $hostname = $router['hostname'];
    // use hostname as device_id if it's all digits
    $device_id = ctype_digit($hostname) ? $hostname : getidbyname($hostname);
    $data = json_decode(file_get_contents('php://input'), true);
    $bad_fields = array('id', 'hostname');
    if (empty($data['field'])) {
        $message = 'Device field to patch has not been supplied';
    } elseif (in_array($data['field'], $bad_fields)) {
        $message = 'Device field is not allowed to be updated';
    } else {
        if (dbUpdate(array(mres($data['field']) => mres($data['data'])), 'devices', '`device_id`=?', array($device_id)) >= 0) {
            $status = 'ok';
            $message = 'Device ' . mres($data['field']) . ' field has been updated';
            $code = 200;
        } else {
            $message = 'Device ' . mres($data['field']) . ' field failed to be updated';
        }
    }
    $output = array('status' => $status, 'message' => $message);
    $app->response->setStatus($code);
    $app->response->headers->set('Content-Type', 'application/json');
    echo _json_encode($output);
}
Ejemplo n.º 29
0
        $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'];
        } else {
            $where = "AND `hostname` LIKE '" . str_replace('*', '%', mres($options['h'])) . "'";
            $doing = $options['h'];
        }
    }
}
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);
Ejemplo n.º 30
0
 * Copyright (c) 2014 Neil Lathwood <https://github.com/laf/ http://www.lathwood.co.uk/fa>
 *
 * 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.  Please see LICENSE.txt at the top level of
 * the source code distribution for details.
 */
if (is_admin() === false) {
    die('ERROR: You need to be admin');
}
require_once '../includes/device-groups.inc.php';
$pattern = $_POST['patterns'];
$group_id = $_POST['group_id'];
$name = mres($_POST['name']);
$desc = mres($_POST['desc']);
if (is_array($pattern)) {
    $pattern = implode(' ', $pattern);
} elseif (!empty($_POST['pattern']) && !empty($_POST['condition']) && !empty($_POST['value'])) {
    $pattern = '%' . $_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 (EditDeviceGroup($group_id, $name, $desc, $pattern)) {
        $update_message = "Edited Group: <i>{$name}: {$pattern}</i>";