function msgShow(retcode,msg) {
if(retcode == 0) { var alertType = 'success';
} else if(retcode == 2 || retcode == 1) {
var alertType = 'danger';
}
var htmlMsg = '
').text(progressText).html() + '
';
$('#system-reset-message').html(progressHtml);
$.post('ajax/networking/do_sys_reset.php?',{'csrf_token':csrfToken},function(data){
setTimeout(function(){
jsonData = JSON.parse(data);
if(jsonData['return'] == 0) {
$('#system-reset-message').text(successHtml);
} else {
$('#system-reset-message').text('Error occured: '+ jsonData['return']);
}
$("#js-system-reset-confirm").hide();
$("#js-system-reset-cancel").text(closeHtml);
},750);
});
});
$('#js-sys-reboot, #js-sys-shutdown').on('click', function (e) {
e.preventDefault();
var csrfToken = $('meta[name=csrf_token]').attr('content');
var action = $(this).data('action');
$.post('ajax/system/sys_actions.php?',{'a': action, 'csrf_token': csrfToken},function(data){
var response = JSON.parse(data);
});
});
$('#install-user-plugin').on('shown.bs.modal', function (e) {
var button = $(e.relatedTarget);
var manifestData = button.data('plugin-manifest');
var installed = button.data('plugin-installed');
if (manifestData) {
$('#plugin-uri').html(manifestData.plugin_uri
? `
${manifestData.plugin_uri}`
: 'Unknown'
);
$('#plugin-icon').attr('class', `${manifestData.icon || 'fas fa-plug'} link-secondary h5 me-2`);
$('#plugin-name').text(manifestData.name || 'Unknown');
$('#plugin-version').text(manifestData.version || 'Unknown');
$('#plugin-description').text(manifestData.description || 'No description provided');
$('#plugin-author').html(manifestData.author
? manifestData.author + (manifestData.author_uri
? ` (
profile)` : '') : 'Unknown'
);
$('#plugin-license').text(manifestData.license || 'Unknown');
$('#plugin-locale').text(manifestData.default_locale || 'Unknown');
$('#plugin-configuration').html(formatProperty(manifestData.configuration || {}));
$('#plugin-dependencies').html(formatProperty(manifestData.dependencies || {}));
$('#plugin-sudoers').html(formatProperty(manifestData.sudoers || []));
$('#plugin-user-name').html(manifestData.user_nonprivileged.name || 'None');
}
if (installed) {
$('#js-install-plugin-confirm').html('OK');
} else {
$('#js-install-plugin-confirm').html('Install now');
}
});
$('#js-install-plugin-confirm').on('click', function (e) {
var progressText = $('#js-install-plugin-confirm').attr('data-message');
var successHtml = $('#plugin-install-message').attr('data-message');
var successText = $('
').text(successHtml).text();
var pluginUri = $('#plugin-uri a').attr('href');
var pluginVersion = $('#plugin-version').text();
var csrfToken = $('meta[name=csrf_token]').attr('content');
$("#install-user-plugin").modal('hide');
if ($('#js-install-plugin-confirm').text() === 'Install now') {
$("#install-plugin-progress").modal('show');
$.post(
'ajax/plugins/do_plugin_install.php',
{
'plugin_uri': pluginUri,
'plugin_version': pluginVersion,
'csrf_token': csrfToken
},
function (data) {
setTimeout(function () {
response = JSON.parse(data);
if (response === true) {
$('#plugin-install-message').contents().first().text(successText);
$('#plugin-install-message')
.find('i')
.removeClass('fas fa-cog fa-spin link-secondary')
.addClass('fas fa-check');
$('#js-install-plugin-ok').removeAttr("disabled");
} else {
const errorMessage = jsonData.error || 'An unknown error occurred.';
var errorLog = '';
$('#plugin-install-message')
.contents()
.first()
.replaceWith('An error occurred installing the plugin:');
$('#plugin-install-message').append(errorLog);
$('#plugin-install-message').find('i').removeClass('fas fa-cog fa-spin link-secondary');
$('#js-install-plugin-ok').removeAttr("disabled");
}
}, 200);
}
).fail(function (xhr) {
const jsonData = JSON.parse(xhr.responseText);
const errorMessage = jsonData.error || 'An unknown error occurred.';
$('#plugin-install-message')
.contents()
.first()
.replaceWith('An error occurred installing the plugin:');
var errorLog = '';
$('#plugin-install-message').append(errorLog);
$('#plugin-install-message').find('i').removeClass('fas fa-cog fa-spin link-secondary');
$('#js-install-plugin-ok').removeAttr("disabled");
});
}
});
$('#js-install-plugin-ok').on('click', function (e) {
$("#install-plugin-progress").modal('hide');
window.location.reload();
});
function formatProperty(prop) {
if (Array.isArray(prop)) {
if (typeof prop[0] === 'object') {
return prop.map(item => {
return Object.entries(item)
.map(([key, value]) => `${key}: ${value}`)
.join('
');
}).join('
');
}
return prop.map(line => `${line}
`).join('');
}
if (typeof prop === 'object') {
return Object.entries(prop)
.map(([key, value]) => `${key}: ${value}`)
.join('
');
}
return prop || 'None';
}
$(document).ready(function(){
$("#PanelManual").hide();
$('.ip_address').mask('0ZZ.0ZZ.0ZZ.0ZZ', {
translation: {
'Z': {
pattern: /[0-9]/, optional: true
}
},
placeholder: "___.___.___.___"
});
$('.date').mask('FF:FF:FF:FF:FF:FF', {
translation: {
"F": {
pattern: /[0-9a-z]/, optional: true
}
},
placeholder: "__:__:__:__:__:__"
});
});
$(document).ready(function() {
$('.cidr').mask('099.099.099.099/099', {
translation: {
'0': { pattern: /[0-9]/ }
},
placeholder: "___.___.___.___/___"
});
});
$('#wg-upload,#wg-manual').on('click', function (e) {
if (this.id == 'wg-upload') {
$('#PanelManual').hide();
$('#PanelUpload').show();
} else if (this.id == 'wg-manual') {
$('#PanelUpload').hide();
$('#PanelManual').show();
}
});
$(".custom-file-input").on("change", function() {
var fileName = $(this).val().split("\\").pop();
$(this).siblings(".custom-file-label").addClass("selected").html(fileName);
});
// Retrieves the 'channel' value specified in hostapd.conf
function getChannel() {
$.get('ajax/networking/get_channel.php',function(data){
jsonData = JSON.parse(data);
loadChannelSelect(jsonData);
});
}
/*
Sets the wirelss channel select options based on frequencies reported by iw.
See: https://git.kernel.org/pub/scm/linux/kernel/git/sforshee/wireless-regdb.git
Also: https://en.wikipedia.org/wiki/List_of_WLAN_channels
*/
function loadChannelSelect(selected) {
var iface = $('#cbxinterface').val();
var hwmodeText = '';
var csrfToken = $('meta[name=csrf_token]').attr('content');
// update hardware mode tooltip
setHardwareModeTooltip();
$.post('ajax/networking/get_frequencies.php',{'interface': iface, 'csrf_token': csrfToken, 'selected': selected},function(response){
var hw_mode = $('#cbxhwmode').val();
var country_code = $('#cbxcountries').val();
var channel_select = $('#cbxchannel');
var btn_save = $('#btnSaveHostapd');
var data = JSON.parse(response);
var selectableChannels = [];
// Map selected hw_mode to available channels
if (hw_mode === 'a') {
selectableChannels = data.filter(item => item.MHz.toString().startsWith('5'));
} else if (hw_mode !== 'ac') {
selectableChannels = data.filter(item => item.MHz.toString().startsWith('24'));
} else if (hw_mode === 'b') {
selectableChannels = data.filter(item => item.MHz.toString().startsWith('24'));
} else if (hw_mode === 'ac') {
selectableChannels = data.filter(item => item.MHz.toString().startsWith('5'));
}
// If selected channel doeesn't exist in allowed channels, set default or null (unsupported)
if (!selectableChannels.find(item => item.Channel === selected)) {
if (selectableChannels.length === 0) {
selectableChannels[0] = { Channel: null };
} else {
defaultChannel = selectableChannels[0].Channel;
selected = defaultChannel
}
}
// Set channel select with available values
channel_select.empty();
if (selectableChannels[0].Channel === null) {
channel_select.append($("").attr("value", "").text("---"));
channel_select.prop("disabled", true);
btn_save.prop("disabled", true);
} else {
channel_select.prop("disabled", false);
btn_save.prop("disabled", false);
$.each(selectableChannels, function(key,value) {
channel_select.append($("").attr("value", value.Channel).text(value.Channel));
});
channel_select.val(selected);
}
});
}
/* Sets hardware mode tooltip text for selected interface
* and calls loadChannelSelect()
*/
function setHardwareModeTooltip() {
var iface = $('#cbxinterface').val();
var hwmodeText = '';
var csrfToken = $('meta[name=csrf_token]').attr('content');
// Explanatory text if 802.11ac is disabled
if ($('#cbxhwmode').find('option[value="ac"]').prop('disabled') == true ) {
var hwmodeText = $('#hwmode').attr('data-tooltip');
}
$.post('ajax/networking/get_nl80211_band.php?',{'interface': iface, 'csrf_token': csrfToken},function(data){
var responseText = JSON.parse(data);
$('#tiphwmode').attr('data-original-title', responseText + '\n' + hwmodeText );
});
}
/* Updates the selected blocklist
* Request is passed to an ajax handler to download the associated list.
* Interface elements are updated to indicate current progress, status.
*/
function updateBlocklist() {
var opt = $('#cbxblocklist option:selected');
var blocklist_id = opt.val();
var csrfToken = $('meta[name=csrf_token]').attr('content');
if (blocklist_id == '') { return; }
$('#cbxblocklist-status').find('i').removeClass('fas fa-check').addClass('fas fa-cog fa-spin');
$('#cbxblocklist-status').removeClass('check-hidden').addClass('check-progress');
$.post('ajax/adblock/update_blocklist.php',{ 'blocklist_id':blocklist_id, 'csrf_token': csrfToken},function(data){
var jsonData = JSON.parse(data);
if (jsonData['return'] == '0') {
$('#cbxblocklist-status').find('i').removeClass('fas fa-cog fa-spin').addClass('fas fa-check');
$('#cbxblocklist-status').removeClass('check-progress').addClass('check-updated').delay(500).animate({ opacity: 1 }, 700);
$('#blocklist-'+jsonData['list']).text("Just now");
}
})
}
function clearBlocklistStatus() {
$('#cbxblocklist-status').removeClass('check-updated').addClass('check-hidden');
}
// Handler for the WireGuard generate key button
$('.wg-keygen').click(function(){
var parentGroup = $(this).closest('.input-group');
var entity_pub = parentGroup.find('input[type="text"]');
var updated = entity_pub.attr('name')+"-pubkey-status";
var csrfToken = $('meta[name="csrf_token"]').attr('content');
$.post('ajax/networking/get_wgkey.php',{'entity':entity_pub.attr('name'), 'csrf_token': csrfToken},function(data){
var jsonData = JSON.parse(data);
entity_pub.val(jsonData.pubkey);
$('#' + updated).removeClass('check-hidden').addClass('check-updated').delay(500).animate({ opacity: 1 }, 700);
});
});
// Handler for wireguard client.conf download
$('.wg-client-dl').click(function(){
var req = new XMLHttpRequest();
var url = 'ajax/networking/get_wgcfg.php';
req.open('get', url, true);
req.responseType = 'blob';
req.setRequestHeader('Content-type', 'text/plain; charset=UTF-8');
req.onreadystatechange = function (event) {
if(req.readyState == 4 && req.status == 200) {
var blob = req.response;
var link=document.createElement('a');
link.href=window.URL.createObjectURL(blob);
link.download = 'client.conf';
link.click();
}
}
req.send();
})
// Event listener for Bootstrap's form validation
window.addEventListener('load', function() {
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function(form) {
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
}, false);
let sessionCheckInterval = setInterval(checkSession, 5000);
function checkSession() {
// skip session check if on login page
if (window.location.pathname === '/login') {
return;
}
var csrfToken = $('meta[name=csrf_token]').attr('content');
$.post('ajax/session/do_check_session.php',{'csrf_token': csrfToken},function (data) {
if (data.status === 'session_expired') {
clearInterval(sessionCheckInterval);
showSessionExpiredModal();
}
}).fail(function (jqXHR, status, err) {
console.error("Error checking session status:", status, err);
});
}
function showSessionExpiredModal() {
$('#sessionTimeoutModal').modal('show');
}
$(document).on("click", "#js-session-expired-login", function(e) {
const loginModal = $('#modal-admin-login');
const redirectUrl = window.location.pathname;
window.location.href = `/login?action=${encodeURIComponent(redirectUrl)}`;
});
// show modal login on page load
$(document).ready(function () {
const params = new URLSearchParams(window.location.search);
const redirectUrl = $('#redirect-url').val() || params.get('action') || '/';
$('#modal-admin-login').modal('show');
$('#redirect-url').val(redirectUrl);
$('#username').focus();
$('#username').addClass("focusedInput");
});
// DHCP or Static IP option group
$('#chkstatic').on('change', function() {
if (this.checked) {
setStaticFieldsEnabled();
}
});
$('#chkdhcp').on('change', function() {
this.checked ? setStaticFieldsDisabled() : null;
});
$('input[name="dhcp-iface"]').change(function() {
if ($('input[name="dhcp-iface"]:checked').val() == '1') {
setDhcpFieldsEnabled();
} else {
setDhcpFieldsDisabled();
}
});
function setStaticFieldsEnabled() {
$('#txtipaddress').prop('required', true);
$('#txtsubnetmask').prop('required', true);
$('#txtgateway').prop('required', true);
$('#txtipaddress').removeAttr('disabled');
$('#txtsubnetmask').removeAttr('disabled');
$('#txtgateway').removeAttr('disabled');
}
function setStaticFieldsDisabled() {
$('#txtipaddress').prop('disabled', true);
$('#txtsubnetmask').prop('disabled', true);
$('#txtgateway').prop('disabled', true);
$('#txtipaddress').removeAttr('required');
$('#txtsubnetmask').removeAttr('required');
$('#txtgateway').removeAttr('required');
}
function setDhcpFieldsEnabled() {
$('#txtrangestart').prop('required', true);
$('#txtrangeend').prop('required', true);
$('#txtrangeleasetime').prop('required', true);
$('#cbxrangeleasetimeunits').prop('required', true);
$('#txtrangestart').removeAttr('disabled');
$('#txtrangeend').removeAttr('disabled');
$('#txtrangeleasetime').removeAttr('disabled');
$('#cbxrangeleasetimeunits').removeAttr('disabled');
$('#txtdns1').removeAttr('disabled');
$('#txtdns2').removeAttr('disabled');
$('#txtmetric').removeAttr('disabled');
}
function setDhcpFieldsDisabled() {
$('#txtrangestart').removeAttr('required');
$('#txtrangeend').removeAttr('required');
$('#txtrangeleasetime').removeAttr('required');
$('#cbxrangeleasetimeunits').removeAttr('required');
$('#txtrangestart').prop('disabled', true);
$('#txtrangeend').prop('disabled', true);
$('#txtrangeleasetime').prop('disabled', true);
$('#cbxrangeleasetimeunits').prop('disabled', true);
$('#txtdns1').prop('disabled', true);
$('#txtdns2').prop('disabled', true);
$('#txtmetric').prop('disabled', true);
}
// Static Array method
Array.range = (start, end) => Array.from({length: (end - start)}, (v, k) => k + start);
$(document).on("click", ".js-toggle-password", function(e) {
var button = $(e.currentTarget);
var field = $(button.data("bsTarget"));
if (field.is(":input")) {
e.preventDefault();
if (!button.data("__toggle-with-initial")) {
$("i", button).removeClass("fas fa-eye").addClass(button.attr("data-toggle-with"));
}
if (field.attr("type") === "password") {
field.attr("type", "text");
} else {
$("i", button).removeClass("fas fa-eye-slash").addClass("fas fa-eye");
field.attr("type", "password");
}
}
});
$(function() {
$('#theme-select').change(function() {
var theme = themes[$( "#theme-select" ).val() ];
var hasDarkTheme = theme === 'custom.php';
var nightModeChecked = $("#night-mode").prop("checked");
if (nightModeChecked && hasDarkTheme) {
if (theme === "custom.php") {
set_theme("dark.css");
}
} else {
set_theme(theme);
}
});
});
function set_theme(theme) {
$('link[title="main"]').attr('href', 'app/css/' + theme);
// persist selected theme in cookie
setCookie('theme',theme,90);
}
$(function() {
var currentTheme = getCookie('theme');
// Check if the current theme is a dark theme
var isDarkTheme = currentTheme === 'dark.css';
$('#night-mode').prop('checked', isDarkTheme);
$('#night-mode').change(function() {
var state = $(this).is(':checked');
var currentTheme = getCookie('theme');
if (state == true) {
if (currentTheme == 'custom.php') {
set_theme('dark.css');
}
} else {
if (currentTheme == 'dark.css') {
set_theme('custom.php');
}
}
});
});
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+ d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
var regx = new RegExp(cname + "=([^;]+)");
var value = regx.exec(document.cookie);
return (value != null) ? unescape(value[1]) : null;
}
// Define themes
var themes = {
"default": "custom.php",
"hackernews" : "hackernews.css",
"lightsout" : "lightsout.php",
"material-light" : "material-light.php",
"material-dark" : "material-dark.php",
}
// Toggles the sidebar navigation.
// Overrides the default SB Admin 2 behavior
$("#sidebarToggleTopbar").on('click', function(e) {
$("body").toggleClass("sidebar-toggled");
$(".sidebar").toggleClass("toggled d-none");
});
// Overrides SB Admin 2
$("#sidebarToggle, #sidebarToggleTop").on('click', function(e) {
var toggled = $(".sidebar").hasClass("toggled");
// Persist state in cookie
setCookie('sidebarToggled',toggled, 90);
});
$(function() {
if ($(window).width() < 768) {
$('.sidebar').addClass('toggled');
setCookie('sidebarToggled',false, 90);
}
});
$(window).on("load resize",function(e) {
if ($(window).width() > 768) {
$('.sidebar').removeClass('d-none d-md-block');
if (getCookie('sidebarToggled') == 'false') {
$('.sidebar').removeClass('toggled');
}
}
});
// Adds active class to current nav-item
$(window).bind("load", function() {
var url = window.location;
$('.sb-nav-link-icon a').filter(function() {
return this.href == url;
}).parent().addClass('active');
});
$(document).ready(function() {
const $htmlElement = $('html');
const $modeswitch = $('#night-mode');
$modeswitch.on('change', function() {
const isChecked = $(this).is(':checked');
const newTheme = isChecked ? 'dark' : 'light';
$htmlElement.attr('data-bs-theme', newTheme);
localStorage.setItem('bsTheme', newTheme);
});
});
$(document)
.ajaxSend(setCSRFTokenHeader)
.ready(contentLoaded)
.ready(loadWifiStations());