Election software/export.php

From Wikimedia Australia
Jump to navigation Jump to search
<?php

// Step 0: Grab the category details

$sql = "SELECT * FROM Categories WHERE id=".$category;

$result = mysql_query($sql);
$row = mysql_fetch_array($result, MYSQL_ASSOC);

$title = $row['name'];

// Step 1: Grab the nominees

$sql = "SELECT * FROM Nominees WHERE category=".$category;

$numberOfNominees = 0;

$result = mysql_query($sql);

if ($result && mysql_num_rows($result) > 0)
{	
	while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
	{
		$nomineeID[$numberOfNominees] 			= $row['id']; 
		$nomineeDescription[$numberOfNominees] 	= $row['description'];
		
		$numberOfNominees++;
	}
}
	
// Step 2: Let's load all the votes into an array.
// Note that only approved voters will be counted.

for ($nominee = 0; $nominee < $numberOfNominees; $nominee++)
{
	$sql = "SELECT * FROM Votes, Voters WHERE voterid = voters.id AND approved = true AND nomineeid=".$nomineeID[$nominee];
	
	$result = mysql_query($sql);
	
	if ($result && mysql_num_rows($result) > 0)
	{
		while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
		{
			$vote[$row['voterid']][$row['nomineeid']] = $row['vote'];
		}
	}
}

// Step 3: Start generating the export file


$export = "";

// The format needs the number of nominees followed by a "1" as the first line.
$export .= $numberOfNominees." 1\n";

// Scan through the voters
foreach ($vote as $voterID => $votes)
{
	$export .= "1 ";
	
	// They've been saved based on ID, but now we want them based on order. 
	// OpenSTV places the number of the candidates in the order in which they were voted for.
	// Thus:
	//			1. 2
	//			2. 3
	// 			3. 1
	// needs to be recorded as 3 1 2
	
	$finished = false;
	$rank = 1;
	
	// So, check each possible rank to see if there is an entry in the current vote for it.
	// (Or, in other words, check to see if there is a nominee numbered 1, one numbered 2, etc)
	
	while (!$finished)
	{
		$count = 0;
		$current = 0;
		
		for ($nominee = 0; $nominee < $numberOfNominees; $nominee++)
		{
			if ($votes[$nomineeID[$nominee]] == $rank)
			{
				$count++;
				$current = $nominee;
			}
		}
		
		if ($count == 1)
		{
			$export .= ($current + 1)." ";
			$rank++;
		}
		else
		{
			// This ends if a) there is no nominee with the required rank, 
			// or b) there are two nominees with the same rank.
			$finished = true;
		}
	}

	$export .= "0\n";
}

$export .= "0\n";

for ($nominee = 0; $nominee < $numberOfNominees; $nominee++)
{
	$nomineeName = strip_tags($nomineeDescription[$nominee]);
	$nomineeName = str_replace("\"", "", $nomineeName);
	
	$pattern = "/ +/";
	$nomineeName = preg_replace($pattern," ",$nomineeName);
	$export .= "\"".$nomineeName."\"\n";
} 

$export .= "\"".str_replace("\"", "", strip_tags($title))."\"";

echo($export);

?>