<?php
/***************************************************************************
 *                            topics_anywhere.php
 *                            -------------------
 *   begin                : Wednesday, Aug 28, 2002
 *   copyright            : (C) 2001 The phpBB Group
 *   email                : support@phpbb.com
 *
 *   $Id: topics_anywhere.php,v 1.9 2005/01/04 15:04:12 saraj 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.
 *
 ***************************************************************************/

//
// Config Section
//

// Who may view the Topics Anywhere setup page and generate scripts to copy and paste?
// Everybody: 0
// Administrators only: 1
// Moderators only: 2
// Administrators and moderators: 3
// All registered users: 4
$topics_anywhere_authlevel = 0;

// By default, only public forums are shown in the picklist. If you want, you can let
// Topics Anywhere show all forums in the picklist (this is including private and hidden forums).
// To do this, change 'true' to 'false' below.
// You can still exclude specific forums from the picklist by changing next config option.
$public_only = true;

// Don't show following forums in the picklist on the setup page.
// This is an array of numbers which are the forum ID's.
// For example use "$hide_forums = array(1, 5, 10);" to hide forums with ID 1, 5 and 10
// Leave the array empty (as below) to show all the forums.
// Note: it is never possible to let Topics Anywhere show topics from excluded forums,
// not even by modifying the URL generated by Topics Anywhere.
$hide_forums = array();

// You can change the format of date and time here...
// For American type dates you probably want to use the other array below
// You can also make your own formats, as long as you use the syntax of PHP's function date()
// Of course, do not add or remove any quotes! (unless escaped)
$date_formats = array('d/m/y', 'd/m/Y', 'd/m/Y H:i:s', 'D d-M-y', 'D d-M-Y', 'D d-M-Y H:i:s', 'l j F Y', 'l j F Y H:i:s');

// Some American style date formats - to enable them uncomment following line by removing the '// '
// $date_formats = array('m/d/y', 'm/d/Y', 'm/d/Y g:i:s A', 'D M d, y', 'D M d, Y', 'D M d, Y g:i:s A', 'l, F jS, Y', 'l, F jS, Y g:i:s A');

// Array of possible bullets
// You can add your own bullets if you want.
// Do not add or remove any quotes! (unless escaped)
$bullets = array('-', '+', '&gt;', '&#155;', '&#187;', '°', '*');

//
// End of Config Section - nothing needs to be modified below...
//

define('IN_PHPBB', true);

$phpbb_root_path = './';

include($phpbb_root_path . 'extension.inc');
include($phpbb_root_path . 'common.'.$phpEx);

include($phpbb_root_path . 'language/lang_' . $board_config['default_lang'] . '/lang_main.' . $phpEx);
include($phpbb_root_path . 'language/lang_' . $board_config['default_lang'] . '/lang_topics_anywhere.' . $phpEx);

$server_protocol = ($board_config['cookie_secure']) ? 'https://' : 'http://';
$server_name = preg_replace('#^\/?(.*?)\/?$#', '\1', trim($board_config['server_name']));
$server_port = ($board_config['server_port'] <> 80) ? ':' . trim($board_config['server_port']) : '';
$script_location = preg_replace('#^\/?(.*?)\/?$#', '\1', trim($board_config['script_path']));
$script_location = ($script_location == '') ? $script_location : '/' . $script_location;

$full_url = $server_protocol . $server_name . $server_port . $script_location;

//
// Start session management
//
$userdata = session_pagestart($user_ip, PAGE_INDEX);
init_userprefs($userdata);
//
// End session management
//

$lang['Topics_anywhere'] = 'Topics Anywhere';

define('TA_SCRIPT_NAME', 'topics_anywhere');
define('TA_VERSION', '1.11.0');

$lastpostby_formats = array($lang['Username'], $lang['Lastpost_from'] . ' ' . $lang['Username']);

// General functions
function output_die($msg)
{
	global $out, $phpEx, $full_url, $version;

	$error = true;

	if ($out == 'js')
	{
		if (is_array($msg))
		{
			$output = implode('<br>', $msg);
		}
		else
		{
			$output = $msg;
		}

		$output = '<b>' . $output . '<br>' . sprintf($lang['Error'], TA_SCRIPT_NAME . $phpEx) . '</b><br><br>TA_VERSION ' . TA_VERSION;
		exit("document.writeln('$output');\n");
	}
	else if ($out == 'rss')
	{
		$output = generate_rss_header($version);

		$link = ($version == '0.91') ? substr($full_url, 0, 500) : $full_url;

		if (is_array($msg))
		{
			while ($error = array_shift($msg))
			{
				$output .= '<item>' . "\n";;
				$output .= '<title>' . $error . '</title>' . "\n";
				$output .= '<link>' . $link . '</link>' . "\n";
				$output .= '<description>' . sprintf($lang['Error'], TA_SCRIPT_NAME . $phpEx) . ' (TA_VERSION ' . TA_VERSION . ')</description>' . "\n";
				$output .= '</item>' . "\n";
			}
		}
		else
		{
			$output .= '<item>' . "\n";;
			$output .= '<title>' . $msg . '</title>' . "\n";
			$output .= '<link>' . $link . '</link>' . "\n";
			$output .= '<description>' . sprintf($lang['Error'], TA_SCRIPT_NAME . $phpEx) . ' (TA_VERSION ' . TA_VERSION . ')</description>' . "\n";
			$output .= '</item>' . "\n";
		}

		$output .= generate_rss_footer();

		header("Content-type: text/xml");
		exit($output);
	}
}

function forum_select() // generates select of all available forums (modified make_jumpbox()-function)
{
	global $template, $lang, $db, $SID, $nav_links, $phpEx, $hide_forums;

	$sql = "SELECT c.cat_id, c.cat_title, c.cat_order
		FROM " . CATEGORIES_TABLE . " c, " . FORUMS_TABLE . " f
		WHERE f.cat_id = c.cat_id
		GROUP BY c.cat_id, c.cat_title, c.cat_order
		ORDER BY c.cat_order";
	if ( !($result = $db->sql_query($sql)) )
	{
		message_die(GENERAL_ERROR, "Couldn't obtain category list.", "", __LINE__, __FILE__, $sql);
	}

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

	if ( $total_categories = count($category_rows) )
	{
		$sql = "SELECT *
			FROM " . FORUMS_TABLE . "
			ORDER BY cat_id, forum_order";
		if ( !($result = $db->sql_query($sql)) )
		{
			message_die(GENERAL_ERROR, 'Could not obtain forums information', '', __LINE__, __FILE__, $sql);
		}

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

		$boxstring = '<select multiple name="' . POST_FORUM_URL . '[]" size=6>';

		if ( $total_forums = count($forum_rows) )
		{
			for($i = 0; $i < $total_categories; $i++)
			{
				$boxstring_forums = '';
				for($j = 0; $j < $total_forums; $j++)
				{
					if ( $forum_rows[$j]['cat_id'] == $category_rows[$i]['cat_id'])
					{
						if (!in_array($forum_rows[$j]['forum_id'], $hide_forums))
						{
							$boxstring_forums .=  '<option value="' . $forum_rows[$j]['forum_id'] . '">' . $forum_rows[$j]['forum_name'] . '</option>';
						}
					}
				}

				if ( $boxstring_forums != '')
				{
					if ($i != 0)
					{
						$boxstring .= '<option value="-1">&nbsp;</option>';
					}
					$boxstring .= '<option value="cat' . $category_rows[$i]['cat_id'] . '">' . $category_rows[$i]['cat_title'] . '</option>';
					$boxstring .= '<option value="-1">----------------</option>';
					$boxstring .= $boxstring_forums;
				}
			}
		}

		$boxstring .= '</select>';
	}
	else
	{
		$boxstring .= '<select multiple name="' . POST_FORUM_URL . '[]" size=1></select>';
	}
	$data = array($boxstring, $total_forums);
	return $data;
}

function bullet_select($bullets) // generates select of all available bullets from array $bullets
{
	global $lang;
	$select = '<select name="bullet_type">';
	$select .= '<option value="non">' . $lang['None'] . '</option>';
	$select .= '<option value="dis">HTML ' . $lang['disc'] . '</option>';
	$select .= '<option value="cir">HTML ' . $lang['circle'] . '</option>';
	$select .= '<option value="squ">HTML ' . $lang['square'] . '</option>';
	$select .= '<option value="num">HTML ' . $lang['numbered'] . '</option>';
	for ($i = 0; $i < count($bullets); $i++)
	{
		$select .= '<option value="' . $i . '">' . $bullets[$i] . '</option>';
	}
	$select .= '</select>';
	return $select;
}

function lastpostby_select($lastpostby_formats) // generates select of "last post by" text formats
{
	global $lang;
	$select = '<select name="lastpostby_format">';
	for ($i = 0; $i < count($lastpostby_formats); $i++)
	{
		$select .= '<option value="' . $i . '">' . $lastpostby_formats[$i] . '</option>';
	}
	$select .= '</select>';
	return $select;
}

function lastpostdate_select($date_formats) // generates select of date formats from array $dateformats
{
	global $lang;
	$now = time();
	$select = '<select name="lastpostdate_format">';
	for ($i = 0; $i < count($date_formats); $i++)
	{
		$select .= '<option value="' . $i . '">' . create_date($date_formats[$i], $now, $board_config['board_timezone']) . '</option>';
	}
	$select .= '</select>';
	return $select;
}

function output_select()
{
	$select = '<select name="out">';
	$select .= '<option value="js">JavaScript</option>';
	$select .= '<option value="rss0.91">RSS 0.91</option>';
	$select .= '<option value="rss2.0">RSS 2.0</option>';
	$select .= '</select>';
	return $select;
}

function show_the_page()
{
	global $template, $lang, $db, $SID, $nav_links, $phpEx, $phpbb_root_path, $theme, $images, $date_formats, $lastpostby_formats, $bullets, $board_config, $full_url;

	$page_title = $lang['Topics_anywhere'];

	include($phpbb_root_path . 'language/lang_' . $board_config['default_lang'] . '/lang_admin.' . $phpEx);

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

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

	$outputarray = forum_select();

	if ($board_config['allow_html'])
	{
		$html_allowed_append = ' (' . strip_tags($lang['HTML_is_ON']) . ' - ' . $lang['Allowed_tags'] . ': &lt;' . str_replace(',', '&gt;, &lt;', $board_config['allow_html_tags']) . '&gt;)';
	}
	else
	{
		$html_allowed_append = ' (' . strip_tags($lang['HTML_is_OFF']) . ')';
	}

	$template->assign_vars(array(
		'L_TOPICS_ANYWHERE' => $lang['Topics_anywhere'] . ' ' . TA_VERSION,
		'L_TOPICS_ANYWHERE_EXPLAIN' => $lang['Topics_anywhere_explain'] . ' ' . $lang['Topics_anywhere_explain_more'],
		'L_OUTPUT' => $lang['Output'],
		'L_OUTPUT_EXPLAIN' => $lang['Output_explain'],
		'OUTPUT_SELECT' => output_select($languages, $langs),
		'L_SELECT_FORUM' => $lang['Forum_select'] . $lang['Category_select'],
		'L_SELECT_FORUM_EXPLAIN' => $lang['Select_forum_explain'] . $lang['Category_explain'],
		'SELECT_FORUM_SELECT' => $outputarray[0],
		'L_OR' => $lang['Or'],
		'L_CHECK_ALLFORA' => $lang['All_available'],
		'L_AMOUNT_TOPICS' => $lang['Amount_topics'],
		'L_AMOUNT_TOPICS_EXPLAIN' => $lang['Amount_topics_explain'],
		'L_TOPICS_LIFESPAN' => $lang['Topics_lifespan'],
		'L_TOPICS_LIFESPAN_EXPLAIN' => $lang['Topics_lifespan_explain'],
		'L_TOPICS_LIFESPAN_NOREPLY' => $lang['Topics_lifespan_noreply'],
		'L_TOPICS_LIFESPAN_STARTDATE' => $lang['Topics_lifespan_startdate'],
		'L_HOURS' => strtolower($lang['Hours']),
		'L_DAYS' => strtolower($lang['Days']),
		'L_JUMP_LAST_POST' => $lang['Url_last_post'],
		'L_JUMP_LAST_POST_EXPLAIN' => $lang['Url_last_post_explain'],
		'L_SHOW_FORUM_NAME' => $lang['Show_forum_name'],
		'L_SHOW_FORUM_NAME_EXPLAIN' => $lang['Show_forum_name_explain'],
		'L_LINK_FORUM_NAME' => $lang['Link_forum_name'],
		'L_LINK_FORUM_NAME_EXPLAIN' => $lang['Link_forum_name_explain'] . ' (*)',
		'L_SHOW_REPLIES' => $lang['Show_replies'],
		'L_SHOW_REPLIES_EXPLAIN' => $lang['Show_replies_explain'],
		'L_SHOW_REPLIES_WORD' => $lang['Show_replies_word'],
		'L_SHOW_REPLIES_WORD_EXPLAIN' => $lang['Show_replies_word_explain'],
		'L_SHOW_ANNOUNCEMENTS' => $lang['Show_announce'],
		'L_SHOW_STICKYS' => $lang['Show_sticky'],
		'L_SHOW_LOCKED' => $lang['Show_locked'],
		'L_SHOW_MOVED' => $lang['Show_moved'],
		'L_SHOW_REGULAR' => $lang['Show_regular'],
		'L_HIDE_LABELS' => $lang['Hide_labels'],
		'L_HIDE_LABELS_EXPLAIN' => $lang['Hide_labels_explain'],
		'O_ANNOUNCEMENT' => strip_tags($lang['Topic_Announcement']),
		'O_STICKY' => strip_tags($lang['Topic_Sticky']),
		'O_MOVED' => strip_tags($lang['Topic_Moved']),
		'O_POLL' => strip_tags($lang['Topic_Poll']),
		'O_LOCKED' => strip_tags($lang['Topic_Locked']),
		'L_SORT_ORDER' => $lang['Sort_order'],
		'L_SORT_ORDER_EXPLAIN' => $lang['Sort_order_explain'],
		'O_PRIORITY' => $lang['Priority'],
		'O_ON_DATE' => $lang['On_date'],
		'L_BULLET_TYPE' => $lang['Bullet_type'],
		'L_BULLET_TYPE_EXPLAIN' => $lang['Bullet_type_explain'] . ' (*)',
		'BULLET_TYPE_SELECT' => bullet_select($bullets),
		'L_SHOW_LASTPOSTBY' => $lang['Show_lastpostby'],
		'L_SHOW_LASTPOSTBY_EXPLAIN' => $lang['Show_lastpostby_explain'],
		'L_LASTPOSTBY_FORMAT' => $lang['Lastpostby_format'],
		'L_LASTPOSTBY_FORMAT_EXPLAIN' => $lang['Lastpostby_format_explain'],
		'LASTPOSTBY_FORMAT_SELECT' => lastpostby_select($lastpostby_formats),
		'L_SHOW_LASTPOSTDATE' => $lang['Show_lastpostdate'],
		'L_SHOW_LASTPOSTDATE_EXPLAIN' => $lang['Show_lastpostdate_explain'],
		'L_LASTPOSTDATE_FORMAT' => $lang['Lastpostdate_format'],
		'L_LASTPOSTDATE_FORMAT_EXPLAIN' => $lang['Lastpostdate_format_explain'],
		'LASTPOSTDATE_FORMAT_SELECT' => lastpostdate_select($date_formats),
		'L_SHOW_LASTPOSTICON' => $lang['Show_lastposticon'],
		'L_SHOW_LASTPOSTICON_EXPLAIN' => $lang['Show_lastposticon_explain'] . ' (*)',
		'L_LASTPOSTICON_AS_BULLET' => $lang['Lastposticon_as_bullet'],
		'L_LASTPOSTICON_AS_BULLET_EXPLAIN' => $lang['Lastposticon_as_bullet_explain'] . ' (*)',
		'L_ADD_BREAK' => $lang['Add_break'],
		'L_ADD_BREAK_EXPLAIN' => $lang['Add_break_explain'] . ' (*)',
		'L_ADD_BLANK_LINE' => $lang['Add_blank_line'],
		'L_ADD_BLANK_LINE_EXPLAIN' => $lang['Add_blank_line_explain'] . ' (*)',
		'L_LIMIT_LENGTH' => $lang['Limit_title_length'],
		'L_LIMIT_LENGTH_EXPLAIN' => $lang['Limit_title_length_explain'],
		'L_LIMIT_WHERE' => $lang['Limit_title_where'],
		'L_LIMIT_WHERE_EXPLAIN' => $lang['Limit_title_where_explain'],
		'L_PREVIOUS_SPACE' => $lang['Limit_title_previous_space'],
		'L_EXACT' => $lang['Limit_title_exact'],
		'L_NEXT_SPACE' => $lang['Limit_title_next_space'],
		'L_CSS_LINK' => $lang['CSS_link'],
		'L_CSS_LINK_EXPLAIN' => $lang['CSS_link_explain'] . ' (*)',
		'L_CSS_TEXT' => $lang['CSS_text'],
		'L_CSS_TEXT_EXPLAIN' => $lang['CSS_text_explain'] . ' (*)',
		'L_TARGET_LINK' => $lang['Target_link'],
		'L_TARGET_LINK_EXPLAIN' => $lang['Target_link_explain'] . ' (*)',
		'L_ADV_FORM' => $lang['Advanced_formatter'],
		'L_ADV_FORM_EXPLAIN' => $lang['Advanced_formatter_explain'],
		'L_ADV_FORM_STRING' => $lang['Advanced_formatter_string'],
		'L_ADV_FORM_STRING_EXPLAIN' => $lang['Advanced_formatter_string_explain'],
		'L_ADV_FORM_DEFAULT' => '§lbl§ §tt§ §fn§ §rep§ - §lpa§, §lpt§ §lpi§',
		'L_ADV_FORM_VARS' => $lang['Advanced_formatter_variables'] . '<br /><br />' . $lang['Advanced_formatter_variables_extra'] . $html_allowed_append,
		'L_YES' => $lang['Yes'],
		'L_NO' => $lang['No'],
		'L_SUBMIT' => $lang['Submit'],
		'L_RESET' => $lang['Reset'],
		'H_TOTAL_FORUMS' => $outputarray[1],
		'S_FORM_ACTION' => append_sid(TA_SCRIPT_NAME . ".$phpEx?mode=generate"))
	);

	$template->pparse('body');

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

function generate_rss_header($version)
{
	global $db, $lang, $board_config, $full_url;

	$sql = "SELECT template_name
		FROM " . THEMES_TABLE . "
		WHERE themes_id = " . $board_config['default_style'];
	if ( !($result = $db->sql_query($sql)) )
	{
		message_die(CRITICAL_ERROR, 'Could not query database for theme info');
	}

	if ( !($row = $db->sql_fetchrow($result)) )
	{
		message_die(CRITICAL_ERROR, "Could not get theme data for themes_id [$style]");
	}

	$dir = $row['template_name'];

	$langs = array('albanian', 'arabic', 'bulgarian', 'catalan', 'chinese_simplified', 'chinese_traditional', 'croatian', 'czech', 'danish', 'dutch', 'english', 'finnish', 'french', 'galego', 'german', 'german_sie', 'greek', 'hebrew', 'hungarian', 'icelandic', 'indonesian', 'italian', 'japanese', 'korean', 'kurdish', 'lithuanian', 'macedonian', 'norwegian', 'polish', 'portuguese', 'portuguese_brazil', 'romanian', 'romanian_no_diacritics', 'russian', 'russian_tu', 'serbian', 'slovak', 'slovenian', 'spanish', 'spanish_argentina', 'swedish', 'thai', 'turkish', 'ukrainian', 'welsh');
	$codes = array('SQ', 'AR', 'BG', 'CA', 'ZH-CN', 'ZH-TW', 'HR', 'CS', 'DA', 'NL', 'EN', 'FI', 'FR', 'GL', 'DE', 'DE', 'EL', 'HE', 'HU', 'IS', 'ID', 'IT', 'JA', 'KO', 'KU', 'LT', 'MK', 'NO', 'PL', 'PT', 'PT-BR', 'RO', 'RO', 'RU', 'RU', 'SR', 'SK', 'SL', 'ES', 'ES-AR', 'SV', 'TH', 'TR', 'UK', 'CY');

	if (($index = array_search($board_config['default_lang'], $langs)) !== FALSE) {
		$langcode = strtolower($codes[$index]);
	}
	else
	{
		$langcode = 'en';
	}

	unset($langs, $codes, $index);

	$title = ($version == '0.91') ? substr($board_config['sitename'], 0, 100) : $board_config['sitename'];
	$link = ($version == '0.91') ? substr($full_url, 0, 500) : $full_url;
	$description = ($version == '0.91') ? substr($board_config['site_desc'], 0, 500) : $board_config['site_desc'];
	$url = ($version == '0.91') ? substr(($full_url . '/templates/' . $dir . '/images/logo_phpBB.gif'), 0, 500) : ($full_url . '/templates/' . $dir . '/images/logo_phpBB.gif');
	$copy = ($version == '0.91') ? substr(('Copyright ' . date('Y', $board_config['board_startdate']) . '-' . date('Y') . ', ' . $board_config['sitename']), 0, 100) : ('Copyright ' . date('Y', $board_config['board_startdate']) . '-' . date('Y') . ', ' . $board_config['sitename']);
	$mail = ($version == '0.91') ? substr($board_config['board_email'], 0, 100) : $board_config['board_email'];
	$docs = ($version == '0.91') ? 'http://backend.userland.com/stories/rss091' : 'http://blogs.law.harvard.edu/tech/rss';
	$date = date('r');

	$output = '<?xml version="1.0" encoding="' . $lang['ENCODING'] . '" ?>' . "\n";
	$output .= '<rss version="' . $version . '">' . "\n";
	$output .= '<channel>' . "\n";
	$output .= '<title>' . $title . '</title>' . "\n";
	$output .= '<link>' . $link . '</link>' . "\n";
	$output .= '<description>' . $description . '</description>' . "\n";
	$output .= '<language>' . $langcode . '</language>' . "\n";
	$output .= '<managingEditor>' . $mail . '</managingEditor>' . "\n";
	$output .= '<webMaster>' . $mail . '</webMaster>' . "\n";
	$output .= '<pubDate>' . $date . '</pubDate>' . "\n";
	$output .= '<lastBuildDate>' . $date . '</lastBuildDate>' . "\n";
	$output .= '<copyright>' . $copy . '</copyright>' . "\n";

	if ($version == '2.0')
	{
		$output .= '<generator>' . $lang['Topics_anywhere'] . ' ' . TA_VERSION . '</generator>' . "\n";
	}

	$output .= '<docs>' . $docs . '</docs>' . "\n";

	$output .= '<image>' . "\n";
	$output .= '<url>' . $url . '</url>' . "\n";
	$output .= '<title>' . $title . '</title>' . "\n";
	$output .= '<link>' . $link . '</link>' . "\n";
	$output .= '</image>' . "\n";

	return $output;
}

function generate_rss_footer()
{
	$output = '</channel>' . "\n";
	$output .= '</rss>' . "\n";

	return $output;
}

if ($public_only) // adds all non-public forum id's to the $hide_forums array so they can't be used
{
	$sql = "SELECT * FROM " . USERS_TABLE . " WHERE user_id = " . ANONYMOUS;
	if (!($result = $db->sql_query($sql)))
	{
		message_die(CRITICAL_ERROR, 'Could not obtain user data from user table', '', __LINE__, __FILE__, $sql);
	}

	$userdata = $db->sql_fetchrow($result);

	$db->sql_freeresult($result);

	$auth_ary = auth(AUTH_READ, AUTH_LIST_ALL, $userdata);

	$public_forums = array();
	while (list($auth_forum_id, $auth_level) = each($auth_ary))
	{
		if ($auth_level['auth_read'])
		{
			array_push($public_forums, $auth_forum_id);
		}
	}

	$sql = "SELECT forum_id FROM " . FORUMS_TABLE . " ORDER BY forum_id";
	if (!($result = $db->sql_query($sql)))
	{
		message_die(GENERAL_ERROR, 'Could not obtain forums information', '', __LINE__, __FILE__, $sql);
	}

	$all_forums = array();
	while ($row = $db->sql_fetchrow($result))
	{
		array_push($all_forums, $row['forum_id']);
	}
	$db->sql_freeresult($result);

	for ($i = 0; $i < count($all_forums); $i++) {
		if (in_array($all_forums[$i], $public_forums)) {
			array_splice($all_forums, $i, 1);
			$i--;
		}
	}

	$hide_forums = array_merge($hide_forums, $all_forums);
	$hide_forums = array_unique($hide_forums);
}

if ($HTTP_GET_VARS['mode'] == "show") // generates topics for output on any page using JavaScript document.writeln (quite heavily modified code from viewtopic.php)
{
	// Output mode check
	$out = 'js';
	if (isset($HTTP_GET_VARS['out'])) {
		if ($HTTP_GET_VARS['out'] == 'rss0.91') {
			$out = 'rss';
			$version = '0.91';
		}
		else if ($HTTP_GET_VARS['out'] == 'rss2.0') {
			$out = 'rss';
			$version = '2.0';
		}
	}

	// Board is disabled, no topics are available
	if ($board_config['board_disable'])
	{
		if ($out == 'js')
		{
			$css_text_wrap_before = '';
			$css_text_wrap_after = '';
			if (isset($HTTP_GET_VARS['ct']))
			{
				if ($HTTP_GET_VARS['ct'] != '')
				{
					$css_text_wrap_before = '<span class=\"' . $HTTP_GET_VARS['ct'] . '\">';
					$css_text_wrap_after = '</span>';
				}
				else
				{
					$error = true;
					output_die('Error: No value for argument (css_text)');
				}
			}
			$msg = $css_text_wrap_before . $lang['Board_disable'] . $css_text_wrap_after;
			exit("document.writeln('$msg');\n");
		}
		else if ($out = 'rss')
		{
			$output = generate_rss_header($version);

			$title = ($version == '0.91') ? substr($lang['Board_disable'], 0, 100) : $lang['Board_disable'];
			$link = ($version == '0.91') ? substr($full_url, 0, 500) : $full_url;

			$output .= '<item>' . "\n";
			$output .= '<title>' . $title . '</title>' . "\n";
			$output .= '<link>' . $link . '</link>' . "\n";
			$output .= '</item>' . "\n";

			$output .= generate_rss_footer();

			header("Content-type: text/xml");
			exit($output);
		}
	}

	// Get most important vars out parameters
	$error = false;
	$errorarray = array();

	$adv_format = false;
	if (isset($HTTP_GET_VARS['af']) && $HTTP_GET_VARS['af'] != '')
	{
		$adv_format = true;
		$af_string = base64_decode(rawurldecode($HTTP_GET_VARS['af']));
	}

	if (!isset($HTTP_GET_VARS['f']) || $HTTP_GET_VARS['f'] == '')
	{
		$error = true;
		array_push($errorarray, 'Error: Missing argument (forum_id)');
	}
	else
	{
		if (is_numeric($HTTP_GET_VARS['f']))
		{
			if (sizeof($hide_forums))
			{
				if (in_array(intval($HTTP_GET_VARS['f']), $hide_forums))
				{
					$error = true;
					array_push($errorarray, 'Error: Not allowed to show topics from this forum');
				}
				else
				{
					$forum_id = intval($HTTP_GET_VARS['f']);
					$forum_sql = "AND t.forum_id = $forum_id";
				}
			}
			else
			{
				$forum_id = intval($HTTP_GET_VARS['f']);
				$forum_sql = "AND t.forum_id = $forum_id";
			}
		}
		else
		{
			if ($HTTP_GET_VARS['f'] == 'a')
			{
				if (sizeof($hide_forums))
				{
					$hidelist = '(' . implode(', ', $hide_forums) . ')';
					$forum_sql = 'AND t.forum_id NOT IN ' . $hidelist;
				}
				else
				{
					$forum_sql = '';
				}
			}
			else
			{
				if (substr($HTTP_GET_VARS['f'], 0, 1) == 'u')
				{
					$forumlist = base64_decode(rawurldecode(substr($HTTP_GET_VARS['f'], 1)));
					$forumlist = '(' . str_replace(',', ', ', $forumlist) . ')';
					$forum_sql = "AND t.forum_id in $forumlist";
				}
				else
				{
					if (substr($HTTP_GET_VARS['f'], 0, 1) == 'b')
					{
						$forumlist = base64_decode(substr($HTTP_GET_VARS['f'], 1));
						$forum_sql = "AND t.forum_id in $forumlist";
					}
					else
					{
						$error = true;
						array_push($errorarray, 'Error: Wrong argument (forum_id)');
					}
				}
			}
		}
	}

	if (!isset($HTTP_GET_VARS['n']) || $HTTP_GET_VARS['n'] == '')
	{
		$error = true;
		array_push($errorarray, 'Error: Missing argument (limit)');
	}
	else
	{
		if (is_numeric($HTTP_GET_VARS['n']))
		{
			$limit = intval($HTTP_GET_VARS['n']);
		}
		else
		{
			$error = true;
			array_push($errorarray, 'Error: Wrong argument (limit)');
		}
	}

	if (!$error) // there are no critical arguments missing - start with generating SQL, then execute it
	{
		$noreply_sql = '';
		if (isset($HTTP_GET_VARS['hnr']))
		{
			if (is_numeric($HTTP_GET_VARS['hnr']))
			{
				$noreply = time() - intval($HTTP_GET_VARS['hnr']) * 100;
				$noreply_sql = 'AND p2.post_time > ' . $noreply;
			}
			else
			{
				$error = true;
				output_die('Error: Wrong value for argument (no reply)');
			}
		}

		$startdate_sql = '';
		if (isset($HTTP_GET_VARS['hsd']))
		{
			if (is_numeric($HTTP_GET_VARS['hsd']))
			{
				$startdate = time() - intval($HTTP_GET_VARS['hsd']) * 100;
				$startdate_sql = 'AND p.post_time > ' . $startdate;
			}
			else
			{
				$error = true;
				output_die('Error: Wrong value for argument (start date)');
			}
		}

		if (isset($HTTP_GET_VARS['a']))
		{
			if ($HTTP_GET_VARS['a'] == 'y')
			{
				$announce_sql = '';
			}
			else
			{
				$error = true;
				output_die('Error: Wrong value for argument (announcement)');
			}
		}
		else
		{
			$announce_sql = 'AND t.topic_type <> ' . POST_ANNOUNCE;
		}

		if (isset($HTTP_GET_VARS['s']))
		{
			if ($HTTP_GET_VARS['s'] == 'y')
			{
				$sticky_sql = '';
			}
			else
			{
				$error = true;
				output_die('Error: Wrong value for argument (sticky)');
			}
		}
		else
		{
			$sticky_sql = "AND t.topic_type <> " . POST_STICKY;
		}

		if (isset($HTTP_GET_VARS['l']))
		{
			if ($HTTP_GET_VARS['l'] == 'y')
			{
				$locked_sql = '';
			}
			else
			{
				$error = true;
				output_die('Error: Wrong value for argument (locked)');
			}
		}
		else
		{
			$locked_sql = "AND t.topic_status <> " . TOPIC_LOCKED;
		}

		if (isset($HTTP_GET_VARS['m']))
		{
			if ($HTTP_GET_VARS['m'] == 'y')
			{
				$locked_sql = '';
			}
			else
			{
				$error = true;
				output_die('Error: Wrong value for argument (moved)');
			}
		}
		else
		{
			$moved_sql = "AND t.topic_status <> " . TOPIC_MOVED;
		}

		if (isset($HTTP_GET_VARS['rt']))
		{
			if ($HTTP_GET_VARS['rt'] == 'n')
			{
				$reg_sql = "AND t.topic_type <> " . POST_NORMAL;
			}
			else
			{
				$error = true;
				output_die('Error: Wrong value for argument (regular topics)');
			}
		}
		else
		{
			$reg_sql = '';
		}

		if (isset($HTTP_GET_VARS['so']) && $HTTP_GET_VARS['so'] == 'd')
		{
			$sql = "SELECT t.*, u.username, u.user_id, u2.username as user2, u2.user_id as id2, p.post_username, p2.post_username AS post_username2, p2.post_time, f.forum_name
				FROM " . TOPICS_TABLE . " t, " . USERS_TABLE . " u, " . POSTS_TABLE . " p, " . POSTS_TABLE . " p2, " . USERS_TABLE . " u2, " . FORUMS_TABLE . " f
				WHERE t.topic_poster = u.user_id
				$forum_sql
				AND p.post_id = t.topic_first_post_id
				AND p2.post_id = t.topic_last_post_id
				AND t.forum_id = f.forum_id
				AND u2.user_id = p2.poster_id
				$noreply_sql
				$startdate_sql
				$announce_sql
				$sticky_sql
				$locked_sql
				$moved_sql
				$reg_sql
				ORDER BY t.topic_last_post_id DESC
				LIMIT $limit";

			if ( !($result = $db->sql_query($sql)) )
			{
				$error = true;
				output_die('General Error: Could not obtain topic information (topics sql)');
			}

			$total_topics = 0;
			while( $row = $db->sql_fetchrow($result) )
			{
				$topic_rowset[] = $row;
				$total_topics++;
			}

			$db->sql_freeresult($result);
		}
		else
		{
			if (isset($HTTP_GET_VARS['a']))
			{
				if ($HTTP_GET_VARS['a'] == 'y')
				{
					$sql = "SELECT t.*, u.username, u.user_id, u2.username as user2, u2.user_id as id2, p.post_time, p.post_username, f.forum_name
						FROM " . TOPICS_TABLE . " t, " . USERS_TABLE . " u, " . POSTS_TABLE . " p, " . USERS_TABLE . " u2, " . FORUMS_TABLE . " f
						WHERE t.topic_poster = u.user_id
						$forum_sql
						AND p.post_id = t.topic_last_post_id
						AND p.poster_id = u2.user_id
						AND t.forum_id = f.forum_id
						AND t.topic_type = " . POST_ANNOUNCE . "
						$noreply_sql
						$startdate_sql
						ORDER BY t.topic_last_post_id DESC
						LIMIT $limit";

					if ( !($result = $db->sql_query($sql)) )
					{
						$error = true;
						output_die('General Error: Could not obtain topic information (announce sql)');
					}

					$topic_rowset = array();
					$total_announcements = 0;
					while( $row = $db->sql_fetchrow($result) )
					{
						$topic_rowset[] = $row;
						$total_announcements++;
					}

					$db->sql_freeresult($result);
				}
				else
				{
					$error = true;
					output_die('Error: Wrong value for argument (announce)');
				}
			}
			else
			{
				$topic_rowset = array();
				$total_announcements = 0;
			}

			$limit = $limit - $total_announcements;

			if ($limit < 1)
			{
				$limit = 0;
			}

			if ($limit)
			{
				$sql = "SELECT t.*, u.username, u.user_id, u2.username as user2, u2.user_id as id2, p.post_username, p2.post_username AS post_username2, p2.post_time, f.forum_name
					FROM " . TOPICS_TABLE . " t, " . USERS_TABLE . " u, " . POSTS_TABLE . " p, " . POSTS_TABLE . " p2, " . USERS_TABLE . " u2, " . FORUMS_TABLE . " f
					WHERE t.topic_poster = u.user_id
					$forum_sql
					AND p.post_id = t.topic_first_post_id
					AND p2.post_id = t.topic_last_post_id
					AND t.forum_id = f.forum_id
					AND u2.user_id = p2.poster_id
					AND t.topic_type <> " . POST_ANNOUNCE . "
					$noreply_sql
					$startdate_sql
					$sticky_sql
					$locked_sql
					$moved_sql
					$reg_sql
					ORDER BY t.topic_type DESC, t.topic_last_post_id DESC
					LIMIT $limit";

				if ( !($result = $db->sql_query($sql)) )
				{
					$error = true;
					output_die('General Error: Could not obtain topic information (topics sql)');
				}

				$total_topics = 0;
				while( $row = $db->sql_fetchrow($result) )
				{
					$topic_rowset[] = $row;
					$total_topics++;
				}

				$db->sql_freeresult($result);
			}

			$total_topics += $total_announcements;
		}

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

		if($total_topics) // topics?
		{
			for($i = 0; $i < $total_topics; $i++) // the loop - transfer data from rowset to different array
			{
				$data[$i]['topic_id'] = $topic_rowset[$i]['topic_id'];
				$data[$i]['topic_last_post_id'] = $topic_rowset[$i]['topic_last_post_id'];
				$data[$i]['topic_title'] = ( count($orig_word) ) ? preg_replace($orig_word, $replacement_word, $topic_rowset[$i]['topic_title']) : $topic_rowset[$i]['topic_title'];
				$data[$i]['replies'] = $topic_rowset[$i]['topic_replies'];
				$data[$i]['topic_type'] = $topic_rowset[$i]['topic_type'];
				$data[$i]['forum_id'] = $topic_rowset[$i]['forum_id'];
				$data[$i]['forum_name'] = $topic_rowset[$i]['forum_name'];

				$temp = $data[$i]['replies'];
				$data[$i]['replies'] = '';
				if (isset($HTTP_GET_VARS['r']))
				{
					if ($HTTP_GET_VARS['r'] == 'y')
					{
						if (isset($HTTP_GET_VARS['sr']))
						{
							if ($HTTP_GET_VARS['sr'] == 'y')
							{
								$data[$i]['replies'] = $temp . ' ' . (($temp == '1')? $lang['Reply'] : $lang['Replies']);
							}
							else
							{
								$error = true;
								output_die('Error: Wrong value for argument (showrepliesword)');
							}
						}
						else
						{
							$data[$i]['replies'] = $temp;
						}
					}
					else
					{
						$error = true;
						output_die('Error: Wrong value for argument (replies)');
					}
				}

				$temp = $data[$i]['forum_name'];
				$data[$i]['forum_name'] = '';
				if (isset($HTTP_GET_VARS['sfn']))
				{
					if ($HTTP_GET_VARS['sfn'] == 'y')
					{
						$data[$i]['forum_name'] = $temp;
					}
					else
					{
						$error = true;
						output_die('Error: Wrong value for argument (show forum name)');
					}
				}

				if( $data[$i]['topic_type'] == POST_ANNOUNCE )
				{
					if (isset($HTTP_GET_VARS['h']))
					{
						if (strstr($HTTP_GET_VARS['h'], 'a'))
						{
							$data[$i]['topic_type'] = '';
						}
						else
						{
							$data[$i]['topic_type'] = $lang['Topic_Announcement'];
						}
					}
					else
					{
						$data[$i]['topic_type'] = $lang['Topic_Announcement'];
					}
				}
				else if( $data[$i]['topic_type'] == POST_STICKY )
				{
					if (isset($HTTP_GET_VARS['h']))
					{
						if (strstr($HTTP_GET_VARS['h'], 's'))
						{
							$data[$i]['topic_type'] = '';
						}
						else
						{
							$data[$i]['topic_type'] = $lang['Topic_Sticky'];
						}
					}
					else
					{
						$data[$i]['topic_type'] = $lang['Topic_Sticky'];
					}
				}
				else
				{
					$data[$i]['topic_type'] = '';
				}

				if( $topic_rowset[$i]['topic_vote'] )
				{
					if (isset($HTTP_GET_VARS['h']))
					{
						if (!strstr($HTTP_GET_VARS['h'], 'p'))
						{
							$data[$i]['topic_type'] .= ($data[$i]['topic_type'] == '') ? '' : ' ';
							$data[$i]['topic_type'] .= $lang['Topic_Poll'];
						}
					}
					else
					{
						$data[$i]['topic_type'] .= ($data[$i]['topic_type']) ? '' : ' ';
						$data[$i]['topic_type'] .= $lang['Topic_Poll'];
					}
				}

				if( $topic_rowset[$i]['topic_status'] == TOPIC_MOVED )
				{
					if (isset($HTTP_GET_VARS['h']))
					{
						if (!strstr($HTTP_GET_VARS['h'], 'm'))
						{
							$data[$i]['topic_type'] .= ($data[$i]['topic_type'] == '') ? '' : ' ';
							$data[$i]['topic_type'] .= $lang['Topic_Moved'];
						}
					}
					else
					{
						$data[$i]['topic_type'] .= ($data[$i]['topic_type'] == '') ? '' : ' ';
						$data[$i]['topic_type'] .= $lang['Topic_Moved'];
					}
					$data[$i]['topic_id'] = $topic_rowset[$i]['topic_moved_id'];
				}

				if( $topic_rowset[$i]['topic_status'] == TOPIC_LOCKED )
				{
					if (isset($HTTP_GET_VARS['h']))
					{
						if (!strstr($HTTP_GET_VARS['h'], 'l'))
						{
							$data[$i]['topic_type'] .= ($data[$i]['topic_type'] == '') ? '' : ' ';
							$data[$i]['topic_type'] .= $lang['Topic_Locked'];
						}
					}
					else
					{
						$data[$i]['topic_type'] .= ($data[$i]['topic_type'] == '') ? '' : ' ';
						$data[$i]['topic_type'] .= $lang['Topic_Locked'];
					}
				}

				$data[$i]['last_post_author'] = '';
				if (isset($HTTP_GET_VARS['lpb']))
				{
					$data[$i]['last_post_author'] = ( $topic_rowset[$i]['id2'] == ANONYMOUS ) ? ( ($topic_rowset[$i]['post_username2'] != '' ) ? $topic_rowset[$i]['post_username2'] . ' ' : $lang['Guest'] . ' ' ) : $topic_rowset[$i]['user2'];
					if (is_numeric($HTTP_GET_VARS['lpb']))
					{
						if (intval($HTTP_GET_VARS['lpb']) == 1)
						{
							$data[$i]['last_post_author'] = $lang['Lastpost_from'] . ' ' . $data[$i]['last_post_author'];
						}
					}
				}

				$data[$i]['last_post_time'] = '';
				if (isset($HTTP_GET_VARS['lpd']))
				{
					if (is_numeric($HTTP_GET_VARS['lpd']))
					{
						if (intval($HTTP_GET_VARS['lpd']) < count($date_formats))
						{
							$data[$i]['last_post_time'] = create_date($date_formats[$HTTP_GET_VARS['lpd']], $topic_rowset[$i]['post_time'], $board_config['board_timezone']);
						}
						else
						{
							$data[$i]['last_post_time'] = create_date($board_config['default_dateformat'], $topic_rowset[$i]['post_time'], $board_config['board_timezone']);
						}
					}
					else
					{
						$data[$i]['last_post_time'] = create_date($board_config['default_dateformat'], $topic_rowset[$i]['post_time'], $board_config['board_timezone']);
					}
				}

				if (isset($HTTP_GET_VARS['ch']))
				{
					if (is_numeric($HTTP_GET_VARS['ch']))
					{
						$max_title_length = intval($HTTP_GET_VARS['ch']);
						if ($max_title_length > 0)
						{
							$trans = get_html_translation_table(HTML_ENTITIES);
							$trans = array_flip($trans);
							$data[$i]['topic_title'] = strtr($data[$i]['topic_title'], $trans);

							if (strlen($data[$i]['topic_title']) > $max_title_length)
							{
								if (isset($HTTP_GET_VARS['chw']))
								{
									if ($HTTP_GET_VARS['chw'] == 'p')
									{
										$data[$i]['topic_title'] = (strstr(strrev(substr($data[$i]['topic_title'], 0, $max_title_length)), ' ')) ? strrev(strstr(strrev(substr($data[$i]['topic_title'], 0, $max_title_length)), ' ')) . '...' : substr($data[$i]['topic_title'], 0, $max_title_length) . '...';
									}
									else if ($HTTP_GET_VARS['chw'] == 'n')
									{
										$topic_title_orig = $data[$i]['topic_title'];
										$data[$i]['topic_title'] = substr($topic_title_orig, 0, $max_title_length);
										$lastpart = substr($topic_title_orig, strlen($data[$i]['topic_title']));
										if (strrpos(strrev($lastpart), ' ') === false)
										{
											$data[$i]['topic_title'] = $topic_title_orig;
										}
										else
										{
											$data[$i]['topic_title'] .= substr($lastpart, 0, -(strrpos(strrev($lastpart), ' ')))  . '...';
										}
									}
									else
									{
										$data[$i]['topic_title'] = substr($data[$i]['topic_title'], 0, $max_title_length) . '...';
									}
								}
								else
								{
									$data[$i]['topic_title'] = substr($data[$i]['topic_title'], 0, $max_title_length) . '...';
								}
							}

							$trans = array_flip($trans);
							$data[$i]['topic_title'] = strtr($data[$i]['topic_title'], $trans);
						}
					}
				}
			}
		}
		else
		{
			$data = false; // no topics
		}

		unset($topic_rowset); // free some memory

		// start with the output of everything
		if ($out == 'js') {
			$css_link = '';
			if (isset($HTTP_GET_VARS['cl']))
			{
				if ($HTTP_GET_VARS['cl'] != '')
				{
					$css_link = ' class=\"' . $HTTP_GET_VARS['cl'] . '\"';
				}
				else
				{
					$error = true;
					output_die('Error: No value for argument (css_link)');
				}
			}

			$css_text_wrap_before = '';
			$css_text_wrap_after = '';
			if (isset($HTTP_GET_VARS['ct']))
			{
				if ($HTTP_GET_VARS['ct'] != '')
				{
					$css_text_wrap_before = '<span class=\"' . $HTTP_GET_VARS['ct'] . '\">';
					$css_text_wrap_after = '</span>';
				}
				else
				{
					$error = true;
					output_die('Error: No value for argument (css_text)');
				}
			}

			$target_link = ' target=\"_self\"';
			if (isset($HTTP_GET_VARS['t']))
			{
				if ($HTTP_GET_VARS['t'] != '')
				{
					$target_link = ' target=\"' . $HTTP_GET_VARS['t'] . '\"';
				}
				else
				{
					$error = true;
					output_die('Error: No value for argument (target_link)');
				}
			}

			$separator = ' - ';
			if (isset($HTTP_GET_VARS['br']))
			{
				if ($HTTP_GET_VARS['br'] == 'y')
				{
					$separator = '<br>';
				}
			}

			$html_list = false;
			$list_wrap_before = '';
			$list_wrap_after = '';
			if (isset($HTTP_GET_VARS['b']))
			{
				if ($HTTP_GET_VARS['b'] == 'dis' || $HTTP_GET_VARS['b'] == 'cir' || $HTTP_GET_VARS['b'] == 'squ' || $HTTP_GET_VARS['b'] == 'num')
				{
					$html_list = true;
					switch($HTTP_GET_VARS['b'])
					{
						case "dis":
							$html_wrap_before = '<ul type=\"disc\">';
							$html_wrap_after = '</ul>';
							break;
						case "cir":
							$html_wrap_before = '<ul type=\"circle\">';
							$html_wrap_after = '</ul>';
							break;
						case "squ":
							$html_wrap_before = '<ul type=\"square\">';
							$html_wrap_after = '</ul>';
							break;
						case "num":
							$html_wrap_before = '<ol type=\"1\">';
							$html_wrap_after = '</ol>';
							break;
						default:
							break;
					}
				}
			}

			if ($css_text_wrap_before != '')
			{
				echo "document.writeln('$css_text_wrap_before');\n";
			}

			if ($html_wrap_before != '')
			{
				echo "document.writeln('$html_wrap_before');\n";
			}

			if ($data !== false)
			{
				$item = '<table width=\"100%\" border=\"0\" cellspacing=\"1\" cellpadding=\"4\">\n<tr><td align=\"center\" class=\"tdlinkslevel\">Topics</td><td align=\"center\" class=\"tdlinkslevel\">Author</td><td align=\"center\" class=\"tdlinkslevel\">Replies</td><td align=\"center\" class=\"tdlinkslevel\">Last Post</td></tr>\n';
				for($i = 0; $i < $total_topics; $i++)
				{
					if (isset($HTTP_GET_VARS['fnl']))
					{
						if ($HTTP_GET_VARS['fnl'] == 'y')
						{
							$data[$i]['forum_name'] = '<a href=\"' . $full_url . "/viewforum.$phpEx?" . POST_FORUM_URL . '=' . $data[$i]['forum_id'] . '\"' . $css_link . $target_link . '>' . addslashes($data[$i]['forum_name']) . '</a>';
						}
						else
						{
							$data[$i]['forum_name'] = addslashes($data[$i]['forum_name']);
						}
					}
					else
					{
						$data[$i]['forum_name'] = addslashes($data[$i]['forum_name']);
					}

					if (isset($HTTP_GET_VARS['jlp']))
					{
						if ($HTTP_GET_VARS['jlp'] == 'y')
						{
							$url_to_topic = '<a href=\"' . $full_url . "/viewtopic.$phpEx?" . POST_POST_URL . '=' . $data[$i]['topic_last_post_id'] . '#' . $data[$i]['topic_last_post_id'] . '\"' . $css_link . $target_link . '>' . addslashes($data[$i]['topic_title']) . '</a>';
						}
						else
						{
							$url_to_topic = '<a href=\"' . $full_url . "/viewtopic.$phpEx?" . POST_TOPIC_URL . '=' . $data[$i]['topic_id'] . '\"' . $css_link . $target_link . '>' . addslashes($data[$i]['topic_title']) . '</a>';
						}
					}
					else
					{
						$url_to_topic = '<a href=\"' . $full_url . "/viewtopic.$phpEx?" . POST_TOPIC_URL . '=' . $data[$i]['topic_id'] . '\"' . $css_link . $target_link . '>' . addslashes($data[$i]['topic_title']) . '</a>';
					}

					$last_post_url = '<a href=\"' . $full_url . "/viewtopic.$phpEx?"  . POST_POST_URL . '=' . $data[$i]['topic_last_post_id'] . '#' . $data[$i]['topic_last_post_id'] . '\"' . $css_link . $target_link . '><img src=\"' . $full_url . '/' . $images['icon_latest_reply'] . '\" alt=\"' . $lang['View_latest_post'] . '\" title=\"' . $lang['View_latest_post'] . '\" border=\"0\" /></a>';

					if ($adv_format)
					{
						$item = $af_string;
						$item = str_replace('§lbl§', addslashes($data[$i]['topic_type']), $item);
						$item = str_replace('§tt§', $url_to_topic, $item);
						$item = str_replace('§fn§', $data[$i]['forum_name'], $item);
						$item = str_replace('§rep§', addslashes($data[$i]['replies']), $item);
						$item = str_replace('§lpa§', addslashes($data[$i]['last_post_author']), $item);
						$item = str_replace('§lpt§', addslashes($data[$i]['last_post_time']), $item);
						$item = str_replace('§lpi§', $last_post_url, $item);
						$item = str_replace('§br§', '<br />', $item);
					}
					else
					{
						$item .= '<tr><td class=\"tdlinkslevel\">';
						$item .= addslashes($data[$i]['topic_type']);
						$item .= ($data[$i]['topic_type'] == '') ? '' : ' ';
						$item .= $url_to_topic;
						$item .= '</td><td class=\"tdlinkslevel\">';

						$item .= addslashes($data[$i]['last_post_author']);
						$item .= '</td><td class=\"tdlinkslevel\" align=\"center\">';

						$item .= ($data[$i]['forum_name'] == '') ? '' : ' ' . addslashes($lang['In']) . ' ';
						$item .= $data[$i]['forum_name'];
//						$item .= ($data[$i]['replies'] == '') ? '' : ' (';
						$item .= addslashes($data[$i]['replies']);
//						$item .= ($data[$i]['replies'] == '') ? '' : ')';
						$item .= '</td><td class=\"tdlinkslevel\">';

						$item .= ($data[$i]['last_post_time'] == '') ? '' : ' ';
						$item .= addslashes($data[$i]['last_post_time']);

						$item = ($item2 == '') ? $item : $item . $separator . $item2;

						if (isset($HTTP_GET_VARS['lpi']))
						{
							if ($HTTP_GET_VARS['lpi'] == 'y' && $HTTP_GET_VARS['b'] != 'lpi')
							{
								$item = $item . ' ' . $last_post_url;
							}
						}

						if (isset($HTTP_GET_VARS['bl']))
						{
							if ($HTTP_GET_VARS['bl'] == 'y')
							{
								$item = $item . '<br>';
							}
						}
					}

					if ($html_list)
					{
						$item = '<li>' . $item . '</li>';
					}
					else
					{
						if (isset($HTTP_GET_VARS['b']))
						{
							if ($HTTP_GET_VARS['b'] == 'non')
							{
								$item = $item . '</td></tr>\n';
							}
							else if ($HTTP_GET_VARS['b'] == 'lpi')
							{
								$item = $last_post_url . ' ' . $item . '<br>';
							}
							else if (is_numeric($HTTP_GET_VARS['b']))
							{
								if (intval($HTTP_GET_VARS['b']) < count($bullets))
								{
									$item = $bullets[intval($HTTP_GET_VARS['b'])] . ' ' . $item . '<br>';
								}
								else
								{
									$error = true;
									output_die('Error: Wrong value for argument (bullet)');
								}
							}
							else
							{
								$error = true;
								output_die('Error: Wrong value for argument (bullet)');
							}
						}
					}
				}
				$item .= '</table>';
				echo "document.writeln('$item');\n";
			}
			else // no topics
			{
				if ($html_list)
				{
					$item = '<li>' . $lang['No_topics'] . '</li>';
				}
				else
				{
					if (isset($HTTP_GET_VARS['b']))
					{
						if ($HTTP_GET_VARS['b'] == 'non' || $HTTP_GET_VARS['b'] == 'lpi')
						{
							$item = $lang['No_topics'] . '<br>';
						}
						else if (is_numeric($HTTP_GET_VARS['b']))
						{
							if (intval($HTTP_GET_VARS['b']) < count($bullets))
							{
								$item = $bullets[intval($HTTP_GET_VARS['b'])] . ' ' . $lang['No_topics'] . '<br>';
							}
							else
							{
								$error = true;
								output_die('Error: Wrong value for argument (bullet)');
							}
						}
					}
				}

				echo "document.writeln('$item');\n";
			}

			if ($html_wrap_before != '')
			{
				echo "document.writeln('$html_wrap_after');\n";
			}

			if ($css_text_wrap_before != '')
			{
				echo "document.writeln('$css_text_wrap_after');\n";
			}
		}
		else if ($out == 'rss')
		{
			header("Content-type: text/xml");
			echo generate_rss_header($version);

			if ($adv_format && strpos($af_string, '|') !== false)
			{
				$pos = strpos($af_string, '|');
			}
			else
			{
				$pos = false;
			}

			if ($data !== false)
			{
				for($i = 0; $i < $total_topics; $i++)
				{
					if ($adv_format)
					{
						if ($pos)
						{
							$title = substr($af_string, 0, $pos);
							$title = str_replace('§lbl§', htmlspecialchars(strip_tags($data[$i]['topic_type']), ENT_QUOTES, $lang['ENCODING']), $title);
							$title = str_replace('§tt§', htmlspecialchars($data[$i]['topic_title'], ENT_QUOTES, $lang['ENCODING']), $title);
							$title = str_replace('§fn§', htmlspecialchars($data[$i]['forum_name'], ENT_QUOTES, $lang['ENCODING']), $title);
							$title = str_replace('§rep§', htmlspecialchars($data[$i]['replies'], ENT_QUOTES, $lang['ENCODING']), $title);
							$title = str_replace('§lpa§', htmlspecialchars($data[$i]['last_post_author'], ENT_QUOTES, $lang['ENCODING']), $title);
							$title = str_replace('§lpt§', htmlspecialchars($data[$i]['last_post_time'], ENT_QUOTES, $lang['ENCODING']), $title);
							if ($title == '')
							{
								$title = htmlspecialchars($data[$i]['topic_title'], ENT_QUOTES, $lang['ENCODING']);
							}

							$desc = substr($af_string, $pos + 1);
							$desc = str_replace('§lbl§', htmlspecialchars(strip_tags($data[$i]['topic_type']), ENT_QUOTES, $lang['ENCODING']), $desc);
							$desc = str_replace('§tt§', htmlspecialchars($data[$i]['topic_title'], ENT_QUOTES, $lang['ENCODING']), $desc);
							$desc = str_replace('§fn§', htmlspecialchars($data[$i]['forum_name'], ENT_QUOTES, $lang['ENCODING']), $desc);
							$desc = str_replace('§rep§', htmlspecialchars($data[$i]['replies'], ENT_QUOTES, $lang['ENCODING']), $desc);
							$desc = str_replace('§lpa§', htmlspecialchars($data[$i]['last_post_author'], ENT_QUOTES, $lang['ENCODING']), $desc);
							$desc = str_replace('§lpt§', htmlspecialchars($data[$i]['last_post_time'], ENT_QUOTES, $lang['ENCODING']), $desc);
						}
						else
						{
							$item = $af_string;
							$item = str_replace('§lbl§', htmlspecialchars(strip_tags($data[$i]['topic_type'])), $item);
							$item = str_replace('§tt§', htmlspecialchars($data[$i]['topic_title'], ENT_QUOTES, $lang['ENCODING']), $item);
							$item = str_replace('§fn§', htmlspecialchars($data[$i]['forum_name'], ENT_QUOTES, $lang['ENCODING']), $item);
							$item = str_replace('§rep§', htmlspecialchars($data[$i]['replies'], ENT_QUOTES, $lang['ENCODING']), $item);
							$item = str_replace('§lpa§', htmlspecialchars($data[$i]['last_post_author'], ENT_QUOTES, $lang['ENCODING']), $item);
							$item = str_replace('§lpt§', htmlspecialchars($data[$i]['last_post_time'], ENT_QUOTES, $lang['ENCODING']), $item);
							$title = $item;
							$desc = '';
						}
					}
					else
					{
						$title = htmlspecialchars(strip_tags($data[$i]['topic_type']), ENT_QUOTES, $lang['ENCODING']);
						$title .= ($data[$i]['topic_type'] == '') ? '' : ' ';
						$title .= htmlspecialchars($data[$i]['topic_title'], ENT_QUOTES, $lang['ENCODING']);
						$title .= ($data[$i]['forum_name'] == '') ? '' : ' ' . htmlspecialchars($lang['In']) . ' ';
						$title .= htmlspecialchars($data[$i]['forum_name'], ENT_QUOTES, $lang['ENCODING']);

						$desc = htmlspecialchars($data[$i]['last_post_author'], ENT_QUOTES, $lang['ENCODING']);
						$desc .= ($data[$i]['last_post_author'] == '') ? '' : ', ';
						$desc .= htmlspecialchars($data[$i]['last_post_time'], ENT_QUOTES, $lang['ENCODING']);
						$desc .= ($data[$i]['replies'] == '') ? '' : ' (';
						$desc .= htmlspecialchars($data[$i]['replies'], ENT_QUOTES, $lang['ENCODING']);
						$desc .= ($data[$i]['replies'] == '') ? '' : ')';
					}

					if (isset($HTTP_GET_VARS['jlp']))
					{
						if ($HTTP_GET_VARS['jlp'] == 'y')
						{
							$view_topic_url = $full_url . "/viewtopic.$phpEx?" . POST_POST_URL . '=' . $data[$i]['topic_last_post_id'] . '#' . $data[$i]['topic_last_post_id'];
						}
						else
						{
							$view_topic_url = $full_url . "/viewtopic.$phpEx?" . POST_TOPIC_URL . '=' . $data[$i]['topic_id'];
						}
					}
					else
					{
						$view_topic_url = $full_url . "/viewtopic.$phpEx?" . POST_TOPIC_URL . '=' . $data[$i]['topic_id'];
					}

					$title = ($version == '0.91') ? substr($title, 0, 100) : $title;
					$link = ($version == '0.91') ? substr($view_topic_url, 0, 500) : $view_topic_url;
					$description = ($version == '0.91') ? substr($desc, 0, 500) : $desc;

					$item = '<item>' . "\n";
					$item .= '<title>' . $title . '</title>' . "\n";
					$item .= '<link>' . $link . '</link>' . "\n";
					$item .= ($desc != '') ? '<description>' . $description . '</description>' . "\n" : '';
					$item .= '</item>' . "\n";

					echo $item;
				}
			}
			else
			{
				$title = ($version == '0.91') ? substr($lang['No_topics'], 0, 100) : $lang['No_topics'];
				$link = ($version == '0.91') ? substr($full_url, 0, 500) : $full_url;

				$item = '<item>' . "\n";
				$item .= '<title>' . $title . '</title>' . "\n";
				$item .= '<link>' . $link . '</link>' . "\n";
				$item .= '</item>' . "\n";

				echo $item;
			}

			echo generate_rss_footer();
		}
	}

	if ($error)
	{
		output_die($errorarray);
	}
}
else if ($HTTP_GET_VARS['mode'] == "generate") // generate and show the code that the user has to put into the page where the topics are to be displayed
{
	$htmlstring = $full_url . '/' . TA_SCRIPT_NAME . '.' . $phpEx . '?mode=show';

	$out = 'js';

	if ($HTTP_POST_VARS['out'] != 'js')
	{
		$out = $HTTP_POST_VARS['out'];
		$htmlstring .= '&out=' . $out;
	}

	if (isset($HTTP_POST_VARS['f']))
	{
		$farray = $HTTP_POST_VARS['f'];
	}
	else
	{
		$farray = array();
	}

	$carray = array();

	if (count($farray) != 0)
	{
		$farray = array_unique($farray);
		sort($farray);
		for ($j = 0; $j < count($farray); $j++) {
			if ($farray[$j] == '-1') {
				array_splice($farray, $j, 1);
			}
		}

		for ($j = 0; $j < count($farray); $j++) {
			if (strpos($farray[$j], 'cat') !== false) {
				$carray = array_merge($carray, array_splice($farray, $j, 1));
				$j--;
			}
		}
	}

	if (count($carray) != 0)
	{
		$carray = str_replace('cat', '', $carray);
		$catsql = '(' . implode(', ', $carray) . ')';

		$sql = "SELECT forum_id
			FROM " . FORUMS_TABLE . "
			WHERE cat_id IN " . $catsql . "
			ORDER BY forum_id";
		if ( !($result = $db->sql_query($sql)) )
		{
			message_die(GENERAL_ERROR, 'Could not obtain forums information', '', __LINE__, __FILE__, $sql);
		}

		$carray = array();
		while ( $row = $db->sql_fetchrow($result) )
		{
			$carray[] = $row['forum_id'];
		}

		$farray = array_merge($farray, $carray);
		$farray = array_unique($farray);
		sort($farray);
	}

	if (count($farray) == 0 && !$HTTP_POST_VARS['allfora'])
	{
		message_die(GENERAL_ERROR, ($lang['Pick_a_forum'] . '<br /><br /><a href="javascript:history.back()">' . $lang['Click_return'] . '</a>'));
	}
	else
	{
		if ($HTTP_POST_VARS['allfora'] || ($HTTP_POST_VARS['total_forums'] == count($farray)))
		{
			$htmlstring .= '&f=a';
		}
		else
		{
			if (count($farray) == 1)
			{
				$htmlstring .= '&f=' . $farray[0];
			}
			else
			{
				$htmlstring .= '&f=u' . rawurlencode(base64_encode(implode(',', $farray)));
			}
		}
	}

	if (!isset($HTTP_POST_VARS['amount_topics']))
	{
		message_die(GENERAL_ERROR, ($lang['Invalid_amount'] . '<br /><br /><a href="javascript:history.back()">' . $lang['Click_return'] . '</a>'));
	}
	else
	{
		if (!is_numeric($HTTP_POST_VARS['amount_topics']))
		{
			message_die(GENERAL_ERROR, ($lang['Invalid_amount'] . '<br /><br /><a href="javascript:history.back()">' . $lang['Click_return'] . '</a>'));
		}
		else
		{
			$amount = floor(intval($HTTP_POST_VARS['amount_topics']));
			if ($amount > 0)
			{
				$htmlstring .= '&n=' . $amount;
			}
			else
			{
				message_die(GENERAL_ERROR, ($lang['Invalid_amount'] . '<br /><br /><a href="javascript:history.back()">' . $lang['Click_return'] . '</a>'));
			}
		}
	}

	if ($HTTP_POST_VARS['noreply'])
	{
		if (!isset($HTTP_POST_VARS['noreply_timespan']))
		{
			message_die(GENERAL_ERROR, ($lang['Invalid_timespan'] . '<br /><br /><a href="javascript:history.back()">' . $lang['Click_return'] . '</a>'));
		}
		else
		{
			if (!is_numeric($HTTP_POST_VARS['noreply_timespan']))
			{
				message_die(GENERAL_ERROR, ($lang['Invalid_timespan'] . '<br /><br /><a href="javascript:history.back()">' . $lang['Click_return'] . '</a>'));
			}
			else
			{
				$timespan = floor(intval($HTTP_POST_VARS['noreply_timespan']));
				if ($timespan > 0)
				{
					if ($HTTP_POST_VARS['noreply_unit'] == 'day')
					{
						$timespan = $timespan * 864;
					}
					else
					{
						$timespan = $timespan * 36;
					}
					$htmlstring .= '&hnr=' . $timespan;
				}
				else
				{
					message_die(GENERAL_ERROR, ($lang['Invalid_timespan'] . '<br /><br /><a href="javascript:history.back()">' . $lang['Click_return'] . '</a>'));
				}
			}
	}
	}

	if ($HTTP_POST_VARS['startdate'])
	{
		if (!isset($HTTP_POST_VARS['startdate_timespan']))
		{
			message_die(GENERAL_ERROR, ($lang['Invalid_timespan'] . '<br /><br /><a href="javascript:history.back()">' . $lang['Click_return'] . '</a>'));
		}
		else
		{
			if (!is_numeric($HTTP_POST_VARS['startdate_timespan']))
			{
				message_die(GENERAL_ERROR, ($lang['Invalid_timespan'] . '<br /><br /><a href="javascript:history.back()">' . $lang['Click_return'] . '</a>'));
			}
			else
			{
				$timespan = floor(intval($HTTP_POST_VARS['startdate_timespan']));
				if ($timespan > 0)
				{
					if ($HTTP_POST_VARS['startdate_unit'] == 'day')
					{
						$timespan = $timespan * 864;
					}
					else
					{
						$timespan = $timespan * 36;
					}
					$htmlstring .= '&hsd=' . $timespan;
				}
				else
				{
					message_die(GENERAL_ERROR, ($lang['Invalid_timespan'] . '<br /><br /><a href="javascript:history.back()">' . $lang['Click_return'] . '</a>'));
				}
			}
		}
	}

	if ($HTTP_POST_VARS['jump_last_post'])
	{
		$htmlstring .= '&jlp=y';
	}

	if ($HTTP_POST_VARS['show_forum_name'])
	{
		$htmlstring .= '&sfn=y';
		if ($HTTP_POST_VARS['link_forum_name'] && $out == 'js')
		{
			$htmlstring .= '&fnl=y';
		}
	}

	if ($HTTP_POST_VARS['show_replies'])
	{
		$htmlstring .= '&r=y';
		if ($HTTP_POST_VARS['show_replies_word'])
		{
			$htmlstring .= '&sr=y';
		}
	}

	if ($HTTP_POST_VARS['show_announce'])
	{
		$htmlstring .= '&a=y';
	}

	if ($HTTP_POST_VARS['show_sticky'])
	{
		$htmlstring .= '&s=y';
	}

	if ($HTTP_POST_VARS['show_locked'])
	{
		$htmlstring .= '&l=y';
	}

	if ($HTTP_POST_VARS['show_moved'])
	{
		$htmlstring .= '&m=y';
	}

	if (!$HTTP_POST_VARS['show_regular'])
	{
		$htmlstring .= '&rt=n';
	}

	if (isset($HTTP_POST_VARS['hidelabel']))
	{
		$htmlstring .= '&h=';
		$hidelabel = $HTTP_POST_VARS['hidelabel'];
		foreach ($hidelabel as $key => $val)
		{
			$htmlstring .= substr($key, 1, -1);
		}
	}

	if ($HTTP_POST_VARS['sort_order'] == 'ondate')
	{
		$htmlstring .= '&so=d';
	}

	if ($out != 'rss') {
		if ($HTTP_POST_VARS['lastposticon_bullet'])
		{
			$htmlstring .= '&b=lpi';
		}
		else
		{
			$htmlstring .= '&b=' . $HTTP_POST_VARS['bullet_type'];
		}
	}

	if ($HTTP_POST_VARS['show_lastpostby'])
	{
		$htmlstring .= '&lpb=' . $HTTP_POST_VARS['lastpostby_format'];
	}

	if ($HTTP_POST_VARS['show_lastpostdate'])
	{
		$htmlstring .= '&lpd=' . $HTTP_POST_VARS['lastpostdate_format'];
	}

	if ($HTTP_POST_VARS['show_lastposticon'] && $out == 'js')
	{
		$htmlstring .= '&lpi=y';
	}

	if ($HTTP_POST_VARS['add_break'] && $out == 'js')
	{
		$htmlstring .= '&br=y';
	}

	if ($HTTP_POST_VARS['add_blank_line'] && $out == 'js')
	{
		$htmlstring .= '&bl=y';
	}

	if (isset($HTTP_POST_VARS['limit_length']))
	{
		if (!is_numeric($HTTP_POST_VARS['limit_length']))
		{
			message_die(GENERAL_ERROR, ($lang['Invalid_title_length'] . '<br /><br /><a href="javascript:history.back()">' . $lang['Click_return'] . '</a>'));
		}
		else
		{
			$limitlength = floor(intval($HTTP_POST_VARS['limit_length']));
			if ($limitlength > 0)
			{
				$htmlstring .= '&ch=' . $limitlength . '&chw=' . $HTTP_POST_VARS['limit_where'];
			}
		}
	}

	if (isset($HTTP_POST_VARS['css_link']) && $out == 'js')
	{
		$css_link = trim($HTTP_POST_VARS['css_link']);
		if (preg_match("/[^a-zA-Z0-9]+$/s", $css_link) || strstr($css_link, ' '))
		{
			message_die(GENERAL_ERROR, ($lang['Invalid_class'] . '<br /><br /><a href="javascript:history.back()">' . $lang['Click_return'] . '</a>'));
		}
		else
		{
			if ($css_link != '')
			{
				$htmlstring .= '&cl=' . $css_link;
			}
		}
	}

	if (isset($HTTP_POST_VARS['css_text']) && $out == 'js')
	{
		$css_text = trim($HTTP_POST_VARS['css_text']);
		if (preg_match("/[^a-zA-Z0-9]+$/s", $css_text) || strstr($css_text, ' '))
		{
			message_die(GENERAL_ERROR, ($lang['Invalid_class'] . '<br /><br /><a href="javascript:history.back()">' . $lang['Click_return'] . '</a>'));
		}
		else
		{
			if ($css_text != '')
			{
				$htmlstring .= '&ct=' . $css_text;
			}
		}
	}

	if (isset($HTTP_POST_VARS['target_link']) && $out == 'js')
	{
		$target_link = trim($HTTP_POST_VARS['target_link']);
		if (preg_match("/[^a-zA-Z0-9_]+$/s", $target_link) || strstr($target_link, ' '))
		{
			message_die(GENERAL_ERROR, ($lang['Invalid_target'] . '<br /><br /><a href="javascript:history.back()">' . $lang['Click_return'] . '</a>'));
		}
		else
		{
			if ($target_link != '')
			{
				$htmlstring .= '&t=' . $target_link;
			}
		}
	}

	if ($HTTP_POST_VARS['adv_form_enable'])
	{
		if (isset($HTTP_POST_VARS['adv_form']))
		{
			if ($out != 'js') {
				$htmlstring .= '&af=' . rawurlencode(base64_encode(strip_tags($HTTP_POST_VARS['adv_form'])));
			}
			else
			{
				include($phpbb_root_path . 'includes/functions_post.'.$phpEx);

				$html_on = (!$board_config['allow_html']) ? 0 : 1;
				$htmlstring .= '&af=' . rawurlencode(base64_encode(prepare_message($HTTP_POST_VARS['adv_form'], $html_on, 0, 0, '')));
			}
		}
	}

	if ($out == 'js')
	{
		$htmlstring = '<script language="JavaScript" type="text/javascript" src="' . $htmlstring . '"></script>';
	}

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

	if ($out == 'js')
	{
		$file = 'topics_anywhere_result.tpl';
		$result = str_replace("&amp;", "&", htmlspecialchars($htmlstring, ENT_QUOTES));
	}
	else if ($out != 'js')
	{
		$file = 'topics_anywhere_result_rss.tpl';
		$result = '<a href="' . $htmlstring . '" target="_blank" class="gen">' . str_replace("&amp;", "&", htmlspecialchars($htmlstring, ENT_QUOTES)) . '</a>';
		$lang['Copy_paste'] = $lang['Copy_paste_rss'];
		$lang['Copy_paste_explain'] = $lang['Copy_paste_explain_rss'];
	}

	$template->set_filenames(array(
		'body' => $file)
	);


	$template->assign_vars(array(
		'L_TOPICS_ANYWHERE' => $lang['Topics_anywhere'] . ' ' . TA_VERSION,
		'L_COPYPASTE' => $lang['Copy_paste'],
		'L_COPYPASTE_EXPLAIN' => $lang['Copy_paste_explain'],
		'RESULT' => $result,
		'L_RESULT' => $lang['The_result'],
		'L_CLASSES_REMARK' => $lang['Classes_remark'],
		'HTMLCODE' => $htmlstring)
	);

	$template->pparse('body');

	include($phpbb_root_path . 'includes/page_tail.'.$phpEx);
}
else // shows option page - page will be shown if no or wrong $mode arguments are given
{
	if ($topics_anywhere_authlevel == 0)
	{
		show_the_page();
	}
	else
	{
		if ( !$userdata['session_logged_in'] )
		{
			$header_location = ( @preg_match("/Microsoft|WebSTAR|Xitami/", getenv("SERVER_SOFTWARE")) ) ? "Refresh: 0; URL=" : "Location: ";
			header($header_location . append_sid("login." . $phpEx . "?redirect=" . TA_SCRIPT_NAME . "." . $phpEx, true));
			exit;
		}
		else // user is logged in - check userlevel
		{
			switch($topics_anywhere_authlevel)
			{
				case 1:
					if ($userdata['user_level'] == ADMIN)
					{
						show_the_page();
					}
					else
					{
						$message = sprintf($lang['Sorry_auth_topicsanywhere'], $lang['Auth_Administrators']);
						message_die(GENERAL_MESSAGE, $message, $lang['Not_Authorised']);
					}
					break;
				case 2:
					if ($userdata['user_level'] == MOD)
					{
						show_the_page();
					}
					else
					{
						$message = sprintf($lang['Sorry_auth_topicsanywhere'], $lang['Auth_Moderators']);
						message_die(GENERAL_MESSAGE, $message, $lang['Not_Authorised']);
					}
					break;
				case 3:
					if ($userdata['user_level'] == ADMIN || $userdata['user_level'] == MOD)
					{
						show_the_page();
					}
					else
					{
						$message = sprintf($lang['Sorry_auth_topicsanywhere'], $lang['Auth_Administrators'] . ' ' . strtolower($lang['Or']) . ' ' . $lang['Auth_Moderators']);
						message_die(GENERAL_MESSAGE, $message, $lang['Not_Authorised']);
					}
					break;
				case 4:
					if ($userdata['user_level'] == USER || $userdata['user_level'] == ADMIN || $userdata['user_level'] == MOD)
					{
						show_the_page();
					}
					else
					{
						$message = sprintf($lang['Sorry_auth_topicsanywhere'], $lang['Auth_Registered_Users']);
						message_die(GENERAL_MESSAGE, $message, $lang['Not_Authorised']);
					}
					break;
				default:
					message_die(GENERAL_MESSAGE, $lang['Error']);
					break;
			}
		}
	}
}

// EOF
?>
