Commit c4b22a4c authored by Franco Fichtner's avatar Franco Fichtner

dashboard: merge extensive widget rework et al

Most of this work was done by @adschellevis.  :)

o Movable widgets
o Mini-API for widgets
o Interfaces menu code reduction
o SVG traffic graphs replaced
o CSRF tightening
parent 7c0151cc
This diff is collapsed.
......@@ -203,23 +203,6 @@ class ControllerBase extends ControllerRoot
// set translator
$this->view->setVar('lang', $this->getTranslator($cnf));
$ifarr = array();
foreach ($cnf->object()->interfaces->children() as $key => $node) {
$ifarr[$key] = !empty($node->descr) ? $node->descr->__toString() : strtoupper($key);
}
natcasesort($ifarr);
$ordid = 0;
foreach ($ifarr as $key => $descr) {
$menu->appendItem('Interfaces', $key, array(
'url' => '/interfaces.php?if='. $key,
'visiblename' => '[' . $descr . ']',
'cssclass' => 'fa fa-sitemap',
'order' => $ordid++,
));
}
unset($ifarr);
$this->view->menuSystem = $menu->getItems("/ui".$this->router->getRewriteUri());
// set theme in ui_theme template var, let template handle its defaults (if there is no theme).
......
......@@ -33,7 +33,6 @@ namespace OPNsense\Core\Api;
use OPNsense\Base\ApiControllerBase;
use OPNsense\Base\Menu;
use OPNsense\Core\ACL;
use OPNsense\Core\Config;
/**
* Class MenuController
......@@ -125,25 +124,6 @@ class MenuController extends ApiControllerBase
$this->username = $this->session->get("Username");
}
// add interfaces to "Interfaces" menu tab... kind of a hack, may need some improvement.
$cnf = Config::getInstance();
$ifarr = array();
foreach ($cnf->object()->interfaces->children() as $key => $node) {
$ifarr[$key] = !empty($node->descr) ? $node->descr->__toString() : strtoupper($key);
}
natcasesort($ifarr);
$ordid = 0;
foreach ($ifarr as $key => $descr) {
$menu->appendItem('Interfaces', $key, array(
'url' => '/interfaces.php?if='. $key,
'visiblename' => '[' . $descr . ']',
'cssclass' => 'fa fa-sitemap',
'order' => $ordid++,
));
}
unset($ifarr);
// fetch menu items and apply acl
$menu_items = $menu->getItems($selected_uri);
$this->applyACL($menu_items, $acl);
......
......@@ -29,6 +29,8 @@
*/
namespace OPNsense\Base\Menu;
use OPNsense\Core\Config;
/**
* Class MenuSystem
* @package OPNsense\Base\Menu
......@@ -101,6 +103,25 @@ class MenuSystem
}
}
}
// add interfaces to "Interfaces" menu tab... kind of a hack, may need some improvement.
$ifarr = array();
foreach (Config::getInstance()->object()->interfaces->children() as $key => $node) {
if (empty($node->virtual)) {
$ifarr[$key] = !empty($node->descr) ? (string)$node->descr : strtoupper($key);
}
}
natcasesort($ifarr);
$ordid = 0;
foreach ($ifarr as $key => $descr) {
$this->appendItem('Interfaces', $key, array(
'url' => '/interfaces.php?if='. $key,
'visiblename' => '[' . $descr . ']',
'cssclass' => 'fa fa-sitemap',
'order' => $ordid++,
));
}
unset($ifarr);
}
/**
......
......@@ -28,7 +28,7 @@
"descr": "Allow access to the 'AJAX: Get Stats' page.",
"match": [
"license.php",
"getstats.php*"
"widgets/api/get.php*"
]
},
"page-all": {
......@@ -51,9 +51,7 @@
"match": [
"index.php*",
"*.widget.php*",
"graph.php*",
"getstats.php*",
"legacy_traffic_stats.php*",
"widgets/api/get.php*",
"diag_logs_filter_dynamic.php*"
]
},
......@@ -99,13 +97,6 @@
"diag_halt.php*"
]
},
"page-diagnostics-interfacetraffic": {
"name": "WebCfg - Diagnostics: Interface Traffic page",
"descr": "Allow access to the 'Diagnostics: Interface Traffic' page.",
"match": [
"graph.php*"
]
},
"page-diagnostics-limiter-info": {
"name": "WebCfg - Diagnostics: Limiter Info",
"descr": "Allows access to the 'Diagnostics: Limiter Info' page",
......@@ -964,9 +955,7 @@
"name": "WebCfg - Status: Traffic Graph page",
"descr": "Allow access to the 'Status: Traffic Graph' page.",
"match": [
"status_graph.php*",
"graph.php*",
"legacy_traffic_stats.php*"
"status_graph.php*"
]
},
"page-service-upnp": {
......@@ -1258,13 +1247,6 @@
"vpn_openvpn_server.php*"
]
},
"page-xmlrpcinterfacestats": {
"name": "WebCfg - XMLRPC Interface Stats page",
"descr": "Allow access to the 'XMLRPC Interface Stats' page.",
"match": [
"legacy_traffic_stats.php*"
]
},
"page-xmlrpclibrary": {
"name": "WebCfg - XMLRPC Library page",
"descr": "Allow access to the 'XMLRPC Library' page.",
......
This diff is collapsed.
......@@ -15,16 +15,6 @@
// CONFIGURATION:
/**
* By default, when you include this file csrf-magic will automatically check
* and exit if the CSRF token is invalid. This will defer executing
* csrf_check() until you're ready. You can also pass false as a parameter to
* that function, in which case the function will not exit but instead return
* a boolean false if the CSRF check failed. This allows for tighter integration
* with your system.
*/
$GLOBALS['csrf']['defer'] = false;
/**
* This is the amount of seconds you wish to allow before any token becomes
* invalid; the default is two hours, which should be more than enough for
......@@ -117,12 +107,6 @@ $GLOBALS['csrf']['input-name'] = '__csrf_magic';
*/
$GLOBALS['csrf']['frame-breaker'] = true;
/**
* Whether or not CSRF Magic should be allowed to start a new session in order
* to determine the key.
*/
$GLOBALS['csrf']['auto-session'] = true;
/**
* Whether or not csrf-magic should produce XHTML style tags.
*/
......@@ -187,7 +171,6 @@ function csrf_check($fatal = true)
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
return true;
}
csrf_start();
$name = $GLOBALS['csrf']['input-name'];
$ok = false;
$tokens = '';
......@@ -232,7 +215,6 @@ function csrf_get_tokens()
} else {
$ip = '';
}
csrf_start();
// These are "strong" algorithms that don't require per se a secret
if (session_id()) {
......@@ -259,27 +241,6 @@ function csrf_get_tokens()
return 'invalid';
}
function csrf_flattenpost($data)
{
$ret = array();
foreach ($data as $n => $v) {
$ret = array_merge($ret, csrf_flattenpost2(1, $n, $v));
}
return $ret;
}
function csrf_flattenpost2($level, $key, $data)
{
if (!is_array($data)) {
return array($key => $data);
}
$ret = array();
foreach ($data as $n => $v) {
$nk = $level >= 1 ? $key."[$n]" : "[$n]";
$ret = array_merge($ret, csrf_flattenpost2($level+1, $nk, $v));
}
return $ret;
}
/**
* @param $tokens is safe for HTML consumption
*/
......@@ -287,18 +248,11 @@ function csrf_callback($tokens)
{
// (yes, $tokens is safe to echo without escaping)
header($_SERVER['SERVER_PROTOCOL'] . ' 403 Forbidden');
$data = '';
foreach (csrf_flattenpost($_POST) as $key => $value) {
if ($key == $GLOBALS['csrf']['input-name']) {
continue;
}
$data .= '<input type="hidden" name="'.htmlspecialchars($key).'" value="'.htmlspecialchars($value).'" />';
}
echo "<html><head><title>CSRF check failed</title></head>
<body>
<p>CSRF check failed. Your form session may have expired, or you may not have
cookies enabled.</p>
<form method='post' action=''>$data<input type='submit' value='Try again' /></form>
<p>Debug: $tokens</p></body></html>
";
}
......@@ -398,16 +352,6 @@ function csrf_conf($key, $val)
$GLOBALS['csrf'][$key] = $val;
}
/**
* Starts a session if we're allowed to.
*/
function csrf_start()
{
if ($GLOBALS['csrf']['auto-session'] && session_status() == PHP_SESSION_NONE) {
session_start();
}
}
/**
* Retrieves the secret, and generates one if necessary.
*/
......@@ -469,6 +413,4 @@ if ($GLOBALS['csrf']['rewrite']) {
ob_start('csrf_ob_handler');
}
// Perform check
if (!$GLOBALS['csrf']['defer']) {
csrf_check();
}
csrf_check();
......@@ -194,9 +194,15 @@ if($need_alert_display == true) {
<a href="<?=$button['href'];?>" class="btn btn-primary"><span class="glyphicon glyphicon-plus-sign __iconspacer"></span><?=$button['label'];?></a>
<?php endforeach; endif; ?>
<?php if (isset($widgetfiles)): ?>
<?php if (isset($widgetCollection)): ?>
<a href="#" id="updatepref" style="display:none" onclick="return updatePref();" class="btn btn-primary"><?=gettext("Save Settings");?></a>
<button type="button" class="btn btn-default" data-toggle="modal" data-target="#modal_widgets"><span class="glyphicon glyphicon-plus-sign __iconspacer"></span><?= gettext('Add widget') ?></button>
<button id="add_widget_btn" type="button" class="btn btn-default" data-toggle="modal" data-target="#modal_widgets"><span class="glyphicon glyphicon-plus-sign __iconspacer"></span><?= gettext('Add widget') ?></button>
<select class="selectpicker" data-width="120px" id="column_count">
<option value="1" <?=$pconfig['column_count'] == "1" ? 'selected="selected"' : "";?>><?=gettext("1 column");?></option>
<option value="2" <?=$pconfig['column_count'] == "2" ? 'selected="selected"' : "";?>><?=gettext("2 columns");?></option>
<option value="3" <?=$pconfig['column_count'] == "3" ? 'selected="selected"' : "";?>><?=gettext("3 columns");?></option>
<option value="4" <?=$pconfig['column_count'] == "4" ? 'selected="selected"' : "";?>><?=gettext("4 columns");?></option>
</select>
<?php endif; ?>
</li>
</ul>
......
......@@ -11,51 +11,44 @@
</main>
<?php
if (isset($widgetfiles)):
$widgetfiles_add = $widgetfiles;
sort($widgetfiles_add);
if (isset($widgetCollection)):
// sort by name
usort($widgetCollection, function ($item1, $item2) {
return strcmp(strtolower($item1['name']), strtolower($item2['name']));
});
?>
<div class="modal fade" id="modal_widgets" tabindex="-1" role="dialog" aria-labelledby="modal_widgets_label" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
<button type="button" class="close" data-dismiss="modal">
<span aria-hidden="true">&times;</span>
<span class="sr-only"><?=gettext("Close");?></span>
</button>
<h4 class="modal-title" id="modal_widgets_label"><?=gettext("Available Widgets"); ?></h4>
</div>
<div class="modal-body">
<table class="table table-striped table-hover">
<table class="table table-condensed table-hover">
<?php
foreach($widgetfiles_add as $widget):
if(!stristr($widget, "widget.php"))
continue;
$periodpos = strpos($widget, ".");
$widgetname = substr($widget, 0, $periodpos);
$nicename = $widgetname;
$nicename = str_replace("_", " ", $nicename);
//make the title look nice
$nicename = ucwords($nicename);
$widgettitle = $widgetname . "_title";
$widgettitlelink = $widgetname . "_title_link";
if (isset($$widgettitle)):?>
<tr>
<td style="cursor: pointer;" onclick='return addWidget("<?=$widgetname; ?>")'><?=$$widgettitle; ?></td>
</tr>
foreach($widgetCollection as $widgetItem):
$widgettitle = $widgetItem['name'] . "_title";
$widgettitlelink = $widgetItem['name'] . "_title_link";?>
<tr id="add_widget_<?=$widgetItem['name']; ?>">
<?php
if (isset($$widgettitle)):?>
<td style="cursor: pointer;" onclick='return addWidget("<?=$widgetItem['name']; ?>")'><?=$$widgettitle; ?></td>
<?php
elseif (!empty($widgetItem['display_name'])): ?>
<td style="cursor: pointer;" onclick='return addWidget("<?=$widgetItem['name']; ?>")'><?=$widgetItem['display_name']; ?></td>
<?php
elseif ($nicename != ""): ?>
<tr>
<td style="cursor: pointer;" onclick='return addWidget("<?=$widgetname; ?>")'><?=$nicename; ?></td>
</tr>
endif;?>
</tr>
<?php
endif;
endforeach; ?>
endforeach; ?>
</table>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-default" data-dismiss="modal"><?=gettext("Close");?></button>
</div>
</div><!-- /modal-content -->
</div><!-- /modal-dialog -->
......
This diff is collapsed.
......@@ -32,22 +32,23 @@
require_once("util.inc");
require_once("config.inc");
/* THIS MUST BE ABOVE ALL OTHER CODE */
if (empty($nocsrf)) {
function csrf_startup()
{
csrf_conf('rewrite-js', '/csrf/csrf-magic.js');
$timeout_minutes = isset($config['system']['webgui']['session_timeout']) ? $config['system']['webgui']['session_timeout'] : 240;
csrf_conf('expires', $timeout_minutes * 60);
}
require_once('csrf/csrf-magic.php');
/* CSRF BEGIN: CHECK MUST BE EXECUTED FIRST; NO EXCEPTIONS */
// make sure the session is closed after executing csrf-magic
if (session_status() != PHP_SESSION_NONE) {
session_write_close();
}
function csrf_startup()
{
global $config;
csrf_conf('rewrite-js', '/csrf/csrf-magic.js');
$timeout_minutes = isset($config['system']['webgui']['session_timeout']) ? $config['system']['webgui']['session_timeout'] : 240;
csrf_conf('expires', $timeout_minutes * 60);
}
session_start();
require_once('csrf/csrf-magic.php');
session_write_close();
/* CSRF END: THANK YOU FOR YOUR COOPERATION */
function set_language()
{
global $config;
......
......@@ -15,24 +15,6 @@ function system_get_language_code() {
// link menu system
$menu = new OPNsense\Base\Menu\MenuSystem();
// add interfaces to "Interfaces" menu tab... kind of a hack, may need some improvement.
$cnf = OPNsense\Core\Config::getInstance();
$ifarr = array();
foreach ($cnf->object()->interfaces->children() as $key => $node) {
$ifarr[$key] = !empty($node->descr) ? $node->descr->__toString() : strtoupper($key);
}
natcasesort($ifarr);
$ordid = 0;
foreach ($ifarr as $key => $descr) {
$menu->appendItem('Interfaces', $key, array(
'url' => '/interfaces.php?if=' . $key,
'visiblename' => '[' . $descr . ']',
'cssclass' => 'fa fa-sitemap',
'order' => $ordid++,
));
}
unset($ifarr);
$menuSystem = $menu->getItems($_SERVER['REQUEST_URI']);
/* XXX workaround for dashboard */
......@@ -75,6 +57,24 @@ $pagetitle .= sprintf(' | %s.%s', $config['system']['hostname'], $config['system
.typeahead {
overflow: hidden;
}
/** jquery-sortable styles **/
body.dragging, body.dragging * {
cursor: move !important;
}
.dragged {
position: absolute;
opacity: 0.5;
z-index: 2000;
}
ol.example li.placeholder {
position: relative;
}
ol.example li.placeholder:before {
position: absolute;
}
</style>
<!-- Favicon -->
......@@ -86,7 +86,6 @@ $pagetitle .= sprintf(' | %s.%s', $config['system']['hostname'], $config['system
<!-- bootstrap dialog -->
<link href="/ui/themes/<?= $themename ?>/build/css/bootstrap-dialog.css" rel="stylesheet" type="text/css" />
<!-- Font awesome -->
<link rel="stylesheet" href="/ui/css/font-awesome.min.css">
......
This diff is collapsed.
/* Most widgets update their backend data every 10 seconds. 11 seconds
* will ensure that we update the GUI right after the stats are updated.
* Seconds * 1000 = value
*/
var Seconds = 11;
var update_interval = (Math.abs(Math.ceil(Seconds))-1)*1000 + 990;
function updateMeters() {
url = '/getstats.php';
jQuery.ajax(url, {
type: 'get',
success: function(data) {
response = data || "";
if (response != "")
stats(data);
}
});
setTimer();
}
function setTimer() {
timeout = window.setTimeout('updateMeters()', update_interval);
}
function stats(x) {
var values = x.split("|");
if (jQuery.each(values,function(key,value){
if (value == 'undefined' || value == null)
return true;
else
return false;
}))
updateUptime(values[2]);
updateDateTime(values[5]);
updateCPU(values[0]);
updateMemory(values[1]);
updateState(values[3]);
updateTemp(values[4]);
updateInterfaceStats(values[6]);
updateInterfaces(values[7]);
updateGatewayStats(values[8]);
updateCpuFreq(values[9]);
updateLoadAverage(values[10]);
updateMbuf(values[11]);
updateMbufMeter(values[12]);
updateStateMeter(values[13]);
}
function updateMemory(x) {
if(jQuery('#memusagemeter'))
jQuery("#memusagemeter").html(x + '%');
if(jQuery('#memUsagePB'))
jQuery('#memUsagePB').css( { width: parseInt(x)+'%' } );
}
function updateMbuf(x) {
if(jQuery('#mbuf'))
jQuery("#mbuf").html(x);
}
function updateMbufMeter(x) {
if(jQuery('#mbufusagemeter'))
jQuery("#mbufusagemeter").html(x + '%');
if(jQuery('#mbufPB'))
jQuery('#mbufPB').css( { width: parseInt(x)+'%' } );
}
function updateCPU(x) {
if(jQuery('#cpumeter'))
jQuery("#cpumeter").html(x + '%');
if(jQuery('#cpuPB'))
jQuery('#cpuPB').css( { width: parseInt(x)+'%' } );
}
function updateTemp(x) {
if(jQuery("#tempmeter"))
jQuery("#tempmeter").html(x + '\u00B0' + 'C');
if(jQuery('#tempPB'))
jQuery("#tempPB").css( { width: parseInt(x)+'%' } );
}
function updateDateTime(x) {
if(jQuery('#datetime'))
jQuery("#datetime").html(x);
}
function updateUptime(x) {
if(jQuery('#uptime'))
jQuery("#uptime").html(x);
}
function updateState(x) {
if(jQuery('#pfstate'))
jQuery("#pfstate").html(x);
}
function updateStateMeter(x) {
if(jQuery('#pfstateusagemeter'))
jQuery("#pfstateusagemeter").html(x + '%');
if(jQuery('#statePB'))
jQuery('#statePB').css( { width: parseInt(x)+'%' } );
}
function updateGatewayStats(x){
if (widgetActive("gateways")){
gateways_split = x.split(",");
for (var y=0; y<gateways_split.length; y++){
if(jQuery('#gateway' + (y + 1))) {
jQuery('#gateway' + (y + 1)).html(gateways_split[y]);
}
}
}
}
function updateCpuFreq(x) {
if(jQuery('#cpufreq'))
jQuery("#cpufreq").html(x);
}
function updateLoadAverage(x) {
if(jQuery('#load_average'))
jQuery("#load_average").html(x);
}
function updateInterfaceStats(x){
if (widgetActive("interface_statistics")){
statistics_split = x.split(",");
var counter = 1;
for (var y=0; y<statistics_split.length-1; y++){
if(jQuery('#stat' + counter)) {
jQuery('#stat' + counter).html(statistics_split[y]);
counter++;
}
}
}
}
function updateInterfaces(x){
if (widgetActive("interfaces")){
interfaces_split = x.split("~");
//interfaces_split.each(function(iface){
jQuery.each(interfaces_split, function(id,iface){
details = iface.split(",");
switch(details[1]) {
case "up":
// Interface Arrow color
jQuery('#' + details[0] ).addClass( "text-success" )
jQuery('#' + details[0] ).removeClass( "text-danger" )
// Interface Icon color
jQuery('#' + details[0] + 'icon').addClass( "text-success" )
jQuery('#' + details[0] + 'icon').removeClass( "text-danger" )
// Interface Arrow type
jQuery('#' + details[0] ).addClass( "glyphicon-arrow-up" )
jQuery('#' + details[0] ).removeClass( "glyphicon-arrow-down" )
jQuery('#' + details[0] ).removeClass( "glyphicon-arrow-remove" )
break;
case "down":
jQuery('#' + details[0] ).addClass( "text-danger" )
jQuery('#' + details[0] ).removeClass( "text-success" )
// Interface Icon color
jQuery('#' + details[0] + 'icon').addClass( "text-danger" )
jQuery('#' + details[0] + 'icon').removeClass( "text-success" )
// Interface Arrow type
jQuery('#' + details[0] ).addClass( "glyphicon-arrow-down" )
jQuery('#' + details[0] ).removeClass( "glyphicon-arrow-up" )
jQuery('#' + details[0] ).removeClass( "glyphicon-arrow-remove" )
break;
case "block":
// Interface Icon color
jQuery('#' + details[0] ).addClass( "text-danger" )
jQuery('#' + details[0] ).removeClass( "text-success" )
// Interface Arrow type
jQuery('#' + details[0] ).addClass( "glyphicon-arrow-remove" )
jQuery('#' + details[0] ).removeClass( "glyphicon-arrow-up" )
jQuery('#' + details[0] ).removeClass( "glyphicon-arrow-down" )
break;
}
});
}
}
function widgetActive(x) {
var widget = jQuery('#' + x + '-container');
if ((widget != null) && (widget.css('display') != null) && (widget.css('display') != "none"))
return true;
else
return false;
}
/* start updater */
jQuery(document).ready(function(){
setTimer();
});
......@@ -29,6 +29,8 @@
*/
require_once("guiconfig.inc");
require_once('interfaces.inc');
require_once("/usr/local/www/widgets/api/plugins/traffic.inc");
// Get configured interface list
$ifdescrs = get_configured_interface_with_descr();
......@@ -45,7 +47,6 @@ foreach (array('server', 'client') as $mode) {
}
}
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
// load initial form data
$pconfig = array();
......@@ -59,6 +60,38 @@ if ($_SERVER['REQUEST_METHOD'] === 'GET') {
$pconfig['sort'] = !empty($_GET['sort']) ? $_GET['sort'] : "";
$pconfig['filter'] = !empty($_GET['filter']) ? $_GET['filter'] : "";
$pconfig['hostipformat'] = !empty($_GET['hostipformat']) ? $_GET['hostipformat'] : "";
$pconfig['act'] = !empty($_GET['act']) ? $_GET['act'] : "";
if ($pconfig['act'] == "traffic") {
// traffic graph data
echo json_encode(traffic_api());
exit;
} elseif ($pconfig['act'] == 'top') {
// top data
$result = array();
$real_interface = get_real_interface($pconfig['if']);
if (does_interface_exist($real_interface)) {
$netmask = find_interface_subnet($real_interface);
$intsubnet = gen_subnet(find_interface_ip($real_interface), $netmask) . "/$netmask";
$cmd_args = $pconfig['filter'] == "local" ? " -c " . $intsubnet . " " : " -lc 0.0.0.0/0 ";
$cmd_args .= $pconfig['sort'] == "out" ? " -T " : " -R ";
$cmd_action = "/usr/local/bin/rate -i {$real_interface} -nlq 1 -Aba 20 {$cmd_args} | tr \"|\" \" \" | awk '{ printf \"%s:%s:%s:%s:%s\\n\", $1, $2, $4, $6, $8 }'";
exec($cmd_action, $listedIPs);
for ($idx = 2 ; $idx < count($listedIPs) ; ++$idx) {
$fields = explode(':', $listedIPs[$idx]);
if (!empty($pconfig['hostipformat'])) {
$addrdata = gethostbyaddr($fields[0]);
if ($pconfig['hostipformat'] == 'hostname' && $addrdata != $fields[0]){
$addrdata = explode(".", $addrdata)[0];
}
} else {
$addrdata = $fields[0];
}
$result[] = array('host' => $addrdata, 'in' => $fields[1], 'out' => $fields[2]);
}
}
echo json_encode($result);
exit;
}
} elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
header("Location: status_graph.php");
exit;
......@@ -74,7 +107,10 @@ include("head.inc");
<script type="text/javascript">
$( document ).ready(function() {
function update_bandwidth_stats() {
$.ajax("legacy_traffic_stats.php", {
$.ajax("status_graph.php", {'type': 'get', 'cache': false, 'dataType': 'json', 'data': {'act': 'traffic'}}).done(function(data){
traffic_widget_update($("[data-plugin=traffic]")[0], data);
});
$.ajax("status_graph.php", {
type: 'get',
cache: false,
dataType: "json",
......@@ -96,9 +132,10 @@ include("head.inc");
$("#bandwidth_details").html(html.join(''));
}
});
setTimeout(update_bandwidth_stats, 1000);
setTimeout(update_bandwidth_stats, 2000);
}
update_bandwidth_stats();
});
</script>
......@@ -107,7 +144,15 @@ include("head.inc");
<div class="row">
<section class="col-xs-12">
<div class="content-box">
<form name="form1" method="get">
<div class="col-xs=-12">
<?php
// plugin dashboard widget
include ('/usr/local/www/widgets/widgets/traffic_graphs.widget.php');?>
</div>
</div>
</section>
<section class="col-xs-12">
<div class="content-box">
<div class="table-responsive" >
<table class="table table-striped">
<thead>
......@@ -121,7 +166,7 @@ include("head.inc");
<tbody>
<tr>
<td>
<select id="if" name="if" onchange="document.form1.submit()">
<select id="if" name="if">
<?php
foreach ($ifdescrs as $ifn => $ifd):?>
<option value="<?=$ifn;?>" <?=$ifn == $pconfig['if'] ? " selected=\"selected\"" : "";?>>
......@@ -132,7 +177,7 @@ include("head.inc");
</select>
</td>
<td>
<select id="sort" name="sort" onchange="document.form1.submit()">
<select id="sort" name="sort">
<option value="">
<?= gettext('Bw In') ?>
</option>
......@@ -142,7 +187,7 @@ include("head.inc");
</select>
</td>
<td>
<select id="filter" name="filter" onchange="document.form1.submit()">
<select id="filter" name="filter">
<option value="local" <?=$pconfig['filter'] == "local" ? " selected=\"selected\"" : "";?>>
<?= gettext('Local') ?>
</option>
......@@ -152,7 +197,7 @@ include("head.inc");
</select>
</td>
<td>
<select id="hostipformat" name="hostipformat" onchange="document.form1.submit()">
<select id="hostipformat" name="hostipformat">
<option value=""><?= gettext('IP Address') ?></option>
<option value="hostname" <?=$pconfig['hostipformat'] == "hostname" ? " selected" : "";?>>
<?= gettext('Host Name') ?>
......@@ -166,24 +211,11 @@ include("head.inc");
</tbody>
</table>
</div>
</form>
</div>
</section>
<section class="col-xs-12">
<div class="content-box">
<div class="col-sm-6 col-xs-12">
<div>
<br/>
<object data="graph.php?ifnum=<?=htmlspecialchars($pconfig['if']);?>&amp;ifname=<?=rawurlencode($ifdescrs[htmlspecialchars($pconfig['if'])]);?>">
<param name="id" value="graph" />
<param name="type" value="image/svg+xml" />
<param name="width" value="100%" />
<param name="height" value="100%" />
<param name="pluginspage" value="http://www.adobe.com/svg/viewer/install/auto" />
</object>
</div>
</div>
<div class="col-sm-6 col-xs-12">
<div class="col-sm-12 col-xs-12">
<div class="table-responsive" >
<table class="table table-condensed">
<thead>
......@@ -198,9 +230,6 @@ include("head.inc");
</table>
</div>
</div>
<div class="col-xs-12">
<p><?=gettext("Note:"); ?> <?=sprintf(gettext('The %sAdobe SVG Viewer%s, Firefox 1.5 or later or other browser supporting SVG is required to view the graph.'),'<a href="http://www.adobe.com/svg/viewer/install/" target="_blank">','</a>'); ?></p>
</div>
</div>
</section>
</div>
......
<?php
/*
Copyright (C) 2016 Deciso B.V.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
/*
Simple wrapper to retrieve data for widgets using legacy code.
Returns a json object containing a list of available plugins and for all requested plugins (parameter load) the
collected data.
*/
header("Last-Modified: " . gmdate( "D, j M Y H:i:s" ) . " GMT" );
header("Expires: " . gmdate( "D, j M Y H:i:s", time() ) . " GMT" );
header("Cache-Control: no-store, no-cache, must-revalidate" );
header("Cache-Control: post-check=0, pre-check=0", FALSE);
header("Pragma: no-cache");
require_once("guiconfig.inc");
// require legacy scripts, so plugins don't have to load them
require_once("system.inc");
require_once("config.inc");
require_once("filter.inc");
require_once("pfsense-utils.inc");
require_once("interfaces.inc");
// parse request, load parameter contains all plugins that should be loaded for this request
if (!empty($_REQUEST['load'])) {
$loadPluginsList = explode(',', $_REQUEST['load']);
} else {
$loadPluginsList = array();
}
// add metadata
$result['system'] = $g['product_name'];
// available plugins
$result['plugins'] = array();
// collected data
$result['data'] = array();
// probe plugins
foreach (glob(__DIR__."/plugins/*.inc") as $filename) {
$pluginName = basename($filename, '.inc');
$result['plugins'][] = $pluginName;
if (in_array($pluginName, $loadPluginsList)) {
require $filename;
$pluginFunctionName = $pluginName."_api";
if (function_exists($pluginName."_api")) {
$result['data'][$pluginName] = $pluginFunctionName();
}
}
}
// output result
legacy_html_escape_form_data($result);
echo json_encode($result);
<?php
/*
Copyright (C) 2016 Deciso B.V.
Copyright (C) 2004-2014 by Electric Sheep Fencing LLC
Copyright (C) 2005-2006 Scott Ullrich <sullrich@gmail.com>
All rights reserved.
Redistribution and use in source and binary forms, with or without
......@@ -28,67 +25,45 @@
POSSIBILITY OF SUCH DAMAGE.
*/
require_once('guiconfig.inc');
require_once('interfaces.inc');
require_once('pfsense-utils.inc');
//get interface IP and break up into an array
$real_interface = get_real_interface($_GET['if']);
if (!does_interface_exist($real_interface)) {
echo gettext("Wrong Interface");
exit;
} elseif (!empty($_GET['act']) && $_GET['act'] == "top") {
//
// find top bandwitdh users
// (parts copied from bandwidth_by_ip.php)
//
//get interface subnet
$netmask = find_interface_subnet($real_interface);
$intsubnet = gen_subnet(find_interface_ip($real_interface), $netmask) . "/$netmask";
$cmd_args = "";
switch (!empty($_GET['filter']) ? $_GET['filter'] : "") {
case "local":
$cmd_args .= " -c " . $intsubnet . " ";
break;
case "remote":
default:
$cmd_args .= " -lc 0.0.0.0/0 ";
break;
}
if (!empty($_GET['sort']) && $_GET['sort'] == "out") {
$cmd_args .= " -T ";
} else {
$cmd_args .= " -R ";
}
$listedIPs = array();
$cmd_action = "/usr/local/bin/rate -i {$real_interface} -nlq 1 -Aba 20 {$cmd_args} | tr \"|\" \" \" | awk '{ printf \"%s:%s:%s:%s:%s\\n\", $1, $2, $4, $6, $8 }'";
exec($cmd_action, $listedIPs);
/**
* widget gateway data
*/
function gateway_api()
{
$result = array();
for ($idx = 2 ; $idx < count($listedIPs) ; ++$idx) {
$fields = explode(':', $listedIPs[$idx]);
if (!empty($_GET['hostipformat'])) {
$addrdata = gethostbyaddr($fields[0]);
if ($_GET['hostipformat'] == 'hostname' && $addrdata != $fields[0]){
$addrdata = explode(".", $addrdata)[0];
$gateways_status = return_gateways_status(true);
foreach(return_gateways_array() as $gname => $gw) {
$gatewayItem = array("name" => $gname);
if (!empty($gateways_status[$gname])) {
$gatewayItem['address'] = lookup_gateway_ip_by_name($gname);
$gatewayItem['status'] = strtolower($gateways_status[$gname]['status']);
$gatewayItem['loss'] = $gateways_status[$gname]['loss'];
$gatewayItem['delay'] = $gateways_status[$gname]['delay'];
switch ($gatewayItem['status']) {
case "none":
$gatewayItem['status_translated'] = gettext("Online");
break;
case "down":
$gatewayItem['status_translated'] = gettext("Offline");
break;
case "delay":
$gatewayItem['status_translated'] = gettext("Latency");
break;
case "loss":
$gatewayItem['status_translated'] = gettext("Packetloss");
break;
default:
$gatewayItem['status_translated'] = gettext("Pending");
break;
}
} else {
$addrdata = $fields[0];
$gatewayItem['address'] = "";
$gatewayItem['status'] = "~";
$gatewayItem['status_translated'] = gettext("Unknown");
$gatewayItem['loss'] = "~";
$gatewayItem['delay'] = "unknown";
}
$result[] = array('host' => $addrdata, 'in' => $fields[1], 'out' => $fields[2]);
$result[] = $gatewayItem;
}
// return json traffic
echo json_encode($result);
} else {
// collect interface statistics
// original source ifstats.php
$ifinfo = legacy_interface_stats($real_interface);
$temp = gettimeofday();
$timing = (double)$temp["sec"] + (double)$temp["usec"] / 1000000.0;
echo "$timing|" . $ifinfo['bytes received'] . "|" . $ifinfo['bytes transmitted'] . "\n";
return $result;
}
exit;
<?php
/*
Copyright (C) 2016 Deciso B.V.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
/**
* widget interfaces data
*/
function interfaces_api()
{
$result = array();
foreach (get_configured_interface_with_descr() as $ifdescr => $ifname) {
$ifinfo = get_interface_info($ifdescr);
$interfaceItem = array();
$interfaceItem['inpkts'] = $ifinfo['inpkts'];
$interfaceItem['outpkts'] = $ifinfo['outpkts'];
$interfaceItem['inbytes'] = $ifinfo['inbytes'];
$interfaceItem['outbytes'] = $ifinfo['outbytes'];
$interfaceItem['inbytes_frmt'] = format_bytes($ifinfo['inbytes']);
$interfaceItem['outbytes_frmt'] = format_bytes($ifinfo['outbytes']);
$interfaceItem['inerrs'] = isset($ifinfo['inerrs']) ? $ifinfo['inerrs'] : "0";
$interfaceItem['outerrs'] = isset($ifinfo['outerrs']) ? $ifinfo['outerrs'] : "0";
$interfaceItem['collisions'] = isset($ifinfo['collisions']) ? $ifinfo['collisions'] : "0";
$interfaceItem['name'] = $ifname;
if ($ifinfo['status'] == "up" || $ifinfo['status'] == "associated") {
$interfaceItem['status'] = "up";
} elseif ($ifinfo['status'] == "no carrier") {
$interfaceItem['status'] = "down";
} elseif ($ifinfo['status'] == "down") {
$interfaceItem['status'] = "block";
} else {
$interfaceItem['status'] = "";
}
$interfaceItem['ipaddr'] = empty($ifinfo['ipaddr']) ? "" : $ifinfo['ipaddr'];
$interfaceItem['media'] = empty($ifinfo['media']) ? "" : $ifinfo['media'];
$result[] = $interfaceItem;
}
return $result;
}
<?php
/*
Copyright (C) 2016 Deciso B.V.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
function system_api_cpu_stats()
{
$cpustats = array();
// take a short snapshot to calculate cpu usage
$diff = array('user', 'nice', 'sys', 'intr', 'idle');
$cpuTicks1 = array_combine($diff, explode(" ", get_single_sysctl('kern.cp_time')));
usleep(100000);
$cpuTicks2 = array_combine($diff, explode(" ", get_single_sysctl('kern.cp_time')));
$totalStart = array_sum($cpuTicks1);
$totalEnd = array_sum($cpuTicks2);
if ($totalEnd <= $totalStart) {
// if for some reason the measurement is invalid, assume nothing has changed (all 0)
$totalEnd = $totalStart;
}
$cpustats['used'] = floor(100 * (($totalEnd - $totalStart) - ($cpuTicks2['idle'] - $cpuTicks1['idle'])) / ($totalEnd - $totalStart));
$cpustats['user'] = floor(100 * (($cpuTicks2['user'] - $cpuTicks1['user'])) / ($totalEnd - $totalStart));
$cpustats['nice'] = floor(100 * (($cpuTicks2['nice'] - $cpuTicks1['nice'])) / ($totalEnd - $totalStart));
$cpustats['sys'] = floor(100 * (($cpuTicks2['sys'] - $cpuTicks1['sys'])) / ($totalEnd - $totalStart));
$cpustats['intr'] = floor(100 * (($cpuTicks2['intr'] - $cpuTicks1['intr'])) / ($totalEnd - $totalStart));
$cpustats['idle'] = floor(100 * (($cpuTicks2['idle'] - $cpuTicks1['idle'])) / ($totalEnd - $totalStart));
// cpu model and count
$cpustats['model'] = get_single_sysctl("hw.model");
$cpustats['cpus'] = get_single_sysctl('kern.smp.cpus');
// cpu frequency
$tmp = get_single_sysctl('dev.cpu.0.freq_levels');
$cpustats['max.freq'] = !empty($tmp) ? explode("/", explode(" ", $tmp)[0])[0] : "-";
$tmp = get_single_sysctl('dev.cpu.0.freq');
$cpustats['cur.freq'] = !empty($tmp) ? $tmp : "-";
$cpustats['freq_translate'] = sprintf(gettext("Current: %s MHz, Max: %s MHz"), $cpustats['cur.freq'], $cpustats['max.freq']);
// system load
exec("/usr/bin/uptime | /usr/bin/sed 's/^.*: //'", $load_average);
$cpustats['load'] = explode(',', $load_average[0]);
return $cpustats;
}
function system_api_config()
{
global $config;
$result = array();
$result['last_change'] = isset($config['revision']['time']) ? intval($config['revision']['time']) : 0;
$result['last_change_frmt'] = date("D M j G:i:s T Y", $result['last_change']);
return $result;
}
function system_api_kernel()
{
global $config;
$result = array();
$result['pf'] = array();
$result['pf']['maxstates'] = !empty($config['system']['maximumstates']) ? $config['system']['maximumstates'] : default_state_size();
exec('/sbin/pfctl -si |grep "current entries" 2>/dev/null', $states);
$result['pf']['states'] = count($states) > 0 ? filter_var($states[0], FILTER_SANITIZE_NUMBER_INT) : 0;
$result['mbuf'] = array();
exec('/usr/bin/netstat -mb | /usr/bin/grep "mbuf clusters in use"', $mbufs);
$result['mbuf']['total'] = count($mbufs) > 0 ? explode('/', $mbufs[0])[2] : 0;
$result['mbuf']['max'] = count($mbufs) > 0 ? explode(' ', explode('/', $mbufs[0])[3])[0] : 0;
$totalMem = get_single_sysctl("vm.stats.vm.v_page_count");
$inactiveMem = get_single_sysctl("vm.stats.vm.v_inactive_count");
$cachedMem = get_single_sysctl("vm.stats.vm.v_cache_count");
$freeMem = get_single_sysctl("vm.stats.vm.v_free_count");
$result['memory']['total'] = get_single_sysctl('hw.physmem') ;
$result['memory']['used'] = round(((($totalMem - ($inactiveMem + $cachedMem + $freeMem))) / $totalMem)*$result['memory']['total'], 0);
return $result;
}
function system_api_disk()
{
$result = array();
$result['swap'] = array();
$result['swap']['device'] = null;
$result['swap']['total'] = null;
$result['swap']['used'] = null;
exec("/usr/sbin/swapinfo -k", $swap_info);
foreach ($swap_info as $line) {
if (strpos($line,'/dev/') !== false) {
$parts = preg_split('/\s+/', $line);
$result['swap']['device'] = $parts[0];
$result['swap']['total'] = $parts[1];
$result['swap']['used'] = $parts[2];
}
}
$result['devices'] = array();
exec("/bin/df -Tht ufs,tmpfs,zfs,cd9660", $disk_info);
foreach ($disk_info as $line) {
if (strpos($line,'Mounted on') === false) {
$parts = preg_split('/\s+/', $line);
$diskItem = array();
$diskItem['device'] = $parts[0];
$diskItem['type'] = $parts[1];
$diskItem['size'] = $parts[2];
$diskItem['used'] = $parts[3];
$diskItem['available'] = $parts[4];
$diskItem['capacity'] = $parts[5];
$diskItem['mountpoint'] = $parts[6];
$result['devices'][] = $diskItem;
}
}
return $result;
}
/**
* widget system data
*/
function system_api()
{
$result = array();
$result['cpu'] = system_api_cpu_stats();
preg_match("/sec = (\d+)/", get_single_sysctl("kern.boottime"), $matches);
$result['uptime'] = time() - $matches[1];
$result['date_frmt'] = date("D M j G:i:s T Y");
$result['config'] = system_api_config();
$result['kernel'] = system_api_kernel();
$result['disk'] = system_api_disk();
return $result;
}
<?php
/*
Copyright (C) 2016 Deciso B.V.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
/**
* widget temperature data
*/
function temperature_api()
{
$result = array();
exec("/sbin/sysctl -a | grep temperature", $sysctlOutput);
foreach ($sysctlOutput as $sysctl) {
$parts = explode(':', $sysctl);
if (count($parts) >= 2) {
$tempItem = array();
$tempItem['device'] = $parts[0];
$tempItem['device_seq'] = filter_var($tempItem['device'], FILTER_SANITIZE_NUMBER_INT);
$tempItem['temperature'] = trim(str_replace('C', '', $parts[1]));
$tempItem['type'] = strpos($tempItem['device'], 'hw.acpi') !== false ? "zone" : "core";
$tempItem['type_translated'] = $tempItem['type'] == "zone" ? gettext("Zone") : gettext("Core");
$result[] = $tempItem;
}
}
usort($result, function ($item1, $item2) {
return strcmp(strtolower($item1['device']), strtolower($item2['device']));
});
return $result;
}
<?php
/*
Copyright (C) 2014-2015 Deciso B.V.
Copyright (C) 2009 Bill Marquette
Copyright (C) 2016 Deciso B.V.
All rights reserved.
Redistribution and use in source and binary forms, with or without
......@@ -27,14 +25,21 @@
POSSIBILITY OF SUCH DAMAGE.
*/
header("Last-Modified: " . gmdate( "D, j M Y H:i:s" ) . " GMT" );
header("Expires: " . gmdate( "D, j M Y H:i:s", time() ) . " GMT" );
header("Cache-Control: no-store, no-cache, must-revalidate" ); // HTTP/1.1
header("Cache-Control: post-check=0, pre-check=0", FALSE );
header("Pragma: no-cache"); // HTTP/1.0
require_once("guiconfig.inc");
require_once("system.inc");
require_once("stats.inc");
echo get_stats();
function traffic_api()
{
global $config;
$result = array();
$result['interfaces'] = legacy_interface_stats();
$temp = gettimeofday();
$result['time'] = (double)$temp["sec"] + (double)$temp["usec"] / 1000000.0;
// collect user friendly interface names
foreach (legacy_config_get_interfaces(array("virtual" => false)) as $interfaceKey => $interfaceData) {
if (array_key_exists($interfaceData['if'], $result['interfaces'])) {
$result['interfaces'][$interfaceData['if']]['name'] = !empty($interfaceData['descr']) ? $interfaceData['descr'] : $interfaceKey;
}
}
if (!empty($result['interfaces']['enc0'])) {
$result['interfaces']['enc0']['name'] = "IPsec";
}
return $result;
}
<?php
/*
$Id: thermal_sensors.inc
File location:
\usr\local\www\widgets\include\
Used by:
\usr\local\www\widgets\widgets\thermal_sensors.widget.php
*/
//set variable for custom title
$thermal_sensors_widget_title = "Thermal Sensors";
//$thermal_sensors_widget_link = "thermal_sensors.php";
//returns core temp data (from coretemp.ko or amdtemp.ko driver) as "|"-delimited string.
//NOTE: depends on proper cofing in System >> Advanced >> Miscellaneous tab >> Thermal Sensors section.
function getThermalSensorsData()
{
$_gb = exec("/sbin/sysctl -a | grep temperature", $dfout);
$thermalSensorsData = join("|", $dfout);
return $thermalSensorsData;
}
function updateIpsec(){
selectIntLink = "ipsecDetailed";
ipsecsettings = "ipsecDetail=";
ipsecsettings += d.getElementById(selectIntLink).checked;
selectIntLink = "ipsec-config";
textlink = d.getElementById(selectIntLink);
textlink.value = ipsecsettings;
}
This diff is collapsed.
function trafficshowDiv(incDiv,swapButtons){
//appear element
selectedDiv = incDiv + "graphdiv";
jQuery('#' + selectedDiv).show();
d = document;
if (swapButtons){
selectIntLink = selectedDiv + "-min";
textlink = d.getElementById(selectIntLink);
textlink.style.display = "inline";
selectIntLink = selectedDiv + "-open";
textlink = d.getElementById(selectIntLink);
textlink.style.display = "none";
}
document.iform["shown[" + incDiv + "]"].value = "show";
}
function trafficminimizeDiv(incDiv,swapButtons){
//fade element
selectedDiv = incDiv + "graphdiv";
jQuery('#' + selectedDiv).hide();
d = document;
if (swapButtons){
selectIntLink = selectedDiv + "-open";
textlink = d.getElementById(selectIntLink);
textlink.style.display = "inline";
selectIntLink = selectedDiv + "-min";
textlink = d.getElementById(selectIntLink);
textlink.style.display = "none";
}
document.iform["shown[" + incDiv + "]"].value = "hide";
}
<?php
/*
Copyright (C) 2014 Deciso B.V.
Copyright (C) 2014-2016 Deciso B.V.
Copyright (C) 2007 Sam Wenham
All rights reserved.
......@@ -27,61 +27,60 @@
POSSIBILITY OF SUCH DAMAGE.
*/
$nocsrf = true;
require_once("guiconfig.inc");
require_once("pfsense-utils.inc");
require_once("interfaces.inc");
require_once("widgets/include/carp_status.inc");
$carp_enabled = (get_single_sysctl('net.inet.carp.allow') > 0);
if (!isset($config['virtualip']['vip'])) {
$config['virtualip']['vip'] = array();
}
?>
<table class="table table-striped" width="100%" border="0" cellspacing="0" cellpadding="0" summary="carp status">
<table class="table table-striped table-condensed">
<?php
if (isset($config['virtualip']['vip'])) {
$carpint=0;
foreach ($config['virtualip']['vip'] as $carp) {
foreach ($config['virtualip']['vip'] as $carp):
if ($carp['mode'] != "carp") {
continue;
}
$ipaddress = $carp['subnet'];
$password = $carp['password'];
$netmask = $carp['subnet_bits'];
$vhid = $carp['vhid'];
$advskew = $carp['advskew'];
$status = get_carp_interface_status("{$carp['interface']}_vip{$vhid}");
?>
<tr>
<td class="vncellt" width="35%">
<span alt="cablenic" class="glyphicon glyphicon-transfer text-success"></span>&nbsp;
<strong><a href="/system_hasync.php">
<span><?=htmlspecialchars(convert_friendly_interface_to_friendly_descr($carp['interface']) . "@{$vhid}");?></span></a></strong>
</td>
<td width="65%" class="listr">
$status = get_carp_interface_status("{$carp['interface']}_vip{$carp['vhid']}");?>
<tr>
<td>
<span class="glyphicon glyphicon-transfer text-success"></span>&nbsp;
<strong>
<a href="/system_hasync.php">
<span><?=htmlspecialchars(convert_friendly_interface_to_friendly_descr($carp['interface']) . "@{$carp['vhid']}");?></span>
</a>
</strong>
</td>
<td>
<?php
if ($carp_enabled == false) {
$status = gettext("DISABLED");
echo "<span class=\"glyphicon glyphicon-remove text-danger\" title=\"$status\" alt=\"$status\" ></span>";
} else {
if ($status == gettext("MASTER")) {
echo "<span class=\"glyphicon glyphicon-play text-success\" title=\"$status\" alt=\"$status\" ></span>";
} elseif ($status == gettext("BACKUP")) {
echo "<span class=\"glyphicon glyphicon-play text-muted\" title=\"$status\" alt=\"$status\" ></span>";
} elseif ($status == gettext("INIT")) {
echo "<span class=\"glyphicon glyphicon-info-sign\" title=\"$status\" alt=\"$status\" ></span>";
}
}
if ($ipaddress) {
?> &nbsp;
if (get_single_sysctl('net.inet.carp.allow') <= 0 ) {
$status = gettext("DISABLED");
echo "<span class=\"glyphicon glyphicon-remove text-danger\" title=\"$status\" alt=\"$status\" ></span>";
} elseif ($status == gettext("MASTER")) {
echo "<span class=\"glyphicon glyphicon-play text-success\" title=\"$status\" alt=\"$status\" ></span>";
} elseif ($status == gettext("BACKUP")) {
echo "<span class=\"glyphicon glyphicon-play text-muted\" title=\"$status\" alt=\"$status\" ></span>";
} elseif ($status == gettext("INIT")) {
echo "<span class=\"glyphicon glyphicon-info-sign\" title=\"$status\" alt=\"$status\" ></span>";
}
if (!empty($carp['subnet'])):?>
&nbsp;
<?=htmlspecialchars($status);?> &nbsp;
<?=htmlspecialchars($ipaddress);
}?>
</td></tr><?php
}
} else {
?>
<tr><td class="listr"><?= sprintf(gettext('No CARP Interfaces Defined. Click %shere%s to configure CARP.'), '<a href="carp_status.php">', '</a>'); ?></td></tr>
<?=htmlspecialchars($carp['subnet']);?>
<?php
endif;?>
</td>
</tr>
<?php
endforeach;
if (count($config['virtualip']['vip']) == 0):?>
<tr>
<td>
<?= sprintf(gettext('No CARP Interfaces Defined. Click %shere%s to configure CARP.'), '<a href="carp_status.php">', '</a>'); ?>
</td>
</tr>
<?php
} ?>
endif;?>
</table>
<?php
/*
Copyright (C) 2014 Deciso B.V.
Copyright (C) 2014-2016 Deciso B.V.
Copyright (C) 2008 Ermal Luci
Copyright (C) 2013 Stanley P. Miller \ stan-qaz
All rights reserved.
......@@ -28,8 +28,6 @@
POSSIBILITY OF SUCH DAMAGE.
*/
$nocsrf = true;
require_once("guiconfig.inc");
require_once("pfsense-utils.inc");
require_once("widgets/include/dyn_dns_status.inc");
......@@ -42,7 +40,7 @@ if (!isset($config['dyndnses']['dyndns'])) {
$a_dyndns = &$config['dyndnses']['dyndns'];
if ($_REQUEST['getdyndnsstatus']) {
if (!empty($_REQUEST['getdyndnsstatus'])) {
$first_entry = true;
foreach ($a_dyndns as $dyndns) {
if ($first_entry) {
......@@ -85,18 +83,24 @@ if ($_REQUEST['getdyndnsstatus']) {
?>
<table class="table table-triped" width="100%" border="0" cellpadding="0" cellspacing="0">
<tr>
<td width="5%" class="listhdrr"><b><?=gettext("Int.");?></b></td>
<td width="15%" class="listhdrr"><b><?=gettext("Service");?></b></td>
<td width="20%" class="listhdrr"><b><?=gettext("Hostname");?></b></td>
<td width="20%" class="listhdrr"><b><?=gettext("Cached IP");?></b></td>
</tr>
<?php $i = 0; foreach ($a_dyndns as $dyndns) :
?>
<tr ondblclick="document.location='services_dyndns_edit.php?id=<?=$i;?>'">
<td class="listlr">
<?php $iflist = get_configured_interface_with_descr();
<table class="table table-striped table-condensed">
<thead>
<tr>
<th><?=gettext("Int.");?></th>
<th><?=gettext("Service");?></th>
<th><?=gettext("Hostname");?></th>
<th><?=gettext("Cached IP");?></th>
</tr>
</thead>
<tbody>
<?php
$iflist = get_configured_interface_with_descr();
$types = services_dyndns_list();
$groupslist = return_gateway_groups_array();
foreach ($a_dyndns as $i => $dyndns) :?>
<tr ondblclick="document.location='services_dyndns_edit.php?id=<?=$i;?>'">
<td>
<?php
foreach ($iflist as $if => $ifdesc) {
if ($dyndns['interface'] == $if) {
if (!isset($dyndns['enable'])) {
......@@ -107,7 +111,6 @@ if ($_REQUEST['getdyndnsstatus']) {
break;
}
}
$groupslist = return_gateway_groups_array();
foreach ($groupslist as $if => $group) {
if ($dyndns['interface'] == $if) {
if (!isset($dyndns['enable'])) {
......@@ -117,12 +120,10 @@ if ($_REQUEST['getdyndnsstatus']) {
}
break;
}
}
?>
</td>
<td class="listr">
<?php
$types = services_dyndns_list();
}?>
</td>
<td>
<?php
if (isset($types[$dyndns['type']])) {
if (!isset($dyndns['enable'])) {
echo '<span class="text-muted">' . htmlspecialchars($types[$dyndns['type']]) . '</span>';
......@@ -130,51 +131,46 @@ if ($_REQUEST['getdyndnsstatus']) {
echo htmlspecialchars($types[$dyndns['type']]);
}
}
?>
</td>
<td class="listr">
<?php
?>
</td>
<td>
<?php
if (!isset($dyndns['enable'])) {
echo "<span class=\"text-muted\">".htmlspecialchars($dyndns['host'])."</span>";
} else {
echo htmlspecialchars($dyndns['host']);
}
?>
</td>
<td class="listr">
<div id='dyndnsstatus<?php echo $i; ?>'><?php echo gettext("Checking ..."); ?></div>
</td>
</tr>
<?php $i++;
endforeach; ?>
?>
</td>
<td>
<div id='dyndnsstatus<?=$i;?>'><?=gettext("Checking ...");?></div>
</td>
</tr>
<?php
endforeach;?>
</tbody>
</table>
<script type="text/javascript">
//<![CDATA[
function dyndns_getstatus() {
scroll(0,0);
var url = "/widgets/widgets/dyn_dns_status.widget.php";
var pars = 'getdyndnsstatus=yes';
jQuery.ajax(
url,
{
type: 'get',
data: pars,
complete: dyndnscallback
});
// Refresh the status every 5 minutes
setTimeout('dyndns_getstatus()', 5*60*1000);
}
function dyndnscallback(transport) {
// The server returns a string of statuses separated by vertical bars
var responseStrings = transport.responseText.split("|");
for (var count=0; count<responseStrings.length; count++)
{
var divlabel = '#dyndnsstatus' + count;
jQuery(divlabel).prop('innerHTML',responseStrings[count]);
}
}
// Do the first status check 2 seconds after the dashboard opens
setTimeout('dyndns_getstatus()', 2000);
//]]>
function dyndns_getstatus()
{
scroll(0,0);
var url = "/widgets/widgets/dyn_dns_status.widget.php";
var pars = 'getdyndnsstatus=yes';
jQuery.ajax(url, {type: 'get', data: pars, complete: dyndnscallback});
// Refresh the status every 5 minutes
setTimeout('dyndns_getstatus()', 5*60*1000);
}
function dyndnscallback(transport)
{
// The server returns a string of statuses separated by vertical bars
var responseStrings = transport.responseText.split("|");
for (var count=0; count<responseStrings.length; count++) {
var divlabel = '#dyndnsstatus' + count;
jQuery(divlabel).prop('innerHTML',responseStrings[count]);
}
}
$( document ).ready(function() {
// Do the first status check 2 seconds after the dashboard opens
setTimeout('dyndns_getstatus()', 2000);
});
</script>
<?php
/*
Copyright (C) 2014 Deciso B.V.
Copyright (C) 2008 Seth Mos
Copyright (C) 2014-2016 Deciso B.V.
Copyright (C) 2008 Seth Mos
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
$nocsrf = true;
require_once("guiconfig.inc");
require_once("pfsense-utils.inc");
require_once("widgets/include/gateways.inc");
$a_gateways = return_gateways_array();
$gateways_status = array();
$gateways_status = return_gateways_status(true);
$counter = 1;
?>
<table class="table table-striped" width="100%" border="0" cellspacing="0" cellpadding="0" summary="gateway status">
<tr>
<td id="gatewayname" align="center"><b><?php echo gettext('Name')?></b></td>
<td align="center"><b><?php echo gettext('RTT')?></b></td>
<td align="center"><b><?php echo gettext('Loss')?></b></td>
<td align="center"><b><?php echo gettext('Status')?></b></td>
</tr>
<?php foreach ($a_gateways as $gname => $gateway) {
?>
<tr>
<td class="h6" id="gateway<?php echo $counter; ?>" rowspan="2" align="center">
<strong>
<?php echo htmlspecialchars($gateway['name']); ?>
</strong>
<?php $counter++; ?>
</td>
<td colspan="3" align="left">
<div class="h6" id="gateway<?php echo $counter; ?>" style="display:inline">
<?php
$if_gw = '';
if (is_ipaddr($gateway['gateway'])) {
$if_gw = htmlspecialchars($gateway['gateway']);
} else {
if ($gateway['ipprotocol'] == "inet") {
$if_gw = htmlspecialchars(get_interface_gateway($gateway['friendlyiface']));
}
if ($gateway['ipprotocol'] == "inet6") {
$if_gw = htmlspecialchars(get_interface_gateway_v6($gateway['friendlyiface']));
}
}
echo ($if_gw == '' ? '~' : $if_gw);
unset ($if_gw);
$counter++;
?>
</div>
</td>
</tr>
<tr>
<td align="center" id="gateway<?php echo $counter; ?>">
<?php
if ($gateways_status[$gname]) {
echo htmlspecialchars($gateways_status[$gname]['delay']);
} else {
echo gettext("Pending");
}
?>
<?php $counter++; ?>
</td>
<td align="center" id="gateway<?php echo $counter; ?>">
<?php
if ($gateways_status[$gname]) {
echo htmlspecialchars($gateways_status[$gname]['loss']);
} else {
echo gettext("Pending");
}
?>
<?php $counter++; ?>
</td>
<?php
if ($gateways_status[$gname]) {
if (stristr($gateways_status[$gname]['status'], "force_down")) {
$online = "Offline (forced)";
$class="danger";
} elseif (stristr($gateways_status[$gname]['status'], "down")) {
$online = "Offline";
$class="danger";
} elseif (stristr($gateways_status[$gname]['status'], "loss")) {
$online = "Packetloss";
$class="warning";
} elseif (stristr($gateways_status[$gname]['status'], "delay")) {
$online = "Latency";
$class="warning";
} elseif ($gateways_status[$gname]['status'] == "none") {
$online = "Online";
$class="success";
} elseif ($gateways_status[$gname]['status'] == "") {
$online = "Pending";
$class="info";
}
} else {
$online = gettext("Unknown");
$class="info";
}
echo "<td class=\"$class\" align=\"center\">$online</td>\n";
$counter++;
?>
</tr>
<?php
} // foreach ?>
<script type="text/javascript">
function gateways_widget_update(sender, data)
{
var tbody = sender.find('tbody');
data.map(function(gateway) {
var tr_content = [];
var tr_id = "gateways_widget_gw_" + gateway['name'];
if (tbody.find("#"+tr_id).length == 0) {
// add new gateway
tr_content.push('<tr id="'+tr_id+'">');
tr_content.push('<td><strong>'+gateway['name']+'</strong><br/><small>'+gateway['address']+'<small></td>');
tr_content.push('<td>'+gateway['delay']+'</td>');
tr_content.push('<td>'+gateway['loss']+'</td>');
tr_content.push('<td><div class="" style="width:150px;">'+gateway['status_translated']+'</div></td>');
tr_content.push('</tr>');
tbody.append(tr_content.join(''));
} else {
// update existing gateway
$("#"+tr_id+" > td:eq(2)").html(gateway['loss']);
$("#"+tr_id+" > td:eq(1)").html(gateway['delay']);
}
// set color on status text
switch (gateway['status']) {
case 'force_down':
status_color = 'danger';
break;
case 'down':
status_color = 'danger';
break;
case 'loss':
status_color = 'warning';
break;
case 'delay':
status_color = 'warning';
break;
case 'none':
status_color = 'success';
break;
default:
status_color = 'info';
}
$("#"+tr_id+" > td:eq(3) > div").removeClass().addClass('bg-'+status_color);
});
}
</script>
<!-- gateway table -->
<table class="table table-striped table-condensed" data-plugin="gateway" data-callback="gateways_widget_update">
<thead>
<tr>
<th><?=gettext('Name')?></th>
<th><?=gettext('RTT')?></th>
<th><?=gettext('Loss')?></th>
<th style="width:160px;"><?=gettext('Status')?></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
This diff is collapsed.
......@@ -30,8 +30,6 @@
POSSIBILITY OF SUCH DAMAGE.
*/
$nocsrf = true;
require_once("guiconfig.inc");
require_once("pfsense-utils.inc");
require_once("interfaces.inc");
......@@ -192,7 +190,6 @@ function format_log_line(row) {
</script>
<script src="/javascript/filter_log.js" type="text/javascript"></script>
<input type="hidden" id="log-config" name="log-config" value="" />
<div id="log-settings" class="widgetconfigdiv" style="display:none;">
<form action="/widgets/widgets/log.widget.php" method="post" name="iforma">
<table class="table table-striped">
......@@ -325,8 +322,6 @@ endforeach;
<!-- needed to display the widget settings menu -->
<script type="text/javascript">
//<![CDATA[
selectIntLink = "log-configure";
textlink = document.getElementById(selectIntLink);
textlink.style.display = "inline";
$("#log-configure").removeClass("disabled");
//]]>
</script>
This diff is collapsed.
This diff is collapsed.
......@@ -26,8 +26,6 @@
POSSIBILITY OF SUCH DAMAGE.
*/
$nocsrf = true;
require_once("guiconfig.inc");
require_once("pfsense-utils.inc");
require_once("simplepie/autoloader.php");
......@@ -80,11 +78,9 @@ if (!empty($config['widgets']['rsswidgettextlength']) && is_numeric($config['wid
}
?>
<input type="hidden" id="rss-config" name="rss-config" value="" />
<div id="rss-settings" class="widgetconfigdiv" style="display:none;">
<form action="/widgets/widgets/rss.widget.php" method="post" name="iformc">
<table class="table table-striped" summary="rss widget">
<table class="table table-striped">
<tr>
<td colspan="2">
<textarea name="rssfeed" class="formfld unknown textarea_widget" id="rssfeed" cols="40" rows="3" style="max-width:100%;"><?=$textarea_txt;?></textarea>
......@@ -174,8 +170,6 @@ if (!empty($config['widgets']['rsswidgettextlength']) && is_numeric($config['wid
<!-- needed to display the widget settings menu -->
<script type="text/javascript">
//<![CDATA[
selectIntLink = "rss-configure";
textlink = document.getElementById(selectIntLink);
textlink.style.display = "inline";
$("#rss-configure").removeClass("disabled");
//]]>
</script>
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment