Subversion Repositories ALCASAR

Rev

Rev 2934 | Blame | Compare with Previous | Last modification | View Log

<?php
# $Id: index.php 2935 2021-03-28 22:14:58Z rexy $
#
# index.php for ALCASAR by Rexy
# UI & css style by stephane ERARD
# The contents of this file may be used under the terms of the GNU
# General Public License Version 2, provided that the above copyright
# notice and this permission notice is included in all copies or
# substantial portions of the software.

/****************************************************************
*                       GLOBAL FILE PATHS                       *
*****************************************************************/
define('CONF_FILE', '/usr/local/etc/alcasar.conf');
define('DOMAIN_ALLOWED_LIST', '/usr/local/etc/alcasar-uamdomain');

/****************************************************************
*                       FILE reading test                       *
*****************************************************************/
$conf_files = array(CONF_FILE, DOMAIN_ALLOWED_LIST);
foreach ($conf_files as $file) {
        if (!file_exists($file)) {
                exit("Fichier $file non présent");
        }
        if (!is_readable($file)) {
                exit("Vous n'avez pas les droits de lecture sur le fichier $file");
        }
}

/****************************************************************
*                       Read 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);

$organisme = $conf["ORGANISM"];
$hostname  = $conf["HOSTNAME"].'.'.$conf["DOMAIN"];
$ssl_status = ($conf['HTTPS_LOGIN'] === 'on');
$protocol = ($ssl_status) ? 'https://' : 'http://';
$useHTTPS = ((isset($_SERVER['HTTPS'])) && (!empty($_SERVER['HTTPS'])) && ($_SERVER['HTTPS'] !== 'off'));
$network_pb = false;
$diagnostic = "can't contact the default router";
$certCa_link = (($useHTTPS) ? 'https' : 'http')."://$hostname/certs/certificat_alcasar_ca.crt";
$logout_link = ((($conf['HTTPS_CHILLI'] === 'on') && $useHTTPS) ? 'https://'.$hostname.':3991' : 'http://'.$hostname.':3990').'/logoff';
$direct_access = false;
$remote_ip = preg_match('#^([0-9]{1,3}\.){3}[0-9]{1,3}$#', $_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';
$connection_history = '';
$nb_connection_history = 3;
$redirect_link = 'www.euronews.com'; // Default redirection for HTTP interception (beware, this website must run in HTTP)
$service_wifi4eu_status = ($conf['WIFI4EU'] === 'on');
$service_wifi4eu_code = $conf['WIFI4EU_CODE'];
$service_wifi4eu_server = 'https://collection.wifi4eu.ec.europa.eu/wifi4eu.min.js';
$service_SMS_status = ($conf['SMS'] === 'on');

// Retrieve the user info behind the remote ip
$output = [];
exec('sudo /usr/sbin/chilli_query list ip '.escapeshellarg($remote_ip), $output);
if (!empty($output)) {
        $userRaw = explode(' ', $output[0]);
        $user = (object) [
                'mac'       =>  $userRaw[0],
                'connected' => ($userRaw[4] === '1'),
                'username'  =>  $userRaw[5]
        ];
} else {
        // CoovaChilli does not know the user
        $user = (object) [
                'mac'       => '',
                'connected' => false,
                'username'  => ''
        ];
}

// Test if it's a direct connection to ALCASAR
if (isset($_SERVER['HTTP_HOST']) && (($_SERVER['HTTP_HOST'] === $_SERVER['SERVER_ADDR']) || ($_SERVER['HTTP_HOST'] === 'alcasar') || ($_SERVER['HTTP_HOST'] === $hostname) || ($_SERVER['HTTP_HOST'] === $organisme))) {
        $direct_access = true;
}

// Function to adapt time connection in seconds to H,M,S
function secondsToDuration($seconds = null){
        if ($seconds == null) return "";
        $temp = $seconds % 3600;
        $time[0] = ( $seconds - $temp ) / 3600 ;        // hours
        $time[2] = $temp % 60 ;                         // seconds
        $time[1] = ( $temp - $time[2] ) / 60;           // minutes
        return $time[0].' h '.$time[1].' m '.$time[2].' s';
}

// if user need to be warned
if (isset($_GET['warn']) && isset($_GET['url'])) {
        $direct_access = false;
}

if ($user->connected) { // the user is authenticated
        if (isset($_GET['redirect'])) { // if user has been warned, we redirect him to his website
                header('Location: '.$_GET['url'], true, 307);
                exit();
        }

        // We retrieve his three last connections
        if ((is_file('./acc/manager/lib/sql/drivers/mysql/functions.php'))&&(is_file('/etc/freeradius-web/config.php'))){
                include_once('/etc/freeradius-web/config.php');
                include_once('./acc/manager/lib/sql/drivers/mysql/functions.php');
                $sql = "SELECT UserName, AcctStartTime, AcctStopTime, acctsessiontime FROM radacct WHERE UserName='$user->username' ORDER BY AcctStartTime DESC LIMIT 0 , $nb_connection_history";
                $link = @da_sql_pconnect($config);
                if ($link) {
                        $res = @da_sql_query($link,$config,$sql);
                        if ($res) {
                                $connection_history .= '<ul>';
                                while (($row = @da_sql_fetch_array($res,$config))) {
                                        $connected = '';
                                        if ($row['acctstoptime'] === '') {
                                                $connected = ' (active)';
                                        }
                                        $sessionTimeFormated = secondsToDuration($row['acctsessiontime']);
                                        $connection_history .= "<li title=\"$row[username] $row[acctstarttime] $row[acctstoptime] ($sessionTimeFormated)\">$row[acctstarttime] ($sessionTimeFormated) $connected</li>";
                                }
                                $connection_history .= '</ul>';
                        }
                }
        }
} else { // the user isn't authenticated
        if (isset($_GET['url'])) { // it's the second stage (when user has clicked on the button "open a connection")
                $redir = 'http://'.$_GET['url'];
                header("Location: $redir", true, 307);
                exit();
        }
}

// 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_access_denied = "Contrôle d'accès";
        $l_access_welcome = "Bienvenue sur ALCASAR";
        $l_access_unavailable = "ACCÈS INDISPONIBLE";
        $l_required_domain = "Site WEB demandé";
        $l_explain_acc_access = "Le centre de gestion permet d'administrer le portail. Vous devez posséder un compte d'administration ou de gestion pour y accéder.";
        $l_explain_access_deny = "Vous tentez d'accéder à une ressource dont le contenu est réputé contenir des informations inappropriées.";
        $l_explain_net_pb = "Votre portail détecte que l'accès à Internet est indisponible.";
        $l_contact_access_deny = "Contactez le responsable de la séurité (OSSI/RSSI) si vous pensez que ce filtrage est abusif.";
        $l_contact_net_pb = "Contactez votre responsable informatique ou votre prestataire Internet pour plus d'information.";
        $l_sms_access = "<a href=\"//$hostname/autoregistrationinfo.php\">Créer votre compte par SMS</a>";
        $l_install_certif = "Installer le certificat racine";
        $l_category = "catégorie :";
        if (!$user->connected) {
                $l_logout_explain = "Aucune session n'est actuellement ouverte";
                $l_logout = "<a href=\"//$hostname/index.php?url=$redirect_link\">Ouvrir une session</a>";
        } else {
                if ($user->username != $user->mac) { // authentication exception or not
                        $l_logout_explain = "Utilisateur connecté : <a href=\"$logout_link\" title=\"Deconnecter l'utilisateur $user->username\"><b>$user->username</b></a><br><br>$nb_connection_history dernières connexions :$connection_history";
                        $l_logout = "<a href=\"$logout_link\">Se déconnecter d'internet</a>";
                } else {
                        $l_logout_explain = "Votre système ($user->username) est en exception d'authentication.<br><br>$nb_connection_history dernières connexions :$connection_history";
                        $l_logout = "<a href=\"\">Information des connexions</a>";
                }
        }
        $l_password_change = "<a href=\"" . $protocol . "$hostname/password.php\">Changer votre mot de passe</a>";
        $l_back_page = "<a href=\"javascript:history.back()\">Page précédente</a>";
        $l_explain_warn = "L'administrateur a créé une archive contenant vos journaux de connexion dans le cadre d'une affaire judiciaire.";
        if (isset($_GET['url'])) {
                $l_continue_link = "<a href=\"index.php?redirect=1&url=".urlencode($_GET['url'])."\" class=\"button\">Je comprends et je souhaite continuer ma navigation.</a>";
        } else {
                $l_continue_link = "<a href=\"index.php\" class=\"button\">Je comprends et je souhaite continuer ma navigation.</a>";
        }
        $l_title_warn="Cher utilisateur, ";
        $l_explain_warn_name="Une personne sous le nom de ";
        $l_explain_warn_ip="sous cette IP : ";
        $l_explain_warn_date="a consulté vos journaux de connexion le ";
        $l_explain_warn_reason="Raison invoquée : ";
        $l_uam_domain = "Sites autorisés : ";
} else if ($Language === 'pt') {        // Portuguese
        $l_access_denied = "Controle de acesso";
        $l_access_welcome = "Bem-vindo ao Alcasar";
        $l_access_unavailable = "ACESSO INDISPONÍVEL";
        $l_required_domain = "Site WEB Obrigatório";
        $l_explain_acc_access = "Este é o centro de controle do portal para acessar você deve ter uma conta administrativa valida.";
        $l_explain_access_deny = "Você tenta se conectar a um recurso cujo conteúdo é considerado inadequado no conteúdo de informações.";
        $l_explain_net_pb = "O sistema detectou que o acesso é de risco, não será permitido o acesso";
        $l_contact_access_deny = "Entre em contato com o administrador do sistema de segurança se acha que essa filtragem é abusiva.";
        $l_contact_net_pb = "Entre em contato com a empresa fornecedora de Internet para mais informações";
        $l_sms_access = "<a href=\"//$hostname/autoregistrationinfo.php\">Crie a conta por SMS</a>";
        $l_install_certif = "Instalar Certificado Alcasar AC";
        $l_category = "categoria :";
        if (!$user->connected) {
                $l_logout_explain = "Não há conexão de Internet aberta em seu computador, deseja conectar?";
                $l_logout = "<a href=\"//$hostname/index.php?url=$redirect_link\">Abrir uma conexão de Internet</a>";
        } else {
                if ($user->username != $user->mac) { // authentication exception or not
                        $l_logout_explain = "Usuário conectado : <a href=\"$logout_link\" title=\"Disconnect user $user->username\"><b>$user->username</b></a><br><br>$nb_connection_history logins últimos :$connection_history";
                        $l_logout = "<a href=\"$logout_link\">Sair da Internet</a>";
                } else {
                        $l_logout_explain = "O sistema ($user->username) detctou exesso de autenticação.<br><br>$nb_connection_history logins últimos :$connection_history";
                        $l_logout = "<a href=\"\">Informações de conexões</a>";
                }
        }
        $l_password_change = "<a href=\"" . $protocol . "$hostname/password.php\">Mudar sua senha</a>";
        $l_back_page = "<a href=\"javascript:history.back()\">Página anterior</a>";
        $l_explain_warn = "El administrador ha creado un archivo que contiene los periódicos de inicio de sesión como parte de un proceso judicial.";
        if (isset($_GET['url'])) {
                $l_continue_link = "<a href=\"index.php?redirect=1&url=".urlencode($_GET['url'])."\" class=\"button\">Lo comprendo y deseo continuar mi navegación.</a>";
        } else {
                $l_continue_link = "<a href=\"index.php\" class=\"button\">Lo comprendo y deseo continuar mi navegación.</a>";
        }
        $l_title_warn="Estimado usuario,";
        $l_explain_warn_name="El usario ";
        $l_explain_warn_ip="con este IP : ";
        $l_explain_warn_date="consultó a sus registros de conexión el ";
        $l_explain_warn_reason="con la siguiente razón : ";
        $l_uam_domain = "Sites autorizados : ";
} else if ($Language === 'zn') {        // Chinese
        $l_access_denied = "访问控制";
        $l_access_welcome = "欢迎来到ALCASAR";
        $l_access_unavailable = "不可访问";
        $l_required_domain = "访问的网站";
        $l_explain_acc_access = "管理中心能管理门户,您必须通过超级用户或者管理用户来访问。";
        $l_explain_access_deny = "您试图访问一个含有不当信息的资源。";
        $l_explain_net_pb = "您的门户检测因特网不可用。";
        $l_contact_access_deny = "如果您认为该过滤不当,请联系安全负责人(OSSI/RSSI)。";
        $l_contact_net_pb = "请联系IT负责人或网络服务商来了解更多信息。";
        $l_sms_access = "<a href=\"//$hostname/autoregistrationinfo.php\">通過短信創建您的帳戶</a>";
        $l_install_certif = "安装根证书";
        $l_category = "类别 :";
        if (!$user->connected) {
                $l_logout_explain = "您的系统目前没有打开任何网络咨询进程。";
                $l_logout = "<a href=\"//$hostname/index.php?url=$redirect_link\">打开一个网络进程</a>";
        } else {
                if ($user->username != $user->mac) { // authentication exception or not
                        $l_logout_explain = "已连接用户:<a href=\"$logout_link\" title=\" $user->username\"><b>$user->username</b></a><br><br>$nb_connection_history 最后连接 :$connection_history";
                        $l_logout = "<a href=\"$logout_link\">断开网络</a>";
                } else {
                        $l_logout_explain = "您的系统($user->username)验证例外<br><br>$nb_connection_history 最后连接: $connection_history";
                        $l_logout = "<a href=\"\">连接信息</a>";
                }
        }
        $l_password_change = "<a href=\"" . $protocol . "$hostname/password.php\">更改您的密码</a>";
        $l_back_page = "<a href=\"javascript:history.back()\">上一页</a>";
        $l_explain_warn = "管理员创建了一份可用于司法调查的连接日志文档。";
        if (isset($_GET['url'])) {
                $l_continue_link = "<a href=\"index.php?redirect=1&url=".urlencode($_GET['url'])."\" class=\"button\">我明白并希望继续浏览。</a>";
        } else {
                $l_continue_link = "<a href=\"index.php\" class=\"button\">我明白并希望继续浏览。</a>";
        }
        $l_title_warn="亲爱的用户,";
        $l_explain_warn_name="一人名为";
        $l_explain_warn_ip="在此IP:";
        $l_explain_warn_date="查看您的连接日志于";
        $l_explain_warn_reason=" 如下原因:";
        $l_uam_domain = "授权网站 : ";
} else if ($Language === 'ar') {        // Arabic
        $l_access_denied = "مراقبة الدخول";
        $l_access_welcome = "ALCASAR مرحبا بك في";
        $l_access_unavailable = "الدخول غير متوفر";
        $l_required_domain = "موقع إنترنيت مطلوب";
        $l_explain_acc_access = "مركز التحكم يمكنك من إدارة البوابة. يلزمك التوفر على حساب الادارة للدخول.";
        $l_explain_access_deny = "محاولة لدخول موارد تحتوي على معلومات غير ملائمة المحتوى";
        $l_explain_net_pb = "بوابتك تكتشف ان الدخول على الانترنت غير متوفر";
        $l_contact_access_deny = "المرجو الاتصال بضابط أمن (OSS / RSS) إذا اعتقدت ان هذه التصفية غير قانونية";
        $l_contact_net_pb = "المرجو الاتصال بمدير المعلومات أو مورد الأنترنت للمزيد من المعلومات";
        $auto_save_sms_text = "تسجيل ذاتي على";
        $l_sms_access = "<a href=\"//$hostname/autoregistrationinfo.php\">إنشاء حسابك لا SMS</a>";
        $l_install_certif = "ركب جذر الشهادة";
        $l_category = "فئة :";
        if (!$user->connected) {
                $l_logout_explain = "و لا جلسة استفسار للإنترنت مفتوحة حاليا على نظامك";
                $close_session_text = "فتح جلسة الإنترنت";
                $l_logout = "<a href=\"//$hostname/index.php?url=$redirect_link\">$close_session_text</a>";
        } else {
                if ($user->username != $user->mac) { // authentication exception or not
                        $close_session_text = "إقفال جلسة المستخدم المتصل حاليا";
                        $userlogged_text = "المستخدم متصل";
                        $disconnect_user_text = "قطع الاتصال على المستخدم";
                        $l_logout_explain = "Utilisateur connecté : <a href=\"$logout_link\" title=\"Deconnecter l'utilisateur $user->username\"><b>$user->username</b></a><br><br>$nb_connection_history dernières connexions :$connection_history";
                        $logout_internet_text = "قطع الاتصال على الإنترنت";
                        $l_logout = "<a href=\"$logout_link\">$logout_internet_text</a>";
                } else {
                        $your_system_text = "نظامك";
                        $auth_except_text = "على توثيق استثنائي";
                        $last_conn_text = "اتصالات مشاركة";
                        $l_logout_explain = "$connection_history :$last_conn_text $nb_connection_history<br><br>$auth_except_text ($user->username) $your_system_text";
                        $l_logout = "<a href=\"\">معلومات على الاتصالات </a>";
                }
        }
        $change_pass_text = "غير كلمتك السرية";
        $l_password_change = "<a href=\"" . $protocol . "$hostname/password.php\">$change_pass_text</a>";
        $redirect_sms_text = "يوجهك على الصفحة التفسيرية للتسجيل الذاتي بطريقة";
        $login_text = "تسجيل الدخول";
        $your_phone_text = "رقم الهاتف الخاص بك";
        $pass_text = "كلمة السر";
        $your_message_text = "رسالتك";
        $previous_text = "الصفحة السابقة";
        $l_back_page = "<a href=\"javascript:history.back()\">$previous_text</a>";
        $l_explain_warn = "المسؤول أنشأ أرشيفاً تحتوي على سجلات الاتصال في إطار تحقيق قضائي";
        $understand_text = "أنا متفهم و أريد ان أواصل التصفح";
        if (isset($_GET['url'])) {
                $l_continue_link = "<a href=\"index.php?redirect=1&url=".urlencode($_GET['url'])."\" class=\"button\">$understand_text</a>";
        } else {
                $l_continue_link = "<a href=\"index.php\" class=\"button\">$understand_text</a>";
        }
        $l_title_warn = "عزيزي المستعمل, ";
        $l_explain_warn_name = "شخص مسمىٰ ";
        $l_explain_warn_ip = "تحت هذا IP: ";
        $l_explain_warn_date = "إطّلع على سجلات الاتصال الخاصة بك في";
        $l_explain_warn_reason = "السبب المسرّح به: ";
        $l_uam_domain = ":المواقع المسموحة ";
} else if ($Language === 'de') {                // German
        $l_access_denied = "Zugangskontrolle";
        $l_access_welcome = "Willkommen bei ALCASAR";
        $l_access_unavailable = "ZUGANG NICHT MÖGLICH";
        $l_required_domain = "Website benötigt";
        $l_explain_acc_access = "Hier ist das Kontrollcenter. Sie benötigen einen Account mit Administratorrechten.";
        $l_explain_access_deny = "Sie haben versucht sich mit einer Seite zu verbinden, die möglicherweise unangemessene Inhalte beinhaltet.";
        $l_explain_net_pb = "Offenbar funktioniert ihr Internetzugriff nicht.";
        $l_contact_access_deny = "Kontaktieren Sie ihren Sicherheitsbeauftragten wenn Sie denken dass diese Filterung unangemessen ist.";
        $l_contact_net_pb = "Kontaktieren Sie Ihren Netzwerkbeauftragten oder Ihren Internetanbieter für weitere Informationen.";
        $l_sms_access = "<a href=\"//$hostname/autoregistrationinfo.php\">Einen Account per SMS erstellen</a>";
        $l_install_certif = "Das ALCASAR AC Zertifikat installieren";
        $l_category = "Kategorie:";
        if (!$user->connected) {
                $l_logout_explain = "Zurzeit ist keine Internetsitzung auf Ihrem System aktiv";
                $l_logout = "<a href=\"//$hostname/index.php?url=$redirect_link\">Eine neue Internetzsitzung eröffnen</a>";
        } else {
                if ($user->username != $user->mac) { // authentication exception or not
                        $l_logout_explain = "Aktuell eingeloggter User: <a href=\"$logout_link\" title=\"Ausloggen $user->username\"><b>$user->username</b></a><br><br>$nb_connection_history letzte Verbindungen:$connection_history";
                        $l_logout = "<a href=\"$logout_link\">Aus dem Internet ausloggen</a>";
                } else {
                        $l_logout_explain = "Ihr System ($user->username) ist nicht authentifiziert.<br><br>$nb_connection_history Letzte Verbindungen:$connection_history";
                        $l_logout = "<a href=\"\">Informationen zur Verbindung</a>";
                }
        }
        $l_password_change = "<a href=\"" . $protocol . "$hostname/password.php\">Passwort ändern</a>";
        $l_back_page = "<a href=\"javascript:history.back()\">Previous page</a>";
        $l_explain_warn = "Der Administrator wird ein Archiv erstellen, welches Ihre Logdaten für den Fall einer gerichtlichen Untersuchung beinhaltet.";
        if (isset($_GET['url'])) {
                $l_continue_link = "<a href=\"index.php?redirect=1&url=".urlencode($_GET['url'])."\" class=\"button\">Ich verstehe und möchte fortfahren.</a>";
        } else {
                $l_continue_link = "<a href=\"index.php\" class=\"button\">Ich verstehe und möchte fortfahren.</a>";
        }
        $l_title_warn="Lieber Benutzer,";
        $l_explain_warn_name="Jemand namens ";
        $l_explain_warn_ip="mit dieser IP: ";
        $l_explain_warn_date="hat Ihre Verbindungsdaten eingesehen, für den ";
        $l_explain_warn_reason="Grund: ";
        $l_uam_domain = "Authorisierte Webseiten: ";
} else if ($Language === 'es'){ // Spanish
        $l_access_denied = "Control de Acceso";
        $l_access_welcome = "Bienvenido, Ud. está en ALCASAR";
        $l_access_unavailable = "ACCESO NO DISPONIBLE";
        $l_required_domain = "Sitio WEB solicitado";
        $l_explain_acc_access = "Este acceso gestiona el portal. Tiene que tener una cuenta administrativa.";
        $l_explain_access_deny = "Intenta conectarse a un recurso cuyo contenido se considera que contiene información inapropiada.";
        $l_explain_net_pb = "El sistema informa que el acceso a Internet no esta disponible.";
        $l_contact_access_deny = "Por favor póngase en contacto con el administrador de la red si cree que este filtrado es abusivo";
        $l_contact_net_pb = "Póngase en contacto con el responsable de la red o con su proveedor de Internet para obtener más información.";
        $l_sms_access = "<a href=\"//$hostname/autoregistrationinfo.php\">Alta de cuenta por SMS</a>";
        $l_install_certif = "Instalar certificado ALCASAR AC";
        $l_category = "categoría:";
        if (!$user->connected) {
                $l_logout_explain = "Actualmente no hay una sesión de acceso a Internet abierta por su sistema";
                $l_logout = "<a href=\"//$hostname/index.php?url=$redirect_link\">Abra una sesión de Internet</a>";
        } else {
                if ($user->username != $user->mac) { // authentication exception or not
                        $l_logout_explain = "Cierre la sesión del usuario actualmente conectado.<br> Usuario conectado: <a href=\"$logout_link\" title=\"Desconectar usuario $user->username\"><b>$user->username</b></a><br><br>$nb_connection_history ultimas sesiones:$connection_history";
                        $l_logout = "<a href=\"$logout_link\">Desconectarse de internet</a>";
                } else {
                        $l_logout_explain = "El sistema ($user->username) detectó un exceso en las autenticaciones.<br><br>$nb_connection_history Últimas conexiones:$connection_history";
                        $l_logout = "Información sobre las conexiones";
                }
        }
        $l_password_change = "<a href=\"https://$hostname/password.php\">Cambie su contraseña</a>";
        $l_back_page = "<a href=\"javascript:history.back()\">Página anterior</a>";
        $l_explain_warn = "El administrador creó un archivo que contiene sus registros de navegacion para una investigación legal.";
        if (isset($_GET['url'])) {
                $l_continue_link = "<a href=\"index.php?redirect=1&url=".urlencode($_GET['url'])."\" class=\"button\">Entiendo y deseo continuar.</a>";
        } else {
                $l_continue_link = "<a href=\"index.php\" class=\"button\">Entiendo y deseo continuar.</a>";
        }
        $l_title_warn="Estimado usuario,";
        $l_explain_warn_name="Alguien llamado ";
        $l_explain_warn_ip="con esta IP: ";
        $l_explain_warn_date="ha leído sus registros de conexión el ";
        $l_explain_warn_reason="Debido a: ";
        $l_uam_domain = "Sitios web autorizados: ";
} else {        // English
        $l_access_denied = "Access control";
        $l_access_welcome = "Welcome to ALCASAR";
        $l_access_unavailable = "ACCESS UNAVAILABLE";
        $l_required_domain = "Required WEB site";
        $l_explain_acc_access = "This center control the portal. You must have an administrative account.";
        $l_explain_access_deny = "You try to connect to a resource whose content is deemed to contain inappropriate information.";
        $l_explain_net_pb = "Your portal has just detected that the Internet access is down";
        $l_contact_access_deny = "Contact your security system manager if you think this filtering is abusive.";
        $l_contact_net_pb = "Contact your network responsive or your Internet provider for further information.";
        $l_sms_access = "<a href=\"//$hostname/autoregistrationinfo.php\">Create your account by SMS</a>";
        $l_install_certif = "Install ALCASAR AC Certificate";
        $l_category = "category:";
        if (!$user->connected) {
                $l_logout_explain = "No session is currently open";
                $l_logout = "<a href=\"//$hostname/index.php?url=$redirect_link\">Open an Internet session</a>";
        } else {
                if ($user->username != $user->mac) { // authentication exception or not
                        $l_logout_explain = "User logged-on: <a href=\"$logout_link\" title=\"Disconnect user $user->username\"><b>$user->username</b></a><br><br>$nb_connection_history last connections:$connection_history";
                        $l_logout = "<a href=\"$logout_link\">Logoff from the Internet</a>";
                } else {
                        $l_logout_explain = "Your system ($user->username) is in exception of authentication.<br><br>$nb_connection_history Last logins:$connection_history";
                        $l_logout = "<a href=\"\">Connections information</a>";
                }
        }
        $l_password_change = "<a href=\"" . $protocol . "$hostname/password.php\">Change your password</a>";
        $l_back_page = "<a href=\"javascript:history.back()\">Previous page</a>";
        $l_explain_warn = "The administrator created an archive which contains your imputabilities logs for a judicial investigation.";
        if (isset($_GET['url'])) {
                $l_continue_link = "<a href=\"index.php?redirect=1&url=".urlencode($_GET['url'])."\" class=\"button\">I understand and I wish to continue.</a>";
        } else {
                $l_continue_link = "<a href=\"index.php\" class=\"button\">I understand and I wish to continue.</a>";
        }
        $l_title_warn="Dear user,";
        $l_explain_warn_name="Someone called ";
        $l_explain_warn_ip="with this IP: ";
        $l_explain_warn_date="has read your connection logs at ";
        $l_explain_warn_reason="For this reason: ";
        $l_uam_domain = "Authorized websites: ";
}

$l_title   = ($direct_access ? $l_access_welcome     : ($network_pb ? $l_access_unavailable : $l_access_denied));
$l_explain = ($direct_access ? $l_explain_acc_access : ($network_pb ? $l_explain_net_pb     : $l_explain_access_deny));

// Set the icons
$img_rep         = '/images/';
$img_organisme   = 'organisme.png';
$img_access      = 'globe_acces_70.png';
$img_connect     = 'globe_70.png';
$img_warning     = 'globe_warning_70.png';
$img_pwd         = 'cle_ombre.png';
$img_certificate = 'certificat.png';
$img_acc         = 'logo-alcasar_70.png';
$img_sms         = 'sms.png';
$img_false       = 'interdit.png';
$img_adm         = 'adm.png';

$img_internet    = (($user->connected) ? $img_connect : ($network_pb ? $img_warning : $img_access));

if ($direct_access) {
        // Read the "Domain allowed" file
        $domainsAllowed = [];
        $fileContent = file(DOMAIN_ALLOWED_LIST); if ($fileContent) { // the file isn't empty
        foreach ($fileContent as $line) {
                        if (!empty(trim($line))) {
                                if (strpos ($line, '#')) { // the domain should be displayed
                                        $domain_fields = explode('#', $line);
                                        $domain = explode('"', $domain_fields[0]);
                                        $domain[1] = ltrim($domain[1], '.'); // remove every '.' from the beginning of domain
                                        $domainsAllowed[] = (object) [
                                                'name'   => trim($domain_fields[1]),
                                                'domain' => trim($domain[1])
                                        ];
                                        
                                }
                        }
                }
        }
} else {
         if (isset($_GET['warn']) && isset($_GET['url']) && $_GET['warn'] === '1') {
                // user need to be warned that someone reads his logs
                $filename = '/var/www/html/acc/backup/log_info.txt';
                if (file_exists($filename)) {
                        $fichier = fopen($filename, 'r');
                        $content = file($filename);
                        foreach ($content as $line) {
                                $infos = explode('|||', $line);
                                $log_date   = $infos[0];
                                $log_user   = $infos[1];
                                $log_reason = $infos[2];
                                $log_ip     = $infos[3];
                        }
                        $l_explain_warn = "$l_explain_warn_name$log_user ($l_explain_warn_ip$log_ip) $l_explain_warn_date$log_date.<br>$l_explain_warn_reason<br>$log_reason";
                } else {
                        $l_explain_warn = 'Log error!';
                }
        }
}

// Search blacklist categories
if ((!$direct_access) && (!$network_pb) && (!isset($_GET['warn']))) {
        $pattern = str_replace('www.', '', $_SERVER['HTTP_HOST']);
        $categories = [];
        exec('grep -Re ' . escapeshellarg('^'.$pattern.'$') . " /etc/e2guardian/lists/blacklists/*/domains | cut -d'/' -f6", $categories);
        $filteredUrlHtml = $l_required_domain.' : '.htmlspecialchars($_SERVER['HTTP_HOST']);
        if (empty($categories)) { // try again to search the category removing the prefix of the domain name
                $tiny_pattern = substr(stristr($pattern, '.'), 1);
                exec('grep -Re ' . escapeshellarg('^'.$tiny_pattern.'$') . " /etc/e2guardian/lists/blacklists/*/domains | cut -d'/' -f6", $categories);
        }
        if (!empty($categories)) {
                $filteredUrlHtml .= "<br>$l_category ".implode(', ', $categories);
        }
}
////////////////////////////////////////////////////////////////////////
/////////////////////////// TEST VARIABLES /////////////////////////////
////////////////////////////////////////////////////////////////////////
//$service_SMS_status = true;
//$direct_access = true;
//$network_pb = false;
//$domainsAllowed[] = (object) [
//      'name'   => 'name_test',
//      'domain' => 'domain_test' 
//];
/////////////////////////////////////////////////////////////////////////

// Cleaning the cache
header('Expires: Tue, 01 Jan 2000 00:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
?>
<!DOCTYPE html>
<html>
        <head>
                <meta charset="UTF-8">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                <title><?= $l_title ?></title>
                <link rel="stylesheet" type="text/css" href="<?= ((!$direct_access) ? "//$hostname" : '') ?>/css/bootstrap.min.css">
                <link rel="stylesheet" type="text/css" href="/css/index.css">
                <link rel="icon" href="/images/favicon-48.ico" type="image/ico">
<? if ($service_wifi4eu_status): ?>
                <script type="text/javascript">
                        var wifi4euTimerStart = Date.now();
                        var wifi4euNetworkIdentifier = '<?= $service_wifi4eu_code ?>';
                        var wifi4euLanguage = '<?= $Language ?>';
                        //var selftestModus = true;
                </script>
                <script type="text/javascript" src="<?= $service_wifi4eu_server ?>"></script>
<? endif; ?>
        </head>
        <body>
        <div class="col-xs-12 col-md-10 col-md-offset-1"> 

                <!-- HeaderBox -->
                <div class="row banner">
                        <!-- Logo box -->
                        <div class="img_banner hidden-xs col-sm-3 col-md-2 col-lg-2">
                                <img class="img-responsive img-organisme" src="<?= ((!$direct_access) ? "//$hostname" : '') ?><?= $img_rep.$img_organisme ?>">
                        </div>

                        <!-- Title -->
                        <div id="cadre_titre" class="titre_banner col-xs-12 col-sm-8">
                                <?php if ($direct_access): ?>
                                        <?php if ($service_wifi4eu_status): ?>
                                                <img id="wifi4eubanner">
                                        <?php else: ?>
                                                <p id="acces_controle" class="titre_controle"><?= $l_title ?></p>
                                        <?php endif; ?>
                                <?php if ($network_pb): ?>
                                        <div class="explanation_net_pb"><?= $l_explain_net_pb ?></div>
                                <?php endif; ?>
                                <?php else: // the user is intercepted ?>
                                        <?php if (isset($_GET['warn']) && isset($_GET['url']) && $_GET['warn'] == '1'): // if user need to be warm that someone reads his log ?>
                                                <div id="cadre_titre" class="titre_refus">
                                                        <p id="acces_controle" class="titre_refus"><?= $l_title_warn ?></p>
                                                </div>
                                        <?php else: // the user is blacklisted (or whitelisted) ?>
                                                <div id="cadre_titre" class="titre_refus">
                                                        <p id="acces_controle" class="titre_refus"><?= $l_title ?></p>
                                                </div>
                                        <?php endif; ?>
                                <?php endif; ?>
                        </div>
                        
                        <!-- Logo box -->
                        <div class="img_banner hidden-xs col-sm-3 col-md-2 col-lg-2">
                                <img class="img-responsive img-organisme" src="<?= ((!$direct_access) ? "//$hostname" : '') ?><?= $img_rep.$img_acc ?>">
                        </div>
                </div>

                <!-- Main content box -->
                <div class="row">
                        <div id="contenu_acces" class="col-xs-12 col-lg-offset-1 col-lg-10">
                                <?php if ((!$direct_access) && (!$network_pb) && (!isset($_GET['warn']))): // print blacklist categories ?>
                                <div id="box_url">
                                        <br>
                                        <?= $l_explain ?>
                                </div>
                                <?php endif; ?>

                                <!-- Menu -->
                                <div class="menu-container container col_xs_12 col-sm-7">
                                        <?php if ($direct_access): ?>
                                                <div class="box_menu<?= (!$network_pb) ? '' : ' box-menu-disabled' ?>" id="box_conn" <?= (!$network_pb) ? '' : 'title=\'Not available\'' ?>>
                                                        <span><?= $l_logout ?></span>
                                                        <div class="menu-image">                                                
                                                                <img class="img-responsive" src="<?= $img_rep.$img_internet ?>">
                                                        </div>
                                                </div>
                                        
                                                <div class="box_menu_right box_menu" id="box_certif">
                                                        <span><a href="<?= $certCa_link ?>"><?= $l_install_certif ?></a></span>
                                                        <div class="menu-image">
                                                                <img class="img-responsive" src="<?= $img_rep.$img_certificate ?>">
                                                        </div>
                                                </div>

                                                <div class="box_menu" id="box_mdp" >
                                                        <div class="menu-image">
                                                                <img class="img-responsive" src="<?= $img_rep.$img_pwd ?>">
                                                        </div>
                                                        <span><?= $l_password_change ?></span>
                                                </div>

                                        <?php if ($service_SMS_status === true): ?>
                                                <div class="box_menu_right box_menu" id="box_acc">
                                                        <span><?= $l_sms_access ?></span>
                                                        <div class="menu-image">
                                                                <img class="img-responsive menu-image" src="<?= $img_rep.$img_sms ?>">
                                                        </div>
                                                </div>
                                        <?php endif; ?>
                                </div>

                                <!-- Info Box -->
                                <div class="info-box-container col-sm-5">       
                                        <div id="box_infos">
                                                <p class="box_infos_explanations"><?= $l_logout_explain ?>
                                                        
                                                <?php if (!empty($domainsAllowed)): ?>
                                                        <p class="domain_allowed_title"><?= $l_uam_domain ?></p>
                                                        <ul>
                                                                <?php foreach ($domainsAllowed as $domainAllowed): ?>
                                                                        <li><a href="http://<?= $domainAllowed->domain ?>"><?= $domainAllowed->name ?></a></li>
                                                                <?php endforeach; ?>
                                                        </ul>
                                                <?php endif; ?>

                                                <?php else: // the user is intercepted ?>
                                                        <?php if (isset($_GET['warn']) && isset($_GET['url']) && $_GET['warn'] === '1'): // user need to be warned that someone reads his logs ?>
                                                                <div id="box_refuse">
                                                                        <img src="//<?= $hostname.$img_rep.$img_warning ?>">
                                                                        <p><?= $l_explain_warn ?></p>
                                                                </div>
                                                                <div id="liens_redir">
                                                                        <p><?= $l_continue_link ?></p>
                                                                </div>
                                                        <?php else: ?>
                                                                <table width="80%">
                                                                        <tr>
                                                                                <td><img src="//<?= $hostname.$img_rep.$img_false ?>"></td>
                                                                                <?php if (($network_pb) && (!$direct_access)): ?>
                                                                                <td><?= "Diagnostic : $diagnostic" ?></td>
                                                                                <?php else: ?>
                                                                                <td><?= $filteredUrlHtml ?></td>
                                                                                <?php endif; ?>
                                                                        </tr><tr>
                                                                                <td></td><td><?= $l_back_page ?></td>
                                                                        </tr>
                                                                </table>
                                                        <?php endif; ?>
                                                <?php endif; ?>
                                        </div>
                                </div>
                        </div>
                        <?php if ($direct_access): // display the admin logo (wheel) at the bottom right ?>
                        <div id="corner">
                                <div id="adm" class="corn">
                                        <a href="<?= "https://$hostname/acc/" ?>"><img src="<?= $img_rep.$img_adm ?>"></a>
                                </div>
                        </div>
                </div>
                <?php endif; ?>
        </div>
        </body>
</html>