<?php

//GLOBAL CONFIG: Change this and change where all the configs are read from and data gets stored
global $SETUP_DIR;
$SETUP_DIR = "setups/wmt08";
global $DISABLED;
$DISABLED = true;
global $DISABLED_MSG;
$DISABLED_MSG = "Judging for the manual evaluation is now finished. Thank you for your participation!";

global $LANG_CODES;
$LANG_CODES = array('en'=>'English','de'=>'German','fr'=>'French','es'=>'Spanish','cz'=>'Czech','hu'=>'Hungarian');


//do error reporting for everything except annoying notice messages
error_reporting(E_ALL ^ E_NOTICE);
ini_set('display_errors', '1');
ini_set('session.use_only_cookies', '1');
session_save_path('/disk/scratch/php_sessions/');
session_start();

//declare all our global variables
global $task,$system,$annotator,$annotator_new,$annotator_pwd,$annotator_email,$annotator_conflict,$annotator_cookie_hash,$assignments;

function get_assignments_file() {
	global $SETUP_DIR;
	return "$SETUP_DIR/assignments";
}

function get_annotators_file() {
	global $SETUP_DIR;
	return "$SETUP_DIR/annotators";
}

function get_tasks_file() {
	global $SETUP_DIR;
	return "$SETUP_DIR/tasks";
}

function get_judgements_file() {
	global $SETUP_DIR;
	return "$SETUP_DIR/judgements";
}


// general task info
$line = file(get_tasks_file());
for($i=0;$i<count($line);$i++) {
	$line[$i] = chop($line[$i]);
	//lines that start with # are comments
	if(preg_match("/^[\s]*#/",$line[$i])) continue;
	list($t,$key,$value,$value2) = split(" \|\|\| ",$line[$i]);
	if ($t == "_DEFAULT") continue;
	
	if (!$already[$t]) {
		$already[$t] = 1;
		$task[] = $t;
	}
	if ($key == "translation" && !$already_system[$value]) {
		$already_system[$value] = 1;
		$system[] = $value;
	}
}

#sort($task);

sort($system);

// annotators
$line = file(get_annotators_file());
for($i=0;$i<count($line);$i++) {
	$line[$i] = chop($line[$i]);
	list($name,$pwd,$email,$conflict) = split(" \|\|\| ",$line[$i]);
	$annotator[] = $name;
	$annotator_pwd[$name] = $pwd;
	$annotator_email[$name] = $email;
	$c = split(" ",$conflict);
	for($j=0;$j<count($c);$j++) { 
		$annotator_conflict[$name][$c[$j]] = 1;
	}
	$annotator_registered[$name] = 1;

	//create hash of cookies hashes to names
	$hash = md5($name.$pwd.get_cookie_salt());
	$annotator_cookie_hash[$hash] = $name;

}

function load_judgements($user_id = null) {
	if ($user_id == null) {
		return file(get_judgements_file());
	} else {
		//TODO: user filtering here
		return file(get_judgements_file());
	}
}


function head($title) {
  ?>
<HTML>
	<HEAD>
		<meta HTTP-EQUIV="content-type" CONTENT="text/html; charset=UTF-8">
		<TITLE>
			<?php print($title);?>
		</TITLE>
	</HEAD>
	<BODY>

	<H2><?php print($title);?></H2>
<?php //end head
}


function tail() {
	?><HR SIZE=1><?php
	if (logged_in()) {
		?><A HREF="logout.php">log out </A>(<?php print(current_user());?>) | <a href="select_task.php">select new task</a> <?php
	} else {
		?><A HREF="index.php">log in</A> <?php
	}
	?> | <A HREF="stats.php">stats</A>
	<P>
	<table align="right"><tr>
		<td align="right">supported by the <a href="http://www.euromatrix.net/" target="_new">EuroMatrix</a> project, P6-IST-5-034291-STP<BR> funded by the European Commission under Framework Programme 6</td>
		<td align="right"><a href="http://www.euromatrix.net/" target="_new"><img src="../euromatrix-logo-small.png" border=0 width=54 height=55></a></td>	
	</tr></table>

	</BODY>
	</HTML>
	<?php
}

function current_user() {
	global $annotator_cookie_hash;
	return $annotator_cookie_hash[strip_tags($_SESSION["logged_in"])];
}

function logged_in() {
	return (current_user() != null);
}

function log_out() {
	unset($_SESSION['logged_in']);
}

function get_cookie_salt() {
	return "oh_look_i_wrote_a_sentence_that_people_wont_guess_muwhaha_2356ss22672";
}


function load_global_task_info($current_task=null) {
	global $task_info;
	$task_info = array();
	$line = file(get_tasks_file());
	$index = 0;
	for($i=0;$i<count($line);$i++) {
		if(preg_match("/^[\s]*#/",$line[$i])) continue;
		list($t,$key,$value,$value2,$value3) = split(" \|\|\| ",chop($line[$i]));
		if ($current_task==null || $t == $current_task || $t == "_DEFAULT") {
			if ($key == "reference") {
				$task_info[$t][$key][] = $value;
			}
			else if ($key == "translation") {
				$task_info[$t]["translation_file"][] = $value2;
				$task_info[$t]["translation_id"][] = $value;
				if ($value3) {
					$indices = process_task_file_value($value3);
					$indices_hash = array();
					foreach ($indices as $ignored=>$index) {
						$indices_hash[$index] = 1;
					}
					$task_info[$t]["translation_exclude"][] = $indices_hash;
				} else {
					$task_info[$t]["translation_exclude"][] = array();
				}
			} else if ($key == "test_types") {
				$task_info[$t]["test_types"] = array();
				$ttypes = split(" ",$value);
				foreach($ttypes as $test_type) {
					$task_info[$t]["test_types"][$test_type] = 1;		
				}
			} else if ($value2) {
				$task_info[$t][$key][$value] = process_task_file_value($value2);
			} else {
				$task_info[$t][$key] = process_task_file_value($value);
			}
		}
	}
	
	#get reverse short_id mappings
	$test_types = get_global_task_property('test_types',null,true,$current_task);
	foreach ($test_types as $test_type=>$value) {
		$short_id = get_global_task_property('short_id',$test_type,true,$current_task);
		$task_info[$current_task]['test_type_ids'][$short_id] = $test_type;
	}
	
}

function get_global_task_property($key,$test_type=null,$default_fallback=true,$task=null) {
	global $task_info;
	//not test-type specific
	#if ($task == null) {
	#	$task = $_POST["TASK"];
	#}
	if (!$test_type) {
		$result = $task_info[$task][$key];
		if (!$result) $result = $task_info['_DEFAULT'][$key];
		return $result;
	} else {
		$test_types = get_global_task_property("test_types",null,$default_fallback,$task);
		if ($test_types[$test_type]) {
			//supported test-type
			$result = $task_info[$task][$test_type][$key];
			if (!$result) $result = $task_info['_DEFAULT'][$test_type][$key];
			return $result;
		} else {
			//tried to fetch for non-supported test
			return null;
		}	
	}
}

function process_task_file_value($value) {
	if (preg_match('/[^\ ]+ [^\ ]+/',$value)) {
		#an array, so split it
		return split(" ",$value);
	}
	else {
		return $value;
	}
}


function check_password() {
	global $annotator_pwd, $annotator_cookie_hash;
	
	//if we have a post item here, some one has logged in. 
	
	$login = null;
	$password = null;
	
	if ($_POST["ANNOTATOR"] || $_POST["PWD"]) {
		//remove html and php tags (hack attempts)
		if ($_POST["ANNOTATOR"]) $login = strip_tags($_POST["ANNOTATOR"]);
		if ($_POST["PWD"]) $password = md5(strip_tags($_POST["PWD"]));
		
		//they're trying to login, so clear session
		log_out();
	}
	
	if ($login && $password && ($annotator_pwd[$login] == $password)) {
		$_SESSION['logged_in'] = md5($login.$password.get_cookie_salt());
		return true;
	} else if (!($login && $password) && $_SESSION["logged_in"] && $annotator_cookie_hash[strip_tags($_SESSION["logged_in"])]) {
		//valid cookie
		return true;
	} else {
		head("Password Error");
		if ($_POST["PWD"] && $_POST["ANNOTATOR"]) {
			print "Bad login, please try again.";
		} else if ($_SESSION['logged_in']) {
			print "Bad/expired session, please log in again.";
		} else if ($_POST["ANNOTATOR"]) {
			print "Empty password, please try again.";
		} else {
			print "Please login again.";
		}
		return false;
	}
}

?>
