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

	session_start();
	html_start("Change password");

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

	echo "<H1>Change password</H1>\n";

	$link = db_connect();

	$oldpassword = $_REQUEST["oldpassword"];
	$newpassword1 = $_REQUEST["newpassword1"];
	$newpassword2 = $_REQUEST["newpassword2"];

	if($newpassword1 != $newpassword2) {
		echo "Password missmatch. Please try again.";
	} else {
		$oldhash = md5($oldpassword);
		$query = "SELECT COUNT(*) AS count FROM users WHERE id = {$_SESSION["id"]} AND pass = \"$oldhash\"";
		$result = mysql_query($query, $link) or die("Can't check old password: ".mysql_error($link));
		$line = mysql_fetch_array($result);
		if($line["count"] != 1) {
			echo "Old password is wrong. Please try again";
		} else {
			$newhash = md5($newpassword1);
			$query = "UPDATE users SET pass = \"$newhash\" WHERE id = {$_SESSION["id"]} AND pass = \"$oldhash\"";
			$result = mysql_query($query, $link) or die("Can't set new password: ".mysql_error($link));
			$num = mysql_affected_rows($link);
			if($num == 1) {
				echo "Password changed succesfully";
			}
		}
	}
	mysql_close($link);

	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>
