<?php
	require("settings.php");
	require_once("helper.php");

	session_start();
	html_start("Post solution");

	if(!session_is_registered("id") || $_SESSION["id"] == "") {
		echo "Not logged in";
		login_form("index.php");
		die();
	}

	echo "<H1>Post solution</H1>\n";

	$link = db_connect();
	$tid = intval($_REQUEST["tid"]);

	$error = $_FILES["file"]["error"];
	if($error == UPLOAD_ERR_OK) {
		$content = file_get_contents($_FILES["file"]["tmp_name"], false);
		if($content === FALSE) {
			echo "Can't read temporary file<BR>\n";
		} else {
			$content = mysql_real_escape_string($content, $link);
			$query = "INSERT INTO solutions SET id = {$_SESSION["id"]}, tid=$tid, solution=\"$content\"";
			$result = mysql_query($query, $link) or die ("Can't store solution: ".mysql_error($link));
			$sid = mysql_insert_id($link);
			if($sid == 0) {
				echo "Storing failed<BR>\n";
			} else {
				echo "Storing successfull<BR>\n";
			}
			echo "<A href=\"assignment.php?tid=$tid\">View Assignment</A><BR>\n";
		}
		mysql_close($link);
	} else if ($error == UPLOAD_ERR_INI_SIZE) {
		echo "File too large<BR>\n";
	} else if ($error == UPLOAD_ERR_FORM_SIZE) {
		echo "File too large<BR>\n";
	} else if($error == UPLOAD_ERR_PARTIAL) {
		echo "Upload incomplete<BR>\n";
	} else if ($error == UPLOAD_ERR_NO_FILE) {
		echo "No file was uploaded<BR>\n";
	} else if($error == UPLOAD_ERR_NO_TMP_DIR) {
		echo "Temporary folder not found<BR>\n";
	} else if($error == UPLOAD_ERR_CANT_WRITE) {
		echo "Temporary folder not writeable<BR>\n";
	} else if($error == UPLOAD_ERR_EXTENSION) {
		echo "Some extension stopped the upload<BR>\n";
	} else {
		echo "Something else went south<BR>\n";
	}

	echo "<DIV class=\"footer\">\n";
	echo "<A href=\"index.php\"><IMG src=\"icons/house.png\" alt=\"home\">Home</A>\n";
	echo "<A href=\"logout.php\"><IMG src=\"icons/door_in.png\" alt=\"logout\">Logout</A>\n";
	echo "<DIV>\n";
?>
 </BODY>
</HTML>
