<?php
/*
Plugin Name: WP-Polls
Plugin URI: http://www.lesterchan.net/portfolio/programming.php
Description: Adds A Poll Feature To WordPress
Version: 2.12
Author: GaMerZ
Author URI: http://www.lesterchan.net
*/


/*  Copyright 2006  Lester Chan  (email : gamerz84@hotmail.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.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/


### Polls Table Name
$wpdb->pollsq					= $table_prefix . 'pollsq';
$wpdb->pollsa					= $table_prefix . 'pollsa';
$wpdb->pollsip					= $table_prefix . 'pollsip';


### Function: Poll Administration Menu
add_action('admin_menu', 'poll_menu');
function poll_menu() {
	if (function_exists('add_menu_page')) {
		add_menu_page(__('Polls'), __('Polls'), 'manage_polls', 'polls/polls-manager.php');
	}
	if (function_exists('add_submenu_page')) {
		add_submenu_page('polls/polls-manager.php', __('Manage Polls'), __('Manage Polls'), 'manage_polls', 'polls/polls-manager.php');
		add_submenu_page('polls/polls-manager.php', __('Poll Options'), __('Poll Options'), 'manage_polls', 'polls/polls-options.php');
	}
}


### Function: Get Poll
function get_poll($temp_poll_id = 0, $display = true) {
	global $wpdb, $polls_loaded;
	// Poll Result Link
	$pollresult_id = intval($_GET['pollresult']);
	// Check Whether Poll Is Disabled
	if(intval(get_settings('poll_currentpoll')) == -1) {
		if($display) {
			echo stripslashes(get_settings('poll_template_disable'));
			return;
		} else {
			return stripslashes(get_settings('poll_template_disable'));
		}		
	// Poll Is Enabled
	} else {
		// Hardcoded Poll ID Is Not Specified
		if(intval($temp_poll_id) == 0) {
			// Random Poll
			if(intval(get_settings('poll_currentpoll')) == -2) {
				$random_poll_id = $wpdb->get_var("SELECT pollq_id FROM $wpdb->pollsq ORDER BY RAND() LIMIT 1");
				$poll_id = intval($random_poll_id);
				if($pollresult_id > 0) {
					$poll_id = $pollresult_id;
				} elseif(intval($_POST['poll_id']) > 0) {
					$poll_id = intval($_POST['poll_id']);
				}
			// Current Poll ID Is Not Specified
			} elseif(intval(get_settings('poll_currentpoll')) == 0) {
				// Get Lastest Poll ID
				$poll_id = intval(get_settings('poll_latestpoll'));
			} else {
				// Get Current Poll ID
				$poll_id = intval(get_settings('poll_currentpoll'));
			}
		// Get Hardcoded Poll ID
		} else {
			$poll_id = intval($temp_poll_id);
		}
	}
	
	// Assign All Loaded Poll To $polls_loaded
	if(empty($polls_loaded)) {
		$polls_loaded = array();
	}
	if(!in_array($poll_id, $polls_loaded)) {
		$polls_loaded[] = $poll_id;
	}

	// User Click on View Results Link
	if($pollresult_id == $poll_id) {
		if($display) {
			echo display_pollresult($poll_id);
			return;
		} else {
			return display_pollresult($poll_id);
		}
	// Check Whether User Has Voted
	} else {
		$poll_active = $wpdb->get_var("SELECT pollq_active FROM $wpdb->pollsq WHERE pollq_id = $poll_id");
		$poll_active = intval($poll_active);
		$check_voted = check_voted($poll_id);
		if($check_voted > 0 || $poll_active == 0 || !check_allowtovote()) {
			if($display) {
				echo display_pollresult($poll_id, $check_voted);
				return;
			} else {
				return display_pollresult($poll_id, $check_voted);
			}
		} else {
			if($display) {
				echo display_pollvote($poll_id);
				return;
			} else {
				return display_pollvote($poll_id);
			}
		}
	}	
}


### Function: Displays Polls Header
add_action('wp_head', 'poll_header');
function poll_header() {	
	if(strpos($_SERVER['SCRIPT_NAME'], 'php.cgi') === false) {
		$ajax_url = $_SERVER['SCRIPT_NAME'];
	} else {
		$ajax_url = $_SERVER['PHP_SELF'];
	}
	echo '<script type="text/javascript">'."\n";
	echo '/* Start Of Javascript Generated By WP-Polls 2.12 */'."\n";
	echo '/* <![CDATA[ */'."\n";
	echo "\t".'if(site_url != \''.get_settings('siteurl').'\' || ajax_url != \''.$ajax_url.'\') {'."\n";
	echo "\t\t".'var site_url = \''.get_settings('siteurl').'\';'."\n";
	echo "\t\t".'var ajax_url = \''.$ajax_url.'\';'."\n";
	echo "\t".'}'."\n";
	echo '/* ]]> */'."\n";
	echo '/* End Of Javascript Generated By WP-Polls 2.12 */'."\n";
	echo '</script>'."\n";
	echo '<script src="'.get_settings('siteurl').'/wp-includes/js/tw-sack.js" type="text/javascript"></script>'."\n";
	echo '<script src="'.get_settings('siteurl').'/wp-content/plugins/polls/polls-js.js" type="text/javascript"></script>'."\n";
	echo '<link rel="stylesheet" href="'.get_settings('siteurl').'/wp-content/plugins/polls/polls-css.css" type="text/css" media="screen" />'."\n";
}


### Function: Check Who Is Allow To Vote
function check_allowtovote() {
	global $user_ID;
	$user_ID = intval($user_ID);
	$allow_to_vote = intval(get_settings('poll_allowtovote'));
	switch($allow_to_vote) {
		// Guests Only
		case 0:
			if($user_ID > 0) {
				return false;
			}
			return true;
			break;
		// Registered Users Only
		case 1:
			if($user_ID == 0) {
				return false;
			}
			return true;
			break;
		// Registered Users And Guests
		case 2:
		default:
			return true;
	}
}


### Funcrion: Check Voted By Cookie Or IP
function check_voted($poll_id) {
	$poll_logging_method = intval(get_settings('poll_logging_method'));
	switch($poll_logging_method) {
		// Do Not Log
		case 0:
			return 0;
			break;
		// Logged By Cookie
		case 1:
			return check_voted_cookie($poll_id);
			break;
		// Logged By IP
		case 2:
			return check_voted_ip($poll_id);
			break;
		// Logged By Cookie And IP
		case 3:
			$check_voted_cookie = check_voted_cookie($poll_id);
			if($check_voted_cookie > 0) {
				return $check_voted_cookie;
			} else {
				return check_voted_ip($poll_id);
			}
			break;
		// Logged By Username
		case 4:
			return check_voted_username($poll_id);
			break;
	}
}


### Function: Check Voted By Cookie
function check_voted_cookie($poll_id) {
	// 0: False | > 0: True
	return intval($_COOKIE["voted_$poll_id"]);
}


### Function: Check Voted By IP
function check_voted_ip($poll_id) {
	global $wpdb;
	// Check IP From IP Logging Database
	$get_voted_aid = $wpdb->get_var("SELECT pollip_aid FROM $wpdb->pollsip WHERE pollip_qid = $poll_id AND pollip_ip = '".get_ipaddress()."'");
	// 0: False | > 0: True
	return intval($get_voted_aid);
}


### Function: Check Voted By Username
function check_voted_username($poll_id) {
	global $wpdb, $user_ID;
	// Check IP If User Is Guest
	if ($user_ID == 0) {
		return check_voted_ip($poll_id);
	}
	$pollsip_userid = intval($user_ID);
	// Check User ID From IP Logging Database
	$get_voted_aid = $wpdb->get_var("SELECT pollip_aid FROM $wpdb->pollsip WHERE pollip_qid = $poll_id AND pollip_userid = $pollsip_userid");
	// 0: False | > 0: True
	return intval($get_voted_aid);
}


### Function: Display Voting Form
function display_pollvote($poll_id, $without_poll_title = false) {
	global $wpdb;
	// Temp Poll Result
	$temp_pollvote = '';
	// Get Poll Question Data
	$poll_question = $wpdb->get_row("SELECT pollq_id, pollq_question, pollq_totalvotes FROM $wpdb->pollsq WHERE pollq_id = $poll_id LIMIT 1");
	// Poll Question Variables
	$poll_question_text = stripslashes($poll_question->pollq_question);
	$poll_question_id = intval($poll_question->pollq_id);
	$poll_question_totalvotes = intval($poll_question->pollq_totalvotes);
	$template_question = stripslashes(get_settings('poll_template_voteheader'));
	$template_question = str_replace("%POLL_QUESTION%", $poll_question_text, $template_question);
	$template_question = str_replace("%POLL_ID%", $poll_question_id, $template_question);
	$template_question = str_replace("%POLL_TOTALVOTES%", $poll_question_totalvotes, $template_question);
	// Get Poll Answers Data
	$poll_answers = $wpdb->get_results("SELECT polla_aid, polla_answers, polla_votes FROM $wpdb->pollsa WHERE polla_qid = $poll_question_id ORDER BY ".get_settings('poll_ans_sortby').' '.get_settings('poll_ans_sortorder'));
	// If There Is Poll Question With Answers
	if($poll_question && $poll_answers) {
		// Display Poll Voting Form
		if(!$without_poll_title) {
			$temp_pollvote .= "<div id=\"polls-$poll_question_id\" class=\"wp-polls\">\n";
			$temp_pollvote .= "\t<form id=\"polls_form_$poll_question_id\" action=\"$_SERVER[REQUEST_URI]\" method=\"post\">\n";
			$temp_pollvote .= "\t\t<p><input type=\"hidden\" name=\"poll_id\" value=\"$poll_question_id\" /></p>\n";
			// Print Out Voting Form Header Template
			$temp_pollvote .= "\t\t$template_question\n";
		}
		foreach($poll_answers as $poll_answer) {
			// Poll Answer Variables
			$poll_answer_id = intval($poll_answer->polla_aid); 
			$poll_answer_text = stripslashes($poll_answer->polla_answers);
			$poll_answer_votes = intval($poll_answer->polla_votes);
			$template_answer = stripslashes(get_settings('poll_template_votebody'));
			$template_answer = str_replace("%POLL_ID%", $poll_question_id, $template_answer);
			$template_answer = str_replace("%POLL_ANSWER_ID%", $poll_answer_id, $template_answer);
			$template_answer = str_replace("%POLL_ANSWER%", $poll_answer_text, $template_answer);
			$template_answer = str_replace("%POLL_ANSWER_VOTES%", number_format($poll_answer_votes), $template_answer);
			// Print Out Voting Form Body Template
			$temp_pollvote .= "\t\t$template_answer\n";
		}
		// Determine Poll Result URL
		$poll_result_url = $_SERVER['REQUEST_URI'];
		$poll_result_url = preg_replace('/pollresult=(\d+)/i', 'pollresult='.$poll_question_id, $poll_result_url);
		if(intval($_GET['pollresult']) == 0) {
			if(strpos($poll_result_url, '?') !== false) {
				$poll_result_url = "$poll_result_url&amp;pollresult=$poll_question_id";
			} else {
				$poll_result_url = "$poll_result_url?pollresult=$poll_question_id";
			}
		}
		// Voting Form Footer Variables
		$template_footer = stripslashes(get_settings('poll_template_votefooter'));
		$template_footer = str_replace("%POLL_ID%", $poll_question_id, $template_footer);
		$template_footer = str_replace("%POLL_RESULT_URL%", $poll_result_url, $template_footer);
		// Print Out Voting Form Footer Template
		$temp_pollvote .= "\t\t$template_footer\n";
		if(!$without_poll_title) {
			$temp_pollvote .= "\t</form>\n";
			$temp_pollvote .= "</div>\n";
			$temp_pollvote .= "<div id=\"polls-$poll_question_id-loading\" class=\"wp-polls-loading\"><img src=\"".get_settings('siteurl')."/wp-content/plugins/polls/images/loading.gif\" width=\"16\" height=\"16\" alt=\"".__('Loading')." ...\" title=\"".__('Loading')." ...\" class=\"wp-polls-image\" />&nbsp;".__('Loading')." ...</div>\n";
		}		
	} else {
		$temp_pollvote .= stripslashes(get_settings('poll_template_disable'));
	}
	// Return Poll Vote Template
	return $temp_pollvote;
}


### Function: Display Results Form
function display_pollresult($poll_id, $user_voted = 0, $without_poll_title = false) {
	global $wpdb;
	// Temp Poll Result
	$temp_pollresult = '';	
	// Most/Least Variables
	$poll_most_answer = '';
	$poll_most_votes = 0;
	$poll_most_percentage = 0;
	$poll_least_answer = '';
	$poll_least_votes = 0;
	$poll_least_percentage = 0;
	// Get Poll Question Data
	$poll_question = $wpdb->get_row("SELECT pollq_id, pollq_question, pollq_totalvotes, pollq_active FROM $wpdb->pollsq WHERE pollq_id = $poll_id LIMIT 1");
	// Poll Question Variables
	$poll_question_text = stripslashes($poll_question->pollq_question);
	$poll_question_id = intval($poll_question->pollq_id);
	$poll_question_totalvotes = intval($poll_question->pollq_totalvotes);
	$poll_question_active = intval($poll_question->pollq_active);
	$template_question = stripslashes(get_settings('poll_template_resultheader'));
	$template_question = str_replace("%POLL_QUESTION%", $poll_question_text, $template_question);
	$template_question = str_replace("%POLL_ID%", $poll_question_id, $template_question);
	$template_question = str_replace("%POLL_TOTALVOTES%", $poll_question_totalvotes, $template_question);
	// Get Poll Answers Data
	$poll_answers = $wpdb->get_results("SELECT polla_aid, polla_answers, polla_votes FROM $wpdb->pollsa WHERE polla_qid = $poll_question_id ORDER BY ".get_settings('poll_ans_result_sortby').' '.get_settings('poll_ans_result_sortorder'));
	// If There Is Poll Question With Answers
	if($poll_question && $poll_answers) {
		// Is The Poll Total Votes 0?
		$poll_totalvotes_zero = true;
		if($poll_question_totalvotes > 0) {
			$poll_totalvotes_zero = false;
		}
		// Print Out Result Header Template
		if(!$without_poll_title) {
			$temp_pollresult .= "<div id=\"polls-$poll_question_id\" class=\"wp-polls\">\n";
			$temp_pollresult .= "\t\t$template_question\n";
		}
		foreach($poll_answers as $poll_answer) {
			// Poll Answer Variables
			$poll_answer_id = intval($poll_answer->polla_aid); 
			$poll_answer_text = stripslashes($poll_answer->polla_answers);
			$poll_answer_votes = intval($poll_answer->polla_votes);
			$poll_answer_percentage = 0;
			$poll_answer_imagewidth = 0;
			// Calculate Percentage And Image Bar Width
			if(!$poll_totalvotes_zero) {
				if($poll_answer_votes > 0) {
					$poll_answer_percentage = round((($poll_answer_votes/$poll_question_totalvotes)*100));
					$poll_answer_imagewidth = round($poll_answer_percentage);
				} else {
					$poll_answer_percentage = 0;
					$poll_answer_imagewidth = 1;
				}
			} else {
				$poll_answer_percentage = 0;
				$poll_answer_imagewidth = 1;
			}
			// Let User See What Options They Voted
			if($user_voted == $poll_answer_id) {
				// Results Body Variables
				$template_answer = stripslashes(get_settings('poll_template_resultbody2'));
				$template_answer = str_replace("%POLL_ANSWER_ID%", $poll_answer_id, $template_answer);
				$template_answer = str_replace("%POLL_ANSWER%", $poll_answer_text, $template_answer);
				$template_answer = str_replace("%POLL_ANSWER_TEXT%", htmlspecialchars(strip_tags($poll_answer_text)), $template_answer);
				$template_answer = str_replace("%POLL_ANSWER_VOTES%", number_format($poll_answer_votes), $template_answer);
				$template_answer = str_replace("%POLL_ANSWER_PERCENTAGE%", $poll_answer_percentage, $template_answer);
				$template_answer = str_replace("%POLL_ANSWER_IMAGEWIDTH%", $poll_answer_imagewidth, $template_answer);
				// Print Out Results Body Template
				$temp_pollresult .= "\t\t$template_answer\n";
			} else {
				// Results Body Variables
				$template_answer = stripslashes(get_settings('poll_template_resultbody'));
				$template_answer = str_replace("%POLL_ANSWER_ID%", $poll_answer_id, $template_answer);
				$template_answer = str_replace("%POLL_ANSWER%", $poll_answer_text, $template_answer);
				$template_answer = str_replace("%POLL_ANSWER_TEXT%", htmlspecialchars(strip_tags($poll_answer_text)), $template_answer);
				$template_answer = str_replace("%POLL_ANSWER_VOTES%", number_format($poll_answer_votes), $template_answer);
				$template_answer = str_replace("%POLL_ANSWER_PERCENTAGE%", $poll_answer_percentage, $template_answer);
				$template_answer = str_replace("%POLL_ANSWER_IMAGEWIDTH%", $poll_answer_imagewidth, $template_answer);
				// Print Out Results Body Template
				$temp_pollresult .= "\t\t$template_answer\n";
			}
			// Get Most Voted Data
			if($poll_answer_votes > $poll_most_votes) {
				$poll_most_answer = $poll_answer_text;
				$poll_most_votes = $poll_answer_votes;
				$poll_most_percentage = $poll_answer_percentage;
			}
			// Get Least Voted Data
			if($poll_least_votes == 0) {
				$poll_least_votes = $poll_answer_votes;
			}
			if($poll_answer_votes <= $poll_least_votes) {
				$poll_least_answer = $poll_answer_text;
				$poll_least_votes = $poll_answer_votes;
				$poll_least_percentage = $poll_answer_percentage;
			}
		}
		// Results Footer Variables
		if($user_voted > 0 || $poll_question_active == 0 || !check_allowtovote()) {
			$template_footer = stripslashes(get_settings('poll_template_resultfooter'));
		} else {
			$template_footer = stripslashes(get_settings('poll_template_resultfooter2'));
		}
		$template_footer = str_replace("%POLL_ID%", $poll_question_id, $template_footer);
		$template_footer = str_replace("%POLL_TOTALVOTES%", number_format($poll_question_totalvotes), $template_footer);
		$template_footer = str_replace("%POLL_MOST_ANSWER%", $poll_most_answer, $template_footer);
		$template_footer = str_replace("%POLL_MOST_VOTES%", number_format($poll_most_votes), $template_footer);
		$template_footer = str_replace("%POLL_MOST_PERCENTAGE%", $poll_most_percentage, $template_footer);
		$template_footer = str_replace("%POLL_LEAST_ANSWER%", $poll_least_answer, $template_footer);
		$template_footer = str_replace("%POLL_LEAST_VOTES%", number_format($poll_least_votes), $template_footer);
		$template_footer = str_replace("%POLL_LEAST_PERCENTAGE%", $poll_least_percentage, $template_footer);
		// Print Out Results Footer Template
		$temp_pollresult .= "\t\t$template_footer\n";
		if(!$without_poll_title) {
			$temp_pollresult .= "</div>\n";
			$temp_pollresult .= "<div id=\"polls-$poll_question_id-loading\" class=\"wp-polls-loading\"><img src=\"".get_settings('siteurl')."/wp-content/plugins/polls/images/loading.gif\" width=\"16\" height=\"16\" alt=\"".__('Loading')." ...\" title=\"".__('Loading')." ...\" class=\"wp-polls-image\" />&nbsp;".__('Loading')." ...</div>\n";
		}		
	} else {
		$temp_pollresult .= stripslashes(get_settings('poll_template_disable'));
	}	
	// Return Poll Result
	return $temp_pollresult;
}


### Function: Vote Poll
add_action('init', 'vote_poll');
function vote_poll() {
	global $wpdb, $user_identity, $user_ID;
	if(!empty($_POST['vote'])) {
		$poll_id = intval($_POST['poll_id']);
		$poll_aid = intval($_POST["poll_$poll_id"]);
		if($poll_id > 0 && $poll_aid > 0 && check_allowtovote()) {
			$check_voted = check_voted($poll_id);
			if($check_voted == 0) {
				if(!empty($user_identity)) {
					$pollip_user = addslashes($user_identity);
				} elseif(!empty($_COOKIE['comment_author_'.COOKIEHASH])) {
					$pollip_user = addslashes($_COOKIE['comment_author_'.COOKIEHASH]);
				} else {
					$pollip_user = 'Guest';
				}
				$pollip_userid = intval($user_ID);
				$pollip_ip = get_ipaddress();
				$pollip_host = gethostbyaddr($pollip_ip);
				$pollip_timestamp = current_time('timestamp');
				// Only Create Cookie If User Choose Logging Method 1 Or 2
				$poll_logging_method = intval(get_settings('poll_logging_method'));
				if($poll_logging_method == 1 || $poll_logging_method == 3) {
					$vote_cookie = setcookie("voted_".$poll_id, $poll_aid, time() + 30000000, COOKIEPATH);						
				}
				// Log Ratings No Matter What
				$vote_ip = $wpdb->query("INSERT INTO $wpdb->pollsip VALUES (0, $poll_id, $poll_aid, '$pollip_ip', '$pollip_host', '$pollip_timestamp', '$pollip_user', $pollip_userid)");
				$vote_a = $wpdb->query("UPDATE $wpdb->pollsa SET polla_votes = (polla_votes+1) WHERE polla_qid = $poll_id AND polla_aid = $poll_aid");
				if($vote_a) {
					$vote_q = $wpdb->query("UPDATE $wpdb->pollsq SET pollq_totalvotes = (pollq_totalvotes+1) WHERE pollq_id = $poll_id");
					if($vote_q) {
						echo "<ul class=\"wp-polls-ul\">\n".display_pollresult($poll_id,$poll_aid, 1);
						exit();
					} else {
						_e("Unable To Update Poll Total Votes. Poll ID #$poll_id.");
						exit();
					} // End if($vote_q)
				} else {
					_e("Unable To Update Poll Answer Votes. Poll ID #$poll_id, Poll Answer ID #$poll_aid.");
					exit();	
				} // End if($vote_a)
			} else {
				_e("You Had Already Voted For This Poll. Poll ID #$poll_id.");
				exit();
			}// End if($check_voted)
		} else {
			_e("Invalid Poll ID Or Poll Answer ID. Poll ID #$poll_id, Poll Answer ID #$poll_aid.");
			exit();
		} // End if($poll_id > 0 && $poll_aid > 0)
	} elseif (intval($_GET['pollresult']) > 0) {
		$poll_id = intval($_GET['pollresult']);
		echo "<ul class=\"wp-polls-ul\">\n".display_pollresult($poll_id, 0, true);
		exit();
	} elseif (intval($_GET['pollbooth']) > 0) {
		$poll_id = intval($_GET['pollbooth']);
		echo "<ul class=\"wp-polls-ul\">\n".display_pollvote($poll_id, true);
		exit();
	} // End if(!empty($_POST['vote']))
}


### Function: Get IP Address
if(!function_exists('get_ipaddress')) {
	function get_ipaddress() {
		if (empty($_SERVER["HTTP_X_FORWARDED_FOR"])) {
			$ip_address = $_SERVER["REMOTE_ADDR"];
		} else {
			$ip_address = $_SERVER["HTTP_X_FORWARDED_FOR"];
		}
		if(strpos($ip_address, ',') !== false) {
			$ip_address = explode(',', $ip_address);
			$ip_address = $ip_address[0];
		}
		return $ip_address;
	}
}


### Function: Place Polls Archive In Content
add_filter('the_content', 'place_pollsarchive', '7');
function place_pollsarchive($content){
     $content = preg_replace( "/\[page_polls\]/ise", "polls_archive()", $content); 
    return $content;
}


### Function: Place Poll In Content (By: Robert Accettura Of http://robert.accettura.com/)
add_filter('the_content', 'place_poll', '7');
function place_poll($content){
     $content = preg_replace( "/\[poll=(\d+)\]/ise", "display_poll('\\1')", $content); 
    return $content;
}


### Function: Display The Poll In Content (By: Robert Accettura Of http://robert.accettura.com/)
function display_poll($poll_id){
	return get_poll($poll_id, false);
}


### Function: Get Poll Total Questions
if(!function_exists('get_pollquestions')) {
	function get_pollquestions($display = true) {
		global $wpdb;
		$totalpollq = $wpdb->get_var("SELECT COUNT(pollq_id) FROM $wpdb->pollsq");
		if($display) {
			echo number_format($totalpollq);
		} else {
			return number_format($totalpollq);
		}
	}
}


### Function: Get Poll Total Answers
if(!function_exists('get_pollanswers')) {
	function get_pollanswers($display = true) {
		global $wpdb;
		$totalpolla = $wpdb->get_var("SELECT COUNT(polla_aid) FROM $wpdb->pollsa");
		if($display) {
			echo number_format($totalpolla);
		} else {
			return number_format($totalpolla);
		}
	}
}


### Function: Get Poll Total Votes
if(!function_exists('get_pollvotes')) {
	function get_pollvotes($display = true) {
		global $wpdb;
		$totalpollip = $wpdb->get_var("SELECT COUNT(pollip_id) FROM $wpdb->pollsip");
		if($display) {
			echo number_format($totalpollip);
		} else {
			return number_format($totalpollip);
		}
	}
}


### Un HTML Entities
function unhtmlentities($string) { 
   $string = preg_replace('~&#x([0-9a-f]+);~ei', 'chr(hexdec("\\1"))', $string);
   $string = preg_replace('~&#([0-9]+);~e', 'chr(\\1)', $string);
   $trans_tbl = get_html_translation_table(HTML_ENTITIES);
   $trans_tbl = array_flip($trans_tbl);
   return strtr($string, $trans_tbl);
}


### Function: Check Voted To Get Voted Answer
function check_voted_multiple($poll_id) {
	global $polls_ips;
	$temp_voted_aid = 0;
	if(intval($_COOKIE["voted_$poll_id"]) > 0) {
		$temp_voted_aid = intval($_COOKIE["voted_$poll_id"]);
	} else {
		if($polls_ips) {
			foreach($polls_ips as $polls_ip) {
				if($polls_ip['qid'] == $poll_id) {
					$temp_voted_aid = $polls_ip['aid'];
				}
			}
		}
	}
	return $temp_voted_aid;
}


### Function: Polls Archive Link
function polls_archive_link($page) {
	$current_url = $_SERVER['REQUEST_URI'];
	$curren_pollpage = intval($_GET['poll_page']);
	$polls_archive_url = preg_replace('/poll_page=(\d+)/i', 'poll_page='.$page, $current_url);
	if($curren_pollpage == 0) {
		if(strpos($current_url, '?') !== false) {
			$polls_archive_url = "$polls_archive_url&amp;poll_page=$page";
		} else {
			$polls_archive_url = "$polls_archive_url?poll_page=$page";
		}
	}
	return $polls_archive_url;
}


### Function: Displays Polls Archive Link
function display_polls_archive_link($display = true) {
	if(intval(get_settings('poll_archive_show')) == 1) {
		if($display) {
			echo "<ul>\n<li><a href=\"".get_settings('poll_archive_url')."\">Polls Archive</a></li></ul>\n";
		} else{
			return "<ul>\n<li><a href=\"".get_settings('poll_archive_url')."\">Polls Archive</a></li></ul>\n";
		}
	}
}


### Function: Display Polls Archive
function polls_archive() {
	global $wpdb, $polls_ips, $in_pollsarchive;
	// Polls Variables
	$in_pollsarchive = true;
	$page = intval($_GET['poll_page']);
	$polls_questions = array();
	$polls_answers = array();
	$polls_ip = array();
	$polls_perpage = intval(get_settings('poll_archive_perpage'));
	$poll_questions_ids = '0';
	$poll_voted = false;
	$poll_voted_aid = 0;
	$poll_id = 0;
	$pollsarchive_output = '';

	// Get Total Polls
	$total_polls = $wpdb->get_var("SELECT COUNT(pollq_id) FROM $wpdb->pollsq");

	// Checking $page and $offset
	if (empty($page) || $page == 0) { $page = 1; }
	if (empty($offset)) { $offset = 0; }

	// Determin $offset
	$offset = ($page-1) * $polls_perpage;

	// Determine Max Number Of Polls To Display On Page
	if(($offset + $polls_perpage) > $total_polls) { 
		$max_on_page = $total_polls; 
	} else { 
		$max_on_page = ($offset + $polls_perpage); 
	}

	// Determine Number Of Polls To Display On Page
	if (($offset + 1) > ($total_polls)) { 
		$display_on_page = $total_polls; 
	} else { 
		$display_on_page = ($offset + 1); 
	}

	// Determing Total Amount Of Pages
	$total_pages = ceil($total_polls / $polls_perpage);

	// Make Sure Poll Is Not Disabled
	if(intval(get_settings('poll_currentpoll')) != -1 && $page < 2) {
		// Hardcoded Poll ID Is Not Specified
		if(intval($temp_poll_id) == 0) {
			// Random Poll
			if(intval(get_settings('poll_currentpoll')) == -2) {
				$random_poll_id = $wpdb->get_var("SELECT pollq_id FROM $wpdb->pollsq ORDER BY RAND() LIMIT 1");
				$poll_id = intval($random_poll_id);
			// Current Poll ID Is Not Specified
			} else if(intval(get_settings('poll_currentpoll')) == 0) {
				// Get Lastest Poll ID
				$poll_id = intval(get_settings('poll_latestpoll'));
			} else {
				// Get Current Poll ID
				$poll_id = intval(get_settings('poll_currentpoll'));
			}
		// Get Hardcoded Poll ID
		} else {
			$poll_id = intval($temp_poll_id);
		}
	}

	// Get Poll Questions
	$questions = $wpdb->get_results("SELECT * FROM $wpdb->pollsq WHERE pollq_id != $poll_id ORDER BY pollq_id DESC LIMIT $offset, $polls_perpage");
	if($questions) {
		foreach($questions as $question) {
			$polls_questions[] = array('id' => intval($question->pollq_id), 'question' => stripslashes($question->pollq_question), 'timestamp' => $question->pollq_timestamp, 'totalvotes' => intval($question->pollq_totalvotes));
			$poll_questions_ids .= intval($question->pollq_id).', ';
		}
		$poll_questions_ids = substr($poll_questions_ids, 0, -2);
	}

	// Get Poll Answers
	$answers = $wpdb->get_results("SELECT polla_aid, polla_qid, polla_answers, polla_votes FROM $wpdb->pollsa WHERE polla_qid IN ($poll_questions_ids) ORDER BY ".get_settings('poll_ans_result_sortby').' '.get_settings('poll_ans_result_sortorder'));
	if($answers) {
		foreach($answers as $answer) {
			$polls_answers[] = array('aid' => intval($answer->polla_aid), 'qid' => intval($answer->polla_qid), 'answers' => stripslashes($answer->polla_answers), 'votes' => intval($answer->polla_votes));
		}
	}

	// Get Poll IPs
	$ips = $wpdb->get_results("SELECT pollip_qid, pollip_aid FROM $wpdb->pollsip WHERE pollip_qid IN ($poll_questions_ids) AND pollip_ip = '".get_ipaddress()."'");
	if($ips) {
		foreach($ips as $ip) {
			$polls_ips[] = array('qid' => intval($ip->pollip_qid), 'aid' => intval($ip->pollip_aid));
		}
	}

	// Current Poll
	if($page < 2) {
		$pollsarchive_output .= '<h2>'.__('Current Poll').'</h2>'."\n";
		// Current Poll
		if(intval(get_settings('poll_currentpoll')) == -1) {
			$pollsarchive_output .= get_settings('poll_template_disable');
		} else {
			// User Click on View Results Link
			if(intval($_GET['pollresult']) == $poll_id) {
				$pollsarchive_output .= display_pollresult($poll_id);
			// Check Whether User Has Voted
			} else {
				$poll_active = $wpdb->get_var("SELECT pollq_active FROM $wpdb->pollsq WHERE pollq_id = $poll_id");
				$poll_active = intval($poll_active);
				$check_voted = check_voted($poll_id);
				if($check_voted > 0  || $poll_active == 0) {
					$pollsarchive_output .= display_pollresult($poll_id, $check_voted);	
				} else {
					$pollsarchive_output .= display_pollvote($poll_id);
				}
			}
		}
	}
	// Poll Archives
	$pollsarchive_output .= "<h2>".__('Polls Archive')."</h2>\n";
	$pollsarchive_output .= "<div class=\"wp-polls\">\n";
	foreach($polls_questions as $polls_question) {
		// Most/Least Variables
		$poll_most_answer = '';
		$poll_most_votes = 0;
		$poll_most_percentage = 0;
		$poll_least_answer = '';
		$poll_least_votes = 0;
		$poll_least_percentage = 0;
		// Is The Poll Total Votes 0?
		$poll_totalvotes_zero = true;
		if($polls_question['totalvotes'] > 0) {
			$poll_totalvotes_zero = false;
		}
		// Poll Question Variables
		$template_question = stripslashes(get_settings('poll_template_resultheader'));
		$template_question = str_replace("%POLL_QUESTION%", $polls_question['question'], $template_question);
		$template_question = str_replace("%POLL_ID%", $polls_question['id'], $template_question);
		$template_question = str_replace("%POLL_TOTALVOTES%", $polls_question['totalvotes'], $template_question);
		// Print Out Result Header Template
		$pollsarchive_output .= $template_question;
		foreach($polls_answers as $polls_answer) {
			if($polls_question['id'] == $polls_answer['qid']) {
				// Calculate Percentage And Image Bar Width
				if(!$poll_totalvotes_zero) {
					if($polls_answer['votes'] > 0) {
						$poll_answer_percentage = round((($polls_answer['votes']/$polls_question['totalvotes'])*100));
						$poll_answer_imagewidth = round($poll_answer_percentage*0.9);
					} else {
						$poll_answer_percentage = 0;
						$poll_answer_imagewidth = 1;
					}
				} else {
					$poll_answer_percentage = 0;
					$poll_answer_imagewidth = 1;
				}
				// Let User See What Options They Voted
				if(check_voted_multiple($polls_question['id']) == $polls_answer['aid']) {				
					// Results Body Variables
					$template_answer = stripslashes(get_settings('poll_template_resultbody2'));
					$template_answer = str_replace("%POLL_ANSWER_ID%", $polls_answer['aid'], $template_answer);
					$template_answer = str_replace("%POLL_ANSWER%", $polls_answer['answers'], $template_answer);
					$template_answer = str_replace("%POLL_ANSWER_TEXT%", htmlspecialchars(strip_tags($polls_answer['answers'])), $template_answer);
					$template_answer = str_replace("%POLL_ANSWER_VOTES%", $polls_answer['votes'], $template_answer);
					$template_answer = str_replace("%POLL_ANSWER_PERCENTAGE%", $poll_answer_percentage, $template_answer);
					$template_answer = str_replace("%POLL_ANSWER_IMAGEWIDTH%", $poll_answer_imagewidth, $template_answer);
					// Print Out Results Body Template
					$pollsarchive_output .= $template_answer;
				} else {
					// Results Body Variables
					$template_answer = stripslashes(get_settings('poll_template_resultbody'));
					$template_answer = str_replace("%POLL_ANSWER_ID%", $polls_answer['aid'], $template_answer);
					$template_answer = str_replace("%POLL_ANSWER%", $polls_answer['answers'], $template_answer);
					$template_answer = str_replace("%POLL_ANSWER_TEXT%", htmlspecialchars(strip_tags($polls_answer['answers'])), $template_answer);
					$template_answer = str_replace("%POLL_ANSWER_VOTES%", $polls_answer['votes'], $template_answer);
					$template_answer = str_replace("%POLL_ANSWER_PERCENTAGE%", $poll_answer_percentage, $template_answer);
					$template_answer = str_replace("%POLL_ANSWER_IMAGEWIDTH%", $poll_answer_imagewidth, $template_answer);
					// Print Out Results Body Template
					$pollsarchive_output .= $template_answer;
				}
				// Get Most Voted Data
				if($polls_answer['votes'] > $poll_most_votes) {
					$poll_most_answer = $polls_answer['answers'];
					$poll_most_votes = $polls_answer['votes'];
					$poll_most_percentage = $poll_answer_percentage;
				}
				// Get Least Voted Data
				if($poll_least_votes == 0) {
					$poll_least_votes = $polls_answer['votes'];
				}
				if($polls_answer['votes'] <= $poll_least_votes) {
					$poll_least_answer = $polls_answer['answers'];
					$poll_least_votes = $polls_answer['votes'];
					$poll_least_percentage = $poll_answer_percentage;
				}
				// Delete Away From Array
				unset($polls_answer['answers']);
			}
		}
		// Results Footer Variables
		$template_footer = stripslashes(get_settings('poll_template_resultfooter'));
		$template_footer = str_replace("%POLL_TOTALVOTES%", $polls_question['totalvotes'], $template_footer);
		$template_footer = str_replace("%POLL_MOST_ANSWER%", $poll_most_answer, $template_footer);
		$template_footer = str_replace("%POLL_MOST_VOTES%", number_format($poll_most_votes), $template_footer);
		$template_footer = str_replace("%POLL_MOST_PERCENTAGE%", $poll_most_percentage, $template_footer);
		$template_footer = str_replace("%POLL_LEAST_ANSWER%", $poll_least_answer, $template_footer);
		$template_footer = str_replace("%POLL_LEAST_VOTES%", number_format($poll_least_votes), $template_footer);
		$template_footer = str_replace("%POLL_LEAST_PERCENTAGE%", $poll_least_percentage, $template_footer);
		// Print Out Results Footer Template
		$pollsarchive_output .= $template_footer;
	}
	$pollsarchive_output .= "</div>\n";

	// Polls Archive Paging
	if($total_pages > 1) {
		// Output Previous Page
		$pollsarchive_output .= "<p>\n";
		$pollsarchive_output .= "<span style=\"float: left;\">\n";
		if($page > 1 && ((($page*$polls_perpage)-($polls_perpage-1)) <= $total_polls)) {
			$pollsarchive_output .= '<strong>&laquo;</strong> <a href="'.polls_archive_link($page-1).'" title="&laquo; '.__('Previous Page').'">'.__('Previous Page').'</a>';
		} else {
			$pollsarchive_output .= '&nbsp;';
		}		
		$pollsarchive_output .= "</span>\n";
		// Output Next Page
		$pollsarchive_output .= "<span style=\"float: right;\">\n";
		if($page >= 1 && ((($page*$polls_perpage)+1) <=  $total_polls)) {
			$pollsarchive_output .= '<a href="'.polls_archive_link($page+1).'" title="'.__('Next Page').' &raquo;">'.__('Next Page').'</a> <strong>&raquo;</strong>';
		} else {
			$pollsarchive_output .= '&nbsp;';
		}
		$pollsarchive_output .= "</span>\n";
		// Output Pages
		$pollsarchive_output .= "</p>\n";
		$pollsarchive_output .= "<br style=\"clear: both;\" />\n";
		$pollsarchive_output .= "<p style=\"text-align: center;\">\n";
		$pollsarchive_output .= __('Pages')." ($total_pages) : ";
		if ($page >= 4) {
			$pollsarchive_output .= '<strong><a href="'.polls_archive_link(1).'" title="'.__('Go to First Page').'">&laquo; '.__('First').'</a></strong> ... ';
		}
		if($page > 1) {
			$pollsarchive_output .= ' <strong><a href="'.polls_archive_link($page-1).'" title="&laquo; '.__('Go to Page').' '.($page-1).'">&laquo;</a></strong> ';
		}
		for($i = $page - 2 ; $i  <= $page +2; $i++) {
			if ($i >= 1 && $i <= $total_pages) {
				if($i == $page) {
					$pollsarchive_output .= "<strong>[$i]</strong> ";
				} else {
					$pollsarchive_output .= '<a href="'.polls_archive_link($i).'" title="'.__('Page').' '.$i.'">'.$i.'</a> ';
				}
			}
		}
		if($page < $total_pages) {
			$pollsarchive_output .= ' <strong><a href="'.polls_archive_link($page+1).'" title="'.__('Go to Page').' '.($page+1).' &raquo;">&raquo;</a></strong> ';
		}
		if (($page+2) < $total_pages) {
			$pollsarchive_output .= ' ... <strong><a href="'.polls_archive_link($total_pages).'" title="'.__('Go to Last Page').'">'.__('Last').' &raquo;</a></strong>';
		}
		$pollsarchive_output .= "</p>\n";
	}

	// Output Polls Archive Page
	return $pollsarchive_output;
}


### Function: Create Poll Tables
add_action('activate_polls/polls.php', 'create_poll_table');
function create_poll_table() {
	global $wpdb;
	include_once(ABSPATH.'/wp-admin/upgrade-functions.php');
	// Create Poll Tables (3 Tables)
	$create_table = array();
	$create_table['pollsq'] = "CREATE TABLE $wpdb->pollsq (".
									"pollq_id int(10) NOT NULL auto_increment,".
									"pollq_question varchar(200) NOT NULL default '',".
									"pollq_timestamp varchar(20) NOT NULL default '',".
									"pollq_totalvotes int(10) NOT NULL default '0',".
									"pollq_active tinyint(1) NOT NULL default '1',".
									"PRIMARY KEY (pollq_id))";
	$create_table['pollsa'] = "CREATE TABLE $wpdb->pollsa (".
									"polla_aid int(10) NOT NULL auto_increment,".
									"polla_qid int(10) NOT NULL default '0',".
									"polla_answers varchar(200) NOT NULL default '',".
									"polla_votes int(10) NOT NULL default '0',".
									"PRIMARY KEY (polla_aid))";
	$create_table['pollsip'] = "CREATE TABLE $wpdb->pollsip (".
									"pollip_id int(10) NOT NULL auto_increment,".
									"pollip_qid varchar(10) NOT NULL default '',".
									"pollip_aid varchar(10) NOT NULL default '',".
									"pollip_ip varchar(100) NOT NULL default '',".
									"pollip_host VARCHAR(200) NOT NULL default '',".
									"pollip_timestamp varchar(20) NOT NULL default '0000-00-00 00:00:00',".
									"pollip_user tinytext NOT NULL,".
									"pollip_userid int(10) NOT NULL default '0',".
									"PRIMARY KEY (pollip_id))";
	maybe_create_table($wpdb->pollsq, $create_table['pollsq']);
	maybe_create_table($wpdb->pollsa, $create_table['pollsa']);
	maybe_create_table($wpdb->pollsip, $create_table['pollsip']);
	// Check Whether It is Install Or Upgrade
	$first_poll = $wpdb->get_var("SELECT pollq_id FROM $wpdb->pollsq LIMIT 1");
	// If Install, Insert 1st Poll Question With 5 Poll Answers
	if(empty($first_poll)) {
		// Insert Poll Question (1 Record)
		$insert_pollq = $wpdb->query("INSERT INTO $wpdb->pollsq VALUES (1, 'How Is My Site?', '".current_time('timestamp')."', 0, 1);");
		if($insert_pollq) {
			// Insert Poll Answers  (5 Records)
			$wpdb->query("INSERT INTO $wpdb->pollsa VALUES (1, 1, 'Good', 0);");
			$wpdb->query("INSERT INTO $wpdb->pollsa VALUES (2, 1, 'Excellent', 0);");
			$wpdb->query("INSERT INTO $wpdb->pollsa VALUES (3, 1, 'Bad', 0);");
			$wpdb->query("INSERT INTO $wpdb->pollsa VALUES (4, 1, 'Can Be Improved', 0);");
			$wpdb->query("INSERT INTO $wpdb->pollsa VALUES (5, 1, 'No Comments', 0);");
		}
	}
	// Add In Options (16 Records)
	add_option('poll_template_voteheader', '<p style="text-align: center;"><strong>%POLL_QUESTION%</strong></p>'.
	'<div id="polls-%POLL_ID%-ans" class="wp-polls-ans">'.
	'<ul class="wp-polls-ul">', 'Template For Poll\'s Question');
	add_option('poll_template_votebody',  '<li><label for="poll-answer-%POLL_ANSWER_ID%"><input type="radio" id="poll-answer-%POLL_ANSWER_ID%" name="poll_%POLL_ID%" value="%POLL_ANSWER_ID%" /> %POLL_ANSWER%</label></li>', 'Template For Poll\'s Answers');
	add_option('poll_template_votefooter', '</ul>'.
	'<p style="text-align: center;"><input type="button" name="vote" value="   Vote   " class="Buttons" onclick="poll_vote(%POLL_ID%);" onkeypress="poll_result(%POLL_ID%);" /></p>'.
	'<p style="text-align: center;"><a href="#ViewPollResults" onclick="poll_result(%POLL_ID%); return false;" onkeypress="poll_result(%POLL_ID%); return false;" title="View Results Of This Poll">View Results</a></p>'.
	'</div>', 'Template For Poll\'s Voting Footer');
	add_option('poll_template_resultheader', '<p style="text-align: center;"><strong>%POLL_QUESTION%</strong></p>'.
	'<div id="polls-%POLL_ID%-ans" class="wp-polls-ans">'.
	'<ul class="wp-polls-ul">', 'Template For Poll Header');
	add_option('poll_template_resultbody', '<li>%POLL_ANSWER% <small>(%POLL_ANSWER_PERCENTAGE%%)</small><div class="pollbar-image" style="width: %POLL_ANSWER_IMAGEWIDTH%%;" title="%POLL_ANSWER_TEXT% (%POLL_ANSWER_PERCENTAGE%% | %POLL_ANSWER_VOTES% Votes)"></div></li>', 'Template For Poll Results');
	add_option('poll_template_resultbody2', '<li><strong><i>%POLL_ANSWER% <small>(%POLL_ANSWER_PERCENTAGE%%)</small></i></strong><div class="pollbar-image" style="width: %POLL_ANSWER_IMAGEWIDTH%%;" title="You Have Voted For This Choice - %POLL_ANSWER_TEXT% (%POLL_ANSWER_PERCENTAGE%% | %POLL_ANSWER_VOTES% Votes)"></div></li>', 'Template For Poll Results (User Voted)');
	add_option('poll_template_resultfooter', '</ul>'.
	'<p style="text-align: center;">Total Votes: <strong>%POLL_TOTALVOTES%</strong></p>'.
	'</div>', 'Template For Poll Result Footer');
	add_option('poll_template_resultfooter2', '</ul>'.
	'<p style="text-align: center;">Total Votes: <strong>%POLL_TOTALVOTES%</strong></p>'.
	'<p style="text-align: center;"><a href="#VotePoll" onclick="poll_booth(%POLL_ID%); return false;" onkeypress="poll_booth(%POLL_ID%); return false;" title="Vote For This Poll">Vote</a></p>'.
	'</div>', 'Template For Poll Result Footer');
	add_option('poll_template_disable', 'Sorry, there are no polls available at the moment.', 'Template For Poll When It Is Disabled');
	add_option('poll_template_error', 'An error has occurred when processing your poll.', 'Template For Poll When An Error Has Occured');
	add_option('poll_currentpoll', 0, 'Current Displayed Poll');
	add_option('poll_latestpoll', 1, 'The Lastest Poll');
	add_option('poll_archive_perpage', 5, 'Number Of Polls To Display Per Page On The Poll\'s Archive', 'no');
	add_option('poll_ans_sortby', 'polla_aid', 'Sorting Of Poll\'s Answers');
	add_option('poll_ans_sortorder', 'asc', 'Sort Order Of Poll\'s Answers');
	add_option('poll_ans_result_sortby', 'polla_votes', 'Sorting Of Poll\'s Answers Result');
	add_option('poll_ans_result_sortorder', 'desc', 'Sorting Order Of Poll\'s Answers Result');
	// Database Upgrade For WP-Polls 2.1
	add_option('poll_logging_method', '3', 'Logging Method Of User Poll\'s Answer');
	add_option('poll_allowtovote', '2', 'Who Is Allowed To Vote');
	maybe_add_column($wpdb->pollsq, 'pollq_active', "ALTER TABLE $wpdb->pollsq ADD pollq_active TINYINT( 1 ) NOT NULL DEFAULT '1';");
	// Database Upgrade For WP-Polls 2.12
	maybe_add_column($wpdb->pollsip, 'pollip_userid', "ALTER TABLE $wpdb->pollsip ADD pollip_userid INT( 10 ) NOT NULL DEFAULT '0';");
	add_option('poll_archive_url', get_settings('siteurl').'/pollsarchive/', 'Polls Archive URL');
	add_option('poll_archive_show', 1, 'Show Polls Archive?');
	// Set 'manage_polls' Capabilities To Administrator	
	$role = get_role('administrator');
	if(!$role->has_cap('manage_polls')) {
		$role->add_cap('manage_polls');
	}
}
?>