<?php
/**
 * SSDForums Main Executable
 *
 * @author Vladimir A. Pronin aka Sidious <sidous@sidious.ru>
 * @author Sergey K. Koshelev aka Serg_pnz <print58@yandex.ru>
 * @author Dmitriy A. Antonov aka AntDima <antdima@mail.ru>
 * @copyright  2007 SSDForums Team
 * @license    GNU/GPL
 * @version    1.0.1
 * @link       http://ponedelnikov.net
 * @since      File available since Release 1.0.2
*/

if (!defined('MODULE_FILE')) {
Header("Location: ../../index.php");
exit;
}


$module_name = basename(dirname(__FILE__));
session_start();
session_set_cookie_params( time() + 3 );

function check_uinf() {
global $version, $conf;
	if ($version=="2.1 Lite" OR $conf['version'] == "3.0 Pro") {
		return "userinfo&user_name";
	} else {
		return "info&uname";
	}
}

get_lang($module_name);
require_once("config/config_forums.php");
if(!defined('SDD_INSTALLED')) {
	if(is_admin($admin)) {
		if(file_exists("modules/$module_name/install.php")) {
			$location = "index.php?name=$module_name&file=install";
		} else {
			$location = "index.php?error=404";
		}
	} else {
		$location = "index.php?error=403";
	}
	header("Location: $location");
	exit;
}
function menu() {
	global $prefix, $db, $user, $module_name;
	OpenTable();
	if (is_user($user)) {
		echo "<div align=\"right\"><font class=\"smalla\">";
		$result = $db->sql_query("SELECT user_visit, user_lastvisit  FROM ".$prefix."_forums_users WHERE user_id='" .$user[0]. "' ");
		if (!($db->sql_numrows($result))) {
			$db->sql_query("INSERT INTO  ".$prefix."_forums_users SET user_id='$user[0]', user_visit='".time()."', user_lastvisit = '0' ");
		}
		list ($user_visit, $user_lastvisit)  =  $db->sql_fetchrow($result);
		if ( (time()-$user_visit) > (2400) ) {
			$db->sql_query("UPDATE  ".$prefix."_forums_users SET user_lastvisit='$user_visit', user_visit='".time()."' WHERE user_id = '" .$user[0]. "' ");
			$user_lastvisit = $user_visit;
		} else {
			$db->sql_query("UPDATE  ".$prefix."_forums_users SET user_visit='".time()."'  WHERE user_id = '" .$user[0]. "' ");
		}
		if ($user_lastvisit=="0") {
			echo "Это Ваше первое посещение форума<br>";
		} else {
			echo ""._LAST_VISIT.": ".date('d.m.Y', $user_lastvisit)." "._IN." ".date('H:i:s', $user_lastvisit)."<br>";
		}
		echo "</font><table border=0 cellpadding=0 cellspacing=0 width=100%><tr align=right><td colspan=2><font class=\"smalla\">Вы вошли как: <b>$user[1]</b> (</font><a href=\"index.php?name=Account&op=logout\" class=\"smalla\">Выход</a>)</td><tr align=right><td align=\"right\" width=100% ><a href=\"index.php?name=$module_name&op=showforum&id=0\" class=\"smalla\"><img src=\"modules/$module_name/images/folder_new.png\" alt=\"Новые сообщения\" title=\"Новые сообщения\" border=0 /></a></td><td nowrap=\"nowrap\">&nbsp;&nbsp;<a href=\"index.php?name=$module_name&op=showforum&id=0\" class=\"smalla\">Новые сообщения</a></td></tr>"
		."<tr align=right><td align=\"right\" width=100% ><a href=\"index.php?name=$module_name&op=searchforumstart\" class=\"smalla\"><img src=\"modules/$module_name/images/folder_search.png\" alt=\"Поиск по форуму\" title=\"Поиск по форуму\" border=0 /></a></td><td nowrap=\"nowrap\">&nbsp;&nbsp;<a href=\"index.php?name=$module_name&op=searchforumstart\" class=\"smalla\">Поиск по форуму</a></td></tr>"
		."</table>";
	} else {
		echo "<div align=\"center\"><font class=\"smalla\">";
		echo "<a href=\"index.php?name=Account&op=newuser\" class=\"smalla\">Регистрация</a> | <a href=\"index.php?name=Account\" class=\"smalla\">Вход</a>"
		."<div align=right><a href=\"index.php?name=$module_name&op=searchforumstart\" class=\"smalla\"><img src=\"modules/$module_name/images/folder_search.png\" alt=\"Поиск по форуму\" title=\"Поиск по форуму\" border=0 /></a>&nbsp;&nbsp;<a href=\"index.php?name=$module_name&op=searchforumstart\" class=\"smalla\">Поиск по форуму</a></div>";
	}
echo "</font></div>";
CloseTable();
}

function forums($id = false) {
global $prefix, $db, $module_name, $pagetitle, $defis, $version, $conf;
	if(!$version) {
		$version = &$conf['version'];
		$defis = &$conf['defis'];
	}
	$pagetitle = "".$defis." "._FORUM."";
	include("header.php");
	menu();
	echo "<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"middle\"><tr><td><table border=\"0\" cellpadding=\"3\" cellspacing=\"1\" width=\"100%\" class=\"bgcolor4\">"
	."<tr><th colspan=\"2\">"._FORUM."</th><th>"._TOPICS."</th><th>"._POSTS."</th></tr>";
	$id ? $catid = $id : $catid = 0;
	$categories = getCategories('0');
	$count = count($categories);
	for($i=0;$i<$count;$i++) {
		$catvalue = $categories[$i];
		if($catvalue) {
			if($id && $id == $categories[$i]['id'] OR !$id) {
				echo "<tr><td colspan=\"4\" style=\"margin: 0px 0px 1px 0px;height: 21px;background-image: url(../../images/editor/bg.gif);	background-repeat: repeat-x;\" bgcolor=\"#FFFFFF\">";
				if($id) echo "<a href=\"index.php?name=$module_name\">Форум</a>&nbsp;->&nbsp;";
				echo "<a href=\"index.php?name=$module_name&op=showforum&id=".$catvalue['id']."\"><b>".$catvalue['title']."</b></a></td></tr>";
				$sub = getCategories($catvalue['id']);
				foreach($sub as $subkey=>$subvalue) {
					echo "<tr class=\"bgcolor1\"><td width=\"32\"><img src=\"modules/$module_name/images/forum.gif\" border=\"0\"></td>"
					."<td><a href=\"index.php?name=$module_name&op=showforum&id=".$subvalue['id']."\"><b>".$subvalue['title']."</b></a><br /><i>".$subvalue['description']."</i></td>"
					."<td align=\"center\" width=\"40\">".$subvalue['totaltopics']."</td>"
					."<td align=\"center\" width=\"70\">".$subvalue['totalposts']."</td></tr>";
				}
			}
		}
	}

	if($catid == 0) {
		$nocat = getCategories('-1');
		if($nocat) {
			 echo "<tr><td colspan=\"4\" bgcolor=\"#FFFFFF\"><hr></td></tr>";
			foreach($nocat as $nockey=>$nocvalue) {
				echo "<tr class=\"bgcolor1\"><td width=\"32\"><img src=\"modules/$module_name/images/forum.gif\" border=\"0\"></td>"
				."<td><a href=\"index.php?name=$module_name&op=showforum&id=".$nocvalue['id']."\"><b>".$nocvalue['title']."</b></a><br /><i>".$nocvalue['description']."</i></td>"
				."<td align=\"center\" width=\"40\">".$nocvalue['totaltopics']."</td>"
				."<td align=\"center\" width=\"70\">".$nocvalue['totalposts']."</td></tr>";
			}
		}
		echo "</table></td></tr></table><br />";
		$fstat['posts'] = 0;
		$fstat['topics'] = 0;
		$ustat = $db->sql_fetchrow($db->sql_query("SELECT count(user_id) AS count from ".$prefix."_users"));
		$ulast = $db->sql_fetchrow($db->sql_query("SELECT user_name FROM ".$prefix."_users ORDER by user_id Desc LIMIT 0,1"));
		$fstat = $db->sql_fetchrow($db->sql_query("SELECT sum(totalposts) as posts, sum(totaltopics) as topics FROM ".$prefix."_forums_cats WHERE pid != '0'"));
		OpenTable();
		echo ""._HELLONEWUSER." <a href=\"index.php?name=Account&op=".check_uinf()."=".$ulast['user_name']."\"><b>".$ulast['user_name']."</b></a>.<br />"
		.""._ALLREG." <b>".$ustat['count']."</b> "._USERS.".<br />"
		.""._ALLT." <b>".$fstat['posts']."</b> "._MESSAGES." <b>".$fstat['topics']."</b> "._TOPCS.".";
		}
	CloseTable();
	include("footer.php");
}


function showsearch($id) {
global $prefix, $db, $module_name, $admin_file, $pagetitle, $topicspg, $rtype, $defis, $user, $version, $conf, $postspg;

session_start();
#pre ($_SESSION);
	$id = isset($_GET['id']) ? intval($_GET['id']) : "0";
	if(isset($_GET['id'])) {
		unset($_SESSION['zapp']);
	}

if ($_SESSION['zapp']!="" ) {$_POST['search_word'] =""; $_POST['search_word'] = $_SESSION['zapp'];}
if (isset ($_POST['search_word']) ) {
	$_SESSION['zapp'] = $_POST['search_word'];
	$search_word = strip_tags(urldecode($_POST['search_word']));
	$search_word = htmlspecialchars(trim($search_word), ENT_QUOTES);
}

	if(!$version) {
		$version = &$conf['version'];
		$defis = &$conf['defis'];
	};
	$collspan = 6;
		$cat = getCategories(0);
		$search = ArraySearchRecursive($id,$cat[0],'id');
		if(is_array($search)) {
			return forums($id);
		}
		list($title) = $db->sql_fetchrow($db->sql_query("SELECT title FROM ".$prefix."_forums_cats WHERE id = '$id'"));

		if ($id == 0 AND !isset($search_word)) {
			$title = "Последние сообщения";
		} elseif (isset($search_word)) {
			$title = "Результаты поиска";
		}

		$num = isset($_GET['pagenum']) ? intval($_GET['pagenum']) : "1";
		$offset = ($num-1) * $topicspg;
		$offset = intval($offset);
		$search = ArraySearchRecursive($title,$cat,'title');
		$search = $search[0];
		$search = ArraySearchRecursive($search,$cat[0],'id');
		$search = $search[0];
		$pagetitle = "".$defis." "._FORUM;
		if($_GET['id']) $pagetitle .= $defis." ".$cat[0][$search]['title'];
		$pagetitle .= $defis." ".$title;
		if(is_user($user)) {
			$userinfo = $db->sql_fetchrow($db->sql_query("SELECT * FROM ".$prefix."_forums_users WHERE user_id = ".$user[0]));
		}
		include("header.php");
		menu();
		$userinfo['user_moder'] == 2 ? $collspan = 8 : 6;
		echo "<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"middle\"><tr><td><table border=\"0\" cellpadding=\"3\" cellspacing=\"1\" width=\"100%\" class=\"bgcolor4\">"
		."<tr><td class=\"bgcolor1\" colspan=\"$collspan\"><a href=\"index.php?name=$module_name\"><b>"._FORUM."</b></a>";
		if($id > 0 AND $cat[0][$search]['id']!="") {
			echo " -> <a href=\"index.php?name=$module_name&op=showforum&id=".$cat[0][$search]['id']."\">".$cat[0][$search]['title']."</a>";
		}
			echo "-> $title</td></tr></table><table class=\"forums\" border=\"0\" cellpadding=\"3\" cellspacing=\"1\" width=\"100%\" class=\"bgcolor4\">"
		."<thead>"
		."<tr>"
		."<th width=\"50%\" colspan=\"2\">"._TNAME."</th>"
		."<th nowrap>"._TAUTHOR."</th>"
		."<th nowrap>"._TSHOWS."</th>"
		."<th nowrap>"._TANSWERS."</th>"
		."<th nowrap>"._TLAST."</th>";
		if($userinfo['user_moder'] == 2) {
			echo "<th nowrap width=20%>&nbsp;&nbsp;Опции&nbsp;&nbsp;</th>";
			echo "<th nowrap width=20%>&nbsp;&nbsp;Статусы&nbsp;&nbsp;</th>";
		}
		echo "</tr>";
		echo "</thead><tbody>";

		unset($_SESSION['bb']);
		if (isset($search_word)) {
			$search_word = str_replace("  ", " ", $search_word);
			$search_word = str_replace("  ", " ", $search_word);
			$search_word = str_replace("(", " ( ", $search_word);
			$search_word = str_replace(")", " ) ", $search_word);
			$mass_sea = explode (" ", $search_word);
			$zap = "";
			foreach ($mass_sea as $key => $val) {
			if (trim($val)=="(" OR trim($val)==")" OR trim($val)=="AND" OR trim($val)=="OR") {
				$zap .= " ".$val." ";
			} elseif (trim($val)!="") {
				$_SESSION['bb'] .= " #".$val."#si";
				$zap .= " ".$prefix."_forums_posts.message LIKE '%".$val."%' ";
			}
			}
			$zap = str_replace("  ", " ", $zap);
			$zap = str_replace("  ", " ", $zap);
			$zap = str_replace("' ".$prefix."_forums_posts.message", "' AND ".$prefix."_forums_posts.message", $zap);
		} elseif ($id>0) {
			$zap = $prefix."_forums_topics.cid=".$id;
		} else {
			$result = $db->sql_query("SELECT user_lastvisit  FROM ".$prefix."_forums_users  WHERE user_id='" .$user[0]. "' ");
			$user_lastvisit  =  $db->sql_fetchrow($result);
			$user_lastvisit = $user_lastvisit[0];
			$user_lastvisit1 = date('Y.m.d', $user_lastvisit)." ".date('H:i:s', $user_lastvisit);
			global $admin;
			if (is_admin($admin)) $user_lastvisit1 = "0000-00-00 00:00";
			$zap = $prefix."_forums_topics.date >='$user_lastvisit1' ";
		}

		$result = $db->sql_query("SELECT * FROM ".$prefix."_forums_topics  LEFT JOIN ".$prefix."_forums_posts on ".$prefix."_forums_topics.id = ".$prefix."_forums_posts.tid WHERE $zap GROUP By ".$prefix."_forums_posts.tid ORDER BY ".$prefix."_forums_topics.date DESC LIMIT $offset, $topicspg");
		if ($db->sql_numrows($result) > 0) {
		$result = $db->sql_fetchrowset($result);
		for($i = 0,$c = count($result); $i<$c; $i++) {
		if ($result[$i]['status'] == 3) {$stype = "<span style=\"color: red;\"><b>Важно:</b></span> "; $tstatus = "3"; $oalt = "Важно";}
		elseif ($result[$i]['status'] == 4) {$stype = "<span style=\"color: red;\"><b>Объявление:</b></span> "; $tstatus = "4"; $oalt = "Объявление";}
		else {$stype = ""; $tstatus = "1";$oalt = "";}
		list($namelast) = $db->sql_fetchrow($db->sql_query("SELECT name FROM ".$prefix."_forums_posts WHERE tid='$result[$i][0]' ORDER BY date DESC"));
		if($result[$i]['closed'] == 1) {
			$tstatus = "2";
			$oalt = "Закрыта";
		}

 		$num_pagelast0 = ceil (($result[$i]['totalposts']+1) / $postspg);
		if ($num_pagelast0 > 1) {$num_pagelast = "&pagenum=$num_pagelast0";} else {$num_pagelast = "";}
if ($num_pagelast0>3) {
	$pagestr = "<a class=\"pn_ssdf\" href=\"index.php?name=Forums&op=showtopic&id=".$result[$i][0]."&pagenum=1\" title=\"На страницу 1\">1</a> <a class=\"pn_ssdf\" href=\"index.php?name=Forums&op=showtopic&id=".$result[$i][0]."&pagenum=2\" title=\"На страницу 2\">2</a> <a class=\"pn_ssdf\" href=\"index.php?name=Forums&op=showtopic&id=".$result[$i][0]."&pagenum=3\" title=\"На страницу 3\">3</a>...<a class=\"pn_ssdf\" href=\"index.php?name=Forums&op=showtopic&id=".$result[$i][0]."".$num_pagelast."\" title=\"На последнюю страницу\">L</a>";
}
elseif ($num_pagelast0==3) {
	$pagestr = "<a class=\"pn_ssdf\" href=\"index.php?name=Forums&op=showtopic&id=".$result[$i][0]."&pagenum=1\" title=\"На страницу 1\">1</a> <a class=\"pn_ssdf\" href=\"index.php?name=Forums&op=showtopic&id=".$result[$i][0]."&pagenum=2\" title=\"На страницу 2\">2</a> <a class=\"pn_ssdf\" href=\"index.php?name=Forums&op=showtopic&id=".$result[$i][0]."&pagenum=3\" title=\"На страницу 3\">3</a>";
}
elseif ($num_pagelast0==2) {
	$pagestr = "<a class=\"pn_ssdf\" href=\"index.php?name=Forums&op=showtopic&id=".$result[$i][0]."&pagenum=1\" title=\"На страницу 1\">1</a> <a class=\"pn_ssdf\" href=\"index.php?name=Forums&op=showtopic&id=".$result[$i][0]."&pagenum=2\" title=\"На страницу 2\">2</a>";
}
else {
	$pagestr = "";
}


		echo "<tr class=\"bgcolor1\">"
		."<td align=\"center\"><img src=\"modules/$module_name/images/statuses/".$tstatus.".gif\" alt=$oalt title=$oalt></td>"
		."<td width=\"100%\">$stype<a href=\"index.php?name=$module_name&op=showtopic&id=".$result[$i][0]."\"><b>".$result[$i]['title']."</b></a> ".$pagestr."</td>"
		."<td align=\"center\"><a href=\"index.php?name=Account&op=".check_uinf()."=".$result[$i]['name']."\" title=\""._PERSONALINFO."\" target=\"_blank\">".$result[$i]['name']."</a></td>"
		."<td align=\"center\">".$result[$i]['totalshows']."</td>"
		."<td align=\"center\">".$result[$i]['totalposts']."</td>"
		."<td align=\"center\"><a href=\"index.php?name=Account&op=".check_uinf()."=".$result[$i]['lastposter_name']."\">".$result[$i]['lastposter_name']."</a></td>";
		if($userinfo['user_moder'] == 2) {
			if($result[$i]['closed'] == 0) {
				$action = "close";
				$alt = "Закрыть";
				$img = 2;
			} else {
				$action = "open";
				$alt = "Открыть";
				$img = 1;
			}
			echo "<td align=\"center\">";
			echo " <a href=\"index.php?name=$module_name&op=theme&action=$action&id=".$result[$i][0]."\" alt=\"$alt тему\"><img title=\"$alt тему\" alt=\"$alt тему\" src=\"modules/$module_name/images/statuses/$img.gif\"  border=0/></a><a href=\"modules/$module_name/images/statuses/\"></a> ";
			echo " <a href=\"index.php?name=$module_name&op=theme&action=move&id=".$result[$i][0]."\" alt=\"Переместить тему\"><img title=\"Переместить тему\" alt=\"Переместить тему\" src=\"modules/$module_name/images/move.gif\"  border=0/></a><a href=\"modules/$module_name/images/statuses/\"></a> ";
			echo "</td>";
			echo "<td align=\"center\">";
			switch ($result[$i]['status']) {
				case 0:
					echo " <a href=\"index.php?name=$module_name&op=theme&action=status&set=3&id=".$result[$i][0]."\"><img src=\"modules/$module_name/images/statuses/3.gif\" alt=\"Статус: Важно\" title=\"Статус: Важно\" border=0></a> <a href=\"index.php?name=$module_name&op=theme&action=status&set=4&id=".$result[$i][0]."\"><img src=\"modules/$module_name/images/statuses/4.gif\" alt=\"Статус: Объявление\" title=\"Статус: Объявление\" border=0></a> ";
				break;
				case 3:
					echo " <a href=\"index.php?name=$module_name&op=theme&action=status&set=0&id=".$result[$i][0]."\"><img src=\"modules/$module_name/images/statuses/1.gif\" alt=\"Статус: Обычный\" title=\"Статус: Обычный\" border=0></a> <a href=\"index.php?name=$module_name&op=theme&action=status&set=4&id=".$result[$i][0]."\"><img src=\"modules/$module_name/images/statuses/4.gif\" alt=\"Статус: Объявление\" title=\"Статус: Объявление\" border=0></a> ";
				break;
				case 4:
					echo " <a href=\"index.php?name=$module_name&op=theme&action=status&set=0&id=".$result[$i][0]."\"><img src=\"modules/$module_name/images/statuses/1.gif\" alt=\"Статус: Обычный\" title=\"Статус: Обычный\" border=0></a> <a href=\"index.php?name=$module_name&op=theme&action=status&set=3&id=".$result[$i][0]."\"><img src=\"modules/$module_name/images/statuses/3.gif\" alt=\"Статус: Важно\" title=\"Статус: Важно\" border=0></a> ";
				break;

			}
			echo "</td>";
		}
		echo "</tr>";
		}
		echo "</tbody>";
		echo "<tr><td class=\"bgcolor1\"><a href=\"index.php?name=$module_name&op=newtopic&cid=$id\"><img src=\"modules/$module_name/images/new.gif\" title="._NEWTOPIC." alt="._NEWTOPIC." border=0 /></a></td><td class=\"bgcolor1\" colspan=\"".($collspan-1)."\"><a href=\"index.php?name=$module_name&op=newtopic&cid=$id\">"._NEWTOPIC."</a></td></tr></table></td></tr></table><br />";
		} else {
		echo "<tr class=\"bgcolor1\">"
		."<td align=\"center\" colspan=\"$collspan\"><br /><center><span class=\"option\">";
		if ($id>0) { echo _NOTOPICS;} else {echo "По Вашему запросу<br>".htmlspecialchars($_SESSION['zapp'])."<br>ничего не найдено.";}
		echo "</span></center><br /></td>"
		."</tr>";
		if($_GET['id']) {
		echo "<tr><td class=\"bgcolor1\"><table border=0 width=100%><tr><td align=right><a href=\"index.php?name=$module_name&op=newtopic&cid=$id\"><img src=\"modules/$module_name/images/new.gif\" title="._NEWTOPIC." alt="._NEWTOPIC." border=0 /></a></td><td align=lfet><a href=\"index.php?name=$module_name&op=newtopic&cid=$id\">"._NEWTOPIC."</a></td></tr></table></td><td class=\"bgcolor1\" colspan=\"".($collspan-1)."\"></td></tr></table></td></tr></table><br />";
		} else echo "</table></td></tr></table><br />";
		}
		$numtopics = $db->sql_numrows($db->sql_query("SELECT tid FROM  ".$prefix."_forums_posts  WHERE $zap GROUP By tid "));
		$numpages = ceil($numtopics/$topicspg);
		if ($search_word=="") {$id1 = "&id=".$id."";}
		num_page($module_name, $numtopics, $numpages, $topicspg, "&op=showsearch".$id1."&");
		include("footer.php");
}


function showforum($id) {
global $prefix, $db, $module_name, $admin_file, $pagetitle, $topicspg, $rtype, $defis, $user, $version, $conf, $postspg;

session_start();
unset($_SESSION['zapp']);
session_destroy();
	if(!$version) {
		$version = &$conf['version'];
		$defis = &$conf['defis'];
	};
	$collspan = 6;
	$id = isset($_GET['id']) ? intval($_GET['id']) : "0";
	if($id >= 0) {
		$cat = getCategories(0);
		$search = ArraySearchRecursive($id,$cat[0],'id');
		if(is_array($search)) {
			return forums($id);
		}
		list($title) = $db->sql_fetchrow($db->sql_query("SELECT title FROM ".$prefix."_forums_cats WHERE id = '$id'"));
		if ($id == 0) {$title = "Последние сообщения";}
		$num = isset($_GET['pagenum']) ? intval($_GET['pagenum']) : "1";
		$offset = ($num-1) * $topicspg;
		$offset = intval($offset);
		$search = ArraySearchRecursive($title,$cat,'title');
		$search = $search[0];
		$search = ArraySearchRecursive($search,$cat[0],'id');
		$search = $search[0];
		$pagetitle = "".$defis." "._FORUM;
		if($_GET['id']) $pagetitle .= $defis." ".$cat[0][$search]['title'];
		$pagetitle .= $defis." ".$title;
		if(is_user($user)) {
			$userinfo = $db->sql_fetchrow($db->sql_query("SELECT * FROM ".$prefix."_forums_users WHERE user_id = ".$user[0]));
		}
		include("header.php");
		menu();
		$userinfo['user_moder'] == 2 ? $collspan = 8 : 6;
		echo "<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"middle\"><tr><td><table border=\"0\" cellpadding=\"3\" cellspacing=\"1\" width=\"100%\" class=\"bgcolor4\">"
		."<tr><td class=\"bgcolor1\" colspan=\"$collspan\"><a href=\"index.php?name=$module_name\"><b>"._FORUM."</b></a>";
		if($id > 0 AND $cat[0][$search]['id']!="") {
			echo " -> <a href=\"index.php?name=$module_name&op=showforum&id=".$cat[0][$search]['id']."\">".$cat[0][$search]['title']."</a>";
		}
			echo "-> $title</td></tr></table><table class=\"forums\" border=\"0\" cellpadding=\"3\" cellspacing=\"1\" width=\"100%\" class=\"bgcolor4\">"
		."<thead>"
		."<tr>"
		."<th width=\"50%\" colspan=\"2\">"._TNAME."</th>"
		."<th nowrap>"._TAUTHOR."</th>"
		."<th nowrap>"._TSHOWS."</th>"
		."<th nowrap>"._TANSWERS."</th>"
		."<th nowrap>"._TLAST."</th>";
		if($userinfo['user_moder'] == 2) {
			echo "<th nowrap width=20%>&nbsp;&nbsp;Опции&nbsp;&nbsp;</th>";
			echo "<th nowrap width=20%>&nbsp;&nbsp;Статусы&nbsp;&nbsp;</th>";
		}
		echo "</tr>";
		echo "</thead><tbody>";
		if ($id>0) {
			$zap = $prefix."_forums_topics.cid=".$id;
		} else {
			$result = $db->sql_query("SELECT user_lastvisit  FROM ".$prefix."_forums_users  WHERE user_id='" .$user[0]. "' ");
			$user_lastvisit  =  $db->sql_fetchrow($result);
			$user_lastvisit = $user_lastvisit[0];
			$user_lastvisit1 = date('Y.m.d', $user_lastvisit)." ".date('H:i:s', $user_lastvisit);
			global $admin;
			if (is_admin($admin)) $user_lastvisit1 = "0000-00-00 00:00";
			$zap = $prefix."_forums_topics.date >='$user_lastvisit1' ";
		}
		$result = $db->sql_query("SELECT * FROM ".$prefix."_forums_topics  LEFT JOIN ".$prefix."_forums_posts on ".$prefix."_forums_topics.id = ".$prefix."_forums_posts.tid WHERE $zap GROUP By ".$prefix."_forums_posts.tid ORDER BY ".$prefix."_forums_topics.date DESC LIMIT $offset, $topicspg");
		if ($db->sql_numrows($result) > 0) {
		$result = $db->sql_fetchrowset($result);
		for($i = 0,$c = count($result); $i<$c; $i++) {
		if ($result[$i]['status'] == 3) {$stype = "<span style=\"color: red;\"><b>Важно:</b></span> "; $tstatus = "3"; $oalt = "Важно";}
		elseif ($result[$i]['status'] == 4) {$stype = "<span style=\"color: red;\"><b>Объявление:</b></span> "; $tstatus = "4"; $oalt = "Объявление";}
		else {$stype = ""; $tstatus = "1";$oalt = "";}
		list($namelast) = $db->sql_fetchrow($db->sql_query("SELECT name FROM ".$prefix."_forums_posts WHERE tid='$result[$i][0]' ORDER BY date DESC"));
		if($result[$i]['closed'] == 1) {
			$tstatus = "2";
			$oalt = "Закрыта";
		}

 		$num_pagelast0 = ceil (($result[$i]['totalposts']+1) / $postspg);
		if ($num_pagelast0 > 1) {$num_pagelast = "&pagenum=$num_pagelast0";} else {$num_pagelast = "";}
if ($num_pagelast0>3) {
	$pagestr = "<a class=\"pn_ssdf\" href=\"index.php?name=Forums&op=showtopic&id=".$result[$i][0]."&pagenum=1\" title=\"На страницу 1\">1</a> <a class=\"pn_ssdf\" href=\"index.php?name=Forums&op=showtopic&id=".$result[$i][0]."&pagenum=2\" title=\"На страницу 2\">2</a> <a class=\"pn_ssdf\" href=\"index.php?name=Forums&op=showtopic&id=".$result[$i][0]."&pagenum=3\" title=\"На страницу 3\">3</a>...<a class=\"pn_ssdf\" href=\"index.php?name=Forums&op=showtopic&id=".$result[$i][0]."".$num_pagelast."\" title=\"На последнюю страницу\">L</a>";
}
elseif ($num_pagelast0==3) {
	$pagestr = "<a class=\"pn_ssdf\" href=\"index.php?name=Forums&op=showtopic&id=".$result[$i][0]."&pagenum=1\" title=\"На страницу 1\">1</a> <a class=\"pn_ssdf\" href=\"index.php?name=Forums&op=showtopic&id=".$result[$i][0]."&pagenum=2\" title=\"На страницу 2\">2</a> <a class=\"pn_ssdf\" href=\"index.php?name=Forums&op=showtopic&id=".$result[$i][0]."&pagenum=3\" title=\"На страницу 3\">3</a>";
}
elseif ($num_pagelast0==2) {
	$pagestr = "<a class=\"pn_ssdf\" href=\"index.php?name=Forums&op=showtopic&id=".$result[$i][0]."&pagenum=1\" title=\"На страницу 1\">1</a> <a class=\"pn_ssdf\" href=\"index.php?name=Forums&op=showtopic&id=".$result[$i][0]."&pagenum=2\" title=\"На страницу 2\">2</a>";
}
else {
	$pagestr = "";
}

		echo "<tr class=\"bgcolor1\">"
		."<td align=\"center\"><img src=\"modules/$module_name/images/statuses/".$tstatus.".gif\" alt=$oalt title=$oalt></td>"
		."<td width=\"100%\">$stype<a href=\"index.php?name=$module_name&op=showtopic&id=".$result[$i][0]."\"><b>".$result[$i]['title']."</b></a> ".$pagestr."</td>"
		."<td align=\"center\"><a href=\"index.php?name=Account&op=".check_uinf()."=".$result[$i]['name']."\" title=\""._PERSONALINFO."\" target=\"_blank\">".$result[$i]['name']."</a></td>"
		."<td align=\"center\">".$result[$i]['totalshows']."</td>"
		."<td align=\"center\">".$result[$i]['totalposts']."</td>"
		."<td align=\"center\"><a href=\"index.php?name=Account&op=".check_uinf()."=".$result[$i]['lastposter_name']."\">".$result[$i]['lastposter_name']."</a></td>";
		if($userinfo['user_moder'] == 2) {
			if($result[$i]['closed'] == 0) {
				$action = "close";
				$alt = "Закрыть";
				$img = 2;
			} else {
				$action = "open";
				$alt = "Открыть";
				$img = 1;
			}
			echo "<td align=\"center\">";
			echo " <a href=\"index.php?name=$module_name&op=theme&action=$action&id=".$result[$i][0]."\" alt=\"$alt тему\"><img title=\"$alt тему\" alt=\"$alt тему\" src=\"modules/$module_name/images/statuses/$img.gif\"  border=0/></a><a href=\"modules/$module_name/images/statuses/\"></a> ";
			echo " <a href=\"index.php?name=$module_name&op=theme&action=move&id=".$result[$i][0]."\" alt=\"Переместить тему\"><img title=\"Переместить тему\" alt=\"Переместить тему\" src=\"modules/$module_name/images/move.gif\"  border=0/></a><a href=\"modules/$module_name/images/statuses/\"></a> ";
			echo "</td>";
			echo "<td align=\"center\">";
			switch ($result[$i]['status']) {
				case 0:
					echo " <a href=\"index.php?name=$module_name&op=theme&action=status&set=3&id=".$result[$i][0]."\"><img src=\"modules/$module_name/images/statuses/3.gif\" alt=\"Статус: Важно\" title=\"Статус: Важно\" border=0></a> <a href=\"index.php?name=$module_name&op=theme&action=status&set=4&id=".$result[$i][0]."\"><img src=\"modules/$module_name/images/statuses/4.gif\" alt=\"Статус: Объявление\" title=\"Статус: Объявление\" border=0></a> ";
				break;
				case 3:
					echo " <a href=\"index.php?name=$module_name&op=theme&action=status&set=0&id=".$result[$i][0]."\"><img src=\"modules/$module_name/images/statuses/1.gif\" alt=\"Статус: Обычный\" title=\"Статус: Обычный\" border=0></a> <a href=\"index.php?name=$module_name&op=theme&action=status&set=4&id=".$result[$i][0]."\"><img src=\"modules/$module_name/images/statuses/4.gif\" alt=\"Статус: Объявление\" title=\"Статус: Объявление\" border=0></a> ";
				break;
				case 4:
					echo " <a href=\"index.php?name=$module_name&op=theme&action=status&set=0&id=".$result[$i][0]."\"><img src=\"modules/$module_name/images/statuses/1.gif\" alt=\"Статус: Обычный\" title=\"Статус: Обычный\" border=0></a> <a href=\"index.php?name=$module_name&op=theme&action=status&set=3&id=".$result[$i][0]."\"><img src=\"modules/$module_name/images/statuses/3.gif\" alt=\"Статус: Важно\" title=\"Статус: Важно\" border=0></a> ";
				break;

			}
			echo "</td>";
		}
		echo "</tr>";
		}
		echo "</tbody>";
		echo "<tr><td class=\"bgcolor1\"><a href=\"index.php?name=$module_name&op=newtopic&cid=$id\"><img src=\"modules/$module_name/images/new.gif\" title="._NEWTOPIC." alt="._NEWTOPIC." border=0 /></a></td><td class=\"bgcolor1\" colspan=\"".($collspan-1)."\"><a href=\"index.php?name=$module_name&op=newtopic&cid=$id\">"._NEWTOPIC."</a></td></tr></table></td></tr></table><br />";
		} else {
		echo "<tr class=\"bgcolor1\">"
		."<td align=\"center\" colspan=\"$collspan\"><br /><center><span class=\"option\">";
		if ($id>0) { echo _NOTOPICS;} else {echo "Нет последних сообщений с Вашего последнего посещения.";}
		echo "</span></center><br /></td>"
		."</tr>";
		if($_GET['id']) {
		echo "<tr><td class=\"bgcolor1\"><table border=0 width=100%><tr><td align=right><a href=\"index.php?name=$module_name&op=newtopic&cid=$id\"><img src=\"modules/$module_name/images/new.gif\" title="._NEWTOPIC." alt="._NEWTOPIC." border=0 /></a></td><td align=lfet><a href=\"index.php?name=$module_name&op=newtopic&cid=$id\">"._NEWTOPIC."</a></td></tr></table></td><td class=\"bgcolor1\" colspan=\"".($collspan-1)."\"></td></tr></table></td></tr></table><br />";
		} else echo "</table></td></tr></table><br />";
		}
		list($numtopics) = $db->sql_fetchrow($db->sql_query("SELECT Count(id) FROM ".$prefix."_forums_topics WHERE $zap ORDER BY date DESC"));
		$numpages = ceil($numtopics/$topicspg);
		num_page($module_name, $numtopics, $numpages, $topicspg, "&op=showforum&id=".$id."&");
		include("footer.php");
	} else {
		header("Location: index.php?name=$module_name");
	}
}


function showtopic($id) {
global $user, $userinfo, $prefix, $db, $module_name, $admin_file, $defis, $pagetitle, $postspg, $num, $rtitle1, $rtitle2, $rtitle3, $rtitle4, $rtitle5, $rtitle6, $rtitle7, $rtitle8, $rtitle9, $rtitle10, $rtitle_moder, $rtitle_admin, $adirectory, $defis, $rank1, $rank2, $rank3, $rank4, $rank5, $rank6, $rank7, $rank8, $rank9, $rank10, $version, $conf, $confu;
$id= intval($id);
	if(!$version) {
		$version = &$conf['version'];
		$defis = &$conf['defis'];
		$adirectory = &$confu['adirectory'];
	};
	$id = isset($_GET['id']) ? intval($_GET['id']) : "0";
	list($cid, $title,$closed) = $db->sql_fetchrow($db->sql_query("SELECT cid, title, closed FROM ".$prefix."_forums_topics WHERE id = '$id'"));
	list($ctitle) = $db->sql_fetchrow($db->sql_query("SELECT title FROM ".$prefix."_forums_cats WHERE id = '$cid'"));
	$pagetitle = "".$defis." "._FORUM." ".$defis." $ctitle ".$defis." ".text_filter($title)."";

	$infoUser = "op=".check_uinf()."=";

include("header.php");
menu();
session_start();
	getusrinfo($user);

	list($userinfo['user_moder'], $userinfo['user_messages'], $userinfo['user_rank']) = $db->sql_fetchrow($db->sql_query("SELECT user_moder, user_messages, user_rank FROM ".$prefix."_forums_users WHERE user_id = '$user[0]'"));

	$num = isset($_GET['pagenum']) ? intval($_GET['pagenum']) : "1";
	$offset = ($num-1) * $postspg;
	$offset = intval($offset);
	if (isset($_GET['pagenum'])) $a = $offset+1; else $a = "1";

	ob_start();
	list($numposts) = $db->sql_fetchrow($db->sql_query("SELECT Count(id) FROM ".$prefix."_forums_posts WHERE tid='$id'"));
	$numpages = ceil($numposts/$postspg);
	num_page($module_name, $numposts, $numpages, $postspg, "op=showtopic&id=$id&");
	$num_pag = ob_get_contents();
	ob_end_clean();
	echo $num_pag = preg_replace("#<b>Всего(.*?)странице</b><br />#si","",$num_pag);

/*веха #1*/
/*if ($id==227) {
	OpenTable();
	echo bb_decode("[center]<br><br>Давайте договоримся так.<br>Тему я всё же оставлю (хотя бы из-за принципа),<br>но ОЧЕНЬ прошу [u]воздержаться[/u] от мата, хамства и наездов,<br>типа кто круче и кто кого щас заддосит.<br>Такие посты будут [color=red][b]удаляться[/b][/color], а не редактироваться.<br><br>[/center]");
	CloseTable();
}
*/

	$db->sql_query("UPDATE ".$prefix."_forums_topics SET totalshows=totalshows+1 WHERE id='$id'");
	echo "<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"middle\"><tr><td><table border=\"0\" cellpadding=\"3\" cellspacing=\"1\" width=\"100%\" class=\"bgcolor4\">"
	."<tr><td class=\"bgcolor1\" colspan=\"2\"><a href=\"index.php?name=$module_name\"><b>"._FORUM."</b></a> -> <a href=\"index.php?name=$module_name&op=showforum&id=$cid\"><b>$ctitle</b></a> -> $title</td></tr>"
	."<tr><th colspan=\"2\">$title</th></tr>";
	$result2 = $db->sql_query("SELECT a.*, b.user_id, b.user_name, b.user_avatar, b.user_regdate, b.user_sig, d.user_rank, d.user_moder, d.user_messages FROM ".$prefix."_forums_posts AS a LEFT JOIN ".$prefix."_users AS b ON a.name=b.user_name LEFT JOIN ".$prefix."_forums_users AS d ON b.user_id=d.user_id WHERE tid='$id' ORDER BY date ASC LIMIT $offset, $postspg");
	while (list($id, $tid, $date, $name, $host, $message, $uid, $uname, $uavatar, $uregdate, $usig, $urank, $umoder, $umessages) = $db->sql_fetchrow($result2)) {

///1-1
	$filn = glob("uploads/SSDForums/SSDForums-".$id.".*");
	if ($filn[0]!="") {
		$delfiles = "<a href=\"index.php?name=$module_name&op=deladdfiles&id=$id\" alt=\"Удалить прикрепленный файл\"><img title=\"Удалить прикрепленный файл\" alt=\"Удалить прикрепленный файл\" src=\"images/blocks/Files_Del.gif\" border=0></a> ";
	} else {
		$delfiles = "";
	}

	if ($userinfo['user_moder'] == 1 || $userinfo['user_moder'] == 2) $editmsg = "".$delfiles."<a href=\"index.php?name=$module_name&op=addfiles&id=$id\" alt=\"Прикрепить файл\"><img title=\"Прикрепить файл\" alt=\"Прикрепить файл\" src=\"images/blocks/Files.gif\" border=0></a> <a href=\"index.php?name=$module_name&op=editpost&id=$id\" alt=\"Редактировать\"><img title=\"Редактировать\" alt=\"Редактировать\" src=\"modules/$module_name/images/statuses/1.gif\" border=0></a> <a class=\"delete_message\" href=\"index.php?name=$module_name&op=deletepost&id=$id&postnum=$a\" ><img alt=\"Удалить\" title=\"Удалить\" src=\"modules/$module_name/images/statuses/2.gif\" border=0 /></a> |";
	elseif ($name == $user[1]) $editmsg = "".$delfiles."<a href=\"index.php?name=$module_name&op=addfiles&id=$id\" alt=\"Прикрепить файл\"><img title=\"Прикрепить файл\" alt=\"Прикрепить файл\" src=\"images/blocks/Files.gif\" border=0></a> <a href=\"index.php?name=$module_name&op=editpost&id=$id\"><img title=\"Редактировать\" alt=\"Редактировать\" src=\"modules/$module_name/images/statuses/1.gif\" border=0></a></a> |";
	else $editmsg = "";
///1-2

	$user_avatar = ($uavatar && file_exists("".$adirectory."/".$uavatar."")) ? "<img src=\"".$adirectory."/".$uavatar."\" alt=\"$name\" title=\"$name\" />" : "<img src=\"".$adirectory."/00.gif\" alt=\"$name\" title=\"$name\" />";
	if ($usig != "") $signature = "".bb_decode($usig).""; else $signature = "";
	for($i = 1; $i < 11; $i++) {
		$srank = 'rank'.$i;
		$trank = 'rtitle'.$i;
		if($umessages>=$$srank) {
			$urank = $i;
			$titleurank = $$trank;
		}
	}
	if(empty($titleurank)) $titleurank = 'Гость';
 	if ($umoder == 1) {
	$titleurank = $rtitle_moder;
	$urank = "moder";
	} elseif ($umoder == 2) {
	$titleurank = $rtitle_admin;
	$urank = "admin";
	}

	if ($urank == "") {$urank = "0";}
	if ($a%2 == 0) {
			$bgcolor_str = " class=\"bgcolor2\" " ;
		} else {
			$bgcolor_str = " class=\"bgcolor1\" " ;
		}
	$num = $_GET['pagenum'];
	if (isset($_GET['pagenum'])) $linkpost = "<a href=\"index.php?name=$module_name&op=showtopic&id=$tid&pagenum=$num#$a\">№$a</a>"; else $linkpost = "<a href=\"index.php?name=$module_name&op=showtopic&id=$tid#$a\">№$a</a>";

/*веха #3*/
/*
	$mkom++;
	if ($mkom==2)	{echo "<tr $bgcolor_str><td colspan=\"2\">
		<!-- Mestkom code BEGIN -->
			<center>
				<a href=\"http://www.mestkom.ru/asp/pay.asp?id_d=391269\" target=\"_blank\"><img src=\"http://www.exaccess.ru/images/arrow/grey_down.gif\" width=\"63\" height=\"16\" border=\"0\"></a><br>
				<script type=\"text/javascript\" src=\"http://static.exaccess.ru/asp/static_script.asp?id_d=391269\"></script>
			</center>
		<!-- Mestkom code END -->
	</td></tr><tr><td height=\"5\" class=\"bgcolor3\" colspan=\"2\"></td></tr>";
	}
*/

	echo "<tr $bgcolor_str><td width=\"150px\" align=\"center\" >"
	."<a name=\"$a\"></a><a href=\"javascript: InsertCode('name', '".$name."', '', '', 'area');\"><b>$name</b></a>"
	."</td>"
	."<td align=\"right\"  width=\"100%\" >"
	."".$editmsg." "._DATE.": ".formatdate($date)." | "._MESSAGE." $linkpost"
	."</td>"
	."</tr>"
	."<tr $bgcolor_str><td valign=\"top\" width=\"150px\" nowrap=\"nowrap\">"
	."<center>".$user_avatar."<img src=\"modules/$module_name/images/ranks/".$urank.".gif\" title=\"$titleurank\"><br />$titleurank</center>"._USER." №: $uid"
	."<br />Сообщений: ".$umessages
	."<br /><br /><a href=\"index.php?name=Account&".$infoUser."$name\" target=\"_blank\"><img src=\"images/info.gif\" border=\"0\" align=\"left\"></a><a href=\"javascript:scroll(0,0);\"><img src=\"modules/$module_name/images/up.gif\" align=\"right\" border=\"0\" hspace=\"2\"></a><a href=\"javascript:scroll(0,10000000);\"><img src=\"modules/$module_name/images/down.gif\"  align=\"right\" border=\"0\" hspace=\"1\"></a>"
	."</td>"
	."<td valign=\"top\">";

///2-1

if ($_SESSION['bb']!="") {	$message = viewword($message);
	$bb = "#\[KIOFGRENSD\](.*?)\[/KIOFGRENSD\]#si";
	$html = "<font style=\"color: red; font-weight: bold; background-color: #ff0;\">\\1</font>";
	$message = preg_replace($bb, $html, $message);
}

	echo "<table height=\"150px\" width=\"100%\" border=\"0\"><tr><td valign=\"top\">".nl2br(bb_decode($message))."";
	if ($filn[0]!="") {
		echo "<font class=\"smalla\"><br><br><i>Прикрепленные файлы: <a target=\"blank_\" class=\"smalla\" href=\"".$filn[0]."\">".basename($filn[0])."</a>";
		echo " ".filesize($filn[0])." байт<i></font>";
	}
	echo "</td></tr>";
///2-2

	if ($signature!="") {echo "<tr><td valign=\"bottom\"><hr>".$signature."</td></tr>";}
	echo "</table>"
	."</td>"
	."</tr>"
	."<tr><td height=\"5\" class=\"bgcolor3\" colspan=\"2\"></td></tr>";
	$a++;
	unset($titleurank);
	}
	$tid = $_GET['id'];
	$result3 = $db->sql_query("SELECT t1.uname, t1.guest, t1.url, t2.user_id, t2.user_name, t3.user_moder FROM ".$prefix."_session AS t1, ".$prefix."_users AS t2, ".$prefix."_forums_users AS t3 WHERE t1.uname = t2.user_name AND t2.user_id = t3.user_id AND t1.url Like '/index.php?name=$module_name&amp;op=showtopic&amp;id=$tid%' AND t1.guest !=1");
if ($db->sql_numrows($result3) > 0) {
	echo "<tr><td class=\"bgcolor1\" colspan=\"2\">"._TREAD.": ";
	$data = $db->sql_fetchrowset($result3);
	for($i = 0, $c = $db->sql_numrows($result3); $i < $c; $i++) {
		if ($data[$i]['guest'] == 2 && $data[$i]['user_moder'] == 2) {
			$utitle = _AUTHOR;
			$spanstyle = "style=\"color: red;\"";
		} elseif ($data[$i]['guest'] == 0) {
			$utitle = _USER;
			$spanstyle = "";
		}
		echo "<a href=\"index.php?name=Account&op=".check_uinf()."=".$data[$i][0]."\"><span ".$spanstyle." title=\"".$utitle."\">".$data[$i][0]."</span></a>";
		if(($i+1) != $c) {
			echo ", ";
		}

	}
	echo "</td></tr>";
}
	echo "<tr><td height=\"5\" class=\"bgcolor3\" colspan=\"2\">";
	echo "</td></tr>";
	if($closed != 1) {
	if (is_user($user)) {
	if ($tid == "" OR $tid == "0") Header("Location: index.php?name=$module_name");

	echo "<form name=\"post\" action=\"index.php?name=$module_name\" method=\"post\">"
	."<tr>"
	."<td class=\"bgcolor1\" align=\"center\" colspan=\"2\"><table align=\"center\"><tr><td>";

/*веха #2*/
/*
	if ($tid==227) {
		OpenTable();
			echo "<center><font color=red><b>Спасибо, что не пишите чушь и оскорбления в чей-либо адрес!</b></font></center>";
		CloseTable();
	}
*/

	echo "<a name=\"answer\"></a>".textarea("1", "comment", replace_break($cmsg), "Forums", "5");

	if (function_exists("get_smilie")) {echo get_smilie();}
	echo "<input type=\"hidden\" name=\"tid\" value=\"$tid\">"
	."<input type=\"hidden\" name=\"cid\" value=\"$cid\">"
	."<input type=\"hidden\" name=\"op\" value=\"savenewpost\">"
	."<input type=\"submit\" value=\""._NEWPOST."\" style=\"width: 200px;\">"
	."<input type=\"reset\" value=\""._RESET."\" style=\"width: 200px;\">"
	."</td></tr></td></tr></table></form></table><br />";
	} else {
		echo "<tr>"
		."<td class=\"bgcolor1\" align=\"center\" colspan=\"2\">"
		."<center><br /><a href=\"index.php?name=Account\"><span class=\"option\">"._PNEWLOCK."</span></a><br /><br /></center></td></tr></table><br />";
	}
	} else {
		echo "</td></tr></table><br />";
	}
echo "</td></tr></table>";

/*	list($numposts) = $db->sql_fetchrow($db->sql_query("SELECT Count(id) FROM ".$prefix."_forums_posts WHERE tid='$tid'"));
	$numpages = ceil($numposts/$postspg);
	num_page($module_name, $numposts, $numpages, $postspg, "op=showtopic&id=$tid&");
*/
echo $num_pag;

include("footer.php");
}


function viewword($sourse) {
session_start();
$bb = explode(" ", trim($_SESSION['bb']));
$html = "[KIOFGRENSD]\\0[/KIOFGRENSD]";

//=========================================

	$sourse = nobbf($bb, $html, $sourse);
	$mass22 = explode ("[nobb]", "JKEVPFBGSV".$sourse."JKEVPFBGSV");
	$sourse = "";
	foreach ($mass22 as $key6 => $val7) {
		$mass23 = explode ("[/nobb]", $val7);
		if ($mass23[1] == "") {
			$sourse .= $mass23[0];
		} else {
			$sourse .= "".$mass23[0]."".$mass23[1];
		}
	}
	$sourse = substr($sourse, 10, -10);
	return $sourse;
}

function nobbf($bb, $html, $text_in) {
	$mass2 = explode ("[nobb]", "JKEVPFBGSV".$text_in."JKEVPFBGSV");
	$text_in = "";
	foreach ($mass2 as $key1 => $val1) {
		$mass3 = explode ("[/nobb]", $val1);
		if ($mass3[1] == "") {
			$mass3[0] = nobbfcode($bb, $html, $mass3[0]);
			$text_in .= $mass3[0];
		} else {
			$mass3[1] = nobbfcode($bb, $html, $mass3[1]);
			$text_in .= "[nobb]<code style=\"color: #000000; line-height: 16px; background-color: #E6E6E6; padding: 2px;\">".$mass3[0]."</code>[/nobb]".$mass3[1];
		}
	}
	$text_in = substr($text_in, 10, -10);
	return $text_in;
}

function nobbfcode($bb, $html, $sourse2) {
	$mass = explode ("[code]", "JKEVPFBGSV".$sourse2."JKEVPFBGSV");
	$sourse2 = "";
	foreach ($mass as $key => $val) {
		$mass1 = explode ("[/code]", $val);
		if ($mass1[1] == "") {
			$mass1[0] = nobbfphp($bb, $html, $mass1[0]);
			$sourse2 .= $mass1[0];
		} else {
		$mass1[1] = nobbfphp($bb, $html, $mass1[1]);
			$sourse2 .= "[code]".$mass1[0]."[/code]".$mass1[1];
		}
	}
	$sourse2 = substr($sourse2, 10, -10);
	return $sourse2;
}

function nobbfphp($bb, $html, $text_in2) {
	$mass4 = explode ("[php]", "JKEVPFBGSV".$text_in2."JKEVPFBGSV");
	$text_in2 = "";
	foreach ($mass4 as $key2 => $val2) {
		$mass5 = explode ("[/php]", $val2);
		if ($mass5[1] == "") {
			$mass5[0] = preg_replace($bb, $html, $mass5[0]);
			$text_in2 .= $mass5[0];
		} else {
			$mass5[1] = preg_replace($bb, $html, $mass5[1]);
			$text_in2 .= "[php]".$mass5[0]."[/php]".$mass5[1];
		}
	}
	$text_in2 = substr($text_in2, 10, -10);
	return $text_in2;
}






///3-1
function addfiles($id) {
global $user, $userinfo, $db, $prefix, $module_name;
include ("header.php");
$id = isset($_REQUEST['id']) ? intval($_REQUEST['id']) : "0";
menu();
	getusrinfo($user);

	list($userinfo['user_moder'], $userinfo['user_messages'], $userinfo['user_rank']) = $db->sql_fetchrow($db->sql_query("SELECT user_moder, user_messages, user_rank FROM ".$prefix."_forums_users WHERE user_id = '$user[0]'"));

	$result = $db->sql_query("SELECT id, name, message FROM ".$prefix."_forums_posts WHERE id='$id'");
	list($id, $uname, $oldmessage) = $db->sql_fetchrow($result);
	if ($uname != $user[1] && $userinfo['user_moder'] == 0) {Header("Location: index.php?error=403");die();}

	echo "<br>";
	OpenTable();
	echo "Допустимые расширения <b>gif, jpg, jpeg, png, zip, rar</b><br>Максимальный размер (объем) <b>2 097 152 байт</b><br>Максимальный размер картинки <b>2 000 x 2 000 px</b>";
	$filn = glob("uploads/SSDForums/SSDForums-".$id.".*");
	if ($filn[0]!="") {
		echo "<br><br><font color=\"red\">Внимание! этот топик уже содержит прикрепленный файл и он будет удален при загрузке нового файла!</font>";
	}
	CloseTable();
	echo "<br>";
	OpenTable();
	echo "<form name=\"post\" enctype=\"multipart/form-data\" action=\"index.php?name=$module_name\" method=\"post\">"
	."<tr><td>Загрузить архив или картинку:</td><td><input name=\"userfile\" type=\"file\" size=\"65\" style=\"width:400px\"></td></tr>"
	."<tr><td colspan=\"2\" align=\"center\"><input type=\"hidden\" name=\"id\" value=\"$id\">"
	."<input type=\"hidden\" name=\"op\" value=\"saveaddfiles\">"
	."<input type=\"submit\" value=\"Загрузить\" style=\"width: 200px;\"></form>"
	."</td></tr></form>";
	CloseTable();

	include("footer.php");
}

function saveaddfiles($id) {
global $prefix, $db, $module_name, $user, $postspg, $version, $conf, $stop;
	if(!$version) {
		$version = &$conf['version'];
	}
	$id = isset($_REQUEST['id']) ? intval($_REQUEST['id']) : "0";
	$result = $db->sql_query("SELECT id, name, message FROM ".$prefix."_forums_posts WHERE id='$id'");
	list($id, $uname, $oldmessage) = $db->sql_fetchrow($result);
	if ($uname != $user[1] && $userinfo['user_moder'] == "0") {Header("Location: index.php?error=403");die();}
	$id = intval($id);
	include("header.php");
	menu();
	$filename = upload("uploads/SSDForums", "gif,jpg,jpeg,png,zip,rar", "2097152", "SSDForums", "2000", "2000");
	if ($stop) {
		warning("".$stop."<br /><br />"._GOBACK."", "", "", 1);
	} else {
	$filename1 = preg_replace ("#SSDForums-(.*?)\.(.*?)#si", "SSDForums-".$id.".\\2", $filename);
	foreach (glob("uploads/SSDForums/SSDForums-".$id.".*") as $filename2) {@unlink ("".$filename2."");	}
	rename("uploads/SSDForums/".$filename."", "uploads/SSDForums/".$filename1."");

	list($tid) = $db->sql_fetchrow($db->sql_query("SELECT tid FROM ".$prefix."_forums_posts WHERE id = '$id'"));
	list($postcount) = $db->sql_fetchrow($db->sql_query("SELECT Count(id) FROM ".$prefix."_forums_posts WHERE id<='$id' AND tid='$tid'"));
	$numcount = ceil($postcount/$postspg);
	Header("Location: index.php?name=$module_name&op=showtopic&id=$tid&pagenum=$numcount#$postcount");
	}
	include("footer.php");
}

function deladdfiles($id) {
global $user, $userinfo, $db, $prefix, $module_name, $postspg;
include ("header.php");
$id = isset($_REQUEST['id']) ? intval($_REQUEST['id']) : "0";
menu();
	getusrinfo($user);

	list($userinfo['user_moder'], $userinfo['user_messages'], $userinfo['user_rank']) = $db->sql_fetchrow($db->sql_query("SELECT user_moder, user_messages, user_rank FROM ".$prefix."_forums_users WHERE user_id = '$user[0]'"));

	$result = $db->sql_query("SELECT id, name, message FROM ".$prefix."_forums_posts WHERE id='$id'");
	list($id, $uname, $oldmessage) = $db->sql_fetchrow($result);
	if ($uname != $user[1] && $userinfo['user_moder'] == 0) {Header("Location: index.php?error=403");die();}
	list($tid) = $db->sql_fetchrow($db->sql_query("SELECT tid FROM ".$prefix."_forums_posts WHERE id = '$id'"));
	list($postcount) = $db->sql_fetchrow($db->sql_query("SELECT Count(id) FROM ".$prefix."_forums_posts WHERE id<='$id' AND tid='$tid'"));
	$numcount = ceil($postcount/$postspg);

	OpenTable();
		echo "<center><font color=\"red\"><b>Удалить прикрепленный файл?<br>Больше сообщений и предупреждений не будет!</b></font><br><br><hr noshade=\"noshade\" size=\"2\" width=\"200\"><br>";
		echo "<a href=\"index.php?name=$module_name&op=deladdfilesyes&id=$id\"><font color=\"red\">[Да]</font></a> | <a href=\"index.php?name=$module_name&op=showtopic&id=$tid&pagenum=$numcount#$postcount\">[Нет]</a><br><br>";
	CloseTable();
	include("footer.php");
}


function deladdfilesyes($id) {
global $user, $userinfo, $db, $prefix, $module_name, $postspg;
$id = isset($_REQUEST['id']) ? intval($_REQUEST['id']) : "0";
include ("header.php");
getusrinfo($user);
	OpenTable();
	list($userinfo['user_moder'], $userinfo['user_messages'], $userinfo['user_rank']) = $db->sql_fetchrow($db->sql_query("SELECT user_moder, user_messages, user_rank FROM ".$prefix."_forums_users WHERE user_id = '$user[0]'"));

	$result = $db->sql_query("SELECT id, name, message FROM ".$prefix."_forums_posts WHERE id='$id'");
	list($id, $uname, $oldmessage) = $db->sql_fetchrow($result);
	if ($uname != $user[1] && $userinfo['user_moder'] == 0) {Header("Location: index.php?error=403");die();}
	foreach (glob("uploads/SSDForums/SSDForums-".$id.".*") as $filename2) {@unlink ("".$filename2."");	}
	list($tid) = $db->sql_fetchrow($db->sql_query("SELECT tid FROM ".$prefix."_forums_posts WHERE id = '$id'"));

	list($tid) = $db->sql_fetchrow($db->sql_query("SELECT tid FROM ".$prefix."_forums_posts WHERE id = '$id'"));
	list($postcount) = $db->sql_fetchrow($db->sql_query("SELECT Count(id) FROM ".$prefix."_forums_posts WHERE id<='$id' AND tid='$tid'"));
	$numcount = ceil($postcount/$postspg);
	Header("Location: index.php?name=$module_name&op=showtopic&id=$tid&pagenum=$numcount#$postcount");
	CloseTable();
	include("footer.php");

}
///3-2


function newtopic() {
global $prefix, $db, $user, $module_name, $pagetitle, $defis, $conf, $confu;
	if(!$version) {
		$version = &$conf['version'];
		$defis = &$conf['defis'];
		$adirectory = &$confu['adirectory'];
	};
	$cid = $_GET['cid'];
	if ($cid == "" OR $cid == "0") Header("Location: index.php?name=$module_name");
	list($ctitle) = $db->sql_fetchrow($db->sql_query("SELECT title FROM ".$prefix."_forums_cats WHERE id = '$cid'"));
	$pagetitle = "".$defis." "._FORUM." ".$defis." $ctitle ".$defis." "._NEWTOPIC."";
include("header.php");
menu();
	echo "<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"middle\"><tr><td><table border=\"0\" cellpadding=\"3\" cellspacing=\"1\" width=\"100%\" class=\"bgcolor4\"><form name=\"post\" action=\"index.php?name=$module_name\" method=\"post\">"
	."<tr><td class=\"bgcolor1\" colspan=\"6\"><a href=\"index.php?name=$module_name\"><b>"._FORUM."</b></a> -> <a href=\"index.php?name=$module_name&op=showforum&id=$cid\"><b>$ctitle</b></a> -> "._NEWTOPIC."</td></tr>";
	if (is_user($user)) {
	echo "<tr><td align=\"right\" class=\"bgcolor1\">"._TNAME.":</td><td class=\"bgcolor1\"><input type=\"text\" name=\"title\" style=\"width:400px\"></td></tr>"
	."<tr><td align=\"right\" class=\"bgcolor1\">"._MESSAGE.":</td><td class=\"bgcolor1\">;".textarea("1", "comment", replace_break($cmsg), "Forums", "5");

	if (function_exists("get_smilie")) {echo get_smilie();}

	echo "</td></tr>"
	."<tr><td colspan=\"2\" align=\"center\" class=\"bgcolor1\">"
	."<input type=\"hidden\" name=\"cid\" value=\"$cid\">"
	."<input type=\"hidden\" name=\"op\" value=\"savenewtopic\">"
	."<input type=\"submit\" value=\""._NEWTOPIC."\"></td></tr></form>";
	} else
	{
	echo "<tr><td class=\"bgcolor1\"><center><br /><a href=\"index.php?name=Account\"><span class=\"option\">"._TNEWLOCK."</span></a><br /><br /></center></td></tr>";
	}
	echo "</table></td></tr></table>";
include("footer.php");
}

function editpost($id) {
global $user, $userinfo, $db, $prefix, $module_name;
include ("header.php");
menu();
	getusrinfo($user);

	list($userinfo['user_moder'], $userinfo['user_messages'], $userinfo['user_rank']) = $db->sql_fetchrow($db->sql_query("SELECT user_moder, user_messages, user_rank FROM ".$prefix."_forums_users WHERE user_id = '$user[0]'"));

	$id = isset($_REQUEST['id']) ? intval($_REQUEST['id']) : "0";
	$result = $db->sql_query("SELECT id, name, message FROM ".$prefix."_forums_posts WHERE id='$id'");
	list($id, $uname, $oldmessage) = $db->sql_fetchrow($result);
	if ($uname != $user[1] && $userinfo['user_moder'] == 0) {Header("Location: index.php?error=403");die();}

	list($tid) = $db->sql_fetchrow($db->sql_query("SELECT tid FROM ".$prefix."_forums_posts WHERE id = '$id'"));
	list($cid, $ttitle) = $db->sql_fetchrow($db->sql_query("SELECT cid, title FROM ".$prefix."_forums_topics WHERE id = '$tid'"));
	list($ctitle) = $db->sql_fetchrow($db->sql_query("SELECT title FROM ".$prefix."_forums_cats WHERE id = '$cid'"));
	list($pid) = $db->sql_fetchrow($db->sql_query("SELECT id FROM ".$prefix."_forums_posts WHERE tid='$tid' ORDER BY id ASC"));
	if ($pid == $id) $tedit = "<input type=\"text\" name=\"title\" value=\"$ttitle\" style=\"width:400px\"><br>";
	echo "<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"middle\"><tr><td><table border=\"0\" cellpadding=\"3\" cellspacing=\"1\" align=\"center\" class=\"bgcolor4\" width=\"100%\">"
	."<tr><td class=\"bgcolor1\" colspan=\"6\"><a href=\"index.php?name=$module_name\"><b>"._FORUM."</b></a> -> <a href=\"index.php?name=$module_name&op=showforum&id=$cid\"><b>$ctitle</b></a> -> <b><a href=\"index.php?name=$module_name&op=showtopic&id=$tid\">$ttitle</a></b> -> "._EDITPOST."$id</td></tr>"
	."<form name=\"post\" action=\"index.php?name=$module_name&op=saveeditpost\" method=\"post\">"
	."<tr>"
	."<td class=\"bgcolor1\" align=\"center\">"
	."".$tedit.""
	.textarea("1", "comment", replace_break($oldmessage), "Forums", "5");

	if (function_exists("get_smilie")) {echo get_smilie();}

	echo "<input type=\"hidden\" name=\"id\" value=\"$id\">"
	."<input type=\"hidden\" name=\"op\" value=\"saveeditpost\">"
	."<input type=\"submit\" value=\""._POSTEDIT."\" style=\"width: 200px;\">"
	."<input type=\"reset\" value=\""._CANCELEDIT."\" style=\"width: 200px;\">"
	."</td></tr></form></table></td></tr></table>";
include("footer.php");
}

function update() {
global $prefix, $db, $user, $rank1, $rank2, $rank3, $rank4, $rank5, $rank6, $rank7, $rank8, $rank9, $rank10;
	if (is_user($user)) {
	$name = $user[1];
	$userposts = $db->sql_numrows($db->sql_query("SELECT id FROM ".$prefix."_forums_posts WHERE name='$name'"));
	if ($userposts == $rank1) $rank = $rank1;
	if ($userposts == $rank2) $rank = $rank2;
	if ($userposts == $rank3) $rank = $rank3;
	if ($userposts == $rank4) $rank = $rank4;
	if ($userposts == $rank5) $rank = $rank5;
	if ($userposts == $rank6) $rank = $rank6;
	if ($userposts == $rank7) $rank = $rank7;
	if ($userposts == $rank8) $rank = $rank8;
	if ($userposts == $rank9) $rank = $rank9;
	if ($userposts == $rank10) $rank = $rank10;
	if ($rank) $db->sql_query("UPDATE ".$prefix."_forums_users  SET user_rank='$rank' WHERE user_id='$user[0]'");
	$db->sql_query("UPDATE ".$prefix."_forums_users  SET user_messages=user_messages+1 WHERE user_id='$user[0]'");
	}
}

function formatdate($date) {
$date = explode(" ", $date);
$time = explode(" ", $date[1]);
$time = explode(":", $date[1]);
$date = explode("-", $date[0]);
$date = "".$date[2].".".$date[1].".".$date[0]."";
return "".$date.", "._IN." ".$time[0].":".$time[1]."";
}

function savenewtopic($cid, $title, $comment) {
global $prefix, $db, $user, $module_name;
	if(!is_user($user)) {
		Header("Location: index.php?error=403");
		die();
	}
	$name = $user[1];
	$ip = getenv("REMOTE_ADDR");
	$comment = text_filter($comment, 2);
	$title = text_filter($title);
	if ($title == "") $stop = ""._CERROR1."";
	if ($comment == "") $stop = ""._CERROR1."";
	if ($cid == "" OR $cid == "0") {
	Header("Location: index.php?name=$module_name");
	} elseif ($stop) {
	include("header.php");
menu();
	warning("".$stop."<br /><br />"._GOBACK."", "", "", 1);
	include("footer.php");
	} else {
	$db->sql_query("INSERT INTO ".$prefix."_forums_topics VALUES (NULL, '$cid', '".date('Y-m-d H:i:s')."', '$name', '$title', '0','0', '-1', '0','$name')");
	list($tid) = $db->sql_fetchrow($db->sql_query("SELECT id FROM ".$prefix."_forums_topics ORDER BY id DESC"));
	$db->sql_query("INSERT INTO ".$prefix."_forums_posts VALUES (NULL, '$tid', '".date('Y-m-d H:i:s')."', '$name', '$ip', '$comment')");
	$db->sql_query("UPDATE ".$prefix."_forums_cats SET totaltopics=totaltopics+1 WHERE id='$cid'");
	update();
	Header("Location: index.php?name=$module_name&op=showtopic&id=$tid");
	}
}

function savenewpost($tid, $cid, $comment) {
global $prefix, $db, $user, $module_name, $postspg;
	if(!is_user($user)) {
		Header("Location: index.php?error=403");
		die();
	}
	$name = $user[1];
	$ip = getenv("REMOTE_ADDR");
	$comment = text_filter($comment, 2);
	if ($comment == "") $stop = ""._CERROR1."";
	if ($tid == "" OR $tid == "0") {
	Header("Location: index.php?name=$module_name");
	} elseif ($stop) {
	include("header.php");
	menu();
	warning("".$stop."<br /><br />"._GOBACK."", "", "", 1);
	include("footer.php");
	} else {
	$db->sql_query("INSERT INTO ".$prefix."_forums_posts VALUES (NULL, '$tid', '".date('Y-m-d H:i:s')."', '$name', '$ip', '$comment')");
	$db->sql_query("UPDATE ".$prefix."_forums_topics SET totalposts=totalposts+1, date='".date('Y-m-d H:i:s')."', lastposter_name='$name' WHERE id='$tid'");
	$db->sql_query("UPDATE ".$prefix."_forums_cats SET totalposts=totalposts+1 WHERE id='$cid'");
	update();
	list($postcount) = $db->sql_fetchrow($db->sql_query("SELECT Count(id) FROM ".$prefix."_forums_posts WHERE tid='$tid'"));
	$numcount = ceil($postcount/$postspg);
	Header("Location: index.php?name=$module_name&op=showtopic&id=$tid&pagenum=$numcount#$postcount");
	}
}

function saveeditpost($id, $uname, $title, $comment) {
global $prefix, $db, $module_name, $user, $postspg, $version, $conf;
	if(!$version) {
		$version = &$conf['version'];
	}
	$id = isset($_REQUEST['id']) ? intval($_REQUEST['id']) : "0";
	$result = $db->sql_query("SELECT id, name, message FROM ".$prefix."_forums_posts WHERE id='$id'");
	list($id, $uname, $oldmessage) = $db->sql_fetchrow($result);
	if ($uname != $user[1] && $userinfo['user_moder'] == "0") {Header("Location: index.php?error=403");die();}
	$id = intval($id);
	$uname = htmlspecialchars(substr($uname, 0, 25));
	$comment = text_filter($comment, 2);
	if ($comment == "") $stop = ""._CERROR1."";
	if ($stop) {
	include("header.php");
	menu();
	warning("".$stop."<br /><br />"._GOBACK."", "", "", 1);
	include("footer.php");
	}

	$comment .= "<br><br>[color=olive][size=9]_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _<br>[i]Отредактированно <b>".$user[1]."</b> ".date('d.m.Y', time())." г. в ".date('H:i:s', time())."[/i][/size][/color]";
	list($tid) = $db->sql_fetchrow($db->sql_query("SELECT tid FROM ".$prefix."_forums_posts WHERE id = '$id'"));
	$title = text_filter($title);
	if ($title) $db->sql_query("UPDATE ".$prefix."_forums_topics SET title='$title' WHERE id='$tid'");
	$db->sql_query("UPDATE ".$prefix."_forums_posts SET message='$comment' WHERE id='$id'");

	list($postcount) = $db->sql_fetchrow($db->sql_query("SELECT Count(id) FROM ".$prefix."_forums_posts WHERE id<='$id' AND tid='$tid'"));
	$numcount = ceil($postcount/$postspg);

	Header("Location: index.php?name=$module_name&op=showtopic&id=$tid&pagenum=$numcount#$postcount");
}

function deletepost($id, $postnum) {
global $prefix, $db, $user, $userinfo, $module_name, $postspg;
	getusrinfo($user);
	list($userinfo['user_moder']) = $db->sql_fetchrow($db->sql_query("SELECT user_moder FROM ".$prefix."_forums_users WHERE user_id = '$user[0]'"));

	if(!is_user($user)) {
		Header("Location: index.php?error=403");
		die();
	}

	if ($userinfo['user_moder'] == "0") {
		Header("Location: index.php?error=403");
		exit;
	}

	$id = isset($_REQUEST['id']) ? intval($_REQUEST['id']) : "0";
	list($tid) = $db->sql_fetchrow($db->sql_query("SELECT tid FROM ".$prefix."_forums_posts WHERE id='$id'"));
	list($cid) = $db->sql_fetchrow($db->sql_query("SELECT cid FROM ".$prefix."_forums_topics WHERE id='$tid'"));
	list($max) = $db->sql_fetchrow($db->sql_query("SELECT max(id) as id FROM ".$prefix."_forums_posts WHERE tid = ".$tid));
	list($mid) = $db->sql_fetchrow($db->sql_query("SELECT id FROM ".$prefix."_forums_posts WHERE tid='$tid' ORDER BY id ASC"));
	list($countid) = $db->sql_fetchrow($db->sql_query("SELECT Count(id) FROM ".$prefix."_forums_posts WHERE tid='$tid'"));

$postnum = intval($postnum) - 1;
$pagenum = ceil ($postnum / $postspg);

	if ($mid == $id) {
		$db->sql_query("UPDATE ".$prefix."_forums_users SET user_messages=user_messages-$countid WHERE user_id='$userinfo[0]'");
		$db->sql_query("UPDATE ".$prefix."_forums_topics SET totalposts=totalposts-1 WHERE id='$tid'");
		$db->sql_query("UPDATE ".$prefix."_forums_cats SET totaltopics=totaltopics-1, totalposts=totalposts-$countid+1 WHERE id='$cid'");
		$db->sql_query("DELETE FROM ".$prefix."_forums_topics WHERE id='$tid'");
		$db->sql_query("DELETE FROM ".$prefix."_forums_posts WHERE tid='$tid'");

/* Пересчет сообщений пользователей*/
$result = $db->sql_query("SELECT  COUNT(user_id) AS summ, user_id  FROM ".$prefix."_forums_posts INNER JOIN ".$prefix."_users ON (name = user_name) GROUP BY user_id");
	while (list($summ, $user_id) = $db->sql_fetchrow($result)) {
		$db->sql_query("UPDATE ".$prefix."_forums_users SET user_messages='$summ' WHERE user_id='$user_id'");
	}
/* Конец Пересчет сообщений пользователей*/
/* Пересчет количества постов в теме*/
$result = $db->sql_query("SELECT  COUNT(tid) AS summ, tid  FROM ".$prefix."_forums_posts GROUP BY tid");
	while (list($summ, $ttid) = $db->sql_fetchrow($result)) {
		$summ--;
		$db->sql_query("UPDATE ".$prefix."_forums_topics SET totalposts ='$summ' WHERE id='$ttid'");
	}
/* Конец Пересчет количества постов в теме*/

		Header("Location: index.php?name=$module_name");
	} else {
		$db->sql_query("UPDATE ".$prefix."_forums_users SET user_messages=user_messages-1 WHERE user_id='$userinfo[0]'");
		$db->sql_query("UPDATE ".$prefix."_forums_topics SET totalposts=totalposts-1 WHERE id='$tid'");
		$db->sql_query("UPDATE ".$prefix."_forums_cats SET totalposts=totalposts-1 WHERE id='$cid'");
		$db->sql_query("DELETE FROM ".$prefix."_forums_posts WHERE id='$id'");
		if($max == $_GET['id']) {
			$newmax = $db->sql_fetchrow($db->sql_query("SELECT max(id) as id FROM ".$prefix."_forums_posts WHERE tid = ".$tid));
			list($newname, $newdate) = $db->sql_fetchrow($db->sql_query("SELECT name, date FROM ".$prefix."_forums_posts WHERE id = ".$newmax['id']));
			$db->sql_query("UPDATE ".$prefix."_forums_topics SET lastposter_name = '".$newname."', date = '".$newdate."' WHERE id = ".$tid);
		}

/* Пересчет сообщений пользователей*/
$result = $db->sql_query("SELECT  COUNT(user_id) AS summ, user_id  FROM ".$prefix."_forums_posts INNER JOIN ".$prefix."_users ON (name = user_name) GROUP BY user_id");
	while (list($summ, $user_id) = $db->sql_fetchrow($result)) {
		$db->sql_query("UPDATE ".$prefix."_forums_users SET user_messages='$summ' WHERE user_id='$user_id'");
	}
/* Конец Пересчет сообщений пользователей*/
/* Пересчет количества постов в теме*/
$result = $db->sql_query("SELECT  COUNT(tid) AS summ, tid  FROM ".$prefix."_forums_posts GROUP BY tid");
	while (list($summ, $ttid) = $db->sql_fetchrow($result)) {
		$summ--;
		$db->sql_query("UPDATE ".$prefix."_forums_topics SET totalposts ='$summ' WHERE id='$ttid'");
	}
/* Конец Пересчет количества постов в теме*/

		Header("Location: index.php?name=$module_name&op=showtopic&id=$tid&pagenum=$pagenum#$postnum");
	}
}

function theme($action,$id) {
	global $db,$prefix,$module_name,$user;
	$_GET['id'] != '' ? $id = $_GET['id'] : $id = 0;
	$action = $_GET['action'];
	if(!$_GET['id'] OR intval($_GET['id']) < 1 OR !is_user($user)) {
		header("Location: index.php?name=$module_name");
		exit;
	}
	$info = $db->sql_fetchrow($db->sql_query("SELECT * FROM ".$prefix."_forums_users WHERE user_id = ".$user[0]));
	if($info['user_moder'] != 2) {
		Header("Location: index.php?error=403");
		exit;
	}
	$query = "SELECT cid FROM ".$prefix."_forums_topics WHERE id = ".$id;
	$cid = $db->sql_fetchrow($db->sql_query($query));
	switch ($action) {
		case 'open':
			$db->sql_query("UPDATE ".$prefix."_forums_topics SET closed = 0 WHERE id = ".$id);
		break;
		case 'close':
			$db->sql_query("UPDATE ".$prefix."_forums_topics SET closed = 1 WHERE id = ".$id);
		break;
		case 'status':
			$status = (int)$_GET['set'];
			$db->sql_query("UPDATE ".$prefix."_forums_topics SET status = ".$status." WHERE id = ".$id);
		break;
		case 'move':
			if(!$_POST['move']) {
				include("header.php");
				menu();
				$topicinfo = $db->sql_fetchrow($db->sql_query('SELECT * FROM '.$prefix.'_forums_topics WHERE id = '.$id));
				$categories = getCategories();
				OpenTable();
				echo '<center><font class="option">Переместить тему '.$topicinfo['title'].' в раздел:</font></center>';
				echo '<form action='.$_SERVER['PHP_SELF'].'?name='.$module_name.'&op=theme&action=move&id='.$id.' method=post>';
				echo '<br/><center><select name=move>';
				foreach ($categories[0] as $category) {
					$cat_prefix = $category['title'];
					$options_data = getCategories($category['id']);
					foreach ($options_data as $data) {
						if($topicinfo['cid'] != $data['id']) {
							echo "<option value=\"".$data['id']."\">".$cat_prefix."->".$data['title']."</option>";
						}
					}
				}

				$sql_result11 = $db->sql_query("SELECT id, title FROM ".$prefix."_forums_cats WHERE pid = -1 AND id<>".$topicinfo['cid']." ORDER BY id ");
				while (list($id11, $title11) = $db->sql_fetchrow($sql_result11)) {
					echo "<option value=\"".$id11."\">".$title11."</option>";
				};

				echo '</select>';
				echo '&nbsp;&nbsp;<input type="submit" value="Переместить" />';
				echo '</center></form>';
				CloseTable();
				include("footer.php");
			} else {
				$topicinfo = $db->sql_fetchrow($db->sql_query('SELECT * FROM '.$prefix.'_forums_topics WHERE id = '.(int)$_GET['id']));
				$dg_query = "UPDATE ".$prefix."_forums_cats SET totaltopics = totaltopics-1, totalposts = totalposts-".$topicinfo['totalposts']." WHERE id = ".$topicinfo['cid'];
				$up_query = "UPDATE ".$prefix."_forums_cats SET totaltopics = totaltopics+1, totalposts = totalposts+".$topicinfo['totalposts']." WHERE id = ".(int)$_POST['move'];
				$query = "UPDATE ".$prefix."_forums_topics SET cid = ".(int)$_POST['move']." WHERE id = ".(int)$_GET['id'];
				$db->sql_query($dg_query);
				$db->sql_query($up_query);
				$db->sql_query($query);
				$cid['cid'] = (int)$_POST['move'];
			}
		break;
			default:
				Header("Location: index.php?error=403");
				exit;
			break;

	}
	header("Location: index.php?name=$module_name&op=showforum&id=".$cid['cid']);
	exit;

}
function getCategories($id = 0) {
	global $db, $prefix;
	static $categories;
	if($categories == 'none') return false;
	if($categories) {
		if($id == '*') {
			return $categories;
        } else {
        	if($categories[$id]) {
            	return $categories[$id];
           } else {
				return false;
           }
       }
   } else {
		$sql_result = $db->sql_query("SELECT * FROM ".$prefix."_forums_cats ORDER BY sort");
		if(!$categories) {
			if($db->sql_numrows($sql_result) == 0) $categories = 'none';
		}
        $data = $db->sql_fetchrowset($sql_result);
        if(is_array($data)) {
        	foreach($data as $key=>$value) {
        		$categories[$value['pid']][] = $value;
        	}
        }
    	return getCategories($id);
    }
}
// Thanks to ob at babcom dot biz
// http://www.php.net/manual/en/function.array-search.php#69232
function ArraySearchRecursive($Needle,$Haystack,$NeedleKey="",
  $Strict=false,$Path=array()) {
  if(!is_array($Haystack))
    return false;
  foreach($Haystack as $Key => $Val) {
    if(is_array($Val)&&
       $SubPath=ArraySearchRecursive($Needle,$Val,$NeedleKey,
                                     $Strict,$Path)) {
      $Path=array_merge($Path,Array($Key),$SubPath);
      return $Path;
    }
    elseif((!$Strict&&$Val==$Needle&&
            $Key==(strlen($NeedleKey)>0?$NeedleKey:$Key))||
            ($Strict&&$Val===$Needle&&
             $Key==(strlen($NeedleKey)>0?$NeedleKey:$Key))) {
      $Path[]=$Key;
      return $Path;
    }
  }
  return false;
}

function searchforumstart() {
global $db, $prefix, $module_name;
include ("header.php");
menu();
OpenTable();
session_start();
unset($_SESSION['zapp']);
		$sql_result = $db->sql_query("SELECT text, rezult FROM ".$prefix."_forums_lastsearch ORDER BY date DESC");
		$num = $db->sql_numrows($sql_result);
echo "<b>Поиск по тексту сообщений.</b><br>Используйте <font color=\"#E500FB\"><b>AND</b></font> или <font color=\"#E500FB\"><b>OR</b></font> для поиска по <font color=\"#E500FB\"><b>И</b></font> и <font color=\"#E500FB\"><b>ИЛИ</b></font>, также разрешены круглые скобки.<br>Поиск осуществляется по части слова.<br>
<br><b>Примеры:</b><br>
1. <font color=\"#E500FB\">модуль файлов</font> ищет оба слова в посте по И<br>
2. <font color=\"#E500FB\">модуль files</font> ищет оба слова в посте по И<br>
3. <font color=\"#E500FB\">модуль AND (файлов OR files)</font> ищет посты, содержащие <font color=\"#E500FB\">модуль И файлов</font> ИЛИ <font color=\"#E500FB\">модуль И files</font><br>
4. Правильнее искать <font color=\"#E500FB\">модул</font> - для того, что бы найти <font color=\"#E500FB\">модуль</font> и <font color=\"#E500FB\">модуля</font><br><br>";

if (intval($_GET['sstop']==1)) {echo "Не допускается поиск при длине строки менее 2-х символов, а так же при пустой строке поиска.";}

echo "<form action=\"index.php?name=$module_name&op=searchaddtop&num=$num\" method=\"post\"><input maxlength=\"150\" type=\"text\" name=\"search_word\" value=\"\" size=\"75\"><br><br><input type=\"submit\" title=\""._SEARCH."\" value=\""._SEARCH."\">";
CloseTable();

OpenTable();
echo "<b>20-ка последних запросов:</b><br>";
#		echo "<input type=\"hidden\" name=\"num\" value=\"$num\">";
		$i=0;
		while (list($textsaerch, $rezult) = $db->sql_fetchrow($result)) {
			$i++;
			echo "<a href=\"index.php?name=$module_name&op=searchaddtop&seanum=$i&num=$num\"><b>".$textsaerch."</b></a> <font color=\"#AAAAAA\">результатов: <b>".$rezult."</b></font><br>";
			$j="zapp".$i;
			$_SESSION[$j] = $textsaerch;
		};

CloseTable();
echo "</form>";
include("footer.php");
}

function searchaddtop() {
global $db, $prefix, $module_name;
#include ("header.php");
#menu();
session_start();
$seanum=intval($_GET['seanum']);
if ($seanum>0) {$seanum="zapp".$seanum;$_POST['search_word'] = $_SESSION[$seanum];}
if ($_POST['search_word']=="") {Header("Location: index.php?name=$module_name&op=searchforumstart");}
#pre ($_POST);
#pre($_GET);
$num = intval ($_GET['num']);
#session_destroy();
	$_SESSION['zapp'] = $_POST['search_word'];
	$search_word = strip_tags(urldecode($_POST['search_word']));
	$search_word = htmlspecialchars(trim($search_word), ENT_QUOTES);

	$search_word_tmp = str_replace("(", "", $search_word);
	$search_word_tmp = str_replace(")", "", $search_word_tmp);
	if (strlen(trim($search_word_tmp))<3) {
		Header("Location: index.php?name=$module_name&op=searchforumstart&sstop=1");
		die();
	}

if ($num>(20-1)) {
			$db->sql_query("DELETE FROM ".$prefix."_forums_lastsearch ORDER BY date ASC Limit 1");
}

			$search_word = str_replace("  ", " ", $search_word);
			$search_word = str_replace("  ", " ", $search_word);
			$search_word = str_replace("(", " ( ", $search_word);
			$search_word = str_replace(")", " ) ", $search_word);
			$mass_sea = explode (" ", $search_word);

			$zap = "";
			foreach ($mass_sea as $key => $val) {
			if (trim($val)=="(" OR trim($val)==")" OR trim($val)=="AND" OR trim($val)=="OR") {
				$zap .= " ".$val." ";
			} elseif (trim($val)!="" AND strlen(trim($val))>2) {
				$zap .= " ".$prefix."_forums_posts.message LIKE '%".$val."%' ";
			}
			}
			$zap = str_replace("  ", " ", $zap);
			$zap = str_replace("  ", " ", $zap);
			$zap = str_replace("' ".$prefix."_forums_posts.message", "' AND ".$prefix."_forums_posts.message", $zap);

		$numtopics = $db->sql_numrows($db->sql_query("SELECT tid FROM  ".$prefix."_forums_posts  WHERE $zap GROUP By tid "));

$nums = $db->sql_numrows($db->sql_query("SELECT rezult FROM  ".$prefix."_forums_lastsearch  WHERE text='$search_word' "));
#echo "*****".htmlspecialchars($zap);
	$search_word_tmp = str_replace("(", "", $zap);
	$search_word_tmp = str_replace(")", "", $search_word_tmp);
	if (strlen(trim($search_word_tmp))<3) {
		Header("Location: index.php?name=$module_name&op=searchforumstart&sstop=1");
		die();
	}

if ($nums<1) {
	$db->sql_query("INSERT INTO ".$prefix."_forums_lastsearch (date, text, rezult) VALUES ('".date('Y-m-d H:i:s')."', '$search_word', '$numtopics')");
} else {
	$db->sql_query("UPDATE ".$prefix."_forums_lastsearch SET date='".date('Y-m-d H:i:s')."', rezult='$numtopics' WHERE text='$search_word'");
}
/*
OpenTable();
echo "<b>Последние запросы:</b><br><br>";
		$sql_result = $db->sql_query("SELECT text FROM ".$prefix."_forums_lastsearch ORDER BY date DESC");
		$num = $db->sql_numrows($sql_result);
		echo "<input type=\"hidden\" name=\"num\" value=\"$num\">";
		while (list($textsaerch) = $db->sql_fetchrow($result)) {
			echo $textsaerch."<br>";
		};
CloseTable();
*/
#pre ($_GET);
#pre ($_POST);
#pre ($_SESSION);
Header("Location: index.php?name=$module_name&op=showsearch");
#include("footer.php");
}


switch($op) {
    default:
    forums();
    break;

    case "showforum":
    showforum($id);
    break;

    case "showtopic":
    showtopic($id);
    break;

    case "newtopic":
    newtopic();
    break;

    case "savenewtopic":
    savenewtopic($cid, $title, $comment);
    break;

    case "savenewpost":
    savenewpost($tid, $cid, $comment);
    break;

    case "editpost":
    editpost($id);
    break;

    case "saveeditpost":
    saveeditpost($id, $uname, $title, $comment);
    break;

    case "deletepost":
    deletepost($id, $postnum);
    break;

    case "theme":
    theme($action,$id);
    break;

///4-1
    case "addfiles":
    addfiles($id);
    break;

    case "saveaddfiles":
    saveaddfiles($id);
    break;

    case "deladdfiles":
    deladdfiles($id);
    break;

    case "deladdfilesyes":
    deladdfilesyes($id);
    break;
///4-2

    case "searchforumstart":
	searchforumstart();
    break;

    case "showsearch":
	showsearch();
    break;

    case "searchaddtop":
	searchaddtop();
    break;
}

?>