Subversion Repositories ALCASAR

Rev

Rev 2404 | Rev 2479 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log

<?php
# $Id: network.php 2450 2017-12-05 21:53:42Z tom.houdayer $

// written by steweb57, Rexy & Tom HOUDAYER

/********************
*  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', '/usr/local/etc/alcasar-dns-name');
define('LETS_ENCRYPT_FILE', '/usr/local/etc/alcasar-letsencrypt');
$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') {       // French
        $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";
        $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";
        $l_import_cert          = "Import de certificat";
        $l_private_key          = "Clé privée (.key) :";
        $l_certificate          = "Certificat (.crt) :";
        $l_server_chain         = "Chaîne de certification (si nécéssaire : .crt) :";
        $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_allow_unsecured_login        = "Autoriser les utilisateurs à se connecter de manière non sécurisée (HTTP) :";
        $l_unsecured_login_warning      = "/!\\ Les identifiants de connexion seront envoyés en clair.";
        $l_cert_expiration      = "Date d'expiration :";
        $l_cert_commonname      = "Nom commun :";
        $l_cert_organization    = "Organisation :";
        $l_upload_certificate   = "Importer un certificat";
        $l_le_integration       = "Intégration 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)";
} else {                        // English
        $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";
        $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";
        $l_import_cert          = "Certificate import";
        $l_private_key          = "Private key (.key) :";
        $l_certificate          = "Certificate (.crt) :";
        $l_server_chain         = "Server-chain (if necessary : .crt) :";
        $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_allow_unsecured_login        = "Allow users to login with insecure connection (HTTP):";
        $l_unsecured_login_warning      = "/!\\ Credentials will be sent in plain text.";
        $l_cert_expiration      = "Expiration date:";
        $l_cert_commonname      = "Common name:";
        $l_cert_organization    = "Organization:";
        $l_upload_certificate   = "Importer un certificat";
        $l_le_integration       = "Let's Encrypt integration";
        $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)";
}

$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_mac     = '/^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$/';
$reg_host    = '/^[a-zA-Z0-9-_]+$/';

$choix = (isset($_POST['choix'])) ? $_POST['choix'] : '';

switch ($choix) {
        case 'DHCP_On':
                exec('sudo /usr/local/bin/alcasar-dhcp.sh -on');
                break;
        case 'DHCP_Off':
                exec('sudo /usr/local/bin/alcasar-dhcp.sh -off');
                break;

        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');
                                }
                        }
                }
                break;
        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');
                        }
                }
                break;

        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('/^address/', $line)) {
                                                $field = explode('/', $line);
                                                $host_name = trim($field[1]);
                                                $ip_addr   = trim($field[2]);
                                                if (strcasecmp($add_host, $host_name) === 0) {
                                                        $insert = false;
                                                        break;
                                                }
                                                if (strcmp($add_ip, $ip_addr) === 0) {
                                                        $insert = false;
                                                        break;
                                                }
                                        }
                                }
                                if ($insert) {
                                        $line1 = 'address=/'.$add_host.'/'.$add_ip."\n";
                                        $explode_ip = explode('.', $add_ip);
                                        $reverse_ip = implode('.', array_reverse($explode_ip));
                                        $line2 = 'ptr-record='.$reverse_ip.'.in-addr.arpa,'.$add_host."\n";
                                        $pointeur=fopen(DNS_LOCAL_FILE, 'a');
                                        fwrite($pointeur, $line1);
                                        fwrite($pointeur, $line2);
                                        fclose($pointeur);
                                        exec('sudo /usr/bin/systemctl restart dnsmasq');
                                        exec('sudo /usr/bin/systemctl restart dnsmasq-blacklist');
                                        exec('sudo /usr/bin/systemctl restart dnsmasq-whitelist');
                                }
                        }
                }
                break;
        case 'del_host':
                foreach ($_POST as $key => $value) {
                        if ($value == 'on') {
                                exec('/bin/sed -i '.escapeshellarg("\\@^address=/$key/@d;\\@^ptr-record=.*,$key\$@d").' '.DNS_LOCAL_FILE); 
                                exec('sudo /usr/bin/systemctl restart dnsmasq');
                                exec('sudo /usr/bin/systemctl restart dnsmasq-blacklist');
                                exec('sudo /usr/bin/systemctl restart dnsmasq-whitelist');
                        }
                }
                break;

        case 'default_cert':    // Restore default certificate
                exec('sudo alcasar-importcert.sh -d');
                break;

        case 'import_cert':     // Import certificate
                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') {
                                        $dest = '/tmp/';
                                        $scpath = '';
                                        if (isset($_FILES['sc']) && (pathinfo($_FILES['sc']['name'])['extension'] == 'crt')) {
                                                $scpath = $dest.'server-chain.crt';
                                                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 'https_login':     // Set HTTPS login status
                if ($_POST['https_login'] === 'on') {
                        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') {
        $network_modification = false;

        if (isset($_POST['dns1']) && (trim($_POST['dns1']) !== $conf['DNS1']) && preg_match($reg_ip, $_POST['dns1'])) {
                file_put_contents(CONF_FILE, str_replace('DNS1='.$conf['DNS1'], 'DNS1='.trim($_POST['dns1']), file_get_contents(CONF_FILE)));
                $network_modification = true;
        }
        if (isset($_POST['dns2']) && (trim($_POST['dns2']) !== $conf['DNS2']) && preg_match($reg_ip, $_POST['dns2'])) {
                file_put_contents(CONF_FILE, str_replace('DNS2='.$conf['DNS2'], 'DNS2='.trim($_POST['dns2']), file_get_contents(CONF_FILE)));
                $network_modification = true;
        }
        if (isset($_POST['ip_public']) && (trim($_POST['ip_public']) !== $conf['PUBLIC_IP']) && preg_match($reg_ip_cidr, $_POST['ip_public'])) {
                file_put_contents(CONF_FILE, str_replace('PUBLIC_IP='.$conf['PUBLIC_IP'], 'PUBLIC_IP='.trim($_POST['ip_public']), file_get_contents(CONF_FILE)));
                $network_modification = true;
        }
        if (isset($_POST['ip_gw']) && (trim($_POST['ip_gw']) !== $conf['GW']) && preg_match($reg_ip, $_POST['ip_gw'])) {
                file_put_contents(CONF_FILE, str_replace('GW='.$conf['GW'], 'GW='.trim($_POST['ip_gw']), file_get_contents(CONF_FILE)));
                $network_modification = true;
        }
        if (isset($_POST['ip_private']) && (trim($_POST['ip_private']) !== $conf['PRIVATE_IP']) && preg_match($reg_ip_cidr, $_POST['ip_private'])) {
                file_put_contents(CONF_FILE, str_replace('PRIVATE_IP='.$conf['PRIVATE_IP'], 'PRIVATE_IP='.trim($_POST['ip_private']), file_get_contents(CONF_FILE)));
                $network_modification = true;
        }

        if ($network_modification) {
                exec('sudo /usr/local/bin/alcasar-conf.sh -apply');
        }

        // 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
$interfacesIgnored = ['lo', 'tun[0-9]*', $conf['EXTIF'], $conf['INTIF']];
exec("ip -o link show | awk -F': ' '{print $2}' | sed '/^" . implode('\\|', $interfacesIgnored) . "$/d'", $interfacesAvailable);

// TODO: Pending the next version
$externalNetworks = [
        (object) [
                'interface' => $conf['EXTIF'],
                'ip'        => $conf['PUBLIC_IP'],
                'gateway'   => $conf['GW']
        ]
];
$internalNetworks = [
        (object) [
                'interface' => $conf['INTIF'],
                'ip'        => $conf['PRIVATE_IP']
        ]
];

?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title><?= $l_network_title ?></title>
        <link rel="stylesheet" href="/css/style.css" type="text/css">
        <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 > .alcasar .actions-externals {
                bottom: 0;
                left: 0;
                border-radius: 0 5px;
        }
        .network-configurator > .alcasar .actions-internals {
                bottom: 0;
                right: 0;
                border-radius: 5px 0;
        }
        .network-configurator .actions-network {
                top: 0;
                right: 0;
                border-radius: 0 5px;
        }
        .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 0px 0px 5px;
        }
        .network-configurator .network-connector[data-connector-direction="right"] {
                border-radius: 0px 5px 5px 0px;
        }
        .network-configurator div[data-network-type] {
                position: relative;
        }
        </style>
        <script>
        $(document).ready(function () {
                const interfacesAvailable = <?= ((!empty($interfacesAvailable)) ? "['".implode("', '", $interfacesAvailable)."']" : '[]') ?>;

                const wireStyles = {
                        available: { border: '5px double green' }
                };

                // Add external network
                $('.network-configurator .add-external-network').click(function (event) {
                        event.preventDefault();
                        let options = '';
                        if (interfacesAvailable.length === 0) {
                                options = '<option value=""></option>';
                        } else {
                                for (let i = 0; i < interfacesAvailable.length; i++) {
                                        options += '<option value="' + interfacesAvailable[i] + '">' + interfacesAvailable[i] + '</option>';
                                }
                        }
                        $('.network-configurator .externals').append(' \
                                <div data-network-type="external"> \
                                        <div class="network-connector" data-connector-network="internet" 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="ext_interface_X"><?= 'Interface' ?></label> <select name="interface" id="ext_interface_X">' + options + '</select><br> \
                                                <label for="ext_ip_X"><?= $l_ip_address ?></label> <input style="width:150px" type="text" name="ip_public" id="ext_ip_X" value="" /><br> \
                                                <label for="ext_gateway_X"><?= $l_ip_router ?></label> <input style="width:120px" type="text" name="ip_gw" id="ext_gateway_X" value="" /> \
                                        </div> \
                                        <div class="network-connector" data-connector-network="external" data-connector-direction="right"></div> \
                                </div>');
                        addWire($('div[data-network-type="external"]:last'));
                });

                // Add internal network
                $('.network-configurator .add-internal-network').click(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 network
                $('.network-configurator').on('click', '.remove-network', function (event) {
                        event.preventDefault();
                        $(this).parent().parent().parent().fadeOut(200, function() {
                                const networkType = $(this).data('networkType');
                                $(this).remove();

                                // Update wires
                                if (networkType === 'external') {
                                        $('div[data-network-type="internet"]>div.network-connector[data-connector-network="internet"]').connections('update');
                                        $('div[data-network-type="alcasar"]>div.network-connector[data-connector-network="external"]').connections('update');
                                } else if (networkType === 'internal') {
                                        $('div[data-network-type="alcasar"]>div.network-connector[data-connector-network="internal"]').connections('update');
                                }
                        });
                });

                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: 'div[data-network-type="external"]>div.network-connector[data-connector-network="internet"]:last', css: wireStyles.available, within: 'div[data-network-type="external"]:last' });
                                $().connections({ from: 'div[data-network-type="alcasar"]>div.network-connector[data-connector-network="external"]', to: 'div[data-network-type="external"]>div.network-connector[data-connector-network="external"]:last', css: wireStyles.available, within: 'div[data-network-type="external"]:last' });
                        } else if (networkType === 'internal') {
                                $().connections({ from: 'div[data-network-type="alcasar"]>div.network-connector[data-connector-network="internal"]', to: 'div[data-network-type="internal"]>div.network-connector[data-connector-network="internal"]:last', css: wireStyles.available, within: 'div[data-network-type="internal"]:last' });
                        }
                };

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

                // Add wires to existing networks
                $('div[data-network-type="external"]').add('div[data-network-type="internal"]').each(function (index, element) {
                        addWire($(this));
                });
        });
        </script>
</head>
<body>
        <div class="panel">
                <div class="panel-header"><?= $l_network_title ?></div>
                <div class="panel-body">
                        <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 class="externals">
                                                <?php foreach ($externalNetworks as $index => $network): ?>
                                                        <div data-network-type="external">
                                                                <div class="network-connector" data-connector-network="internet" 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="ext_interface_<?= $index ?>"><?= 'Interface' ?></label> <select name="ext_interface[<?= $index ?>]" id="ext_interface_<?= $index ?>" disabled><option value="<?= $network->interface ?>"><?= $network->interface ?></option></select><br>
                                                                        <label for="ext_ip_<?= $index ?>"><?= $l_ip_address ?></label> <input style="width:150px" type="text" name="ip_public" id="ext_ip_<?= $index ?>" value="<?= $network->ip ?>" /><br>
                                                                        <label for="ext_gateway_<?= $index ?>"><?= $l_ip_router ?></label> <input style="width:120px" type="text" name="ip_gw" id="ext_gateway_<?= $index ?>" value="<?= $network->gateway ?>" />
                                                                </div>
                                                                <div class="network-connector" data-connector-network="external" data-connector-direction="right"></div>
                                                        </div>
                                                <? endforeach; ?>
                                        </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="actions actions-externals">
                                                                        <div><a href="#" class="add-external-network" title="Ajouter un réseau externe">+</a></div>
                                                                </div> -->
                                                                <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 class="internals">
                                                <?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>
                                <hr>
                                <div style="text-align: center; margin: 5px">
                                        <input type="hidden" name="choix" value="network_change">
                                        <input type="submit" value="<?= $l_apply ?>">
                                </div>
                        </form>
                </div>
        </div>
        <br>

<table width="100%" cellspacing="0" cellpadding="0" border="0">
        <tr><th><?= $l_dhcp_title?></th></tr>
        <tr bgcolor="#FFCC66"><td><img src="/images/pix.gif" width="1" height="2"></td></tr>
</table>
<table width="100%" cellspacing="0" cellpadding="5" border="1">
        <tr><td colspan="2" valign="middle" align="left">
        <center><h3><?= $l_dhcp_state ?> : <?= ${'l_DHCP_'.$conf['DHCP']} ?></h3></center>
        <form action="<?= htmlspecialchars($_SERVER['PHP_SELF']) ?>" method="POST">
                <select name="choix">
                        <option value="DHCP_Off"<?= ((!strcmp($conf['DHCP'], 'off')) ? ' selected' : '') ?>><?= $l_DHCP_off ?></option>
                        <option value="DHCP_On"<?= ((!strcmp($conf['DHCP'], 'on')) ? ' selected' : '') ?>><?= $l_DHCP_on ?></option>
                </select>
                <input type="submit" value="<?= $l_apply ?>">
                <br><?= $l_DHCP_off_explain ?>
        </form>
        </td></tr>

        <?php
        if ($conf['DHCP'] === 'on') {
                require('network2.php');
        }
        ?>
</table>
<br>

<table width="100%" cellspacing="0" cellpadding="0" border="0">
        <tr><th><?= $l_local_dns?></th></tr>
        <tr bgcolor="#FFCC66"><td><img src="/images/pix.gif" width="1" height="2"></td></tr>
</table>
<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_host_name ?></th><th><?= $l_ip_address ?></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 ('/^address/', $line)) {
                                        $line_exist = true;
                                        $field = explode('/', $line);
                                        $host_name = $field[1];
                                        $ip_addr   = $field[2];
                                        echo "<tr><td>$host_name</td>";
                                        echo "<td>$ip_addr</td>";
                                        echo "<td><input type=\"checkbox\" name=\"$host_name\"></td>";
                                        echo "</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" 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_host_name ?></th><th><?= $l_ip_address ?></th><td></td>
                </tr>
                <tr>
                        <td>Ex. : my_nas</td><td>Ex. : 192.168.182.10</td><td></td>
                </tr>
                <tr>
                        <td><input type="text" name="add_host" size="17"></td>
                        <td><input type="text" name="add_ip" size="10"><input type="hidden" name="choix" value="new_host"></td>
                        <td><input type=submit class=button value="<?= $l_add_to_list ?>"></td>
                </tr>
                </table>
                </form>
        </td>
</tr>
</table>
<br>

<table width="100%" cellspacing="0" cellpadding="0" border="0">
        <tr><th><?= $l_import_cert ?></th></tr>
        <tr bgcolor="#FFCC66"><td><img src="/images/pix.gif" width="1" height="2"></td></tr>
</table>
<table width="100%" cellspacing="0" cellpadding="5" border="1">
        <tr>
                <td width="50%" valign="top">
                        <form method="post" action="<?= htmlspecialchars($_SERVER['PHP_SELF']) ?>">
                                <input type="hidden" name="choix" value="https_login">
                                <span><?= $l_allow_unsecured_login ?></span><br>
                                <select name="https_login">
                                        <option value="on"<?=  (($conf['HTTPS_LOGIN'] === 'on')  ? ' selected' : '') ?>><?= $l_no ?></option>
                                        <option value="off"<?= (($conf['HTTPS_LOGIN'] === 'off') ? ' selected' : '') ?>><?= $l_yes ?></option>
                                </select>
                                <input type="submit" value="<?= $l_apply ?>"><br>
                                <span><?= $l_unsecured_login_warning ?></span>
                        </form>
                        <br>
                        <form method="post" action="<?= htmlspecialchars($_SERVER['PHP_SELF']) ?>">
                                <input type="hidden" name="choix" value="default_cert">
                                <input type="submit" value="<?= $l_default_cert ?>" <?= (!file_exists('/etc/pki/tls/certs/alcasar.crt.old') || !file_exists('/etc/pki/tls/private/alcasar.key.old')) ? ' disabled' : '' ?>>
                        </form>
                </td>
                <td width="50%" valign="top">
                        <?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>
                        <?= $l_cert_expiration ?> <?= $cert_expiration_date ?><br>
                        <?= $l_cert_commonname ?> <?= $domain ?><br>
                        <?= $l_cert_organization ?> <?= $organization ?><br/>
                        <h4><?=  $l_validated ?></h4>
                        <?= $l_cert_commonname ?> <?= $CAdomain ?><br>
                        <?= $l_cert_organization ?> <?= $CAorganization ?><br>
                </td>
        </tr>
        <tr>
                <td width="50%" valign="top">
                        <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" value="<?= $l_import ?>">
                        </form>
                </td>
                <td width="50%" valign="top">
                        <?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" 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" name="recheck" value="<?= $l_recheck ?>"> <input type="submit" 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" name="recheck" value="<?= $l_renew ?>"><br>
                                        <?php else: ?>
                                                <input type="submit" name="recheck_force" value="<?= $l_renew_force ?>"><br>
                                        <?php endif; ?>
                                </form>
                        <?php endif; ?>
                        <?php if (isset($cmdResponse)): ?>
                                <p><?= $cmdResponse ?></p>
                        <?php endif; ?>
                </td>
        </tr>
</table>
</body>
</html>