Subversion Repositories ALCASAR

Rev

Rev 3041 | Rev 3049 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log

<?php
# $Id: network.php 3042 2022-07-22 12:35:45Z rexy $

// written by steweb57, Rexy, Tom HOUDAYER & Pierre RIVAULT

/********************
*  READ CONF FILES  *
*********************/
define('CONF_FILE', '/usr/local/etc/alcasar.conf');
define('ETHERS_FILE', '/usr/local/etc/alcasar-ethers');
define('ETHERS_INFO_FILE', '/usr/local/etc/alcasar-ethers-info');
define('DNS_LOCAL_FILE', '/etc/hosts');
define('LETS_ENCRYPT_FILE', '/usr/local/etc/alcasar-letsencrypt');
define('TEMP_FILE', '/tmp/alcasar.conf.temp');

$conf_files = [CONF_FILE, ETHERS_FILE, ETHERS_INFO_FILE, DNS_LOCAL_FILE, LETS_ENCRYPT_FILE];

// Files reading test
foreach ($conf_files as $file) {
        if (!file_exists($file)) {
                exit("Requested file $file isn't present");
        }
        if (!is_readable($file)) {
                exit("Can't read the file $file");
        }
}

// Read ALCASAR CONF_FILE
$file_conf = fopen(CONF_FILE, 'r');
if (!$file_conf) {
        exit('Error opening the file '.CONF_FILE);
}
while (!feof($file_conf)) {
        $buffer = fgets($file_conf, 4096);
        if ((strpos($buffer, '=') !== false) && (substr($buffer, 0, 1) !== '#')) {
                $tmp = explode('=', $buffer, 2);
                $conf[trim($tmp[0])] = trim($tmp[1]);
        }
}
fclose($file_conf);

// Choice of language
$Language = 'en';
if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
        $Langue   = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
        $Language = strtolower(substr(chop($Langue[0]), 0, 2));
}
if ($Language === 'fr') {
        $l_network_title        = "Configuration réseau";
        $l_internet_legend      = "INTERNET";
        $l_ip_mask              = "Masque";
        $l_ip_router            = "Passerelle";
        $l_ip_public            = "Adresse IP publique";
        $l_ip_dns1              = "DNS n°1";
        $l_ip_dns2              = "DNS n°2";
        $l_dhcp_title           = "Service DHCP";
        $l_dhcp_state           = "Mode actuel";
        $l_DHCP_on              = "actif";
        $l_DHCP_off             = "inactif";
        $l_DHCP_off_explain     = "/!\\ Avant d'arrêter le serveur DHCP, vous devez renseigner les paramètres d'un serveur externe (cf. documentation).";
        $l_static_dhcp_title    = "Réservation d'adresses IP statiques (DHCP)";
        $l_mac_address          = "Adresse MAC";
        $l_ip_address           = "Adresse IP";
        $l_host_name            = "Nom d'hôte";
        $l_del                  = "Supprimer de la liste";
        $l_add_to_list          = "Ajouter";
        $l_apply                = "Appliquer les changements";
        $l_local_dns            = "Résolution local de nom (DNS)";
        $l_import_cert          = "Import de certificat";
        $l_private_key          = "Clé privée (.key) :";
        $l_certificate          = "Certificat (.crt ou .cer) :";
        $l_server_chain         = "Chaîne de certification (.crt, .cer ou .pem) :";
        $l_default_cert         = "Revenir au certificat d'origine :";
        $l_import               = "Importer";
        $l_current_certificate  = "Certificat actuel";
        $l_validated            = "Validé par :";
        $l_empty                = "Vide";
        $l_yes                  = "Oui";
        $l_no                   = "Non";
        $l_ssl_title            = "Chiffrer les flux d'authentification entre les utilisateurs et ALCASAR";
        $l_ssh_title            = "SSH";
        $l_ssh_port                     = "Port";
        $l_ssh_from                     = "IP autorisée";
        $l_ssh_wan_activate     = "Activer SSH sur WAN";
        $l_ssh_lan_activate     = "Activer SSH sur LAN";
        $l_cert_expiration      = "Date d'expiration :";
        $l_cert_commonname      = "Nom commun :";
        $l_cert_organization    = "Organisation :";
        $l_upload_certificate   = "Importer un certificat officiel";
        $l_le_integration       = "Intégrer un certificat Let's Encrypt";
        $l_le_status            = "Status :";
        $l_disabled             = "Inactif";
        $l_pending_validation   = "En attente de validation";
        $l_enabled              = "Actif";
        $l_le_email             = "Email :";
        $l_le_domain_name       = "Nom de domaine :";
        $l_send                 = "Envoyer";
        $l_le_ask_on            = "Demandé le :";
        $l_le_dns_entry_txt     = "Entrée DNS TXT :";
        $l_le_challenge         = "Challenge :";
        $l_recheck              = "Revérifier";
        $l_cancel               = "Annuler";
        $l_le_api               = "API :";
        $l_le_next_renewal      = "Prochain renouvellement :";
        $l_renew                = "Renouveller";
        $l_renew_force          = "Renouveller (forcer)";
        $l_previous_LE_cert     = "Revenir au certificat Let's Encrypt :";
        $l_gw_weight    = "Poids";
        $l_error        = "Erreur";
        $l_error_bad_ip = "Ceci n'est pas une adresse IP valide";
        $l_error_bad_ip_CIDR = "Ceci n'est pas une adresse CIDR valide";
        $l_error_bad_ip_port = "Ceci n'est pas une adresse IP + port valide";
        $l_error_weight = "Ceci n'est pas un poids valide";
    $l_change_successful = "Changement effectué avec succès";

} else if ($Language === 'es') {
        $l_network_title        = "Configuración de Red";
        $l_internet_legend      = "INTERNET";
        $l_ip_mask              = "Máscara";
        $l_ip_router            = "Puerta de enlace";
        $l_ip_public            = "IP Pública";
        $l_ip_dns1              = "DNS n°1";
        $l_ip_dns2              = "DNS n°2";
        $l_dhcp_title           = "Servicio DHCP";
        $l_dhcp_state           = "Modo actual";
        $l_DHCP_on              = "activado";
        $l_DHCP_off             = "desactivado";
        $l_DHCP_off_explain     = "/!\\ Antes de desactivar el servidor DHCP, debe escribir los parámetros externos de DHCP en el archivo de configuración (consulte la Documentación";
        $l_static_dhcp_title    = "Reserva de direcciones IP estáticas (DHCP)";
        $l_mac_address          = "Dirección MAC";
        $l_ip_address           = "Dirección IP";
        $l_host_name            = "Nombre de Host";
        $l_del                  = "Borrar de la lista";
        $l_add_to_list          = "Agregar";
        $l_apply                = "Aplicar cambios";
        $l_local_dns            = "Resolución de Nombres Local (DNS)";
        $l_import_cert          = "Importar Certificado";
        $l_private_key          = "Clave Privada (.key) :";
        $l_certificate          = "Certificado (.crt) :";
        $l_server_chain         = "Cadena completa (de ser necesario: .crt) :";
        $l_default_cert         = "Volverl al certificado por defecto";
        $l_import               = "Importar";
        $l_current_certificate  = "Certificado en uso";
        $l_validated            = "Validado por :";
        $l_empty                = "Vacío";
        $l_yes                  = "Si";
        $l_no                   = "No";
        $l_ssl_title            = "La autenticación de cifrado fluye entre usuarios y ALCASAR";
        $l_ssh_title            = "SSH";
        $l_ssh_port                     = "Puerto";
        $l_ssh_from                     = "IP autorizada";
        $l_ssh_wan_activate     = "Activar SSH on WAN";
        $l_ssh_lan_activate     = "Activar SSH on LAN";
        $l_cert_expiration      = "Fecha de vencimiento:";
        $l_cert_commonname      = "Common name:";
        $l_cert_organization    = "Organización:";
        $l_upload_certificate   = "Importar un certificado";
        $l_le_integration       = "Integración con Let's Encrypt";
        $l_le_status            = "Estado:";
        $l_disabled             = "Desactivado";
        $l_pending_validation   = "Validación pendiente";
        $l_enabled              = "Activado";
        $l_le_email             = "Email:";
        $l_le_domain_name       = "Nombre de dominio:";
        $l_send                 = "Enviar";
        $l_le_ask_on            = "Preguntar el:";
        $l_le_dns_entry_txt     = "Entrada DNS TXT:";
        $l_le_challenge         = "Desafío:";
        $l_recheck              = "Verificar";
        $l_cancel               = "Cancelar";
        $l_le_api               = "API:";
        $l_le_next_renewal      = "Siguiente renovación:";
        $l_renew                = "Renovar";
        $l_renew_force          = "Renovar (forzado)";
        $l_previous_LE_cert     = "Volver al certificado de Let's Encrypt :";
    $l_gw_weight        = "Peso";
    $l_error            = "Error";
    $l_error_bad_ip     = "Esta no es una dirección IP válida";
    $l_error_bad_ip_CIDR        = "Esta no es una dirección CIDR válida";
    $l_error_bad_ip_port        = "Esto no es una dirección IP + puerto válidos";
    $l_error_weight     = "Esto no es un peso válido";
    $l_change_successful        = "Cambio completado con éxito";
} else {
        $l_network_title        = "Network configuration";
        $l_internet_legend      = "INTERNET";
        $l_ip_mask              = "Mask";
        $l_ip_router            = "Gateway";
        $l_ip_public            = "Public IP address";
        $l_ip_dns1              = "DNS n°1";
        $l_ip_dns2              = "DNS n°2";
        $l_dhcp_title           = "DHCP service";
        $l_dhcp_state           = "Current mode";
        $l_DHCP_on              = "enabled";
        $l_DHCP_off             = "disabled";
        $l_DHCP_off_explain     = "/!\\ Before disabling the DHCP server, you must write the extern DHCP parameters in the config file (see Documentation)";
        $l_static_dhcp_title    = "Static IP addresses reservation (DHCP)";
        $l_mac_address          = "MAC address";
        $l_ip_address           = "IP address";
        $l_host_name            = "Host name";
        $l_del                  = "Delete from list";
        $l_add_to_list          = "Add";
        $l_apply                = "Apply changes";
        $l_local_dns            = "Local name resolution (DNS";
        $l_import_cert          = "Certificate import";
        $l_private_key          = "Private key (.key) :";
        $l_certificate          = "Certificate (.crt or .cer) :";
        $l_server_chain         = "Server-chain (.crt, .cer or .pem) :";
        $l_default_cert         = "Back to default certificate :";
        $l_import               = "Import";
        $l_current_certificate  = "Current certificate";
        $l_validated            = "Validated by :";
        $l_empty                = "Empty";
        $l_yes                  = "Yes";
        $l_no                   = "No";
        $l_ssl_title            = "Cipher authentication flows between users and ALCASAR";
        $l_ssh_title            = "SSH";
        $l_ssh_port                     = "Port";
        $l_ssh_from                     = "Authorized IP";
        $l_ssh_wan_activate     = "Activate SSH on WAN";
        $l_ssh_lan_activate     = "Activate SSH on LAN";
        $l_cert_expiration      = "Expiration date:";
        $l_cert_commonname      = "Common name:";
        $l_cert_organization    = "Organization:";
        $l_upload_certificate   = "Import an officlal certificate";
        $l_le_integration       = "Integrate a Let's Encrypt certificate";
        $l_le_status            = "Status:";
        $l_disabled             = "Disabled";
        $l_pending_validation   = "Pending validation";
        $l_enabled              = "Enabled";
        $l_le_email             = "Email:";
        $l_le_domain_name       = "Domain name:";
        $l_send                 = "Send";
        $l_le_ask_on            = "Ask on:";
        $l_le_dns_entry_txt     = "DNS TXT entry:";
        $l_le_challenge         = "Challenge:";
        $l_recheck              = "Recheck";
        $l_cancel               = "Cancel";
        $l_le_api               = "API:";
        $l_le_next_renewal      = "Next renewal:";
        $l_renew                = "Renew";
        $l_renew_force          = "Renew (force)";
        $l_previous_LE_cert     = "Back to the Let's Encrypt certificate :";
    $l_gw_weight = "Weight";
    $l_error        = "Error";
    $l_error_bad_ip = "This is not a valid IP";
    $l_error_bad_ip_CIDR = "This is not a valid CIDR IP";
    $l_error_bad_ip_port = "This is not a valid IP + port";
    $l_error_weight = "This is not a valid weight";
    $l_change_successful = "Network updated successfully";
}

$reg_ip      = '/^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/';
$reg_ip_cidr = '/^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\/([0-9]|[1-2][0-9]|3[0-2]))$/';
$reg_ip_port = '/^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\:([1-9]|[1-9][0-9]|[1-9][0-9]{2}|[1-9][0-9]{3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5]))$/';
$reg_mac     = '/^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$/';
$reg_host    = '/^[a-zA-Z0-9-_]+$/';
$reg_weight  = '/^[0-9]*$/';
$ext_conf_error = false;

$choix = (isset($_POST['choix'])) ? $_POST['choix'] : '';
switch ($choix) {
        case 'DHCP_On':
                exec('sudo /usr/local/bin/alcasar-dhcp.sh -on');
                header('Location: '.$_SERVER['PHP_SELF']);
                exit();
        case 'DHCP_Off':
                exec('sudo /usr/local/bin/alcasar-dhcp.sh -off');
                header('Location: '.$_SERVER['PHP_SELF']);
                exit();
        case 'new_mac':
                $new_mac_addr = trim($_POST['add_mac']);
                $new_ip_addr  = trim($_POST['add_ip']);
                if (((!empty($new_mac_addr)) && (preg_match($reg_mac, $new_mac_addr))) && ((!empty($new_ip_addr)) && (preg_match($reg_ip, $new_ip_addr)))) {
                        $tab = file(ETHERS_FILE);
                        if ($tab) { // the file isn't empty
                                $insert = true;
                                foreach ($tab as $line) { // verify that MAC or IP address doesn't exist
                                        $field = explode(' ', $line);
                                        $mac_addr = trim($field[0]);
                                        $ip_addr  = trim($field[1]);
                                        if (strcasecmp($new_mac_addr, $mac_addr) === 0) {
                                                $insert = false;
                                                break;
                                        }
                                        if (strcasecmp($new_ip_addr, $ip_addr) === 0) {
                                                $insert = false;
                                                break;
                                        }
                                }
                                if ($insert) {
                                        $line = $new_mac_addr . ' ' . $new_ip_addr . "\n";
                                        $pointeur = fopen(ETHERS_FILE, 'a');
                                        fwrite($pointeur, $line);
                                        fclose($pointeur);
                                        $pointeur = fopen(ETHERS_INFO_FILE, 'a');
                                        $line = "$new_mac_addr $new_ip_addr #" . trim($_POST['info'],"\x00..\x20") . "\n";
                                        fwrite($pointeur, $line);
                                        fclose($pointeur);
                                        exec('sudo /usr/bin/systemctl reload chilli');
                                }
                        }
                }
                header('Location: '.$_SERVER['PHP_SELF']);
                exit();
        case 'del_mac':
                foreach ($_POST as $key => $value) {
                        if ($value == 'on') {
                                $ether_file = ETHERS_FILE;
                                $ether_file_info = ETHERS_INFO_FILE;
                                exec("/bin/sed -i ".escapeshellarg("/^$key/d")." $ether_file");
                                exec("/bin/sed -i ".escapeshellarg("/^$key/d")." $ether_file_info");
                                exec('sudo /usr/bin/systemctl reload chilli');
                        }
                }
                header('Location: '.$_SERVER['PHP_SELF']);
                exit();
        case 'new_host':
                $add_host = trim($_POST['add_host']);
                $add_ip   = trim($_POST['add_ip']);
                if (((!empty($add_host)) && (preg_match($reg_host, $add_host))) && ((!empty($add_ip)) && (preg_match($reg_ip, $add_ip)))) {
                        $tab = file(DNS_LOCAL_FILE);
                        if ($tab) { // the file isn't empty
                                $insert = true;
                                foreach ($tab as $line) { // verify that host or IP address doesn't exist
                                        if (preg_match('/^\d+/', $line)) {
                                                $field = preg_split("/\s+/",$line);
                                                $ip_addr = $field[0];
                                                $host_name = trim($field[1]);
                                                if (strcasecmp($add_host, $host_name) === 0) {
                                                        $insert = false;
                                                        break;
                                                }
                                        }
                                }
                                if ($insert) {
                                        exec("sudo /usr/local/bin/alcasar-dns-local.sh --add $add_ip $add_host");
                                }
                        }
                }
                header('Location: '.$_SERVER['PHP_SELF']);
                exit();
        case 'del_host':
                foreach ($_POST as $key => $value) {
                        if ($value == 'on') {
                                $del_host = explode ("|", $key);
                                $del_ip = str_replace("_",".",$del_host[0]);
                                exec("sudo /usr/local/bin/alcasar-dns-local.sh --del $del_ip $del_host[1]");
                        }
                }
                header('Location: '.$_SERVER['PHP_SELF']);
                exit();

        case 'set_default_cert':
                exec('sudo alcasar-importcert.sh -d');
                break;
        case 'set_last_LE_cert':
                exec('sudo alcasar-letsencrypt.sh --install-cert');
                break;
        case 'import_cert':     // Import certificate
                $maxsize = 100000;
                if (isset($_FILES['key']) && isset($_FILES['crt']) && ($_FILES['key']['error'] == 0) && ($_FILES['crt']['error'] == 0)) {
                        if ($_FILES['key']['size'] <= $maxsize && $_FILES['crt']['size'] <= $maxsize) {
                                if (pathinfo($_FILES['key']['name'])['extension'] == 'key' && ((pathinfo($_FILES['crt']['name'])['extension'] == 'crt') || (pathinfo($_FILES['crt']['name'])['extension'] == 'cer'))) {
                                        $dest = '/tmp/';
                                        $scpath = '';
                                        if (isset($_FILES['sc']) && ((pathinfo($_FILES['sc']['name'])['extension'] == 'crt') || (pathinfo($_FILES['sc']['name'])['extension'] == 'cer') || (pathinfo($_FILES['sc']['name']['extension'] == 'pem')))){
                                                $scpath = $dest.'server-chain.pem';
                                                move_uploaded_file($_FILES['sc']['tmp_name'], $scpath);
                                        }
                                        $keypath = $dest.'alcasar.key';
                                        $crtpath = $dest.'alcasar.crt';
                                        move_uploaded_file($_FILES['key']['tmp_name'], $keypath);
                                        move_uploaded_file($_FILES['crt']['tmp_name'], $crtpath);
                                        exec("sudo alcasar-importcert.sh -i $crtpath -k $keypath -c $scpath");
                                        if (file_exists($crtpath)) unlink($crtpath);
                                        if (file_exists($keypath)) unlink($keypath);
                                        if (file_exists($scpath))  unlink($scpath);
                                }
                        }
                }
                break;
        case 'enable_lan_ssh': // Activate SSH on LAN
                if (isset($_POST['sshlan'])) {
                        exec('sudo /usr/local/bin/alcasar-ssh.sh --on -l -p'.escapeshellarg($_POST["ssh_port"]).' -i'.escapeshellarg($_POST["ssh_from"]),$output,$exitCode);
                        if($exitCode === 1){
                                echo("<html><script>if(!alert(`$l_error_bad_ip_port`)){window.location.href = window.location.href;}</script></html>");
                        }else{
                                header('Location: '.$_SERVER['PHP_SELF']);
                        }
                } else{
                        exec('sudo /usr/local/bin/alcasar-ssh.sh --off -l');
                        header('Location: '.$_SERVER['PHP_SELF']);
                }
                exit(); 
        case 'enable_wan_ssh': // Activate SSH on WAN
                if (isset($_POST['togglessh'])) {
                        exec('sudo /usr/local/bin/alcasar-ssh.sh --on -w -p'.escapeshellarg($_POST["ssh_port"]).' -i'.escapeshellarg($_POST["ssh_from"]),$output,$exitCode);
                        if($exitCode === 1){
                                echo("<html><script>if(!alert(`$l_error_bad_ip_port`)){window.location.href = window.location.href;}</script></html>");
                        }else{
                                header('Location: '.$_SERVER['PHP_SELF']);
                        }
                } else{
                        exec('sudo /usr/local/bin/alcasar-ssh.sh --off -w');
                        header('Location: '.$_SERVER['PHP_SELF']);
                }
                exit();
        case 'https_login':     // Set HTTPS login status
                if (isset($_POST['https_login']))        {
                        exec('sudo /usr/local/bin/alcasar-https.sh --on');
                } else {
                        exec('sudo /usr/local/bin/alcasar-https.sh --off');
                }
                header('Location: '.$_SERVER['PHP_SELF']);
                exit();
}

// Network changes
if ($choix === 'network_change') {
    exec('sudo /usr/local/bin/alcasar-network.sh --save');
        $modification_network = false;
        $modification_dns = false;
        $modification_proxy = false;
        $ext_conf_error_list = [];
        copy(CONF_FILE, TEMP_FILE);

        if (isset($_POST['dns1']) && (trim($_POST['dns1']) !== $conf['DNS1'])) {
            if (!preg_match($reg_ip, $_POST['dns1'])) {
            $ext_conf_error = true;
            $ext_conf_error_list[] = $l_error.': '.$l_ip_dns1.': '.$l_error_bad_ip;
        }
                file_put_contents(TEMP_FILE, str_replace('DNS1='.$conf['DNS1'], 'DNS1='.trim($_POST['dns1']), file_get_contents(TEMP_FILE)));
                $modification_dns = true;
        }
        if (isset($_POST['dns2']) && (trim($_POST['dns2']) !== $conf['DNS2'])) {
            if (!preg_match($reg_ip, $_POST['dns2'])) {
            $ext_conf_error = true;
            $ext_conf_error_list[] = $l_error.': '.$l_ip_dns2.': '.$l_error_bad_ip;
        }
                file_put_contents(TEMP_FILE, str_replace('DNS2='.$conf['DNS2'], 'DNS2='.trim($_POST['dns2']), file_get_contents(TEMP_FILE)));
                $modification_dns = true;
        }
    if (isset($_POST['ip_private']) && (trim($_POST['ip_private']) !== $conf['PRIVATE_IP'])) {
        if (!preg_match($reg_ip_cidr, $_POST['ip_private'])) {
            $ext_conf_error = true;
            $ext_conf_error_list[] = $l_error.': '.$l_ip_address.' LAN: '.$l_error_bad_ip_CIDR;
        }
        file_put_contents(TEMP_FILE, str_replace('PRIVATE_IP='.$conf['PRIVATE_IP'], 'PRIVATE_IP='.trim($_POST['ip_private']), file_get_contents(TEMP_FILE)));
        $modification_network = true;
    }
        if (isset($_POST['ip_public']) && (trim($_POST['ip_public']) !== $conf['PUBLIC_IP'])) {
            if (!preg_match($reg_ip_cidr, $_POST['ip_public'])) {
            $ext_conf_error = true;
            $ext_conf_error_list[] = $l_error.': '.$l_ip_address.' WAN: '.$l_error_bad_ip_CIDR;
        }
                file_put_contents(TEMP_FILE, str_replace('PUBLIC_IP='.$conf['PUBLIC_IP'], 'PUBLIC_IP='.trim($_POST['ip_public']), file_get_contents(TEMP_FILE)));
                $modification_network = true;
        }
    if (isset($_POST['ip_gw']) && (trim($_POST['ip_gw']) !== $conf['GW'])) {
        if (!preg_match($reg_ip, $_POST['ip_gw'])) {
            $ext_conf_error = true;
            $ext_conf_error_list[] = $l_error.': '.$l_ip_router.' 1: '.$l_error_bad_ip;
        }
        file_put_contents(TEMP_FILE, str_replace('GW='.$conf['GW'], 'GW='.trim($_POST['ip_gw']), file_get_contents(TEMP_FILE)));
        $modification_network = true;
    }
    if (isset($_POST['enable_proxy']) && $_POST['enable_proxy'] == 'P_Enabled')
    {
        if ($conf['PROXY'] !== 'On')
        {
            file_put_contents(TEMP_FILE, str_replace('PROXY='.$conf['PROXY'], 'PROXY=On', file_get_contents(TEMP_FILE)));
            $modification_proxy = true;
        }
        if (isset($_POST['proxy']) && (trim($_POST['proxy']) !== $conf['PROXY_IP'])) {
            if (!preg_match($reg_ip_port, $_POST['proxy'])) {
                $ext_conf_error = true;
                $ext_conf_error_list[] = $l_error.': Proxy: '.$l_error_bad_ip_port;
            }
            file_put_contents(TEMP_FILE, str_replace('PROXY_IP='.$conf['PROXY_IP'], 'PROXY_IP='.trim($_POST['proxy']), file_get_contents(TEMP_FILE)));
            $modification_proxy = true;
        }
        if ($conf['MULTIWAN'] !== 'off')
        {
            file_put_contents(TEMP_FILE, str_replace('MULTIWAN='.$conf['MULTIWAN'], 'MULTIWAN=off', file_get_contents(TEMP_FILE)));
            $modification_network = true;
        }
    }
    else
    {
        //set multiwan value to off and delete every "WANx=" line
        if ($_POST['gw_count'] === "1" && $conf['MULTIWAN'] !== 'off')
        {
            file_put_contents(TEMP_FILE, str_replace('MULTIWAN='.$conf['MULTIWAN'], 'MULTIWAN=off', file_get_contents(TEMP_FILE)));
            $temp = 1;
            while (isset($conf['WAN'.$temp]))
            {
                file_put_contents(TEMP_FILE, str_replace('WAN'.$temp.'='.$conf['WAN'.$temp]."\n", '', file_get_contents(TEMP_FILE)));
                $temp++;
            }
            $modification_network = true;
        }
        if ($_POST['gw_count'] !== "1")
        {
            $changed = false;
            //testing the existence of a change in the routing configuration
            exec("grep \"^WAN\" " . CONF_FILE . " | wc -l", $nb_gw);
            if ($_POST['gw_count'] == ($nb_gw[0] + 1))
            {
                if ($_POST['weight'] !== $conf['PUBLIC_WEIGHT']) {
                    $changed = true;
                }
                else {
                    for($i=1;$i<$_POST['gw_count'];$i++)
                    {
                        if( '"'.$_POST['ip_gw_'.$i].','.$_POST['weight_'.$i].'"' != $conf['WAN'.$i])
                        {
                            $changed = true;
                            break;
                        }
                    }
                }
            }
            else
            {
                $changed = true;
            }

            if ($changed == true)
            {
                //deleting all the old lines containing "WANx="
                $temp = 1;
                while (isset($conf['WAN'.$temp]))
                {
                    file_put_contents(TEMP_FILE, str_replace('WAN'.$temp.'='.$conf['WAN'.$temp]."\n", '', file_get_contents(TEMP_FILE)));
                    $temp++;
                }
                //setting back the line "WAN1=" which will be our base
                if (!preg_match($reg_weight, $_POST['weight'])) {
                    $ext_conf_error = true;
                    $ext_conf_error_list[] = $l_error.': '.$l_gw_weight.' 1: '.$l_error_weight;
                }
                file_put_contents(TEMP_FILE, str_replace('PUBLIC_WEIGHT='.$conf['PUBLIC_WEIGHT'], 'PUBLIC_WEIGHT='.(($_POST['weight'] !== '')?$_POST['weight']:1), file_get_contents(TEMP_FILE)));
                //Set Multiwan status
                file_put_contents(TEMP_FILE, str_replace('MULTIWAN='.$conf['MULTIWAN'], "MULTIWAN=on\nWAN1=", file_get_contents(TEMP_FILE)));
                //Adding the correct number of "WANx=" lines, numbered
                for($i=2;$i<$_POST['gw_count'];$i++)
                {
                    file_put_contents(TEMP_FILE, str_replace('WAN'.($i-1).'=', 'WAN'.($i-1)."=\nWAN".$i.'=', file_get_contents(TEMP_FILE)));
                }
                //Adding the content
                for($i=1;$i<$_POST['gw_count'];$i++)
                {
                    if (!preg_match($reg_ip, $_POST['ip_gw_'.$i])) {
                        $ext_conf_error = true;
                        $ext_conf_error_list[] = $l_error.': '.$l_ip_router.' '.($i+1).': '.$l_error_bad_ip;
                    }
                    if (!preg_match($reg_weight, $_POST['weight_'.$i])) {
                        $ext_conf_error = true;
                        $ext_conf_error_list[] = $l_error.': '.$l_gw_weight.' '.($i+1).': '.$l_error_weight;
                    }
                    file_put_contents(TEMP_FILE, str_replace('WAN'.$i.'=', 'WAN'.$i.'="'.$_POST['ip_gw_'.$i].','.(($_POST['weight_'.$i] === "0" || $_POST['weight_'.$i] === "")?"1":$_POST['weight_'.$i]).'"', file_get_contents(TEMP_FILE)));
                }
                $modification_network = true;
            }
        }
        //set proxy value to off
        if ($conf['PROXY'] !== 'Off')
        {
            file_put_contents(TEMP_FILE, str_replace('PROXY='.$conf['PROXY'], 'PROXY=Off', file_get_contents(TEMP_FILE)));
            if($_POST['gw_count'] !== "1" && $conf['MULTIWAN'] !== 'on') {
                file_put_contents(TEMP_FILE, str_replace('MULTIWAN='.$conf['MULTIWAN'], 'MULTIWAN=on', file_get_contents(TEMP_FILE)));
                $modification_network = true;
            }
            $modification_proxy = true;
        }
    }

    //if no errors are detected
    if ($ext_conf_error == false) {
        copy(TEMP_FILE, CONF_FILE);
        //DNS values modification, several services needs to be reloading, reloads the full server.
        if ($modification_dns) {
            exec('sudo /usr/local/bin/alcasar-conf.sh -apply');
        }
        //External network modifications, no service reloading
        if ($modification_network) {
            exec('sudo /usr/local/bin/alcasar-network.sh');
            exec('sudo /usr/local/bin/alcasar-iptables.sh');
        }
        //If only the proxy has been modified, only the firewall needs a change
        else if ($modification_proxy) {
            exec('sudo /usr/local/bin/alcasar-iptables.sh');
        }
    }
    unlink(TEMP_FILE);

        // Read CONF_FILE updated
        $file_conf = fopen(CONF_FILE, 'r');
        if (!$file_conf) {
                exit('Error opening the file '.CONF_FILE);
        }
        while (!feof($file_conf)) {
                $buffer = fgets($file_conf, 4096);
                if ((strpos($buffer, '=') !== false) && (substr($buffer, 0, 1) !== '#')) {
                        $tmp = explode('=', $buffer, 2);
                        $conf[trim($tmp[0])] = trim($tmp[1]);
                }
        }
        fclose($file_conf);
}

// Let's Encrypt actions
if ($choix === 'le_issueCert') {
        // TODO: check ndd & mail format
        $email      = $_POST['email'];
        $domainName = $_POST['domainname'];
        exec('sudo /usr/local/bin/alcasar-letsencrypt.sh --issue --email '.escapeshellarg($email).' --domain '.escapeshellarg($domainName), $output, $exitCode);
        $cmdResponse = implode("<br>\n", $output);
}
if ($choix === 'le_renewCert') {
        if ((isset($_POST['recheck'])) && ((!empty($_POST['recheck'])) || (!empty($_POST['recheck_force'])))) {
                $forceOpt = (!empty($_POST['recheck_force'])) ? ' --force' : '';

                exec('sudo /usr/local/bin/alcasar-letsencrypt.sh --renew' . $forceOpt, $output, $exitCode);

                $cmdResponse = implode("<br>\n", $output);
        } else if ((isset($_POST['cancel'])) && (!empty($_POST['cancel']))) {
                file_put_contents(LETS_ENCRYPT_FILE, preg_replace('/challenge=.*/','challenge=', file_get_contents(LETS_ENCRYPT_FILE)));
                file_put_contents(LETS_ENCRYPT_FILE, preg_replace('/domainRequest=.*/','domainRequest=', file_get_contents(LETS_ENCRYPT_FILE)));
        }
}

// Read Let's Encrypt configuration file
$file_conf_LE = fopen(LETS_ENCRYPT_FILE, 'r');
if (!$file_conf_LE) {
        exit('Error opening the file '.LETS_ENCRYPT_FILE);
}
while (!feof($file_conf_LE)) {
        $buffer = fgets($file_conf_LE, 4096);
        if ((strpos($buffer, '=') !== false) && (substr($buffer, 0, 1) !== '#')) {
                $tmp = explode('=', $buffer, 2);
                $LE_conf[trim($tmp[0])] = trim($tmp[1]);
        }
}
fclose($file_conf_LE);

// Fonction de test de connectivité internet
function internetTest() {
        $host = 'www.google.fr'; # Google Test
        $port = '80';

        if (! $sock = @fsockopen($host, $port, $num, $error, 5)) {
                return false;
        } else {
                fclose($sock);
                return true;
        }
}

$internet_connected = InternetTest();
if ($internet_connected) {
        $ch = curl_init('https://api.ipify.org/');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $internet_publicIP = curl_exec($ch);
        curl_close($ch);
} else {
        $internet_publicIP = '-.-.-.-';
}

// Network interfaces, will be use later for multiple LAN interfaces
$interfacesIgnored = ['lo', 'tun[0-9]*', $conf['INTIF']];
exec("ip -o link show | awk -F': ' '{print $2}' | sed '/^" . implode('\\|', $interfacesIgnored) . "$/d'", $interfacesAvailable);

//retreive gateway(s) parameters
$gateways = [
        (object) [
                'gateway'   => $conf['GW'],
        'weight'    => $conf['PUBLIC_WEIGHT']
        ]
];
exec("grep \"^WAN\" " . CONF_FILE . " | wc -l", $nbIfaces);
if ($nbIfaces > 0)
{
    for ($i = 1; $i <= $nbIfaces[0]; $i++) {
        exec("grep \"WAN" . $i . "=\" " . CONF_FILE . " | awk -F'\"' '{ print $2 }' | awk -F, '{ print $1 }'", $temp_gw);
        exec("grep \"WAN" . $i . "=\" " . CONF_FILE . " | awk -F'\"' '{ print $2 }' | awk -F, '{ print $2 }'", $temp_weight);
        $gateways[] = (object) [
            'gateway'   => $temp_gw[0],
            'weight'    => $temp_weight[0]
        ];
        $temp_gw = "";
        $temp_weight = "";
    }
}

//retreive internal networks parameters
$internalNetworks = [
        (object) [
                'interface' => $conf['INTIF'],
                'ip'        => $conf['PRIVATE_IP']
        ]
];

?>
<!DOCTYPE HTML>
<html>
<head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title><?= $l_network_title ?></title>
        <link rel="stylesheet" href="/css/acc.css" type="text/css">
        <script src="/js/jquery.min.js"></script>
        <script src="/js/jquery.connections.js"></script>
        <script type="text/javascript">
        function MAC_Control(formulaire){
                // MAC control (upper case and '-' separator)
                var regex_mac = /^([0-9a-fA-F]{2}(-|:)){5}[0-9a-fA-F]{2}$/;
                if (regex_mac.test(document.forms[formulaire].add_mac.value)){
                        document.forms[formulaire].add_mac.value = document.forms[formulaire].add_mac.value.toUpperCase().replace(/:/g, '-');
                        return true;
                } else {
                        alert('Invalid MAC address');
                        return false;
                }
        }
        </script>
        <style>
                .network-configurator {
                        width: 100%;
                }
                .network-configurator > * {
                        display: inline-block;
                        vertical-align: top;
                        text-align: center;
                }
                .network-configurator > .internet, .network-configurator > .alcasar {
                        width: 20%;
                }
                .network-configurator > .externals, .network-configurator > .internals {
                        width: 30%;
                }
                .network-configurator .actions {
            position: absolute;
                        background-color: #ddd;
                        padding: 0 2px;
                }
                .network-configurator .actions a {
                        text-decoration: none;
                }
                .network-configurator .actions a:hover {
                        font-weight: bold;
                }
                .network-configurator .actions-externals {
                        right: 0;
                        border-radius: 5px;
            position: relative;
            text-decoration: none;
                }
                .network-configurator > .alcasar .actions-internals {
                        bottom: 0;
                        right: 0;
                        border-radius: 5px 0;
                }
                .network-configurator .actions-network {
                        right: 0;
                        border-radius: 5px;
            position: relative;
            text-decoration: none;
                }
                .network-configurator .network-box {
                        display: inline-block;
                        min-height: 100px;
                        margin: 5px;
                        padding: 3px;
                        text-align: left;
                        background-color: #f7f3ef;
                        position: relative;
                        border-radius: 5px;
                        border: 2px solid grey;
                }
                .network-configurator .network-connector {
                        display: inline-block;
                        position: absolute;
                        top: 50%;
                        margin-top: -5px;
                        margin-left: -5px;
                        width: 10px;
                        height: 10px;
                        border-radius: 5px;
                        background-color: black;
                }
                .network-configurator .network-connector[data-connector-direction="left"] {
                        border-radius: 5px 0 0 5px;
                }
                .network-configurator .network-connector[data-connector-direction="right"] {
                        border-radius: 0 5px 5px 0;
                }
                .network-configurator div[data-network-type] {
                        position: relative;
                }
        </style>
        <script>
        $(document).ready(function () {

        setTimeout(function(){$("#change_success").fadeOut('normal');}, 10000);

            //Will be used later for multiple LAN interfaces
                let interfacesAvailable = <?= ((!empty($interfacesAvailable)) ? "['".implode("', '", $interfacesAvailable)."']" : '[]') ?>;
                const wireStyles = { available: { border: '5px double green' } };

                // Add gateway
                $('.network-configurator').on('click', '.add-external-network', function (event) {
                        event.preventDefault();
                        ifaces_count = parseInt(document.getElementById("gw_count").getAttribute('value'));
                        $('.network-configurator .externals .network-box #ext_gateways').append(' \
                                    <div id="ip_routeur_' + ifaces_count + '" data-info_type="gateway" data-number="'+ ifaces_count +'">\
                        <label for="ext_gateway_' + ifaces_count + '"><?= $l_ip_router.' ' ?></label><span class="gw_number">'+ (ifaces_count + 1) +'</span> <input style="width:100px" type="text" name="ip_gw_' + ifaces_count + '" id="ext_gateway_' + ifaces_count + '" value="" /> \
                        <label for="ext_weight_'+ ifaces_count +'"><?= $l_gw_weight ?></label> <input style="width:20px" type="text" name="weight_' + ifaces_count + '" id="ext_weight_'+ ifaces_count +'" value="0"/> \
                        <div class="actions actions-network" style="display:inline-block; width:11px"><a href="#" style="display:block; text-align:center" class="remove-network" title="Supprimer ce réseau">-</a></div><br></div> ');
            ifaces_count++;
            document.getElementById("gw_count").setAttribute('value', ifaces_count);
            updateGatewayView();
            $('div.network-connector[data-connector-network]').connections('update');
                });

                // Add internal network
                $('.network-configurator').on('click', '.add-internal-network', function (event) {
                        event.preventDefault();
                        $('.network-configurator .internals').append(' \
                                        <div data-network-type="internal"> \
                                                <div class="network-connector" data-connector-network="internal" data-connector-direction="left"></div> \
                                                <div class="network-box"> \
                                                        <div class="actions actions-network"><a href="#" class="remove-network" title="Supprimer ce réseau">-</a></div> \
                                                        <label for="int_interface_X"><?= 'Interface' ?></label> <select name="interface" id="int_interface_X" disabled><option value=""></option></select><br> \
                                                        <label for="int_ip_X"><?= $l_ip_address ?></label> <input style="width:150px" type="text" name="ip_private" id="int_ip_X" value="" /><br> \
                                                </div> \
                                        </div>');
                        addWire($('div[data-network-type="internal"]:last'));
                });

                // Remove gateway
                $('.network-box').on('click', '.remove-network', function (event) {
                        event.preventDefault();
                        $(this).parent().parent().fadeOut(200, function() {

                            $(this).remove();
                                //update network numbers
                $('div[data-info_type="gateway"]').each(function (index, value) {
                    updateGatewayNumbers($(this), index);
                });
                ifaces_count = parseInt(document.getElementById("gw_count").getAttribute('value'));
                document.getElementById("gw_count").setAttribute('value', (ifaces_count - 1));
                updateGatewayView();

                $('div.network-connector[data-connector-network]').connections('update');
                        });
                });

                //proxy enabled or disabled
                $('.network-configurator').on('click', '.enable_proxy', function(event){
                    if ($(this).is(':checked'))
            {
                document.getElementById("add_external").setAttribute('hidden', 'true');
                document.getElementById("ext_proxy").removeAttribute('disabled');
                $('div[id="ip_routeur_0"]').children('span').html('');
                $('div[data-info_type="gateway"]').each(function(index, value) {
                    if ($(this).attr('data-number') !== "0")
                    {
                        $(this).attr('hidden', 'true');
                    }
                    else
                    {
                        $(this).children('input[id="ext_weight_0"]').attr('hidden', 'true');
                        $(this).children('label[for="ext_weight_0"]').attr('hidden', 'true');
                        $(this).children('div[class="actions actions-network"]').css('display', 'none');
                    }
                });
            }
            else
            {
                document.getElementById("add_external").removeAttribute('hidden');
                document.getElementById("ext_proxy").setAttribute('disabled', 'true');
                $('div[id="ip_routeur_0"]').children('span').html('1');
                $('div[data-info_type="gateway"]').each(function(index, value) {
                    if ($(this).attr('data-number') !== "0")
                    {
                        $(this).removeAttr('hidden');
                    }
                    else
                    {
                        $(this).children('input[id="ext_weight_0"]').removeAttr('hidden');
                        $(this).children('label[for="ext_weight_0"]').removeAttr('hidden');
                        $(this).children('div[class="actions actions-network"]').css('display', 'inline-block');
                    }
                });
                updateGatewayView();
            }
            $('div.network-connector[data-connector-network]').connections('update');
        });

                //Add a wire between two connectors
                const addWire = function (network) {
                        const networkType = network.data('networkType');
                        if (networkType === 'external') {
                $().connections({ from: 'div[data-network-type="internet"]>div.network-connector[data-connector-network="internet"]', to: network.children('div.network-connector[data-connector-network="internet"]'), css: wireStyles.available, within: network });
                $().connections({ from: 'div[data-network-type="alcasar"]>div.network-connector[data-connector-network="external"]', to: network.children('div.network-connector[data-connector-network="external"]'), css: wireStyles.available, within: network });
            } else if (networkType === 'internal') {
                                $().connections({ from: 'div[data-network-type="alcasar"]>div.network-connector[data-connector-network="internal"]', to: network.children('div.network-connector[data-connector-network="internal"]'), css: wireStyles.available, within: network });
                        }
                };

                //reindex the gateway numbers when a gateway is deleted
                const updateGatewayNumbers = function(gateway, number) {
                    old_number = gateway.attr('data-number');
            gateway.attr('data-number', number);
            gateway.attr('id', 'ip_routeur_'+number);
            if (number === 0)
            {
                gateway.children('input[id="ext_gateway_'+old_number+'"]').attr('name', 'ip_gw');
                gateway.children('input[id="ext_weight_'+old_number+'"]').attr('name', 'weight');
            }
            else
            {
                gateway.children('input[id="ext_gateway_'+old_number+'"]').attr('name', 'ip_gw_'+number);
                gateway.children('input[id="ext_weight_'+old_number+'"]').attr('name', 'weight_'+number);
            }
            gateway.children('label[for="ext_gateway_'+old_number+'"]').attr('for', 'ext_gateway_'+number);
            gateway.children('input[id="ext_gateway_'+old_number+'"]').attr('id', 'ext_gateway_'+number);
            gateway.children('label[for="ext_weight_'+old_number+'"]').attr('for', 'ext_weight_'+number);
            gateway.children('input[id="ext_weight_'+old_number+'"]').attr('id', 'ext_weight_'+number);
            gateway.children('span[class="gw_number"]').html((number+1)+' ');

        };

                //hide the delete button and the weight field when there is only one gateway (or when there is a proxy)
                const updateGatewayView = function() {
            ifaces_count = parseInt(document.getElementById("gw_count").getAttribute('value'));
            if (ifaces_count === 1)
            {
                $('div#ip_routeur_0').children('input[id="ext_weight_0"]').attr('hidden', 'true');
                $('div#ip_routeur_0').children('label[for="ext_weight_0"]').attr('hidden', 'true');
                $('div#ip_routeur_0').children('div[class="actions actions-network"]').css('display', 'none');
            }
            else
            {
                $('div#ip_routeur_0').children('input[id="ext_weight_0"]').removeAttr('hidden');
                $('div#ip_routeur_0').children('label[for="ext_weight_0"]').removeAttr('hidden');
                $('div#ip_routeur_0').children('div[class="actions actions-network"]').css('display', 'inline-block');
            }
        };

                //resize the connections to fit the window
                window.addEventListener('resize', function () {
                        $('div.network-connector[data-connector-network]').connections('update');
                });

                // Add wires to existing networks at page first render
                $('div[data-network-type="external"]').add('div[data-network-type="internal"]').each(function (index, element) {
                        addWire($(this));
                });
        });
        </script>
</head>
<body>
<div id="ldoverlay" class="overlay">
        <div class="lds-spinner" id="spinner"><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div></div>
</div>
<div class="panel">
        <div class="panel-header"><?= $l_network_title ?></div>
        <div class="panel-row">
                <form action="<?= htmlspecialchars($_SERVER['PHP_SELF']) ?>" method="post">
                        <div class="network-configurator">
                                <div class="internet">
                                        <div data-network-type="internet">
                                                <div class="network-box">
                                                        <?= $l_internet_legend ?> <img src="/images/state_<?= (($internet_connected) ? 'ok' : 'error') ?>.gif"><br>
                                                        <?= $l_ip_public ?> : <?= $internet_publicIP ?><br>
                                                        <label for="dns1"><?= $l_ip_dns1 ?></label> : <input style="width:120px" type="text" id="dns1" name="dns1" value="<?= $conf['DNS1'] ?>" /><br>
                                                        <label for="dns2"><?= $l_ip_dns2 ?></label> : <input style="width:120px" type="text" id="dns2" name="dns2" value="<?= $conf['DNS2'] ?>" />
                                                </div>
                                                <div class="network-connector" data-connector-network="internet" data-connector-direction="right"></div>
                                        </div>
                                </div><div id="externals_id" class="externals">
                                                <div data-network-type="external">
                                                        <div class="network-connector" data-connector-network="internet" data-connector-direction="left"></div>
                                                        <div class="network-box">
                                                                <label for="ext_interface">Interface</label> <input name="ext_interface" id="ext_interface" value="<?= $conf['EXTIF'] ?>" disabled="disabled"/><br>
                                                                <label for="ext_ip"><?= $l_ip_address ?></label> <input style="width:130px" type="text" name="ip_public" id="ext_ip" value="<?= $conf['PUBLIC_IP'] ?>" /><br>
                                <input class="enable_proxy" type="checkbox" name="enable_proxy" value="P_Enabled" <?php if($conf['PROXY'] === 'on' || $conf['PROXY'] === 'On') { echo 'checked'; }?>/>
                                <label for="proxy">Proxy</label> <input style="width:140px" type="text" name="proxy" id="ext_proxy" value=<?= $conf['PROXY_IP']?> <?php echo ($conf['PROXY'] === 'on' || $conf['PROXY'] === 'On')? '' : 'disabled'?>/><br>
                                <div id="ext_gateways" >
                                    <input type="text" name="gw_count" id="gw_count" value="<?=count($gateways)?>" hidden="hidden"/>
                                    <?php foreach ($gateways as $index => $network):
                                        if ($index == 0) {?>
                                            <div id="ip_routeur_<?= $index ?>" data-info_type="gateway" data-number="<?= $index ?>">
                                                <label for="ext_gateway_<?= $index ?>"><?= $l_ip_router.' ' ?></label>
                                                <span class="gw_number"><?= ($conf['PROXY'] === 'on' || $conf['PROXY'] === 'On')?'':($index+1) ?> </span>
                                                <input style="width:100px" type="text" name="ip_gw" id="ext_gateway_<?= $index ?>" value="<?= $network->gateway ?>" />
                                                <label for="ext_weight_<?= $index ?>" <?php echo ($conf['PROXY'] === 'on' || $conf['PROXY'] === 'On'|| $conf['MULTIWAN'] === 'Off' || $conf['MULTIWAN'] === 'off')? 'hidden' : '' ?>><?= $l_gw_weight ?></label>
                                                <input style="width:20px" type="text" name="weight" id="ext_weight_<?= $index ?>" value="<?= $network->weight ?>" <?php echo ($conf['PROXY'] === 'on' || $conf['PROXY'] === 'On' || $conf['MULTIWAN'] === 'Off' || $conf['MULTIWAN'] === 'off')? 'hidden' : '' ?>/>
                                                <div class="actions actions-network" style="display: <?php echo ($conf['PROXY'] === 'on' || $conf['PROXY'] === 'On'|| $conf['MULTIWAN'] === 'Off' || $conf['MULTIWAN'] === 'off')? 'none' : 'inline-block' ?>; width:11px">
                                                    <a style="display:block; text-align:center" href="#" class="remove-network" title="Supprimer ce réseau">-</a>
                                                </div><br>
                                            </div>
                                        <?php } else {?>
                                            <div id="ip_routeur_<?= $index ?>" data-info_type="gateway" data-number="<?= $index ?>" <?php echo ($conf['PROXY'] === 'on' || $conf['PROXY'] === 'On')? 'hidden' : '' ?>>
                                                <label for="ext_gateway_<?= $index ?>"><?= $l_ip_router.' ' ?></label>
                                                <span class="gw_number"><?= ($index+1) ?> </span>
                                                <input style="width:100px" type="text" name="ip_gw_<?= $index ?>" id="ext_gateway_<?= $index ?>" value="<?= $network->gateway ?>"/>
                                                <label for="ext_weight_<?= $index ?>"><?= $l_gw_weight ?></label>
                                                <input style="width:20px" type="text" name="weight_<?= $index ?>" id="ext_weight_<?= $index ?>" value="<?= $network->weight ?>"/>
                                                <div class="actions actions-network" style="display:inline-block; width:11px">
                                                    <a style="display:block; text-align:center" href="#" class="remove-network" title="Supprimer ce réseau">-</a>
                                                </div><br>
                                            </div>
                                    <?php } endforeach; ?>
                                </div>
                                <div class="actions actions-externals" style="margin: 0 auto; width:11px"><a id="add_external" href="#" class="add-external-network" title="Ajouter un réseau externe" <?php echo ($conf['PROXY'] === 'on' || $conf['PROXY'] === 'On')? 'hidden' : '' ?>>+</a></div>
                            </div>
                                                        <div class="network-connector" data-connector-network="external" data-connector-direction="right"></div>
                                                </div>
                                </div><div class="alcasar">
                                        <div data-network-type="alcasar">
                                                <div class="network-connector" data-connector-network="external" data-connector-direction="left"></div>
                                                <div class="network-box">
                                                        <div class="alcasar-logo"><img src="/images/logo-alcasar.png" style="width: 100px;height: 100px;"></div>
                                                        <!-- <div class="actions actions-internals">
                                                                <div><a href="#" class="add-internal-network" title="Ajouter un réseau interne">+</a></div>
                                                                <div><a href="#" class="add-internal-wifi-network">++</a></div>
                                                        </div> -->
                                                </div>
                                                <div class="network-connector" data-connector-network="internal" data-connector-direction="right"></div>
                                        </div>
                                </div><div id="internals_id" class="internals" data-count="1">
                                        <?php foreach ($internalNetworks as $network): ?>
                                                <div data-network-type="internal">
                                                        <div class="network-connector" data-connector-network="internal" data-connector-direction="left"></div>
                                                        <div class="network-box">
                                                                <!-- <div class="actions actions-network"><a href="#" class="remove-network" title="Supprimer ce réseau">-</a></div> -->
                                                                <label for="int_interface_<?= $index ?>"><?= 'Interface' ?></label> <select name="int_interface[<?= $index ?>]" id="int_interface_<?= $index ?>" disabled><option value="<?= $network->interface ?>"><?= $network->interface ?></option></select><br>
                                                                <label for="int_ip_<?= $index ?>"><?= $l_ip_address ?></label> <input style="width:150px" type="text" name="ip_private" id="int_ip_<?= $index ?>" value="<?= $network->ip ?>" /><br>
                                                        </div>
                                                </div>
                                        <? endforeach; ?>
                                </div>
                        </div>
            <?php if ($ext_conf_error == true) {
                echo '<span style="color:red">';
                $temp = 0;
                while (isset($ext_conf_error_list[$temp])) {
                    echo $ext_conf_error_list[$temp].'<br>';
                    $temp++;
                }
                echo '</span>';
            }
            else if (($choix === 'network_change') && ($modification_proxy || $modification_dns || $modification_network)) {
                echo '<span id="change_success" style="color:green">'.$l_change_successful.'</span>';
            }?>
                        <hr>
                        <div style="text-align: center; margin: 5px">
                                <input type="hidden" name="choix" value="network_change">
                                <input type="submit" onClick="document.getElementById('ldoverlay').style.display='block';" value="<?= $l_apply ?>">
                        </div>
                </form>
        </div>
</div>
<br>
<div class="panel">
        <div class="panel-header"><?= $l_static_dhcp_title ?></div>
</div>
<table width="100%" cellspacing="0" cellpadding="5" border="1">
        <tr><td width="50%" align="center" valign="middle">
                <form action="network.php" method="POST">
                <table cellspacing="2" cellpadding="3" border="1">
                <tr><th><?= $l_mac_address ?></th><th><?= $l_ip_address ?></th><th>Info<th><?= $l_del ?></th></tr>
                <?php
                // Read the "ether" file
                exec('sudo /sbin/ip link show '.escapeshellarg($conf["INTIF"]), $output);
                $detail = explode(' ', $output[1]);
                $intif_mac_addr = strtoupper(str_replace(':', '-', $detail[5]));
                unset($output); unset($detail);
                $line_exist = false;
                $tab = file(ETHERS_INFO_FILE);
                if ($tab) { // le fichier n'est pas vide
                        foreach ($tab as $line) {
                                $fields = explode(' ', $line);
                                $mac_addr = $fields[0];
                                $ip_addr  = $fields[1];
                                $info     = (isset($fields[2])) ? implode(' ', array_slice($fields, 2)) : ' ';

                                echo '<tr>';
                                echo "<td>$mac_addr</td>";
                                echo "<td>$ip_addr</td>";
                                if ($mac_addr !== $intif_mac_addr) {
                                        echo '<td>'.ltrim($info, '#').'</td>';
                                        echo "<td><input type=\"checkbox\" name=\"$mac_addr\"></td>";
                                        $line_exist=True;
                                } else {
                                        echo '<td>ALCASAR</td>';
                                        echo '<td></td>';
                                }
                                echo '</tr>';
                        }
                }
                ?>
                </table>
                <?php if ($line_exist): ?>
                        <input type="hidden" name="choix" value="del_mac">
                        <input type="submit" onClick="document.getElementById('ldoverlay').style.display='block';" value="<?= $l_apply ?>">
                <?php endif; ?>
                </form>
        </td><td width="50%" valign="middle" align="center">
                <form name="new_mac" action="network.php" method="POST">
                        <table cellspacing="2" cellpadding="3" border="1">
                                <tr><th><?= $l_mac_address ?></th><th><?= $l_ip_address ?></th><th>Info</th><td></td></tr>
                                <tr><td>Ex. : 12-2F-36-A4-DF-43</td><td>Ex. : 192.168.182.10</td><td>Ex. : Switch<td></td></tr>
                                <tr><td><input type="text" name="add_mac" size="17"></td>
                                <td><input type="text" name="add_ip" size="10"></td>
                                <td><input type="text" name="info" size="10"></td>
                                <td>
                                        <input type="hidden" name="choix" value="new_mac">
                                        <input type="submit" onClick="document.getElementById('ldoverlay').style.display='block';" class="button" value="<?= $l_add_to_list ?>" onclick="return MAC_Control('new_mac');">
                                </td>
                        </tr></table>
                </form>
        </td></tr>
</table>
<br>
<div class="panel">
        <div class="panel-header"><?= $l_local_dns ?></div>
</div>
<table width="100%" cellspacing="0" cellpadding="5" border="1">
        <tr>
                <td width="50%" align="center">
                        <form action="<?= htmlspecialchars($_SERVER['PHP_SELF']) ?>" method="POST">
                        <table cellspacing="2" cellpadding="3" border="1">
                        <tr><th><?= $l_ip_address ?></th><th><?= $l_host_name ?></th><th><?= $l_del ?></th></tr>
                        <?php
                        // Read the "dns_local" file
                        $line_exist = false;
                        $tab = file(DNS_LOCAL_FILE);
                        if ($tab) { // not empty
                                foreach ($tab as $line) {
                                        if (preg_match ('/^\d+/', $line)) { # begin with one or several digit
                                                $line_exist = true;
                                                $field = preg_split("/\s+/",$line); # split with one or several whitespace (or tab)
                                                $ip_addr   = $field[0];
                                                $host_name = $field[1];
                                                echo "<tr><td>$ip_addr</td>";
                                                echo "<td>$host_name</td>";
                                                if (($ip_addr == "127.0.0.1")|($host_name == "alcasar")) {
                                                        echo "<td>";}
                                                else {
                                                        echo "<td><input type=\"checkbox\" name=\"$ip_addr|$host_name\">";
                                                }
                                                echo "</td></tr>";
                                        }
                                }
                        }
                        if (!$line_exist) {
                                echo '<tr><td colspan="3" style="text-align: center;font-style: italic;">'.$l_empty.'</td></tr>';
                        }
                        ?>
                        </table>
                        <?php if ($line_exist): ?>
                                <input type="hidden" name="choix" value="del_host">
                                <input type="submit" onClick="document.getElementById('ldoverlay').style.display='block';" value="<?= $l_apply ?>">
                        <?php endif; ?>
                        </form>
                </td>
                <td width="50%" valign="middle" align="center">
                        <form name="new_host" action="<?= htmlspecialchars($_SERVER['PHP_SELF']) ?>" method="POST">
                        <table cellspacing="2" cellpadding="3" border="1">
                        <tr>
                                <th><?= $l_ip_address ?></th><th><?= $l_host_name ?></th><td></td>
                        </tr>
                        <tr>
                                <td>Ex. : 192.168.182.10</td><td>Ex. : my_nas</td><td></td>
                        </tr>
                        <tr>
                                <td><input type="text" name="add_ip" size="10"><input type="hidden" name="choix" value="new_host"></td>
                                <td><input type="text" name="add_host" size="17"></td>
                                <td><input type="submit" onClick="document.getElementById('ldoverlay').style.display='block';" class="button" value="<?= $l_add_to_list ?>"></td>
                        </tr>
                        </table>
                        </form>
                </td>
        </tr>
</table>
<br>
<div class="panel">
        <div class="panel-header"><?= $l_ssl_title ?></div>
        <div class="panel-row">
                <form method="post" action="<?= htmlspecialchars($_SERVER['PHP_SELF']) ?>">
                        <input type="hidden" name="choix" value="https_login">
                        <input type="checkbox" name="https_login" id="https_login" <?= ($conf['HTTPS_LOGIN'] === 'on')? "checked": "" ?>><b><?= $l_ssl_title ?></b><br>
                        <input type="submit" onClick="document.getElementById('ldoverlay').style.display='block';" value="<?= $l_apply ?>"><br>
                </form>
        </div>
</div>
<br>
<div class="panel">
        <div class="panel-header"><?= $l_ssh_title ?></div>
        <table width="100%" cellspacing="0" cellpadding="5" border="1">
        <tr>
                <td width="50%" align="center">
                        <div class="panel-row">
                                <form method="post" action="<?= htmlspecialchars($_SERVER['PHP_SELF']) ?>">
                                        <input type="hidden" name="choix" value="enable_lan_ssh">
                                        <input type="checkbox" name="sshlan" id="sshlan" <?= $conf['SSH_LAN'] !== '0' ? "checked": "" ?> onchange="document.getElementById('sshtablelan').style.display = this.checked ? 'block' : 'none';"> <b><?= $l_ssh_lan_activate ?></b><br><br>
                                        <div id="sshtablelan" style="display:<?= $conf['SSH_LAN'] !== '0'? "block": "none" ?>">
                                        <table cellspacing="2" cellpadding="3" border="1">
                                                <tr>
                                                        <th><?= $l_ssh_port ?></th><th><?= $l_ssh_from ?></th>
                                                </tr>
                                                <tr>
                                                        <td><input style="width:120px" type="text" id="ssh_port" name="ssh_port" value="<?= $conf['SSH_LAN'] !== '0' ? $conf['SSH_LAN']:22 ?>" /></td>
                                                        <td><input style="width:120px" type="text" id="ssh_from" name="ssh_from" value="<?= explode('/',$conf['SSH_ADMIN_FROM'])[0] ?>" /></td>         
                                                </tr>
                                        </table>
                                        <p>Activer sur tout le LAN : 0.0.0.0</p>
                                </div>
                                        <input type="submit" onClick="document.getElementById('ldoverlay').style.display='block';" value="<?= $l_apply ?>"><br>
                                </form>
                        </div>
                </td>
                <td width="50%" align="center">
                        <div class="panel-row">
                                <form method="post" action="<?= htmlspecialchars($_SERVER['PHP_SELF']) ?>">
                                <input type="hidden" name="choix" value="enable_wan_ssh">
                                <input type="checkbox" name="togglessh" id="togglessh" <?= $conf['SSH_WAN'] !== '0'? "checked": "" ?> onchange="document.getElementById('sshtablewan').style.display = this.checked ? 'block' : 'none';"> <b><?= $l_ssh_wan_activate ?></b><br><br>
                                <div id="sshtablewan" style="display:<?= $conf['SSH_WAN'] !== '0'? "block": "none" ?>">
                                        <table cellspacing="2" cellpadding="3" border="1">
                                                <tr>
                                                        <th><?= $l_ssh_port ?></th><th><?= $l_ssh_from ?></th>
                                                </tr>
                                                <tr>
                                                        <td><input style="width:120px" type="text" id="ssh_port" name="ssh_port" value="<?= $conf['SSH_WAN'] !== '0' ? $conf['SSH_WAN']:22 ?>" /></td>
                                                        <td><input style="width:120px" type="text" id="ssh_from" name="ssh_from" value="<?= explode('/',$conf['SSH_ADMIN_FROM'])[1] ?>" /></td>         
                                                </tr>
                                        </table>
                                        <p>Activer sur tout réseau : 0.0.0.0</p>
                                </div>
                                <input type="submit" onClick="document.getElementById('ldoverlay').style.display='block';" value="<?= $l_apply ?>"><br>
                                </form>
                        </div>
                </td>
        </tr>
        </table>
</div>
<br>
<div class="panel">
        <div class="panel-header"><?= $l_import_cert ?></div>
        <div class="panel-row">
                <div class="panel-cell">
                        <?php
                        $certificateInfos = openssl_x509_parse(file_get_contents('/etc/pki/tls/certs/alcasar.crt'));
                        $cert_expiration_date = date('d-m-Y H:i:s', $certificateInfos['validTo_time_t']);
                        $domain               = $certificateInfos['subject']['CN'];
                        $organization         = (isset($certificateInfos['subject']['O'])) ? $certificateInfos['subject']['O'] : '';
                        $CAdomain             = $certificateInfos['issuer']['CN'];
                        $CAorganization       = (isset($certificateInfos['issuer']['O'])) ? $certificateInfos['issuer']['O'] : '';
                        ?>
                        <h3><?= $l_current_certificate ?></h3>
                        <b><?= $l_cert_commonname ?></b> <?= $domain ?><br>
                        <b><?= $l_cert_expiration ?></b> <?= $cert_expiration_date ?><br>
                        <b><?= $l_cert_organization ?></b> <?= $organization ?><br>
                        <b><?= $l_validated ?></b> <?= $CAdomain ?> (<?= $CAorganization ?>)<br>
                </div>
                <div class="panel-cell">
                        <?
                        if (file_exists('/etc/pki/tls/certs/alcasar.crt.old') && file_exists('/etc/pki/tls/private/alcasar.key.old')){ // An old default certificate exist ?
                                echo "<form method=\"post\" action=\"".htmlspecialchars($_SERVER['PHP_SELF'])."\">\n";
                                echo "\t\t\t\t<input type=\"hidden\" name=\"choix\" value=\"set_default_cert\">\n";
                                echo "\t\t\t\t<input type=\"submit\" onClick=\"document.getElementById('ldoverlay').style.display='block';\" value=\"$l_default_cert\"> (alcasar.localdomain)<br>\n";
                                echo "\t\t\t</form>\n";}
                        if (!empty($LE_conf['domainRequest']) && ($domain != $LE_conf['domainRequest'])) { // A Let's encrypt certificate exist & it's not the active one ?
                                echo "\t\t\t<form method=\"post\" action=\"".htmlspecialchars($_SERVER['PHP_SELF'])."\">\n";
                                echo "\t\t\t\t<input type=\"hidden\" name=\"choix\" value=\"set_last_LE_cert\">\n";
                                echo "\t\t\t\t<input type=\"submit\" onClick=\"document.getElementById('ldoverlay').style.display='block';\" value=\"".$l_previous_LE_cert."\"> (".$LE_conf['domainRequest'].")\n";
                                echo "\t\t\t</form>\n";}
                        ?>
                </div>
        </div>
        <div class="panel-row">
                <div class="panel-cell">
                        <h3><?= $l_upload_certificate ?></h3>
                        <form method="post" action="<?= htmlspecialchars($_SERVER['PHP_SELF']) ?>" enctype="multipart/form-data">
                                <?= $l_private_key;?> <input type="file" name="key"><br>
                                <?= $l_certificate;?> <input type="file" name="crt"><br>
                                <?= $l_server_chain;?> <input type="file" name="sc"><br>
                                <input type="hidden" name="choix" value="import_cert">
                                <input type="submit" onClick="document.getElementById('ldoverlay').style.display='block';" value="<?= $l_import ?>">
                        </form>
                </div>
                <div class="panel-cell">
                        <?php
                        // Get step
                        if (empty($LE_conf['domainRequest'])) {
                                $step = 1;
                        } else if (!empty($LE_conf['challenge'])) {
                                $step = 2;
                        } else if (($domain === $LE_conf['domainRequest']) && (empty($LE_conf['challenge']))) {
                                $step = 3;
                        } else {
                                $step = 1;
                        }
                        ?>
                        <h3><?= $l_le_integration ?></h3>
                        <?php if ($step === 1): ?>
                                <form method="post" action="<?= htmlspecialchars($_SERVER['PHP_SELF']) ?>">
                                        <input type="hidden" name="choix" value="le_issueCert">
                                        <?= $l_le_status ?> <?= $l_disabled ?><br>
                                        <?= $l_le_email ?> <input type="text" name="email" placeholder="adresse@email.com"<?= ((!empty($LE_conf['email'])) ? ' value="'.$LE_conf['email'].'"' : '') ?>><br>
                                        <?= $l_le_domain_name ?> <input type="text" name="domainname" placeholder="alcasar.domain.tld" required><br>
                                        <input type="submit" onClick="document.getElementById('ldoverlay').style.display='block';" name="issue" value="<?= $l_send ?>"><br>
                                </form>
                        <?php elseif ($step === 2): ?>
                                <form method="post" action="<?= htmlspecialchars($_SERVER['PHP_SELF']) ?>">
                                        <input type="hidden" name="choix" value="le_renewCert">
                                        <?= $l_le_status ?> <?= $l_pending_validation ?><br>
                                        <?= $l_le_domain_name ?> <?= $LE_conf['domainRequest'] ?><br>
                                        <?= $l_le_ask_on ?> <?= date('d-m-Y H:i:s', $LE_conf['dateIssueRequest']) ?><br>
                                        <?= $l_le_dns_entry_txt ?> "<?= '_acme-challenge.'.$LE_conf['domainRequest'] ?>"<br>
                                        <?= $l_le_challenge ?> "<?= $LE_conf['challenge'] ?>"<br>
                                        <input type="submit" onClick="document.getElementById('ldoverlay').style.display='block';" name="recheck" value="<?= $l_recheck ?>"> <input type="submit" onClick="document.getElementById('ldoverlay').style.display='block';" name="cancel" value="<?= $l_cancel ?>"><br>
                                </form>
                        <?php elseif ($step === 3): ?>
                                <form method="post" action="<?= htmlspecialchars($_SERVER['PHP_SELF']) ?>">
                                        <input type="hidden" name="choix" value="le_renewCert">
                                        <?= $l_le_status ?> <?= $l_enabled ?><br>
                                        <?= $l_le_domain_name ?> <?= $LE_conf['domainRequest'] ?><br>
                                        <?= $l_le_api ?>  <?= $LE_conf['dnsapi'] ?><br>
                                        <?= $l_le_next_renewal ?> <?= date('d-m-Y', $LE_conf['dateNextRenewal']) ?><br>
                                        <?php if ($LE_conf['dateNextRenewal'] <= date('U')): ?>
                                                <input type="submit" onClick="document.getElementById('ldoverlay').style.display='block';" name="recheck" value="<?= $l_renew ?>"><br>
                                        <?php else: ?>
                                                <input type="submit" onClick="document.getElementById('ldoverlay').style.display='block';" name="recheck_force" value="<?= $l_renew_force ?>"><br>
                                        <?php endif; ?>
                                </form>
                        <?php endif; ?>
                        <?php if (isset($cmdResponse)): ?>
                                <p><?= $cmdResponse ?></p>
                        <?php endif; ?>
                </div>
        </div>
</div>
</body>
</html>