#!/usr/bin/php -q
<?php
$wprotect_version="1.300";
if (version_compare(phpversion(), '6.0.0', '<')) {
    mb_internal_encoding("UTF-8");
}
set_time_limit(0);
ob_implicit_flush();
declare(ticks = 1);
$config = array();
$__server_listening = true;
$thread_list=array();
error_reporting(-1);
error_reporting(E_ALL);
ini_set('display_errors', '1');
ini_set('display_errors', true);
ini_set('display_startup_errors', true);
ini_set('log_errors', true);
ini_set('error_log', '/var/log/wprotect/install.log');
require_once("/opt/wprotect/class/share_functions.php");
//------------------------------------------------------------------------------------
function GenerationCle($Texte,$CleDEncryptage) {
  $CleDEncryptage = md5($CleDEncryptage); 
  $Compteur=0; 
  $VariableTemp = ""; 
  for ($Ctr=0;$Ctr<strlen($Texte);$Ctr++) 
    { 
    if ($Compteur==strlen($CleDEncryptage))
      $Compteur=0; 
    $VariableTemp.= substr($Texte,$Ctr,1) ^ substr($CleDEncryptage,$Compteur,1); 
    $Compteur++; 
    } 
  return $VariableTemp; 
  }
//------------------------------------------------------------------------------------
function Crypte($Texte) {
	global $config;
  $Cle = $config['config_security_key'];
  srand((double)microtime()*1000000); 
  $CleDEncryptage = md5(rand(0,32000) ); 
  $Compteur=0; 
  $VariableTemp = ""; 
  for ($Ctr=0;$Ctr<strlen($Texte);$Ctr++) 
    { 
    if ($Compteur==strlen($CleDEncryptage)) 
      $Compteur=0; 
    $VariableTemp.= substr($CleDEncryptage,$Compteur,1).(substr($Texte,$Ctr,1) ^ substr($CleDEncryptage,$Compteur,1) ); 
    $Compteur++;
    } 
  return base64_encode(GenerationCle($VariableTemp,$Cle) );
  }
//------------------------------------------------------------------------------------
function Decrypte($Texte) {
	global $config;
  $Cle = $config['config_security_key'];
  $Texte = GenerationCle(base64_decode($Texte),$Cle);
  $VariableTemp = ""; 
  for ($Ctr=0;$Ctr<strlen($Texte);$Ctr++) 
    { 
    $md5 = substr($Texte,$Ctr,1); 
    $Ctr++; 
    $VariableTemp.= (substr($Texte,$Ctr,1) ^ $md5); 
    } 
  return $VariableTemp; 
  }
//------------------------------------------------------------------------------------
function activate_option_to_a_configfile($file, $option, $sign, $value) {
	$final_file=array();
	$find=false;
	$handle = @fopen($file, "r+");
	if ($handle) {
		while (($buffer = fgets($handle, 4096)) !== false) {
			$f=explode($sign, $buffer);
			$f[0] = rtrim($f[0]);
			if ($f[0]==$option) {
				$final_file[] = $option.$sign.$value."\n";
				$find=TRUE;
			}
			else {
				$final_file[] = $buffer;
			}
		}
    fclose($handle);
	}
	else {
			logme("Impossible d'ouvrir le fichier ".$file." : merci de vérifier que le programme est installé...");
			fclose($handle);
			return FALSE;
		}
	$first=TRUE;
	foreach ($final_file AS $k=>$v) {
		if ($first) {
			file_put_contents ( $file , $v );
			$first=FALSE;
		}
		else {
			file_put_contents ( $file , $v, FILE_APPEND );
		}
	}
	if (!$find) {
		file_put_contents ( $file , $option.$sign.$value."\n" , FILE_APPEND );
	}
	return TRUE;
} 
//------------------------------------------------------------------------------------
function myexec($commande) {
	exec ($commande, $result);
	return $result;
}
//------------------------------------------------------------------------------------
function logme ($data) {
date_default_timezone_set("Europe/Paris");
$date=date('d-m-Y H:i:s');
file_put_contents("/var/log/wprotect/install.log", $date." ".$data."\n", FILE_APPEND | LOCK_EX);
echo $data."\n";
}
//------------------------------------------------------------------------------------
function connect_mysql () {
    global $config;
	global $connbdd;
	$connbdd = mysqli_connect ($config['config_mysql_host'], $config['config_mysql_user'], $config['config_mysql_password'], $config['config_mysql_db']);
	mysqli_query($connbdd, "SET NAMES 'utf8'");
    if (!mysqli_query($connbdd, "SET NAMES 'utf8'")) {
        return FALSE;
	}
    return TRUE;
}
//------------------------------------------------------------------------------------
function verif_mysql () {
    global $config;
	global $connbdd;
    $result = mysqli_query($connbdd, "SET NAMES 'utf8'");
    if (!$result) {
        $connbdd = mysqli_connect ($config['config_mysql_host'], $config['config_mysql_user'], $config['config_mysql_password'], $config['config_mysql_db']);
        $result = mysqli_query($connbdd, "SET NAMES 'utf8'");
        if (!$result) {
            return FALSE;
        }
        return TRUE;
    }
    return TRUE;

}
//------------------------------------------------------------------------------------
function exec_mysql($query) {
	global $config;
	global $connbdd;
	if (isset($connbdd)) {
		$result = mysqli_query($connbdd, $query);
		if (!$result) {
			connect_mysql();
			$result2 = mysqli_query($connbdd, $query);
			if (!$result2) {
				//logme ($query."\n\n".$result);
				//logme (mysqli_error($connbdd));
				return FALSE;
			}
			else {
				return $result2;
			}
		}
		else {
			return $result;
		}
	}
	else {
		connect_mysql();
		$result = mysqli_query($connbdd, $query);
		if (!$result) {
			//logme ($query."\n\n".$result);
			//logme (mysqli_error($connbdd));
			return FALSE;
		}
		else {
			return $result;
		}
	}
}
//------------------------------------------------------------------------------------
function readconfig() {
	global $config;
	if (file_exists("/etc/wprotect.conf")) {
		passthru("mv /etc/wprotect.conf /etc/wprotect/wprotect.conf");
	}
	if (!file_exists("/etc/wprotect/wprotect.conf")) {
		return FALSE;
	}
	$reader = new XMLReader(); 
	$reader->open("/etc/wprotect/wprotect.conf"); 
	while ($reader->read()) { 
		switch ($reader->nodeType)  { 
			case (XMLREADER::ELEMENT): 
				if ($reader->name == "security_key") { $reader->read(); $config['config_security_key'] = trim( $reader->value ); break; }
				if ($reader->name == "master_ip") { $reader->read(); $config['master_ip'] = trim( $reader->value ); break; }
				if ($reader->name == "master_port") { $reader->read(); $config['master_port'] = trim( $reader->value ); break; }
				if ($reader->name == "config_mysql_host") { $reader->read(); $config['config_mysql_host'] = trim( $reader->value ); break; }
				if ($reader->name == "config_mysql_user") { $reader->read(); $config['config_mysql_user'] = trim( $reader->value ); break; }
				if ($reader->name == "config_mysql_password") { $reader->read(); $config['config_mysql_password'] = trim( $reader->value ); break; }
				if ($reader->name == "config_mysql_db") { $reader->read(); $config['config_mysql_db'] = trim( $reader->value ); break; }
				if ($reader->name == "admin_interface") { $reader->read(); $config['admin_interface'] = trim( $reader->value ); break; }
				if ($reader->name == "theme") { $reader->read(); $config['theme'] = trim( $reader->value ); break; }
				if ($reader->name == "debug") { $reader->read(); $config['debug'] = trim( $reader->value ); break; }
				if ($reader->name == "wifi_access_point_ip") { $reader->read(); $config['wifi_access_point_ip'] = trim( $reader->value ); break; }
				if ($reader->name == "wifi_access_point_mac") { $reader->read(); $config['wifi_access_point_mac'] = trim( $reader->value ); break; }
				if ($reader->name == "public_interface") { $reader->read(); $config['public_interface'][1]['name'] = trim( $reader->value ); break; }
				if ($reader->name == "private_interface") { $reader->read(); $config['private_interface'][1]['name'] = trim( $reader->value ); break; }
				if ($reader->name == "bridge_interface") { $reader->read(); $config['bridge_interface'][1]['name'] = trim( $reader->value ); break; }
				if ($reader->name == "public2_interface") { $reader->read(); $config['public_interface'][2]['name'] = trim( $reader->value ); break; }
				if ($reader->name == "private2_interface") { $reader->read(); $config['private_interface'][2]['name'] = trim( $reader->value ); break; }
				if ($reader->name == "bridge2_interface") { $reader->read(); $config['bridge_interface'][2]['name'] = trim( $reader->value ); break; }
				if ($reader->name == "public3_interface") { $reader->read(); $config['public_interface'][3]['name'] = trim( $reader->value ); break; }
				if ($reader->name == "private3_interface") { $reader->read(); $config['private_interface'][3]['name'] = trim( $reader->value ); break; }
				if ($reader->name == "bridge3_interface") { $reader->read(); $config['bridge_interface'][3]['name'] = trim( $reader->value ); break; }
				if ($reader->name == "public4_interface") { $reader->read(); $config['public_interface'][4]['name'] = trim( $reader->value ); break; }
				if ($reader->name == "private4_interface") { $reader->read(); $config['private_interface'][4]['name'] = trim( $reader->value ); break; }
				if ($reader->name == "bridge4_interface") { $reader->read(); $config['bridge_interface'][4]['name'] = trim( $reader->value ); break; }
		}
	}
	
	$detected_config = array();
	$cu_iface="error";
	$handle = @fopen("/etc/network/interfaces", "r");
	if ($handle) {
		while (($buffer = fgets($handle, 4096)) !== false) {
			preg_match("/^\s*iface\s(?P<iface>[a-z,0-9]+)\sinet\s(?P<status>[a-z]+)$/", $buffer, $match);
			if (isset($match['iface']) AND isset($match['status'])) {
				$cu_iface=$match['iface'];
				$detected_config[$cu_iface]=array();
				$detected_config[$cu_iface]['status']=$match['status'];
			}
			preg_match("/^\s*address\s(?P<ip>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/", $buffer, $match);
			if (isset($match['ip'])) {
				$detected_config[$cu_iface]['ip']=$match['ip'];
			}
			preg_match("/^\s*netmask\s(?P<netmask>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/", $buffer, $match);
			if (isset($match['netmask'])) {
				$detected_config[$cu_iface]['netmask']=$match['netmask'];
			}
			preg_match("/^\s*network\s(?P<network>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/", $buffer, $match);
			if (isset($match['network'])) {
				$detected_config[$cu_iface]['network']=$match['network'];
			}
			preg_match("/^\s*gateway\s(?P<gateway>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/", $buffer, $match);
			if (isset($match['gateway'])) {
				$detected_config[$cu_iface]['gateway']=$match['gateway'];
			}
			preg_match("/^\s*dns-nameservers\s(?P<dns>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/", $buffer, $match);
			if (isset($match['dns'])) {
				$detected_config[$cu_iface]['dns']=$match['dns'];
			}
		}
		fclose($handle);
	}
	else {
		logme("INSTALL : Error reading network config exiting ...");
		exit();
	}
	$config['admin_ip'] = $detected_config[$config['admin_interface']]['ip'];
	
	$i=0;
	foreach ($config['bridge_interface'] AS $k=>$v) {
		$i++;
		if (isset($detected_config[$v['name']])) {
			$config['bridge_interface'][$k]['ip'] = $detected_config[$v['name']]['ip'];
			$config['bridge_interface'][$k]['netmask'] = $detected_config[$v['name']]['netmask'];
			$config['bridge_interface'][$k]['network'] = $detected_config[$v['name']]['network'];
		}
	}
	$config['public_network_number']=$i;
	logme ("INSTALL : ".$config['public_network_number']." réseaux public detectés ...");
	return TRUE;
}
//------------------------------------------------------------------------------------
function check_config_interfaces() {
	global $config;
	$detected_config = array();
	$cu_iface="error";
	if (!file_exists("/etc/network/interfaces")) {
		return false;
	}
	$handle = @fopen("/etc/network/interfaces", "r");
	if ($handle) {
		while (($buffer = fgets($handle, 4096)) !== false) {
			preg_match("/^\s*iface\s(?P<iface>[a-z,0-9]+)\sinet\s(?P<status>[a-z]+)$/", $buffer, $match);
			if (isset($match['iface']) AND isset($match['status'])) {
				$cu_iface=$match['iface'];
				$detected_config[$cu_iface]=array();
				$detected_config[$cu_iface]['status']=$match['status'];
				logme( "iface ".$match['iface']. " ".$match['status']);
			
			}
			preg_match("/^\s*address\s(?P<ip>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/", $buffer, $match);
			if (isset($match['ip'])) {
				$detected_config[$cu_iface]['ip']=$match['ip'];
				logme( "ip ".$match['ip']);
				
			}
			preg_match("/^\s*netmask\s(?P<netmask>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/", $buffer, $match);
			if (isset($match['netmask'])) {
				$detected_config[$cu_iface]['netmask']=$match['netmask'];
				logme ("netmask ".$match['netmask']);
				
			}
			preg_match("/^\s*network\s(?P<network>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/", $buffer, $match);
			if (isset($match['network'])) {
				$detected_config[$cu_iface]['network']=$match['network'];
				logme ("network ".$match['network']);
				
			}
			preg_match("/^\s*gateway\s(?P<gateway>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/", $buffer, $match);
			if (isset($match['gateway'])) {
				$detected_config[$cu_iface]['gateway']=$match['gateway'];
				logme( "gateway ".$match['gateway']);
				
			}
			preg_match("/^\s*dns-nameservers\s(?P<dns>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/", $buffer, $match);
			if (isset($match['dns'])) {
				$detected_config[$cu_iface]['dns']=$match['dns'];
				logme( "dns-nameservers ".$match['dns']);
				
			}
		}
		fclose($handle);
			//----check config ready-----
				if (!isset($detected_config['br0']['status']) OR $detected_config['br0']['status']!="static") return false;
				if (!isset($detected_config['br0']['ip'])) return false;
				if (!isset($detected_config['br0']['netmask'])) return false;
				return true;
			//--------------------------
	}
	else return false;
}
//------------------------------------------------------------------------------------
function configure_php_apc() {
	global $config;
	if (file_exists("/etc/php5/cli/conf.d/20-apcu.ini")) {
		activate_option_to_a_configfile("/etc/php5/cli/conf.d/20-apc.ini", "apc.enabled", "=", "1"); // active php APC for cli script
		activate_option_to_a_configfile("/etc/php5/cli/conf.d/20-apc.ini", "apc.enable_cli", "=", "1"); // active php APC for cli script
		activate_option_to_a_configfile("/etc/php5/cli/conf.d/20-apc.ini", "extension", "=", "apcu.so"); // active php APC for cli script
	}
	else if (file_exists("/etc/php/7.4/cli/conf.d/20-apcu.ini")) {
		activate_option_to_a_configfile("/etc/php/7.4/cli/conf.d/20-apcu.ini", "apc.enable_cli", "=", "1"); // active php APC for cli script
 	}
	else {
		activate_option_to_a_configfile("/etc/php5/cli/conf.d/20-apc.ini", "apc.enable_cli", "=", "1"); // active php APC for cli script
		activate_option_to_a_configfile("/etc/php5/cli/conf.d/20-apc.ini", "extension", "=", "apc.so"); // active php APC for cli script
	}
}
//------------------------------------------------------------------------------------
function mysql_install() {
	global $config;
	logme("INSTALL : création d\'une nouvelle BDD");
	$r=FALSE;
	while (!$r) {
		logme("Saisir le mot de pass root de la base de donnée :");
		$entry = stream_get_line (STDIN, 4096, "\n");
		if ($entry=="") exit(0);
		$cbdd = mysqli_connect ($config['config_mysql_host'], "root", $entry);
		if (mysqli_connect_errno()) $r=FALSE;
		else $r=true;
	}
	mysqli_query($cbdd, "CREATE USER '".$config['config_mysql_user']."'@'127.0.0.1' IDENTIFIED BY '".$config['config_mysql_password']."'");
	mysqli_query($cbdd, "GRANT USAGE ON *.* TO '".$config['config_mysql_user']."'@'127.0.0.1' IDENTIFIED BY '".$config['config_mysql_password']."' WITH MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0");
	mysqli_query($cbdd, "CREATE DATABASE IF NOT EXISTS wprotect");
	mysqli_query($cbdd, "GRANT ALL PRIVILEGES ON wprotect.* TO '".$config['config_mysql_user']."'@'127.0.0.1'");
	passthru("mysql -u root -p".$entry." wprotect < /opt/wprotect/wprotect_init.sql");
}
//------------------------------------------------------------------------------------
function mysql_upgrade() {
	global $config;
	global $connbdd;
	global $wprotect_version;
	exec_mysql("CREATE TABLE IF NOT EXISTS `data_volume` (
  `id` int(15) NOT NULL AUTO_INCREMENT,
  `mac` varchar(17) DEFAULT NULL,
  `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `dl` int(15) NOT NULL DEFAULT '0',
  `ul` int(15) NOT NULL DEFAULT '0',
  `id_login` int(10) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  KEY `mac` (`mac`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;");


exec_mysql("CREATE TABLE IF NOT EXISTS `bornes_config` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `bid` int(10) NOT NULL DEFAULT '0',
  `config` text NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;");

exec_mysql("CREATE TABLE IF NOT EXISTS `vip` (
  `mac` varchar(17) NOT NULL DEFAULT '',
  `description` text NOT NULL,
  UNIQUE KEY `mac` (`mac`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;");

exec_mysql("CREATE TABLE IF NOT EXISTS `network` (
  `id` int(1) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NOT NULL DEFAULT '',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;");

exec_mysql("INSERT INTO network SET id='1', name='WIFI' ON DUPLICATE KEY UPDATE id='1';");

exec_mysql("CREATE TABLE IF NOT EXISTS `pages` (
  `id` int(5) NOT NULL AUTO_INCREMENT,
  `type` int(1) NOT NULL DEFAULT '0',
  `page` text NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;");

exec_mysql("CREATE TABLE IF NOT EXISTS `pages_perso` (
  `id` int(5) NOT NULL AUTO_INCREMENT,
  `type` int(1) NOT NULL DEFAULT '0',
  `page` text NOT NULL,
  `name` varchar(100) NOT NULL,
  `lang` varchar(2) NOT NULL DEFAULT 'fr',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;");

exec_mysql("CREATE TABLE IF NOT EXISTS `net_connection` (
  `id` int(5) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NOT NULL DEFAULT '',
  `ip_to_check` varchar(15) NOT NULL DEFAULT '',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;");

exec_mysql("INSERT INTO net_connection SET id='1', name='WAN1', ip_to_check='8.8.8.8'");

	$result=exec_mysql("SELECT * FROM options");
	$t=array();
	while ($val=mysqli_fetch_array($result)) {
		$t[] = $val['name'];
	}
	//---------------DELETE----------------------------------------------------------------------
	if (in_array("squid_proxy_enable", $t)) {
		exec_mysql("DELETE FROM `wprotect`.`options` WHERE `options`.`name` = 'squid_proxy_enable';");
	}
	if (in_array("auto_archive", $t)) {
		exec_mysql("DELETE FROM `wprotect`.`options` WHERE `options`.`name` = 'auto_archive';");
	}
	if (in_array("time_archive", $t)) {
		exec_mysql("DELETE FROM `wprotect`.`options` WHERE `options`.`name` = 'time_archive';");
	}
	if (in_array("dauto_time", $t)) {
		exec_mysql("DELETE FROM `wprotect`.`options` WHERE `options`.`name` = 'dauto_time';");
	}
	if (in_array("dauto_status", $t)) {
		exec_mysql("DELETE FROM `wprotect`.`options` WHERE `options`.`name` = 'dauto_status';");
	}
	if (in_array("apple_mode_enable", $t)) {
		exec_mysql("DELETE FROM `wprotect`.`options` WHERE `options`.`name` = 'apple_mode_enable';");
	}
	if (in_array("pakets_out_limit", $t)) {
		exec_mysql("DELETE FROM `wprotect`.`options` WHERE `options`.`name` = 'pakets_out_limit';");
	}
	if (in_array("pakets_out_limit_burst", $t)) {
		exec_mysql("DELETE FROM `wprotect`.`options` WHERE `options`.`name` = 'pakets_out_limit_burst';");
	}
	if (in_array("free_wifi_welcome", $t)) {
		exec_mysql("DELETE FROM `wprotect`.`options` WHERE `options`.`name` = 'free_wifi_welcome';");
	}
	if (in_array("free_wifi_welcome_time", $t)) {
		exec_mysql("DELETE FROM `wprotect`.`options` WHERE `options`.`name` = 'free_wifi_welcome_time';");
	}
	//----------------ADD------------------------------------------------------------------------
	if (!in_array("download_max", $t)) {
		exec_mysql("INSERT INTO options SET name='download_max', value='10'");
	}
	if (!in_array("max_clients", $t)) {
		exec_mysql("INSERT INTO options SET name='max_clients', value='20'");
	}
	if (!in_array("load_ratio", $t)) {
		exec_mysql("INSERT INTO options SET name='load_ratio', value='2'");
	}
	if (!in_array("version", $t)) {
		exec_mysql("INSERT INTO options SET name='version', value='".$wprotect_version."'");
	}
	else {
		exec_mysql("UPDATE options SET value='".$wprotect_version."' WHERE name='version'");
	}
	if (!in_array("clean_database_old_than", $t)) {
		exec_mysql("INSERT INTO options SET name='clean_database_old_than', value='375'");
	}
	if (!in_array("clean_discover_useless", $t)) {
		exec_mysql("INSERT INTO options SET name='clean_discover_useless', value='3500'");
	}
	if (!in_array("time_idle_disconnect", $t)) {
		exec_mysql("INSERT INTO options SET name='time_idle_disconnect', value='180'");
	}
	if (!in_array("imp_num_col", $t)) {
		exec_mysql("INSERT INTO options SET name='imp_num_col', value='2'");
	}
	if (!in_array("redirect_active", $t)) {
		exec_mysql("INSERT INTO options SET name='redirect_active', value='0'");
	}
	if (!in_array("redirect_url", $t)) {
		exec_mysql("INSERT INTO options SET name='redirect_url', value='https://google.fr'");
	}
	if (!in_array("wispr_mode_enable", $t)) {
		exec_mysql("INSERT INTO options SET name='wispr_mode_enable', value='0'");
	}
	if (!in_array("default_user_conn_s", $t)) {
		exec_mysql("INSERT INTO options SET name='default_user_conn_s', value='0'");
	}
	if (!in_array("expire_time", $t)) {
		exec_mysql("INSERT INTO options SET name='expire_time', value='12:00'");
	}
	if (!in_array("bornes_admin_login", $t)) {
		exec_mysql("INSERT INTO options SET name='bornes_admin_login', value='admin'");
	}
	if (!in_array("bornes_admin_password", $t)) {
		exec_mysql("INSERT INTO options SET name='bornes_admin_password', value=''");
	}
	if (!in_array("imp_ticket_mode", $t)) {
		exec_mysql("INSERT INTO options SET name='imp_ticket_mode', value='0'");
	}
	if (!in_array("firewall_allow_vpn", $t)) {
		exec_mysql("INSERT INTO options SET name='firewall_allow_vpn', value='1'");
	}
	if (!in_array("lan_discover_cleaner", $t)) {
		exec_mysql("INSERT INTO options SET name='lan_discover_cleaner', value='360'");
	}
	if (!in_array("login_auto_clean", $t)) {
		exec_mysql("INSERT INTO options SET name='login_auto_clean', value='0'");
	}
	if (!in_array("beta_test", $t)) {
		exec_mysql("INSERT INTO options SET name='beta_test', value='0'");
	}
	if (!in_array("mail_send_objet", $t)) {
		exec_mysql("INSERT INTO options SET name='mail_send_objet', value='WIFI : vos identifiants de connexion'");
	}
	if (!in_array("mail_send_from", $t)) {
		exec_mysql("INSERT INTO options SET name='mail_send_from', value='test@test.fr'");
	}
	if (!in_array("mail_send_server", $t)) {
		exec_mysql("INSERT INTO options SET name='mail_send_server', value=''");
	}
	if (!in_array("mail_send_login", $t)) {
		exec_mysql("INSERT INTO options SET name='mail_send_login', value=''");
	}
	if (!in_array("mail_send_password", $t)) {
		exec_mysql("INSERT INTO options SET name='mail_send_password', value=''");
	}
	if (!in_array("ftp_backup_server", $t)) {
		exec_mysql("INSERT INTO options SET name='ftp_backup_server', value=''");
	}
	if (!in_array("ftp_backup_user", $t)) {
		exec_mysql("INSERT INTO options SET name='ftp_backup_user', value=''");
	}
	if (!in_array("ftp_backup_password", $t)) {
		exec_mysql("INSERT INTO options SET name='ftp_backup_password', value=''");
	}
	if (!in_array("ftp_backup_time", $t)) {
		exec_mysql("INSERT INTO options SET name='ftp_backup_time', value=''");
	}
	if (!in_array("portal_mobile_mode", $t)) {
		exec_mysql("INSERT INTO options SET name='portal_mobile_mode', value='0'");
	}
	if (!in_array("client_must_dhcp", $t)) {
		exec_mysql("INSERT INTO options SET name='client_must_dhcp', value='0'");
	}
	if (!in_array("smtp_from", $t)) {
		exec_mysql("INSERT INTO options SET name='smtp_from', value=''");
	}
	if (!in_array("smtp_server", $t)) {
		exec_mysql("INSERT INTO options SET name='smtp_server', value=''");
	}
	if (!in_array("smtp_port", $t)) {
		exec_mysql("INSERT INTO options SET name='smtp_port', value=''");
	}
	if (!in_array("smtp_username", $t)) {
		exec_mysql("INSERT INTO options SET name='smtp_username', value=''");
	}
	if (!in_array("smtp_password", $t)) {
		exec_mysql("INSERT INTO options SET name='smtp_password', value=''");
	}
	if (!in_array("seek_routeur_enable", $t)) {
		exec_mysql("INSERT INTO options SET name='seek_routeur_enable', value='0'");
	}
	if (in_array("wprotect_mac", $t)) {
		exec_mysql("DELETE FROM options WHERE name='wprotect_mac'");
	}
	if (in_array("routeur_mac", $t)) {
		exec_mysql("DELETE FROM options WHERE name='routeur_mac'");
	}
	if (in_array("wprotect_ip", $t)) {
		exec_mysql("DELETE FROM options WHERE name='wprotect_ip'");
	}
	if (in_array("routeur_ip", $t)) {
		exec_mysql("DELETE FROM options WHERE name='routeur_ip'");
	}
	if (!in_array("seek_rooter", $t)) {
		exec_mysql("INSERT INTO options SET name='seek_rooter', value='0'");
	}
	if (!in_array("seek_rooter_action", $t)) {
		exec_mysql("INSERT INTO options SET name='seek_rooter_action', value='log'");
	}
	if (!in_array("mail_mod_is_enable", $t)) {
		exec_mysql("INSERT INTO options SET name='mail_mod_is_enable', value='0'");
	}
	if (!in_array("debug_borne_watcher", $t)) {
		exec_mysql("DELETE FROM options WHERE name='debug_borne_watcher'");
	}
	if (!in_array("debug", $t)) {
		exec_mysql("INSERT INTO options SET name='debug', value='0'");
	}
	if (!in_array("auto_reboot_ap_time", $t)) {
		exec_mysql("INSERT INTO options SET name='auto_reboot_ap_time', value=''");
	}
	if (!in_array("disable_darkstats", $t)) {
		exec_mysql("INSERT INTO options SET name='disable_darkstats', value='1'");
	}
	if (!in_array("poll_bornes_status", $t)) {
		exec_mysql("INSERT INTO options SET name='poll_bornes_status', value='1'");
	}
	if (!in_array("apache_ddos_protection", $t)) {
		exec_mysql("INSERT INTO options SET name='apache_ddos_protection', value='0'");
	}
	if (!in_array("nginx_proxy_cache", $t)) {
		exec_mysql("INSERT INTO options SET name='nginx_proxy_cache', value='1'");
	}
	if (!in_array("mca_airmax", $t)) {
		exec_mysql("INSERT INTO options SET name='mca_airmax', value='0'");
	}
	if (!in_array("omada_name", $t)) {
		exec_mysql("INSERT INTO options SET name='omada_name', value=''");
	}
	if (!in_array("omada_pass", $t)) {
		exec_mysql("INSERT INTO options SET name='omada_pass', value=''");
	}
	if (!in_array("omada_ip", $t)) {
		exec_mysql("INSERT INTO options SET name='omada_ip', value=''");
	}
	if (!in_array("printer_ip", $t)) {
		exec_mysql("INSERT INTO options SET name='printer_ip', value=''");
	}
	if (!in_array("p2p_disconnect_device", $t)) {
		exec_mysql("INSERT INTO options SET name='p2p_disconnect_device', value='0'");
	}
	if (!in_array("captive_portal_https", $t)) {
		exec_mysql("INSERT INTO options SET name='captive_portal_https', value='0'");
	}
	//--------
	exec_mysql("ALTER TABLE `login`  ADD `language` VARCHAR(2) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT 'fr'");
	exec_mysql("ALTER TABLE `bornes`  ADD `status` INT(1) NOT NULL DEFAULT '0'");
	exec_mysql("ALTER TABLE  `bornes` ADD  `last_seen` TIMESTAMP NOT NULL DEFAULT 0");
	exec_mysql("ALTER TABLE `bornes`  ADD `model` VARCHAR(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT ''");
	exec_mysql("ALTER TABLE `bornes_config`  ADD `date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP");
	exec_mysql("ALTER TABLE `pages`  ADD `name` VARCHAR(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT ''");
	exec_mysql("ALTER TABLE `pages`  ADD `lang` VARCHAR(2) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT 'fr'");
	exec_mysql("ALTER TABLE `bornes`  ADD `version` VARCHAR(50) NOT NULL DEFAULT ''");
	exec_mysql("ALTER TABLE `bornes`  ADD `ssid` VARCHAR(50) NOT NULL DEFAULT ''");
	exec_mysql("ALTER TABLE `bornes`  ADD `mip` VARCHAR(15) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT ''");
	exec_mysql("ALTER TABLE `lan_discover` DROP `ticket`");
	exec_mysql("ALTER TABLE `log`  ADD `smac` VARCHAR(17) NOT NULL DEFAULT ''");
	exec_mysql("ALTER TABLE `log`  ADD `sip` VARCHAR(15) NOT NULL DEFAULT ''");
	exec_mysql("ALTER TABLE `session_login`  ADD `ip` VARCHAR(15) NOT NULL DEFAULT ''");
	exec_mysql("ALTER TABLE `login`  ADD `network` INT(1) NOT NULL DEFAULT '1'");
	exec_mysql("ALTER TABLE `lan_discover`  ADD `network` INT(1) NOT NULL DEFAULT '1'");
	exec_mysql("ALTER TABLE `session_login`  ADD `network` INT(1) NOT NULL DEFAULT '1'");
	exec_mysql("ALTER TABLE `log`  ADD `network` INT(1) NOT NULL DEFAULT '1'");
	exec_mysql("ALTER TABLE `pages`  ADD `network` INT(1) NOT NULL DEFAULT '0'");
	exec_mysql("ALTER TABLE `lan_discover` DROP INDEX `mac`");
	exec_mysql("ALTER TABLE `wprotect`.`lan_discover` ADD UNIQUE `macnet` (`mac`, `network`)");
	exec_mysql("ALTER TABLE `network`  ADD `vlan` VARCHAR(50) NOT NULL DEFAULT ''");
	exec_mysql("ALTER TABLE `data_volume`  ADD `network` INT(1) NOT NULL DEFAULT '1'");
	exec_mysql("ALTER TABLE `network`  ADD `firewall` INT(1) NOT NULL DEFAULT '1'");
	exec_mysql("ALTER TABLE `network`  ADD `cp_type` INT(1) NOT NULL DEFAULT '0'");
	exec_mysql("ALTER TABLE `network`  ADD `client_auto_disconnect_time` VARCHAR(5) NOT NULL DEFAULT '0'");
	exec_mysql("ALTER TABLE `bornes`  ADD `network` INT(1) NOT NULL DEFAULT '1'");
	exec_mysql("ALTER TABLE `login`  ADD `email` VARCHAR(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT ''");
	exec_mysql("DELETE FROM pages WHERE name='default'");
	exec_mysql("ALTER TABLE `pages` DROP `name`");
	exec_mysql("ALTER TABLE `pages` DROP `description`");
	exec_mysql("ALTER TABLE `bornes`  ADD `last_mca` TIMESTAMP NOT NULL");
	exec_mysql("ALTER TABLE `bornes`  ADD `nb_client` INT(4) NOT NULL DEFAULT '0'");
	exec_mysql("ALTER TABLE `bornes`  ADD `ccq` INT(3) NOT NULL DEFAULT '0'");
	exec_mysql("ALTER TABLE `bornes`  ADD `cpu` INT(3) NOT NULL DEFAULT '0'");
	exec_mysql("ALTER TABLE `bornes`  ADD `mem_use` INT(3) NOT NULL DEFAULT '0'");
	exec_mysql("ALTER TABLE `wprotect`.`options` DROP INDEX `name`, ADD UNIQUE `name` (`name`)");
	exec_mysql("ALTER TABLE `bornes`  ADD `last_ping` TIMESTAMP NOT NULL DEFAULT 0");
	exec_mysql("ALTER TABLE  `login` ADD  `no_auto_disconnect` BOOLEAN NOT NULL DEFAULT  '0'");
	exec_mysql("ALTER TABLE  `bornes` ADD  `last_config_save` TIMESTAMP NOT NULL DEFAULT 0");
	exec_mysql("ALTER TABLE  `bornes` ADD  `security_set` VARCHAR( 1 ) NOT NULL DEFAULT  ''");
	exec_mysql("ALTER TABLE  `bornes` ADD  `last_info` TIMESTAMP NOT NULL DEFAULT 0");
	exec_mysql("ALTER TABLE  `login` ADD  `no_delete` TINYINT( 1 ) NOT NULL DEFAULT  '0'");
	exec_mysql("ALTER TABLE  `network` ADD  `ip_routeur` VARCHAR( 15 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT  ''");
	exec_mysql("ALTER TABLE  `network` ADD  `mac_routeur` VARCHAR( 17 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT  ''");
	exec_mysql("ALTER TABLE  `network` ADD  `ip_wprotect` VARCHAR( 15 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT  ''");
	exec_mysql("ALTER TABLE  `network` ADD  `mac_wprotect` VARCHAR( 17 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT  ''");
	exec_mysql("ALTER TABLE  `bornes` ADD  `gamme` VARCHAR( 50 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT  '' AFTER  `last_seen`");
	exec_mysql("ALTER TABLE `vip` ADD PRIMARY KEY(`mac`)");
	exec_mysql("ALTER TABLE  `bornes` ADD  `network_add` VARCHAR( 3 ) NOT NULL DEFAULT  '' AFTER  `network`");
	exec_mysql("ALTER TABLE  `network` ADD  `unifi_iface` VARCHAR( 50 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT  ''");
	exec_mysql("ALTER TABLE `bornes` CHANGE `security_set` `security_set` VARCHAR(2) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT ''");
	exec_mysql("ALTER TABLE `bornes`  ADD `unifi_1_iface` VARCHAR(5) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT ''");
	exec_mysql("ALTER TABLE `bornes`  ADD `unifi_2_iface` VARCHAR(5) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT ''");
	exec_mysql("ALTER TABLE `bornes`  ADD `unifi_3_iface` VARCHAR(5) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT ''");
	exec_mysql("ALTER TABLE `bornes`  ADD `unifi_4_iface` VARCHAR(5) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT ''");
	exec_mysql("ALTER TABLE `bornes` CHANGE `unifi_1_iface` `unifi_1_iface` VARCHAR(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT ''");
	exec_mysql("ALTER TABLE `bornes` CHANGE `unifi_2_iface` `unifi_2_iface` VARCHAR(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT ''");
	exec_mysql("ALTER TABLE `bornes` CHANGE `unifi_3_iface` `unifi_3_iface` VARCHAR(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT ''");
	exec_mysql("ALTER TABLE `bornes` CHANGE `unifi_4_iface` `unifi_4_iface` VARCHAR(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT ''");
	exec_mysql("ALTER TABLE `network`  ADD `dl_min` INT(15) NOT NULL DEFAULT '0',  ADD `dl_max` INT(15) NOT NULL DEFAULT '0',  ADD `ul_min` INT(15) NOT NULL DEFAULT '0',  ADD `ul_max` INT(15) NOT NULL DEFAULT '0'");
	exec_mysql("ALTER TABLE `network`  ADD `dl_bucket` INT(15) NOT NULL DEFAULT '0',  ADD `ul_bucket` INT(15) NOT NULL DEFAULT '0'");
	exec_mysql("ALTER TABLE `lan_discover`  ADD `bid_connect` INT(15) NOT NULL DEFAULT '0'");
	exec_mysql("ALTER TABLE  `bornes` ADD  `iperf` VARCHAR( 10 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT  'N/A'");
	exec_mysql("ALTER TABLE  `lan_discover` ADD  `traff` INT( 15 ) NOT NULL DEFAULT  '0'");
	exec_mysql("ALTER TABLE  `lan_discover` ADD  `signal` INT( 3 ) NOT NULL");
	exec_mysql("ALTER TABLE `lan_discover` CHANGE `login_id` `login_id` INT( 10 ) NOT NULL DEFAULT '0'");
	exec_mysql("ALTER TABLE `lan_discover` CHANGE `signal` `signal` INT( 3 ) NOT NULL DEFAULT '0'");
	exec_mysql("ALTER TABLE `login` CHANGE `clients_id` `clients_id` INT( 5 ) NOT NULL DEFAULT '0'");
	exec_mysql("ALTER TABLE `bornes` CHANGE `ssid` `ssid` TEXT CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT ''");
	exec_mysql("ALTER TABLE `bornes` CHANGE `ccq` `ccq` INT(3) NOT NULL DEFAULT '0'");
	exec_mysql("ALTER TABLE `bornes` CHANGE `mem_use` `mem_use` INT(3) NOT NULL DEFAULT '0'");
	//--------
	exec_mysql("DELETE FROM menu WHERE action='options' AND affiche='Options'");
	exec_mysql("DELETE FROM menu WHERE action='editor' AND affiche='Editor'");
	exec_mysql("DELETE FROM menu WHERE action='stats_load_cpu'");
	exec_mysql("DELETE FROM menu WHERE action='stats_memory'");
	exec_mysql("DELETE FROM menu WHERE action='stats_firewall'");
	exec_mysql("DELETE FROM menu WHERE action='stats_web_server'");
	exec_mysql("DELETE FROM menu WHERE action='stats_traffic'");
	$result=exec_mysql("SELECT * FROM menu");
	$t=array();
	while ($val=mysqli_fetch_array($result)) {
		$t[] = $val['action'];
	}
	if (!in_array("login_list", $t)) {
		exec_mysql("INSERT INTO menu SET menu_id='1', smenu_id='0', affiche='Identifiants', `right`='5', action='login_list'");
	}
	else {
		exec_mysql("UPDATE menu SET menu_id='1', smenu_id='0', affiche='Identifiants' WHERE action='login_list'");
	}
	if (!in_array("lan_discover", $t)) {
		exec_mysql("INSERT INTO menu SET menu_id='2', smenu_id='0', affiche='Appareils', `right`='5', action='lan_discover'");
	}
	else {
		exec_mysql("UPDATE menu SET menu_id='2', smenu_id='0', affiche='Appareils' WHERE action='lan_discover'");
	}
	if (!in_array("iptrack_list", $t)) {
		exec_mysql("INSERT INTO menu SET menu_id='3', smenu_id='1', affiche='Connections', `right`='1', action='iptrack_list'");
	}
	else {
		exec_mysql("UPDATE menu SET menu_id='3', smenu_id='1', affiche='Connections' WHERE action='iptrack_list'");
	}
	if (!in_array("urltrack_list", $t)) {
		exec_mysql("INSERT INTO menu SET menu_id='3', smenu_id='2', affiche='URL visitées', `right`='1', action='urltrack_list'");
	}
	else {
		exec_mysql("UPDATE menu SET menu_id='3', smenu_id='2', affiche='URL visitées' WHERE action='urltrack_list'");
	}
	if (!in_array("save", $t)) {
		exec_mysql("INSERT INTO menu SET menu_id='5', smenu_id='1', affiche='Sauvegardes', `right`='1', action='save'");
	}
	else {
		exec_mysql("UPDATE menu SET menu_id='5', smenu_id='1', affiche='Sauvegardes' WHERE action='save'");
	}
	if (!in_array("options", $t)) {
		exec_mysql("INSERT INTO menu SET menu_id='7', smenu_id='1', affiche='Configuration', `right`='0', action='options'");
	}
	else {
		exec_mysql("UPDATE menu SET menu_id='7', smenu_id='1', affiche='Configuration' WHERE action='options'");
	}
	if (!in_array("firewall_list", $t)) {
		exec_mysql("INSERT INTO menu SET menu_id='7', smenu_id='2', affiche='Firewall', `right`='0', action='firewall_list'");
	}
	else {
		exec_mysql("UPDATE menu SET menu_id='7', smenu_id='2', affiche='Firewall' WHERE action='firewall_list'");
	}
	if (!in_array("bornes_list", $t)) {
		exec_mysql("INSERT INTO menu SET menu_id='7', smenu_id='3', affiche='Bornes Wifi', `right`='0', action='bornes_list'");
	}
	else {
		exec_mysql("UPDATE menu SET menu_id='7', smenu_id='3', affiche='Bornes Wifi' WHERE action='bornes_list'");
	}
	if (!in_array("mac_ignore", $t)) {
		exec_mysql("INSERT INTO menu SET menu_id='7', smenu_id='4', affiche='MAC ignore', `right`='0', action='mac_ignore'");
	}
	else {
		exec_mysql("UPDATE menu SET menu_id='7', smenu_id='4', affiche='MAC ignore' WHERE action='mac_ignore'");
	}
	if (!in_array("forbidden_network_list", $t)) {
		exec_mysql("INSERT INTO menu SET menu_id='7', smenu_id='5', affiche='Réseaux interdits', `right`='0', action='forbidden_network_list'");
	}
	else {
		exec_mysql("UPDATE menu SET menu_id='7', smenu_id='5', affiche='Réseaux interdits' WHERE action='forbidden_network_list'");
	}
	if (!in_array("cert_passthrough", $t)) {
		exec_mysql("INSERT INTO menu SET menu_id='7', smenu_id='6', affiche='Sites autorisés', `right`='0', action='cert_passthrough'");
	}
	else {
		exec_mysql("UPDATE menu SET menu_id='7', smenu_id='6', affiche='Sites autorisés' WHERE action='cert_passthrough'");
	}
	if (!in_array("vip_edit", $t)) {
		exec_mysql("INSERT INTO menu SET menu_id='7', smenu_id='7', affiche='VIP', `right`='0', action='vip_edit'");
	}
	else {
		exec_mysql("UPDATE menu SET menu_id='7', smenu_id='7', affiche='VIP' WHERE action='vip_edit'");
	}
	if (!in_array("statistiques", $t)) {
		exec_mysql("INSERT INTO menu SET menu_id='8', smenu_id='0', affiche='Statistiques', `right`='1', action='statistiques'");
	}
	else {
		exec_mysql("UPDATE menu SET menu_id='8', smenu_id='0', affiche='Statistiques' WHERE action='statistiques'");
	}
	if (!in_array("log", $t)) {
		exec_mysql("INSERT INTO menu SET menu_id='9', smenu_id='0', affiche='Logs', `right`='5', action='log'");
	}
	else {
		exec_mysql("UPDATE menu SET menu_id='9', smenu_id='0', affiche='Logs' WHERE action='log'");
	}
	if (!in_array("editor", $t)) {
		exec_mysql("INSERT INTO menu SET menu_id='10', smenu_id='1', affiche='Authentification FR', `right`='1', action='editor'");
	}
	else {
		exec_mysql("UPDATE menu SET menu_id='10', smenu_id='1', affiche='Authentification FR' WHERE action='editor'");
	}
	if (!in_array("wifi_network", $t)) {
		exec_mysql("INSERT INTO menu SET menu_id='7', smenu_id='8', affiche='Réseaux WIFI', `right`='0', action='wifi_network'");
	}
	else {
		exec_mysql("UPDATE menu SET menu_id='7', smenu_id='8', affiche='Réseaux WIFI' WHERE action='wifi_network'");
	}
	if (!in_array("extract", $t)) {
		exec_mysql("INSERT INTO menu SET menu_id='11', smenu_id='0', affiche='Extraction', `right`='0', action='extract'");
	}
	else {
		exec_mysql("UPDATE menu SET menu_id='11', smenu_id='0', affiche='Extraction' WHERE action='extract'");
	}
	
	//--------update menu V1.100 for single menu editor----
	exec_mysql("UPDATE menu SET smenu_id='0', affiche='Editeur' WHERE action='editor'");
	exec_mysql("DELETE FROM menu WHERE action='editor_en'");
	exec_mysql("DELETE FROM menu WHERE action='editor_conditions'");
	exec_mysql("DELETE FROM menu WHERE action='editor_conditions_en'");
	exec_mysql("DELETE FROM menu WHERE action='editor_card'");
	exec_mysql("DELETE FROM menu WHERE action='editor_card_en'");
	exec_mysql("DELETE FROM menu WHERE action='editor_already_auth'");
	exec_mysql("DELETE FROM menu WHERE action='editor_already_auth_en'");
	exec_mysql("DELETE FROM menu WHERE action='archive'");
	exec_mysql("DELETE FROM menu WHERE action='iptrack_list'");
	exec_mysql("DELETE FROM menu WHERE action='urltrack_list'");
	exec_mysql("UPDATE menu SET smenu_id='0' WHERE action='save'");
	load_default_pages_to_mysql();
	$result=exec_mysql("SELECT * FROM pages");
	$t=array();
	while ($val=mysqli_fetch_array($result)) {
		$t[$val['type']][$val['lang']][$val['network']] = $val['page'];
	}
	$result=exec_mysql("SELECT * FROM pages_default");
	$u=array();
	while ($val=mysqli_fetch_array($result)) {
		$u[$val['type']][$val['lang']] = $val['page'];
	}
	for ($i = 1; $i <= 4; $i++) {
		if (!isset($t[0]['fr'][$i])) {
			exec_mysql("INSERT INTO pages SET type='0', lang='fr', network='".$i."', page='".mysqli_real_escape_string( $connbdd, stripslashes($u[0]['fr']))."'");
		}
		if (!isset($t[0]['en'][$i])) {
			exec_mysql("INSERT INTO pages SET type='0', lang='en', network='".$i."', page='".mysqli_real_escape_string( $connbdd, stripslashes($u[0]['en']))."'");
		}
		if (!isset($t[2]['fr'][$i])) {
			exec_mysql("INSERT INTO pages SET type='2', lang='fr', network='".$i."', page='".mysqli_real_escape_string( $connbdd, stripslashes($u[2]['fr']))."'");
		}
		if (!isset($t[2]['en'][$i])) {
			exec_mysql("INSERT INTO pages SET type='2', lang='en', network='".$i."', page='".mysqli_real_escape_string( $connbdd, stripslashes($u[2]['en']))."'");
		}
		if (!isset($t[3]['fr'][$i])) {
			exec_mysql("INSERT INTO pages SET type='3', lang='fr', network='".$i."', page='".mysqli_real_escape_string( $connbdd, stripslashes($u[3]['fr']))."'");
		}
		if (!isset($t[3]['en'][$i])) {
			exec_mysql("INSERT INTO pages SET type='3', lang='en', network='".$i."', page='".mysqli_real_escape_string( $connbdd, stripslashes($u[3]['en']))."'");
		}
	}
	if (!isset($t[1]['fr'][0])) {
		logme("reset by default Card FR");
		exec_mysql("INSERT INTO pages SET type='1', lang='fr', network='0', page='".mysqli_real_escape_string( $connbdd, stripslashes($u[1]['fr']))."'");
	}
	if (!isset($t[1]['en'][0])) {
		logme("reset by default Card EN");
		exec_mysql("INSERT INTO pages SET type='1', lang='en', network='0', page='".mysqli_real_escape_string( $connbdd, stripslashes($u[1]['en']))."'");
	}
	
	//Upgrade DNS passtrought
	exec_mysql("DELETE FROM firewall_certificat WHERE dns='mscrl.microsoft.com'");
	exec_mysql("DELETE FROM firewall_certificat WHERE dns='crl.microsoft.com'");
	exec_mysql("DELETE FROM firewall_certificat WHERE dns='ctldl.windowsupdate.com'");
	exec_mysql("DELETE FROM firewall_certificat WHERE dns='www.startssl.com'");
	exec_mysql("DELETE FROM firewall_certificat WHERE dns='crl.startssl.com ocsp.startssl.com aia.startssl.com'");
	exec_mysql("DELETE FROM firewall_certificat WHERE dns='crl.startssl.com'");
	exec_mysql("DELETE FROM firewall_certificat WHERE dns='ocsp.startssl.com'");
	exec_mysql("DELETE FROM firewall_certificat WHERE dns='aia.startssl.com'");
	exec_mysql("INSERT INTO firewall_certificat SET dns='cert.int-x3.letsencrypt.org', ip=''");
	exec_mysql("INSERT INTO firewall_certificat SET dns='dl.ui.com', ip=''");
	exec_mysql("INSERT INTO firewall_certificat SET dns='dl.ubnt.com', ip=''");
	exec_mysql("INSERT INTO firewall_certificat SET dns='d2cnv2pop2xy4v.cloudfront.net', ip=''");
	
	//Add index on table for performance memory cache
	mysql_add_index_if_not_exist("vip", "mac");
	mysql_add_index_if_not_exist("thread", "pid");
	mysql_add_index_if_not_exist("session_login", "mac");
	mysql_add_index_if_not_exist("session_login", "id_login");
	mysql_add_index_if_not_exist("session_login", "ip");
	mysql_add_index_if_not_exist("pages_perso", "type");
	mysql_add_index_if_not_exist("pages_default", "type");
	mysql_add_index_if_not_exist("pages", "type");
	mysql_add_index_if_not_exist("options", "name");
	mysql_add_index_if_not_exist("menu", "menu_id");
	mysql_add_index_if_not_exist("menu", "smenu_id");
	mysql_add_index_if_not_exist("menu", "right");
	mysql_add_index_if_not_exist("mac_ignore_list", "mac");
	mysql_add_index_if_not_exist("login", "clients_id");
	mysql_add_index_if_not_exist("login", "disable");
	mysql_add_index_if_not_exist("login", "clogin");
	mysql_add_index_if_not_exist("login", "network");
	mysql_add_index_if_not_exist("log", "smac");
	mysql_add_index_if_not_exist("log", "sip");
	mysql_add_index_if_not_exist("log", "network");
	mysql_add_index_if_not_exist("lan_discover", "mac");
	mysql_add_index_if_not_exist("lan_discover", "ip");
	mysql_add_index_if_not_exist("lan_discover", "login_id");
	mysql_add_index_if_not_exist("lan_discover", "network");
	mysql_add_index_if_not_exist("lan_discover", "authorize");
	mysql_add_index_if_not_exist("firewall_certificat", "ip");
	mysql_add_index_if_not_exist("data_volume", "mac");
	mysql_add_index_if_not_exist("data_volume", "id_login");
	mysql_add_index_if_not_exist("bornes_config", "bid");
	mysql_add_index_if_not_exist("bornes", "ip");
	mysql_add_index_if_not_exist("bornes", "mac");
	$result=exec_mysql("SELECT `AUTO_INCREMENT` FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'wprotect' AND TABLE_NAME = 'pages_perso';");
	$val=mysqli_fetch_array($result);
	if (isset($val['AUTO_INCREMENT'])) {
		if ($val['AUTO_INCREMENT']<999) {
			exec_mysql("ALTER TABLE pages_perso AUTO_INCREMENT=1000;");
		}
	}
}
//------------------------------------------------------------------------------------
function mysql_add_index_if_not_exist($table, $index) {
	$r=exec_mysql("SHOW INDEX FROM ".$table." WHERE Key_name = '".$index."'");
	$v=mysqli_fetch_array($r);
	if (!isset($v['Key_name'])) {
		exec_mysql("ALTER TABLE `".$table."` ADD INDEX ( `".$index."` )");
	}
}
//------------------------------------------------------------------------------------
function gen_pages_from_mysql() {
	global $config;
	global $connbdd;
	$result=exec_mysql("SELECT * FROM pages");
	$t=array();
	while ($val=mysqli_fetch_array($result)) {
		$t[$val['type']][$val['lang']][$val['network']] = $val['page'];
	}
	for ($i = 1; $i <= 4; $i++) {
		file_put_contents ("/var/www/portal".$i."/themes/default/index.tpl", $t[0]['fr'][$i]);
		file_put_contents ("/var/www/portal".$i."/themes/default/index_en.tpl", $t[0]['en'][$i]);
		file_put_contents ("/var/www/portal".$i."/themes/default/conditions.tpl", $t[2]['fr'][$i]);
		file_put_contents ("/var/www/portal".$i."/themes/default/conditions_en.tpl", $t[2]['en'][$i]);
		file_put_contents ("/var/www/portal".$i."/themes/default/already_connect.tpl", $t[3]['fr'][$i]);
		file_put_contents ("/var/www/portal".$i."/themes/default/already_connect_en.tpl", $t[3]['en'][$i]);
	}
	file_put_contents ("/var/www/admin/themes/default/card.tpl", $t[1]['fr'][0]);
	file_put_contents ("/var/www/admin/themes/default/card_en.tpl", $t[1]['en'][0]);
}
//------------------------------------------------------------------------------------
function configure_apache2() {
	global $config;
	if (file_exists("/etc/apache2/sites-available/default-ssl")) {
		passthru("rm /etc/apache2/sites-available/default-ssl");
	}
	if (file_exists("/etc/apache2/sites-available/default")) {
		passthru("rm /etc/apache2/sites-available/default");
	}
	if (file_exists("/var/www/index.html")) {
		passthru("rm /var/www/index.html");
	}
	
	passthru("cp /etc/wprotect/apache2/wprotect.sample /etc/apache2/sites-available/wprotect.conf");
	if (version_compare(phpversion(), '6.0.0', '>')) {
		passthru("cp /etc/wprotect/apache2/apache2.conf.9 /etc/apache2/apache2.conf");
	}
	else {
		passthru("cp /etc/wprotect/apache2/apache2.conf /etc/apache2/apache2.conf");
	}
	passthru("a2enmod rewrite");
	passthru("a2enmod ssl");
	passthru("a2enmod headers");
	passthru("a2enmod expires");
	passthru("a2enmod rpaf");
	passthru("a2enmod ssl");
	passthru("a2dismod mod-evasive");
	passthru("a2dismod cache");
	passthru("echo '' > /etc/apache2/ports.conf");
	passthru("sed -i 's/A.A.A.A/".$config['admin_ip']."/g' /etc/apache2/sites-available/wprotect.conf");
	passthru("a2dissite wprotect");
	passthru("a2ensite wprotect.conf");
	passthru("a2dissite 000-default");
	passthru("a2dissite default");
	foreach ($config['bridge_interface'] AS $k=>$v) {
		passthru("cp /etc/wprotect/apache2/portal".$k.".sample /etc/apache2/sites-available/portal".$k.".conf");
		$s = chr(65+$k);
		passthru("sed -i 's/".$s.".".$s.".".$s.".".$s."/".$v['ip']."/g' /etc/apache2/sites-available/portal".$k.".conf");
	}
	for ($m=1; $m < 5; $m++) {
		passthru("a2dissite portal".$m);
	}
	foreach ($config['bridge_interface'] AS $k=>$v) {
		passthru("a2ensite portal".$k.".conf");
	}
	if (file_exists("/etc/apache2/sites-available/portal1")) {
		passthru("rm /etc/apache2/sites-available/portal1");
	}
	if (file_exists("/etc/apache2/sites-available/portal2")) {
		passthru("rm /etc/apache2/sites-available/portal2");
	}
	if (file_exists("/etc/apache2/sites-available/portal3")) {
		passthru("rm /etc/apache2/sites-available/portal3");
	}
	if (file_exists("/etc/apache2/sites-available/portal4")) {
		passthru("rm /etc/apache2/sites-available/portal4");
	}
	if (file_exists("/etc/apache2/sites-available/portal1")) {
		passthru("rm /etc/apache2/sites-available/portal1");
	}
	if (file_exists("/etc/apache2/sites-available/portal2")) {
		passthru("rm /etc/apache2/sites-available/portal2");
	}
	if (file_exists("/etc/apache2/sites-available/portal3")) {
		passthru("rm /etc/apache2/sites-available/portal3");
	}
	if (file_exists("/etc/apache2/sites-available/wprotect")) {
		passthru("rm /etc/apache2/sites-available/wprotect");
	}
}
//------------------------------------------------------------------------------------
function set_file_permission() {
	global $config;
	passthru("chmod 777 /var/www/admin/themes/default/card.tpl");
	passthru("chmod 777 /var/www/portal1/themes/default/already_connect.tpl");
	passthru("chown www-data:root -R /var/www/admin");
	passthru("chown www-data:root -R /var/www/portal1");
	passthru("chown www-data:root -R /var/www/portal2");
	passthru("chown www-data:root -R /var/www/portal3");
	passthru("chown www-data:root -R /var/www/portal4");
	passthru("chmod +x /etc/init.d/wprotect");
	if (!file_exists("/var/log/wprotect/api.log")) {
		passthru("touch /var/log/wprotect/api.log");
	}
	if (!file_exists("/var/log/wprotect/direct_print_ticket.log")) {
		passthru("touch /var/log/wprotect/direct_print_ticket.log");
	}
	passthru("chmod 777 /var/log/wprotect/api.log");
	passthru("chmod 777 /var/log/wprotect/api.log");
	passthru("chmod +x /opt/wprotect/wprotect");
	passthru("chmod +x /opt/wprotect/install");
	passthru("chmod +x /opt/wprotect/wp_backup");
	passthru("chmod +x /opt/wprotect/wp_restore");
	passthru("chmod +x /opt/wprotect/wifi");
	passthru("chmod 777 /opt/wprotect/wifi");
	//passthru("chmod 777 /opt/wprotect/hosts.local");
	//passthru("chmod 777 /opt/wprotect/hosts.perso");
	passthru("systemctl enable wprotect");
	passthru("mkdir -p /backup");
	passthru("mkdir -p /archive");
	passthru("mkdir -p /opt/wprotect/firmware");
	passthru("chmod 777 /opt/wprotect/firmware");
}
//------------------------------------------------------------------------------------
function load_default_pages_to_mysql() {
	global $config;
	global $connbdd;
	myexec("mysql --force -h ".$config['config_mysql_host']." -u ".$config['config_mysql_user']." -p".$config['config_mysql_password']." wprotect < /etc/wprotect/default_pages.sql");
	myexec("mysql --force -h ".$config['config_mysql_host']." -u ".$config['config_mysql_user']." -p".$config['config_mysql_password']." wprotect < /etc/wprotect/default_perso.sql");
	
	//load old pages format to current pages
	$result=exec_mysql("SELECT * FROM pages");
	while ($val=mysqli_fetch_array($result)) {
		$a[$val['type']][$val['lang']][$val['network']] = 1;
	}
	
	if (file_exists("/var/www/portal/themes/default/index.tpl")) {
		$t=file_get_contents("/var/www/portal/themes/default/index.tpl");
		if (isset($a[0]['fr'][1])) exec_mysql("UPDATE pages SET page='".mysqli_real_escape_string( $connbdd, stripslashes($t))."' WHERE type='0' AND lang='fr' AND network='1'");
		else exec_mysql("INSERT INTO pages SET type='0', lang='fr', network='1', page='".mysqli_real_escape_string( $connbdd, stripslashes($t))."'");
		rename ("/var/www/portal/themes/default/index.tpl", "/var/www/portal/themes/default/index.tpl.old");
	}
	
	if (file_exists("/var/www/portal/themes/default/index_en.tpl")) {
		$t=file_get_contents("/var/www/portal/themes/default/index_en.tpl");
		if (isset($a[0]['en'][1])) exec_mysql("UPDATE pages SET page='".mysqli_real_escape_string( $connbdd, stripslashes($t))."' WHERE type='0' AND lang='en' AND network='1'");
		else exec_mysql("INSERT INTO pages SET type='0', lang='en', network='1', page='".mysqli_real_escape_string( $connbdd, stripslashes($t))."'");
		rename ("/var/www/portal/themes/default/index_en.tpl", "/var/www/portal/themes/default/index_en.tpl.old");
	}
	
	if (file_exists("/var/www/admin/themes/default/card.tpl")) {
		$t=file_get_contents("/var/www/admin/themes/default/card.tpl");
		if (isset($a[1]['fr'][0])) exec_mysql("UPDATE pages SET page='".mysqli_real_escape_string( $connbdd, stripslashes($t))."' WHERE type='1' AND lang='fr' AND network='0'");
		else exec_mysql("INSERT INTO pages SET type='1', lang='fr', network='0', page='".mysqli_real_escape_string( $connbdd, stripslashes($t))."'");
	}
	
	if (file_exists("/var/www/admin/themes/default/card_en.tpl")) {
		$t=file_get_contents("/var/www/admin/themes/default/card_en.tpl");
		if (isset($a[1]['en'][0])) exec_mysql("UPDATE pages SET page='".mysqli_real_escape_string( $connbdd, stripslashes($t))."' WHERE type='1' AND lang='en' AND network='0'");
		else exec_mysql("INSERT INTO pages SET type='1', lang='en', network='0', page='".mysqli_real_escape_string( $connbdd, stripslashes($t))."'");
	}
	
	if (file_exists("/var/www/portal/themes/default/conditions.tpl")) {
		$t=file_get_contents("/var/www/portal/themes/default/conditions.tpl");
		if (isset($a[2]['fr'][1])) exec_mysql("UPDATE pages SET page='".mysqli_real_escape_string( $connbdd, stripslashes($t))."' WHERE type='2' AND lang='fr' AND network='1'");
		else exec_mysql("INSERT INTO pages SET type='2', lang='fr', network='1', page='".mysqli_real_escape_string( $connbdd, stripslashes($t))."'");
		rename ("/var/www/portal/themes/default/conditions.tpl", "/var/www/portal/themes/default/conditions.tpl.old");
	}
	
	if (file_exists("/var/www/portal/themes/default/conditions_en.tpl")) {
		$t=file_get_contents("/var/www/portal/themes/default/conditions_en.tpl");
		if (isset($a[2]['en'][1])) exec_mysql("UPDATE pages SET page='".mysqli_real_escape_string( $connbdd, stripslashes($t))."' WHERE type='2' AND lang='en' AND network='1'");
		else exec_mysql("INSERT INTO pages SET type='2', lang='en', network='1', page='".mysqli_real_escape_string( $connbdd, stripslashes($t))."'");
		rename ("/var/www/portal/themes/default/conditions_en.tpl", "/var/www/portal/themes/default/conditions_en.tpl.old");
	}
	
	if (file_exists("/var/www/portal/themes/default/already_connect.tpl")) {
		$t=file_get_contents("/var/www/portal/themes/default/already_connect.tpl");
		if (isset($a[3]['fr'][1])) exec_mysql("UPDATE pages SET page='".mysqli_real_escape_string( $connbdd, stripslashes($t))."' WHERE type='3' AND lang='fr' AND network='1'");
		else exec_mysql("INSERT INTO pages SET type='3', lang='fr', network='1', page='".mysqli_real_escape_string( $connbdd, stripslashes($t))."'");
		rename ("/var/www/portal/themes/default/already_connect.tpl", "/var/www/portal/themes/default/already_connect.tpl.old");
	}
	
	if (file_exists("/var/www/portal/themes/default/already_connect_en.tpl")) {
		$t=file_get_contents("/var/www/portal/themes/default/already_connect_en.tpl");
		if (isset($a[3]['en'][1])) exec_mysql("UPDATE pages SET page='".mysqli_real_escape_string( $connbdd, stripslashes($t))."' WHERE type='3' AND lang='en' AND network='1'");
		else exec_mysql("INSERT INTO pages SET type='3', lang='en', network='1', page='".mysqli_real_escape_string( $connbdd, stripslashes($t))."'");
		rename ("/var/www/portal/themes/default/already_connect_en.tpl", "/var/www/portal/themes/default/already_connect_en.tpl.old");
	}
}
//------------------------------------------------------------------------------------
function configure_sysctl() {
	global $config;
	$tmp = array();
	$tmp[1][1] = "net.ipv6.conf.all.disable_ipv6=1";
	$tmp[1][0] = "net.ipv6.conf.all.disable_ipv6=0";
	$tmp[2][1] = "net.ipv6.conf.default.disable_ipv6=1";
	$tmp[2][0] = "net.ipv6.conf.default.disable_ipv6=0";
	$tmp[3][1] = "net.ipv6.conf.lo.disable_ipv6=1";
	$tmp[3][0] = "net.ipv6.conf.lo.disable_ipv6=0";
	$tmp[4][1] = "net.ipv6.conf.all.accept_redirects = 0";
	$tmp[4][0] = "net.ipv6.conf.all.accept_redirects = 1";
	$tmp[5][1] = "net.ipv6.conf.all.accept_source_route = 0";
	$tmp[5][0] = "net.ipv6.conf.all.accept_source_route = 1";
	$handle = @fopen("/etc/sysctl.conf", "r+");
	if ($handle) {
		while (($buffer = fgets($handle, 4096)) !== false) {
			foreach ($tmp AS $k=>$v) {
				if ($buffer==$v[0]."\n") {
					fputs($handle, $v[1]."\n");
					break;
				}
				if ($buffer==$v[1]."\n") {
					$tmp[$k][2]=1;
					break;
				}
			}
		}
		foreach ($tmp AS $k=>$v) {
			if (!isset($v[2])) {
				fputs($handle, $v[1]."\n");
			}
		}
		if (!feof($handle)) {
		}
		fclose($handle);
	}
}
//------------------------------------------------------------------------------------
function configure_dnsmasq() {
	global $config;
	passthru("echo '' > /etc/dnsmasq.conf");
	passthru("/etc/init.d/dnsmasq stop");
	
}
//------------------------------------------------------------------------------------
function configure_munin() {
	global $config;
	passthru("rm /etc/munin/plugins/*");
	passthru("ln -s /usr/share/munin/plugins/apache_accesses /etc/munin/plugins/apache_accesses");
	passthru("ln -s /usr/share/munin/plugins/cpu /etc/munin/plugins/cpu");
	passthru("ln -s /opt/wprotect/wifi /etc/munin/plugins/wifi");
	passthru("ln -s /opt/wprotect/mysql_stat_size /etc/munin/plugins/mysql_stat_size");
	if (version_compare(phpversion(), '6.0.0', '<')) {
		passthru("ln -s /usr/share/munin/plugins/if_ /etc/munin/plugins/if_eth2");
		passthru("ln -s /usr/share/munin/plugins/if_ /etc/munin/plugins/if_eth4");
		passthru("ln -s /usr/share/munin/plugins/if_ /etc/munin/plugins/if_eth6");
	}
	else {
		passthru("ln -s /usr/share/munin/plugins/if_ /etc/munin/plugins/if_ens20");
		passthru("ln -s /usr/share/munin/plugins/if_ /etc/munin/plugins/if_ens22");
		passthru("ln -s /usr/share/munin/plugins/if_ /etc/munin/plugins/if_ens24");
	}
	passthru("ln -s /usr/share/munin/plugins/memory /etc/munin/plugins/memory");
	passthru("ln -s /usr/share/munin/plugins/load /etc/munin/plugins/load");
	passthru("ln -s /usr/share/munin/plugins/fw_packets /etc/munin/plugins/fw_packets");
	passthru("ln -s /usr/share/munin/plugins/fw_conntrack /etc/munin/plugins/fw_conntrack");
	passthru("ln -s /usr/share/munin/plugins/mysql_queries /etc/munin/plugins/mysql_queries");
	passthru("chmod -R 777 /etc/munin/plugins");
}
//------------------------------------------------------------------------------------
function configure_darkstat() {
	global $config;
	activate_option_to_a_configfile("/etc/darkstat/init.cfg", "START_DARKSTAT", "=", "yes"); 
	activate_option_to_a_configfile("/etc/darkstat/init.cfg", "INTERFACE", "=", "\"-i br0\"");
	activate_option_to_a_configfile("/etc/darkstat/init.cfg", "DIR", "=", "\"/var/lib/darkstat\"");
	activate_option_to_a_configfile("/etc/darkstat/init.cfg", "PORT", "=", "\"-p 666\"");
	activate_option_to_a_configfile("/etc/darkstat/init.cfg", "BINDIP", "=", "\"-b 0.0.0.0\"");
	activate_option_to_a_configfile("/etc/darkstat/init.cfg", "LOCAL", "=", "\"-l ".$config['public_network']."/".$config['public_subnet']."\"");
	activate_option_to_a_configfile("/etc/darkstat/init.cfg", "DNS", "=", "\"--no-dns\"");
	activate_option_to_a_configfile("/etc/darkstat/init.cfg", "OPTIONS", "=", "\"--local-only\"");
}
//------------------------------------------------------------------------------------
function configure_portal_files() {
	passthru("rm -R /var/www/portal2");
	passthru("rm -R /var/www/portal3");
	passthru("rm -R /var/www/portal4");
	passthru("mkdir -p /var/www/portal1/fileman");
	passthru("mkdir -p /var/www/portal2/fileman");
	passthru("mkdir -p /var/www/portal3/fileman");
	passthru("mkdir -p /var/www/portal4/fileman");
	passthru("ln -s /var/www/admin/fileman/Uploads /var/www/portal1/fileman/");
	passthru("ln -s /var/www/admin/fileman/Uploads /var/www/portal2/fileman/");
	passthru("ln -s /var/www/admin/fileman/Uploads /var/www/portal3/fileman/");
	passthru("ln -s /var/www/admin/fileman/Uploads /var/www/portal4/fileman/");
	passthru("ln -s /var/www/portal1/index.php /var/www/portal2/index.php");
	passthru("ln -s /var/www/portal1/index.php /var/www/portal3/index.php");
	passthru("ln -s /var/www/portal1/index.php /var/www/portal4/index.php");
	passthru("ln -s /var/www/portal1/speedtest.php /var/www/portal2/speedtest.php");
	passthru("ln -s /var/www/portal1/speedtest.php /var/www/portal3/speedtest.php");
	passthru("ln -s /var/www/portal1/speedtest.php /var/www/portal4/speedtest.php");
	passthru("ln -s /var/www/portal1/report.php /var/www/portal2/report.php");
	passthru("ln -s /var/www/portal1/report.php /var/www/portal3/report.php");
	passthru("ln -s /var/www/portal1/report.php /var/www/portal4/report.php");
	passthru("ln -s /var/www/portal1/lib /var/www/portal2/lib");
	passthru("ln -s /var/www/portal1/lib /var/www/portal3/lib");
	passthru("ln -s /var/www/portal1/lib /var/www/portal4/lib");
	passthru("ln -s /var/www/portal1/css /var/www/portal2/css");
	passthru("ln -s /var/www/portal1/css /var/www/portal3/css");
	passthru("ln -s /var/www/portal1/css /var/www/portal4/css");
	passthru("echo '<?php \$network=1; ?>' > /var/www/portal1/network.php");
	passthru("echo '<?php \$network=2; ?>' > /var/www/portal2/network.php");
	passthru("echo '<?php \$network=3; ?>' > /var/www/portal3/network.php");
	passthru("echo '<?php \$network=4; ?>' > /var/www/portal4/network.php");
	passthru("mkdir -p /var/www/portal2/themes/default");
	passthru("mkdir -p /var/www/portal3/themes/default");
	passthru("mkdir -p /var/www/portal4/themes/default");
	passthru("ln -s /var/www/portal1/themes/default/error.tpl /var/www/portal2/themes/default/error.tpl");
	passthru("ln -s /var/www/portal1/themes/default/error.tpl /var/www/portal3/themes/default/error.tpl");
	passthru("ln -s /var/www/portal1/themes/default/error.tpl /var/www/portal4/themes/default/error.tpl");
	passthru("ln -s /var/www/portal1/themes/default/footer.tpl /var/www/portal2/themes/default/footer.tpl");
	passthru("ln -s /var/www/portal1/themes/default/footer.tpl /var/www/portal3/themes/default/footer.tpl");
	passthru("ln -s /var/www/portal1/themes/default/footer.tpl /var/www/portal4/themes/default/footer.tpl");
	passthru("ln -s /var/www/portal1/themes/default/header.tpl /var/www/portal2/themes/default/header.tpl");
	passthru("ln -s /var/www/portal1/themes/default/header.tpl /var/www/portal3/themes/default/header.tpl");
	passthru("ln -s /var/www/portal1/themes/default/header.tpl /var/www/portal4/themes/default/header.tpl");
	passthru("ln -s /var/www/portal1/themes/default/header2.tpl /var/www/portal2/themes/default/header2.tpl");
	passthru("ln -s /var/www/portal1/themes/default/header2.tpl /var/www/portal3/themes/default/header2.tpl");
	passthru("ln -s /var/www/portal1/themes/default/header2.tpl /var/www/portal4/themes/default/header2.tpl");
	passthru("ln -s /var/www/portal1/themes/default/wispr_login.tpl /var/www/portal2/themes/default/wispr_login.tpl");
	passthru("ln -s /var/www/portal1/themes/default/wispr_login.tpl /var/www/portal3/themes/default/wispr_login.tpl");
	passthru("ln -s /var/www/portal1/themes/default/wispr_login.tpl /var/www/portal4/themes/default/wispr_login.tpl");
	passthru("ln -s /var/www/portal1/themes/default/wispr_logoff.tpl /var/www/portal2/themes/default/wispr_logoff.tpl");
	passthru("ln -s /var/www/portal1/themes/default/wispr_logoff.tpl /var/www/portal3/themes/default/wispr_logoff.tpl");
	passthru("ln -s /var/www/portal1/themes/default/wispr_logoff.tpl /var/www/portal4/themes/default/wispr_logoff.tpl");
	passthru("ln -s /var/www/portal1/themes/default/wispr_status.tpl /var/www/portal2/themes/default/wispr_status.tpl");
	passthru("ln -s /var/www/portal1/themes/default/wispr_status.tpl /var/www/portal3/themes/default/wispr_status.tpl");
	passthru("ln -s /var/www/portal1/themes/default/wispr_status.tpl /var/www/portal4/themes/default/wispr_status.tpl");
	passthru("ln -s /var/www/portal1/themes/default/wispr.tpl /var/www/portal2/themes/default/wispr.tpl");
	passthru("ln -s /var/www/portal1/themes/default/wispr.tpl /var/www/portal3/themes/default/wispr.tpl");
	passthru("ln -s /var/www/portal1/themes/default/wispr.tpl /var/www/portal4/themes/default/wispr.tpl");
	passthru("ln -s /opt/wprotect/firmware /var/www/portal1/firmware");
	passthru("ln -s /var/www/portal1/themes/default/speedtest.tpl /var/www/portal2/themes/default/speedtest.tpl");
	passthru("ln -s /var/www/portal1/themes/default/speedtest.tpl /var/www/portal3/themes/default/speedtest.tpl");
	passthru("ln -s /var/www/portal1/themes/default/speedtest.tpl /var/www/portal4/themes/default/speedtest.tpl");
	gen_pages_from_mysql();
}
//------------------------------------------------------------------------------------
function update_certs() {
	logme("UPDATE CERTIFICATS started ...");
	$cert = file_get_contents("https://connectoo.fr/wprotect/cert", false);
	$key = file_get_contents("https://connectoo.fr/wprotect/key", false);
	if (isset($cert) AND $cert!="" AND isset($key) AND $key!="") {
		file_put_contents("/etc/ssl/certs/acces-wifi.ovh.crt", $cert);
		file_put_contents("/etc/ssl/private/acces-wifi.ovh.key", $key);
		myexec("/etc/init.d/apache2 reload");
		logme("UPDATE CERTIFICATS : OK");
		return true;
	}
	logme("UPDATE CERTIFICATS : FAILED ...");
	return false;
}
//------------------------------------------------------------------------------------
function configure_mysql() {
	global $config;
	//activate_option_to_a_configfile("/etc/mysql/my.cnf", "expire_logs_days", "=", "1");
	//activate_option_to_a_configfile("/etc/mysql/my.cnf", "wait_timeout", "=", "3600");
	//activate_option_to_a_configfile("/etc/mysql/my.cnf", "connect_timeout", "=", "60");
	//activate_option_to_a_configfile("/etc/mysql/my.cnf", "max_allowed_packet", "=", "64M");
	//activate_option_to_a_configfile("/etc/mysql/my.cnf", "max_connections", "=", "100");
}
//--------------------S T A R T----------------------------
passthru("mkdir -p /var/log/wprotect");
logme("INSTALL : start ...");
if (!check_config_interfaces()) {
	logme("INSTALL : interfaces not config - config interfaces and restart install ...");
	logme("INSTALL : terminated not completed ...");
	exit();
}
if (!readconfig()) {
	logme("INSTALL : Wprotect n\'est pas configuré...");
	logme("INSTALL : créer le fichier de config et redémarrer l\'installation ...");
	exit();
}
if (!connect_mysql ()) {
	logme("INSTALL : Install wprotect BDD ...");
	mysql_install();
	logme("INSTALL : Install wprotect BDD DONE !");
	logme("INSTALL : upgrade wprotect BDD ...");
	mysql_upgrade();
	logme("INSTALL : upgrade wprotect BDD DONE !");
}
else {
	logme("INSTALL : upgrade wprotect BDD ...");
	mysql_upgrade();
	logme("INSTALL : upgrade wprotect BDD DONE !");
}
logme("INSTALL : configure wprotect BDD ...");
configure_mysql();
logme("INSTALL : Configure wprotect DONE !");
logme("INSTALL : Configure apache2 ...");
configure_apache2();
logme("INSTALL : Configure apache2 DONE !");
logme("INSTALL : Configure NGINX ...");
nginx_configure();
logme("INSTALL : Configure NGINX done!");
logme("INSTALL : Configure sysctl...");
configure_sysctl();
logme("INSTALL : Configure sysctl DONE !");
logme("INSTALL : Configure dnsmasq ...");
configure_dnsmasq();
logme("INSTALL : Configure dnsmasq DONE !");
logme("INSTALL : Configure munin ...");
configure_munin();
logme("INSTALL : Configure munin DONE !");
logme("INSTALL : Configure php apc ...");
configure_php_apc();
logme("INSTALL : Configure php apc DONE !");
logme("INSTALL : Configure darkstat ...");
configure_darkstat();
logme("INSTALL : Configure darkstat DONE !");
logme("INSTALL : configure portal pages ...");
configure_portal_files();
logme("INSTALL : configure portal pages DONE !");
logme("INSTALL : configure files permissions ...");
set_file_permission();
logme("INSTALL : configure files permissions DONE !");
logme("DOWNLOAD speedtest file ...");
passthru("wget http://www.connectoo.fr/speedtest.jpg -O /var/www/portal1/speedtest.jpg");
if (!file_exists("/var/www/portal1/iperf.bin") OR (filesize("/var/www/portal1/iperf.bin") < 7000000)) {
	myexec("cp /var/www/portal1/speedtest.jpg /var/www/portal1/iperf.bin; cat /var/www/portal1/speedtest.jpg >> /var/www/portal1/iperf.bin; cat /var/www/portal1/speedtest.jpg >> /var/www/portal1/iperf.bin; cat /var/www/portal1/speedtest.jpg >> /var/www/portal1/iperf.bin && echo /var/www/portal1/speedtest.jpg >> /var/www/portal1/iperf.bin; cat /var/www/portal1/speedtest.jpg >> /var/www/portal1/iperf.bin; cat /var/www/portal1/speedtest.jpg >> /var/www/portal1/iperf.bin");
}
passthru("chmod 777 /var/www/portal1/speedtest.jpg");
passthru("chmod 777 /var/www/portal1/iperf.bin");
passthru("ln -s /var/www/portal1/speedtest.jpg /var/www/portal2/speedtest.jpg");
passthru("ln -s /var/www/portal1/speedtest.jpg /var/www/portal3/speedtest.jpg");
passthru("ln -s /var/www/portal1/speedtest.jpg /var/www/portal4/speedtest.jpg");
passthru("ln -s /var/www/portal1/iperf.bin /var/www/portal2/iperf.bin");
passthru("ln -s /var/www/portal1/iperf.bin /var/www/portal3/iperf.bin");
passthru("ln -s /var/www/portal1/iperf.bin /var/www/portal4/iperf.bin");
passthru("mv /var/www/portal /var/www/portal.old");
passthru("mkdir -p /var/log/wprotect/extract");
update_certs();
logme("DOWNLOAD finished");
logme("INSTALL : Terminated !");
?>
