<?
require_once ('include/general.php');

session_start();
$login = $_SESSION['login'] = $_POST['login'];
$_SESSION['uni'] = "uni4";
function get_ip() {
    if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    elseif(isset($_SERVER['HTTP_CLIENT_IP'])) {
        $ip  = $_SERVER['HTTP_CLIENT_IP'];
    }
    else {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}
$_SESSION['ip'] = get_ip();
include 'config.php';

//$login=$_POST['login'];
$pass = $_POST['passs'];
$mail=$_POST['mail'];

$key = "8Z5q7?&Pu!?M!?5Xs";
$passs = md5($pass.$key);


/*
$paz = 'paz';

$test = strripos($login,$paz);

if( $test === false ) {
	echo '<script language=javascript> alert ("Pseudo contient paz à l adresse '.$test.'");</script>';
}*/
/*
if( $login == "S\'paz" ) {
	echo '<script language=javascript> alert ("Coucou Spaz");</script>';
}
if( $login == "S'paz" ) {
	echo '<script language=javascript> alert ("Coucou Spaz sans \");</script>';
}

echo '<script language=javascript> alert ("Coucou '.stripslashes($login).'");</script>';
*/
/*
if($login != "M@tttt34" && $login != "Bin alors tu connais pas ton pseudo" && $login != "Spaz")
{
echo '<script language=javascript> alert ("Univers fermé pour mise a jours.");</script>';

echo '<script language="javascript" type="text/javascript">
<!--
window.location.replace("http://www.sg-univers.fr/");
-->
</script>';
session_destroy();
exit;
}
*/


// L ip est elle ban

$sql = "SELECT id, date FROM matgraph_banni_ip WHERE ip = '".get_ip()."'";
$req = db_mysql_Query($sql) or die('Erreur SQL !<br>'.$sql.'<br>'.mysql_error());
if( $data = mysql_fetch_array($req) ) {
	// Ohh, est elle toujours ban ?
	$datetime = $data['date'];

	ereg ("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2}) ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})", $datetime, $thetime);
	$time = mktime($thetime[4],$thetime[5],$thetime[6],$thetime[2],$thetime[3],$thetime[1]);

	$diftemps = time() - $time;

	if( $diftemps > 0 ) {
		// Il ne l est plus, snif
		$sql = "DELETE FROM matgraph_banni_ip WHERE id = $data[id]";
		$req = db_mysql_Query($sql) or die('Erreur SQL !<br>'.$sql.'<br>'.mysql_error());
	} else {
		// Petit message ?
		echo '<script language=javascript> alert ("IP banni");</script>';
		echo '<script language="javascript" type="text/javascript">
		<!--
		window.location.replace("http://www.sg-univers.fr/");
		-->
		</script>';
		session_destroy();
		exit;
	}
}

$sql = "SELECT password FROM matgraph_users WHERE login = '".$login."' AND password != 'no' ";
$req = db_mysql_Query($sql);
if( $data = mysql_fetch_array($req) ) {

} else {

	//essayons en stripslashant
	
	//attention la sécu 
	if ((preg_match("/union/i", $login)) || (preg_match("/select/i", $login)) || (preg_match("/update/i", $login)) || (preg_match("/outfile/i", $login)) )
	{
    echo '<script language=javascript> alert ("Mauvais login / password. Merci de recommencer.");</script>';

		echo '<script language="javascript" type="text/javascript">
		<!--
		window.location.replace("http://www.sg-univers.fr/");
		-->
		</script>';
		session_destroy();
		exit;
	}

	$login = stripslashes($login);
	$sql = "SELECT password FROM matgraph_users WHERE login = '".$login."' AND password != 'no' ";
	$req = db_mysql_Query($sql);

	$data = mysql_fetch_array($req);
}

if( !$data ) {
echo '<script language=javascript> alert ("Mauvais login / password. Merci de recommencer.");</script>';

echo '<script language="javascript" type="text/javascript">
<!--
window.location.replace("http://www.sg-univers.fr/");
-->
</script>';
session_destroy();
exit;
}

if($data['password'] != $passs)
{
echo '<script language=javascript> alert ("Mauvais login / password. Merci de recommencer.");</script>';

echo '<script language="javascript" type="text/javascript">
<!--
window.location.replace("http://www.sg-univers.fr/");
-->
</script>';
session_destroy();
exit;
} else {
	// Rien que pour voir, voyons si il n aurait pas un cookie avec un pseudo différent
	if( isset($_COOKIE['wtf_powa'] ) ) {
		$ancien_login = $_COOKIE['wtf_powa'];
	}
	SetCookie("wtf_powa", md5($login), mktime(0, 0, 0, 1, 1, 3000));
	// On test si il est banni
	$sql = "SELECT id,date, jour, heure, minute, motif  FROM matgraph_banni WHERE login = '$login' ORDER by date DESC LIMIT 1";
	$res = db_mysql_Query($sql)or die('erreur sql<br>'.$sql.'<br>'.mysql_error());
	$num = mysql_num_rows($res);
	if( $num > 0 ) {
		$row = mysql_fetch_array($res);

		// On sauve les jours heures minutes de ban
		$jour = $row['jour'];
		$heure = $row['heure'];
		$minute = $row['minute'];
		$datetime = $row['date'];

		ereg ("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2}) ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})", $datetime, $thetime);
		$time = mktime($thetime[4],$thetime[5],$thetime[6],$thetime[2],$thetime[3],$thetime[1]);

		$diftemps = time() - $time;

		if( $diftemps < 0 ) {
			// Il est toujours ban
			echo '<script language=javascript> alert ("Votre peine de ban n\'est pas expiré'; if(!empty($row[motif])) { echo "(Motif : $row[motif])"; } echo'.Vous pourrez rejouer le : '.$row[date].'");</script>';
			echo '<script language="javascript" type="text/javascript">
			<!--
			window.location.replace("http://www.sg-univers.fr/");
			-->
			</script>';
			session_destroy();
			exit;
		} else {
			// Duree de ban expiré
			$sql = "DELETE FROM matgraph_banni WHERE id = $row[id] LIMIT 1";
			$res = db_mysql_Query($sql)or die('erreur sql<br>'.$sql.'<br>'.mysql_error());

			// On met à jour également la date, pour qu il ne produise rien durant son ban
			$sql = "SELECT id, date FROM matgraph_users WHERE login = '$login'";
			$req = db_mysql_Query($sql) or die('Erreur SQL !<br>'.$sql.'<br>'.mysql_error());
			while( $row = mysql_fetch_array($req) ) {
				$datetime = $row['date'];

				//echo "<br>$datetime";
				ereg ("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2}) ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})", $datetime, $thetime);
				$new_date = date("Y-m-d H:i:s",mktime($thetime[4]+$heure,$thetime[5]+$minute,$thetime[6],$thetime[2],$thetime[3]+$jour,$thetime[1]));

				//echo "<br>$new_date";

				$sql2 = "UPDATE matgraph_users SET date = '".$new_date."' WHERE id = $row[id]";
				$res2 = db_mysql_Query($sql2)or die('erreur sql<br>'.$sql2.'<br>'.mysql_error());
			}
			$sql = "UPDATE matgraph_users SET vacance = '0000-00-00 00:00:00' WHERE login= '$login' AND password != 'no'";
			$res = db_mysql_Query($sql)or die('erreur sql<br>'.$sql.'<br>'.mysql_error());
			//$row = mysql_fetch_array($res);
		}
	}

// Vérification univers ouvert....
if(strftime("%Y-%m-%d %H:%M:%S", time()) < '2006-03-11 20:00:00' && $login !== 'M@tttt34' && $login !== 'Spaz')
{
	$sql = "SELECT planete,galaxi,system,position FROM matgraph_users WHERE login = '".$login."' AND password != 'no' ";
	$req = db_mysql_Query($sql) or die('Erreur SQL !<br>'.$sql.'<br>'.mysql_error());
	$data = mysql_fetch_array($req);
	echo '<script language=javascript> alert ("Salut '.$login.' cet univers n\'est pas encore ouvert, il ouvrira samedi 11 mars à 20h, vous débuterez votre empire sur '.$data[planete].' ['.$data[galaxi].':'.$data[system].':'.$data[position].']");</script>';
	echo '<script language="javascript" type="text/javascript">
	<!--
	window.location.replace("http://www.sg-univers.fr/");
	-->
	</script>';
	session_destroy();
	exit;
}
//session_start();
session_register('login');
$_SESSION['login']="$login";
SetCookie("matgraph","1",mktime(0,0,0,1,1,2010),"$login","$passs","$mail");
//session_start ();
if ( !session_is_registered("login"))
{
header('location:apercu.php') ;
}


$sql2 = "SELECT * FROM matgraph_users WHERE login='".$login."' AND id = idjoueur limit 1";
$res2 = db_mysql_Query($sql2)or die('erreur sql<br>'.$sql2.'<br>'.mysql_error());
$row2 = mysql_fetch_array($res2);
$idlogin = $row2['id'] ;

// On loggue l'ip
$sql_ip = "SELECT * FROM matgraph_ip WHERE idlogin = $idlogin";
$res_ip = db_mysql_Query($sql_ip)or die('erreur sql<br>'.$sql_ip.'<br>'.mysql_error());
$num_ip = mysql_num_rows($res_ip);
if( $num_ip == 0 ) {
	$sql_ip2 = "INSERT INTO matgraph_ip
		(idlogin, ip, date_connexion, vientde, browser, hote, port)
		VALUES (
			$idlogin, '".get_ip()."', now(), '".$_SERVER['HTTP_REFERER']."', '".$_SERVER['HTTP_USER_AGENT']."', '".gethostbyaddr(get_ip())."', ".$_SERVER['REMOTE_PORT']."
		)";
} else {
	$sql_ip2 = "UPDATE matgraph_ip
	SET ip = '".get_ip()."', date_connexion = now(),
	vientde = '".$_SERVER['HTTP_REFERER']."', browser = '".$_SERVER['HTTP_USER_AGENT']."', hote = '".gethostbyaddr(get_ip())."', port = ".$_SERVER['REMOTE_PORT']."
	WHERE idlogin = $idlogin";
}
$res_ip2 = db_mysql_Query($sql_ip2)or die('erreur sql<br>'.$sql_ip2.'<br>'.mysql_error());

$sql_ip = "SELECT id FROM matgraph_login_ip WHERE ip = '".get_ip()."'";
$res_ip = db_mysql_Query($sql_ip)or die('erreur sql<br>'.$sql_ip.'<br>'.mysql_error());
$num_ip = mysql_num_rows($res_ip);

$id_ip = 0;

if( !$num_ip ) {
    $sql_ip_ins = "INSERT INTO matgraph_login_ip (ip) VALUES ('".get_ip()."')";
    $res_ip_ins = db_mysql_Query($sql_ip_ins)or die('erreur sql<br>'.$sql_ip_ins.'<br>'.mysql_error());
    $id_ip = mysql_insert_id();
} else {
    $row_ip = mysql_fetch_array($res_ip);
    $id_ip = $row_ip['id'];
}

if( $id_ip ) {
    if( isset($ancien_login) ) {
        if( $ancien_login == md5($login) ) {
            unset($ancien_login);
        }
    }
    $sql_connexion = "INSERT INTO matgraph_login_connexion (idjoueur, ext_id_ip, date, vientde, browser, hote, port";
    $sql_connexion = ( isset($ancien_login) ) ? ( $sql_connexion . ", alogin" ) : $sql_connexion;
    $sql_connexion .= ") VALUES ";
    
    $sql_connexion .= "(".$idlogin.",".$id_ip.",now(),'".$_SERVER['HTTP_REFERER']."','".$_SERVER['HTTP_USER_AGENT']."','".gethostbyaddr(get_ip())."',".$_SERVER['REMOTE_PORT'];
    $sql_connexion = ( isset($ancien_login) ) ? ( $sql_connexion . ",'".$ancien_login."'" ) : $sql_connexion;
    $sql_connexion .= ") ";
    
    $res_connexion = db_mysql_Query($sql_connexion)or die('erreur sql<br>'.$sql_connexion.'<br>'.mysql_error());
    
}

include ('recompte_pts_include.php');
}
//idlogin deja ok grace a recompte_pts

//detection multi :
$req = "SELECT * FROM `matgraph_ip` WHERE ip = '".get_ip()."' ";
$res = db_mysql_Query($req) or die('Erreur SQL! <br>'.$req.'<br>'.mysql_error());
$num = mysql_num_rows($res);
if ( $num > 0 ) {
  While ( $row = mysql_fetch_array($res) ) {
  	if($idlogin != $row[idlogin]) {
  			$ok = FALSE;	
				//premier ordre
				$req = "SELECT id FROM matgraph_multi WHERE joueur2='$row[idlogin]' AND joueur1='$idlogin' limit 1";
				$res = db_mysql_Query($req) or die('Erreur SQL! <br>'.$req.'<br>'.mysql_error());
				$num = mysql_num_rows($res);
				if ( $num > 0 ) {
				  While ( $row = mysql_fetch_array($res) ) {
				  	$requete = "UPDATE matgraph_multi SET connection_multi = connection_multi + 1  WHERE id='$row[id]'";
						$resultat = db_mysql_Query($requete)or die('erreur sql<br>'.$requete.'<br>'.mysql_error());
				  }
				  $ok = TRUE;
				}
				else
				{
					//second ordre
					$req = "SELECT id FROM matgraph_multi WHERE joueur1='$row[idlogin]' AND joueur2='$idlogin' limit 1";
					$res = db_mysql_Query($req) or die('Erreur SQL! <br>'.$req.'<br>'.mysql_error());
					$num = mysql_num_rows($res);
					if ( $num > 0 ) {
					  While ( $row = mysql_fetch_array($res) ) {
					  	$requete = "UPDATE matgraph_multi SET connection_multi = connection_multi + 1  WHERE id='$row[id]'";
					  	$resultat = db_mysql_Query($requete)or die('erreur sql<br>'.$requete.'<br>'.mysql_error());
					  }
					$ok = TRUE;
					}
				}
				if($ok == FALSE)
				{
					//créer
					$requete = "INSERT INTO matgraph_multi VALUES ('', '$idlogin', '$row[idlogin]', '0', '0', '0', '0', '0', '1', '0', '0', now(), '1')";
					$resultat = db_mysql_Query($requete)or die('erreur sql<br>'.$requete.'<br>'.mysql_error());
				}
			}
		}
	}


$req2 = "SELECT * FROM matgraph_changementlogin WHERE idlogin = $idlogin ORDER by id ASC";
$res2 = db_mysql_Query($req2) or die('Erreur SQL! <br>'.$req2.'<br>'.mysql_error());
$num2 = mysql_num_rows($res2);
if($num2 > 0)
{
	$row2 = mysql_fetch_array($res2);
	echo '<script language=javascript> alert ("Vous avez une demande de changement de pseudo en cours : '.$row2[login].' qui sera effectué le : '.$row2[date].'");</script>';
}

$req = "SELECT * FROM matgraph_changementlogin WHERE date < now()";
$res = db_mysql_Query($req) or die('Erreur SQL! <br>'.$req.'<br>'.mysql_error());
$num = mysql_num_rows($res);
if ( $num > 0 ) {
  While ( $row = mysql_fetch_array($res) ) {
  
		$sql2 = "SELECT idjoueur,login FROM matgraph_users WHERE id='$row[idlogin]' limit 1";
		$res2 = db_mysql_Query($sql2)or die('erreur sql<br>'.$sql2.'<br>'.mysql_error());
		$row2 = mysql_fetch_array($res2);
		 //maj users
		$requete = 'UPDATE matgraph_users SET login="'.$row[login].'"  WHERE idjoueur="'.$row2[idjoueur].'"';
		$resultat = db_mysql_Query($requete)or die('erreur sql<br>'.$requete.'<br>'.mysql_error());
		//maj ban
		$requete = 'UPDATE matgraph_banni SET login="'.$row[login].'"  WHERE login="'.$row2[login].'"';
		$resultat = db_mysql_Query($requete)or die('erreur sql<br>'.$requete.'<br>'.mysql_error());
		//autoriser
		$requete = 'UPDATE matgraph_autoriser SET joueur1="'.$row[login].'"  WHERE joueur1="'.$row2[login].'"';
		$resultat = db_mysql_Query($requete)or die('erreur sql<br>'.$requete.'<br>'.mysql_error());
		
		$requete = 'UPDATE matgraph_autoriser SET joueur2="'.$row[login].'"  WHERE joueur2="'.$row2[login].'"';
		$resultat = db_mysql_Query($requete)or die('erreur sql<br>'.$requete.'<br>'.mysql_error());
		
		//del souhait
		$sql = "DELETE FROM matgraph_changementlogin WHERE id = $row[id] LIMIT 1";
		$res = db_mysql_Query($sql)or die('erreur sql<br>'.$sql.'<br>'.mysql_error());
		
  }
}

function make_seed () {
   list($usec, $sec) = explode(' ', microtime());
   return (float) $sec + ((float) $usec * 100000);
}
mt_srand(make_seed());
$_SESSION['secu_multi_pc'] = $idlogin.mt_rand();
$req = "SELECT * FROM matgraph_connexion WHERE idjoueur = '".$idlogin."'";
$res = mysql_query($req) or die('Erreur SQL! <br>'.$req.'<br>'.mysql_error());
$num = mysql_num_rows($res);
if ( $num > 0 ) { // update
$query="UPDATE matgraph_connexion SET secu = '".$_SESSION['secu_multi_pc']."'
	    WHERE idjoueur='".$idlogin."'";
$res = mysql_query($query) or TraiterErreur($query, mysql_error(),__FILE__,__LINE__);
} else { // insert
$query="INSERT INTO `matgraph_connexion` ( `idjoueur` , `secu` )
				VALUES (
				'".$idlogin."', '".$_SESSION['secu_multi_pc']."'
				)";
$res = mysql_query($query) or TraiterErreur($query, mysql_error(),__FILE__,__LINE__);
}

echo '<script language="javascript" type="text/javascript">
<!--
window.location.replace("apercu.php");
-->
</script>';




?>
<style type="text/css">
<!--
body {
	background-color: #000000;
}
-->
</style>

