<?php
	session_start();
	session_regenerate_id(true);
	if(!isset($_SESSION['user'])){
		header("Location: index.php");
		exit;
	}
	
/*	if(isset($_SERVER['HTTP_REFERER']) && $_SERVER['HTTP_REFERER']!="http://localhost/chat.php"){
		echo 'XSRF attack';
		exit;
	}
	*/
	
/*	if(isset($_SERVER['HTTP_ORIGIN']) && $_SERVER['HTTP_ORIGIN']!="http://localhost"){
		echo 'XSRF attack';
		exit;
	}
	*/
	
/*	if(!isset($_POST['xsrftoken']) || !isset($_SESSION['xsrftoken']) || $_POST['xsrftoken']!=$_SESSION['xsrftoken']){
		echo 'XSRF attack detected with token!';
		exit;
	}
	*/
	
	if(!isset($_POST['xsrftoken_dynamic']) || !isset($_POST['xsrftoken_mixed'])){
		header("Location: chat.php");
		exit;
	}
	
	if($_POST['xsrftoken_mixed'] !== hash_hmac("sha256", $_POST['xsrftoken_dynamic'], $_SESSION['xsrftoken'])){
		echo 'XSRF attack detected';
		exit;
	}
	
	
	if(!isset($_POST['message']) || empty(trim($_POST['message']))){
		header("Location: chat.php");
		exit;
	}
	
	$link = @mysqli_connect("localhost", "mainuser", "gfdagfda", "osup2020");
	if(!$link){
		echo 'Има проблем с базата от данни. Пробвайте по-късно.';
		exit;
	}
	
	$sql = "INSERT INTO chatmessages(uid, message) VALUES(
			".$_SESSION['id'].",
			'".@mysqli_real_escape_string($link, $_POST['message'])."')";
	$result = @mysqli_query($link, $sql);
	header("Location: chat.php");
	exit;
?>