diff options
Diffstat (limited to 'src/usr/local/www/widgets')
20 files changed, 1185 insertions, 1132 deletions
diff --git a/src/usr/local/www/widgets/javascript/thermal_sensors.js b/src/usr/local/www/widgets/javascript/thermal_sensors.js index 2ee8c3e..5791961 100644 --- a/src/usr/local/www/widgets/javascript/thermal_sensors.js +++ b/src/usr/local/www/widgets/javascript/thermal_sensors.js @@ -23,7 +23,7 @@ criticalTemp = 100; ajaxBusy = false; //should be called from "thermal_sensors.widget.php" -function showThermalSensorsData() { +function showThermalSensorsData(widgetKey, tsParams, firstTime) { if (!ajaxBusy) { ajaxBusy = true; //get data from thermal_sensors.widget.php @@ -35,34 +35,35 @@ function showThermalSensorsData() { type: 'get', success: function(data) { var thermalSensorsData = data || ""; - buildThermalSensorsData(thermalSensorsData); + buildThermalSensorsData(thermalSensorsData, widgetKey, tsParams, firstTime); + firstTime = false; }, error: function(jqXHR, status, error) { + firstTime = true; warningTemp = 9999; - buildThermalSensorsDataRaw('<span class="alert-danger">Temperature data could not be read.</span>'); + buildThermalSensorsDataRaw('<span class="alert-danger">Temperature data could not be read.</span>', widgetKey); } }); ajaxBusy = false; } //call itself in 11 seconds - window.setTimeout(showThermalSensorsData, 11000); + window.setTimeout(function(){showThermalSensorsData(widgetKey, tsParams, firstTime);}, 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); +function buildThermalSensorsData(thermalSensorsData, widgetKey, tsParams, firstTime) { + if (tsParams.showRawOutput) { + buildThermalSensorsDataRaw(thermalSensorsData, widgetKey); } else { - if (warningTemp == 9999) { - buildThermalSensorsDataGraph(thermalSensorsData); + if (firstTime) { + buildThermalSensorsDataGraph(thermalSensorsData, tsParams, widgetKey); } - updateThermalSensorsDataGraph(thermalSensorsData); + updateThermalSensorsDataGraph(thermalSensorsData, tsParams, widgetKey); } } -function buildThermalSensorsDataRaw(thermalSensorsData) { +function buildThermalSensorsDataRaw(thermalSensorsData, widgetKey) { var thermalSensorsContent = ""; @@ -71,20 +72,20 @@ function buildThermalSensorsDataRaw(thermalSensorsData) { //rawData = thermalSensorsData.split("|").join("<br />"); } - loadThermalSensorsContainer(thermalSensorsContent); + loadThermalSensorsContainer(thermalSensorsContent, widgetKey); } -function loadThermalSensorsContainer (thermalSensorsContent) { +function loadThermalSensorsContainer (thermalSensorsContent, widgetKey) { if (thermalSensorsContent && thermalSensorsContent != "") { //load generated graph (or raw data) into thermalSensorsContainer (thermalSensorsContainer DIV defined in "thermal_sensors.widget.php") - $('#thermalSensorsContainer').html(thermalSensorsContent); + $('#thermalSensorsContainer-' + widgetKey).html(thermalSensorsContent); } else { - $('#thermalSensorsContainer').html("No Thermal Sensors data available."); + $('#thermalSensorsContainer-' + widgetKey).html("No Thermal Sensors data available."); } } -function buildThermalSensorsDataGraph(thermalSensorsData) { +function buildThermalSensorsDataGraph(thermalSensorsData, tsParams, widgetKey) { var thermalSensorsArray = new Array(); @@ -103,26 +104,25 @@ function buildThermalSensorsDataGraph(thermalSensorsData) { //set thresholds if (sensorName.indexOf("cpu") > -1) { //check CPU Threshold config settings - warningTemp = thermal_sensors_widget_coreWarningTempThreshold; - criticalTemp = thermal_sensors_widget_coreCriticalTempThreshold; + warningTemp = tsParams.coreWarningTempThreshold; + criticalTemp = tsParams.coreCriticalTempThreshold; } else { //assuming sensor is for a zone, check Zone Threshold config settings - warningTemp = thermal_sensors_widget_zoneWarningTempThreshold; - criticalTemp = thermal_sensors_widget_zoneCriticalTempThreshold; + warningTemp = tsParams.zoneWarningTempThreshold; + criticalTemp = tsParams.zoneCriticalTempThreshold; } - //NOTE: variable thermal_sensors_widget_showFullSensorName is declared/set in "thermal_sensors.widget.php" - if (!thermal_sensors_widget_showFullSensorName) { + if (!tsParams.showFullSensorName) { sensorName = getSensorFriendlyName(sensorName); } //build temperature item/row for a sensor var thermalSensorRow = '<div class="progress">' + - '<div id="temperaturebarL' + i + '" class="progress-bar progress-bar-success progress-bar-striped" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="1" style="width: 1%"></div>' + - '<div id="temperaturebarM' + i + '" class="progress-bar progress-bar-warning progress-bar-striped" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0" style="width: 0%"></div>' + - '<div id="temperaturebarH' + i + '" class="progress-bar progress-bar-danger progress-bar-striped" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0" style="width: 0%"></div>' + + '<div id="temperaturebarL' + i + widgetKey + '" class="progress-bar progress-bar-success progress-bar-striped" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="1" style="width: 1%"></div>' + + '<div id="temperaturebarM' + i + widgetKey + '" class="progress-bar progress-bar-warning progress-bar-striped" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0" style="width: 0%"></div>' + + '<div id="temperaturebarH' + i + widgetKey + '" class="progress-bar progress-bar-danger progress-bar-striped" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0" style="width: 0%"></div>' + '</div>' + - '<span><b>' + sensorName + ': </b></span>' + '<span id="temperaturemsg' + i + '">' + thermalSensorValue + ' °C</span>'; + '<span><b>' + sensorName + ': </b></span>' + '<span id="temperaturemsg' + i + widgetKey + '">' + thermalSensorValue + ' °C</span>'; thermalSensorsHTMLContent = thermalSensorsHTMLContent + thermalSensorRow; @@ -130,12 +130,12 @@ function buildThermalSensorsDataGraph(thermalSensorsData) { } //load generated graph into thermalSensorsContainer (DIV defined in "thermal_sensors.widget.php") - loadThermalSensorsContainer(thermalSensorsHTMLContent); + loadThermalSensorsContainer(thermalSensorsHTMLContent, widgetKey); } -function updateThermalSensorsDataGraph(thermalSensorsData) { +function updateThermalSensorsDataGraph(thermalSensorsData, tsParams, widgetKey) { var thermalSensorsArray = new Array(); if (thermalSensorsData && thermalSensorsData != "") { @@ -152,19 +152,18 @@ function updateThermalSensorsDataGraph(thermalSensorsData) { //set thresholds if (sensorName.indexOf("cpu") > -1) { //check CPU Threshold config settings - warningTemp = thermal_sensors_widget_coreWarningTempThreshold; - criticalTemp = thermal_sensors_widget_coreCriticalTempThreshold; + warningTemp = tsParams.coreWarningTempThreshold; + criticalTemp = tsParams.coreCriticalTempThreshold; } else { //assuming sensor is for a zone, check Zone Threshold config settings - warningTemp = thermal_sensors_widget_zoneWarningTempThreshold; - criticalTemp = thermal_sensors_widget_zoneCriticalTempThreshold; + warningTemp = tsParams.zoneWarningTempThreshold; + criticalTemp = tsParams.zoneCriticalTempThreshold; } - //NOTE: variable thermal_sensors_widget_showFullSensorName is declared/set in "thermal_sensors.widget.php" - if (!thermal_sensors_widget_showFullSensorName) { + if (!tsParams.showFullSensorName) { sensorName = getSensorFriendlyName(sensorName); } - setTempProgress(i, thermalSensorValue); + setTempProgress(i, thermalSensorValue, widgetKey); } } @@ -189,7 +188,7 @@ function getThermalSensorValue(stringValue) { // Update the progress indicator // transition = true allows the bar to move at default speed, false = instantaneous -function setTempProgress(bar, percent) { +function setTempProgress(bar, percent, widgetKey) { var barTempL, barTempM, barTempH; if (percent <= warningTemp) { @@ -207,9 +206,9 @@ function setTempProgress(bar, percent) { } - $('#' + 'temperaturebarL' + bar).css('width', barTempL + '%').attr('aria-valuenow', barTempL); - $('#' + 'temperaturebarM' + bar).css('width', barTempM + '%').attr('aria-valuenow', barTempM); - $('#' + 'temperaturebarH' + bar).css('width', barTempH + '%').attr('aria-valuenow', barTempH); + $('#' + 'temperaturebarL' + bar + widgetKey).css('width', barTempL + '%').attr('aria-valuenow', barTempL); + $('#' + 'temperaturebarM' + bar + widgetKey).css('width', barTempM + '%').attr('aria-valuenow', barTempM); + $('#' + 'temperaturebarH' + bar + widgetKey).css('width', barTempH + '%').attr('aria-valuenow', barTempH); - $('#' + 'temperaturemsg' + bar).html(percent + ' °C'); + $('#' + 'temperaturemsg' + bar + widgetKey).html(percent + ' °C'); } diff --git a/src/usr/local/www/widgets/widgets/captive_portal_status.widget.php b/src/usr/local/www/widgets/widgets/captive_portal_status.widget.php index 65c8b4a..725ca60 100644 --- a/src/usr/local/www/widgets/widgets/captive_portal_status.widget.php +++ b/src/usr/local/www/widgets/widgets/captive_portal_status.widget.php @@ -54,9 +54,11 @@ unset($cpzone); flush(); -function clientcmp($a, $b) { - global $order; - return strcmp($a[$order], $b[$order]); +if (!function_exists('clientcmp')) { + function clientcmp($a, $b) { + global $order; + return strcmp($a[$order], $b[$order]); + } } $cpdb_all = array(); diff --git a/src/usr/local/www/widgets/widgets/dyn_dns_status.widget.php b/src/usr/local/www/widgets/widgets/dyn_dns_status.widget.php index 6e90d4e..c5dfd98 100644 --- a/src/usr/local/www/widgets/widgets/dyn_dns_status.widget.php +++ b/src/usr/local/www/widgets/widgets/dyn_dns_status.widget.php @@ -29,17 +29,21 @@ require_once("functions.inc"); require_once("/usr/local/www/widgets/include/dyn_dns_status.inc"); // Constructs a unique key that will identify a Dynamic DNS entry in the filter list. -function get_dyndnsent_key($dyndns) { - return $dyndns['id']; +if (!function_exists('get_dyndnsent_key')) { + function get_dyndnsent_key($dyndns) { + return $dyndns['id']; + } } -function get_dyndns_hostname_text($dyndns) { - global $dyndns_split_domain_types; - if (in_array($dyndns['type'], $dyndns_split_domain_types)) { - return $dyndns['host'] . "." . $dyndns['domainname']; - } +if (!function_exists('get_dyndns_hostname_text')) { + function get_dyndns_hostname_text($dyndns) { + global $dyndns_split_domain_types; + if (in_array($dyndns['type'], $dyndns_split_domain_types)) { + return $dyndns['host'] . "." . $dyndns['domainname']; + } - return $dyndns['host']; + return $dyndns['host']; + } } if (!is_array($config['dyndnses']['dyndns'])) { @@ -64,9 +68,8 @@ array_walk($all_dyndns, function(&$dyndns) { } }); -$skipdyndns = explode(",", $user_settings['widgets']['dyn_dns_status']['filter']); - if ($_REQUEST['getdyndnsstatus']) { + $skipdyndns = explode(",", $user_settings['widgets'][$_REQUEST['getdyndnsstatus']]['filter']); $first_entry = true; foreach ($all_dyndns as $dyndns) { if (in_array(get_dyndnsent_key($dyndns), $skipdyndns)) { @@ -114,7 +117,7 @@ if ($_REQUEST['getdyndnsstatus']) { } } exit; -} else if ($_POST) { +} else if ($_POST['widgetkey']) { $validNames = array(); @@ -123,9 +126,9 @@ if ($_REQUEST['getdyndnsstatus']) { } if (is_array($_POST['show'])) { - $user_settings['widgets']['dyn_dns_status']['filter'] = implode(',', array_diff($validNames, $_POST['show'])); + $user_settings['widgets'][$_POST['widgetkey']]['filter'] = implode(',', array_diff($validNames, $_POST['show'])); } else { - $user_settings['widgets']['dyn_dns_status']['filter'] = ""; + $user_settings['widgets'][$_POST['widgetkey']]['filter'] = implode(',', $validNames); } save_widget_settings($_SESSION['Username'], $user_settings["widgets"], gettext("Saved Dynamic DNS Filter via Dashboard.")); @@ -134,28 +137,34 @@ if ($_REQUEST['getdyndnsstatus']) { $iflist = get_configured_interface_with_descr(); -function get_dyndns_interface_text($dyndns_iface) { - global $iflist; - if (isset($iflist[$dyndns_iface])) { - return $iflist[$dyndns_iface]; - } +if (!function_exists('get_dyndns_interface_text')) { + function get_dyndns_interface_text($dyndns_iface) { + global $iflist; + if (isset($iflist[$dyndns_iface])) { + return $iflist[$dyndns_iface]; + } - // This will be a gateway group name. - return $dyndns_iface; + // This will be a gateway group name. + return $dyndns_iface; + } } $dyndns_providers = array_combine(explode(" ", DYNDNS_PROVIDER_VALUES), explode(",", DYNDNS_PROVIDER_DESCRIPTIONS)); +$skipdyndns = explode(",", $user_settings['widgets'][$widgetkey]['filter']); +$widgetkey_nodash = str_replace("-", "", $widgetkey); -function get_dyndns_service_text($dyndns_type) { - global $dyndns_providers; +if (!function_exists('get_dyndns_service_text')) { + function get_dyndns_service_text($dyndns_type) { + global $dyndns_providers; - if (isset($dyndns_providers[$dyndns_type])) { - return $dyndns_providers[$dyndns_type]; - } else if ($dyndns_type == '_rfc2136_') { - return "RFC 2136"; - } + if (isset($dyndns_providers[$dyndns_type])) { + return $dyndns_providers[$dyndns_type]; + } else if ($dyndns_type == '_rfc2136_') { + return "RFC 2136"; + } - return $dyndns_type; + return $dyndns_type; + } } ?> @@ -204,15 +213,23 @@ function get_dyndns_service_text($dyndns_type) { </td> </tr> <?php endforeach;?> + <?php if ($rowid == -1):?> + <tr> + <td colspan="4" class="text-center"> + <?=gettext('All Dyn DNS entries are hidden.');?> + </td> + </tr> + <?php endif;?> </tbody> </table> </div> <!-- close the body we're wrapped in and add a configuration-panel --> -</div><div id="widget-<?=$widgetname?>_panel-footer" class="panel-footer collapse"> +</div><div id="<?=$widget_panel_footer_id?>" class="panel-footer collapse"> <form action="/widgets/widgets/dyn_dns_status.widget.php" method="post" class="form-horizontal"> <div class="panel panel-default col-sm-10"> <div class="panel-body"> + <input type="hidden" name="widgetkey" value="<?=$widgetkey; ?>"> <div class="table responsive"> <table class="table table-striped table-hover table-condensed"> <thead> @@ -225,7 +242,7 @@ function get_dyndns_service_text($dyndns_type) { </thead> <tbody> <?php - $skipdyndns = explode(",", $user_settings['widgets']['dyn_dns_status']['filter']); + $skipdyndns = explode(",", $user_settings['widgets'][$widgetkey]['filter']); foreach ($all_dyndns as $dyndns): ?> <tr> @@ -246,46 +263,41 @@ function get_dyndns_service_text($dyndns_type) { <div class="form-group"> <div class="col-sm-offset-3 col-sm-6"> <button type="submit" class="btn btn-primary"><i class="fa fa-save icon-embed-btn"></i><?=gettext('Save')?></button> - <button id="showalldyndns" type="button" class="btn btn-info"><i class="fa fa-undo icon-embed-btn"></i><?=gettext('All')?></button> + <button id="<?=$widget_showallnone_id?>" type="button" class="btn btn-info"><i class="fa fa-undo icon-embed-btn"></i><?=gettext('All')?></button> </div> </div> </form> <script type="text/javascript"> //<![CDATA[ - function dyndns_getstatus() { + function dyndns_getstatus_<?=$widgetkey_nodash?>() { scroll(0,0); var url = "/widgets/widgets/dyn_dns_status.widget.php"; - var pars = 'getdyndnsstatus=yes'; + var pars = 'getdyndnsstatus=<?=$widgetkey?>'; $.ajax( url, { type: 'get', data: pars, - complete: dyndnscallback + complete: dyndnscallback_<?=$widgetkey_nodash?> }); } - function dyndnscallback(transport) { + function dyndnscallback_<?=$widgetkey_nodash?>(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; + var divlabel = '#widget-<?=$widgetkey?> #dyndnsstatus' + count; $(divlabel).prop('innerHTML',responseStrings[count]); } // Refresh the status every 5 minutes - setTimeout('dyndns_getstatus()', 5*60*1000); + setTimeout('dyndns_getstatus_<?=$widgetkey_nodash?>()', 5*60*1000); } events.push(function(){ - $("#showalldyndns").click(function() { - $("#widget-<?=$widgetname?>_panel-footer [id^=show]").each(function() { - $(this).prop("checked", true); - }); - }); - + set_widget_checkbox_events("#<?=$widget_panel_footer_id?> [id^=show]", "<?=$widget_showallnone_id?>"); }); // Do the first status check 2 seconds after the dashboard opens - setTimeout('dyndns_getstatus()', 2000); + setTimeout('dyndns_getstatus_<?=$widgetkey_nodash?>()', 2000); //]]> </script> diff --git a/src/usr/local/www/widgets/widgets/gateways.widget.php b/src/usr/local/www/widgets/widgets/gateways.widget.php index d414a5e..7dfd8ac 100644 --- a/src/usr/local/www/widgets/widgets/gateways.widget.php +++ b/src/usr/local/www/widgets/widgets/gateways.widget.php @@ -31,34 +31,164 @@ require_once("pfsense-utils.inc"); require_once("functions.inc"); require_once("/usr/local/www/widgets/include/gateways.inc"); +if (!function_exists('compose_table_body_contents')) { + function compose_table_body_contents($widgetkey) { + global $user_settings; + + $rtnstr = ''; + + $a_gateways = return_gateways_array(); + $gateways_status = array(); + $gateways_status = return_gateways_status(true); + + if (isset($user_settings["widgets"][$widgetkey]["display_type"])) { + $display_type = $user_settings["widgets"][$widgetkey]["display_type"]; + } else { + $display_type = "gw_ip"; + } + + $hiddengateways = explode(",", $user_settings["widgets"][$widgetkey]["gatewaysfilter"]); + $gw_displayed = false; + + foreach ($a_gateways as $gname => $gateway) { + if (in_array($gname, $hiddengateways)) { + continue; + } + + $gw_displayed = true; + $rtnstr .= "<tr>\n"; + $rtnstr .= "<td>\n"; + $rtnstr .= htmlspecialchars($gateway['name']) . "<br />"; + $rtnstr .= '<div id="gateway' . $counter . '" style="display:inline"><b>'; + + $monitor_address = ""; + $monitor_address_disp = ""; + if ($display_type == "monitor_ip" || $display_type == "both_ip") { + $monitor_address = $gateway['monitor']; + if ($monitor_address != "" && $display_type == "both_ip") { + $monitor_address_disp = " (" . $monitor_address . ")"; + } else { + $monitor_address_disp = $monitor_address; + } + } + + $if_gw = ''; + // If the user asked to display Gateway IP or both IPs, or asked for just monitor IP but the monitor IP is blank + // then find the gateway IP (which is also the monitor IP if the monitor IP was not explicitly set). + if ($display_type == "gw_ip" || $display_type == "both_ip" || ($display_type == "monitor_ip" && $monitor_address == "")) { + 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'])); + } + } + if ($if_gw == "") { + $if_gw = "~"; + } + } + + if ($monitor_address == $if_gw) { + $monitor_address_disp = ""; + } + + $rtnstr .= $if_gw . $monitor_address_disp; + unset ($if_gw); + unset ($monitor_address); + unset ($monitor_address_disp); + $counter++; + + $rtnstr .= "</b>"; + $rtnstr .= "</div>\n"; + $rtnstr .= "</td>\n"; + + if ($gateways_status[$gname]) { + if (stristr($gateways_status[$gname]['status'], "force_down")) { + $online = gettext("Offline (forced)"); + $bgcolor = "danger"; // lightcoral + } elseif (stristr($gateways_status[$gname]['status'], "down")) { + $online = gettext("Offline"); + $bgcolor = "danger"; // lightcoral + } elseif (stristr($gateways_status[$gname]['status'], "highloss")) { + $online = gettext("Packetloss"); + $bgcolor = "danger"; // lightcoral + } elseif (stristr($gateways_status[$gname]['status'], "loss")) { + $online = gettext("Packetloss"); + $bgcolor = "warning"; // khaki + } elseif (stristr($gateways_status[$gname]['status'], "highdelay")) { + $online = gettext("Latency"); + $bgcolor = "danger"; // lightcoral + } elseif (stristr($gateways_status[$gname]['status'], "delay")) { + $online = gettext("Latency"); + $bgcolor = "warning"; // khaki + } elseif ($gateways_status[$gname]['status'] == "none") { + if ($gateways_status[$gname]['monitor_disable'] || ($gateways_status[$gname]['monitorip'] == "none")) { + $online = gettext("Online <br/>(unmonitored)"); + } else { + $online = gettext("Online"); + } + $bgcolor = "success"; // lightgreen + } elseif ($gateways_status[$gname]['status'] == "") { + $online = gettext("Pending"); + $bgcolor = "info"; // lightgray + } + } else { + $online = gettext("Unknown"); + $bgcolor = "info"; // lightblue + } + + $rtnstr .= "<td>" . ($gateways_status[$gname] ? ($gateways_status[$gname]['delay'] ? htmlspecialchars(number_format((float)rtrim($gateways_status[$gname]['delay'], "ms"), 1)) . "ms" : '') : gettext("Pending")) . "</td>\n"; + $rtnstr .= "<td>" . ($gateways_status[$gname] ? ($gateways_status[$gname]['stddev'] ? htmlspecialchars(number_format((float)rtrim($gateways_status[$gname]['stddev'], "ms"), 1)) . "ms" : '') : gettext("Pending")) . "</td>\n"; + $rtnstr .= "<td>" . ($gateways_status[$gname] ? htmlspecialchars($gateways_status[$gname]['loss']) : gettext("Pending")) . "</td>\n"; + $rtnstr .= '<td class="bg-' . $bgcolor . '">' . $online . "</td>\n"; + $rtnstr .= "</tr>\n"; + } + + if (!$gw_displayed) { + $rtnstr .= '<tr>'; + $rtnstr .= '<td colspan="5" class="text-center">'; + if (count($a_gateways)) { + $rtnstr .= gettext('All gateways are hidden.'); + } else { + $rtnstr .= gettext('No gateways found.'); + } + $rtnstr .= '</td>'; + $rtnstr .= '</tr>'; + } + return($rtnstr); + } +} + // Compose the table contents and pass it back to the ajax caller if ($_REQUEST && $_REQUEST['ajax']) { - print(compose_table_body_contents()); + print(compose_table_body_contents($_REQUEST['widgetkey'])); exit; } -if ($_POST) { +if ($_POST['widgetkey']) { - - if (!is_array($user_settings["widgets"]["gateways_widget"])) { - $user_settings["widgets"]["gateways_widget"] = array(); + if (!is_array($user_settings["widgets"][$_POST['widgetkey']])) { + $user_settings["widgets"][$_POST['widgetkey']] = array(); } if (isset($_POST["display_type"])) { - $user_settings["widgets"]["gateways_widget"]["display_type"] = $_POST["display_type"]; + $user_settings["widgets"][$_POST['widgetkey']]["display_type"] = $_POST["display_type"]; } - if (is_array($_POST['show'])) { - $validNames = array(); - $a_gateways = return_gateways_array(); + $validNames = array(); + $a_gateways = return_gateways_array(); - foreach ($a_gateways as $gname => $gateway) { - array_push($validNames, $gname); - } + foreach ($a_gateways as $gname => $gateway) { + array_push($validNames, $gname); + } - $user_settings["widgets"]["gateways_widget"]["gatewaysfilter"] = implode(',', array_diff($validNames, $_POST['show'])); + if (is_array($_POST['show'])) { + $user_settings["widgets"][$_POST['widgetkey']]["gatewaysfilter"] = implode(',', array_diff($validNames, $_POST['show'])); } else { - $user_settings["widgets"]["gateways_widget"]["gatewaysfilter"] = ""; + $user_settings["widgets"][$_POST['widgetkey']]["gatewaysfilter"] = implode(',', $validNames); } save_widget_settings($_SESSION['Username'], $user_settings["widgets"], gettext("Updated gateways widget settings via dashboard.")); @@ -67,6 +197,8 @@ if ($_POST) { } $widgetperiod = isset($config['widgets']['period']) ? $config['widgets']['period'] * 1000 : 10000; +$widgetkey_nodash = str_replace("-", "", $widgetkey); + ?> <div class="table-responsive"> @@ -80,15 +212,15 @@ $widgetperiod = isset($config['widgets']['period']) ? $config['widgets']['period <th><?=gettext("Status")?></th> </tr> </thead> - <tbody id="gwtblbody"> + <tbody id="<?=$widgetkey?>-gwtblbody"> <?php - print(compose_table_body_contents()); + print(compose_table_body_contents($widgetkey)); ?> </tbody> </table> </div> <!-- close the body we're wrapped in and add a configuration-panel --> -</div><div id="widget-<?=$widgetname?>_panel-footer" class="panel-footer collapse"> +</div><div id="<?=$widget_panel_footer_id?>" class="panel-footer collapse"> <form action="/widgets/widgets/gateways.widget.php" method="post" class="form-horizontal"> <div class="form-group"> <label class="col-sm-3 control-label"><?=gettext('Display')?></label> @@ -96,8 +228,8 @@ $widgetperiod = isset($config['widgets']['period']) ? $config['widgets']['period $display_type_gw_ip = "checked"; $display_type_monitor_ip = ""; $display_type_both_ip = ""; - if (isset($user_settings["widgets"]["gateways_widget"]["display_type"])) { - $selected_radio = $user_settings["widgets"]["gateways_widget"]["display_type"]; + if (isset($user_settings["widgets"][$widgetkey]["display_type"])) { + $selected_radio = $user_settings["widgets"][$widgetkey]["display_type"]; if ($selected_radio == "gw_ip") { $display_type_gw_ip = "checked"; $display_type_monitor_ip = ""; @@ -130,6 +262,7 @@ $widgetperiod = isset($config['widgets']['period']) ? $config['widgets']['period <div class="panel panel-default col-sm-10"> <div class="panel-body"> + <input type="hidden" name="widgetkey" value="<?=$widgetkey; ?>"> <div class="table responsive"> <table class="table table-striped table-hover table-condensed"> <thead> @@ -141,7 +274,7 @@ $widgetperiod = isset($config['widgets']['period']) ? $config['widgets']['period <tbody> <?php $a_gateways = return_gateways_array(); - $hiddengateways = explode(",", $user_settings["widgets"]["gateways_widget"]["gatewaysfilter"]); + $hiddengateways = explode(",", $user_settings["widgets"][$widgetkey]["gatewaysfilter"]); $idx = 0; foreach ($a_gateways as $gname => $gateway): @@ -162,7 +295,7 @@ $widgetperiod = isset($config['widgets']['period']) ? $config['widgets']['period <div class="form-group"> <div class="col-sm-offset-3 col-sm-6"> <button type="submit" class="btn btn-primary"><i class="fa fa-save icon-embed-btn"></i><?=gettext('Save')?></button> - <button id="showallgateways" type="button" class="btn btn-info"><i class="fa fa-undo icon-embed-btn"></i><?=gettext('All')?></button> + <button id="<?=$widget_showallnone_id?>" type="button" class="btn btn-info"><i class="fa fa-undo icon-embed-btn"></i><?=gettext('All')?></button> </div> </div> </form> @@ -170,164 +303,29 @@ $widgetperiod = isset($config['widgets']['period']) ? $config['widgets']['period <script> //<![CDATA[ - function get_gw_stats() { + function get_gw_stats_<?=$widgetkey_nodash?>() { var ajaxRequest; ajaxRequest = $.ajax({ url: "/widgets/widgets/gateways.widget.php", type: "post", - data: { ajax: "ajax"} + data: { ajax: "ajax", widgetkey: "<?=$widgetkey?>"} }); // Deal with the results of the above ajax call ajaxRequest.done(function (response, textStatus, jqXHR) { - $('#gwtblbody').html(response); + $('#<?=$widgetkey?>-gwtblbody').html(response); // and do it again - setTimeout(get_gw_stats, "<?=$widgetperiod?>"); + setTimeout(get_gw_stats_<?=$widgetkey_nodash?>, "<?=$widgetperiod?>"); }); } events.push(function(){ - $("#showallgateways").click(function() { - $("#widget-<?=$widgetname?>_panel-footer [id^=show]").each(function() { - $(this).prop("checked", true); - }); - }); + set_widget_checkbox_events("#<?=$widget_panel_footer_id?> [id^=show]", "<?=$widget_showallnone_id?>"); // Start polling for updates some small random number of seconds from now (so that all the widgets don't // hit the server at exactly the same time) - setTimeout(get_gw_stats, Math.floor((Math.random() * 10000) + 1000)); + setTimeout(get_gw_stats_<?=$widgetkey_nodash?>, Math.floor((Math.random() * 10000) + 1000)); }); //]]> </script> - -<?php -function compose_table_body_contents() { - global $user_settings; - - $rtnstr = ''; - - $a_gateways = return_gateways_array(); - $gateways_status = array(); - $gateways_status = return_gateways_status(true); - - if (isset($user_settings["widgets"]["gateways_widget"]["display_type"])) { - $display_type = $user_settings["widgets"]["gateways_widget"]["display_type"]; - } else { - $display_type = "gw_ip"; - } - - $hiddengateways = explode(",", $user_settings["widgets"]["gateways_widget"]["gatewaysfilter"]); - $gw_displayed = false; - - foreach ($a_gateways as $gname => $gateway) { - if (in_array($gname, $hiddengateways)) { - continue; - } - - $gw_displayed = true; - $rtnstr .= "<tr>\n"; - $rtnstr .= "<td>\n"; - $rtnstr .= htmlspecialchars($gateway['name']) . "<br />"; - $rtnstr .= '<div id="gateway' . $counter . '" style="display:inline"><b>'; - - $monitor_address = ""; - $monitor_address_disp = ""; - if ($display_type == "monitor_ip" || $display_type == "both_ip") { - $monitor_address = $gateway['monitor']; - if ($monitor_address != "" && $display_type == "both_ip") { - $monitor_address_disp = " (" . $monitor_address . ")"; - } else { - $monitor_address_disp = $monitor_address; - } - } - - $if_gw = ''; - // If the user asked to display Gateway IP or both IPs, or asked for just monitor IP but the monitor IP is blank - // then find the gateway IP (which is also the monitor IP if the monitor IP was not explicitly set). - if ($display_type == "gw_ip" || $display_type == "both_ip" || ($display_type == "monitor_ip" && $monitor_address == "")) { - 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'])); - } - } - if ($if_gw == "") { - $if_gw = "~"; - } - } - - if ($monitor_address == $if_gw) { - $monitor_address_disp = ""; - } - - $rtnstr .= $if_gw . $monitor_address_disp; - unset ($if_gw); - unset ($monitor_address); - unset ($monitor_address_disp); - $counter++; - - $rtnstr .= "</b>"; - $rtnstr .= "</div>\n"; - $rtnstr .= "</td>\n"; - - if ($gateways_status[$gname]) { - if (stristr($gateways_status[$gname]['status'], "force_down")) { - $online = gettext("Offline (forced)"); - $bgcolor = "danger"; // lightcoral - } elseif (stristr($gateways_status[$gname]['status'], "down")) { - $online = gettext("Offline"); - $bgcolor = "danger"; // lightcoral - } elseif (stristr($gateways_status[$gname]['status'], "highloss")) { - $online = gettext("Packetloss"); - $bgcolor = "danger"; // lightcoral - } elseif (stristr($gateways_status[$gname]['status'], "loss")) { - $online = gettext("Packetloss"); - $bgcolor = "warning"; // khaki - } elseif (stristr($gateways_status[$gname]['status'], "highdelay")) { - $online = gettext("Latency"); - $bgcolor = "danger"; // lightcoral - } elseif (stristr($gateways_status[$gname]['status'], "delay")) { - $online = gettext("Latency"); - $bgcolor = "warning"; // khaki - } elseif ($gateways_status[$gname]['status'] == "none") { - if ($gateways_status[$gname]['monitor_disable'] || ($gateways_status[$gname]['monitorip'] == "none")) { - $online = gettext("Online <br/>(unmonitored)"); - } else { - $online = gettext("Online"); - } - $bgcolor = "success"; // lightgreen - } elseif ($gateways_status[$gname]['status'] == "") { - $online = gettext("Pending"); - $bgcolor = "info"; // lightgray - } - } else { - $online = gettext("Unknown"); - $bgcolor = "info"; // lightblue - } - - $rtnstr .= "<td>" . ($gateways_status[$gname] ? htmlspecialchars($gateways_status[$gname]['delay']) : gettext("Pending")) . "</td>\n"; - $rtnstr .= "<td>" . ($gateways_status[$gname] ? htmlspecialchars($gateways_status[$gname]['stddev']) : gettext("Pending")) . "</td>\n"; - $rtnstr .= "<td>" . ($gateways_status[$gname] ? htmlspecialchars($gateways_status[$gname]['loss']) : gettext("Pending")) . "</td>\n"; - $rtnstr .= '<td class="bg-' . $bgcolor . '">' . $online . "</td>\n"; - $rtnstr .= "</tr>\n"; - } - - if (!$gw_displayed) { - $rtnstr .= '<tr>'; - $rtnstr .= '<td colspan="5">'; - if (count($a_gateways)) { - $rtnstr .= gettext('All gateways are hidden.'); - } else { - $rtnstr .= gettext('No gateways found.'); - } - $rtnstr .= '</td>'; - $rtnstr .= '</tr>'; - } - return($rtnstr); -} -?> diff --git a/src/usr/local/www/widgets/widgets/gmirror_status.widget.php b/src/usr/local/www/widgets/widgets/gmirror_status.widget.php index 046e9f3..60f11ba 100644 --- a/src/usr/local/www/widgets/widgets/gmirror_status.widget.php +++ b/src/usr/local/www/widgets/widgets/gmirror_status.widget.php @@ -33,6 +33,7 @@ require_once("gmirror.inc"); <?=gmirror_html_status()?> </div> +<?php if ($widget_first_instance): ?> <script type="text/javascript"> //<![CDATA[ function gmirrorStatusUpdateFromServer() { @@ -45,7 +46,10 @@ function gmirrorStatusUpdateFromServer() { return raw.replace(/<script>([\s\S]*)<\/script>/gi, ''); }, success: function(data){ - $('#gmirror_status').html(data); + $('[id="gmirror_status"]').html(data); + }, + error: function(){ + $('[id="gmirror_status"]').html("<div class=\"alert alert-danger\"><?=gettext('Unable to retrieve status'); ?></div>"); } }); } @@ -55,3 +59,4 @@ events.push(function(){ }); //]]> </script> +<?php endif; ?>
\ No newline at end of file diff --git a/src/usr/local/www/widgets/widgets/installed_packages.widget.php b/src/usr/local/www/widgets/widgets/installed_packages.widget.php index 1840d6f..d344ce5 100644 --- a/src/usr/local/www/widgets/widgets/installed_packages.widget.php +++ b/src/usr/local/www/widgets/widgets/installed_packages.widget.php @@ -146,6 +146,7 @@ if ($_REQUEST && $_REQUEST['ajax']) { <?=gettext("Packages may be added/managed here: ")?> <a href="pkg_mgr_installed.php"><?=gettext("System")?> -> <?=gettext("Packages")?></a> </p> +<?php if ($widget_first_instance): ?> <script type="text/javascript"> //<![CDATA[ @@ -160,7 +161,7 @@ if ($_REQUEST && $_REQUEST['ajax']) { // Deal with the results of the above ajax call ajaxRequest.done(function (response, textStatus, jqXHR) { - $('#pkgtbl').html(response); + $('[id="pkgtbl"]').html(response); // and do it again // NOT! There is no need to refresh this widget @@ -173,3 +174,4 @@ if ($_REQUEST && $_REQUEST['ajax']) { }); //]]> </script> +<?php endif; ?>
\ No newline at end of file diff --git a/src/usr/local/www/widgets/widgets/interface_statistics.widget.php b/src/usr/local/www/widgets/widgets/interface_statistics.widget.php index bb10731..7944b4b 100644 --- a/src/usr/local/www/widgets/widgets/interface_statistics.widget.php +++ b/src/usr/local/www/widgets/widgets/interface_statistics.widget.php @@ -48,7 +48,8 @@ if ($_REQUEST && $_REQUEST['ajax']) { 'collisions' => gettext('Collisions'), ); - $skipinterfaces = explode(",", $user_settings['widgets']['interface_statistics']['iffilter']); + $skipinterfaces = explode(",", $user_settings['widgets'][$_REQUEST['widgetkey']]['iffilter']); + $interface_is_displayed = false; print("<thead>"); print( "<tr>"); @@ -57,9 +58,14 @@ if ($_REQUEST && $_REQUEST['ajax']) { foreach ($ifdescrs as $ifdescr => $ifname) { if (!in_array($ifdescr, $skipinterfaces)) { print( "<th>" . $ifname . "</th>"); + $interface_is_displayed = true; } } + if (!$interface_is_displayed) { + print("<th>" . gettext('All interfaces are hidden.') . "</th>"); + } + print( "</tr>"); print( "</thead>"); print( "<tbody>"); @@ -90,7 +96,7 @@ if ($_REQUEST && $_REQUEST['ajax']) { } print( "</tbody>"); exit; -} else if ($_POST) { +} else if ($_POST['widgetkey']) { $validNames = array(); @@ -99,9 +105,9 @@ if ($_REQUEST && $_REQUEST['ajax']) { } if (is_array($_POST['show'])) { - $user_settings['widgets']['interface_statistics']['iffilter'] = implode(',', array_diff($validNames, $_POST['show'])); + $user_settings['widgets'][$_POST['widgetkey']]['iffilter'] = implode(',', array_diff($validNames, $_POST['show'])); } else { - $user_settings['widgets']['interface_statistics']['iffilter'] = ""; + $user_settings['widgets'][$_POST['widgetkey']]['iffilter'] = implode(',', $validNames); } save_widget_settings($_SESSION['Username'], $user_settings["widgets"], gettext("Saved Interface Statistics Filter via Dashboard.")); @@ -109,18 +115,20 @@ if ($_REQUEST && $_REQUEST['ajax']) { } $widgetperiod = isset($config['widgets']['period']) ? $config['widgets']['period'] * 1000 : 10000; +$widgetkey_nodash = str_replace("-", "", $widgetkey); ?> -<table id="iftbl" class="table table-striped table-hover"> +<table id="<?=$widgetkey?>-iftbl" class="table table-striped table-hover"> <tr><td><?=gettext("Retrieving interface data")?></td></tr> </table> <!-- close the body we're wrapped in and add a configuration-panel --> -</div><div id="widget-<?=$widgetname?>_panel-footer" class="panel-footer collapse"> +</div><div id="<?=$widget_panel_footer_id?>" class="panel-footer collapse"> <form action="/widgets/widgets/interface_statistics.widget.php" method="post" class="form-horizontal"> <div class="panel panel-default col-sm-10"> <div class="panel-body"> + <input type="hidden" name="widgetkey" value="<?=$widgetkey; ?>"> <div class="table responsive"> <table class="table table-striped table-hover table-condensed"> <thead> @@ -131,7 +139,7 @@ $widgetperiod = isset($config['widgets']['period']) ? $config['widgets']['period </thead> <tbody> <?php - $skipinterfaces = explode(",", $user_settings['widgets']['interface_statistics']['iffilter']); + $skipinterfaces = explode(",", $user_settings['widgets'][$widgetkey]['iffilter']); $idx = 0; foreach ($ifdescrs as $ifdescr => $ifname): @@ -152,7 +160,7 @@ $widgetperiod = isset($config['widgets']['period']) ? $config['widgets']['period <div class="form-group"> <div class="col-sm-offset-3 col-sm-6"> <button type="submit" class="btn btn-primary"><i class="fa fa-save icon-embed-btn"></i><?=gettext('Save')?></button> - <button id="showallinterfacesforstats" type="button" class="btn btn-info"><i class="fa fa-undo icon-embed-btn"></i><?=gettext('All')?></button> + <button id="<?=$widget_showallnone_id?>" type="button" class="btn btn-info"><i class="fa fa-undo icon-embed-btn"></i><?=gettext('All')?></button> </div> </div> </form> @@ -160,34 +168,30 @@ $widgetperiod = isset($config['widgets']['period']) ? $config['widgets']['period <script type="text/javascript"> //<![CDATA[ - function get_if_stats() { + function get_if_stats_<?=$widgetkey_nodash?>() { var ajaxRequest; ajaxRequest = $.ajax({ url: "/widgets/widgets/interface_statistics.widget.php", type: "post", - data: { ajax: "ajax"} + data: { ajax: "ajax", widgetkey: "<?=$widgetkey?>"} }); // Deal with the results of the above ajax call ajaxRequest.done(function (response, textStatus, jqXHR) { - $('#iftbl').html(response); + $('#<?=$widgetkey?>-iftbl').html(response); // and do it again - setTimeout(get_if_stats, "<?=$widgetperiod?>"); + setTimeout(get_if_stats_<?=$widgetkey_nodash?>, "<?=$widgetperiod?>"); }); } events.push(function(){ - $("#showallinterfacesforstats").click(function() { - $("#widget-<?=$widgetname?>_panel-footer [id^=show]").each(function() { - $(this).prop("checked", true); - }); - }); + set_widget_checkbox_events("#<?=$widget_panel_footer_id?> [id^=show]", "<?=$widget_showallnone_id?>"); // Start polling for updates some small random number of seconds from now (so that all the widgets don't // hit the server at exactly the same time) - setTimeout(get_if_stats, Math.floor((Math.random() * 10000) + 1000)); + setTimeout(get_if_stats_<?=$widgetkey_nodash?>, Math.floor((Math.random() * 10000) + 1000)); }); //]]> </script> diff --git a/src/usr/local/www/widgets/widgets/interfaces.widget.php b/src/usr/local/www/widgets/widgets/interfaces.widget.php index 69a2869..0528402 100644 --- a/src/usr/local/www/widgets/widgets/interfaces.widget.php +++ b/src/usr/local/www/widgets/widgets/interfaces.widget.php @@ -28,8 +28,10 @@ require_once("functions.inc"); require_once("/usr/local/www/widgets/include/interfaces.inc"); $ifdescrs = get_configured_interface_with_descr(); +// Update once per minute by default, instead of every 10 seconds +$widgetperiod = isset($config['widgets']['period']) ? $config['widgets']['period'] * 1000 * 6 : 60000; -if ($_POST) { +if ($_POST['widgetkey']) { $validNames = array(); @@ -38,28 +40,38 @@ if ($_POST) { } if (is_array($_POST['show'])) { - $user_settings['widgets']['interfaces']['iffilter'] = implode(',', array_diff($validNames, $_POST['show'])); + $user_settings['widgets'][$_POST['widgetkey']]['iffilter'] = implode(',', array_diff($validNames, $_POST['show'])); } else { - $user_settings['widgets']['interfaces']['iffilter'] = ""; + $user_settings['widgets'][$_POST['widgetkey']]['iffilter'] = implode(',', $validNames); } save_widget_settings($_SESSION['Username'], $user_settings["widgets"], gettext("Saved Interfaces Filter via Dashboard.")); header("Location: /index.php"); } +// When this widget is included in the dashboard, $widgetkey is already defined before the widget is included. +// When the ajax call is made to refresh the interfaces table, 'widgetkey' comes in $_REQUEST. +if ($_REQUEST['widgetkey']) { + $widgetkey = $_REQUEST['widgetkey']; +} + ?> -<div class="table-responsive"> +<div class="table-responsive" id="ifaces_status_<?=$widgetkey?>"> <table class="table table-striped table-hover table-condensed"> <tbody> + <?php -$skipinterfaces = explode(",", $user_settings['widgets']['interfaces']['iffilter']); +$skipinterfaces = explode(",", $user_settings['widgets'][$widgetkey]['iffilter']); +$widgetkey_nodash = str_replace("-", "", $widgetkey); +$interface_is_displayed = false; foreach ($ifdescrs as $ifdescr => $ifname): if (in_array($ifdescr, $skipinterfaces)) { continue; } + $interface_is_displayed = true; $ifinfo = get_interface_info($ifdescr); if ($ifinfo['pppoelink'] || $ifinfo['pptplink'] || $ifinfo['l2tplink']) { /* PPP link (non-cell) - looks like a modem */ @@ -104,7 +116,7 @@ foreach ($ifdescrs as $ifdescr => $ifname): <?php endif; ?> </td> <td> - <?php if ($ifinfo['pppoelink'] == "up" || $ifinfo['pptplink'] == "up" || $ifinfo['l2tplink'] == "up"):?> + <?php if ($ifinfo['pppoelink'] == "up" || $ifinfo['pptplink'] == "up" || $ifinfo['l2tplink'] == "up"):?> <?=sprintf(gettext("Uptime: %s"), htmlspecialchars($ifinfo['ppp_uptime']));?> <?php else: ?> <?=htmlspecialchars($ifinfo['media']);?> @@ -127,16 +139,27 @@ foreach ($ifdescrs as $ifdescr => $ifname): </tr> <?php endforeach; +if (!$interface_is_displayed): +?> + <tr> + <td class="text-center"> + <?=gettext('All interfaces are hidden.');?> + </td> + </tr> + +<?php +endif; ?> </tbody> </table> </div> <!-- close the body we're wrapped in and add a configuration-panel --> -</div><div id="widget-<?=$widgetname?>_panel-footer" class="panel-footer collapse"> +</div><div id="<?=$widget_panel_footer_id?>" class="panel-footer collapse"> <form action="/widgets/widgets/interfaces.widget.php" method="post" class="form-horizontal"> - <div class="panel panel-default col-sm-10"> + <div class="panel panel-default col-sm-10"> <div class="panel-body"> + <input type="hidden" name="widgetkey" value="<?=$widgetkey; ?>"> <div class="table responsive"> <table class="table table-striped table-hover table-condensed"> <thead> @@ -147,7 +170,7 @@ endforeach; </thead> <tbody> <?php - $skipinterfaces = explode(",", $user_settings['widgets']['interfaces']['iffilter']); + $skipinterfaces = explode(",", $user_settings['widgets'][$widgetkey]['iffilter']); $idx = 0; foreach ($ifdescrs as $ifdescr => $ifname): @@ -168,20 +191,43 @@ endforeach; <div class="form-group"> <div class="col-sm-offset-3 col-sm-6"> <button type="submit" class="btn btn-primary"><i class="fa fa-save icon-embed-btn"></i><?=gettext('Save')?></button> - <button id="showallinterfaces" type="button" class="btn btn-info"><i class="fa fa-undo icon-embed-btn"></i><?=gettext('All')?></button> + <button id="<?=$widget_showallnone_id?>" type="button" class="btn btn-info"><i class="fa fa-undo icon-embed-btn"></i><?=gettext('All')?></button> </div> </div> </form> -<script> +<?php + +/* for AJAX response, we only need the panels */ +if ($_REQUEST['widgetkey']) { + exit; +} +?> + +<script type="text/javascript"> //<![CDATA[ - events.push(function(){ - $("#showallinterfaces").click(function() { - $("#widget-<?=$widgetname?>_panel-footer [id^=show]").each(function() { - $(this).prop("checked", true); - }); - }); +function getstatus_ifaces_<?=$widgetkey_nodash?>() { + $.ajax({ + type: 'get', + url: '/widgets/widgets/interfaces.widget.php', + dataType: 'html', + data: { widgetkey: "<?=$widgetkey?>" }, + dataFilter: function(raw){ + // We reload the entire widget, strip this block of javascript from it + return raw.replace(/<script>([\s\S]*)<\/script>/gi, ''); + }, + success: function(data){ + $('#ifaces_status_<?=$widgetkey?>').html(data); + }, + error: function(){ + $('#ifaces_status_<?=$widgetkey?>').html("<div class=\"alert alert-danger\"><?=gettext('Unable to retrieve status'); ?></div>"); + } + }); +} + events.push(function(){ + set_widget_checkbox_events("#<?=$widget_panel_footer_id?> [id^=show]", "<?=$widget_showallnone_id?>"); + setInterval('getstatus_ifaces_<?=$widgetkey_nodash?>()', "<?=$widgetperiod?>"); }); //]]> </script> diff --git a/src/usr/local/www/widgets/widgets/ipsec.widget.php b/src/usr/local/www/widgets/widgets/ipsec.widget.php index 766745b..62aa804 100644 --- a/src/usr/local/www/widgets/widgets/ipsec.widget.php +++ b/src/usr/local/www/widgets/widgets/ipsec.widget.php @@ -170,11 +170,13 @@ if ($_REQUEST && $_REQUEST['ajax']) { exit; } +$widgetkey_nodash = str_replace("-", "", $widgetkey); + if (isset($config['ipsec']['phase1'])) { $tab_array = array(); - $tab_array[] = array(gettext("Overview"), true, "ipsec-Overview"); - $tab_array[] = array(gettext("Tunnels"), false, "ipsec-tunnel"); - $tab_array[] = array(gettext("Mobile"), false, "ipsec-mobile"); + $tab_array[] = array(gettext("Overview"), true, $widgetkey_nodash . "-Overview"); + $tab_array[] = array(gettext("Tunnels"), false, $widgetkey_nodash . "-tunnel"); + $tab_array[] = array(gettext("Mobile"), false, $widgetkey_nodash . "-mobile"); display_widget_tabs($tab_array); } @@ -183,7 +185,7 @@ $mobile = ipsec_dump_mobile(); $widgetperiod = isset($config['widgets']['period']) ? $config['widgets']['period'] * 1000 : 10000; if (isset($config['ipsec']['phase2'])): ?> -<div id="ipsec-Overview" style="display:block;" class="table-responsive"> +<div id="<?=$widgetkey_nodash?>-Overview" style="display:block;" class="table-responsive"> <table class="table table-striped table-hover"> <thead> <tr> @@ -197,7 +199,7 @@ if (isset($config['ipsec']['phase2'])): ?> </tbody> </table> </div> -<div class="table-responsive" id="ipsec-tunnel" style="display:none;"> +<div class="table-responsive" id="<?=$widgetkey_nodash?>-tunnel" style="display:none;"> <table class="table table-striped table-hover"> <thead> <tr> @@ -214,7 +216,7 @@ if (isset($config['ipsec']['phase2'])): ?> </div> <?php if (is_array($mobile['pool'])): ?> -<div id="ipsec-mobile" style="display:none;" class="table-responsive"> +<div id="<?=$widgetkey_nodash?>-mobile" style="display:none;" class="table-responsive"> <table class="table table-striped table-hover"> <thead> <tr> @@ -288,7 +290,7 @@ function changeTabDIV(selectedDiv) { } } -function get_ipsec_stats() { +function get_ipsec_stats_<?=$widgetkey_nodash?>() { var ajaxRequest; ajaxRequest = $.ajax({ @@ -303,17 +305,17 @@ function get_ipsec_stats() { // Deal with the results of the above ajax call ajaxRequest.done(function (response, textStatus, jqXHR) { - $('tbody', '#ipsec-' + curtab).html(response); + $('tbody', '#<?=$widgetkey_nodash?>-' + curtab).html(response); // and do it again - setTimeout(get_ipsec_stats, "<?=$widgetperiod?>"); + setTimeout(get_ipsec_stats_<?=$widgetkey_nodash?>, "<?=$widgetperiod?>"); }); } events.push(function(){ // Start polling for updates some small random number of seconds from now (so that all the widgets don't // hit the server at exactly the same time) - setTimeout(get_ipsec_stats, Math.floor((Math.random() * 10000) + 1000)); + setTimeout(get_ipsec_stats_<?=$widgetkey_nodash?>, Math.floor((Math.random() * 10000) + 1000)); }); //]]> </script> diff --git a/src/usr/local/www/widgets/widgets/log.widget.php b/src/usr/local/www/widgets/widgets/log.widget.php index fb9aae6..6d759e3 100644 --- a/src/usr/local/www/widgets/widgets/log.widget.php +++ b/src/usr/local/www/widgets/widgets/log.widget.php @@ -29,11 +29,11 @@ require_once("functions.inc"); /* In an effort to reduce duplicate code, many shared functions have been moved here. */ require_once("filter_log.inc"); -if ($_POST) { +if ($_POST['widgetkey']) { if (is_numeric($_POST['filterlogentries'])) { - $user_settings['widgets']['filterlogentries'] = $_POST['filterlogentries']; + $user_settings['widgets'][$_POST['widgetkey']]['filterlogentries'] = $_POST['filterlogentries']; } else { - unset($user_settings['widgets']['filterlogentries']); + unset($user_settings['widgets'][$_POST['widgetkey']]['filterlogentries']); } $acts = array(); @@ -48,22 +48,22 @@ if ($_POST) { } if (!empty($acts)) { - $user_settings['widgets']['filterlogentriesacts'] = implode(" ", $acts); + $user_settings['widgets'][$_POST['widgetkey']]['filterlogentriesacts'] = implode(" ", $acts); } else { - unset($user_settings['widgets']['filterlogentriesacts']); + unset($user_settings['widgets'][$_POST['widgetkey']]['filterlogentriesacts']); } unset($acts); if (($_POST['filterlogentriesinterfaces']) and ($_POST['filterlogentriesinterfaces'] != "All")) { - $user_settings['widgets']['filterlogentriesinterfaces'] = trim($_POST['filterlogentriesinterfaces']); + $user_settings['widgets'][$_POST['widgetkey']]['filterlogentriesinterfaces'] = trim($_POST['filterlogentriesinterfaces']); } else { - unset($user_settings['widgets']['filterlogentriesinterfaces']); + unset($user_settings['widgets'][$_POST['widgetkey']]['filterlogentriesinterfaces']); } if (is_numeric($_POST['filterlogentriesinterval'])) { - $user_settings['widgets']['filterlogentriesinterval'] = $_POST['filterlogentriesinterval']; + $user_settings['widgets'][$_POST['widgetkey']]['filterlogentriesinterval'] = $_POST['filterlogentriesinterval']; } else { - unset($user_settings['widgets']['filterlogentriesinterval']); + unset($user_settings['widgets'][$_POST['widgetkey']]['filterlogentriesinterval']); } save_widget_settings($_SESSION['Username'], $user_settings["widgets"], gettext("Saved Filter Log Entries via Dashboard.")); @@ -71,32 +71,39 @@ if ($_POST) { exit(0); } +// When this widget is included in the dashboard, $widgetkey is already defined before the widget is included. +// When the ajax call is made to refresh the firewall log table, 'widgetkey' comes in $_REQUEST. +if ($_REQUEST['widgetkey']) { + $widgetkey = $_REQUEST['widgetkey']; +} + $iface_descr_arr = get_configured_interface_with_descr(); -$nentries = isset($user_settings['widgets']['filterlogentries']) ? $user_settings['widgets']['filterlogentries'] : 5; +$nentries = isset($user_settings['widgets'][$widgetkey]['filterlogentries']) ? $user_settings['widgets'][$widgetkey]['filterlogentries'] : 5; //set variables for log -$nentriesacts = isset($user_settings['widgets']['filterlogentriesacts']) ? $user_settings['widgets']['filterlogentriesacts'] : 'All'; -$nentriesinterfaces = isset($user_settings['widgets']['filterlogentriesinterfaces']) ? $user_settings['widgets']['filterlogentriesinterfaces'] : 'All'; +$nentriesacts = isset($user_settings['widgets'][$widgetkey]['filterlogentriesacts']) ? $user_settings['widgets'][$widgetkey]['filterlogentriesacts'] : 'All'; +$nentriesinterfaces = isset($user_settings['widgets'][$widgetkey]['filterlogentriesinterfaces']) ? $user_settings['widgets'][$widgetkey]['filterlogentriesinterfaces'] : 'All'; $filterfieldsarray = array( "act" => $nentriesacts, "interface" => isset($iface_descr_arr[$nentriesinterfaces]) ? $iface_descr_arr[$nentriesinterfaces] : $nentriesinterfaces ); -$nentriesinterval = isset($user_settings['widgets']['filterlogentriesinterval']) ? $user_settings['widgets']['filterlogentriesinterval'] : 60; +$nentriesinterval = isset($user_settings['widgets'][$widgetkey]['filterlogentriesinterval']) ? $user_settings['widgets'][$widgetkey]['filterlogentriesinterval'] : 60; $filter_logfile = "{$g['varlog_path']}/filter.log"; $filterlog = conv_log_filter($filter_logfile, $nentries, 50, $filterfieldsarray); + +$widgetkey_nodash = str_replace("-", "", $widgetkey); ?> <script type="text/javascript"> //<![CDATA[ - var logWidgetLastRefresh = <?=time()?>; + var logWidgetLastRefresh<?=$widgetkey_nodash?> = <?=time()?>; //]]> </script> - <table class="table table-striped table-hover"> <thead> <tr> @@ -177,38 +184,39 @@ if (isset($_GET['lastsawtime'])) { <script type="text/javascript"> //<![CDATA[ -function logWidgetUpdateFromServer() { +function logWidgetUpdateFromServer<?=$widgetkey_nodash?>() { $.ajax({ type: 'get', url: '/widgets/widgets/log.widget.php', - data: 'lastsawtime='+logWidgetLastRefresh, + data: { lastsawtime: logWidgetLastRefresh<?=$widgetkey_nodash?>, widgetkey: "<?=$widgetkey?>"}, dataFilter: function(raw){ // We reload the entire widget, strip this block of javascript from it return raw.replace(/<script>([\s\S]*)<\/script>/gi, ''); }, dataType: 'html', success: function(data){ - $('#widget-log .panel-body').html(data); + $('#widget-<?=$widgetkey?> .panel-body').html(data); } }); } events.push(function(){ - setInterval('logWidgetUpdateFromServer()', <?=$nentriesinterval?>*1000); + setInterval('logWidgetUpdateFromServer<?=$widgetkey_nodash?>()', <?=$nentriesinterval?>*1000); }); //]]> </script> <!-- close the body we're wrapped in and add a configuration-panel --> </div> -<div id="widget-<?=$widgetname?>_panel-footer" class="panel-footer collapse"> +<div id="<?=$widget_panel_footer_id?>" class="panel-footer collapse"> <?php -$pconfig['nentries'] = isset($user_settings['widgets']['filterlogentries']) ? $user_settings['widgets']['filterlogentries'] : ''; -$pconfig['nentriesinterval'] = isset($user_settings['widgets']['filterlogentriesinterval']) ? $user_settings['widgets']['filterlogentriesinterval'] : ''; +$pconfig['nentries'] = isset($user_settings['widgets'][$widgetkey]['filterlogentries']) ? $user_settings['widgets'][$widgetkey]['filterlogentries'] : ''; +$pconfig['nentriesinterval'] = isset($user_settings['widgets'][$widgetkey]['filterlogentriesinterval']) ? $user_settings['widgets'][$widgetkey]['filterlogentriesinterval'] : ''; ?> <form action="/widgets/widgets/log.widget.php" method="post" class="form-horizontal"> + <input type="hidden" name="widgetkey" value="<?=$widgetkey; ?>"> <div class="form-group"> <label for="filterlogentries" class="col-sm-4 control-label"><?=gettext('Number of entries')?></label> <div class="col-sm-6"> diff --git a/src/usr/local/www/widgets/widgets/ntp_status.widget.php b/src/usr/local/www/widgets/widgets/ntp_status.widget.php index efe5675..9f0e964 100644 --- a/src/usr/local/www/widgets/widgets/ntp_status.widget.php +++ b/src/usr/local/www/widgets/widgets/ntp_status.widget.php @@ -194,7 +194,7 @@ if ($_REQUEST['updateme']) { exit; } ?> - +<?php if ($widget_first_instance): ?> <script type="text/javascript"> //<![CDATA[ var d = new Date('<?=date_format(date_create(), 'c')?>'); @@ -210,11 +210,11 @@ setInterval(function() { thisMinute = thisMinute < 10 ? "0" + thisMinute : thisMinute; thisSecond = thisSecond < 10 ? "0" + thisSecond : thisSecond; - $('#ntpStatusClock').html(thisHour +':' + thisMinute + ':' + thisSecond + ' ' + tz); + $('[id="ntpStatusClock"]').html(thisHour +':' + thisMinute + ':' + thisSecond + ' ' + tz); }, 1000); //]]> </script> - +<?php endif; ?> <table id="ntpstatus" class="table table-striped table-hover"> <tbody> <tr> @@ -224,7 +224,7 @@ setInterval(function() { </tr> </tbody> </table> - +<?php if ($widget_first_instance): ?> <script type="text/javascript"> //<![CDATA[ function ntp_getstatus() { @@ -242,7 +242,7 @@ setInterval(function() { function ntpstatuscallback(transport) { // The server returns formatted html code var responseStringNtp = transport.responseText - $('#ntpstatus').prop('innerHTML',responseStringNtp); + $('[id="ntpstatus"]').prop('innerHTML',responseStringNtp); // Refresh the status at the configured interval setTimeout('ntp_getstatus()', "<?=$widgetperiod?>"); @@ -254,3 +254,4 @@ setInterval(function() { //]]> </script> +<?php endif; ?>
\ No newline at end of file diff --git a/src/usr/local/www/widgets/widgets/openvpn.widget.php b/src/usr/local/www/widgets/widgets/openvpn.widget.php index a3ad6e4..3956d62 100644 --- a/src/usr/local/www/widgets/widgets/openvpn.widget.php +++ b/src/usr/local/www/widgets/widgets/openvpn.widget.php @@ -24,6 +24,253 @@ $nocsrf = true; require_once("guiconfig.inc"); require_once("openvpn.inc"); +// Output the widget panel from this function so that it can be called from the AJAX handler as well as +// when first rendering the page +if (!function_exists('printPanel')) { + function printPanel($widgetkey) { + global $user_settings; + + $servers = openvpn_get_active_servers(); + $sk_servers = openvpn_get_active_servers("p2p"); + $clients = openvpn_get_active_clients(); + $skipovpns = explode(",", $user_settings['widgets'][$widgetkey]['filter']); + + $opstring = ""; + $got_ovpn_server = false; + + foreach ($servers as $server): + if (in_array($server['vpnid'], $skipovpns)) { + continue; + } + + $got_ovpn_server = true; + + $opstring .= "<div class=\"widget panel panel-default\">"; + $opstring .= "<div class=\"panel-heading\"><h2 class=\"panel-title\">" . htmlspecialchars($server['name']) . "</h2></div>"; + $opstring .= "<div class=\"table-responsive\">"; + $opstring .= "<table class=\"table table-striped table-hover table-condensed sortable-theme-bootstrap\" data-sortable>"; + $opstring .= "<thead>"; + $opstring .= "<tr>"; + $opstring .= "<th>" . gettext('Name/Time') . "</th>"; + $opstring .= "<th>" . gettext('Real/Virtual IP') . "</th>"; + $opstring .= "<th></th>"; + $opstring .= "</tr>"; + $opstring .= "</thead>"; + $opstring .= "<tbody>"; + + $rowIndex = 0; + foreach ($server['conns'] as $conn): + $evenRowClass = $rowIndex % 2 ? " listMReven" : " listMRodd"; + $rowIndex++; + + $opstring .= "<tr name=\"" . "r:" . $server['mgmt'] . ":" . $conn['remote_host'] . "\" class=\"" . $evenRowClass . "\">"; + $opstring .= "<td>"; + $opstring .= $conn['common_name']; + $opstring .= "</td>"; + $opstring .= "<td>"; + $opstring .= $conn['remote_host']; + $opstring .= "</td>"; + $opstring .= "<td>"; + $opstring .= "<i class=\"fa fa-times-circle\" "; + $opstring .= "onclick=\"killClient('" . $server['mgmt'] . "', '" . $conn['remote_host'] . "');\" "; + $opstring .= "style=\"cursor:pointer;\" "; + $opstring .= "name=\"" . "i:" . $server['mgmt'] . ":" . $conn['remote_host'] . "\" "; + $opstring .= "title=\"" . sprintf(gettext('Kill client connection from %s'), $conn['remote_host']) . "\">"; + $opstring .= "</i>"; + $opstring .= "</td>"; + $opstring .= "</tr>"; + $opstring .= "<tr name=\"" . "r:" . $server['mgmt'] . ":" . $conn['remote_host'] . "\" class=\"" . $evenRowClass . "\">"; + $opstring .= "<td>"; + $opstring .= $conn['connect_time']; + $opstring .= "</td>"; + $opstring .= "<td>"; + $opstring .= $conn['virtual_addr']; + if (!empty($conn['virtual_addr']) && !empty($conn['virtual_addr6'])) { + $opstring .= "<br />"; + } + $opstring .= $conn['virtual_addr6']; + $opstring .= "</td>"; + $opstring .= "<td></td>"; + $opstring .= "</tr>"; + + endforeach; + + $opstring .= "</tbody>"; + $opstring .= "</table>"; + $opstring .= "</div>"; + $opstring .= "</div>"; + + endforeach; + + print($opstring); + + $got_sk_server = false; + + if (!empty($sk_servers)): + foreach ($sk_servers as $sk_server): + if (!in_array($sk_server['vpnid'], $skipovpns)) { + $got_sk_server = true; + break; + } + endforeach; + endif; + + if ($got_sk_server): + + $opstring = ""; + $opstring .= "<div class=\"widget panel panel-default\">"; + $opstring .= "<div class=\"panel-heading\"><h2 class=\"panel-title\">" . gettext("Peer to Peer Server Instance Statistics") . "</h2></div>"; + $opstring .= "<div class=\"table-responsive\">"; + $opstring .= "<table class=\"table table-striped table-hover table-condensed sortable-theme-bootstrap\" data-sortable>"; + $opstring .= "<thead>"; + $opstring .= "<tr>"; + $opstring .= "<th>" . gettext('Name/Time') . "</th>"; + $opstring .= "<th>" . gettext('Remote/Virtual IP') . "</th>"; + $opstring .= "<th></th>"; + $opstring .= "</tr>"; + $opstring .= "</thead>"; + $opstring .= "<tbody>"; + + foreach ($sk_servers as $sk_server): + if (in_array($sk_server['vpnid'], $skipovpns)) { + continue; + } + + $opstring .= "<tr name=\"r:" . $sk_server['port'] . ":" . $sk_server['remote_host'] . "\">"; + $opstring .= "<td>"; + $opstring .= $sk_server['name']; + $opstring .= "</td>"; + $opstring .= "<td>"; + $opstring .= $sk_server['remote_host']; + $opstring .= "</td>"; + $opstring .= "<td>"; + + if ($sk_server['status'] == "up") { + /* tunnel is up */ + $opstring .= "<i class=\"fa fa-arrow-up text-success\"></i>"; + } else { + /* tunnel is down */ + $opstring .= "<i class=\"fa fa-arrow-down text-danger\"></i>"; + } + + $opstring .= "</td>"; + $opstring .= "</tr>"; + $opstring .= "<tr name=\"r:" . $sk_server['port'] . ":" . $sk_server['remote_host'] . "\">"; + $opstring .= "<td>"; + $opstring .= $sk_server['connect_time']; + $opstring .= "</td>"; + $opstring .= "<td>"; + $opstring .= $sk_server['virtual_addr']; + if (!empty($sk_server['virtual_addr']) && !empty($sk_server['virtual_addr6'])) { + $opstring .= "<br />"; + } + $opstring .= $sk_server['virtual_addr6']; + $opstring .= "</td>"; + $opstring .= "<td></td>"; + $opstring .= "</tr>"; + + endforeach; + + $opstring .= "</tbody>"; + $opstring .= "</table>"; + $opstring .= "</div>"; + $opstring .= "</div>"; + + print($opstring); + + endif; + + $got_ovpn_client = false; + + if (!empty($clients)): + foreach ($clients as $client): + if (!in_array($client['vpnid'], $skipovpns)) { + $got_ovpn_client = true; + break; + } + endforeach; + endif; + + if ($got_ovpn_client): + + $opstring = ""; + + $opstring .= "<div class=\"widget panel panel-default\">"; + $opstring .= "<div class=\"panel-heading\"><h2 class=\"panel-title\">" . gettext("Client Instance Statistics") . "</h2></div>"; + $opstring .= "<div class=\"table-responsive\">"; + $opstring .= "<table class=\"table table-striped table-hover table-condensed sortable-theme-bootstrap\" data-sortable>"; + $opstring .= "<thead>"; + $opstring .= "<tr>"; + $opstring .= "<th>" . gettext('Name/Time') . "</th>"; + $opstring .= "<th>" . gettext('Remote/Virtual IP') . "</th>"; + $opstring .= "<th></th>"; + $opstring .= "</tr>"; + $opstring .= "</thead>"; + $opstring .= "<tbody>"; + + foreach ($clients as $client): + if (in_array($client['vpnid'], $skipovpns)) { + continue; + } + + $opstring .= "<tr name=\"r:" . $client['port'] . ":" . $client['remote_host'] . "\">"; + $opstring .= "<td>"; + $opstring .= $client['name']; + $opstring .= "</td>"; + $opstring .= "<td>"; + $opstring .= $client['remote_host']; + $opstring .= "</td>"; + $opstring .= "<td>"; + + if ($client['status'] == "up") { + /* tunnel is up */ + $opstring .= "<i class=\"fa fa-arrow-up text-success\"></i>"; + } else { + /* tunnel is down */ + $opstring .= "<i class=\"fa fa-arrow-down text-danger\"></i>"; + } + + $opstring .= "</td>"; + $opstring .= "</tr>"; + $opstring .= "<tr name=\"r:" . $client['port'] . ":" . $client['remote_host'] . "\">"; + $opstring .= "<td>"; + $opstring .= $client['connect_time']; + $opstring .= "</td>"; + $opstring .= "<td>"; + $opstring .= $client['virtual_addr']; + if (!empty($client['virtual_addr']) && !empty($client['virtual_addr6'])) { + $opstring .= "<br />"; + } + $opstring .= $client['virtual_addr6']; + $opstring .= "</td>"; + $opstring .= "<td></td>"; + $opstring .= "</tr>"; + + endforeach; + + $opstring .= "</tbody>"; + $opstring .= "</table>"; + $opstring .= "</div>"; + $opstring .= "</div>"; + + print($opstring); + + endif; + + if ((empty($clients)) && (empty($servers)) && (empty($sk_servers))) { + $none_to_display_text = gettext("No OpenVPN instances defined"); + } else if (!$got_ovpn_server && !$got_sk_server && !$got_ovpn_client) { + $none_to_display_text = gettext("All OpenVPN instances are hidden"); + } else { + $none_to_display_text = ""; + } + + if (strlen($none_to_display_text) > 0) { + print('<table class="table"><tbody><td class="text-center">' . $none_to_display_text . '</td></tbody></table>'); + } + } +} + /* Handle AJAX */ if ($_GET['action']) { if ($_GET['action'] == "kill") { @@ -41,9 +288,9 @@ if ($_GET['action']) { // Compose the table contents and pass it back to the ajax caller if ($_REQUEST && $_REQUEST['ajax']) { - printPanel(); + printPanel($_REQUEST['widgetkey']); exit; -} else if ($_POST) { +} else if ($_POST['widgetkey']) { $validNames = array(); $servers = openvpn_get_active_servers(); @@ -63,320 +310,33 @@ if ($_REQUEST && $_REQUEST['ajax']) { } if (is_array($_POST['show'])) { - $user_settings['widgets']['openvpn']['filter'] = implode(',', array_diff($validNames, $_POST['show'])); + $user_settings['widgets'][$_POST['widgetkey']]['filter'] = implode(',', array_diff($validNames, $_POST['show'])); } else { - $user_settings['widgets']['openvpn']['filter'] = ""; + $user_settings['widgets'][$_POST['widgetkey']]['filter'] = implode(',', $validNames); } save_widget_settings($_SESSION['Username'], $user_settings["widgets"], gettext("Saved OpenVPN Filter via Dashboard.")); header("Location: /index.php"); } -// Output the widget panel from this function so that it can be called from the AJAX handler as well as -// when first rendering the page -function printPanel() { - global $user_settings; - - $servers = openvpn_get_active_servers(); - $sk_servers = openvpn_get_active_servers("p2p"); - $clients = openvpn_get_active_clients(); - $skipovpns = explode(",", $user_settings['widgets']['openvpn']['filter']); - - $opstring = ""; - - foreach ($servers as $server): - if (in_array($server['vpnid'], $skipovpns)) { - continue; - } - - $opstring .= "<div class=\"widget panel panel-default\">"; - $opstring .= "<div class=\"panel-heading\"><h2 class=\"panel-title\">" . htmlspecialchars($server['name']) . "</h2></div>"; - $opstring .= "<div class=\"table-responsive\">"; - $opstring .= "<table class=\"table table-striped table-hover table-condensed sortable-theme-bootstrap\" data-sortable>"; - $opstring .= "<thead>"; - $opstring .= "<tr>"; - $opstring .= "<th>" . gettext('Name/Time') . "</th>"; - $opstring .= "<th>" . gettext('Real/Virtual IP') . "</th>"; - $opstring .= "<th></th>"; - $opstring .= "</tr>"; - $opstring .= "</thead>"; - $opstring .= "<tbody>"; - - $rowIndex = 0; - foreach ($server['conns'] as $conn): - $evenRowClass = $rowIndex % 2 ? " listMReven" : " listMRodd"; - $rowIndex++; - - $opstring .= "<tr name=\"" . "r:" . $server['mgmt'] . ":" . $conn['remote_host'] . "\" class=\"" . $evenRowClass . "\">"; - $opstring .= "<td>"; - $opstring .= $conn['common_name']; - $opstring .= "</td>"; - $opstring .= "<td>"; - $opstring .= $conn['remote_host']; - $opstring .= "</td>"; - $opstring .= "<td>"; - $opstring .= "<i class=\"fa fa-times-circle\" "; - $opstring .= "onclick=\"killClient('" . $server['mgmt'] . "', '" . $conn['remote_host'] . "');\" "; - $opstring .= "style=\"cursor:pointer;\" "; - $opstring .= "name=\"" . "i:" . $server['mgmt'] . ":" . $conn['remote_host'] . "\" "; - $opstring .= "title=\"" . sprintf(gettext('Kill client connection from %s'), $conn['remote_host']) . "\">"; - $opstring .= "</i>"; - $opstring .= "</td>"; - $opstring .= "</tr>"; - $opstring .= "<tr name=\"" . "r:" . $server['mgmt'] . ":" . $conn['remote_host'] . "\" class=\"" . $evenRowClass . "\">"; - $opstring .= "<td>"; - $opstring .= $conn['connect_time']; - $opstring .= "</td>"; - $opstring .= "<td>"; - $opstring .= $conn['virtual_addr']; - if (!empty($conn['virtual_addr']) && !empty($conn['virtual_addr6'])) { - $opstring .= "<br />"; - } - $opstring .= $conn['virtual_addr6']; - $opstring .= "</td>"; - $opstring .= "<td></td>"; - $opstring .= "</tr>"; - - endforeach; - - $opstring .= "</tbody>"; - $opstring .= "</table>"; - $opstring .= "</div>"; - $opstring .= "</div>"; - - endforeach; - - print($opstring); - - $got_sk_server = false; - - if (!empty($sk_servers)): - foreach ($sk_servers as $sk_server): - if (!in_array($sk_server['vpnid'], $skipovpns)) { - $got_sk_server = true; - break; - } - endforeach; - endif; - - if ($got_sk_server): - - $opstring = ""; - $opstring .= "<div class=\"widget panel panel-default\">"; - $opstring .= "<div class=\"panel-heading\"><h2 class=\"panel-title\">" . gettext("Peer to Peer Server Instance Statistics") . "</h2></div>"; - $opstring .= "<div class=\"table-responsive\">"; - $opstring .= "<table class=\"table table-striped table-hover table-condensed sortable-theme-bootstrap\" data-sortable>"; - $opstring .= "<thead>"; - $opstring .= "<tr>"; - $opstring .= "<th>" . gettext('Name/Time') . "</th>"; - $opstring .= "<th>" . gettext('Remote/Virtual IP') . "</th>"; - $opstring .= "<th></th>"; - $opstring .= "</tr>"; - $opstring .= "</thead>"; - $opstring .= "<tbody>"; - - foreach ($sk_servers as $sk_server): - if (in_array($sk_server['vpnid'], $skipovpns)) { - continue; - } - - $opstring .= "<tr name=\"r:" . $sk_server['port'] . ":" . $sk_server['remote_host'] . "\">"; - $opstring .= "<td>"; - $opstring .= $sk_server['name']; - $opstring .= "</td>"; - $opstring .= "<td>"; - $opstring .= $sk_server['remote_host']; - $opstring .= "</td>"; - $opstring .= "<td>"; - - if ($sk_server['status'] == "up") { - /* tunnel is up */ - $opstring .= "<i class=\"fa fa-arrow-up text-success\"></i>"; - } else { - /* tunnel is down */ - $opstring .= "<i class=\"fa fa-arrow-down text-danger\"></i>"; - } - - $opstring .= "</td>"; - $opstring .= "</tr>"; - $opstring .= "<tr name=\"r:" . $sk_server['port'] . ":" . $sk_server['remote_host'] . "\">"; - $opstring .= "<td>"; - $opstring .= $sk_server['connect_time']; - $opstring .= "</td>"; - $opstring .= "<td>"; - $opstring .= $sk_server['virtual_addr']; - if (!empty($sk_server['virtual_addr']) && !empty($sk_server['virtual_addr6'])) { - $opstring .= "<br />"; - } - $opstring .= $sk_server['virtual_addr6']; - $opstring .= "</td>"; - $opstring .= "<td></td>"; - $opstring .= "</tr>"; - - endforeach; - - $opstring .= "</tbody>"; - $opstring .= "</table>"; - $opstring .= "</div>"; - $opstring .= "</div>"; - - print($opstring); - - endif; - - $got_ovpn_client = false; - - if (!empty($clients)): - foreach ($clients as $client): - if (!in_array($client['vpnid'], $skipovpns)) { - $got_ovpn_client = true; - break; - } - endforeach; - endif; - - if ($got_ovpn_client): - - $opstring = ""; - - $opstring .= "<div class=\"widget panel panel-default\">"; - $opstring .= "<div class=\"panel-heading\"><h2 class=\"panel-title\">" . gettext("Client Instance Statistics") . "</h2></div>"; - $opstring .= "<div class=\"table-responsive\">"; - $opstring .= "<table class=\"table table-striped table-hover table-condensed sortable-theme-bootstrap\" data-sortable>"; - $opstring .= "<thead>"; - $opstring .= "<tr>"; - $opstring .= "<th>" . gettext('Name/Time') . "</th>"; - $opstring .= "<th>" . gettext('Remote/Virtual IP') . "</th>"; - $opstring .= "<th></th>"; - $opstring .= "</tr>"; - $opstring .= "</thead>"; - $opstring .= "<tbody>"; - - foreach ($clients as $client): - if (in_array($client['vpnid'], $skipovpns)) { - continue; - } - - $opstring .= "<tr name=\"r:" . $client['port'] . ":" . $client['remote_host'] . "\">"; - $opstring .= "<td>"; - $opstring .= $client['name']; - $opstring .= "</td>"; - $opstring .= "<td>"; - $opstring .= $client['remote_host']; - $opstring .= "</td>"; - $opstring .= "<td>"; - - if ($client['status'] == "up") { - /* tunnel is up */ - $opstring .= "<i class=\"fa fa-arrow-up text-success\"></i>"; - } else { - /* tunnel is down */ - $opstring .= "<i class=\"fa fa-arrow-down text-danger\"></i>"; - } - - $opstring .= "</td>"; - $opstring .= "</tr>"; - $opstring .= "<tr name=\"r:" . $client['port'] . ":" . $client['remote_host'] . "\">"; - $opstring .= "<td>"; - $opstring .= $client['connect_time']; - $opstring .= "</td>"; - $opstring .= "<td>"; - $opstring .= $client['virtual_addr']; - if (!empty($client['virtual_addr']) && !empty($client['virtual_addr6'])) { - $opstring .= "<br />"; - } - $opstring .= $client['virtual_addr6']; - $opstring .= "</td>"; - $opstring .= "<td></td>"; - $opstring .= "</tr>"; - - endforeach; - - $opstring .= "</tbody>"; - $opstring .= "</table>"; - $opstring .= "</div>"; - $opstring .= "</div>"; - - print($opstring); - - endif; - - if ((empty($clients)) && (empty($servers)) && (empty($sk_servers))) { - print(gettext("No OpenVPN instances defined")); - } -} - $widgetperiod = isset($config['widgets']['period']) ? $config['widgets']['period'] * 1000 : 10000; +$widgetkey_nodash = str_replace("-", "", $widgetkey); ?> -<script type="text/javascript"> -//<![CDATA[ - function killClient(mport, remipp) { - - $.ajax( - "widgets/widgets/openvpn.widget.php" + - "?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; - } - - $('tr[name="r:' + values[1] + ":" + values[2] + '"]').each( - function(index,row) { $(row).fadeOut(1000); } - ); - } - - // Refresh the panel - function get_update() { - var ajaxRequest; - - ajaxRequest = $.ajax({ - url: "/widgets/widgets/openvpn.widget.php", - type: "post", - data: { ajax: "ajax"} - }); - - // Deal with the results of the above ajax call - ajaxRequest.done(function (response, textStatus, jqXHR) { - $('#mainpanel').html(response); - - // and do it again - setTimeout(get_update, "<?=$widgetperiod?>"); - }); - } - - events.push(function(){ - $("#showallovpns").click(function() { - $("#widget-<?=$widgetname?>_panel-footer [id^=show]").each(function() { - $(this).prop("checked", true); - }); - }); - - // Start polling for updates some small random number of seconds from now (so that all the widgets don't - // hit the server at exactly the same time) - setTimeout(get_update, Math.floor((Math.random() * 10000) + 1000)); - }); -//]]> -</script> -<div id="mainpanel" class="content"> +<div id="<?=$widgetkey?>-openvpn-mainpanel" class="content"> <?php - printPanel(); + printPanel($widgetkey); ?> </div> <!-- close the body we're wrapped in and add a configuration-panel --> -</div><div id="widget-<?=$widgetname?>_panel-footer" class="panel-footer collapse"> +</div><div id="<?=$widget_panel_footer_id?>" class="panel-footer collapse"> <form action="/widgets/widgets/openvpn.widget.php" method="post" class="form-horizontal"> <div class="panel panel-default col-sm-10"> <div class="panel-body"> + <input type="hidden" name="widgetkey" value="<?=$widgetkey; ?>"> <div class="table responsive"> <table class="table table-striped table-hover table-condensed"> <thead> @@ -390,7 +350,7 @@ $widgetperiod = isset($config['widgets']['period']) ? $config['widgets']['period $servers = openvpn_get_active_servers(); $sk_servers = openvpn_get_active_servers("p2p"); $clients = openvpn_get_active_clients(); - $skipovpns = explode(",", $user_settings['widgets']['openvpn']['filter']); + $skipovpns = explode(",", $user_settings['widgets'][$widgetkey]['filter']); foreach ($servers as $server): ?> <tr> @@ -425,7 +385,59 @@ $widgetperiod = isset($config['widgets']['period']) ? $config['widgets']['period <div class="form-group"> <div class="col-sm-offset-3 col-sm-6"> <button type="submit" class="btn btn-primary"><i class="fa fa-save icon-embed-btn"></i><?=gettext('Save')?></button> - <button id="showallovpns" type="button" class="btn btn-info"><i class="fa fa-undo icon-embed-btn"></i><?=gettext('All')?></button> + <button id="<?=$widget_showallnone_id?>" type="button" class="btn btn-info"><i class="fa fa-undo icon-embed-btn"></i><?=gettext('All')?></button> </div> </div> </form> + +<script type="text/javascript"> +//<![CDATA[ + function killClient(mport, remipp) { + + $.ajax( + "widgets/widgets/openvpn.widget.php" + + "?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; + } + + $('tr[name="r:' + values[1] + ":" + values[2] + '"]').each( + function(index,row) { $(row).fadeOut(1000); } + ); + } + + // Refresh the panel + function get_openvpn_update_<?=$widgetkey_nodash?>() { + var ajaxRequest; + + ajaxRequest = $.ajax({ + url: "/widgets/widgets/openvpn.widget.php", + type: "post", + data: { ajax: "ajax", widgetkey: "<?=$widgetkey?>"} + }); + + // Deal with the results of the above ajax call + ajaxRequest.done(function (response, textStatus, jqXHR) { + $('#<?=$widgetkey?>-openvpn-mainpanel').html(response); + + // and do it again + setTimeout(get_openvpn_update_<?=$widgetkey_nodash?>, "<?=$widgetperiod?>"); + }); + } + + events.push(function(){ + set_widget_checkbox_events("#<?=$widget_panel_footer_id?> [id^=show]", "<?=$widget_showallnone_id?>"); + + // Start polling for updates some small random number of seconds from now (so that all the widgets don't + // hit the server at exactly the same time) + setTimeout(get_openvpn_update_<?=$widgetkey_nodash?>, Math.floor((Math.random() * 10000) + 1000)); + }); +//]]> +</script> diff --git a/src/usr/local/www/widgets/widgets/picture.widget.php b/src/usr/local/www/widgets/widgets/picture.widget.php index ae02f0f..41e9497 100644 --- a/src/usr/local/www/widgets/widgets/picture.widget.php +++ b/src/usr/local/www/widgets/widgets/picture.widget.php @@ -26,19 +26,19 @@ require_once("pfsense-utils.inc"); require_once("functions.inc"); if ($_GET['getpic']=="true") { - $pic_type_s = explode(".", $user_settings['widgets']['picturewidget_filename']); + $pic_type_s = explode(".", $user_settings['widgets'][$_GET['widgetkey']]['picturewidget_filename']); $pic_type = $pic_type_s[1]; - if ($user_settings['widgets']['picturewidget']) { - $data = base64_decode($user_settings['widgets']['picturewidget']); + if ($user_settings['widgets'][$_GET['widgetkey']]['picturewidget']) { + $data = base64_decode($user_settings['widgets'][$_GET['widgetkey']]['picturewidget']); } - header("Content-Disposition: inline; filename=\"{$user_settings['widgets']['picturewidget_filename']}\""); + header("Content-Disposition: inline; filename=\"{$user_settings['widgets'][$_GET['widgetkey']]['picturewidget_filename']}\""); header("Content-Type: image/{$pic_type}"); header("Content-Length: " . strlen($data)); echo $data; exit; } -if ($_POST) { +if ($_POST['widgetkey']) { if (is_uploaded_file($_FILES['pictfile']['tmp_name'])) { /* read the file contents */ $fd_pic = fopen($_FILES['pictfile']['tmp_name'], "rb"); @@ -52,8 +52,8 @@ if ($_POST) { die("Could not read temporary file"); } else { $picname = basename($_FILES['uploadedfile']['name']); - $user_settings['widgets']['picturewidget'] = base64_encode($data); - $user_settings['widgets']['picturewidget_filename'] = $_FILES['pictfile']['name']; + $user_settings['widgets'][$_POST['widgetkey']]['picturewidget'] = base64_encode($data); + $user_settings['widgets'][$_POST['widgetkey']]['picturewidget_filename'] = $_FILES['pictfile']['name']; save_widget_settings($_SESSION['Username'], $user_settings["widgets"], gettext("Picture widget saved via Dashboard.")); header("Location: /index.php"); exit; @@ -62,14 +62,15 @@ if ($_POST) { } ?> -<a href="/widgets/widgets/picture.widget.php?getpic=true" target="_blank"> - <img style="width:100%; height:100%" src="/widgets/widgets/picture.widget.php?getpic=true" alt="picture" /> +<a href="/widgets/widgets/picture.widget.php?getpic=true&widgetkey=<?=$widgetkey?>" target="_blank"> + <img style="width:100%; height:100%" src="/widgets/widgets/picture.widget.php?getpic=true&widgetkey=<?=$widgetkey?>" alt="picture" /> </a> <!-- close the body we're wrapped in and add a configuration-panel --> -</div><div id="widget-<?=$widgetname?>_panel-footer" class="panel-footer collapse"> +</div><div id="<?=$widget_panel_footer_id?>" class="panel-footer collapse"> <form action="/widgets/widgets/picture.widget.php" method="post" enctype="multipart/form-data" class="form-inline"> + <input type="hidden" name="widgetkey" value="<?=$widgetkey; ?>"> <label for="pictfile"><?=gettext('New picture:')?> </label> <input id="pictfile" name="pictfile" type="file" class="form-control" /> <button type="submit" class="btn btn-primary btn-xs"> diff --git a/src/usr/local/www/widgets/widgets/rss.widget.php b/src/usr/local/www/widgets/widgets/rss.widget.php index 9fdd254..7d5f0a7 100644 --- a/src/usr/local/www/widgets/widgets/rss.widget.php +++ b/src/usr/local/www/widgets/widgets/rss.widget.php @@ -25,36 +25,38 @@ require_once("guiconfig.inc"); require_once("pfsense-utils.inc"); require_once("functions.inc"); -if ($_POST['rssfeed']) { - $user_settings['widgets']['rssfeed'] = str_replace("\n", ",", htmlspecialchars($_POST['rssfeed'], ENT_QUOTES | ENT_HTML401)); - $user_settings['widgets']['rssmaxitems'] = str_replace("\n", ",", htmlspecialchars($_POST['rssmaxitems'], ENT_QUOTES | ENT_HTML401)); - $user_settings['widgets']['rsswidgetheight'] = htmlspecialchars($_POST['rsswidgetheight'], ENT_QUOTES | ENT_HTML401); - $user_settings['widgets']['rsswidgettextlength'] = htmlspecialchars($_POST['rsswidgettextlength'], ENT_QUOTES | ENT_HTML401); +if ($_POST['widgetkey']) { + $user_settings['widgets'][$_POST['widgetkey']]['rssfeed'] = str_replace("\n", ",", htmlspecialchars($_POST['rssfeed'], ENT_QUOTES | ENT_HTML401)); + $user_settings['widgets'][$_POST['widgetkey']]['rssmaxitems'] = str_replace("\n", ",", htmlspecialchars($_POST['rssmaxitems'], ENT_QUOTES | ENT_HTML401)); + $user_settings['widgets'][$_POST['widgetkey']]['rsswidgetheight'] = htmlspecialchars($_POST['rsswidgetheight'], ENT_QUOTES | ENT_HTML401); + $user_settings['widgets'][$_POST['widgetkey']]['rsswidgettextlength'] = htmlspecialchars($_POST['rsswidgettextlength'], ENT_QUOTES | ENT_HTML401); save_widget_settings($_SESSION['Username'], $user_settings["widgets"], gettext("Saved RSS Widget feed via Dashboard.")); header("Location: /"); } // Use saved feed and max items -if ($user_settings['widgets']['rssfeed']) { - $rss_feed_s = explode(",", $user_settings['widgets']['rssfeed']); +if ($user_settings['widgets'][$widgetkey]['rssfeed']) { + $rss_feed_s = explode(",", $user_settings['widgets'][$widgetkey]['rssfeed']); } -if ($user_settings['widgets']['rssmaxitems']) { - $max_items = $user_settings['widgets']['rssmaxitems']; +if ($user_settings['widgets'][$widgetkey]['rssmaxitems']) { + $max_items = $user_settings['widgets'][$widgetkey]['rssmaxitems']; } -if (is_numeric($user_settings['widgets']['rsswidgetheight'])) { - $rsswidgetheight = $user_settings['widgets']['rsswidgetheight']; +if (is_numeric($user_settings['widgets'][$widgetkey]['rsswidgetheight'])) { + $rsswidgetheight = $user_settings['widgets'][$widgetkey]['rsswidgetheight']; } -if (is_numeric($user_settings['widgets']['rsswidgettextlength'])) { - $rsswidgettextlength = $user_settings['widgets']['rsswidgettextlength']; +if (is_numeric($user_settings['widgets'][$widgetkey]['rsswidgettextlength'])) { + $rsswidgettextlength = $user_settings['widgets'][$widgetkey]['rsswidgettextlength']; } // Set a default feed if none exists if (!$rss_feed_s) { $rss_feed_s = "https://www.netgate.com/blog/"; - $user_settings['widgets']['rssfeed'] = "https://www.netgate.com/blog/"; + if ($widgetkey != "") { + $user_settings['widgets'][$widgetkey]['rssfeed'] = $rss_feed_s; + } } if (!$max_items || !is_numeric($max_items)) { @@ -69,8 +71,8 @@ if (!$rsswidgettextlength || !is_numeric($rsswidgettextlength)) { $rsswidgettextlength = 140; // oh twitter, how do we love thee? } -if ($user_settings['widgets']['rssfeed']) { - $textarea_txt = str_replace(",", "\n", $user_settings['widgets']['rssfeed']); +if ($user_settings['widgets'][$widgetkey]['rssfeed']) { + $textarea_txt = str_replace(",", "\n", $user_settings['widgets'][$widgetkey]['rssfeed']); } else { $textarea_txt = ""; } @@ -85,11 +87,13 @@ if ($user_settings['widgets']['rssfeed']) { exec("chmod a+rw /tmp/simplepie/."); exec("chmod a+rw /tmp/simplepie/cache/."); require_once("simplepie/simplepie.inc"); - function textLimit($string, $length, $replacer = '...') { - if (strlen($string) > $length) { - return (preg_match('/^(.*)\W.*$/', substr($string, 0, $length+1), $matches) ? $matches[1] : substr($string, 0, $length)) . $replacer; + if (!function_exists('textLimit')) { + function textLimit($string, $length, $replacer = '...') { + if (strlen($string) > $length) { + return (preg_match('/^(.*)\W.*$/', substr($string, 0, $length+1), $matches) ? $matches[1] : substr($string, 0, $length)) . $replacer; + } + return $string; } - return $string; } $feed = new SimplePie(); $feed->set_cache_location("/tmp/simplepie/"); @@ -120,9 +124,10 @@ if ($user_settings['widgets']['rssfeed']) { </div> <!-- close the body we're wrapped in and add a configuration-panel --> -</div><div id="widget-<?=$widgetname?>_panel-footer" class="panel-footer collapse"> +</div><div id="<?=$widget_panel_footer_id?>" class="panel-footer collapse"> <form action="/widgets/widgets/rss.widget.php" method="post" class="form-horizontal"> + <input type="hidden" name="widgetkey" value="<?=$widgetkey; ?>"> <div class="form-group"> <label for="rssfeed" class="col-sm-3 control-label"><?=gettext('Feeds')?></label> <div class="col-sm-6"> diff --git a/src/usr/local/www/widgets/widgets/services_status.widget.php b/src/usr/local/www/widgets/widgets/services_status.widget.php index 4672b2e..62cfcf1 100644 --- a/src/usr/local/www/widgets/widgets/services_status.widget.php +++ b/src/usr/local/www/widgets/widgets/services_status.widget.php @@ -48,7 +48,7 @@ for ($idx=1; $idx < $numsvcs; $idx++) { } } -if ($_POST) { +if ($_POST['widgetkey']) { $validNames = array(); @@ -57,9 +57,9 @@ if ($_POST) { } if (is_array($_POST['show'])) { - $user_settings['widgets']['servicestatusfilter'] = implode(',', array_diff($validNames, $_POST['show'])); + $user_settings['widgets'][$_POST['widgetkey']]['filter'] = implode(',', array_diff($validNames, $_POST['show'])); } else { - $user_settings['widgets']['servicestatusfilter'] = ""; + $user_settings['widgets'][$_POST['widgetkey']]['filter'] = implode(',', $validNames); } save_widget_settings($_SESSION['Username'], $user_settings["widgets"], gettext("Saved Service Status Filter via Dashboard.")); @@ -79,16 +79,19 @@ if ($_POST) { </thead> <tbody> <?php -$skipservices = explode(",", $user_settings['widgets']['servicestatusfilter']); +$skipservices = explode(",", $user_settings['widgets'][$widgetkey]['filter']); if (count($services) > 0) { uasort($services, "service_dispname_compare"); + $service_is_displayed = false; foreach ($services as $service) { if ((!$service['dispname']) || (in_array($service['dispname'], $skipservices)) || (!is_service_enabled($service['dispname']))) { continue; } + $service_is_displayed = true; + if (empty($service['description'])) { $service['description'] = get_pkg_descr($service['name']); } @@ -103,19 +106,24 @@ if (count($services) > 0) { </tr> <?php } + + if (!$service_is_displayed) { + echo "<tr><td colspan=\"4\" class=\"text-center\">" . gettext("All services are hidden") . ". </td></tr>\n"; + } } else { - echo "<tr><td colspan=\"3\" class=\"text-center\">" . gettext("No services found") . ". </td></tr>\n"; + echo "<tr><td colspan=\"4\" class=\"text-center\">" . gettext("No services found") . ". </td></tr>\n"; } ?> </tbody> </table> </div> <!-- close the body we're wrapped in and add a configuration-panel --> -</div><div id="widget-<?=$widgetname?>_panel-footer" class="panel-footer collapse"> +</div><div id="<?=$widget_panel_footer_id?>" class="panel-footer collapse"> <form action="/widgets/widgets/services_status.widget.php" method="post" class="form-horizontal"> <div class="panel panel-default col-sm-10"> <div class="panel-body"> + <input type="hidden" name="widgetkey" value="<?=$widgetkey; ?>"> <div class="table responsive"> <table class="table table-striped table-hover table-condensed"> <thead> @@ -126,7 +134,7 @@ if (count($services) > 0) { </thead> <tbody> <?php - $skipservices = explode(",", $user_settings['widgets']['servicestatusfilter']); + $skipservices = explode(",", $user_settings['widgets'][$widgetkey]['filter']); $idx = 0; foreach ($services as $service): @@ -149,7 +157,7 @@ if (count($services) > 0) { <div class="form-group"> <div class="col-sm-offset-3 col-sm-6"> <button type="submit" class="btn btn-primary"><i class="fa fa-save icon-embed-btn"></i><?=gettext('Save')?></button> - <button id="showallservices" type="button" class="btn btn-info"><i class="fa fa-undo icon-embed-btn"></i><?=gettext('All')?></button> + <button id="<?=$widget_showallnone_id?>" type="button" class="btn btn-info"><i class="fa fa-undo icon-embed-btn"></i><?=gettext('All')?></button> </div> </div> </form> @@ -157,12 +165,7 @@ if (count($services) > 0) { <script type="text/javascript"> //<![CDATA[ events.push(function(){ - $("#showallservices").click(function() { - $("#widget-<?=$widgetname?>_panel-footer [id^=show]").each(function() { - $(this).prop("checked", true); - }); - }); - + set_widget_checkbox_events("#<?=$widget_panel_footer_id?> [id^=show]", "<?=$widget_showallnone_id?>"); }); //]]> </script> diff --git a/src/usr/local/www/widgets/widgets/smart_status.widget.php b/src/usr/local/www/widgets/widgets/smart_status.widget.php index eae61c7..eec84b5 100644 --- a/src/usr/local/www/widgets/widgets/smart_status.widget.php +++ b/src/usr/local/www/widgets/widgets/smart_status.widget.php @@ -36,7 +36,7 @@ if ($specplatform['name'] != "Hyper-V") { $devs = get_smart_drive_list(); } -if ($_POST) { +if ($_POST['widgetkey']) { $validNames = array(); @@ -45,9 +45,9 @@ if ($_POST) { } if (is_array($_POST['show'])) { - $user_settings['widgets']['smart_status']['filter'] = implode(',', array_diff($validNames, $_POST['show'])); + $user_settings['widgets'][$_POST['widgetkey']]['filter'] = implode(',', array_diff($validNames, $_POST['show'])); } else { - $user_settings['widgets']['smart_status']['filter'] = ""; + $user_settings['widgets'][$_POST['widgetkey']]['filter'] = implode(',', $validNames); } save_widget_settings($_SESSION['Username'], $user_settings["widgets"], gettext("Saved SMART Status Filter via Dashboard.")); @@ -68,7 +68,8 @@ if ($_POST) { </thead> <tbody> <?php -$skipsmart = explode(",", $user_settings['widgets']['smart_status']['filter']); +$skipsmart = explode(",", $user_settings['widgets'][$widgetkey]['filter']); +$smartdrive_is_displayed = false; if (count($devs) > 0) { foreach ($devs as $dev) { ## for each found drive do @@ -76,6 +77,7 @@ if (count($devs) > 0) { continue; } + $smartdrive_is_displayed = true; $dev_ident = exec("diskinfo -v /dev/$dev | grep ident | awk '{print $1}'"); ## get identifier from drive $dev_state = trim(exec("smartctl -H /dev/$dev | awk -F: '/^SMART overall-health self-assessment test result/ {print $2;exit} /^SMART Health Status/ {print $2;exit}'")); ## get SMART state from drive @@ -104,17 +106,28 @@ if (count($devs) > 0) { </tr> <?php } + + if (!$smartdrive_is_displayed) { +?> + <tr> + <td colspan="4" class="text-center"> + <?=gettext('All SMART drives are hidden.');?> + </td> + </tr> +<?php + } } ?> </tbody> </table> </div> <!-- close the body we're wrapped in and add a configuration-panel --> -</div><div id="widget-<?=$widgetname?>_panel-footer" class="panel-footer collapse"> +</div><div id="<?=$widget_panel_footer_id?>" class="panel-footer collapse"> <form action="/widgets/widgets/smart_status.widget.php" method="post" class="form-horizontal"> <div class="panel panel-default col-sm-10"> <div class="panel-body"> + <input type="hidden" name="widgetkey" value="<?=$widgetkey; ?>"> <div class="table responsive"> <table class="table table-striped table-hover table-condensed"> <thead> @@ -143,19 +156,14 @@ if (count($devs) > 0) { <div class="form-group"> <div class="col-sm-offset-3 col-sm-6"> <button type="submit" class="btn btn-primary"><i class="fa fa-save icon-embed-btn"></i><?=gettext('Save')?></button> - <button id="showallsmartdrives" type="button" class="btn btn-info"><i class="fa fa-undo icon-embed-btn"></i><?=gettext('All')?></button> + <button id="<?=$widget_showallnone_id?>" type="button" class="btn btn-info"><i class="fa fa-undo icon-embed-btn"></i><?=gettext('All')?></button> </div> </div> </form> <script type="text/javascript"> //<![CDATA[ events.push(function(){ - $("#showallsmartdrives").click(function() { - $("#widget-<?=$widgetname?>_panel-footer [id^=show]").each(function() { - $(this).prop("checked", true); - }); - }); - + set_widget_checkbox_events("#<?=$widget_panel_footer_id?> [id^=show]", "<?=$widget_showallnone_id?>"); }); //]]> </script> diff --git a/src/usr/local/www/widgets/widgets/system_information.widget.php b/src/usr/local/www/widgets/widgets/system_information.widget.php index e55d611..789cef9 100644 --- a/src/usr/local/www/widgets/widgets/system_information.widget.php +++ b/src/usr/local/www/widgets/widgets/system_information.widget.php @@ -33,6 +33,7 @@ include_once("includes/functions.inc.php"); $sysinfo_items = array( 'name' => gettext('Name'), 'system' => gettext('System'), + 'bios' => gettext('BIOS'), 'version' => gettext('Version'), 'cpu_type' => gettext('CPU Type'), 'hwcrypto' => gettext('Hardware Crypto'), @@ -96,7 +97,7 @@ if ($_REQUEST['getupdatestatus']) { } exit; -} elseif ($_POST) { +} elseif ($_POST['widgetkey']) { $validNames = array(); @@ -105,9 +106,9 @@ if ($_REQUEST['getupdatestatus']) { } if (is_array($_POST['show'])) { - $user_settings['widgets']['system_information']['filter'] = implode(',', array_diff($validNames, $_POST['show'])); + $user_settings['widgets'][$_POST['widgetkey']]['filter'] = implode(',', array_diff($validNames, $_POST['show'])); } else { - $user_settings['widgets']['system_information']['filter'] = ""; + $user_settings['widgets'][$_POST['widgetkey']]['filter'] = implode(',', $validNames); } save_widget_settings($_SESSION['Username'], $user_settings["widgets"], gettext("Saved System Information Widget Filter via Dashboard.")); @@ -122,7 +123,8 @@ $widgetperiod += 1000; $filesystems = get_mounted_filesystems(); -$skipsysinfoitems = explode(",", $user_settings['widgets']['system_information']['filter']); +$skipsysinfoitems = explode(",", $user_settings['widgets'][$widgetkey]['filter']); +$rows_displayed = false; ?> <div class="table-responsive"> @@ -130,6 +132,7 @@ $skipsysinfoitems = explode(",", $user_settings['widgets']['system_information'] <tbody> <?php if (!in_array('name', $skipsysinfoitems)): + $rows_displayed = true; ?> <tr> <th><?=gettext("Name");?></th> @@ -138,6 +141,7 @@ $skipsysinfoitems = explode(",", $user_settings['widgets']['system_information'] <?php endif; if (!in_array('system', $skipsysinfoitems)): + $rows_displayed = true; ?> <tr> <th><?=gettext("System");?></th> @@ -156,7 +160,36 @@ $skipsysinfoitems = explode(",", $user_settings['widgets']['system_information'] </tr> <?php endif; + if (!in_array('bios', $skipsysinfoitems)): + $rows_displayed = true; + unset($biosvendor); + unset($biosversion); + unset($biosdate); + $_gb = exec('/bin/kenv -q smbios.bios.vendor 2>/dev/null', $biosvendor); + $_gb = exec('/bin/kenv -q smbios.bios.version 2>/dev/null', $biosversion); + $_gb = exec('/bin/kenv -q smbios.bios.reldate 2>/dev/null', $biosdate); + /* Only display BIOS information if there is any to show. */ + if (!empty($biosvendor[0]) || !empty($biosversion[0]) || !empty($biosdate[0])): +?> + <tr> + <th><?=gettext("BIOS");?></th> + <td> + <?php if (!empty($biosvendor[0])): ?> + <?=gettext("Vendor: ");?><strong><?=$biosvendor[0];?></strong><br/> + <?php endif; ?> + <?php if (!empty($biosversion[0])): ?> + <?=gettext("Version: ");?><strong><?=$biosversion[0];?></strong><br/> + <?php endif; ?> + <?php if (!empty($biosdate[0])): ?> + <?=gettext("Release Date: ");?><strong><?=$biosdate[0];?></strong><br/> + <?php endif; ?> + </td> + </tr> +<?php + endif; + endif; if (!in_array('version', $skipsysinfoitems)): + $rows_displayed = true; ?> <tr> <th><?=gettext("Version");?></th> @@ -178,6 +211,7 @@ $skipsysinfoitems = explode(",", $user_settings['widgets']['system_information'] <?php endif; if (!in_array('cpu_type', $skipsysinfoitems)): + $rows_displayed = true; ?> <tr> <th><?=gettext("CPU Type");?></th> @@ -195,6 +229,7 @@ $skipsysinfoitems = explode(",", $user_settings['widgets']['system_information'] <?php endif; if (!in_array('hwcrypto', $skipsysinfoitems)): + $rows_displayed = true; ?> <?php if ($hwcrypto): ?> <tr> @@ -205,6 +240,7 @@ $skipsysinfoitems = explode(",", $user_settings['widgets']['system_information'] <?php endif; if (!in_array('uptime', $skipsysinfoitems)): + $rows_displayed = true; ?> <tr> <th><?=gettext("Uptime");?></th> @@ -213,6 +249,7 @@ $skipsysinfoitems = explode(",", $user_settings['widgets']['system_information'] <?php endif; if (!in_array('current_datetime', $skipsysinfoitems)): + $rows_displayed = true; ?> <tr> <th><?=gettext("Current date/time");?></th> @@ -221,6 +258,7 @@ $skipsysinfoitems = explode(",", $user_settings['widgets']['system_information'] <?php endif; if (!in_array('dns_servers', $skipsysinfoitems)): + $rows_displayed = true; ?> <tr> <th><?=gettext("DNS server(s)");?></th> @@ -238,6 +276,7 @@ $skipsysinfoitems = explode(",", $user_settings['widgets']['system_information'] <?php endif; if (!in_array('last_config_change', $skipsysinfoitems)): + $rows_displayed = true; ?> <?php if ($config['revision']): ?> <tr> @@ -248,6 +287,7 @@ $skipsysinfoitems = explode(",", $user_settings['widgets']['system_information'] <?php endif; if (!in_array('state_table_size', $skipsysinfoitems)): + $rows_displayed = true; ?> <tr> <th><?=gettext("State table size");?></th> @@ -266,6 +306,7 @@ $skipsysinfoitems = explode(",", $user_settings['widgets']['system_information'] <?php endif; if (!in_array('mbuf_usage', $skipsysinfoitems)): + $rows_displayed = true; ?> <tr> <th><?=gettext("MBUF Usage");?></th> @@ -284,6 +325,7 @@ $skipsysinfoitems = explode(",", $user_settings['widgets']['system_information'] <?php endif; if (!in_array('temperature', $skipsysinfoitems)): + $rows_displayed = true; ?> <?php if (get_temp() != ""): ?> <tr> @@ -301,6 +343,7 @@ $skipsysinfoitems = explode(",", $user_settings['widgets']['system_information'] <?php endif; if (!in_array('load_average', $skipsysinfoitems)): + $rows_displayed = true; ?> <tr> <th><?=gettext("Load average");?></th> @@ -311,6 +354,7 @@ $skipsysinfoitems = explode(",", $user_settings['widgets']['system_information'] <?php endif; if (!in_array('cpu_usage', $skipsysinfoitems)): + $rows_displayed = true; ?> <tr> <th><?=gettext("CPU usage");?></th> @@ -326,6 +370,7 @@ $skipsysinfoitems = explode(",", $user_settings['widgets']['system_information'] <?php endif; if (!in_array('memory_usage', $skipsysinfoitems)): + $rows_displayed = true; ?> <tr> <th><?=gettext("Memory usage");?></th> @@ -342,6 +387,7 @@ $skipsysinfoitems = explode(",", $user_settings['widgets']['system_information'] <?php endif; if (!in_array('swap_usage', $skipsysinfoitems)): + $rows_displayed = true; ?> <?php if ($showswap == true): ?> <tr> @@ -360,6 +406,7 @@ $skipsysinfoitems = explode(",", $user_settings['widgets']['system_information'] <?php endif; if (!in_array('disk_usage', $skipsysinfoitems)): + $rows_displayed = true; $diskidx = 0; foreach ($filesystems as $fs): ?> @@ -377,17 +424,27 @@ $skipsysinfoitems = explode(",", $user_settings['widgets']['system_information'] $diskidx++; endforeach; endif; + if (!$rows_displayed): +?> + <tr> + <td class="text-center"> + <?=gettext('All System Information items are hidden.');?> + </td> + </tr> +<?php + endif; ?> </tbody> </table> </div> <!-- close the body we're wrapped in and add a configuration-panel --> -</div><div id="widget-<?=$widgetname?>_panel-footer" class="panel-footer collapse"> +</div><div id="<?=$widget_panel_footer_id?>" class="panel-footer collapse"> <form action="/widgets/widgets/system_information.widget.php" method="post" class="form-horizontal"> <div class="panel panel-default col-sm-10"> <div class="panel-body"> + <input type="hidden" name="widgetkey" value="<?=$widgetkey; ?>"> <div class="table responsive"> <table class="table table-striped table-hover table-condensed"> <thead> @@ -416,13 +473,14 @@ $skipsysinfoitems = explode(",", $user_settings['widgets']['system_information'] <div class="form-group"> <div class="col-sm-offset-3 col-sm-6"> <button type="submit" class="btn btn-primary"><i class="fa fa-save icon-embed-btn"></i><?=gettext('Save')?></button> - <button id="showallsysinfoitems" type="button" class="btn btn-info"><i class="fa fa-undo icon-embed-btn"></i><?=gettext('All')?></button> + <button id="<?=$widget_showallnone_id?>" type="button" class="btn btn-info"><i class="fa fa-undo icon-embed-btn"></i><?=gettext('All')?></button> </div> </div> </form> <script type="text/javascript"> //<![CDATA[ +<?php if ($widget_first_instance): ?> <?php if (!isset($config['system']['firmware']['disablecheck'])): ?> function systemStatusGetUpdateStatus() { $.ajax({ @@ -435,7 +493,7 @@ function systemStatusGetUpdateStatus() { }, dataType: 'html', success: function(data){ - $('#widget-system_information #updatestatus').html(data); + $('[id^=widget-system_information] #updatestatus').html(data); } }); } @@ -459,18 +517,10 @@ function updateMeters() { } -events.push(function(){ - $("#showallsysinfoitems").click(function() { - $("#widget-<?=$widgetname?>_panel-footer [id^=show]").each(function() { - $(this).prop("checked", true); - }); - }); -}); - var update_interval = "<?=$widgetperiod?>"; function setProgress(barName, percent) { - $('#' + barName).css('width', percent + '%').attr('aria-valuenow', percent); + $('[id="' + barName + '"]').css('width', percent + '%').attr('aria-valuenow', percent); } function setTimer() { @@ -503,7 +553,7 @@ function stats(x) { function updateMemory(x) { if ($('#memusagemeter')) { - $("#memusagemeter").html(x); + $('[id="memusagemeter"]').html(x); } if ($('#memUsagePB')) { setProgress('memUsagePB', parseInt(x)); @@ -512,13 +562,13 @@ function updateMemory(x) { function updateMbuf(x) { if ($('#mbuf')) { - $("#mbuf").html('(' + x + ')'); + $('[id="mbuf"]').html('(' + x + ')'); } } function updateMbufMeter(x) { if ($('#mbufusagemeter')) { - $("#mbufusagemeter").html(x + '%'); + $('[id="mbufusagemeter"]').html(x + '%'); } if ($('#mbufPB')) { setProgress('mbufPB', parseInt(x)); @@ -528,7 +578,7 @@ function updateMbufMeter(x) { function updateCPU(x) { if ($('#cpumeter')) { - $("#cpumeter").html(x + '%'); + $('[id="cpumeter"]').html(x + '%'); } if ($('#cpuPB')) { setProgress('cpuPB', parseInt(x)); @@ -542,7 +592,7 @@ function updateCPU(x) { function updateTemp(x) { if ($("#tempmeter")) { - $("#tempmeter").html(x + '°' + 'C'); + $('[id="tempmeter"]').html(x + '°' + 'C'); } if ($('#tempPB')) { setProgress('tempPB', parseInt(x)); @@ -551,25 +601,25 @@ function updateTemp(x) { function updateDateTime(x) { if ($('#datetime')) { - $("#datetime").html(x); + $('[id="datetime"]').html(x); } } function updateUptime(x) { if ($('#uptime')) { - $("#uptime").html(x); + $('[id="uptime"]').html(x); } } function updateState(x) { if ($('#pfstate')) { - $("#pfstate").html('(' + x + ')'); + $('[id="pfstate"]').html('(' + x + ')'); } } function updateStateMeter(x) { if ($('#pfstateusagemeter')) { - $("#pfstateusagemeter").html(x + '%'); + $('[id="pfstateusagemeter"]').html(x + '%'); } if ($('#statePB')) { setProgress('statePB', parseInt(x)); @@ -578,13 +628,13 @@ function updateStateMeter(x) { function updateCpuFreq(x) { if ($('#cpufreq')) { - $("#cpufreq").html(x); + $('[id="cpufreq"]').html(x); } } function updateLoadAverage(x) { if ($('#load_average')) { - $("#load_average").html(x); + $('[id="load_average"]').html(x); } } @@ -594,7 +644,7 @@ function updateInterfaceStats(x) { var counter = 1; for (var y=0; y<statistics_split.length-1; y++) { if ($('#stat' + counter)) { - $('#stat' + counter).html(statistics_split[y]); + $('[id="stat' + counter + '"]').html(statistics_split[y]); counter++; } } @@ -613,25 +663,25 @@ function updateInterfaces(x) { } switch (details[1]) { case "up": - $('#' + details[0] + '-up').css("display","inline"); - $('#' + details[0] + '-down').css("display","none"); - $('#' + details[0] + '-block').css("display","none"); - $('#' + details[0] + '-ip').html(ipv4_details); - $('#' + details[0] + '-ipv6').html(details[3]); - $('#' + details[0] + '-media').html(details[4]); + $('[id="' + details[0] + '-up"]').css("display","inline"); + $('[id="' + details[0] + '-down"]').css("display","none"); + $('[id="' + details[0] + '-block"]').css("display","none"); + $('[id="' + details[0] + '-ip"]').html(ipv4_details); + $('[id="' + details[0] + '-ipv6"]').html(details[3]); + $('[id="' + details[0] + '-media"]').html(details[4]); break; case "down": - $('#' + details[0] + '-down').css("display","inline"); - $('#' + details[0] + '-up').css("display","none"); - $('#' + details[0] + '-block').css("display","none"); - $('#' + details[0] + '-ip').html(ipv4_details); - $('#' + details[0] + '-ipv6').html(details[3]); - $('#' + details[0] + '-media').html(details[4]); + $('[id="' + details[0] + '-down"]').css("display","inline"); + $('[id="' + details[0] + '-up"]').css("display","none"); + $('[id="' + details[0] + '-block"]').css("display","none"); + $('[id="' + details[0] + '-ip"]').html(ipv4_details); + $('[id="' + details[0] + '-ipv6"]').html(details[3]); + $('[id="' + details[0] + '-media"]').html(details[4]); break; case "block": - $('#' + details[0] + '-block').css("display","inline"); - $('#' + details[0] + '-down').css("display","none"); - $('#' + details[0] + '-up').css("display","none"); + $('[id="' + details[0] + '-block"]').css("display","inline"); + $('[id="' + details[0] + '-down"]').css("display","none"); + $('[id="' + details[0] + '-up"]').css("display","none"); break; } }); @@ -651,5 +701,9 @@ function widgetActive(x) { events.push(function(){ setTimer(); }); +<?php endif; // $widget_first_instance ?> +events.push(function(){ + set_widget_checkbox_events("#<?=$widget_panel_footer_id?> [id^=show]", "<?=$widget_showallnone_id?>"); +}); //]]> </script> diff --git a/src/usr/local/www/widgets/widgets/thermal_sensors.widget.php b/src/usr/local/www/widgets/widgets/thermal_sensors.widget.php index e776e4e..2630993 100644 --- a/src/usr/local/www/widgets/widgets/thermal_sensors.widget.php +++ b/src/usr/local/www/widgets/widgets/thermal_sensors.widget.php @@ -33,7 +33,6 @@ if (isset($_GET["getThermalSensorsData"])) { const WIDGETS_CONFIG_SECTION_KEY = "widgets"; -const THERMAL_SENSORS_WIDGET_SUBSECTION_KEY = "thermal_sensors_widget"; //default constants const DEFAULT_WARNING_THRESHOLD = 60; //60 C @@ -41,10 +40,71 @@ const DEFAULT_CRITICAL_THRESHOLD = 70; //70 C const MIN_THRESHOLD_VALUE = 1; //deg C const MAX_THRESHOLD_VALUE = 100; //deg C +if (!function_exists('saveThresholdSettings')) { + function saveThresholdSettings(&$configArray, &$postArray, $warningValueKey, $criticalValueKey) { + $warningValue = 0; + $criticalValue = 0; + + if (isset($postArray[$warningValueKey]) && is_numeric($postArray[$warningValueKey])) { + $warningValue = (int) $postArray[$warningValueKey]; + } + + if (isset($postArray[$criticalValueKey]) && is_numeric($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][$postArray['widgetkey']][$warningValueKey] = $warningValue; + $configArray[WIDGETS_CONFIG_SECTION_KEY][$postArray['widgetkey']][$criticalValueKey] = $criticalValue; + } + } +} + +if (!function_exists('saveGraphDisplaySettings')) { + function saveGraphDisplaySettings(&$configArray, &$postArray, $valueKey) { + $configArray[WIDGETS_CONFIG_SECTION_KEY][$postArray['widgetkey']][$valueKey] = isset($postArray[$valueKey]) ? 1 : 0; + } +} + +if (!function_exists('getThresholdValueFromConfig')) { + function getThresholdValueFromConfig(&$configArray, $valueKey, $defaultValue, $widgetKey) { + + $thresholdValue = $defaultValue; + + if (isset($configArray[WIDGETS_CONFIG_SECTION_KEY][$widgetKey][$valueKey])) { + $thresholdValue = (int) $configArray[WIDGETS_CONFIG_SECTION_KEY][$widgetKey][$valueKey]; + } + + if ($thresholdValue < MIN_THRESHOLD_VALUE || $thresholdValue > MAX_THRESHOLD_VALUE) { + //set to default if not in allowed range + $thresholdValue = $defaultValue; + } + return $thresholdValue; + } +} + +if (!function_exists('getBoolValueFromConfig')) { + function getBoolValueFromConfig(&$configArray, $valueKey, $defaultValue, $widgetKey) { + + $boolValue = false; + + if (isset($configArray[WIDGETS_CONFIG_SECTION_KEY][$widgetKey][$valueKey])) { + $boolValue = (bool) $configArray[WIDGETS_CONFIG_SECTION_KEY][$widgetKey][$valueKey]; + } else { + //set to default if not in allowed range + $boolValue = $defaultValue; + } + return $boolValue; + } +} + //NOTE: keys used in $_POST and $config and $user_settings should match text and checkbox inputs' IDs/names in HTML code section //========================================================================= //save widget config settings on POST -if ($_POST) { +if ($_POST['widgetkey']) { saveThresholdSettings($user_settings, $_POST, "thermal_sensors_widget_zone_warning_threshold", "thermal_sensors_widget_zone_critical_threshold"); saveThresholdSettings($user_settings, $_POST, "thermal_sensors_widget_core_warning_threshold", "thermal_sensors_widget_core_critical_threshold"); @@ -59,106 +119,55 @@ if ($_POST) { header("Location: ../../index.php"); } -function saveThresholdSettings(&$configArray, &$postArray, $warningValueKey, $criticalValueKey) { - $warningValue = 0; - $criticalValue = 0; - - if (isset($postArray[$warningValueKey]) && is_numeric($postArray[$warningValueKey])) { - $warningValue = (int) $postArray[$warningValueKey]; - } - - if (isset($postArray[$criticalValueKey]) && is_numeric($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; - } -} - -function saveGraphDisplaySettings(&$configArray, &$postArray, $valueKey) { - $configArray[WIDGETS_CONFIG_SECTION_KEY][THERMAL_SENSORS_WIDGET_SUBSECTION_KEY][$valueKey] = isset($postArray[$valueKey]) ? 1 : 0; -} +$widgetkey_nodash = str_replace("-", "", $widgetkey); //========================================================================= //get Threshold settings from config (apply defaults if missing) -$thermal_sensors_widget_zoneWarningTempThreshold = getThresholdValueFromConfig($user_settings, "thermal_sensors_widget_zone_warning_threshold", DEFAULT_WARNING_THRESHOLD); -$thermal_sensors_widget_zoneCriticalTempThreshold = getThresholdValueFromConfig($user_settings, "thermal_sensors_widget_zone_critical_threshold", DEFAULT_CRITICAL_THRESHOLD); -$thermal_sensors_widget_coreWarningTempThreshold = getThresholdValueFromConfig($user_settings, "thermal_sensors_widget_core_warning_threshold", DEFAULT_WARNING_THRESHOLD); -$thermal_sensors_widget_coreCriticalTempThreshold = getThresholdValueFromConfig($user_settings, "thermal_sensors_widget_core_critical_threshold", DEFAULT_CRITICAL_THRESHOLD); +$thermal_sensors_widget_zoneWarningTempThreshold = getThresholdValueFromConfig($user_settings, "thermal_sensors_widget_zone_warning_threshold", DEFAULT_WARNING_THRESHOLD, $widgetkey); +$thermal_sensors_widget_zoneCriticalTempThreshold = getThresholdValueFromConfig($user_settings, "thermal_sensors_widget_zone_critical_threshold", DEFAULT_CRITICAL_THRESHOLD, $widgetkey); +$thermal_sensors_widget_coreWarningTempThreshold = getThresholdValueFromConfig($user_settings, "thermal_sensors_widget_core_warning_threshold", DEFAULT_WARNING_THRESHOLD, $widgetkey); +$thermal_sensors_widget_coreCriticalTempThreshold = getThresholdValueFromConfig($user_settings, "thermal_sensors_widget_core_critical_threshold", DEFAULT_CRITICAL_THRESHOLD, $widgetkey); //get display settings from config (apply defaults if missing) -$thermal_sensors_widget_showRawOutput = getBoolValueFromConfig($user_settings, "thermal_sensors_widget_show_raw_output", false); -$thermal_sensors_widget_showFullSensorName = getBoolValueFromConfig($user_settings, "thermal_sensors_widget_show_full_sensor_name", false); -$thermal_sensors_widget_pulsateWarning = getBoolValueFromConfig($user_settings, "thermal_sensors_widget_pulsate_warning", true); -$thermal_sensors_widget_pulsateCritical = getBoolValueFromConfig($user_settings, "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]; - } - - if ($thresholdValue < MIN_THRESHOLD_VALUE || $thresholdValue > MAX_THRESHOLD_VALUE) { - //set to default if not in allowed range - $thresholdValue = $defaultValue; - } - 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; - } - return $boolValue; -} +$thermal_sensors_widget_showRawOutput = getBoolValueFromConfig($user_settings, "thermal_sensors_widget_show_raw_output", false, $widgetkey); +$thermal_sensors_widget_showFullSensorName = getBoolValueFromConfig($user_settings, "thermal_sensors_widget_show_full_sensor_name", false, $widgetkey); +$thermal_sensors_widget_pulsateWarning = getBoolValueFromConfig($user_settings, "thermal_sensors_widget_pulsate_warning", true, $widgetkey); +$thermal_sensors_widget_pulsateCritical = getBoolValueFromConfig($user_settings, "thermal_sensors_widget_pulsate_critical", true, $widgetkey); //========================================================================= ?> <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). events.push(function(){ - showThermalSensorsData(); + var tsParams = { + zoneWarningTempThreshold:<?= $thermal_sensors_widget_zoneWarningTempThreshold; ?>, + zoneCriticalTempThreshold:<?= $thermal_sensors_widget_zoneCriticalTempThreshold; ?>, + coreWarningTempThreshold:<?= $thermal_sensors_widget_coreWarningTempThreshold; ?>, + coreCriticalTempThreshold:<?= $thermal_sensors_widget_coreCriticalTempThreshold; ?>, + showRawOutput:<?= $thermal_sensors_widget_showRawOutput ? "true" : "false"; ?>, + showFullSensorName:<?= $thermal_sensors_widget_showFullSensorName ? "true" : "false"; ?>, + pulsateWarning:<?= $thermal_sensors_widget_pulsateWarning ? "true" : "false"; ?>, + pulsateCritical:<?= $thermal_sensors_widget_pulsateCritical ? "true" : "false"; ?> + }; + // showThermalSensorsData("<?=$widgetkey?>", true); + setTimeout(function(){showThermalSensorsData("<?=$widgetkey?>", tsParams, true);}, Math.floor((Math.random() * 10000) + 1000)); }); //]]> </script> <div style="padding: 5px"> - <div id="thermalSensorsContainer" class="listr"> + <div id="thermalSensorsContainer-<?=$widgetkey?>" class="listr"> <?=gettext('(Updating...)')?><br /><br /> </div> </div> </div> <input type="hidden" id="thermal_sensors-config" name="thermal_sensors-config" value="" /> -<div id="widget-<?=$widgetname?>_panel-footer" class="widgetconfigdiv panel-footer collapse" > +<div id="<?=$widget_panel_footer_id?>" class="widgetconfigdiv panel-footer collapse" > <form action="/widgets/widgets/thermal_sensors.widget.php" method="post" id="iform_thermal_sensors_settings" name="iform_thermal_sensors_settings"> + <input type="hidden" name="widgetkey" value="<?=$widgetkey; ?>"> <table> <tr> <td class="text-left" colspan="2"> diff --git a/src/usr/local/www/widgets/widgets/traffic_graphs.widget.php b/src/usr/local/www/widgets/widgets/traffic_graphs.widget.php index ebe2180..579bc32 100644 --- a/src/usr/local/www/widgets/widgets/traffic_graphs.widget.php +++ b/src/usr/local/www/widgets/widgets/traffic_graphs.widget.php @@ -26,16 +26,6 @@ * limitations under the License. */ -/* TODOs */ -//re-use on Status > traffic graphs -//figure out why there is a missing datapoint at the start -//name things/variables better -//apply css change to Status > Monitoring -//show interface name and latest in/out in upper left -//add stacked overall graph? - //also show pie graph of lastest precentages of total? (split 50/50 on width) - //make this an option? - $nocsrf = true; require_once("guiconfig.inc"); @@ -49,98 +39,72 @@ if (ipsec_enabled()) { $ifdescrs['enc0'] = "IPsec"; } -//there are no traffic graph widget defaults in config yet. so set them, but don't write the config -if (!is_array($config["widgets"]["trafficgraphs"])) { - - $config["widgets"]["trafficgraphs"] = array(); - $config["widgets"]["trafficgraphs"]["refreshinterval"] = 1; - $config["widgets"]["trafficgraphs"]["invert"] = "true"; - $config["widgets"]["trafficgraphs"]["size"] = 1; - $config["widgets"]["trafficgraphs"]["backgroundupdate"] = "false"; - $config["widgets"]["trafficgraphs"]["shown"] = array(); - $config["widgets"]["trafficgraphs"]["shown"]["item"] = array(); - - foreach($ifdescrs as $ifname => $ifdescr) { - - $ifinfo = get_interface_info($ifname); - - if ($ifinfo['status'] != "down") { - $config["widgets"]["trafficgraphs"]["shown"]["item"][] = $ifname; - } +if ($_POST) { + if (!is_array($user_settings["widgets"]["traffic_graphs"])) { + $user_settings["widgets"]["traffic_graphs"] = array(); } - //TODO silently write to config? (use a config message about saving defaults) - -} - -if(!isset($config["widgets"]["trafficgraphs"]["size"])) { - $config["widgets"]["trafficgraphs"]["size"] = 1; -} - -if(!isset($config["widgets"]["trafficgraphs"]["invert"])) { - $config["widgets"]["trafficgraphs"]["invert"] = "true"; -} - -if(!isset($config["widgets"]["trafficgraphs"]["backgroundupdate"])) { - $config["widgets"]["trafficgraphs"]["backgroundupdate"] = "true"; -} -$a_config = &$config["widgets"]["trafficgraphs"]; - -// save new default config options that have been submitted -if ($_POST) { - - //TODO validate data and throw error - $a_config["shown"]["item"] = $_POST["traffic-graph-interfaces"]; + if (isset($_POST["refreshinterval"])) { + $user_settings["widgets"]["traffic_graphs"]["refreshinterval"] = $_POST["refreshinterval"]; + } - // TODO check if between 1 and 10 - if (isset($_POST["traffic-graph-interval"]) && is_numericint($_POST["traffic-graph-interval"])) { - $a_config["refreshinterval"] = $_POST["traffic-graph-interval"]; - } else { - die('{ "error" : "Refresh Interval is not a valid number between 1 and 10." }'); + if (isset($_POST["invert"])) { + $user_settings["widgets"]["traffic_graphs"]["invert"] = $_POST["invert"]; } - if($_POST["traffic-graph-invert"] === "true" || $_POST["traffic-graph-invert"] === "false") { - $a_config["invert"] = $_POST["traffic-graph-invert"]; - } else { - die('{ "error" : "Invert is not a boolean of true or false." }'); + if (isset($_POST["backgroundupdate"])) { + $user_settings["widgets"]["traffic_graphs"]["backgroundupdate"] = $_POST["backgroundupdate"]; } - if($_POST["traffic-graph-backgroundupdate"] === "true" || $_POST["traffic-graph-backgroundupdate"] === "false") { - $a_config["backgroundupdate"] = $_POST["traffic-graph-backgroundupdate"]; - } else { - die('{ "error" : "Backgroundupdate is not a boolean of true or false." }'); + if (isset($_POST["size"])) { + $user_settings["widgets"]["traffic_graphs"]["size"] = $_POST["size"]; } - - //TODO validate data and throw error - $a_config["size"] = $_POST["traffic-graph-size"]; - write_config(gettext("Updated traffic graph settings via dashboard.")); + $validNames = array(); - header('Content-Type: application/json'); + foreach ($ifdescrs as $ifdescr => $ifname) { + array_push($validNames, $ifdescr); + } - die('{ "success" : "The changes have been applied successfully." }'); + if (is_array($_POST['show'])) { + $user_settings["widgets"]["traffic_graphs"]["filter"] = implode(',', array_diff($validNames, $_POST['show'])); + } else { + $user_settings["widgets"]["traffic_graphs"]["filter"] = implode(',', $validNames); + } + save_widget_settings($_SESSION['Username'], $user_settings["widgets"], gettext("Updated traffic graphs widget settings via dashboard.")); + header("Location: /"); + exit(0); } -$refreshinterval = $a_config["refreshinterval"]; - -$ifsarray = []; - -foreach ($a_config["shown"]["item"] as $ifname) { - - $ifinfo = get_interface_info($ifname); +if (isset($user_settings['widgets']['traffic_graphs']['refreshinterval'])) { + $tg_refreshinterval = $user_settings['widgets']['traffic_graphs']['refreshinterval']; +} else { + $tg_refreshinterval = 1; +} - if ($ifinfo['status'] != "down") { - $ifsarray[] = $ifname; - } else { - //TODO throw error? - } +if (isset($user_settings['widgets']['traffic_graphs']['size'])) { + $tg_size = $user_settings['widgets']['traffic_graphs']['size']; +} else { + $tg_size = 1; +} +if (isset($user_settings['widgets']['traffic_graphs']['invert'])) { + $tg_invert = $user_settings['widgets']['traffic_graphs']['invert']; +} else { + $tg_invert = 'true'; } -$allifs = implode("|", $ifsarray); +if (isset($user_settings['widgets']['traffic_graphs']['backgroundupdate'])) { + $tg_backgroundupdate = $user_settings['widgets']['traffic_graphs']['backgroundupdate']; +} else { + $tg_backgroundupdate = 'true'; +} +$skip_tg_items = explode(",", $user_settings['widgets']['traffic_graphs']['filter']); +$tg_displayed = false; +$tg_displayed_ifs_array = []; ?> <script src="/vendor/d3/d3.min.js"></script> <script src="/vendor/nvd3/nv.d3.js"></script> @@ -149,17 +113,138 @@ $allifs = implode("|", $ifsarray); <link href="/vendor/nvd3/nv.d3.css" media="screen, projection" rel="stylesheet" type="text/css"> <div id="traffic-chart-error" class="alert alert-danger" style="display: none;"></div> +<?php + foreach ($ifdescrs as $ifdescr => $ifname) { + if (in_array($ifdescr, $skip_tg_items)) { + continue; + } - <?php - foreach($a_config["shown"]["item"] as $ifname) { - echo '<div id="traffic-chart-' . $ifname . '" class="d3-chart traffic-widget-chart">'; + $ifinfo = get_interface_info($ifdescr); + + if ($ifinfo['status'] == "down") { + // Do not try to display the traffic graph of a down interface, + // even though it is selected for display. + continue; + } + + $tg_displayed = true; + $tg_displayed_ifs_array[] = $ifdescr; + echo '<div id="traffic-chart-' . $ifdescr . '" class="d3-chart traffic-widget-chart">'; echo ' <svg></svg>'; echo '</div>'; } + + if (!$tg_displayed) { + echo '<div id="traffic-chartnone" class="d3-chart traffic-widget-chart">'; + echo gettext('All traffic graphs are hidden.'); + echo '</div>'; + } +?> + +<!-- close the body we're wrapped in and add a configuration-panel --> +</div> + +<div id="widget-<?=$widgetname?>_panel-footer" class="panel-footer collapse"> + + <form action="/widgets/widgets/traffic_graphs.widget.php" method="post" class="form-horizontal"> + <div class="form-group"> + <label for="traffic-graph-interval" class="col-sm-3 control-label"><?=gettext('Refresh Interval')?></label> + <div class="col-sm-9"> + <input type="number" id="refreshinterval" name="refreshinterval" value="<?=$tg_refreshinterval?>" min="1" max="10" class="form-control" /> + </div> + </div> + + <div class="form-group"> + <label for="invert" class="col-sm-3 control-label"><?=gettext('Inverse')?></label> + <div class="col-sm-9"> + <select class="form-control" id="invert" name="invert"> + <?php + if ($tg_invert === "true") { + echo '<option value="true" selected>On</option>'; + echo '<option value="false">Off</option>'; + } else { + echo '<option value="true">On</option>'; + echo '<option value="false" selected>Off</option>'; + } + ?> + </select> + </div> + </div> + + <div class="form-group"> + <label for="size" class="col-sm-3 control-label"><?=gettext('Unit Size')?></label> + <div class="col-sm-9"> + <select class="form-control" id="size" name="size"> + <?php + if ($tg_size === "8") { + echo '<option value="8" selected>Bits</option>'; + echo '<option value="1">Bytes</option>'; + } else { + echo '<option value="8">Bits</option>'; + echo '<option value="1" selected>Bytes</option>'; + } + ?> + </select> + </div> + </div> + + <div class="form-group"> + <label for="backgroundupdate" class="col-sm-3 control-label"><?=gettext('Background updates')?></label> + <div class="col-sm-9"> + <select class="form-control" id="backgroundupdate" name="backgroundupdate"> + <?php + if ($tg_backgroundupdate === "true") { + echo '<option value="true" selected>Keep graphs updated on inactive tab. (increases cpu usage)</option>'; + echo '<option value="false">Clear graphs when not visible.</option>'; + } else { + echo '<option value="true">Keep graphs updated on inactive tab. (increases cpu usage)</option>'; + echo '<option value="false" selected>Clear graphs when not visible.</option>'; + } + ?> + </select> + </div> + </div> + + <div class="panel panel-default col-sm-10"> + <div class="panel-body"> + <div class="table responsive"> + <table class="table table-striped table-hover table-condensed"> + <thead> + <tr> + <th><?=gettext("Interface")?></th> + <th><?=gettext("Show")?></th> + </tr> + </thead> + <tbody> + <?php + $idx = 0; + + foreach ($ifdescrs as $ifdescr => $ifname): + ?> + <tr> + <td><?=$ifname?></td> + <td class="col-sm-2"><input id="show[]" name ="show[]" value="<?=$ifdescr?>" type="checkbox" <?=(!in_array($ifdescr, $skip_tg_items) ? 'checked':'')?>></td> + </tr> + <?php + endforeach; ?> + </tbody> + </table> + </div> + </div> + </div> + + <div class="form-group"> + <div class="col-sm-offset-3 col-sm-6"> + <button type="submit" class="btn btn-primary"><i class="fa fa-save icon-embed-btn"></i><?=gettext('Save')?></button> + <button id="showalltgitems" type="button" class="btn btn-info"><i class="fa fa-undo icon-embed-btn"></i><?=gettext('All')?></button> + </div> + </div> + </form> - <script type="text/javascript"> +<script type="text/javascript"> //<![CDATA[ +// Used by /js/traffic-graphs.js to display description from name var graph_interfacenames = <?php foreach ($ifdescrs as $ifname => $ifdescr) { $iflist[$ifname] = $ifdescr; @@ -169,16 +254,16 @@ var graph_interfacenames = <?php events.push(function() { - var InterfaceString = "<?=$allifs?>"; + var InterfaceString = "<?=implode("|", $tg_displayed_ifs_array)?>"; //store saved settings in a fresh localstorage localStorage.clear(); - localStorage.setItem('interval', <?=$refreshinterval?>); - localStorage.setItem('invert', <?=$a_config["invert"]?>); - localStorage.setItem('size', <?=$a_config["size"]?>); - localStorage.setItem('backgroundupdate', <?=$a_config["backgroundupdate"]?>); + localStorage.setItem('interval', <?=$tg_refreshinterval?>); + localStorage.setItem('invert', <?=$tg_invert?>); + localStorage.setItem('size', <?=$tg_size?>); + localStorage.setItem('backgroundupdate', <?=$tg_backgroundupdate?>); - window.interfaces = InterfaceString.split("|"); + window.interfaces = InterfaceString.split("|").filter(function(entry) { return entry.trim() != ''; }); window.charts = {}; window.myData = {}; window.updateIds = 0; @@ -203,27 +288,29 @@ events.push(function() { var itemOut = new Object(); itemIn.key = value + " (in)"; - if(localStorage.getItem('invert') === "true") { itemIn.area = true; } + if (localStorage.getItem('invert') === "true") { itemIn.area = true; } itemIn.first = true; itemIn.values = [{x: nowTime, y: 0}]; myData[value].push(itemIn); itemOut.key = value + " (out)"; - if(localStorage.getItem('invert') === "true") { itemOut.area = true; } + if (localStorage.getItem('invert') === "true") { itemOut.area = true; } itemOut.first = true; itemOut.values = [{x: nowTime, y: 0}]; myData[value].push(itemOut); }); - draw_graph(refreshInterval, then, backgroundupdate); + if (window.interfaces.length > 0) { + draw_graph(refreshInterval, then, backgroundupdate); + } //re-draw graph when the page goes from inactive (in it's window) to active Visibility.change(function (e, state) { - if($('#traffic-graph-backgroundupdate').val() === "true"){ + if (backgroundupdate) { return; } - if(state === "visible") { + if (state === "visible") { now = then = new Date(Date.now()); @@ -240,242 +327,29 @@ events.push(function() { var itemOut = new Object(); itemIn.key = value + " (in)"; - if(localStorage.getItem('invert') === "true") { itemIn.area = true; } + if (localStorage.getItem('invert') === "true") { itemIn.area = true; } itemIn.first = true; itemIn.values = [{x: nowTime, y: 0}]; myData[value].push(itemIn); itemOut.key = value + " (out)"; - if(localStorage.getItem('invert') === "true") { itemOut.area = true; } + if (localStorage.getItem('invert') === "true") { itemOut.area = true; } itemOut.first = true; itemOut.values = [{x: nowTime, y: 0}]; myData[value].push(itemOut); }); - draw_graph(refreshInterval, then, backgroundupdate); + if (window.interfaces.length > 0) { + draw_graph(refreshInterval, then, backgroundupdate); + } } }); - // save new config defaults - $( '#traffic-graph-form' ).submit(function(event) { - - var error = false; - $("#traffic-chart-error").hide(); - - var interfaces = $( "#traffic-graph-interfaces" ).val(); - refreshInterval = parseInt($( "#traffic-graph-interval" ).val()); - var invert = $( "#traffic-graph-invert" ).val(); - var size = $( "#traffic-graph-size" ).val(); - var backgroundupdate = $( "#traffic-graph-backgroundupdate" ).val(); - - //TODO validate interfaces data and throw error - - if(!Number.isInteger(refreshInterval) || refreshInterval < 1 || refreshInterval > 10) { - error = 'Refresh Interval is not a valid number between 1 and 10.'; - } - - if(invert != "true" && invert != "false") { - - error = 'Invert is not a boolean of true or false.'; - - } - - if(!error) { - - var formData = { - 'traffic-graph-interfaces' : interfaces, - 'traffic-graph-interval' : refreshInterval, - 'traffic-graph-invert' : invert, - 'traffic-graph-size' : size, - 'traffic-graph-backgroundupdate' : backgroundupdate - }; - - $.ajax({ - type : 'POST', - url : '/widgets/widgets/traffic_graphs.widget.php', - data : formData, - dataType : 'json', - encode : true - }) - .done(function(message) { - - if(message.success) { - - Visibility.stop(updateIds); - clearInterval(updateTimerIds); - - //remove all old graphs (divs/svgs) - $( ".traffic-widget-chart" ).remove(); - - window.interfaces = interfaces; - localStorage.setItem('interval', refreshInterval); - localStorage.setItem('invert', invert); - localStorage.setItem('size', size); - localStorage.setItem('backgroundupdate', backgroundupdate); - - //redraw graph with new settings - now = then = new Date(Date.now()); - - var freshData = []; - - var nowTime = now.getTime(); - - $.each( interfaces, function( key, value ) { - - //create new graphs (divs/svgs) - $("#widget-traffic_graphs_panel-body").append('<div id="traffic-chart-' + value + '" class="d3-chart traffic-widget-chart"><svg></svg></div>'); - - myData[value] = []; - - var itemIn = new Object(); - var itemOut = new Object(); - - itemIn.key = value + " (in)"; - if(localStorage.getItem('invert') === "true") { itemIn.area = true; } - itemIn.first = true; - itemIn.values = [{x: nowTime, y: 0}]; - myData[value].push(itemIn); - - itemOut.key = value + " (out)"; - if(localStorage.getItem('invert') === "true") { itemOut.area = true; } - itemOut.first = true; - itemOut.values = [{x: nowTime, y: 0}]; - myData[value].push(itemOut); - - }); - - draw_graph(refreshInterval, then, backgroundupdate); - - $( "#traffic-graph-message" ).removeClass("text-danger").addClass("text-success"); - $( "#traffic-graph-message" ).text(message.success); - - setTimeout(function() { - $( "#traffic-graph-message" ).empty(); - $( "#traffic-graph-message" ).removeClass("text-success"); - }, 5000); - - } else { - - $( "#traffic-graph-message" ).addClass("text-danger"); - $( "#traffic-graph-message" ).text(message.error); - - console.warn(message.error); - - } - - }) - .fail(function() { - - console.warn( "The Traffic Graphs widget AJAX request failed." ); - - }); - - } else { - - $( "#traffic-graph-message" ).addClass("text-danger"); - $( "#traffic-graph-message" ).text(error); - - console.warn(error); - - } - - event.preventDefault(); - }); - + set_widget_checkbox_events("#widget-<?=$widgetname?>_panel-footer [id^=show]", "showalltgitems"); }); //]]> </script> <script src="/js/traffic-graphs.js"></script> - -<!-- close the body we're wrapped in and add a configuration-panel --> -</div> - -<div id="widget-<?=$widgetname?>_panel-footer" class="panel-footer collapse"> - - <form id="traffic-graph-form" action="/widgets/widgets/traffic_graphs.widget.php" method="post" class="form-horizontal"> - <div class="form-group"> - <label for="traffic-graph-interfaces" class="col-sm-3 control-label"><?=gettext('Show graphs')?></label> - <div class="col-sm-9"> - <select name="traffic-graph-interfaces[]" id="traffic-graph-interfaces" multiple> - <?php - foreach ($ifdescrs as $ifname => $ifdescr) { - - $if_shown = ""; - if (in_array($ifname, $a_config["shown"]["item"])) { $if_shown = " selected"; }; - echo '<option value="' . $ifname . '"' . $if_shown . '>' . $ifdescr . "</option>\n"; - - } - ?> - </select> - </div> - </div> - - <div class="form-group"> - <label for="traffic-graph-interval" class="col-sm-3 control-label"><?=gettext('Refresh Interval')?></label> - <div class="col-sm-9"> - <input type="number" id="traffic-graph-interval" name="traffic-graph-interval" value="<?=$refreshinterval?>" min="1" max="10" class="form-control" /> - </div> - </div> - - <div class="form-group"> - <label for="traffic-graph-invert" class="col-sm-3 control-label"><?=gettext('Inverse')?></label> - <div class="col-sm-9"> - <select class="form-control" id="traffic-graph-invert" name="traffic-graph-invert"> - <?php - if($a_config["invert"] === "true") { - echo '<option value="true" selected>On</option>'; - echo '<option value="false">Off</option>'; - } else { - echo '<option value="true">On</option>'; - echo '<option value="false" selected>Off</option>'; - } - ?> - </select> - </div> - </div> - - <div class="form-group"> - <label for="traffic-graph-size" class="col-sm-3 control-label"><?=gettext('Unit Size')?></label> - <div class="col-sm-9"> - <select class="form-control" id="traffic-graph-size" name="traffic-graph-size"> - <?php - if($a_config["size"] === "8") { - echo '<option value="8" selected>Bits</option>'; - echo '<option value="1">Bytes</option>'; - } else { - echo '<option value="8">Bits</option>'; - echo '<option value="1" selected>Bytes</option>'; - } - ?> - </select> - </div> - </div> - - <div class="form-group"> - <label for="traffic-graph-backgroundupdate" class="col-sm-3 control-label"><?=gettext('Background updates')?></label> - <div class="col-sm-9"> - <select class="form-control" id="traffic-graph-backgroundupdate" name="traffic-graph-backgroundupdate"> - <?php - if($a_config["backgroundupdate"] === "true") { - echo '<option value="true" selected>Keep graphs updated on inactive tab. (increases cpu usage)</option>'; - echo '<option value="false">Clear graphs when not visible.</option>'; - } else { - echo '<option value="true">Keep graphs updated on inactive tab. (increases cpu usage)</option>'; - echo '<option value="false" selected>Clear graphs when not visible.</option>'; - } - ?> - </select> - </div> - </div> - <div class="form-group"> - <div class="col-sm-3 text-right"> - <button type="submit" class="btn btn-primary"><i class="fa fa-save icon-embed-btn"></i><?=gettext('Save')?></button> - </div> - <div class="col-sm-9"> - <div id="traffic-graph-message"></div> - </div> - </div> - </form> diff --git a/src/usr/local/www/widgets/widgets/wake_on_lan.widget.php b/src/usr/local/www/widgets/widgets/wake_on_lan.widget.php index 3d528f4..a6a10a5 100644 --- a/src/usr/local/www/widgets/widgets/wake_on_lan.widget.php +++ b/src/usr/local/www/widgets/widgets/wake_on_lan.widget.php @@ -32,11 +32,13 @@ if (is_array($config['wol']['wolentry'])) { } // Constructs a unique key that will identify a WoL entry in the filter list. -function get_wolent_key($wolent) { - return ($wolent['interface'] . "|" . $wolent['mac']); +if (!function_exists('get_wolent_key')) { + function get_wolent_key($wolent) { + return ($wolent['interface'] . "|" . $wolent['mac']); + } } -if ($_POST) { +if ($_POST['widgetkey']) { $validNames = array(); @@ -45,9 +47,9 @@ if ($_POST) { } if (is_array($_POST['show'])) { - $user_settings['widgets']['wol']['filter'] = implode(',', array_diff($validNames, $_POST['show'])); + $user_settings['widgets'][$_POST['widgetkey']]['filter'] = implode(',', array_diff($validNames, $_POST['show'])); } else { - $user_settings['widgets']['wol']['filter'] = ""; + $user_settings['widgets'][$_POST['widgetkey']]['filter'] = implode(',', $validNames); } save_widget_settings($_SESSION['Username'], $user_settings["widgets"], gettext("Saved Wake on LAN Filter via Dashboard.")); @@ -67,14 +69,17 @@ if ($_POST) { </thead> <tbody> <?php -$skipwols = explode(",", $user_settings['widgets']['wol']['filter']); +$skipwols = explode(",", $user_settings['widgets'][$widgetkey]['filter']); if (count($wolcomputers) > 0): + $wol_entry_is_displayed = false; + foreach ($wolcomputers as $wolent): if (in_array(get_wolent_key($wolent), $skipwols)) { continue; } + $wol_entry_is_displayed = true; $is_active = exec("/usr/sbin/arp -an |/usr/bin/grep {$wolent['mac']}| /usr/bin/wc -l|/usr/bin/awk '{print $1;}'"); $status = exec("/usr/sbin/arp -an | /usr/bin/awk '$4 == \"{$wolent['mac']}\" { print $7 }'"); ?> @@ -101,8 +106,15 @@ if (count($wolcomputers) > 0): </a> </td> </tr> -<?php endforeach; -else: ?> +<?php + endforeach; + if (!$wol_entry_is_displayed): +?> + <tr><td colspan="4" class="text-center"><?=gettext("All WoL entries are hidden.")?></td></tr> +<?php + endif; +else: +?> <tr><td colspan="4" class="text-center"><?= gettext("No saved WoL addresses") ?></td></tr> <?php endif; @@ -125,11 +137,12 @@ if (is_array($config['dhcpd'])) { <?php endif; ?> </div> <!-- close the body we're wrapped in and add a configuration-panel --> -</div><div id="widget-<?=$widgetname?>_panel-footer" class="panel-footer collapse"> +</div><div id="<?=$widget_panel_footer_id?>" class="panel-footer collapse"> <form action="/widgets/widgets/wake_on_lan.widget.php" method="post" class="form-horizontal"> <div class="panel panel-default col-sm-10"> <div class="panel-body"> + <input type="hidden" name="widgetkey" value="<?=$widgetkey; ?>"> <div class="table responsive"> <table class="table table-striped table-hover table-condensed"> <thead> @@ -142,7 +155,7 @@ if (is_array($config['dhcpd'])) { </thead> <tbody> <?php - $skipwols = explode(",", $user_settings['widgets']['wol']['filter']); + $skipwols = explode(",", $user_settings['widgets'][$widgetkey]['filter']); $idx = 0; foreach ($wolcomputers as $wolent): @@ -165,7 +178,7 @@ if (is_array($config['dhcpd'])) { <div class="form-group"> <div class="col-sm-offset-3 col-sm-6"> <button type="submit" class="btn btn-primary"><i class="fa fa-save icon-embed-btn"></i><?=gettext('Save')?></button> - <button id="showallwols" type="button" class="btn btn-info"><i class="fa fa-undo icon-embed-btn"></i><?=gettext('All')?></button> + <button id="<?=$widget_showallnone_id?>" type="button" class="btn btn-info"><i class="fa fa-undo icon-embed-btn"></i><?=gettext('All')?></button> </div> </div> </form> @@ -173,12 +186,7 @@ if (is_array($config['dhcpd'])) { <script> //<![CDATA[ events.push(function(){ - $("#showallwols").click(function() { - $("#widget-<?=$widgetname?>_panel-footer [id^=show]").each(function() { - $(this).prop("checked", true); - }); - }); - + set_widget_checkbox_events("#<?=$widget_panel_footer_id?> [id^=show]", "<?=$widget_showallnone_id?>"); }); //]]> </script> |