<?php
session_start(); ?>
<?php
$filename = 'idl_multi.php';
if (!file_exists($filename)) {
	@rename ("_idl_multi.php", "idl_multi.php");
}
@include('idl_multi.php');
require_once(dirname(__DIR__, 1) . '/config.php');
if(@$multi=="ON") {
	if(@$multipref==1) {
		$_SESSION['etabchoix'] = substr($_POST['login'],0,5);
	}
	else {
		$_SESSION['etabchoix'] = $_POST['etabchoix'];
	}
	include('idl_multi.php');
	require_once(BASE_PATH . '/db/idl_connect.php');
}
else {
	require_once(BASE_PATH . '/db/idl_connect.php');
}

$table_name = $prefix . "_parametres";
$check_table = mysqli_query($bdd, "SHOW TABLES LIKE '$table_name'");
if (mysqli_num_rows($check_table) > 0) {
	if(isset($_POST['login'])&&isset($_POST['mdp'])) {
		if(@$multi=="ON"&&@$multipref==1) {
			$log1 = mysqli_real_escape_string($bdd,substr($_POST['login'],5));
		}
		else {
			$log1 = mysqli_real_escape_string($bdd,$_POST['login']);
		}
		$log2 = mysqli_real_escape_string($bdd,$_POST['mdp']);
		$_SESSION['essai_con']=0;
	}
	else { $_SESSION['essai_con']++; }

	if(!isset($prefix)) { $prefix = 'idlog'; }
	if(isset($log1)&&isset($log2)&&$log1!=""&&$log2!=""&&$_SESSION['essai_con']<6) {
		$css = mysqli_query($bdd,"SELECT valeur FROM ".$prefix."_parametres WHERE param_nom = 'version_bdd'");
		$cssbdd = mysqli_fetch_assoc($css);
		$verif_user = mysqli_query($bdd,"SELECT * FROM ".$prefix."_user WHERE login = '$log1'");
		if(mysqli_num_rows($verif_user)==0) {
			$reserv_could=mysqli_fetch_assoc(mysqli_query($bdd,"SELECT valeur FROM ".$prefix."_parametres WHERE param_nom = 'freq_reseleve'"));
			if($reserv_could['valeur']==1&&$log1=='reserver') {
				$log3 = mysqli_real_escape_string($bdd,$_POST['mdp']);
				$reserv_exist = mysqli_fetch_assoc(mysqli_query($bdd,"SELECT * FROM ".$prefix."_parametres WHERE param_nom = 'freq_reseleve_mdp'"));
				$reserv_existsel = mysqli_fetch_assoc(mysqli_query($bdd,"SELECT * FROM ".$prefix."_parametres WHERE param_nom = 'freq_reseleve_mdpsel'"));
				if ($reserv_existsel['valeur'] === '0') {
					// Méthode PASSWORD
					if(mysqli_num_rows(mysqli_query($bdd,"SELECT * FROM ".$prefix."_parametres WHERE param_nom = 'freq_reseleve_mdp' AND valeur = PASSWORD('$log3')"))>0) {
						$logincheck = 'OK';
						do {
						    $sel = bin2hex(random_bytes(16));
						} while ($sel === '0');
						$mdp_avec_sel = $log3.$sel;
						$hashed_password = hash('sha256', $mdp_avec_sel);
						mysqli_query($bdd,"UPDATE ".$prefix."_parametres SET valeur='".$hashed_password."' WHERE param_nom = 'freq_reseleve_mdp'");
						mysqli_query($bdd,"UPDATE ".$prefix."_parametres SET valeur='".$sel."' WHERE param_nom = 'freq_reseleve_mdpsel'");
					}
					else {
						$logincheck = 'KO';
					}
				}
				else {
					// Méthode SHA-256
			        $mdp_avec_sel = $log3.$reserv_existsel['valeur'];
			        $hashed_password = hash('sha256', $mdp_avec_sel);
			        if ($hashed_password === $reserv_exist['valeur']) {
			            $logincheck = 'OK';
					}
					else {
						$logincheck = 'KO';
					}
				}
				if($logincheck == 'KO') {
					?><script language="Javascript">
					<!--
					document.location.replace("../index.php");
					// -->
					</script><?php
				}
				else {
					$_SESSION['userres_droits'] = 1;
					if(@$multipref==1) {
						@$_SESSION['etabchoix'] = @substr($_POST['login'],0,5);
					}
					else {
						@$_SESSION['etabchoix'] = @$_POST['etabchoix'];
					}
					$_SESSION['essai_res']=0;
					?><script language="Javascript">
					<!--
					document.location.replace("../reserver.php");
					// -->
					</script><?php
				}				
			}
			else if($reserv_could['valeur']==2) {
				if($cssbdd['valeur']>0.47) {
					$auth_info = mysqli_fetch_assoc(mysqli_query($bdd,"SELECT valeur FROM ".$prefix."_parametres WHERE param_nom = 'freq_resmodauth'"));
					if($auth_info['valeur']=="prenomnom"||$auth_info['valeur']=="pnom") {
						$identmod = "id_constr";
					}
					else if($auth_info['valeur']=="perso") {
						$identmod = "id_perso";
					}
					else {
						$identmod = "code";
					}
				}
				else {
					$identmod = "code";
				}
				$reserv_exist = mysqli_query($bdd,"SELECT * FROM ".$prefix."_eleves WHERE ".$identmod." = '$log1'");
				if(mysqli_num_rows($reserv_exist)>0) {
					$user_info = mysqli_fetch_assoc($reserv_exist);
					$_SESSION['lang'] = $user_info['lang'];
					if (@$user_info['sel'] === '0' || @$user_info['sel'] === 'NULL') {
						// Méthode PASSWORD
						if(mysqli_num_rows(mysqli_query($bdd,"SELECT * FROM ".$prefix."_eleves WHERE ".$identmod." = '$log1' AND mdp = PASSWORD('$log2')"))>0) {
							$logincheck = 'OK';
							do {
							    $sel = bin2hex(random_bytes(16));
							} while ($sel === '0');
							$mdp_avec_sel = $log2.$sel;
							$hashed_password = hash('sha256', $mdp_avec_sel);
							mysqli_query($bdd,"UPDATE ".$prefix."_eleves SET mdp='".$hashed_password."', sel = '".$sel."' WHERE ".$identmod." = '".$log1."'");
						}
						else {
							$logincheck = 'KO';
						}
					}
					else {
						// Méthode SHA-256
				        $mdp_avec_sel = $log2.$user_info['sel'];
				        $hashed_password = hash('sha256', $mdp_avec_sel);
				        if ($hashed_password === $user_info['mdp']) {
				            $logincheck = 'OK';
						}
						else {
							$logincheck = 'KO';
						}
					}
					if($logincheck == 'KO') {
						?><script language="Javascript">
						<!--
						document.location.replace("../index.php");
						// -->
						</script><?php
					}
					else {
						$_SESSION['userres_droits'] = 1;
						if(@$multipref==1) {
							@$_SESSION['etabchoix'] = @substr($_POST['login'],0,5);
						}
						else {
							@$_SESSION['etabchoix'] = @$_POST['etabchoix'];
						}
						$_SESSION['coderes'] = $log1;
						$_SESSION['essai_res']=0;					
						?><script language="Javascript">
						<!--
						document.location.replace("../reserver.php");
						// -->
						</script><?php
					}						
				}
				else {
					$_SESSION['essai_con']++;
					if($_SESSION['essai_con']>5) {
						$_SESSION['essai_con_mes'] = '<p class="signal">'.ESSAIS1.'</p>';
					}
					?><script language="Javascript">
					<!--
					document.location.replace("../index.php");
					// -->
					</script><?php
				}
			}
			else {
				$_SESSION['essai_con']++;
				if($_SESSION['essai_con']>5) {
					$_SESSION['essai_con_mes'] = '<p class="signal">'.ESSAIS1.'</p>';
				}
				?><script language="Javascript">
				<!--
				document.location.replace("../index.php");
				// -->
				</script><?php
			}
		}
		else {
			$user_info = mysqli_fetch_assoc($verif_user);
			if($cssbdd['valeur']<0.50) {
				// Méthode PASSWORD
				if(mysqli_num_rows(mysqli_query($bdd,"SELECT * FROM ".$prefix."_user WHERE login = '$log1' AND mdp = PASSWORD('$log2')"))>0) {
					$logincheck = 'OK';
				}
				else {
					$logincheck = 'KO';
				}
			}
			else if ($user_info['sel'] === '0') {
				// Méthode PASSWORD
				if(mysqli_num_rows(mysqli_query($bdd,"SELECT * FROM ".$prefix."_user WHERE login = '$log1' AND mdp = PASSWORD('$log2')"))>0) {
					$logincheck = 'OK';
					do {
					    $sel = bin2hex(random_bytes(16));
					} while ($sel === '0');
					$mdp_avec_sel = $log2.$sel;
					$hashed_password = hash('sha256', $mdp_avec_sel);
					mysqli_query($bdd,"UPDATE ".$prefix."_user SET mdp='".$hashed_password."', sel = '".$sel."' WHERE login = '".$log1."'");
				}
				else {
					$logincheck = 'KO';
				}
			}
			else {
				// Méthode SHA-256
		        $mdp_avec_sel = $log2.$user_info['sel'];
		        $hashed_password = hash('sha256', $mdp_avec_sel);
		        if ($hashed_password === $user_info['mdp']) {
		            $logincheck = 'OK';
				}
				else {
					$logincheck = 'KO';
				}
			}
			if($logincheck=='OK') {
				$_SESSION['user_droits'] = $user_info['droits'];
				$specdroits = explode(';',$user_info['droits_spe']);
				$_SESSION['minutes'] = $specdroits[0];
				$_SESSION['nbcren'] = $specdroits[1];
				$_SESSION['inscprec'] = $specdroits[2];
				$_SESSION['crenchoix'] = $specdroits[3];
				$_SESSION['classinscript'] = $specdroits[4];
				$_SESSION['affgroupe'] = $specdroits[5];
				$_SESSION['journalmodif'] = $specdroits[6];
				$_SESSION['buttonsor'] = $specdroits[7];
				$_SESSION['buttonexc'] = $specdroits[8];
				$_SESSION['retardsaff1'] = $specdroits[9];
				$_SESSION['retardsaff2'] = $specdroits[10];
				$_SESSION['accesjournal'] = @$specdroits[11];
				$_SESSION['freqinscritsafter'] = @$specdroits[12];
				$_SESSION['inscriptallday'] = @$specdroits[13];
				$_SESSION['freqonlyresas'] = @$specdroits[14];
				$_SESSION['freqvalidmes'] = @$specdroits[15];
				$_SESSION['freqcodeonly'] = @$specdroits[16];
				$_SESSION['affresa_norights'] = @$specdroits[17];
				
				$_SESSION['user_id'] = $user_info['id'];
				$_SESSION['login'] = $user_info['login'];
				$_SESSION['lang'] = $user_info['lang'];
				$_SESSION['accueil'] = $user_info['accueil'];
				$_SESSION['auth_mail'] = $user_info['auth_mail'];
				$_SESSION['auth_chat'] = $user_info['auth_chat'];
				$_SESSION['freq_res_dureemax'] = $user_info['freq_res_dureemax'];
				if(isset($_SERVER['HTTPS'] ) ) { $http='https://'; } else { $http = 'http://'; }
				$_SESSION['url_base'] = $http.$_SERVER["HTTP_HOST"].substr($_SERVER["REQUEST_URI"],0,-13);
				$_SESSION['connected_info'] = $user_info['connected_info'];
				if(@$multi=="ON"&&@$multipref==1) {
					$_SESSION['prefident'] = $prefident;
				}
				if(@$multi=="ON") {
					if(@$multipref==1) {
						$_SESSION['etabchoix'] = substr($_POST['login'],0,5);
					}
					else {
						$_SESSION['etabchoix'] = $_POST['etabchoix'];
					}
				}
							
				$dnns = mysqli_fetch_array(mysqli_query($bdd,"SELECT COUNT(user_id) AS nb FROM ".$prefix."_userconnect WHERE user_id='".$user_info['id']."'"));
		        if($dnns['nb']>0) {
		            mysqli_query($bdd,"UPDATE ".$prefix."_userconnect SET connected='".time()."' WHERE user_id='".$user_info['id']."'");
		        }
		        else {
		            mysqli_query($bdd,"INSERT INTO ".$prefix."_userconnect (user_id, connected) values ('".$user_info['id']."', '".time()."')");
		        }											
				if(!empty($user_info['espace_default'])) {
					$_SESSION['espuser'] = $user_info['espace_default']; 
				}
				$_SESSION['align_activ'] = $user_info['align_activ'];
				$_SESSION['align_espace'] = $user_info['align_espace'];
							
				// Version installée du logiciel
				$url = '../version.txt';
				$vers_offurl = htmlspecialchars(implode('', file($url)));
				$vers_offic = substr($vers_offurl, 0, strpos($vers_offurl,"/"));
				// On passe la version du logiciel dans la BDD si besoin :
				$versin = mysqli_query($bdd,"SELECT valeur FROM ".$prefix."_parametres WHERE param_nom = 'version_log'");
				$versin_info = mysqli_fetch_assoc($versin);
				if($versin_info['valeur']!=$vers_offic) {
					mysqli_query($bdd,"UPDATE ".$prefix."_parametres SET valeur = '".$vers_offic."' WHERE param_nom = 'version_log'");
				}

				// Gestion des mises à jour de la base de données
				if($_SESSION['user_droits'][4]=="2") {
					if($dossier = opendir('../db/bddmaj')) {
						$versinb = mysqli_query($bdd,"SELECT valeur FROM ".$prefix."_parametres WHERE param_nom = 'version_bdd'");
						$versinb_info = mysqli_fetch_assoc($versinb);
						while(false !== ($fichier = readdir($dossier))) {
							if($fichier != '.' && $fichier != '..') {
								$verscheck = substr($fichier,3,1).'.'.substr($fichier,4,2);
								if($verscheck>$versinb_info['valeur']) {
									?><script language="Javascript">
									<!--
									document.location.replace("../param.php?page=majlog");
									// -->
									</script><?php
								}
							}
						}
					}
				}
				
				// Suppression des fichiers d'installation :
				if ($server != "127.0.0.1" && $server != "localhost") {
				    $filename = './install.php';
				    
				    // Vérification de l'existence du fichier avant suppression
				    if (file_exists($filename)) {
				        // Essayer de supprimer le fichier, avec gestion d'erreur en cas d'échec
				        if (!unlink($filename)) {
				            // Si l'effacement échoue, tu pourrais loguer l'erreur ou faire quelque chose ici
				            error_log("Impossible de supprimer le fichier $filename");
				        }
				    }
				}
				// Vérification du calendrier :
				$dday = date("Y-m-d");
				$cal = mysqli_query($bdd,"SELECT * FROM ".$prefix."_calendrier WHERE date = '".$dday."'");
				$cal_nb = mysqli_num_rows($cal);
				if($cal_nb==0) {
					$date = new DateTime($dday);
					for($i=0;$i<366;$i++) {
						mysqli_query($bdd,"INSERT INTO ".$prefix."_calendrier (date, statut) VALUES ('".date_format($date, 'Y-m-d')."', 1)");
						$date->modify('+1 day');
					}
				}

				if(@$multi=="ON") { //mémorisation de la base par cookie si multi
					setcookie(
						'LOGGED_ETAB',
						$_SESSION['etabchoix'],
						[
							'domain' => $_SERVER["SERVER_NAME"],
							'expires' => time() + 90*24*3600,
							'secure' => true,
							'SameSite' => 'Strict',
							'path' => '/',
						]
					);
					setcookie(
					    'PREFIX',
					    $prefix,
					    [
					        'domain' => $_SERVER["SERVER_NAME"],
					        'expires' => time() + 90*24*3600,
					        'secure' => true,
					        'SameSite' => 'Strict',
					        'path' => '/',
					    ]
					);
					setcookie(
					    'LANGM',
					    $_SESSION['lang'],
					    [
					        'domain' => $_SERVER["SERVER_NAME"],
					        'expires' => time() + 90*24*3600,
					        'secure' => true,
					        'SameSite' => 'Strict',
					        'path' => '/',
					    ]
					);
					setcookie(
						'CLASS_INS',
						$_SESSION['classinscript'],
						[
							'domain' => $_SERVER["SERVER_NAME"],
							'expires' => time() + 90*24*3600,
							'secure' => true,
							'SameSite' => 'Strict',
							'path' => '/',
						]
					);
				}

				// Redirection après actions précédentes :
				$redirect = array('','eval','edit','edt','freq','param','database');
				if($_SESSION['accueil']> 0&&$_SESSION['accueil']< 7) {
					?><script language="Javascript">
					<!--
					document.location.replace("../<?php echo$redirect[$_SESSION['accueil']]; ?>.php");
					// -->
					</script><?php
				}		
				else {
					$check_droits = $user_info['droits'];
					$check_eval = substr("$check_droits", 0, 1);
					$check_edit = substr("$check_droits", 1, 1);
					$check_edt = substr("$check_droits", 2, 1);
					$check_freq = substr("$check_droits", 3, 1);
					$check_param = substr("$check_droits", 4, 1);
					$check_database = substr("$check_droits", 5, 1);
					$redircheck = array('freq','edt','edit','eval','database','param');
					$checkedredir=0;
					foreach($redircheck as $suffix) {
						if(${'check_'.$suffix}==0||(${'check_'.$suffix}>1&&${'check_'.$suffix}<7)) {
							?><script language="Javascript">
							<!--
							document.location.replace("../<?php echo $suffix; ?>.php");
							// -->
							</script><?php
							$checkedredir=1;
						}
					}					
					if($checkedredir==0) {
						echo NOACCESS;
					}				
				}
			}
			else {
				$_SESSION['essai_con']++;
				if($_SESSION['essai_con']>5) {
					$_SESSION['essai_con_mes'] = '<p class="signal">'.ESSAIS1.'</p>';
				}
				?><script language="Javascript">
				<!--
				document.location.replace("../index.php");
				// -->
				</script><?php
			}
		}
	}
	else {
		$_SESSION['essai_con']++;
		if($_SESSION['essai_con']>5) {
			$_SESSION['essai_con_mes'] = '<p class="signal">'.ESSAIS1.'</p>';
		}
		?><script language="Javascript">
		<!--
		document.location.replace("../index.php");
		// -->
		</script><?php
	}
}
else {
	if($multi=='ON') {
		if(isset($server)) {
			$_POST['server'] = $server;
			$_POST['user'] = $user;
			$_POST['pwd'] = $pwd;
			$_POST['base'] = $base;
			$_POST['prefix'] = $prefix;
			$_POST['prefident'] = @$prefident;
			include('install_tables.php');
		}
		else {
			?><script language="Javascript">
			<!--
			document.location.replace("../index.php");
			// -->
			</script><?php
		}
	}
}
mysqli_close($bdd);
?>
