<?php
if (!defined('PmWiki'))
	exit ();

/**
 * This script allows complex votings
 * 
 * @author Patrick R. Michaud <pmichaud@pobox.com> 
 * @author Sebastian Siedentopf <schlaefer@macnews.de>
 * @version 0.4
 * @link http://www.pmwiki.org/wiki/Cookbook/Voting http://www.pmwiki.org/wiki/Cookbook/Voting
 * @copyright by the respective authors 2004-2005
 * @license http://www.gnu.org/copyleft/gpl.html GNU General Public License
 * @package complexvote
 */

/**
 * cookbook complexvote is included
 * and running on this pmwiki installation
 */
define('complexvote', 1);

SDV($HandleActions['complexvote'], 'HandleComplexVote');
SDV($HandleAuth['complexvote'], 'read');

SDV($ComplexVoteCookie, $CookiePrefix.'complexvote');
SDV($ComplexVoteExpires, $Now +60 * 60 * 24 * 30);
SDV($ComplexVoteDir, '/');

Markup('showcomplexvote', '<split', '/(\(:input form.*?action=complexvote.*?input end:\))/se', "showComplexVote(PSS('$0'))");

/**
 * Belongs to Markup "showcomplexvote" and hides the vote input form if someone already voted
 * 
 * @param string $text
 */
function showComplexVote($text) {
	global $ComplexVoteCookie;
	preg_match("/\(:input hidden votename\s*(.*?)\s*?:\)/", $text, $votename);
	$cookiename = $ComplexVoteCookie.$votename[1];
	if (isset ($_COOKIE[$cookiename]))
		return "";
	else
		return $text;
}

/**
 * Handles the voting process
 * 
 * @param string $pagename
 */
function HandleComplexVote($pagename, $auth = 'edit') {

	global $HandleActions, $ChangeSummary, $ComplexVoteCookie, $ComplexVoteExpires, $ComplexVoteDir;

	if (!isset ($_REQUEST['vote']))
		Redirect($pagename);

	Lock(2);
	$page = RetrieveAuthPage($pagename, $auth);
	if (!$page)
		Abort("?cannot edit $pagename");

	# searches all votes on the wiki page
	$votes = preg_split("/(\(:input form.*?action=complexvote)/", $page['text'], -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
	$votename = $_REQUEST['votename'];

	foreach ($votes as $key => $text) {
		# searchs the vote form in question, if there are more then one on a wiki page
		if (!preg_match("/\(:input hidden votename\s*".$votename."/", $text))
			continue;
		
		
		$cookiename = $ComplexVoteCookie.$votename;
		if (!isset ($_COOKIE[$cookiename]))
			setcookie($cookiename, "true", $ComplexVoteExpires, $ComplexVoteDir);
		else
			Redirect($pagename);

		# searchs for the label and values in the vote form
		preg_match_all("/\(:input radio vote\s*(.*?)\s*?:\)(.*?)(\n|\(:|\\\\)/", $text, $options);
		
		$diagrammdivider = "%comment%ComplexVotesDiagramDivider".$votename."%%";
		
		if (strpos($text, 'Votes:') === false) {
			# outputs the counter after the first vote
			$text = preg_split("/((?<=\(:input end:\))\n)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
			$v = "\n\n%comment%Votes:\\\\\n";
			foreach ($options[2] as $k)
				$v .= "".trim($k).": 0\\\\\n";
			$text[0] = $text[0].$v;
			$text[2] = $text[2];

		} else
			$text = explode($diagrammdivider, $text);
		
		# adding the counter for the particular vote by one
		$where = trim($options[2][array_search($_REQUEST['vote'], $options[1])]);
		$vote = preg_replace("/(\\b".$where.":\s)(\\d*)/e", "'\\1'.addone('\${2}')", $text[0], 1);
		
		$text = $vote.$diagrammdivider.drawdiagram($vote).$diagrammdivider.$text[2];
		$votes[$key] = $text;
	}

	$pagetext = implode("", $votes);
	$_POST['text'] = get_magic_quotes_gpc() ? addslashes($pagetext) : $pagetext;
	$ChangeSummary = FmtPageName("$[Vote]", $pagename);
	$_POST['post'] = 1;
	$HandleActions['edit'] ($pagename, $auth);
}

/**
 * Handles the drawing of the votes.
 * 
 * @param string $vote
 */
function drawdiagram($vote) {
	$out = "\n";
	preg_match_all("/\\b(.*?):\s(\\d*)/", $vote, $values);
	
    // Install your own fancy output/drawing code here. 
    // Label are in $values[1][$i], numerical values in $values[2][$i]
	$sum = 100 / array_sum($values[2]);
	$out .= "(:table:)\n";
	foreach ($values[0] as $k => $v) {
		$percentage = floor($values[2][$k] * $sum);
		$upbound = $percentage * 4;
		$out .= "(:cellnr:)".$values[1][$k]."\n(:cell style=\"width:".$upbound."px;display:block; background : silver; color:silver;\":).\n";
		$out .= "(:cell style=\"color:gray;\":) (".$values[2][$k]."/".$percentage."%)\n"; 
	}
	$out .= "(:tableend:) \n";
	
	return $out;
}

/**
 * santas little helper
 * 
 * @param int $value
 */
function addone($value) {
	return $value +1;
}
?>