Subversion Repositories ALCASAR

Rev

Rev 2324 | Rev 2326 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log

<?php
# $Id: network.php 2325 2017-07-10 12:13:57Z 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);
                $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";
} 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";
}

$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]))$/';

$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':
                if ((!empty(trim($_POST['add_mac']))) && (!empty(trim($_POST['add_ip'])))) {
                        $tab = file(ETHERS_FILE);
                        if ($tab) { // the file isn't empty
                                $insert = true;
                                $new_mac_addr = trim($_POST['add_mac'], "\x00..\x20");
                                $new_ip_addr  = trim($_POST['add_ip'],  "\x00..\x20");
                                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':
                if ((!empty(trim($_POST['add_host']))) and (!empty(trim($_POST['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(trim($_POST['add_host']), trim($host_name)) === 0) {
                                                        $insert = false;
                                                        break;
                                                }
                                                if (strcasecmp(trim($_POST['add_ip']), trim($ip_addr)) === 0) {
                                                        $insert = false;
                                                        break;
                                                }
                                        }
                                }
                                if ($insert) {
                                        $line1 = 'address=/'.trim($_POST['add_host']).'/'.trim($_POST['add_ip'])."\n";
                                        $explode_ip = explode('.', trim($_POST['add_ip']));
                                        $reverse_ip = implode('.', array_reverse($explode_ip));
                                        $line2 = 'ptr-record='.$reverse_ip.'.in-addr.arpa,'.trim($_POST['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') {
                                $dns_local_file = DNS_LOCAL_FILE;
                                exec("/bin/sed -i ".escapeshellarg("/^$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);
                        $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);
                $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) {
        $internet_publicIP = file_get_contents('http://ipecho.net/plain');
} 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>Autoriser les utilisateurs à se connecter de manière non sécurisée :</span><br>
                                <select name="https_login">
                                        <option value="on"<?=  (($conf['HTTPS_LOGIN'] === 'on')  ? ' selected' : '') ?>>Non</option>
                                        <option value="off"<?= (($conf['HTTPS_LOGIN'] === 'off') ? ' selected' : '') ?>>Oui</option>
                                </select>
                                <input type="submit" value="<?= $l_apply ?>"><br>
                                <span>/!\ Les identifiants de connexion seront envoyés en clair.</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>
                        Expiration Date : <?= $cert_expiration_date ?><br>
                        Common name : <?= $domain ?><br>
                        Organization : <?= $organization ?><br/>
                        <h4><?=  $l_validated ?></h4>
                        Common name : <?= $CAdomain ?><br>
                        Organization : <?= $CAorganization ?><br>
                </td>
        </tr>
        <tr>
                <td width="50%" valign="top">
                        <h3>Importer un certificat</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>Intégration Let's Encrypt</h3>
                        <?php if ($step === 1): ?>
                                <form method="post" action="<?= htmlspecialchars($_SERVER['PHP_SELF']) ?>">
                                        <input type="hidden" name="choix" value="le_issueCert">
                                        Status : Inactif<br>
                                        Email : <input type="text" name="email" placeholder="adresse@email.com"<?= ((!empty($LE_conf['email'])) ? ' value="'.$LE_conf['email'].'"' : '') ?>><br>
                                        Nom de domaine : <input type="text" name="domainname" placeholder="alcasar.domain.tld" required><br>
                                        <input type="submit" name="issue" value="Envoyer"><br>
                                </form>
                        <?php elseif ($step === 2): ?>
                                <form method="post" action="<?= htmlspecialchars($_SERVER['PHP_SELF']) ?>">
                                        <input type="hidden" name="choix" value="le_renewCert">
                                        Status : En attente de validation<br>
                                        Nom de domaine : <?= $LE_conf['domainRequest'] ?><br>
                                        Demandé le : <?= date('d-m-Y H:i:s', $LE_conf['dateIssueRequest']) ?><br>
                                        Entrée DNS TXT : "<?= '_acme-challenge.'.$LE_conf['domainRequest'] ?>"<br>
                                        Challenge : "<?= $LE_conf['challenge'] ?>"<br>
                                        <input type="submit" name="recheck" value="Revérifier"> <input type="submit" name="cancel" value="Annuler"><br>
                                </form>
                        <?php elseif ($step === 3): ?>
                                <form method="post" action="<?= htmlspecialchars($_SERVER['PHP_SELF']) ?>">
                                        <input type="hidden" name="choix" value="le_renewCert">
                                        Status : Actif<br>
                                        Nom de domaine : <?= $LE_conf['domainRequest'] ?><br>
                                        API :  <?= $LE_conf['dnsapi'] ?><br>
                                        Prochain renouvellement : <?= date('d-m-Y', $LE_conf['dateNextRenewal']) ?><br>
                                        <?php if ($LE_conf['dateNextRenewal'] <= date('U')): ?>
                                                <input type="submit" name="recheck" value="Renouveller"><br>
                                        <?php else: ?>
                                                <input type="submit" name="recheck_force" value="Renouveller (forcer)"><br>
                                        <?php endif; ?>
                                </form>
                        <?php endif; ?>
                        <?php if (isset($cmdResponse)): ?>
                                <p><?= $cmdResponse ?></p>
                        <?php endif; ?>
                </td>
        </tr>
</table>
</body>
</html>