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
<?php
require_once("config.inc");
require_once("filter.inc");
require_once("pfsense-utils.inc");
require_once("interfaces.inc");
function get_uptime_sec()
{
$boottime = "";
$matches = "";
$boottime = get_single_sysctl("kern.boottime");
preg_match("/sec = (\d+)/", $boottime, $matches);
$boottime = $matches[1];
if (intval($boottime) == 0) {
return 0;
}
$uptime = time() - $boottime;
return $uptime;
}
function get_stats()
{
$stats['cpu'] = cpu_usage();
$stats['mem'] = mem_usage();
$stats['uptime'] = get_uptime();
$stats['states'] = get_pfstate();
$stats['temp'] = get_temp();
$stats['datetime'] = update_date_time();
$stats['interfacestatistics'] = get_interfacestats();
$stats['interfacestatus'] = get_interfacestatus();
$stats['gateways'] = get_gatewaystats();
$stats['cpufreq'] = get_cpufreq();
$stats['load_average'] = get_load_average();
$stats['mbuf'] = get_mbuf();
$stats['mbufpercent'] = get_mbuf(true);
$stats['statepercent'] = get_pfstate(true);
$stats = join("|", $stats);
return $stats;
}
function get_gatewaystats()
{
$a_gateways = return_gateways_array();
$gateways_status = array();
$gateways_status = return_gateways_status(true);
$data = "";
$isfirst = true;
foreach($a_gateways as $gname => $gw) {
if (!$isfirst) {
$data .= ",";
}
$isfirst = false;
$data .= $gw['name'] . ",";
if ($gateways_status[$gname]) {
$data .= lookup_gateway_ip_by_name($gname) . ",";
$gws = $gateways_status[$gname];
switch(strtolower($gws['status'])) {
case "none":
$online = "Online";
$bgcolor = "#90EE90"; // lightgreen
break;
case "down":
$online = "Offline";
$bgcolor = "#F08080"; // lightcoral
break;
case "delay":
$online = "Latency";
$bgcolor = "#F0E68C"; // khaki
break;
case "loss":
$online = "Packetloss";
$bgcolor = "#F0E68C"; // khaki
break;
default:
$online = "Pending";
break;
}
} else {
$data .= "~,";
$gws['delay'] = "~";
$gws['loss'] = "~";
$online = "Unknown";
$bgcolor = "#ADD8E6"; // lightblue
}
$data .= ($online == "Pending") ? "{$online},{$online}," : "{$gws['delay']},{$gws['loss']},";
$data .= "<table border=\"0\" cellpadding=\"0\" cellspacing=\"2\" style=\"table-layout: fixed;\" summary=\"status\"><tr><td bgcolor=\"$bgcolor\">&nbsp;$online&nbsp;</td></tr></table>";
}
return $data;
}
function get_uptime()
{
$uptime = get_uptime_sec();
if (intval($uptime) == 0) {
return;
}
$updays = (int)($uptime / 86400);
$uptime %= 86400;
$uphours = (int)($uptime / 3600);
$uptime %= 3600;
$upmins = (int)($uptime / 60);
$uptime %= 60;
$upsecs = (int)($uptime);
$uptimestr = "";
if ($updays > 1) {
$uptimestr .= "$updays Days ";
} elseif ($updays > 0) {
$uptimestr .= "1 Day ";
}
if ($uphours > 1) {
$hours = "s";
} else {
$hours = "";
}
if ($upmins > 1) {
$minutes = "s";
} else {
$minutes = "" ;
}
if ($upmins > 1) {
$seconds = "s";
} else {
$seconds = "";
}
$uptimestr .= sprintf("%02d Hour$hours %02d Minute$minutes %02d Second$seconds", $uphours, $upmins, $upsecs);
return $uptimestr;
}
/* Calculates non-idle CPU time and returns as a percentage */
function cpu_usage()
{
$duration = 1;
$diff = array('user', 'nice', 'sys', 'intr', 'idle');
$cpuTicks = array_combine($diff, explode(" ", get_single_sysctl('kern.cp_time')));
sleep($duration);
$cpuTicks2 = array_combine($diff, explode(" ", get_single_sysctl('kern.cp_time')));
$totalStart = array_sum($cpuTicks);
$totalEnd = array_sum($cpuTicks2);
// Something wrapped ?!?!
if ($totalEnd <= $totalStart) {
return 0;
}
// Calculate total cycles used
$totalUsed = ($totalEnd - $totalStart) - ($cpuTicks2['idle'] - $cpuTicks['idle']);
// Calculate the percentage used
$cpuUsage = floor(100 * ($totalUsed / ($totalEnd - $totalStart)));
return $cpuUsage;
}
function get_pfstate($percent=false)
{
global $config;
$matches = "";
if (isset($config['system']['maximumstates']) and $config['system']['maximumstates'] > 0) {
$maxstates="{$config['system']['maximumstates']}";
} else {
$maxstates=default_state_size();
}
$curentries = `/sbin/pfctl -si |grep current`;
if (preg_match("/([0-9]+)/", $curentries, $matches)) {
$curentries = $matches[1];
}
if (!is_numeric($curentries)) {
$curentries = 0;
}
if ($percent) {
if (intval($maxstates) > 0) {
return round(($curentries / $maxstates) * 100, 0);
} else {
return "NA";
}
} else {
return $curentries . "/" . $maxstates;
}
}
function get_mbuf($percent=false)
{
$mbufs_output=trim(`/usr/bin/netstat -mb | /usr/bin/grep "mbuf clusters in use" | /usr/bin/awk '{ print $1 }'`);
list( $mbufs_current, $mbufs_cache, $mbufs_total, $mbufs_max ) = explode( "/", $mbufs_output);
if ($percent) {
if ($mbufs_max > 0) {
return round(($mbufs_total / $mbufs_max) * 100, 0);
} else {
return "NA";
}
} else {
return "{$mbufs_total}/{$mbufs_max}";
}
}
function get_temp()
{
$temp_out = get_single_sysctl("dev.cpu.0.temperature");
if ($temp_out == "") {
$temp_out = get_single_sysctl("hw.acpi.thermal.tz0.temperature");
}
// Remove 'C' from the end
return rtrim($temp_out, 'C');
}
/* Get mounted filesystems and usage. Do not display entries for virtual filesystems (e.g. devfs, nullfs, unionfs) */
function get_mounted_filesystems()
{
$mout = "";
$filesystems = array();
exec("/bin/df -Tht ufs,tmpfs,zfs,cd9660 | /usr/bin/awk '{print $1, $2, $3, $4, $6, $7;}'", $mout);
/* Get rid of the header */
array_shift($mout);
foreach ($mout as $fs) {
$f = array();
list($f['device'], $f['type'], $f['total_size'], $f['used_size'], $f['percent_used'], $f['mountpoint']) = explode(' ', $fs);
/* We dont' want the trailing % sign. */
$f['percent_used'] = trim($f['percent_used'], '%');
$filesystems[] = $f;
}
return $filesystems;
}
function swap_usage()
{
exec("/usr/sbin/swapinfo", $swap_info);
$swap_used = "";
foreach ($swap_info as $line) {
if (preg_match('/(\d+)%$/', $line, $matches)) {
$swap_used = $matches[1];
break;
}
}
return $swap_used;
}
function mem_usage()
{
$totalMem = get_single_sysctl("vm.stats.vm.v_page_count");
if ($totalMem > 0) {
$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");
$usedMem = $totalMem - ($inactiveMem + $cachedMem + $freeMem);
$memUsage = round(($usedMem * 100) / $totalMem, 0);
} else {
$memUsage = "NA";
}
return $memUsage;
}
function update_date_time()
{
$datetime = date("D M j G:i:s T Y");
return $datetime;
}
function get_cpufreq()
{
$cpufreqs = "";
$out = "";
$cpufreqs = explode(" ", get_single_sysctl('dev.cpu.0.freq_levels'));
$maxfreq = explode("/", $cpufreqs[0]);
$maxfreq = $maxfreq[0];
$curfreq = "";
$curfreq = get_single_sysctl('dev.cpu.0.freq');
if (($curfreq > 0) && ($curfreq != $maxfreq)) {
$out = "Current: {$curfreq} MHz, Max: {$maxfreq} MHz";
}
return $out;
}
function get_cpu_count($show_detail = false)
{
$cpucount = get_single_sysctl('kern.smp.cpus');
if ($show_detail) {
$cpudetail = "";
exec("/usr/bin/grep 'SMP.*package.*core' /var/run/dmesg.boot | /usr/bin/cut -f2- -d' '", $cpudetail);
$cpucount = $cpudetail[0];
}
return $cpucount;
}
function get_load_average()
{
$load_average = "";
exec("/usr/bin/uptime | /usr/bin/sed 's/^.*: //'", $load_average);
return $load_average[0];
}
function get_interfacestats()
{
$ifdescrs = get_configured_interface_list();
$array_collisions = array();
$new_data = '';
foreach ($ifdescrs as $ifdescr => $ifname) {
$ifinfo = get_interface_info($ifdescr);
$new_data .= "{$ifinfo['inpkts']},";
$new_data .= "{$ifinfo['outpkts']},";
$new_data .= format_bytes($ifinfo['inbytes']) . ",";
$new_data .= format_bytes($ifinfo['outbytes']) . ",";
if (isset($ifinfo['inerrs'])){
$new_data .= "{$ifinfo['inerrs']},";
$new_data .= "{$ifinfo['outerrs']},";
} else {
$new_data .= "0,";
$new_data .= "0,";
}
if (isset($ifinfo['collisions'])) {
$new_data .= htmlspecialchars($ifinfo['collisions']) . ",";
} else {
$new_data .= "0,";
}
}
return $new_data;
}
function get_interfacestatus()
{
$ifdescrs = get_configured_interface_with_descr();
$data = '';
foreach ($ifdescrs as $ifdescr => $ifname) {
$ifinfo = get_interface_info($ifdescr);
$data .= $ifname . ",";
if ($ifinfo['status'] == "up" || $ifinfo['status'] == "associated") {
$data .= "up";
} elseif ($ifinfo['status'] == "no carrier") {
$data .= "down";
} elseif ($ifinfo['status'] == "down") {
$data .= "block";
}
$data .= ",";
if ($ifinfo['ipaddr']) {
$data .= htmlspecialchars($ifinfo['ipaddr']);
}
$data .= ",";
if ($ifinfo['status'] != "down") {
$data .= htmlspecialchars($ifinfo['media']);
}
$data .= "~";
}
return $data;
}
......@@ -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.",
......
/* ===================================================
* jquery-sortable.js v0.9.13
* http://johnny.github.com/jquery-sortable/
* ===================================================
* Copyright (c) 2012 Jonas von Andrian
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * 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.
* * The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 <COPYRIGHT HOLDER> 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 ( $, window, pluginName, undefined){
var containerDefaults = {
// If true, items can be dragged from this container
drag: true,
// If true, items can be droped onto this container
drop: true,
// Exclude items from being draggable, if the
// selector matches the item
exclude: "",
// If true, search for nested containers within an item.If you nest containers,
// either the original selector with which you call the plugin must only match the top containers,
// or you need to specify a group (see the bootstrap nav example)
nested: true,
// If true, the items are assumed to be arranged vertically
vertical: true
}, // end container defaults
groupDefaults = {
// This is executed after the placeholder has been moved.
// $closestItemOrContainer contains the closest item, the placeholder
// has been put at or the closest empty Container, the placeholder has
// been appended to.
afterMove: function ($placeholder, container, $closestItemOrContainer) {
},
// The exact css path between the container and its items, e.g. "> tbody"
containerPath: "",
// The css selector of the containers
containerSelector: "ol, ul",
// Distance the mouse has to travel to start dragging
distance: 0,
// Time in milliseconds after mousedown until dragging should start.
// This option can be used to prevent unwanted drags when clicking on an element.
delay: 0,
// The css selector of the drag handle
handle: "",
// The exact css path between the item and its subcontainers.
// It should only match the immediate items of a container.
// No item of a subcontainer should be matched. E.g. for ol>div>li the itemPath is "> div"
itemPath: "",
// The css selector of the items
itemSelector: "li",
// The class given to "body" while an item is being dragged
bodyClass: "dragging",
// The class giving to an item while being dragged
draggedClass: "dragged",
// Check if the dragged item may be inside the container.
// Use with care, since the search for a valid container entails a depth first search
// and may be quite expensive.
isValidTarget: function ($item, container) {
return true
},
// Executed before onDrop if placeholder is detached.
// This happens if pullPlaceholder is set to false and the drop occurs outside a container.
onCancel: function ($item, container, _super, event) {
},
// Executed at the beginning of a mouse move event.
// The Placeholder has not been moved yet.
onDrag: function ($item, position, _super, event) {
$item.css(position)
},
// Called after the drag has been started,
// that is the mouse button is being held down and
// the mouse is moving.
// The container is the closest initialized container.
// Therefore it might not be the container, that actually contains the item.
onDragStart: function ($item, container, _super, event) {
$item.css({
height: $item.outerHeight(),
width: $item.outerWidth()
})
$item.addClass(container.group.options.draggedClass)
$("body").addClass(container.group.options.bodyClass)
},
// Called when the mouse button is being released
onDrop: function ($item, container, _super, event) {
$item.removeClass(container.group.options.draggedClass).removeAttr("style")
$("body").removeClass(container.group.options.bodyClass)
},
// Called on mousedown. If falsy value is returned, the dragging will not start.
// Ignore if element clicked is input, select or textarea
onMousedown: function ($item, _super, event) {
if (!event.target.nodeName.match(/^(input|select|textarea)$/i)) {
event.preventDefault()
return true
}
},
// The class of the placeholder (must match placeholder option markup)
placeholderClass: "placeholder",
// Template for the placeholder. Can be any valid jQuery input
// e.g. a string, a DOM element.
// The placeholder must have the class "placeholder"
placeholder: '<li class="placeholder"></li>',
// If true, the position of the placeholder is calculated on every mousemove.
// If false, it is only calculated when the mouse is above a container.
pullPlaceholder: true,
// Specifies serialization of the container group.
// The pair $parent/$children is either container/items or item/subcontainers.
serialize: function ($parent, $children, parentIsContainer) {
var result = $.extend({}, $parent.data())
if(parentIsContainer)
return [$children]
else if ($children[0]){
result.children = $children
}
delete result.subContainers
delete result.sortable
return result
},
// Set tolerance while dragging. Positive values decrease sensitivity,
// negative values increase it.
tolerance: 0
}, // end group defaults
containerGroups = {},
groupCounter = 0,
emptyBox = {
left: 0,
top: 0,
bottom: 0,
right:0
},
eventNames = {
start: "touchstart.sortable mousedown.sortable",
drop: "touchend.sortable touchcancel.sortable mouseup.sortable",
drag: "touchmove.sortable mousemove.sortable",
scroll: "scroll.sortable"
},
subContainerKey = "subContainers"
/*
* a is Array [left, right, top, bottom]
* b is array [left, top]
*/
function d(a,b) {
var x = Math.max(0, a[0] - b[0], b[0] - a[1]),
y = Math.max(0, a[2] - b[1], b[1] - a[3])
return x+y;
}
function setDimensions(array, dimensions, tolerance, useOffset) {
var i = array.length,
offsetMethod = useOffset ? "offset" : "position"
tolerance = tolerance || 0
while(i--){
var el = array[i].el ? array[i].el : $(array[i]),
// use fitting method
pos = el[offsetMethod]()
pos.left += parseInt(el.css('margin-left'), 10)
pos.top += parseInt(el.css('margin-top'),10)
dimensions[i] = [
pos.left - tolerance,
pos.left + el.outerWidth() + tolerance,
pos.top - tolerance,
pos.top + el.outerHeight() + tolerance
]
}
}
function getRelativePosition(pointer, element) {
var offset = element.offset()
return {
left: pointer.left - offset.left,
top: pointer.top - offset.top
}
}
function sortByDistanceDesc(dimensions, pointer, lastPointer) {
pointer = [pointer.left, pointer.top]
lastPointer = lastPointer && [lastPointer.left, lastPointer.top]
var dim,
i = dimensions.length,
distances = []
while(i--){
dim = dimensions[i]
distances[i] = [i,d(dim,pointer), lastPointer && d(dim, lastPointer)]
}
distances = distances.sort(function (a,b) {
return b[1] - a[1] || b[2] - a[2] || b[0] - a[0]
})
// last entry is the closest
return distances
}
function ContainerGroup(options) {
this.options = $.extend({}, groupDefaults, options)
this.containers = []
if(!this.options.rootGroup){
this.scrollProxy = $.proxy(this.scroll, this)
this.dragProxy = $.proxy(this.drag, this)
this.dropProxy = $.proxy(this.drop, this)
this.placeholder = $(this.options.placeholder)
if(!options.isValidTarget)
this.options.isValidTarget = undefined
}
}
ContainerGroup.get = function (options) {
if(!containerGroups[options.group]) {
if(options.group === undefined)
options.group = groupCounter ++
containerGroups[options.group] = new ContainerGroup(options)
}
return containerGroups[options.group]
}
ContainerGroup.prototype = {
dragInit: function (e, itemContainer) {
this.$document = $(itemContainer.el[0].ownerDocument)
// get item to drag
var closestItem = $(e.target).closest(this.options.itemSelector);
// using the length of this item, prevents the plugin from being started if there is no handle being clicked on.
// this may also be helpful in instantiating multidrag.
if (closestItem.length) {
this.item = closestItem;
this.itemContainer = itemContainer;
if (this.item.is(this.options.exclude) || !this.options.onMousedown(this.item, groupDefaults.onMousedown, e)) {
return;
}
this.setPointer(e);
this.toggleListeners('on');
this.setupDelayTimer();
this.dragInitDone = true;
}
},
drag: function (e) {
if(!this.dragging){
if(!this.distanceMet(e) || !this.delayMet)
return
this.options.onDragStart(this.item, this.itemContainer, groupDefaults.onDragStart, e)
this.item.before(this.placeholder)
this.dragging = true
}
this.setPointer(e)
// place item under the cursor
this.options.onDrag(this.item,
getRelativePosition(this.pointer, this.item.offsetParent()),
groupDefaults.onDrag,
e)
var p = this.getPointer(e),
box = this.sameResultBox,
t = this.options.tolerance
if(!box || box.top - t > p.top || box.bottom + t < p.top || box.left - t > p.left || box.right + t < p.left)
if(!this.searchValidTarget()){
this.placeholder.detach()
this.lastAppendedItem = undefined
}
},
drop: function (e) {
this.toggleListeners('off')
this.dragInitDone = false
if(this.dragging){
// processing Drop, check if placeholder is detached
if(this.placeholder.closest("html")[0]){
this.placeholder.before(this.item).detach()
} else {
this.options.onCancel(this.item, this.itemContainer, groupDefaults.onCancel, e)
}
this.options.onDrop(this.item, this.getContainer(this.item), groupDefaults.onDrop, e)
// cleanup
this.clearDimensions()
this.clearOffsetParent()
this.lastAppendedItem = this.sameResultBox = undefined
this.dragging = false
}
},
searchValidTarget: function (pointer, lastPointer) {
if(!pointer){
pointer = this.relativePointer || this.pointer
lastPointer = this.lastRelativePointer || this.lastPointer
}
var distances = sortByDistanceDesc(this.getContainerDimensions(),
pointer,
lastPointer),
i = distances.length
while(i--){
var index = distances[i][0],
distance = distances[i][1]
if(!distance || this.options.pullPlaceholder){
var container = this.containers[index]
if(!container.disabled){
if(!this.$getOffsetParent()){
var offsetParent = container.getItemOffsetParent()
pointer = getRelativePosition(pointer, offsetParent)
lastPointer = getRelativePosition(lastPointer, offsetParent)
}
if(container.searchValidTarget(pointer, lastPointer))
return true
}
}
}
if(this.sameResultBox)
this.sameResultBox = undefined
},
movePlaceholder: function (container, item, method, sameResultBox) {
var lastAppendedItem = this.lastAppendedItem
if(!sameResultBox && lastAppendedItem && lastAppendedItem[0] === item[0])
return;
item[method](this.placeholder)
this.lastAppendedItem = item
this.sameResultBox = sameResultBox
this.options.afterMove(this.placeholder, container, item)
},
getContainerDimensions: function () {
if(!this.containerDimensions)
setDimensions(this.containers, this.containerDimensions = [], this.options.tolerance, !this.$getOffsetParent())
return this.containerDimensions
},
getContainer: function (element) {
return element.closest(this.options.containerSelector).data(pluginName)
},
$getOffsetParent: function () {
if(this.offsetParent === undefined){
var i = this.containers.length - 1,
offsetParent = this.containers[i].getItemOffsetParent()
if(!this.options.rootGroup){
while(i--){
if(offsetParent[0] != this.containers[i].getItemOffsetParent()[0]){
// If every container has the same offset parent,
// use position() which is relative to this parent,
// otherwise use offset()
// compare #setDimensions
offsetParent = false
break;
}
}
}
this.offsetParent = offsetParent
}
return this.offsetParent
},
setPointer: function (e) {
var pointer = this.getPointer(e)
if(this.$getOffsetParent()){
var relativePointer = getRelativePosition(pointer, this.$getOffsetParent())
this.lastRelativePointer = this.relativePointer
this.relativePointer = relativePointer
}
this.lastPointer = this.pointer
this.pointer = pointer
},
distanceMet: function (e) {
var currentPointer = this.getPointer(e)
return (Math.max(
Math.abs(this.pointer.left - currentPointer.left),
Math.abs(this.pointer.top - currentPointer.top)
) >= this.options.distance)
},
getPointer: function(e) {
var o = e.originalEvent || e.originalEvent.touches && e.originalEvent.touches[0]
return {
left: e.pageX || o.pageX,
top: e.pageY || o.pageY
}
},
setupDelayTimer: function () {
var that = this
this.delayMet = !this.options.delay
// init delay timer if needed
if (!this.delayMet) {
clearTimeout(this._mouseDelayTimer);
this._mouseDelayTimer = setTimeout(function() {
that.delayMet = true
}, this.options.delay)
}
},
scroll: function (e) {
this.clearDimensions()
this.clearOffsetParent() // TODO is this needed?
},
toggleListeners: function (method) {
var that = this,
events = ['drag','drop','scroll']
$.each(events,function (i,event) {
that.$document[method](eventNames[event], that[event + 'Proxy'])
})
},
clearOffsetParent: function () {
this.offsetParent = undefined
},
// Recursively clear container and item dimensions
clearDimensions: function () {
this.traverse(function(object){
object._clearDimensions()
})
},
traverse: function(callback) {
callback(this)
var i = this.containers.length
while(i--){
this.containers[i].traverse(callback)
}
},
_clearDimensions: function(){
this.containerDimensions = undefined
},
_destroy: function () {
containerGroups[this.options.group] = undefined
}
}
function Container(element, options) {
this.el = element
this.options = $.extend( {}, containerDefaults, options)
this.group = ContainerGroup.get(this.options)
this.rootGroup = this.options.rootGroup || this.group
this.handle = this.rootGroup.options.handle || this.rootGroup.options.itemSelector
var itemPath = this.rootGroup.options.itemPath
this.target = itemPath ? this.el.find(itemPath) : this.el
this.target.on(eventNames.start, this.handle, $.proxy(this.dragInit, this))
if(this.options.drop)
this.group.containers.push(this)
}
Container.prototype = {
dragInit: function (e) {
var rootGroup = this.rootGroup
if( !this.disabled &&
!rootGroup.dragInitDone &&
this.options.drag &&
this.isValidDrag(e)) {
rootGroup.dragInit(e, this)
}
},
isValidDrag: function(e) {
return e.which == 1 ||
e.type == "touchstart" && e.originalEvent.touches.length == 1
},
searchValidTarget: function (pointer, lastPointer) {
var distances = sortByDistanceDesc(this.getItemDimensions(),
pointer,
lastPointer),
i = distances.length,
rootGroup = this.rootGroup,
validTarget = !rootGroup.options.isValidTarget ||
rootGroup.options.isValidTarget(rootGroup.item, this)
if(!i && validTarget){
rootGroup.movePlaceholder(this, this.target, "append")
return true
} else
while(i--){
var index = distances[i][0],
distance = distances[i][1]
if(!distance && this.hasChildGroup(index)){
var found = this.getContainerGroup(index).searchValidTarget(pointer, lastPointer)
if(found)
return true
}
else if(validTarget){
this.movePlaceholder(index, pointer)
return true
}
}
},
movePlaceholder: function (index, pointer) {
var item = $(this.items[index]),
dim = this.itemDimensions[index],
method = "after",
width = item.outerWidth(),
height = item.outerHeight(),
offset = item.offset(),
sameResultBox = {
left: offset.left,
right: offset.left + width,
top: offset.top,
bottom: offset.top + height
}
if(this.options.vertical){
var yCenter = (dim[2] + dim[3]) / 2,
inUpperHalf = pointer.top <= yCenter
if(inUpperHalf){
method = "before"
sameResultBox.bottom -= height / 2
} else
sameResultBox.top += height / 2
} else {
var xCenter = (dim[0] + dim[1]) / 2,
inLeftHalf = pointer.left <= xCenter
if(inLeftHalf){
method = "before"
sameResultBox.right -= width / 2
} else
sameResultBox.left += width / 2
}
if(this.hasChildGroup(index))
sameResultBox = emptyBox
this.rootGroup.movePlaceholder(this, item, method, sameResultBox)
},
getItemDimensions: function () {
if(!this.itemDimensions){
this.items = this.$getChildren(this.el, "item").filter(
":not(." + this.group.options.placeholderClass + ", ." + this.group.options.draggedClass + ")"
).get()
setDimensions(this.items, this.itemDimensions = [], this.options.tolerance)
}
return this.itemDimensions
},
getItemOffsetParent: function () {
var offsetParent,
el = this.el
// Since el might be empty we have to check el itself and
// can not do something like el.children().first().offsetParent()
if(el.css("position") === "relative" || el.css("position") === "absolute" || el.css("position") === "fixed")
offsetParent = el
else
offsetParent = el.offsetParent()
return offsetParent
},
hasChildGroup: function (index) {
return this.options.nested && this.getContainerGroup(index)
},
getContainerGroup: function (index) {
var childGroup = $.data(this.items[index], subContainerKey)
if( childGroup === undefined){
var childContainers = this.$getChildren(this.items[index], "container")
childGroup = false
if(childContainers[0]){
var options = $.extend({}, this.options, {
rootGroup: this.rootGroup,
group: groupCounter ++
})
childGroup = childContainers[pluginName](options).data(pluginName).group
}
$.data(this.items[index], subContainerKey, childGroup)
}
return childGroup
},
$getChildren: function (parent, type) {
var options = this.rootGroup.options,
path = options[type + "Path"],
selector = options[type + "Selector"]
parent = $(parent)
if(path)
parent = parent.find(path)
return parent.children(selector)
},
_serialize: function (parent, isContainer) {
var that = this,
childType = isContainer ? "item" : "container",
children = this.$getChildren(parent, childType).not(this.options.exclude).map(function () {
return that._serialize($(this), !isContainer)
}).get()
return this.rootGroup.options.serialize(parent, children, isContainer)
},
traverse: function(callback) {
$.each(this.items || [], function(item){
var group = $.data(this, subContainerKey)
if(group)
group.traverse(callback)
});
callback(this)
},
_clearDimensions: function () {
this.itemDimensions = undefined
},
_destroy: function() {
var that = this;
this.target.off(eventNames.start, this.handle);
this.el.removeData(pluginName)
if(this.options.drop)
this.group.containers = $.grep(this.group.containers, function(val){
return val != that
})
$.each(this.items || [], function(){
$.removeData(this, subContainerKey)
})
}
}
var API = {
enable: function() {
this.traverse(function(object){
object.disabled = false
})
},
disable: function (){
this.traverse(function(object){
object.disabled = true
})
},
serialize: function () {
return this._serialize(this.el, true)
},
refresh: function() {
this.traverse(function(object){
object._clearDimensions()
})
},
destroy: function () {
this.traverse(function(object){
object._destroy();
})
}
}
$.extend(Container.prototype, API)
/**
* jQuery API
*
* Parameters are
* either options on init
* or a method name followed by arguments to pass to the method
*/
$.fn[pluginName] = function(methodOrOptions) {
var args = Array.prototype.slice.call(arguments, 1)
return this.map(function(){
var $t = $(this),
object = $t.data(pluginName)
if(object && API[methodOrOptions])
return API[methodOrOptions].apply(object, args) || this
else if(!object && (methodOrOptions === undefined ||
typeof methodOrOptions === "object"))
$t.data(pluginName, new Container($t, methodOrOptions))
return this
});
};
}(jQuery, window, 'sortable');
......@@ -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 -->
......
<?php
/*
Copyright (C) 2014-2015 Deciso B.V.
Copyright (C) 2004-2006 T. Lechat <dev@lechat.org>, Manuel Kasper <mk@neon1.net>
and Jonathan Watt <jwatt@jwatt.org>.
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.
*/
require_once("guiconfig.inc");
require_once("interfaces.inc");
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
header("Content-type: image/svg+xml");
/********** HTTP GET Based Conf ***********/
$ifnum=@$_GET["ifnum"]; // BSD / SNMP interface name / number
$ifnum = get_real_interface($ifnum);
$ifname=@$_GET["ifname"]?$_GET["ifname"]:"Interface $ifnum"; //Interface name that will be showed on top right of graph
/********* Other conf *******/
if (isset($config["widgets"]["trafficgraphs"]["scale_type"]))
$scale_type = $config["widgets"]["trafficgraphs"]["scale_type"];
else
$scale_type = "up";
$nb_plot=120; //NB plot in graph
if ($_GET["timeint"])
$time_interval = $_GET["timeint"]; //Refresh time Interval
else
$time_interval = 3;
if ($_GET["initdelay"])
$init_delay = $_GET["initdelay"]; //Initial Delay
else
$init_delay = 3;
//SVG attributes
$attribs['axis']='fill="black" stroke="black"';
$attribs['in']='fill="#f07712" font-family="Tahoma, Verdana, Arial, Helvetica, sans-serif" font-size="7"';
$attribs['out']='fill="#333333" font-family="Tahoma, Verdana, Arial, Helvetica, sans-serif" font-size="7"';
$attribs['graph_in']='fill="none" stroke="#f07712" stroke-opacity="0.8"';
$attribs['graph_out']='fill="none" stroke="#333333" stroke-opacity="0.8"';
$attribs['legend']='fill="black" font-family="Tahoma, Verdana, Arial, Helvetica, sans-serif" font-size="4"';
$attribs['graphname']='fill="#f07712" font-family="Tahoma, Verdana, Arial, Helvetica, sans-serif" font-size="8"';
$attribs['grid_txt']='fill="gray" font-family="Tahoma, Verdana, Arial, Helvetica, sans-serif" font-size="6"';
$attribs['grid']='stroke="gray" stroke-opacity="0.5"';
$attribs['switch_unit']='fill="#f07712" font-family="Tahoma, Verdana, Arial, Helvetica, sans-serif" font-size="4" text-decoration="underline"';
$attribs['switch_scale']='fill="#f07712" font-family="Tahoma, Verdana, Arial, Helvetica, sans-serif" font-size="4" text-decoration="underline"';
$attribs['error']='fill="blue" font-family="Arial" font-size="4"';
$attribs['collect_initial']='fill="gray" font-family="Tahoma, Verdana, Arial, Helvetica, sans-serif" font-size="4"';
//Error text if we cannot fetch data : depends on which method is used
$error_text = sprintf(gettext('Cannot get data about interface %s'), htmlspecialchars($ifnum));
$height=100; //SVG internal height : do not modify
$width=200; //SVG internal width : do not modify
$fetch_link = "legacy_traffic_stats.php?if=" . htmlspecialchars($ifnum);
/********* Graph DATA **************/
print('<?xml version="1.0" ?>' . "\n");?>
<svg width="100%" height="100%" viewBox="0 0 <?=$width?> <?=$height?>" preserveAspectRatio="none" xml:space="preserve" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" onload="init(evt)">
<g id="graph">
<rect id="bg" x1="0" y1="0" width="100%" height="100%" fill="white"/>
<line id="axis_x" x1="0" y1="0" x2="0" y2="100%" <?=$attribs['axis']?>/>
<line id="axis_y" x1="0" y1="100%" x2="100%" y2="100%" <?=$attribs['axis']?>/>
<path id="graph_out" d="M0 <?=$height?> L 0 <?=$height?>" <?=$attribs['graph_out']?>/>
<path id="graph_in" d="M0 <?=$height?> L 0 <?=$height?>" <?=$attribs['graph_in']?>/>
<path id="grid" d="M0 <?=$height/4*1?> L <?=$width?> <?=$height/4*1?> M0 <?=$height/4*2?> L <?=$width?> <?=$height/4*2?> M0 <?=$height/4*3?> L <?=$width?> <?=$height/4*3?>" <?=$attribs['grid']?>/>
<text id="grid_txt1" x="<?=$width?>" y="<?=$height/4*1?>" <?=$attribs['grid_txt']?> text-anchor="end"> </text>
<text id="grid_txt2" x="<?=$width?>" y="<?=$height/4*2?>" <?=$attribs['grid_txt']?> text-anchor="end"> </text>
<text id="grid_txt3" x="<?=$width?>" y="<?=$height/4*3?>" <?=$attribs['grid_txt']?> text-anchor="end"> </text>
<text id="graph_in_lbl" x="5" y="8" <?=$attribs['in']?>><?=gettext("In"); ?></text>
<text id="graph_out_lbl" x="5" y="16" <?=$attribs['out']?>><?=gettext("Out"); ?></text>
<text id="graph_in_txt" x="20" y="8" <?=$attribs['in']?>> </text>
<text id="graph_out_txt" x="20" y="16" <?=$attribs['out']?>> </text>
<text id="ifname" x="<?=$width?>" y="8" <?=$attribs['graphname']?> text-anchor="end"><?=htmlspecialchars($ifname)?></text>
<text id="switch_unit" x="<?=$width*0.55?>" y="5" <?=$attribs['switch_unit']?>><?=gettext("Switch to bytes/s"); ?></text>
<text id="switch_scale" x="<?=$width*0.55?>" y="11" <?=$attribs['switch_scale']?>><?=gettext("AutoScale"); ?> (<?=$scale_type?>)</text>
<text id="date" x="<?=$width*0.33?>" y="5" <?=$attribs['legend']?>> </text>
<text id="time" x="<?=$width*0.33?>" y="11" <?=$attribs['legend']?>> </text>
<text id="graphlast" x="<?=$width*0.55?>" y="17" <?=$attribs['legend']?>><?=gettext("Graph shows last"); ?> <?=$time_interval*$nb_plot?> <?=gettext("seconds"); ?></text>
<polygon id="axis_arrow_x" <?=$attribs['axis']?> points="<?=($width) . "," . ($height)?> <?=($width-2) . "," . ($height-2)?> <?=($width-2) . "," . $height?>"/>
<text id="error" x="<?=$width*0.5?>" y="<?=$height*0.5?>" visibility="hidden" <?=$attribs['error']?> text-anchor="middle"><?=$error_text?></text>
<text id="collect_initial" x="<?=$width*0.5?>" y="<?=$height*0.5?>" visibility="hidden" <?=$attribs['collect_initial']?> text-anchor="middle"><?=gettext("Collecting initial data, please wait"); ?>...</text>
</g>
<script type="text/ecmascript">
<![CDATA[
/**
* getURL is a proprietary Adobe function, but it's simplicity has made it very
* popular. If getURL is undefined we spin our own by wrapping XMLHttpRequest.
*/
if (typeof getURL == 'undefined') {
getURL = function(url, callback) {
if (!url)
throw '<?=gettext("No URL for getURL"); ?>';
try {
if (typeof callback.operationComplete == 'function')
callback = callback.operationComplete;
} catch (e) {}
if (typeof callback != 'function')
throw '<?=gettext("No callback function for getURL"); ?>';
var http_request = null;
if (typeof XMLHttpRequest != 'undefined') {
http_request = new XMLHttpRequest();
}
else if (typeof ActiveXObject != 'undefined') {
try {
http_request = new ActiveXObject('Msxml2.XMLHTTP');
} catch (e) {
try {
http_request = new ActiveXObject('Microsoft.XMLHTTP');
} catch (e) {}
}
}
if (!http_request)
throw '<?=gettext("Both getURL and XMLHttpRequest are undefined"); ?>';
http_request.onreadystatechange = function() {
if (http_request.readyState == 4) {
callback( { success : true,
content : http_request.responseText,
contentType : http_request.getResponseHeader("Content-Type") } );
}
}
http_request.open('GET', url, true);
http_request.send(null);
}
}
var SVGDoc = null;
var last_ifin = 0;
var last_ifout = 0;
var last_ugmt = 0;
var max = 0;
var plot_in = new Array();
var plot_out = new Array();
var max_num_points = <?=$nb_plot?>; // maximum number of plot data points
var step = <?=$width?> / max_num_points ;
var unit = 'bits';
var scale_type = '<?=$scale_type?>';
function init(evt) {
SVGDoc = evt.target.ownerDocument;
SVGDoc.getElementById("switch_unit").addEventListener("mousedown", switch_unit, false);
SVGDoc.getElementById("switch_scale").addEventListener("mousedown", switch_scale, false);
fetch_data();
}
function switch_unit(event)
{
SVGDoc.getElementById('switch_unit').firstChild.data = '<?=gettext("Switch to"); ?> ' + unit + '/s';
unit = (unit == 'bits') ? 'bytes' : 'bits';
}
function switch_scale(event)
{
scale_type = (scale_type == 'up') ? '<?=gettext("follow"); ?>' : '<?=gettext("up"); ?>';
SVGDoc.getElementById('switch_scale').firstChild.data = 'AutoScale (' + scale_type + ')';
}
function fetch_data() {
getURL('<?=$fetch_link?>', plot_data);
}
function plot_data(obj) {
// Show datetimelegend
var now = new Date();
var time = LZ(now.getHours()) + ":" + LZ(now.getMinutes()) + ":" + LZ(now.getSeconds());
SVGDoc.getElementById('time').firstChild.data = time;
var date = (now.getMonth()+1) + "/" + now.getDate() + "/" + now.getFullYear();
SVGDoc.getElementById('date').firstChild.data = date;
if (!obj.success)
return handle_error(); // getURL failed to get data
var t = obj.content.split("|");
var ugmt = parseFloat(t[0]); // ugmt is an unixtimestamp style
var ifin = parseInt(t[1], 10); // number of bytes received by the interface
var ifout = parseInt(t[2], 10); // number of bytes sent by the interface
var scale;
if (!isNumber(ifin) || !isNumber(ifout))
return handle_error();
var diff_ugmt = ugmt - last_ugmt;
var diff_ifin = ifin - last_ifin;
var diff_ifout = ifout - last_ifout;
if (diff_ugmt == 0)
diff_ugmt = 1; /* avoid division by zero */
last_ugmt = ugmt;
last_ifin = ifin;
last_ifout = ifout;
var graphTimerId = 0;
switch (plot_in.length) {
case 0:
SVGDoc.getElementById("collect_initial").setAttributeNS(null, 'visibility', 'visible');
plot_in[0] = diff_ifin / diff_ugmt;
plot_out[0] = diff_ifout / diff_ugmt;
setTimeout('fetch_data()',<?=1000*($time_interval + $init_delay)?>);
return;
case 1:
SVGDoc.getElementById("collect_initial").setAttributeNS(null, 'visibility', 'hidden');
break;
case max_num_points:
// shift plot to left if the maximum number of plot points has been reached
var i = 0;
while (i < max_num_points) {
plot_in[i] = plot_in[i+1];
plot_out[i] = plot_out[++i];
}
plot_in.length--;
plot_out.length--;
}
plot_in[plot_in.length] = diff_ifin / diff_ugmt;
plot_out[plot_out.length]= diff_ifout / diff_ugmt;
var index_plot = plot_in.length - 1;
SVGDoc.getElementById('graph_in_txt').firstChild.data = formatSpeed(plot_in[index_plot], unit);
SVGDoc.getElementById('graph_out_txt').firstChild.data = formatSpeed(plot_out[index_plot], unit);
/* determine peak for sensible scaling */
if (scale_type == 'up') {
if (plot_in[index_plot] > max)
max = plot_in[index_plot];
if (plot_out[index_plot] > max)
max = plot_out[index_plot];
}
else if (scale_type == 'follow') {
i = 0;
max = 0;
while (i < plot_in.length) {
if (plot_in[i] > max)
max = plot_in[i];
if (plot_out[i] > max)
max = plot_out[i];
i++;
}
}
var rmax; // max, rounded up
if (unit == 'bits') {
/* round up max, such that
100 kbps -> 200 kbps -> 400 kbps -> 800 kbps -> 1 Mbps -> 2 Mbps -> ... */
rmax = 12500;
i = 0;
while (max > rmax) {
i++;
if (i && (i % 4 == 0))
rmax *= 1.25;
else
rmax *= 2;
}
} else {
/* round up max, such that
10 KB/s -> 20 KB/s -> 40 KB/s -> 80 KB/s -> 100 KB/s -> 200 KB/s -> 400 KB/s -> 800 KB/s -> 1 MB/s ... */
rmax = 10240;
i = 0;
while (max > rmax) {
i++;
if (i && (i % 4 == 0))
rmax *= 1.25;
else
rmax *= 2;
if (i == 8)
rmax *= 1.024;
}
}
scale = <?=$height?> / rmax;
/* change labels accordingly */
SVGDoc.getElementById('grid_txt1').firstChild.data = formatSpeed(3*rmax/4,unit);
SVGDoc.getElementById('grid_txt2').firstChild.data = formatSpeed(2*rmax/4,unit);
SVGDoc.getElementById('grid_txt3').firstChild.data = formatSpeed(rmax/4,unit);
var path_in = "M 0 " + (<?=$height?> - (plot_in[0] * scale));
var path_out = "M 0 " + (<?=$height?> - (plot_out[0] * scale));
for (i = 1; i < plot_in.length; i++)
{
var x = step * i;
var y_in = <?=$height?> - (plot_in[i] * scale);
var y_out = <?=$height?> - (plot_out[i] * scale);
path_in += " L" + x + " " + y_in;
path_out += " L" + x + " " + y_out;
}
SVGDoc.getElementById('error').setAttributeNS(null, 'visibility', 'hidden');
SVGDoc.getElementById('graph_in').setAttributeNS(null, 'd', path_in);
SVGDoc.getElementById('graph_out').setAttributeNS(null, 'd', path_out);
setTimeout('fetch_data()',<?=1000*$time_interval?>);
}
function handle_error() {
SVGDoc.getElementById("error").setAttributeNS(null, 'visibility', 'visible');
setTimeout('fetch_data()',<?=1000*$time_interval?>);
}
function isNumber(a) {
return typeof a == 'number' && isFinite(a);
}
function formatSpeed(speed, unit) {
if (unit == 'bits')
return formatSpeedBits(speed);
if (unit == 'bytes')
return formatSpeedBytes(speed);
}
function formatSpeedBits(speed) {
// format speed in bits/sec, input: bytes/sec
if (speed < 125000)
return Math.round(speed / 125) + " <?=gettext("Kbps"); ?>";
if (speed < 125000000)
return Math.round(speed / 1250)/100 + " <?=gettext("Mbps"); ?>";
// else
return Math.round(speed / 1250000)/100 + " <?=gettext("Gbps"); ?>"; /* wow! */
}
function formatSpeedBytes(speed) {
// format speed in bytes/sec, input: bytes/sec
if (speed < 1048576)
return Math.round(speed / 10.24)/100 + " <?=gettext("KB/s"); ?>";
if (speed < 1073741824)
return Math.round(speed / 10485.76)/100 + " <?=gettext("MB/s"); ?>";
// else
return Math.round(speed / 10737418.24)/100 + " <?=gettext("GB/s"); ?>"; /* wow! */
}
function LZ(x) {
return (x < 0 || x > 9 ? "" : "0") + x;
}
]]>
</script>
</svg>
......@@ -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">
......
<?php
/*
Copyright (C) 2014 Deciso B.V.
Copyright (C) 2014-2016 Deciso B.V.
Copyright (C) 2004-2012 Scott Ullrich
Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>.
All rights reserved.
......@@ -34,317 +34,90 @@ ini_set('output_buffering', 'true');
// Start buffering with a cache size of 100000
ob_start(null, "1000");
## Load Essential Includes
// Load Essential Includes
require_once('guiconfig.inc');
// closing should be $_POST, but the whole notice handling needs more attention. Leave it as is for now.
if (isset($_REQUEST['closenotice'])) {
close_notice($_REQUEST['closenotice']);
echo get_menu_messages();
exit;
}
##build list of widgets
$directory = "/usr/local/www/widgets/widgets/";
$dirhandle = opendir($directory);
$filename = "";
$widgetnames = array();
$widgetfiles = array();
$widgetlist = array();
while (false !== ($filename = readdir($dirhandle))) {
$periodpos = strpos($filename, ".");
/* Ignore files not ending in .php */
if (substr($filename, -4, 4) != ".php") {
continue;
}
$widgetname = substr($filename, 0, $periodpos);
$widgetnames[] = $widgetname;
if ($widgetname != "system_information") {
$widgetfiles[] = $filename;
}
}
##sort widgets alphabetically
sort($widgetfiles);
##insert the system information widget as first, so as to be displayed first
array_unshift($widgetfiles, "system_information.widget.php");
##if no config entry found, initialize config entry
if (!is_array($config['widgets'])) {
if (empty($config['widgets']) || !is_array($config['widgets'])) {
$config['widgets'] = array();
}
if ($_POST && $_POST['sequence']) {
$config['widgets']['sequence'] = $_POST['sequence'];
foreach ($widgetnames as $widget) {
if ($_POST[$widget . '-config']) {
$config['widgets'][$widget . '-config'] = $_POST[$widget . '-config'];
}
}
write_config(gettext("Widget configuration has been changed."));
header("Location: index.php");
exit;
}
## Check to see if we have a swap space,
## if true, display, if false, hide it ...
if (file_exists('/usr/sbin/swapinfo')) {
$swapinfo = `/usr/sbin/swapinfo`;
if (stristr($swapinfo, '%')) {
$showswap = true;
}
}
##build widget saved list information
if ($config['widgets'] && $config['widgets']['sequence'] != "") {
$pconfig['sequence'] = $config['widgets']['sequence'];
$widgetlist = $pconfig['sequence'];
$colpos = array();
$savedwidgetfiles = array();
$widgetname = "";
$widgetlist = explode(",", $widgetlist);
##read the widget position and display information
foreach ($widgetlist as $widget) {
$dashpos = strpos($widget, "-");
$widgetname = substr($widget, 0, $dashpos);
if (!in_array($widgetname, $widgetnames)) {
continue;
}
$colposition = strpos($widget, ":");
$displayposition = strrpos($widget, ":");
$colpos[] = substr($widget, $colposition+1, $displayposition - $colposition-1);
$displayarray[] = substr($widget, $displayposition+1);
$savedwidgetfiles[] = $widgetname . ".widget.php";
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
$pconfig = $config['widgets'];
if (empty($pconfig['sequence'])) {
// set default dashboard view
$pconfig['sequence'] = 'system_information-container:col1:show,interface_list-container:col1:show,traffic_graphs-container:col1:show';
}
##add widgets that may not be in the saved configuration, in case they are to be displayed later
foreach ($widgetfiles as $defaultwidgets) {
if (!in_array($defaultwidgets, $savedwidgetfiles)) {
$savedwidgetfiles[] = $defaultwidgets;
// default 2 column grid layout
$pconfig['column_count'] = !empty($pconfig['column_count']) ? $pconfig['column_count'] : 2;
// build list of widgets
$widgetCollection = array();
$widgetSeqParts = explode(",", $pconfig['sequence']);
foreach (glob('/usr/local/www/widgets/widgets/*.widget.php') as $php_file) {
$widgetItem = array();
$widgetItem['name'] = basename($php_file, '.widget.php');
$widgetItem['display_name'] = ucwords(str_replace("_", " ", $widgetItem['name']));
$widgetItem['filename'] = $php_file;
$widgetItem['state'] = "none";
/// default sort order
$widgetItem['sortKey'] = $widgetItem['name'] == 'system_information' ? "00000000" : "99999999" . $widgetItem['name'];
foreach ($widgetSeqParts as $seqPart) {
$tmp = explode(':', $seqPart);
if (count($tmp) == 3 && explode('-', $tmp[0])[0] == $widgetItem['name']) {
$widgetItem['state'] = $tmp[2];
$widgetItem['sortKey'] = $tmp[1];
}
}
$widgetCollection[] = $widgetItem;
}
##find custom configurations of a particular widget and load its info to $pconfig
foreach ($widgetnames as $widget) {
if (isset($config['widgets'][$widget . '-config'])) {
$pconfig[$widget . '-config'] = $config['widgets'][$widget . '-config'];
// sort widgets
usort($widgetCollection, function ($item1, $item2) {
return strcmp(strtolower($item1['sortKey']), strtolower($item2['sortKey']));
});
} elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (!empty($_POST['sequence'])) {
$config['widgets']['sequence'] = $_POST['sequence'];
if (!empty($_POST['column_count'])) {
$config['widgets']['column_count'] = $_POST['column_count'];
}
write_config(gettext("Widget configuration has been changed."));
}
$widgetlist = $savedwidgetfiles;
} else {
// no saved widget sequence found, build default list.
$widgetlist = $widgetfiles;
}
##build list of php include files
$phpincludefiles = array();
$directory = "/usr/local/www/widgets/include/";
$dirhandle = opendir($directory);
$filename = "";
while (false !== ($filename = readdir($dirhandle))) {
$phpincludefiles[] = $filename;
}
foreach ($phpincludefiles as $includename) {
if (!stristr($includename, ".inc")) {
continue;
}
include($directory . $includename);
}
##begin AJAX
$jscriptstr = <<<EOD
<script type="text/javascript">
//<![CDATA[
function widgetAjax(widget) {
uri = "widgets/widgets/" + widget + ".widget.php";
var opt = {
// Use GET
type: 'get',
async: true,
// Handle 404
statusCode: {
404: function(t) {
alert('Error 404: location "' + t.statusText + '" was not found.');
}
},
// Handle other errors
error: function(t) {
alert('Error ' + t.status + ' -- ' + t.statusText);
},
success: function(data) {
widget2 = '#' + widget + "-loader";
jQuery(widget2).fadeOut(1000,function(){
jQuery('#' + widget).show();
});
jQuery('#' + widget).html(data);
}
}
jQuery.ajax(uri, opt);
}
function addWidget(selectedDiv){
container = $('#'+selectedDiv);
state = $('#'+selectedDiv+'-config');
container.show();
showSave();
state.val('show');
}
function configureWidget(selectedDiv){
selectIntLink = '#' + selectedDiv + "-settings";
if ($(selectIntLink).css('display') == "none")
$(selectIntLink).show();
else
$(selectIntLink).hide();
}
function showWidget(selectedDiv,swapButtons){
container = $('#'+selectedDiv+'-container');
min_btn = $('#'+selectedDiv+'-min');
max_btn = $('#'+selectedDiv+'-max');
state = $('#'+selectedDiv+'-config');
container.show();
min_btn.show();
max_btn.hide();
showSave();
state.val('show');
}
function minimizeWidget(selectedDiv,swapButtons){
container = $('#'+selectedDiv+'-container');
min_btn = $('#'+selectedDiv+'-min');
max_btn = $('#'+selectedDiv+'-max');
state = $('#'+selectedDiv+'-config');
container.hide();
min_btn.hide();
max_btn.show();
showSave();
state.val('hide');
}
function closeWidget(selectedDiv){
widget = $('#'+selectedDiv);
state = $('#'+selectedDiv+'-config');
showSave();
widget.hide();
state.val('close');
}
function showSave(){
$('#updatepref').show();
}
function updatePref(){
var widgets = $('.widgetdiv');
var widgetSequence = '';
var firstprint = false;
widgets.each(function(key) {
obj = $(this);
if (firstprint)
widgetSequence += ',';
state = $('input[name='+obj.attr('id')+'-config]').val();
widgetSequence += obj.attr('id')+'-container:col1:'+state;
firstprint = true;
});
$("#sequence").val(widgetSequence);
$("#iform").submit();
return false;
header("Location: index.php");
exit;
}
function changeTabDIV(selectedDiv){
var dashpos = selectedDiv.indexOf("-");
var tabclass = selectedDiv.substring(0,dashpos);
d = document;
//get deactive tabs first
tabclass = tabclass + "-class-tabdeactive";
var tabs = document.getElementsByClassName(tabclass);
var incTabSelected = selectedDiv + "-deactive";
for (i=0; i<tabs.length; i++){
var tab = tabs[i].id;
dashpos = tab.lastIndexOf("-");
var tab2 = tab.substring(0,dashpos) + "-deactive";
if (tab2 == incTabSelected){
tablink = d.getElementById(tab2);
tablink.style.display = "none";
tab2 = tab.substring(0,dashpos) + "-active";
tablink = d.getElementById(tab2);
tablink.style.display = "table-cell";
//now show main div associated with link clicked
tabmain = d.getElementById(selectedDiv);
tabmain.style.display = "block";
}
else
{
tab2 = tab.substring(0,dashpos) + "-deactive";
tablink = d.getElementById(tab2);
tablink.style.display = "table-cell";
tab2 = tab.substring(0,dashpos) + "-active";
tablink = d.getElementById(tab2);
tablink.style.display = "none";
//hide sections we don't want to see
tab2 = tab.substring(0,dashpos);
tabmain = d.getElementById(tab2);
tabmain.style.display = "none";
}
}
// handle widget includes
foreach (glob("/usr/local/www/widgets/include/*.inc") as $filename) {
include($filename);
}
//]]>
</script>
EOD;
include("head.inc");
?>
<body>
<?php
include("fbegin.inc");
echo "\n\t<script type=\"text/javascript\" src=\"/javascript/index/ajax.js\"></script>\n";
echo $jscriptstr;
?>
include("fbegin.inc");?>
<?php
## If it is the first time webConfigurator has been
## accessed since initial install show this stuff.
if (isset($config['trigger_initial_wizard'])) :
?>
## If it is the first time webConfigurator has been
## accessed since initial install show this stuff.
if (isset($config['trigger_initial_wizard'])) :?>
<script type="text/javascript">
$( document ).ready(function() {
$(".page-content-head:first").hide();
});
</script>
<header class="page-content-head">
<div class="container-fluid">
<h1><?= gettext("Starting initial configuration!") ?></h1>
</div>
</header>
<section class="page-content-main">
<div class="container-fluid col-xs-12 col-sm-10 col-md-9">
<div class="row">
......@@ -368,196 +141,270 @@ if (isset($config['trigger_initial_wizard'])) :
</div>
</section>
<meta http-equiv="refresh" content="3;url=wizard.php">
<?php exit; ?>
<?php
endif; ?>
// normal dashboard
else:?>
<section class="page-content-main">
<div class="container-fluid">
<div class="row">
<?php
$crash_report = get_crash_report();
if ($crash_report != '') {
print_info_box($crash_report);
<script src='/ui/js/jquery-sortable.js'></script>
<script type="text/javascript">
function addWidget(selectedDiv) {
$('#'+selectedDiv).show();
$('#add_widget_'+selectedDiv).hide();
$('#'+selectedDiv+'-config').val('show');
showSave();
}
function configureWidget(selectedDiv) {
selectIntLink = '#' + selectedDiv + "-settings";
if ($(selectIntLink).css('display') == "none") {
$(selectIntLink).show();
} else {
$(selectIntLink).hide();
}
}
function showWidget(selectedDiv,swapButtons) {
$('#'+selectedDiv+'-container').show();
$('#'+selectedDiv+'-min').show();
$('#'+selectedDiv+'-max').hide();
$('#'+selectedDiv+'-config').val('show');
showSave();
}
function minimizeWidget(selectedDiv, swapButtons) {
$('#'+selectedDiv+'-container').hide();
$('#'+selectedDiv+'-min').hide();
$('#'+selectedDiv+'-max').show();
$('#'+selectedDiv+'-config').val('hide');
showSave();
}
function closeWidget(selectedDiv) {
$('#'+selectedDiv).hide();
$('#'+selectedDiv+'-config').val('close');
showSave();
}
$totalwidgets = count($widgetfiles);
$halftotal = $totalwidgets / 2 - 2;
$widgetcounter = 0;
$directory = "/usr/local/www/widgets/widgets/";
$printed = false;
$firstprint = false;
function showSave() {
$('#updatepref').show();
}
foreach ($widgetlist as $widget) {
if (!stristr($widget, "widget.php")) {
continue;
function updatePref() {
var widgetInfo = [];
var index = 0;
$('.widgetdiv').each(function(key) {
if ($(this).is(':visible')) {
// only capture visible widgets
var index_str = "0000000" + index;
index_str = index_str.substr(index_str.length-8);
col_index = $(this).parent().attr("id").split('_')[1];
widgetInfo.push($(this).attr('id')+'-container:'+index_str+'-'+col_index+':'+$('input[name='+$(this).attr('id')+'-config]').val());
index++;
}
$periodpos = strpos($widget, ".");
$widgetname = substr($widget, 0, $periodpos);
if ($widgetname != "") {
$nicename = $widgetname;
$nicename = str_replace("_", " ", $nicename);
});
$("#sequence").val(widgetInfo.join(','));
$("#iform").submit();
return false;
}
//make the title look nice
$nicename = ucwords($nicename);
/**
* ajax update widget data, searches data-plugin attributes and use function in data-callback to update widget
*/
function process_widget_data()
{
var plugins = [];
var callbacks = [];
// collect plugins and callbacks
$("[data-plugin]").each(function(){
if (plugins.indexOf($(this).data('plugin')) < 0) {
plugins.push($(this).data('plugin'));
}
if ($(this).data('callback') != undefined) {
callbacks.push({'function' : $(this).data('callback'), 'plugin': $(this).data('plugin'), 'sender': $(this)});
}
})
// collect data for provided plugins
$.ajax("/widgets/api/get.php",{type: 'get', cache: false, dataType: "json", data: {'load': plugins.join(',')}})
.done(function(response) {
callbacks.map( function(callback) {
try {
if (response['data'][callback['plugin']] != undefined) {
window[callback['function']](callback['sender'], response['data'][callback['plugin']]);
}
} catch (err) {
console.log(err);
}
});
// schedule next update
setTimeout('process_widget_data()', 5000);
});
}
</script>
if (isset($config['widgets']) && isset($pconfig['sequence'])) {
if (isset($displayarray[$widgetcounter])) {
$disparr = $displayarray[$widgetcounter];
} else {
$disparr = null;
}
switch($disparr){
case "show":
$divdisplay = "block";
$display = "block";
$inputdisplay = "show";
$showWidget = "none";
$mindiv = "inline";
break;
case "hide":
$divdisplay = "block";
$display = "none";
$inputdisplay = "hide";
$showWidget = "inline";
$mindiv = "none";
break;
case "close":
$divdisplay = "none";
$display = "block";
$inputdisplay = "close";
$showWidget = "none";
$mindiv = "inline";
break;
default:
$divdisplay = "none";
$display = "block";
$inputdisplay = "none";
$showWidget = "none";
$mindiv = "inline";
break;
<script type="text/javascript">
$( document ).ready(function() {
// rearrange widgets to stored column
$(".widgetdiv").each(function(){
var widget = $(this);
var container = $(this).parent();
var target_col = widget.data('sortkey').split('-')[1];
if (target_col != undefined) {
if (container.attr('id').split('_')[1] != target_col) {
widget.remove().appendTo("#dashboard_"+target_col);
}
} else {
if ($firstprint == false) {
// dashboard_colx (source) is not visible, move other items to col4
widget.remove().appendTo("#dashboard_col4");
}
});
// show dashboard widgets after initial rendering
$("#dashboard_container").show();
// sortable widgets
$(".dashboard_grid_column").sortable({
handle: '.content-box-head',
group: 'dashboard_grid_column',
itemSelector: '.widgetdiv',
containerSelector: '.dashboard_grid_column',
placeholder: '<div class="placeholder"><i class="fa fa-hand-o-right" aria-hidden="true"></i></div>',
afterMove: function (placeholder, container, closestItemOrContainer) {
showSave();
}
});
// select number of columns
$("#column_count").change(function(){
if ($("#column_count_input").val() != $("#column_count").val()) {
showSave();
}
$("#column_count_input").val($("#column_count").val());
$(".dashboard_grid_column").each(function(){
var widget_col = $(this);
$.each(widget_col.attr("class").split(' '), function(index, classname) {
if (classname.indexOf('col-md') > -1) {
widget_col.removeClass(classname);
}
});;
widget_col.addClass('col-md-'+(12 / $("#column_count_input").val()));
});
});
$("#column_count").change();
// trigger initial ajax data poller
process_widget_data();
// in "Add Widget" dialog, hide widgets already on screen
$("#add_widget_btn").click(function(){
$(".widgetdiv").each(function(widget){
if ($(this).is(':visible')) {
$("#add_widget_" + $(this).attr('id')).hide();
} else {
$("#add_widget_" + $(this).attr('id')).show();
}
});
});
});
</script>
<section class="page-content-main">
<form method="post" id="iform">
<input type="hidden" value="" name="sequence" id="sequence" />
<input type="hidden" value="<?= $pconfig['column_count'];?>" name="column_count" id="column_count_input" />
</form>
<div class="container-fluid">
<div class="row">
<div class="col-md-12 col-xs-12">
<?php
$crash_report = get_crash_report();
if ($crash_report != '') {
print_info_box($crash_report);
}?>
</div>
</div>
<div id="dashboard_container" class="row" style="display:none">
<div class="col-xs-12 col-md-4 dashboard_grid_column hidden" id="dashboard_colx">
<?php
foreach ($widgetCollection as $widgetItem):
$widgettitle = $widgetItem['name'] . "_title";
$widgettitlelink = $widgetItem['name'] . "_title_link";
switch ($widgetItem['state']) {
case "show":
$divdisplay = "block";
$display = "block";
$inputdisplay = "show";
$showWidget = "none";
$mindiv = "inline";
$firstprint = true;
} else {
switch ($widget) {
case "interface_list.widget.php":
case "traffic_graphs.widget.php":
$divdisplay = "block";
$display = "block";
$inputdisplay = "show";
$showWidget = "none";
$mindiv = "inline";
break;
default:
$divdisplay = "none";
$display = "block";
$inputdisplay = "close";
$showWidget = "none";
$mindiv = "inline";
break;
}
}
break;
case "hide":
$divdisplay = "block";
$display = "none";
$inputdisplay = "hide";
$mindiv = "none";
break;
case "close":
$divdisplay = "none";
$display = "block";
$inputdisplay = "close";
$mindiv = "inline";
break;
default:
$divdisplay = "none";
$display = "block";
$inputdisplay = "none";
$mindiv = "inline";
break;
}?>
<section class="col-xs-12 col-md-6 widgetdiv" id="<?= $widgetname ?>" style="display:<?= $divdisplay ?>;">
<section class="widgetdiv" data-sortkey="<?=$widgetItem['sortKey'] ?>" id="<?=$widgetItem['name'];?>" style="display:<?=$divdisplay;?>;">
<div class="content-box">
<form action="<?=$_SERVER['REQUEST_URI'];?>" method="post" id="iform">
<input type="hidden" value="" name="sequence" id="sequence" />
<header class="content-box-head container-fluid">
<ul class="list-inline __nomb">
<li><h3>
<header class="content-box-head container-fluid">
<ul class="list-inline __nomb">
<li><h3>
<?php
$widgettitle = $widgetname . "_title";
$widgettitlelink = $widgetname . "_title_link";
if (isset($$widgettitle)) {
//only show link if defined
if ($$widgettitlelink != "") {
?>
<u><span onclick="location.href='/<?= $$widgettitlelink ?>'" style="cursor:pointer">
<?php
}
//echo widget title
echo $$widgettitle;
if (isset($$widgettitlelink)) {
?>
</span></u>
<?php
}
} else {
if (isset($$widgettitlelink)) {
?>
<u><span onclick="location.href='/<?= $$widgettitlelink ?>'" style="cursor:pointer">
<?php
}
echo $nicename;
if (isset($$widgettitlelink)) {
?>
</span></u>
<?php
}
}?>
</h3></li>
<li class="pull-right">
<div class="btn-group">
<button type="button" class="btn btn-default btn-xs" title="minimize" id="<?= $widgetname ?>-min" onclick='return minimizeWidget("<?= $widgetname ?>",true)' style="display:<?= $mindiv ?>;"><span class="glyphicon glyphicon-minus"></span></button>
<button type="button" class="btn btn-default btn-xs" title="maximize" id="<?= $widgetname ?>-max" onclick='return showWidget("<?= $widgetname ?>",true)' style="display:<?= $mindiv == 'none' ? 'inline' : 'none' ?>;"><span class="glyphicon glyphicon-plus"></span></button>
<button type="button" class="btn btn-default btn-xs" title="remove widget" onclick='return closeWidget("<?= $widgetname ?>",true)'><span class="glyphicon glyphicon-remove"></span></button>
<button type="button" class="btn btn-default btn-xs" id="<?= $widgetname ?>-configure" onclick='return configureWidget("<?= $widgetname ?>")' style="display:none; cursor:pointer" ><span class="glyphicon glyphicon-pencil"></span></button>
</div>
</li>
</ul>
</header>
</form>
<div class="content-box-main collapse in" id="<?= $widgetname ?>-container" style="display:<?= $mindiv ?>">
<input type="hidden" value="<?= $inputdisplay ?>" id="<?= $widgetname ?>-config" name="<?= $widgetname ?>-config" />
if (isset($$widgettitlelink)):?>
<u><span onclick="location.href='/<?= $$widgettitlelink ?>'" style="cursor:pointer">
<?php
if ($divdisplay != "block") {?>
<div id="<?= $widgetname ?>-loader" style="display:<?= $display ?>;" align="center">
<br />
<span class="glyphicon glyphicon-refresh"></span> <?= gettext("Loading selected widget") ?>
<br />
</div> <?php $display = "none";
}
if (file_exists($directory . $widget)) {
if ($divdisplay == 'block') {
include($directory . $widget);
}
}
$widgetcounter++; ?>
endif;
echo empty($$widgettitle) ? $widgetItem['display_name'] : $$widgettitle;
if (isset($$widgettitlelink)):?>
</span></u>
<?php
endif;?>
</h3></li>
<li class="pull-right">
<div class="btn-group">
<button type="button" class="btn btn-default btn-xs disabled" id="<?= $widgetItem['name'] ?>-configure" onclick='return configureWidget("<?= $widgetItem['name'] ?>")' style="cursor:pointer" ><span class="glyphicon glyphicon-pencil"></span></button>
<button type="button" class="btn btn-default btn-xs" title="minimize" id="<?= $widgetItem['name'] ?>-min" onclick='return minimizeWidget("<?= $widgetItem['name'] ?>",true)' style="display:<?= $mindiv ?>;"><span class="glyphicon glyphicon-minus"></span></button>
<button type="button" class="btn btn-default btn-xs" title="maximize" id="<?= $widgetItem['name'] ?>-max" onclick='return showWidget("<?= $widgetItem['name'] ?>",true)' style="display:<?= $mindiv == 'none' ? 'inline' : 'none' ?>;"><span class="glyphicon glyphicon-plus"></span></button>
<button type="button" class="btn btn-default btn-xs" title="remove widget" onclick='return closeWidget("<?= $widgetItem['name'] ?>",true)'><span class="glyphicon glyphicon-remove"></span></button>
</div>
</li>
</ul>
</header>
<div class="content-box-main collapse in" id="<?= $widgetItem['name'] ?>-container" style="display:<?= $mindiv ?>">
<input type="hidden" value="<?= $inputdisplay ?>" id="<?= $widgetItem['name'] ?>-config" name="<?= $widgetItem['name'] ?>-config" />
<?php
if ($divdisplay != "block"):?>
<div id="<?= $widgetItem['name'] ?>-loader" style="display:<?= $display ?>;">
&nbsp;&nbsp;<span class="glyphicon glyphicon-refresh"></span> <?= gettext("Save to load widget") ?>
</div>
<?php
else:
include($widgetItem['filename']);
endif;
?>
</div>
</div>
</section>
<?php
} //end foreach ?>
endforeach;?>
</div>
<div class="col-md-4 dashboard_grid_column" id="dashboard_col1"></div>
<div class="col-md-4 dashboard_grid_column" id="dashboard_col2"></div>
<div class="col-md-4 dashboard_grid_column" id="dashboard_col3"></div>
<div class="col-md-4 dashboard_grid_column" id="dashboard_col4"></div>
</div>
</div>
</section>
<?php
//build list of javascript include files
$jsincludefiles = array();
$directory = "widgets/javascript/";
$dirhandle = opendir($directory);
$filename = "";
while (false !== ($filename = readdir($dirhandle))) {
$jsincludefiles[] = $filename;
}
foreach ($jsincludefiles as $jsincludename) {
if (!preg_match('/\.js$/', $jsincludename)) {
continue;
}
echo "<script src='{$directory}{$jsincludename}' type='text/javascript'></script>\n";
}
?>
<?php include("foot.inc");
endif;
include("foot.inc");?>
/* 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;
}
/*
$Id: thermal_sensors.js
Description:
Javascript functions to get and show thermal sensors data in thermal_sensors.widget.php.
NOTE: depends on proper cofing in System >> Advanced >> Miscellaneous tab >> Thermal Sensors section.
File location:
\usr\local\www\widgets\javascript\
Used by:
\usr\local\www\widgets\widgets\thermal_sensors.widget.php
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.
*/
//should be called from "thermal_sensors.widget.php"
function showThermalSensorsData() {
//get data from thermal_sensors.widget.php
url = "/widgets/widgets/thermal_sensors.widget.php?getThermalSensorsData=1"
//IE fix to disable cache when using http:// , just append timespan
+ new Date().getTime();
jQuery.ajax(url, {
type: 'get',
success: function(data) {
var thermalSensorsData = data || "";
buildThermalSensorsData(thermalSensorsData);
},
error: function(jqXHR, status, error){
buildThermalSensorsDataRaw(
"Error getting data from [thermal_sensors.widget.php] - |" +
"status: [" + (status || "") + "]|" +
"error: [" + (error || "") + "]");
}
});
//call itself in 11 seconds
window.setTimeout(showThermalSensorsData, 11000);
}
function buildThermalSensorsData(thermalSensorsData) {
//NOTE: variable thermal_sensors_widget_showRawOutput is declared/set in "thermal_sensors.widget.php"
if (thermal_sensors_widget_showRawOutput) {
buildThermalSensorsDataRaw(thermalSensorsData);
}
else {
buildThermalSensorsDataGraph(thermalSensorsData);
}
}
function buildThermalSensorsDataRaw(thermalSensorsData) {
var thermalSensorsContent = "";
if (thermalSensorsData && thermalSensorsData != "") {
thermalSensorsContent = thermalSensorsData.replace(/\|/g, "<br />");
//rawData = thermalSensorsData.split("|").join("<br />");
}
loadThermalSensorsContainer(thermalSensorsContent);
}
function loadThermalSensorsContainer (thermalSensorsContent) {
if (thermalSensorsContent && thermalSensorsContent != "") {
//load generated graph (or raw data) into thermalSensorsContainer (thermalSensorsContainer DIV defined in "thermal_sensors.widget.php")
jQuery('#thermalSensorsContainer').html(thermalSensorsContent);
} else {
jQuery('#thermalSensorsContainer').html("No Thermal Sensors data available.<br /><br />");
jQuery('<div/>').html(
"<span>* You can configure a proper Thermal Sensor / Module under <br />" +
"&nbsp;&nbsp;&nbsp;<a href='system_advanced_misc.php'>System &gt; Advanced &gt; Miscellaneous : Thermal Sensors section</a>.</span>"
).appendTo('#thermalSensorsContainer');
}
}
function buildThermalSensorsDataGraph(thermalSensorsData) {
//local constants
var normalColor = "LimeGreen";
var normalColorShadowTop = "Lime";
var normalColorShadowBottom = "Green";
var warningColor = "Orange";
var warningColorShadowBottom = "Chocolate";
var criticalColor = "Red";
var criticalColorShadowBottom = "DarkRed";
//local variables
var barBgColor = normalColor; //green/normal as default
var barBgColorShadowTop = normalColorShadowTop; //green/normal as default
var barBgColorShadowBottom = normalColorShadowBottom; //green/normal as default
var thermalSensorsArray = new Array();
if (thermalSensorsData && thermalSensorsData != ""){
thermalSensorsArray = thermalSensorsData.split("|");
}
var thermalSensorsHTMLContent = "";
var itemsToPulsate = new Array();
//generate graph for each temperature sensor and append to thermalSensorsHTMLContent string
for (var i = 0; i < thermalSensorsArray.length; i++) {
var sensorDataArray = thermalSensorsArray[i].split(":");
var sensorName = sensorDataArray[0].trim();
var thermalSensorValue = getThermalSensorValue(sensorDataArray[1]);
var pulsateTimes = 0;
var pulsateDuration = 0;
var warningTempThresholdPosition = 0;
var criticalTempThresholdPosition = 0;
//NOTE: the following variables are declared/set in "thermal_sensors.widget.php":
// thermal_sensors_widget_coreWarningTempThreshold, thermal_sensors_widget_coreCriticalTempThreshold,
// thermal_sensors_widget_zoneWarningTempThreshold, thermal_sensors_widget_zoneCriticalTempThreshold
// thermal_sensors_widget_pulsateWarning, thermal_sensors_widget_pulsateCritical
//set graph color and pulsate parameters
if (sensorName.indexOf("cpu") > -1) { //check CPU Threshold config settings
warningTempThresholdPosition = thermal_sensors_widget_coreWarningTempThreshold;
criticalTempThresholdPosition = thermal_sensors_widget_coreCriticalTempThreshold;
if (thermalSensorValue < thermal_sensors_widget_coreWarningTempThreshold) {
barBgColor = normalColor;
barBgColorShadowTop = normalColorShadowTop;
barBgColorShadowBottom = normalColorShadowBottom;
pulsateTimes = 0;
pulsateDuration = 0;
} else if (thermalSensorValue >= thermal_sensors_widget_coreWarningTempThreshold && thermalSensorValue < thermal_sensors_widget_coreCriticalTempThreshold) {
barBgColor = warningColor;
barBgColorShadowTop = warningColor;
barBgColorShadowBottom = warningColorShadowBottom;
pulsateTimes = thermal_sensors_widget_pulsateWarning ? 4 : 0;
pulsateDuration = thermal_sensors_widget_pulsateWarning ? 900 : 0;
} else { // thermalSensorValue > thermal_sensors_widget_coreCriticalTempThreshold
barBgColor = criticalColor;
barBgColorShadowTop = criticalColor;
barBgColorShadowBottom = criticalColorShadowBottom;
pulsateTimes = thermal_sensors_widget_pulsateCritical ? 7 : 0;
pulsateDuration = thermal_sensors_widget_pulsateCritical ? 900 : 0;
}
} else { //assuming sensor is for a zone, check Zone Threshold config settings
warningTempThresholdPosition = thermal_sensors_widget_zoneWarningTempThreshold;
criticalTempThresholdPosition = thermal_sensors_widget_zoneCriticalTempThreshold;
if (thermalSensorValue < thermal_sensors_widget_zoneWarningTempThreshold) {
barBgColor = normalColor;
barBgColorShadowTop = normalColorShadowTop;
barBgColorShadowBottom = normalColorShadowBottom;
pulsateTimes = 0;
pulsateDuration = 0;
} else if (thermalSensorValue >= thermal_sensors_widget_zoneWarningTempThreshold
&& thermalSensorValue < thermal_sensors_widget_zoneCriticalTempThreshold) {
barBgColor = warningColor;
barBgColorShadowTop = warningColor;
barBgColorShadowBottom = warningColorShadowBottom;
pulsateTimes = thermal_sensors_widget_pulsateWarning ? 4 : 0;
pulsateDuration = thermal_sensors_widget_pulsateWarning ? 900 : 0;
} else { // thermalSensorValue > thermal_sensors_widget_zoneCriticalTempThreshold
barBgColor = criticalColor;
barBgColorShadowTop = criticalColor;
barBgColorShadowBottom = criticalColorShadowBottom;
pulsateTimes = thermal_sensors_widget_pulsateCritical ? 7 : 0;
pulsateDuration = thermal_sensors_widget_pulsateCritical ? 900 : 0;
}
}
//NOTE: variable thermal_sensors_widget_showFullSensorName is declared/set in "thermal_sensors.widget.php"
if (!thermal_sensors_widget_showFullSensorName) {
sensorName = getSensorFriendlyName(sensorName);
}
//build temperature item/row for a sensor
//NOTE: additional styles are set in 'thermal_sensors.widget.php'
var thermalSensorRow = "<div class='thermalSensorRow' id='thermalSensorRow" + i + "' >" +
//sensor name and temperature value
" <div class='thermalSensorTextShell'><div class='thermalSensorText' id='thermalSensorText" + i + "'>" + sensorName + ": </div><div class='thermalSensorValue' id='thermalSensorValue" + i + "'>" + thermalSensorValue + " &deg;C</div></div>" +
//temperature bar
" <div class='thermalSensorBarShell' id='thermalSensorBarShell" + i + "' >" +
" <div class='thermalSensorBar' id='thermalSensorBar" + i + "' style='background-color: " + barBgColor + "; border-top-color: " + barBgColorShadowTop + "; border-bottom-color: " + barBgColorShadowBottom + "; width:" + thermalSensorValue + "%;' ></div>" +
//threshold targets (warning and critical)
" <div class='thermalSensorWarnThresh' id='thermalSensorWarnThresh" + i + "' style='left:" + warningTempThresholdPosition + "%;' ></div>" +
" <div class='thermalSensorCritThresh' id='thermalSensorCritThresh" + i + "' style='left:" + criticalTempThresholdPosition + "%;' ></div>" +
//temperature scale (max 100 C)
" <div class='thermal_sensors_widget_scale000'></div>" +
" <div class='thermal_sensors_widget_scale010'></div>" +
" <div class='thermal_sensors_widget_scale020'></div>" +
" <div class='thermal_sensors_widget_scale030'></div>" +
" <div class='thermal_sensors_widget_scale040'></div>" +
" <div class='thermal_sensors_widget_scale050'></div>" +
" <div class='thermal_sensors_widget_scale060'></div>" +
" <div class='thermal_sensors_widget_scale070'></div>" +
" <div class='thermal_sensors_widget_scale080'></div>" +
" <div class='thermal_sensors_widget_scale090'></div>" +
" <div class='thermal_sensors_widget_scale100'></div>" +
" <div class='thermal_sensors_widget_mark100'>100&deg;</div>" +
" </div>" +
"</div>";
//collect parameters for warning/critical items we need to pulsate
if (pulsateTimes > 0) {
var params = i + "|" + barBgColor + "|" + pulsateTimes + "|" + pulsateDuration;
itemsToPulsate.push(params);
}
//append HTML item
thermalSensorsHTMLContent = thermalSensorsHTMLContent + thermalSensorRow;
}
//load generated graph into thermalSensorsContainer (DIV defined in "thermal_sensors.widget.php")
loadThermalSensorsContainer(thermalSensorsHTMLContent);
if (itemsToPulsate.length > 0) {
//pulsate/flash warning/critical items we collected
pulsateThermalSensorsItems(itemsToPulsate);
}
}
function pulsateThermalSensorsItems(itemsToPulsate) {
//pulsate/flash warning/critical items we collected
for (var i = 0; i < itemsToPulsate.length; i++) {
var pulsateParams = itemsToPulsate[i].split("|");
var rowNum = parseInt(pulsateParams[0]);
//var textColor = pulsateParams[1];
var pulsateTimes = parseInt(pulsateParams[2]);
var pulsateDuration = parseInt(pulsateParams[3]);
//pulsate temp Value
var divThermalSensorValue = jQuery("#thermalSensorValue" + rowNum); //get temp value by id
divThermalSensorValue.effect("pulsate", {
times: pulsateTimes
,easing: 'linear' //'easeInExpo'
}, pulsateDuration);
////set Temp Value color
//divThermalSensorValue.css( { color: textColor } );
//pulsate temp Bar
var divThermalSensorBar = jQuery("#thermalSensorBar" + rowNum); //get temp bar by id
divThermalSensorBar.effect("pulsate", {
times: pulsateTimes
,easing: 'linear' //'easeInExpo'
}, pulsateDuration);
}
}
function getSensorFriendlyName(sensorFullName){
var rzone = /^hw\.acpi\.thermal\.tz([0-9]+)\.temperature$/;
var rcore = /^dev\.cpu\.([0-9]+)\.temperature$/;
if (rzone.test(sensorFullName))
return "Zone " + rzone.exec(sensorFullName)[1];
if (rcore.test(sensorFullName))
return "Core " + rcore.exec(sensorFullName)[1];
return sensorFullName;
}
function getThermalSensorValue(stringValue){
return (+parseFloat(stringValue) || 0).toFixed(1);
}
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>
<?php
/*
Copyright (C) 2014 Deciso B.V.
Copyright (C) 2007 Scott Dale
Copyright (C) 2004-2005 T. Lechat <dev@lechat.org>, Manuel Kasper <mk@neon1.net>
and Jonathan Watt <jwatt@jwatt.org>.
All rights reserved.
Copyright (C) 2014-2016 Deciso B.V.
Copyright (C) 2007 Scott Dale
Copyright (C) 2004-2005 T. Lechat <dev@lechat.org>, Manuel Kasper <mk@neon1.net>
and Jonathan Watt <jwatt@jwatt.org>.
All rights reserved.
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/interfaces.inc");
require_once("interfaces.inc");
$i = 0;
$iswireless=false;
$ifdescrs = get_configured_interface_with_descr();
?>
<table class="table table-striped">
<?php
foreach ($ifdescrs as $ifdescr => $ifname) {
$ifinfo = get_interface_info($ifdescr);
$iswireless = is_interface_wireless($ifdescr);
?>
<tr>
<td class="vncellt" >
<?php
if (isset($ifinfo['ppplink'])) {
?> <span alt="3g" class="glyphicon glyphicon-phone text-success"></span> <?php
} elseif ($iswireless) {
if ($ifinfo['status'] == 'associated' || $ifinfo['status'] == 'up') {
?>
<span alt="wlan" class="glyphicon glyphicon-signal text-success"></span>
<?php
} else {
?>
<span alt="wlan_d" class="glyphicon glyphicon-signal text-danger"></span>
<?php
} ?>
<?php
} else {
?>
<?php if ($ifinfo['status'] == "up") {
?>
<span alt="cablenic" id="<?php echo $ifname . 'icon';?>" class="glyphicon glyphicon-transfer text-success"></span>
<?php
} else {
?>
<span alt="cablenic" id="<?php echo $ifname . 'icon';?>" class="glyphicon glyphicon-transfer text-danger"></span>
<?php
} ?>
<?php
} ?>&nbsp;
<strong><u>
<span onclick="location.href='/interfaces.php?if=<?=$ifdescr; ?>'" style="cursor:pointer">
<?=htmlspecialchars($ifname);?></span></u></strong>
<?php
if (isset($ifinfo['dhcplink'])) {
echo "&nbsp;(DHCP)";
}
?>
</td>
<?php if ($ifinfo['status'] == "up" || $ifinfo['status'] == "associated") {
?>
<td class="listr" align="center">
<span id="<?php echo $ifname;?>" class="glyphicon glyphicon-arrow-up text-success"></span>
</td>
<?php
} elseif ($ifinfo['status'] == "no carrier") {
?>
<td class="listr" align="center">
<span id="<?php echo $ifname;?>" class="glyphicon glyphicon-arrow-down text-danger"></span>
</td>
<?php
} elseif ($ifinfo['status'] == "down") {
?>
<td class="listr" align="center">
<span id="<?php echo $ifname;?>" class="glyphicon glyphicon-arrow-remove text-danger"></span>
</td>
<?php
} else {
?><?=htmlspecialchars($ifinfo['status']);
}?>
<td class="listr">
<div id="<?php echo $ifname; ?>" style="display:inline"><?php
$media = $ifinfo['media'];
if (empty($media)) {
$media = $ifinfo['cell_mode'];
}
echo htmlspecialchars($media);
?></div>
</td>
<td class="vncellt">
<?php if ($ifinfo['ipaddr'] != "") {
?>
<div id="<?php echo $ifname;
?>-ip" style="display:inline"><?=htmlspecialchars($ifinfo['ipaddr']);?> </div>
<br />
<?php
}
if ($ifinfo['ipaddrv6'] != "") {
?>
<div id="<?php echo $ifname;
?>-ipv6" style="display:inline"><?=htmlspecialchars($ifinfo['ipaddrv6']);?> </div>
<?php
} ?>
</td>
</tr>
<?php
}//end for each ?>
</table>
<script type="text/javascript">
/**
* Hybrid widget only update interface status using ajax
*/
function interface_widget_update(sender, data)
{
var tbody = sender.find('tbody');
data.map(function(interface_data) {
var tr_id = 'interface_widget_item_' + interface_data['name'];
if (tbody.find("#"+tr_id).length != 0) {
switch (interface_data['status']) {
case 'up':
$("#"+tr_id).find('.text-danger').removeClass('text-danger').addClass('text-success');
$("#"+tr_id).find('.glyphicon-arrow-down').removeClass('glyphicon-arrow-down').addClass('glyphicon-arrow-up');
$("#"+tr_id).find('.glyphicon-arrow-remove').removeClass('glyphicon-arrow-remove').addClass('glyphicon-arrow-up');
break;
case 'down':
$("#"+tr_id).find('.text-success').removeClass('text-success').addClass('text-danger');
$("#"+tr_id).find('.glyphicon-arrow-up').removeClass('glyphicon-arrow-up').addClass('glyphicon-arrow-down');
$("#"+tr_id).find('.glyphicon-arrow-remove').removeClass('glyphicon-arrow-remove').addClass('glyphicon-arrow-down');
break;
default:
$("#"+tr_id).find('.text-success').removeClass('text-success').addClass('text-danger');
$("#"+tr_id).find('.glyphicon-arrow-down').removeClass('glyphicon-arrow-down').addClass('glyphicon-arrow-remove');
$("#"+tr_id).find('.glyphicon-arrow-up').removeClass('glyphicon-arrow-up').addClass('glyphicon-arrow-remove');
}
}
});
}
</script>
<table class="table table-striped table-condensed" data-plugin="interfaces" data-callback="interface_widget_update">
<tbody>
<?php
foreach (get_configured_interface_with_descr() as $ifdescr => $ifname):
$ifinfo = get_interface_info($ifdescr);
$iswireless = is_interface_wireless($ifdescr);?>
<tr id="interface_widget_item_<?=$ifname;?>">
<td>
<?php
if (isset($ifinfo['ppplink'])):?>
<span alt="3g" class="glyphicon glyphicon-phone text-success"></span>
<?php
elseif ($iswireless):
if ($ifinfo['status'] == 'associated' || $ifinfo['status'] == 'up'):?>
<span alt="wlan" class="glyphicon glyphicon-signal text-success"></span>
<?php
else:?>
<span alt="wlan_d" class="glyphicon glyphicon-signal text-danger"></span>
<?php
endif;?>
<?php
else:?>
<?php
if ($ifinfo['status'] == "up"):?>
<span alt="cablenic" class="glyphicon glyphicon-transfer text-success"></span>
<?php
else:?>
<span alt="cablenic" class="glyphicon glyphicon-transfer text-danger"></span>
<?php
endif;?>
<?php
endif;?>
&nbsp;
<strong>
<u>
<span onclick="location.href='/interfaces.php?if=<?=htmlspecialchars($ifdescr); ?>'" style="cursor:pointer">
<?=htmlspecialchars($ifname);?>
</span>
</u>
</strong>
</td>
<td>
<?php
if ($ifinfo['status'] == "up" || $ifinfo['status'] == "associated"):?>
<span class="glyphicon glyphicon-arrow-up text-success"></span>
<?php
elseif ($ifinfo['status'] == "no carrier"):?>
<span class="glyphicon glyphicon-arrow-down text-danger"></span>
<?php
elseif ($ifinfo['status'] == "down"):?>
<span class="glyphicon glyphicon-arrow-remove text-danger"></span>
<?php
else:?>
<?=htmlspecialchars($ifinfo['status']);?>
<?php
endif;?>
<td>
<?=empty($ifinfo['media']) ? htmlspecialchars($ifinfo['cell_mode']) : htmlspecialchars($ifinfo['media']);?>
</td>
<td>
<?=htmlspecialchars($ifinfo['ipaddr']);?>
<?=!empty($ifinfo['ipaddr']) ? "<br/>" : "";?>
<?=htmlspecialchars($ifinfo['ipaddrv6']);?>
</td>
</tr>
<?php
endforeach;?>
</tbody>
</table>
<?php
/*
Copyright (C) 2014 Deciso B.V.
Copyright (C) 2007 Scott Dale
Copyright (C) 2004-2005 T. Lechat <dev@lechat.org>, Manuel Kasper <mk@neon1.net>
and Jonathan Watt <jwatt@jwatt.org>.
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.
Copyright (C) 2014-2016 Deciso B.V.
Copyright (C) 2007 Scott Dale
Copyright (C) 2004-2005 T. Lechat <dev@lechat.org>, Manuel Kasper <mk@neon1.net>
and Jonathan Watt <jwatt@jwatt.org>.
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.
*/
$nocsrf = true;
require_once("guiconfig.inc");
require_once("pfsense-utils.inc");
require_once("interfaces.inc");
require_once("widgets/include/interface_statistics.inc");
$ifdescrs = get_configured_interface_with_descr();
$array_in_packets = array();
$array_out_packets = array();
$array_in_bytes = array();
$array_out_bytes = array();
$array_in_errors = array();
$array_out_errors = array();
$array_collisions = array();
$array_interrupt = array();
$interfacecounter = 0;
//build data arrays
foreach ($ifdescrs as $ifdescr => $ifname) {
$ifinfo = get_interface_info($ifdescr);
$interfacecounter++;
if ($ifinfo['status'] != "down") {
$array_in_packets[] = $ifinfo['inpkts'];
$array_out_packets[] = $ifinfo['outpkts'];
$array_in_bytes[] = format_bytes($ifinfo['inbytes']);
$array_out_bytes[] = format_bytes($ifinfo['outbytes']);
if (isset($ifinfo['inerrs'])) {
$array_in_errors[] = $ifinfo['inerrs'];
$array_out_errors[] = $ifinfo['outerrs'];
} else {
$array_in_errors[] = gettext("n/a");
$array_out_errors[] = gettext("n/a");
}
if (isset($ifinfo['collisions'])) {
$array_collisions[] = htmlspecialchars($ifinfo['collisions']);
} else {
$array_collisions[] = gettext("n/a");
}
}
}//end for
?>
<div id="int_labels" style="float:left;width:32%">
<table class="table table-striped" width="100%" border="0" cellspacing="0" cellpadding="0" summary="interfaces statistics">
<tr><td class="widgetsubheader" style="height:25px">&nbsp;&nbsp;&nbsp;</td></tr>
<tr>
<td><b><?php echo gettext('Packets In')?></b></td>
</tr>
<tr>
<td><b><?php echo gettext('Packets Out')?></b></td>
</tr>
<tr>
<td><b><?php echo gettext('Bytes In')?></b></td>
</tr>
<tr>
<td><b><?php echo gettext('Bytes Out')?></b></td>
</tr>
<tr>
<td><b><?php echo gettext('Errors In')?></b></td>
</tr>
<tr>
<td><b><?php echo gettext('Errors Out')?></b></td>
</tr>
<tr>
<td><b><?php echo gettext('Collisions')?></b></td>
</tr>
</table>
</div>
<div id="interfacestats" style="float:right;overflow: auto; width:68%">
<table class="table table-striped" width="100%" border="0" cellspacing="0" cellpadding="0" summary="the stats">
<tr>
<?php
$interface_names = array();
foreach ($ifdescrs as $ifdescr => $ifname) :
$ifinfo = get_interface_info($ifdescr);
if ($ifinfo['status'] != "down") {
?>
<td class="widgetsubheader nowrap" style="height:25px">
<b><?=htmlspecialchars($ifname);?></b>
</td>
<?php
//build array of interface names
$interface_names[] = $ifname;
}
endforeach; ?>
</tr>
<tr>
<?php
$counter = 1;
foreach ($array_in_packets as $data) :
?>
<td class="listr nowrap" id="stat<?php echo $counter?>" style="height:25px">
<?=htmlspecialchars($data);?>
</td>
<?php
$counter = $counter + 7;
endforeach; ?>
</tr>
<tr>
<?php
$counter = 2;
foreach ($array_out_packets as $data) :
?>
<td class="listr nowrap" id="stat<?php echo $counter;?>" style="height:25px">
<?=htmlspecialchars($data);?>
</td>
<?php
$counter = $counter + 7;
endforeach; ?>
</tr>
<tr>
<?php
$counter = 3;
foreach ($array_in_bytes as $data) :
?>
<td class="listr nowrap" id="stat<?php echo $counter;?>" style="height:25px">
<?=htmlspecialchars($data);?>
</td>
<?php
$counter = $counter + 7;
endforeach; ?>
</tr>
<tr>
<?php
$counter = 4;
foreach ($array_out_bytes as $data) :
?>
<td class="listr nowrap" id="stat<?php echo $counter;?>" style="height:25px">
<?=htmlspecialchars($data);?>
</td>
<?php
$counter = $counter + 7;
endforeach; ?>
</tr>
<tr>
<?php
$counter = 5;
foreach ($array_in_errors as $data) :
?>
<td class="listr nowrap" id="stat<?php echo $counter;?>" style="height:25px">
<?=htmlspecialchars($data);?>
</td>
<?php
$counter = $counter + 7;
endforeach; ?>
</tr>
<tr>
<?php
$counter = 6;
foreach ($array_out_errors as $data) :
?>
<td class="listr nowrap" id="stat<?php echo $counter;?>" style="height:25px">
<?=htmlspecialchars($data);?>
</td>
<?php
$counter = $counter + 7;
endforeach; ?>
</tr>
<tr>
<?php
$counter = 7;
foreach ($array_collisions as $data) :
?>
<td class="listr nowrap" id="stat<?php echo $counter;?>" style="height:25px">
<?=htmlspecialchars($data);?>
</td>
<?php
$counter = $counter + 7;
endforeach; ?>
</tr>
</table>
</div>
<script type="text/javascript">
/**
* update interface statistics
*/
function interface_statistics_widget_update(sender, data)
{
var tbody = sender.find('tbody');
var thead = sender.find('thead');
data.map(function(interface_data) {
var th_id = "interface_statistics_widget_intf_" + interface_data['name'];
if (thead.find("#"+th_id).length == 0) {
thead.find('tr:eq(0)').append('<th id="'+th_id+'">'+interface_data['name']+'</th>');
tbody.find('tr').append('<td></td>')
}
// fill in stats, use column index to determine td location
var item_index = $("#"+th_id).index();
$("#interface_statistics_widget_pkg_in > td:eq("+item_index+")").html(interface_data['inpkts']);
$("#interface_statistics_widget_pkg_out > td:eq("+item_index+")").html(interface_data['outpkts']);
$("#interface_statistics_widget_bytes_in > td:eq("+item_index+")").html(interface_data['inbytes_frmt']);
$("#interface_statistics_widget_bytes_out > td:eq("+item_index+")").html(interface_data['outbytes_frmt']);
$("#interface_statistics_widget_errors_in > td:eq("+item_index+")").html(interface_data['inerrs']);
$("#interface_statistics_widget_errors_out > td:eq("+item_index+")").html(interface_data['outerrs']);
$("#interface_statistics_widget_collisions > td:eq("+item_index+")").html(interface_data['collisions']);
});
}
</script>
<table class="table table-striped table-condensed" data-plugin="interfaces" data-callback="interface_statistics_widget_update">
<thead>
<tr>
<th>&nbsp;</th>
</tr>
</thead>
<tbody>
<tr id="interface_statistics_widget_pkg_in"><td><strong><?=gettext('Packets In');?></strong></td></tr>
<tr id="interface_statistics_widget_pkg_out"><td><strong><?=gettext('Packets Out');?></strong></td></tr>
<tr id="interface_statistics_widget_bytes_in"><td><strong><?=gettext('Bytes In');?></strong></td></tr>
<tr id="interface_statistics_widget_bytes_out"><td><strong><?=gettext('Bytes Out');?></strong></td></tr>
<tr id="interface_statistics_widget_errors_in"><td><strong><?=gettext('Errors In');?></strong></td></tr>
<tr id="interface_statistics_widget_errors_out"><td><strong><?=gettext('Errors Out');?></strong></td></tr>
<tr id="interface_statistics_widget_collisions"><td><strong><?=gettext('Collisions');?></strong></td></tr>
</tbody>
</table>
<?php
/*
Copyright (C) 2014-2016 Deciso B.V.
Copyright (C) 2007 Scott Dale
Copyright (C) 2004-2005 T. Lechat <dev@lechat.org>, Manuel Kasper <mk@neon1.net>
and Jonathan Watt <jwatt@jwatt.org>.
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.
*/
Copyright (C) 2014-2016 Deciso B.V.
Copyright (C) 2007 Scott Dale
Copyright (C) 2004-2005 T. Lechat <dev@lechat.org>, Manuel Kasper <mk@neon1.net>
and Jonathan Watt <jwatt@jwatt.org>.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
$nocsrf = true;
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.
*/
require_once("guiconfig.inc");
......@@ -70,6 +68,7 @@ if (isset($config['ipsec']['phase1'])) {
echo "&nbsp;&nbsp;&nbsp;</b>";
echo "</div>";
}
echo "</div>";
$ipsec_leases = json_decode(configd_run("ipsec list leases"), true);
if ($ipsec_leases == null) {
......@@ -106,7 +105,45 @@ if (isset($config['ipsec']['phase1'])) {
if (isset($config['ipsec']['phase2'])) {
?>
<script type="text/javascript">
function changeTabDIV(selectedDiv){
var dashpos = selectedDiv.indexOf("-");
var tabclass = selectedDiv.substring(0,dashpos);
d = document;
//get deactive tabs first
tabclass = tabclass + "-class-tabdeactive";
var tabs = document.getElementsByClassName(tabclass);
var incTabSelected = selectedDiv + "-deactive";
for (i=0; i<tabs.length; i++){
var tab = tabs[i].id;
dashpos = tab.lastIndexOf("-");
var tab2 = tab.substring(0,dashpos) + "-deactive";
if (tab2 == incTabSelected){
tablink = d.getElementById(tab2);
tablink.style.display = "none";
tab2 = tab.substring(0,dashpos) + "-active";
tablink = d.getElementById(tab2);
tablink.style.display = "table-cell";
//now show main div associated with link clicked
tabmain = d.getElementById(selectedDiv);
tabmain.style.display = "block";
}
else
{
tab2 = tab.substring(0,dashpos) + "-deactive";
tablink = d.getElementById(tab2);
tablink.style.display = "table-cell";
tab2 = tab.substring(0,dashpos) + "-active";
tablink = d.getElementById(tab2);
tablink.style.display = "none";
//hide sections we don't want to see
tab2 = tab.substring(0,dashpos);
tabmain = d.getElementById(tab2);
tabmain.style.display = "none";
}
}
}
</script>
<div id="ipsec-Overview" style="display:block;background-color:#EEEEEE;">
<table class="table table-striped">
<thead>
......
<?php
/*
Copyright (C) 2014 Deciso B.V.
Copyright (C) 2010 Jim Pingle
Copyright (C) 2010 Seth Mos <seth.mos@dds.nl>
Copyright (C) 2005-2008 Bill Marquette
Copyright (C) 2004-2005 T. Lechat <dev@lechat.org>, Manuel Kasper <mk@neon1.net>
and Jonathan Watt <jwatt@jwatt.org>.
All rights reserved.
Copyright (C) 2014 Deciso B.V.
Copyright (C) 2010 Jim Pingle
Copyright (C) 2010 Seth Mos <seth.mos@dds.nl>
Copyright (C) 2005-2008 Bill Marquette
Copyright (C) 2004-2005 T. Lechat <dev@lechat.org>, Manuel Kasper <mk@neon1.net>
and Jonathan Watt <jwatt@jwatt.org>.
All rights reserved.
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("filter.inc");
......@@ -61,16 +59,18 @@ $nentries = isset($config['syslog']['nentries']) ? $config['syslog']['nentries']
?>
<table class="table table-stiped" bgcolor="#990000" width="100%" border="0" cellspacing="0" cellpadding="0" summary="load balancer">
<thead>
<td width="10%" class="listhdrr"><?= gettext('Server') ?></td>
<td width="10%" class="listhdrr"><?= gettext('Pool') ?></td>
<td width="30%" class="listhdr"><?= gettext('Description') ?></td>
</thead>
<?php $i = 0; foreach ($a_vs as $vsent) :
<table class="table table-striped table-condensed">
<thead>
<tr>
<th width="10%" class="listhdrr"><?= gettext('Server') ?></th>
<th width="10%" class="listhdrr"><?= gettext('Pool') ?></th>
<th width="30%" class="listhdr"><?= gettext('Description') ?></th>
</tr>
</thead>
<?php $i = 0; foreach ($a_vs as $vsent) :
?>
<tr>
<?php
<tr>
<?php
switch (trim($rdr_a[$vsent['name']]['status'])) {
case 'active':
$bgcolor = "#90EE90"; // lightgreen
......@@ -85,14 +85,14 @@ $nentries = isset($config['syslog']['nentries']) ? $config['syslog']['nentries']
$rdr_a[$vsent['name']]['status'] = gettext('Unknown - relayd not running?');
}
?>
<td class="listlr">
<?=$vsent['name'];?><br />
<span style="background-color: <?=$bgcolor?>; display: block"><i><?= $rdr_a[$vsent['name']]['status'] ?></i></span>
<?=$vsent['ipaddr'].":".$vsent['port'];?><br />
</td>
<td class="listr" align="center" >
<table border="0" cellpadding="0" cellspacing="2" summary="status">
<?php
<td class="listlr">
<?=$vsent['name'];?><br />
<span style="background-color: <?=$bgcolor?>; display: block"><i><?= $rdr_a[$vsent['name']]['status'] ?></i></span>
<?=$vsent['ipaddr'].":".$vsent['port'];?><br />
</td>
<td class="listr" align="center" >
<table>
<?php
foreach ($a_pool as $pool) {
if ($pool['name'] == $vsent['poolname']) {
$pool_hosts=array();
......@@ -135,13 +135,13 @@ $nentries = isset($config['syslog']['nentries']) ? $config['syslog']['nentries']
}
}
?>
</table>
</td>
<td class="listbg" >
<?=$vsent['descr'];?>
</td>
</tr>
<?php $i++;
</table>
</td>
<td class="listbg" >
<?=$vsent['descr'];?>
</td>
</tr>
<?php $i++;
endforeach; ?>
</table>
......@@ -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>
<?php
/*
Copyright (C) 2014 Deciso B.V.
Copyright (c) 2007 Scott Dale
Copyright (C) 2004-2005 T. Lechat <dev@lechat.org>, Manuel Kasper <mk@neon1.net>
and Jonathan Watt <jwatt@jwatt.org>.
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.
Copyright (C) 2014 Deciso B.V.
Copyright (c) 2007 Scott Dale
Copyright (C) 2004-2005 T. Lechat <dev@lechat.org>, Manuel Kasper <mk@neon1.net>
and Jonathan Watt <jwatt@jwatt.org>.
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.
*/
$nocsrf = true;
require_once("guiconfig.inc");
require_once("pfsense-utils.inc");
require_once("widgets/include/ntp_status.inc");
......@@ -125,42 +123,42 @@ if ($_REQUEST['updateme']) {
}
?>
<table class="table table-striped" width="100%" border="0" cellspacing="0" cellpadding="0" summary="clock">
<tbody>
<tr>
<td width="40%" class="vncellt">Sync Source</td>
<td width="60%" class="listr">
<?php if ($ntpq_counter == 0) :
<table >
<tbody>
<tr>
<td width="40%" class="vncellt">Sync Source</td>
<td width="60%" class="listr">
<?php if ($ntpq_counter == 0) :
?>
<?= gettext('No active peers available') ?>
<?php
<?php
else :
?>
<?php echo $syncsource; ?>
<?php
<?php echo $syncsource; ?>
<?php
endif; ?>
</td>
</tr>
<?php if (($gps_ok) && ($gps_lat) && ($gps_lon)) :
</td>
</tr>
<?php if (($gps_ok) && ($gps_lat) && ($gps_lon)) :
?>
<tr>
<tr>
<td width="40%" class="vncellt"><?= gettext('Clock location') ?></td>
<td width="60%" class="listr">
<a target="_gmaps" href="http://maps.google.com/?q=<?php echo $gps_lat; ?>,<?php echo $gps_lon; ?>">
<?php
<td width="60%" class="listr">
<a target="_gmaps" href="http://maps.google.com/?q=<?php echo $gps_lat; ?>,<?php echo $gps_lon; ?>">
<?php
echo sprintf("%.5f", $gps_lat) . " " . $gps_la . ", " . sprintf("%.5f", $gps_lon) . " " . $gps_lo; ?>
</a>
<?php if (isset($gps_alt)) {
</a>
<?php if (isset($gps_alt)) {
echo " (" . $gps_alt . " " . $gps_alt_unit . " alt.)";
} ?>
</td>
</tr>
<?php if (isset($gps_sat) || isset($gps_satview)) :
</td>
</tr>
<?php if (isset($gps_sat) || isset($gps_satview)) :
?>
<tr>
<tr>
<td width="40%" class="vncellt"><?= gettext('Satellites') ?></td>
<td width="60%" class="listr">
<?php
<td width="60%" class="listr">
<?php
if (isset($gps_satview)) {
echo gettext('in view ') . intval($gps_satview);
}
......@@ -171,13 +169,13 @@ endif; ?>
echo gettext('in use ') . $gps_sat;
}
?>
</td>
</tr>
<?php
</td>
</tr>
<?php
endif; ?>
<?php
<?php
endif; ?>
</tbody>
</tbody>
</table>
<?php
exit;
......@@ -246,9 +244,9 @@ classic Netscape, or Netscape 6/W3C DOM methods is available.
The optional inLayer argument helps Netscape 4 find objects in
the named layer or floating DIV. */
function simpleFindObj(name, inLayer) {
return document[name] || (document.all && document.all[name])
|| (document.getElementById && document.getElementById(name))
|| (document.layers && inLayer && document.layers[inLayer].document[name]);
return document[name] || (document.all && document.all[name])
|| (document.getElementById && document.getElementById(name))
|| (document.layers && inLayer && document.layers[inLayer].document[name]);
}
/*** Beginning of Clock 2.1.2, by Andrew Shearer
......@@ -279,12 +277,12 @@ Compatibility: IE 4.x and 5.0, Netscape 4.x and 6.0, Mozilla 1.0. Mac & Windows.
History: 1.0 2000-05-09 GIF-image digits
2.0 2000-06-29 Uses text DIV layers (so 4.0 browsers req'd), &
cookies to work around Win IE stale-time bug
2.1 2002-10-12 Noted Mozilla 1.0 compatibility; released PHP version.
2.1.1 2002-10-20 Fixed octal bug in the PHP translation; the number of
minutes & seconds were misinterpretes when less than 10
2.1.2 2003-08-07 The previous fix had introduced a bug when the
minutes or seconds were exactly 0. Thanks to Man Bui
for reporting the bug.
2.1 2002-10-12 Noted Mozilla 1.0 compatibility; released PHP version.
2.1.1 2002-10-20 Fixed octal bug in the PHP translation; the number of
minutes & seconds were misinterpretes when less than 10
2.1.2 2003-08-07 The previous fix had introduced a bug when the
minutes or seconds were exactly 0. Thanks to Man Bui
for reporting the bug.
*/
var clockIncrementMillis = 1000;
var localTime;
......@@ -365,9 +363,9 @@ function clockToggleSeconds()
}
function clockTimeString(inHours, inMinutes, inSeconds) {
return inHours
+ (inMinutes < 10 ? ":0" : ":") + inMinutes
+ (inSeconds < 10 ? ":0" : ":") + inSeconds;
return inHours
+ (inMinutes < 10 ? ":0" : ":") + inMinutes
+ (inSeconds < 10 ? ":0" : ":") + inSeconds;
}
function clockDisplayTime(inHours, inMinutes, inSeconds) {
......@@ -465,51 +463,45 @@ function clockUpdate()
</script>
<table class="table table-striped" width="100%" border="0" cellspacing="0" cellpadding="0" summary="clock">
<tbody>
<tr>
<td width="40%" class="vncellt">Server Time</td>
<td width="60%" class="listr">
<div id="ClockTime">
<b><?php echo(clockTimeString($gDate, $gClockShowsSeconds));?></b>
</div>
</td>
</tr>
</tbody>
<table class="table table-striped table-condensed">
<tbody>
<tr>
<td width="40%" class="vncellt">Server Time</td>
<td width="60%" class="listr">
<div id="ClockTime">
<b><?php echo(clockTimeString($gDate, $gClockShowsSeconds));?></b>
</div>
</td>
</tr>
<tr>
<td colspan="2" id="ntpstatus">
<?=gettext("Updating...");?>
</td>
</tr>
</tbody>
</table>
<div id='ntpstatus'>
<table width="100%" border="0" cellspacing="0" cellpadding="0" summary="clock">
<tbody>
<tr>
<td width="100%" class="listr">
Updating...
</td>
</tr>
</tbody>
</table>
</div>
<script type="text/javascript">
function ntp_getstatus() {
scroll(0,0);
var url = "/widgets/widgets/ntp_status.widget.php";
var pars = 'updateme=yes';
jQuery.ajax(
url,
{
type: 'get',
data: pars,
complete: ntpstatuscallback
});
// Refresh the status every 1 minute
setTimeout('ntp_getstatus()', 1*60*1000);
}
function ntpstatuscallback(transport) {
// The server returns formatted html code
var responseStringNtp = transport.responseText
jQuery('#ntpstatus').prop('innerHTML',responseStringNtp);
}
// Do the first status check 1 second after the dashboard opens
setTimeout('ntp_getstatus()', 1000);
function ntp_getstatus() {
scroll(0,0);
var url = "/widgets/widgets/ntp_status.widget.php";
var pars = 'updateme=yes';
jQuery.ajax(
url,
{
type: 'get',
data: pars,
complete: ntpstatuscallback
});
// Refresh the status every 1 minute
setTimeout('ntp_getstatus()', 1*60*1000);
}
function ntpstatuscallback(transport) {
// The server returns formatted html code
var responseStringNtp = transport.responseText
jQuery('#ntpstatus').prop('innerHTML',responseStringNtp);
}
// Do the first status check 1 second after the dashboard opens
setTimeout('ntp_getstatus()', 1000);
</script>
<?php
/*
Copyright (C) 2014 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.
Copyright (C) 2014-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.
*/
$nocsrf = true;
require_once("guiconfig.inc");
require_once("openvpn.inc");
/* Handle AJAX */
if ($_GET['action']) {
if ($_GET['action'] == "kill") {
$port = $_GET['port'];
$remipp = $_GET['remipp'];
if (!empty($port) and !empty($remipp)) {
$retval = kill_client($port, $remipp);
echo htmlentities("|{$port}|{$remipp}|{$retval}|");
} else {
echo gettext("invalid input");
}
exit;
}
}
function kill_client($port, $remipp)
{
//$tcpsrv = "tcp://127.0.0.1:{$port}";
$tcpsrv = "unix:///var/etc/openvpn/{$port}.sock";
$errval;
$errstr;
/* open a tcp connection to the management port of each server */
$fp = @stream_socket_client($tcpsrv, $errval, $errstr, 1);
$killed = -1;
if ($fp) {
stream_set_timeout($fp, 1);
fputs($fp, "kill {$remipp}\n");
while (!feof($fp)) {
$line = fgets($fp, 1024);
$info = stream_get_meta_data($fp);
if ($info['timed_out']) {
break;
}
/* parse header list line */
if (strpos($line, "INFO:") !== false) {
continue;
}
if (strpos($line, "SUCCESS") !== false) {
$killed = 0;
}
break;
}
fclose($fp);
}
return $killed;
}
$servers = openvpn_get_active_servers();
$sk_servers = openvpn_get_active_servers("p2p");
$clients = openvpn_get_active_clients();
?>
<br />
<script type="text/javascript">
function killClient(mport, remipp) {
var busy = function(index,icon) {
jQuery(icon).bind("onclick","");
jQuery(icon).attr('src',jQuery(icon).attr('src').replace("\.gif", "_d.gif"));
jQuery(icon).css("cursor","wait");
}
jQuery('span[name="i:' + mport + ":" + remipp + '"]').each(busy);
jQuery.ajax(
"<?=$_SERVER['SCRIPT_NAME'];?>" +
"?action=kill&port=" + mport + "&remipp=" + remipp,
{ type: "get", complete: killComplete }
);
}
function killComplete(req) {
var values = req.responseText.split("|");
if(values[3] != "0") {
alert('<?=gettext("An error occurred.");?>' + ' (' + values[3] + ')');
return;
}
jQuery('tr[name="r:' + values[1] + ":" + values[2] + '"]').each(
function(index,row) { jQuery(row).fadeOut(1000); }
);
}
$( document ).ready(function() {
// link kill buttons
$(".act_kill_client").click(function(event){
event.preventDefault();
var port = $(this).data("client-port");
var ip = $(this).data("client-ip");
$.post('/status_openvpn.php', {action: 'kill', port:port, remipp:ip}, function(data) {
location.reload();
});
});
});
</script>
<?php foreach ($servers as $server) :
?>
<table class="table table-striped" style="padding-top:0px; padding-bottom:0px; padding-left:0px; padding-right:0px" width="100%" border="0" cellpadding="0" cellspacing="0">
<tr>
<td colspan="6" class="listtopic">
<?=$server['name'];?> Client connections
</td>
</tr>
<tr>
<td>
<table style="padding-top:0px; padding-bottom:0px; padding-left:0px; padding-right:0px" class="tabcont sortable" width="100%" border="0" cellpadding="0" cellspacing="0" sortableMultirow="2">
<tr>
<td class="listhdrr">Name/Time</td>
<td class="listhdrr">Real/Virtual IP</td>
</tr>
<?php $rowIndex = 0;
foreach ($server['conns'] as $conn) :
$evenRowClass = $rowIndex % 2 ? " listMReven" : " listMRodd";
$rowIndex++;
?>
<tr name='<?php echo "r:{$server['mgmt']}:{$conn['remote_host']}"; ?>' class="<?=$evenRowClass?>">
<td class="listMRlr">
<?=$conn['common_name'];?>
</td>
<td class="listMRr">
<?=$conn['remote_host'];?>
</td>
<td class='listMR' rowspan="2">
<span class="glyphicon glyphicon-remove"
onclick="killClient('<?php echo $server['mgmt']; ?>', '<?php echo $conn['remote_host']; ?>');" style='cursor:pointer;'
name='<?php echo "i:{$server['mgmt']}:{$conn['remote_host']}"; ?>'
title='Kill client connection from <?php echo $conn['remote_host']; ?>' alt='' ></span>
</td>
</tr>
<tr name='<?php echo "r:{$server['mgmt']}:{$conn['remote_host']}"; ?>' class="<?=$evenRowClass?>">
<td class="listMRlr">
<?=$conn['connect_time'];?>
</td>
<td class="listMRr">
<?=$conn['virtual_addr'];?>
</td>
</tr>
<?php
endforeach; ?>
<tfoot>
<tr>
<td colspan="6" class="list" height="12"></td>
</tr>
</tfoot>
</table>
</td>
</tr>
</table>
<?php
endforeach; ?>
<?php if (!empty($sk_servers)) {
?>
<table class="table table-striped" style="padding-top:0px; padding-bottom:0px; padding-left:0px; padding-right:0px" width="100%" border="0" cellpadding="0" cellspacing="0">
<tr>
<td colspan="6" class="listtopic">
<?= gettext('Peer to Peer Server Instance Statistics') ?>
</td>
</tr>
<tr>
<table style="padding-top:0px; padding-bottom:0px; padding-left:0px; padding-right:0px" class="tabcont sortable" width="100%" border="0" cellpadding="0" cellspacing="0">
<tr>
<td class="listhdrr"><?= gettext('Name/Time') ?></td>
<td class="listhdrr"><?= gettext('Remote/Virtual IP') ?></td>
</tr>
<?php foreach ($sk_servers as $sk_server) :
?>
<tr name='<?php echo "r:{$sk_server['port']}:{$sk_server['remote_host']}"; ?>'>
<td class="listlr">
<?=$sk_server['name'];?>
</td>
<td class="listr">
<?=$sk_server['remote_host'];?>
</td>
<td rowspan="2" align="center">
<?php
if ($sk_server['status'] == "up") {
/* tunnel is up */
$iconfn = "text-success";
} else {
/* tunnel is down */
$iconfn = "text-danger";
}
echo "<span class='glyphicon glyphicon-transfer ".$iconfn."'></span>";
?>
</td>
</tr>
<tr name='<?php echo "r:{$sk_server['port']}:{$sk_server['remote_host']}"; ?>'>
<td class="listlr">
<?=$sk_server['connect_time'];?>
</td>
<td class="listr">
<?=$sk_server['virtual_addr'];?>
</td>
</tr>
foreach ($servers as $server) :?>
<table class="table table-striped table-condensed">
<thead>
<tr>
<th colspan="3">
<?=$server['name'];?> <?=gettext("Client connections");?>
</th>
</tr>
<tr>
<th><?=gettext("Name/Time");?></th>
<th><?=gettext("Real/Virtual IP");?></th>
<th></th>
</tr>
</thead>
<tbody>
<?php
endforeach; ?>
</table>
</tr>
</table>
$server['conns'] = array();
$server['conns'][] = array('remote_host' => 'xxx1', 'common_name' => 'cn1');
$server['conns'][] = array('remote_host' => 'xxx2', 'common_name' => 'cn2');
$server['conns'][] = array('remote_host' => 'xxx3', 'common_name' => 'cn3');
foreach ($server['conns'] as $conn) :?>
<tr>
<td><?=$conn['common_name'];?><br/><?=$conn['connect_time'];?></td>
<td><?=$conn['remote_host'];?><br/><?=$conn['virtual_addr'];?></td>
<td>
<span class="glyphicon glyphicon-remove act_kill_client" data-client-port="<?=$server['mgmt'];?>"
data-client-ip="<?=$conn['remote_host'];?>"
style='cursor:pointer;'
title='Kill client connection from <?=$conn['remote_host']; ?>'>
</span>
</td>
</tr>
<?php
} ?>
<?php if (!empty($clients)) {
?>
<table class="table table-striped" style="padding-top:0px; padding-bottom:0px; padding-left:0px; padding-right:0px" width="100%" border="0" cellpadding="0" cellspacing="0">
<tr>
<td colspan="6" class="listtopic">
<?= gettext('Client Instance Statistics') ?>
</td>
</tr>
<tr>
<table class="table table-striped" style="padding-top:0px; padding-bottom:0px; padding-left:0px; padding-right:0px" class="tabcont sortable" width="100%" border="0" cellpadding="0" cellspacing="0">
<tr>
<td class="listhdrr"><?= gettext('Name/Time') ?></td>
<td class="listhdrr"><?= gettext('Remote/Virtual IP') ?></td>
</tr>
endforeach; ?>
</tbody>
</table>
<br/>
<?php
endforeach; ?>
<?php
if (!empty($sk_servers)):?>
<table class="table table-striped table-condensed">
<thead>
<tr>
<th colspan="3"><?= gettext('Peer to Peer Server Instance Statistics') ?></th>
</tr>
<tr>
<th><?= gettext('Name/Time') ?></th>
<th><?= gettext('Remote/Virtual IP') ?></th>
<th></th>
</tr>
</thead>
<tbody>
<?php
foreach ($sk_servers as $sk_server) :?>
<tr>
<td><?=$sk_server['name'];?><br/><?=$sk_server['connect_time'];?></td>
<td><?=$sk_server['remote_host'];?><br/><?=$sk_server['virtual_addr'];?></td>
<td>
<span class='glyphicon glyphicon-transfer <?=$sk_server['status'] == "up" ? "text-success" : "text-danger";?>'></span>
</td>
</tr>
<?php
endforeach; ?>
</tbody>
</table>
<br/>
<?php
endif; ?>
<?php
if (!empty($clients)) {?>
<table class="table table-striped table-condensed">
<thead>
<tr>
<th colspan="3"><?= gettext('Client Instance Statistics') ?></th>
</tr>
<tr>
<th><?= gettext('Name/Time') ?></th>
<th><?= gettext('Remote/Virtual IP') ?></th>
<th></th>
</tr>
</thead>
<tbody>
<?php foreach ($clients as $client) :
?>
<tr name='<?php echo "r:{$client['port']}:{$client['remote_host']}"; ?>'>
<td class="listlr">
<?=$client['name'];?>
</td>
<td class="listr">
<?=$client['remote_host'];?>
</td>
<td rowspan="2" align="center">
<?php
if ($client['status'] == "up") {
/* tunnel is up */
$iconfn = "text-success";
} else {
/* tunnel is down */
$iconfn = "text-danger";
}
echo "<span class='glyphicon glyphicon-transfer ".$iconfn."'></span>";
?>
</td>
</tr>
<tr name='<?php echo "r:{$client['port']}:{$client['remote_host']}"; ?>'>
<td class="listlr">
<?=$client['connect_time'];?>
</td>
<td class="listr">
<?=$client['virtual_addr'];?>
</td>
</tr>
<?php
endforeach; ?>
</table>
</tr>
</table>
foreach ($clients as $client) :?>
<tr>
<td><?=$client['name'];?><br/><?=$client['connect_time'];?></td>
<td><?=$client['remote_host'];?><br/><?=$client['virtual_addr'];?></td>
<td>
<span class='glyphicon glyphicon-transfer <?=$client['status'] == "up" ? "text-success" : "text-danger" ;?>'></span>
</td>
</tr>
<?php
endforeach; ?>
</tbody>
</table>
<?php
}
......
......@@ -26,8 +26,6 @@
POSSIBILITY OF SUCH DAMAGE.
*/
$nocsrf = true;
require_once("guiconfig.inc");
require_once("pfsense-utils.inc");
......@@ -69,40 +67,36 @@ if ($_POST) {
?>
<input type="hidden" id="picture-config" name="picture-config" value="" />
<div id="picture-settings" class="widgetconfigdiv" style="display:none;">
<form action="/widgets/widgets/picture.widget.php" method="post" name="iforma" enctype="multipart/form-data">
<table class="table table-striped">
<tr>
<td>
<input name="pictfile" type="file" class="btn btn-primary formbtn" id="pictfile" size="20" />
</td>
</tr>
<tr>
<td>
<input id="submita" name="submita" type="submit" class="btn btn-primary formbtn" value="<?= gettext('Upload') ?>" />
</td>
</tr>
</table>
</form>
<form action="/widgets/widgets/picture.widget.php" method="post" name="iforma" enctype="multipart/form-data">
<table class="table table-striped">
<tr>
<td>
<input name="pictfile" type="file" class="btn btn-primary formbtn" id="pictfile" size="20" />
</td>
</tr>
<tr>
<td>
<input id="submita" name="submita" type="submit" class="btn btn-primary formbtn" value="<?= gettext('Upload') ?>" />
</td>
</tr>
</table>
</form>
</div>
<!-- hide picture if none is defined in the configuration -->
<?php if ($config['widgets']['picturewidget_filename'] != "") :
?>
<div id="picture-widgets" style="padding: 5px">
<a href='/widgets/widgets/picture.widget.php?getpic=true' target='_blank'>
<img border="0" width="100%" height="100%" src="/widgets/widgets/picture.widget.php?getpic=true" alt="picture" />
</a>
</div>
<?php
if ($config['widgets']['picturewidget_filename'] != "") :?>
<div id="picture-widgets" style="padding: 5px">
<a href='/widgets/widgets/picture.widget.php?getpic=true' target='_blank'>
<img border="0" width="100%" height="100%" src="/widgets/widgets/picture.widget.php?getpic=true" alt="picture" />
</a>
</div>
<?php
endif ?>
<!-- needed to show the settings widget icon -->
<script type="text/javascript">
//<![CDATA[
selectIntLink = "picture-configure";
textlink = document.getElementById(selectIntLink);
textlink.style.display = "inline";
$("#picture-configure").removeClass("disabled");
//]]>
</script>
......@@ -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>
......@@ -29,73 +29,80 @@
POSSIBILITY OF SUCH DAMAGE.
*/
$nocsrf = true;
require_once("guiconfig.inc");
require_once("services.inc");
require_once("system.inc");
require_once('plugins.inc');
require_once("ipsec.inc");
require_once("interfaces.inc");
require_once("widgets/include/services_status.inc");
$services = services_get();
if (isset($_POST['servicestatusfilter'])) {
$config['widgets']['servicestatusfilter'] = htmlspecialchars($_POST['servicestatusfilter'], ENT_QUOTES | ENT_HTML401);
write_config("Saved Service Status Filter via Dashboard");
header("Location: ../../index.php");
header("Location: /index.php");
}
?>
<input type="hidden" id="services_status-config" name="services_status-config" value="" />
<div id="services_status-settings" class="widgetconfigdiv" style="display:none;">
<form action="/widgets/widgets/services_status.widget.php" method="post" name="iformd">
<?= gettext('Comma separated list of services to NOT display in the widget') ?><br />
<input type="text" size="30" name="servicestatusfilter" class="formfld unknown" id="servicestatusfilter" value="<?= $config['widgets']['servicestatusfilter'] ?>" />
<input id="submitd" name="submitd" type="submit" class="btn btn-primary" value="Save" />
</form>
<form action="/widgets/widgets/services_status.widget.php" method="post" name="iformd">
<table class="table table-condensed">
<thead>
<tr>
<th><?= gettext('Comma separated list of services to NOT display in the widget') ?></th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" name="servicestatusfilter" id="servicestatusfilter" value="<?= $config['widgets']['servicestatusfilter'] ?>" /></td>
</tr>
<tr>
<td>
<input id="submitd" name="submitd" type="submit" class="btn btn-primary" value="<?=gettext("Save");?>" />
</td>
</tr>
</tbody>
</table>
</form>
</div>
<table class="table table-striped" width="100%" border="0" cellpadding="0" cellspacing="0" summary="services">
<tr>
<td class="widgetsubheader" align="center"><b><?= gettext('Service') ?></b></td>
<td class="widgetsubheader" align="center"><b><?= gettext('Description') ?></b></td>
<td class="widgetsubheader" align="center"><b><?= gettext('Status') ?></b></td>
<td class="widgetsubheader">&nbsp;</td>
</tr>
<table class="table table-striped table-condensed">
<thead>
<tr>
<th><?= gettext('Service') ?></th>
<th><?= gettext('Description') ?></th>
<th><?= gettext('Status') ?></th>
</tr>
</thead>
<tbody>
<?php
$skipservices = explode(",", $config['widgets']['servicestatusfilter']);
if (count($services) > 0) {
uasort($services, "service_name_compare");
foreach ($services as $service) {
if (!$service['name'] || in_array($service['name'], $skipservices)) {
continue;
}
$service_desc = explode(".", $service['description']);
echo "<tr><td class=\"listlr\">" . $service['name'] . "</td>\n";
echo "<td class=\"listr\">" . $service_desc[0] . "</td>\n";
// if service is running then listr else listbg
$bgclass = null;
if (get_service_status($service)) {
$bgclass = "listr";
} else {
$bgclass = "listbg";
}
echo "<td class=\"" . $bgclass . "\" align=\"center\">" . str_replace('btn ', 'btn btn-xs ', get_service_status_icon($service, false, true)) . "</td>\n";
echo "<td valign=\"middle\" class=\"list nowrap\">" . str_replace('btn ', 'btn btn-xs ', get_service_control_links($service)) . "</td></tr>\n";
}
} else {
echo "<tr><td colspan=\"3\" align=\"center\">" . gettext("No services found") . " . </td></tr>\n";
}
?>
$skipservices = explode(",", $config['widgets']['servicestatusfilter']);
if (count($services) > 0):
uasort($services, "service_name_compare");
foreach ($services as $service):
if (!$service['name'] || in_array($service['name'], $skipservices)) {
continue;
}
$service_desc = explode(".", $service['description']);?>
<tr>
<td><?=$service['name'];?></td>
<td><?=$service_desc[0];?></td>
<td><?=str_replace('btn ', 'btn btn-xs ', get_service_status_icon($service, false, true));?>
<?=str_replace('btn ', 'btn btn-xs ', get_service_control_links($service));?>
</td>
</tr>
<?php
endforeach;
else:?>
<tr><td colspan="3"><?=gettext("No services found");?></td></tr>
<?php
endif;?>
</tbody>
</table>
<!-- needed to display the widget settings menu -->
<script type="text/javascript">
//<![CDATA[
selectIntLink = "services_status-configure";
textlink = document.getElementById(selectIntLink);
textlink.style.display = "inline";
$("#services_status-configure").removeClass("disabled");
//]]>
</script>
<?php
/*
Copyright (C) 2014 Deciso B.V.
Copyright (C) 2007 Scott Dale
Copyright (C) 2004-2005 T. Lechat <dev@lechat.org>, Manuel Kasper <mk@neon1.net>
and Jonathan Watt <jwatt@jwatt.org>.
All rights reserved.
Copyright (C) 2014-2016 Deciso B.V.
Copyright (C) 2007 Scott Dale
Copyright (C) 2004-2005 T. Lechat <dev@lechat.org>, Manuel Kasper <mk@neon1.net>
and Jonathan Watt <jwatt@jwatt.org>.
All rights reserved.
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.
*/
require_once("guiconfig.inc");
require_once("pfsense-utils.inc");
require_once("system.inc");
require_once("stats.inc");
if (isset($_REQUEST['getupdatestatus'])) {
if (isset($_POST['getupdatestatus'])) {
$pkg_json = trim(configd_run('firmware check'));
if ($pkg_json != '') {
$pkg_status = json_decode($pkg_json, true);
}
if (!isset($pkg_status) || $pkg_status["connection"]=="error") {
echo "<span class='text-danger'>".gettext("Connection Error")."</span><br/><span class='btn-link' onclick='checkupdate()'>".gettext("Click to retry")."</span>";
echo "<span class='text-danger'>".gettext("Connection Error")."</span><br/><span class='btn-link' onclick='system_information_widget_checkupdate()'>".gettext("Click to retry")."</span>";
} elseif ($pkg_status["repository"]=="error") {
echo "<span class='text-danger'>".gettext("Repository Problem")."</span><br/><span class='btn-link' onclick='checkupdate()'>".gettext("Click to retry")."</span>";
echo "<span class='text-danger'>".gettext("Repository Problem")."</span><br/><span class='btn-link' onclick='system_information_widget_checkupdate()'>".gettext("Click to retry")."</span>";
} elseif ($pkg_status["updates"]=="0") {
echo "<span class='text-info'>".gettext("Your system is up to date.")."</span><br/><span class='btn-link' onclick='checkupdate()'>".gettext('Click to check for updates')."</span>";
echo "<span class='text-info'>".gettext("Your system is up to date.")."</span><br/><span class='btn-link' onclick='system_information_widget_checkupdate()'>".gettext('Click to check for updates')."</span>";
} else {
echo "<span class='text-info'>".sprintf(gettext("There are %s update(s) available."),$pkg_status["updates"])."</span><br/><a href='/ui/core/firmware/#checkupdate'>".gettext("Click to upgrade")."</a> | <span class='btn-link' onclick='checkupdate()'>".gettext('Re-check now')."</span>";
echo "<span class='text-info'>".sprintf(gettext("There are %s update(s) available."),$pkg_status["updates"])."</span><br/><a href='/ui/core/firmware/#checkupdate'>".gettext("Click to upgrade")."</a> | <span class='btn-link' onclick='system_information_widget_checkupdate()'>".gettext('Re-check now')."</span>";
}
exit;
}
$filesystems = get_mounted_filesystems();
?>
<script src="/ui/js/moment-with-locales.min.js" type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
jQuery(function() {
jQuery("#statePB").css( { width: '<?php echo get_pfstate(true); ?>%' } );
jQuery("#mbufPB").css( { width: '<?php echo get_mbuf(true); ?>%' } );
jQuery("#cpuPB").css( { width:0 } );
jQuery("#memUsagePB").css( { width: '<?php echo mem_usage(); ?>%' } );
var system_information_widget_cpu_data = []; // reference to measures
var system_information_widget_cpu_chart = null; // reference to chart object
var system_information_widget_cpu_chart_data = null; // reference to chart data object
<?php $d = 0; ?>
<?php foreach ($filesystems as $fs) : ?>
jQuery("#diskUsagePB<?php echo $d++; ?>").css( { width: '<?php echo $fs['percent_used']; ?>%' } );
<?php endforeach; ?>
/**
* check for updates
*/
function system_information_widget_checkupdate() {
$('#updatestatus').html('<span class="text-info"><?= html_safe(gettext('Fetching... (may take up to 30 seconds)')) ?></span>');
$.ajax({
type: "POST",
url: '/widgets/widgets/system_information.widget.php',
data:{getupdatestatus:'yes'},
success:function(html) {
$('#updatestatus').prop('innerHTML',html);
}
});
}
<?php if ($showswap == true) : ?>
jQuery("#swapUsagePB").css( { width: '<?php echo swap_usage(); ?>%' } );
<?php endif; ?>
<?php if (get_temp() != "") : ?>
jQuery("#tempPB").css( { width: '<?php echo get_temp(); ?>%' } );
<?php endif; ?>
});
//]]>
</script>
/**
* update cpu chart
*/
function system_information_widget_cpu_update(sender, data)
{
// tooltip current percentage
$("#system_information_widget_chart_cpu_usage").tooltip({ title: ''});
$("#system_information_widget_chart_cpu_usage").attr("title", data['cpu']['used'] + ' %').tooltip('fixTitle');
// push new measurement, keep a maximum of 100 measures in
system_information_widget_cpu_data.push(parseInt(data['cpu']['used']));
if (system_information_widget_cpu_data.length > 100) {
system_information_widget_cpu_data.shift();
} else if (system_information_widget_cpu_data.length == 1) {
system_information_widget_cpu_data.push(parseInt(data['cpu']['used']));
}
chart_data = [];
count = 0;
system_information_widget_cpu_data.map(function(item){
chart_data.push([count, item]);
count++;
});
system_information_widget_cpu_chart_data.datum([{'key':'cpu', 'values':chart_data}]).transition().duration(500).call(system_information_widget_cpu_chart);
}
<table class="table table-striped">
<tbody>
<tr>
<td width="25%" class="vncellt"><?=gettext("Name");?></td>
<td width="75%" class="listr"><?php echo $config['system']['hostname'] . "." . $config['system']['domain']; ?></td>
</tr>
<tr>
<td width="25%" valign="top" class="vncellt"><?=gettext("Versions");?></td>
<td width="75%" class="listr">
<?php
$pkgver = explode('-', trim(file_get_contents('/usr/local/opnsense/version/opnsense')));
echo sprintf('%s %s-%s', $g['product_name'], $pkgver[0], php_uname('m'));
?>
<br /><?php echo php_uname('s') . ' ' . php_uname('r'); ?>
<br /><?php echo exec('/usr/local/bin/openssl version'); ?>
</td>
/**
* update widget
*/
function system_information_widget_update(sender, data)
{
// update cpu usage chart
system_information_widget_cpu_update(sender, data);
</tr>
<tr>
<td>
<?= gettext('Updates') ?>
</td>
<td>
<div id='updatestatus'><span class='btn-link' onclick='checkupdate()'><?=gettext("Click to check for updates");?></span></div>
</td>
</tr>
<tr>
<td width="25%" class="vncellt"><?=gettext("CPU Type");?></td>
<td width="75%" class="listr">
<?php echo (htmlspecialchars(get_single_sysctl("hw.model"))); ?>
<div id="cpufreq"><?= get_cpufreq(); ?></div>
<?php $cpucount = get_cpu_count();
if ($cpucount > 1) :
?>
<div id="cpucount">
<?= htmlspecialchars($cpucount) ?> CPUs: <?= htmlspecialchars(get_cpu_count(true)); ?></div>
<?php endif; ?>
</td>
</tr>
<tr>
<td width="25%" class="vncellt"><?=gettext("Uptime");?></td>
<td width="75%" class="listr" id="uptime"><?= htmlspecialchars(get_uptime()); ?></td>
</tr>
<tr>
<td width="25%" class="vncellt"><?=gettext("Current date/time");?></td>
<td width="75%" class="listr">
<div id="datetime"><?= date("D M j G:i:s T Y"); ?></div>
</td>
</tr>
<tr>
<td width="30%" class="vncellt"><?=gettext("DNS server(s)");?></td>
<td width="70%" class="listr">
<?php
$dns_servers = get_dns_servers();
foreach ($dns_servers as $dns) {
echo "{$dns}<br />";
}
?>
</td>
</tr>
<?php if (isset($config['revision']['time'])) :
?>
<tr>
<td width="25%" class="vncellt"><?=gettext("Last config change");?></td>
<td width="75%" class="listr"><?= htmlspecialchars(date("D M j G:i:s T Y", intval($config['revision']['time'])));?></td>
</tr>
<?php endif; ?>
<tr>
<td width="25%" class="vncellt"><?=gettext("State table size");?></td>
<td width="75%" class="listr">
<?php $pfstatetext = get_pfstate();
$pfstateusage = get_pfstate(true);
?>
<div class="progress">
<div id="statePB" class="progress-bar" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 0%;">
<span class="sr-only"></span>
</div>
</div>
$("#system_information_widget_cpu_type").html(data['cpu']['model'] + ' ( '+data['cpu']['cpus']+' cores )');
var uptime_days = parseInt(moment.duration(parseInt(data['uptime']), 'seconds').asDays());
var uptime_str = "";
if (uptime_days > 0) {
uptime_str += uptime_days + " <?=html_safe(gettext('days'));?> ";
}
<span id="pfstateusagemeter"><?= $pfstateusage.'%';
?></span> (<span id="pfstate"><?= htmlspecialchars($pfstatetext); ?></span>)
<br />
<a href="diag_dump_states.php"><?=gettext("Show states");?></a>
</td>
</tr>
<tr>
<td width="25%" class="vncellt"><?=gettext("MBUF Usage");?></td>
<td width="75%" class="listr">
<?php
$mbufstext = get_mbuf();
$mbufusage = get_mbuf(true);
?>
uptime_str += moment.utc(parseInt(data['uptime'])*1000).format("HH:mm:ss");
$("#system_information_widget_uptime").html(uptime_str);
$("#system_information_widget_datetime").html(data['date_frmt']);
$("#system_information_widget_last_config_change").html(data['config']['last_change_frmt']);
<div class="progress">
<div id="mbufPB" class="progress-bar" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 0%;">
<span class="sr-only"></span>
</div>
</div>
<span id="mbufusagemeter"><?= $mbufusage.'%'; ?></span> (<span id="mbuf"><?= $mbufstext ?></span>)
</td>
</tr>
<?php if (get_temp() != "") :
?>
<tr>
<td width="25%" class="vncellt"><?=gettext("Temperature");?></td>
<td width="75%" class="listr">
<?php $TempMeter = $temp = get_temp(); ?>
var states_perc = parseInt((parseInt(data['kernel']['pf']['states']) / parseInt(data['kernel']['pf']['maxstates']))*100);
$("#system_information_widget_states .progress-bar").css("width", states_perc + "%").attr("aria-valuenow", states_perc + "%");
var states_text = states_perc + " % " + "( " + data['kernel']['pf']['states'] + "/" + data['kernel']['pf']['maxstates'] + " )"
$("#system_information_widget_states .state_text").html(states_text);
<div class="progress">
<div id="tempPB" class="progress-bar" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 0%;">
<span class="sr-only"></span>
</div>
</div>
<span id="tempmeter"><?= $temp."&#176;C"; ?></span>
</td>
</tr>
<?php endif; ?>
<tr>
<td width="25%" class="vncellt"><?=gettext("Load average");?></td>
<td width="75%" class="listr">
<div id="load_average" title="Last 1, 5 and 15 minutes"><?= get_load_average(); ?></div>
</td>
</tr>
<tr>
<td width="25%" class="vncellt"><?=gettext("CPU usage");?></td>
<td width="75%" class="listr">
var mbuf_perc = parseInt((parseInt(data['kernel']['mbuf']['total']) / parseInt(data['kernel']['mbuf']['max']))*100);
$("#system_information_widget_mbuf .progress-bar").css("width", mbuf_perc + "%").attr("aria-valuenow", mbuf_perc + "%");
var mbuf_text = mbuf_perc + " % " + "( " + data['kernel']['mbuf']['total'] + "/" + data['kernel']['mbuf']['max'] + " )"
$("#system_information_widget_mbuf .state_text").html(mbuf_text);
$("#system_information_widget_load").html(data['cpu']['load'].join(','));
var mem_perc = parseInt(data['kernel']['memory']['used'] / data['kernel']['memory']['total']*100);
$("#system_information_widget_memory .progress-bar").css("width", mem_perc + "%").attr("aria-valuenow", mem_perc + "%");
var mem_text = mem_perc + " % " + "( " + parseInt(data['kernel']['memory']['used']/1024/1024) + "/";
mem_text += parseInt(data['kernel']['memory']['total']/1024/1024) + " MB )"
$("#system_information_widget_memory .state_text").html(mem_text);
<div class="progress">
<div id="cpuPB" class="progress-bar" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 0%;">
<span class="sr-only"></span>
</div>
</div>
<span id="cpumeter">(<?= gettext('Updating in 10 seconds') ?>)</span>
</td>
</tr>
<tr>
<td width="25%" class="vncellt"><?=gettext("Memory usage");?></td>
<td width="75%" class="listr">
<?php $memUsage = mem_usage(); ?>
<div class="progress">
<div id="memUsagePB" class="progress-bar" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 0%;">
<span class="sr-only"></span>
</div>
</div>
<span id="memusagemeter"><?= $memUsage.'%'; ?></span> used <?= sprintf("%.0f/%.0f", $memUsage/100.0 * get_single_sysctl('hw.physmem') / (1024*1024), get_single_sysctl('hw.physmem') / (1024*1024)) ?> MB
</td>
</tr>
<?php if ($showswap == true) :
?>
<tr>
<td width="25%" class="vncellt"><?=gettext("SWAP usage");?></td>
<td width="75%" class="listr">
<?php $swapusage = swap_usage(); ?>
<div class="progress">
<div id="swapUsagePB" class="progress-bar" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 0%;">
<span class="sr-only"></span>
</div>
</div>
<span id="swapusagemeter"><?= $swapusage.'%'; ?></span> used <?= sprintf("%.0f/%.0f", `/usr/sbin/swapinfo -m | /usr/bin/grep -v Device | /usr/bin/awk '{ print $3;}'`, `/usr/sbin/swapinfo -m | /usr/bin/grep -v Device | /usr/bin/awk '{ print $2;}'`) ?> MB
</td>
</tr>
<?php endif; ?>
<tr>
<td width="25%" class="vncellt"><?=gettext("Disk usage");?></td>
<td width="75%" class="listr">
<?php $d = 0; ?>
<?php foreach ($filesystems as $fs) : ?>
<div class="progress">
<div id="diskUsagePB<?php echo $d; ?>" class="progress-bar" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 0%;">
<span class="sr-only"></span>
</div>
</div>
<?php if (substr(basename($fs['device']), 0, 5) == "tmpfs") {
$fs['type'] .= " in RAM";
} ?>
<?php echo "{$fs['mountpoint']} ({$fs['type']})";?>: <span id="diskusagemeter<?php echo $d++ ?>"><?= $fs['percent_used'].'%'; ?></span> used <?php echo $fs['used_size'] ."/". $fs['total_size'];
if ($d != count($filesystems)) {
echo '<br/><br/>';
}
endforeach; ?>
</td>
</tr>
</tbody>
</table>
<script type="text/javascript">
//<![CDATA[
function checkupdate() {
jQuery('#updatestatus').html('<span class="text-info"><?= html_safe(gettext('Fetching... (may take up to 30 seconds)')) ?></span>');
jQuery.ajax({
type: "POST",
url: '/widgets/widgets/system_information.widget.php',
data:{action:'pkg_update'},
success:function(html) {
getstatus();
}
});
}
function getstatus() {
scroll(0,0);
var url = "/widgets/widgets/system_information.widget.php";
var pars = 'getupdatestatus=yes';
jQuery.ajax(
url,
{
type: 'get',
data: pars,
complete: activitycallback
});
}
// swap usage
if (data['disk']['swap']['used'] != "") {
var swap_perc = parseInt(data['disk']['swap']['used'] / data['disk']['swap']['total']*100);
$("#system_information_widget_swap .progress-bar").css("width", swap_perc + "%").attr("aria-valuenow", swap_perc + "%");
var swap_text = swap_perc + " % " + "( " + parseInt(data['disk']['swap']['used']/1024) + "/";
swap_text += parseInt(data['disk']['swap']['total']/1024) + " MB )"
$("#system_information_widget_swap .state_text").html(swap_text);
$("#system_information_widget_swap").show();
} else {
$("#system_information_widget_swap").hide();
}
function activitycallback(transport) {
// .html() method process all script tags contained in responseText,
// to avoid this we set the innerHTML property
jQuery('#updatestatus').prop('innerHTML',transport.responseText);
}
//]]>
// disk usage
counter = 0;
$("#system_information_widget_disk .disk_devices").html("");
data['disk']['devices'].map(function(device) {
var html = $("#system_information_widget_disk .disk_template").html();
html = html.replace('disk_id_sequence', 'system_information_widget_disk_'+counter);
$("#system_information_widget_disk .disk_devices").html($("#system_information_widget_disk .disk_devices").html() + html);
var disk_perc = device['capacity'].replace('%', '');
$("#system_information_widget_disk_"+counter+' .progress-bar').css("width", disk_perc + "%").attr("aria-valuenow", disk_perc + "%");
var disk_text = device['capacity'] + ' ' + device['mountpoint'] + ' ['+device['type']+'] (' + device['used'] +'/' + device['size'] + ')';
$("#system_information_widget_disk_"+counter+" .state_text").html(disk_text);
counter += 1;
});
}
/**
* page setup
*/
$( document ).ready(function() {
// draw cpu graph
nv.addGraph(function() {
system_information_widget_cpu_chart = nv.models.lineChart()
.x(function(d) { return d[0] })
.y(function(d) { return d[1] })
.useInteractiveGuideline(false)
.interactive(false)
.showLegend(false)
.showXAxis(false)
.clipEdge(true)
.margin({top:5,right:5,bottom:5,left:25});
system_information_widget_cpu_chart.yAxis.tickFormat(d3.format('.0'));
system_information_widget_cpu_chart.forceY([0, 100]);
system_information_widget_cpu_chart_data = d3.select("#system_information_widget_chart_cpu_usage svg").datum([{'key':'cpu', 'values':[[0, 0]]}]);
system_information_widget_cpu_chart_data.transition().duration(500).call(system_information_widget_cpu_chart);
});
});
</script>
<table class="table table-striped table-condensed" data-plugin="system" data-callback="system_information_widget_update">
<tbody>
<tr>
<td width="30%"><?=gettext("Name");?></td>
<td><?=$config['system']['hostname'] . "." . $config['system']['domain']; ?></td>
</tr>
<tr>
<td><?=gettext("Versions");?></td>
<td>
<?=sprintf('%s %s-%s', $g['product_name'], explode('-', trim(file_get_contents('/usr/local/opnsense/version/opnsense')))[0], php_uname('m'));?><br/>
<?=php_uname('s') . ' ' . php_uname('r'); ?><br/>
<?=exec('/usr/local/bin/openssl version'); ?>
</td>
</tr>
<tr>
<td><?= gettext('Updates') ?></td>
<td>
<div id='updatestatus'><span class='btn-link' onclick='system_information_widget_checkupdate()'><?=gettext("Click to check for updates");?></span></div>
</td>
</tr>
<tr>
<td><?=gettext("CPU Type");?></td>
<td id="system_information_widget_cpu_type"></td>
</tr>
<tr>
<td><?=gettext("CPU usage");?></td>
<td>
<div id="system_information_widget_chart_cpu_usage">
<svg style="height:40px;"></svg>
</div>
</td>
</tr>
<tr>
<td><?=gettext("Load average");?></td>
<td id="system_information_widget_load"></td>
</tr>
<tr>
<td><?=gettext("Uptime");?></td>
<td id="system_information_widget_uptime"></td>
</tr>
<tr>
<td><?=gettext("Current date/time");?></td>
<td id="system_information_widget_datetime"></td>
</tr>
<tr>
<td><?=gettext("Last config change");?></td>
<td id="system_information_widget_last_config_change"></td>
</tr>
<tr>
<td><?=gettext("State table size");?></td>
<td id="system_information_widget_states">
<div class="progress" style="text-align:center;">
<span class="state_text" style="position:absolute;right:0;left:0;z-index:200;"></span>
<div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%;"></div>
</div>
</td>
</tr>
<tr>
<td><?=gettext("MBUF Usage");?></td>
<td id="system_information_widget_mbuf">
<div class="progress" style="text-align:center;">
<span class="state_text" style="position:absolute;right:0;left:0;z-index:200;"></span>
<div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%;"></div>
</div>
</td>
</tr>
<tr>
<td><?=gettext("Memory usage");?></td>
<td id="system_information_widget_memory">
<div class="progress" style="text-align:center;">
<span class="state_text" style="position:absolute;right:0;left:0;z-index:200;"></span>
<div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%;"></div>
</div>
</td>
</tr>
<tr id="system_information_widget_swap">
<td><?=gettext("SWAP usage");?></td>
<td>
<div class="progress" style="text-align:center;">
<span class="state_text" style="position:absolute;right:0;left:0;z-index:200;"></span>
<div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%;"></div>
</div>
</td>
</tr>
<tr>
<td><?=gettext("Disk usage");?></td>
<td id="system_information_widget_disk">
<div style="display:none" class="disk_template">
<!-- template -->
<div id="disk_id_sequence" class="progress" style="text-align:center;">
<span class="state_text" style="position:absolute;right:0;left:0;z-index:200;"></span>
<div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%;"></div>
</div>
<div style="height:1px;">
</div>
</div>
<div class="disk_devices">
</div>
</td>
</tr>
</tbody>
</table>
<?php
/*
Copyright (C) 2015 S. Linke <dev@devsash.de>
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.
Copyright (C) 2015 S. Linke <dev@devsash.de>
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.
*/
require_once("guiconfig.inc");
......@@ -32,9 +32,9 @@ require_once("pfsense-utils.inc");
$system_logfile = '/var/log/system.log';
if (!$config['widgets']['systemlogfiltercount']){
$syslogEntriesToFetch = isset($config['syslog']['nentries']) ? $config['syslog']['nentries'] : 20;
$syslogEntriesToFetch = isset($config['syslog']['nentries']) ? $config['syslog']['nentries'] : 20;
} else {
$syslogEntriesToFetch = $config['widgets']['systemlogfiltercount'];
$syslogEntriesToFetch = $config['widgets']['systemlogfiltercount'];
}
if(is_numeric($_POST['logfiltercount'])) {
......@@ -46,41 +46,35 @@ if(is_numeric($_POST['logfiltercount'])) {
}
?>
<input type="hidden" id="system_log-config" name="system_log-config" value="" />
<div id="system_log-settings" class="widgetconfigdiv" style="display:none;">
<form action="/widgets/widgets/system_log.widget.php" method="post" name="iform">
<table class="table table-striped" summary="system_log widget">
<tr>
<td><?=gettext("Number of Log lines to display");?>:</td>
<td>
<select name="logfiltercount" id="logfiltercount">
<?php for ($i = 1; $i <= 50; $i++) {?>
<option value="<?php echo $i;?>" <?php if ($syslogEntriesToFetch == $i) { echo "selected=\"selected\"";}?>><?php echo $i;?></option>
<?php } ?>
</td>
<td>
<input id="submit" name="submit" type="submit" class="btn btn-primary formbtn" value="<?= gettext('Save') ?>" autocomplete="off">
</td>
</tr>
</table>
</form>
<form action="/widgets/widgets/system_log.widget.php" method="post" name="iform">
<table class="table table-striped">
<tr>
<td><?=gettext("Number of Log lines to display");?>:</td>
<td>
<select name="logfiltercount" id="logfiltercount">
<?php for ($i = 1; $i <= 50; $i++) {?>
<option value="<?php echo $i;?>" <?php if ($syslogEntriesToFetch == $i) { echo "selected=\"selected\"";}?>><?php echo $i;?></option>
<?php } ?>
</select>
</td>
<td>
<input id="submit" name="submit" type="submit" class="btn btn-primary formbtn" value="<?= gettext('Save') ?>" autocomplete="off">
</td>
</tr>
</table>
</form>
</div>
<div id="system_log-widgets" class="content-box" style="overflow:scroll;">
<table class="table table-striped" cellspacing="0" cellpadding="0">
<?php dump_clog($system_logfile, $syslogEntriesToFetch); ?>
</table>
<table class="table table-striped" cellspacing="0" cellpadding="0">
<?php dump_clog($system_logfile, $syslogEntriesToFetch); ?>
</table>
</div>
<!-- needed to display the widget settings menu -->
<script type="text/javascript">
//<![CDATA[
selectIntLink = "system_log-configure";
textlink = document.getElementById(selectIntLink);
textlink.style.display = "inline";
$("#system_log-configure").removeClass("disabled");
//]]>
</script>
<?php
/*
Copyright (C) 2014 Deciso B.V.
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.
*/
/*
Description: Thermal Sensors Widget.
NOTE: depends on proper cofing in System >> Advanced >> Miscellaneous tab >> Thermal Sensors section.
File location:
\usr\local\www\widgets\widgets\
Depends on:
\usr\local\www\widgets\javascript\thermal_sensors.js
\usr\local\www\widgets\include\thermal_sensors.inc
Copyright (C) 2014-2016 Deciso B.V.
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.
*/
require_once("guiconfig.inc");
require_once("widgets/include/thermal_sensors.inc");
//=========================================================================
//called by showThermalSensorsData() (jQuery Ajax call) in thermal_sensors.js
if (isset($_GET["getThermalSensorsData"])) {
//get Thermal Sensors data and return
echo getThermalSensorsData();
return;
}
//=========================================================================
const WIDGETS_CONFIG_SECTION_KEY = "widgets";
const THERMAL_SENSORS_WIDGET_SUBSECTION_KEY = "thermal_sensors_widget";
//default constants
const DEFAULT_WARNING_THRESHOLD = 70; //60 C
const DEFAULT_CRITICAL_THRESHOLD = 80; //70 C
const MIN_THRESHOLD_VALUE = 1; //deg C
const MAX_THRESHOLD_VALUE = 100; //deg C
//NOTE: keys used in $_POST and $config should match text and checkbox inputs' IDs/names in HTML code section
//=========================================================================
//save widget config settings on POST
if ($_POST) {
saveThresholdSettings($config, $_POST, "thermal_sensors_widget_zone_warning_threshold", "thermal_sensors_widget_zone_critical_threshold");
saveThresholdSettings($config, $_POST, "thermal_sensors_widget_core_warning_threshold", "thermal_sensors_widget_core_critical_threshold");
//handle checkboxes separately
saveGraphDisplaySettings($config, $_POST, "thermal_sensors_widget_show_raw_output");
saveGraphDisplaySettings($config, $_POST, "thermal_sensors_widget_show_full_sensor_name");
saveGraphDisplaySettings($config, $_POST, "thermal_sensors_widget_pulsate_warning");
saveGraphDisplaySettings($config, $_POST, "thermal_sensors_widget_pulsate_critical");
//write settings to config file
write_config("Saved thermal_sensors_widget settings via Dashboard.");
header("Location: ../../index.php");
}
function saveThresholdSettings(&$configArray, &$postArray, $warningValueKey, $criticalValueKey)
function validate_temp_value($value)
{
$warningValue = 0;
$criticalValue = 0;
if (isset($postArray[$warningValueKey])) {
$warningValue = (int) $postArray[$warningValueKey];
}
if (isset($postArray[$criticalValueKey])) {
$criticalValue = (int) $postArray[$criticalValueKey];
}
if (($warningValue >= MIN_THRESHOLD_VALUE && $warningValue <= MAX_THRESHOLD_VALUE) &&
($criticalValue >= MIN_THRESHOLD_VALUE && $criticalValue <= MAX_THRESHOLD_VALUE) &&
($warningValue < $criticalValue)
) {
//all validated ok, save to config array
$configArray[WIDGETS_CONFIG_SECTION_KEY][THERMAL_SENSORS_WIDGET_SUBSECTION_KEY][$warningValueKey] = $warningValue;
$configArray[WIDGETS_CONFIG_SECTION_KEY][THERMAL_SENSORS_WIDGET_SUBSECTION_KEY][$criticalValueKey] = $criticalValue;
if (is_numeric($value) && (int)$value == $value && $value >= 0 and $value <= 100) {
return true;
} else {
return false;
}
}
function saveGraphDisplaySettings(&$configArray, &$postArray, $valueKey)
{
$configArray[WIDGETS_CONFIG_SECTION_KEY][THERMAL_SENSORS_WIDGET_SUBSECTION_KEY][$valueKey] = isset($postArray[$valueKey]) ? 1 : 0;
}
//=========================================================================
//get Threshold settings from config (apply defaults if missing)
$thermal_sensors_widget_zoneWarningTempThreshold = getThresholdValueFromConfig($config, "thermal_sensors_widget_zone_warning_threshold", DEFAULT_WARNING_THRESHOLD);
$thermal_sensors_widget_zoneCriticalTempThreshold = getThresholdValueFromConfig($config, "thermal_sensors_widget_zone_critical_threshold", DEFAULT_CRITICAL_THRESHOLD);
$thermal_sensors_widget_coreWarningTempThreshold = getThresholdValueFromConfig($config, "thermal_sensors_widget_core_warning_threshold", DEFAULT_WARNING_THRESHOLD);
$thermal_sensors_widget_coreCriticalTempThreshold = getThresholdValueFromConfig($config, "thermal_sensors_widget_core_critical_threshold", DEFAULT_CRITICAL_THRESHOLD);
//get display settings from config (apply defaults if missing)
$thermal_sensors_widget_showRawOutput = getBoolValueFromConfig($config, "thermal_sensors_widget_show_raw_output", false);
$thermal_sensors_widget_showFullSensorName = getBoolValueFromConfig($config, "thermal_sensors_widget_show_full_sensor_name", false);
$thermal_sensors_widget_pulsateWarning = getBoolValueFromConfig($config, "thermal_sensors_widget_pulsate_warning", true);
$thermal_sensors_widget_pulsateCritical = getBoolValueFromConfig($config, "thermal_sensors_widget_pulsate_critical", true);
function getThresholdValueFromConfig(&$configArray, $valueKey, $defaultValue)
{
$thresholdValue = $defaultValue;
if (isset($configArray[WIDGETS_CONFIG_SECTION_KEY][THERMAL_SENSORS_WIDGET_SUBSECTION_KEY][$valueKey])) {
$thresholdValue = (int) $configArray[WIDGETS_CONFIG_SECTION_KEY][THERMAL_SENSORS_WIDGET_SUBSECTION_KEY][$valueKey];
$fieldnames = array('thermal_sensors_widget_zone_warning_threshold', 'thermal_sensors_widget_zone_critical_threshold',
'thermal_sensors_widget_core_warning_threshold', 'thermal_sensors_widget_core_critical_threshold');
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
$pconfig = array();
foreach ($fieldnames as $fieldname) {
$defaultValue = strpos($fieldname, 'critical') !== false ? 80 : 70;
$pconfig[$fieldname] = !empty($config['widgets']['thermal_sensors_widget'][$fieldname]) ? $config['widgets']['thermal_sensors_widget'][$fieldname] : $defaultValue;
}
if ($thresholdValue < MIN_THRESHOLD_VALUE || $thresholdValue > MAX_THRESHOLD_VALUE) {
//set to default if not in allowed range
$thresholdValue = $defaultValue;
} elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
// save widget config
if (empty($config['widgets']['thermal_sensors_widget']) || !is_array($config['widgets']['thermal_sensors_widget'])) {
$config['widgets']['thermal_sensors_widget'] = array();
}
return $thresholdValue;
}
function getBoolValueFromConfig(&$configArray, $valueKey, $defaultValue)
{
$boolValue = false;
if (isset($configArray[WIDGETS_CONFIG_SECTION_KEY][THERMAL_SENSORS_WIDGET_SUBSECTION_KEY][$valueKey])) {
$boolValue = (bool) $configArray[WIDGETS_CONFIG_SECTION_KEY][THERMAL_SENSORS_WIDGET_SUBSECTION_KEY][$valueKey];
} else {
//set to default if not in allowed range
$boolValue = $defaultValue;
foreach ($fieldnames as $fieldname) {
$defaultValue = strpos($fieldname, 'critical') !== false ? 80 : 70;
$newValue = !empty($_POST[$fieldname]) ? $_POST[$fieldname] : "";
$config['widgets']['thermal_sensors_widget'][$fieldname] = validate_temp_value($newValue) ? $newValue : $defaultValue;
}
return $boolValue;
write_config("Thermal sensors widget saved via Dashboard.");
header("Location: /index.php");
die;
}
//=========================================================================
?>
<script type="text/javascript">
//<![CDATA[
//set Thresholds, to be used in thermal_sensors.js
var thermal_sensors_widget_zoneWarningTempThreshold = <?= $thermal_sensors_widget_zoneWarningTempThreshold; ?>;
var thermal_sensors_widget_zoneCriticalTempThreshold = <?= $thermal_sensors_widget_zoneCriticalTempThreshold; ?>;
var thermal_sensors_widget_coreWarningTempThreshold = <?= $thermal_sensors_widget_coreWarningTempThreshold; ?>;
var thermal_sensors_widget_coreCriticalTempThreshold = <?= $thermal_sensors_widget_coreCriticalTempThreshold; ?>;
//set Graph display settings, to be used in thermal_sensors.js
var thermal_sensors_widget_showRawOutput = <?= $thermal_sensors_widget_showRawOutput ? "true" : "false"; ?>;
var thermal_sensors_widget_showFullSensorName = <?= $thermal_sensors_widget_showFullSensorName ? "true" : "false"; ?>;
var thermal_sensors_widget_pulsateWarning = <?= $thermal_sensors_widget_pulsateWarning ? "true" : "false"; ?>;
var thermal_sensors_widget_pulsateCritical = <?= $thermal_sensors_widget_pulsateCritical ? "true" : "false"; ?>;
//start showing temp data
//NOTE: the refresh interval will be reset to a proper value in showThermalSensorsData() (thermal_sensors.js).
jQuery(document).ready(function() {
showThermalSensorsData();
});
//]]>
function thermal_sensors_widget_update(sender, data)
{
data.map(function(sensor) {
var tempIntValue = parseInt(sensor['temperature']);
var progressbar = $("#thermal_sensors_widget_progress_bar").html();
var tbody = sender.find('tbody');
var tr_id = "thermal_sensors_widget_" + sensor['device'].replace(/\./g, '_');
if (tbody.find("#"+tr_id).length == 0) {
var tr_content = [];
tr_content.push('<tr id="'+tr_id+'">');
tr_content.push('<td>'+progressbar+'</td>');
tr_content.push('</tr>');
tbody.append(tr_content.join(''));
}
// probe warning / danger temp
if (sensor['type'] == 'core') {
danger_temp = parseInt($("#thermal_sensors_widget_core_critical_threshold").val());
warning_temp = parseInt($("#thermal_sensors_widget_core_warning_threshold").val());
} else {
danger_temp = parseInt($("#thermal_sensors_widget_zone_critical_threshold").val());
warning_temp = parseInt($("#thermal_sensors_widget_zone_warning_threshold").val());
}
// progress bar style
if (tempIntValue > danger_temp) {
$("#"+tr_id + " .progress-bar").removeClass('progress-bar-success')
.removeClass('progress-bar-warning')
.removeClass('progress-bar-danger')
.addClass('progress-bar-danger');
} else if (tempIntValue > warning_temp) {
$("#"+tr_id + " .progress-bar").removeClass('progress-bar-success')
.removeClass('progress-bar-warning')
.removeClass('progress-bar-danger')
.addClass('progress-bar-warning');
} else {
$("#"+tr_id + " .progress-bar").removeClass('progress-bar-success')
.removeClass('progress-bar-warning')
.removeClass('progress-bar-danger')
.addClass('progress-bar-success');
}
// update bar
$("#"+tr_id + " .progress-bar").html(sensor['temperature'] + ' &deg;C');
$("#"+tr_id + " .progress-bar").css("width", tempIntValue + "%").attr("aria-valuenow", tempIntValue + "%");
// update label
$("#"+tr_id + " .info").html(sensor['type_translated'] + " " + sensor['device_seq'] + " <small>("+sensor['device']+")<small>");
});
}
</script>
<input type="hidden" id="thermal_sensors-config" name="thermal_sensors-config" value="" />
<div id="thermal_sensors-settings" class="widgetconfigdiv" style="display:none;">
<form action="/widgets/widgets/thermal_sensors.widget.php" method="post" id="iform_thermal_sensors_settings" name="iform_thermal_sensors_settings">
<table class="table table-striped" width="100%" border="0" summary="thermal sensors widget">
<tr>
<td align="left" colspan="2">
<span style="font-weight: bold" ><?= gettext('Thresholds in &deg;C (1 to 100):') ?></span>
</td>
<td align="right" colspan="1">
<span style="font-weight: bold" ><?= gettext('Display settings:') ?></span>
</td>
</tr>
<tr>
<td>
<?= gettext('Zone Warning:') ?>
</td>
<td>
<input type="text" maxlength="3" size="3" class="formfld unknown"
name="thermal_sensors_widget_zone_warning_threshold"
id="thermal_sensors_widget_zone_warning_threshold"
value="<?= $thermal_sensors_widget_zoneWarningTempThreshold; ?>" />
</td>
<td>
<label for="thermal_sensors_widget_show_raw_output"><?= gettext('Show raw output (no graph):') ?> </label>
<input type="checkbox"
id="thermal_sensors_widget_show_raw_output"
name="thermal_sensors_widget_show_raw_output"
value="<?= $thermal_sensors_widget_showRawOutput;
?>" <?= ($thermal_sensors_widget_showRawOutput) ? " checked='checked'" : ""; ?> />
</td>
</tr>
<tr>
<td>
<?= gettext('Zone Critical:') ?>
</td>
<td>
<input type="text" maxlength="3" size="3" class="formfld unknown"
name="thermal_sensors_widget_zone_critical_threshold"
id="thermal_sensors_widget_zone_critical_threshold"
value="<?= $thermal_sensors_widget_zoneCriticalTempThreshold; ?>" />
</td>
<td>
<label for="thermal_sensors_widget_show_full_sensor_name"><?= gettext('Show full sensor name:') ?> </label>
<input type="checkbox"
id="thermal_sensors_widget_show_full_sensor_name"
name="thermal_sensors_widget_show_full_sensor_name"
value="<?= $thermal_sensors_widget_showFullSensorName;
?>" <?= ($thermal_sensors_widget_showFullSensorName) ? " checked='checked'" : ""; ?> />
</td>
</tr>
<tr>
<td>
<?= gettext('Core Warning:') ?>
</td>
<td>
<input type="text" maxlength="3" size="3" class="formfld unknown"
name="thermal_sensors_widget_core_warning_threshold"
id="thermal_sensors_widget_core_warning_threshold"
value="<?= $thermal_sensors_widget_coreWarningTempThreshold ?>" />
</td>
<td>
<label for="thermal_sensors_widget_pulsate_warning"><?= gettext('Pulsate Warning:') ?> </label>
<input type="checkbox"
id="thermal_sensors_widget_pulsate_warning"
name="thermal_sensors_widget_pulsate_warning"
value="<?= $thermal_sensors_widget_pulsateWarning;
?>" <?= ($thermal_sensors_widget_pulsateWarning) ? " checked='checked'" : ""; ?> />
</td>
</tr>
<tr>
<td>
<?= gettext('Core Critical:') ?>
</td>
<td>
<input type="text" maxlength="3" size="3" class="formfld unknown"
name="thermal_sensors_widget_core_critical_threshold"
id="thermal_sensors_widget_core_critical_threshold"
value="<?= $thermal_sensors_widget_coreCriticalTempThreshold ?>" />
</td>
<td>
<label for="thermal_sensors_widget_pulsate_critical"><?= gettext('Pulsate Critical:') ?> </label>
<input type="checkbox"
id="thermal_sensors_widget_pulsate_critical"
name="thermal_sensors_widget_pulsate_critical"
value="<?= $thermal_sensors_widget_pulsateCritical;
?>" <?= ($thermal_sensors_widget_pulsateCritical) ? " checked='checked'" : ""; ?> />
</td>
</tr>
<tr>
<td colspan="3">
<input type="submit" id="thermal_sensors_widget_submit" name="thermal_sensors_widget_submit" class="btn btn-primary formbtn" value="<?= gettext('Save') ?>" />
</td>
</tr>
<tr>
<td colspan="3">
<span>* <?= sprintf(gettext('You can configure a proper Thermal Sensor / Module %shere%s.'),'<a href="system_advanced_misc.php">','</a>') ?></span>
</td>
</tr>
</table>
</form>
<form action="/widgets/widgets/thermal_sensors.widget.php" method="post" id="iform_thermal_sensors_settings" name="iform_thermal_sensors_settings">
<table class="table table-striped">
<thead>
<tr>
<th colspan="2"><?= gettext('Thresholds in °C (1 to 100):') ?></th>
</tr>
</thead>
<tbody>
<tr>
<td><?= gettext('Zone Warning:') ?></td>
<td>
<input type="text" id="thermal_sensors_widget_zone_warning_threshold" name="thermal_sensors_widget_zone_warning_threshold" value="<?= $pconfig['thermal_sensors_widget_zone_warning_threshold']; ?>" />
</td>
</tr>
<tr>
<td><?= gettext('Zone Critical:') ?></td>
<td>
<input type="text" id="thermal_sensors_widget_zone_critical_threshold" name="thermal_sensors_widget_zone_critical_threshold" value="<?= $pconfig['thermal_sensors_widget_zone_critical_threshold']; ?>" />
</td>
</tr>
<tr>
<td><?= gettext('Core Warning:') ?></td>
<td>
<input type="text" id="thermal_sensors_widget_core_warning_threshold" name="thermal_sensors_widget_core_warning_threshold" value="<?= $pconfig['thermal_sensors_widget_core_warning_threshold']; ?>" />
</td>
</tr>
<tr>
<td><?= gettext('Core Critical:') ?></td>
<td>
<input type="text" id="thermal_sensors_widget_core_critical_threshold" name="thermal_sensors_widget_core_critical_threshold" value="<?= $pconfig['thermal_sensors_widget_core_critical_threshold']; ?>" />
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" id="thermal_sensors_widget_submit" name="thermal_sensors_widget_submit" class="btn btn-primary formbtn" value="<?= gettext('Save') ?>" />
</td>
</tr>
<tr>
<td colspan="2">
<span>* <?= sprintf(gettext('You can configure a proper Thermal Sensor / Module %shere%s.'),'<a href="system_advanced_misc.php">','</a>') ?></span>
</td>
</tr>
</tbody>
</table>
</form>
</div>
<div style="padding: 5px">
<div id="thermalSensorsContainer" class="listr">
(<?= gettext('Updating...') ?>)<br /><br />
</div>
<!-- template progress bar used for all constructed items in thermal_sensors_widget_update() -->
<div style="display:none" id="thermal_sensors_widget_progress_bar">
<div class="progress">
<div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%"></div>
</div>
<span class="info">
</span>
</div>
<table class="table table-striped table-condensed" data-plugin="temperature" data-callback="thermal_sensors_widget_update">
<tbody>
</tbody>
</table>
<!-- needed to display the widget settings menu -->
<script type="text/javascript">
//<![CDATA[
textlink = jQuery("#thermal_sensors-configure");
textlink.css({display: "inline"});
$("#thermal_sensors-configure").removeClass("disabled");
//]]>
</script>
<?php
/*
Copyright (C) 2014 Deciso B.V.
Copyright 2007 Scott Dale
Copyright (C) 2004-2005 T. Lechat <dev@lechat.org>, Manuel Kasper <mk@neon1.net>
and Jonathan Watt <jwatt@jwatt.org>.
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.
Copyright (C) 2014-2016 Deciso B.V.
Copyright 2007 Scott Dale
Copyright (C) 2004-2005 T. Lechat <dev@lechat.org>, Manuel Kasper <mk@neon1.net>
and Jonathan Watt <jwatt@jwatt.org>.
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.
*/
$nocsrf = true;
require_once("guiconfig.inc");
require_once("pfsense-utils.inc");
require_once("interfaces.inc");
$first_time = false;
if (!is_array($config["widgets"]["trafficgraphs"])) {
$first_time = true;
$config["widgets"]["trafficgraphs"] = array();
}
$a_config = &$config["widgets"]["trafficgraphs"];
if (!is_array($a_config["shown"])) {
$a_config["shown"] = array();
}
if (!is_array($a_config["shown"]["item"])) {
$a_config["shown"]["item"] = array();
}
$ifdescrs = get_configured_interface_with_descr();
if (isset($config['ipsec']['enable'])) {
$ifdescrs['enc0'] = "IPsec";
}
if ($_POST) {
if (isset($_POST["refreshinterval"])) {
$a_config["refreshinterval"] = $_POST["refreshinterval"];
}
if (isset($_POST["scale_type"])) {
$a_config["scale_type"] = $_POST["scale_type"];
}
$a_config["shown"]["item"] = array();
foreach ($ifdescrs as $ifname => $ifdescr) {
$state = $_POST["shown"][$ifname];
if ($state === "show") {
$a_config["shown"]["item"][] = $ifname;
}
}
write_config("Updated traffic graph settings via dashboard.");
header("Location: /");
exit(0);
}
$shown = array();
foreach ($a_config["shown"]["item"] as $if) {
$shown[$if] = true;
}
if ($first_time) {
$keys = array_keys($ifdescrs);
$shown[$keys[0]] = true;
}
if (isset($a_config["refreshinterval"])) {
$refreshinterval = $a_config["refreshinterval"];
} else {
$refreshinterval = 10;
}
if (isset($a_config["scale_type"])) {
$scale_type = $a_config["scale_type"];
} else {
$scale_type = "up";
}
?>
<input type="hidden" id="traffic_graphs-config" name="traffic_graphs-config" value="" />
<div id="traffic_graphs-settings" class="widgetconfigdiv" style="display:none;">
<form action="/widgets/widgets/traffic_graphs.widget.php" method="post" name="iform" id="iform">
<?php foreach ($ifdescrs as $ifname => $ifdescr) {
?>
<input type="hidden" name="shown[<?= $ifname ?>]" value="<?= $shown[$ifname] ? "show" : "hide" ?>" />
<?php
} ?>
<table class="table table-striped">
<tbody>
<tr>
<td>
<?= gettext('Default AutoScale:') ?>
</td>
</tr>
<?php
$scale_type_up='checked="checked"';
$scale_type_follow="";
if (isset($config["widgets"]["trafficgraphs"]["scale_type"])) {
$selected_radio = $config["widgets"]["trafficgraphs"]["scale_type"];
if ($selected_radio == "up") {
$scale_type_up = 'checked="checked"';
$scale_type_follow="";
} elseif ($selected_radio == "follow") {
$scale_type_up="";
$scale_type_follow = 'checked="checked"';
}
}
?>
<tr>
<td>
<input name="scale_type" type="radio" id="scale_type_up" value="up" <?= $scale_type_up; ?> /> <?= gettext('Scale up')?>
</td>
</tr>
<tr>
<td>
<input name="scale_type" type="radio" id="scale_type_follow" value="follow" <?= $scale_type_follow; ?> /> <?= gettext('Scale follow')?><br /><br />
<?= gettext('Refresh Interval:') ?>
<select name="refreshinterval" class="formfld" id="refreshinterval" >
<?php for ($i = 1; $i <= 10; $i += 1) {
?>
<option value="<?= $i ?>" <?php if ($refreshinterval == $i) {
echo 'selected="selected"';
}?>><?= $i ?></option>
<?php
} ?>
</select>&nbsp; <?= gettext('Seconds') ?><br />&nbsp; &nbsp; &nbsp; <b><?= gettext('Note:') ?></b> <?= gettext('changing this setting will increase CPU utilization') ?><br /><br />
</td>
</tr>
<tr>
<td>
<input id="submit_settings" name="submit_settings" type="submit" class="formbtn btn btn-primary" value="<?= gettext('Save Settings') ?>" />
</td>
</tr>
</tbody>
</table>
</form>
</div>
<script type="text/javascript">
//<![CDATA[
d = document;
selectIntLink = "traffic_graphs-configure";
textlink = d.getElementById(selectIntLink);
textlink.style.display = "inline";
//]]>
var traffic_graph_widget_data = [];
var traffic_graph_widget_chart_in = null;
var traffic_graph_widget_chart_data_in = null;
var traffic_graph_widget_chart_out = null;
var traffic_graph_widget_chart_data_out = null;
function traffic_widget_update(sender, data, max_measures)
{
if (max_measures == undefined) {
max_measures = 100;
}
// push new measurement, keep a maximum of max_measures measures in
traffic_graph_widget_data.push(data);
if (traffic_graph_widget_data.length > max_measures) {
traffic_graph_widget_data.shift();
} else if (traffic_graph_widget_data.length == 1) {
traffic_graph_widget_data.push(data);
}
chart_data_in = [];
chart_data_out = [];
chart_data_keys = {};
for (var i=traffic_graph_widget_data.length-1 ; i > 0 ; --i) {
var elapsed_time = traffic_graph_widget_data[i]['time'] - traffic_graph_widget_data[i-1]['time'];
for (var key in traffic_graph_widget_data[i]['interfaces']) {
var intf_item = traffic_graph_widget_data[i]['interfaces'][key];
var prev_intf_item = traffic_graph_widget_data[i-1]['interfaces'][key];
if (chart_data_keys[key] == undefined && intf_item['name'] != undefined) {
// only show configured interfaces
chart_data_keys[key] = chart_data_in.length;
chart_data_in[chart_data_in.length] = {'key': intf_item['name'], 'values': []};
chart_data_out[chart_data_out.length] = {'key': intf_item['name'], 'values': []};
}
if (chart_data_keys[key] != undefined) {
if (elapsed_time > 0) {
bps_in = ((parseInt(intf_item['bytes received']) - parseInt(prev_intf_item['bytes received']))/elapsed_time)*8;
bps_out = ((parseInt(intf_item['bytes transmitted']) - parseInt(prev_intf_item['bytes transmitted']))/elapsed_time)*8;
} else {
bps_in = 0;
bps_out = 0;
}
chart_data_in[chart_data_keys[key]]['values'].push([traffic_graph_widget_data[i]['time']*1000, bps_in])
chart_data_out[chart_data_keys[key]]['values'].push([traffic_graph_widget_data[i]['time']*1000, bps_out])
}
}
}
// get selections
var deselected_series_in = [];
var deselected_series_out = [];
d3.select("#traffic_graph_widget_chart_in").selectAll(".nv-series").each(function(d, i) {
if (d.disabled) {
deselected_series_in.push(d.key);
}
});
d3.select("#traffic_graph_widget_chart_out").selectAll(".nv-series").each(function(d, i) {
if (d.disabled) {
deselected_series_out.push(d.key);
}
});
// load data
traffic_graph_widget_chart_data_in.datum(chart_data_in).transition().duration(500).call(traffic_graph_widget_chart_in);
traffic_graph_widget_chart_data_out.datum(chart_data_out).transition().duration(500).call(traffic_graph_widget_chart_out);
// set selection
d3.selectAll("#traffic_graph_widget_chart_in").selectAll(".nv-series").each(function(d, i) {
if (deselected_series_in.indexOf(d.key) > -1) {
d3.select(this).on("click").apply(this, [d, i]);
}
});
d3.selectAll("#traffic_graph_widget_chart_out").selectAll(".nv-series").each(function(d, i) {
if (deselected_series_out.indexOf(d.key) > -1) {
d3.select(this).on("click").apply(this, [d, i]);
}
});
}
/**
* page setup
*/
$( document ).ready(function() {
// draw traffic in graph
nv.addGraph(function() {
traffic_graph_widget_chart_in = nv.models.lineChart()
.x(function(d) { return d[0] })
.y(function(d) { return d[1] })
.useInteractiveGuideline(false)
.interactive(true)
.showLegend(true)
.showXAxis(false)
.clipEdge(true)
.margin({top:5,right:5,bottom:5,left:50})
;
traffic_graph_widget_chart_in.yAxis.tickFormat(d3.format(',.2s'));
traffic_graph_widget_chart_in.xAxis.tickFormat(function(d) {
return d3.time.format('%b %e %H:%M:%S')(new Date(d));
});
traffic_graph_widget_chart_data_in = d3.select("#traffic_graph_widget_chart_in svg").datum([{'key':'', 'values':[[0, 0]]}]);
traffic_graph_widget_chart_data_in.transition().duration(500).call(traffic_graph_widget_chart_in);
});
// draw traffic out graph
nv.addGraph(function() {
traffic_graph_widget_chart_out = nv.models.lineChart()
.x(function(d) { return d[0] })
.y(function(d) { return d[1] })
.useInteractiveGuideline(false)
.interactive(true)
.showLegend(true)
.showXAxis(false)
.clipEdge(true)
.margin({top:5,right:5,bottom:5,left:50})
;
traffic_graph_widget_chart_out.yAxis.tickFormat(d3.format(',.2s'));
traffic_graph_widget_chart_out.xAxis.tickFormat(function(d) {
return d3.time.format('%b %e %H:%M:%S')(new Date(d));
});
traffic_graph_widget_chart_data_out = d3.select("#traffic_graph_widget_chart_out svg").datum([{'key':'', 'values':[[0, 0]]}]);
traffic_graph_widget_chart_data_out.transition().duration(500).call(traffic_graph_widget_chart_out);
});
});
</script>
<?php
foreach ($ifdescrs as $ifname => $ifdescr) {
$ifinfo = get_interface_info($ifname);
if ($shown[$ifname]) {
$mingraphbutton = "inline";
$showgraphbutton = "none";
$graphdisplay = "inline";
$interfacevalue = "show";
} else {
$mingraphbutton = "none";
$showgraphbutton = "inline";
$graphdisplay = "none";
$interfacevalue = "hide";
}
if ($ifinfo['status'] != "down") {
?>
<div id="<?=$ifname;?>trafficdiv" style="padding: 5px">
<div id="<?=$ifname;?>topic" class="widgetsubheader">
<div style="float:left;width:49%">
<span onclick="location.href='/status_graph.php?if=<?=$ifname;
?>'" style="cursor:pointer"><?= sprintf(gettext('Current %s Traffic'),$ifdescr) ?></span>
</div>
<div align="right" style="float:right;width:49%">
<div id="<?=$ifname;?>graphdiv-min" onclick='return trafficminimizeDiv("<?= $ifname ?>", true);'
style="display:<?php echo $mingraphbutton;
?>; cursor:pointer" ><span class="glyphicon glyphicon-minus" alt="Minimize <?=$ifname;?> traffic graph" /></span></div>
<div id="<?=$ifname;?>graphdiv-open" onclick='return trafficshowDiv("<?= $ifname ?>", true);'
style="display:<?php echo $showgraphbutton;
?>; cursor:pointer" ><span class="glyphicon glyphicon-plus" alt="Show <?=$ifname;?> traffic graph" /></span></div>
</div>
<div style="clear:both;"></div>
</div>
<div id="<?=$ifname;?>graphdiv" style="display:<?= $graphdisplay;?>">
<object data="graph.php?ifnum=<?=$ifname;
?>&amp;ifname=<?=rawurlencode($ifdescr);
?>&amp;timeint=<?=$refreshinterval;
?>&amp;initdelay=<?=($graphcounter+1) * 2;?>" height="100%" width="100%">
<param name="id" value="graph" />
<param name="type" value="image/svg+xml" />
<param name="pluginspage" value="http://www.adobe.com/svg/viewer/install/auto" />
</object>
</div>
</div>
<?php
}
}
<!-- traffic graph table -->
<table class="table table-condensed" data-plugin="traffic" data-callback="traffic_widget_update">
<tbody>
<tr>
<td><?=gettext("In (bps)");?></td>
</tr>
<tr>
<td>
<div id="traffic_graph_widget_chart_in">
<svg style="height:150px;"></svg>
</div>
</td>
</tr>
<tr>
<td><?=gettext("Out (bps)");?></td>
</tr>
<tr>
<td>
<div id="traffic_graph_widget_chart_out">
<svg style="height:150px;"></svg>
</div>
</td>
</tr>
</tbody>
</table>
<?php
/*
Copyright (C) 2014 Deciso B.V.
Copyright (C) 2010 Yehuda Katz
Copyright (C) 2014-2016 Deciso B.V.
Copyright (C) 2010 Yehuda Katz
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("widgets/include/wake_on_lan.inc");
require_once("interfaces.inc");
......@@ -39,42 +37,44 @@ if (isset($config['wol']['wolentry'])) {
}
?>
<table width="100%" border="0" cellpadding="0" cellspacing="0" summary="wol status">
<tr>
<?php
echo '<td class="widgetsubheader" align="center">' . gettext("Computer / Device") . '</td>';
echo '<td class="widgetsubheader" align="center">' . gettext("Interface") . '</td>';
echo '<td class="widgetsubheader" align="center">' . gettext("Status") . '</td>';
?>
<td class="widgetsubheader">&nbsp;</td>
</tr>
<table class="table table-striped table-condensed">
<thead>
<tr>
<th><?=gettext("Computer / Device");?></th>
<th><?=gettext("Interface");?></th>
<th><?=gettext("Status");?></th>
<th></th>
</tr>
</thead>
<tbody>
<?php
if (count($wolcomputers) > 0) {
foreach ($wolcomputers as $wolent) {
echo '<tr><td class="listlr">' . $wolent['descr'] . '<br />' . $wolent['mac'] . '</td>' . "\n";
echo '<td class="listr">' . convert_friendly_interface_to_friendly_descr($wolent['interface']) . '</td>' . "\n";
$is_active = exec("/usr/sbin/arp -an |/usr/bin/grep {$wolent['mac']}| /usr/bin/wc -l|/usr/bin/awk '{print $1;}'");
if ($is_active == 1) {
echo '<td class="listr" align="center">' . "\n";
echo "<span class=\"glyphicon glyphicon-play text-success\" alt=\"pass\" ></span> " . gettext("Online") . "</td>\n";
} else {
echo '<td class="listbg" align="center">' . "\n";
echo "<span class=\"glyphicon glyphicon-remove text-danger\" alt=\"block\" ></span> " . gettext("Offline") . "</td>\n";
}
echo '<td valign="middle" class="list nowrap">';
/*if($is_active) { */
/* Will always show wake-up button even if the code thinks it is awake */
/* } else { */
echo "<a href='services_wol.php?mac={$wolent['mac']}&amp;if={$wolent['interface']}'> ";
echo "<span class='glyphicon glyphicon-flash' title='" . gettext("Wake Up") . "' border='0' alt='wol' ></span></a>\n";
/* } */
echo "</td></tr>\n";
}
} else {
echo "<tr><td colspan=\"4\" align=\"center\">" . gettext("No saved WoL addresses") . ".</td></tr>\n";
}
?>
foreach ($wolcomputers as $wolent):
$is_active = exec("/usr/sbin/arp -an |/usr/bin/grep {$wolent['mac']}| /usr/bin/wc -l|/usr/bin/awk '{print $1;}'");?>
<tr>
<td><?=$wolent['descr'];?><br/><?=$wolent['mac'];?></td>
<td><?=htmlspecialchars(convert_friendly_interface_to_friendly_descr($wolent['interface']));?></td>
<td>
<span class="glyphicon glyphicon-<?=$is_active == 1 ? "play" : "remove";?> text-<?=$is_active == 1 ? "success" : "danger";?>" ></span>
<?=$is_active == 1 ? gettext("Online") : gettext("Offline");?>
</td>
<td>
<a href="services_wol.php?mac=<?=$wolent['mac'];?>&amp;if=<?=$wolent['interface'];?>">
<span class="glyphicon glyphicon-flash" title="<?=gettext("Wake Up");?>"></span>
</a>
</td>
</tr>
<?php
endforeach;
if (count($wolcomputers) == 0):?>
<tr>
<td colspan="4" ><?=gettext("No saved WoL addresses");?></td>
</tr>
<?php
endif;?>
</tbody>
<tfoot>
<tr>
<td colspan="4"><a href="status_dhcp_leases.php" class="navlink"><?= gettext('DHCP Leases Status') ?></a></td>
</tr>
</tfoot>
</table>
<center><a href="status_dhcp_leases.php" class="navlink"><?= gettext('DHCP Leases Status') ?></a></center>
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