All pastes #628720 Raw Edit

viewtopic.php

public text v1 · immutable
·published 2007-07-21 16:12 UTC
rendered paste body
<?php
//-- mod : calendar ------------------------------------------------------------
/***************************************************************************
 *                               viewtopic.php
 *                            -------------------
 *   begin                : Saturday, Feb 13, 2001
 *   copyright            : (C) 2001 The phpBB Group
 *   email                : support@phpbb.com
 *
 *   $Id: viewtopic.php,v 1.186.2.43 2005/07/19 20:01:21 acydburn Exp $
 *
 *
 ***************************************************************************/

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

define('IN_PHPBB', true);
define('IN_CASHMOD', true);
define('CM_VIEWTOPIC', true);
$phpbb_root_path = './';
include($phpbb_root_path . 'extension.inc');
include($phpbb_root_path . 'common.'.$phpEx);
include($phpbb_root_path . 'includes/bbcode.'.$phpEx);
include($phpbb_root_path . 'reputation_common.'.$phpEx);
include($phpbb_root_path . 'includes/functions_reputation.'.$phpEx);
include($phpbb_root_path . 'includes/functions_post.'.$phpEx);
include($phpbb_root_path . 'includes/def_icons.'. $phpEx);
// RegMod-Begin
include($phpbb_root_path . 'includes/functions_regmod.'.$phpEx);
// RegMod-End
#======================================================================= | 
#==== Start: == Activity Mod Plus ====================================== | 
#==== v1.1.0 =========================================================== | 
#====       
include_once($phpbb_root_path .'includes/functions_amod_plus.'. $phpEx);
   $q = "SELECT * 
         FROM ". INA_HOF .""; 
   $r          = $db->sql_query($q); 
   $hof_data   = $db->sql_fetchrowset($r); 
#==== 
#==== Author: aUsTiN [austin@phpbb-amod.com] [http://phpbb-amod.com] === | 
#==== End: ==== Activity Mod Plus ====================================== |    
#======================================================================= |
// Cache Posts
// Here you can change the style of the CPS indicators
$CPS_Indicator = array(
	'cached' => '<span style="color: limegreen"><b>&bull;</b></span>',
	'not_cached' => '<span style="color: green"><b>&bull;</b></span>',
	'error' => '<span style="color: red"><b>&bull;</b></span>',
	'dont_cache' => '<span style="color: yellow"><b>&bull;</b></span>',
	'off_but_cached' => '<span style="color: orange"><b>&bull;</b></span>',
	'off' => '<span style="color: black"><b>&bull;</b></span>');
// Cache Posts
//
// Start initial var setup
//
$topic_id = $post_id = 0;
if ( isset($HTTP_GET_VARS[POST_TOPIC_URL]) )
{
	$topic_id = intval($HTTP_GET_VARS[POST_TOPIC_URL]);
}
else if ( isset($HTTP_GET_VARS['topic']) )
{
	$topic_id = intval($HTTP_GET_VARS['topic']);
}

if ( isset($HTTP_GET_VARS[POST_POST_URL]))
{
	$post_id = intval($HTTP_GET_VARS[POST_POST_URL]);
}


$start = ( isset($HTTP_GET_VARS['start']) ) ? intval($HTTP_GET_VARS['start']) : 0;
$start = ($start < 0) ? 0 : $start;
$download = ( isset($HTTP_GET_VARS['download']) ) ? $HTTP_GET_VARS['download'] : '';

if (!$topic_id && !$post_id)

{
	message_die(GENERAL_MESSAGE, 'Topic_post_not_exist');
}

//
// Find topic id if user requested a newer
// or older topic
//
if ( isset($HTTP_GET_VARS['view']) && empty($HTTP_GET_VARS[POST_POST_URL]) )
{
	if ( $HTTP_GET_VARS['view'] == 'newest' )
	{
		if ( isset($HTTP_COOKIE_VARS[$board_config['cookie_name'] . '_sid']) || isset($HTTP_GET_VARS['sid']) )
		{
			$session_id = isset($HTTP_COOKIE_VARS[$board_config['cookie_name'] . '_sid']) ? $HTTP_COOKIE_VARS[$board_config['cookie_name'] . '_sid'] : $HTTP_GET_VARS['sid'];

			if (!preg_match('/^[A-Za-z0-9]*$/', $session_id)) 
			{
				$session_id = '';
			}

			if ( $session_id )
			{
				$sql = "SELECT p.post_id
					FROM " . POSTS_TABLE . " p, " . SESSIONS_TABLE . " s,  " . USERS_TABLE . " u
					WHERE s.session_id = '$session_id'
						AND u.user_id = s.session_user_id
						AND p.topic_id = $topic_id
						AND p.post_time >= u.user_lastvisit
						AND p.post_draft = 0
					ORDER BY p.post_time ASC
					LIMIT 1";
// start mod save posts as drafts (and end mod too): added an AND constraint in the foregoing sql definition that post_draft be zero (i.e. that the post not just be a draft)
				if ( !($result = $db->sql_query($sql)) )
				{
					message_die(GENERAL_ERROR, 'Could not obtain newer/older topic information', '', __LINE__, __FILE__, $sql);
				}

				if ( !($row = $db->sql_fetchrow($result)) )
				{
					message_die(GENERAL_MESSAGE, 'No_new_posts_last_visit');
				}

				$post_id = $row['post_id'];

				if (isset($HTTP_GET_VARS['sid']))
				{
					redirect("viewtopic.$phpEx?sid=$session_id&" . POST_POST_URL . "=$post_id#$post_id");
				}
				else
				{
					redirect("viewtopic.$phpEx?" . POST_POST_URL . "=$post_id#$post_id");
				}
			}
		}

		redirect(append_sid("viewtopic.$phpEx?" . POST_TOPIC_URL . "=$topic_id", true));
	}
	else if ( $HTTP_GET_VARS['view'] == 'next' || $HTTP_GET_VARS['view'] == 'previous' )
	{
		$sql_condition = ( $HTTP_GET_VARS['view'] == 'next' ) ? '>' : '<';
		$sql_ordering = ( $HTTP_GET_VARS['view'] == 'next' ) ? 'ASC' : 'DESC';

		$sql = "SELECT t.topic_id
			FROM " . TOPICS_TABLE . " t, " . TOPICS_TABLE . " t2
			WHERE
				t2.topic_id = $topic_id
				AND t.forum_id = t2.forum_id
				AND t.topic_moved_id = 0

				AND t.topic_last_post_id $sql_condition t2.topic_last_post_id
				AND t.topic_last_post_id > 0
			ORDER BY t.topic_last_post_id $sql_ordering
			LIMIT 1";
// start mod save posts as drafts (and end mod too): added an AND constraint in the foregoing sql definition that last_post_id be greater than 0 (i.e. that the topic not just be a new draft topic not yet submitted)		
        if ( !($result = $db->sql_query($sql)) )
		{
			message_die(GENERAL_ERROR, "Could not obtain newer/older topic information", '', __LINE__, __FILE__, $sql);
		}

		if ( $row = $db->sql_fetchrow($result) )
		{
			$topic_id = intval($row['topic_id']);
		}
		else
		{
			$message = ( $HTTP_GET_VARS['view'] == 'next' ) ? 'No_newer_topics' : 'No_older_topics';
			message_die(GENERAL_MESSAGE, $message);
		}
	}
}

//
// This rather complex gaggle of code handles querying for topics but
// also allows for direct linking to a post (and the calculation of which
// page the post is on and the correct display of viewtopic)
//
$join_sql_table = (!$post_id) ? '' : ", " . POSTS_TABLE . " p, " . POSTS_TABLE . " p2 ";
$join_sql = (!$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 AND p2.post_draft = 0";
// start mod save posts as drafts (and end too)...added constraint at end of previous line that post_draft be 0 (i.e. that the post not be a draft)
$count_sql = (!$post_id) ? '' : ", COUNT(p2.post_id) AS prev_posts";

$order_sql = (!$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, t.topic_last_post_id, 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, f.min_posts_to_view, f.max_posts_to_view ORDER BY p.post_id ASC";

// start mod tabulated survey at topic head (and end too)...added reference to t.topic_survey in next line
// mod topic mod add to sql query
//mod topic description add to sql query
$sql = "SELECT t.topic_id, t.topic_title, t.topic_description, t.topic_descmod, t.topic_status,t.topic_noguest, t.topic_adminedit, t.topic_password, t.topic_pass_level, t.topic_replies, t.topic_time, t.topic_type, t.topic_vote, t.topic_first_post_id, t.topic_reg, t.topic_survey, t.topic_last_post_id, t.topic_cache_lock, 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, f.min_posts_to_view, f.max_posts_to_view" . $count_sql . "
	FROM " . TOPICS_TABLE . " t, " . FORUMS_TABLE . " f" . $join_sql_table . "
	WHERE $join_sql
		AND f.forum_id = t.forum_id
		$order_sql";
//-- mod : calendar ------------------------------------------------------------
//-- add
$fields = array('f.auth_cal', 't.topic_first_post_id', 't.topic_calendar_time', 't.topic_calendar_duration');
$sql = preg_replace('/^SELECT /', 'SELECT ' . implode(', ', $fields) . ', ', $sql);
if ( $post_id )
{
	$sql = preg_replace('/GROUP BY /', 'GROUP BY ' . implode(', ', $fields) . ', ', $sql);
}
//-- fin mod : calendar --------------------------------------------------------
attach_setup_viewtopic_auth($order_sql, $sql);
if ( !($result = $db->sql_query($sql)) )
{
	message_die(GENERAL_ERROR, "Could not obtain topic information", '', __LINE__, __FILE__, $sql);
}

if ( !($forum_topic_data = $db->sql_fetchrow($result)) )
{
	message_die(GENERAL_MESSAGE, 'Topic_post_not_exist');
}

$forum_id = intval($forum_topic_data['forum_id']);

//
// Start session management
//
$userdata = session_pagestart($user_ip, $forum_id);
init_userprefs($userdata);
//
// End session management
//
//-- mod : calendar ------------------------------------------------------------
//-- add
$user->set();
$calendar_api->set();
$calendar_front_title = new front_calendar();
//-- fin mod : calendar --------------------------------------------------------
if ( $download )
{
	$sql_download = ( $download != -1 ) ? " AND p.post_id = " . intval($download) . " " : '';

	$orig_word = array();
	$replacement_word = array();
	obtain_word_list($orig_word, $replacement_word);

	$sql = "SELECT u.*, u.user_birthday, u.birthday_display, u.user_zodiac, u.user_rank_theme, u.user_custom_rank_status, u.user_custom_rank, p.*,  pt.post_text, pt.post_subject, pt.bbcode_uid
		FROM " . POSTS_TABLE . " p, " . USERS_TABLE . " u, " . POSTS_TEXT_TABLE . " pt
		WHERE p.topic_id = $topic_id
			$sql_download
			AND pt.post_id = p.post_id
			AND u.user_id = p.poster_id
			ORDER BY p.post_time ASC, p.post_id ASC";
	if ( !($result = $db->sql_query($sql)) )
	{
		message_die(GENERAL_ERROR, "Could not create download stream for post.", '', __LINE__, __FILE__, $sql);
	}

	$download_file = '';

	$is_auth_read = array();

	while ( $row = $db->sql_fetchrow($result) )
	{
		$is_auth_read = auth(AUTH_ALL, $row['forum_id'], $userdata);

		$poster_id = $row['user_id'];
		$poster = ( $poster_id == ANONYMOUS ) ? $lang['Guest'] : $row['username'];

		$post_date = create_date($board_config['default_dateformat'], $row['post_time'], $board_config['board_timezone']);

		$post_subject = ( $row['post_subject'] != '' ) ? $row['post_subject'] : '';

		$bbcode_uid = $row['bbcode_uid'];
		$message = $row['post_text'];
		$message = strip_tags($message);
		$message = preg_replace("/\[.*?:$bbcode_uid:?.*?\]/si", '', $message);
		$message = preg_replace('/\[url\]|\[\/url\]/si', '', $message);
		$message = preg_replace('/\:[0-9a-z\:]+\]/si', ']', $message);

		$message = unprepare_message($message);
		$message = preg_replace('/&#40;/', '(', $message);
		$message = preg_replace('/&#41;/', ')', $message);
		$message = preg_replace('/&#58;/', ':', $message);
		$message = preg_replace('/&#91;/', '[', $message);
		$message = preg_replace('/&#93;/', ']', $message);
		$message = preg_replace('/&#123;/', '{', $message);
		$message = preg_replace('/&#125;/', '}', $message);

		if (count($orig_word))
		{
			$post_subject = preg_replace($orig_word, $replacement_word, $post_subject);

			$message = str_replace('\"', '"', substr(preg_replace('#(\>(((?>([^><]+|(?R)))*)\<))#se', "preg_replace(\$orig_word, \$replacement_word, '\\0')", '>' . $message . '<'), 1, -1));
		}

		$break = "\n\r";
		$line = '-----------------------------------';
		$download_file .= $break.$line.$break.$poster.$break.$post_date.$break.$break.$post_subject.$break.$line.$break.$message.$break;
	}

	$disp_folder = ( $download == -1 ) ? 'Topic_'.$topic_id : 'Post_'.$download;

	if (!$is_auth_read['auth_read'])
	{
		$download_file = sprintf($lang['Sorry_auth_read'], $is_auth_read['auth_read_type']);
		$disp_folder = 'Download';
	}

	$filename = $board_config['sitename']."_".$disp_folder."_".date("Ymd",time()).".txt";
	header('Content-Type: text/x-delimtext; name="'.$filename.'"');
	header('Content-Disposition: attachment;filename="'.$filename.'"');
	header('Content-Transfer-Encoding: plain/text');
	header('Content-Length: '.strlen($download_file));
	print $download_file;

	exit;
}

//
// Start auth check
//
$is_auth = array();
$is_auth = auth(AUTH_ALL, $forum_id, $userdata, $forum_topic_data);

if( !$is_auth['auth_view'] || !$is_auth['auth_read'] )
{
	if ( !$userdata['session_logged_in'] )
	{
		$redirect = ($post_id) ? POST_POST_URL . "=$post_id" : POST_TOPIC_URL . "=$topic_id";
		$redirect .= ($start) ? "&start=$start" : '';

		redirect(append_sid("login.$phpEx?redirect=viewtopic.$phpEx&$redirect", true));
	}

	$message = ( !$is_auth['auth_view'] ) ? $lang['Topic_post_not_exist'] : sprintf($lang['Sorry_auth_read'], $is_auth['auth_read_type']);

	message_die(GENERAL_MESSAGE, $message);
}
//
// End auth check
//

// BEGIN Forum Auth by Post Count 1.0.0 (www.phpBBDoctor.com)
if ( !(phpbbdoctor_post_count_auth($forum_topic_data['min_posts_to_view'], $forum_topic_data['max_posts_to_view'])) )
{
	message_die(GENERAL_MESSAGE, $lang['Not_Authorised']);
}
// END Forum Auth by Post Count 1.0.0 (www.phpBBDoctor.com)

// Forum Icon Mod
$sql = "SELECT forum_icon
	FROM " . FORUMS_TABLE . "
	WHERE forum_id = $forum_id";
if ( !($result = $db->sql_query($sql)) )
{
	message_die(GENERAL_ERROR, 'Could not obtain forums information', '', __LINE__, __FILE__, $sql);
}
$forum_row = $db->sql_fetchrow($result);
$forum_icon = $forum_row['forum_icon'];

if ( isset($HTTP_GET_VARS['mode']) && $HTTP_GET_VARS['mode'] == 'breakdown' )
{
	$gen_simple_header = TRUE;

	if (!$topic_id)
	{
		message_die(GENERAL_MESSAGE, 'Topic_post_not_exist');
	}

	$sql = "SELECT u.user_id, u.username, COUNT(p.poster_id) AS total, MIN(p.post_time) AS first_post 
		FROM " . POSTS_TABLE . " AS p, " . USERS_TABLE . " AS u 
		WHERE topic_id = $topic_id 
			AND u.user_id = p.poster_id
			AND u.user_id <> " . ANONYMOUS . " 
		GROUP BY u.user_id
		UNION
			SELECT " . ANONYMOUS . ", post_username AS username, COUNT(poster_id) AS total, MIN(post_time) AS first_post
			FROM phpbb_posts
			WHERE topic_id = $topic_id
				AND poster_id = " . ANONYMOUS . " 
			GROUP BY post_username
		ORDER BY total DESC, first_post ASC";

	if ( !($result = $db->sql_query($sql)) )
	{
		message_die(GENERAL_ERROR, 'Could not breakdown topic', '', __LINE__, __FILE__, $sql);
	}

	$i = 0;
	$total_posts = 0;
	while ( $row = $db->sql_fetchrow($result) )
	{
		if ( $row['user_id'] != ANONYMOUS )
		{
			$temp_url = append_sid("profile.$phpEx?mode=viewprofile&amp;" . POST_USERS_URL . '=' . $row['user_id']);
			$username = '<a href="#" onclick="jump_to_profile(\'' . $temp_url . '\'); return false">' . $row['username'] . '</a>';
		}
		else
		{
			$username = ( empty($row['username']) ) ? $lang['Guest'] : $row['username'];
		}

		$template->assign_block_vars('posterrow', array(
			'ROW_CLASS' => ( !($i % 2) ) ? $theme['td_class1'] : $theme['td_class2'],
			'USERNAME' => $username,
			'POSTS' => $row['total'])
		);

		$total_posts+= $row['total'];
		$i++;
	}

	$template->assign_vars(array(
		'L_CLOSE_WINDOW' => $lang['Close_window'],
		'L_WHO_POSTED' => $lang['Who_has_Posted'],
		'L_TOTAL' => sprintf($lang['Posts_total'], $total_posts),
		'L_USERNAME' => $lang['Username'],
		'L_POSTS' => $lang['Posts'])
	);

	$page_title = $lang['Who_has_Posted'];
	include($phpbb_root_path . 'includes/page_header.'.$phpEx);

	$template->set_filenames(array(
		'body' => 'breakdown_popup.tpl')
	);

	$template->pparse('body');

	include($phpbb_root_path . 'includes/page_tail.'.$phpEx);
}

$forum_name = $forum_topic_data['forum_name'];
$topic_title = $forum_topic_data['topic_title'];
$topic_id = intval($forum_topic_data['topic_id']);
$topic_time = $forum_topic_data['topic_time'];

if ($post_id)

{
	$start = floor(($forum_topic_data['prev_posts'] - 1) / intval($board_config['posts_per_page'])) * intval($board_config['posts_per_page']);
}

// www.phpBB-SEO.com SEO TOOLKIT BEGIN
if ( !isset($phpbb_seo->seo_url['forum'][$forum_topic_data['forum_id']]) ) {
	$phpbb_seo->seo_url['forum'][$forum_topic_data['forum_id']] = $phpbb_seo->format_url($forum_name, $phpbb_seo->seo_static['forum']);
}
// www.phpBB-SEO.com SEO TOOLKIT END

// www.phpBB-SEO.com SEO TOOLKIT BEGIN
$uri = $phpbb_seo->seo_req_uri();
$postorder_redir = empty($_POST['postorder']) && empty($_GET['postorder']);
if ($_GET['postorder'] == 'asc'  || $_POST['postorder'] == 'asc' ) {
	$postorder_redir = TRUE;
}
$phpbb_seo->seo_start( $start, $board_config['posts_per_page'] );
$phpbb_seo->page_url = $phpbb_seo->seo_static['topic'] . $topic_id . $phpbb_seo->start . $phpbb_seo->seo_ext['topic'];
$phpbb_seo->seo_cond(!$userdata['session_logged_in'] && ( strpos($uri, "sid=" ) !== FALSE ) );
if ( $phpbb_seo->do_redir || ( $postorder_redir &&  strpos($uri, 'watch=') === FALSE && strpos($uri, $phpbb_seo->page_url) === FALSE )  ) {
	$phpbb_seo->seo_redirect( $phpbb_seo->seo_path['phpbb_url'] . $phpbb_seo->page_url . ( ( $post_id ) ? "#$post_id" : "" ) );
}
// www.phpBB-SEO.com SEO TOOLKIT END

//
// Is user watching this thread?
//
if( $userdata['session_logged_in'] )
{
	$can_watch_topic = TRUE;

	$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)) )
	{
		message_die(GENERAL_ERROR, "Could not obtain topic watch information", '', __LINE__, __FILE__, $sql);
	}

	if ( $row = $db->sql_fetchrow($result) )
	{
		if ( isset($HTTP_GET_VARS['unwatch']) )
		{
			if ( $HTTP_GET_VARS['unwatch'] == 'topic' )
			{
				$is_watching_topic = 0;

				$sql_priority = (SQL_LAYER == "mysql") ? "LOW_PRIORITY" : '';
				$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)) )
				{
					message_die(GENERAL_ERROR, "Could not delete topic watch information", '', __LINE__, __FILE__, $sql);
				}
			}

			$template->assign_vars(array(
				'META' => '<meta http-equiv="refresh" content="3;url=' . append_sid("viewtopic.$phpEx?" . POST_TOPIC_URL . "=$topic_id&amp;start=$start") . '">')
			);

			$message = $lang['No_longer_watching'] . '<br /><br />' . sprintf($lang['Click_return_topic'], '<a href="' . append_sid("viewtopic.$phpEx?" . POST_TOPIC_URL . "=$topic_id&amp;start=$start") . '">', '</a>');
			message_die(GENERAL_MESSAGE, $message);
		}
		else
		{
			$is_watching_topic = TRUE;

			if ( $row['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
						AND user_id = " . $userdata['user_id'];
				if ( !($result = $db->sql_query($sql)) )
				{
					message_die(GENERAL_ERROR, "Could not update topic watch information", '', __LINE__, __FILE__, $sql);
				}
			}
		}
	}
	else
	{
		if ( isset($HTTP_GET_VARS['watch']) )
		{
			if ( $HTTP_GET_VARS['watch'] == 'topic' )
			{
				$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)
					VALUES (" . $userdata['user_id'] . ", $topic_id, 0)";
				if ( !($result = $db->sql_query($sql)) )
				{
					message_die(GENERAL_ERROR, "Could not insert topic watch information", '', __LINE__, __FILE__, $sql);
				}
			}

			$template->assign_vars(array(
				'META' => '<meta http-equiv="refresh" content="3;url=' . append_sid("viewtopic.$phpEx?" . POST_TOPIC_URL . "=$topic_id&amp;start=$start") . '">')
			);

			$message = $lang['You_are_watching'] . '<br /><br />' . sprintf($lang['Click_return_topic'], '<a href="' . append_sid("viewtopic.$phpEx?" . POST_TOPIC_URL . "=$topic_id&amp;start=$start") . '">', '</a>');
			message_die(GENERAL_MESSAGE, $message);
		}
		else
		{
			$is_watching_topic = 0;
		}
	}
}
else
{
	if ( isset($HTTP_GET_VARS['unwatch']) )
	{
		if ( $HTTP_GET_VARS['unwatch'] == 'topic' )
		{
			redirect(append_sid("login.$phpEx?redirect=viewtopic.$phpEx&" . POST_TOPIC_URL . "=$topic_id&unwatch=topic", true));
		}
	}
	else
	{
		$can_watch_topic = 0;
		$is_watching_topic = 0;
	}
}

//
// Generate a 'Show posts in previous x days' select box. If the postdays var is POSTed
// then get it's value, find the number of topics with dates newer than it (to properly
// handle pagination) and alter the main query
//
$valid = FALSE;
if( $userdata['session_logged_in'] ) {
$sql = "SELECT p.poster_id, p.topic_id
FROM " . POSTS_TABLE . " p
WHERE p.topic_id = $topic_id
AND p.poster_id = " . $userdata['user_id'];
$resultat = $db->sql_query($sql);
$valid = $db->sql_numrows($resultat) ? TRUE : FALSE;}

$previous_days = array(0, 1, 7, 14, 30, 90, 180, 364);
$previous_days_text = array($lang['All_Posts'], $lang['1_Day'], $lang['7_Days'], $lang['2_Weeks'], $lang['1_Month'], $lang['3_Months'], $lang['6_Months'], $lang['1_Year']);

if( !empty($HTTP_POST_VARS['postdays']) || !empty($HTTP_GET_VARS['postdays']) )
{
	$post_days = ( !empty($HTTP_POST_VARS['postdays']) ) ? intval($HTTP_POST_VARS['postdays']) : intval($HTTP_GET_VARS['postdays']);
	$min_post_time = time() - (intval($post_days) * 86400);

	$sql = "SELECT COUNT(p.post_id) AS num_posts
		FROM " . TOPICS_TABLE . " t, " . POSTS_TABLE . " p
		WHERE t.topic_id = $topic_id
			AND p.topic_id = t.topic_id
			AND p.post_time >= $min_post_time
			AND p.post_draft = 0";
// start mod save posts as drafts (and end too)...added constraint at end of next line that post_draft be 0 (i.e. that the post not be a draft)
	if ( !($result = $db->sql_query($sql)) )
	{
		message_die(GENERAL_ERROR, "Could not obtain limited topics count information", '', __LINE__, __FILE__, $sql);
	}

	$total_replies = ( $row = $db->sql_fetchrow($result) ) ? intval($row['num_posts']) : 0;

	$limit_posts_time = "AND p.post_time >= $min_post_time ";

	if ( !empty($HTTP_POST_VARS['postdays']))
	{
		$start = 0;
	}
}
else
{
	$total_replies = intval($forum_topic_data['topic_replies']) + 1;

	$limit_posts_time = '';
	$post_days = 0;
}

$select_post_days = '<select name="postdays">';
for($i = 0; $i < count($previous_days); $i++)
{
	$selected = ($post_days == $previous_days[$i]) ? ' selected="selected"' : '';
	$select_post_days .= '<option value="' . $previous_days[$i] . '"' . $selected . '>' . $previous_days_text[$i] . '</option>';
}
$select_post_days .= '</select>';

//
// Decide how to order the post display
//
if ( !empty($HTTP_POST_VARS['postorder']) || !empty($HTTP_GET_VARS['postorder']) )
{
	$post_order = (!empty($HTTP_POST_VARS['postorder'])) ? htmlspecialchars($HTTP_POST_VARS['postorder']) : htmlspecialchars($HTTP_GET_VARS['postorder']);
	$post_time_order = ($post_order == "asc") ? "ASC" : "DESC";
}
else
{
	$post_order = 'asc';
	$post_time_order = 'ASC';
}

$select_post_order = '<select name="postorder">';
if ( $post_time_order == 'ASC' )
{
	$select_post_order .= '<option value="asc" selected="selected">' . $lang['Oldest_First'] . '</option><option value="desc">' . $lang['Newest_First'] . '</option>';
}
else
{
	$select_post_order .= '<option value="asc">' . $lang['Oldest_First'] . '</option><option value="desc" selected="selected">' . $lang['Newest_First'] . '</option>';
}
$select_post_order .= '</select>';

//
// Go ahead and pull all data for this topic
//
//--  mod : IP Country Flag II ------------------------------------------
// add , u.user_cf_iso3661_1 AND ,u.user_timezone AND , u.user_from_flag_cf_iso3661_1
$sql = "SELECT u.*, u.user_phoogle_map_center, u.user_phoogle_allow, u.user_phoogle_show_me, u.user_from_flag_cf_iso3661_1, u.user_timezone, u.user_cf_iso3661_1, u.user_myspace, u.ct_miserable_user, u.user_shouts, u.user_weblog, u.user_trophies, u.ina_char_name, p.*, pt.post_text, pt.post_subject, pt.bbcode_uid, ft.flag_name, u.user_reputation, pt.scribble_string
	FROM " . POSTS_TABLE . " p, " . USERS_TABLE . " u, " . POSTS_TEXT_TABLE . " pt, " . FLAG_TABLE . " ft
	WHERE p.topic_id = $topic_id
		$limit_posts_time
		AND pt.post_id = p.post_id
		AND u.user_id = p.poster_id
		AND ft.flag_image = u.user_from_flag
		AND p.post_draft = 0
	ORDER BY p.post_time $post_time_order
	LIMIT $start, ".$board_config['posts_per_page'];
//-- mod : browsers list -------------------------------------------------------
//-- add
$sql = str_replace('SELECT ', 'SELECT u.user_browser, ', $sql);
//-- fin mod : browsers list ---------------------------------------------------
//-- mod : rank color system ---------------------------------------------------
//-- add
$sql = str_replace('SELECT ', 'SELECT u.user_level, u.user_color, u.user_group_id, ', $sql);
//-- fin mod : rank color system -----------------------------------------------
$cm_viewtopic->generate_columns($template,$forum_id,$sql);
// start mod save posts as drafts (and end mod too)...note that I added AND p.post_draft = 0 in the forgoing $sql definition to assure that draft posts would not be displayed in viewtopic
if ( !($result = $db->sql_query($sql)) )
{
	message_die(GENERAL_ERROR, "Could not obtain post/user information.", '', __LINE__, __FILE__, $sql);
}
//-- end mod : IP Country Flag II ----------------------------------------------

$postrow = array();
if ($row = $db->sql_fetchrow($result))
{
	do
	{
		$postrow[] = $row;
	}
	while ($row = $db->sql_fetchrow($result));
	$db->sql_freeresult($result);

	$total_posts = count($postrow);
}
else 
{ 
   include($phpbb_root_path . 'includes/functions_admin.' . $phpEx); 
   sync('topic', $topic_id); 

   message_die(GENERAL_MESSAGE, $lang['No_posts_topic']); 
} 

$resync = FALSE; 
if ($forum_topic_data['topic_replies'] + 1 < $start + count($postrow)) 
{ 
   $resync = TRUE; 
} 
elseif ($start + $board_config['posts_per_page'] > $forum_topic_data['topic_replies']) 
{ 
   $row_id = intval($forum_topic_data['topic_replies']) % intval($board_config['posts_per_page']); 
   if ($postrow[$row_id]['post_id'] != $forum_topic_data['topic_last_post_id'] || $start + count($postrow) < $forum_topic_data['topic_replies']) 
   { 
      $resync = TRUE; 
   } 
} 
elseif (count($postrow) < $board_config['posts_per_page']) 
{ 
   $resync = TRUE; 
} 

if ($resync) 
{ 
   include($phpbb_root_path . 'includes/functions_admin.' . $phpEx); 
   sync('topic', $topic_id); 

   $result = $db->sql_query('SELECT COUNT(post_id) AS total FROM ' . POSTS_TABLE . ' WHERE topic_id = ' . $topic_id); 
   $row = $db->sql_fetchrow($result); 
   $total_replies = $row['total']; 
}

$sql = "SELECT *
	FROM " . RANKS_TABLE . "
	ORDER BY rank_special, rank_min";
if ( !($result = $db->sql_query($sql)) )
{
	message_die(GENERAL_ERROR, "Could not obtain ranks information.", '', __LINE__, __FILE__, $sql);
}

$ranksrow = array();
while ( $row = $db->sql_fetchrow($result) )
{
	$ranksrow[] = $row;
}
$db->sql_freeresult($result);

//
// Define censored word matches
//
$orig_word = array();
$replacement_word = array();
obtain_word_list($orig_word, $replacement_word);

//
// Censor topic title
//
if ( count($orig_word) )
{
	$topic_title = preg_replace($orig_word, $replacement_word, $topic_title);
}

//
// Word hightlighter with CrackerTracker Protection Engine
// Security System powered by http://www.cback.de
//
$highlight_match = $highlight = '';
if (isset($HTTP_GET_VARS['lighter']))
{
	// Split words and phrases
	$words = explode(' ', trim(htmlspecialchars($HTTP_GET_VARS['highlight'])));

	for($i = 0; $i < sizeof($words); $i++)
	{
		if (trim($words[$i]) != '')
		{
			$highlight_match .= (($highlight_match != '') ? '|' : '') . str_replace('*', '\w*', preg_quote($words[$i], '#'));

		}
	}
	unset($words);

	$highlight = urlencode($HTTP_GET_VARS['highlight']);
	$highlight_match = phpbb_rtrim($highlight_match, "\\");
}

//
// Post, reply and other URL generation for
// templating vars
//
$new_topic_url = append_sid("posting.$phpEx?mode=newtopic&amp;" . POST_FORUM_URL . "=$forum_id");
$reply_topic_url = append_sid("posting.$phpEx?mode=reply&amp;" . POST_TOPIC_URL . "=$topic_id");
$view_forum_url = append_sid("viewforum.$phpEx?" . POST_FORUM_URL . "=$forum_id");
// www.phpBB-SEO.com SEO TOOLKIT BEGIN 
if ($userdata['session_logged_in']) { 
$view_prev_topic_url = append_sid("viewtopic.$phpEx?" . POST_TOPIC_URL . "=$topic_id&amp;view=previous"); 
$view_next_topic_url = append_sid("viewtopic.$phpEx?" . POST_TOPIC_URL . "=$topic_id&amp;view=next"); 

// 
// Mozilla navigation bar 
// 
$nav_links['prev'] = array( 
   'url' => $view_prev_topic_url, 
   'title' => $lang['View_previous_topic'] 
); 
$nav_links['next'] = array( 
   'url' => $view_next_topic_url, 
   'title' => $lang['View_next_topic'] 
); 
} 
// www.phpBB-SEO.com SEO TOOLKIT END
$nav_links['up'] = array(
	'url' => $view_forum_url,
	'title' => $forum_name
);

if ( $forum_topic_data['forum_status'] == FORUM_LOCKED || $forum_topic_data['topic_status'] == TOPIC_LOCKED ) 
{ 
$reply_img = ( !$is_auth['auth_mod'] ) ? $images['reply_locked'] : $images['reply_new'];
$reply_alt = ( !$is_auth['auth_mod'] ) ? $lang['Topic_locked'] : $lang['Reply_to_topic'];
$post_img = ( !$is_auth['auth_mod'] ) ? $images['post_locked'] : $images['post_new'];
$post_alt = ( !$is_auth['auth_mod'] ) ? $lang['Forum_locked'] : $lang['Post_new_topic'];

} 
else 
{ 
   $reply_img = $images['reply_new']; 
   $reply_alt = $lang['Reply_to_topic']; 
   $post_img = $images['post_new']; 
   $post_alt = $lang['Post_new_topic']; 
} 
//
// Set a cookie for this topic
//
if ( $userdata['session_logged_in'] )
{
	$tracking_topics = ( isset($HTTP_COOKIE_VARS[$board_config['cookie_name'] . '_t']) ) ? unserialize($HTTP_COOKIE_VARS[$board_config['cookie_name'] . '_t']) : array();
	$tracking_forums = ( isset($HTTP_COOKIE_VARS[$board_config['cookie_name'] . '_f']) ) ? unserialize($HTTP_COOKIE_VARS[$board_config['cookie_name'] . '_f']) : array();

	if ( !empty($tracking_topics[$topic_id]) && !empty($tracking_forums[$forum_id]) )
	{
		$topic_last_read = ( $tracking_topics[$topic_id] > $tracking_forums[$forum_id] ) ? $tracking_topics[$topic_id] : $tracking_forums[$forum_id];
	}
	else if ( !empty($tracking_topics[$topic_id]) || !empty($tracking_forums[$forum_id]) )
	{
		$topic_last_read = ( !empty($tracking_topics[$topic_id]) ) ? $tracking_topics[$topic_id] : $tracking_forums[$forum_id];
	}
	else
	{
		$topic_last_read = $userdata['user_lastvisit'];
	}

	if ( count($tracking_topics) >= 150 && empty($tracking_topics[$topic_id]) )
	{
		asort($tracking_topics);
		unset($tracking_topics[key($tracking_topics)]);
	}

	$tracking_topics[$topic_id] = time();

	setcookie($board_config['cookie_name'] . '_t', serialize($tracking_topics), 0, $board_config['cookie_path'], $board_config['cookie_domain'], $board_config['cookie_secure']);
}

//
// Load templates
//
$template->set_filenames(array(
	'body' => 'viewtopic_body.tpl')
);
$all_forums = array();
make_jumpbox_ref('viewforum.'.$phpEx, $forum_id, $all_forums);

$parent_id = 0;
for($i=0; $i<count($all_forums); $i++)
{
	if($all_forums[$i]['forum_id'] == $forum_id)
	{
		$parent_id = $all_forums[$i]['forum_parent'];
	}
}
if($parent_id)
{
	for($i=0; $i<count($all_forums); $i++)
	{
		if($all_forums[$i]['forum_id'] == $parent_id)
		{
			$template->assign_vars(array(
				'PARENT_FORUM'			=> 1,
				'U_VIEW_PARENT_FORUM'	=> append_sid("viewforum.$phpEx?" . POST_FORUM_URL .'=' . $all_forums[$i]['forum_id']),
				'PARENT_FORUM_NAME'		=> $all_forums[$i]['forum_name'],
				));
		}
	}
}

//
// Output page header
//
// www.phpBB-SEO.com SEO TOOLKIT BEGIN - TITLE
$extra_title = ($start != 0) ? ' - ' . $lang['Page'] . ( floor( ($start / $board_config['posts_per_page']) ) + 1 ) : '';
$page_title = "$forum_name : " . $topic_title . $extra_title;
// www.phpBB-SEO.com SEO TOOLKIT END - TITLE
include($phpbb_root_path . 'includes/page_header.'.$phpEx);

//-- mod : toolbar -------------------------------------------------------------
//-- add
if ( $can_watch_topic )
{
	$uw_parm = $is_watching_topic ? 'unwatch' : 'watch';
	$tlbr_more = array(
		'watch' => array('link_pgm' => 'viewtopic', 'link_parms' => array(POST_TOPIC_URL => intval($topic_id), $uw_parm => 'topic', 'start' => intval($start)), 'txt' => $is_watching_topic ? 'Stop_watching_topic' : 'Start_watching_topic', 'img' => $is_watching_topic ? 'tlbr_un_watch' : 'tlbr_watch'),
	);
}
build_toolbar('viewtopic', $l_privmsgs_text, $s_privmsg_new, $forum_id, $tlbr_more);
//-- fin mod : toolbar ---------------------------------------------------------

// mod topic mod add
if ( ( ( $board_config['allow_tnologguest'] && $forum_topic_data['topic_noguest'] ) || $board_config['globalnoguestt'] ) && $userdata['user_id'] == ANONYMOUS ) 
{
	// if this is a bot we let it through... people wanted this *shrugs*
	if ( !user_is_bot( ) )
	{
		if ( $board_config['redirectnoguest'] )
		{
			redirect("login.$phpEx");
		}
		else
		{
			message_die ( GENERAL_MESSAGE, $lang['topic_noguest'] );
		}
	}
}
check_topicban ( $topic_id, TRUE );

$password = $forum_topic_data['topic_password'];
$pass_lvl = $forum_topic_data['topic_pass_level'];
$topic_logged = ( is_array( $userdata['log_topics'] ) ) ? array_search ( $forum_topic_data['topic_id'], $userdata['log_topics'] ) : FALSE;
$mod = FALSE;
if ( $pass_lvl == $userdata['user_level'] ) 
{
	$mod = FALSE;
}
elseif ( $pass_lvl == USER && $userdata['user_level'] > USER )
{
	$mod = TRUE;
}
if ( $userdata['user_level'] == ADMIN || !$board_config['enable_topicpass'] || ( $postrow[0]['user_id'] == ANONYMOUS && !$board_config['allow_guestpass'] ) ) 
{
	$mod = TRUE;
}

if ( $topic_logged === FALSE && $password != '' && !$mod ) 
{
	if ( !$board_config['allow_guesttlogin'] && $userdata['user_id'] == ANONYMOUS )
	{
		if ( $board_config['redirectnoguest'] )
		{
			redirect("login.$phpEx");
		}else
		{
			message_die ( GENERAL_MESSAGE, $lang['guest_nologin'] );
		}
	}elseif ( !$userdata['user_allow_tlogin'] ) 
	{
		message_die ( GENERAL_MESSAGE, $lang['user_nologin'] );
	}elseif ( !isset($HTTP_POST_VARS['topic_login'] )) 
	{
		$template -> assign_vars ( array (
			'L_LOGIN' => $lang['Login'],
			'L_PASSWORD' => $lang['Password'],
	
			'MESSAGE_TITLE' => $lang['Login'],
			'MESSAGE_TEXT' => $lang['topic_login'],

			'S_LOGIN_ACTION' => append_sid ( "viewtopic.$phpEx?" . POST_TOPIC_URL . "=$topic_id" )
		) );

		$template -> set_filenames ( array (
			'login' => 'topic_login.tpl'
		) );
	
		$template->pparse('login');

		include($phpbb_root_path . 'includes/page_tail.'.$phpEx);
	
		break;
	}else
	{
		$pass = md5 ( $HTTP_POST_VARS['topic_pass'] );
		if ( $pass == $password ) 
		{
			$log_topics = $userdata['log_topics'];
			$log_topics[count ( $log_topics ) + 1] = $topic_id;
			//add this to session table
			$sid = $userdata['session_id'];
			$log_topics = implode ( ',', $log_topics );
			$sql = "UPDATE " . SESSIONS_TABLE . " SET " .
				"session_logged_topics='$log_topics' " .
				"WHERE session_id='$sid' LIMIT 1";
			$db -> sql_query ( $sql );
		}else
		{
			message_die ( GENERAL_ERROR, $lang['wrong_tpass'] );
		}
	}
}elseif ( $topic_logged === FALSE && ( $mod || $password == '' ) )
{
	$log_topics = $userdata['log_topics'];
	$log_topics[count ( $log_topics ) + 1] = $topic_id;
	//add this to session table
	$sid = $userdata['session_id'];
	$log_topics = implode ( ',', $log_topics );
	$sql = "UPDATE " . SESSIONS_TABLE . " SET " .
		"session_logged_topics='$log_topics' " .
		"WHERE session_id='$sid' LIMIT 1";
	$db -> sql_query ( $sql );
}
// mod topic mod end


//
// User authorisation levels output
//
$s_auth_can = ( ( $is_auth['auth_post'] ) ? $lang['Rules_post_can'] : $lang['Rules_post_cannot'] ) . '<br />';
$s_auth_can .= ( ( $is_auth['auth_reply'] ) ? $lang['Rules_reply_can'] : $lang['Rules_reply_cannot'] ) . '<br />';
$s_auth_can .= ( ( $is_auth['auth_edit'] ) ? $lang['Rules_edit_can'] : $lang['Rules_edit_cannot'] ) . '<br />';
$s_auth_can .= ( ( $is_auth['auth_delete'] ) ? $lang['Rules_delete_can'] : $lang['Rules_delete_cannot'] ) . '<br />';
$s_auth_can .= ( ( $is_auth['auth_vote'] ) ? $lang['Rules_vote_can'] : $lang['Rules_vote_cannot'] ) . '<br />';
//-- mod : calendar ------------------------------------------------------------
//-- add
$s_auth_can .= ( ( $is_auth['auth_cal'] ) ? $lang['Rules_calendar_can'] : $lang['Rules_calendar_cannot'] ) . '<br />';
//-- fin mod : calendar --------------------------------------------------------

// mod topic mod add
$pass = ( check_tauth ( $forum_row['auth_tpass'], 'auth_tpass', $forum_id ) && $userdata['user_allow_pass'] ) ? $lang['Rules_tpass_can']: $lang['Rules_tpass_cannot'];
$ban = ( check_tauth ( $forum_row['auth_tban'], 'auth_tban', $forum_id ) && $userdata['user_allow_tban'] ) ? $lang['Rules_tban_can']: $lang['Rules_tban_cannot'];
$noguest = ( check_tauth ( $forum_row['auth_tnoguest'], 'auth_tnoguest', $forum_id ) ) ? $lang['Rules_tnoguest_can']: $lang['Rules_tnoguest_cannot'];
$log = ( $userdata['user_allow_tlogin'] || ( $board_config['allow_guestlogin'] && $userdata['user_id'] == ANONYMOUS ) ) ? $lang['Rules_tlog_can']: $lang['Rules_tlog_cannot'];
$s_auth_can .= ( $board_config['enable_topicpass'] ) ? $pass . '<br />' : '';
$s_auth_can .= ( $board_config['enable_topicpass'] ) ? $log . '<br />' : '';
$s_auth_can .= ( $board_config['enable_topicban'] ) ? $ban . '<br />' : '';
$s_auth_can .= ( $board_config['allow_tnologguest'] ) ? $noguest . '<br />' : '';
// mod topic mod end

attach_build_auth_levels($is_auth, $s_auth_can);

$topic_mod = '';


// mod topic mod change arguments

if ( $is_auth['auth_mod'] && ( !$forum_topic_data['topic_adminedit'] || $userdata['user_level'] == ADMIN ))
{
	$s_auth_can .= sprintf($lang['Rules_moderate'], "<a href=\"modcp.$phpEx?" . POST_FORUM_URL . "=$forum_id&amp;sid=" . $userdata['session_id'] . '">', '</a>');

	$topic_mod .= "<a onclick=\"return AJAXTopicDelete($topic_id, '". $lang['Confirm_delete_topic'] ."');\" href=\"modcp.$phpEx?" . POST_TOPIC_URL . "=$topic_id&amp;mode=delete&amp;sid=" . $userdata['session_id'] . '"><img src="' . $images['topic_mod_delete'] . '" alt="' . $lang['Delete_topic'] . '" title="' . $lang['Delete_topic'] . '" border="0" /></a>&nbsp;';

	$topic_mod .= "<a onclick=\"return AJAXTopicMoveSelect();\" href=\"modcp.$phpEx?" . POST_TOPIC_URL . "=$topic_id&amp;mode=move&amp;sid=" . $userdata['session_id'] . '"><img src="' . $images['topic_mod_move'] . '" alt="' . $lang['Move_topic'] . '" title="' . $lang['Move_topic'] . '" border="0" /></a>&nbsp;';

	$topic_mod .= ( $forum_topic_data['topic_status'] == TOPIC_UNLOCKED ) ? "<a id=\"topic_locklink\" onclick=\"return AJAXLockTopic($topic_id, 1);\" href=\"modcp.$phpEx?" . POST_TOPIC_URL . "=$topic_id&amp;mode=lock&amp;sid=" . $userdata['session_id'] . '"><img id="topic_lockimg" src="' . $images['topic_mod_lock'] . '" alt="' . $lang['Lock_topic'] . '" title="' . $lang['Lock_topic'] . '" border="0" /></a>&nbsp;' : "<a id=\"topic_locklink\" onclick=\"return AJAXLockTopic($topic_id, 0);\" href=\"modcp.$phpEx?" . POST_TOPIC_URL . "=$topic_id&amp;mode=unlock&amp;sid=" . $userdata['session_id'] . '"><img id="topic_lockimg" src="' . $images['topic_mod_unlock'] . '" alt="' . $lang['Unlock_topic'] . '" title="' . $lang['Unlock_topic'] . '" border="0" /></a>&nbsp;';

	$topic_mod .= "<a href=\"modcp.$phpEx?" . POST_TOPIC_URL . "=$topic_id&amp;mode=split&amp;sid=" . $userdata['session_id'] . '"><img src="' . $images['topic_mod_split'] . '" alt="' . $lang['Split_topic'] . '" title="' . $lang['Split_topic'] . '" border="0" /></a>&nbsp;&nbsp;';

	$topic_mod .= "<a href=\"modcp.$phpEx?" . POST_TOPIC_URL . "=$topic_id&amp;mode=multi_del&amp;sid=" . $userdata['session_id'] . '"><img src="' . $images['topic_mod_multi_delete'] . '" alt="' . $lang['Delete_multiple_posts'] . '" title="' . $lang['Delete_multiple_posts'] . '" border="0" /></a>&nbsp;';

	$topic_mod .= ( $forum_topic_data['topic_type'] != 1 ) ? "<a id=\"sticky_link\" onclick=\"return AJAXTopicTypeChange($topic_id, 1);\" href=\"modcp.$phpEx?" . POST_TOPIC_URL . "=$topic_id&amp;mode=sticky&amp;sid=" . $userdata['session_id'] . '"><img id="sticky_img" src="' . $images['topic_mod_sticky'] . '" alt="' . $lang['Post_Sticky'] . '" title="' . $lang['Post_Sticky'] . '" border="0" /></a>&nbsp;' : "<a id=\"sticky_link\" onclick=\"return AJAXTopicTypeChange($topic_id, 0);\" href=\"modcp.$phpEx?" . POST_TOPIC_URL . "=$topic_id&amp;mode=unsticky&amp;sid=" . $userdata['session_id'] . '"><img id="sticky_img" src="' . $images['topic_mod_unsticky'] . '" alt="' . $lang['Post_Normal'] . '" title="' . $lang['Post_Normal'] . '" border="0" /></a>&nbsp;';

	$topic_mod .= ( $forum_topic_data['topic_type'] != 2 ) ? "<a id=\"announce_link\" onclick=\"return AJAXTopicTypeChange($topic_id, 2);\" href=\"modcp.$phpEx?" . POST_TOPIC_URL . "=$topic_id&amp;mode=announce&amp;sid=" . $userdata['session_id'] . '"><img id="announce_img" src="' . $images['topic_mod_announce'] . '" alt="' . $lang['Post_Announcement'] . '" title="' . $lang['Post_Announcement'] . '" border="0" /></a>&nbsp;' : "<a id=\"announce_link\" onclick=\"return AJAXTopicTypeChange($topic_id, 0);\" href=\"modcp.$phpEx?" . POST_TOPIC_URL . "=$topic_id&amp;mode=unannounce&amp;sid=" . $userdata['session_id'] . '"><img id="announce_img" src="' . $images['topic_mod_unannounce'] . '" alt="' . $lang['Post_Normal'] . '" title="' . $lang['Post_Normal'] . '" border="0" /></a>&nbsp;';

	include_once($phpbb_root_path . 'includes/functions_admin.'.$phpEx);
	$make_move_select = make_forum_select($topic_id.'_new_forum', $forum_id);
	if (strpos($make_move_select, '<select') !== false)
	{
		$topic_mod .= "<div id=\"move_topic\" style=\"display:none\" class=\"gen\"><hr /><b>".$lang['Move'].":</b> ".$make_move_select;
		$topic_mod .= "<br /><input type=\"checkbox\" id=\"shadow\" />&nbsp;" . $lang['Leave_shadow_topic'];
		$topic_mod .= "<hr /><input type=\"button\" value=\"".$lang['Move']."\" onclick=\"return AJAXTopicMove($topic_id, $forum_id);\" />";
		$topic_mod .= "&nbsp;<input type=\"button\" value=\"".$lang['Reset']."\" onclick=\"return AJAXTopicMoveCancel();\" /></div>";
	}
//-- mod : merge -----------------------------------------------------------------------------------
//-- add
	$topic_mod .= '<a href="' . append_sid("merge.$phpEx?" . POST_TOPIC_URL . '=' . $topic_id) . '"><img src="' . $images['topic_mod_merge'] . '" alt="' . $lang['Merge_topics'] . '" title="' . $lang['Merge_topics'] . '" border="0" /></a>&nbsp;';
//-- fin mod : merge -------------------------------------------------------------------------------
}

//
// Topic watch information
//
$s_watching_topic = '';
if ( $can_watch_topic )
{
	if ( $is_watching_topic )
	{
		$s_watching_topic = "<a id=\"watchlink\" onclick=\"return AJAXWatchTopic($topic_id, $start, 0);\" href=\"viewtopic.$phpEx?" . POST_TOPIC_URL . "=$topic_id&amp;unwatch=topic&amp;start=$start&amp;sid=" . $userdata['session_id'] . '">' . $lang['Stop_watching_topic'] . '</a>';
		$s_watching_topic_img = ( isset($images['topic_un_watch']) ) ? "<a id=\"watchlink_img\" onclick=\"return AJAXWatchTopic($topic_id, $start, 0);\" href=\"viewtopic.$phpEx?" . POST_TOPIC_URL . "=$topic_id&amp;unwatch=topic&amp;start=$start&amp;sid=" . $userdata['session_id'] . '"><img id="watchimage" src="' . $images['topic_un_watch'] . '" alt="' . $lang['Stop_watching_topic'] . '" title="' . $lang['Stop_watching_topic'] . '" border="0"></a>' : '';
	}
	else
	{
		$s_watching_topic = "<a id=\"watchlink\" onclick=\"return AJAXWatchTopic($topic_id, $start, 1);\" href=\"viewtopic.$phpEx?" . POST_TOPIC_URL . "=$topic_id&amp;watch=topic&amp;start=$start&amp;sid=" . $userdata['session_id'] . '">' . $lang['Start_watching_topic'] . '</a>';
		$s_watching_topic_img = ( isset($images['Topic_watch']) ) ? "<a id=\"watchlink_img\" onclick=\"return AJAXWatchTopic($topic_id, $start, 1);\" href=\"viewtopic.$phpEx?" . POST_TOPIC_URL . "=$topic_id&amp;watch=topic&amp;start=$start&amp;sid=" . $userdata['session_id'] . '"><img id="watchimage" src="' . $images['Topic_watch'] . '" alt="' . $lang['Start_watching_topic'] . '" title="' . $lang['Start_watching_topic'] . '" border="0"></a>' : '';
	}
}

//
// If we've got a hightlight set pass it on to pagination,
// I get annoyed when I lose my highlight after the first page.
//
$pagination = ( $highlight != '' ) ? generate_pagination("viewtopic.$phpEx?" . POST_TOPIC_URL . "=$topic_id&amp;postdays=$post_days&amp;postorder=$post_order&amp;lighter=$highlight", $total_replies, $board_config['posts_per_page'], $start) : generate_pagination("viewtopic.$phpEx?" . POST_TOPIC_URL . "=$topic_id&amp;postdays=$post_days&amp;postorder=$post_order", $total_replies, $board_config['posts_per_page'], $start);

// Start Smilies Invasion Mod
if ( $board_config['allow_smilies'] )
{
  $forum_name = smilies_pass($forum_name);
  $topic_title = smilies_pass($topic_title);
}
// End Smilies Invasion Mod

// Cache Posts
if ($board_config['enable_post_cache'])
{
	$cps_topic_img = '<a href="modcp.'.$phpEx.'?'.POST_CPS_MANAGE_URL.'=recycle_topic&amp;'.POST_TOPIC_URL.'='.$topic_id.'&amp;sid='.$userdata['session_id'].'"><img src="'.$images['icon_cache_recycle_topic'].'" alt="'.$lang['CPS_recycle_topic'].'" title="'.$lang['CPS_recycle_topic'].'" border="0" /></a>&nbsp;';
	$cps_topic_img .= ( !$forum_topic_data['topic_cache_lock'] ) ? '<a href="modcp.'.$phpEx.'?'.POST_CPS_MANAGE_URL.'=deactivate_topic&amp;'.POST_TOPIC_URL.'='.$topic_id.'&amp;sid='.$userdata['session_id'].'"><img src="'.$images['icon_cache_deactivate_topic'].'" alt="'.$lang['CPS_dont_cache_topic'].'" title="'.$lang['CPS_dont_cache_topic'].'" border="0" /></a>&nbsp;' : '';
}
else
{
	$cps_topic_img = ($userdata['user_level'] == ADMIN) ? '<a href="modcp.'.$phpEx.'?'.POST_CPS_MANAGE_URL.'=delete_topic&amp;'.POST_TOPIC_URL.'='.$topic_id.'&amp;sid='.$userdata['session_id'].'"><img src="'.$images['icon_cache_delete_topic'].'" alt="'.$lang['CPS_delete_topic'].'" title="'.$lang['CPS_delete_topic'].'" border="0" /></a>&nbsp;' : '';
}
// Cache Posts

//
// Send vars to template
//

$template->assign_vars(array(
	'L_DOWNLOAD_POST' => $lang['Download_post'],
	'L_DOWNLOAD_TOPIC' => $lang['Download_topic'],
	'DOWNLOAD_TOPIC' => append_sid("viewtopic.$phpEx?download=-1&amp;".POST_TOPIC_URL."=".$topic_id),
	'FORUM_ID' => $forum_id,
    'FORUM_NAME' => $forum_name,
	'FORUM_ICON_IMG' => ($forum_icon) ? '<img src="' . $phpbb_root_path . $board_config['forum_icon_path'] . '/' . $forum_icon . '" alt="'.$forum_name.'" title="'.$forum_name.'" border="0" />&nbsp;' : '',	// Forum Icon Mod
    'TOPIC_ID' => $topic_id,
    'TOPIC_TITLE' => $topic_title,
	'PAGINATION' => $pagination,
	'PAGE_NUMBER' => sprintf($lang['Page_of'], ( floor( $start / intval($board_config['posts_per_page']) ) + 1 ), ceil( $total_replies / intval($board_config['posts_per_page']) )),
	'HIGHLIGHT' => $highlight,

	'POST_IMG' => $post_img,
	'REPLY_IMG' => $reply_img,

	'L_AUTHOR' => $lang['Author'],
	'L_MESSAGE' => $lang['Message'],
	'L_POSTED' => $lang['Posted'],
	'L_POST_SUBJECT' => $lang['Post_subject'],
	'L_VIEW_NEXT_TOPIC' => $lang['View_next_topic'],
	'L_VIEW_PREVIOUS_TOPIC' => $lang['View_previous_topic'],
	'L_POST_NEW_TOPIC' => $post_alt,
	'L_POST_REPLY_TOPIC' => $reply_alt,
	'L_BACK_TO_TOP' => $lang['Back_to_top'],
	'L_DISPLAY_POSTS' => $lang['Display_posts'],
	'L_LOCK_TOPIC' => $lang['Lock_topic'],
	'L_UNLOCK_TOPIC' => $lang['Unlock_topic'],
	'L_MOVE_TOPIC' => $lang['Move_topic'],
	'L_SPLIT_TOPIC' => $lang['Split_topic'],
	'L_DELETE_TOPIC' => $lang['Delete_topic'],
	'L_GOTO_PAGE' => $lang['Goto_page'],
	'L_FULL_EDIT' => $lang['Full_edit'],
	'L_PREVIEW' => $lang['Preview'],
	'L_SAVE_CHANGES' => $lang['Save_changes'],
	'L_CANCEL' => $lang['Cancel'],

	'S_TOPIC_LINK' => POST_TOPIC_URL,
	'S_SELECT_POST_DAYS' => $select_post_days,
	'S_SELECT_POST_ORDER' => $select_post_order,
	'S_POST_DAYS_ACTION' => append_sid("viewtopic.$phpEx?" . POST_TOPIC_URL . '=' . $topic_id . "&amp;start=$start"),
	'S_AUTH_LIST' => $s_auth_can,
	'S_TOPIC_ADMIN' => $topic_mod,
// Cache Posts
	'S_CPS_IMG_TOPIC' => ( $is_auth['auth_mod'] && $board_config['allow_cache_moderate'] || $userdata['user_level'] == ADMIN ) ? $cps_topic_img : '',
// Cache Posts
	'S_WATCH_TOPIC' => $s_watching_topic,
	'S_WATCH_TOPIC_IMG' => $s_watching_topic_img,
	'S_DISPLAY_PREVIEW' => 'style="display:none;"',

	'U_MORE_SMILIES' => append_sid("smile.$phpEx?mode=smilies"),
	'U_VIEW_TOPIC' => append_sid("viewtopic.$phpEx?" . POST_TOPIC_URL . "=$topic_id&amp;start=$start&amp;postdays=$post_days&amp;postorder=$post_order&amp;highlight=$highlight"),
	'U_VIEW_FORUM' => $view_forum_url,
	'U_VIEW_OLDER_TOPIC' => $view_prev_topic_url,
	'U_VIEW_NEWER_TOPIC' => $view_next_topic_url,
	'U_POST_NEW_TOPIC' => $new_topic_url,
	'U_POST_REPLY_TOPIC' => $reply_topic_url)
);
// Bookmarks MOD, 1.0.1
// Check to see if the topic has already been bookmarked


if ($userdata['session_logged_in']) {
	
	$sql = "SELECT *
		FROM " . BOOKMARKS_TABLE . "
		WHERE user_id = '" . $userdata['user_id'] . "' AND topic_id = '" . intval($topic_id) ."'";

	$result = $db->sql_query($sql);

	$num_row = $db->sql_numrows($result);
	
	if (intval($num_row) == 0) {
		$template->assign_vars(array(
			'U_BOOKMARK' => "<a class=\"nav\" href=\"". append_sid("bookmarks.$phpEx?t=" . $topic_id . "&amp;mode=add" . "\">" . $lang['add_book'] . "</a>")) 
		);
	}
	else {
		$template->assign_vars(array(
			'U_BOOKMARK' => "<a class=\"nav\" href=\"". append_sid("bookmarks.$phpEx?t=" . $topic_id . "&amp;mode=remove" . "\">" . $lang['remove_book'] . "</a>")) 
		);
	}

}

//
// Does this topic contain a poll?
//
if (empty($forum_topic_data['topic_vote']))
{
	$template->assign_vars(array(
		'MAX_POLL_OPTION' => 0,
		'MAX_VOTE' => 0)
	);
}
else
if ( !empty($forum_topic_data['topic_vote']) )
{
	$s_hidden_fields = '';

	$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, "Could not obtain vote data for this topic", '', __LINE__, __FILE__, $sql);
	}

	if ( $vote_info = $db->sql_fetchrowset($result) )
	{
		$db->sql_freeresult($result);
		$vote_options = count($vote_info);

		$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 = " . intval($userdata['user_id']);
		if ( !($result = $db->sql_query($sql)) )
		{
			message_die(GENERAL_ERROR, "Could not obtain user vote data for this topic", '', __LINE__, __FILE__, $sql);
		}

		$user_voted = ( $row = $db->sql_fetchrow($result) ) ? TRUE : 0;
		$db->sql_freeresult($result);

		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'] || $forum_topic_data['topic_status'] == TOPIC_LOCKED )
		{
			$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;

				if ( count($orig_word) )
				{
					$vote_info[$i]['vote_option_text'] = preg_replace($orig_word, $replacement_word, $vote_info[$i]['vote_option_text']);
				}

				$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(
				'L_TOTAL_VOTES' => $lang['Total_votes'],
				'TOTAL_VOTES' => $vote_results_sum,
				'MAX_POLL_OPTION' => 0,
				'MAX_VOTE' => 0,
				
				'L_VIEW_BALLOT' => $lang['View_ballot'],
				'U_VIEW_BALLOT' => append_sid("viewtopic.$phpEx?". POST_TOPIC_URL ."=$topic_id&amp;postdays=$post_days&amp;postorder=$post_order"))
			);
			
			if (!$user_voted && !$poll_expired && $is_auth['auth_vote'] && ($forum_topic_data['topic_status'] != TOPIC_LOCKED))
			{
				$template->assign_block_vars('switch_view_ballot', array());
			}

		}
		else
		{
			$template->set_filenames(array(
				'pollbox' => 'viewtopic_poll_ballot.tpl')
			);

			for($i = 0; $i < $vote_options; $i++)
			{
				if ( count($orig_word) )
				{
					$vote_info[$i]['vote_option_text'] = preg_replace($orig_word, $replacement_word, $vote_info[$i]['vote_option_text']);
				}

				$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'],
				'L_MAX_POLL_OPTION' => $lang['Max_voting_1_explain'] . (($max_vote) ? $max_vote : 1) . $lang['Max_voting_2_explain'],

				'MAX_VOTE' => ($max_vote) ? $max_vote : 1,
				'MAX_POLL_OPTION' => $vote_options,

				'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" />';
		}

		if ( count($orig_word) )
		{
			$vote_title = preg_replace($orig_word, $replacement_word, $vote_title);
		}

		$s_hidden_fields .= '<input type="hidden" name="sid" value="' . $userdata['session_id'] . '" />';

		$template->assign_vars(array(
			'POLL_QUESTION' => $vote_title,

			'S_HIDDEN_FIELDS' => $s_hidden_fields,
			'S_POLL_ACTION' => append_sid("posting.$phpEx?mode=vote&amp;" . POST_TOPIC_URL . "=$topic_id"))
		);

		$template->assign_var_from_handle('POLL_DISPLAY', 'pollbox');
	}
}
// RegMod-Begin
include($phpbb_root_path . 'includes/regmod_viewtopic.' . $phpEx);
// RegMod-End


// start mod survey at topic head
//
// Does this topic contain a survey?
//
if ( !empty($forum_topic_data['topic_survey']) )
{
	// first, get question data
	$sql = "SELECT survey_id, survey_caption, group_ids, show_order, show_nonresponders, lines_to_skip, allow_change_answers, survey_start, survey_length, survey_height, widths, questions, question_sums, question_selected_text, question_average_round
		FROM " . SURVEY_TABLE . "
		WHERE topic_id = $topic_id";

	if ( !($result = $db->sql_query($sql)) )
	{
		message_die(GENERAL_ERROR, "Could not obtain survey data for this topic", '', __LINE__, __FILE__, $sql);
	}

	$survey_info = $db->sql_fetchrow($result);
	$db->sql_freeresult($result);

	// place questions and other question related data into arrays
	$questions = explode("|", $survey_info['questions']);
	$question_sums = explode("|", $survey_info['question_sums']);
	$question_selected_text = explode("|", $survey_info['question_selected_text']);
	$question_average_round = explode("|", $survey_info['question_average_round']);
	$widths = explode("|", $survey_info['widths']);
	$group_ids = $survey_info['group_ids'];
	$number_of_questions = count($questions);

	//now, get the answers plus the names and ids of users in any of the designated groups filling out the survey
	// first, figure out the order we need to show the responders in (show order is 0 for alphabetical, 1 for order of response and 2 for sort by the first answer and then by username)
	if($survey_info['show_order'] == SURVEY_ALPHABETICAL)
	{
		$order_sql = 'u.username';
	}

	if($survey_info['show_order'] == SURVEY_ORDER_OF_RESPONSE)
	{
		$order_sql = 'sa.response_order';
	}

	if($survey_info['show_order'] == SURVEY_SORT_BY_FIRST_ANSWER)
	{
		$order_sql = 'sa.first_answer, u.username';
	}

	if($survey_info['show_order'] == SURVEY_SORT_BY_FIRST_ANSWER_DESCENDING_ORDER)
	{
		$order_sql = 'sa.first_answer DESC, u.username';
	}

	// now do the query for the actual responses...
	$sql = "SELECT DISTINCT u.username, u.user_id, sa.response_order, sa.answers
			FROM " . USERS_TABLE . " u
			INNER JOIN " . USER_GROUP_TABLE . " ug ON ug.user_id = u.user_id
			INNER JOIN " . SURVEY_ANSWERS_TABLE . " sa ON sa.user_id = ug.user_id
			WHERE ( (ug.group_id IN ($group_ids) AND ug.user_pending = 0) OR " . SURVEY_ALL_REGISTERED_USERS . " IN ($group_ids) )
			AND sa.survey_id = " . $survey_info['survey_id'] . "
			ORDER BY $order_sql";

	if ( !($result = $db->sql_query($sql)) )
	{
		message_die(GENERAL_ERROR, "Could not obtain answer data for the survey in this topic", '', __LINE__, __FILE__, $sql);
	}
	// fetch all the answer info; store all the user_ids in a comma separated user_id_list with commas
	// on the outside (for use in figuring out if the current user has already responded, using the strpos function later on) and in a regular
	// comma separated list for use in the sql that fetches nonresponders
	while ($row = $db->sql_fetchrow($result))
	{
		$answer_info[] = $row;
		$user_id_list_in_commas = $user_id_list_in_commas . ',' . $row['user_id'];
	}
	$db->sql_freeresult($result);
	$user_id_list_in_commas = ( $user_id_list_in_commas ) ? $user_id_list_in_commas . ',' : '';
	$user_id_list = ( $user_id_list_in_commas ) ? trim( $user_id_list_in_commas, ',' ) : '';

	// count the number of responders
	$number_of_responders = count($answer_info);

	// now, get the usernames of the nonresponders if we are supposed to show nonresponders
	$sql_not_in_user_id_list = ( $user_id_list ) ? "AND u.user_id NOT IN ($user_id_list)" : '';
	if( $survey_info['show_nonresponders'] )
	{
		$sql = "SELECT DISTINCT u.username, u.user_id
				FROM " . USERS_TABLE . " u
				INNER JOIN " . USER_GROUP_TABLE . " ug ON ug.user_id = u.user_id
				WHERE ( (ug.group_id IN ($group_ids) AND ug.user_pending = 0) OR (" . SURVEY_ALL_REGISTERED_USERS . " IN ($group_ids) AND u.user_id <> " . ANONYMOUS . ") )
				$sql_not_in_user_id_list
				ORDER BY u.username";

		if ( !($result = $db->sql_query($sql)) )
		{
			message_die(GENERAL_ERROR, "Could not obtain answer data for the survey in this topic", '', __LINE__, __FILE__, $sql);
		}

		while ($row = $db->sql_fetchrow($result))
		{
			$nonresponders[] = $row;
		}
		$db->sql_freeresult($result);
		$number_of_nonresponders = count($nonresponders);
	}

	// now, let's find out if the current user is supposed to be filling out this survey
	$sql = "SELECT user_id
			FROM " . USER_GROUP_TABLE . "
			WHERE user_id = " . $userdata['user_id'] . "
			AND ( (group_id IN ($group_ids) && user_pending = 0) OR (" . SURVEY_ALL_REGISTERED_USERS . " IN ($group_ids) AND user_id <> " . ANONYMOUS . ") )";

	if ( !($result = $db->sql_query($sql)) )
	{
		message_die(GENERAL_ERROR, "Could not obtain user data from user groups table", '', __LINE__, __FILE__, $sql);
	}

	if($db->sql_fetchrow($result) && $userdata['session_logged_in'])
	{
		$user_should_answer = 1;
	}
	$db->sql_freeresult($result);


	// now specify the template the results will be shown on at the top of viewtopic
	$template->set_filenames(array(
		'survey_box' => 'survey_result_viewtopic.tpl')
	);

	// figure out if survey has a time limit and has expired
	if($survey_info['survey_length'])
	{
		$survey_expired = ( $survey_info['survey_start'] + $survey_info['survey_length'] < time() ) ? TRUE : 0;
	}
	// let's turn on the survey expired text if the survey has expired
	if( $survey_expired )
	{
		$template->assign_block_vars('switch_survey_expired', array());
	}

	// now, let's turn on the fill in survey button if the user is in one of the specified groups
	// unlss either: (a) the survey has a time limit or the user has already answered the survey or (b) users are not
	// supposed to be able to change their answers and this user has already answered
	if( $user_should_answer && !$survey_expired && ($survey_info['allow_change_answers'] || strpos($user_id_list_in_commas, ','.$userdata['user_id'].',') === false) )
	{
		$template->assign_block_vars('switch_include_fill_in_button', array());
	}

	// and now, let's turn on the fill in survey for other user button if the user is an ADMIN
	if( $userdata['user_level'] == ADMIN )
	{
		$template->assign_block_vars('switch_include_fill_out_for_other_user_button', array());
	}

	// next, send the questions to the template
	for ( $i = 0; $i < $number_of_questions; $i++ )
	{
			$template->assign_block_vars("questions", array(
			'QUESTION_WIDTH' => $widths[$i + 1],
			'QUESTION' => nl2br($questions[$i])
			)
		);
	}

	// now, loop through the responding users, get their answers and send info to the template
	for ( $i = 0; $i < $number_of_responders; $i++ )
	{
		// test if survey designer set username width to -1; if so, skip the username column
		if( $widths[0] <> -1 )
		{
			$viewprofile = append_sid("profile.$phpEx?mode=viewprofile&amp;" . POST_USERS_URL . "=" . $answer_info[$i]['user_id']);
			$username = $answer_info[$i]['username'];
			$template->assign_block_vars("user_rows", array(
				'USERNAME' => "<a href='$viewprofile' class='gen'> $username </a>"
				)
			);
		}
		else
		{
			$template->assign_block_vars("user_rows", array(
				'U_VIEWPROFILE' => '',
				'USERNAME' => ''
				)
			);
//
		}

		// explode all the answers of this user into an answer array
		$answers = explode("|", $answer_info[$i]['answers']);

		// now loop through the questions and send the answers for this user to the template
		for ( $j = 0; $j < $number_of_questions; $j++ )
		{
			$template->assign_block_vars("user_rows.answers", array(
				'ANSWER_WIDTH' => $widths[$j + 1],
				'ANSWER' => nl2br( str_replace('&&', ' || ', $answers[$j]) )
				)
			);

			// here, increment the total if the question is answered and supposed to be totalled at the bottom
			switch( $question_sums[$j] )
			{
				case "":
				case SURVEY_NO_TOTAL:
					break;

				case SURVEY_TOTAL_BY_RESPONSES:
					if( $answers[$j] != '' )
					{
						$total[$j]++;
						$include_total = 1;
					}
					break;

				case SURVEY_TOTAL_BY_NUMBERS_IN_RESPONSES:
					if( $answers[$j] != '' )
					{
						$total[$j] = $total[$j] + $answers[$j];
						$include_total = 1;
					}
					break;

				case SURVEY_TOTAL_BY_MATCHING_TEXT:
					// note that I used strtolower to make this case insensitive
					if( strtolower($answers[$j]) == strtolower($question_selected_text[$j]) )
					{
						$total[$j]++;
						$include_total = 1;
					}
					break;
				case SURVEY_TOTAL_BY_AVERAGE_OF_NUMBERS_IN_REPSONSES:
					// note: the average gets stored in $total[$j]
					if( $answers[$j] != '' )
					{
						$running_total[$j] = $running_total[$j] + $answers[$j];
						$total_responders[$j]++;
						$total[$j] = round($running_total[$j]/$total_responders[$j],$question_average_round[$j]);
						$include_average = 1;
					}
					break;
			}
		}
	}

	// now send the names of the nonresponders to the template if the survey is supposed to show nonresponders
	if( $survey_info['show_nonresponders'] )
	{
		switch( $survey_info['show_nonresponders'] )
		{
			case SURVEY_SHOW_NONRESPONDERS_CENTER_COLUMN:
				$character_separator = "<br />";
				$alignment = "center";
				$line_height = "line-height:110%";
				break;

			case SURVEY_SHOW_NONRESPONDERS_LEFT_COLUMN:
				$character_separator = "<br />";
				$alignment = "left";
				$line_height = "line-height:110%";
				break;

			case SURVEY_SHOW_NONRESPONDERS_CENTER_COMMA_SEPARATED:
				$character_separator = ", ";
				$alignment = "center";
				$line_height = "line-height:100%";
				break;

			case SURVEY_SHOW_NONRESPONDERS_LEFT_COMMA_SEPARATED:
				$character_separator = ", ";
				$alignment = "left";
				$line_height = "line-height:100%";
				break;
		}

		for ( $i = 0; $i < $number_of_nonresponders; $i++ )
		{
			$viewprofile = append_sid("profile.$phpEx?mode=viewprofile&amp;" . POST_USERS_URL . "=" . $nonresponders[$i]['user_id']);
			$username = $nonresponders[$i]['username'];
			$all_nonresponders = ($all_nonresponders) ? $all_nonresponders . $character_separator . "<a href='$viewprofile' class='gen'>$username</a>" : "<a href='$viewprofile' class='gen'>$username</a>";
		}

		$template->assign_vars(array(
			'NONRESPONDER' => $all_nonresponders,
			'ALIGNMENT' => $alignment,
			'LINE_HEIGHT' => $line_height
			)
		);
	}

	// now, send other info to the template (name of survey, total responses, etc)
	$s_hidden_fields = '<input type="hidden" name="topic_id" value="' . $topic_id . '" /><input type="hidden" name="survey_id" value="' . $survey_info['survey_id'] . '" />';
	$s_hidden_fields .= '<input type="hidden" name="sid" value="' . $userdata['session_id'] . '" />';

	// test to see if the current user has already answered the survey; if so, the button allows the user to change his answers;
	// if not, the button allows the user to fill out the survey for the first time
	if ( strpos($user_id_list_in_commas, ','.$userdata['user_id'].',') !== false )
	{
		$fill_out_button = $lang['Change_your_answers'];
		$survey_fill_out_img = $images['change_survey_answers'];
		$survey_link = append_sid("survey.$phpEx?topic_id=" . $topic_id . "&amp;survey_id=" . $survey_info['survey_id'] . "&amp;mode=answer_edit");
	}
	else
	{
		$fill_out_button = $lang['Fill_out_survey'];
		$survey_fill_out_img = $images['fill_out_survey'];
		$survey_link = append_sid("survey.$phpEx?topic_id=" . $topic_id . "&amp;survey_id=" . $survey_info['survey_id']);
	}

	// build a variable called lines_to_skip with a number of <br>s equal to the number specified for this survey
	$lines_to_skip = '';
	for($i=0; $i < $survey_info['lines_to_skip']; $i++)
	{
		$lines_to_skip = $lines_to_skip . '<br />';
	}

	// now figure out if the survey is supposed to have a maximum survey height and is so turn on that switch
	if( $survey_info['survey_height'] > 0 )
	{
		$template->assign_block_vars('switch_max_survey_height', array());
	}

	$template->assign_vars(array(
		'SURVEY_CAPTION' => nl2br($survey_info['survey_caption']),
		'USERNAME_WIDTH' => ( $widths[0] <> -1 ) ? $widths[0] : '',
		'TOTAL_RESPONSES' => $number_of_responders,
		'MAX_SURVEY_HEIGHT' => $survey_info['survey_height'],

		'L_TOTAL_RESPONSES' => $lang['Total_responses'],
		'L_FILL_OUT' => $fill_out_button,
		'L_FILL_OUT_FOR_OTHER_USER' => $lang['Fill_out_survey_for_someone_else'],
		'L_LINES_TO_SKIP' => $lines_to_skip,
		'L_SURVEY_EXPIRED' => $lang['Survey_has_expired_(no_more_voting)'],

		'SURVEY_FILL_OUT_IMG' => $survey_fill_out_img,

		'U_FILL_OUT_SURVEY' => $survey_link,

		'S_HIDDEN_FIELDS' => $s_hidden_fields,
		'S_SURVEY_ACTION' => append_sid("survey.$phpEx")
		)
	);

	// next, give totals for questions where the question table says to give totals
	for ( $i = 0; $i < $number_of_questions; $i++ )
	{
		$totals = $total[$i];
			$template->assign_block_vars("totals", array(
				'TOTAL' => $totals
				)
			);
	}

	// now, add a total caption if any columns are totalled and none are averaged
	if($include_total && !$include_average)
	{
		$template->assign_vars(array('L_TOTAL' => $lang['Total']));
	}

	// else, add an average caption if any columns are averaged and none are totalled
	if($include_average && !$include_total)
	{
		$template->assign_vars(array('L_TOTAL' => $lang['Average']));
	}

	// else add a total or average caption if some columns are totalled and some are averaged
	if($include_total && $include_average)
	{
		$template->assign_vars(array('L_TOTAL' => $lang['Total_or_average']));
	}

	// else if nothing is getting totalled or averaged, send empty text to the template
	if(!$include_total && !$include_average)
	{
		$template->assign_vars(array('L_TOTAL' => ''));
	}

	if($nonresponders && $survey_info['show_nonresponders'])
	{
		$template->assign_vars(array('L_NONRESPONDERS' => $lang['Nonresponders']));
	}
	
    else
	{
		$template->assign_vars(array('L_NONRESPONDERS' => ''));
	}

	$template->assign_var_from_handle('SURVEY_DISPLAY', 'survey_box');
}
// end mod survey at topic head


init_display_post_attachments($forum_topic_data['topic_attachment']);
//
// Update the topic view counter
//
$sql = "UPDATE " . TOPICS_TABLE . "
	SET topic_views = topic_views + 1
	WHERE topic_id = $topic_id";
if ( !$db->sql_query($sql) )
{
	message_die(GENERAL_ERROR, "Could not update topic views.", '', __LINE__, __FILE__, $sql);
}

//
// Okay, let's do the loop, yeah come on baby let's do the loop
// and it goes like this ...
//

//-- mod : topics enhanced -----------------------------------------------------
//-- add
//-- topics nav buttons
$num_row = 0;
//-- fin mod : topics enhanced -------------------------------------------------
for($i = 0; $i < $total_posts; $i++)
{
//-- mod : topics enhanced -----------------------------------------------------
//-- add
//-- topics nav buttons
	$num_row++;

	$nav_buttons = (empty($i)) ? '<a href="' . append_sid('viewtopic.' . $phpEx . '?' . POST_TOPIC_URL . '=' . $topic_id . '&amp;view=previous') . '"><img alt="" src="' . $images['nav_prev'] . '" title="' . $lang['View_previous_topic'] . '" border="0" /></a>' : '';
	$nav_buttons .= (($i == $total_posts - 1) && $total_posts != 1) ? '<a href="#top"><img alt="" src="' . $images['nav_top'] . '" title="' . $lang['Back_to_top'] . '" border="0" /></a>' : '';
	$nav_buttons .= (!empty($i)) ? '<a href="#' . ($num_row - 1) . '"><img alt="" src="' . $images['nav_prev_post'] . '" title="' . $lang['View_previous_post'] . '" border="0" /></a>' : '';
	$nav_buttons .= ($i != $total_posts - 1) ? '<a href="#' . ($num_row + 1) . '"><img alt="" src="' . $images['nav_next_post'] . '" title="' . $lang['View_next_post'] . '" border="0" /></a>' : '';
	$nav_buttons .= (empty($i)) ? '<a href="#bot"><img alt="" src="' . $images['nav_bot'] . '" title="' . $lang['Go_to_bottom'] . '" border="0" /></a>' : '';
	$nav_buttons .= (empty($i)) ? '<a href="' . append_sid('viewtopic.' . $phpEx . '?' . POST_TOPIC_URL . '=' . $topic_id . '&amp;view=next') . '"><img alt="" src="' . $images['nav_next'] . '" title="' . $lang['View_next_topic'] . '" border="0" /></a>' : '';
//-- fin mod : topics enhanced -------------------------------------------------
	$poster_id = $postrow[$i]['user_id'];
	$poster = ( $poster_id == ANONYMOUS ) ? $lang['Guest'] : $postrow[$i]['username'];
//-- mod : browsers list -------------------------------------------------------
//-- add
	$poster_browser = ( $postrow[$i]['user_id'] != ANONYMOUS ) ? display_browser($postrow[$i]['user_browser'], true) : '';
//-- fin mod : browsers list ---------------------------------------------------

    $post_date = create_date2($board_config['default_dateformat'], $postrow[$i]['post_time'], $board_config['board_timezone']);

	$poster_posts = ( $postrow[$i]['user_id'] != ANONYMOUS ) ? '<b>' . $lang['Posts'] . ':</b> ' . $postrow[$i]['user_posts'] : '';
// Topics a user has started MOD, By Manipe (Begin)
	$poster_topics = ( $postrow[$i]['user_id'] != ANONYMOUS ) ? $lang['Topics'] . ': ' . (( $postrow[$i]['user_topics'] ) ? $postrow[$i]['user_topics'] : '0') : '';
// Topics a user has started MOD, By Manipe (End)

	$poster_from = ( $postrow[$i]['user_from'] && $postrow[$i]['user_id'] != ANONYMOUS ) ? $lang['Location'] . ': ' . $postrow[$i]['user_from'] : '';

	// Country/Location Flags
	$poster_from_flag = ( $postrow[$i]['user_from_flag'] && $postrow[$i]['user_id'] != ANONYMOUS ) ? '<br /><img src="images/flags/' . $postrow[$i]['user_from_flag'] . '" alt="' . $postrow[$i]['flag_name'] . '" title="' . $postrow[$i]['flag_name'] . '" border="1" /><br />' : '';
	$poster_shouts = ( $postrow[$i]['user_shouts'] && $postrow[$i]['user_id'] != ANONYMOUS ) ? $lang['shoutbox_shouts_text'] .': '. number_format($postrow[$i]['user_shouts']) : '';

	$poster_joined = ( $postrow[$i]['user_id'] != ANONYMOUS ) ? '<b>' . $lang['Joined'] . ':</b> ' . create_date($lang['DATE_FORMAT'], $postrow[$i]['user_regdate'], $board_config['board_timezone']) : '';

	$poster_avatar = '';
	if ( $postrow[$i]['user_avatar_type'] && $poster_id != ANONYMOUS && $postrow[$i]['user_allowavatar'] )
	{
		switch( $postrow[$i]['user_avatar_type'] )
		{
			case USER_AVATAR_UPLOAD:
				$poster_avatar = ( $board_config['allow_avatar_upload'] ) ? '<img src="' . $board_config['avatar_path'] . '/' . $postrow[$i]['user_avatar'] . '" alt="" border="0" />' : '';
				break;
			case USER_AVATAR_REMOTE:
                // Resize Remote Avatars mod
                // $poster_avatar = ( $board_config['allow_avatar_remote'] ) ? '<img src="' . $postrow[$i]['user_avatar'] . '" alt="" border="0" />' : '';
                // set these vars to your preference for viewtopic (these are only a suggestion)
                // if the remote image is larger than one of these values, the "remote image too large" message will be displayed
                $max_width = 400;
                $max_height = 400;
                $poster_avatar = get_remote_img_tag( $postrow[$i]['user_avatar'], $max_width, $max_height );
                // end Resize Remote Avatars mod
				break;
			case USER_AVATAR_GALLERY:
				$poster_avatar = ( $board_config['allow_avatar_local'] ) ? '<img src="' . $board_config['avatar_gallery_path'] . '/' . $postrow[$i]['user_avatar'] . '" alt="" border="0" />' : '';
				break;
		}
	}

// Default avatar MOD, By Manipe (Begin)
	if ((!$poster_avatar) && ($board_config['default_avatar_set'] != 3)){
		if (($board_config['default_avatar_set'] == 0) && ($poster_id == -1) && ($board_config['default_avatar_guests_url'])){
			$poster_avatar = '<img src="' . $board_config['default_avatar_guests_url'] . '" alt="" border="0" />';
		}
		else if (($board_config['default_avatar_set'] == 1) && ($poster_id != -1) && ($board_config['default_avatar_users_url']) ){
			$poster_avatar = '<img src="' . $board_config['default_avatar_users_url'] . '" alt="" border="0" />';
		}
		else if ($board_config['default_avatar_set'] == 2){
			if (($poster_id == -1) && ($board_config['default_avatar_guests_url'])){
				$poster_avatar = '<img src="' . $board_config['default_avatar_guests_url'] . '" alt="" border="0" />';
			}
			else if (($poster_id != -1) && ($board_config['default_avatar_users_url'])){
				$poster_avatar = '<img src="' . $board_config['default_avatar_users_url'] . '" alt="" border="0" />';
			}
		}
	}
// Default avatar MOD, By Manipe (End)

//--  mod : IP Country Flag II ------------------------------------------
	$ipcfguest = $lang['IPCF_Guest'];

	if ($postrow[$i]['user_id'] == ANONYMOUS)
		{
			$poster_avatar = '<img src="images/avatars/gallery/ipcf_flags/' . $ipcfguest . '.gif" alt="' . $ipcfguest . '" title="' . $ipcfguest . '" border="0" />';
		}
		else if ($postrow[$i]['user_avatar_type'] == 0)
		{
			$poster_avatar = '<img src="images/avatars/gallery/ipcf_flags/' . $postrow[$i]['user_cf_iso3661_1'] . '.gif" alt="' . $lang['IP2Country'][$postrow[$i]['user_cf_iso3661_1']] . '" title="' . $lang['IP2Country'][$postrow[$i]['user_cf_iso3661_1']] . '" border="0" />';
		}
//-- end mod : IP Country Flag II ------------------------------------------

	//
	// Define the little post icon
	//
	if ( $userdata['session_logged_in'] && $postrow[$i]['post_time'] > $userdata['user_lastvisit'] && $postrow[$i]['post_time'] > $topic_last_read )
	{
		$mini_post_img = $images['icon_minipost_new'];
		$mini_post_alt = $lang['New_post'];
	}
	else
	{
		$mini_post_img = $images['icon_minipost'];
		$mini_post_alt = $lang['Post'];
	}

	$mini_post_url = append_sid("viewtopic.$phpEx?" . POST_POST_URL . '=' . $postrow[$i]['post_id']) . '#' . $postrow[$i]['post_id'];

	//
	// Generate ranks, set them to empty string initially.
	//
	$poster_rank = '';
	$rank_image = '';
//-- mod : Rank Tags ------------------------------------------------------------
//-- add
	$rank_tags = '';
//-- fin mod : Rank Tags --------------------------------------------------------

// Start add - Gender MOD
$gender_image = ''; 
// End add - Gender MOD

	if ( $postrow[$i]['user_id'] == ANONYMOUS )
	{
	}
	else if ( $postrow[$i]['user_rank'] )
	{
		for($j = 0; $j < count($ranksrow); $j++)
		{
			if ( $postrow[$i]['user_rank'] == $ranksrow[$j]['rank_id'] && $ranksrow[$j]['rank_special'] )
			{
//-- mod : Rank Tags ------------------------------------------------------------
//-- add
				$rank_tags = ($ranksrow[$j]['rank_tags']) ? explode("\n", $ranksrow[$j]['rank_tags']) : '';
//-- fin mod : Rank Tags --------------------------------------------------------
				$poster_rank = $ranksrow[$j]['rank_title'];
				$rank_image = ( $ranksrow[$j]['rank_image'] ) ? '<img src="' . $ranksrow[$j]['rank_image'] . '" alt="' . $poster_rank . '" title="' . $poster_rank . '" border="0" /><br />' : '';
//-- mod : Rank Tags ------------------------------------------------------------
//-- add
				$poster_rank = ( sizeof ( $rank_tags ) ) ? $rank_tags[0] . $poster_rank . $rank_tags[1] : $poster_rank;
//-- fin mod : Rank Tags --------------------------------------------------------
			}
		}
	}
	else if ( $postrow[$i]['user_rank_theme'] == -1 && ( ( !$postrow[$i]['user_custom_rank_status'] && $postrow[$i]['user_posts'] >= $board_config['custom_rank_posts'] ) || $postrow[$i]['user_custom_rank_status'] ) )
	{
		$poster_rank = $postrow[$i]['user_custom_rank'];
	}
	else
	{
		for($j = 0; $j < count($ranksrow); $j++)
		{
			if ( $postrow[$i]['user_posts'] >= $ranksrow[$j]['rank_min'] && !$ranksrow[$j]['rank_special'] && $postrow[$i]['user_rank_theme'] == $ranksrow[$j]['rank_theme'] )
			{
//-- mod : Rank Tags ------------------------------------------------------------
//-- add
				$rank_tags = ($ranksrow[$j]['rank_tags']) ? explode("\n", $ranksrow[$j]['rank_tags']) : '';
//-- fin mod : Rank Tags --------------------------------------------------------
				$poster_rank = $ranksrow[$j]['rank_title'];
				$rank_image = ( $ranksrow[$j]['rank_image'] ) ? '<img src="' . $ranksrow[$j]['rank_image'] . '" alt="' . $poster_rank . '" title="' . $poster_rank . '" border="0" /><br />' : '';
//-- mod : Rank Tags ------------------------------------------------------------
//-- add
				$poster_rank = ( sizeof ( $rank_tags ) ) ? $rank_tags[0] . $poster_rank . $rank_tags[1] : $poster_rank;
//-- fin mod : Rank Tags --------------------------------------------------------
			}
		}
	}

	//
	// Handle anon users posting with usernames
	//
	if ( $poster_id == ANONYMOUS && $postrow[$i]['post_username'] != '' )
	{
		$poster = $postrow[$i]['post_username'];
		$poster_rank = $lang['Guest'];

	}

	$temp_url = '';

	if ( $poster_id != ANONYMOUS )
	{
		$temp_url = append_sid("profile.$phpEx?mode=viewprofile&amp;" . POST_USERS_URL . "=$poster_id");
		$profile_img = '<a href="' . $temp_url . '"><img src="' . $images['icon_profile'] . '" alt="' . $lang['Read_profile'] . '" title="' . $lang['Read_profile'] . '" border="0" /></a>';
		$profile = '<a href="' . $temp_url . '">' . $lang['Read_profile'] . '</a>';

		$temp_url = append_sid("privmsg.$phpEx?mode=post&amp;" . POST_USERS_URL . "=$poster_id");
		$pm_img = '<a href="' . $temp_url . '"><img src="' . $images['icon_pm'] . '" alt="' . $lang['Send_private_message'] . '" title="' . $lang['Send_private_message'] . '" border="0" /></a>';

			// Start add - Gender MOD
			switch ($postrow[$i]['user_gender'])
			{
				case 1 : $gender_image = "<img src=\"" . $images['icon_minigender_male'] . "\" alt=\"" . $lang['Gender'].  ":".$lang['Male']."\" title=\"" . $lang['Gender'] . ":".$lang['Male']. "\" border=\"0\" />"; break;
				case 2 : $gender_image = "<img src=\"" . $images['icon_minigender_female'] . "\" alt=\"" . $lang['Gender']. ":".$lang['Female']. "\" title=\"" . $lang['Gender'] . ":".$lang['Female']. "\" border=\"0\" />"; break;
				default : $gender_image="";
			}
			// End add - Gender MOD
    
		$pm = '<a href="' . $temp_url . '">' . $lang['Send_private_message'] . '</a>';
		$temp_url_profile = append_sid("profile.$phpEx?mode=viewprofile&amp;" . POST_USERS_URL . "=$poster_id");
		$vb_menu_profile = '<a class="vbm" href="' . $temp_url_profile . '">&nbsp;<img src="' . $images['vb_menu_profile'] . '" border="0" />&nbsp;' . $lang['vb_menu_l_profile'] . '</a>';
		$temp_url_menu = append_sid("privmsg.$phpEx?mode=post&amp;" . POST_USERS_URL . "=$poster_id");
		$vb_menu_pm = '<a class="vbm" href="' . $temp_url_menu . '">&nbsp;<img src="' . $images['vb_menu_pm'] . '" border="0" />&nbsp;' . $lang['vb_menu_l_pm'] . '&nbsp;' . $postrow[$i]['username'] . '&nbsp;</a>';
		$vb_menu_search = '<a class="vbm" href="search.php?show_results=posts&amp;search_author=' . $poster . '">&nbsp;<img src="' . $images['vb_menu_search'] . '" border="0" />&nbsp;' . $lang['vb_menu_l_search'] . '&nbsp;' . $postrow[$i]['username'] . '</a>';
		$vb_menu_www = ( $postrow[$i]['user_website'] ) ? '<a class="vbm" href="' . $postrow[$i]['user_website'] . '" target="_userwww">&nbsp;<img src="' . $images['vb_menu_www'] . '" border="0" />&nbsp;' . $lang['vb_menu_l_www1'] . '&nbsp;' . $postrow[$i]['username'] . '`s&nbsp;' . $lang['vb_menu_l_www2'] . '!</a>' : '';
		//$vb_menu_album = '<a class="vbm" href="album.php?user_id=' . $poster_id . '&mode=list">&nbsp;<img src="' . $images['vb_menu_album'] . '" border="0" />&nbsp;' . $lang['vb_menu_l_album'] . '&nbsp;' . $postrow[$i]['username'] . '</a>';
		$vb_menu_id = $poster_id;

		if ( !empty($postrow[$i]['user_viewemail']) || $is_auth['auth_mod'] )
		{
			$email_uri = ( $board_config['board_email_form'] ) ? append_sid("profile.$phpEx?mode=email&amp;" . POST_USERS_URL .'=' . $poster_id) : 'mailto:' . $postrow[$i]['user_email'];

			$email_img = '<a href="' . $email_uri . '"><img src="' . $images['icon_email'] . '" alt="' . $lang['Send_email'] . '" title="' . $lang['Send_email'] . '" border="0" /></a>';
			$email = '<a href="' . $email_uri . '">' . $lang['Send_email'] . '</a>';
			$vb_menu_email = '<a class="vbm" href="' . $email_uri . '">&nbsp;<img src="' . $images['vb_menu_email'] . '" border="0" />&nbsp;' . $lang['vb_menu_l_email'] . '&nbsp;' . $postrow[$i]['username'] . '</a>';
	}
		else
		{
			$email_img = '';
			$email = '';
			$vb_menu_email = '';
		}

		$www_img = ( $postrow[$i]['user_website'] ) ? '<a href="' . $postrow[$i]['user_website'] . '" target="_userwww"><img src="' . $images['icon_www'] . '" alt="' . $lang['Visit_website'] . '" title="' . $lang['Visit_website'] . '" border="0" /></a>' : '';
		$www = ( $postrow[$i]['user_website'] ) ? '<a href="' . $postrow[$i]['user_website'] . '" target="_userwww">' . $lang['Visit_website'] . '</a>' : '';

		$bday_month_day = floor($postrow[$i]['user_birthday'] / 10000);
		$bday_year_age = ( $postrow[$i]['birthday_display'] != BIRTHDAY_NONE && $postrow[$i]['birthday_display'] != BIRTHDAY_DATE ) ? $postrow[$i]['user_birthday'] - 10000*$bday_month_day : 0;
		$fudge = ( gmdate('md') < $bday_month_day ) ? 1 : 0;
		$age = ( $bday_year_age ) ? gmdate('Y')-$bday_year_age-$fudge : false;
// Start add - Birthdays by TerraFrost - Chinese Zodiac add-on 
		$chinese = '';
		$u_chinese = '';
		$chinese_img = '';
		if ( $age !== false )
		{
			include_once($phpbb_root_path . 'includes/chinese.'.$phpEx);
			preg_match('/(..)(..)/', sprintf('%08d',$postrow[$i]['user_birthday']), $bday_parts);
			$chinese_date = create_date('Ymd', gmmktime(0,0,0, $bday_parts[1], $bday_parts[2], $bday_year_age), 0);
			$chinese = get_chinese_year($chinese_date);
			$u_chinese = $images[$chinese];
			$chinese_img = ($chinese == 'Unknown') ? '' : '<img src="' . $u_chinese . '" alt="' . $lang[$chinese] . '" title="' . $lang[$chinese] . '" align="top" border="0" />';
		}
// End add - Birthdays by TerraFrost - Chinese Zodiac add-on

// Start add - Birthdays add-on zodiac
		if ( $age !== false )
		{
			$user_zodiac = $postrow[$i]['user_zodiac'];
			$zodiac = $lang[$zodiacs[$user_zodiac]];
			$u_zodiac = $images[$zodiacs[$user_zodiac]];
			$zodiac_img = '<img src="' . $u_zodiac . '" alt="' . $zodiac . '" title="' . $zodiac . '" align="top" border="0" />';
			$u_horoscope = append_sid($phpbb_root_path . 'horoscope.'.$phpEx . '?sign=' . $zodiacs[$user_zodiac] . '&amp;date=today');
			$zodiac_img = '<a href="' . $u_horoscope . '" onClick="return openpopup(this.href);" />' . $zodiac_img . '</a>';
		}
		else
		{
			$zodiac = '';
			$u_zodiac = '';
			$zodiac_img = '';
			$u_horoscope = '';
		}
// End add - Birthdays add-on zodiac

		if ( !empty($postrow[$i]['user_icq']) )
		{
			$icq_status_img = '<a href="http://wwp.icq.com/' . $postrow[$i]['user_icq'] . '#pager"><img src="http://web.icq.com/whitepages/online?icq=' . $postrow[$i]['user_icq'] . '&img=5" width="18" height="18" border="0" /></a>';
			$icq_img = '<a href="http://www.icq.com/people/cmd.php?action=add&uin=' . $postrow[$i]['user_icq'] . '"><img src="' . $images['icon_icq'] . '" alt="' . $lang['ICQ'] . '" title="' . $lang['ICQ'] . '" border="0" /></a>';
			$icq =  '<a href="http://www.icq.com/people/cmd.php?action=add&uin=' . $postrow[$i]['user_icq'] . '">' . $lang['ICQ'] . '</a>';
		}
		else
		{
			$icq_status_img = '';
			$icq_img = '';
			$icq = '';
		}

		$aim_img = ( $postrow[$i]['user_aim'] ) ? '<a href="aim:goim?screenname=' . $postrow[$i]['user_aim'] . '&amp;message=Hello+Are+you+there?"><img src="' . $images['icon_aim'] . '" alt="' . $lang['AIM'] . '" title="' . $lang['AIM'] . '" border="0" /></a>' : '';
		$aim = ( $postrow[$i]['user_aim'] ) ? '<a href="aim:goim?screenname=' . $postrow[$i]['user_aim'] . '&amp;message=Hello+Are+you+there?">' . $lang['AIM'] . '</a>' : '';

		$temp_url = append_sid("profile.$phpEx?mode=viewprofile&amp;" . POST_USERS_URL . "=$poster_id");
		//
		// MSN Messenger MOD by Omar Ramadan
		//

		$msn_onlinestatus_server_img = $board_config['msn_server'];
		$msn_img = ( $postrow[$i]['user_msnm'] ) ? ' <a href="#" onclick="SendMSNMessage(\'' . addslashes( $postrow[$i]['user_msnm'] ) . '\'); return false;"><img src="' . $msn_onlinestatus_server_img . $postrow[$i]['user_msnm'] . '/' : '&nbsp;';
		$msn_img2 = ( $postrow[$i]['user_msnm'] ) ? '" alt="' . sprintf($lang['MSN_Send'], $poster) . '" title="' . sprintf($lang['MSN_Send'], $poster) . '" border="0" /></a>' : '&nbsp;';
		$script_name = preg_replace('/^\/?(.*?)\/?$/', '\1', trim($board_config['script_path']));
		$script_name = ( $script_name != '' ) ? $script_name . '/' : '';
		$server_name = trim($board_config['server_name']);
		$server_port = ( $board_config['server_port'] <> 80 ) ? ':' . trim($board_config['server_port']) . '/' : '/';

		$forum_url = $server_name . $server_port . $script_name;
		$msn_img = ( $postrow[$i]['user_msnm'] ) ? '<span class="gen">' . $msn_img . 'onurl=' . $forum_url. $images['icon_msn_online'] . '/offurl=' . $forum_url .$images['icon_msn_offline'] . '/unknownurl=' . $forum_url . $images['icon_msn_unknown'] . $msn_img2. '</span>' : '';

		$myspace_img = ( $postrow[$i]['user_myspace'] ) ? '<a href="http://www.myspace.com/'.$postrow[$i]['user_myspace'].'" target="_blank"><img src="' . $images['icon_myspace'] . '" alt="' . $lang['myspace'] . '" title="' . $lang['myspace'] . '" border="0" /></a>' : '';
		$myspace = ( $postrow[$i]['user_myspace'] ) ? '<a href="http://www.myspace.com'.$postrow[$i]['user_myspace'].'">' . $lang['myspace'] . '</a>' : '';

		$im_img = ( $postrow[$i]['username'] ) ? '<a href="javascript:void(0)" onclick="window.open(\'im.' . $phpEx . '\',\'imwin\',\'width=1024,height=768,scrollbars=yes,status=no\')"><img src="profile.' . $phpEx . '?mode=im&username=' . $postrow[$i]['username'] . '&sid=' . $userdata['session_id'] . '" style="border:0" /></a>' : '';
		$im = ( $postrow[$i]['username'] ) ? '<img src="profile.' . $phpEx . '?mode=im&username=' . $postrow[$i]['username'] . '&sid=' . $userdata['session_id'] . '" style="border:0" />' : '';

		$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'] . '" alt="' . $lang['YIM'] . '" title="' . $lang['YIM'] . '" border="0" /></a>' : '';
		$yim = ( $postrow[$i]['user_yim'] ) ? '<a href="http://edit.yahoo.com/config/send_webmesg?.target=' . $postrow[$i]['user_yim'] . '&amp;.src=pg">' . $lang['YIM'] . '</a>' : '';
// Phoogle Map
		$temp_url = append_sid("phoogle_map.$phpEx?" . POST_USERS_URL . "=$poster_id");
		$phoogle_img = ( $postrow[$i]['user_phoogle_map_center'] && $postrow[$i]['user_phoogle_show_me'] && $postrow[$i]['user_phoogle_allow']) ? '<a href="' . $temp_url . '"><img src="' . $images['icon_phoogle'] . '" alt="' . $lang['Phoogle_Map_Title'] . '" title="' . $lang['Phoogle_Map_Title'] . '" border="0" /></a>' : '';
		$phoogle = ( $postrow[$i]['user_phoogle_map_center'] && $postrow[$i]['user_phoogle_show_me'] && $postrow[$i]['user_phoogle_allow'] ) ? '<a href="' . $temp_url . '">' . $lang['Phoogle_Map_Title'] . '</a>' : '';

// End Phoogle Map
//-- mod : IP Country Flag II ----------------------------------------------
		$flag = $lang['Country'] . ': <img src="images/flags/small/' . $postrow[$i]['user_cf_iso3661_1'] . '.png" alt="' . $lang['IP2Country'][$postrow[$i]['user_cf_iso3661_1']] . '" title="' . $lang['IP2Country'][$postrow[$i]['user_cf_iso3661_1']] . '" border="0" />';
		$user_flag = $lang['User_Country'] . ': <img src="images/flags/' . $postrow[$i]['user_from_flag_cf_iso3661_1'] . '.png" alt="' . $lang['IP2Country'][$postrow[$i]['user_from_flag_cf_iso3661_1']] . '" title="' . $lang['IP2Country'][$postrow[$i]['user_from_flag_cf_iso3661_1']] . '" width="14" height="9" border="0" />';
//-- end mod : IP Country Flag II ------------------------------------------
		$bday_month_day = floor($postrow[$i]['user_birthday'] / 10000);
		$bday_year = $postrow[$i]['user_birthday'] - 10000*$bday_month_day;
		$fudge = ( gmdate('md') < $bday_month_day ) ? 1 : 0;
		$age = ( $bday_year ) ? ' ('.(gmdate('Y')-$bday_year-$fudge).')' : '';
		$lang_bd = ( $bday_year ) ? $lang['bd_user'] : $lang['bd_user_none'];
		$weblog_img = ( $postrow[$i]['user_weblog'] ) ? '<a href="' . append_sid("weblog.$phpEx?" . POST_WEBLOG_URL . "=".$postrow[$i]['user_weblog']) . '"><img src="' . $images['icon_weblog'] . '" alt="' . $lang['Weblog'] . '" title="' . $lang['Weblog'] . '" border="0" /></a>' : '';
		$weblog = ( $postrow[$i]['user_weblog'] ) ? '<a href="' . append_sid("weblog.$phpEx?" . POST_WEBLOG_URL . "=".$postrow[$i]['user_weblog']) . '">' . $lang['Weblog'] . '</a>' : '';
		// Start add - Online/Offline/Hidden Mod
		if ( $postrow[$i]['user_session_time'] >= (time()-$board_config['online_time']) )
		{
			if ( $postrow[$i]['user_allow_viewonline'] )
			{
				$online_status_img = '<a href="' . append_sid("viewonline.$phpEx") . '"><img src="' . $images['icon_online'] . '" alt="' . sprintf($lang['is_online'], $poster) . '" title="' . sprintf($lang['is_online'], $poster) . '" /></a>&nbsp;';
				$online_status = '<br />' . $lang['Online_status'] . ': <strong><a href="' . append_sid("viewonline.$phpEx") . '" title="' . sprintf($lang['is_online'], $poster) . '"' . $online_color . '>' . $lang['Online'] . '</a></strong>';
			}
			else if ( $is_auth['auth_mod'] || $userdata['user_id'] == $poster_id )
			{
				$online_status_img = '<a href="' . append_sid("viewonline.$phpEx") . '"><img src="' . $images['icon_hidden'] . '" alt="' . sprintf($lang['is_hidden'], $poster) . '" title="' . sprintf($lang['is_hidden'], $poster) . '" /></a>&nbsp;';
				$online_status = '<br />' . $lang['Online_status'] . ': <strong><em><a href="' . append_sid("viewonline.$phpEx") . '" title="' . sprintf($lang['is_hidden'], $poster) . '"' . $hidden_color . '>' . $lang['Hidden'] . '</a></em></strong>';
			}
			else
			{
				$online_status_img = '<img src="' . $images['icon_offline'] . '" alt="' . sprintf($lang['is_offline'], $poster) . '" title="' . sprintf($lang['is_offline'], $poster) . '" />&nbsp;';
				$online_status = '<br />' . $lang['Online_status'] . ': <span title="' . sprintf($lang['is_offline'], $poster) . '"' . $offline_color . '><strong>' . $lang['Offline'] . '</strong></span>';
			}
		}
		else
		{
			$online_status_img = '<img src="' . $images['icon_offline'] . '" alt="' . sprintf($lang['is_offline'], $poster) . '" title="' . sprintf($lang['is_offline'], $poster) . '" />&nbsp;';
			$online_status = '<br />' . $lang['Online_status'] . ': <span title="' . sprintf($lang['is_offline'], $poster) . '"' . $offline_color . '><strong>' . $lang['Offline'] . '</strong></span>';
		}
		// End add - Online/Offline/Hidden Mod
	}
	else
	{
		$profile_img = '';
		$profile = '';
		$pm_img = '';
		$pm = '';
		$email_img = '';
		$email = '';
		$www_img = '';
		$www = '';
		$age = false;
		$chinese = '';
		$u_chinese = '';
		$chinese_img = '';
		$zodiac = '';
		$u_zodiac = '';
		$zodiac_img = '';
		$u_horoscope = '';
		$icq_status_img = '';
		$icq_img = '';
		$icq = '';
		$aim_img = '';
		$aim = '';
		$msn_img = '';
		$msn = '';
		$myspace_img = '';
		$myspace = '';
		$im_img = '';
		$im = '';
		$yim_img = '';
		$yim = '';
// Phoogle Map
		$phoogle_img = '';
		$phoogle = '';
// End Phoogle Map
//-- mod : IP Country Flag II ----------------------------------------------
		$flag = '';
		$user_flag = '';
//-- end mod : IP Country Flag II ------------------------------------------
		$vb_menu_profile = '';
		$vb_menu_pm = '';
		$vb_menu_search = '';
		$vb_menu_email = '';
		$vb_menu_www = '';
		//$vb_menu_album = '';
		$age = '';
		$lang_bd = $lang['bd_user_none'];
		$weblog_img = '';
		$weblog = '';
		// Start add - Online/Offline/Hidden Mod
		$online_status_img = '';
		$online_status = '';
		// End add - Online/Offline/Hidden Mod
	}

	$temp_url = append_sid("posting.$phpEx?mode=quote&amp;" . POST_POST_URL . "=" . $postrow[$i]['post_id']);
	$quote_img = '<a href="' . $temp_url . '"><img src="' . $images['icon_quote'] . '" alt="' . $lang['Reply_with_quote'] . '" title="' . $lang['Reply_with_quote'] . '" border="0" /></a>';
	$quote = '<a href="' . $temp_url . '">' . $lang['Reply_with_quote'] . '</a>';
	// start mod clone posts
	if ( $is_auth['auth_pollcreate'] )
	{
		$temp_url = append_sid("clone.$phpEx?" . POST_POST_URL . "=" . $postrow[$i]['post_id']);
		$clone_img = '<a href="' . $temp_url . '"><img src="' . $images['icon_clone'] . '" alt="' . $lang['Clone_post'] . '" title="' . $lang['Clone_post'] . '" border="0" /></a>';
	}
	else $clone_img = '';
	// end mod clone posts

	$temp_url = append_sid("search.$phpEx?search_author=" . urlencode($postrow[$i]['username']) . "&amp;showresults=posts");
	$search_img = '<a href="' . $temp_url . '"><img src="' . $images['icon_search'] . '" alt="' . sprintf($lang['Search_user_posts'], $postrow[$i]['username']) . '" title="' . sprintf($lang['Search_user_posts'], $postrow[$i]['username']) . '" border="0" /></a>';
	$search = '<a href="' . $temp_url . '">' . sprintf($lang['Search_user_posts'], $postrow[$i]['username']) . '</a>';
	if ( ( $userdata['user_id'] == $poster_id && $is_auth['auth_edit'] && ($forum_topic_data['topic_status'] != TOPIC_LOCKED)) || $is_auth['auth_mod'] )
	{
		$edit_url = append_sid("posting.$phpEx?mode=editpost&amp;" . POST_POST_URL . "=" . $postrow[$i]['post_id']);
		$edit_img = '<a href="'. $edit_url .'"><img src="' . $images['icon_edit'] . '" alt="' . $lang['Edit_delete_post'] . '" title="' . $lang['Edit_delete_post'] . '" border="0" /></a>';
		$edit = '<a id="editlink_'. $postrow[$i]['post_id'] .'" onclick="return AJAXPostEdit('. $postrow[$i]['post_id'] .');" href="' . $edit_url . '" style="text-decoration: none;">[ ' . $lang['Edit_quick_post'] . ' ]</a>';
	}
	else
	{
		$edit_img = '';
		$edit = '';
		$edit_url = '';
	}


// mod topic mod add
if ( check_can_tban ( $topic_id ) ) 
{
	$url = "modcp.$phpEx?mode=tban&amp;" . POST_USERS_URL . "=" . $postrow[$i]['poster_id'] . "&amp;" . POST_TOPIC_URL . "=" . $topic_id . "&amp;sid=" . $userdata['session_id'];
	$tban_img = '<a href="' . $url . '"><img src="' . $images['icon_topicban'] . '" alt="' . $lang['topic_ban'] . '" title="' . $lang['topic_ban'] . '" border="0" /></a>';
	$tban = $lang['topic_ban'];
}
// mod topic mod end

	if ( $is_auth['auth_mod'] )
	{
		$temp_url = "modcp.$phpEx?mode=ip&amp;" . POST_POST_URL . "=" . $postrow[$i]['post_id'] . "&amp;" . POST_TOPIC_URL . "=" . $topic_id . "&amp;sid=" . $userdata['session_id'];
		// Start Advanced IP Tools Pack MOD
		$ip_img = '<a href="' . $temp_url . '"><img src="' . $images['icon_ip'] . '" alt="' . $lang['View_IP'] . ' (' . decode_ip($postrow[$i]['poster_ip']) . ')" title="' . $lang['View_IP'] . ' (' . decode_ip($postrow[$i]['poster_ip']) . ')" border="0" /></a>';
		// End Advanced IP Tools Pack MOD
		$ip = '<a href="' . $temp_url . '">' . $lang['View_IP'] . '</a>';

		$temp_url = "posting.$phpEx?mode=delete&amp;" . POST_POST_URL . "=" . $postrow[$i]['post_id'] . "&amp;sid=" . $userdata['session_id'];
		$delpost_img = '<a href="' . $temp_url . '"><img src="' . $images['icon_delpost'] . '" alt="' . $lang['Delete_post'] . '" title="' . $lang['Delete_post'] . '" border="0" /></a>';
		$delpost = '<a href="' . $temp_url . '">' . $lang['Delete_post'] . '</a>';
	}
	else
	{
		$ip_img = '';
		$ip = '';

		if ( $userdata['user_id'] == $poster_id && $is_auth['auth_delete'] && $forum_topic_data['topic_last_post_id'] == $postrow[$i]['post_id'] )
		{
			$temp_url = "posting.$phpEx?mode=delete&amp;" . POST_POST_URL . "=" . $postrow[$i]['post_id'] . "&amp;sid=" . $userdata['session_id'];
			$delpost_img = '<a href="' . $temp_url . '"><img src="' . $images['icon_delpost'] . '" alt="' . $lang['Delete_post'] . '" title="' . $lang['Delete_post'] . '" border="0" /></a>';
			$delpost = '<a href="' . $temp_url . '">' . $lang['Delete_post'] . '</a>';
		}
		else
		{
			$delpost_img = '';
			$delpost = '';
		}
	}

	$post_subject = ( $postrow[$i]['post_subject'] != '' ) ? $postrow[$i]['post_subject'] : '';
	$post_ajax_raw_subject = $post_subject;

	// CrackerTracker v5.x
	if ( $postrow[$i]['ct_miserable_user'] == 1 && $postrow[$i]['user_id'] != $userdata['user_id'] && $userdata['user_level'] == 0)
	{
		$message = $lang['ctracker_message_dialog_title'] . '<br /><br />' . $lang['ctracker_ipb_deleted'];
	}
	else
	{
// Cache Posts
	$parsed = ($board_config['enable_post_cache']) ? $postrow[$i]['parsed'] : 0;
	// Quiz Hack
	if (!empty($forum_topic_data['topic_quiz']) && (!$postrow[$i]['dont_parse'] || !$forum_topic_data['topic_cache_lock']))
	{
		if ($parsed)
		{
			foreach (glob($phpbb_root_path.'cache/posts/*post_'.$postrow[$i]['post_id'].'.gz') as $cachefile)
			{
				@unlink($cachefile);
			}
		}
		$parsed = 0;
		$postrow[$i]['dont_parse'] = 1;
		$sql = "UPDATE " . POSTS_TABLE . "
			SET parsed = 0, dont_cache = 1, cache_file_md5 = NULL 
			WHERE post_id = ".$postrow[$i]['post_id'];
		if(!$result = $db->sql_query($sql))
		{
			message_die(GENERAL_ERROR, 'Could not update parse info', '', __LINE__, __FILE__, $sql);
		}
		$forum_topic_data['topic_cache_lock'] = 1;
		$sql = "UPDATE " . TOPICS_TABLE . "
			SET topic_cache_lock = 1 
			WHERE topic_id = $topic_id";
		if(!$result = $db->sql_query($sql))
		{
			message_die(GENERAL_ERROR, 'Could not update parse info', '', __LINE__, __FILE__, $sql);
		}
	}
	// Quiz Hack
	if (!$parsed || !$board_config['enable_post_cache'])
	{
		$message = $postrow[$i]['post_text'];
	} else {
		$cstyle = ($userdata['session_logged_in'] && $userdata['user_style'] != $board_config['default_style'] && $board_config['cache_each_template']) ? $userdata['user_style'].'_' : '';
		$cachefile = 'cache/posts/'.$cstyle.'post_'.$postrow[$i]['post_id'].'.gz';
		if (file_exists($cachefile) && filemtime($cachefile) >= $postrow[$i]['post_edit_time'] && $postrow[$i]['cache_file_md5'] == md5_file($cachefile))
		{
			$handle = @fopen($phpbb_root_path.$cachefile, 'r');
			$message = gzinflate(@fread($handle, @filesize($cachefile)+1));
			@fclose($handle);
		} else {
			@unlink($cachefile);
			$message = $postrow[$i]['post_text'];
			$parsed = 0;
		}
	}
// Cache Posts
//	$message = $postrow[$i]['post_text'];
		if ( $postrow[$i]['ct_miserable_user'] == 1 && $userdata['user_level'] == ADMIN )
		{
			$message .= '<br /><br />' . $lang['ctracker_mu_success'];
		}
	}
	$scribble_string = addslashes($postrow[$i]['scribble_string']);
	$pid = $postrow[$i]['post_id'];
	$scname = "scribble_cache/s".str_pad($pid,10,"0",STR_PAD_LEFT).".png";
	if(file_exists($scname)) {
	  $scribble_image ="<br /><img src=\"$scname\" alt=\"scribble\"><br />";
	}
	else {
	  $scribble_image = ($scribble_string=="") ? "":"<br /><img src=\"showscribble.php?id=$pid&amp;junk=".rand()."\" alt=\"scribble\"><br />";
	}

	$bbcode_uid = $postrow[$i]['bbcode_uid'];
// mod topic description: add
	if ( $i == 0 )
	{
		$topic_desc4mod = $forum_topic_data['topic_descmod'];
		$topic_desc = fetch_desc( $forum_topic_data['topic_description'], $bbcode_uid );
		$topic_desc = preg_replace($orig_word, $replacement_word, $topic_desc);
		$template->assign_var( 'TOPIC_DESC', $topic_desc );
	}
// mod topic description: end

	$user_sig = ( $postrow[$i]['enable_sig'] && $postrow[$i]['user_sig'] != '' && $board_config['allow_sig'] ) ? $postrow[$i]['user_sig'] : '';
        //
        // Referral Plus
        //
        if (($board_config['rp_enable']) && ($userdata['user_id'] == ANONYMOUS))
        {
                $temp_url = append_sid("profile.$phpEx?mode=register&amp;refer_id=$poster_id");
                $refer_img = '<a href="' . $temp_url . '"><img src="' . $images['icon_referplus'] . '" alt="' . $lang['Rp_viewtopic'] . '" title="' . $lang['Rp_viewtopic'] . '" border="0" /></a>';
        }
        else
        {
                $refer_img = '';
		}
        //
        // Referral Plus
        //
	$user_sig_bbcode_uid = $postrow[$i]['user_sig_bbcode_uid'];

	//
	// Note! The order used for parsing the message _is_ important, moving things around could break any
	// output
	//

	//
	// 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'] || !$userdata['user_allowhtml'])
	{
		if ( $user_sig != '' )
		{
			$user_sig = preg_replace('#(<)([\/]?.*?)(>)#is', "&lt;\\2&gt;", $user_sig);
		}

		// Cache Posts
		if (!$parsed || !$board_config['enable_post_cache'])
		{
			if ( $postrow[$i]['enable_html'] )
			{
				$message = preg_replace('#(<)([\/]?.*?)(>)#is', "&lt;\\2&gt;", $message);
			}
		}
		// Cache Posts
/*		if ( $postrow[$i]['enable_html'] )
		{
			$message = preg_replace('#(<)([\/]?.*?)(>)#is', "&lt;\\2&gt;", $message);
		}*/
	}

	//
	// Parse message and/or sig for BBCode if reqd
	//
	if ( $user_sig != '' && $user_sig_bbcode_uid != '' )
	{

    // Start add - Signatures control MOD
    if ( $userdata['user_allowsignature'] != 2 && $board_config['sig_allow_font_sizes'] == 0 )
    {
	$user_sig = '[size=' . $board_config['sig_max_font_size'] . ':' . $user_sig_bbcode_uid . ']' . $user_sig . '[/size:' . $user_sig_bbcode_uid . ']';
    }
    // End add - Signatures control MOD

		$user_sig = ($board_config['allow_bbcode']) ? bbencode_second_pass($user_sig, $user_sig_bbcode_uid) : preg_replace("/\:$user_sig_bbcode_uid/si", '', $user_sig);
        $user_sig = bbencode_third_pass($user_sig, $user_sig_bbcode_uid, $valid);
	}

		// Cache Posts
		if (!$parsed || !$board_config['enable_post_cache'])
		{
			if ( $bbcode_uid != '' )
			{
				$message = ($board_config['allow_bbcode']) ? bbencode_second_pass($message, $bbcode_uid) : preg_replace("/\:$bbcode_uid/si", '', $message);
				$message = bbencode_third_pass($message, $bbcode_uid, $valid);
			}
		}
		// Cache Posts
/*		if ( $bbcode_uid != '' )
		{
			$message = ($board_config['allow_bbcode']) ? bbencode_second_pass($message, $bbcode_uid) : preg_replace("/\:$bbcode_uid/si", '', $message);
		}*/

	if ( $user_sig != '' && $board_config['sig_allow_url'] != 0 )
	{
		$user_sig = make_clickable($user_sig);
	}
	(!$parsed || !$board_config['enable_post_cache']) ? $message = make_clickable($message) : ''; // Cache Posts
//	$message = make_clickable($message);

	//
	// Parse smilies
	//
	if ( $board_config['allow_smilies'] )
	{
		if ( $postrow[$i]['user_allowsmile'] && $user_sig != '' && $board_config['sig_allow_smilies'] != 0 )
		{
			$user_sig = smilies_pass($user_sig);
		}

		(!$parsed || !$board_config['enable_post_cache']) ? (($postrow[$i]['enable_smilies']) ? $message = smilies_pass($message) : '') : ''; // Cache Posts
/*		if ( $postrow[$i]['enable_smilies'] )
		{
			$message = smilies_pass($message);
		}*/
	}

// Cache Posts
	if (!$parsed && $board_config['enable_post_cache'] && ($postrow[$i]['enable_bbcode'] || $postrow[$i]['enable_html']) && !$postrow[$i]['dont_cache'] && !$forum_topic_data['topic_cache_lock'])
	{
		$cstyle = ($userdata['session_logged_in'] && $userdata['user_style'] != $board_config['default_style'] && $board_config['cache_each_template']) ? $userdata['user_style'].'_' : '';
		$cachefile = 'cache/posts/'.$cstyle.'post_'.$postrow[$i]['post_id'].'.gz';
		$handle = @fopen($phpbb_root_path.$cachefile, 'w');
		@flock($handle, LOCK_EX);
		$packed = gzdeflate($message, 9);
		$cf_size = @fwrite($handle, $packed);
		@flock($handle, LOCK_UN);
		@fclose($handle);
		@chmod($phpbb_root_path.$cachefile, 0666);

		if ($cf_size)
		{
			if ($cf_size > $board_config['min_post_cache_size'])
			{
				$parsed = 1;
				$sql = "UPDATE " . POSTS_TABLE . "
					SET parsed = 1, cache_file_md5 = '".md5_file($cachefile)."'
					WHERE post_id = ".$postrow[$i]['post_id'];
				if(!$result = $db->sql_query($sql))
				{
					message_die(GENERAL_ERROR, 'Could not update parse info', '', __LINE__, __FILE__, $sql);
				}
			}
			else
			{
				$parsed = 0;
				$postrow[$i]['dont_cache'] = 1;
				foreach (glob($phpbb_root_path.'cache/posts/*post_'.$postrow[$i]['post_id'].'.gz') as $cachefile)
				{
					@unlink($cachefile);
				}
				$sql = "UPDATE " . POSTS_TABLE . "
					SET parsed = 0, dont_cache = 1, cache_file_md5 = NULL 
					WHERE post_id = ".$postrow[$i]['post_id'];
				if(!$result = $db->sql_query($sql))
				{
					message_die(GENERAL_ERROR, 'Could not update parse info', '', __LINE__, __FILE__, $sql);
				}
			}
		}
		else if ($postrow[$i]['parsed'])
		{
			$parsed = 0;
			$sql = "UPDATE " . POSTS_TABLE . "
				SET parsed = 0, cache_file_md5 = NULL 
				WHERE post_id = ".$postrow[$i]['post_id'];
			if(!$result = $db->sql_query($sql))
			{
				message_die(GENERAL_ERROR, 'Could not update parse info', '', __LINE__, __FILE__, $sql);
			}
		}
		$postrow[$i]['parsed'] = $parsed;
	}
	else if ( $forum_topic_data['topic_cache_lock'] )
	{
		$parsed = 0;
		$postrow[$i]['dont_cache'] = 1;
		$sql = "UPDATE " . POSTS_TABLE . "
			SET parsed = 0, dont_cache = 1, cache_file_md5 = NULL 
			WHERE post_id = ".$postrow[$i]['post_id'];
		if(!$result = $db->sql_query($sql))
		{
			message_die(GENERAL_ERROR, 'Could not update parse info', '', __LINE__, __FILE__, $sql);
		}
		$postrow[$i]['parsed'] = $parsed;
	}
	if ($board_config['enable_post_cache'])
	{
		$parse_status = ($parsed) ? $CPS_Indicator['cached'] : (($postrow[$i]['dont_cache']) ? $CPS_Indicator['dont_cache'] : ((!$postrow[$i]['enable_bbcode'] && !$postrow[$i]['enable_html']) ? $CPS_Indicator['not_cached'] : $CPS_Indicator['error']));
		$cps_img = (!$forum_topic_data['topic_cache_lock']) ? '<a href="modcp.'.$phpEx.'?'.POST_CPS_MANAGE_URL.'=recycle&amp;'.POST_POST_URL.'='.$postrow[$i]['post_id'].'&amp;'.POST_TOPIC_URL.'='.$postrow[$i]['topic_id'].'&amp;sid='.$userdata['session_id'].'"><img src="'.$images['icon_cache_recycle'].'" alt="'.$lang['CPS_recycle'].'" title="'.$lang['CPS_recycle'].'" border="0" /></a>' : '';
		$cps_img .= ($parsed) ? ' <a href="modcp.'.$phpEx.'?'.POST_CPS_MANAGE_URL.'=deactivate&amp;'.POST_POST_URL.'='.$postrow[$i]['post_id'].'&amp;'.POST_TOPIC_URL.'='.$postrow[$i]['topic_id'].'&amp;sid='.$userdata['session_id'].'"><img src="'.$images['icon_cache_deactivate'].'" alt="'.$lang['CPS_dont_cache'].'" title="'.$lang['CPS_dont_cache'].'" border="0" /></a>' : '';
	} else {
		$parse_status = ($postrow[$i]['parsed']) ? $CPS_Indicator['off_but_cached'] : $CPS_Indicator['off'] ;
		$cps_img = ($postrow[$i]['parsed'] && $userdata['user_level'] == ADMIN) ? '<a href="modcp.'.$phpEx.'?'.POST_CPS_MANAGE_URL.'=delete&amp;'.POST_POST_URL.'='.$postrow[$i]['post_id'].'&amp;'.POST_TOPIC_URL.'='.$postrow[$i]['topic_id'].'&amp;sid='.$userdata['session_id'].'"><img src="'.$images['icon_cache_delete'].'" alt="'.$lang['CPS_delete'].'" title="'.$lang['CPS_delete'].'" border="0" /></a>' : '';
	}
// Cache Posts

	//
	// Highlight active words (primarily for search)
	//
	if ($highlight_match)
	{
		// This has been back-ported from 3.0 CVS
		$message = preg_replace('#(?!<.*)(?<!\w)(' . $highlight_match . ')(?!\w|[^<>]*>)#i', '<b style="color:#'.$theme['fontcolor3'].'">\1</b>', $message);
	}

	//
	// Replace naughty words
	//
	if (count($orig_word))
	{
		$post_subject = preg_replace($orig_word, $replacement_word, $post_subject);
		$post_ajax_raw_subject = preg_replace($orig_word, $replacement_word, $post_ajax_raw_subject);

		if ($user_sig != '')
		{
			$user_sig = str_replace('\"', '"', substr(@preg_replace('#(\>(((?>([^><]+|(?R)))*)\<))#se', "@preg_replace(\$orig_word, \$replacement_word, '\\0')", '>' . $user_sig . '<'), 1, -1));
		}

		$message = str_replace('\"', '"', substr(@preg_replace('#(\>(((?>([^><]+|(?R)))*)\<))#se', "@preg_replace(\$orig_word, \$replacement_word, '\\0')", '>' . $message . '<'), 1, -1));
	}

	//
	// Replace newlines (we use this rather than nl2br because
	// till recently it wasn't XHTML compliant)
	//
	if ( $user_sig != '' && $userdata['user_allowsignature'] != 0 )
	{
		$user_sig = word_wrap_pass($user_sig);
		$user_sig = '<br /><img src="' . $images['sig_divide'] . '" alt="User Signature" /><br />' . str_replace("\n", "\n<br />\n", $user_sig);
	} else $user_sig = '';

	$message = word_wrap_pass($message);
	$message = str_replace("\n", "\n<br />\n", $message);

	//
	// Editing information
	//
	// Start add - User Class Mod
	switch ($postrow[$i]['user_level'])
	{
		case ADMIN:
			$poster_name = '<strong>' . $poster . '</strong>';
			$style_color = ($poster_id == 2) ? ' style="color: #' . $theme['color_founder'] . '"' : ' style="color: #' . $theme['color_admin'] . '"';
			break;
		case MAIN_MOD:
			$poster_name = '<strong>' . $poster . '</strong>';
			$style_color = ' style="color: #' . $theme['color_main_mod'] . '"';
			break;
		case MOD:
			$poster_name = '<strong>' . $poster . '</strong>';
			$style_color = ' style="color: #' . $theme['color_mod'] . '"';
			break;
		case SUPPORT:
			$poster_name = '<strong>' . $poster . '</strong>';
			$style_color = ' style="color: #' . $theme['color_support'] . '"';
			break;
		case VIP:
			$poster_name = '<strong>' . $poster . '</strong>';
			$style_color = ' style="color: #' . $theme['color_vip'] . '"';
			break;
		case BOT:
			$poster_name = '<strong>' . $poster . '</strong>';
			$style_color = ' style="color: #' . $theme['color_bot'] . '"';
			break;
		case USER:
			$poster_name = '<strong>' . $poster . '</strong>';
			$style_color = ' style="color: #' . $theme['color_user'] . '"';
			break;
		default:
			$poster_name = $poster;
			$style_color = '';
			break;
	}

	// Display profile link
	if ($poster_id != ANONYMOUS)
	{
		switch ($userdata['user_level'])
		{
			case ADMIN:
				$poster_name = '<a href="' . $phpbb_root_path . "admin/admin_users.$phpEx?mode=edit&amp;" . POST_USERS_URL . "=" . $poster_id . "&amp;sid=" . $userdata['session_id'] . '"' . $style_color . '>' . $poster_name . '</a>';
				break;
			// If the ModCP is installed, you can uncomment the code below
			/*case MAIN_MOD:
			case MOD:
				$poster_name = '<a href="' . $phpbb_root_path . "modcp/admin_users.$phpEx?mode=edit&amp;" . POST_USERS_URL . "=" . $poster_id . "&amp;sid=" . $userdata['session_id'] . '"' . $style_color . '>' . $poster_name . '</a>';
				break;*/
			default:
				$poster_name = '<a href="' . append_sid("profile.$phpEx?mode=viewprofile&amp;" . POST_USERS_URL . "=" . $poster_id) . '"' . $style_color . '>' . $poster_name . '</a>';
				break;
		}
	}
	// End add - User Class Mod
	if ( $postrow[$i]['post_edit_count'] )
	{
		$l_edit_time_total = ( $postrow[$i]['post_edit_count'] == 1 ) ? $lang['Edited_time_total'] : $lang['Edited_times_total'];

		$l_edited_by = '<br /><br />' . sprintf($l_edit_time_total, $poster_name, create_date($board_config['default_dateformat'], $postrow[$i]['post_edit_time'], $board_config['board_timezone']), $postrow[$i]['post_edit_count']);
	}
	else
	{
		$l_edited_by = '';
	}
	// START ADD Reputation Mod v.1.0.0
	$reputation = '';
	if ($postrow[$i]['user_id'] != ANONYMOUS)
	{
		if ($rep_config['rep_disable'] == 0)
		{
			if ($postrow[$i]['user_reputation'] == 0)
			{
				$reputation = $lang['Zero_reputation'];
			} else
			{
				if ($rep_config['graphic_version'] == 0)
				{
					// Text version
					$reputation =  $lang['Reputation'] . ": ";
					if ($postrow[$i]['user_reputation'] > 0)
					{
						$reputation .= "<strong><font color=\"green\">" . round($postrow[$i]['user_reputation'],1) . "</font></strong>";
					} else {
						$reputation .= "<strong><font color=\"red\">" . round($postrow[$i]['user_reputation'],1) . "</font></strong>";
					}
					$reputation_add = '';
				} else {
					// Graphic version
					get_reputation_medals($postrow[$i]['user_reputation']);
				}
			}
			$reputation .=  " <a href=\""  . append_sid("reputation.$phpEx?a=add&" . POST_USERS_URL . "=" . $postrow[$i]['user_id']) . "&" . POST_POST_URL . "=" . $postrow[$i]['post_id'] . "&c=" . substr(md5($bbcode_uid),0,8) . "\" target=\"_blank\" onClick=\"popupWin = window.open(this.href, '" . $lang['Reputation'] . "', 'location,width=700,height=400,top=0,scrollbars=yes'); popupWin.focus(); return false;\"><img src=\"images/reputation_add_plus.gif\" alt=\"\" border=\"0\"><img src=\"images/reputation_add_minus.gif\" alt=\"\" border=\"0\"></a>";
			$sql = "SELECT COUNT(user_id) AS count_reps
					FROM " . REPUTATION_TABLE . " AS r
					WHERE r.user_id = " . $postrow[$i]['user_id'] . "
					GROUP BY user_id";
			if ( !($result = $db->sql_query($sql)) )
			{
				message_die(GENERAL_ERROR, "Could not obtain reputation stats for this user", '', __LINE__, __FILE__, $sql);
			}
			$row_rep = $db->sql_fetchrow($result);
			if ($row_rep)
			{
				$reputation .= "<br /><a href=\""  . append_sid("reputation.$phpEx?a=stats&" . POST_USERS_URL . "=" . $postrow[$i]['user_id']) . "\" target=\"_blank\" onClick=\"popupWin = window.open(this.href, '" . $lang['Reputation'] . "', 'location,width=700,height=400,top=0,scrollbars=yes'); popupWin.focus(); return false;\">" . $lang['Votes'] . "</a>: " . $row_rep['count_reps'];
			}
		}
	}
	// END ADD Reputation Mod v.1.0.0

	// Medal MOD
	$medal ='';
	$sql = "SELECT m.medal_id, m.medal_name
		FROM " . MEDAL_TABLE . " m, " . MEDAL_USER_TABLE . " mu
		WHERE mu.user_id = '" . $postrow[$i]['user_id'] . "'
		AND m.medal_id = mu.medal_id
		ORDER BY m.medal_name";
	
	if(!$result = $db->sql_query($sql))
		message_die(GENERAL_ERROR, "Error getting medal information", "", __LINE__, __FILE__, $sql);
		
	$medal_list = $db->sql_fetchrowset($result);
	$medal_count = count($medal_list);

	if ( $postrow[$i]['user_id'] == ANONYMOUS )
	{
		$medal_count = '';
	} 
	else
	{
		$medal_count = ($medal_count) ? $lang['Medals'] . ': <a href="' . append_sid("profile.$phpEx?mode=viewprofile&amp;" . POST_USERS_URL . "=" . $postrow[$i]['user_id'] . "#medal") . '" class="gensmall">' . $medal_count . '</a>' . ' (<a href="' . append_sid("profile.$phpEx?mode=viewprofile&amp;" . POST_USERS_URL . "=" . $postrow[$i]['user_id'] . "#medal") . '" class="gensmall">' . $lang['View_More'] . '</a>)' : $lang['Medals'] . ': ' . $lang['None'];
	}

	$post_raw_subject = $post_subject;
	$post_subject = get_icon_title($postrow[$i]['post_icon']) . '&nbsp;' . $post_subject;

	// WORD COUNT START by NoahK
		$sql = "SELECT user_wordcount FROM " . USERS_TABLE . " WHERE user_id='$poster_id'";
		$result = $db->sql_query($sql);
		$words = $db->sql_fetchrow($result);
		$wordcount = $words['user_wordcount'];
	// Format the result in a human readable number
		$rest3 = number_format($wordcount);
	// The code below is not utilized in this mod for viewtopic, however the .TPL could easily be changed to include the word average by using WORD_AVG.
	// Check for division by 0, if a user has no posts you can safely change the lang[word_na] to '0' or any other text in the language file
	// The 2 at the end of the next line controls the number of decimal places shown at the end of the number. Change that to 0 if you want to use whole numbers.
		$avg_words = ($wordcount == 0) ? $lang['Word_NA'] : round(($wordcount / $postrow[$i]['user_posts']),2);
	// WORD COUNT END by NoahK

	//
	// Again this will be handled by the templating
	// code at some point
	//
	$row_color = ( !($i % 2) ) ? $theme['td_color1'] : $theme['td_color2'];
	$row_class = ( !($i % 2) ) ? $theme['td_class1'] : $theme['td_class2'];

	$is_firstpost = ($postrow[$i]['post_id'] == $forum_topic_data['topic_first_post_id']) ? 1 : 0;
	if ($can_edit = ($is_auth['auth_mod'] || (($postrow[$i]['user_id'] == $userdata['user_id'] && ($forum_topic_data['topic_status'] != TOPIC_LOCKED)) && $is_auth['auth_edit'])))
	{
		$raw_message = $postrow[$i]['post_text'];
		if (!empty($postrow[$i]['bbcode_uid']))
		{
			$raw_message = preg_replace('/\:(([a-z0-9]:)*)' . $postrow[$i]['bbcode_uid'] . '/s', '', $raw_message);
		}
	
		include_once($phpbb_root_path . 'includes/functions_post.'.$phpEx);
		$raw_message = unprepare_message($raw_message);
		$raw_message = str_replace('<br />', "\n", $raw_message);
	}

	// Start Smilies Invasion Mod
  if ( $board_config['allow_smilies'] )
  {
    $post_subject = smilies_pass($post_subject);
  }
  // End Smilies Invasion Mod
	$post_id = $postrow[$i]['post_id'];
	$post_edit_string = ($userdata['user_level'] <= 0 || $userdata['user_id'] == ANONYMOUS) ? '' : '<a href="javascript:void(0);" onclick="javascript:post_time_edit('.$topic_id.', '.$post_id.')" class="postdetails">'.$lang['Edit_post_time'].'</a>';
//-- mod : IP Country Flag II ----------------------------------------------
  if ($postrow[$i]['user_id'] != ANONYMOUS)
  {
	  $local_time_end = $lang['Local_Time'] . create_date('Y M d - g:i A', time(), $postrow[$i]['user_timezone']);
  }
  else
  {
   	  $local_time_end = '';
  }
//-- end mod : IP Country Flag II ------------------------------------------
	$template->assign_block_vars('postrow', array(
		'DOWNLOAD_POST' => append_sid("viewtopic.$phpEx?download=".$postrow[$i]['post_id']."&amp;".POST_TOPIC_URL."=".$topic_id),
		'ROW_COLOR' => '#' . $row_color,
		'ROW_CLASS' => $row_class,
		'POSTER_DETAILS' => '<b>' . $lang['Poster_details'] . '</b>',
//-- mod : rank color system ---------------------------------------------------
//-- delete
/*-MOD
		'POSTER_NAME' => $poster,
MOD-*/
		'POSTER_NAME' => ($poster_id == ANONYMOUS) ? (($postrow[$i]['post_username'] != '') ? $postrow[$i]['post_username'] : $lang['Guest']) : $rcs->get_colors($postrow[$i], $postrow[$i]['username']),
//-- fin mod : rank color system -----------------------------------------------
		'CHINESE' => $lang[$chinese],
		'CHINESE_IMG' => $chinese_img,
		'U_CHINESE' => $u_chinese,
		'L_CHINESE' => ($chinese) ? $lang['Chinese_zodiac'] . ': ' : '',
		'ZODIAC_IMG' => $zodiac_img,
		'ZODIAC' => $zodiac,
		'U_ZODIAC' => $u_zodiac,
		'L_ZODIAC' => ($zodiac) ? $lang['Zodiac'] . ': ' : '',
		'WORD_COUNT' => $rest3,
		'WORD_AVG' => $avg_words,
		'TOTAL_WORDS_TEXT' => $lang['Total_Words'],
		'ZODIAC_IMG' => $zodiac_img,
		'ZODIAC' => $zodiac,
		'U_ZODIAC' => $u_zodiac,
		'L_ZODIAC' => ($zodiac) ? $lang['Zodiac'] . ': ' : '',

//-- mod : browsers list -------------------------------------------------------
//-- add
		'POSTER_BROWSER' => $poster_browser,
//-- fin mod : browsers list ---------------------------------------------------
		'POSTER_RANK' => $poster_rank,

		'POSTER_SHOUTS' => $poster_shouts,

// Start add - Gender MOD
'POSTER_GENDER' => $gender_image,
// End add - Gender MOD

		'RANK_IMAGE' => $rank_image,
		'POSTER_JOINED' => $poster_joined,
		'POSTER_AGE' => ( $age !== false ) ? sprintf($lang['Age'], $age) : '',
		'POSTER_POSTS' => $poster_posts,
// Topics a user has started MOD, By Manipe (Begin)
		'POSTER_TOPICS' => $poster_topics,
// Topics a user has started MOD, By Manipe (End)
		'POSTER_FROM' => $poster_from . $poster_from_flag,
	// START ADD Reputation Mod v.1.0.0
		'REPUTATION_ADD' => $reputation_add,
		'REPUTATION' => $reputation,
	// END ADD Reputation Mod v.1.0.0

		'POSTER_AVATAR' => $poster_avatar,
#======================================================================= |
#==== Start: == Activity Mod Plus ====================================== |
#==== v1.1.0 =========================================================== |
#====
		'POSTER_TROPHY' => Amod_Build_Topics($hof_data, $postrow[$i]['user_id'], $postrow[$i]['user_trophies'], $postrow[$i]['username'], $postrow[$i]['ina_char_name']),
#====
#==== Author: aUsTiN [austin@phpbb-amod.com] [http://phpbb-amod.com] === |
#==== End: ==== Activity Mod Plus ====================================== |	
#======================================================================= |
		'POSTER_MEDAL_COUNT' => $medal_count,	// Medal MOD
		// Start add - Online/Offline/Hidden Mod
		'POSTER_ONLINE_STATUS_IMG' => $online_status_img,
		'POSTER_ONLINE_STATUS' => $online_status,
		// End add - Online/Offline/Hidden Mod
		'POST_DATE' => $post_date,
		'POST_EDIT_STRING' => $post_edit_string,
		'POST_SUBJECT' => (empty($post_subject)) ? $lang['No_subject'] : $post_subject,
		'POST_RAW_SUBJECT' => $post_ajax_raw_subject,
// mod txt2binary changed line a bit
		'MESSAGE' => ( !$userdata['user_binary'] ) ? $message : txt2bin( $message ),
		'SCRIBBLE_IMAGE' => $scribble_image,
		'SIGNATURE' => $user_sig,
		'EDITED_MESSAGE' => $l_edited_by,
//-- mod : IP Country Flag II ----------------------------------------------
		'FLAG' => $flag,
		'USER_FLAG' => $user_flag,
		'COUNTRY' => $country,
		'USER_COUNTRY' => $user_country,
		'L_COUNTRY' => $lang['IP2Country'][$postrow[$i]['user_cf_iso3661_1']],
		'LOCAL_TIME' => $local_time_end,
//-- end mod : IP Country Flag II ------------------------------------------
		'VB_MENU_PROFILE' => $vb_menu_profile,
		'VB_MENU_EMAIL' => $vb_menu_email,
		'VB_MENU_PM' => $vb_menu_pm,
		'VB_MENU_WWW' => $vb_menu_www,
		'VB_MENU_SEARCH' => $vb_menu_search,
		//'VB_MENU_ALBUM' => $vb_menu_album,
		'VB_MENU_ID' => $vb_menu_id,
		'VB_MENU_L_PROFILE' => $vb_menu_l_profile,
		'VB_MENU_L_EMAIL' => $vb_menu_l_email,
		'VB_MENU_L_PM' => $vb_menu_l_pm,
		'VB_MENU_L_WWW1' => $vb_menu_l_www1,
		'VB_MENU_L_WWW2' => $vb_menu_l_www2,
		'VB_MENU_L_SEARCH' => $vb_menu_l_search,
		//'VB_MENU_L_ALBUM' => $vb_menu_l_album,
		'POSTER_AGE' => $lang_bd . $age,
//-- mod : topics enhanced -----------------------------------------------------
//-- add
//-- topics nav buttons		
		'S_NUM_ROW' => $num_row,
		'S_NAV_BUTTONS' => $nav_buttons,
//-- minitime
		'I_MINITIME' => $images['icon_minitime'],
//-- fin mod : topics enhanced -------------------------------------------------

		'MINI_POST_IMG' => $mini_post_img,
		'PROFILE_IMG' => $profile_img,
		'PROFILE' => $profile,
        'REFER_IMG' => $refer_img, // Referral Plus
		'SEARCH_IMG' => $search_img,
		'SEARCH' => $search,
		'PM_IMG' => $pm_img,
		'PM' => $pm,
		'EMAIL_IMG' => $email_img,
		'EMAIL' => $email,
		'WWW_IMG' => $www_img,
		'WWW' => $www,
		'ICQ_STATUS_IMG' => $icq_status_img,
		'ICQ_IMG' => $icq_img,
		'ICQ' => $icq,
		'AIM_IMG' => $aim_img,
		'AIM' => $aim,
		'MSN_IMG' => $msn_img,
		'MSN' => $msn,
		'MYSPACE_IMG' => $myspace_img, 
		'MYSPACE' => $myspace,
		'IM_IMG' => $im_img,
		'IM' => $im,
		'YIM_IMG' => $yim_img,
		'YIM' => $yim,
		'WEBLOG_IMG' => $weblog_img,
		'WEBLOG' => $weblog,
		'EDIT_IMG' => $edit_img,
		'EDIT' => $edit,
		'QUOTE_IMG' => $quote_img,
		'QUOTE' => $quote,
		'CLONE_IMG' => $clone_img,
		'IP_IMG' => $ip_img,
		'IP' => $ip,
		'DELETE_IMG' => $delpost_img,
		'DELETE' => $delpost,
// Phoogle Map
		'PHOOGLE_IMG' => $phoogle_img,
		'PHOOGLE' => $phoogle,
// End Phoogle Map
		// Cache Posts
		'CPS_STATUS' => $parse_status,
		'CPS_IMG' => ($is_auth['auth_mod'] && $board_config['allow_cache_moderate'] || $userdata['user_level'] == ADMIN) ? $cps_img : '',
		// Cache Posts
		'RAW_MESSAGE' => ($can_edit) ? $raw_message : '',

// mod topic mod add
'TBAN_IMG' => $tban_img,
'TBAN' => $tban,
// mod topic mod end


// Start add - Gender MOD
'L_GENDER' => $lang['Gender'],
// End add - Gender MOD


		'L_MINI_POST_ALT' => $mini_post_alt,

		'S_FIRST_POST' => $is_firstpost,
		'S_AJAX_EDIT_TITLE' => ($can_edit) ? 'ondblclick="AJAXTitleEdit('. $postrow[$i]['post_id'] .', '. $is_firstpost .');"' : '',
		
		'U_EDIT_POST' => $edit_url,
		'U_MINI_POST' => $mini_post_url,
		'U_POST_ID' => $postrow[$i]['post_id'])
	);
//-- mod : calendar ------------------------------------------------------------
//-- add
	if ( $postrow[$i]['post_id'] == $forum_topic_data['topic_first_post_id'] )
	{
		$calendar_front_title->topic_title('postrow', intval($forum_topic_data['topic_calendar_time']), intval($forum_topic_data['topic_calendar_duration']));
	}
//-- fin mod : calendar --------------------------------------------------------
	//
  // Custom Profile Fields MOD
  //
  include_once($phpbb_root_path . 'includes/functions_profile_fields.'.$phpEx);
  $profile_data = get_fields('WHERE view_in_topic = ' . VIEW_IN_TOPIC . ' AND users_can_view = ' . ALLOW_VIEW);
  $profile_names = array();
  
  $aboves = array();
  $belows = array();
  $author = array();
  foreach($profile_data as $field)
  {
    $name = $field['field_name'];
    $col_name = text_to_column($field['field_name']);
    $id = $poster_id;
    $type = $field['field_type'];
    $location = $field['topic_location'];
    
    $sql2 = "SELECT $col_name FROM " . USERS_TABLE . "
      WHERE user_id = $id";
    if(!($result2 = $db->sql_query($sql2)))
      message_die(GENERAL_ERROR,'Could not obtain field value','',__LINE__,__FILE__,$sql2);
    
    $temp = $db->sql_fetchrow($result2);
    $profile_names[$name] = displayable_field_data($temp[$col_name],$field['field_type'],$field['linkify']);
    
    if (($profile_names[$name] != '') || (!$board_config['collapse_fields'])) {
    if($location == AUTHOR)
      $author[] = $name . ': ' . $profile_names[$name];
    elseif($location == ABOVE_SIGNATURE)
      $aboves[] = $name . ': ' . $profile_names[$name];
  	else
  	  $belows[] = $name . ': ' . $profile_names[$name];
  	  }
  }
  
  foreach($aboves as $above_val)
    $template->assign_block_vars('postrow.above_sig',array('ABOVE_VAL' => $above_val));
  foreach($belows as $below_val)
    $template->assign_block_vars('postrow.below_sig',array('BELOW_VAL' => $below_val));
  foreach($author as $author_val)
    $template->assign_block_vars('postrow.author_profile',array('AUTHOR_VAL' => $author_val));
  //
  // END Custom Profile Fields MOD
  //

//-- mod : topics enhanced -----------------------------------------------------
//-- add
//-- split posts
	if ( $i != $total_posts - 1 )
	{
		$template->assign_block_vars('postrow.spacing', array());
	}
//-- fin mod : topics enhanced -------------------------------------------------

	$cm_viewtopic->post_vars($postrow[$i],$userdata,$forum_id
	);
	//Medal MOD
	if ( $board_config['allow_medal_display'] )
	{
		$order = ( $board_config['medal_display_order'] ) ? "RAND()" : "m.medal_name";

		$template->assign_block_vars('postrow.medal', array());

		$sql = "SELECT m.medal_id, m.medal_name, m.medal_image
			FROM " . MEDAL_TABLE . " m, " . MEDAL_USER_TABLE . " mu
			WHERE mu.user_id = '" . $poster_id . "'
			AND m.medal_id = mu.medal_id
			ORDER BY " . $order;
	
		if ($result = $db->sql_query($sql))
		{
			$rowset = array();
			while ($row = $db->sql_fetchrow($result))
			{
				$rowset[$row['medal_image']]['medal_name'] = $row['medal_name'];
				if ($rowset[$row['medal_image']]['medal_name'] == $row['medal_name'])
				$rowset[$row['medal_image']]['medal_count'] += 1;
			}

			// Check Medal config in ACP
			$medal_rows = $board_config['medal_display_row'];
			$medal_cols = $board_config['medal_display_col'];
			$medal_width = ( $board_config['medal_display_width'] ) ? 'width="'.$board_config['medal_display_width'].'"' : '';
			$medal_height = ( $board_config['medal_display_height'] ) ? 'height="'.$board_config['medal_display_height'].'"' : '';
	
			if ($medal_list)
			{
				$split_row = $medal_cols - 1;

				$s_colspan = 0;
				$row = 0;
				$col = 0;

				while (list($medal_image, $medal) = @each($rowset))
				{
					if (!$col)
			       		{ 
						$template->assign_block_vars('postrow.medal.medal_row', array()); 
					}

					$template->assign_block_vars('postrow.medal.medal_row.medal_col', array(
						'MEDAL_IMAGE' => $phpbb_root_path . $medal_image,
						'MEDAL_WIDTH' => $medal_width,
						'MEDAL_HEIGHT' => $medal_height,
						'MEDAL_NAME' => $medal['medal_name'],
						'MEDAL_COUNT' => '('. $lang['Medal_amount'] . $medal['medal_count']. ')')
					);

					$s_colspan = max($s_colspan, $col + 1);

					if ($col == $split_row)
					{
						if ($row == $medal_rows - 1) 
						{ 
							break; 
						}
						$col = 0;
						$row++;
					}
					else 
					{ 
						$col++; 
					}
				}
			}
		}
	}
	display_post_attachments($postrow[$i]['post_id'], $postrow[$i]['post_attachment']);

	if ($can_edit)
	{
		$template->assign_block_vars('postrow.can_edit', array());
	}

	// Edit-Reason
	$edit_reason_include = 5;
	include($phpbb_root_path . 'includes/edit_reason.'.$phpEx);

}

ratings_view_topic();
$template->pparse('body');

include($phpbb_root_path . 'includes/page_tail.'.$phpEx);

?>