<?php
error_reporting(0);

if(isset($_POST['ver'])) $_GET['ver'] = $_POST['ver'];

include("config.php");
include("./includes/".$ver."/banned");

$bots = file("bots/bots.dat");

$nocache = rand(10000, 99999);

list($msec, $sec) = explode(chr(32), microtime()); 
$headtime = $sec + $msec;

switch($ver)
{
////////////////////////////////////////////////////////
//WML VERSION
////////////////////////////////////////////////////////
case 'wml':
header("Content-type:text/vnd.wap.wml; charset=utf-8");
header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
header("Cache-Control: no-cache, must-revalidate");

$q = mysql_query("SELECT `id` FROM `chat_banned` WHERE `ip` = '".getenv('REMOTE_ADDR')."' AND `ua` = '".htmlspecialchars(getenv('HTTP_USER_AGENT'))."';");

if(mysql_num_rows($q) != 0)
{
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
echo "<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.3//EN\" \"http://www.wapforum.org/DTD/wml13.dtd\"><wml>\n";
echo "<card title=\"ERROR\"><p align=\"center\">\n";
echo "Вы забанены на этом чате.<br/>\n";
list($msec, $sec) = explode(chr(32), microtime());
echo "<br/><small>[".round(($sec+$msec)-$headtime,5)."] sec</small><br/>\n";
echo "</p></card></wml>";
exit();
}

//AUTH
$id = intval($_GET['id']);
$password = mysql_escape_string($_GET['password']);
$q = mysql_query("SELECT `nickname`, `level`, `security`, `fsize`, `translit`, `smiles`, `refresh`, `msgs`, `kick`, `moder`, `reason` FROM `chat_users` WHERE `id` = '".$id."' AND `password` = '".$password."';");
if(mysql_num_rows($q) == 0)
{
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
echo "<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.3//EN\" \"http://www.wapforum.org/DTD/wml13.dtd\"><wml>\n";
echo "<card title=\"ERROR\" ontimer=\"index.php?ver=wml\"><timer value=\"15\"/><p align=\"left\">\n";
echo "<small>Ошибка авторизации!<br/>\n";
list($msec, $sec) = explode(chr(32), microtime());
echo "<br/>[".round(($sec+$msec)-$headtime,5)."] sec<br/>\n";
echo "</small></p></card></wml>";
exit();
}
else
{
$user = mysql_fetch_array($q);
$nickname = $user['nickname'];
$smiles = $user['smiles'];
$translit  = $user['translit'];
$msgs  = $user['msgs'];
$refresh = $user['refresh'];
$fsize = $user['fsize'];
$security  = $user['security'];
$level = $user['level'];
$kick = $user['kick'];
$moder = $user['moder'];
$reason = $user['reason'];
$refresh = $refresh * 10;
}
//END AUTH

if(!isset($_POST['key']))
{
if(preg_match("/[^0-9a-zA-Z_]+/", $_GET['key']))
	{
	  echo "nedopustimye simvoly v klyu4e!";
	  exit;
	}
else
	{
	  $key = $_GET['key'];
	}
}
else
{
if(preg_match("/[^0-9a-zA-Z_]+/", $_POST['key']))
	{
	  echo "nedopustimye simvoly v klyu4e!";
	  exit;
	}
else
	{
	  $key = $_POST['key'];
	}
}

if(empty($key)) $key = 'public';

if($kick > time())
{
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
echo "<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.3//EN\" \"http://www.wapforum.org/DTD/wml13.dtd\"><wml>\n";
echo "<card title=\"Ошибка\" ontimer=\"rules.php?id=$id&amp;password=$password&amp;ver=wml\"><timer value=\"50\"/><p align=\"left\">\n";
echo "<small>Вы временно заблокированы модератором <u>$moder</u> на <u>".($kick - time())."</u> сек.<br/>\n";
echo "Причина: $reason<br/>\n";
list($msec, $sec) = explode(chr(32), microtime());
echo "<br/>[".round(($sec+$msec)-$headtime,5)."] sec<br/>\n";
echo "</small></p></card></wml>";
exit();
}

//ONLINE
$online = time() + 60;
$update = mysql_query("UPDATE `chat_users` SET `intim` = '".$online."', `key` = '".$key."', `ip` = '".getenv('REMOTE_ADDR')."', `ua` = '".htmlspecialchars(getenv('HTTP_USER_AGENT'))."' WHERE `id` = '".$id."';");
//END ONLINE

$sql = mysql_query("SELECT `nickname` FROM `chat_users` WHERE `key` = '".$key."' AND `intim` >= ".time().";");

echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
echo "<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.3//EN\" \"http://www.wapforum.org/DTD/wml13.dtd\"><wml>\n";
echo "<head><meta http-equiv=\"Cache-Control\" content=\"no-cache\" forua=\"true\"/></head>\n";
echo "<card id=\"chat\" title=\"Интимная\" ontimer=\"".$_SERVER['PHP_SELF']."?id=$id&amp;password=$password&amp;ver=wml&amp;key=$key&amp;nocache=$nocache\">\n";
echo "<timer value=\"$refresh\"/>\n";
echo "<do type=\"options\" name=\"add\" label=\"Сказать\"><go href=\"intim.php?id=$id&amp;password=$password&amp;ver=wml&amp;key=$key&amp;nocache=$nocache#add\" method=\"get\"/></do>\n";
echo "<do type=\"options\" name=\"refresh\" label=\"Обновить\"><go href=\"intim.php?id=$id&amp;password=$password&amp;ver=wml&amp;key=$key&amp;nocache=$nocache\" method=\"get\"/></do>\n";
echo "<do type=\"options\" name=\"online\" label=\"Онлайн\"><go href=\"online.php?id=$id&amp;password=$password&amp;ver=wml&amp;nocache=$nocache\" method=\"get\"/></do>\n";
echo "<do type=\"options\" name=\"key\" label=\"Сменить ключ\"><go href=\"key.php?id=$id&amp;password=$password&amp;ver=wml&amp;nocache=$nocache\" method=\"get\"/></do>\n";
echo "<do type=\"options\" name=\"menu\" label=\"Меню чата\"><go href=\"menu.php?id=$id&amp;password=$password&amp;ver=wml&amp;nocache=$nocache\" method=\"get\"/></do>\n";
echo "<p align=\"left\">\n";

if($fsize == 0)
{
$open_tag = "<small>";
$close_tag = "</small>";
}
if($fsize == 1)
{
$open_tag = "";
$close_tag = "";
}
if($fsize == 2)
{
$open_tag = "<big>";
$close_tag = "</big>";
}

echo $open_tag;

$c = 0;
echo "В этой комнате: ";
while($users = mysql_fetch_array($sql))
{
echo $users['nickname'].", ";
}
echo "<br/>\n";

echo "<a href='intim.php?id=$id&amp;password=$password&amp;ver=wml&amp;key=$key&amp;nocache=$nocache'>Обновить</a><br/>\n";
echo "<a href=\"#add\">Сказать</a><br/>\n";

if(isset($_POST['msg']))
{
mysql_query("SELECT * FROM `chat` WHERE `aid` = '".$id."' AND `seconds` > ".(time() - 20).";");
if(mysql_affected_rows() > 3)
{
$reason = "Вы были автоматически забанены системой за флуд (многократное повторение сообщений).";
mysql_query("UPDATE `chat_users` SET `kick` = ".(time() + 180).", `moder` = '".$bots[3]."', `reason` = '".$reason."';");
}

$msg = trim($_POST['msg']);

if(isset($_POST['uid']))
{
$sql = mysql_query("SELECT `nickname` FROM `chat_users` WHERE `id` = ".intval($_POST['uid']).";");
$nick = mysql_result($sql, 0);
}
else
{
$nick = "";
}

$msg = addslashes($msg);

	if($_POST['translit'] == "true")
	{
	$msg = str_replace("\"", "ъ", $msg);
	$msg = str_replace("'", "ь", $msg);

	$lat = array("CH", "ch", "SC", "sc", "YE", "ye", "YU", "yu", "YA", "ya", "YO", "yo");
	$rus = array("Ч", "ч", "Щ", "щ", "Э", "э", "Ю", "ю", "Я", "я", "Ё", "ё");
	$msg = str_replace($lat, $rus, $msg);

	$lat = array("A", "a", "B", "b", "C", "c", "D", "d", "E", "e", "F", "f", "G", "g", "H", "h", "I", "i", "J", "j", "K", "k", "L", "l", "M", "m", "N", "n", "O", "o", "P", "p", "R", "r", "S", "s", "T", "t", "U", "u", "V", "v", "H", "h", "Z", "z", "W", "w", "X", "x", "Y", "y");
	$rus = array("А", "а", "Б", "б", "Ц", "ц", "Д", "д", "Е", "е", "Ф", "ф", "Г", "г", "Х", "х", "И", "и", "Ж", "ж", "К", "к", "Л", "л", "М", "м", "Н", "н", "О", "о", "П", "п", "Р", "р", "С", "с", "Т", "т", "У", "у", "В", "в", "Х", "х", "З", "з", "Ш", "ш", "Ы", "ы", "Й", "й");
	$msg = str_replace($lat, $rus, $msg);
	}

$msg = htmlspecialchars($msg);

//SMILES
include "smiles.php";
$msg = preg_replace($smiles_array, $smile, $msg, 2);

if(!empty($nick))
{
$msg = "$nick, $msg";
}

$msg = iconv('utf-8', 'windows-1251', $msg);
$msg = substr($msg, 0, 1000);
$msg = iconv('windows-1251', 'utf-8', $msg);
$msg = str_replace("$", "$$", $msg);

$emotions = intval($_POST['emotions']);

switch($emotions)
{
case 1:
$msg = "[Радостно] $msg";
break;

case 2:
$msg = "[Печально] $msg";
break;

case 3:
$msg = "[Удивленно] $msg";
break;

case 4:
$msg = "[Ласково] $msg";
break;

case 5:
$msg = "[Смущенно] $msg";
break;

case 6:
$msg = "[Кокетливо] $msg";
break;

case 7:
$msg = "[Обиженно] $msg";
break;

case 8:
$msg = "[Настойчиво] $msg";
break;

case 9:
$msg = "[Шепотом] $msg";
break;

case 10:
$msg = "[Задумчиво] $msg";
break;

case 11:
$msg = "[Злобно] $msg";
break;
}

	if($level > 0)
	{
	$attributs = $_POST['attributs'];
	$post_fsize = (int)$_POST['fsize'];

	if(substr_count($attributs, "underline") != 0) $msg = "<u>$msg</u>";

		if($level > 2)
		{
		if(substr_count($attributs, "bold") != 0) $msg = "<b>$msg</b>";
		}

		if($level == 4)
		{
		if(substr_count($attributs, "italic") != 0) $msg = "<i>$msg</i>";
		if($post_fsize == 0) $msg = "<small>$msg</small>";
		if($post_fsize == 2) $msg = "<big>$msg</big>";
		}
	}

$msg = eregi_replace("((http://))((([a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z;]{2,3}))|(([0-9]{1,3}\.){3}([0-9]{1,3})))((/|\?)[a-z0-9~#%&'_\+=:;\?\.-]*)*)", "<a href=\"\\0\">\\3</a>", $msg);

if($level == 4) 
{
$msg = preg_replace("|\*\((.*)\)\*|isU", "<b>\\1</b>", $msg);
}

$sql = mysql_query("SELECT `msg` FROM `chat_intim` WHERE `key` = '".$key."' AND `aid` = '".$id."' ORDER BY `id` DESC LIMIT 1;");
$last_msg = mysql_escape_string(mysql_result($sql, 0));

	if($last_msg != $msg && !empty($msg))
	{
	$to = (int)$_POST['to'];
	$sql = mysql_query("INSERT INTO `chat_intim` VALUES(0, '".$id."', '".$nickname."', '".$msg."', '".$key."', '".$to."', '".date("H:i:s")."',".time().");");
		if(mysql_insert_id() > 4000000000)
		{
		mysql_query("TRUNCATE TABLE `chat`;");
		$message = "Комнаты интима были очищены системой. Данная операция была важна для снятия нагрузки с базы данных.";
		$sql = mysql_query("SELECT `id` FROM `chat_intim`;");
			while($room_id = mysql_fetch_array($sql))
			{
			mysql_query("INSERT INTO `chat` VALUES(0, '5', '".$bots[3]."', '".$message."', '".$key."', '0', '".date("H:i:s")."',".time().");");
			}
		}
		if(!$sql)
		{
		$sql = mysql_query("INSERT INTO `chat` VALUES(0, '".$id."', '".$nickname."', '".$msg."', '".$rid."', '".$to."', '".date("H:i:s")."', ".time().");");
		}
	mysql_query("UPDATE `chat_users` SET `posts` = `posts` + 1 WHERE `id` = '".$id."';");
	}
}

$sql = mysql_query("SELECT COUNT(*) FROM `chat_intim` WHERE `key` = '".$key."';");
$all = mysql_result($sql, 0);

if(isset($_GET['s'])) $s = intval($_GET['s']);
else $s = 0;
if($s < 0) $s = 0;
if($s > $all) $s = 0;

$sql = mysql_query("SELECT * FROM `chat_intim` WHERE `key` = '".$key."' ORDER BY `id` DESC LIMIT $s, $msgs;");

while($post = mysql_fetch_array($sql))
{
echo "<a href=\"addto.php?id=$id&amp;password=$password&amp;ver=wml&amp;key=$key&amp;nocache=$nocache&amp;uid=".$post['aid']."\">".$post['nickname']."</a> [".$post['time']."]<br/>\n";
echo $post['msg']."<br/>\n";
}

if ($all > $s + $msgs)  print "<a href=\"intim.php?id=$id&amp;password=$password&amp;ver=wml&amp;key=$key&amp;nocache=$nocache&amp;s=".($s + $msgs)."\">&gt;&gt;&gt;</a><br/>\n";
if ($s > 0)  print "<a href=\"intim.php?id=$id&amp;password=$password&amp;ver=wml&amp;key=$key&amp;nocache=$nocache&amp;s=".($s - $msgs)."\">&lt;&lt;&lt;</a><br/>\n";

echo "<a href=\"menu.php?id=$id&amp;password=$password&amp;ver=wml&amp;nocache=$nocache\">Меню чата</a><br/>\n";

echo $close_tag;

list($msec, $sec) = explode(chr(32), microtime());
echo "<br/><small>[".round(($sec+$msec) - $headtime, 5)."] sec</small><br/>\n";
echo "</p></card><card id=\"add\" title=\"Сказать\"><p align=\"left\">";
echo "Сообщение:<br/>\n";
echo "<input type=\"text\" name=\"msg$nocache\" maxlength=\"300\" value=\"\"/><br/>\n";
if($translit == 1)
{
echo "Транслитировать:<br/>\n";
echo "<select name=\"translit$nocache\" value=\"true\">\n";
echo "<option value=\"true\">Да</option>\n";
echo "<option value=\"false\">Нет</option>\n";
echo "</select><br/>\n";
}
if($level > 0)
{
echo "Аттрибуты:<br/>\n";
echo "<select name=\"attributs$nocache\" multiple=\"true\">\n";
if($level > 2) echo "<option value=\"bold\">Жирный</option>\n";
echo "<option value=\"underline\">Подчеркнутый</option>\n";
if($level == 4)echo "<option value=\"italic\">Курсив</option>\n";
echo "</select><br/>\n";
}
if($level == 4)
{
echo "Размер:<br/>\n";
echo "<select name=\"fsize$nocache\" value=\"1\">\n";
echo "<option value=\"0\">Маленький</option>\n";
echo "<option value=\"1\">Нормальный</option>\n";
echo "<option value=\"2\">Большой</option>\n";
echo "</select><br/>\n";
}
echo "<anchor>[Сказать]<go href=\"intim.php?id=$id&amp;password=$password&amp;ver=wml&amp;key=$key&amp;nocache=$nocache\" method=\"post\">\n";
echo "<postfield name=\"msg\" value=\"$(msg$nocache)\"/>\n";
echo "<postfield name=\"translit\" value=\"$(translit$nocache)\"/>\n";
echo "<postfield name=\"attributs\" value=\"$(attributs$nocache)\"/>\n";
echo "<postfield name=\"fsize\" value=\"$(fsize$nocache)\"/>\n";
echo "<postfield name=\"key\" value=\"".$key."\"/>\n";
echo "</go></anchor><br/>\n";
echo "<a href=\"intim.php?id=$id&amp;password=$password&amp;ver=wml&amp;key=$key&amp;nocache=$nocache\">Назад</a><br/>\n";
echo "</p></card></wml>";
break;

////////////////////////////////////////////////////////
//HTML VERSION
////////////////////////////////////////////////////////
case 'html':
header ("Content-type: text/html; charset=utf-8");
header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
header("Cache-Control: no-cache, must-revalidate");

//AUTH
$id = intval($_GET['id']);
$password = mysql_escape_string($_GET['password']);
$q = mysql_query("SELECT * FROM `chat_users` WHERE `id` = '".$id."' AND `password` = '".$password."';");

if(mysql_affected_rows() == 0)
{
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
echo "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n";
echo "<html><head>\n";
echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>\n";
echo "<link rel=\"shortcut icon\" href=\"$icon\" /><title>".$title."</title>\n";
echo "<style type=\"text/css\">
body { font-weight: normal; font-size: normal; font-family: ".$font."; color: ".$color."; background-color: ".$background." }
a:link,a:active,a:visited { text-decoration: underline; color : ".$links." }
</style></head><body>";
echo "<small>Ошибка авторизации!<br/>\n";
list($msec, $sec) = explode(chr(32), microtime());
echo "<br/>[".round(($sec+$msec)-$headtime,5)."] sec<br/>\n";
echo "</body></html>";
exit();
}
else
{
$user = mysql_fetch_array($q);
$nickname = $user['nickname'];
$smiles = $user['smiles'];
$translit  = $user['translit'];
$msgs  = $user['msgs'];
$refresh = $user['refresh'];
$fsize = $user['fsize'];
$security  = $user['security'];
$level = $user['level'];
$kick = $user['kick'];
$moder = $user['moder'];
$reason = $user['reason'];
$fsize = $user['fsize'];
}
//END AUTH

if(!isset($_POST['key']))
{
if(preg_match("/[^0-9a-zA-Z_]+/", $_GET['key']))
	{
	  echo "nedopustimye simvoly v klyu4e!";
	  exit;
	}
else
	{
	  $key = $_GET['key'];
	}
}
else
{
if(preg_match("/[^0-9a-zA-Z_]+/", $_POST['key']))
	{
	  echo "nedopustimye simvoly v klyu4e!";
	  exit;
	}
else
	{
	  $key = $_POST['key'];
	}
}

if(empty($key)) $key = "public";

if($level < 1 && $type != 0)
{
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
echo "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n";
echo "<html><head>\n";
echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>\n";
echo "<link rel=\"shortcut icon\" href=\"$icon\" /><title>".$title."</title>\n";
echo "<style type=\"text/css\">
body { font-weight: normal; font-size: normal; font-family: ".$font."; color: ".$color."; background-color: ".$background." }
a:link,a:active,a:visited { text-decoration: underline; color : ".$links." }
</style></head><body>";
echo "Доступ запрещен.<br/>\n";
list($msec, $sec) = explode(chr(32), microtime());
echo "<br/>[".round(($sec+$msec)-$headtime,5)."] sec<br/>\n";
echo "</body></html>";
exit();
}

if($kick > time())
{
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
echo "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n";
echo "<html><head>\n";
echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>\n";
echo "<link rel=\"shortcut icon\" href=\"$icon\" /><title>".$title."</title>\n";
echo "<style type=\"text/css\">
body { font-weight: normal; font-size: normal; font-family: ".$font."; color: ".$color."; background-color: ".$background." }
a:link,a:active,a:visited { text-decoration: underline; color : ".$links." }
</style></head><body>";
echo "Вы временно заблокированы модератором <u>$moder</u> на <u>".($kick - time())."</u> сек.<br/>\n";
echo "Причина: $reason<br/>\n";
list($msec, $sec) = explode(chr(32), microtime());
echo "<br/>[".round(($sec+$msec)-$headtime,5)."] sec<br/>\n";
echo "</body></html>";
exit();
}

//ONLINE
$online = time() + 60;
$update = mysql_query("UPDATE `chat_users` SET `intim` = '".$online."', `key` = '".$key."', `ip` = '".getenv('REMOTE_ADDR')."', `ua` = '".htmlspecialchars(getenv('HTTP_USER_AGENT'))."' WHERE `id` = '".$id."';");
//END ONLINE

$sql = mysql_query("SELECT `nickname` FROM `chat_users` WHERE `key` = '".$key."' AND `intim` >= ".time().";");

if($fsize == 0)
{
$fsize = "small";
}
if($fsize == 1)
{
$fsize = "normal";
}
if($fsize == 2)
{
$fsize = "large";
}

echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
echo "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n";
echo "<html><head>\n";
echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>\n";
echo "<meta http-equiv=\"refresh\" content=\"$refresh;url=".$_SERVER['PHP_SELF']."?id=$id&amp;password=$password&amp;ver=html&amp;key=$key&amp;nocache=$nocache\"/>\n";
echo "<link rel=\"shortcut icon\" href=\"$icon\" /><title>Интимная</title>\n";
echo "<style type=\"text/css\">
body { font-weight: normal; font-size: $fsize; font-family: ".$font."; color: ".$color."; background-color: ".$background." }
a:link,a:active,a:visited { text-decoration: underline; color : ".$links." }
div.form { background-color: ".$form_color." }
</style></head><body>";

$c = 0;
echo "В этой комнате: ";
while($users = mysql_fetch_array($sql))
{
echo $users['nickname'].", ";
}
echo "<br/>\n";

echo "<a href=\"intim.php?id=$id&amp;password=$password&amp;ver=html&amp;key=$key&amp;nocache=$nocache\">Обновить</a><br/>\n";
echo "<a href=\"add_in_intim.php?id=$id&amp;password=$password&amp;ver=html&amp;key=$key&amp;nocache=$nocache\">Сказать</a><br/>\n";
echo "<a href=\"online.php?id=$id&amp;password=$password&amp;ver=html&amp;nocache=$nocache\">Онлайн</a><br/>\n";

if(isset($_POST['msg']))
{
mysql_query("SELECT * FROM `chat` WHERE `aid` = '".$id."' AND `seconds` > ".(time() - 20).";");
if(mysql_affected_rows() > 3)
{
$reason = "Вы были автоматически забанены системой за флуд (многократное повторение сообщений).";
mysql_query("UPDATE `chat_users` SET `kick` = ".(time() + 180).", `moder` = '".$bots[3]."', `reason` = '".$reason."';");
}

$msg = trim($_POST['msg']);

if(isset($_POST['uid']))
{
$sql = mysql_query("SELECT `nickname` FROM `chat_users` WHERE `id` = ".intval($_POST['uid']).";");
$nick = mysql_result($sql, 0);
}
else
{
$nick = "";
}

$msg = addslashes($msg);

	if($_POST['translit'] == "true")
	{
	$msg = str_replace("\"\"", "Ъ", $msg);
	$msg = str_replace("\"", "ъ", $msg);
	$msg = str_replace("''", "Ь", $msg);
	$msg = str_replace("'", "ь", $msg);

	$lat = array("CH", "ch", "SC", "sc", "YE", "ye", "YU", "yu", "YA", "ya", "YO", "yo");
	$rus = array("Ч", "ч", "Щ", "щ", "Э", "э", "Ю", "ю", "Я", "я", "Ё", "ё");
	$msg = str_replace($lat, $rus, $msg);

	$lat = array("A", "a", "B", "b", "C", "c", "D", "d", "E", "e", "F", "f", "G", "g", "H", "h", "I", "i", "J", "j", "K", "k", "L", "l", "M", "m", "N", "n", "O", "o", "P", "p", "R", "r", "S", "s", "T", "t", "U", "u", "V", "v", "H", "h", "Z", "z", "W", "w", "X", "x", "Y", "y");
	$rus = array("А", "а", "Б", "б", "Ц", "ц", "Д", "д", "Е", "е", "Ф", "ф", "Г", "г", "Х", "х", "И", "и", "Ж", "ж", "К", "к", "Л", "л", "М", "м", "Н", "н", "О", "о", "П", "п", "Р", "р", "С", "с", "Т", "т", "У", "у", "В", "в", "Х", "х", "З", "з", "Ш", "ш", "Ы", "ы", "Й", "й");
	$msg = str_replace($lat, $rus, $msg);
	}

$msg = htmlspecialchars($msg);

//SMILES
include "smiles.php";
$msg = preg_replace($smiles_array, $smile, $msg, 2);

if(!empty($nick))
{
$msg = "$nick, $msg";
}

$msg = iconv('utf-8', 'windows-1251', $msg);
$msg = substr($msg, 0, 1000);
$msg = iconv('windows-1251', 'utf-8', $msg);
$msg = str_replace("$", "$$", $msg);

$emotions = intval($_POST['emotions']);

switch($emotions)
{
case 1:
$msg = "[Радостно] $msg";
break;

case 2:
$msg = "[Печально] $msg";
break;

case 3:
$msg = "[Удивленно] $msg";
break;

case 4:
$msg = "[Ласково] $msg";
break;

case 5:
$msg = "[Смущенно] $msg";
break;

case 6:
$msg = "[Кокетливо] $msg";
break;

case 7:
$msg = "[Обиженно] $msg";
break;

case 8:
$msg = "[Настойчиво] $msg";
break;

case 9:
$msg = "[Шепотом] $msg";
break;

case 10:
$msg = "[Задумчиво] $msg";
break;

case 11:
$msg = "[Злобно] $msg";
break;
}

	if($level > 0)
	{
	$attributs = $_POST['attributs'];
	$post_fsize = (int)$_POST['fsize'];

	if(substr_count($attributs, "underline") != 0) $msg = "<u>$msg</u>";

		if($level > 2)
		{
		if(substr_count($attributs, "bold") != 0) $msg = "<b>$msg</b>";
		}

		if($level == 4)
		{
		if(substr_count($attributs, "italic") != 0) $msg = "<i>$msg</i>";
		if($post_fsize == 0) $msg = "<small>$msg</small>";
		if($post_fsize == 2) $msg = "<big>$msg</big>";
		}
	}

$msg = eregi_replace("((http://))((([a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z;]{2,3}))|(([0-9]{1,3}\.){3}([0-9]{1,3})))((/|\?)[a-z0-9~#%&'_\+=:;\?\.-]*)*)", "<a href=\"\\0\">\\3</a>", $msg);

if($level == 4) 
{
$msg = preg_replace("|\*\((.*)\)\*|isU", "<b>\\1</b>", $msg);
}

$sql = mysql_query("SELECT `msg` FROM `chat_intim` WHERE `key` = '".$key."' AND `aid` = '".$id."' ORDER BY `id` DESC LIMIT 1;");
$last_msg = mysql_escape_string(mysql_result($sql, 0));

	if($last_msg != $msg && !empty($msg))
	{
	$to = (int)$_POST['to'];
	$sql = mysql_query("INSERT INTO `chat_intim` VALUES(0, '".$id."', '".$nickname."', '".$msg."', '".$key."', '".$to."', '".date("H:i:s")."',".time().");");
		if(mysql_insert_id() > 4000000000)
		{
		mysql_query("TRUNCATE TABLE `chat`;");
		$message = "Комнаты интима были очищены системой. Данная операция была важна для снятия нагрузки с базы данных.";
		$sql = mysql_query("SELECT `id` FROM `chat_intim`;");
			while($room_id = mysql_fetch_array($sql))
			{
			mysql_query("INSERT INTO `chat` VALUES(0, '5', '".$bots[3]."', '".$message."', '".$key."', '0', '".date("H:i:s")."',".time().");");
			}
		}
		if(!$sql)
		{
		$sql = mysql_query("INSERT INTO `chat` VALUES(0, '".$id."', '".$nickname."', '".$msg."', '".$rid."', '".$to."', '".date("H:i:s")."', ".time().");");
		}
	mysql_query("UPDATE `chat_users` SET `posts` = `posts` + 1 WHERE `id` = '".$id."';");
	}
}
$sql = mysql_query("SELECT COUNT(*) FROM `chat_intim` WHERE `key` = '".$key."';");
$all = mysql_result($sql, 0);

if(isset($_GET['s'])) $s = intval($_GET['s']);
else $s = 0;
if($s < 0) $s = 0;
if($s > $all) $s = 0;

$sql = mysql_query("SELECT * FROM `chat_intim` WHERE `key` = '".$key."' ORDER BY `id` DESC LIMIT $s, $msgs;");

$c = 0;

while($post = mysql_fetch_array($sql))
{
if($c == 0)
{
$div = "<div class=\"form\">\n";
$close = "</div>\n";
$c = 1;
}
else
{
$div = "";
$close = "";
$c = 0;
}
echo $div;
echo "<a href=\"addto.php?id=$id&amp;password=$password&amp;ver=html&amp;key=$key&amp;nocache=$nocache&amp;uid=".$post['aid']."\">".$post['nickname']."</a> [".$post['time']."]<br/>\n";
echo $post['msg']."<br/>\n";
echo $close;
}

if ($all > $s + $msgs)  print "<a href=\"intim.php?id=$id&amp;password=$password&amp;ver=html&amp;key=$key&amp;nocache=$nocache&amp;s=".($s + $msgs)."\">&gt;&gt;&gt;</a><br/>\n";
if ($s > 0)  print "<a href=\"intim.php?id=$id&amp;password=$password&amp;ver=html&amp;key=$key&amp;nocache=$nocache&amp;s=".($s - $msgs)."\">&lt;&lt;&lt;</a><br/>\n";

echo "<a href=\"menu.php?id=$id&amp;password=$password&amp;ver=html&amp;nocache=$nocache\">Меню чата</a><br/>\n";

list($msec, $sec) = explode(chr(32), microtime());
echo "<br/><span style=\"font-size: small\">[".round(($sec+$msec)-$headtime,5)."] sec</span><br/>\n";
echo "</body></html>";
break;
}
?>