diff --git a/phpBB/admin/admin_db_utilities.php b/phpBB/admin/admin_db_utilities.php
index f512b6622a..656233c259 100644
--- a/phpBB/admin/admin_db_utilities.php
+++ b/phpBB/admin/admin_db_utilities.php
@@ -782,7 +782,7 @@ if( isset($HTTP_GET_VARS['perform']) || isset($HTTP_POST_VARS['perform']) )
 				break;
 			}
 
-			$tables = array('auth_access', 'banlist', 'categories', 'config', 'disallow', 'forums', 'forum_prune', 'groups', 'posts', 'posts_text', 'privmsgs', 'privmsgs_text', 'ranks', 'session', 'smilies', 'themes', 'themes_name', 'topics', 'user_group', 'users', 'words');
+			$tables = array('auth_access', 'banlist', 'categories', 'config', 'disallow', 'forums', 'forum_prune', 'groups', 'posts', 'posts_text', 'privmsgs', 'privmsgs_text', 'ranks', 'session', 'smilies', 'themes', 'themes_name', 'topics', 'user_group', 'users', 'vote_desc', 'vote_results', 'vote_voters', 'words');
 
 			$additional_tables = (isset($HTTP_POST_VARS['additional_tables'])) ? $HTTP_POST_VARS['additional_tables'] : ( (isset($HTTP_GET_VARS['additional_tables'])) ? $HTTP_GET_VARS['additional_tables'] : "" );
 
@@ -846,7 +846,7 @@ if( isset($HTTP_GET_VARS['perform']) || isset($HTTP_POST_VARS['perform']) )
 				);
 
 				$template->assign_vars(array(
-					"META" => "<meta http-equiv=\"refresh\" content=\"0;url=admin_db_utilities.$phpEx?perform=backup&additional_tables=" . quotemeta($additional_tables) . "&backup_type=$backup_type&drop=1&backupstart=1&gzipcompress=$gzipcompress&startdownload=1\">",
+					"META" => "<meta http-equiv=\"refresh\" content=\"0;url=admin_db_utilities.$phpEx?perform=backup&amp;additional_tables=" . quotemeta($additional_tables) . "&amp;backup_type=$backup_type&amp;drop=1&amp;backupstart=1&amp;gzipcompress=$gzipcompress&amp;startdownload=1\">",
 
 					"MESSAGE_TITLE" => $lang['Database_Utilities'] . " : " . $lang['Backup'],
 					"MESSAGE_TEXT" => $lang['Backup_download'])
@@ -863,7 +863,7 @@ if( isset($HTTP_GET_VARS['perform']) || isset($HTTP_POST_VARS['perform']) )
 			//
 			// Build the sql script file...
 			//
-			$backup_sql = "#\n";
+			$backup_sql  = "#\n";
 			$backup_sql .= "# phpBB Backup Script\n";
 			$backup_sql .= "# Dump of tables for $dbname\n";
 			$backup_sql .= "#\n# DATE : " .  gmdate("d-m-Y H:i:s", time()) . " GMT\n";
diff --git a/phpBB/admin/admin_forumauth.php b/phpBB/admin/admin_forumauth.php
index d976074e7e..350f0031e4 100644
--- a/phpBB/admin/admin_forumauth.php
+++ b/phpBB/admin/admin_forumauth.php
@@ -37,18 +37,18 @@ require('pagestart.inc');
 // Start program - define vars
 //
 $simple_auth_ary = array(
-	0  => array(0, 0, 0, 0, 1, 1, 1, 3),
-	1  => array(0, 0, 1, 1, 1, 1, 1, 3),
-	2  => array(1, 1, 1, 1, 1, 1, 1, 3),
-	3  => array(0, 2, 2, 2, 2, 2, 2, 3),
-	4  => array(2, 2, 2, 2, 2, 2, 2, 3),
-	5  => array(0, 3, 3, 3, 3, 3, 3, 3),
-	6  => array(3, 3, 3, 3, 3, 3, 3, 3),
+	0  => array(0, 0, 0, 0, 1, 1, 1, 3, 1, 1),
+	1  => array(0, 0, 1, 1, 1, 1, 1, 3, 1, 1),
+	2  => array(1, 1, 1, 1, 1, 1, 1, 3, 1, 1),
+	3  => array(0, 2, 2, 2, 2, 2, 2, 3, 2, 2),
+	4  => array(2, 2, 2, 2, 2, 2, 2, 3, 2, 2),
+	5  => array(0, 3, 3, 3, 3, 3, 3, 3, 3, 3),
+	6  => array(3, 3, 3, 3, 3, 3, 3, 3, 3, 3),
 );
 
 $simple_auth_types = array($lang['Public'], $lang['Registered'], $lang['Registered'] . " [" . $lang['Hidden'] . "]", $lang['Private'], $lang['Private'] . " [" . $lang['Hidden'] . "]", $lang['Moderators'], $lang['Moderators'] . " [" . $lang['Hidden'] . "]");
 
-$forum_auth_fields = array("auth_view", "auth_read", "auth_post", "auth_reply", "auth_edit", "auth_delete", "auth_sticky", "auth_announce");
+$forum_auth_fields = array("auth_view", "auth_read", "auth_post", "auth_reply", "auth_edit", "auth_delete", "auth_sticky", "auth_announce", "auth_vote", "auth_pollcreate");
 
 $field_names = array(
 	"auth_view" => $lang['View'],
@@ -58,9 +58,11 @@ $field_names = array(
 	"auth_edit" => $lang['Edit'],
 	"auth_delete" => $lang['Delete'],
 	"auth_sticky" => $lang['Sticky'],
-	"auth_announce" => $lang['Announce']);
+	"auth_announce" => $lang['Announce'], 
+	"auth_vote" => $lang['Vote'], 
+	"auth_pollcreate" => $lang['Pollcreate']);
 
-$forum_auth_levels = array("ALL", "REG", "ACL", "MOD", "ADMIN");
+$forum_auth_levels = array("ALL", "REG", "PRIVATE", "MOD", "ADMIN");
 $forum_auth_const = array(AUTH_ALL, AUTH_REG, AUTH_ACL, AUTH_MOD, AUTH_ADMIN);
 
 if(isset($HTTP_GET_VARS[POST_FORUM_URL]) || isset($HTTP_POST_VARS[POST_FORUM_URL]))
diff --git a/phpBB/admin/admin_groupauth.php b/phpBB/admin/admin_groupauth.php
index e3fe8d3a4c..4a36bbf932 100644
--- a/phpBB/admin/admin_groupauth.php
+++ b/phpBB/admin/admin_groupauth.php
@@ -28,15 +28,35 @@ if($setmodules == 1)
 	return;
 }
 
+$phpbb_root_path = "./../";
+include($phpbb_root_path . 'extension.inc');
+include($phpbb_root_path . 'common.'.$phpEx);
+
 //
-// Include required files, get $phpEx and check permissions
+// Start session management
 //
-require('pagestart.inc');
+$userdata = session_pagestart($user_ip, PAGE_INDEX, $session_length);
+init_userprefs($userdata);
+//
+// End session management
+//
+
+//
+// Is user logged in? If yes are they an admin?
+//
+if( !$userdata['session_logged_in'] )
+{
+	header("Location: ../login.$phpEx?forward_page=admin/");
+}
+else if( $userdata['user_level'] != ADMIN )
+{
+	message_die(GENERAL_MESSAGE, $lang['Not_admin']);
+}
 
 //
 // Start program - define vars
 //
-$forum_auth_fields = array("auth_view", "auth_read", "auth_post", "auth_reply", "auth_edit", "auth_delete", "auth_sticky", "auth_announce");
+$forum_auth_fields = array("auth_view", "auth_read", "auth_post", "auth_reply", "auth_edit", "auth_delete", "auth_sticky", "auth_announce", "auth_vote", "auth_pollcreate");
 
 $auth_field_match = array(
 	"auth_view" => AUTH_VIEW,
@@ -46,7 +66,9 @@ $auth_field_match = array(
 	"auth_edit" => AUTH_EDIT,
 	"auth_delete" => AUTH_DELETE,
 	"auth_sticky" => AUTH_STICKY,
-	"auth_announce" => AUTH_ANNOUNCE);
+	"auth_announce" => AUTH_ANNOUNCE, 
+	"auth_vote" => AUTH_VOTE, 
+	"auth_pollcreate" => AUTH_POLLCREATE);
 
 $field_names = array(
 	"auth_view" => $lang['View'],
@@ -56,7 +78,9 @@ $field_names = array(
 	"auth_edit" => $lang['Edit'],
 	"auth_delete" => $lang['Delete'],
 	"auth_sticky" => $lang['Sticky'],
-	"auth_announce" => $lang['Announce']);
+	"auth_announce" => $lang['Announce'], 
+	"auth_vote" => $lang['Vote'], 
+	"auth_pollcreate" => $lang['Pollcreate']);
 
 
 // ---------------
@@ -458,7 +482,7 @@ if(isset($HTTP_POST_VARS['submit']) && !empty($HTTP_POST_VARS[POST_GROUPS_URL]))
 		{
 			if(!empty($valid_auth_mod_sql[$forum_id]))
 			{
-				$warning_list .= "<b><a href=\"admin_userauth.$phpEx?" . POST_USERS_URL . "=" . $user_ary[$i] . "\">" . $warning_mod_username[$forum_id][$i] . "</a></b> " . $lang['has_moderator_status'] .  " <b>" . $warning_mod_frmname[$forum_id][$i] . "</b><br />";
+				$warning_list .= "<b><a href=\"" . append_sid("admin_userauth.$phpEx?" . POST_USERS_URL . "=" . $user_ary[$i]) . "\">" . $warning_mod_username[$forum_id][$i] . "</a></b> " . $lang['has_moderator_status'] .  " <b>" . $warning_mod_frmname[$forum_id][$i] . "</b><br />";
 			}
 		}
 	}
@@ -469,14 +493,16 @@ if(isset($HTTP_POST_VARS['submit']) && !empty($HTTP_POST_VARS[POST_GROUPS_URL]))
 		{
 			if(!empty($valid_auth_prv_sql[$forum_id]))
 			{
-				$warning_list .= "<b><a href=\"admin_userauth.$phpEx?" . POST_USERS_URL . "=" . $user_ary[$i] . "\">" . $warning_prv_username[$forum_id][$i] . "</a></b> " . $lang['has_access_status'] .  " <b>" . $warning_prv_frmname[$forum_id][$i] . "</b><br />";
+				$warning_list .= "<b><a href=\"" . append_sid("admin_userauth.$phpEx?" . POST_USERS_URL . "=" . $user_ary[$i]) . "\">" . $warning_prv_username[$forum_id][$i] . "</a></b> " . $lang['has_access_status'] .  " <b>" . $warning_prv_frmname[$forum_id][$i] . "</b><br />";
 			}
 		}
 	}
 
 	if($warning_list != "")
 	{
-		$warning_list = "<br />" . $lang['Conflict_message_groupauth'] . "<br/><br/>" . $warning_list . "<br />" . $lang['Click'] ." <a href=\"admin_groupauth.$phpEx?" . POST_GROUPS_URL . "=$group_id\">" . $lang['HERE'] . "</a> " . $lang['return_group_auth_admin'] . "<br />";
+		$warning_list = "<br />" . $lang['Conflict_message_groupauth'] . "<br/><br/>" . $warning_list . "<br />" . $lang['Click'] ." <a href=\"" . append_sid("admin_groupauth.$phpEx?" . POST_GROUPS_URL . "=$group_id") . "\">" . $lang['HERE'] . "</a> " . $lang['return_group_auth_admin'] . "<br />";
+
+		include('page_header_admin.'.$phpEx);
 
 		$template->set_filenames(array(
 			"body" => "admin/admin_message_body.tpl")
@@ -489,7 +515,7 @@ if(isset($HTTP_POST_VARS['submit']) && !empty($HTTP_POST_VARS[POST_GROUPS_URL]))
 	}
 	else
 	{
-		header("Location: admin_groupauth.$phpEx?" . POST_GROUPS_URL . "=$group_id");
+		header("Location: " . append_sid("admin_groupauth.$phpEx?" . POST_GROUPS_URL . "=$group_id"));
 	}
 
 }
@@ -514,6 +540,8 @@ else if(empty($HTTP_GET_VARS[POST_GROUPS_URL]))
 	}
 	$select_list .= "</select>";
 
+	include('page_header_admin.'.$phpEx);
+
 	$template->set_filenames(array(
 		"body" => "admin/auth_select_body.tpl")
 	);
@@ -544,6 +572,8 @@ else
 		$adv = FALSE;
 	}
 
+	include('page_header_admin.'.$phpEx);
+
 	$template->set_filenames(array(
 		"body" => "admin/auth_ug_body.tpl")
 	);
@@ -812,7 +842,7 @@ else
 		$t_usergroup_list = "";
 		for($i = 0; $i < count($username); $i++)
 		{
-			$t_usergroup_list .= "<a href=\"admin_userauth.$phpEx?" . POST_USERS_URL . "=" . $user_id[$i] . "\">" . $username[$i] . "</a>";
+			$t_usergroup_list .= "<a href=\"" . append_sid("admin_userauth.$phpEx?" . POST_USERS_URL . "=" . $user_id[$i]) . "\">" . $username[$i] . "</a>";
 			if($i < count($username) - 1)
 			{
 				$t_usergroup_list .= ", ";
@@ -850,7 +880,7 @@ else
 	$switch_mode = "admin_groupauth.$phpEx?" . POST_GROUPS_URL . "=" . $group_id . "&adv=";
 	$switch_mode .= ( !$adv ) ? "1" : "0";
 	$switch_mode_text = ( !$adv ) ? $lang['Advanced_mode'] : $lang['Simple_mode'];
-	$u_switch_mode = '<a href="' . $switch_mode . '">' . $switch_mode_text . '</a>';
+	$u_switch_mode = '<a href="' . append_sid($switch_mode) . '">' . $switch_mode_text . '</a>';
 
 	$template->assign_vars(array(
 		"USERNAME" => $t_groupname,
diff --git a/phpBB/admin/admin_userauth.php b/phpBB/admin/admin_userauth.php
index caae189210..f34676ec6a 100644
--- a/phpBB/admin/admin_userauth.php
+++ b/phpBB/admin/admin_userauth.php
@@ -40,6 +40,10 @@ init_userprefs($userdata);
 //
 // End session management
 //
+
+//
+// Is user logged in? If yes are they an admin?
+//
 if( !$userdata['session_logged_in'] )
 {
 	header("Location: ../login.$phpEx?forward_page=admin/");
@@ -52,7 +56,7 @@ else if( $userdata['user_level'] != ADMIN )
 //
 // Start program - define vars
 //
-$forum_auth_fields = array("auth_view", "auth_read", "auth_post", "auth_reply", "auth_edit", "auth_delete", "auth_sticky", "auth_announce");
+$forum_auth_fields = array("auth_view", "auth_read", "auth_post", "auth_reply", "auth_edit", "auth_delete", "auth_sticky", "auth_announce", "auth_vote", "auth_pollcreate");
 
 $auth_field_match = array(
 	"auth_view" => AUTH_VIEW,
@@ -62,7 +66,9 @@ $auth_field_match = array(
 	"auth_edit" => AUTH_EDIT,
 	"auth_delete" => AUTH_DELETE,
 	"auth_sticky" => AUTH_STICKY,
-	"auth_announce" => AUTH_ANNOUNCE);
+	"auth_announce" => AUTH_ANNOUNCE, 
+	"auth_vote" => AUTH_VOTE, 
+	"auth_pollcreate" => AUTH_POLLCREATE);
 
 $field_names = array(
 	"auth_view" => $lang['View'],
@@ -72,7 +78,9 @@ $field_names = array(
 	"auth_edit" => $lang['Edit'],
 	"auth_delete" => $lang['Delete'],
 	"auth_sticky" => $lang['Sticky'],
-	"auth_announce" => $lang['Announce']);
+	"auth_announce" => $lang['Announce'], 
+	"auth_vote" => $lang['Vote'], 
+	"auth_pollcreate" => $lang['Pollcreate']);
 
 // ---------------
 // Start Functions
@@ -177,7 +185,7 @@ if(isset($HTTP_POST_VARS['submit']) && !empty($HTTP_POST_VARS[POST_USERS_URL]))
 			}
 		}
 
-		header("Location: admin_userauth.$phpEx?" . POST_USERS_URL . "=$user_id");
+		header("Location: " . append_sid("admin_userauth.$phpEx?" . POST_USERS_URL . "=$user_id"));
 
 	}
 	else if( $HTTP_POST_VARS['userlevel'] == "admin" && $ug_info['user_level'] != ADMIN )
@@ -214,7 +222,7 @@ if(isset($HTTP_POST_VARS['submit']) && !empty($HTTP_POST_VARS[POST_USERS_URL]))
 			// Error ...
 		}
 
-		header("Location: admin_userauth.$phpEx?" . POST_USERS_URL . "=$user_id");
+		header("Location: " . append_sid("admin_userauth.$phpEx?" . POST_USERS_URL . "=$user_id"));
 
 	}
 	else
@@ -223,7 +231,7 @@ if(isset($HTTP_POST_VARS['submit']) && !empty($HTTP_POST_VARS[POST_USERS_URL]))
 		// Pull all the auth/group
 		// for this user
 		//
-		$sql = "SELECT aa.forum_id, aa.auth_view, aa.auth_read, aa.auth_post, aa.auth_reply, aa.auth_edit, aa.auth_delete, aa.auth_sticky, aa.auth_announce, aa.auth_mod, g.group_single_user, g.group_id, g.group_name
+		$sql = "SELECT aa.forum_id, aa.auth_view, aa.auth_read, aa.auth_post, aa.auth_reply, aa.auth_edit, aa.auth_delete, aa.auth_sticky, aa.auth_announce, aa.auth_vote, aa.auth_pollcreate, aa.auth_mod, g.group_single_user, g.group_id, g.group_name
 		FROM " . AUTH_ACCESS_TABLE . " aa, " . USER_GROUP_TABLE . " ug, " . GROUPS_TABLE. " g
 			WHERE ug.user_id = $user_id
 				AND g.group_id = ug.group_id
@@ -235,7 +243,7 @@ if(isset($HTTP_POST_VARS['submit']) && !empty($HTTP_POST_VARS[POST_USERS_URL]))
 			$u_access = $db->sql_fetchrowset($au_result);
 		}
 
-		$sql = "SELECT f.forum_id, f.forum_name, f.auth_view, f.auth_read, f.auth_post, f.auth_reply, f.auth_edit, f.auth_delete, f.auth_sticky, f.auth_announce
+		$sql = "SELECT f.forum_id, f.forum_name, f.auth_view, f.auth_read, f.auth_post, f.auth_reply, f.auth_edit, f.auth_delete, f.auth_sticky, f.auth_announce, f.auth_vote, f.auth_pollcreate 
 			FROM " . FORUMS_TABLE . " f, " . CATEGORIES_TABLE . " c
 			WHERE c.cat_id = f.cat_id
 			ORDER BY c.cat_order ASC, f.forum_order ASC";
@@ -352,7 +360,7 @@ if(isset($HTTP_POST_VARS['submit']) && !empty($HTTP_POST_VARS[POST_USERS_URL]))
 								if($new_mod_status)
 								{
 									$valid_auth_mod_sql[$this_forum_id] = "UPDATE " . AUTH_ACCESS_TABLE . "
-										SET auth_view = 0, auth_read = 0, auth_post = 0, auth_reply = 0, auth_edit = 0, auth_delete = 0, auth_announce = 0, auth_sticky = 0, auth_mod = $new_mod_status
+										SET auth_view = 0, auth_read = 0, auth_post = 0, auth_reply = 0, auth_edit = 0, auth_delete = 0, auth_sticky = 0, auth_announce = 0, auth_vote = 0, auth_pollcreate = 0, auth_mod = $new_mod_status
 										WHERE forum_id = $this_forum_id
 											AND group_id = " . $ug_info['group_id'];
 								}
@@ -538,7 +546,7 @@ if(isset($HTTP_POST_VARS['submit']) && !empty($HTTP_POST_VARS[POST_USERS_URL]))
 			{
 				if(!empty($valid_auth_mod_sql[$forum_id]))
 				{
-					$warning_list .= "<b><a href=\"admin_groupauth.$phpEx?" . POST_GROUPS_URL . "=" . $group_ary[$i] . "\">" . $warning_mod_grpname[$forum_id][$i] . "</a></b> " . $lang['grants_moderator_status'] . " <b>" . $warning_mod_frmname[$forum_id][$i] . "</b> " . $lang['for_this_user'] . "<br />";
+					$warning_list .= "<b><a href=\"" . append_sid("admin_groupauth.$phpEx?" . POST_GROUPS_URL . "=" . $group_ary[$i]) . "\">" . $warning_mod_grpname[$forum_id][$i] . "</a></b> " . $lang['grants_moderator_status'] . " <b>" . $warning_mod_frmname[$forum_id][$i] . "</b> " . $lang['for_this_user'] . "<br />";
 				}
 			}
 		}
@@ -549,14 +557,14 @@ if(isset($HTTP_POST_VARS['submit']) && !empty($HTTP_POST_VARS[POST_USERS_URL]))
 			{
 				if(!empty($valid_auth_prv_sql[$forum_id]))
 				{
-					$warning_list .= "<b><a href=\"admin_groupauth.$phpEx?" . POST_GROUPS_URL . "=" . $group_ary[$i] . "\">" . $warning_prv_grpname[$forum_id][$i] . "</a></b> " . $lang['grants_access_status'] . " <b>" . $warning_prv_frmname[$forum_id][$i] . "</b> " . $lang['for_this_user'] . "<br />";
+					$warning_list .= "<b><a href=\"" . append_sid("admin_groupauth.$phpEx?" . POST_GROUPS_URL . "=" . $group_ary[$i]) . "\">" . $warning_prv_grpname[$forum_id][$i] . "</a></b> " . $lang['grants_access_status'] . " <b>" . $warning_prv_frmname[$forum_id][$i] . "</b> " . $lang['for_this_user'] . "<br />";
 				}
 			}
 		}
 
 		if($warning_list != "")
 		{
-			$warning_list = "<br />" . $lang['Conflict_message_userauth'] . "<br/><br/>" . $warning_list . "<br />" . $lang['Click'] . " <a href=\"admin_userauth.$phpEx?" . POST_USERS_URL . "=$user_id\">" . $lang['HERE'] . "</a> ". $lang['return_user_auth_admin'] . "<br />";
+			$warning_list = "<br />" . $lang['Conflict_message_userauth'] . "<br/><br/>" . $warning_list . "<br />" . $lang['Click'] . " <a href=\"" . append_sid("admin_userauth.$phpEx?" . POST_USERS_URL . "=$user_id") . "\">" . $lang['HERE'] . "</a> ". $lang['return_user_auth_admin'] . "<br />";
 
 			include('page_header_admin.'.$phpEx);
 
@@ -628,7 +636,6 @@ else
 		$adv = FALSE;
 	}
 
-	$template_header = "admin/page_header.tpl";
 	include('page_header_admin.'.$phpEx);
 
 	$template->set_filenames(array(
@@ -905,7 +912,7 @@ else
 		$t_usergroup_list = "";
 		for($i = 0; $i < count($userinf); $i++)
 		{
-			$t_usergroup_list .= "<a href=\"admin_groupauth.$phpEx?" . POST_GROUPS_URL . "=" . $group_id[$i] . "\">" . $group_name[$i] . "</a>";
+			$t_usergroup_list .= "<a href=\"" . append_sid("admin_groupauth.$phpEx?" . POST_GROUPS_URL . "=" . $group_id[$i]) . "\">" . $group_name[$i] . "</a>";
 			if($i < count($group_name) - 1)
 			{
 				$t_usergroup_list .= ", ";
@@ -941,7 +948,7 @@ else
 		}
 	}
 
-	$switch_mode = "admin_userauth.$phpEx?" . POST_USERS_URL . "=" . $user_id . "&adv=";
+	$switch_mode = append_sid("admin_userauth.$phpEx?" . POST_USERS_URL . "=" . $user_id . "&adv=");
 	$switch_mode .= ( empty($adv) ) ? "1" : "0";
 	$switch_mode_text = ( empty($adv) ) ? $lang['Advanced_mode'] : $lang['Simple_mode'];
 	$u_switch_mode = '<a href="' . $switch_mode . '">' . $switch_mode_text . '</a>';
diff --git a/phpBB/admin/pagestart.inc b/phpBB/admin/pagestart.inc
index dd56651f8f..4cf241444b 100644
--- a/phpBB/admin/pagestart.inc
+++ b/phpBB/admin/pagestart.inc
@@ -34,7 +34,7 @@ init_userprefs($userdata);
 //
 if( !$userdata['session_logged_in'] )
 {
-	header("Location: ../login.$phpEx?forward_page=admin/");
+	header("Location: " . append_sid("../login.$phpEx?forward_page=admin/"));
 }
 else if( $userdata['user_level'] != ADMIN )
 {
diff --git a/phpBB/common.php b/phpBB/common.php
index 35691cfec8..aa250de253 100644
--- a/phpBB/common.php
+++ b/phpBB/common.php
@@ -167,6 +167,7 @@ else
 	$board_config['posts_per_page'] = $config['posts_per_page'];
 	$board_config['topics_per_page'] = $config['topics_per_page'];
 	$board_config['hot_threshold'] = $config['hot_threshold'];
+	$board_config['max_poll_options'] = $config['max_poll_options'];
 	$board_config['default_theme'] = $config['default_theme'];
 	$board_config['default_dateformat'] = stripslashes($config['default_dateformat']);
 	$board_config['default_template'] = stripslashes($config['sys_template']);
diff --git a/phpBB/db/mysql_basic.sql b/phpBB/db/mysql_basic.sql
index 4fe9540df2..055fedc285 100644
--- a/phpBB/db/mysql_basic.sql
+++ b/phpBB/db/mysql_basic.sql
@@ -4,13 +4,13 @@
 # $Id$
 
 # -- Config
-INSERT INTO phpbb_config (config_id, board_disable, sitename, cookie_name, cookie_path, cookie_domain, cookie_secure, session_length, allow_html, allow_bbcode, allow_smilies, allow_sig, allow_namechange, posts_per_page, hot_threshold, topics_per_page, flood_interval, allow_theme_create, override_themes, email_sig, email_from, default_theme, default_lang, default_dateformat, system_timezone, sys_template, avatar_filesize, avatar_path, allow_avatar_upload, avatar_max_width, avatar_max_height, allow_avatar_local, allow_avatar_remote) VALUES ( '1', '0', 'phpbb.com', 'phpbb2mysql', '/', '', '0', 600, '0', '1', '1', '1', '0', '10', '10', '25', '10', '0', '0', '', '', '2', 'english', 'd M Y H:i', '0', 'PSO', '6144', 'images/avatars', '0', '70', '70', '0', '0');
+INSERT INTO phpbb_config (config_id, board_disable, sitename, cookie_name, cookie_path, cookie_domain, cookie_secure, session_length, allow_html, allow_html_tags, allow_bbcode, allow_smilies, allow_sig, allow_namechange, allow_theme_create, allow_avatar_local, allow_avatar_remote, allow_avatar_upload, override_themes, posts_per_page, topics_per_page, hot_threshold, max_poll_options, email_sig, email_from, require_activation, flood_interval, avatar_filesize, avatar_max_width, avatar_max_height, avatar_path, smilies_path, default_theme, default_lang, default_dateformat, system_timezone, sys_template, prune_enable, gzip_compress, board_startdate, smtp_delivery, smtp_host) VALUES (1,0,'yourdomain.com','phpbb2mysql','/','','',900,'','b,i,u,pre',1,1,1,'','','',1,1,'',15,50,25,10,'Thanks, The Management','youraddress@yourdomain.com','',15,6144,80,80,'images/avatars','images/smiles',2,'english','D M d, Y g:i a',-8,'PSO',1,1,994190324,'','');
 
 # -- Categories
 INSERT INTO phpbb_categories (cat_id, cat_title, cat_order) VALUES (1, 'Test category 1', 1);
 
 # -- Forums
-INSERT INTO phpbb_forums (forum_id, forum_name, forum_desc, cat_id, forum_order, forum_posts, forum_topics, forum_last_post_id, auth_view, auth_read, auth_post, auth_reply, auth_edit, auth_delete, auth_announce, auth_sticky, auth_votecreate, auth_vote, auth_attachments) VALUES (1, 'Test Forum 1', 'This is just a test forum, nothing special here.', 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 3, 3, 3, 3, 3);
+INSERT INTO phpbb_forums (forum_id, forum_name, forum_desc, cat_id, forum_order, forum_posts, forum_topics, forum_last_post_id, auth_view, auth_read, auth_post, auth_reply, auth_edit, auth_delete, auth_announce, auth_sticky, auth_pollcreate, auth_vote, auth_attachments) VALUES (1, 'Test Forum 1', 'This is just a test forum, nothing special here.', 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 3, 1, 1, 1, 3);
 
 # -- Users
 INSERT INTO phpbb_users (user_id, username, user_level, user_regdate, user_password, user_autologin_key, user_email, user_icq, user_website, user_occ, user_from, user_interests, user_sig, user_viewemail, user_theme, user_aim, user_yim, user_msnm, user_posts, user_attachsig, user_allowsmile, user_allowhtml, user_allowbbcode, user_allow_pm, user_notify_pm, user_allow_viewonline, user_rank, user_avatar, user_lang, user_timezone, user_dateformat, user_actkey, user_newpasswd, user_notify, user_active, user_template) VALUES ( '-1', 'Anonymous', '0', '972086460', '', '', '', '', '', '', '', '', '', '0', '0', '', '', '', '', '', '', '', '0', '0', '1', '', '', '', '', '', '', '', '', '0', '0', '');
@@ -34,10 +34,10 @@ INSERT INTO phpbb_user_group (group_id, user_id, user_pending) VALUES (1, -1, 0)
 INSERT INTO phpbb_user_group (group_id, user_id, user_pending) VALUES (2, 2, 0);
 
 # -- User Access (admin is set as ... an admin)
-INSERT INTO phpbb_auth_access (group_id, forum_id, auth_view, auth_read, auth_post, auth_reply, auth_edit, auth_delete, auth_announce, auth_sticky, auth_votecreate, auth_vote, auth_mod) VALUES (2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1);
+INSERT INTO phpbb_auth_access (group_id, forum_id, auth_view, auth_read, auth_post, auth_reply, auth_edit, auth_delete, auth_announce, auth_sticky, auth_pollcreate, auth_vote, auth_mod) VALUES (2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1);
 
 # -- Demo Topic
-INSERT INTO phpbb_topics (topic_id, topic_title, topic_poster, topic_time, topic_views, topic_replies, forum_id, topic_status, topic_type, topic_last_post_id) VALUES (1, 'Demo Topic', 2, '972086460', 0, 0, 1, 0, 0, 1);
+INSERT INTO phpbb_topics (topic_id, topic_title, topic_poster, topic_time, topic_views, topic_replies, forum_id, topic_status, topic_type, topic_vote, topic_last_post_id) VALUES (1, 'Demo Topic', 2, '972086460', 0, 0, 1, 0, 0, 0, 1);
 
 # -- Demo Post
 INSERT INTO phpbb_posts (post_id, topic_id, forum_id, poster_id, post_time, post_username, poster_ip) VALUES (1, 1, 1, 2, '972086460', '', '7F000001');
@@ -128,12 +128,11 @@ INSERT INTO phpbb_words (word_id, word, replacement) VALUES ( '26', 'dickweed',
 INSERT INTO phpbb_words (word_id, word, replacement) VALUES ( '27', 'dickwad', '*beep*');
 INSERT INTO phpbb_words (word_id, word, replacement) VALUES ( '28', 'frig*', '*beep*');
 INSERT INTO phpbb_words (word_id, word, replacement) VALUES ( '29', 'hore', '*beep*');
-INSERT INTO phpbb_words (word_id, word, replacement) VALUES ( '30', 'fag*', '*beep*');
-INSERT INTO phpbb_words (word_id, word, replacement) VALUES ( '31', 'asswipe', '*beep*');
-INSERT INTO phpbb_words (word_id, word, replacement) VALUES ( '32', 'asstool*', '*beep*');
-INSERT INTO phpbb_words (word_id, word, replacement) VALUES ( '33', '*cock*', '*beep*');
-INSERT INTO phpbb_words (word_id, word, replacement) VALUES ( '34', 'b!tch', '*beep*');
-INSERT INTO phpbb_words (word_id, word, replacement) VALUES ( '35', 'masturbation', '*beep*');
-INSERT INTO phpbb_words (word_id, word, replacement) VALUES ( '36', 'dickhead', '*beep*');
-INSERT INTO phpbb_words (word_id, word, replacement) VALUES ( '37', 'spunk', '*beep*');
-INSERT INTO phpbb_words (word_id, word, replacement) VALUES ( '38', '*crap*', '*beep*');
+INSERT INTO phpbb_words (word_id, word, replacement) VALUES ( '30', 'asswipe', '*beep*');
+INSERT INTO phpbb_words (word_id, word, replacement) VALUES ( '31', 'asstool*', '*beep*');
+INSERT INTO phpbb_words (word_id, word, replacement) VALUES ( '32', '*cock*', '*beep*');
+INSERT INTO phpbb_words (word_id, word, replacement) VALUES ( '33', 'b!tch', '*beep*');
+INSERT INTO phpbb_words (word_id, word, replacement) VALUES ( '34', 'masturbat*', '*beep*');
+INSERT INTO phpbb_words (word_id, word, replacement) VALUES ( '35', 'dickhead', '*beep*');
+INSERT INTO phpbb_words (word_id, word, replacement) VALUES ( '36', 'spunk', '*beep*');
+INSERT INTO phpbb_words (word_id, word, replacement) VALUES ( '37', '*crap*', '*beep*');
diff --git a/phpBB/db/mysql_schema.sql b/phpBB/db/mysql_schema.sql
index 5e3a8c168a..22e7c9913d 100644
--- a/phpBB/db/mysql_schema.sql
+++ b/phpBB/db/mysql_schema.sql
@@ -7,7 +7,6 @@
 #
 # Table structure for table 'phpbb_auth_access'
 #
-
 DROP TABLE IF EXISTS phpbb_auth_access;
 CREATE TABLE phpbb_auth_access (
    group_id int(11) DEFAULT '0' NOT NULL,
@@ -18,25 +17,25 @@ CREATE TABLE phpbb_auth_access (
    auth_reply tinyint(1) DEFAULT '0' NOT NULL,
    auth_edit tinyint(1) DEFAULT '0' NOT NULL,
    auth_delete tinyint(1) DEFAULT '0' NOT NULL,
-   auth_announce tinyint(1) DEFAULT '0' NOT NULL,
    auth_sticky tinyint(1) DEFAULT '0' NOT NULL,
-   auth_votecreate tinyint(1) DEFAULT '0' NOT NULL,
-   auth_attachments tinyint(1) DEFAULT '0' NOT NULL,
+   auth_announce tinyint(1) DEFAULT '0' NOT NULL,
    auth_vote tinyint(1) DEFAULT '0' NOT NULL,
-   auth_mod tinyint(1) DEFAULT '0' NOT NULL,
+   auth_pollcreate tinyint(1) DEFAULT '0' NOT NULL,
+   auth_attachments tinyint(1) DEFAULT '0' NOT NULL,
+   auth_mod tinyint(1) DEFAULT '0' NOT NULL, 
    KEY group_id (group_id),
    KEY forum_id (forum_id)
 );
 
+
 #
 # Table structure for table 'phpbb_user_group'
 #
-
 DROP TABLE IF EXISTS phpbb_user_group;
 CREATE TABLE phpbb_user_group (
    group_id int(11) DEFAULT '0' NOT NULL,
    user_id int(11) DEFAULT '0' NOT NULL,
-   user_pending tinyint(1),
+   user_pending tinyint(1), 
    KEY group_id (group_id),
    KEY user_id (user_id)
 );
@@ -47,15 +46,16 @@ CREATE TABLE phpbb_user_group (
 DROP TABLE IF EXISTS phpbb_groups;
 CREATE TABLE phpbb_groups (
    group_id int(11) NOT NULL auto_increment,
-   group_type tinyint(4) DEFAULT '1' NOT NULL,
+   group_type tinyint(4) DEFAULT '1' NOT NULL, 
    group_name varchar(40) NOT NULL,
    group_description varchar(255) NOT NULL,
    group_moderator int(11) DEFAULT '0' NOT NULL,
    group_single_user tinyint(1) DEFAULT '0' NOT NULL,
-   PRIMARY KEY (group_id),
+   PRIMARY KEY (group_id), 
    KEY group_single_user (group_single_user)
 );
 
+
 # --------------------------------------------------------
 #
 # Table structure for table 'phpbb_banlist'
@@ -66,7 +66,7 @@ CREATE TABLE phpbb_banlist (
    ban_userid int(11) NOT NULL,
    ban_ip char(8) NOT NULL,
    ban_email varchar(255),
-   PRIMARY KEY (ban_id),
+   PRIMARY KEY (ban_id), 
    KEY ban_ip_user_id (ban_ip, ban_userid)
 );
 
@@ -80,7 +80,7 @@ CREATE TABLE phpbb_categories (
    cat_id int(11) NOT NULL auto_increment,
    cat_title varchar(100),
    cat_order int(11) NOT NULL,
-   PRIMARY KEY (cat_id),
+   PRIMARY KEY (cat_id), 
    KEY cat_order (cat_order)
 );
 
@@ -92,46 +92,47 @@ CREATE TABLE phpbb_categories (
 DROP TABLE IF EXISTS phpbb_config;
 CREATE TABLE phpbb_config (
    config_id int(11) NOT NULL auto_increment,
-   board_disable tinyint(1) DEFAULT '0' NOT NULL,
-   board_startdate int(11),
+   board_disable tinyint(1) DEFAULT '0' NOT NULL, 
+   board_startdate int(11), 
    sitename varchar(100),
    cookie_name char(20),
    cookie_path char(25),
-   cookie_domain char(50),
-   cookie_secure tinyint(1),
-   session_length int(11),
+   cookie_domain char(50), 
+   cookie_secure tinyint(1), 
+   session_length int(11), 
    allow_html tinyint(1),
-   allow_html_tags char(255) DEFAULT 'b,u,i,pre,font color' NOT NULL,
+   allow_html_tags char(255) DEFAULT 'b,u,i,pre,font color' NOT NULL, 
    allow_bbcode tinyint(1),
    allow_smilies tinyint(1),
    allow_sig tinyint(1),
    allow_namechange tinyint(1),
    allow_theme_create tinyint(1),
-   allow_avatar_local tinyint(1) DEFAULT '0' NOT NULL,
-   allow_avatar_remote tinyint(1) DEFAULT '0' NOT NULL,
+   allow_avatar_local tinyint(1) DEFAULT '0' NOT NULL, 
+   allow_avatar_remote tinyint(1) DEFAULT '0' NOT NULL, 
    allow_avatar_upload tinyint(1) DEFAULT '0' NOT NULL,
    override_themes tinyint(3),
    posts_per_page int(11),
    topics_per_page int(11),
    hot_threshold int(11),
+   max_poll_options int(11), 
    email_sig varchar(255),
-   email_from varchar(100),
-   smtp_delivery smallint(1) DEFAULT '0' NOT NULL,
-   smtp_host varchar(50),
-   require_activation tinyint(1) DEFAULT '0' NOT NULL,
+   email_from varchar(100), 
+   smtp_delivery tinyint(1) DEFAULT '0' NOT NULL, 
+   smtp_host varchar(50), 
+   require_activation tinyint(1) DEFAULT '0' NOT NULL, 
    flood_interval int(4) NOT NULL,
    avatar_filesize int(11) DEFAULT '6144' NOT NULL,
-   avatar_max_width smallint(6) DEFAULT '70' NOT NULL,
-   avatar_max_height smallint(6) DEFAULT '70' NOT NULL,
+   avatar_max_width smallint(6) DEFAULT '70' NOT NULL, 
+   avatar_max_height smallint(6) DEFAULT '70' NOT NULL, 
    avatar_path varchar(255) DEFAULT 'images/avatars' NOT NULL,
-   smilies_path char(100) DEFAULT 'images/smiles' NOT NULL,
+   smilies_path char(100) DEFAULT 'images/smiles' NOT NULL, 
    default_theme int(11) DEFAULT '1' NOT NULL,
    default_lang varchar(255),
    default_dateformat varchar(14) DEFAULT 'd M Y H:i' NOT NULL,
    system_timezone int(11) DEFAULT '0' NOT NULL,
    sys_template varchar(100) DEFAULT 'Default' NOT NULL,
-   prune_enable tinyint(1) DEFAULT '0' NOT NULL,
-   gzip_compress tinyint(1) DEFAULT '0' NOT NULL,
+   prune_enable tinyint(1) DEFAULT '1' NOT NULL, 
+   gzip_compress tinyint(1) DEFAULT '0' NOT NULL, 
    PRIMARY KEY (config_id)
 );
 
@@ -162,6 +163,7 @@ CREATE TABLE phpbb_forum_prune (
    KEY forum_id (forum_id)
 );
 
+
 # --------------------------------------------------------
 #
 # Table structure for table 'phpbb_forums'
@@ -172,33 +174,32 @@ CREATE TABLE phpbb_forums (
    cat_id int(11) NOT NULL,
    forum_name varchar(150),
    forum_desc text,
-   forum_status tinyint(4) DEFAULT '0' NOT NULL,
+   forum_status tinyint(4) DEFAULT '0' NOT NULL, 
    forum_order int(11) DEFAULT '1' NOT NULL,
    forum_posts int(11) DEFAULT '0' NOT NULL,
-   forum_topics tinyint(4) DEFAULT '0' NOT NULL,
+   forum_topics int(11) DEFAULT '0' NOT NULL,
    forum_last_post_id int(11) DEFAULT '0' NOT NULL,
    prune_next int(11),
    prune_enable tinyint(1) DEFAULT '1' NOT NULL,
-   auth_view tinyint(4) DEFAULT '0' NOT NULL,
-   auth_read tinyint(4) DEFAULT '0' NOT NULL,
-   auth_post tinyint(4) DEFAULT '0' NOT NULL,
-   auth_reply tinyint(4) DEFAULT '0' NOT NULL,
-   auth_edit tinyint(4) DEFAULT '0' NOT NULL,
-   auth_delete tinyint(4) DEFAULT '0' NOT NULL,
-   auth_announce tinyint(4) DEFAULT '0' NOT NULL,
-   auth_sticky tinyint(4) DEFAULT '0' NOT NULL,
-   auth_votecreate tinyint(4) DEFAULT '0' NOT NULL,
-   auth_vote tinyint(4) DEFAULT '0' NOT NULL,
-   auth_attachments tinyint(4) DEFAULT '0' NOT NULL,
+   auth_view tinyint(2) DEFAULT '0' NOT NULL,
+   auth_read tinyint(2) DEFAULT '0' NOT NULL,
+   auth_post tinyint(2) DEFAULT '0' NOT NULL,
+   auth_reply tinyint(2) DEFAULT '0' NOT NULL,
+   auth_edit tinyint(2) DEFAULT '0' NOT NULL,
+   auth_delete tinyint(2) DEFAULT '0' NOT NULL,
+   auth_sticky tinyint(2) DEFAULT '0' NOT NULL,
+   auth_announce tinyint(2) DEFAULT '0' NOT NULL,
+   auth_vote tinyint(2) DEFAULT '0' NOT NULL,
+   auth_pollcreate tinyint(2) DEFAULT '0' NOT NULL,
+   auth_attachments tinyint(2) DEFAULT '0' NOT NULL,
    PRIMARY KEY (forum_id),
    KEY forum_id (forum_id),
    KEY forums_order (forum_order),
-   KEY cat_id (cat_id),
+   KEY cat_id (cat_id), 
    KEY forum_last_post_id (forum_last_post_id)
 );
 
 
-
 # --------------------------------------------------------
 #
 # Table structure for table 'phpbb_posts'
@@ -210,14 +211,14 @@ CREATE TABLE phpbb_posts (
    forum_id int(11) DEFAULT '0' NOT NULL,
    poster_id int(11) DEFAULT '0' NOT NULL,
    post_time int(11) DEFAULT '0' NOT NULL,
-   poster_ip char(8) NOT NULL,
-   post_username varchar(30),
-   enable_bbcode smallint(1) DEFAULT '1' NOT NULL,
-   enable_html smallint(1) DEFAULT '0' NOT NULL,
-   enable_smilies smallint(1) DEFAULT '1' NOT NULL,
+   poster_ip char(8) NOT NULL, 
+   post_username varchar(30), 
+   enable_bbcode tinyint(1) DEFAULT '1' NOT NULL,
+   enable_html tinyint(1) DEFAULT '0' NOT NULL,
+   enable_smilies tinyint(1) DEFAULT '1' NOT NULL,
    bbcode_uid char(10) NOT NULL,
    post_edit_time int(11),
-   post_edit_count smallint(4) DEFAULT '0' NOT NULL,
+   post_edit_count smallint(6) DEFAULT '0' NOT NULL,
    PRIMARY KEY (post_id),
    KEY forum_id (forum_id),
    KEY topic_id (topic_id),
@@ -242,7 +243,6 @@ CREATE TABLE phpbb_posts_text (
 #
 # Table structure for table 'phpbb_privmsgs'
 #
-
 DROP TABLE IF EXISTS phpbb_privmsgs;
 CREATE TABLE phpbb_privmsgs (
    privmsgs_id int(11) NOT NULL auto_increment,
@@ -252,10 +252,10 @@ CREATE TABLE phpbb_privmsgs (
    privmsgs_to_userid int(11) DEFAULT '0' NOT NULL,
    privmsgs_date int(11) DEFAULT '0' NOT NULL,
    privmsgs_ip char(8) NOT NULL,
-   privmsgs_enable_bbcode smallint(1) DEFAULT '1' NOT NULL,
-   privmsgs_enable_html smallint(1) DEFAULT '0' NOT NULL,
-   privmsgs_enable_smilies smallint(1) DEFAULT '1' NOT NULL,
-   privmsgs_bbcode_uid char(10) DEFAULT '0' NOT NULL,
+   privmsgs_enable_bbcode tinyint(1) DEFAULT '1' NOT NULL,
+   privmsgs_enable_html tinyint(1) DEFAULT '0' NOT NULL,
+   privmsgs_enable_smilies tinyint(1) DEFAULT '1' NOT NULL,
+   privmsgs_bbcode_uid char(10) DEFAULT '0' NOT NULL, 
    PRIMARY KEY (privmsgs_id),
    KEY privmsgs_from_userid (privmsgs_from_userid),
    KEY privmsgs_to_userid (privmsgs_to_userid)
@@ -266,7 +266,6 @@ CREATE TABLE phpbb_privmsgs (
 #
 # Table structure for table 'phpbb_privmsgs_text'
 #
-
 DROP TABLE IF EXISTS phpbb_privmsgs_text;
 CREATE TABLE phpbb_privmsgs_text (
    privmsgs_text_id int(11) DEFAULT '0' NOT NULL,
@@ -287,7 +286,7 @@ CREATE TABLE phpbb_ranks (
    rank_max int(11) DEFAULT '0' NOT NULL,
    rank_special tinyint(1) DEFAULT '0',
    rank_image varchar(255),
-   PRIMARY KEY (rank_id)
+   PRIMARY KEY (rank_id) 
 );
 
 
@@ -299,7 +298,7 @@ CREATE TABLE phpbb_ranks (
 # this table a type HEAP. This type of table is stored
 # within system memory and therefore for big busy boards
 # is likely to be noticeably faster than continually
-# writing to disk ...
+# writing to disk ... 
 #
 # I must admit I read about this type on vB's board.
 # Hey, I never said you cannot get basic ideas from
@@ -442,6 +441,7 @@ CREATE TABLE phpbb_topics (
    topic_views int(11) DEFAULT '0' NOT NULL,
    topic_replies int(11) DEFAULT '0' NOT NULL,
    topic_status tinyint(3) DEFAULT '0' NOT NULL,
+   topic_vote tinyint(1) DEFAULT '0' NOT NULL,
    topic_type tinyint(3) DEFAULT '0' NOT NULL,
    topic_last_post_id int(11) DEFAULT '0' NOT NULL,
    topic_moved_id int(11),
@@ -460,7 +460,7 @@ CREATE TABLE phpbb_topics_watch (
   user_id int(11) NOT NULL DEFAULT '0',
   notify_status tinyint(1) NOT NULL default '0',
   KEY topic_id (topic_id),
-  KEY user_id (user_id),
+  KEY user_id (user_id), 
   KEY notify_status (notify_status)
 );
 
@@ -487,12 +487,12 @@ CREATE TABLE phpbb_users (
    user_attachsig tinyint(1),
    user_allowhtml tinyint(1),
    user_allowbbcode tinyint(1),
-   user_allowsmile tinyint(1),
-   user_allowavatar tinyint(1) DEFAULT '1' NOT NULL,
-   user_allow_pm tinyint(1) DEFAULT '1' NOT NULL,
-   user_allow_viewonline tinyint(1) DEFAULT '1' NOT NULL,
+   user_allowsmile tinyint(1), 
+   user_allowavatar tinyint(1) DEFAULT '1' NOT NULL, 
+   user_allow_pm tinyint(1) DEFAULT '1' NOT NULL, 
+   user_allow_viewonline tinyint(1) DEFAULT '1' NOT NULL, 
    user_notify tinyint(1) DEFAULT '1' NOT NULL,
-   user_notify_pm tinyint(1) DEFAULT '1' NOT NULL,
+   user_notify_pm tinyint(1) DEFAULT '1' NOT NULL, 
    user_regdate int(11) DEFAULT '0' NOT NULL,
    user_rank int(11) DEFAULT '0',
    user_avatar varchar(100),
@@ -512,6 +512,52 @@ CREATE TABLE phpbb_users (
 );
 
 
+# --------------------------------------------------------
+#
+# Table structure for table 'phpbb_vote_desc'
+#
+DROP TABLE IF EXISTS phpbb_vote_desc;
+CREATE TABLE phpbb_vote_desc (
+  vote_id int(11) NOT NULL auto_increment,
+  topic_id int(11) NOT NULL DEFAULT '0',
+  vote_text text NOT NULL,
+  vote_start int(11) NOT NULL DEFAULT '0',
+  vote_length int(11) NOT NULL DEFAULT '0',
+  PRIMARY KEY  (vote_id),
+  KEY topic_id (topic_id)
+);
+
+
+# --------------------------------------------------------
+#
+# Table structure for table 'phpbb_vote_results'
+#
+DROP TABLE IF EXISTS phpbb_vote_results;
+CREATE TABLE phpbb_vote_results (
+  vote_id int(11) NOT NULL DEFAULT '0',
+  vote_option_id int(11) NOT NULL DEFAULT '0',
+  vote_option_text varchar(255) NOT NULL,
+  vote_result int(11) NOT NULL DEFAULT '0',
+  KEY vote_option_id (vote_option_id),
+  KEY vote_id (vote_id)
+);
+
+
+# --------------------------------------------------------
+#
+# Table structure for table 'phpbb_vote_voters'
+#
+DROP TABLE IF EXISTS phpbb_vote_voters;
+CREATE TABLE phpbb_vote_voters (
+  vote_id int(11) NOT NULL DEFAULT '0',
+  vote_user_id int(11) NOT NULL DEFAULT '0',
+  vote_user_ip char(8) NOT NULL,
+  KEY vote_id (vote_id),
+  KEY vote_user_id (vote_user_id),
+  KEY vote_user_ip (vote_user_ip)
+);
+
+
 # --------------------------------------------------------
 #
 # Table structure for table 'phpbb_words'
@@ -522,4 +568,4 @@ CREATE TABLE phpbb_words (
    word varchar(100) NOT NULL,
    replacement varchar(100) NOT NULL,
    PRIMARY KEY (word_id)
-);
+);
\ No newline at end of file
diff --git a/phpBB/images/voting/bar_1.gif b/phpBB/images/voting/bar_1.gif
new file mode 100644
index 0000000000..3131e7d75f
Binary files /dev/null and b/phpBB/images/voting/bar_1.gif differ
diff --git a/phpBB/images/voting/bar_2.gif b/phpBB/images/voting/bar_2.gif
new file mode 100644
index 0000000000..d0238f6ed3
Binary files /dev/null and b/phpBB/images/voting/bar_2.gif differ
diff --git a/phpBB/images/voting/bar_3.gif b/phpBB/images/voting/bar_3.gif
new file mode 100644
index 0000000000..6b419f7962
Binary files /dev/null and b/phpBB/images/voting/bar_3.gif differ
diff --git a/phpBB/images/voting/bar_4.gif b/phpBB/images/voting/bar_4.gif
new file mode 100644
index 0000000000..53e9d9efe0
Binary files /dev/null and b/phpBB/images/voting/bar_4.gif differ
diff --git a/phpBB/images/voting/bar_5.gif b/phpBB/images/voting/bar_5.gif
new file mode 100644
index 0000000000..58627af68a
Binary files /dev/null and b/phpBB/images/voting/bar_5.gif differ
diff --git a/phpBB/includes/auth.php b/phpBB/includes/auth.php
index 575574f9e1..5fcbe0eb4f 100644
--- a/phpBB/includes/auth.php
+++ b/phpBB/includes/auth.php
@@ -1,15 +1,15 @@
 <?php
 /***************************************************************************
  *                                 auth.php
- *                            -------------------
- *   begin                : Saturday, Feb 13, 2001
- *   copyright            : (C) 2001 The phpBB Group
- *   email                : support@phpbb.com
- *
- *   $Id$
- *
- *
- ***************************************************************************/
+ *                            -------------------                         
+ *   begin                : Saturday, Feb 13, 2001 
+ *   copyright            : (C) 2001 The phpBB Group        
+ *   email                : support@phpbb.com                           
+ *                                                          
+ *   $Id$                                                           
+ *                                                            
+ * 
+ ***************************************************************************/ 
 
 /***************************************************************************
  *
@@ -59,8 +59,8 @@ function auth($type, $forum_id, $userdata, $f_access = -1)
 	switch($type)
 	{
 		case AUTH_ALL:
-			$a_sql = "a.auth_view, a.auth_read, a.auth_post, a.auth_reply, a.auth_edit, a.auth_delete, a.auth_sticky, a.auth_announce";
-			$auth_fields = array("auth_view", "auth_read", "auth_post", "auth_reply", "auth_edit", "auth_delete", "auth_sticky", "auth_announce");
+			$a_sql = "a.auth_view, a.auth_read, a.auth_post, a.auth_reply, a.auth_edit, a.auth_delete, a.auth_sticky, a.auth_announce, a.auth_vote, a.auth_pollcreate";
+			$auth_fields = array("auth_view", "auth_read", "auth_post", "auth_reply", "auth_edit", "auth_delete", "auth_sticky", "auth_announce", "auth_vote", "auth_pollcreate");
 			break;
 
 		case AUTH_VIEW:
@@ -98,9 +98,13 @@ function auth($type, $forum_id, $userdata, $f_access = -1)
 			$auth_fields = array("auth_sticky");
 			break;
 
-		case AUTH_VOTECREATE:
+		case AUTH_POLLCREATE:
+			$a_sql = "a.auth_pollcreate";
+			$auth_fields = array("auth_pollcreate");
 			break;
 		case AUTH_VOTE:
+			$a_sql = "a.auth_vote";
+			$auth_fields = array("auth_vote");
 			break;
 		case AUTH_ATTACH:
 			break;
diff --git a/phpBB/includes/bbcode.php b/phpBB/includes/bbcode.php
index 45c6774d6c..c4e799a0d5 100644
--- a/phpBB/includes/bbcode.php
+++ b/phpBB/includes/bbcode.php
@@ -28,6 +28,7 @@ define("BBCODE_UID_LEN", 10);
  */
 function bbencode_second_pass($text, $uid)
 {
+	global $lang;
 
 	//$uid_tag_length = strpos($text, ']') + 1;
 	//$uid = substr($text, 5, BBCODE_UID_LEN);
@@ -60,8 +61,8 @@ function bbencode_second_pass($text, $uid)
 	$text = preg_replace("/\[list=([a1]):$uid\]/si", '<OL TYPE="\1">', $text);
 
 	// [QUOTE] and [/QUOTE] for posting replies with quote, or just for quoting stuff.
-	$text = str_replace("[quote:$uid]", '<TABLE BORDER="0" ALIGN="CENTER" WIDTH="85%"><TR><TD><font size="-1">Quote:</font><HR></TD></TR><TR><TD><FONT SIZE="-1"><BLOCKQUOTE>', $text);
-	$text = str_replace("[/quote:$uid]", '</BLOCKQUOTE></FONT></TD></TR><TR><TD><HR></TD></TR></TABLE>', $text);
+	$text = str_replace("[quote:$uid]", '<table border="0" align="center" width="85%"><tr><td><font size="-1">' . $lang['Quote'] . '</font><hr /> </td></tr><tr><td><font size="-1"><blockquote>', $text);
+	$text = str_replace("[/quote:$uid]", '</blockquote></font></td></tr><tr><td><hr></td></tr></table>', $text);
 
 	// [b] and [/b] for bolding text.
 	$text = str_replace("[b:$uid]", '<B>', $text);
@@ -89,15 +90,15 @@ function bbencode_second_pass($text, $uid)
 
 	// [url=xxxx://www.phpbb.com]phpBB[/url] code..
 	$patterns[2] = "#\[url=([a-z]+?://){1}(.*?)\](.*?)\[/url\]#si";
-	$replacements[2] = '<A HREF="\1\2" TARGET="_blank">\3</A>';
+	$replacements[2] = '<a href="\1\2" target="_blank">\3</A>';
 
 	// [url=www.phpbb.com]phpBB[/url] code.. (no xxxx:// prefix).
 	$patterns[3] = "#\[url=(.*?)\](.*?)\[/url\]#si";
-	$replacements[3] = '<A HREF="http://\1" TARGET="_blank">\2</A>';
+	$replacements[3] = '<A href="http://\1" TARGET="_blank">\2</A>';
 
 	// [email]user@domain.tld[/email] code..
 	$patterns[4] = "#\[email\](.*?)\[/email\]#si";
-	$replacements[4] = '<A HREF="mailto:\1">\1</A>';
+	$replacements[4] = '<A href="mailto:\1">\1</A>';
 
 	$text = preg_replace($patterns, $replacements, $text);
 
@@ -351,11 +352,13 @@ function bbencode_first_pass_pda($text, $uid, $open_tag, $close_tag, $close_tag_
  */
 function bbencode_second_pass_code($text, $uid)
 {
-	// If HTML is turned on we undo any HTML special chars that were created by the viewtopic code.
-//	$text = undo_htmlspecialchars($text);
+	global $lang;
 
-	$code_start_html = '<TABLE BORDER="0" ALIGN="CENTER" WIDTH="85%"><TR><TD><font size="-1">Code:</font><HR></TD></TR><TR><TD><FONT SIZE="-1"><PRE>';
-	$code_end_html =  '</PRE></FONT></TD></TR><TR><TD><HR></TD></TR></TABLE>';
+	$html_entities_match = array("#<#", "#>#");
+	$html_entities_replace = array("&lt;", "&gt;");
+
+	$code_start_html = '<table width="85%" border="0" align="center"><tr><td><font size="-1">' . $lang['Code'] . '</font><hr /></td></tr><tr><td><font size="-1"><pre>';
+	$code_end_html =  '</pre></font></td></tr><tr><td><hr /></td></tr></table>';
 
 	// First, do all the 1st-level matches. These need an htmlspecialchars() run,
 	// so they have to be handled differently.
@@ -366,7 +369,7 @@ function bbencode_second_pass_code($text, $uid)
 		$before_replace = $matches[1][$i];
 		$after_replace = $matches[1][$i];
 
-		$after_replace = htmlspecialchars($after_replace);
+		$after_replace = preg_replace($html_entities_match, $html_entities_replace, $after_replace);
 
 		$str_to_match = "[code:1:$uid]" . $before_replace . "[/code:1:$uid]";
 
diff --git a/phpBB/includes/constants.php b/phpBB/includes/constants.php
index 9124fcdd47..79d44a885b 100644
--- a/phpBB/includes/constants.php
+++ b/phpBB/includes/constants.php
@@ -28,16 +28,19 @@
 define(DEBUG, 1); // Debugging on
 //define(DEBUG, 0); // Debugging off
 
+
 // User Levels <- Do not change the values of USER or ADMIN
 define(DELETED, -1);
 define(ANONYMOUS, -1);
 define(USER, 0);
 define(ADMIN, 1);
 
+
 // Forum state
 define(FORUM_UNLOCKED, 0);
 define(FORUM_LOCKED, 1);
 
+
 // Topic status
 define(TOPIC_UNLOCKED, 0);
 define(TOPIC_LOCKED, 1);
@@ -57,6 +60,7 @@ define(POST_GLOBAL_ANNOUNCE, 3);
 define(BEGIN_TRANSACTION, 1);
 define(END_TRANSACTION, 2);
 
+
 // Error codes
 define(GENERAL_MESSAGE, 200);
 define(GENERAL_ERROR, 202);
@@ -70,11 +74,15 @@ define(SESSION_CREATE, 4);
 define(NO_TOPICS, 5);
 define(LOGIN_FAILED, 7);
 
+
 // Private messaging
 define(PRIVMSGS_READ_MAIL, 0);
 define(PRIVMSGS_NEW_MAIL, 1);
 define(PRIVMSGS_SENT_MAIL, 2);
 define(PRIVMSGS_SAVED_MAIL, 3);
+define(PRIVMSGS_SAVED_IN_MAIL, 3);
+define(PRIVMSGS_SAVED_OUT_MAIL, 4);
+
 
 // URL PARAMETERS
 define(POST_TOPIC_URL, 't');
@@ -83,10 +91,12 @@ define(POST_USERS_URL, 'u');
 define(POST_POST_URL, 'p');
 define(POST_GROUPS_URL, 'g');
 
+
 // Session parameters
 define(SESSION_METHOD_COOKIE, 100);
 define(SESSION_METHOD_GET, 101);
 
+
 // Page numbers for session handling
 define(PAGE_INDEX, 0);
 define(PAGE_LOGIN, -1);
@@ -101,6 +111,7 @@ define(PAGE_PRIVMSGS, -10);
 define(PAGE_GROUPCP, -11);
 define(PAGE_TOPIC_OFFSET, 5000);
 
+
 // Auth settings
 define(AUTH_ALL, 0);
 
@@ -119,12 +130,13 @@ define(AUTH_DELETE, 6);
 
 define(AUTH_ANNOUNCE, 7);
 define(AUTH_STICKY, 8);
-define(AUTH_VOTECREATE, 9);
+define(AUTH_POLLCREATE, 9);
 define(AUTH_VOTE, 10);
 define(AUTH_ATTACH, 11);
 
 define(AUTH_LIST_ALL, 20);
 
+
 // Table names
 define('AUTH_ACCESS_TABLE', $table_prefix.'auth_access');
 define('BANLIST_TABLE', $table_prefix.'banlist');
@@ -138,6 +150,7 @@ define('POSTS_TEXT_TABLE', $table_prefix.'posts_text');
 define('PRIVMSGS_TABLE', $table_prefix.'privmsgs');
 define('PRIVMSGS_TEXT_TABLE', $table_prefix.'privmsgs_text');
 define('PRIVMSGS_IGNORE_TABLE', $table_prefix.'privmsgs_ignore');
+define('PRUNE_TABLE', $table_prefix.'forum_prune');
 define('RANKS_TABLE', $table_prefix.'ranks');
 define('SESSIONS_TABLE', $table_prefix.'session');
 define('SMILIES_TABLE', $table_prefix.'smilies');
@@ -147,6 +160,8 @@ define('TOPICS_WATCH_TABLE', $table_prefix.'topics_watch');
 define('USER_GROUP_TABLE', $table_prefix.'user_group');
 define('USERS_TABLE', $table_prefix.'users');
 define('WORDS_TABLE', $table_prefix.'words');
-define('PRUNE_TABLE', $table_prefix.'forum_prune');
+define('VOTE_DESC_TABLE', $table_prefix.'vote_desc');
+define('VOTE_RESULTS_TABLE', $table_prefix.'vote_results');
+define('VOTE_USERS_TABLE', $table_prefix.'vote_voters');
 
 ?>
\ No newline at end of file
diff --git a/phpBB/includes/functions.php b/phpBB/includes/functions.php
index cc668e8f3a..4642446a21 100644
--- a/phpBB/includes/functions.php
+++ b/phpBB/includes/functions.php
@@ -627,7 +627,15 @@ function sync($type, $id)
 			{
 				message_die(GENERAL_ERROR, "Could not get post count", "Error", __LINE__, __FILE__, $sql);
 			}
-			$total_posts = ( $row = $db->sql_fetchrow($result) ) ? $row['total'] : 0;
+
+			if( $row = $db->sql_fetchrow($result) )
+			{
+				$total_posts = ($row['total']) ? $row['total'] : 0;
+			}
+			else
+			{
+				$total_posts = 0;
+			}
 
 			$sql = "SELECT COUNT(topic_id) AS total
 				FROM " . TOPICS_TABLE . "
@@ -636,7 +644,15 @@ function sync($type, $id)
 			{
 				message_die(GENERAL_ERROR, "Could not get topic count", "Error", __LINE__, __FILE__, $sql);
 			}
-			$total_topics = ( $row = $db->sql_fetchrow($result) ) ? $row['total'] : 0;
+
+			if( $row = $db->sql_fetchrow($result) )
+			{
+				$total_topics = ($row['total']) ? $row['total'] : 0;
+			}
+			else
+			{
+				$total_topics = 0;
+			}
 
 			$sql = "UPDATE " . FORUMS_TABLE . "
 				SET forum_last_post_id = $last_post, forum_posts = $total_posts, forum_topics = $total_topics
@@ -658,7 +674,7 @@ function sync($type, $id)
 
 			if( $row = $db->sql_fetchrow($result) )
 			{
-				$last_post = $row['last_post'];
+				$last_post = ($row['last_post']) ? $row['last_post'] : 0;
 			}
 			else
 			{
@@ -672,7 +688,15 @@ function sync($type, $id)
 			{
 				message_die(GENERAL_ERROR, "Could not get post count", "Error", __LINE__, __FILE__, $sql);
 			}
-			$total_posts = ( $row = $db->sql_fetchrow($result) ) ? $row['total'] - 1 : 0;
+
+			if( $row = $db->sql_fetchrow($result) )
+			{
+				$total_posts = ($row['total']) ? $row['total'] - 1 : 0;
+			}
+			else
+			{
+				$total_posts = 0;
+			}
 
 			$sql = "UPDATE " . TOPICS_TABLE . "
 				SET topic_replies = $total_posts, topic_last_post_id = $last_post
diff --git a/phpBB/includes/post.php b/phpBB/includes/post.php
index 9d41b85f28..ac364f6472 100644
--- a/phpBB/includes/post.php
+++ b/phpBB/includes/post.php
@@ -35,50 +35,60 @@ function prepare_message($message, $html_on, $bbcode_on, $smile_on, $bbcode_uid
 
 	if( $html_on )
 	{
-		$start = -1;
-		$end = 0;
+		$html_entities_match = array("#<#", "#>#", "#& #");
+		$html_entities_replace = array("&lt;", "&gt;", "&amp; ");
 
-		for($h = 0; $h < strlen($message); $h++)
+		$start_html = 1;
+
+		$message = " " . $message;
+		while( $start_html = strpos($message, "<", $start_html) )
 		{
-			$start = strpos($message, "<", $h);
-
-			if($start > -1)
+			if( $end_html = strpos($message, ">", $start_html) )
 			{
-				$end = strpos($message, ">", $start);
+				$length = $end_html - $start_html + 1;
 
-				if($end)
+				$tagallowed = 0;
+				for($i = 0; $i < sizeof($board_config['allow_html_tags']); $i++)
 				{
-					$length = $end - $start + 1;
-					$tagallowed = 0;
+					$match_tag = trim($board_config['allow_html_tags'][$i]);
 
-					for($i = 0; $i < sizeof($board_config['allow_html_tags']); $i++)
+					if( preg_match("/^[\/]?" . $match_tag . "( .*?)*$/i", trim(substr($message, $start_html + 1, $length - 2))) )
 					{
-						$match_tag = trim($board_config['allow_html_tags'][$i]);
-						list($match_tag_split) = explode(" ", $match_tag);
-
-						if( preg_match("/^((\/" . $match_tag_split . ")|(" . $match_tag . "))[ \=]+/i", trim(substr($message, $start + 1, $length - 2)) . " ") )
+						if( !preg_match("/(^\?)|(\?$)/", trim(substr($message, $start_html + 1, $length - 2))) )
 						{
 							$tagallowed = 1;
 						}
 					}
-
-					if($length && !$tagallowed)
-					{
-						$message = str_replace(substr($message, $start, $length), htmlspecialchars(substr($message, $start, $length)), $message);
-					}
 				}
-				$start = -1;
+
+				if( $length && !$tagallowed )
+				{
+					$message = str_replace(substr($message, $start_html, $length), preg_replace($html_entities_match, $html_entities_replace, substr($message, $start_html, $length)), $message);
+				}
+
+				$start_html += $length;
+			}
+			else
+			{
+				$message = str_replace(substr($message, $start_html, 1), preg_replace($html_entities_match, $html_entities_replace, substr($message, $start_html, 1)), $message);
+
+				$start_html = strlen($message);
 			}
 		}
+		$message = trim($message);
+	}
+	else
+	{
+		$html_entities_match = array("#<#", "#>#", "#& #");
+		$html_entities_replace = array("&lt;", "&gt;", "&amp; ");
+		$message = preg_replace($html_entities_match, $html_entities_replace, $message);
 	}
 
-	if($bbcode_on)
+	if( $bbcode_on && $bbcode_uid != "" )
 	{
 		$message = bbencode_first_pass($message, $bbcode_uid);
 	}
 
-	$message = addslashes($message);
-
 	return($message);
 }
 
diff --git a/phpBB/includes/prune.php b/phpBB/includes/prune.php
index 9224e71a25..a9680dadcf 100644
--- a/phpBB/includes/prune.php
+++ b/phpBB/includes/prune.php
@@ -24,115 +24,108 @@ function prune($forum_id, $prune_date)
 {
 	global $db, $lang;
 
-	$sql = "SELECT t.topic_id
+	$pruned_topic_list = array();
+
+	//
+	// Those without polls ...
+	//
+	$sql = "SELECT t.topic_id 
 		FROM " . POSTS_TABLE . " p, " . TOPICS_TABLE . " t
 		WHERE t.forum_id = $forum_id
-			AND t.topic_type = " . POST_NORMAL . "
+			AND t.topic_vote = 0 
+			AND t.topic_type <> " . POST_ANNOUNCE . "
 			AND p.post_id = t.topic_last_post_id";
-	// Do we want to delete everything in the forum?
-	if ($prune_date != FALSE)
+	if ($prune_date != "")
 	{
 		$sql .= " AND p.post_time < $prune_date";
 	}
+
 	if(!$result_topics = $db->sql_query($sql))
 	{
 		message_die(GENERAL_ERROR, "Couldn't obtain lists of topics to prune.", "", __LINE__, __FILE__, $sql);
 	}
-	$pruned_topics = $db->sql_numrows($result_topics);
 
-	$sql = "SELECT p.post_id
-		FROM " . POSTS_TABLE . " p, " . TOPICS_TABLE . " t
-		WHERE p.forum_id = $forum_id
-			AND t.topic_id = p.topic_id
-			AND t.topic_type = " . POST_NORMAL;
-	// Do we want to delete everything in the forum?
-	if ($prune_date != FALSE)
-	{
-		$sql .= " AND p.post_time < $prune_date";
-	}
-	if(!$result_posts = $db->sql_query($sql))
-	{
-		message_die(GENERAL_ERROR, "Couldn't obtain list of posts to prune.", "", __LINE__, __FILE__, $sql);
-	}
-	$pruned_posts = $db->sql_numrows($result_posts);
-
-	if( $pruned_topics > 0 )
+	if( $pruned_topics = $db->sql_numrows($result_topics) )
 	{
 		$pruned_topic_list = $db->sql_fetchrowset($result_topics);
-
+	
 		$sql_topics = "";
-
 		for($i = 0; $i < $pruned_topics; $i++)
 		{
 			if($sql_topics != "")
 			{
-				$sql_topics .= " OR ";
+				$sql_topics .= ", ";
 			}
-			$sql_topics .= "topic_id = " . $pruned_topic_list[$i]['topic_id'];
+			$sql_topics .= $pruned_topic_list[$i]['topic_id'];
 		}
+		$sql_topics = "topic_id IN (" . $sql_topics . ")";
 
-		$sql_topics = "DELETE FROM " . TOPICS_TABLE . " WHERE " . $sql_topics;
-
-		if(!$result = $db->sql_query($sql_topics))
+		$sql = "SELECT post_id
+			FROM " . POSTS_TABLE . " 
+			WHERE forum_id = $forum_id 
+				AND $sql_topics";
+		if(!$result_posts = $db->sql_query($sql))
 		{
-			message_die(GENERAL_ERROR, "Couldn't delete topics during prune.", "", __LINE__, __FILE__, $sql_topics);
+			message_die(GENERAL_ERROR, "Couldn't obtain list of posts to prune.", "", __LINE__, __FILE__, $sql);
 		}
-	}
 
-	if( $pruned_posts > 0 )
-	{
+		$pruned_posts = $db->sql_numrows($result_posts);
 		$pruned_post_list = $db->sql_fetchrowset($result_posts);
 
-		$sql_post_text = "";
 		$sql_post = "";
-
 		for($i = 0; $i < $pruned_posts; $i++)
 		{
 			$post_id = $pruned_post_list[$i]['post_id'];
 
-			if($sql_post_text != "")
+			if( $sql_post != "" )
 			{
-				$sql_post_text .= " OR ";
+				$sql_post .= ", ";
 			}
-			$sql_post_text .= "post_id = $post_id";
+			$sql_post .= $post_id;
+		}
+		$sql_post = "post_id IN (" . $sql_post . ")";
 
-			if($sql_post != "")
-			{
-				$sql_post .= " OR ";
-			}
-			$sql_post .= "post_id = $post_id";
+		$sql = "DELETE FROM " . TOPICS_TABLE . " 
+			WHERE " . $sql_topics;
+		if(!$result = $db->sql_query($sql))
+		{
+			message_die(GENERAL_ERROR, "Couldn't delete topics during prune.", "", __LINE__, __FILE__, $sql);
 		}
 
-		$sql_post_text = "DELETE FROM " . POSTS_TEXT_TABLE . " WHERE " . $sql_post_text;
-		$sql_post = "DELETE FROM " . POSTS_TABLE . " WHERE " . $sql_post;
-
-		if(!$result = $db->sql_query($sql_post_text, BEGIN_TRANSACTION))
+		$sql = "DELETE FROM " . POSTS_TABLE . " 
+			WHERE " . $sql_post;
+		if(!$result = $db->sql_query($sql, BEGIN_TRANSACTION))
 		{
-			message_die(GENERAL_ERROR, "Couldn't delete post_text during prune.", "", __LINE__, __FILE__, $sql_post_text);
+			message_die(GENERAL_ERROR, "Couldn't delete post_text during prune.", "", __LINE__, __FILE__, $sql);
 		}
 		else
 		{
-			if(!$result = $db->sql_query($sql_post, END_TRANSACTION))
+			$sql = "DELETE FROM " . POSTS_TEXT_TABLE . " 
+				WHERE " . $sql_post;
+			if(!$result = $db->sql_query($sql, END_TRANSACTION))
 			{
-				message_die(GENERAL_ERROR, "Couldn't delete post during prune.", "", __LINE__, __FILE__, $sql_post);
+				message_die(GENERAL_ERROR, "Couldn't delete post during prune.", "", __LINE__, __FILE__, $sql);
 			}
 		}
-	}
 
-	$sql = "UPDATE " . FORUMS_TABLE . "
-		SET forum_topics = forum_topics - $pruned_topics, forum_posts = forum_posts - $pruned_posts
-		WHERE forum_id = $forum_id";
-	if(!$result = $db->sql_query($sql))
+		$sql = "UPDATE " . FORUMS_TABLE . "
+			SET forum_topics = forum_topics - $pruned_topics, forum_posts = forum_posts - $pruned_posts
+			WHERE forum_id = $forum_id";
+		if(!$result = $db->sql_query($sql))
+		{
+			message_die(GENERAL_ERROR, "Couldn't update forum data after prune.", "", __LINE__, __FILE__, $sql);
+		}
+
+		$returnval = array (
+			"topics" => $pruned_topics,
+			"posts" => $pruned_posts);
+
+		return $returnval;
+	}
+	else
 	{
-		message_die(GENERAL_ERROR, "Couldn't update forum data after prune.", "", __LINE__, __FILE__, $sql);
+		return (array("topics" => 0, "posts" => 0));
 	}
-
-	$returnval = array (
-		"topics" => $pruned_topics,
-		"posts" => $pruned_posts);
-
-	return $returnval;
-
 }
 
 /***************************************************************************\
@@ -145,8 +138,6 @@ function auto_prune($forum_id = 0)
 {
 	global $db, $lang;
 
-	$one_day = 60 * 60 * 24;
-
 	$sql = "SELECT *
 		FROM " . PRUNE_TABLE . "
 		WHERE forum_id = $forum_id";
@@ -156,18 +147,21 @@ function auto_prune($forum_id = 0)
 		message_die(GENERAL_ERROR, "Auto-Prune: Couldn't read auto_prune table.", __LINE__, __FILE__);
 	}
 
-	while($row = $db->sql_fetchrow($result))
+	if( $db->sql_numrows($result) )
 	{
-		if($row['prune_freq'] > 0 && $row['prune_days'] > 0)
+		$row = $db->sql_fetchrow($result);
+
+		if( $row['prune_freq'] && $row['prune_days'] )
 		{
-			$forum_id = $row['forum_id'];
-			$prune_date = time() - ($row['prune_days'] * $one_day);
-			$pruned = prune($forum_id, $prune_date);
-			$next_prune = time() + ($row['prune_freq'] * $one_day);
-			$sql = "UPDATE " . FORUMS_TABLE . "
-						SET prune_next = $next_prune
-						WHERE forum_id = $forum_id";
-			if(!$db->sql_query($sql))
+			$prune_date = time() - ( $row['prune_days'] * 86400 );
+			prune($forum_id, $prune_date);
+
+			$next_prune = time() + ( $row['prune_freq'] * 86400 );
+
+			$sql = "UPDATE " . FORUMS_TABLE . " 
+				SET prune_next = $next_prune
+				WHERE forum_id = $forum_id";
+			if( !$db->sql_query($sql) )
 			{
 				message_die(GENERAL_ERROR, "Auto-Prune: Couldn't update forum table.", __LINE__, __FILE__);
 			}
@@ -177,4 +171,4 @@ function auto_prune($forum_id = 0)
 	return;
 }
 
-?>
+?>
\ No newline at end of file
diff --git a/phpBB/language/lang_english.php b/phpBB/language/lang_english.php
index 99ef15703a..37243dfbe0 100755
--- a/phpBB/language/lang_english.php
+++ b/phpBB/language/lang_english.php
@@ -1,6 +1,6 @@
 <?php
 /***************************************************************************
- *                           lang_english.php  -  description
+ *                               lang_english.php
  *                              -------------------
  *     begin                : Sat Dec 16 2000
  *     copyright            : (C) 2001 The phpBB Group
@@ -197,6 +197,7 @@ $lang['Display_topics'] = "Display topics from previous";
 $lang['All_Topics'] = "All Topics";
 $lang['Topic_Announcement'] = "<b>Announcement:</b>";
 $lang['Topic_Sticky'] = "<b>Sticky:</b>";
+$lang['Topic_Moved'] = "<b>Moved:</b>";
 
 //
 // Viewtopic
@@ -207,6 +208,8 @@ $lang['Guest'] = 'Guest';
 $lang['Post_subject'] = "Post subject";
 $lang['View_next_topic'] = "View next topic";
 $lang['View_previous_topic'] = "View previous topic";
+$lang['Submit_vote'] = "Submit Vote";
+$lang['View_results'] = "View Results";
 
 $lang['No_newer_topics'] = "There are no newer topics in this forum";
 $lang['No_older_topics'] = "There are no older topics in this forum";
@@ -258,16 +261,16 @@ $lang['Edit_Post'] = "Edit post";
 $lang['Post_Normal'] = "Normal";
 $lang['Post_Announcement'] = "Announcement";
 $lang['Post_Sticky'] = "Sticky";
-$lang['Topic_Moved'] = "Moved";
 $lang['Options'] = "Options";
 
 $lang['Confirm'] = "Confirm";
 $lang['Confirm_delete'] = "Are you sure you want to delete this post?";
+$lang['Confirm_delete_poll'] = "Are you sure you want to delete this poll?";
 $lang['Submit_post'] = "Submit Post";
 $lang['Preview'] = "Preview";
 $lang['Cancel_post'] = "Cancel post";
 
-$lang['Flood_Error'] = "Your last post was less then " . $board_config['flood_interval'] . " seconds ago. You must wait before you post again!";
+$lang['Flood_Error'] = "You cannot make another post so soon after your last, please try again in a short while.";
 $lang['Sorry_edit_own_posts'] = "Sorry but you can only edit your own posts";
 $lang['Empty_subject'] = "You must specifiy a subject when posting a new topic";
 $lang['Empty_message'] = "You must enter a message when posting";
@@ -279,6 +282,20 @@ $lang['No_topic_id'] = "You must select a topic to reply to";
 $lang['No_valid_mode'] = "You can only post, reply edit or quote messages, please return and try again";
 $lang['No_such_post'] = "There is no such post, please return and try again";
 
+$lang['Add_poll'] = "Add a Poll";
+$lang['Add_poll_explain'] = "If you do not want to add a poll to your topic leave the fields blank";
+$lang['Poll_question'] = "Poll question";
+$lang['Poll_option'] = "Poll option";
+$lang['Add_option'] = "Add option";
+$lang['Update'] = "Update";
+$lang['Delete'] = "Delete";
+$lang['Poll_for'] = "Run poll for";
+$lang['Poll_for_explain'] = "[ Enter 0 or leave blank for a never ending poll ]";
+$lang['Delete_poll'] = "Delete Poll";
+$lang['Empty_poll_title'] = "You must enter a title for your poll";
+$lang['To_few_poll_options'] = "You must enter at least two poll options";
+$lang['To_many_poll_options'] = "You have tried to enter too many poll options";
+
 $lang['Attach_signature'] = "Attach signature (signatures can be changed in profile)";
 $lang['Disable'] = "Disable "; // This is followed by a type, eg. HTML, Smilies, etc. and then 'on this post'
 $lang['HTML'] = "HTML";
@@ -290,8 +307,12 @@ $lang['Delete_post'] = "Delete this post";
 $lang['is_ON'] = " is ON"; // this goes after either BBCode or HTML
 $lang['is_OFF'] = " is OFF"; // see above
 
+$lang['wrote'] = "wrote"; // proceeds the username and is followed by the quoted text
+
 $lang['Stored'] = "Your message has been entered successfully";
 $lang['Deleted'] = "Your message has been deleted successfully";
+$lang['Poll_delete'] = "Your poll has been deleted successfully";
+$lang['Vote_cast'] = "Your vote has been cast";
 $lang['Click'] = "Click"; // Followed by here and then either return to topic or view message
 $lang['Here'] = "Here";
 $lang['to_return_forum'] = "to return to the forum";
@@ -610,7 +631,6 @@ $lang['New_forum'] = "New forum";
 $lang['None_selected'] = "You have no selected any topics to preform this operation on. Please go back and select at least one.";
 
 
-
 //
 // Timezones ... for display on each page
 //
@@ -744,6 +764,8 @@ $lang['Edit'] = "Edit";
 $lang['Delete'] = "Delete";
 $lang['Sticky'] = "Sticky";
 $lang['Announce'] = "Announce";
+$lang['Vote'] = "Vote";
+$lang['Pollcreate'] = "Poll create";
 
 $lang['Permissions'] = "Permissions";
 $lang['Simple_Permission'] = "Simple Permission";
@@ -837,14 +859,21 @@ $lang['group_delete'] = "Delete group";
 $lang['group_delete_check'] = "Click here to delete this group.";
 $lang['submit_group_changes'] = "Submit Changes";
 $lang['reset_group_changes'] = "Reset Changes";
+
 //
 // Prune Administration
 //
-$lang['prune_days'] = 'Remove topics that haven\'t been posted to in';
+$lang['Forum_Prune'] = "Forum Prune";
+$lang['Forum_Prune_explain'] = "This will delete any topic which has not been posted to within the number of days you select. If you do not enter a number then all topics will be deleted. It will not remove topics in which polls are still running nor will it remove announcements. You will need to remove these topics manually.";
+$lang['Do_Prune'] = "Do Prune";
+$lang['All_Forums'] = "All Forums";
+$lang['prune_days'] = "Remove topics that have not been posted to in";
+$lang['Prune_topics_not_posted'] = "Prune topics that haven't been posted to in the last";
 $lang['prune_freq'] = 'Check for topic age every';
-$lang['days'] = 'Days';
-$lang['Set_prune_data'] = "You have turned on auto-prune for this forum but did not set a frequency or number of days to prune, please go back and do so";
-
+$lang['Set_prune_data'] = "You have turned on auto-prune for this forum but did not set a frequency or number of days to prune. Please go back and do so";
+$lang['Topics_pruned'] = "Topics pruned";
+$lang['Posts_pruned'] = "Posts pruned";
+$lang['Prune_success'] = "Pruning of forums was successful";
 //
 // Word censor
 //
@@ -874,70 +903,6 @@ $lang['Compose'] = "Compose";
 // -------------------------------------------------
 // Old format ... _DON'T_add_any_ new entries here!!
 //
-// Register
-$l_mailingaddress =
-"
-	James Atkinson<br />
-	c/o 100World.com Inc.<br />
-	512-1529 West 6th Ave.<br />
-	Vancouver BC, V6J 1R1<br />
-	Canada<br />
-";
-
-$l_faxinfo = "
-	Mark Fax with:
-  ATTN: James Atkinson<br />
-	RE: Forum Registration<br />
-	<br />
-	Fax Number: +1-604-742-1770<br />
-";
-$l_coppa = "Your account has been created, however in complance with the COPPA act you must print out this page and have you parent or guardian mail it to: <br />$l_mailingaddress<br />Or fax it to: <br />$l_faxinfo<br /> Once this information has been recived your account will be activated by the administrator and you will recive and email notification.";
-$l_welcomesubj	= "Welcome to ".$board_config['sitename']." Forums";
-$l_welcomemail	= "
-$l_welcomesubj,
-
-Please keep this email for your records.
-
-
-Your account information is as follows:
-
-----------------------------
-Username: $username
-Password: $password
-----------------------------
-
-Please do not forget your password as it has been encrypted in our database and we cannot retrieve it for you.
-However, should you forget your password we provide an easy to use script to generate and email a new, random, password.
-
-Thank you for registering.
-
-";
-
-// Editpost
-// Newtopic
-$l_notifybody	= 'Dear $m[username]\r\nYou are receiving this Email because a message
-you posted on $sitename forums has been replied to, and
-you selected to be notified on this event.
-
-You may view the topic at:
-
-http://$SERVER_NAME$url_phpbb/viewtopic.$phpEx?topic=$topic&forum=$forum
-
-Or view the $sitename forum index at
-
-http://$SERVER_NAME$url_phpbb
-
-Thank you for using $sitename forums.
-
-Have a nice day.
-
-';
-
-
-// Smilies
-$l_smilesym	= "What to type";
-$l_smileemotion	= "Emotion";
-$l_smilepict	= "Picture";
 
 // Sendpasswd
 $l_wrongactiv	= "The activation key you provided is not correct. Please check email $l_message you recived and make sure you have copied the activation key exactly.";
@@ -970,4 +935,4 @@ $l_emailpass	= "Email Lost Password";
 $l_passexplain	= "Please fill out the form, a new password will be sent to your Email address";
 $l_sendpass	= "Send Password";
 
-?>
+?>
\ No newline at end of file
diff --git a/phpBB/posting.php b/phpBB/posting.php
index a9ddb08991..cd3e51e3fe 100644
--- a/phpBB/posting.php
+++ b/phpBB/posting.php
@@ -26,6 +26,90 @@ include($phpbb_root_path . 'common.'.$phpEx);
 include($phpbb_root_path . 'includes/post.'.$phpEx);
 include($phpbb_root_path . 'includes/bbcode.'.$phpEx);
 
+// -------------------------------------------
+// Do some initial checks, set basic variables,
+// etc.
+//
+
+$submit = ( isset($HTTP_POST_VARS['submit']) ) ? TRUE : 0;
+$cancel = ( isset($HTTP_POST_VARS['cancel']) ) ? TRUE : 0;
+$preview = ( isset($HTTP_POST_VARS['preview']) ) ? TRUE : 0;
+$confirm = ( isset($HTTP_POST_VARS['confirm']) ) ? TRUE : 0;
+$delete = ( isset($HTTP_POST_VARS['delete']) ) ? TRUE : 0;
+$poll_delete = ( isset($HTTP_POST_VARS['poll_delete']) ) ? TRUE : 0;
+
+$poll_add_option = ( isset($HTTP_POST_VARS['add_poll_option']) ) ? TRUE : 0;
+$poll_edit_option = ( isset($HTTP_POST_VARS['edit_poll_option']) ) ? TRUE : 0;
+$poll_delete_option = ( isset($HTTP_POST_VARS['del_poll_option']) ) ? TRUE : 0;
+
+$refresh = $preview || $poll_add_option || $poll_edit_option || $poll_delete_option;
+
+//
+// Mode, topic_id, post_id and forum_id settings
+//
+if( isset($HTTP_POST_VARS['mode']) || isset($HTTP_GET_VARS['mode']) )
+{
+	$mode = ( isset($HTTP_POST_VARS['mode']) ) ? $HTTP_POST_VARS['mode'] : $HTTP_GET_VARS['mode'];
+}
+else
+{
+	$mode = "";
+}
+
+if( isset($HTTP_GET_VARS[POST_FORUM_URL]) || isset($HTTP_POST_VARS[POST_FORUM_URL]) )
+{
+	$forum_id = (isset($HTTP_POST_VARS[POST_FORUM_URL])) ? $HTTP_POST_VARS[POST_FORUM_URL] : $HTTP_GET_VARS[POST_FORUM_URL];
+}
+else
+{
+	$forum_id = "";
+}
+
+if( isset($HTTP_GET_VARS[POST_POST_URL]) || isset($HTTP_POST_VARS[POST_POST_URL]) )
+{
+	$post_id = (isset($HTTP_POST_VARS[POST_POST_URL])) ? $HTTP_POST_VARS[POST_POST_URL] : $HTTP_GET_VARS[POST_POST_URL];
+}
+else
+{
+	$post_id = "";
+}
+
+if( isset($HTTP_GET_VARS[POST_TOPIC_URL]) || isset($HTTP_POST_VARS[POST_TOPIC_URL]) )
+{
+	$topic_id = (isset($HTTP_POST_VARS[POST_TOPIC_URL])) ? $HTTP_POST_VARS[POST_TOPIC_URL] : $HTTP_GET_VARS[POST_TOPIC_URL];
+}
+else
+{
+	$topic_id = "";
+}
+
+//
+// Was cancel pressed? If so then redirect to the appropriate
+// page, no point in continuing with any further checks
+//
+if( $cancel )
+{
+	if($post_id != "")
+	{
+		header("Location: " . append_sid("viewtopic.$phpEx?" . POST_POST_URL . "=$post_id#$post_id"));
+	}
+	else if($topic_id != "")
+	{
+		header("Location: " . append_sid("viewtopic.$phpEx?" . POST_TOPIC_URL . "=$topic_id"));
+	}
+	else if($forum_id != "")
+	{
+		header("Location: " . append_sid("viewforum.$phpEx?" . POST_FORUM_URL . "=$forum_id"));
+	}
+	else
+	{
+		header("Location: " . append_sid("index.$phpEx"));
+	}
+}
+//
+// Continue var definitions
+//
+
 //
 // Start session management
 //
@@ -36,94 +120,8 @@ init_userprefs($userdata);
 //
 
 //
-// Set initial conditions
+// Set topic type
 //
-if( isset($HTTP_GET_VARS[POST_FORUM_URL]) || isset($HTTP_POST_VARS[POST_FORUM_URL]) )
-{
-	$forum_id = (isset($HTTP_POST_VARS[POST_FORUM_URL])) ? $HTTP_POST_VARS[POST_FORUM_URL] : $HTTP_GET_VARS[POST_FORUM_URL];
-}
-else
-{
-	$forum_id = "";
-}
-if( isset($HTTP_GET_VARS[POST_POST_URL]) || isset($HTTP_POST_VARS[POST_POST_URL]) )
-{
-	$post_id = (isset($HTTP_POST_VARS[POST_POST_URL])) ? $HTTP_POST_VARS[POST_POST_URL] : $HTTP_GET_VARS[POST_POST_URL];
-}
-else
-{
-	$post_id = "";
-}
-if( isset($HTTP_GET_VARS[POST_TOPIC_URL]) || isset($HTTP_POST_VARS[POST_TOPIC_URL]) )
-{
-	$topic_id = (isset($HTTP_POST_VARS[POST_TOPIC_URL])) ? $HTTP_POST_VARS[POST_TOPIC_URL] : $HTTP_GET_VARS[POST_TOPIC_URL];
-}
-else
-{
-	$topic_id = "";
-}
-
-$mode = (isset($HTTP_POST_VARS['mode'])) ? $HTTP_POST_VARS['mode'] : ( (isset($HTTP_GET_VARS['mode'])) ? $HTTP_GET_VARS['mode'] : "");
-
-//
-// Set toggles for various options
-//
-if(!$board_config['allow_html'])
-{
-	$html_on = 0;
-}
-else
-{
-	$html_on = ( isset($HTTP_POST_VARS['submit']) || isset($HTTP_POST_VARS['preview']) ) ? ( ( !empty($HTTP_POST_VARS['disable_html']) ) ? 0 : TRUE ) : $userdata['user_allowhtml'];
-}
-
-if(!$board_config['allow_bbcode'])
-{
-	$bbcode_on = 0;
-}
-else
-{
-	$bbcode_on = ( isset($HTTP_POST_VARS['submit']) || isset($HTTP_POST_VARS['preview']) ) ? ( ( !empty($HTTP_POST_VARS['disable_bbcode']) ) ? 0 : TRUE ) : $userdata['user_allowbbcode'];
-}
-
-if(!$board_config['allow_smilies'])
-{
-	$smilies_on = 0;
-}
-else
-{
-	$smilies_on = ( isset($HTTP_POST_VARS['submit']) || isset($HTTP_POST_VARS['preview']) ) ? ( ( !empty($HTTP_POST_VARS['disable_smilies']) ) ? 0 : TRUE ) : $userdata['user_allowsmile'];
-}
-
-$attach_sig = ( isset($HTTP_POST_VARS['submit']) || isset($HTTP_POST_VARS['preview']) ) ? ( ( !empty($HTTP_POST_VARS['attach_sig']) ) ? TRUE : 0 ) : $userdata['user_attachsig'];
-
-if($mode == "reply" && !empty($topic_id) )
-{
-	if( isset($HTTP_POST_VARS['submit']) || isset($HTTP_POST_VARS['preview']) )
-	{
-		$notify = ( !empty($HTTP_POST_VARS['notify']) ) ? TRUE : 0;
-	}
-	else
-	{
-		$sql = "SELECT *
-			FROM " . TOPICS_WATCH_TABLE . "
-			WHERE topic_id = $topic_id
-				AND user_id = " . $userdata['user_id'];
-		if( !$result = $db->sql_query($sql) )
-		{
-			message_die(GENERAL_ERROR, "Couldn't obtain topic watch information", "", __LINE__, __FILE__, $sql);
-		}
-
-		$notify = ( $db->sql_numrows($result)) ? TRUE : 0;
-	}
-}
-else
-{
-	$notify = ( isset($HTTP_POST_VARS['submit']) || isset($HTTP_POST_VARS['preview']) ) ? ( ( !empty($HTTP_POST_VARS['notify']) ) ? TRUE : 0 ) : $userdata['user_notify'];
-}
-
-$preview = (isset($HTTP_POST_VARS['preview'])) ? TRUE : 0;
-
 if( isset($HTTP_POST_VARS['topictype']) )
 {
 	if($HTTP_POST_VARS['topictype']  == "announce")
@@ -144,49 +142,109 @@ else
 	$topic_type = POST_NORMAL;
 }
 
+
+//
+// Notify on reply
+//
+if($mode == "reply" && $topic_id )
+{
+	if( $submit || $refresh )
+	{
+		$notify_user = ( !empty($HTTP_POST_VARS['notify']) ) ? TRUE : 0;
+	}
+	else
+	{
+		$sql = "SELECT topic_id 
+			FROM " . TOPICS_WATCH_TABLE . "
+			WHERE topic_id = $topic_id
+				AND user_id = " . $userdata['user_id'];
+		if( !$result = $db->sql_query($sql) )
+		{
+			message_die(GENERAL_ERROR, "Couldn't obtain topic watch information", "", __LINE__, __FILE__, $sql);
+		}
+
+		$notify_user = ( $db->sql_numrows($result) ) ? TRUE : $userdata['user_notify'];
+	}
+}
+else
+{
+	$notify_user = ( $submit || $preview ) ? ( ( !empty($HTTP_POST_VARS['notify']) ) ? TRUE : 0 ) : $userdata['user_notify'];
+}
+
+//
+// Set toggles for various options
+//
+if( !$board_config['allow_html'] )
+{
+	$html_on = 0;
+}
+else
+{
+	$html_on = ( $submit || $refresh ) ? ( ( !empty($HTTP_POST_VARS['disable_html']) ) ? 0 : TRUE ) : $userdata['user_allowhtml'];
+}
+
+if( !$board_config['allow_bbcode'] )
+{
+	$bbcode_on = 0;
+}
+else
+{
+	$bbcode_on = ( $submit || $refresh ) ? ( ( !empty($HTTP_POST_VARS['disable_bbcode']) ) ? 0 : TRUE ) : $userdata['user_allowbbcode'];
+}
+
+if( !$board_config['allow_smilies'] )
+{
+	$smilies_on = 0;
+}
+else
+{
+	$smilies_on = ( $submit || $refresh ) ? ( ( !empty($HTTP_POST_VARS['disable_smilies']) ) ? 0 : TRUE ) : $userdata['user_allowsmile'];
+}
+
+$attach_sig = ( $submit || $refresh ) ? ( ( !empty($HTTP_POST_VARS['attach_sig']) ) ? TRUE : 0 ) : $userdata['user_attachsig'];
+
 //
 // Here we do various lookups to find topic_id, forum_id, post_id etc.
 // Doing it here prevents spoofing (eg. faking forum_id, topic_id or post_id
 //
 if( $mode != "newtopic" )
 {
-	if($mode == "reply" || $mode == "quote")
+	if( $mode == "reply" || $mode == "quote" || $mode == "vote" )
 	{
-		if($mode == "reply" && !empty($topic_id) )
+		if( ( $mode == "reply" || $mode == "vote" ) && $topic_id )
 		{
-			$sql = "SELECT f.forum_id, f.forum_status, t.topic_status
+			$sql = "SELECT f.forum_id, f.forum_status, f.forum_name, t.topic_status
 				FROM " . FORUMS_TABLE . " f, " . TOPICS_TABLE . " t
 				WHERE t.topic_id = $topic_id
 					AND f.forum_id = t.forum_id";
-
-			$msg = $lang['No_topic_id'];
 		}
-		else if( !empty($post_id) )
+		else if( $mode == "quote" && $post_id )
 		{
-			$sql = "SELECT f.forum_id, f.forum_status, t.topic_id, t.topic_status
+			$sql = "SELECT f.forum_id, f.forum_status, f.forum_name, t.topic_id, t.topic_status
 				FROM " . POSTS_TABLE . " p, " . TOPICS_TABLE . " t, " . FORUMS_TABLE . " f
 				WHERE p.post_id = $post_id
 					AND t.topic_id = p.topic_id
 					AND f.forum_id = t.forum_id";
-
-			$msg = $lang['No_post_id'];
 		}
 		else
 		{
-			message_die(GENERAL_MESSAGE, $msg);
+			$message = ( $mode == "quote" ) ? $lang['No_post_id'] : $lang['No_topic_id'];
+			message_die(GENERAL_MESSAGE, $message);
 		}
 	}
-	else if($mode == "editpost")
+	else if( $mode == "editpost" )
 	{
-		if( isset($post_id) )
+		if( $post_id )
 		{
-			$sql = "SELECT p.post_id, t.forum_id, t.topic_status, t.topic_last_post_id, f.forum_last_post_id, f.forum_status
-				FROM " . POSTS_TABLE . " p, " . TOPICS_TABLE . " t, " . FORUMS_TABLE . " f
-				WHERE t.topic_id = $topic_id
-					AND p.topic_id = t.topic_id
+			$sql = "SELECT p2.post_id, t.topic_id, t.topic_status, t.topic_last_post_id, t.topic_vote, f.forum_id, f.forum_name, f.forum_status, f.forum_last_post_id 
+				FROM " . POSTS_TABLE . " p, " . POSTS_TABLE . " p2, " . TOPICS_TABLE . " t, " . FORUMS_TABLE . " f
+				WHERE p.post_id = $post_id 
+					AND p2.topic_id = p.topic_id 
+					AND t.topic_id = p.topic_id
 					AND f.forum_id = t.forum_id
-				ORDER BY p.post_time ASC
+				ORDER BY p2.post_time ASC
 				LIMIT 1";
+
 		}
 		else
 		{
@@ -198,29 +256,68 @@ if( $mode != "newtopic" )
 		message_die(GENERAL_MESSAGE, $lang['No_valid_mode']);
 	}
 
-	if($result = $db->sql_query($sql))
+	if( $result = $db->sql_query($sql) )
 	{
 		$check_row = $db->sql_fetchrow($result);
 
 		$forum_id = $check_row['forum_id'];
+
+		$forum_name = $check_row['forum_name'];
 		$topic_status = $check_row['topic_status'];
 		$forum_status = $check_row['forum_status'];
 
 		if( $mode == "editpost" )
 		{
-			$is_first_post = ($check_row['post_id'] == $post_id) ? TRUE : 0;
-			$is_last_post = ($check_row['topic_last_post_id'] == $post_id) ? TRUE : 0;
+			$topic_id = $check_row['topic_id'];
+
+			$is_first_post_topic = ($check_row['post_id'] == $post_id) ? TRUE : 0;
+			$is_last_post_topic = ($check_row['topic_last_post_id'] == $post_id) ? TRUE : 0;
 			$is_last_post_forum = ($check_row['forum_last_post_id'] == $post_id) ? TRUE : 0;
+
+			$post_has_poll = ($check_row['topic_vote']) ? TRUE : 0;
+
+			if( $is_first_post_topic && $post_has_poll )
+			{
+				$sql = "SELECT vd.vote_id, vr.vote_result 
+					FROM " . VOTE_DESC_TABLE . " vd, " . VOTE_RESULTS_TABLE . " vr 
+					WHERE vd.topic_id = $topic_id 
+						AND vr.vote_id = vd.vote_id";
+				if( !$result = $db->sql_query($sql) )
+				{
+					message_die(GENERAL_ERROR, "Couldn't obtain vote data for this topic", "", __LINE__, __FILE__, $sql);
+				}
+
+				if( $vote_rows = $db->sql_numrows($result) )
+				{
+					$rowset = $db->sql_fetchrowset($result);
+
+					$vote_id = $rowset[0]['vote_id'];
+			
+					$vote_results_sum = 0;
+					for($i = 0; $i < $vote_rows; $i++ )
+					{
+						$vote_results_sum += $rowset[$i]['vote_result'];
+					}
+
+					$can_edit_poll = ( !$vote_results_sum ) ? TRUE : 0;
+				}
+			}
+			else
+			{
+				$can_edit_poll = 0;
+			}
 		}
 		else
 		{
-			if($mode == "quote")
+			if( $mode == "quote" )
 			{
 				$topic_id = $check_row['topic_id'];
 			}
 
-			$is_first_post = 0;
-			$is_last_post = 0;
+			$is_first_post_topic = 0;
+			$is_last_post_topic = 0;
+			$post_has_poll = 0;
+			$can_edit_poll = 0;
 		}
 	}
 	else
@@ -230,17 +327,22 @@ if( $mode != "newtopic" )
 }
 else
 {
-	$sql = "SELECT forum_status
-		FROM " . FORUMS_TABLE . " f
+	$sql = "SELECT forum_name, forum_status
+		FROM " . FORUMS_TABLE . " 
 		WHERE forum_id = $forum_id";
-	if($result = $db->sql_query($sql))
+	if( $result = $db->sql_query($sql) )
 	{
 		$check_row = $db->sql_fetchrow($result);
 
-		$is_first_post = TRUE;
-		$is_last_post = 0;
+		$forum_status = $check_row['forum_status']; 
+		$forum_name = $check_row['forum_name'];
 		$topic_status = TOPIC_UNLOCKED;
-		$forum_status = $check_row['forum_status'];
+
+		$is_first_post_topic = TRUE;
+		$is_last_post_topic = 0;
+		$post_has_poll = 0;
+		$can_edit_poll = 0;
+
 	}
 	else
 	{
@@ -251,11 +353,11 @@ else
 //
 // Is topic or forum locked?
 //
-if($forum_status == FORUM_LOCKED)
+if( $forum_status == FORUM_LOCKED )
 {
 	message_die(GENERAL_MESSAGE, $lang['Forum_locked']);
 }
-else if($topic_status == TOPIC_LOCKED)
+else if( $topic_status == TOPIC_LOCKED )
 {
 	message_die(GENERAL_MESSAGE, $lang['Topic_locked']);
 }
@@ -263,140 +365,113 @@ else if($topic_status == TOPIC_LOCKED)
 //
 // Auth checks
 //
-switch($mode)
+$auth_type = AUTH_ALL;
+switch( $mode )
 {
 	case 'newtopic':
-		if($topic_type == POST_ANNOUNCE)
+		if( $topic_type == POST_ANNOUNCE )
 		{
-			$auth_type = AUTH_ANNOUNCE;
 			$is_auth_type = "auth_announce";
 			$auth_string = $lang['can_post_announcements'];
 		}
-		else if($topic_type == POST_STICKY)
+		else if( $topic_type == POST_STICKY )
 		{
-			$auth_type = AUTH_STICKY;
 			$is_auth_type = "auth_sticky";
 			$auth_string = $lang['can_post_sticky_topics'];
 		}
 		else
 		{
-			$auth_type = AUTH_ALL;
 			$is_auth_type = "auth_post";
 			$auth_string = $lang['can_post_new_topics'];
 		}
 		break;
+
 	case 'reply':
-		$auth_type = AUTH_ALL;
-		$is_auth_type = "auth_reply";
-		$auth_string = $lang['can_reply_to_topics'];
-		break;
 	case 'quote':
-		$auth_type = AUTH_ALL;
 		$is_auth_type = "auth_reply";
 		$auth_string = $lang['can_reply_to_topics'];
 		break;
+
 	case 'editpost':
-		$auth_type = AUTH_ALL;
 		$is_auth_type = "auth_edit";
 		$auth_string = $lang['can_edit_topics'];
 		break;
+
 	case 'delete':
-		$auth_type = AUTH_DELETE;
 		$is_auth_type = "auth_delete";
 		$auth_string = $lang['can_delete_topics'];
 		break;
+
+	case 'vote':
+		$is_auth_type = "auth_vote";
+		$auth_string = $lang['can_vote'];
+		break;
+
 	default:
-		$auth_type = AUTH_ALL;
-		$is_auth_type = "auth_all";
-		$auth_string = $lang['can_post_new_topics'];
+		message_die(GENERAL_MESSAGE, $lang['No_post_mode']);
 		break;
 }
 
+//
+// Do required auth check
+//
 $is_auth = auth($auth_type, $forum_id, $userdata);
 
-if(!$is_auth[$is_auth_type])
+//
+// The user is not authed, if they're not logged in then redirect
+// them, else show them an error message
+//
+if( !$is_auth[$is_auth_type] )
 {
-	//
-	// The user is not authed
-	//
-	if(!$userdata['session_logged_in'])
+	if( !$userdata['session_logged_in'] )
 	{
-		if($mode == "newtopic")
+		switch( $mode )
 		{
-			$redirect = "mode=newtopic&" . POST_FORUM_URL . "=$forum_id";
-		}
-		else if($mode == "reply")
-		{
-			$redirect = "mode=reply&" . POST_TOPIC_URL . "=$topic_id";
-		}
-		else if($mode == "quote")
-		{
-			$redirect = "mode=quote&" . POST_POST_URL ."=$post_id";
-		}
-		else if($mode == "editpost")
-		{
-			$redirect = "mode=editpost&" . POST_POST_URL ."=$post_id&" . POST_TOPIC_URL . "=$topic_id";
+			case 'newtopic':
+				$redirect = "mode=newtopic&" . POST_FORUM_URL . "=$forum_id";
+				break;
+			case 'reply':
+				$redirect = "mode=reply&" . POST_TOPIC_URL . "=$topic_id";
+				break;
+			case 'quote':
+				$redirect = "mode=quote&" . POST_POST_URL ."=$post_id";
+				break;
+			case 'editpost':
+				$redirect = "mode=editpost&" . POST_POST_URL ."=$post_id&" . POST_TOPIC_URL . "=$topic_id";
+				break;
 		}
 
-		header("Location: login.$phpEx?forward_page=posting.$phpEx&" . $redirect);
+		header("Location: " . append_sid("login.$phpEx?forward_page=posting.$phpEx&" . $redirect));
 
 	}
 	else
 	{
-		$msg = $lang['Sorry_auth'] . $is_auth[$is_auth_type . "_type"] . $auth_string . $lang['this_forum'];
+		$message = $lang['Sorry_auth'] . $is_auth[$is_auth_type . "_type"] . $auth_string . $lang['this_forum'];
 	}
 
-	message_die(GENERAL_MESSAGE, $msg);
+	message_die(GENERAL_MESSAGE, $message);
 }
 //
 // End Auth
 //
 
 //
-// Clear error check
-//
-$error = 0;
-$error_msg = "";
+// End variable checks and definitions
+// -----------------------------------
 
+
+// -------------------------------------------------------
+// All initial checks complete, we can not start the major
+// posting related code
 //
-// Prepare our message and subject on a 'submit' (inc. preview)
-//
-if( ( isset($HTTP_POST_VARS['submit']) || $preview ) && $topic_status == TOPIC_UNLOCKED )
+
+if( $submit && $mode != "vote" )
 {
-
-	//
-	// Flood control
-	//
-	if($mode != 'editpost' && !$preview)
+	if( isset($HTTP_POST_VARS['username']) )
 	{
-		$sql = "SELECT MAX(post_time) AS last_post_time
-			FROM " . POSTS_TABLE . "
-			WHERE poster_ip = '$user_ip'";
-		if($result = $db->sql_query($sql))
-		{
-			$db_row = $db->sql_fetchrow($result);
+		$post_username = trim(strip_tags($HTTP_POST_VARS['username']));
 
-			$last_post_time = $db_row['last_post_time'];
-			$current_time = get_gmt_ts();
-
-			if(($current_time - $last_post_time) < $board_config['flood_interval'])
-			{
-				$error = TRUE;
-				$error_msg = $lang['Flood_Error'];
-			}
-		}
-	}
-	//
-	// End Flood control
-	//
-
-	//
-	// Handle anon posting with usernames
-	//
-	if(isset($HTTP_POST_VARS['username']))
-	{
-		$username = trim(strip_tags(htmlspecialchars($HTTP_POST_VARS['username'])));
-		if(!validate_username(stripslashes($username)))
+		if( !validate_username(stripslashes($post_username)) )
 		{
 			$error = TRUE;
 			if(!empty($error_msg))
@@ -408,44 +483,36 @@ if( ( isset($HTTP_POST_VARS['submit']) || $preview ) && $topic_status == TOPIC_U
 	}
 	else
 	{
-		$username = "";
+		$post_username = "";
 	}
 
-	$subject = trim(strip_tags(htmlspecialchars($HTTP_POST_VARS['subject'])));
-	if($mode == 'newtopic' && empty($subject))
+	$post_subject = trim(strip_tags($HTTP_POST_VARS['subject']));
+	if( $mode == 'newtopic' && empty($post_subject) )
 	{
 		$error = TRUE;
-		if(!empty($error_msg))
+		if( !empty($error_msg) )
 		{
 			$error_msg .= "<br />";
 		}
 		$error_msg .= $lang['Empty_subject'];
 	}
 
-	if(!empty($HTTP_POST_VARS['message']))
+	if( !empty($HTTP_POST_VARS['message']) )
 	{
-		if(!$error && !$preview)
+		if( !$error )
 		{
-			if($bbcode_on)
+			if( $bbcode_on )
 			{
 				$bbcode_uid = make_bbcode_uid();
 			}
 
-			//
-			// prepare_message returns a bbcode parsed html parsed and slashed result
-			// ... note that we send NOT'ed version of the disable vars to the function
-			//
-			$message = prepare_message(stripslashes($HTTP_POST_VARS['message']), $html_on, $bbcode_on, $smilies_on, $bbcode_uid);
+			$post_message = prepare_message($HTTP_POST_VARS['message'], $html_on, $bbcode_on, $smilies_on, $bbcode_uid);
 
 			if( $attach_sig )
 			{
-				$message .= (ereg(" $", $message)) ? "[addsig]" : " [addsig]";
+				$post_message .= (ereg(" $", $post_message)) ? "[addsig]" : " [addsig]";
 			}
 		}
-		else
-		{
-			$message = stripslashes(trim($HTTP_POST_VARS['message']));
-		}
 	}
 	else
 	{
@@ -456,31 +523,116 @@ if( ( isset($HTTP_POST_VARS['submit']) || $preview ) && $topic_status == TOPIC_U
 		}
 		$error_msg .= $lang['Empty_message'];
 	}
+
+	//
+	// Handle poll stuff
+	//
+	$topic_vote = 0;
+
+	if( $mode == "newtopic" || $mode == "editpost" )
+	{
+		if( $is_auth['auth_pollcreate'] && $is_first_post_topic )
+		{
+			$poll_title = ( isset($HTTP_POST_VARS['poll_title']) ) ? trim(strip_tags($HTTP_POST_VARS['poll_title'])) : "";
+			$poll_length = ( isset($HTTP_POST_VARS['poll_length']) ) ? intval($HTTP_POST_VARS['poll_length']) : 0;
+			if( $poll_length < 0 )
+			{
+				$poll_length = 0;
+			}
+
+			$poll_options = 0;
+			$poll_option_list = array();
+			if( isset($HTTP_POST_VARS['poll_option_text']) )
+			{
+				while( list($option_id, $option_text) = each($HTTP_POST_VARS['poll_option_text']) )
+				{
+					$poll_option_list[$option_id] = trim(strip_tags($option_text));
+					$poll_options++;
+				}
+			}
+
+			if( $poll_title == "" && $poll_options )
+			{
+				$error = TRUE;
+				if(!empty($error_msg))
+				{
+					$error_msg .= "<br />";
+				}
+				$error_msg .= $lang['Empty_poll_title']; 
+			}
+
+			if( $poll_title != "" )
+			{
+				if( $poll_options < 2 )
+				{
+					$error = TRUE;
+					if(!empty($error_msg))
+					{
+						$error_msg .= "<br />";
+					}
+					$error_msg .= $lang['To_few_poll_options']; 
+				}
+				else if( $poll_options > $board_config['max_poll_options'] )
+				{
+					$error = TRUE;
+					if(!empty($error_msg))
+					{
+						$error_msg .= "<br />";
+					}
+					$error_msg .= $lang['To_many_poll_options']; 
+				}
+			}
+
+			if( $poll_title != "" && $poll_options >= 2 && $poll_options <= $board_config['max_poll_options'] )
+			{
+				$topic_vote = 1;
+				$sql_topic_vote_edit = ", topic_vote = 1";
+			}
+		}
+	}
 }
 
 //
-// If submitted then update tables
-// according to the mode
+// Submit or confirm ... big chunk of code ... can probably be
+// still further reduced, will look at it later, possibly for
+// 2.2
 //
-if( ($mode == "newtopic" || $mode == "reply") && $topic_status == TOPIC_UNLOCKED)
+if( ( $submit || $confirm ) && !$error )
 {
-	$page_title = ($mode == "newtopic") ? " " . $lang['Post_new_topic'] : " " . $lang['Post_reply'];
-	$section_title = ($mode == "newtopic") ? $lang['Post_new_topic_in'] : " " . $Lang['Post_reply_to'];
+	$current_time = time();
 
-	if(isset($HTTP_POST_VARS['submit']) && !$error && !$preview)
+	//
+	// Which mode was selected?
+	//
+	if( $mode == "newtopic" || $mode == "reply" )
 	{
-		$topic_time = get_gmt_ts();
-
-		if($mode == "reply")
+		//
+		// Flood control
+		//
+		$sql = "SELECT MAX(post_time) AS last_post_time
+			FROM " . POSTS_TABLE . "
+			WHERE poster_ip = '$user_ip'";
+		if($result = $db->sql_query($sql))
 		{
-			$new_topic_id = $topic_id;
+			$db_row = $db->sql_fetchrow($result);
+
+			$last_post_time = $db_row['last_post_time'];
+
+			if( ($current_time - $last_post_time) < $board_config['flood_interval'] )
+			{
+				message_die(GENERAL_MESSAGE, $lang['Flood_Error']);
+			}
 		}
-		else if($mode == "newtopic")
-		{
-			$sql  = "INSERT INTO " . TOPICS_TABLE . " (topic_title, topic_poster, topic_time, forum_id, topic_status, topic_type)
-				VALUES ('$subject', " . $userdata['user_id'] . ", " . $topic_time . ", $forum_id, " . TOPIC_UNLOCKED . ", $topic_type)";
+		//
+		// End Flood control
+		//
 
-			if($result = $db->sql_query($sql, BEGIN_TRANSACTION))
+		if( $mode == "newtopic" )
+		{
+			$sql  = "INSERT INTO " . TOPICS_TABLE . " (topic_title, topic_poster, topic_time, forum_id, topic_status, topic_type, topic_vote)
+				VALUES ('$subject', " . $userdata['user_id'] . ", $current_time, $forum_id, " . TOPIC_UNLOCKED . ", $topic_type, $topic_vote)";
+
+			if( $result = $db->sql_query($sql, BEGIN_TRANSACTION) )
 			{
 				$new_topic_id = $db->sql_nextid();
 			}
@@ -488,157 +640,184 @@ if( ($mode == "newtopic" || $mode == "reply") && $topic_status == TOPIC_UNLOCKED
 			{
 				message_die(GENERAL_ERROR, "Error inserting data into topics table", "", __LINE__, __FILE__, $sql);
 			}
+
+			//
+			// Handle poll ...
+			//
+			if( $is_auth['auth_pollcreate'] && $topic_vote )
+			{
+				$sql = "INSERT INTO " . VOTE_DESC_TABLE . " (topic_id, vote_text, vote_start, vote_length) 
+					VALUES ($new_topic_id, '$poll_title', $current_time, " . ( $poll_length * 86400 ) . ")";
+				if( $result = $db->sql_query($sql) )
+				{
+					$new_vote_id = $db->sql_nextid();
+
+					$poll_option_id = 1;
+					while( list($option_id, $option_text) = each($poll_option_list) )
+					{
+						$sql = "INSERT INTO " . VOTE_RESULTS_TABLE . " (vote_id, vote_option_id, vote_option_text, vote_result)
+							VALUES ($new_vote_id, $poll_option_id, '$option_text', 0)";
+						if( !$result = $db->sql_query($sql) )
+						{
+							// Rollback ...
+							if(SQL_LAYER == "mysql")
+							{
+								$sql_del_t = "DELETE FROM " . TOPICS_TABLE . " 
+									WHERE topic_id = $topic_id";
+								$db->sql_query($sql_del_t);
+								$sql_del_v = "DELETE FROM " . VOTE_DESC_TABLE . " 
+									WHERE vote_id = $new_vote_id";
+								$db->sql_query($sql_del_v);
+							}
+							message_die(GENERAL_ERROR, "Couldn't insert new poll options", "", __LINE__, __FILE__, $sql);
+						}
+						$poll_option_id++;
+					}
+				}
+				else
+				{
+					if(SQL_LAYER == "mysql")
+					{
+						// Rollback ...
+						$sql_del_t = "DELETE FROM " . TOPICS_TABLE . " 
+							WHERE topic_id = $topic_id";
+						$db->sql_query($sql_del_t);
+					}
+					message_die(GENERAL_ERROR, "Couldn't insert new poll information", "", __LINE__, __FILE__, $sql);
+				}
+			}
+		}
+		else
+		{
+			$new_topic_id = $topic_id;
 		}
 
-		if($mode == "reply" || ( $mode == "newtopic" && $result ) )
+		$sql = "INSERT INTO " . POSTS_TABLE . " (topic_id, forum_id, poster_id, post_username, post_time, poster_ip, bbcode_uid, enable_bbcode, enable_html, enable_smilies)
+			VALUES ($new_topic_id, $forum_id, " . $userdata['user_id'] . ", '$post_username', $current_time, '$user_ip', '$bbcode_uid', $bbcode_on, $html_on, $smilies_on)";
+		$result = ($mode == "reply") ? $db->sql_query($sql, BEGIN_TRANSACTION) : $db->sql_query($sql);
+
+		if($result)
 		{
-			$sql = "INSERT INTO " . POSTS_TABLE . " (topic_id, forum_id, poster_id, post_username, post_time, poster_ip, bbcode_uid, enable_bbcode, enable_html, enable_smilies)
-				VALUES ($new_topic_id, $forum_id, " . $userdata['user_id'] . ", '$username', $topic_time, '$user_ip', '$bbcode_uid', $bbcode_on, $html_on, $smilies_on)";
-			if($mode == "reply")
-			{
-				$result = $db->sql_query($sql, BEGIN_TRANSACTION);
-			}
-			else
-			{
-				$result = $db->sql_query($sql);
-			}
+			$new_post_id = $db->sql_nextid();
 
-			if($result)
-			{
-				$new_post_id = $db->sql_nextid();
+			$sql = "INSERT INTO " . POSTS_TEXT_TABLE . " (post_id, post_subject, post_text)
+				VALUES ($new_post_id, '$post_subject', '$post_message')";
 
-				$sql = "INSERT INTO " . POSTS_TEXT_TABLE . " (post_id, post_subject, post_text)
-					VALUES ($new_post_id, '$subject', '$message')";
+			if($db->sql_query($sql))
+			{
+				$sql = "UPDATE " . TOPICS_TABLE . "
+					SET topic_last_post_id = $new_post_id";
+				if($mode == "reply")
+				{
+					$sql .= ", topic_replies = topic_replies + 1 ";
+				}
+				$sql .= " WHERE topic_id = $new_topic_id";
 
 				if($db->sql_query($sql))
 				{
-					$sql = "UPDATE " . TOPICS_TABLE . "
-						SET topic_last_post_id = $new_post_id";
-					if($mode == "reply")
+					$sql = "UPDATE " . FORUMS_TABLE . "
+						SET forum_last_post_id = $new_post_id, forum_posts = forum_posts + 1";
+					if($mode == "newtopic")
 					{
-						$sql .= ", topic_replies = topic_replies + 1 ";
+						$sql .= ", forum_topics = forum_topics + 1";
 					}
-					$sql .= " WHERE topic_id = $new_topic_id";
+					$sql .= " WHERE forum_id = $forum_id";
 
 					if($db->sql_query($sql))
 					{
-						$sql = "UPDATE " . FORUMS_TABLE . "
-							SET forum_last_post_id = $new_post_id, forum_posts = forum_posts + 1";
-						if($mode == "newtopic")
-						{
-							$sql .= ", forum_topics = forum_topics + 1";
-						}
-						$sql .= " WHERE forum_id = $forum_id";
+						$sql = "UPDATE " . USERS_TABLE . "
+							SET user_posts = user_posts + 1
+							WHERE user_id = " . $userdata['user_id'];
 
-						if($db->sql_query($sql))
+						if($db->sql_query($sql, END_TRANSACTION))
 						{
-							$sql = "UPDATE " . USERS_TABLE . "
-								SET user_posts = user_posts + 1
-								WHERE user_id = " . $userdata['user_id'];
-
-							if($db->sql_query($sql, END_TRANSACTION))
+							//
+							// Email users who are watching this topic
+							//
+							if($mode == "reply")
 							{
-								setcookie('phpbb2_' . $forum_id . '_' . $new_topic_id, '', time() - 1, $cookiepath, $cookiedomain, $cookiesecure);
-
-								//
-								// Email users who are watching this topic
-								//
-								if($mode == "reply")
+								$sql = "SELECT u.user_id, u.username, u.user_email, t.topic_title
+									FROM " . TOPICS_WATCH_TABLE . " tw, " . TOPICS_TABLE . " t, " . USERS_TABLE . " u
+									WHERE tw.topic_id = $new_topic_id
+										AND tw.user_id NOT IN (" . $userdata['user_id'] . ", " . ANONYMOUS . " ) 
+										AND tw.notify_status = " . TOPIC_WATCH_UN_NOTIFIED . "
+										AND t.topic_id = tw.topic_id
+										AND u.user_id = tw.user_id";
+								if( $result = $db->sql_query($sql) )
 								{
-									$sql = "SELECT u.user_id, u.username, u.user_email, t.topic_title
-										FROM " . TOPICS_WATCH_TABLE . " tw, " . TOPICS_TABLE . " t, " . USERS_TABLE . " u
-										WHERE tw.topic_id = $new_topic_id
-											AND tw.user_id <> " . $userdata['user_id'] . "
-											AND tw.user_id <> " . ANONYMOUS . "
-											AND tw.notify_status = " . TOPIC_WATCH_UN_NOTIFIED . "
-											AND t.topic_id = tw.topic_id
-											AND u.user_id = tw.user_id";
-									if( $result = $db->sql_query($sql) )
+									$email_set = $db->sql_fetchrowset($result);
+									$update_watched_sql = "";
+
+									for($i = 0; $i < count($email_set); $i++)
 									{
-										$email_set = $db->sql_fetchrowset($result);
-										$update_watched_sql = "";
-
-										for($i = 0; $i < count($email_set); $i++)
+										if( $email_set[$i]['user_email'] != "")
 										{
-											if($email_set[$i]['user_email'] != "")
+											$email_headers = "From: " . $board_config['board_email_from'] . "\nReturn-Path: " . $board_config['board_email_from'] . "\r\n";
+
+											$emailer->use_template("topic_notify");
+											$emailer->email_address($email_set[$i]['user_email']);
+											$emailer->set_subject($lang['Topic_reply_notification']);
+											$emailer->extra_headers($email_headers);
+
+											$path = (dirname($HTTP_SERVER_VARS['REQUEST_URI']) == "/") ? "" : dirname($HTTP_SERVER_VARS['REQUEST_URI']);
+
+											$emailer->assign_vars(array(
+												"USERNAME" => $email_set[$i]['username'],
+												"SITENAME" => $board_config['sitename'],
+												"TOPIC_TITLE" => $email_set[$i]['topic_title'],
+												"TOPIC_URL" => "http://" . $HTTP_SERVER_VARS['SERVER_NAME'] . $path . "/viewtopic.$phpEx?" . POST_POST_URL . "=$new_post_id#$new_post_id",
+												"UN_WATCH_URL" => "http://" . $HTTP_SERVER_VARS['SERVER_NAME'] . $path . "/viewtopic.$phpEx?" . POST_TOPIC_URL . "=$new_topic_id&unwatch=topic",
+												"EMAIL_SIG" => $board_config['board_email'])
+											);
+
+											$emailer->send();
+											$emailer->reset();
+
+											if($update_watched_sql != "")
 											{
-												$email_headers = "From: " . $board_config['board_email_from'] . "\nReturn-Path: " . $board_config['board_email_from'] . "\r\n";
-
-												$emailer->use_template("topic_notify");
-												$emailer->email_address($email_set[$i]['user_email']);
-												$emailer->set_subject($lang['Topic_reply_notification']);
-												$emailer->extra_headers($email_headers);
-
-												$path = (dirname($HTTP_SERVER_VARS['REQUEST_URI']) == "/") ? "" : dirname($HTTP_SERVER_VARS['REQUEST_URI']);
-
-												$emailer->assign_vars(array(
-													"USERNAME" => $email_set[$i]['username'],
-													"SITENAME" => $board_config['sitename'],
-													"TOPIC_TITLE" => $email_set[$i]['topic_title'],
-													"TOPIC_URL" => "http://" . $HTTP_SERVER_VARS['SERVER_NAME'] . $path . "/viewtopic.$phpEx?" . POST_POST_URL . "=$new_post_id#$new_post_id",
-													"UN_WATCH_URL" => "http://" . $HTTP_SERVER_VARS['SERVER_NAME'] . $path . "/viewtopic.$phpEx?" . POST_TOPIC_URL . "=$new_topic_id&unwatch=topic",
-													"EMAIL_SIG" => $board_config['board_email'])
-												);
-
-												$emailer->send();
-												$emailer->reset();
-
-												if($update_watched_sql != "")
-												{
-													$update_watched_sql .= " OR ";
-												}
-												$update_watched_sql .= "user_id = " . $email_set[$i]['user_id'];
+												$update_watched_sql .= ", ";
 											}
-										}
-
-										if($update_watched_sql != "")
-										{
-											$sql = "UPDATE " . TOPICS_WATCH_TABLE . "
-												SET notify_status = " . TOPIC_WATCH_NOTIFIED . "
-												WHERE topic_id = $new_topic_id
-													AND $update_watched_sql";
-											$db->sql_query($sql);
+											$update_watched_sql .= $email_set[$i]['user_id'];
 										}
 									}
-								}
 
-								//
-								// Handle notification request ... not complete
-								// only fully functional for new posts
-								//
-								if( isset($notify) )
-								{
-									if($mode == "reply")
+									if($update_watched_sql != "")
 									{
-										$sql = "SELECT *
-											FROM " . TOPICS_WATCH_TABLE . "
+										$sql = "UPDATE " . TOPICS_WATCH_TABLE . "
+											SET notify_status = " . TOPIC_WATCH_NOTIFIED . "
 											WHERE topic_id = $new_topic_id
-												AND user_id = " . $userdata['user_id'];
-										if( !$result = $db->sql_query($sql) )
-										{
-											message_die(GENERAL_ERROR, "Couldn't obtain topic watch information", "", __LINE__, __FILE__, $sql);
-										}
+												AND user_id IN ($update_watched_sql)";
+										$db->sql_query($sql);
+									}
+								}
+							}
 
-										if( $db->sql_numrows($result))
+							//
+							// Handle notification request ... 
+							//
+							if( isset($notify) )
+							{
+								if($mode == "reply")
+								{
+									$sql = "SELECT *
+										FROM " . TOPICS_WATCH_TABLE . "
+										WHERE topic_id = $new_topic_id
+											AND user_id = " . $userdata['user_id'];
+									if( !$result = $db->sql_query($sql) )
+									{
+										message_die(GENERAL_ERROR, "Couldn't obtain topic watch information", "", __LINE__, __FILE__, $sql);
+									}
+
+									if( $db->sql_numrows($result) )
+									{
+										if( !$notify )
 										{
-											if( !$notify )
-											{
-												$sql = "DELETE FROM " . TOPICS_WATCH_TABLE . "
-													WHERE topic_id = $new_topic_id
-														AND user_id = " . $userdata['user_id'];
-												if( !$result = $db->sql_query($sql) )
-												{
-													message_die(GENERAL_ERROR, "Couldn't delete topic watch information", "", __LINE__, __FILE__, $sql);
-												}
-											}
-										}
-										else if( $notify )
-										{
-											$sql = "INSERT INTO " . TOPICS_WATCH_TABLE . " (user_id, topic_id, notify_status)
-												VALUES (" . $userdata['user_id'] . ", $new_topic_id, 0)";
+											$sql = "DELETE FROM " . TOPICS_WATCH_TABLE . "
+												WHERE topic_id = $new_topic_id
+													AND user_id = " . $userdata['user_id'];
 											if( !$result = $db->sql_query($sql) )
 											{
-												message_die(GENERAL_ERROR, "Couldn't insert topic watch information", "", __LINE__, __FILE__, $sql);
+												message_die(GENERAL_ERROR, "Couldn't delete topic watch information", "", __LINE__, __FILE__, $sql);
 											}
 										}
 									}
@@ -652,152 +831,101 @@ if( ($mode == "newtopic" || $mode == "reply") && $topic_status == TOPIC_UNLOCKED
 										}
 									}
 								}
-
-								//
-								// If we get here the post has been inserted successfully.
-								//
-								$msg = $lang['Stored'] . "<br /><br />" . $lang['Click'] . " <a href=\"" . append_sid("viewtopic.$phpEx?" . POST_POST_URL . "=$new_post_id") . "#$new_post_id\">" . $lang['Here'] . "</a> " . $lang['to_view_message'] . "<br /><br />" . $lang['Click'] . " <a href=\"" . append_sid("viewforum.$phpEx?" . POST_FORUM_URL . "=$forum_id") . "\">" . $lang['Here'] . "</a> ". $lang['to_return_forum'];
-
-								message_die(GENERAL_MESSAGE, $msg);
-							}
-							else
-							{
-								if(SQL_LAYER == "mysql")
+								else if( $notify )
 								{
+									$sql = "INSERT INTO " . TOPICS_WATCH_TABLE . " (user_id, topic_id, notify_status)
+										VALUES (" . $userdata['user_id'] . ", $new_topic_id, 0)";
+									if( !$result = $db->sql_query($sql) )
+									{
+										message_die(GENERAL_ERROR, "Couldn't insert topic watch information", "", __LINE__, __FILE__, $sql);
+									}
 								}
-								message_die(GENERAL_ERROR, "Error updating users table", "", __LINE__, __FILE__, $sql);
 							}
+
+							//
+							// If we get here the post has been inserted successfully.
+							//
+							$template->assign_vars(array(
+								"META" => '<meta http-equiv="refresh" content="3;url=viewtopic.' . $phpEx . '?' . POST_POST_URL . '=' . $new_post_id .'#' . $new_post_id . '">')
+							);
+
+							$msg_die = $lang['Stored'] . "<br /><br />" . $lang['Click'] . " <a href=\"" . append_sid("viewtopic.$phpEx?" . POST_POST_URL . "=$new_post_id") . "#$new_post_id\">" . $lang['Here'] . "</a> " . $lang['to_view_message'] . "<br /><br />" . $lang['Click'] . " <a href=\"" . append_sid("viewforum.$phpEx?" . POST_FORUM_URL . "=$forum_id") . "\">" . $lang['Here'] . "</a> ". $lang['to_return_forum'];
+
+							message_die(GENERAL_MESSAGE, $msg_die);
 						}
 						else
 						{
-							if(SQL_LAYER == "mysql")
-							{
-							}
-							// Rollback ?
-							message_die(GENERAL_ERROR, "Error updating forums table", "", __LINE__, __FILE__, $sql);
+							message_die(GENERAL_ERROR, "Error updating users table", "", __LINE__, __FILE__, $sql);
 						}
 					}
 					else
 					{
-						if(SQL_LAYER == "mysql")
-						{
-						}
-						// Rollback ?
-						message_die(GENERAL_ERROR, "Error updating topics table", "", __LINE__, __FILE__, $sql);
+						message_die(GENERAL_ERROR, "Error updating forums table", "", __LINE__, __FILE__, $sql);
 					}
 				}
 				else
 				{
-					if(SQL_LAYER == "mysql")
-					{
-						$sql = "DELETE FROM " . POSTS_TABLE . "
-							WHERE post_id = $new_post_id";
-						if( !$db->sql_query($sql) )
-						{
-							message_die(GENERAL_ERROR, "Error inserting data into posts text table and could not rollback", "", __LINE__, __FILE__, $sql);
-						}
-					}
-					// Rollback ?
-					message_die(GENERAL_ERROR, "Error inserting data into posts text table", "", __LINE__, __FILE__, $sql);
+					message_die(GENERAL_ERROR, "Error updating topics table", "", __LINE__, __FILE__, $sql);
 				}
 			}
 			else
 			{
-				// Rollback ?
-				message_die(GENERAL_ERROR, "Error inserting data into posts table", "", __LINE__, __FILE__, $sql);
+				// Rollback
+				if(SQL_LAYER == "mysql")
+				{
+					$sql = "DELETE FROM " . POSTS_TABLE . "
+						WHERE post_id = $new_post_id";
+					$db->sql_query($sql);
+				}
+				message_die(GENERAL_ERROR, "Error inserting data into posts text table", "", __LINE__, __FILE__, $sql);
 			}
 		}
-	}
-}
-else if($mode == "quote" && !$preview && $topic_status == TOPIC_UNLOCKED)
-{
-	$page_title = " " . $lang['Post_reply'];
-	$section_title = " " . $Lang['Post_reply_to'];
-
-	if( isset($post_id) )
-	{
-		$sql = "SELECT p.*, pt.post_text, pt.post_subject, u.username, u.user_id, u.user_sig, t.topic_title, t.topic_type
-			FROM " . POSTS_TABLE . " p, " . USERS_TABLE . " u, " . TOPICS_TABLE . " t, " . POSTS_TEXT_TABLE . " pt
-			WHERE p.post_id = $post_id
-				AND pt.post_id = p.post_id
-				AND p.topic_id = t.topic_id
-				AND p.poster_id = u.user_id";
-		if($result = $db->sql_query($sql))
-		{
-			$postrow = $db->sql_fetchrow($result);
-
-			$poster = stripslashes(trim($postrow['username']));
-			$subject = stripslashes(trim($postrow['post_subject']));
-			$message = stripslashes(trim($postrow['post_text']));
-			if(eregi("\[addsig]$", $message))
-			{
-				$attach_sig = TRUE;
-			}
-			$message = eregi_replace("\[addsig]$", "", $message);
-
-			// Removes UID from BBCode entries
-			$message = preg_replace("/\:[0-9a-z\:]*?\]/si", "]", $message);
-
-			$message = str_replace("<br />", "\n", $message);
-
-			$message = undo_htmlspecialchars($message);
-
-			// Special handling for </textarea> tags in the message, which can break the editing form..
-			$message = preg_replace('#</textarea>#si', '&lt;/TEXTAREA&gt;', $message);
-
-			$msg_date =  create_date($board_config['default_dateformat'], $postrow['post_time'], $board_config['default_timezone']);
-
-			$message = "On " . $msg_date . " " . $poster . " wrote:\n\n[quote]\n" . $message . "\n[/quote]";
-
-		}
 		else
 		{
-			message_die(GENERAL_ERROR, "Couldn't obtain post and post text", "", __LINE__, __FILE__, $sql);
+			message_die(GENERAL_ERROR, "Error inserting data into posts table", "", __LINE__, __FILE__, $sql);
 		}
-	}
-	else
-	{
-		message_die(GENERAL_MESSAGE, $lang['No_such_post']);
-	}
-}
-else if( $mode == "editpost" && $topic_status == TOPIC_UNLOCKED )
-{
-	$page_title = " " . $lang['Edit_post'];
-	$section_title = $lang['Edit_post_in'];
+		//
+		// End of mode = newtopic || reply
+		//
 
-	if( ( isset($HTTP_POST_VARS['submit']) || isset($HTTP_GET_VARS['confirm']) || isset($HTTP_POST_VARS['confirm']) ) &&
-		!$error && !$preview )
+	}
+	else if( $mode == "editpost" )
 	{
 
 		$sql = "SELECT poster_id
 			FROM " . POSTS_TABLE . "
 			WHERE post_id = $post_id";
-
 		if($result = $db->sql_query($sql))
 		{
-			list($check_user_id) = $db->sql_fetchrow($result);
+			$row = $db->sql_fetchrow($result);
 
-			if($userdata['user_id'] != $check_user_id && !$is_auth['auth_mod'])
+			if( $userdata['user_id'] != $row['poster_id'] && !$is_auth['auth_mod'])
 			{
-				$msg = ( isset($HTTP_POST_VARS['delete']) || isset($HTTP_GET_VARS['delete']) ) ? $lang['Sorry_delete_own_posts'] : $lang['Sorry_edit_own_posts'];
-
-				message_die(GENERAL_MESSAGE, $msg);
+				$message = ( $delete ) ? $lang['Sorry_delete_own_posts'] : $lang['Sorry_edit_own_posts'];
+				message_die(GENERAL_MESSAGE, $message);
 			}
 		}
+		else
+		{
+			message_die(GENERAL_ERROR, "Couldn't obtain post information", "", __LINE__, __FILE__, $sql);
+		}
 
-		if( ( isset($HTTP_POST_VARS['delete']) || isset($HTTP_GET_VARS['delete']) ) &&
-			( $is_last_post || $is_auth['auth_mod'] ) )
+		//
+		// The user has chosen to delete a post or a poll
+		//
+		if( ( $delete || $poll_delete ) && ( ( $is_auth['auth_delete'] && $is_last_post_topic ) || $is_auth['auth_mod'] ) )
 		{
 			//
-			// Output a confirmation message, unless we've over-ridden it on the posting_body form (
-			// override_confirm set ), this is so people can implement JavaScript checkers if they wish
+			// Output a confirmation message if the user
+			// chose to delete this post
 			//
-			if( isset($HTTP_POST_VARS['delete']) &&
-				!isset($HTTP_POST_VARS['override_confirm']) &&
-				!isset($HTTP_GET_VARS['confirm']) && !isset($HTTP_POST_VARS['confirm']))
+			if( ( $delete || $poll_delete ) && !$confirm )
 			{
+				$s_hidden_fields = '<input type="hidden" name="mode" value="' . $mode . '" /><input type="hidden" name="' . POST_TOPIC_URL . '" value="'. $topic_id . '" /><input type="hidden" name="' . POST_POST_URL . '" value="' . $post_id . '" />';
 
-				$s_hidden_fields = '<input type="hidden" name="mode" value="' . $mode . '" /><input type="hidden" name="' . POST_TOPIC_URL . '" value="'. $topic_id . '" /><input type="hidden" name="' . POST_POST_URL . '" value="' . $post_id . '" /><input type="hidden" name="delete" value="true" />';
+				$s_hidden_fields .= ( $delete ) ? '<input type="hidden" name="delete" value="true" />' : '<input type="hidden" name="poll_delete" value="true" />';
+
+				$l_confirm = ( ( $delete ) ? $lang['Confirm_delete'] : $lang['Confirm_delete_poll'] );
 
 				//
 				// Output confirmation page
@@ -809,7 +937,7 @@ else if( $mode == "editpost" && $topic_status == TOPIC_UNLOCKED )
 				);
 				$template->assign_vars(array(
 					"MESSAGE_TITLE" => $lang['Information'],
-					"MESSAGE_TEXT" => $lang['Confirm_delete'],
+					"MESSAGE_TEXT" => $l_confirm,
 
 					"L_YES" => $lang['Yes'],
 					"L_NO" => $lang['No'],
@@ -822,188 +950,238 @@ else if( $mode == "editpost" && $topic_status == TOPIC_UNLOCKED )
 				include($phpbb_root_path . 'includes/page_tail.'.$phpEx);
 
 			}
-			else if( isset($HTTP_GET_VARS['confirm']) || isset($HTTP_POST_VARS['confirm']) ||
-				isset($HTTP_POST_VARS['override_confirm']) )
+			else if( $confirm && ( $delete || $poll_delete ) )
 			{
 
-				$sql = "DELETE FROM " . POSTS_TEXT_TABLE . "
-					WHERE post_id = $post_id";
-
-				if($db->sql_query($sql, BEGIN_TRANSACTION))
+				//
+				// Delete poll
+				//
+				if( $is_first_post_topic && $post_has_poll && ( $can_edit_poll || $is_auth['auth_mod'] ) )
 				{
-					$sql = "DELETE FROM " . POSTS_TABLE . "
-						WHERE post_id = $post_id";
-
-					if($is_last_post && $is_first_post)
+					$sql = "DELETE FROM " . VOTE_USERS_TABLE . " 
+						WHERE vote_id = " . $rowset[0]['vote_id'];
+					if($db->sql_query($sql, BEGIN_TRANSACTION))
 					{
-						//
-						// Delete the topic completely, updating the forum_last_post_id
-						// if necessary
-						//
+						$sql = "DELETE FROM " . VOTE_RESULTS_TABLE . " 
+							WHERE vote_id = " . $rowset[0]['vote_id'];
 						if($db->sql_query($sql))
 						{
-							$sql = "DELETE FROM " . TOPICS_TABLE . "
-								WHERE topic_id = $topic_id";
-
-							$sql_forum_upd = "forum_posts = forum_posts - 1, forum_topics = forum_topics - 1";
-
-							$if_die_msg = "Couldn't delete from topics table";
-						}
-						else
-						{
-							if(SQL_LAYER == "mysql")
+							$sql = "DELETE FROM " . VOTE_DESC_TABLE . " 
+								WHERE vote_id = " . $rowset[0]['vote_id'];
+							if($db->sql_query($sql, END_TRANSACTION))
 							{
-							}
-							// Rollback ?
-							message_die(GENERAL_ERROR, "Error deleting from post  table", "", __LINE__, __FILE__, $sql);
-						}
-					}
-					else if($is_last_post)
-					{
-						//
-						// Delete the post and update the _last_post_id's of both
-						// the topic and forum if necessary
-						//
-						if($db->sql_query($sql))
-						{
-							$sql = "SELECT MAX(post_id) AS new_last_post_id
-								FROM " . POSTS_TABLE . "
-								WHERE topic_id = $topic_id";
-
-							if($result = $db->sql_query($sql))
-							{
-								list($new_last_post_id) = $db->sql_fetchrow($result);
-
-								$sql = "UPDATE " . TOPICS_TABLE . "
-									SET topic_replies = topic_replies - 1, topic_last_post_id = $new_last_post_id
-									WHERE topic_id = $topic_id";
-
-								$sql_forum_upd = "forum_posts = forum_posts - 1";
-
-								$if_die_msg = "Error updating topics table";
-							}
-							else
-							{
-								if(SQL_LAYER == "mysql")
+								//
+								// If we're just deleting the poll then show results
+								// and jump back to topic
+								//
+								if( $poll_delete )
 								{
+									$sql = "UPDATE " . TOPICS_TABLE . " 
+										SET topic_vote = 0 
+										WHERE topic_id = $topic_id";
+									if($db->sql_query($sql))
+									{
+										$template->assign_vars(array(
+											"META" => '<meta http-equiv="refresh" content="3;url=viewtopic.' . $phpEx . '?' . POST_TOPIC_URL . '=' . $topic_id . '">')
+										);
+
+										$msg_die = $lang['Poll_delete'] . "<br /><br />" . $lang['Click'] . " <a href=\"" . append_sid("viewtopic.$phpEx?" . POST_TOPIC_URL . "=$topic_id") . "\">" . $lang['Here'] . "</a> ". $lang['to_return_topic'];
+
+										message_die(GENERAL_MESSAGE, $msg_die);
+									}
+									else
+									{
+										message_die(GENERAL_ERROR, "Couldn't update topics vote information", "", __LINE__, __FILE__, $sql);
+									}
 								}
-								// Rollback ?
-								message_die(GENERAL_ERROR, "Error obtaining new last topic id", "", __LINE__, __FILE__, $sql);
-							}
-						}
-						else
-						{
-							if(SQL_LAYER == "mysql")
-							{
-							}
-							// Rollback ?
-							message_die(GENERAL_ERROR, "Error deleting from post table", "", __LINE__, __FILE__, $sql);
-						}
-					}
-					else if($is_auth['auth_mod'])
-					{
-						//
-						// It's not last and it's not both first and last so it's somewhere in
-						// the middle(!) Only moderators can delete these posts, all we need do
-						// is update the forums table data as necessary
-						//
-						$sql_forum_upd = "forum_posts = forum_posts - 1";
-
-						$if_die_msg = "Couldn't delete from posts table";
-					}
-
-					//
-					// Updating the forum is common to all three possibilities,
-					// _remember_ we're still in a transaction here!
-					//
-					if($db->sql_query($sql))
-					{
-						if($is_last_post_forum)
-						{
-							$sql = "SELECT MAX(post_id) AS new_last_post_id
-								FROM " . POSTS_TABLE . "
-								WHERE forum_id = $forum_id";
-
-							if($result = $db->sql_query($sql))
-							{
-								list($new_last_post_id) = $db->sql_fetchrow($result);
 							}
 							else
 							{
-								message_die(GENERAL_ERROR, "Couldn't obtain new last post id for the forum", "", __LINE__, __FILE__, $sql);
+								message_die(GENERAL_ERROR, "Couldn't delete from vote descriptions table", "", __LINE__, __FILE__, $sql);
 							}
-
-							$new_last_sql = ", forum_last_post_id = $new_last_post_id";
 						}
 						else
 						{
-							$new_last_sql = "";
-						}
-
-						$sql = "UPDATE " . FORUMS_TABLE . "
-							SET " . $sql_forum_upd . $new_last_sql . "
-							WHERE forum_id = $forum_id";
-
-						if($db->sql_query($sql, END_TRANSACTION))
-						{
-							//
-							// If we get here the post has been deleted successfully.
-							//
-							$msg = $lang['Deleted'];
-
-							if(!$is_last_post || !$is_first_post)
-							{
-								$msg .= "<br /><br />" . $lang['Click'] . " <a href=\"" . append_sid("viewtopic.$phpEx?" . POST_TOPIC_URL . "=$topic_id") . "\">" . $lang['Here'] . "</a> " . $lang['to_return_topic'];
-							}
-							$msg .= "<br /><br />" . $lang['Click'] . " <a href=\"" . append_sid("viewforum.$phpEx?" . POST_FORUM_URL . "=$forum_id") . "\">" . $lang['Here'] . "</a> ". $lang['to_return_forum'];
-
-							message_die(GENERAL_MESSAGE, $msg);
-						}
-						else
-						{
-							if(SQL_LAYER == "mysql")
-							{
-							}
-							// Rollback ?
-							message_die(GENERAL_ERROR, "Error updating forums table", "", __LINE__, __FILE__, $sql);
+							message_die(GENERAL_ERROR, "Couldn't delete from vote results table", "", __LINE__, __FILE__, $sql);
 						}
 					}
 					else
 					{
-						//
-						// This error is produced by the last SQL query carried out
-						// before we jumped into this common block
-						//
-						if(SQL_LAYER == "mysql")
-						{
-						}
-						// Rollback ?
-						message_die(GENERAL_ERROR, $if_die_msg, "", __LINE__, __FILE__, $sql);
+						message_die(GENERAL_ERROR, "Couldn't delete from vote users table", "", __LINE__, __FILE__, $sql);
 					}
 				}
-				else
+
+				if( $delete )
 				{
-					if(SQL_LAYER == "mysql")
+
+					$sql = "DELETE FROM " . POSTS_TEXT_TABLE . "
+						WHERE post_id = $post_id";
+
+					if($db->sql_query($sql, BEGIN_TRANSACTION))
 					{
+						$sql = "DELETE FROM " . POSTS_TABLE . "
+							WHERE post_id = $post_id";
+						if($db->sql_query($sql))
+						{
+
+							if( $is_last_post_topic && $is_first_post_topic )
+							{
+								//
+								// Delete the topic completely, updating the forum_last_post_id
+								// if necessary
+								//
+								if( $db->sql_query($sql) )
+								{
+									$sql = "DELETE FROM " . TOPICS_TABLE . "
+										WHERE topic_id = $topic_id";
+
+									$sql_forum_upd = "forum_posts = forum_posts - 1, forum_topics = forum_topics - 1";
+
+									$if_die_msg = "Error deleting from topics table";
+								}
+								else
+								{
+									message_die(GENERAL_ERROR, "Error deleting from post  table", "", __LINE__, __FILE__, $sql);
+								}
+							}
+							else if( $is_last_post_topic )
+							{
+								//
+								// Delete the post and update the _last_post_id's of both
+								// the topic and forum if necessary
+								//
+								if($db->sql_query($sql))
+								{
+									$sql = "SELECT MAX(post_id) AS new_last_post_id
+										FROM " . POSTS_TABLE . "
+										WHERE topic_id = $topic_id";
+
+									if($result = $db->sql_query($sql))
+									{
+										$row = $db->sql_fetchrow($result);
+
+										$sql = "UPDATE " . TOPICS_TABLE . "
+											SET topic_replies = topic_replies - 1, topic_last_post_id = " . $row['new_last_post_id'] . "
+											WHERE topic_id = $topic_id";
+
+										$sql_forum_upd = "forum_posts = forum_posts - 1";
+
+										$if_die_msg = "Error updating topics table";
+									}
+									else
+									{
+										message_die(GENERAL_ERROR, "Error obtaining new last topic id", "", __LINE__, __FILE__, $sql);
+									}
+								}
+								else
+								{
+									message_die(GENERAL_ERROR, "Error deleting from post table", "", __LINE__, __FILE__, $sql);
+								}
+							}
+							else if( $is_auth['auth_mod'] )
+							{
+								//
+								// It's not last and it's not both first and last so it's somewhere in
+								// the middle(!) Only moderators can delete these posts, all we need do
+								// is update the forums table data as necessary
+								//
+								$sql = "UPDATE " . TOPICS_TABLE . "
+									SET topic_replies = topic_replies - 1 
+									WHERE topic_id = $topic_id";
+
+								$sql_forum_upd = "forum_posts = forum_posts - 1";
+
+								$if_die_msg = "Couldn't delete from posts table";
+							}
+
+							//
+							// Updating the forum is common to all three possibilities,
+							// _remember_ we're still in a transaction here!
+							//
+							if( $db->sql_query($sql) )
+							{
+								if( $is_last_post_forum )
+								{
+									$sql = "SELECT MAX(post_id) AS new_post_id
+										FROM " . POSTS_TABLE . "
+										WHERE forum_id = $forum_id";
+
+									if($result = $db->sql_query($sql))
+									{
+										$row = $db->sql_fetchrow($result);
+									}
+									else
+									{
+										message_die(GENERAL_ERROR, "Couldn't obtain new last post id for the forum", "", __LINE__, __FILE__, $sql);
+									}
+
+									$new_last_sql = ", forum_last_post_id = " . $row['new_post_id'];
+								}
+								else
+								{
+									$new_last_sql = "";
+								}
+
+								$sql = "UPDATE " . FORUMS_TABLE . "
+									SET " . $sql_forum_upd . $new_last_sql . "
+									WHERE forum_id = $forum_id";
+
+								if($db->sql_query($sql, END_TRANSACTION))
+								{
+									//
+									// If we get here the post has been deleted successfully.
+									//
+									$msg_die = $lang['Deleted'];
+
+									if( !$is_first_post_topic && !$is_last_post_topic )
+									{
+										$template->assign_vars(array(
+											"META" => '<meta http-equiv="refresh" content="3;url=viewtopic.' . $phpEx . '?' . POST_TOPIC_URL . '=' . $topic_id . '">')
+										);
+
+										$msg_die .= "<br /><br />" . $lang['Click'] . " <a href=\"" . append_sid("viewtopic.$phpEx?" . POST_TOPIC_URL . "=$topic_id") . "\">" . $lang['Here'] . "</a> " . $lang['to_return_topic'];
+									}
+									else
+									{
+										$template->assign_vars(array(
+											"META" => '<meta http-equiv="refresh" content="3;url=viewforum.' . $phpEx . '?' . POST_FORUM_URL . '=' . $forum_id . '">')
+										);
+									}
+									$msg_die .= "<br /><br />" . $lang['Click'] . " <a href=\"" . append_sid("viewforum.$phpEx?" . POST_FORUM_URL . "=$forum_id") . "\">" . $lang['Here'] . "</a> ". $lang['to_return_forum'];
+
+									message_die(GENERAL_MESSAGE, $msg_die);
+								}
+								else
+								{
+									message_die(GENERAL_ERROR, "Error updating forums table", "", __LINE__, __FILE__, $sql);
+								}
+							}
+							else
+							{
+								message_die(GENERAL_ERROR, $if_die_msg, "", __LINE__, __FILE__, $sql);
+							}
+						}
+						else
+						{
+							message_die(GENERAL_ERROR, "Error deleting from posts table", "", __LINE__, __FILE__, $sql);
+						}
+					}
+					else
+					{
+						message_die(GENERAL_ERROR, "Error deleting from posts text table", "", __LINE__, __FILE__, $sql);
 					}
-					// Rollback ?
-					message_die(GENERAL_ERROR, "Error deleting from posts text table", "", __LINE__, __FILE__, $sql);
 				}
 			}
 			else
 			{
-				//
-				// No action matched so return to viewtopic, should be fine for URL based
-				// confirmations
-				//
-				header("Location: viewtopic.$phpEx?" . POST_TOPIC_URL . "=$topic_id");
+				header("Location: " . append_sid("viewtopic.$phpEx?" . POST_TOPIC_URL . "=$topic_id"));
 			}
 		}
 		else
 		{
-			if( !$is_last_post && ( !$is_auth['auth_mod'] || $check_user_id == $userdata['user_id'] ) )
+			if( !$is_last_post_topic && ( !$is_auth['auth_mod'] || $row['poster_id'] == $userdata['user_id'] ) )
 			{
-				$edited_sql = ", post_edit_time = " . time() . ", post_edit_count = post_edit_count + 1 ";
+				$edited_sql = ", post_edit_time = $current_time, post_edit_count = post_edit_count + 1 ";
 			}
 			else
 			{
@@ -1017,181 +1195,673 @@ else if( $mode == "editpost" && $topic_status == TOPIC_UNLOCKED )
 			if($db->sql_query($sql, BEGIN_TRANSACTION))
 			{
 				$sql = "UPDATE " . POSTS_TEXT_TABLE . "
-					SET post_text = '$message', post_subject = '$subject'
+					SET post_text = '$post_message', post_subject = '$post_subject'
 					WHERE post_id = $post_id";
 
-				if($is_first_post)
+				if( $is_first_post_topic )
 				{
-					if($db->sql_query($sql))
+					if( $db->sql_query($sql) )
 					{
 						//
-						// Update topics table here, set notification level and such
+						// Update topics table here 
 						//
 						$sql = "UPDATE " . TOPICS_TABLE . "
-							SET topic_title = '$subject', topic_type = '".$topic_type."'
+							SET topic_title = '$post_subject', topic_type = $topic_type" . $sql_topic_vote_edit . " 
 							WHERE topic_id = $topic_id";
-
 						if($db->sql_query($sql, END_TRANSACTION))
 						{
+							//
+							// Update of voting required?
+							//
+							if( $is_auth['auth_pollcreate'] && $topic_vote  )
+							{
+								if( $post_has_poll && ( $can_edit_poll || $is_auth['auth_mod'] ) )
+								{
+									$sql = "SELECT vote_option_id, vote_result  
+										FROM " . VOTE_RESULTS_TABLE . " 
+										WHERE vote_id = $vote_id 
+										ORDER BY vote_option_id ASC";
+									if( !$result = $db->sql_query($sql) )
+									{
+										message_die(GENERAL_ERROR, "Couldn't obtain vote data results for this topic", "", __LINE__, __FILE__, $sql);
+									}
+
+									if( $db->sql_numrows($result) )
+									{
+										$old_poll_result = array();
+										while( $row = $db->sql_fetchrow($result) )
+										{
+											$old_poll_result[$row['vote_option_id']] = $row['vote_result'];
+										}
+
+										//
+										// Previous entry with no results (or a moderator), update
+										//
+										$sql = "UPDATE " . VOTE_DESC_TABLE . " 
+											SET vote_text = '$poll_title', vote_length = " . ( $poll_length * 86400 ) . " 
+											WHERE topic_id = $topic_id";
+										if( $result = $db->sql_query($sql, BEGIN_TRANSACTION) )
+										{
+											$sql = "DELETE FROM " . VOTE_RESULTS_TABLE . " 
+												WHERE vote_id = $vote_id";
+											if( $result = $db->sql_query($sql) )
+											{
+												$poll_option_id = 1;
+												while( list($option_id, $option_text) = each($poll_option_list) )
+												{
+													$vote_result = ( $old_poll_result[$option_id] ) ? $old_poll_result[$option_id] : 0;
+
+													$sql = "INSERT INTO " . VOTE_RESULTS_TABLE . " (vote_id, vote_option_id, vote_option_text, vote_result)
+														VALUES ($vote_id, $poll_option_id, '$option_text', $vote_result)";
+													if( !$result = $db->sql_query($sql, END_TRANSACTION) )
+													{
+														message_die(GENERAL_ERROR, "Couldn't insert new poll options", "", __LINE__, __FILE__, $sql);
+													}
+													$poll_option_id++;
+												}
+											}
+											else
+											{
+												message_die(GENERAL_ERROR, "Couldn't delete existing options", "", __LINE__, __FILE__, $sql);
+											}
+										}
+									}
+									else
+									{
+										message_die(GENERAL_ERROR, "Failed to obtain row set for this poll", "", __LINE__, __FILE__, $sql);
+									}
+								}
+								else
+								{
+									//
+									// No previous entry, create new
+									//
+									$sql = "INSERT INTO " . VOTE_DESC_TABLE . " (topic_id, vote_text, vote_start, vote_length) 
+										VALUES ($topic_id, '$poll_title', $current_time, " . ( $poll_length * 86400 ) . ")";
+									if( $result = $db->sql_query($sql, BEGIN_TRANSACTION) )
+									{
+										$new_vote_id = $db->sql_nextid();
+
+										$poll_option_id = 1;
+										while( list($option_id, $option_text) = each($poll_option_list) )
+										{
+											$sql = "INSERT INTO " . VOTE_RESULTS_TABLE . " (vote_id, vote_option_id, vote_option_text, vote_result)
+												VALUES ($new_vote_id, $poll_option_id, '$option_text', 0)";
+											if( !$result = $db->sql_query($sql, END_TRANSACTION) )
+											{
+												// Rollback ...
+												if(SQL_LAYER == "mysql")
+												{
+													$sql_del_v = "DELETE FROM " . VOTE_DESC_TABLE . " 
+														WHERE vote_id = $new_vote_id";
+													$db->sql_query($sql_del_v);
+												}
+												message_die(GENERAL_ERROR, "Couldn't insert new poll options", "", __LINE__, __FILE__, $sql);
+											}
+											$poll_option_id++;
+										}
+									}
+								}
+							}
+
 							//
 							// If we get here the post has been inserted successfully.
 							//
-							$msg = $lang['Stored'] . "<br /><br />" . $lang['Click'] . " <a href=\"" . append_sid("viewtopic.$phpEx?" . POST_POST_URL . "=$post_id") . "#$post_id\">" . $lang['Here'] . "</a> " . $lang['to_view_message'] . "<br /><br />" . $lang['Click'] . " <a href=\"" . append_sid("viewforum.$phpEx?" . POST_FORUM_URL . "=$forum_id") . "\">" . $lang['Here'] . "</a> ". $lang['to_return_forum'];
+							$template->assign_vars(array(
+								"META" => '<meta http-equiv="refresh" content="3;url=viewtopic.' . $phpEx . '?' . POST_POST_URL . '=' . $post_id . '#' . $post_id . '">')
+							);
 
-							message_die(GENERAL_MESSAGE, $msg);
+							$msg_die = $lang['Stored'] . "<br /><br />" . $lang['Click'] . " <a href=\"" . append_sid("viewtopic.$phpEx?" . POST_POST_URL . "=$post_id") . "#$post_id\">" . $lang['Here'] . "</a> " . $lang['to_view_message'] . "<br /><br />" . $lang['Click'] . " <a href=\"" . append_sid("viewforum.$phpEx?" . POST_FORUM_URL . "=$forum_id") . "\">" . $lang['Here'] . "</a> ". $lang['to_return_forum'];
+
+							message_die(GENERAL_MESSAGE, $msg_die);
 						}
 						else
 						{
-							if(SQL_LAYER == "mysql")
-							{
-							}
 							message_die(GENERAL_ERROR, "Updating topics table", "", __LINE__, __FILE__, $sql);
 						}
 					}
 					else
 					{
-						if(SQL_LAYER == "mysql")
-						{
-						}
+
 					}
 				}
 				else
 				{
-					if($db->sql_query($sql, END_TRANSACTION))
+					if( $db->sql_query($sql, END_TRANSACTION) )
 					{
 						//
 						// If we get here the post has been inserted successfully.
 						//
-						$msg = $lang['Stored'] . "<br /><br />" . $lang['Click'] . " <a href=\"" . append_sid("viewtopic.$phpEx?" . POST_POST_URL . "=$post_id") . "#$post_id\">" . $lang['Here'] . "</a> " . $lang['to_view_message'] . "<br /><br />" . $lang['Click'] . " <a href=\"" . append_sid("viewforum.$phpEx?" . POST_FORUM_URL . "=$forum_id") . "\">" . $lang['Here'] . "</a> ". $lang['to_return_forum'];
+						$template->assign_vars(array(
+							"META" => '<meta http-equiv="refresh" content="3;url=viewtopic.' . $phpEx . '?' . POST_POST_URL . '=' . $post_id . '#' . $post_id . '">')
+						);
 
-						message_die(GENERAL_MESSAGE, $msg);
+						$msg_die = $lang['Stored'] . "<br /><br />" . $lang['Click'] . " <a href=\"" . append_sid("viewtopic.$phpEx?" . POST_POST_URL . "=$post_id") . "#$post_id\">" . $lang['Here'] . "</a> " . $lang['to_view_message'] . "<br /><br />" . $lang['Click'] . " <a href=\"" . append_sid("viewforum.$phpEx?" . POST_FORUM_URL . "=$forum_id") . "\">" . $lang['Here'] . "</a> ". $lang['to_return_forum'];
+
+						message_die(GENERAL_MESSAGE, $msg_die);
 					}
 					else
 					{
-						if(SQL_LAYER == "mysql")
-						{
-						}
 						message_die(GENERAL_ERROR, "Error updating posts text table", "", __LINE__, __FILE__, $sql);
 					}
 				}
 			}
 			else
 			{
-				if(SQL_LAYER == "mysql")
-				{
-				}
 				message_die(GENERAL_ERROR, "Error updating posts text table", "", __LINE__, __FILE__, $sql);
 			}
 		}
+		//
+		// End of mode = editpost
+		//
 	}
-	else if( isset($HTTP_GET_VARS['not_confirm']) || isset($HTTP_POST_VARS['not_confirm']) )
+	else if( $mode == "vote" )
 	{
 
-		//
-		// Cancelled a confirmation, just to viewtopic
-		//
-		header("Location: viewtopic.$phpEx?" . POST_TOPIC_URL . "=$topic_id");
-
-	}
-	else
-	{
-		if( !empty($post_id) )
+		if( !empty($HTTP_POST_VARS['vote_id']) )
 		{
-   			$sql = "SELECT p.*, pt.post_text, pt.post_subject, u.username, u.user_id, u.user_sig, t.topic_title, t.topic_type
-				FROM " . POSTS_TABLE . " p, " . USERS_TABLE . " u, " . TOPICS_TABLE . " t, " . POSTS_TEXT_TABLE . " pt
-				WHERE p.post_id = $post_id
-					AND pt.post_id = p.post_id
-					AND p.topic_id = t.topic_id
-					AND p.poster_id = u.user_id";
+			$vote_option_id = $HTTP_POST_VARS['vote_id'];
 
-			if($result = $db->sql_query($sql))
+			$sql = "SELECT vd.vote_id, MAX(vr.vote_option_id) AS max_vote_option   
+				FROM " . VOTE_DESC_TABLE . " vd, " . VOTE_RESULTS_TABLE . " vr
+				WHERE vd.topic_id = $topic_id 
+					AND vr.vote_id = vd.vote_id 
+				GROUP BY vd.vote_id";
+			if( !$result = $db->sql_query($sql) )
 			{
-				$postrow = $db->sql_fetchrow($result);
+				message_die(GENERAL_ERROR, "Couldn't obtain vote data for this topic", "", __LINE__, __FILE__, $sql);
+			}
 
+			if( $vote_options = $db->sql_numrows($result) )
+			{
+				$vote_info = $db->sql_fetchrow($result);
+
+				if( $vote_info['max_vote_option'] < $vote_option_id )
+				{
+					$template->assign_vars(array(
+						"META" => '<meta http-equiv="refresh" content="3;url=viewtopic.' . $phpEx . '?' . POST_TOPIC_URL . '=' . $topic_id . '">')
+					);
+
+					$message = $lang['No_vote_option'] . "<br /><br />" . $lang['Click'] . " <a href=\"" . append_sid("viewtopic.$phpEx?" . POST_TOPIC_URL . "=$topic_id") . "\">" . $lang['Here'] . "</a> " . $lang['to_return_topic'];
+
+					message_die(GENERAL_MESSAGE, $message);
+				}
+
+				$vote_id = $vote_info['vote_id'];
+
+				$sql = "SELECT * 
+					FROM " . VOTE_USERS_TABLE . "  
+					WHERE vote_id = $vote_id 
+						AND vote_user_id = " . $userdata['user_id'];
+				if( !$result = $db->sql_query($sql) )
+				{
+					message_die(GENERAL_ERROR, "Couldn't obtain user vote data for this topic", "", __LINE__, __FILE__, $sql);
+				}
+
+				$user_voted = ( $db->sql_numrows($result) ) ? TRUE : 0;
+
+				if( !$user_voted )
+				{
+					$sql = "UPDATE " . VOTE_RESULTS_TABLE . " 
+						SET vote_result = vote_result + 1 
+						WHERE vote_id = $vote_id 
+							AND vote_option_id = $vote_option_id";
+					if( $db->sql_query($sql, BEGIN_TRANSACTION) )
+					{
+						$sql = "INSERT INTO " . VOTE_USERS_TABLE . " (vote_id, vote_user_id, vote_user_ip) 
+							VALUES ($vote_id, " . $userdata['user_id'] . ", '$user_ip')";
+						if( $db->sql_query($sql, END_TRANSACTION) )
+						{
+
+							$template->assign_vars(array(
+								"META" => '<meta http-equiv="refresh" content="3;url=viewtopic.' . $phpEx . '?' . POST_TOPIC_URL . '=' . $topic_id . '">')
+							);
+
+							$message = $lang['Vote_cast'] . "<br /><br />" . $lang['Click'] . " <a href=\"" . append_sid("viewtopic.$phpEx?" . POST_TOPIC_URL . "=$topic_id") . "\">" . $lang['Here'] . "</a> " . $lang['to_return_topic'];
+
+							message_die(GENERAL_MESSAGE, $message);
+						}
+						else
+						{
+							if(SQL_LAYER == "mysql")
+							{
+								$sql_rewind = "UPDATE " . VOTE_RESULTS_TABLE . " 
+									SET vote_option_result = vote_option_result - 1 
+									WHERE vote_id = $vote_id 
+										AND vote_option_id = $vote_option_id";
+								$db->sql_query($sql_rewind);
+							}
+
+							message_die(GENERAL_ERROR, "Error updating vote users table", "", __LINE__, __FILE__, $sql);
+						}
+					}
+					else
+					{
+						message_die(GENERAL_ERROR, "Error updating vote results table", "", __LINE__, __FILE__, $sql);
+					}
+				}
+				else
+				{
+					$template->assign_vars(array(
+						"META" => '<meta http-equiv="refresh" content="3;url=viewtopic.' . $phpEx . '?' . POST_TOPIC_URL . '=' . $topic_id . '">')
+					);
+
+					$message = $lang['Already_voted'] . "<br /><br />" . $lang['Click'] . " <a href=\"" . append_sid("viewtopic.$phpEx?" . POST_TOPIC_URL . "=$topic_id") . "\">" . $lang['Here'] . "</a> " . $lang['to_return_topic'];
+
+					message_die(GENERAL_MESSAGE, $message);
+				}
+			}
+		}
+		else
+		{
+			$message = $lang['No_vote_option'] . "<br /><br />" . $lang['Click'] . " <a href=\"" . append_sid("viewtopic.$phpEx?" . POST_TOPIC_URL . "=$topic_id") . "\">" . $lang['Here'] . "</a> " . $lang['to_return_topic'];
+
+			message_die(GENERAL_MESSAGE, $message);
+		}
+		//
+		// End of mode = vote
+		//
+	}
+
+}
+else if( $preview || $refresh || $error )
+{
+
+	//
+	// If we're previewing or refreshing then obtain the data
+	// passed to the script, process it a little, do some checks
+	// where neccessary, etc.
+	//
+	$post_username = ( isset($HTTP_POST_VARS['username']) ) ? trim(strip_tags(stripslashes($HTTP_POST_VARS['username']))) : "";
+	$post_subject = ( isset($HTTP_POST_VARS['subject']) ) ? trim(strip_tags(stripslashes($HTTP_POST_VARS['subject']))) : "";
+	$post_message = ( isset($HTTP_POST_VARS['message']) ) ? trim(stripslashes($HTTP_POST_VARS['message'])) : "";
+	$post_message = preg_replace('#<textarea>#si', '&lt;textarea&gt;', $post_message);
+
+	$poll_title = ( isset($HTTP_POST_VARS['poll_title']) ) ? trim(strip_tags(stripslashes($HTTP_POST_VARS['poll_title']))) : "";
+	$poll_length = ( isset($HTTP_POST_VARS['poll_length']) ) ? intval($HTTP_POST_VARS['poll_length']) : 0;
+
+	$poll_options = 0;
+	$poll_option_list = array();
+	if( isset($HTTP_POST_VARS['del_poll_option']) )
+	{
+		if( isset($HTTP_POST_VARS['poll_option_text']) )
+		{
+			while( list($option_id, $option_text) = each($HTTP_POST_VARS['poll_option_text']) )
+			{
+				if( !isset($HTTP_POST_VARS['del_poll_option'][$option_id]) )
+				{
+					$poll_option_list[$option_id] = trim(strip_tags(stripslashes($option_text)));
+					$poll_options++;
+				}
+			}
+		}
+	}
+	else 
+	{
+		if( isset($HTTP_POST_VARS['poll_option_text']) )
+		{
+			@reset($HTTP_POST_VARS['poll_option_text']);
+			while( list($option_id, $option_text) = each($HTTP_POST_VARS['poll_option_text']) )
+			{
+				$poll_option_list[$option_id] = trim(strip_tags(stripslashes($option_text)));
+				$poll_options++;
+			}
+		}
+
+		if( isset($HTTP_POST_VARS['add_poll_option']) )
+		{
+			if( $poll_options < $board_config['max_poll_options'] ) 
+			{
+				$new_poll_option = trim(strip_tags(stripslashes($HTTP_POST_VARS['add_poll_option_text'])));
+
+				if($new_poll_option != "")
+				{
+					$poll_option_list[] = $new_poll_option;
+				}
+			}
+			else
+			{
+				$error = TRUE;
+				if(!empty($error_msg))
+				{
+					$error_msg .= "<br />";
+				}
+				$error_msg .= $lang['To_many_poll_options']; 
+			}
+		}
+	}
+
+	//
+	// Do mode specific things
+	//
+	if( $mode == "newtopic" )
+	{
+
+		$page_title = $lang['Post_a_new_topic'];
+		$display_poll = ( $is_auth['auth_pollcreate'] ) ? TRUE : 0;
+
+		$user_sig = ( $userdata['user_sig'] != "" ) ? $userdata['user_sig'] : "";
+
+	}
+	else if( $mode == "reply" )
+	{
+
+		$page_title = $lang['Post_a_reply'];
+		$display_poll = 0;
+
+		$user_sig = ( $userdata['user_sig'] != "" ) ? $userdata['user_sig'] : "";
+
+	}
+	else if( $mode == "editpost" )
+	{
+		$page_title = $lang['Edit_Post'];
+
+		$sql = "SELECT u.user_id, u.user_sig 
+			FROM " . POSTS_TABLE . " p, " . USERS_TABLE . " u 
+			WHERE p.post_id = $post_id
+				AND u.user_id = p.poster_id";
+		if($result = $db->sql_query($sql))
+		{
+			$postrow = $db->sql_fetchrow($result);
+
+			if($userdata['user_id'] != $postrow['user_id'] && !$is_auth['auth_mod'])
+			{
+				message_die(GENERAL_MESSAGE, $lang['Sorry_edit_own_posts']);
+			}
+
+			$user_sig = ( $postrow['user_sig'] != "" ) ? $postrow['user_sig'] : "";
+		}
+		else
+		{
+			message_die(GENERAL_ERROR, "Couldn't obtain post and post text", "", __LINE__, __FILE__, $sql);
+		}
+
+		if( $is_auth['auth_pollcreate'] && $is_first_post_topic )
+		{
+			$display_poll = ( !$post_has_poll || ( $post_has_poll && ( $is_auth['auth_mod'] || $can_edit_poll ) ) ) ? TRUE : 0;
+		}
+		else
+		{
+			$display_poll = 0;
+		}
+	}
+}
+else
+{
+	//
+	// This is the entry point for posting, some basic variables
+	// are set, for editpost/quote the original message is obtained
+	// and for editpost a check is done to ensure the user isn't
+	// trying to edit someone elses post ( additional checks on polling
+	// capability are also carried out )
+	//
+
+	if( $mode == "newtopic" )
+	{
+
+		$page_title = $lang['Post_a_new_topic'];
+
+		$display_poll = ( $is_auth['auth_pollcreate'] ) ? TRUE : 0;
+		$poll_title = "";
+		$poll_length = 0;
+
+		$user_sig = ( $userdata['user_sig'] != "" ) ? $userdata['user_sig'] : "";
+
+		$post_username = ($userdata['session_logged_in']) ? $userdata['username'] : "";
+		$post_subject = "";
+		$post_message = "";
+
+	}
+	else if( $mode == "reply" )
+	{
+
+		$page_title = $lang['Post_a_reply'];
+
+		$display_poll = 0;
+		$poll_title = "";
+		$poll_length = 0;
+
+		$user_sig = ( $userdata['user_sig'] != "" ) ? $userdata['user_sig'] : "";
+
+		$post_username = ($userdata['session_logged_in']) ? $userdata['username'] : "";
+		$post_subject = "";
+		$post_message = "";
+
+	}
+	else if( $mode == "editpost" || $mode == "quote" && ( !$preview && !$refresh ) )
+	{
+
+		$sql = "SELECT p.*, pt.post_text, pt.post_subject, u.username, u.user_id, u.user_sig, t.topic_title, t.topic_type, t.topic_vote
+			FROM " . POSTS_TABLE . " p, " . USERS_TABLE . " u, " . TOPICS_TABLE . " t, " . POSTS_TEXT_TABLE . " pt
+			WHERE p.post_id = $post_id
+				AND pt.post_id = p.post_id
+				AND p.topic_id = t.topic_id
+				AND p.poster_id = u.user_id";
+		if($result = $db->sql_query($sql))
+		{
+			$postrow = $db->sql_fetchrow($result);
+
+			if( $mode == "editpost" )
+			{
 				if($userdata['user_id'] != $postrow['user_id'] && !$is_auth['auth_mod'])
 				{
 					message_die(GENERAL_MESSAGE, $lang['Sorry_edit_own_posts']);
 				}
+			}
 
-				if(!$preview)
+			$post_username = $postrow['username'];
+			$post_subject = $postrow['post_subject'];
+			$post_message = $postrow['post_text'];
+
+			if( eregi("\[addsig]$", $post_message) )
+			{
+				$post_message = eregi_replace("\[addsig]$", "", $post_message);
+
+				$attach_sig = ( $mode == "editpost" ) ? ( ( $postrow['user_sig'] != "" ) ? TRUE : 0 ) : ( ( $userdata['user_sig'] != "" ) ? TRUE : 0 );
+			}
+			else 
+			{
+				$attach_sig = ( $mode == "editpost" ) ? 0 : ( ( $userdata['user_sig'] != "" ) ? TRUE : 0 );
+			}
+			$user_sig = ( $attach_sig ) ? ( ( $mode == "editpost" ) ? $postrow['user_sig'] : $userdata['user_sig'] ) : "";
+
+			$post_message = preg_replace("/\:[0-9a-z\:]*?\]/si", "]", $post_message);
+			$post_message = str_replace("<br />", "\n", $post_message);
+			$post_message = undo_htmlspecialchars($post_message);
+			$post_message = preg_replace('#</textarea>#si', '&lt;/textarea&gt;', $post_message);
+
+			//
+			// Finish off edit/quote grab by doing specific
+			// things for each mode
+			//
+			if( $mode == "quote" )
+			{
+				$page_title = $lang['Post_a_reply'];
+
+				$msg_date =  create_date($board_config['default_dateformat'], $postrow['post_time'], $board_config['default_timezone']);
+
+				$post_message = $poster . " " . $lang['wrote'] . ":\n\n[quote]\n" . $post_message . "\n[/quote]";
+
+				$mode = "reply";
+			}
+			else if( $mode == "editpost" ) 
+			{
+				$page_title = $lang['Edit_Post'];
+
+				$html_on = ( $postrow['enable_html'] && $board_config['allow_html'] ) ? TRUE : 0;
+				$bbcode_on = ( $postrow['enable_bbcode'] && $board_config['allow_bbcode'] ) ? TRUE : 0;
+				$smilies_on = ( $postrow['enable_smilies'] && $board_config['allow_smilies'] ) ? TRUE : 0;
+
+				if( $is_first_post_topic )
 				{
-					$subject = stripslashes(trim($postrow['post_subject']));
-					$message = stripslashes(trim($postrow['post_text']));
+					$post_subject = $postrow['topic_title'];
+					$topic_type = $postrow['topic_type'];
 
-					if(eregi("\[addsig]$", $message))
+					if( $is_auth['auth_pollcreate'] && ( $can_edit_poll || $is_auth['auth_mod'] ) )
 					{
-						$message = eregi_replace("\[addsig]$", "", $message);
+						$sql = "SELECT vd.vote_text, vd.vote_length, vr.vote_option_id, vr.vote_option_text  
+							FROM " . VOTE_DESC_TABLE . " vd, " . VOTE_RESULTS_TABLE . " vr 
+							WHERE vd.topic_id = $topic_id 
+								AND vr.vote_id = vd.vote_id 
+							ORDER BY vr.vote_option_id ASC";
+						if( !$result = $db->sql_query($sql) )
+						{
+							message_die(GENERAL_ERROR, "Couldn't obtain vote data for this topic", "", __LINE__, __FILE__, $sql);
+						}
 
-						$user_sig = ($postrow['user_sig'] != "") ? $postrow['user_sig'] : "";
-						$attach_sig = ($postrow['user_sig'] != "") ? TRUE : 0;
+						$vote_results_sum = 0;
+						while( $row = $db->sql_fetchrow($result) )
+						{
+							$poll_title = $row['vote_text'];
+							$poll_length = $row['vote_length'];
+
+							$poll_option_list[$row['vote_option_id']] = $row['vote_option_text'];
+						}
+						$poll_length = $poll_length / 86400;
+
+						$display_poll = TRUE;
 					}
 					else
 					{
-						$attach_sig = 0;
-					}
-
-					// Removes UID from BBCode entries
-					$message = preg_replace("/\:[0-9a-z\:]+\]/si", "]", $message);
-
-					$message = str_replace("<br />", "\n", $message);
-
-   					$message = undo_htmlspecialchars($message);
-
-					// Special handling for </textarea> tags in the message, which can break the editing form..
-					$message = preg_replace('#</textarea>#si', '&lt;/TEXTAREA&gt;', $message);
-
-					if($is_first_post)
-					{
-						$subject = stripslashes($postrow['topic_title']);
-
-						switch($postrow['topic_type'])
-						{
-							case POST_ANNOUNCE:
-								$is_announce = TRUE;
-								break;
-
-							case POST_STICKY:
-								$is_sticky = TRUE;
-								break;
-						}
+						$display_poll = ( $is_auth['auth_pollcreate'] && !$post_has_poll ) ? TRUE : 0;
+						$poll_length = 0;
 					}
 				}
+				else
+				{
+					$display_poll = 0;
+				}
 			}
-   		}
-		else
-		{
-			message_die(GENERAL_MESSAGE, $lang['No_such_post']);
-   		}
+			else
+			{
+				message_die(GENERAL_ERROR, "Couldn't obtain post and post text", "", __LINE__, __FILE__, $sql);
+			}
+		}
 	}
-}// end if ... mode
+	
+}
+//
+// Major posting code complete
+// ---------------------------
+
+
+// --------------------
+// Generate page output
+//
 
 //
-// Output page
+// Include page header
 //
-if($mode == "newtopic")
-{
-	$post_a = $lang['Post_a_new_topic'];
-}
-else if($mode == "reply" || $mode == "quote")
-{
-	//
-	// Set mode to reply
-	//
-	$mode = "reply";
-	$post_a = $lang['Post_a_reply'];
-}
-else if($mode == "editpost")
-{
-	$post_a = $lang['Edit_Post'];
-}
-
-$page_title = $post_a;
 include($phpbb_root_path . 'includes/page_header.'.$phpEx);
 
+$template->set_filenames(array(
+	"body" => "posting_body.tpl", 
+	"pollbody" => "posting_poll_body.tpl", 
+	"jumpbox" => "jumpbox.tpl")
+);
+
+$jumpbox = make_jumpbox();
+$template->assign_vars(array(
+	"L_GO" => $lang['Go'],
+	"L_JUMP_TO" => $lang['Jump_to'],
+	"L_SELECT_FORUM" => $lang['Select_forum'],
+
+	"JUMPBOX_LIST" => $jumpbox,
+	"SELECT_NAME" => POST_FORUM_URL)
+);
+$template->assign_var_from_handle("JUMPBOX", "jumpbox");
+
+$template->assign_vars(array(
+	"FORUM_NAME" => $forum_name,
+	"L_POST_A" => $page_title,
+
+	"U_VIEW_FORUM" => append_sid("viewforum.$phpEx?" . POST_FORUM_URL . "=$forum_id"))
+);
+
+//
+// Output preview of post if requested
+//
+if( $preview && !$error )
+{
+
+	$orig_word = array();
+	$replacement_word = array();
+	$result = obtain_word_list($orig_word, $replacement_word);
+
+	if( $bbcode_on )
+	{
+		$bbcode_uid = make_bbcode_uid();
+	}
+
+	$preview_subject = $post_subject;
+	$preview_message = prepare_message($post_message, $html_on, $bbcode_on, $smilies_on, $bbcode_uid);
+
+	//
+	// Finalise processing as per viewtopic
+	//
+	if( !$html_on )
+	{
+		if( $user_sig != "" )
+		{
+			$user_sig = preg_replace("#(<)([\/]?.*?)(>)#is", "&lt;\\2&gt;", $user_sig);
+		}
+	}
+
+	if( $user_sig != "" && $board_config['allow_bbcode'] )
+	{
+		$sig_uid = make_bbcode_uid();
+		$user_sig = bbencode_first_pass($user_sig, $sig_uid);
+		$user_sig = bbencode_second_pass($user_sig, $sig_uid);
+	}
+
+	if( $bbcode_on )
+	{
+		$preview_message = bbencode_second_pass($preview_message, $bbcode_uid);
+	}
+
+	if( $attach_sig && $user_sig != "" )
+	{
+		$preview_message = $preview_message . "<br /><br />_________________<br />" . $user_sig;
+	}
+
+	if( count($orig_word) )
+	{
+		$preview_subject = preg_replace($orig_word, $replacement_word, $preview_subject);
+		$preview_message = preg_replace($orig_word, $replacement_word, $preview_message);
+	}
+
+	if( $smilies_on )
+	{
+		$preview_message = smilies_pass($preview_message);
+	}
+
+	$preview_message = make_clickable($preview_message);
+	$preview_message = str_replace("\n", "<br />", $preview_message);
+
+	$template->set_filenames(array(
+		"preview" => "posting_preview.tpl")
+	);
+	$template->assign_vars(array(
+		"TOPIC_TITLE" => $preview_subject,
+		"POST_SUBJECT" => $preview_subject,
+		"POSTER_NAME" => $username,
+		"POST_DATE" => create_date($board_config['default_dateformat'], time(), $board_config['default_timezone']),
+		"MESSAGE" => $preview_message,
+
+		"L_PREVIEW" => $lang['Preview'],
+		"L_POSTED" => $lang['Posted'])
+	);
+	$template->pparse("preview");
+
+}
+//
+// End preview output
+//
+
 //
 // Start Error handling
 //
-if($error)
+if( $error )
 {
 	$template->set_filenames(array(
 		"reg_header" => "error_body.tpl")
@@ -1205,201 +1875,19 @@ if($error)
 // End error handling
 //
 
-if(empty($username))
+//
+// User not logged in so offer up a username
+// field box
+//
+if( !$userdata['session_logged_in'] )
 {
-	$username = stripslashes($userdata['username']);
+	$template->assign_block_vars("username_select", array());
 }
 
-//
-// Define a signature, this is in practice only used for
-// preview but doing this here allows us to use it as a
-// check for attach_sig later
-//
-if( $mode == "editpost" )
-{
-	$user_sig = ($postrow['user_sig'] != "") ? $postrow['user_sig'] : "";
-}
-else
-{
-	$user_sig = ($userdata['user_sig'] != "") ? $userdata['user_sig'] : "";
-}
-
-//
-// Start: Preview Post
-//
-if($preview && !$error)
-{
-	switch($topic_type)
-	{
-		case POST_ANNOUNCE:
-			$is_announce = TRUE;
-			break;
-
-		case POST_STICKY:
-			$is_sticky = TRUE;
-			break;
-	}
-
-	//
-	// Define censored word matches
-	//
-	$sql = "SELECT word, replacement
-		FROM  " . WORDS_TABLE;
-	if( !$words_result = $db->sql_query($sql) )
-	{
-		message_die(GENERAL_ERROR, "Couldn't get censored words from database.", "", __LINE__, __FILE__, $sql);
-	}
-	else
-	{
-		$word_list = $db->sql_fetchrowset($words_result);
-
-		$orig_word = array();
-		$replacement_word = array();
-
-		for($i = 0; $i < count($word_list); $i++)
-		{
-			$word = str_replace("\*", "\w*?", preg_quote($word_list[$i]['word']));
-
-			$orig_word[] = "/\b(" . $word . ")\b/i";
-			$replacement_word[] = $word_list[$i]['replacement'];
-		}
-	}
-
-	if($bbcode_on)
-	{
-		$bbcode_uid = make_bbcode_uid();
-	}
-
-	$preview_message = stripslashes(prepare_message($message, $html_on, $bbcode_on, $smilies_on, $bbcode_uid));
-
-	//
-	// Finalise processing as per viewtopic
-	//
-	if( !$html_on )
-	{
-		if($user_sig != "")
-		{
-			$user_sig = htmlspecialchars($user_sig);
-		}
-		$preview_message = htmlspecialchars($preview_message);
-	}
-
-	if($user_sig != "")
-	{
-		$sig_uid = make_bbcode_uid();
-		$user_sig = bbencode_first_pass($user_sig, $sig_uid);
-		$user_sig = bbencode_second_pass($user_sig, $sig_uid);
-	}
-
-	if($bbcode_on)
-	{
-		$preview_message = bbencode_second_pass($preview_message, $bbcode_uid);
-
-		//
-		// This compensates for bbcode's rather agressive (but I guess necessary)
-		// HTML handling
-		//
-		if( !$html_on )
-		{
-			$preview_message = preg_replace("'&amp;'", "&", $preview_message);
-		}
-	}
-	else
-	{
-		// Removes UID from BBCode entries
-		$preview_message = preg_replace("/\:[0-9a-z\:]+\]/si", "]", $preview_message);
-	}
-
-	if( count($orig_word) )
-	{
-		$preview_subject = preg_replace($orig_word, $replacement_word, stripslashes($subject));
-		$preview_message = preg_replace($orig_word, $replacement_word, $preview_message);
-	}
-
-	if($smilies_on)
-	{
-		$preview_message = smilies_pass($preview_message);
-	}
-
-	if($attach_sig && $user_sig != "")
-	{
-		$preview_message = $preview_message . "<br /><br />_________________<br />" . $user_sig;
-	}
-
-	$preview_message = make_clickable($preview_message);
-	$preview_message = str_replace("\n", "<br />", $preview_message);
-
-	$template->set_filenames(array(
-		"preview" => "posting_preview.tpl")
-	);
-	$template->assign_vars(array(
-		"TOPIC_TITLE" => $preview_subject,
-		"POST_SUBJECT" => $preview_subject,
-		"POSTER_NAME" => stripslashes($username),
-		"POST_DATE" => create_date($board_config['default_dateformat'], time(), $board_config['default_timezone']),
-		"MESSAGE" => $preview_message,
-
-		"L_PREVIEW" => $lang['Preview'],
-		"L_POSTED" => $lang['Posted'])
-	);
-	$template->pparse("preview");
-}
-//
-// End Preview Post
-//
-
-//
-// Show the same form for each mode.
-//
-if( empty($forum_id) )
-{
-	message_die(GENERAL_ERROR, $lang['Forum_not_exist']);
-}
-
-$sql = "SELECT forum_name
-	FROM " . FORUMS_TABLE . "
-	WHERE forum_id = $forum_id";
-if(!$result = $db->sql_query($sql))
-{
-	message_die(GENERAL_ERROR, "Could not obtain forum information.", "", __LINE__, __FILE__, $sql);
-}
-$forum_info = $db->sql_fetchrow($result);
-$forum_name = stripslashes($forum_info['forum_name']);
-
-$template->set_filenames(array(
-	"body" => "posting_body.tpl",
-	"jumpbox" => "jumpbox.tpl")
-);
-
-$jumpbox = make_jumpbox();
-$template->assign_vars(array(
-	"L_GO" => $lang['Go'],
-	"L_JUMP_TO" => $lang['Jump_to'],
-	"L_SELECT_FORUM" => $lang['Select_forum'],
-	"JUMPBOX_LIST" => $jumpbox,
-	"SELECT_NAME" => POST_FORUM_URL)
-);
-$template->assign_var_from_handle("JUMPBOX", "jumpbox");
-
-$template->assign_vars(array(
-	"FORUM_ID" => $forum_id,
-	"FORUM_NAME" => $forum_name,
-
-	"L_POSTNEWIN" => $section_title,
-
-	"U_VIEW_FORUM" => append_sid("viewforum.$phpEx?" . POST_FORUM_URL . "=$forum_id"))
-);
-
-//
-// Generate form data
-//
-$display_username = ($userdata['session_logged_in']) ? stripslashes($userdata["username"]) : "";
-$display_subject = ($subject != "") ? stripslashes($subject) : "";
-
 //
 // HTML toggle selection
 //
-if($board_config['allow_html'])
+if( $board_config['allow_html'] )
 {
 	$html_status = $lang['ON'];
 	$template->assign_block_vars("html_checkbox", array());
@@ -1444,10 +1932,18 @@ if( $user_sig != "" )
 	$template->assign_block_vars("signature_checkbox", array());
 }
 
+//
+// Notify checkbox - only show if user is logged in
+//
+if( $userdata['session_logged_in'] )
+{
+	$template->assign_block_vars("notify_checkbox", array());
+}
+
 //
 // Delete selection
 //
-if($mode == 'editpost' && !$preview && ( $is_last_post || $is_auth['auth_mod'] ) )
+if( $mode == 'editpost' && ( ( $is_auth['auth_delete'] && $is_last_post_topic && ( !$post_has_poll || $can_edit_poll ) ) || $is_auth['auth_mod'] ) )
 {
 	$template->assign_block_vars("delete_checkbox", array());
 }
@@ -1456,26 +1952,26 @@ if($mode == 'editpost' && !$preview && ( $is_last_post || $is_auth['auth_mod'] )
 // Topic type selection
 //
 $topic_type_radio = '';
-if($mode == 'newtopic' || ( $mode == 'editpost' && $is_first_post ) )
+if( $mode == 'newtopic' || ( $mode == 'editpost' && $is_first_post_topic ) )
 {
 	$template->assign_block_vars("type_toggle", array());
 
-	if($is_auth['auth_announce'])
+	if( $is_auth['auth_announce'] )
 	{
 		$announce_toggle = '<input type="radio" name="topictype" value="announce"';
-		if($is_announce)
+		if( $topic_type == POST_ANNOUNCE )
 		{
-			$announce_toggle .= ' checked';
+			$announce_toggle .= ' checked="checked"';
 		}
 		$announce_toggle .= ' /> ' . $lang['Post_Announcement'] . '&nbsp;&nbsp;';
 	}
 
-	if($is_auth['auth_sticky'])
+	if( $is_auth['auth_sticky'] )
 	{
 		$sticky_toggle = '<input type="radio" name="topictype" value="sticky"';
-		if($is_sticky)
+		if( $topic_type == POST_STICKY )
 		{
-			$sticky_toggle .= ' checked';
+			$sticky_toggle .= ' checked="checked"';
 		}
 		$sticky_toggle .= ' /> ' . $lang['Post_Sticky'] . '&nbsp;&nbsp;';
 	}
@@ -1483,9 +1979,9 @@ if($mode == 'newtopic' || ( $mode == 'editpost' && $is_first_post ) )
 	if( $is_auth['auth_announce'] || $is_auth['auth_sticky'] )
 	{
 		$topic_type_toggle = $lang['Post_topic_as'] . ': <input type="radio" name="topictype" value="normal"';
-		if(!$is_announce && !$is_sticky)
+		if( $topic_type == POST_NORMAL )
 		{
-			$topic_type_toggle .= ' checked';
+			$topic_type_toggle .= ' checked="checked"';
 		}
 		$topic_type_toggle .= ' /> ' . $lang['Post_Normal'] . '&nbsp;&nbsp;' . $sticky_toggle . $announce_toggle;
 	}
@@ -1494,73 +1990,35 @@ if($mode == 'newtopic' || ( $mode == 'editpost' && $is_first_post ) )
 //
 // Define hidden fields
 //
-$hidden_form_fields = "";
-if($mode == "newtopic")
-{
-	$hidden_form_fields .= "<input type=\"hidden\" name=\"" . POST_FORUM_URL . "\" value=\"$forum_id\" />";
-}
-else if($mode == "reply")
-{
-	$hidden_form_fields .= "<input type=\"hidden\" name=\"" . POST_TOPIC_URL . "\" value=\"$topic_id\" />";
-}
-else if($mode == "editpost")
-{
-	$hidden_form_fields .= "<input type=\"hidden\" name=\"" . POST_TOPIC_URL . "\" value=\"$topic_id\" /><input type=\"hidden\" name=\"" . POST_POST_URL . "\" value=\"$post_id\" />";
-}
-$hidden_form_fields .= "<input type=\"hidden\" name=\"mode\" value=\"$mode\" />";
+$hidden_form_fields = '<input type="hidden" name="mode" value="' . $mode . '" />';
 
-//
-// User not logged in so offer up a username
-// field box
-//
-if( !$userdata['session_logged_in'] )
+switch($mode)
 {
-	$template->assign_block_vars("anon_user", array());
-}
+	case 'newtopic':
+		$hidden_form_fields .= '<input type="hidden" name="' . POST_FORUM_URL . '" value="' . $forum_id . '" />';
+		break;
 
-//
-// Here we check (if we're editing or replying)
-// whether the post has html/bbcode/smilies disabled
-// if it does then we modify the status vars appropriately
-//
-if( !$preview && $mode == "editpost" )
-{
-	if($postrow['enable_html'] && $board_config['allow_html'])
-	{
-		$html_on = TRUE;
-	}
-	else
-	{
-		$html_on = 0;
-	}
-	if($postrow['enable_bbcode'] && $board_config['allow_bbcode'])
-	{
-		$bbcode_on = TRUE;
-	}
-	else
-	{
-		$bbcode_on = 0;
-	}
-	if($postrow['enable_smilies'] && $board_config['allow_smilies'])
-	{
-		$smilies_on = TRUE;
-	}
-	else
-	{
-		$smilies_on = 0;
-	}
+	case 'reply':
+		$hidden_form_fields .= '<input type="hidden" name="' . POST_TOPIC_URL . '" value="' . $topic_id . '" />';
+		break;
+
+	case 'editpost':
+		$hidden_form_fields .= '<input type="hidden" name="' . POST_POST_URL . '" value="' . $post_id . '" />';
+		break;
 }
 
 //
 // Output the data to the template
 //
 $template->assign_vars(array(
-	"USERNAME" => $display_username,
-	"SUBJECT" => $display_subject,
-	"MESSAGE" => $message,
+	"USERNAME" => $post_username,
+	"SUBJECT" => $post_subject,
+	"MESSAGE" => $post_message,
 	"HTML_STATUS" => $html_status,
 	"BBCODE_STATUS" => $bbcode_status,
-	"SMILIES_STATUS" => $smilies_status,
+	"SMILIES_STATUS" => $smilies_status, 
+	"POLL_TITLE" => $poll_title,
+	"POLL_LENGTH" => $poll_length, 
 
 	"L_SUBJECT" => $lang['Subject'],
 	"L_MESSAGE_BODY" => $lang['Message_body'],
@@ -1569,30 +2027,72 @@ $template->assign_vars(array(
 	"L_SUBMIT" => $lang['Submit_post'],
 	"L_CANCEL" => $lang['Cancel_post'],
 	"L_CONFIRM_DELETE" => $lang['Confirm_delete'],
-	"L_POST_A" => $post_a,
 	"L_HTML_IS" => $lang['HTML'] . " " . $lang['is'],
 	"L_BBCODE_IS" => $lang['BBCode'] . " " . $lang['is'],
 	"L_SMILIES_ARE" => $lang['Smilies'] . " " . $lang['are'],
-
-	"L_DISABLE_HTML" => $lang['Disable'] . $lang['HTML'] . $lang['in_this_post'],
-	"L_DISABLE_BBCODE" => $lang['Disable'] . $lang['BBCode'] . $lang['in_this_post'],
-	"L_DISABLE_SMILIES" => $lang['Disable'] . $lang['Smilies'] . $lang['in_this_post'],
-	"L_ATTACH_SIGNATURE" => $lang['Attach_signature'],
-	"L_NOTIFY_ON_REPLY" => $lang['Notify'],
+	"L_DISABLE_HTML" => $lang['Disable'] . $lang['HTML'] . $lang['in_this_post'], 
+	"L_DISABLE_BBCODE" => $lang['Disable'] . $lang['BBCode'] . $lang['in_this_post'], 
+	"L_DISABLE_SMILIES" => $lang['Disable'] . $lang['Smilies'] . $lang['in_this_post'], 
+	"L_ATTACH_SIGNATURE" => $lang['Attach_signature'], 
+	"L_NOTIFY_ON_REPLY" => $lang['Notify'], 
 	"L_DELETE_POST" => $lang['Delete_post'],
 
-	"S_HTML_CHECKED" => (!$html_on) ? "checked=\"checked\"" : "",
-	"S_BBCODE_CHECKED" => (!$bbcode_on) ? "checked=\"checked\"" : "",
-	"S_SMILIES_CHECKED" => (!$smilies_on) ? "checked=\"checked\"" : "",
-	"S_SIGNATURE_CHECKED" => ($attach_sig) ? "checked=\"checked\"" : "",
-	"S_NOTIFY_CHECKED" => ($notify) ? "checked=\"checked\"" : "",
-	"S_TYPE_TOGGLE" => $topic_type_toggle,
-	"S_TOPIC_ID" => $topic_id,
-
+	"S_HTML_CHECKED" => (!$html_on) ? "checked=\"checked\"" : "", 
+	"S_BBCODE_CHECKED" => (!$bbcode_on) ? "checked=\"checked\"" : "", 
+	"S_SMILIES_CHECKED" => (!$smilies_on) ? "checked=\"checked\"" : "", 
+	"S_SIGNATURE_CHECKED" => ($attach_sig) ? "checked=\"checked\"" : "", 
+	"S_NOTIFY_CHECKED" => ($notify_user) ? "checked=\"checked\"" : "", 
+	"S_TYPE_TOGGLE" => $topic_type_toggle, 
+	"S_TOPIC_ID" => $topic_id, 
 	"S_POST_ACTION" => append_sid("posting.$phpEx"),
 	"S_HIDDEN_FORM_FIELDS" => $hidden_form_fields)
 );
 
+//
+// Poll entry switch/output
+//
+if( $display_poll )
+{
+	$template->assign_vars(array(
+		"L_ADD_A_POLL" => $lang['Add_poll'],  
+		"L_ADD_POLL_EXPLAIN" => $lang['Add_poll_explain'],   
+		"L_POLL_QUESTION" => $lang['Poll_question'],   
+		"L_POLL_OPTION" => $lang['Poll_option'],  
+		"L_ADD_OPTION" => $lang['Add_option'],
+		"L_UPDATE_OPTION" => $lang['Update'],
+		"L_DELETE_OPTION" => $lang['Delete'], 
+		"L_POLL_LENGTH" => $lang['Poll_for'],  
+		"L_DAYS" => $lang['Days'], 
+		"L_POLL_LENGTH_EXPLAIN" => $lang['Poll_for_explain'], 
+		"L_POLL_DELETE" => $lang['Delete_poll'],
+		
+		"POLL_LENGTH" => $poll_length)
+	);
+
+	if( $mode == "editpost" && ( $can_edit_poll || $is_auth['auth_mod'] ) && $post_has_poll )
+	{
+		$template->assign_block_vars("poll_delete_toggle", array());
+	}
+
+	if( is_array($poll_option_list) )
+	{
+		while( list($option_id, $option_text) = each($poll_option_list) )
+		{
+			$template->assign_block_vars("poll_option_rows", array(
+				"POLL_OPTION" => $option_text, 
+
+				"S_POLL_OPTION_NUM" => $option_id)
+			);
+		}
+	}
+
+	$template->assign_var_from_handle("POLLBOX", "pollbody");
+
+}
+
+//
+// Parse and print the body
+//
 $template->pparse("body");
 
 include($phpbb_root_path . 'includes/page_tail.'.$phpEx);
diff --git a/phpBB/templates/PSO/confirm_body.tpl b/phpBB/templates/PSO/confirm_body.tpl
index 1080beda67..e99585f1d9 100644
--- a/phpBB/templates/PSO/confirm_body.tpl
+++ b/phpBB/templates/PSO/confirm_body.tpl
@@ -1,13 +1,12 @@
-
-<div align="center"><table width="80%" cellpadding="1" cellspacing="0" border="0">
+<form action="{S_CONFIRM_ACTION}" method="POST"><table width="80%" cellpadding="1" cellspacing="0" border="0" align="center">
 	<tr>
 		<td class="tablebg"><table width="100%" cellpadding="4" cellspacing="1" border="0">
 			<tr>
 				<th class="secondary"><b>{MESSAGE_TITLE}</b></th>
 			</tr>
-			<tr><form action="{S_CONFIRM_ACTION}" method="POST">
-				<td class="row2" width="100%" align="center"><span class="gen">{MESSAGE_TEXT}</span><br /><br />{S_HIDDEN_FIELDS}<input type="submit" name="confirm" value="{L_YES}">&nbsp;&nbsp;<input type="submit" name="not_confirm" value="{L_NO}"><br /></td>
-			</form></tr>
+			<tr>
+				<td class="row2" width="100%" align="center"><br /><span class="gen">{MESSAGE_TEXT}</span><br /><br />{S_HIDDEN_FIELDS}<input type="submit" name="confirm" value="{L_YES}" />&nbsp;&nbsp;<input type="submit" name="cancel" value="{L_NO}" /><br /><br /></td>
+			</tr>
 		</table></td>
 	</tr>
 </table>
diff --git a/phpBB/templates/PSO/posting_body.tpl b/phpBB/templates/PSO/posting_body.tpl
index 8a62866890..cc7c35bd47 100644
--- a/phpBB/templates/PSO/posting_body.tpl
+++ b/phpBB/templates/PSO/posting_body.tpl
@@ -1,4 +1,4 @@
-<form action="{S_POST_ACTION}" method="POST"><table width="80%" cellspacing="0" cellpadding="4" border="0" align="center">
+<form action="{S_POST_ACTION}" method="POST" name="post"><table width="80%" cellspacing="0" cellpadding="4" border="0" align="center">
 	<tr>
 		<td align="left"><span class="gensmall"><a href="{U_INDEX}">{SITENAME}&nbsp;{L_INDEX}</a> -> <a href="{U_VIEW_FORUM}">{FORUM_NAME}</a></span></td>
 	</tr>
@@ -6,11 +6,33 @@
 
 <script language="JavaScript" type="text/javascript">
 <!--
-function insertCode(formObj, selectObj)
-{
-	formObj.message.value += selectObj.options[selectObj.selectedIndex].value;
-	return;
+//
+// This is 'borrowed' from subBlue's subSilver template
+// coming soon to phpBB 2.0 !
+//
+function bbstyle(formObj, bbopen, bbclose) {
+	if ((parseInt(navigator.appVersion) >= 4) && (navigator.appName == "Microsoft Internet Explorer")) {
+		theSelection = document.selection.createRange().text;
+		if (!theSelection) {
+			formObj.message.value += bbopen + bbclose;
+			formObj.message.focus();
+			return;
+		}
+		document.selection.createRange().text = bbopen + theSelection + bbclose;
+		formObj.message.focus();
+		return;
+	} else {
+		formObj.message.value += bbopen + bbclose;
+		formObj.message.focus();
+		return;
+	}
 }
+
+function emoticon(theSmilie) {
+	document.post.message.value += ' ' + theSmilie + ' ';
+	document.post.message.focus();
+}
+
 //-->
 </script>
 
@@ -20,22 +42,63 @@ function insertCode(formObj, selectObj)
 			<tr>
 				<td class="cat" colspan="2"><span class="cattitle"><b>{L_POST_A}</b></span></td>
 	        </tr>
-			<!-- BEGIN anon_user -->
+			<!-- BEGIN username_select -->
 			<tr>
 				<td class="row1"><span class="gen"><b>{L_USERNAME}</b></span></td>
 				<td class="row2"><span class="courier"><input type="text" name="username" size="25" maxlength="25" value="{USERNAME}" /></span></td>
 			</tr>
-			<!-- END anon_user -->
+			<!-- END username_select -->
             <tr>
 				<td class="row1"><span class="gen"><b>{L_SUBJECT}</b></span></td>
 				<td class="row2"><span class="courier"><input type="text" name="subject" size="50" maxlength="100" value="{SUBJECT}" /></span></td>
 			</tr>
 			<tr>
 				<td class="row1"><span class="gen"><b>{L_MESSAGE_BODY}</b></span><br /><br /><span class="gensmall">{L_HTML_IS} <u>{HTML_STATUS}</u><br />{L_BBCODE_IS} <u>{BBCODE_STATUS}</u><br />{L_SMILIES_ARE} <u>{SMILIES_STATUS}</u></span></td>
-				<td class="row2"><table width="100%" cellspacing="0" cellpadding="0" border="0">
+				<td class="row2" valign="middle"><table width="100%" cellspacing="0" cellpadding="0" border="0">
 					<tr>
-						<td><span class="courier"><textarea name="message" rows="10" cols="45" wrap="virtual">{MESSAGE}</textarea></span></td>
-						<td valign="top">&nbsp;<span class="gensmall">BBcodes:</span><br /><span class="couriersmall"><select class="small" name="addbbcode" size="6" onchange="insertCode(this.form, this);"> <option value="[b][/b]">[b] [/b]</option> <option value="[i][/i]">[i] [/i]</option> <option value="[quote][/quote]">[quote] [/quote]</option> <option value="[code][/code]">[code] [/code]</option> <option value="[list][/list]">[list] [/list]</option> <option value="[list=][/list]">[list=] [/list]</option> <option value="[img][/img]">[img] [/img]</option> <option value="[url][/url]">[url] [/url]</option></select></span> <br clear="all" />&nbsp;<span class="gensmall">Smiley codes:</span><br /><span class="couriersmall"><select class="small" name="addsmiley" size="1" onchange="insertCode(this.form, this);"> <option value=":)">Smiley</option> </option> <option value=";)">Wink</option> <option value=":d">Big Grin</option> <option value=":lol:">Laugh Out Loud</option> <option value=":(">Sad</option> <option value=":o">Eek!</option> <option value=":">Eek!</option> <option value=":oops:">Opps!</option> <option value="8)">Cool</option> <option value=":?">Confused</option> <option value=":roll:">Rolling Eyes</option> <option value=":p">Razz</option> <option value=":x">Mad</option> <option value=":|">Neutral</option> <option value=":!:">Exclamation</option> <option value=":?:">Question</option> <option value=":idea:">Idea</option> <option value=":arrow:">Arrow</option></select></span></td>
+						<td width="50%"><table border="0" cellspacing="0" cellpadding="2">
+							<tr>
+								<td align="center"><span class="courier"><input type="button" name="addbbcode1" value=" B " title="Bold" style="font-weight:bold" onClick="bbstyle(this.form,'[b]','[/b]');"> <input type="button" name="addbbcode2" value=" i " title="Italic" style="font-style:italic" onClick="bbstyle(this.form,'[i]','[/i]');"> <input type="button" name="addbbcode3" value="Quote" title="Quote"  onClick="bbstyle(this.form,'[quote]','[/quote]');"> <input type="button" name="addbbcode4" value="Code" title="Code"  onClick="bbstyle(this.form,'[code]','[/code]');"> <input type="button" name="addbbcode5" value="List" title="List"  onClick="bbstyle(this.form,'[list]','[/list]');"> <input type="button" name="addbbcode6" value="List=" title="Ordered list" onClick="bbstyle(this.form,'[list=]','[/list]');"> <input type="button" name="addbbcode7" value="Img" title="Image"  onClick="bbstyle(this.form,'[img]','[/img]');"> <input type="button" name="addbbcode8" value="URL" title="URL" style="text-decoration: underline" onClick="bbstyle(this.form,'[url]','[/url]');"></span></td>
+							</tr>
+							<tr>
+								<td><span class="courier"><textarea name="message" rows="12" cols="45" wrap="virtual" tabindex="2" />{MESSAGE}</textarea></span></td>
+							</tr>
+						</table></td>
+						<td width="50%" valign="middle"><table border="0" cellspacing="0" cellpadding="5" align="center">
+							<tr	align="center">
+								<td colspan="4"><span class="gensmall"><b>Emoticons</b></span></td>
+							</tr>
+							<tr align="center" valign="middle">
+								<td><a href="javascript:emoticon(':)')"><img src="images/smiles/icon_smile.gif" width="15" height="15"	border="0" alt="Smile"></a></td>
+								<td><a href="javascript:emoticon(':D')"><img src="images/smiles/icon_biggrin.gif" width="15" height="15"	border="0" alt="Big grin"></a></td>
+								<td><a href="javascript:emoticon(':lol:')"> <img src="images/smiles/icon_lol.gif" width="15" height="15"	border="0" alt="Laugh"></a></td>
+								<td><a href="javascript:emoticon(';)')"><img src="images/smiles/icon_wink.gif" width="15" height="15"	border="0" alt="Wink"></a></td>
+							</tr>
+							<tr align="center" valign="middle">
+								<td><a href="javascript:emoticon(':|')"><img src="images/smiles/icon_neutral.gif" width="15" height="15"	border="0"></a></td>
+								<td><a href="javascript:emoticon(':(')"><img src="images/smiles/icon_sad.gif" width="15" height="15"	border="0"></a></td>
+								<td><a href="javascript:emoticon(':?')"><img src="images/smiles/icon_confused.gif" width="15" height="15"	border="0"></a></td>
+								<td><a href="javascript:emoticon(':o')"><img src="images/smiles/icon_eek.gif" width="15" height="15"	border="0"></a></td>
+							</tr>
+							<tr align="center" valign="middle">
+								<td><a href="javascript:emoticon(':roll:')"><img src="images/smiles/icon_rolleyes.gif" width="15" height="15"	border="0"></a></td>
+								<td><a href="javascript:emoticon('8)')"><img src="images/smiles/icon_cool.gif" width="15" height="15"	border="0"></a></td>
+								<td><a href="javascript:emoticon(':p')"><img src="images/smiles/icon_razz.gif" width="15" height="15"	border="0"></a></td>
+								<td><a href="javascript:emoticon(':oops:')"><img src="images/smiles/icon_redface.gif" width="15" height="15"	border="0"></a></td>
+							</tr>
+							<tr align="center" valign="middle">
+								<td><a href="javascript:emoticon(':evil:')"><img src="images/smiles/icon_evil.gif" width="15" height="15"	border="0"></a></td>
+								<td><a href="javascript:emoticon(':x')"><img src="images/smiles/icon_mad.gif" width="15" height="15"	border="0"></a></td>
+								<td><a href="javascript:emoticon(':cry:')"><img src="images/smiles/icon_cry.gif" width="15" height="15"	border="0"></a></td>
+								<td><a href="javascript:emoticon(':o')"><img src="images/smiles/icon_surprised.gif" width="15" height="15"	border="0"></a></td>
+							</tr>
+							<tr align="center" valign="middle">
+								<td><a href="javascript:emoticon(':idea:')"><img src="images/smiles/icon_idea.gif" width="15" height="15"	border="0"></a></td>
+								<td><a href="javascript:emoticon(':?')"><img src="images/smiles/icon_question.gif" width="15" height="15"	border="0"></a></td>
+								<td><a href="javascript:emoticon(':!')"><img src="images/smiles/icon_exclaim.gif" width="15" height="15"	border="0"></a></td>
+								<td><a href="javascript:emoticon(':arrow:')"><img src="images/smiles/icon_arrow.gif" width="15" height="15"	border="0"></a></td>
+							</tr>
+						</table></td>
 					</tr>
 				</table></td>
 			</tr>
@@ -66,10 +129,12 @@ function insertCode(formObj, selectObj)
 						<td><span class="gen">{L_ATTACH_SIGNATURE}</span></td>
 					</tr>
 					<!-- END signature_checkbox -->
+					<!-- BEGIN notify_checkbox -->
 					<tr>
 						<td><input type="checkbox" name="notify" {S_NOTIFY_CHECKED} /></td>
 						<td><span class="gen">{L_NOTIFY_ON_REPLY}</span></td>
 					</tr>
+					<!-- END notify_checkbox -->
 					<!-- BEGIN delete_checkbox -->
 					<tr>
 						<td><input type="checkbox" name="delete" /></td>
@@ -79,13 +144,14 @@ function insertCode(formObj, selectObj)
 					<!-- BEGIN type_toggle -->
 					<tr>
 						<td></td>
-						<td><br /><span class="gen">{S_TYPE_TOGGLE}</span></td>
+						<td><span class="gen">{S_TYPE_TOGGLE}</span></td>
 					</tr>
 					<!-- END type_toggle -->
 				</table></td>
 			</tr>
+{POLLBOX}
 			<tr>
-				<td class="cat" colspan="2" align="center">{S_HIDDEN_FORM_FIELDS}<input type="submit" name="preview" value="{L_PREVIEW}">&nbsp;<input type="submit" name="submit" value="{L_SUBMIT}">&nbsp;<input type="submit" name="cancel" value="{L_CANCEL}"></td>
+				<td class="cat" colspan="2" align="center">{S_HIDDEN_FORM_FIELDS}<input type="submit" name="preview" value="{L_PREVIEW}" /> &nbsp;<input type="submit" name="submit" value="{L_SUBMIT}" /> &nbsp;<input type="submit" name="cancel" value="{L_CANCEL}" /></td>
 			</tr>
 		</table></td>
 	</tr>
diff --git a/phpBB/templates/PSO/posting_poll_body.tpl b/phpBB/templates/PSO/posting_poll_body.tpl
new file mode 100644
index 0000000000..ce12bef7d5
--- /dev/null
+++ b/phpBB/templates/PSO/posting_poll_body.tpl
@@ -0,0 +1,27 @@
+			<tr>
+				<td class="cat" colspan="2"><span class="cattitle"><b>{L_ADD_A_POLL}</b></span><br /><span class="gensmall">{L_ADD_POLL_EXPLAIN}</span></td>
+	        </tr>
+            <tr>
+				<td class="row1"><span class="gen"><b>{L_POLL_QUESTION}</b></span></td>
+				<td class="row2"><span class="courier"><input type="text" name="poll_title" size="50" maxlength="255" value="{POLL_TITLE}" /></span></td>
+			</tr>
+			<!-- BEGIN poll_option_rows -->
+            <tr>
+				<td class="row1"><span class="gen"><b>{L_POLL_OPTION}</b></span></td>
+				<td class="row2"><span class="courier"><input type="text" name="poll_option_text[{poll_option_rows.S_POLL_OPTION_NUM}]" size="50" maxlength="255" value="{poll_option_rows.POLL_OPTION}" /></span> &nbsp;<input type="submit" name="edit_poll_option[{poll_option_rows.S_POLL_OPTION_NUM}]" value="{L_UPDATE_OPTION}" /> <input type="submit" name="del_poll_option[{poll_option_rows.S_POLL_OPTION_NUM}]" value="{L_DELETE_OPTION}" /></td>
+			</tr>
+			<!-- END poll_option_rows -->
+            <tr>
+				<td class="row1"><span class="gen"><b>{L_POLL_OPTION}</b></span></td>
+				<td class="row2"><span class="courier"><input type="text" name="add_poll_option_text" size="50" maxlength="255" value="{ADD_POLL_OPTION}" /></span> &nbsp;<input type="submit" name="add_poll_option" value="{L_ADD_OPTION}" /></td>
+			</tr>
+            <tr>
+				<td class="row1"><span class="gen"><b>{L_POLL_LENGTH}</b></span></td>
+				<td class="row2"><span class="courier"><input type="text" name="poll_length" size="3" maxlength="3" value="{POLL_LENGTH}" /></span>&nbsp;<span class="gen"><b>{L_DAYS}</b></span> &nbsp; <span class="gensmall">{L_POLL_LENGTH_EXPLAIN}</span></td>
+			</tr>
+			<!-- BEGIN poll_delete_toggle -->
+            <tr>
+				<td class="row1"><span class="gen"><b>{L_POLL_DELETE}</b></span></td>
+				<td class="row2"><input type="checkbox" name="poll_delete" /></td>
+			</tr>
+			<!-- END poll_delete_toggle -->
\ No newline at end of file
diff --git a/phpBB/templates/PSO/viewtopic_body.tpl b/phpBB/templates/PSO/viewtopic_body.tpl
index c33e97dd36..59a5a39cc7 100644
--- a/phpBB/templates/PSO/viewtopic_body.tpl
+++ b/phpBB/templates/PSO/viewtopic_body.tpl
@@ -5,34 +5,32 @@
 	</tr>
 </table>
 
-<table border="0" cellpadding="1" cellspacing="0" width="98%" align="center">
+<table width="98%" cellpadding="1" cellspacing="0" border="0" align="center">
 	<tr>
 		<td class="tablebg"><table border="0" cellpadding="4" cellspacing="1" width="100%">
 			<tr>
 		        <td class="cat" colspan="2"><table width="100%" cellspacing="0" cellpadding="0" border="0"> 
 	                <tr>
                			<td><span class="cattitle"><b>{TOPIC_TITLE}</b></span></td> 
-               			<td align="right" valign="middle"><a href="{U_POST_NEW_TOPIC}"><img src="{IMG_POST}" border="1" alt="L_TOPIC_POST" /></a>&nbsp;&nbsp;<a href="{U_POST_REPLY_TOPIC}"><img src="{IMG_REPLY}" border="1" alt="L_TOPIC_REPLY" /></a></td>  
+               			<td align="right" valign="middle"><a href="{U_POST_NEW_TOPIC}"><img src="{IMG_POST}" border="0" alt="{L_TOPIC_POST}" /></a>&nbsp;&nbsp;<a href="{U_POST_REPLY_TOPIC}"><img src="{IMG_REPLY}" border="0" alt="{L_TOPIC_REPLY}" /></a></td>  
 	               </tr>
       			</table></td>
 			</tr>
+{POLL_DISPLAY}
 			<tr>
-				<th width="22%"><b>{L_AUTHOR}</b></th>
+				<th><b>{L_AUTHOR}</b></th>
 				<th><b>{L_MESSAGE}</b></th>
 			</tr>
 	        <!-- BEGIN postrow -->
 			<tr bgcolor="{postrow.ROW_COLOR}">
-				<td width="22%" align="left" valign="top"><a name="{postrow.U_POST_ID}"></a><table width="100%" height="100%" cellspacing="0" cellpadding="0" border="0">
+				<td align="left" valign="top"><a name="{postrow.U_POST_ID}"></a><table width="170" cellspacing="0" cellpadding="0" border="0">
 					<tr>
 						<td valign="top"><span class="gen"><b>{postrow.POSTER_NAME}</b></span><br /><span class="gensmall">{postrow.POSTER_RANK}<br />{postrow.RANK_IMAGE}{postrow.POSTER_AVATAR}<br /><br />{postrow.POSTER_JOINED}<br />{postrow.POSTER_POSTS}<br />{postrow.POSTER_FROM}</span><br /><br /></td>
 					</tr>
-					<tr>
-						<td valign="bottom"><span class="gensmall"><a href="#top">{L_RETURN_TO_TOP}</a></span></td>
-					</tr>
 				</table></td>
-				<td width="78%" height="100%"><table width="100%" height="100%" cellspacing="1" cellpadding="0" border="0">
+				<td width="100%" valign="top"><table width="100%" cellspacing="1" cellpadding="0" border="0">
 					<tr>
-						<td><table width="100%" cellspacing="0" cellpadding="0" border="0">
+						<td valign="top"><table width="100%" cellspacing="0" cellpadding="0" border="0">
 							<tr>
 								<td valign="middle"><img src="images/icon_minipost.gif" alt="Post image icon" /><span class="gensmall">{L_POSTED}: {postrow.POST_DATE}&nbsp;&nbsp;&nbsp;&nbsp;{L_POST_SUBJECT}: {postrow.POST_SUBJECT}</span></td>
 								<td align="right" valign="middle" nowrap="nowrap">&nbsp; {postrow.EDIT_IMG} {postrow.QUOTE_IMG}&nbsp;</td>
@@ -45,16 +43,14 @@
 					<tr>
 						<td width="100%" height="100%" valign="top"><span class="gen">{postrow.MESSAGE}</span></td>
 					</tr>
+				</table></td>
+			</tr>
+			<tr bgcolor="{postrow.ROW_COLOR}">
+				<td height="20" align="center" valign="middle"><span class="gensmall"><a href="#top">{L_RETURN_TO_TOP}</a></span></td>
+				<td height="20"><table width="100%" cellspacing="0" cellpadding="0" border="0">
 					<tr>
-						<td><table width="100%" cellspacing="0" cellpadding="0" border="0">
-							<tr>
-								<td colspan="2"><hr /></td>
-							</tr>
-							<tr>
-								<td valign="middle">&nbsp;{postrow.PROFILE_IMG} {postrow.PM_IMG} {postrow.EMAIL_IMG} {postrow.WWW_IMG} {postrow.ICQ_STATUS_IMG} {postrow.ICQ_ADD_IMG} {postrow.AIM_IMG} {postrow.YIM_IMG} {postrow.MSN_IMG}&nbsp;</td>
-								<td align="right" valign="middle">&nbsp;{postrow.IP_IMG}&nbsp;</td>
-							</tr>
-						</table></td>
+						<td valign="middle">&nbsp;{postrow.PROFILE_IMG} {postrow.PM_IMG} {postrow.EMAIL_IMG} {postrow.WWW_IMG} {postrow.ICQ_STATUS_IMG} {postrow.ICQ_ADD_IMG} {postrow.AIM_IMG} {postrow.YIM_IMG} {postrow.MSN_IMG}&nbsp;</td>
+						<td align="right" valign="middle">&nbsp;{postrow.IP_IMG}&nbsp;</td>
 					</tr>
 				</table></td>
 			</tr>
@@ -62,7 +58,7 @@
 			<tr>
 				<td class="cat" colspan="2"><table width="100%" cellspacing="0" cellpadding="0" border="0">
 					<tr>
-						<td width="140" align="left" valign="middle" nowrap="nowrap"><a href="{U_POST_REPLY_TOPIC}"><img src="{IMG_REPLY}" border="1" alt="{L_TOPIC_REPLY}" /></a>&nbsp;&nbsp;<a href="{U_POST_NEW_TOPIC}"><img src="{IMG_POST}" border="1" alt="{L_TOPIC_POST}" /></a></td>
+						<td width="140" align="left" valign="middle" nowrap="nowrap"><a href="{U_POST_REPLY_TOPIC}"><img src="{IMG_REPLY}" border="0" alt="{L_TOPIC_REPLY}" /></a>&nbsp;&nbsp;<a href="{U_POST_NEW_TOPIC}"><img src="{IMG_POST}" border="0" alt="{L_TOPIC_POST}" /></a></td>
 						<td align="left" valign="middle">&nbsp;<span class="gen">{L_PAGE} <b>{ON_PAGE}</b> {L_OF} <b>{TOTAL_PAGES}</b></span>&nbsp;</td>
 						<td align="right" valign="middle"><span class="gen">{PAGINATION}</span></td>
 					</tr>
diff --git a/phpBB/templates/PSO/viewtopic_poll_ballot.tpl b/phpBB/templates/PSO/viewtopic_poll_ballot.tpl
new file mode 100644
index 0000000000..4f53f92ada
--- /dev/null
+++ b/phpBB/templates/PSO/viewtopic_poll_ballot.tpl
@@ -0,0 +1,23 @@
+			<tr>
+				<td class="row2" colspan="2"><br clear="all" /><form method="POST" action="{S_VOTE_ACTION}"><table cellspacing="0" cellpadding="4" border="0" align="center">
+					<tr>
+						<td align="center"><span class="gen"><b>{POLL_QUESTION}</b></span></td>
+					</tr>
+					<tr>
+						<td align="center"><table cellspacing="0" cellpadding="2" border="0">
+							<!-- BEGIN poll_option -->
+							<tr>
+								<td><input type="radio" name="vote_id" value="{poll_option.POLL_OPTION_ID}">&nbsp;</td>
+								<td><span class="gensmall">{poll_option.POLL_OPTION_CAPTION}</span></td>
+							</tr>
+							<!-- END poll_option -->
+						</table></td>
+					</tr>
+					<tr>
+						<td align="center"><input type="submit" name="submit" value="{L_SUBMIT_VOTE}" /></td>
+					</tr>
+					<tr>
+						<td align="center"><span class="gensmall"><a href="{U_VIEW_RESULTS}">{L_VIEW_RESULTS}</a></span></td>
+					</tr>
+				</table>{S_HIDDEN_FIELDS}</form></td>
+			</tr>
\ No newline at end of file
diff --git a/phpBB/templates/PSO/viewtopic_poll_result.tpl b/phpBB/templates/PSO/viewtopic_poll_result.tpl
new file mode 100644
index 0000000000..36c1f41bb0
--- /dev/null
+++ b/phpBB/templates/PSO/viewtopic_poll_result.tpl
@@ -0,0 +1,26 @@
+			<tr>
+				<td class="row2" colspan="2"><br clear="all" /><table cellspacing="0" cellpadding="4" border="0" align="center">
+					<tr>
+						<td colspan="4" align="center"><span class="gen"><b>{POLL_QUESTION}</b></span></td>
+					</tr>
+					<tr>
+						<td align="center"><table cellspacing="0" cellpadding="2" border="0">
+							<!-- BEGIN poll_option -->
+							<tr>
+								<td><span class="gensmall">{poll_option.POLL_OPTION_CAPTION}</span></td>
+								<td><table width="{poll_option.POLL_OPTION_IMG_WIDTH}" cellspacing="0" cellpadding="0" border="0">
+									<tr>
+										<td width="100%" bgcolor="{poll_option.POLL_OPTION_IMG_COLOR}"><img src="{poll_option.POLL_OPTION_IMG}" width="{poll_option.POLL_OPTION_IMG_WIDTH}" height="8" alt="{poll_option.POLL_OPTION_PERCENT}" /></td>
+									</tr>
+								</table></td>
+								<td align="center">&nbsp;<span class="gensmall"><b>{poll_option.POLL_OPTION_PERCENT}</b></span>&nbsp;</td>
+								<td align="center">&nbsp;<span class="gensmall">[ {poll_option.POLL_OPTION_RESULT} ]</span>&nbsp;</td>
+							</tr>
+							<!-- END poll_option -->
+						</table></td>
+					</tr>
+					<tr>
+						<td colspan="4" align="center"><span class="gensmall"><b>Total Votes : {TOTAL_VOTES}</b></span></td>
+					</tr>
+				</table><br clear="all" /></td>
+			</tr>
\ No newline at end of file
diff --git a/phpBB/viewforum.php b/phpBB/viewforum.php
index d727803c8f..b718d2ec74 100644
--- a/phpBB/viewforum.php
+++ b/phpBB/viewforum.php
@@ -65,7 +65,7 @@ init_userprefs($userdata);
 //
 if(isset($forum_id))
 {
-	$sql = "SELECT forum_name, forum_status, forum_topics, auth_view, auth_read, auth_post, auth_reply, auth_edit, auth_delete, auth_votecreate, auth_vote, prune_enable, prune_next
+	$sql = "SELECT forum_name, forum_status, forum_topics, auth_view, auth_read, auth_post, auth_reply, auth_edit, auth_delete, auth_pollcreate, auth_vote, prune_enable, prune_next
 		FROM " . FORUMS_TABLE . "
 		WHERE forum_id = $forum_id";
 	if(!$result = $db->sql_query($sql))
@@ -88,7 +88,7 @@ if(!$total_rows = $db->sql_numrows($result))
 }
 $forum_row = $db->sql_fetchrow($result);
 
-$forum_name = stripslashes($forum_row['forum_name']);
+$forum_name = $forum_row['forum_name'];
 
 //
 // Start auth check
@@ -190,18 +190,18 @@ if(!empty($HTTP_POST_VARS['topicdays']) || !empty($HTTP_GET_VARS['topicdays']))
 		FROM " . TOPICS_TABLE . " t, " . POSTS_TABLE . " p
 		WHERE t.forum_id = $forum_id
 			AND p.post_id = t.topic_last_post_id
-			AND ( p.post_time >= $min_topic_time
-				OR t.topic_type = " . POST_ANNOUNCE . " )";
+			AND p.post_time >= $min_topic_time";
 
 	if(!$result = $db->sql_query($sql))
 	{
 		message_die(GENERAL_ERROR, "Couldn't obtain limited topics count information", "", __LINE__, __FILE__, $sql);
 	}
-	list($topics_count) = $db->sql_fetchrow($result);
+	$row = $db->sql_fetchrow($result);
 
-	$limit_topics_time = "AND ( p.post_time >= $min_topic_time OR t.topic_type = " . POST_ANNOUNCE . " ) ";
+	$topics_count = $row['forum_topics'];
+	$limit_topics_time = "AND p.post_time >= $min_topic_time";
 
-	if(!empty($HTTP_POST_VARS['topicdays']))
+	if( !empty($HTTP_POST_VARS['topicdays']) )
 	{
 		$start = 0;
 	}
@@ -232,7 +232,6 @@ $sql = "SELECT t.*, u.username, u.user_id, u2.username as user2, u2.user_id as i
 		AND t.topic_poster = u.user_id
 		AND p.post_id = t.topic_last_post_id
 		AND p.poster_id = u2.user_id
-		AND t.topic_type <> " . POST_GLOBAL_ANNOUNCE . "
 		AND t.topic_type <> " . POST_ANNOUNCE . "
 		$limit_topics_time
 	ORDER BY t.topic_type DESC, p.post_time DESC
@@ -249,8 +248,7 @@ $total_topics = $db->sql_numrows($t_result);
 //
 $sql = "SELECT t.*, u.username, u.user_id, u2.username as user2, u2.user_id as id2, p.post_time, p.post_username
 	FROM " . TOPICS_TABLE . " t, " . USERS_TABLE . " u, " . POSTS_TABLE . " p, " . USERS_TABLE . " u2
-	WHERE ( t.forum_id = $forum_id
-			OR t.forum_id = -1 )
+	WHERE t.forum_id IN ($forum_id, -1)
 		AND t.topic_poster = u.user_id
 		AND p.post_id = t.topic_last_post_id
 		AND p.poster_id = u2.user_id
@@ -270,27 +268,9 @@ $total_topics += $total_announcements;
 //
 // Define censored word matches
 //
-$sql = "SELECT word, replacement
-	FROM  " . WORDS_TABLE;
-if( !$words_result = $db->sql_query($sql) )
-{
-	message_die(GENERAL_ERROR, "Couldn't get censored words from database.", "", __LINE__, __FILE__, $sql);
-}
-else
-{
-	$word_list = $db->sql_fetchrowset($words_result);
-
-	$orig_word = array();
-	$replacement_word = array();
-
-	for($i = 0; $i < count($word_list); $i++)
-	{
-		$word = str_replace("\*", "\w*?", preg_quote($word_list[$i]['word']));
-
-		$orig_word[] = "/\b(" . $word . ")\b/i";
-		$replacement_word[] = $word_list[$i]['replacement'];
-	}
-}
+$orig_word = array();
+$replacement_word = array();
+obtain_word_list($orig_word, $replacement_word);
 
 //
 // Post URL generation for templating vars
@@ -332,12 +312,6 @@ else
 	$s_auth_mod_img = "";
 }
 
-//
-// Dump out the page header and load viewforum template
-//
-$page_title = $lang['View_forum'] . " - $forum_name";
-include($phpbb_root_path . 'includes/page_header.'.$phpEx);
-
 $template->set_filenames(array(
 	"body" => "viewforum_body.tpl",
 	"jumpbox" => "jumpbox.tpl")
@@ -398,11 +372,11 @@ if($total_topics)
 	{
 		if( count($orig_word) )
 		{
-			$topic_title = preg_replace($orig_word, $replacement_word, stripslashes($topic_rowset[$i]['topic_title']));
+			$topic_title = preg_replace($orig_word, $replacement_word, $topic_rowset[$i]['topic_title']);
 		}
 		else
 		{
-			$topic_title = stripslashes($topic_rowset[$i]['topic_title']);
+			$topic_title = $topic_rowset[$i]['topic_title'];
 		}
 
 		$topic_type = $topic_rowset[$i]['topic_type'];
@@ -426,7 +400,7 @@ if($total_topics)
 
 		if($replies > $board_config['posts_per_page'])
 		{
-			$goto_page = "&nbsp;&nbsp;&nbsp;(<img src=\"" . $images['icon_minipost'] . "\" />" . $lang['Goto_page'] . ": ";
+			$goto_page = "&nbsp;&nbsp;&nbsp;(<img src=\"" . $images['icon_minipost'] . "\" alt=\"" . $lang['Goto_page'] . "\" />" . $lang['Goto_page'] . ": ";
 
 			$times = 1;
 			for($j = 0; $j < $replies + 1; $j += $board_config['posts_per_page'])
@@ -490,11 +464,11 @@ if($total_topics)
 				}
 			}
 
-			if(empty($HTTP_COOKIE_VARS['phpbb2_' . $forum_id . '_' . $topic_id]) && $topic_rowset[$i]['post_time'] > $userdata['session_last_visit'])
+			if( empty($HTTP_COOKIE_VARS['phpbb2_' . $forum_id . '_' . $topic_id]) && $topic_rowset[$i]['post_time'] > $userdata['session_last_visit'] )
 			{
 				if($mark_read == "topics")
 				{
-					setcookie('phpbb2_' . $forum_id . '_' . $topic_id, time(), time()+6000, $board_config['cookie_path'], $board_config['cookie_domain'], $board_config['cookie_secure']);
+					setcookie('phpbb2_' . $forum_id . '_' . $topic_id, time(), 0, $board_config['cookie_path'], $board_config['cookie_domain'], $board_config['cookie_secure']);
 					$folder_image = "<img src=\"$folder\" alt=\"" . $lang['No_new_posts'] . "\" />";
 				}
 				else
@@ -508,7 +482,7 @@ if($total_topics)
 				{
 					if($mark_read == "topics")
 					{
-						setcookie('phpbb2_' . $forum_id . '_' . $topic_id, time(), time()+6000, $board_config['cookie_path'], $board_config['cookie_domain'], $board_config['cookie_secure']);
+						setcookie('phpbb2_' . $forum_id . '_' . $topic_id, time(), 0, $board_config['cookie_path'], $board_config['cookie_domain'], $board_config['cookie_secure']);
 						$folder_image = "<img src=\"$folder\" alt=\"" . $lang['No_new_posts'] . "\" />";
 					}
 					else
@@ -525,7 +499,7 @@ if($total_topics)
 
 		$view_topic_url = append_sid("viewtopic.$phpEx?" . POST_TOPIC_URL . "=$topic_id");
 
-		$topic_poster = stripslashes($topic_rowset[$i]['username']);
+		$topic_poster = $topic_rowset[$i]['username'];
 		$topic_poster_profile_url = append_sid("profile.$phpEx?mode=viewprofile&amp;" . POST_USERS_URL . "=" . $topic_rowset[$i]['user_id']);
 
 		$last_post_time = create_date($board_config['default_dateformat'], $topic_rowset[$i]['post_time'], $board_config['default_timezone']);
@@ -582,15 +556,19 @@ else
 	//
 	$no_topics_msg = ($forum_row['forum_status'] == FORUM_LOCKED) ? $lang['Forum_locked'] : $lang['No_topics_post_one'];
 	$template->assign_vars(array(
-		"L_NO_TOPICS" => $no_topics_msg,
-
-		"S_NO_TOPICS" => TRUE)
+		"L_NO_TOPICS" => $no_topics_msg)
 	);
 
 	$template->assign_block_vars("notopicsrow", array() );
 
 }
 
+//
+// Dump out the page header and load viewforum template
+//
+$page_title = $lang['View_forum'] . " - $forum_name";
+include($phpbb_root_path . 'includes/page_header.'.$phpEx);
+
 //
 // Parse the page and print
 //
@@ -601,4 +579,4 @@ $template->pparse("body");
 //
 include($phpbb_root_path . 'includes/page_tail.'.$phpEx);
 
-?>
+?>
\ No newline at end of file
diff --git a/phpBB/viewtopic.php b/phpBB/viewtopic.php
index 1d14d33023..c4233c0c77 100644
--- a/phpBB/viewtopic.php
+++ b/phpBB/viewtopic.php
@@ -105,9 +105,9 @@ $join_sql_table = (!isset($post_id)) ? "" : "" . POSTS_TABLE . " p, " . POSTS_TA
 $join_sql = (!isset($post_id)) ? "t.topic_id = $topic_id" : "p.post_id = $post_id AND t.topic_id = p.topic_id AND p2.topic_id = p.topic_id AND p2.post_id <= $post_id";
 $count_sql = (!isset($post_id)) ? "" : ", COUNT(p2.post_id) AS prev_posts";
 
-$order_sql = (!isset($post_id)) ? "" : "GROUP BY p.post_id, t.topic_id, t.topic_title, t.topic_status, t.topic_replies, t.topic_time, f.forum_name, f.forum_status, f.forum_id, f.auth_view, f.auth_read, f.auth_post, f.auth_reply, f.auth_edit, f.auth_delete, f.auth_sticky, f.auth_announce, f.auth_votecreate, f.auth_vote, f.auth_attachments ORDER BY p.post_id ASC";
+$order_sql = (!isset($post_id)) ? "" : "GROUP BY p.post_id, t.topic_id, t.topic_title, t.topic_status, t.topic_replies, t.topic_time, t.topic_type, t.topic_vote, f.forum_name, f.forum_status, f.forum_id, f.auth_view, f.auth_read, f.auth_post, f.auth_reply, f.auth_edit, f.auth_delete, f.auth_sticky, f.auth_announce, f.auth_pollcreate, f.auth_vote, f.auth_attachments ORDER BY p.post_id ASC";
 
-$sql = "SELECT t.topic_id, t.topic_title, t.topic_status, t.topic_replies, t.topic_time, f.forum_name, f.forum_status, f.forum_id, f.auth_view, f.auth_read, f.auth_post, f.auth_reply, f.auth_edit, f.auth_delete, f.auth_sticky, f.auth_announce, f.auth_votecreate, f.auth_vote, f.auth_attachments" . $count_sql . "
+$sql = "SELECT t.topic_id, t.topic_title, t.topic_status, t.topic_replies, t.topic_time, t.topic_type, t.topic_vote, f.forum_name, f.forum_status, f.forum_id, f.auth_view, f.auth_read, f.auth_post, f.auth_reply, f.auth_edit, f.auth_delete, f.auth_sticky, f.auth_announce, f.auth_pollcreate, f.auth_vote, f.auth_attachments" . $count_sql . "
 	FROM $join_sql_table " . TOPICS_TABLE . " t, " . FORUMS_TABLE . " f
 	WHERE $join_sql
 		AND f.forum_id = t.forum_id
@@ -164,7 +164,7 @@ if(!$is_auth['auth_view'] || !$is_auth['auth_read'])
 //
 
 //
-// Is user watching this thread? This could potentially
+// Is user watching this thread? This could potentially 
 // be combined into the above query but the LEFT JOIN causes
 // a number of problems which will probably end up in this
 // solution being practically as fast and certainly simpler!
@@ -173,9 +173,9 @@ if($userdata['user_id'] != ANONYMOUS)
 {
 	$can_watch_topic = TRUE;
 
-	$sql = "SELECT notify_status
-		FROM " . TOPICS_WATCH_TABLE . "
-		WHERE topic_id = $topic_id
+	$sql = "SELECT notify_status 
+		FROM " . TOPICS_WATCH_TABLE . " 
+		WHERE topic_id = $topic_id 
 			AND user_id = " . $userdata['user_id'];
 	if( !$result = $db->sql_query($sql) )
 	{
@@ -190,8 +190,8 @@ if($userdata['user_id'] != ANONYMOUS)
 				$is_watching_topic = 0;
 
 				$sql_priority = (SQL_LAYER == "mysql") ? "LOW_PRIORITY" : "";
-				$sql = "DELETE $sql_priority FROM " . TOPICS_WATCH_TABLE . "
-					WHERE topic_id = $topic_id
+				$sql = "DELETE $sql_priority FROM " . TOPICS_WATCH_TABLE . " 
+					WHERE topic_id = $topic_id 
 						AND user_id = " . $userdata['user_id'];
 				if( !$result = $db->sql_query($sql) )
 				{
@@ -208,9 +208,9 @@ if($userdata['user_id'] != ANONYMOUS)
 			if( $watch_data['notify_status'] )
 			{
 				$sql_priority = (SQL_LAYER == "mysql") ? "LOW_PRIORITY" : "";
-				$sql = "UPDATE $sql_priority " . TOPICS_WATCH_TABLE . "
-					SET notify_status = 0
-					WHERE topic_id = $topic_id
+				$sql = "UPDATE $sql_priority " . TOPICS_WATCH_TABLE . " 
+					SET notify_status = 0 
+					WHERE topic_id = $topic_id 
 						AND user_id = " . $userdata['user_id'];
 				if( !$result = $db->sql_query($sql) )
 				{
@@ -228,7 +228,7 @@ if($userdata['user_id'] != ANONYMOUS)
 				$is_watching_topic = TRUE;
 
 				$sql_priority = (SQL_LAYER == "mysql") ? "LOW_PRIORITY" : "";
-				$sql = "INSERT $sql_priority INTO " . TOPICS_WATCH_TABLE . " (user_id, topic_id, notify_status)
+				$sql = "INSERT $sql_priority INTO " . TOPICS_WATCH_TABLE . " (user_id, topic_id, notify_status) 
 					VALUES (" . $userdata['user_id'] . ", $topic_id, 0)";
 				if( !$result = $db->sql_query($sql) )
 				{
@@ -279,7 +279,8 @@ if(!empty($HTTP_POST_VARS['postdays']) || !empty($HTTP_GET_VARS['postdays']))
 	{
 		message_die(GENERAL_ERROR, "Couldn't obtain limited topics count information", "", __LINE__, __FILE__, $sql);
 	}
-	list($total_replies) = $db->sql_fetchrow($result);
+
+	$total_replies = ( $row = $db->sql_fetchrow($result) ) ? $row['num_posts'] : 0;
 
 	$limit_posts_time = "AND p.post_time >= $min_post_time ";
 
@@ -362,27 +363,9 @@ $ranksrow = $db->sql_fetchrowset($ranksresult);
 //
 // Define censored word matches
 //
-$sql = "SELECT word, replacement
-	FROM  " . WORDS_TABLE;
-if( !$words_result = $db->sql_query($sql) )
-{
-	message_die(GENERAL_ERROR, "Couldn't get censored words from database.", "", __LINE__, __FILE__, $sql);
-}
-else
-{
-	$word_list = $db->sql_fetchrowset($words_result);
-
-	$orig_word = array();
-	$replacement_word = array();
-
-	for($i = 0; $i < count($word_list); $i++)
-	{
-		$word = str_replace("\*", "\w*?", preg_quote($word_list[$i]['word']));
-
-		$orig_word[] = "/\b(" . $word . ")\b/i";
-		$replacement_word[] = $word_list[$i]['replacement'];
-	}
-}
+$orig_word = array();
+$replacement_word = array();
+obtain_word_list($orig_word, $replacement_word);
 
 //
 // Dump out the page header and load viewtopic body template
@@ -413,8 +396,8 @@ $template->assign_vars(array(
     "TOPIC_ID" => $topic_id,
     "TOPIC_TITLE" => $topic_title,
 
-	"L_DISPLAY_POSTS" => $lang['Display_posts'],
-	"L_RETURN_TO_TOP" => $lang['Return_to_top'],
+	"L_DISPLAY_POSTS" => $lang['Display_posts'], 
+	"L_RETURN_TO_TOP" => $lang['Return_to_top'], 
 
 	"S_SELECT_POST_DAYS" => $select_post_days,
 	"S_SELECT_POST_ORDER" => $select_post_order,
@@ -467,6 +450,126 @@ $template->assign_vars(array(
 	"U_POST_REPLY_TOPIC" => $reply_topic_url)
 );
 
+//
+// Does this topic contain a voting element?
+//
+if( !empty($forum_row['topic_vote']) )
+{
+	$sql = "SELECT vd.vote_id, vd.vote_text, vd.vote_start, vd.vote_length, vr.vote_option_id, vr.vote_option_text, vr.vote_result 
+		FROM " . VOTE_DESC_TABLE . " vd, " . VOTE_RESULTS_TABLE . " vr 
+		WHERE vd.topic_id = $topic_id 
+			AND vr.vote_id = vd.vote_id 
+		ORDER BY vr.vote_option_id ASC";
+	if( !$result = $db->sql_query($sql) )
+	{
+		message_die(GENERAL_ERROR, "Couldn't obtain vote data for this topic", "", __LINE__, __FILE__, $sql);
+	}
+
+	if( $vote_options = $db->sql_numrows($result) )
+	{
+		$vote_info = $db->sql_fetchrowset($result);
+
+		$vote_id = $vote_info[0]['vote_id'];
+		$vote_title = $vote_info[0]['vote_text'];
+
+		$sql = "SELECT vote_id  
+			FROM " . VOTE_USERS_TABLE . "  
+			WHERE vote_id = $vote_id 
+				AND vote_user_id = " . $userdata['user_id'];
+		if( !$result = $db->sql_query($sql) )
+		{
+			message_die(GENERAL_ERROR, "Couldn't obtain user vote data for this topic", "", __LINE__, __FILE__, $sql);
+		}
+
+		$user_voted = ( $db->sql_numrows($result) ) ? TRUE : 0;
+
+		if( isset($HTTP_GET_VARS['vote']) || isset($HTTP_POST_VARS['vote']) )
+		{
+			$view_result = ( ( ( isset($HTTP_GET_VARS['vote']) ) ? $HTTP_GET_VARS['vote'] : $HTTP_POST_VARS['vote'] ) == "viewresult" ) ? TRUE : 0;
+		}
+		else
+		{
+			$view_result = 0;
+		}
+
+		$poll_expired = ( $vote_info[0]['vote_length'] ) ? ( ( $vote_info[0]['vote_start'] + $vote_info[0]['vote_length'] < time() ) ? TRUE : 0 ) : 0;
+
+		if( $user_voted || $view_result || $poll_expired || !$is_auth['auth_vote'] )
+		{
+
+			$template->set_filenames(array(
+				"pollbox" => "viewtopic_poll_result.tpl")
+			);
+
+			$vote_results_sum = 0;
+
+			for($i = 0; $i < $vote_options; $i++)
+			{
+				$vote_results_sum += $vote_info[$i]['vote_result'];
+			}
+
+			$vote_graphic = 0;
+			$vote_graphic_max = count($images['voting_graphic']);
+
+			for($i = 0; $i < $vote_options; $i++)
+			{
+				$vote_percent = ( $vote_results_sum > 0 ) ? $vote_info[$i]['vote_result'] / $vote_results_sum : 0;
+				$vote_graphic_length = round($vote_percent * $board_config['vote_graphic_length']);
+
+				$vote_graphic_img = $images['voting_graphic'][$vote_graphic];
+				$vote_graphic = ($vote_graphic < $vote_graphic_max - 1) ? $vote_graphic + 1 : 0;
+				
+				$template->assign_block_vars("poll_option", array(
+					"POLL_OPTION_CAPTION" => $vote_info[$i]['vote_option_text'], 
+					"POLL_OPTION_RESULT" => $vote_info[$i]['vote_result'], 
+					"POLL_OPTION_PERCENT" => sprintf("%.1d%%", ($vote_percent * 100)), 
+
+					"POLL_OPTION_IMG" => $vote_graphic_img, 
+					"POLL_OPTION_IMG_WIDTH" => $vote_graphic_length)
+				);
+			}
+
+			$template->assign_vars(array(
+				"TOTAL_VOTES" => $vote_results_sum)
+			);
+
+		}
+		else
+		{
+			$template->set_filenames(array(
+				"pollbox" => "viewtopic_poll_ballot.tpl")
+			);
+
+			for($i = 0; $i < $vote_options; $i++)
+			{
+				$template->assign_block_vars("poll_option", array(
+					"POLL_OPTION_ID" => $vote_info[$i]['vote_option_id'], 
+					"POLL_OPTION_CAPTION" => $vote_info[$i]['vote_option_text'])
+				);
+			}
+
+			$template->assign_vars(array(
+				"L_SUBMIT_VOTE" => $lang['Submit_vote'],
+				"L_VIEW_RESULTS" => $lang['View_results'],
+			
+				"U_VIEW_RESULTS" => append_sid("viewtopic.$phpEx?" . POST_TOPIC_URL . "=$topic_id&amp;postdays=$post_days&amp;postorder=$post_order&amp;vote=viewresult"))
+			);
+
+			$s_hidden_fields = '<input type="hidden" name="topic_id" value="' . $topic_id . '"><input type="hidden" name="mode" value="vote">';
+		}
+
+		$template->assign_vars(array(
+			"POLL_QUESTION" => $vote_title, 
+			
+			"S_HIDDEN_FIELDS" => $s_hidden_fields, 
+			"S_VOTE_ACTION" => append_sid("posting.$phpEx?" . POST_TOPIC_URL . "=$topic_id"))
+		);
+
+		$template->assign_var_from_handle("POLL_DISPLAY", "pollbox");
+
+	}
+}
+
 //
 // Update the topic view counter
 //
@@ -485,19 +588,19 @@ if(!$update_result = $db->sql_query($sql))
 for($i = 0; $i < $total_posts; $i++)
 {
 	$poster_id = $postrow[$i]['user_id'];
-	$poster = stripslashes($postrow[$i]['username']);
+	$poster = $postrow[$i]['username'];
 
 	$post_date = create_date($board_config['default_dateformat'], $postrow[$i]['post_time'], $board_config['default_timezone']);
 
 	$poster_posts = ($postrow[$i]['user_id'] != ANONYMOUS) ? $lang['Posts'] . ": " . $postrow[$i]['user_posts'] : "";
 
-	$poster_from = ($postrow[$i]['user_from'] && $postrow[$i]['user_id'] != ANONYMOUS) ? $lang['From'] . ": " . stripslashes($postrow[$i]['user_from']) : "";
+	$poster_from = ($postrow[$i]['user_from'] && $postrow[$i]['user_id'] != ANONYMOUS) ? $lang['From'] . ": " . $postrow[$i]['user_from'] : "";
 
 	$poster_joined = ($postrow[$i]['user_id'] != ANONYMOUS) ? $lang['Joined'] . ": " . create_date($board_config['default_dateformat'], $postrow[$i]['user_regdate'], $board_config['default_timezone']) : "";
 
 	if($postrow[$i]['user_avatar'] != "" && $poster_id != ANONYMOUS)
 	{
-		$poster_avatar = (eregi("http", $postrow[$i]['user_avatar']) && $board_config['allow_avatar_remote']) ? "<br /><img src=\"" . stripslashes($postrow[$i]['user_avatar']) . "\"><br />" : "<br /><img src=\"" . $board_config['avatar_path'] . "/" . stripslashes($postrow[$i]['user_avatar']) . "\" alt=\"\" /><br />";
+		$poster_avatar = (eregi("http", $postrow[$i]['user_avatar']) && $board_config['allow_avatar_remote']) ? "<br /><img src=\"" . $postrow[$i]['user_avatar'] . "\"><br />" : "<br /><img src=\"" . $board_config['avatar_path'] . "/" . $postrow[$i]['user_avatar'] . "\" alt=\"\" /><br />";
 	}
 	else
 	{
@@ -518,8 +621,8 @@ for($i = 0; $i < $total_posts; $i++)
 		{
 			if($postrow[$i]['user_rank'] == $ranksrow[$j]['rank_id'] && $ranksrow[$j]['rank_special'])
 			{
-				$poster_rank = stripslashes($ranksrow[$j]['rank_title']);
-				$rank_image = ($ranksrow[$j]['rank_image']) ? "<img src=\"" . stripslashes($ranksrow[$j]['rank_image']) . "\"><br />" : "";
+				$poster_rank = $ranksrow[$j]['rank_title'];
+				$rank_image = ($ranksrow[$j]['rank_image']) ? "<img src=\"" . $ranksrow[$j]['rank_image'] . "\"><br />" : "";
 			}
 		}
 	}
@@ -529,8 +632,8 @@ for($i = 0; $i < $total_posts; $i++)
 		{
 			if($postrow[$i]['user_posts'] > $ranksrow[$j]['rank_min'] && $postrow[$i]['user_posts'] < $ranksrow[$j]['rank_max'] && !$ranksrow[$j]['rank_special'])
 			{
-				$poster_rank = stripslashes($ranksrow[$j]['rank_title']);
-				$rank_image = ($ranksrow[$j]['rank_image']) ? "<img src=\"" . stripslashes($ranksrow[$j]['rank_image']) . "\"><br />" : "";
+				$poster_rank = $ranksrow[$j]['rank_title'];
+				$rank_image = ($ranksrow[$j]['rank_image']) ? "<img src=\"" . $ranksrow[$j]['rank_image'] . "\"><br />" : "";
 			}
 		}
 	}
@@ -540,7 +643,7 @@ for($i = 0; $i < $total_posts; $i++)
 	//
 	if($poster_id == ANONYMOUS && $postrow[$i]['post_username'] != '')
 	{
-		$poster = stripslashes($postrow[$i]['post_username']);
+		$poster = $postrow[$i]['post_username'];
 		$poster_rank = $lang['Guest'];
 	}
 
@@ -550,16 +653,16 @@ for($i = 0; $i < $total_posts; $i++)
 
 		$pm_img = "<a href=\"" . append_sid("privmsg.$phpEx?mode=post&amp;" . POST_USERS_URL . "=$poster_id") . "\"><img src=\"". $images['icon_pm'] . "\" alt=\"" . $lang['Private_messaging'] . "\" border=\"0\" /></a>";
 
-		$email_addr = str_replace("@", " at ", stripslashes($postrow[$i]['user_email']));
+		$email_addr = str_replace("@", " at ", $postrow[$i]['user_email']);
 		$email_img = ($postrow[$i]['user_viewemail']) ? "<a href=\"mailto:$email_addr\"><img src=\"" . $images['icon_email'] . "\" alt=\"" . $lang['Send_email'] . " $poster\" border=\"0\" /></a>" : "";
 
-		$www_img = ($postrow[$i]['user_website']) ? "<a href=\"" . stripslashes($postrow[$i]['user_website']) . "\" target=\"_userwww\"><img src=\"" . $images['icon_www'] . "\" alt=\"" . $lang['Visit_website'] . "\" border=\"0\" /></a>" : "";
+		$www_img = ($postrow[$i]['user_website']) ? "<a href=\"" . $postrow[$i]['user_website'] . "\" target=\"_userwww\"><img src=\"" . $images['icon_www'] . "\" alt=\"" . $lang['Visit_website'] . "\" border=\"0\" /></a>" : "";
 
 		if($postrow[$i]['user_icq'])
 		{
-			$icq_status_img = "<a href=\"http://wwp.icq.com/" . stripslashes($postrow[$i]['user_icq']) . "#pager\"><img src=\"http://online.mirabilis.com/scripts/online.dll?icq=" . $postrow[$i]['user_icq'] . "&amp;img=5\" border=\"0\" /></a>";
+			$icq_status_img = "<a href=\"http://wwp.icq.com/" . $postrow[$i]['user_icq'] . "#pager\"><img src=\"http://online.mirabilis.com/scripts/online.dll?icq=" . $postrow[$i]['user_icq'] . "&amp;img=5\" border=\"0\" /></a>";
 
-			$icq_add_img = "<a href=\"http://wwp.icq.com/scripts/search.dll?to=" . stripslashes($postrow[$i]['user_icq']) . "\"><img src=\"" . $images['icon_icq'] . "\" alt=\"" . $lang['ICQ'] . "\" border=\"0\" /></a>";
+			$icq_add_img = "<a href=\"http://wwp.icq.com/scripts/search.dll?to=" . $postrow[$i]['user_icq'] . "\"><img src=\"" . $images['icon_icq'] . "\" alt=\"" . $lang['ICQ'] . "\" border=\"0\" /></a>";
 		}
 		else
 		{
@@ -571,7 +674,7 @@ for($i = 0; $i < $total_posts; $i++)
 
 		$msn_img = ($postrow[$i]['user_msnm']) ? "<a href=\"profile.$phpEx?mode=viewprofile&amp;" . POST_USERS_URL . "=$poster_id\"><img src=\"" . $images['icon_msnm'] . "\" border=\"0\" alt=\"" . $lang['MSNM'] . "\" /></a>" : "";
 
-		$yim_img = ($postrow[$i]['user_yim']) ? "<a href=\"http://edit.yahoo.com/config/send_webmesg?.target=" . stripslashes($postrow[$i]['user_yim']) . "&amp;.src=pg\"><img src=\"" . $images['icon_yim'] . "\" border=\"0\" alt=\"" . $lang['YIM'] . "\" /></a>" : "";
+		$yim_img = ($postrow[$i]['user_yim']) ? "<a href=\"http://edit.yahoo.com/config/send_webmesg?.target=" . $postrow[$i]['user_yim'] . "&amp;.src=pg\"><img src=\"" . $images['icon_yim'] . "\" border=\"0\" alt=\"" . $lang['YIM'] . "\" /></a>" : "";
 	}
 	else
 	{
@@ -586,36 +689,56 @@ for($i = 0; $i < $total_posts; $i++)
 		$yim_img = "";
 	}
 
+	$quote_img = "<a href=\"" . append_sid("posting.$phpEx?mode=quote&amp;" . POST_POST_URL . "=" . $postrow[$i]['post_id']) . "\"><img src=\"" . $images['icon_quote'] . "\" alt=\"" . $lang['Reply_with_quote'] ."\" border=\"0\" /></a>";
+
 	$search_img = "<a href=\"" . append_sid("search.$phpEx?a=" . urlencode($poster) . "&amp;f=all&amp;b=0&amp;d=DESC&amp;c=100&amp;dosearch=1") . "\"><img src=\"" . $images['icon_search'] . "\" border=\"0\" /></a>";
 
-	$edit_img = "<a href=\"" . append_sid("posting.$phpEx?mode=editpost&amp;" . POST_POST_URL . "=" . $postrow[$i]['post_id'] . "&amp;" . POST_TOPIC_URL . "=$topic_id") . "\"><img src=\"" . $images['icon_edit'] . "\" alt=\"" . $lang['Edit_delete_post'] . "\" border=\"0\" /></a>";
-
-	$quote_img = "<a href=\"" . append_sid("posting.$phpEx?mode=quote&amp;" . POST_POST_URL . "=" . $postrow[$i]['post_id']) . "\"><img src=\"" . $images['icon_quote'] . "\" alt=\"" . $lang['Reply_with_quote'] ."\" border=\"0\" /></a>";
+	if( ( $userdata['user_id'] == $poster_id && $is_auth['auth_edit'] ) || $is_auth['auth_mod'] )
+	{
+		$edit_img = "<a href=\"" . append_sid("posting.$phpEx?mode=editpost&amp;" . POST_POST_URL . "=" . $postrow[$i]['post_id']) . "\"><img src=\"" . $images['icon_edit'] . "\" alt=\"" . $lang['Edit_delete_post'] . "\" border=\"0\" /></a>";
+	}
+	else
+	{
+		$edit_img = "";
+	}
 
 	if( $is_auth['auth_mod'] )
 	{
-		$ip_img = "<a href=\"" . append_sid("modcp.$phpEx?mode=ip&amp;" . POST_POST_URL . "=" . $postrow[$i]['post_id'] . "&" . POST_TOPIC_URL . "=$topic_id") . "\"><img src=\"" . $images['icon_ip'] . "\" alt=\"" . $lang['View_IP'] . "\" border=\"0\" /></a>";
+		$ip_img = "<a href=\"" . append_sid("modcp.$phpEx?mode=viewip&amp;" . POST_POST_URL . "=" . $post_id) . "\"><img src=\"" . $images['icon_ip'] . "\" alt=\"" . $lang['View_IP'] . "\" border=\"0\" /></a>";
 
 		$delpost_img = "<a href=\"" . append_sid("topicadmin.$phpEx?mode=delpost&amp;" . POST_POST_URL . "=" . $postrow[$i]['post_id']) . "\"><img src=\"" . $images['icon_delpost'] . "\" alt=\"" . $lang['Delete_post'] . "\" border=\"0\" /></a>";
 	}
-
-	$message = stripslashes($postrow[$i]['post_text']);
-	$post_subject = ($postrow[$i]['post_subject'] != "") ? stripslashes($postrow[$i]['post_subject']) : $topic_title;
+	else
+	{
+		$ip_img = "";
+		$delpost_img = "";
+	}
+	
+	$message = $postrow[$i]['post_text'];
+	$post_subject = ( $postrow[$i]['post_subject'] != "" ) ? $postrow[$i]['post_subject'] : $topic_title;
 
 	$bbcode_uid = $postrow[$i]['bbcode_uid'];
 
-	$user_sig = stripslashes($postrow[$i]['user_sig']);
+	$user_sig = $postrow[$i]['user_sig'];
 
-	if(!$board_config['allow_html'] || !$postrow[$i]['enable_html'])
+	//
+	// If the board has HTML off but the post has HTML
+	// on then we process it, else leave it alone
+	//
+	if( !$board_config['allow_html'] ) 
 	{
 		if($user_sig != "")
 		{
-			$user_sig = htmlspecialchars($user_sig);
+			$user_sig = preg_replace("#(<)([\/]?.*?)(>)#is", "&lt;\\2&gt;", $user_sig);
+		}
+
+		if( $postrow[$i]['enable_html'] )
+		{
+			$message = preg_replace("#(<)([\/]?.*?)(>)#is", "&lt;\\2&gt;", $message);
 		}
-		$message = htmlspecialchars($message);
 	}
 
-	if($board_config['allow_bbcode'] && $bbcode_uid != "")
+	if( $board_config['allow_bbcode'] && $bbcode_uid != "" )
 	{
 		if($user_sig != "")
 		{
@@ -625,19 +748,9 @@ for($i = 0; $i < $total_posts; $i++)
 		}
 
 		$message = bbencode_second_pass($message, $bbcode_uid);
-
-		//
-		// This compensates for bbcode's rather agressive (but I guess necessary)
-		// HTML handling
-		//
-		if(!$postrow[$i]['enable_html'] || ($postrow[$i]['enable_html'] && !$board_config['allow_html']) )
-		{
-			$message = preg_replace("'&amp;'", "&", $message);
-		}
 	}
-	else
+	else if( !$board_config['allow_bbcode'] && $bbcode != "" )
 	{
-		// Removes UID from BBCode entries
 		$message = preg_replace("/\:[0-9a-z\:]+\]/si", "]", $message);
 	}
 
@@ -771,15 +884,15 @@ $template->assign_vars(array(
 	"ON_PAGE" => ( floor( $start / $board_config['posts_per_page'] ) + 1 ),
 	"TOTAL_PAGES" => ceil( $total_replies / $board_config['posts_per_page'] ),
 
-	"S_AUTH_LIST" => $s_auth_can,
-	"S_AUTH_READ_IMG" => $s_auth_read_img,
-	"S_AUTH_POST_IMG" => $s_auth_post_img,
-	"S_AUTH_REPLY_IMG" => $s_auth_reply_img,
-	"S_AUTH_EDIT_IMG" => $s_auth_edit_img,
+	"S_AUTH_LIST" => $s_auth_can, 
+	"S_AUTH_READ_IMG" => $s_auth_read_img, 
+	"S_AUTH_POST_IMG" => $s_auth_post_img, 
+	"S_AUTH_REPLY_IMG" => $s_auth_reply_img, 
+	"S_AUTH_EDIT_IMG" => $s_auth_edit_img, 
 	"S_AUTH_MOD_IMG" => $s_auth_mod_img,
-	"S_TOPIC_ADMIN" => $topic_mod,
-	"S_WATCH_TOPIC" => $s_watching_topic,
-	"S_WATCH_TOPIC_IMG" => $s_watching_topic_img,
+	"S_TOPIC_ADMIN" => $topic_mod, 
+	"S_WATCH_TOPIC" => $s_watching_topic, 
+	"S_WATCH_TOPIC_IMG" => $s_watching_topic_img, 
 
 	"L_OF" => $lang['of'],
 	"L_PAGE" => $lang['Page'],