Location: PHPKode > scripts > Tapps > tapps/functions.inc.php
<?php

/************************************************************************
 *									*
 *	Tapps - functions.inc.php					*
 *									*
 *	description	: advanced PHP poll system			*
 *	copyright	: (c) 2001,2002 by Stephan Uhlmann		*
 *	email		: hide@address.com				*
 *									*
 ************************************************************************/

/************************************************************************
 *                                                                      *
 * This program is free software; you can redistribute it and/or modify *
 * it under the terms of the GNU General Public License as published by *
 * the Free Software Foundation; either version 2 of the License, or    *
 * (at your option) any later version.                                  *
 *                                                                      *
 ************************************************************************/


function getVar($name, $default)
{
	global $HTTP_GET_VARS, $HTTP_POST_VARS;

	$retVal = $default;
	if (isset($HTTP_GET_VARS[$name]))
	{
		$retVal = $HTTP_GET_VARS[$name];
	} else
	if (isset($HTTP_POST_VARS[$name]))
	{
		$retVal = $HTTP_POST_VARS[$name];
	}
	return $retVal;
}

// establishes database connection
function db_connect()
{
	global $tapps_db_type, $tapps_db_host, $tapps_db_user, $tapps_db_password, $tapps_db_db;

	if ($tapps_db_type == "mysql")
	{
		mysql_pconnect($tapps_db_host,$tapps_db_user,$tapps_db_password) or die(mysql_error());
		mysql_select_db($tapps_db_db) or die(mysql_error());
	}
	else
	{
		die("Database \"$tapps_db_type\" not supported.<br>\n");
	}
}

// executes $query on current database conection
function db_query($query)
{
	global $tapps_db_type;

	if ($tapps_db_type == "mysql")
	{
		$result = mysql_query($query) or die(mysql_error());
		return $result;
	} else
	{
		die("Database \"$tapps_db_type\" not supported.<br>\n");
	}
}

// gets first entry (row) of a $result of a database query as an object
function db_fetch_object($result)
{
	global $tapps_db_type;

	if ($tapps_db_type == "mysql")
	{
		return mysql_fetch_object($result);
	} else
	{
		die("Database \"$tapps_db_type\" not supported.<br>\n");
	}
}

// prints the results of a poll
function poll_over($poll_id)
{
	$over = TRUE;

	$result = db_query("SELECT UNIX_TIMESTAMP(valid_until) AS time FROM tapps_polls WHERE poll_id=$poll_id");
	$o = db_fetch_object($result);

	if (($o->time == 0) || ($o->time > time())) $over=FALSE;

	return $over;
}


// prints the results of a poll
function print_results($poll_id)
{
	global $tapps_dir;
	global $tapps_pollbar_image_max_width;

	if (isset($tapps_pollbar_image_max_width))
		$barmaxwidth=$tapps_pollbar_image_max_width;
	else
		$barmaxwidth=128;

	$result = db_query("SELECT * FROM tapps_polls WHERE poll_id=$poll_id");
	$poll = db_fetch_object($result);

	if ($poll)
	{
		echo "<b>$poll->title</b><br>\n";
		echo "<br>\n";
		echo "$poll->description<br>\n";
		echo "<br>\n";

		$result = db_query("SELECT SUM(counter) AS sum_counter FROM tapps_votes WHERE poll_id=$poll_id");
		$o = db_fetch_object($result);
		$sum_counter = $o->sum_counter;

		$result = db_query("SELECT MAX(counter) AS max_counter FROM tapps_votes WHERE poll_id=$poll_id");
		$o = db_fetch_object($result);
		$max_counter = $o->max_counter;

		$result = db_query("SELECT option_text,counter FROM tapps_votes WHERE poll_id=$poll_id ORDER BY option_id");

		echo "<table cellpadding=0 cellspacing=4>\n";

		while ($row = db_fetch_object($result))
		{
			echo "<tr>\n";
			echo "<td>$row->option_text</td>\n";
			if ($row->counter > 0)
			{
				$p = (float)(100*$row->counter/$sum_counter);
				$w = (int)($barmaxwidth*$row->counter/$max_counter);
			}
			else
			{
				$p = 0;
				$w = 1;
			}
			$s = strip_tags($row->option_text);
			echo "<td><img src=\"".$tapps_dir."poll_bar.jpg\" height=15 width=$w alt=\"$s\"></td>\n";
			printf("<td>%.1f %% (%d)</td>\n", $p, $row->counter);
			echo "</tr>\n";
		}

		echo "</table>\n";
		echo "<br>\n";
		echo "$sum_counter total votes.<br>\n";
	} else
	{
		echo "Poll does not exist.<br>\n";
	}
}

// prints the voting form for poll with given $poll_id
function print_vote_form($poll_id)
{
	global $tapps_dir, $tapps_email_confirmation;

	$result = db_query("SELECT * FROM tapps_polls WHERE poll_id=$poll_id");
	$poll = db_fetch_object($result);

	if ($poll)
	{
		echo "<b>$poll->title</b><br>\n";
		echo "<br>\n";
		echo "$poll->description<br>\n";
		echo "<br>\n";

		$result = db_query("SELECT option_id,option_text,counter FROM tapps_votes WHERE poll_id=$poll_id ORDER BY option_id");

		echo "<form action=\"".$tapps_dir."poll.php\" method=\"post\">\n";

		echo "<input type=\"hidden\" name=\"mode\" value=\"vote\">\n";
		echo "<input type=\"hidden\" name=\"poll_id\" value=\"$poll->poll_id\">\n";

		$num_votes=0;
		if ($poll->max_answers > 1)
		{
			echo "(You can vote for $poll->max_answers options.)<br>\n";
			echo "<table cellpadding=0 cellspacing=2>\n";
			while ($row = db_fetch_object($result))
			{
				echo "<tr><td align=\"right\">\n";
				echo "<input type=checkbox name=\"options[]\" value=\"$row->option_id\" id=\"o$poll->poll_id-$row->option_id\">\n";
				echo "</td><td align=\"left\">\n";
				echo "<label for=\"o$poll->poll_id-$row->option_id\">$row->option_text</label><br>\n";
				echo "</td></tr>\n";
				$num_votes=$num_votes+$row->counter;
			}
			echo "</table>\n";
		} else
		if ($poll->max_answers > 0)
		{
			echo "<table><tr><td>\n";
			while ($row = db_fetch_object($result))
			{
				echo "<input type=radio name=\"options[]\" value=\"$row->option_id\" id=\"o$poll->poll_id-$row->option_id\">\n";
				echo "<label for=\"o$poll->poll_id-$row->option_id\">$row->option_text</label><br>\n";
				$num_votes=$num_votes+$row->counter;
			}
			echo "</td></tr></table>\n";
		}

		echo "<br>\n";
		if (isset($tapps_email_confirmation) && $tapps_email_confirmation==TRUE)
		{
			echo "Email: <input type=\"text\" name=\"voter_email\" value=\"\"><br>\n";
		}

		echo "<br>\n";

		echo "<input type=submit value=\"Vote\"><br>\n";
		echo "<a href=\"".$tapps_dir."poll.php?mode=results&amp;poll_id=$poll->poll_id\">Results</a> ($num_votes Votes)<br>\n";
		echo "</form>\n";
	} else
	{
		echo "Poll does not exist. Boo!<br>\n";
	}
}

// lists all polls
function print_poll_list()
{
	$result = db_query("SELECT * FROM tapps_polls WHERE enabled='Y' ORDER BY valid_until");
	while ($o = db_fetch_object($result))
	{
		echo "<a href=\"poll.php?mode=poll&amp;poll_id=$o->poll_id\">$o->title</a><br>\n";
	}
}

// default action
function default_action()
{
	$result = db_query("SELECT MAX(poll_id) AS max_poll_id FROM tapps_polls WHERE enabled='Y'");
	$o = db_fetch_object($result);
	if ($o->max_poll_id != NULL)
	{
		if (poll_over($o->max_poll_id)==TRUE)
		{
			print_results($o->max_poll_id);
			echo "Voting for this poll is over.<br>\n";
		}
		else
		{
			print_vote_form($o->max_poll_id);
		}
	}
}

// counts the vote (make changes in db)
function count_vote($poll_id, $options)
{
	global $HTTP_SERVER_VARS;
	global $tapps_ip_locking;

	// store data
	foreach ($options as $option_id)
	{
		db_query("UPDATE tapps_votes SET counter=counter+1 WHERE poll_id=$poll_id AND option_id=$option_id");
	}

	// lock ip 
	if (isset($tapps_ip_locking) && $tapps_ip_locking==TRUE)
	{
		$ip = $HTTP_SERVER_VARS['REMOTE_ADDR'];
		db_query("INSERT INTO tapps_iplocks (poll_id,ip) VALUES($poll_id,'$ip')");
	}

	// give feedback
	if (sizeof($options) > 1)
	{
		$c = $options[0]+1;
		echo "Your votes for options $c";
		for ($i=1;$i<sizeof($options)-1;$i++)
		{
			$c = $options[$i]+1;
			echo ", $c";
		}
		$i = sizeof($options)-1;
		$c = $options[$i]+1;
		echo " and $c";
		echo " have been counted.<br><br>\n";
	} else
	{
		$c = $options[0]+1;
		echo "Your vote for option $c has been counted.<br><br>\n";
	}

	// show updated results
	print_results($poll_id);
}

// checks if a vote is allowed
function check_vote($poll_id, $options)
{
	global $HTTP_SERVER_VARS;
	global $tapps_referer;
	global $tapps_ip_locking, $tapps_ip_locking_timeout;
	global $tapps_cookie, $tapps_cookie_name, $tapps_cookie_force;
	global $tapps_email_confirmation, $tapps_email_locking, $tapps_email_locking_timeout;
	global $already_voted, $voter_email;

	$result = db_query("SELECT * FROM tapps_polls WHERE poll_id=$poll_id");
	$poll = db_fetch_object($result);


	// referer check
	if (isset($tapps_referer) && $tapps_referer!="")
	{
		$referer=$HTTP_SERVER_VARS['HTTP_REFERER'];
		if ($i=strpos($referer,"?"))
		{
			$referer= substr($referer,0,$i);
		}
		if ($tapps_referer != $referer)
		{
			die("Go whence you came!<br>(a.k.a. \"Bad referer\")<br>\n");
		}
	}

	// valid number of options?
	if (sizeof($options) > $poll->max_answers)
	{
		die("You are only allowed to vote for $poll->max_answers options.<br>\n");
	}
	if (sizeof($options) > sizeof(array_unique($options)))
	{
		die("You are only allowed to vote once for each option.<br>(Strange... how did you do that?!?)<br>\n");
	}


	// ip locking
	if (isset($tapps_ip_locking) && $tapps_ip_locking==TRUE)
	{
		if (isset($tapps_ip_locking_timeout) && $tapps_ip_locking_timeout>0)
		{
			$i = time() - $tapps_ip_locking_timeout;
			db_query("DELETE FROM tapps_iplocks WHERE UNIX_TIMESTAMP(timestamp) < $i");
		}
		$ip = $HTTP_SERVER_VARS['REMOTE_ADDR'];

		$result = db_query("SELECT COUNT(*) AS locked FROM tapps_iplocks WHERE poll_id=$poll_id AND ip='$ip'");
		$o = db_fetch_object($result);
		if ($o->locked > 0)
		{
			die("You (or someone else from your IP-address) already voted for this poll recently.<br>\n");
		}
	}

	// cookie check
	if (isset($tapps_cookie) && $tapps_cookie==TRUE)
	{
		if (in_array($poll_id, $already_voted))
		{
			die("You already voted for this poll.<br>\n");
		}
	}

	// email ok
	if (isset($tapps_email_confirmation) && $tapps_email_confirmation==TRUE)
	{
		if (eregi("^[_\.0-9a-z-]+@([0-9a-z][-0-9a-z\.]+)\.([a-z][a-z]+$)",$voter_email) == FALSE)
		{
			die("Invalid email address.<br>\n");
		}

		// email locking
		if (isset($tapps_email_locking) && $tapps_email_locking==TRUE)
		{
			if (isset($tapps_email_locking_timeout) && $tapps_email_locking_timeout>0)
			{
				$i = time() - $tapps_email_locking_timeout;
				db_query("DELETE FROM tapps_emaillocks WHERE UNIX_TIMESTAMP(timestamp) < $i");
			}

			$result = db_query("SELECT COUNT(*) AS locked FROM tapps_emaillocks WHERE poll_id=$poll_id AND email='$voter_email'");
			$o = db_fetch_object($result);
			if ($o->locked > 0)
			{
				die("You (or someone else using your Email-address) already voted for this poll recently.<br>\n");
			}
		}
	}
}

// does the vote
function do_vote($poll_id,$options)
{
	global $HTTP_SERVER_VARS;
	global $tapps_cookie, $tapps_cookie_name, $tapps_cookie_force;
	global $tapps_email_confirmation, $tapps_email_confirmation_from, $tapps_email_locking;
	global $already_voted, $voter_email;

	$url = "";
	// cookie
	if (isset($tapps_cookie) && $tapps_cookie==TRUE)
	{
		array_push($already_voted, $poll_id);
		$cookie_value = serialize($already_voted);
		setcookie("$tapps_cookie_name","$cookie_value",time()+31536000);
		// if we force the user to accpet the cookie then create a pending vote
		// and redirect to that url
		if (isset($tapps_cookie_force) && $tapps_cookie_force==TRUE)
		{
			$db_value = serialize($options);
			$id = md5(uniqid(rand()));
			db_query("INSERT INTO tapps_pending (id,poll_id,options) VALUES('$id',$poll_id,'$db_value')");
			$url = "http://".$HTTP_SERVER_VARS['HTTP_HOST'].$HTTP_SERVER_VARS['PHP_SELF']."?mode=activate&pending_id=$id";

			// don't redirect now if we have email confirmation enabled (handled later)
			if (isset($tapps_email_confirmation)==FALSE || $tapps_email_confirmation!=TRUE ||
			    isset($voter_email)==FALSE || $voter_email == "")
			{
				header("Location: $url");
				echo "<html><body></body></html>";
				exit;
			}
		}
	}


	if (isset($tapps_email_confirmation) && $tapps_email_confirmation==TRUE &&
	    isset($voter_email) && $voter_email!="")
	{
		// when there is no pending vote yet then create one
		if ($url == "")
		{
			$db_value = serialize($options);
			$id = md5(uniqid(rand()));
			db_query("INSERT INTO tapps_pending (id,poll_id,options) VALUES('$id',$poll_id,'$db_value')");
			$url = "http://".$HTTP_SERVER_VARS['HTTP_HOST'].$HTTP_SERVER_VARS['PHP_SELF']."?mode=activate&pending_id=$id";
		}
		mail($voter_email,"Poll confirmation",
			"To activate your vote please go to the following URL\n".
			"$url\n",
			"From: $tapps_email_confirmation_from");
		echo "Emailed $voter_email for confirmation.<br>\n";
		// lock email
		if (isset($tapps_email_locking) && $tapps_email_locking==TRUE)
		{
			db_query("INSERT INTO tapps_emaillocks (poll_id,email) VALUES($poll_id,'$voter_email')");
		}
		exit;
	}

	// if nothing else hen immediatly count the vote
	count_vote($poll_id,$options);
}

// activates a pending vote
function activate_vote($pending_id)
{
	global $tapps_pending_timeout;
	global $already_voted;


	if (isset($tapps_pending_timeout) && $tapps_pending_timeout>0)
	{
		$i = time() - $tapps_pending_timeout;
		db_query("DELETE FROM tapps_pending WHERE UNIX_TIMESTAMP(timestamp) < $i");
	}

	$result = db_query("SELECT poll_id,options FROM tapps_pending WHERE id='$pending_id'");
	$o = db_fetch_object($result);
	if (is_object($o) && isset($o->poll_id) && isset($o->options))
	{
		db_query("DELETE FROM tapps_pending WHERE id='$pending_id'");
		if ((isset($already_voted)) && (in_array($o->poll_id, $already_voted)))
		{
			$options = array();
			$options = unserialize($o->options);
			count_vote($o->poll_id,$options);
		} else
		{
			die("You must accept cookies (or this particular cookie) to be able to vote.<br>\n");
		}
	} else
	{
		die("Invalid pending vote.<br>(Don't mess with the input. I don't trust you!)<br>\n");
	}
}


?>
Return current item: Tapps