<?PHP
	require("db.php");

	$access_levels = parse_level();
	session_start();

	// First of all, make sure any users wanting to log out get their session destroyed.
	if($_GET[logout] == "true")
		logout();

	// Check if the user has a password stored in his session, if he does, try to verify him.
	// Given his credentials are valid, also update his user ID and access levels from the database.
	if(isset($_SESSION[password]))
	{
		$query = "select id, access_level, nickname, password from taj_users where nickname = '$_SESSION[nickname]' and password = '$_SESSION[password]'";
		$result = mysql_query($query);
		$line = @mysql_fetch_array($result);

		// Check if we actually got anything from the database, if not, tell the user not to tamper with the system and die.
		if(count($line) < 4)
		{
			echo "_SESSION[nickname] is: $_SESSION[nickname]<br>_SESSION[password] is: $_SESSION[password]<br>";
			die("Please dont tamper with the system.");
		}

		// We survied the check above so the databse contained a user with the provided name/pass.
		// Continue by saving the user data in the session.
		if(check_level($line[access_level],"buf_login"))
		{
			$_SESSION['user'] = $line[id];
			$_SESSION['level'] = $line[access_level];
			$_SESSION['password'] = $line['password'];
			$_SESSION['nickname'] = $line['nickname'];
		}
		else
			die("This account does not have access to the buffe<br>");
	}
	// Obviously, the user wasn't logged in, check if he provided a user/pass by POST method
	else if(isset($_POST[pass]) && isset($_POST[user]))
	{
		$user = $_POST[user];
		$query = "select id, nickname, password, access_level from taj_users where nickname='$user' and password=md5('$_POST[pass]') and 1=MOD(FLOOR(access_level/$access_levels[buf_login]),2)";
		$result = mysql_query($query);
		$line = mysql_fetch_array($result);
		if(!(count($line) > 1))
			die ("No such user, hit the back button on your browser and try again.");
		// Instead of saving the password in plain text in the session, store the md5 hash, it will still be easy to hijack the session but given the user doesn't have too
		// high access level (ie to edit users) the hijacker will only be able to browse the stolen account with its original access level
		// This prevents the password from being sent in plain text more than once.
		if(check_level($line[access_level],"buf_login"))
		{
			$_SESSION['user'] = $line[id];
			$_SESSION['level'] = $line[access_level];
			$_SESSION['password'] = $line['password'];
			$_SESSION['nickname'] = $line['nickname'];
		}
		else
			die("This account does not have access to the buffe<br>");
	}
	// The user provied neither a session nor a POST password, destroy any session data and show the login page
	else
	{
		logout();
		show_login();
	}

	function logout()
	{
		$_SESSION = array();
		if (isset($_COOKIE[session_name()]))
			setcookie(session_name(), '', time()-42000, '/');
		@session_destroy();
	}

	function parse_level()
	{
		$query = "select access_item, value from taj_access_levels order by value desc";
		$result = mysql_query($query);
		$access_array = array();
		while($line = mysql_fetch_array($result))
			$access_array[$line[access_item]] = $line[value];
		return $access_array;
	}

	function countwords($filename)
	{
		$fp = fopen($filename, "r");
		$fstring = fread($fp, filesize($filename));
		$fstring = preg_replace('/<[\w|\"|\/|#|\.|\=|\s|\'|;]*>/',"",$fstring);
		$matches = preg_match_all('/\w+\s/',$fstring, $results);
		return $matches;
	}

	if($_GET[action] == "boka")
	{
		$query = "update taj_documents set bookedby='$_SESSION[user]' where article_id='$_GET[aid]' and document_id='$_GET[did]'";
		mysql_query($query);
	}

	if($_FILES[translated_document][tmp_name] && $_POST[aid] && $_POST[did])
	{
		// parse number of words in document and insert into database
		$fp = fopen($_FILES[translated_document][tmp_name], "r");
		unset($line);
		while(!feof($fp))
		{
			$line[$n++] = fgets($fp, 1024);
		}
		$wc = countwords($_FILES[translated_document][tmp_name]);
		@unlink($_FILES[translated_document][tmp_name]);
		$text = implode("", $line);
		$query = "update taj_documents set translator='$_SESSION[user]', translated='$text', words='$wc', bookedby='-1' where article_id='$_POST[aid]' and document_id='$_POST[did]'";
		mysql_query($query);
	}

	if($_FILES[spellchecked_document][tmp_name] && $_POST[aid] && $_POST[did])
	{
		// parse number of words in document and insert into database
		$fp = fopen($_FILES[spellchecked_document][tmp_name], "r");
		while(!feof($fp))
		{
			$line[$n++] = fgets($fp, 1024);
		}
		@unlink($_FILES[spellchecked_document][tmp_name]);
		$text = implode("", $line);
		$query = "update taj_documents set spellchecker='$_SESSION[user]', corrected='$text', bookedby='0' where article_id='$_POST[aid]' and document_id='$_POST[did]'";
		mysql_query($query);
	}

	if($_GET[id] && $_GET['action'] == "translate" || $_GET['action'] == "ignore")
	{
		$query = "select count(article_id) from taj_documents where article_id='$_GET[id]'";
		$result = mysql_query($query);
		$line = @mysql_fetch_row($result);
		if(!$line[0] > 0)
		{
			$query = "select ordning, rubrik, text from artikel_innehall where link='$_GET[id]' order by ordning";
			$result = mysql_query($query, $db_link_se);

			$query = "select rubrik from artikel_grund where id='$_GET[id]'";
			$result2 = mysql_query($query, $db_link_se);
			$line2 = mysql_fetch_array($result2);
			$line2[0] = preg_replace("/'/", "\\'", $line2[0]);			

			while($line = mysql_fetch_array($result))
			{
				if($line[rubrik] == "")
					$line[rubrik] = "Ingen rubrik";
				// Mangla $line[text] samt $line[rubrik] så att special chars dör eller escapeas.
				$line[text] = preg_replace("/'/", "\\'", $line[text]);
				$line[rubrik] = preg_replace("/'/", "\\'", $line[rubrik]);
				if($_GET['action'] == "ignore")
					$query = "insert into taj_documents values('$_GET[id]','$line[ordning]',0,'','','','','$line2[0]','$line[rubrik]','$line[text]','','')";
				else
					$query = "insert into taj_documents values('$_GET[id]','$line[ordning]',1,'','','','','$line2[0]','$line[rubrik]','$line[text]','','-1')";
				mysql_query($query);
			}
		}
	}

	if($_POST[action] == "Finalize" && $_POST[id] != "" && check_level($_SESSION['level'], "buf_admin"))
	{
		finalize_article($_POST[id], $_POST[article_overview]);
	}

	if($_GET['action'] == "show_swedish" && $_GET['aid'] && $_GET['did'])
		show_document($_GET['aid'], $_GET['did'], "swedish");
	else if($_GET['action'] == "show_translated" && $_GET['aid'] && $_GET['did'])
		show_document($_GET['aid'], $_GET['did'], "translated");
	else if($_GET['action'] == "show_corrected" && $_GET['aid'] && $_GET['did'])
		show_document($_GET['aid'], $_GET['did'], "corrected");

	function check_level($user_level, $access_object)
	{
		global $access_levels;
		if(floor($user_level/$access_levels[$access_object]) % 2)
			return true;
		return false;
	}
	
	function finalize_article($article_id, $overview)
	{
		// Select all the neccessary data from both the swedish database and the table taj_documents
		// in the english database.
		// Parse all the fields for instances of ' and replace with \'
		// Copy the image from the swedish server into the correct dir on the .com server.
		// Compile the querys with the gathered data.
		// Run the query to insert the article into artikel_grund and all the beloning pages into artikel_innehall.
		// Update taj_documents setting all the rows with the current article_id to status = 0
		// This will hide the article from the translation interface as "ignored" once it has
		// been inserted into the live database.
		echo "Finalize article called on article_id $article_id.<br>Overview is:<br>$overview<br>";
	}

	function show_current_documents()
	{
		// Create an array of all the users nickname using their user IDs as keys.
		$query = "select id, nickname from taj_users";
		$result = mysql_query($query);
		$user_table = array();
		while($line = mysql_fetch_array($result))
			$user_table[$line[id]] = $line[nickname];

		$query = "select * from taj_documents where status=1 order by article_id, document_id asc";
		$result = mysql_query($query);
		$headline = "";
		echo "<center>\n<table width=880 border=0 cellpadding=0 cellspacing=0>\n";
		$article_count = 0;
		echo "<tr><td colspan=4 bgcolor=\"ffffff\"><center><b>----[ Currently active articles ]----</b></center></td></tr>\n";
		$complete = true;

		while($line = mysql_fetch_array($result))
		{
			++$article_count;
			
			// If this is true it means we are parsing the first article page from the query
			// and we have to save the article_id in order to ba able to call the finalize_article()
			// function on it if all of the articles documents have been translated and corrected.
			// Later on this value will be updated in the loop below when a new article is encountered.
			
			if($headline != $line[article_name])
			{
				if($last_article_id && $complete && check_level($_SESSION['level'], "buf_admin"))
				{
					// This is where verification of user rights and echoing of controls takes place
					echo "<tr><td colspan=4><br>This article is complete and you may now move it into the article
					database.<br>Please, take your time and write a short introduction/overview of the article
					before you press the Finalize button. Once you press Finalize the article will be inserted
					into the sharp article database and instantaneously accessible via the web.<br>\n";
					echo "<form action=\"$_SERVER[PHP_SELF]\" method=post><textarea style=\"height:100px;
					width:500px;\" name=\"article_overview\">Replace this text with a short description of the
					article.</textarea>\n<br>\n<input type=hidden name=id value=$last_article_id>\n<input type=submit name=action value=Finalize></form><br></td></tr>\n";
				}
				echo "<tr><td colspan=4 height=10 bgcolor=\"#ffffff\"></td></tr>\n";
				echo "<tr>\n<td colspan=4 bgcolor=\"#000000\"><center><b><font color=\"#ffffff\">$line[article_name]</font></b></center></td>\n</tr>\n";
				echo "<tr>\n<td width=200 bgcolor=\"#cccccc\">Rubrik</td>\n<td width=80 bgcolor=\"#cccccc\">Booked by</td>\n<td width=200 bgcolor=\"#cccccc\">Translator</td>\n<td width=200 bgcolor=\"#cccccc\">Corrected by</td>\n</tr>\n";
				$headline = $line[article_name];
				
				// Make sure we start looping over the new article assuming it is complete until
				// we encounter something that contradicts this.
				$complete = true;

				// It is important to update the stored article_id AFTER we've used the value
				// in the adminstrative controls above.
				$last_article_id = $line[article_id];
			}
			echo "<tr>\n<td><a href=\".?action=show_swedish&did=$line[document_id]&aid=$line[article_id]\">$line[document_name]</a></td>\n<td>";
			if($line[bookedby] > 0)
				echo $user_table[$line[bookedby]];
			else if($line[bookedby] < 0)
				echo "<a href=\"$_SERVER[PHP_SELF]?action=boka&aid=$line[article_id]&did=$line[document_id]\">boka</a>";
			echo "</td>\n<td>";
			if($line[translator])
			{
				echo $user_table[$line[translator]] . " <a href=\"$_SERVER[PHP_SELF]?action=show_translated&aid=$line[article_id]&did=$line[document_id]\">(Download)</a>";
			}
			else
			{
				echo "<form action=$_SERVER[PHP_SELF] enctype=\"multipart/form-data\" method=post>\n";
				echo "<input type=\"hidden\" name=\"aid\" value=$line[0]>\n<input type=\"hidden\" name=\"did\" value=$line[1]>\n";
				echo "<input type=\"file\" name=\"translated_document\">\n";
				echo "<input type=\"submit\" value=\"Skicka\"></form>";
			}
			echo "</td>\n<td>";
			if($line[spellchecker])
				echo $user_table[$line[spellchecker]] . " <a href=\"$_SERVER[PHP_SELF]?action=show_corrected&aid=$line[article_id]&did=$line[document_id]\">(Download)</a>";
			else if($line[translator])
			{
				echo "<form action=$_SERVER[PHP_SELF] enctype=\"multipart/form-data\" method=post>\n";
				echo "<input type=\"hidden\" name=\"aid\" value=$line[0]>\n<input type=\"hidden\" name=\"did\" value=$line[1]>\n";
				echo "<input type=\"file\" name=\"spellchecked_document\">";
				echo "<input type=\"submit\" value=\"Skicka\"></form>";
				
				// Since the document doesnt have a spellchecker it can not be completed.
				$complete = false;
			}
			else
				$complete = false;	// As the above case but catch even if the document hasnt been translated.
			echo "</td>\n</tr>\n";
		}
		if(!$article_count)
			echo "<tr>\n<td colspan=4>No active articles found!</td>\n</tr>\n";
		echo "\n</table>\n</center>\n<br><br>";
	}

	function show_admin_tools()
	{
		global $db_link_se;
		$query = "select id, rubrik from artikel_grund";
		$result = mysql_query($query, $db_link_se);
		unset($line);
		while($line = mysql_fetch_array($result))
			$swedish_articles[$n++] = $line[0];

		$query = "select distinct article_id from taj_documents";
		$result = mysql_query($query);
		unset($line);
		while($line = @mysql_fetch_array($result))
			$existing_articles[$i++] = $line[0];
		$n = 0;
		if(count($swedish_articles) > 0)
		{
			foreach($swedish_articles as $swedish_article)
			{
				$add = 1;
				if(count($existing_articles) > 0)
					foreach($existing_articles as $existing_article)
						if($swedish_article == $existing_article)
							$add = 0;
				if($add)
					$new_articles[$n++] = $swedish_article;
			}
		}

		echo "<center>\n<table width=880 border=0 cellpadding=0 cellspacing=0>\n";
		if(count($new_articles) > 0)
		{
			echo "<tr><td colspan=3><center><b>----[ New articles: ]----</b></center><br></td></tr>\n";
			echo "<tr><td height=1 colspan=3 bgcolor=\"#000000\"></td></tr>\n";
			foreach($new_articles as $new_article)
			{
				$query = "select rubrik from artikel_grund where id='$new_article'";
				$result = mysql_query($query, $db_link_se);
				$line = mysql_fetch_row($result);
				echo "<tr>\n<td>$line[0]</td>\n";
				echo "<td><a href=\".?action=translate&id=$new_article\">Add to worklist</a></td>\n";
				echo "<td><a href=\".?action=ignore&id=$new_article\">Ignore article</a></td>\n</tr>\n";
				echo "<tr><td height=1 colspan=3 bgcolor=\"#000000\"></td></tr>\n";
			}
		}
		else
			echo "<tr><td colspan=3><center><b>----[ No new articles found ]----</b></center></td></tr>\n";
		echo "\n</table>\n</center>\n";
	}

	function show_document($aid, $did, $version)
	{
		$query = "select $version from taj_documents where article_id='$aid' and document_id='$did'";
		$result = mysql_query($query);
		$line = mysql_fetch_array($result);
		echo $line[0];
		die();
	}

	// *** Function show_login() starts
	function show_login()
	{
		PHP?>
		<form action="<?PHP echo $_SERVER['PHP_SELF']; PHP?>" method="post">
		<center>
		<table border=0 cellpadding=0 cellspacing=0>
		<tr>
		<td width=150>Username:</td>
		<td width=200><input type="text" name="user"></td>
		</tr>
		<tr>
		<td width=150>Password:</td>
		<td width=200><input type="password" name="pass"></td>
		</tr>
		<tr>
		<td colspan=2><center><input type="submit" value="Log on"></center></td>
		</tr>
		</table>
		</center>
		<?PHP
	}
	// *** Function show_login() ends

	function login($user, $pass)
	{
		$pass = md5($pass);
		$query = "select id, nickname, password, access_level from taj_users where nickname='$user' and password='$pass'";
		$result = mysql_query($query);
		$line = mysql_fetch_row($result);
		if($line[0] == null)
			return false;
		else
		{
		}
		return true;
	}

PHP?>

<html>
<head>
<title>Nordichardware buffe 3.0.2</title>

<style type="text/css">
<!--
        a {font-weight:bold; text-decoration:none; font-size:12px; font-family:Arial; color:#000000;}
        a:hover {font-weight:bold; font-size:12px; font-family:Arial; color:#505050;}
        td {font-size:12px; font-family:Arial;}
//-->
</style>

</head>

<body>

<?PHP
	if(isset($_SESSION[user]))
	{
		echo "<center><img src=\"images/buffe-logga.gif\" border=0 style=\"position:relative; top:-8px;\"></center>";
		echo "<center style=\"position:relative; top:-65px;\">Russki for teh win!<br>[ <a href=\"$_SERVER[PHP_SELF]?logout=true\">logout</a> ] [ <a href=\"$_SERVER[PHP_SELF]\">Main page (update
		view)</a> ]</center>";
		show_current_documents();
	}

	if(check_level($_SESSION['level'], "buf_admin"))
		show_admin_tools();

PHP?>

</body>
</html>
