diff --git a/phpBB/viewtopic.php b/phpBB/viewtopic.php
index 7471dbfe9e..7914b261c7 100644
--- a/phpBB/viewtopic.php
+++ b/phpBB/viewtopic.php
@@ -176,43 +176,63 @@ watch_topic_forum('topic', $s_watching_topic, $s_watching_topic_img, $user->data
$limit_days = array(0 => $user->lang['ALL_POSTS'], 1 => $user->lang['1_DAY'], 7 => $user->lang['7_DAYS'], 14 => $user->lang['2_WEEKS'], 30 => $user->lang['1_MONTH'], 90 => $user->lang['3_MONTHS'], 180 => $user->lang['6_MONTHS'], 364 => $user->lang['1_YEAR']);
$sort_by_text = array('a' => $user->lang['AUTHOR'], 't' => $user->lang['POST_TIME'], 's' => $user->lang['SUBJECT']);
-$sort_by_sql = array('a' => 'u.username', 't' => 'p.post_id', 's' => 'pt.post_subject');
+$sort_by_sql = array('a' => 'u.username', 't' => 'p.post_id', 's' => 'p.post_subject');
gen_sort_selects($limit_days, $sort_by_text, $s_limit_days, $s_sort_key, $s_sort_dir);
-// Limit posts to certain time frame, obtain correct post count
-if (isset($_REQUEST['sort']))
-{
- if ($sort_days)
- {
- $min_post_time = time() - ($sort_days * 86400);
-
- $sql = "SELECT COUNT(post_id) AS num_posts
- FROM " . POSTS_TABLE . "
- WHERE topic_id = $topic_id
- AND post_time >= $min_post_time
- AND post_approved = " . TRUE;
- $result = $db->sql_query($sql);
-
- $start = 0;
- $topic_replies = ($row = $db->sql_fetchrow($result)) ? $row['num_posts'] : 0;
- $limit_posts_time = "AND p.post_time >= $min_post_time ";
- }
- else
- {
- $topic_replies++;
- }
-}
-else
-{
- $topic_replies++;
- $limit_posts_time = '';
-}
-
-// Select the sort order
+$sort_days = (!empty($_REQUEST['sort_days'])) ? max(intval($_REQUEST['sort_days']), 0) : 0;
+$sort_key = (!empty($_REQUEST['sort_key']) && preg_match('/^(a|t|s)$/', $_REQUEST['sort_key'])) ? $_REQUEST['sort_key'] : 't';
+$sort_dir = (!empty($_REQUEST['sort_dir']) && preg_match('/^(a|d)$/', $_REQUEST['sort_dir'])) ? $_REQUEST['sort_dir'] : 'a';
$sort_order = $sort_by_sql[$sort_key] . ' ' . (($sort_dir == 'd') ? 'DESC' : 'ASC');
+$limit_posts_time = '';
+$total_posts = $topic_replies + 1;
+
+if ($sort_days)
+{
+ $min_post_time = time() - ($sort_days * 86400);
+
+ $sql = 'SELECT COUNT(post_id) AS num_posts
+ FROM ' . POSTS_TABLE . "
+ WHERE topic_id = $topic_id
+ AND post_time >= $min_post_time
+ AND post_approved = 1";
+ $result = $db->sql_query($sql);
+
+ $start = 0;
+ $total_posts = ($row = $db->sql_fetchrow($result)) ? $row['num_posts'] : 0;
+ $limit_posts_time = "AND p.post_time >= $min_post_time ";
+}
+
+$select_sort_days = '';
+
+$select_sort = '';
+
+$select_sort_dir = '';
+
+$select_post_days = '';
+
// Cache this? ... it is after all doing a simple data grab
$sql = "SELECT *
@@ -267,7 +287,8 @@ $topic_mod .= ($auth->acl_gets('m_merge', 'a_', $forum_id)) ? '