<?

header('Cache-Control: no-store, no-cache, must-revalidate');
if ($ver=="wml")header ("Content-type:text/vnd.wap.wml; charset=utf-8");
else header("Content-Type:text/html; charset=UTF-8");

require("inc.php");

$link = connect_db();
list($row, $id, $ps, $fsize1, $fsize2) = check_login($link);
require("version.php");

if(isset($HTTP_GET_VARS['rm'])) {$rm = $HTTP_GET_VARS['rm'];}
if (!ctype_digit($rm)) { header("Location: index.php"); die; }
$rm = mysql_escape_string($rm);

mysql_query ("Select rm from rooms where rm='".$rm."';");
if (mysql_affected_rows() == 0){
if ($ver=="wml"){
echo $xml;
echo $dtd;
echo "<wml>";
echo "<card id=\"error\" title=\"Ошибка\" ontimer=\"enter.php?$ses&amp;ref=$ref\"><timer value=\"15\"/>";
echo "<p align=\"center\">";
}else{
echo "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">";
echo "<html xmlns=\"http://www.w3.org/1999/xhtml\">";
echo "<head><link rel=\"stylesheet\" type=\"text/css\" href=\"css/css.css\"/>";
echo "<title>Ошибка</title>";
echo "<META HTTP-EQUIV=\"Refresh\" CONTENT=\"2; URL=enter.php?$ses&amp;ref=$ref\">";
echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/></head><body>";
echo "<div align=\"center\">";
}
echo $fsize1;
echo "Такой комнаты не существует!";
echo $fsize2;
if ($ver=="wml")echo "</p></card></wml>";
else echo "</div></body></html>";
mysql_close($link);
exit;
}

mysql_query ("Select * from bannlist WHERE (ip = '".$REMOTE_ADDR."')and(soft = '".$HTTP_USER_AGENT."')");
if ((mysql_affected_rows()!=0)&&($rm!=9)&&($row["level"]<7)) {
$re = mysql_query("SELECT name FROM rooms where rm = '9'"); 
$inam = mysql_fetch_array ($re); 
$nam = $inam["name"];
if ($ver=="wml"){
echo $xml;
echo $dtd;  
echo "<wml>\n";
echo "<head><meta http-equiv=\"Cache-Control\" content=\"no-cache\" forua=\"true\"/></head>\n";
echo "<card id=\"ban\" title=\"Стоп!\" ontimer=\"index.php?ver=$ver&amp;ref=$ref\"><timer value=\"300\"/>\n";
echo "<p align=\"center\">\n";
}else{
echo "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">";
echo "<html xmlns=\"http://www.w3.org/1999/xhtml\">";
echo "<head><link rel=\"stylesheet\" type=\"text/css\" href=\"css/css.css\"/>";
echo "<title>Стоп!</title>";
echo "<META HTTP-EQUIV=\"Refresh\" CONTENT=\"30; URL=index.php?ver=$ver&amp;ref=$ref\">";
echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/></head><body>";
echo "<div align=\"center\">";
}
echo $fsize1;
echo "Вы забанены по связке ip+soft!!!<br/>\n";
echo "И доступ вам разрешен только в  <a href=\"chat.php?$ses&amp;rm=9&amp;ref=$ref\">".$nam."</a>\n";
echo $fsize2;
if ($ver=="wml")echo "</p></card></wml>";
else echo "</div></body></html>";
mysql_close($link);
exit;
}   

if (($row["level"]<4)&&($rm==8)){
if ($ver=="wml"){
echo $xml;
echo $dtd;
echo "<wml>";
echo "<card id=\"error\" title=\"Внимание!!!\" ontimer=\"enter.php?$ses&amp;ref=$ref\"><timer value=\"15\"/>";
echo "<p align=\"center\">";
}else{
echo "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">";
echo "<html xmlns=\"http://www.w3.org/1999/xhtml\">";
echo "<head><link rel=\"stylesheet\" type=\"text/css\" href=\"css/css.css\"/>";
echo "<title>Внимание!!!</title>";
echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/></head><body>";
echo "<div align=\"center\">";
}
echo $fsize1;
echo "Извините!!! Но в эту комнату ВАМ доступ закрыт.";
echo $fsize2;
if ($ver=="wml")echo "</p></card></wml>";
else echo "</div></body></html>";
mysql_close($link);
exit;
}

if((time()<$row["kik"]&&$rm!=9)||(time()<$row["kik"]&&$rm==9&&$row["whokik"]=="[Система]")){
$re = mysql_query("SELECT name FROM rooms where rm = '9'"); 
$inam = mysql_fetch_array ($re); 
$nam = $inam["name"];
if ($ver=="wml"){
echo $xml;
echo $dtd;
echo "<wml>";
echo "<head><meta http-equiv=\"Cache-Control\" content=\"no-cache\" forua=\"true\"/></head>";
echo "<card id=\"vypnut\" title=\"Стоп!\" ontimer=\"index.php?ref=$ref\"><timer value=\"300\"/>";
echo "<p align=\"center\">";
}else{
echo "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">";
echo "<html xmlns=\"http://www.w3.org/1999/xhtml\">";
echo "<head><link rel=\"stylesheet\" type=\"text/css\" href=\"css/css.css\"/>";
echo "<title>Внимание!!!</title>";
echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/></head><body>";
echo "<div align=\"center\">";
}
echo $fsize1;
$tleft = $row["kik"] - time();
$whokik = $row["whokik"];
$whykik = $row["whykik"];
echo "".$whokik." выпнул вас из чата. Разбан через ".$tleft." (сек)<br/>";
echo "Причина: ".$whykik."<br/>";
echo "А пока вам разрешен доступ только в <a href=\"chat.php?$ses&amp;rm=9&amp;rul=9&amp;ref=$ref\">".$nam."</a>";
echo $fsize2;
if ($ver=="wml")echo "</p></card></wml>";
else echo "</div></body></html>";
mysql_close($link);
exit;
}

if($rm==8){
$fi = fopen("log/admroom.dat", "a+");
$dat = date ("~d F в H:i~");
$dat = str_replace("January","Января",$dat);
$dat = str_replace("February","Февраля",$dat);
$dat = str_replace("March","Марта",$dat);
$dat= str_replace("April","Апреля",$dat);
$dat = str_replace("May","Мая",$dat);
$dat = str_replace("June","Июня",$dat);
$dat = str_replace("July","Июля",$dat);
$dat = str_replace("August","Августа",$dat);
$dat = str_replace("September","Сентября",$dat);
$dat = str_replace("October","Октября",$dat);
$dat = str_replace("November","Ноября",$dat);
$dat = str_replace("December","Декабря",$dat);
$lst = "<b><u>$us</u></b> Посещал комнату для администрации $dat, Его  ip: $REMOTE_ADDR, Браузер: $HTTP_USER_AGENT<br/>";
fwrite($fi, "$divide");
fwrite($fi, "$lst\n");
fflush($fi);
fclose($fi);
}

if ($rm==10) {
$fi = fopen("log/intim.dat", "a+");
$dat = date ("~d F в H:i~");
$dat = str_replace("January","Января",$dat);
$dat = str_replace("February","Февраля",$dat);
$dat = str_replace("March","Марта",$dat);
$dat= str_replace("April","Апреля",$dat);
$dat = str_replace("May","Мая",$dat);
$dat = str_replace("June","Июня",$dat);
$dat = str_replace("July","Июля",$dat);
$dat = str_replace("August","Августа",$dat);
$dat = str_replace("September","Сентября",$dat);
$dat = str_replace("October","Октября",$dat);
$dat = str_replace("November","Ноября",$dat);
$dat = str_replace("December","Декабря",$dat);
$lst = "<b><u>$us</u></b> Посещал интим-комнату $dat, Его пароль: <b>$pwd</b> ip: $REMOTE_ADDR, Браузер: $HTTP_USER_AGENT<br/>";
fwrite($fi, "$divide");
fwrite($fi, "$lst\n");
fflush($fi);
fclose($fi);
}

## Очистка комнат с предупредждением (для модеров)
if(file_exists("log/clear.dat")){
$f=fopen("log/clear.dat","r");
$clrdata=file("log/clear.dat");
fclose($f);
if ($clrdata[0]<time()){
unlink("log/clear.dat");
for ($num = 0; $num <=23; $num++){
$room = "room".$num;
$res = mysql_query ("Select id from $room order by id desc");
$kol = mysql_affected_rows(); 
$lines = mysql_fetch_array($res);      
for ($k = 0; $k <= $kol; $k++){
$lines = @mysql_fetch_array ($res);
$kl = $lines["id"];  
mysql_query ("Delete from $room where id = '".$kl."'");
}
}
}
}

## Автоочистка комнат
$r = mysql_query ("SELECT * FROM optim");
$a = mysql_fetch_array ($r);
if ($a["go"]<time()){
$i = time() + 104800;
mysql_query ("Update optim set go='".$i."' WHERE klu4 = '1'"); 
$i = time() - 104800;
for ($num = 0; $num <= 23; $num++){
$roptim = "room".$num;
mysql_query("delete from $roptim WHERE id<'".$i."'");
mysql_query("OPTIMIZE TABLE $roptim");
}
}

$room="room".$rm;
$us=$row["user"];
$max = $row["max"];
$smset = $row["smiles"];
$us_ip = $row["user_ip"];
$us_soft = $row["user_soft"];

if ($rm!=23){
$setting = @mysql_query ("Select * from setting where klu4=1");
$set = mysql_fetch_array ($setting);

require ("birthday.php"); ##Поздравление с днюхой 

$smthwr = 0;
$bmax = $max*2;
if (empty($pwd)) $pwd=pub;
$pwd=htmlspecialchars(stripslashes(trim($pwd)));

if ($rm == 10) $res = mysql_query ("Select klu4,time,who,message,messagewosm,messagewoasm,id,towhom,hid,usid,pwd,komu from room10 WHERE ((pwd = '".$pwd."')OR(pwd = '')) and ((usid = '".$id."')OR(towhom = '".$id."')OR(towhom = '')) order by id desc LIMIT $bmax");
elseif($mod=="privat") $res = mysql_query ("Select klu4,time,who,message,messagewosm,messagewoasm,id,towhom,hid,usid,komu from $room WHERE (usid = '".$id."')OR(towhom = '".$id."') order by id desc LIMIT $bmax");
else $res = mysql_query ("Select klu4,time,who,message,messagewosm,messagewoasm,id,towhom,hid,usid,komu from $room WHERE (usid = '".$id."')OR(towhom = '".$id."')OR(towhom = '') order by id desc LIMIT $bmax");
$kol = mysql_affected_rows(); 

if ($rm == 0) require("umnik1.php");
if ($rm == 11) require("umnikmat1.php");

if(@$msg){
$msg = trim(" $msg ");
$msg = ereg_replace(" +"," ",$msg);
$msg = substr($msg,0,400);
$msg = str_replace("", " ", $msg);
$msg = str_replace("$", "$$", $msg);
$msg = strtr($msg,array(chr("0")=>"",chr("1")=>"",chr("2")=>"",chr("3")=>"",chr("4")=>"",chr("5")=>"",chr("6")=>"",chr("7")=>"",chr("8")=>"",chr("9")=>"",chr("10")=>"",chr("11")=>"",chr("12")=>"",chr("13")=>"",chr("14")=>"",chr("15")=>"",chr("16")=>"",chr("17")=>"",chr("18")=>"",chr("19")=>"",chr("20")=>"",chr("21")=>"",chr("22")=>"",chr("23")=>"",chr("24")=>"",chr("25")=>"",chr("26")=>"",chr("27")=>"",chr("28")=>"",chr("29")=>"",chr("30")=>"",chr("31")=>""));
##$msg = str_replace("к","С‘",$msg);
$msg = htmlspecialchars($msg); 
$msg = str_replace("\"", "&quot;", $msg);
$msg = str_replace("|", "&#0166;", $msg); 
$msg = str_replace("'", "&#8216;", $msg); 
$msg = str_replace("\\", "", $msg); 
$msg = addslashes($msg); 


if (!isset($prvt)) $prvt = 0;

$str1="";
$str2=$msg;

if ($prvt == 0) $towhom = "";
if (!isset($towhom)) $towhom = "";

if ($row["level"]<5) {require("antirekl.php");}

require("smile.php");
$minpos = 500; $nm = 500;
for ($j=0;$j<=count($smiles)-1;$j++){
$tmpp = strpos($msg,$smiles[$j]);
if (($tmpp < $minpos)&&($tmpp !== false)){
$minpos = $tmpp; $nm = $j;};};
if ($minpos !=500){
if ($row["translit"]!=1){
$st1 = substr($msg,0,$minpos+strlen($smiles[$nm]));
$st2 = substr($msg,$minpos+strlen($smiles[$nm]),strlen($msg)-strlen($st1));
$st1_wosm = $st1;
$st1 = str_replace($smiles[$nm],$replaces[$nm],$st1);
if (strpos($replaces[$nm],"smilean/")!==false) $st1_woasm = $st1_wosm; else $st1_woasm = $st1;
$msg_woasm = $st1.$st2;
$msg_wosm = $st1_wosm.$st2;
$msg = $st1_woasm.$st2;
}else{
$st1 = substr($msg,0,$minpos);
$st2 = substr($msg,$minpos, strlen($smiles[$nm]));
$st3 = substr($msg,$minpos+strlen($smiles[$nm]),strlen($msg)-strlen($st1)-strlen($st2));
$st1 = trun_to_rus($st1);
$st2_wosm = $st2;
$st2 = $replaces[$nm];
if (strpos($replaces[$nm],"smilean/")!==false) $st2_woasm = $st2_wosm; else $st2_woasm = $st2;
$st3 = trun_to_rus($st3);
$msg = $st1.$st2_woasm.$st3;
$msg_wosm = $st1.$st2_wosm.$st3;
$msg_woasm = $st1.$st2.$st3;
}
}
else if ($row["translit"]==1) $msg = trun_to_rus($msg);
unset($smiles);
unset($replaces);
if($row["level"]>6)$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);


$msg = $str1.$msg;
if (@$msg_wosm!="") $msg_wosm = $str1.$msg_wosm;
if (@$msg_woasm!="") $msg_woasm = $str1.$msg_woasm;

if(!empty($shrift)){
if (($row["level"]>=4) && ($shrift==1)) $msg = '<i>'.$msg.'</i>';
else if (($row["level"]>=5) && ($shrift==2)) $msg = '<u>'.$msg.'</u>';
else if (($row["level"]>=6) && ($shrift==3)) $msg = '<i><u>'.$msg.'</u></i>';
else if (($row["level"]>=6) && ($shrift==4)) $msg = '<b>'.$msg.'</b>';
else if (($row["level"]>=7) && ($shrift==5)) $msg = '<u><b>'.$msg.'</b></u>';
else if (($row["level"]>=7) && ($shrift==6)) $msg = '<i><u><b>'.$msg.'</b></u></i>';
}


$r = mysql_query("SELECT message FROM $room WHERE usid = '".$id."' order by id desc LIMIT 1");
$a = mysql_fetch_array($r);
if ($a["message"] !== $msg){
$time = getmicrotime();
$ftime = $time - 90;
$r = mysql_query("SELECT count(*) as sum from $room WHERE (usid = '".$id."')and(id > '".$ftime."')");
$a = mysql_fetch_array($r);
$sum = $a["sum"];
if ($sum>=10&&$row["level"]<4){
$ftime = $time + 240;
$sys2 = @mysql_query ("Select user from users where id='1' LIMIT 1;");
$zz2 = @mysql_fetch_array ($sys2);
$sysik = $zz2["user"];
mysql_query("update users set kik = '".$ftime."', whykik = 'Флуд', whokik = '".$sysik."' WHERE id = '".$id."'");
}

$today=date ("H:i");
$posts =  $row["posts"];
$posts++;
if($ver=="wml"){
if ($rm == 10) mysql_query ("Update users set posts='".$posts."', onl='".$time."', version='1' where id ='".$id."'");
else mysql_query ("Update users set posts='".$posts."', onl='".$time."', room='".$rm."', version='1' where id ='".$id."'");
}else{
if ($rm == 10) mysql_query ("Update users set posts='".$posts."', onl='".$time."', version='2' where id ='".$id."'");
else mysql_query ("Update users set posts='".$posts."', onl='".$time."', room='".$rm."', version='2' where id ='".$id."'");
}
$hid = $row["inv"];
$kol++;
$rnd = rand(0,99999999);

if($rm==0) {require("umnik2.php");
}

if($prvt==2){
$data = date("d-M-Y [H:i]");
$kol = rand(0,99999999);
$time = time();
$remn = mysql_query("SELECT name FROM rooms where rm = '".$rm."'"); 
$inamen = mysql_fetch_array ($remn); 
$names = $inamen["name"];
$tema = "Из комнаты ".$names."";
@mysql_query("Insert into zapiski set klu4='".$kol."', who ='".$us."', idwho ='".$id."', message = '".$msg."', towhom = '".$user."', idtowhom = '".$towhom."', time = '".$time."', readd = '0', topic = '".$tema."', date='".$data."'");
}else{
$msg = $nastr.$msg;
$komu = check($komu);
if (($rm == 0)&&($amsg == $kansw||$amsg == $tran)&&$nom!=5){
@mysql_query ("Insert into room0 set klu4= '".$rnd."', time='".$today."', who='".$us."', message='".$msg."', messagewosm = '".$msg_wosm."', messagewoasm = '".$msg_woasm."', id='".$time."', towhom='".$towhom."', hid='2', usid='".$id."', komu='".$komu."'");
} else if ($rm == 10){
@mysql_query ("Insert into room10 set klu4= '".$rnd."', time='".$today."', who='".$us."', message='".$msg."', messagewosm = '".$msg_wosm."', messagewoasm = '".$msg_woasm."', id='".$time."', towhom='".$towhom."', hid='".$hid."', usid='".$id."', pwd='".$pwd."', komu='".$komu."'");
} else {
@mysql_query ("Insert into $room set klu4= '".$rnd."', time='".$today."', who='".$us."', message='".$msg."', messagewosm = '".$msg_wosm."', messagewoasm = '".$msg_woasm."', id='".$time."', towhom='".$towhom."', hid='".$hid."', usid='".$id."', komu='".$komu."'");
}
} 

$usmes["komu"] = $komu;
$usmes["time"] = $today;
$usmes["who"] = $us;
$usmes["usid"] = $id;
$usmes["message"] = stripslashes($msg);
@$usmes["messagewosm"] = stripslashes($msg_wosm);
@$usmes["messagewoasm"] = stripslashes($msg_woasm);
$usmes["id"] = $time;
$usmes["towhom"] = $towhom;
$smthwr = 1;

if($rm==0) {require("umnik3.php");
}
if($rm==11) {require("umnikmat2.php");
}
}
}

##Бот Шутник
if($set["shut"] == 0){
$interv = $set["shutint"];
$r1 = $set["roomon"];
$r2 = $set["roomoff"];
$printan=0;
$f=fopen("log/shutnik.dat","a+");
flock($f,LOCK_EX);
$andata=file("log/shutnik.dat");
if ($andata[0]<time()){
ftruncate($f,0);
$andata = time() + $interv;
fwrite($f,$andata);
fflush($f);
$printan=1;
}
flock($f,LOCK_UN);
fclose($f);
if($printan==1){
$r = mysql_query("select count(klu4) as num from shutki");
$a = mysql_fetch_array($r);
$rnd = rand(1,$a["num"]);
$r = mysql_query ("SELECT message FROM shutki WHERE klu4 = '".$rnd."' LIMIT 1;");
$b = mysql_fetch_array($r);
$mes = $b["message"];
$rnd = rand(0,99999999);
$today=date ("H:i");
$time = getmicrotime();
$shut = @mysql_query ("Select user from users where id='3' LIMIT 1;");
$zz = @mysql_fetch_array ($shut);
$shutnik = $zz["user"];
for ($num = $r1; $num <= $r2; $num++){
$ranec = "room".$num;
mysql_query ("Insert into $ranec set klu4= '".$rnd."', time='".$today."', who='".$shutnik."', message='".$mes."', id='".$time."', towhom='', hid='0', usid='3', komu=''");
mysql_query("ANALYZE TABLE $ranec");
}
}
}

##Бот Трахтенберг
$interv=600;
$printans=0;
$f=fopen("log/anekdot.dat","a+");
flock($f,LOCK_EX);
$andata=file("log/anekdot.dat");
if ($andata[0]<time())
{
ftruncate($f,0);
$andata = time() + $interv;
fwrite($f,$andata);
fflush($f);
$printans=1;
}
flock($f,LOCK_UN);
fclose($f);
if($printans==1){
$r = mysql_query("select count(klu4) as num from anekdot");
$a = mysql_fetch_array($r);
$rnd = rand(1,$a["num"]);
$r = mysql_query ("SELECT message,who FROM anekdot WHERE klu4 = '".$rnd."' LIMIT 1;");
$b = mysql_fetch_array($r);
$mes = $b["message"];
$kto = $b["who"];
$r3 = mysql_query("SELECT user FROM users WHERE id = '".$kto."' LIMIT 1;");
$a4 = mysql_fetch_array($r3);
$usanek=$a4["user"];
$rnd = rand(0,99999999);
$today=date ("H:i");
$time = getmicrotime();
$trah = @mysql_query ("Select user from users where id='6' LIMIT 1;");
$rr = @mysql_fetch_array ($trah);
$trahtenberg = $rr["user"];
$messs = "".$mes." (".$usanek.")";
mysql_query ("Insert into room12 set klu4= '".$rnd."', time='".$today."', who='".$trahtenberg."', message='".$messs."', id='".$time."', towhom='', hid='0', usid='6', komu=''");
mysql_query("ANALYZE TABLE room12");
}
## Общающийся бот матершинник
if ($rm==11){
$bot = @mysql_query ("Select user from users where id='8' LIMIT 1;");
$zz1 = @mysql_fetch_array ($bot);
$botik = $zz1["user"];
$interv=600;
$printans=0;
$f=fopen("log/klaznet.dat","a+");
flock($f,LOCK_EX);
$andata=file("log/klaznet.dat");
if ($andata[0]<time())
{
ftruncate($f,0);
$andata = time() + $interv;
fwrite($f,$andata);
fflush($f);
$printans=1;
}
flock($f,LOCK_UN);
fclose($f);
if($printans==1){
$r = mysql_query("select count(klu4) as num from frazi");
$a = mysql_fetch_array($r);
$rnd = rand(1,$a["num"]);
$r = mysql_query ("SELECT message FROM frazi WHERE klu4 = '".$rnd."' LIMIT 1;");
$b = mysql_fetch_array($r);
$mes = $b["message"];
$rnd = rand(0,99999999);
$today=date ("H:i");
$time = getmicrotime();
mysql_query ("Insert into room11 set klu4= '".$rnd."', time='".$today."', who='".$botik."', message='".$mes."', id='".$time."', towhom='', hid='0', usid='8', komu=''");
mysql_query("ANALYZE TABLE room11");
}
## Ответы юзерам
/*
if($bot==1 && !empty($komu) && $komu=='Morpheus,')
{
include 'includes/func_bot.php';
if(!empty($te)) mysql_query("insert into chats(id,roomid,kto,komu,time,text) values(0,'".$room."','0|Morpheus','".$log.",','".time()."'+1,'".bot($log,$te)."');") or die(mysql_error());			
}
unset($te);
*/

if((!empty($komu)&&($komu=="$botik")||(ereg('ривет|даров|рям|дравствуй|чмак|Чмак|рива|драствуй|драсти|расти',$msg))||(ereg('удак|изда|уй|бля|Бля|издец|тупой|Тупой|ебок|ебать|Ебать|еби|Еби|соси|Соси|издуй|овно|ерьмо|урак|лупый',$msg)))){
if(!empty($msg)){ 
//if ($row["sex"]=="М") require ("botm.php");
//else require ("botj.php");
require ("bot.php");
$mess = "".bot($us,$msg)."";
//$mess = "".bot($us,$msg)."";
$rnd = rand(0,99999999);
$today=date ("H:i");
$time = getmicrotime();
mysql_query ("Insert into room11 set klu4= '".$rnd."', time='".$today."', who='".$botik."', message='".$mess."', id='".$time."', towhom='', hid='0', usid='8', komu='".$us."'");	
}
}
## Конец бота
##Мат по запросу
if ($msg=="!prikol"||$msg=="!прикол"){
$rs = mysql_query("select count(id) as num from bot_dialog");
$as = mysql_fetch_array($rs);
$rnds = rand(1,$as["num"]);
$rs = mysql_query ("SELECT message FROM bot_dialog WHERE id = '".$rnds."' LIMIT 1;");
$bs = mysql_fetch_array($rs);
$mes = $bs["message"];
$mess = $mes;
$bot8 = @mysql_query ("Select user from users where id='8' LIMIT 1;");
$zz1 = @mysql_fetch_array ($bot8);
$bot81 = $zz1["user"];
$rnd = rand(0,99999999);
$today=date ("H:i");
$time = getmicrotime();
$room="room".$rm;
mysql_query ("Insert into $room set klu4= '".$rnd."', time='".$today."', who='".$bot81."', message='".$mess."', id='".$time."', towhom='', hid='0', usid='8', komu='".$us."'");
mysql_query("ANALYZE TABLE $room");
}
}

##Анекдот по запросу
if ($msg=="!anekdot"||$msg=="!анекдот"){
$rs = mysql_query("select count(klu4) as num from anekdot");
$as = mysql_fetch_array($rs);
$rnds = rand(1,$as["num"]);
$rs = mysql_query ("SELECT message FROM anekdot WHERE klu4 = '".$rnds."' LIMIT 1;");
$bs = mysql_fetch_array($rs);
$mes = $bs["message"];
$mess = $mes;
$bot8 = @mysql_query ("Select user from users where id='6' LIMIT 1;");
$zz1 = @mysql_fetch_array ($bot8);
$bot81 = $zz1["user"];
$rnd = rand(0,99999999);
$today=date ("H:i");
$time = getmicrotime();
$room="room".$rm;
mysql_query ("Insert into $room set klu4= '".$rnd."', time='".$today."', who='".$bot81."', message='".$mess."', id='".$time."', towhom='', hid='0', usid='6', komu='".$us."'");
mysql_query("ANALYZE TABLE $room");
}
unset($msg);

$bind1=$row['bind1'];
$bind2=$row['bind2'];
$bind3=$row['bind3'];
$bind4=$row['bind4'];
$avr = $row["avr"];
$avr2 = $avr/10;
$time=date ("H:i");

if($rm==10) $takep="&amp;pwd=$pwd&amp;ref=$ref";
else if($mod=="privat") $takep="&amp;mod=$mod&amp;ref=$ref";
else $takep="&amp;ref=$ref";

$rem = mysql_query("SELECT topic FROM rooms where rm = '".$rm."'"); 
$iname = mysql_fetch_array ($rem); 
$topic = $iname["topic"];

$agent = htmlentities(addslashes($HTTP_USER_AGENT));

$r = mysql_query ("select count(readd) as num from zapiski WHERE (idtowhom = '".$id."')and(readd = '0')and(ininc = '1')");
$a = mysql_fetch_array($r);
$inb = $a["num"]; 

ob_start();
if ($ver=="wml"){
echo $xml;
echo $dtd;
echo "<wml>";
if ($avr!==0) echo "<card id=\"chat\" title=\"".$topic."-(".$time.")\" ontimer=\"chat.php?$ses&amp;rm=$rm$takep\"><timer value=\"".$avr."\"/>";
else echo "<card id=\"chat\" title=\"".$topic."-(".$time.")\">";
if ($row["kn_update"]==0) echo "<do type=\"options\" name=\"refresh\" label=\"Обновить\"><go href=\"chat.php?$ses&amp;rm=$rm$takep\"/></do>";
if ($row["kn_say"]==0){
if (((strpos ($agent,"M3Gate") !== false)||(strpos ($agent,"Opera") !== false)||(strpos ($agent,"emulator") !== false)||(strpos ($agent,"WinWAP") !== false)||(strpos ($agent,"Wapsilon") !== false)||(strpos ($agent,"Mozilla") !== false)||(strpos ($agent,"M3GATE") !== false))){
echo "<do type=\"options\" name=\"add\" label=\"Сказать\"><go href=\"chat.php?$ses&amp;rm=$rm$takep#add\"/></do>";
}else{
echo "<do type=\"options\" name=\"add\" label=\"Сказать\"><go href=\"#add\"/></do>";
}
}
if (($row["kn_privat"]==0)&&($rm!=10)){
if ($mod=="privat")echo "<do type=\"options\" name=\"privat\" label=\"Фильтр[P!]-выкл\"><go href=\"chat.php?$ses&amp;rm=$rm&amp;ref=$ref\"/></do>";
else echo "<do type=\"options\" name=\"privat\" label=\"Фильтр[P!]-вкл\"><go href=\"chat.php?$ses&amp;rm=$rm&amp;mod=privat$takep\"/></do>";
}
if ($row["kn_letters"]==0) echo "<do type=\"options\" name=\"mes\" label=\"Записки(".$inb.")\"><go href=\"chatmail.php?$ses&amp;rm=$rm$takep\"/></do>";
if ($row["kn_whochat"]==0) echo "<do type=\"options\" name=\"who\" label=\"Кто где?\"><go href=\"who.php?$ses&amp;rm=$rm$takep\"/></do>";
$room = "room".$rm;
$tm = time()-300;
$r = @mysql_query ("Select who from $room WHERE id > '".$tm."' group by who order by id desc;");
$asnum = mysql_affected_rows();
if (($row["kn_whoroom"]==0)&&($rm!=10)) echo "<do type=\"options\" name=\"who_room\" label=\"Кто тут?(".($asnum).")\"><go href=\"whoroom.php?$ses&amp;rm=$rm$takep\"/></do>";
if ($row["kn_nood"]==0) echo "<do type=\"options\" name=\"nastroi\" label=\"Настроение\"><go href=\"nood.php?$ses&amp;mod=select&amp;rm=$rm$takep\"/></do>";
if ($row["kn_holl"]==0) echo "<do type=\"options\" name=\"enter\" label=\"Прихожая\"><go href=\"enter.php?$ses&amp;rm=$rm$takep\"/></do>";
if ($row["kn_cabinet"]==0) echo "<do type=\"options\" name=\"enter\" label=\"Личное\"><go href=\"cabinet.php?$ses&amp;rm=$rm$takep\"/></do>";
if (($row["kn_stats"]==0)&&($rm==0)) echo "<do type=\"options\" name=\"stats\" label=\"Статистика\"><go href=\"statistik.php?$ses&amp;rm=$rm&amp;mod=10ym&amp;ref=$ref\"/></do>";
if (($row["kn_kommands"]==0)&&($rm==0)) echo "<do type=\"options\" name=\"kom\" label=\"Команды\"><go href=\"faq.php?$ses&amp;rm=$rm&amp;ref=$ref&amp;mod=vict_kom\"/></do>";
if (($row["trade"]==0)&&($rm==0)) echo "<do type=\"options\" name=\"trader\" label=\"Купи ответ\"><go href=\"prodavec.php?$ses&amp;rm=$rm$takep\"/></do>";
if (($rm!=9)&&($rm!=10)&&($row["level"]<4)) echo "<do type=\"options\" name=\"help\" label=\"Вызов Модера\"><go href=\"sos.php?$ses&amp;rm=$rm$takep\"/></do>";
if ($rm==10) echo "<do type=\"options\" name=\"klu4\" label=\"Сменить ключ\"><go href=\"intim.php?$ses&amp;ref=$ref\"/></do>";
if (($row["level"]>5)&&($rm!=10)) echo "<do type=\"options\" name=\"topic\" label=\"Топик\"><go href=\"topic.php?$ses&amp;rm=$rm$takep\"/></do>"; 
if (($rm==9)||($rm==11)) echo "<do type=\"options\" name=\"genmat\" label=\"Генератор мата\"><go href=\"./genmat/index.php?$ses&amp;rm=$rm&amp;ref=$ref\"/></do>";
echo "<p>";
}else{
echo "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">";
echo "<html xmlns=\"http://www.w3.org/1999/xhtml\">";
echo "<head><link rel=\"stylesheet\" type=\"text/css\" href=\"css/css.css\"/>";
echo "<title>".$topic."-(".$time.")</title>";
if ($avr==0) echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>";
else echo "<META HTTP-EQUIV=\"Refresh\" CONTENT=\"".$avr2."; URL=chat.php?$ses&amp;rm=$rm$takep\">";
echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/></head><body>";
echo "<div align=\"left\">";
}
echo $fsize1;
if($inb != "0") echo "<img src=\"smile/new.gif\" alt=\"NEW\"/><b>Вам письмо <a href=\"inbox.php?$ses&amp;rm=$rm&amp;ref=$ref\">(".$inb.")</a></b><br/>\n";
if ($ver=="wml"){
if (((strpos ($agent,"M3Gate") !== false)||(strpos ($agent,"Opera") !== false)||(strpos ($agent,"emulator") !== false)||(strpos ($agent,"WinWAP") !== false)||(strpos ($agent,"Wapsilon") !== false)||(strpos ($agent,"M3GATE") !== false))){
echo "<a href=\"chat.php?$ses&amp;rm=$rm$takep#add\" accesskey=\"$bind1\">Сказать(".$bind1.")</a><br/>";
}else{
echo "<a href=\"#add\" accesskey=\"$bind1\">Сказать(".$bind1.")</a><br/>";
}
}else{
echo "<div class=\"d1\"><a href=\"add.php?$ses&amp;rm=$rm$takep\" accesskey=\"$bind1\">Сказать(".$bind1.")</a></div>";
}
if ($ver=="wml"){ 
echo "<a href=\"chat.php?$ses&amp;rm=$rm$takep\" accesskey=\"$bind2\">Обновить(".$bind2.")</a><br/>---";
}else{ 
echo "<div class=\"d1\"><a href=\"chat.php?$ses&amp;rm=$rm$takep\" accesskey=\"$bind2\">Обновить(".$bind2.")</a></div>";	
echo "<div class=\"d1\"><a href=\"function.php?$ses&amp;rm=$rm$takep\" accesskey=\"3\">Функции(3)</a></div>";
}
@$total=$kol-1;
$mread = 0;

if ($smthwr != 0){
$komu = $usmes["komu"];
$date = $usmes["time"];
$klu4 = $usmes["klu4"];
$name = $usmes["who"];
$usid = $usmes["usid"];
$msg = $usmes["message"];
if ($smset==0&&$usmes["messagewosm"]!="") $msg = $usmes["messagewosm"];
if ($smset==2&&$usmes["messagewoasm"]!="") $msg = $usmes["messagewoasm"];
$time = $usmes["id"];
$th = $usmes["towhom"];
@mysql_query ("Select * from ignor where usid='".$usid."' and id='".$id."'");
if (mysql_affected_rows() == false){
$pols = @mysql_query ("SELECT sex FROM users where user='".$name."'");
$zs1 = @mysql_fetch_array ($pols);
$sex = $zs1["sex"];
if ($th == ""){
if (!empty($komu)) {
if ($us==$komu) $komu = "-<b>".$komu."</b>";
else $komu = "-".$komu."";
}
if ($row["level"]<5){
if ($ver=="wml"){
echo "<br/><b><a href=\"inside.php?$ses&amp;rm=$rm&amp;nk=$usid$takep\">".$name."</a></b>".$komu."(".$date.")\n".$msg.""; $mread++;
}else{
if ($sex=="М") {echo "<br/><img src=\"smile/pol_m.gif\" alt=\"М\"/><b><a href=\"inside.php?$ses&amp;rm=$rm&amp;nk=$usid$takep\">".$name."</a></b>".$komu."(".$date.")\n".$msg.""; $mread++;}
else {echo "<br/><img src=\"smile/pol_j.gif\" alt=\"Ж\"/><b><a href=\"inside.php?$ses&amp;rm=$rm&amp;nk=$usid$takep\">".$name."</a></b>".$komu."(".$date.")\n".$msg.""; $mread++;}
}
}else{
if ($ver=="wml"){
echo "<br/><b><a href=\"inside.php?$ses&amp;rm=$rm&amp;nk=$usid$takep\">".$name."</a>".$komu."</b>(".$date.")";
}else{
if ($sex=="М") {echo "<br/><img src=\"smile/pol_m.gif\" alt=\"М\"/><b><a href=\"inside.php?$ses&amp;rm=$rm&amp;nk=$usid$takep\">".$name."</a></b>".$komu."(".$date.")";}
else {echo "<br/><img src=\"smile/pol_j.gif\" alt=\"Ж\"/><b><a href=\"inside.php?$ses&amp;rm=$rm&amp;nk=$usid$takep\">".$name."</a></b>".$komu."(".$date.")";}
}
echo "<a href=\"delmess.php?$ses&amp;rm=$rm&amp;klu4=$klu4$takep\">[X]</a>\n".$msg.""; $mread++;
}
}
else if (($th == $id)||($id == $usid)){
if (!empty($komu)) {
if ($us==$komu) $komu = "-<b>".$komu."</b>";
else $komu = "-".$komu."";
}
if ($row["level"]<5){
if ($ver=="wml"){
echo "<br/><b><a href=\"inside.php?$ses&amp;rm=$rm&amp;nk=$usid$takep\">".$name."</a></b>".$komu."(".$date.")<b>[P!]</b>\n".$msg.""; $mread++;
}else{
if ($sex=="М") {echo "<br/><img src=\"smile/pol_m.gif\" alt=\"М\"/><b><a href=\"inside.php?$ses&amp;rm=$rm&amp;nk=$usid$takep\">".$name."</a></b>".$komu."(".$date.")<b>[P!]</b>\n".$msg.""; $mread++;}
else {echo "<br/><img src=\"smile/pol_j.gif\" alt=\"Ж\"/><b><a href=\"inside.php?$ses&amp;rm=$rm&amp;nk=$usid$takep\">".$name."</a></b>".$komu."(".$date.")<b>[P!]</b>\n".$msg.""; $mread++;}
}
}else{
if ($ver=="wml"){
echo "<br/><b><a href=\"inside.php?$ses&amp;rm=$rm&amp;nk=$usid$takep\">".$name."</a>".$komu."</b>(".$date.")<b>[P!]</b>";
}else{
if ($sex=="М") {echo "<br/><img src=\"smile/pol_m.gif\" alt=\"М\"/><b><a href=\"inside.php?$ses&amp;rm=$rm&amp;nk=$usid$takep\">".$name."</a>".$komu."</b>(".$date.")<b>[P!]</b>";}
else {echo "<br/><img src=\"smile/pol_j.gif\" alt=\"Ж\"/><b><a href=\"inside.php?$ses&amp;rm=$rm&amp;nk=$usid$takep\">".$name."</a>".$komu."</b>(".$date.")<b>[P!]</b>";}
}
echo "<a href=\"delmess.php?$ses&amp;rm=$rm&amp;klu4=$klu4$takep\">[X]</a>\n".$msg.""; $mread++;
}
}
}
}
while ($mread < $max){
$lines = mysql_fetch_array ($res);
if($lines===false)break;
$komu = $lines["komu"];
$date = $lines["time"];
$klu4 = $lines["klu4"];
$name = $lines["who"];
$usid = $lines["usid"];
$msg = $lines["message"];
if ($smset==0&&$lines["messagewosm"]!="") $msg = $lines["messagewosm"];
if ($smset==2&&$lines["messagewoasm"]!="") $msg = $lines["messagewoasm"];
$time = $lines["id"];
$th = $lines["towhom"];
$hid = $lines["hid"];
@mysql_query ("Select * from ignor where usid='".$usid."' and id='".$id."'");
if ((mysql_affected_rows() == false)&&(($hid != 2)||($id == $usid))){
$pols = @mysql_query ("SELECT sex FROM users where user='".$name."'");
$zs1 = @mysql_fetch_array ($pols);
$sex = $zs1["sex"];
if ($th == ""){
if (!empty($komu)) {
if ($us==$komu) $komu = "-<b>".$komu."</b>";
else $komu = "-".$komu."";
}
if ($row["level"]<5){
if ($ver=="wml"){
echo "<br/><b><a href=\"inside.php?$ses&amp;rm=$rm&amp;rm=$rm&amp;nk=$usid$takep\">".$name."</a></b>".$komu."(".$date.")\n".$msg."";$mread++;
}else{
if ($sex=="М") {echo "<br/><img src=\"smile/pol_m.gif\" alt=\"М\"/><b><a href=\"inside.php?$ses&amp;rm=$rm&amp;nk=$usid$takep\">".$name."</a></b>".$komu."(".$date.")\n".$msg.""; $mread++;}
else {echo "<br/><img src=\"smile/pol_j.gif\" alt=\"Ж\"/><b><a href=\"inside.php?$ses&amp;rm=$rm&amp;nk=$usid$takep\">".$name."</a></b>".$komu."(".$date.")\n".$msg.""; $mread++;}
}
}else{
if ($ver=="wml"){
echo "<br/><b><a href=\"inside.php?$ses&amp;rm=$rm&amp;nk=$usid$takep\">".$name."</a></b>".$komu."(".$date.")";
}else{
if ($sex=="М") {echo "<br/><img src=\"smile/pol_m.gif\" alt=\"М\"/><b><a href=\"inside.php?$ses&amp;rm=$rm&amp;nk=$usid$takep\">".$name."</a></b>".$komu."(".$date.")";}
else {echo "<br/><img src=\"smile/pol_j.gif\" alt=\"Ж\"/><b><a href=\"inside.php?$ses&amp;rm=$rm&amp;nk=$usid$takep\">".$name."</a></b>".$komu."(".$date.")";}
}
echo "<a href=\"delmess.php?$ses&amp;rm=$rm&amp;klu4=$klu4$takep\">[X]</a>\n".$msg."";$mread++;
}
} else {
if (($th == $id)||($id == $usid)){
if (!empty($komu)) {
if ($us==$komu) $komu = "-<b>".$komu."</b>";
else $komu = "-".$komu."";
}
if ($row["level"]<5){
if ($ver=="wml"){
echo "<br/><b><a href=\"inside.php?$ses&amp;rm=$rm&amp;nk=$usid$takep\">".$name."</a>".$komu."</b>(".$date.")<b>[P!]</b>\n"
.$msg."";$mread++;
}else{
if ($sex=="М") {echo "<br/><img src=\"smile/pol_m.gif\" alt=\"М\"/><b><a href=\"inside.php?$ses&amp;rm=$rm&amp;nk=$usid$takep\">".$name."</a></b>".$komu."(".$date.")<b>[P!]</b>\n".$msg.""; $mread++;}
else {echo "<br/><img src=\"smile/pol_j.gif\" alt=\"Ж\"/><b><a href=\"inside.php?$ses&amp;rm=$rm&amp;nk=$usid$takep\">".$name."</a></b>".$komu."(".$date.")<b>[P!]</b>\n".$msg.""; $mread++;}
}
}else{
if ($ver=="wml"){
echo "<br/><b><a href=\"inside.php?$ses&amp;rm=$rm&amp;nk=$usid$takep\">".$name."</a>".$komu."</b>(".$date.")<b>[P!]</b>";
}else{
if ($sex=="М") {echo "<br/><img src=\"smile/pol_m.gif\" alt=\"М\"/><b><a href=\"inside.php?$ses&amp;rm=$rm&amp;nk=$usid$takep\">".$name."</a>".$komu."</b>(".$date.")<b>[P!]</b>";}
else {echo "<br/><img src=\"smile/pol_j.gif\" alt=\"Ж\"/><b><a href=\"inside.php?$ses&amp;rm=$rm&amp;nk=$usid$takep\">".$name."</a>".$komu."</b>(".$date.")<b>[P!]</b>";}
}
echo "<a href=\"delmess.php?$ses&amp;rm=$rm&amp;klu4=$klu4$takep\">[X]</a>\n".$msg."";$mread++;
}
}
}
}
}
$page_next = $max;
if ($ver=="wml") echo "<br/>---";
else echo "<br/><br/>";
if ($max < $total){
if ($ver=="wml") echo "<br/><a href=\"history.php?$ses&amp;rm=$rm&amp;num=$page_next$takep\" accesskey=\"$bind3\">История(".$bind3.") &#8594;</a>";
else echo "<div class=\"d1\"><a href=\"history.php?$ses&amp;rm=$rm&amp;num=$page_next$takep\" accesskey=\"$bind3\">История(".$bind3.") &#8594;</a></div>";
}
if ($ver=="wml") echo "<br/><a href=\"enter.php?$ses&amp;ref=$ref\" accesskey=\"$bind4\">&#8592; Прихожая(".$bind4.")</a><br/>";
else echo "<div class=\"d1\"><a href=\"enter.php?$ses&amp;ref=$ref\" accesskey=\"$bind4\">&#8592; Прихожая(".$bind4.")</a></div>";
if ($ver=="wml") echo $divide;
$pagesize=round((ob_get_length()+200)/1024,1);
if ($ver=="wml") echo "[Вес страницы: <a href=\"trafik.php?$ses&amp;rm=$rm$takep\">".$pagesize." кб.</a>]<br/>";
else echo "<div class=\"d1\">[Вес страницы: <a href=\"trafik.php?$ses&amp;rm=$rm$takep\">".$pagesize." кб.</a>]<br/></div>";
info_compress();
echo $fsize2;
if ($ver=="wml")echo "</p></card>";
else echo "</div></body></html>";
if ($ver=="wml"){
echo "<card id=\"add\" title=\"Сказать\">";
echo "<p>";
echo $fsize1;
echo "Текст<br/>\n";
echo $fsize2;
echo "<input name=\"msg$ref\" maxlength=\"200\" title=\"Text\"/><br/>";
if ($row["level"]>=4){
echo $fsize1;
echo "Шрифт<br/>\n";
echo $fsize2;
echo "<select name=\"shrift\">\n";
echo "<option value=\"0\">Обычный</option>\n";
echo "<option value=\"1\">Наклонный</option>\n";
}
if ($row["level"]>=5) {echo "<option value=\"2\">Подчёркнутый</option>\n";}
if ($row["level"]>=6) {echo "<option value=\"3\">Накл. и подч.</option>\n";}
if ($row["level"]>=6) {echo "<option value=\"4\">Жирный</option>\n";}
if ($row["level"]>=7) {echo "<option value=\"5\">Жирн. и подч.</option>\n";}
if ($row["level"]>=7) {echo "<option value=\"6\">Огромный</option>\n";}
if ($row["level"]>=4) {echo "</select><br/>\n";}
echo $fsize1;
echo "<anchor title=\"send\">Сказать<go href=\"chat.php?$ses&amp;rm=$rm$takep\" method=\"post\">";
echo "<postfield name=\"msg\" value=\"$(msg$ref)\"/>";
echo "<postfield name=\"shrift\" value=\"$(shrift)\"/>\n";
echo "</go></anchor>";
echo $fsize2;
echo "<br/>";
echo $fsize1;
echo $divide;
echo "<a href=\"chat.php?$ses&amp;rm=$rm$takep\">В чат</a>";
echo $fsize2;
echo "</p></card>";
echo "</wml>";
}
}else{
## Файл Мафия            
## Модуль задаёт имя мафиозии ##
$maf = @mysql_query ("Select user,id from users where id='5' LIMIT 1;");
$x = @mysql_fetch_array ($maf);
$mafiozi = $x["user"];
$mafid = $x["id"];
$rmafaction = "mafaction".$rm;
$rscores = "scores".$rm;
$ringame = "ingame".$rm;

## В игре человек или нет: ##
mysql_query ("select * from $ringame WHERE gamer_id = '".$id."'");
if (mysql_affected_rows()!=0) $gmes = 1; 
else $gmes = 0;  

## Проверка, на связи ли человек: ##     
$tm = time()-300;
$r = mysql_query ("select * from $ringame WHERE (onl<'".$tm."')");
if (mysql_affected_rows() != 0){ 
$mmsg = "";        

while (($a = mysql_fetch_array($r))!==false){
$grole = get_role_by_id($a["id_in_game"], $rm);
$gname = get_name_by_id($a["id_in_game"], $rm);                
$gid = $a["gamer_id"];
$mmsg = $mmsg."$grole $gname покидает игру (превышено время ожидания ответа)! ";    
     
## Вычитаем очки: ##   
mysql_query("update users set creditsingame = creditsingame - 100 WHERE id = '".$gid."'");
$r = mysql_query("select creditsingame from users WHERE id = '".$gid."'");
$a = mysql_fetch_array($r);
$cring = $a["creditsingame"];     
## Записываем для дальнейшего вывода, кто сколько очков набрал ##
mysql_query("insert into $rscores set gamer_id = '".$gid."', score = '".$cring."'"); 
mysql_query("delete from $ringame WHERE gamer_id = '".$gid."'"); 
}          
$tm = getmicrotime();
$today=date ("H:i");
$rnd = rand(0,99999999); 
mysql_query ("Insert into $room set klu4= '".$rnd."', time='".$today."', who='".$mafiozi."', usid = '".$mafid."', message='".$mmsg."', id='".$tm."', towhom='', gamemes='1', komu=''");
mysql_query ("Update users set posts = posts + 1 WHERE id = '".$mafid."'");         
$vktr = false; 

$r = mysql_query("select count(*) as sm from $ringame");
$a = mysql_fetch_array($r);
$sm = $a["sm"];  

mysql_query ("select * from $ringame WHERE role = 'главарь мафии'");
if (mysql_affected_rows()==0&&$sm!=0){
$r = mysql_query ("select * from $ringame WHERE role = 'мафиози'");
if (mysql_affected_rows()==0){ 
$vktr = true;
mysql_query ("update $rmafaction set action = 'nogame'"); 
                 
$r = mysql_query("select role, gamer_id from $ringame");
while (($a = mysql_fetch_array($r))!==false){
$role = $a["role"];
$gamer_id = $a["gamer_id"];
if ($role == "обыватель") mysql_query("update users set creditsingame = creditsingame + 100 WHERE id = '".$gamer_id."'"); 
else mysql_query("update users set creditsingame = creditsingame + 50 WHERE id = '".$gamer_id."'");
}
$mmsg = "Игра окончена, победа мирных жителей! А роли были такие: "; 
$r = mysql_query("Select * from $ringame");
while (($a = mysql_fetch_array($r))!==false){ 
$gnick = get_name_by_id($a["id_in_game"], $rm);
$grole = get_role_by_id($a["id_in_game"], $rm);
$mmsg = $mmsg."<b>$gnick</b> - $grole, ";
} 
$mmsg = substr($mmsg,0,strlen($mmsg)-2);  
mysql_query("insert into $rscores select gamer_id, creditsingame from $ringame, users WHERE users.id = $ringame.gamer_id");
mysql_query ("delete from $ringame");
$tm = getmicrotime();
$today=date ("H:i");
$rnd = rand(0,99999999); 
mysql_query ("Insert into $room set klu4= '".$rnd."', time='".$today."', who='".$mafiozi."', usid='".$mafid."', message='".$mmsg."', id='".$tm."', towhom='', gamemes='1', komu=''"); 
mysql_query ("Update users set posts = posts + 1 WHERE id = '".$mafid."'"); 
$mmsg = "За эту игру заработали столько очков: "; 
$mmes = scores($rm); 
$mmsg = $mmsg.$mmes; 
$tm = getmicrotime();
$today=date ("H:i");
$rnd = rand(0,99999999); 
mysql_query ("Insert into $room set klu4= '".$rnd."', time='".$today."', who='".$mafiozi."', usid='".$mafid."', message='".$mmsg."', id='".$tm."', towhom='', gamemes='1', komu=''"); mysql_query ("Update users set posts = posts + 1 WHERE id = '".$mafid."'");
}else{ 
$a = mysql_fetch_array($r);  
$id_in_game = $a["id_in_game"];
$gamer_id = $a["gamer_id"];
$igrok = @mysql_fetch_array(@mysql_query ("Select user from users where id='".$gamer_id."' LIMIT 1;"));
mysql_query ("update $ringame set role = 'главарь мафии' WHERE id_in_game = '".$id_in_game."'");
$mmsg = "Теперь вы главарь мафии!"; 
$tm = getmicrotime();
$today=date ("H:i");
$rnd = rand(0,99999999); 
mysql_query ("Insert into $room set klu4= '".$rnd."', time='".$today."', who='".$mafiozi."', usid='".$mafid."', message='".$mmsg."', id='".$tm."', towhom='".$gamer_id."', gamemes='1', komu='".$igrok[0]."'");            
mysql_query ("Update users set posts = posts + 1 WHERE id = '".$mafid."'");
}
} 

if ($vktr!==true){

$r = mysql_query ("select count(*) as sm from $ringame");
$a = mysql_fetch_array($r); 

if ($a["sm"]==2){
mysql_query("select * from $ringame WHERE (role = 'главарь мафии')or(role = 'мафиози')"); 

if (mysql_affected_rows()==2) $vk = "maf";
if (mysql_affected_rows()==1){
mysql_query("select * from $ringame WHERE (role = 'доктор')or(role = 'комиссар катани')or(role = 'путана')or(role = 'маньяк')");   
if (mysql_affected_rows() != 0) $vk = "ni4"; else $vk = "maf";
}
}
if ($a["sm"]==1){
mysql_query ("select * from $ringame WHERE (role = 'главарь мафии')or(role = 'мафиози')");
if (mysql_affected_rows() != 0) $vk = "maf";
}
if ($a["sm"]==0) $vk = "ni4";
 
mysql_query("select * from $ringame");
$nm = round(mysql_affected_rows()/2-0.5); 
$r = mysql_query("Select count(*) as sm from $ringame WHERE (role='мафиози')or(role='главарь мафии')");
$a = mysql_fetch_array($r);
$sm = $a["sm"];
if ($sm>$nm) $vk = "maf";

if (isset($vk)){ 
$vktr = true;
if ($vk == "ni4"){ 
$vktr = true;
mysql_query ("update $rmafaction set action = 'nogame'");
$r = mysql_query("select gamer_id from $ringame");
while (($a = mysql_fetch_array($r))!==false){
$gamer_id = $a["gamer_id"];
mysql_query("update users set creditsingame = creditsingame + 25 WHERE id = '".$gamer_id."'"); 
}
$mmsg = "Силы Мафии и мирных жителей равны, ничья! А роли были такие: "; 
$r = mysql_query("Select * from $ringame");
while (($a = mysql_fetch_array($r))!==false){ 
$gnick = get_name_by_id($a["id_in_game"], $rm);
$grole = get_role_by_id($a["id_in_game"], $rm);
$mmsg = $mmsg."<b>$gnick</b> - $grole, ";
} 
$mmsg = substr($mmsg,0,strlen($mmsg)-2);  
mysql_query("insert into $rscores select gamer_id, creditsingame from $ringame, users WHERE users.id = $ringame.gamer_id");
mysql_query ("delete from $ringame");
$tm = getmicrotime();
$today=date ("H:i");
$rnd = rand(0,99999999); 
mysql_query ("Insert into $room set klu4= '".$rnd."', time='".$today."', who='".$mafiozi."', usid='".$mafid."', message='".$mmsg."', id='".$tm."', towhom='', gamemes='1', komu=''");
mysql_query ("Update users set posts = posts + 1 WHERE id = '".$mafid."'"); 
$mmsg = "За эту игру заработали столько очков: "; 
$mmes = scores($rm); 
$mmsg = $mmsg.$mmes;
$tm = getmicrotime();
$today=date ("H:i");
$rnd = rand(0,99999999); 
mysql_query ("Insert into $room set klu4= '".$rnd."', time='".$today."', who='".$mafiozi."', usid='".$mafid."', message='".$mmsg."', id='".$tm."', towhom='', gamemes='1', komu=''"); 
mysql_query ("Update users set posts = posts + 1 WHERE id = '".$mafid."'");
}
if ($vk == "maf"){ 
$vktr = true;
mysql_query ("update $rmafaction set action = 'nogame'"); 
$r = mysql_query("select role, gamer_id from $ringame");
while (($a = mysql_fetch_array($r))!==false){
$role = $a["role"];
$gamer_id = $a["gamer_id"];
if ($role == "мафиози"||$role == "главарь мафии") 
mysql_query("update users set creditsingame = creditsingame + 50 WHERE id = '".$gamer_id."'"); 
}
$mmsg = "Всем хана, победа Мафов! А роли были такие: "; 
$r = mysql_query("Select * from $ringame");
while (($a = mysql_fetch_array($r))!==false){ 
$gnick = get_name_by_id($a["id_in_game"], $rm);
$grole = get_role_by_id($a["id_in_game"], $rm);
$mmsg = $mmsg."<b>$gnick</b> - $grole, ";
} 
$mmsg = substr($mmsg,0,strlen($mmsg)-2);
mysql_query("insert into $rscores select gamer_id, creditsingame from $ringame, users WHERE users.id = $ringame.gamer_id");
mysql_query ("delete from $ringame");
$tm = getmicrotime();
$today=date ("H:i");
$rnd = rand(0,99999999); 
mysql_query ("Insert into $room set klu4= '".$rnd."', time='".$today."', who='".$mafiozi."', usid='".$mafid."', message='".$mmsg."', id='".$tm."', towhom='', gamemes='1', komu=''");
mysql_query ("Update users set posts = posts + 1 WHERE id = '".$mafid."'");    
$mmsg = "За эту игру заработали столько очков: "; 
$mmes = scores($rm); 
$mmsg = $mmsg.$mmes;
$tm = getmicrotime();
$today=date ("H:i");
$rnd = rand(0,99999999); 
mysql_query ("Insert into $room set klu4= '".$rnd."', time='".$today."', who='".$mafiozi."', usid='".$mafid."', message='".$mmsg."', id='".$tm."', towhom='', gamemes='1', komu=''"); 
mysql_query ("Update users set posts = posts + 1 WHERE id = '".$mafid."'");
}
} 
}
}
$tm = time();
mysql_query ("update users set onl = '".$tm."' WHERE id = '".$id."'"); 
if ($gmes == 1) mysql_query ("update $ringame set onl = '".$tm."' WHERE gamer_id = '".$id."'");
$r = mysql_query ("select * from $rmafaction");
$a = mysql_fetch_array($r);
$action = $a["action"];         
$nexttime = $a["nexttime"]; 

if (($action == "game_night"&&$tm>$nexttime)||($action == "dvote"&&$tm>$nexttime)){ 
$tm = time()+120;
mysql_query ("update $rmafaction set action = 'game_day', nexttime = '".$tm."', kiked = '0', cround = cround + 1"); 
$kiked = $a["kiked"];
if ($kiked==1) $mmsg = "Наступает ночь, все жители засыпают, кроме некоторых..."; 
else $mmsg = "Жители, прогалдев целый день, так ничего и не решили. Наступает ночь...";

mysql_query("update $ringame set dvote = '0', wholin = '0'");

$tm = getmicrotime();
$today=date ("H:i");
$rnd = rand(0,99999999); 
mysql_query ("Insert into $room set klu4= '".$rnd."', time='".$today."', who='".$mafiozi."', usid = '".$mafid."', message='".$mmsg."', id='".$tm."', towhom='', gamemes='1', komu=''"); 
mysql_query ("Update users set posts = posts + 1 WHERE id = '".$mafid."'");           

mysql_query("select gamer_id from $ringame WHERE role = 'комиссар катани'");
if(mysql_affected_rows()==0){ 
$r = mysql_query("select state from $ringame WHERE role = 'жена комиссара'");      
if (mysql_affected_rows()!=0){ 
$a = mysql_fetch_array($r);
if ($a["state"]==0) mysql_query ("update $ringame set state = '1' WHERE role = 'жена комиссара'");
}
}
 
mysql_query("update $ringame set gamer_act = ''");
$r = mysql_query("select * from $ringame WHERE role = 'мафиози'");
if (mysql_affected_rows()!=0){
while (($a = mysql_fetch_array($r))!==false){
$thg = $a["gamer_id"];
$igrok = @mysql_fetch_array(@mysql_query ("Select user from users where id='".$thg."' LIMIT 1;"));
$re = mysql_query("select * from $ringame WHERE ((role = 'мафиози')or(role = 'главарь мафии'))and(gamer_id != '".$thg."')");
$so = "";
while (($b = mysql_fetch_array($re))!==false){
$sname = get_name_by_id($b["id_in_game"], $rm);
if (get_role_by_id($b["id_in_game"], $rm)!="главарь мафии") $so = $so."$sname, "; else $so = $so."$sname(главарь), ";
}    
$so = substr($so,0,strlen($so)-2);
$mmsg = "Сообщники: $so";
$tm = getmicrotime();
$today=date ("H:i");
$rnd = rand(0,99999999); 
mysql_query ("Insert into $room set klu4= '".$rnd."', time='".$today."', who='".$mafiozi."', usid='".$mafid."', message='".$mmsg."', id='".$tm."', towhom='".$thg."', gamemes='1', komu='".$igrok[0]."'");  
mysql_query ("Update users set posts = posts + 1 WHERE id = '".$mafid."'");  
}          
}

$r = mysql_query("select * from $ringame WHERE role = 'главарь мафии'");
$a = mysql_fetch_array($r);
$glmaf_id = $a["gamer_id"];             
$igrok = @mysql_fetch_array(@mysql_query ("Select user from users where id='".$glmaf_id."' LIMIT 1;"));
$mmsg = "Выбирайте, кому сегодня не поздоровится(!номер, в приват Мафу): ";
$r = mysql_query("select * from $ringame");
$kol = mysql_affected_rows();
for ($i=1;$i<=$kol;$i++){
$a = mysql_fetch_array($r);
$gamer_id = $a["gamer_id"];
$r2 = mysql_query ("select * from users where id = '".$gamer_id."'");
$b = mysql_fetch_array($r2);
$gname = $b["user"];
$id_in_game = $a["id_in_game"];
$s = $s."$id_in_game - $gname, "; 
}      
$mmsg = $mmsg.$s;
$mmsg = substr($mmsg,0,strlen($mmsg)-2);

$r = mysql_query ("select * from $ringame WHERE role = 'мафиози'"); 
if (mysql_affected_rows()!=0){
$sg = "";
while (($a = mysql_fetch_array($r))!==false){
$sname = get_name_by_id($a["id_in_game"], $rm);
$sg = $sg."$sname, ";
}
$sg = substr($sg,0,strlen($sg)-2);
$mmsg = $mmsg."<br/>"."(ваши сообщники: $sg)";
}

$tm = getmicrotime();
$today=date ("H:i");
$rnd = rand(0,99999999); 
mysql_query ("Insert into $room set klu4= '".$rnd."', time='".$today."', who='".$mafiozi."', usid = '".$mafid."', message='".$mmsg."', id='".$tm."', towhom='".$glmaf_id."', gamemes='1', komu='".$igrok[0]."'"); 
mysql_query ("Update users set posts = posts + 1 WHERE id = '".$mafid."'");           
          
$r = mysql_query("select * from $ringame WHERE role = 'комиссар катани'"); 
if (mysql_affected_rows()!=0){
$a = mysql_fetch_array($r);
$kom_id = $a["gamer_id"];
$igrok = @mysql_fetch_array(@mysql_query ("Select user from users where id='".$kom_id."' LIMIT 1;"));
$mmsg = "Выбирайте, кого проверить (!номер, в приват Мафу) или убить (!!номер): ".$s;
$tm = getmicrotime();
$today=date ("H:i");
$rnd = rand(0,99999999); 
mysql_query ("Insert into $room set klu4= '".$rnd."', time='".$today."', who='".$mafiozi."', usid='".$mafid."', message='".$mmsg."', id='".$tm."', towhom='".$kom_id."', gamemes='1', komu='".$igrok[0]."'"); 
mysql_query ("Update users set posts = posts + 1 WHERE id = '".$mafid."'");           
}

$r = mysql_query("select * from $ringame WHERE role = 'маньяк'"); 
if (mysql_affected_rows()!=0){
$a = mysql_fetch_array($r);
$man_id = $a["gamer_id"];
$igrok = @mysql_fetch_array(@mysql_query ("Select user from users where id='".$man_id."' LIMIT 1;"));
$mmsg = "Кто же будет жертвой маньяка? (!номер, в приват Мафу): ".$s;
$tm = getmicrotime();
$today=date ("H:i");
$rnd = rand(0,99999999); 
mysql_query ("Insert into $room set klu4= '".$rnd."', time='".$today."', who='".$mafiozi."', usid = '".$mafid."', message='".$mmsg."', id='".$tm."', towhom='".$man_id."', gamemes='1', komu='".$igrok[0]."'"); 
mysql_query ("Update users set posts = posts + 1 WHERE id = '".$mafid."'");           
}

$r = mysql_query("select * from $ringame WHERE role = 'путана'");  
if (mysql_affected_rows()!=0){
$a = mysql_fetch_array($r);
$put_id = $a["gamer_id"];
$igrok = @mysql_fetch_array(@mysql_query ("Select user from users where id='".$put_id."' LIMIT 1;"));
$mmsg = "К кому же шлюха направится сегодня? (!номер, в приват Мафу): ".$s;
$tm = getmicrotime();
$today=date ("H:i");
$rnd = rand(0,99999999); 
mysql_query ("Insert into $room set klu4= '".$rnd."', time='".$today."', who='".$mafiozi."', usid='".$mafid."', message='".$mmsg."', id='".$tm."', towhom='".$put_id."', gamemes='1', komu='".$igrok[0]."'");   
mysql_query ("Update users set posts = posts + 1 WHERE id = '".$mafid."'");         
}
  
$r = mysql_query("select * from $ringame WHERE role = 'бомж'"); 
if (mysql_affected_rows()!=0){
$a = mysql_fetch_array($r);
$bomj_id = $a["gamer_id"];
$igrok = @mysql_fetch_array(@mysql_query ("Select user from users where id='".$bomj_id."' LIMIT 1;"));
$mmsg = "У кого роемся в карманах? (!номер, в приват Мафу): ".$s;
$tm = getmicrotime();
$today=date ("H:i");
$rnd = rand(0,99999999); 
mysql_query ("Insert into $room set klu4= '".$rnd."', time='".$today."', who='".$mafiozi."', usid='".$mafid."', message='".$mmsg."', id='".$tm."', towhom='".$bomj_id."', gamemes='1', komu='".$igrok[0]."'");    
mysql_query ("Update users set posts = posts + 1 WHERE id = '".$mafid."'");           
}

$r = mysql_query("select * from $ringame WHERE role = 'доктор'");
if (mysql_affected_rows()!=0){ 
$a = mysql_fetch_array($r);
$dok_id = $a["gamer_id"];
$igrok = @mysql_fetch_array(@mysql_query ("Select user from users where id='".$dok_id."' LIMIT 1;"));
$mmsg = "Кого лечим? (!номер, в приват Мафу): ".$s;
$tm = getmicrotime();
$today=date ("H:i");
$rnd = rand(0,99999999); 
mysql_query ("Insert into $room set klu4= '".$rnd."', time='".$today."', who='".$mafiozi."', usid='".$mafid."', message='".$mmsg."', id='".$tm."', towhom='".$dok_id."', gamemes='1', komu='".$igrok[0]."'");          
mysql_query ("Update users set posts = posts + 1 WHERE id = '".$mafid."'");  
}      

$r = mysql_query("select * from $ringame WHERE role = 'клоун'"); 
$a = mysql_fetch_array($r);
$state = $a["state"];
if (mysql_affected_rows()!=0&&$state==0){ 
$kloun_id = $a["gamer_id"];
$igrok = @mysql_fetch_array(@mysql_query ("Select user from users where id='".$kloun_id."' LIMIT 1;"));
$mmsg = "Выберите, чьи роли поменять местами(''!номер !номер'', через пробел, в приват Мафу): ".$s;
$tm = getmicrotime();
$today=date ("H:i");
$rnd = rand(0,99999999); 
mysql_query ("Insert into $room set klu4= '".$rnd."', time='".$today."', who='".$mafiozi."', usid='".$mafid."', message='".$mmsg."', id='".$tm."', towhom='".$kloun_id."', gamemes='1', komu='".$igrok[0]."'");          
mysql_query ("Update users set posts = posts + 1 WHERE id = '".$mafid."'");  
}   

$r = mysql_query("select * from $ringame WHERE role = 'жена комиссара'"); 
$a = mysql_fetch_array($r);
$state = $a["state"];
if (mysql_affected_rows()!=0&&$state==1){ 
$jena_id = $a["gamer_id"];
$igrok = @mysql_fetch_array(@mysql_query ("Select user from users where id='".$jena_id."' LIMIT 1;"));
$mmsg = "На кого выпустим нашу месть? (!номер, в приват Мафу): ".$s;
$tm = getmicrotime();
$today=date ("H:i");
$rnd = rand(0,99999999); 
mysql_query ("Insert into $room set klu4= '".$rnd."', time='".$today."', who='".$mafiozi."', usid='".$mafid."', message='".$mmsg."', id='".$tm."', towhom='".$jena_id."', gamemes='1', komu='".$igrok[0]."'");          
mysql_query ("Update users set posts = posts + 1 WHERE id = '".$mafid."'");  
}
} 

if (($action=="game_day"&&$tm>$nexttime)||$action == "allvoted"){ 
$tm = time()+180;
mysql_query ("update $rmafaction set action = 'game_night', nexttime = '".$tm."'"); 
$kom_kil = 0;
$maf_kil = 0;
$man_kil = 0;  
$jena_kil = 0;
$mmsg = "Вот и день наступил. Но все ли дожили до него?";
$r = mysql_query("select * from $ringame WHERE role = 'путана'");
$a = mysql_fetch_array($r);
$put_act = 0;
$put_act = $a["gamer_act"];
$put_id = $a["gamer_id"]; 

$r = mysql_query("select * from $ringame WHERE role = 'горец'");
$a = mysql_fetch_array($r);
$gor_id_in_game = $a["id_in_game"];

if ($put_act != 0) mysql_query("update users set creditsingame = creditsingame + 5 WHERE id = '".$put_id."'"); 

$r = mysql_query("select * from $ringame WHERE role = 'доктор'");
$a = mysql_fetch_array($r);
$doknotact = false;
$dok_act = 0;
if ($put_act != $a["id_in_game"]) $dok_act = $a["gamer_act"]; 

$r = mysql_query("select * from $ringame WHERE role = 'комиссар катани'");
if (mysql_affected_rows()!=0){ 
$a = mysql_fetch_array($r);
$kom_id = $a["gamer_id"];
$igrok = @mysql_fetch_array(@mysql_query ("Select user from users where id='".$kom_id."' LIMIT 1;"));
if ($a["gamer_act"]!=""){
$wh = get_name_by_id($a["gamer_act"], $rm);
if ($put_act==$a["id_in_game"]) $mmsg = $mmsg." Инспектор катани всю ночь был занят шлюхой, и не успел отловить бандитов."; 
else if (strpos($a["gamer_act"],"!")===false){
mysql_query("update users set creditsingame = creditsingame + 5 WHERE id = '".$kom_id."'");
$mmsg = $mmsg." Инспектор катани времени зря не терял. Проведя тщательное расследование, он наконец-то выяснил, кто такой $wh!";
if (get_role_by_id($a["gamer_act"], $rm)=="мафиози"||get_role_by_id($a["gamer_act"], $rm)=="главарь мафии")$tokom = "$wh - мафиози"; 
else $tokom = "$wh - мирный житель";  
$tm = getmicrotime();
$today=date ("H:i");
$rnd = rand(0,99999999); 
mysql_query ("Insert into $room set klu4= '".$rnd."', time='".$today."', who='".$mafiozi."', usid='".$mafid."', message='".$tokom."', id='".$tm."', towhom='".$kom_id."', gamemes='1', komu='".$igrok[0]."'");              
mysql_query ("Update users set posts = posts + 1 WHERE id = '".$mafid."'");
}else{
$a["gamer_act"] = str_replace("!","",$a["gamer_act"]);
$wh = get_name_by_id($a["gamer_act"], $rm);
$kto = role_to_rpadej(get_role_by_id($a["gamer_act"], $rm));  
if ($gor_id_in_game!=$a["gamer_act"]){
if ($a["gamer_act"] != $dok_act){ 
if (get_role_by_id($a["gamer_act"], $rm)=="мафиози"||get_role_by_id($a["gamer_act"], $rm)=="главарь мафии") {$mmsg = $mmsg." Проведя сложнейшую операцию, инспектор катани наконец-то вычислил и убил $kto $wh!!!"; mysql_query("update users set creditsingame = creditsingame + 20 WHERE id = '".$kom_id."'");}
else {$mmsg = $mmsg." Инспектор катани так спятил, что казнил ни в чем не повинного $kto $wh!"; mysql_query("update users set creditsingame = creditsingame - 20 WHERE id = '".$kom_id."'");}
$kom_kil = $a["gamer_act"];
}else { 
$mmsg = $mmsg." Комиссар катани почти расстрелял $wh, но добрый доктор буквально достал того из гроба."; 
$doknotact = true;
}
}else {    
$mmsg = $mmsg." Комиссар катани расстрелял ночью горца, и был очень удивлен, когда тот не умер.";
}                                                                                                                                      }
}          
}    

$r = mysql_query("select * from $ringame WHERE role = 'главарь мафии'");
$a = mysql_fetch_array($r);
$maf_id = $a["gamer_id"];
if ($a["gamer_act"]!=""){
$wh = get_name_by_id($a["gamer_act"], $rm);
if ($put_act==$a["id_in_game"]) $mmsg = $mmsg." Шлюха направилась в логово к мафии и всю ночь пробыла с главарем мафии, отвлекая его от дел."; 
else{   
if ($gor_id_in_game != $a["gamer_act"]){
mysql_query("update users set creditsingame = creditsingame + 10 WHERE id = '".$maf_id."'");
$kto = role_to_tpadej(get_role_by_id($a["gamer_act"], $rm));  
if ($dok_act != $a["gamer_act"]){
$mmsg = $mmsg." Мафия сегодня зверски расправилась с $kto $wh!";             
$maf_kil = $a["gamer_act"];
}else{ 
$mmsg = $mmsg." Мафы убили $wh, но доктор сгонял на кладбище и пришил ему все обратно";    
$doknotact = true; 
} 
}else{ 
$mmsg = $mmsg." Мафия ночью нарвалась на горца, он ей так накостылял, что мафы еле ноги унесли.";
}
}
}
  
$r = mysql_query("select * from $ringame WHERE role = 'маньяк'");
if (mysql_affected_rows()!=0){ 
$a = mysql_fetch_array($r);
$man_id = $a["gamer_id"];
$man_act = $a["gamer_act"]; 
if ($a["gamer_act"]!=""){                    
$wh = get_name_by_id($a["gamer_act"], $rm);
if ($put_act==$a["id_in_game"]) $mmsg = $mmsg." Маньяк так хотел намотать кишки на руку кому-нибудь этой ночью, но встретил шлюху и решил отложить это дело."; 
else{        
$kto = get_role_by_id($a["gamer_act"], $rm); 
if ($dok_act != $a["gamer_act"]){  
mysql_query("select * from $ringame WHERE (id_in_game = '".$man_act."')and((role = 'мафиози')or(role = 'главарь мафии'))");
if (mysql_affected_rows()!=0) mysql_query("update users set creditsingame = creditsingame + 20 WHERE id = '".$man_id."'");
else mysql_query("update users set creditsingame = creditsingame - 5 WHERE id = '".$man_id."'"); 
$mmsg = $mmsg." $kto $wh был наден утром в мусорном баке с топором в жопе. Похоже, тут не обошлось без маньяка...";
$man_kil = $a["gamer_act"];
}else{ 
$mmsg = $mmsg." Маньяк вставил топор в жопу $wh, но операция была успешной, док его вытащил"; 
$doknotact = true;
}
}
}
}    

$r = mysql_query("select * from $ringame WHERE role = 'бомж'");
if (mysql_affected_rows()!=0){
$a = mysql_fetch_array($r);
$bomj_id = $a["gamer_id"];                                   
$igrok = @mysql_fetch_array(@mysql_query ("Select user from users where id='".$bomj_id."' LIMIT 1;"));
if ($a["gamer_act"]!=""){                    
$wh = get_name_by_id($a["gamer_act"], $rm);
if ($put_act==$a["id_in_game"]) $mmsg = $mmsg." Нахальный бомж поймал шлюху на улице и затащил к подвал. Там они и провели всю ночь."; 
else{         
mysql_query("update users set creditsingame = creditsingame + 5 WHERE id = '".$bomj_id."'"); 
$mmsg = $mmsg." Бомж ночью рылся в карманах у $wh!";
$kto = get_role_by_id($a["gamer_act"], $rm);
$mmsgtob = "$wh это $kto!";
$tm = getmicrotime();
$today=date ("H:i");
$rnd = rand(0,99999999); 
mysql_query ("Insert into $room set klu4= '".$rnd."', time='".$today."', who='".$mafiozi."', usid='".$mafid."', message='".$mmsgtob."', id='".$tm."', towhom='".$bomj_id."', gamemes='1', komu='".$igrok[0]."'");   
mysql_query ("Update users set posts = posts + 1 WHERE id = '".$mafid."'");
}
}
} 

$r = mysql_query("select * from $ringame WHERE role = 'жена комиссара'");
if (mysql_affected_rows()!=0){
$a = mysql_fetch_array($r);
$jena_id = $a["gamer_id"];  
$state = $a["state"];
if ($a["gamer_act"]!=""){
$wh = get_name_by_id($a["gamer_act"], $rm);
if ($put_act==$a["id_in_game"]) $mmsg = $mmsg." Шлюха сегодня направилась к жене комиссара. Камасутра отдыхает."; 
else{   
if ($gor_id_in_game != $a["gamer_act"]){
mysql_query("update users set creditsingame = creditsingame + 50 WHERE id = '".$jena_id."'"); 
$kto = role_to_rpadej(get_role_by_id($a["gamer_act"], $rm));  
if ($dok_act != $a["gamer_act"]){
$mmsg = $mmsg." Жена комиссара отравила ночью $kto $wh, отомстив за смерть мужа.!";             
$jena_kil = $a["gamer_act"];
}else{ 
$mmsg = $mmsg." Жена комиссара почти зарезала $wh, но добрый док за небольшую плату все восстановил.";    
$doknotact = true; 
} 
}else{
$mmsg = $mmsg." Жена комиссара продырявила ножом горца, а он даже не заметил. Теперь ходит с ножом в жопе.";
}
}
}
} 

$r = mysql_query("select * from $ringame WHERE role = 'доктор'");
if (mysql_affected_rows()!=0){ 
$a = mysql_fetch_array($r);
$dok_id = $a["gamer_id"];  
if ($doknoact==true) mysql_query("update users set creditsingame = creditsingame + 20 WHERE id = '".$dok_id."'");
else if ($put_act!=$a["id_in_game"]) mysql_query("update users set creditsingame = creditsingame + 5 WHERE id = '".$dok_id."'"); 

if ($a["gamer_act"]!=""&&$doknotact===false){ 
$wh = get_name_by_id($a["gamer_act"], $rm);
if ($put_act==$a["id_in_game"]) $mmsg = $mmsg." Доктор целую ночь прокувыркался с путаной, так никого и не вылечив";
else{
if ($a["gamer_id"]==$a["gamer_act"]) $mmsg = $mmsg." Наш доктор эгоистично лечил сам себя.";
else $mmsg = $mmsg." Доктор накачал лекарствами $wh";
}
}
}

$r = mysql_query("select * from $ringame WHERE role = 'клоун'");
if (mysql_affected_rows()!=0){  
$a = mysql_fetch_array($r);
$state = $a["state"];
$kloun_id = $a["gamer_id"];   
if ($a["gamer_act"]!=""){ 
list($g1,$g2) = explode (" ",$a["gamer_act"]);
mysql_query("select gamer_id from $ringame WHERE (id_in_game = '".$g1."')or(id_in_game = '".$g2."')");
if (mysql_affected_rows()==2){ 
$r = mysql_query("select gamer_id, role, state from $ringame WHERE id_in_game = '".$g1."'");
$b = mysql_fetch_array($r);
$gid1 = $b["gamer_id"];
$igrok1 = @mysql_fetch_array(@mysql_query ("Select user from users where id='".$gid1."' LIMIT 1;"));
$role1 = $b["role"]; 
$state1 = $b["state"];
$r = mysql_query("select gamer_id, role, state from $ringame WHERE id_in_game = '".$g2."'");
$b = mysql_fetch_array($r);
$gid2 = $b["gamer_id"];
$igrok2 = @mysql_fetch_array(@mysql_query ("Select user from users where id='".$gid2."' LIMIT 1;"));
$role2 = $b["role"]; 
$state2 = $b["state"];     
$mmsg1 = "Ваша новая роль: $role2!"; 
$mmsg2 = "Ваша новая роль: $role1!";
$tm = getmicrotime();
$today=date ("H:i");
$rnd = rand(0,99999999); 
mysql_query ("Insert into $room set klu4= '".$rnd."', time='".$today."', who='".$mafiozi."', usid='".$mafid."', message='".$mmsg1."', id='".$tm."', towhom='".$gid1."', gamemes='1', komu='".$igrok1[0]."'");    
mysql_query ("Update users set posts = posts + 1 WHERE id = '".$mafid."'");    
$tm = getmicrotime();
$today=date ("H:i");
$rnd = rand(0,99999999); 
mysql_query ("Insert into $room set klu4= '".$rnd."', time='".$today."', who='".$mafiozi."', usid='".$mafid."', message='".$mmsg2."', id='".$tm."', towhom='".$gid2."', gamemes='1', komu='".$igrok2[0]."'");    
mysql_query ("Update users set posts = posts + 1 WHERE id = '".$mafid."'");        
mysql_query("update $ringame set role = '".$role2."', state = '".$state2."' WHERE id_in_game = '".$g1."'"); 
mysql_query("update $ringame set role = '".$role1."', state = '".$state1."' WHERE id_in_game = '".$g2."'");
$mmsg = $mmsg." Жители! В городе завелся клоун, и этой ночью он поменял роли двух игроков!!!"; 
$r = mysql_query("select cround from $rmafaction");
$a = mysql_fetch_array($r);
$sc = $a["cround"]*30;  
mysql_query("update users set creditsingame = creditsingame + '".$sc."' WHERE id = '".$kloun_id."'");
mysql_query("update $ringame set state = '1' WHERE role = 'клоун'");
}
} 
}      

$tm = getmicrotime();
$today=date ("H:i");
$rnd = rand(0,99999999); 
mysql_query ("Insert into $room set klu4= '".$rnd."', time='".$today."', who='".$mafiozi."', usid='".$mafid."', message='".$mmsg."', id='".$tm."', towhom='', gamemes='1', komu=''");
mysql_query ("Update users set posts = posts + 1 WHERE id = '".$mafid."'");        
mysql_query("insert into $rscores select gamer_id, creditsingame from $ringame, users WHERE ((id_in_game = '".$kom_kil."')or(id_in_game = '".$maf_kil."')or(id_in_game = '".$man_kil."')or(id_in_game = '".$jena_kil."'))and(users.id = $ringame.gamer_id)");
mysql_query ("delete from $ringame WHERE (id_in_game = '".$kom_kil."')or(id_in_game = '".$maf_kil."')or(id_in_game = '".$man_kil."')or(id_in_game='".$jena_kil."')");
$vktr = false;
$r = mysql_query("select count(*) as sm from $ringame");
$a = mysql_fetch_array($r);
$sm = $a["sm"]; 
$r = mysql_query("select current,prev,prevprev from $rmafaction");
$a = mysql_fetch_array($r);
$current = $a["current"];
$prev = $a["prev"];
## $prevprev = $a["prevprev"];
$prevprev = $prev;
$prev = $current;
$current = $sm;
mysql_query("update $rmafaction set prevprev = '".$prevprev."', prev = '".$prev."', current = '".$current."'");  
if ($current == $prevprev){
  
mysql_query ("update $rmafaction set action = 'nogame'");
$vktr = true;  
$mmsg = "Два раунда жители тормозят, и никто не умирает. Поэтому объявляется ничья! А роли были такие: "; 
$r = mysql_query("select gamer_id from $ringame");
while (($a = mysql_fetch_array($r))!==false){
$gamer_id = $a["gamer_id"];
mysql_query("update users set creditsingame = creditsingame + 25 WHERE id = '".$gamer_id."'"); 
}
$r = mysql_query("Select * from $ringame");
while (($a = mysql_fetch_array($r))!==false){ 
$gnick = get_name_by_id($a["id_in_game"], $rm);
$grole = get_role_by_id($a["id_in_game"], $rm);
$mmsg = $mmsg."<b>$gnick</b> - $grole, ";
} 
$mmsg = substr($mmsg,0,strlen($mmsg)-2); 
$tm = getmicrotime();
$today=date ("H:i");
$rnd = rand(0,99999999); 
mysql_query ("Insert into $room set klu4= '".$rnd."', time='".$today."', who='".$mafiozi."', usid='".$mafid."', message='".$mmsg."', id='".$tm."', towhom='', gamemes='1', komu=''"); 
mysql_query ("Update users set posts = posts + 1 WHERE id = '".$mafid."'"); 
mysql_query("insert into $rscores select gamer_id, creditsingame from $ringame, users WHERE users.id = $ringame.gamer_id");
mysql_query("delete from $ringame");  
$mmsg = "За эту игру заработали столько очков: "; 
$mmes = scores($rm); 
$mmsg = $mmsg.$mmes;
$tm = getmicrotime();
$today=date ("H:i");
$rnd = rand(0,99999999); 
mysql_query ("Insert into $room set klu4= '".$rnd."', time='".$today."', who='".$mafiozi."', usid='".$mafid."', message='".$mmsg."', id='".$tm."', towhom='', gamemes='1', komu=''"); mysql_query ("Update users set posts = posts + 1 WHERE id = '".$mafid."'"); 
}
mysql_query ("select * from $ringame WHERE role = 'главарь мафии'");
if (mysql_affected_rows()==0&&$sm!=0&&$vktr!==true){ 
$r = mysql_query ("select * from $ringame WHERE role = 'мафиози'");
if (mysql_affected_rows()==0){ 
$vktr = true;
mysql_query ("update $rmafaction set action = 'nogame'"); 
$r = mysql_query("select role, gamer_id from $ringame");
while (($a = mysql_fetch_array($r))!==false){
$role = $a["role"];
$gamer_id = $a["gamer_id"];
if ($role == "обыватель") mysql_query("update users set creditsingame = creditsingame + 100 WHERE id = '".$gamer_id."'"); 
else mysql_query("update users set creditsingame = creditsingame + 50 WHERE id = '".$gamer_id."'");
}
$mmsg = "Игра окончена, победа мирных жителей! А роли были такие: "; 
$r = mysql_query("Select * from $ringame");
while (($a = mysql_fetch_array($r))!==false){
$gnick = get_name_by_id($a["id_in_game"], $rm);
$grole = get_role_by_id($a["id_in_game"], $rm);
$mmsg = $mmsg."<b>$gnick</b> - $grole, ";
} 
$mmsg = substr($mmsg,0,strlen($mmsg)-2);  
mysql_query("insert into $rscores select gamer_id, creditsingame from $ringame, users WHERE users.id = $ringame.gamer_id");
mysql_query ("delete from $ringame"); 
$tm = getmicrotime();
$today=date ("H:i");
$rnd = rand(0,99999999); 
mysql_query ("Insert into $room set klu4= '".$rnd."', time='".$today."', who='".$mafiozi."', usid='".$mafid."', message='".$mmsg."', id='".$tm."', towhom='', gamemes='1', komu=''"); 
mysql_query ("Update users set posts = posts + 1 WHERE id = '".$mafid."'"); 
$mmsg = "За эту игру заработали столько очков: "; 
$mmes = scores($rm); 
$mmsg = $mmsg.$mmes;
$tm = getmicrotime();
$today=date ("H:i");
$rnd = rand(0,99999999); 
mysql_query ("Insert into $room set klu4= '".$rnd."', time='".$today."', who='".$mafiozi."', usid='".$mafid."', message='".$mmsg."', id='".$tm."', towhom='', gamemes='1', komu=''");
mysql_query ("Update users set posts = posts + 1 WHERE id = '".$mafid."'");
}else{
$a = mysql_fetch_array($r);  
$id_in_game = $a["id_in_game"];
$gamer_id = $a["gamer_id"];
$igrok = @mysql_fetch_array(@mysql_query ("Select user from users where id='".$gamer_id."' LIMIT 1;"));
mysql_query ("update $ringame set role = 'главарь мафии' WHERE id_in_game = '".$id_in_game."'");
$mmsg = "Теперь вы главарь мафии!"; 
$tm = getmicrotime();
$today=date ("H:i");
$rnd = rand(0,99999999); 
mysql_query ("Insert into $room set klu4= '".$rnd."', time='".$today."', who='".$mafiozi."', usid='".$mafid."', message='".$mmsg."', id='".$tm."', towhom='".$gamer_id."', gamemes='1', komu='".$igrok[0]."'");     
mysql_query ("Update users set posts = posts + 1 WHERE id = '".$mafid."'");
}
} 

if ($vktr!==true){
$r = mysql_query ("select count(*) as sm from $ringame");
$a = mysql_fetch_array($r); 

if ($a["sm"]==2){
mysql_query("select * from $ringame WHERE (role = 'главарь мафии')or(role = 'мафиози')"); 

if (mysql_affected_rows()==2) $vk = "maf";
if (mysql_affected_rows()==1){ 
mysql_query("select * from $ringame WHERE (role = 'доктор')or(role = 'комиссар катани')or(role = 'путана')or(role = 'маньяк')");   
if (mysql_affected_rows() != 0) $vk = "ni4"; 
else $vk = "maf";
}
}
if ($a["sm"]==1){
mysql_query ("select * from $ringame WHERE (role = 'главарь мафии')or(role = 'мафиози')");
if (mysql_affected_rows() != 0) $vk = "maf";
}
if ($a["sm"]==0) $vk = "ni4";
mysql_query("select * from $ringame");
$nm = round(mysql_affected_rows()/2-0.5);
$r = mysql_query("Select count(*) as sm from $ringame WHERE (role='мафиози')or(role='главарь мафии')");
$a = mysql_fetch_array($r);
$sm = $a["sm"];
if ($sm>$nm) $vk = "maf";

if (isset($vk)){
$vktr = true;
if ($vk == "ni4"){
$vktr = true;
mysql_query ("update $rmafaction set action = 'nogame'");
    
$r = mysql_query("select gamer_id from $ringame");
while (($a = mysql_fetch_array($r))!==false){
$gamer_id = $a["gamer_id"];
mysql_query("update users set creditsingame = creditsingame + 25 WHERE id = '".$gamer_id."'"); 
}
$mmsg = "Силы Мафии и мирных жителей равны, ничья! А роли были такие: "; 
$r = mysql_query("Select * from $ringame");
while (($a = mysql_fetch_array($r))!==false){
$gnick = get_name_by_id($a["id_in_game"], $rm);
$grole = get_role_by_id($a["id_in_game"], $rm);
$mmsg = $mmsg."<b>$gnick</b> - $grole, ";
} 
$mmsg = substr($mmsg,0,strlen($mmsg)-2);   
mysql_query("insert into $rscores select gamer_id, creditsingame from $ringame, users WHERE users.id = $ringame.gamer_id");
mysql_query ("delete from $ringame"); 
$tm = getmicrotime();
$today=date ("H:i");
$rnd = rand(0,99999999); 
mysql_query ("Insert into $room set klu4= '".$rnd."', time='".$today."', who='".$mafiozi."', usid='".$mafid."', message='".$mmsg."', id='".$tm."', towhom='', gamemes='1', komu=''");
mysql_query ("Update users set posts = posts + 1 WHERE id = '".$mafid."'"); 
$mmsg = "За эту игру заработали столько очков: "; 
$mmes = scores($rm); 
$mmsg = $mmsg.$mmes;
$tm = getmicrotime();
$today=date ("H:i");
$rnd = rand(0,99999999); 
mysql_query ("Insert into $room set klu4= '".$rnd."', time='".$today."', who='".$mafiozi."', usid='".$mafid."', message='".$mmsg."', id='".$tm."', towhom='', gamemes='1', komu=''");
mysql_query ("Update users set posts = posts + 1 WHERE id = '".$mafid."'");
}
  
if ($vk == "maf"){ 
$vktr = true;
mysql_query ("update $rmafaction set action = 'nogame'"); 
$r = mysql_query("select role, gamer_id from $ringame");
while (($a = mysql_fetch_array($r))!==false){
$role = $a["role"];
$gamer_id = $a["gamer_id"];
if ($role == "мафиози"||$role == "главарь мафии") mysql_query("update users set creditsingame = creditsingame + 50 WHERE id = '".$gamer_id."'"); 
}
        
$mmsg = "Всем хана, победа Мафов! А роли были такие: "; 
$r = mysql_query("Select * from $ringame");
while (($a = mysql_fetch_array($r))!==false){ 
$gnick = get_name_by_id($a["id_in_game"], $rm);
$grole = get_role_by_id($a["id_in_game"], $rm);
$mmsg = $mmsg."<b>$gnick</b> - $grole, ";
} 
$mmsg = substr($mmsg,0,strlen($mmsg)-2);    
mysql_query("insert into $rscores select gamer_id, creditsingame from $ringame, users WHERE users.id = $ringame.gamer_id");
mysql_query ("delete from $ringame");

$tm = getmicrotime();
$today=date ("H:i");
$rnd = rand(0,99999999); 
mysql_query ("Insert into $room set klu4= '".$rnd."', time='".$today."', who='".$mafiozi."', usid='".$mafid."', message='".$mmsg."', id='".$tm."', towhom='', gamemes='1', komu=''"); 
mysql_query ("Update users set posts = posts + 1 WHERE id = '".$mafid."'");  
$mmsg = "За эту игру заработали столько очков: "; 
$mmes = scores($rm); 
$mmsg = $mmsg.$mmes;
$tm = getmicrotime();
$today=date ("H:i");
$rnd = rand(0,99999999); 
mysql_query ("Insert into $room set klu4= '".$rnd."', time='".$today."', who='".$mafiozi."', usid='".$mafid."', message='".$mmsg."', id='".$tm."', towhom='', gamemes='1', komu=''"); 
mysql_query ("Update users set posts = posts + 1 WHERE id = '".$mafid."'");
}
}   
}

mysql_query ("update $ringame set gamer_act=''");    
if ($vktr===false){
$mmsg = "Кого же залинчуем сегодня днем? День длится 3 минуты. Голосуем.(!номер) ";
$r = mysql_query("select * from $ringame");
$kol = mysql_affected_rows();
for ($i=1;$i<=$kol;$i++){
$a = mysql_fetch_array($r);
$gamer_id = $a["gamer_id"];
$r2 = mysql_query ("select * from users where id = '".$gamer_id."'");
$b = mysql_fetch_array($r2);
$gname = $b["user"];
$id_in_game = $a["id_in_game"];
$s = $s."<b>$id_in_game</b> - $gname, "; 
} 
$mmsg = $mmsg.$s;
$tm = getmicrotime();
$today=date ("H:i");
$rnd = rand(0,99999999); 
mysql_query ("Insert into $room set klu4= '".$rnd."', time='".$today."', who='".$mafiozi."', usid='".$mafid."', message='".$mmsg."', id='".$tm."', towhom='', gamemes='1', komu=''"); 
mysql_query ("Update users set posts = posts + 1 WHERE id = '".$mafid."'");           
}
}

if ($action=="registration"&&$tm>$nexttime){
mysql_query("select * from $ringame");
if (mysql_affected_rows()<3){      
mysql_query ("update $rmafaction set action = 'nogame'");
$mmsg = "Игра не начнется, пока не будет хотя бы 3 игроков!";
$tm = getmicrotime();
$today=date ("H:i");
$rnd = rand(0,99999999);
mysql_query ("Insert into $room set klu4= '".$rnd."', time='".$today."', who='".$mafiozi."', usid = '".$mafid."', message='".$mmsg."', id='".$tm."', towhom='', gamemes='1', komu=''"); 
mysql_query ("Update users set posts = posts + 1 WHERE id = '".$mafid."'");           
mysql_query ("delete from $ringame");
}else{
mysql_query("delete from $rscores");                                                                     
$tm = time()+25;
mysql_query ("update $rmafaction set action = 'game_night', nexttime = '".$tm."', kiked = '1', cround = '0'");
$r = mysql_query ("select * from $ringame");
$roles = array("обыватель","главарь мафии","комиссар катани"); 
if (mysql_affected_rows()>3) array_push ($roles,"доктор");
if (mysql_affected_rows()>4) array_push ($roles,"обыватель");
if (mysql_affected_rows()>5) array_push ($roles,"мафиози");
if (mysql_affected_rows()>6) array_push ($roles,"маньяк");
if (mysql_affected_rows()>7) array_push ($roles,"путана");
if (mysql_affected_rows()>8) array_push ($roles,"обыватель");
if (mysql_affected_rows()>9) array_push ($roles,"мафиози");
if (mysql_affected_rows()>10) array_push ($roles,"бомж");   
if (mysql_affected_rows()>11) array_push ($roles,"мафиози"); 
if (mysql_affected_rows()>12) array_push ($roles,"горец"); 
if (mysql_affected_rows()>13) array_push ($roles,"клоун");  
if (mysql_affected_rows()>14) array_push ($roles,"мафиози"); 
if (mysql_affected_rows()>15) array_push ($roles,"жена комиссара");

for ($i=1;$i<=((mysql_affected_rows()-15)/3);$i++) array_push ($roles,"мафиози");     
$j = count ($roles);
for ($i=1;$i<=mysql_affected_rows()-$j;$i++) array_push ($roles,"обыватель");

mt_srand(time()*100000);
shuffle($roles);
$i = 0;
while (($a = mysql_fetch_array($r))!==false){
$gamer_id = $a["gamer_id"]; 
$igrok = @mysql_fetch_array(@mysql_query ("Select user from users where id='".$gamer_id."' LIMIT 1;"));
mysql_query("update users set creditsingame = '0' WHERE id = '".$gamer_id."'");
$id_in_game = $i+1;           
$role = $roles[$i];
$mmsg = "Вы $role!"; 
$tm = getmicrotime();
$today=date ("H:i");
$rnd = rand(0,99999999);
mysql_query ("Insert into $room set klu4= '".$rnd."', time='".$today."', who='".$mafiozi."', usid = '".$mafid."', message='".$mmsg."', id='".$tm."', towhom='".$gamer_id."', gamemes='1', komu='".$igrok[0]."'"); 
mysql_query ("Update users set posts = posts + 1 WHERE id = '".$mafid."'");           

mysql_query("update $ringame set role = '".$role."', id_in_game = '".$id_in_game."' WHERE gamer_id = '".$gamer_id."'");
$i++;
} 
$mmsg = "Раздача ролей окончена! Ночь начнется через 20 секунд!"; 
$tm = getmicrotime();
$today=date ("H:i");
$rnd = rand(0,99999999);
mysql_query ("Insert into $room set klu4= '".$rnd."', time='".$today."', who='".$mafiozi."', usid = '".$mafid."', message='".$mmsg."', id='".$tm."', towhom='', gamemes='1', komu=''");
mysql_query ("Update users set posts = posts + 1 WHERE id = '".$mafid."'");  
mysql_query ("update $rmafaction set prevprev = '199', prev = '199', current = '200'");
}
}

$smthwr = 0;
$res = mysql_query ("Select * from $room order by id desc LIMIT 100");
$kol = mysql_affected_rows();
 
if(@$msg){       
$msg = trim(" $msg ");
$msg = ereg_replace(" +"," ",$msg);
$msg = substr($msg,0,400);
$msg = str_replace("", " ", $msg);
$msg = str_replace("$", "$$", $msg);
$msg = strtr($msg,array(chr("0")=>"",chr("1")=>"",chr("2")=>"",chr("3")=>"",chr("4")=>"",chr("5")=>"",chr("6")=>"",chr("7")=>"",chr("8")=>"",chr("9")=>"",chr("10")=>"",chr("11")=>"",chr("12")=>"",chr("13")=>"",chr("14")=>"",chr("15")=>"",chr("16")=>"",chr("17")=>"",chr("18")=>"",chr("19")=>"",chr("20")=>"",chr("21")=>"",chr("22")=>"",chr("23")=>"",chr("24")=>"",chr("25")=>"",chr("26")=>"",chr("27")=>"",chr("28")=>"",chr("29")=>"",chr("30")=>"",chr("31")=>""));
//$msg = str_replace("к","С‘",$msg);
$msg = htmlspecialchars($msg); 
$msg = str_replace("\"", "&quot;", $msg);
$msg = str_replace("|", "&#0166;", $msg); 
$msg = str_replace("'", "&#8216;", $msg); 
$msg = str_replace("\\", "", $msg); 
$msg = addslashes($msg); 

if (!isset($prvt)) $prvt = 0;

$str1="";
$str2=$msg;

if ($prvt == 0) $towhom = "";
if (!isset($towhom)) $towhom = "";

if ($row["level"]<5) {require("antirekl.php");}

require("smile.php");
$minpos = 500; $nm = 500;
for ($j=0;$j<=count($smiles)-1;$j++){   
$tmpp = strpos($msg,$smiles[$j]);
if (($tmpp < $minpos)&&($tmpp !== false)){ 
$minpos = $tmpp; $nm = $j;};
                     };         
if ($minpos !=500){
if ($row["translit"]!=1){
$st1 = substr($msg,0,$minpos+strlen($smiles[$nm]));
$st2 = substr($msg,$minpos+strlen($smiles[$nm]),strlen($msg)-strlen($st1));
$st1_wosm = $st1; 
$st1 = str_replace($smiles[$nm],$replaces[$nm],$st1);
if (strpos($replaces[$nm],"smilean/")!==false) $st1_woasm = $st1_wosm; else $st1_woasm = $st1;     
$msg_woasm = $st1.$st2;  
$msg_wosm = $st1_wosm.$st2; 
$msg = $st1_woasm.$st2;
} else {
$st1 = substr($msg,0,$minpos);
$st2 = substr($msg,$minpos, strlen($smiles[$nm]));
$st3 = substr($msg,$minpos+strlen($smiles[$nm]),strlen($msg)-strlen($st1)-strlen($st2));
$st1 = trun_to_rus($st1);
$st2_wosm = $st2;
$st2 = $replaces[$nm];    
if (strpos($replaces[$nm],"smilean/")!==false) $st2_woasm = $st2_wosm; else $st2_woasm = $st2;
$st3 = trun_to_rus($st3);
$msg = $st1.$st2_woasm.$st3;
$msg_wosm = $st1.$st2_wosm.$st3; 
$msg_woasm = $st1.$st2.$st3;
}
} 
else if ($row["translit"]==1) $msg = trun_to_rus($msg);          
Unset($smiles);
unset($replaces);   
if(($row["translit"]==0)&&($row["level"]>6)) {
$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);
}

$msg = $str1.$msg;
if ($msg_wosm!="") $msg_wosm = $str1.$msg_wosm;
if ($msg_woasm!="") $msg_woasm = $str1.$msg_woasm;
$komu = check($komu);
if(!empty($shrift)){
if (($row["level"]>=4) && ($shrift==1)) $msg = '<i>'.$msg.'</i>';
else if (($row["level"]>=5) && ($shrift==2)) $msg = '<u>'.$msg.'</u>';
else if (($row["level"]>=6) && ($shrift==3)) $msg = '<i><u>'.$msg.'</u></i>';
else if (($row["level"]>=6) && ($shrift==4)) $msg = '<b>'.$msg.'</b>';
else if (($row["level"]>=7) && ($shrift==5)) $msg = '<u><b>'.$msg.'</b></u>';
else if (($row["level"]>=7) && ($shrift==6)) $msg = '<i><u><b>'.$msg.'</b></u></i>';
}

$r = mysql_query("SELECT * FROM $room WHERE usid = '".$id."' order by id desc LIMIT 1");
$a = mysql_fetch_array($r);
if ($a["message"] !== $msg)
{
$time = getmicrotime();
$today=date ("H:i");
$posts =  $row["posts"];
$posts++;
if($ver=="wml") mysql_query ("Update users set posts='".$posts."', onl='".$time."', room='".$rm."', version='1' where id ='".$id."'");
else mysql_query ("Update users set posts='".$posts."', onl='".$time."', room='".$rm."', version='2' where id ='".$id."'");
$hid = $row["inv"];
$kol++;   
$rnd = rand(0,99999999);

$msg = $nastr.$msg;
mysql_query ("Insert into $room set klu4= '".$rnd."', time='".$today."', who='".$us."', message='".$msg."', messagewosm = '".$msg_wosm."', messagewoasm = '".$msg_woasm."', id='".$time."', towhom='".$towhom."', hid='".$hid."', usid='".$id."', gamemes = '".$gmes."', komu='".$komu."'");           
$usmes["komu"] = $komu;
$usmes["time"] = $today; 
$usmes["who"] = $us;
$usmes["usid"] = $id;
$usmes["message"] = $msg; 
$usmes["messagewosm"] = $msg_wosm;
$usmes["messagewoasm"] = $msg_woasm;
$usmes["id"] = $time;
$usmes["towhom"] = $towhom; 
$usmes["gamemes"] = $gmes;
$smthwr = 1;

$r = mysql_query ("select * from $rmafaction");
$a = mysql_fetch_array($r);     
$action = $a["action"];     

if ($action == "game_night"&&$gmes==1){
$s = str_replace("!","",$msg);
$r = mysql_query("select * from $ringame WHERE id_in_game = '".$s."'"); 
if (mysql_affected_rows()!==0){ 
$a = mysql_fetch_array($r);
$id_in_game = $a["id_in_game"];
mysql_query ("update $ringame set gamer_act = '".$s."' WHERE gamer_id = '".$id."'");
$wh = get_name_by_id($id_in_game, $rm);
   
mysql_query("select * from $ringame WHERE gamer_act = '".$s."'");
$sm = mysql_affected_rows();
$mmsg = "$us голосует за $wh!(<b>$sm</b>)"; 
$tm = getmicrotime();
$today=date ("H:i");
$rnd = rand(0,99999999);
mysql_query ("Insert into $room set klu4= '".$rnd."', time='".$today."', who='".$mafiozi."', usid = '".$mafid."', message='".$mmsg."', id='".$tm."', towhom='', gamemes='1', komu=''");  
mysql_query ("Update users set posts = posts + 1 WHERE id = '".$mafid."'");       
}

mysql_query ("select * from $ringame");
$nm = round(mysql_affected_rows()/3);
$r = mysql_query ("select *,count(gamer_act) from $ringame WHERE gamer_act != '' group by gamer_act having count(gamer_act)>'".$nm."'");
$a = mysql_fetch_array($r); 
if (mysql_affected_rows() != 0){
$w = $a["gamer_act"]; 
mysql_query ("update $rmafaction set action = 'dvote'"); 
mysql_query ("update $ringame set dvote = '1' WHERE id_in_game = '".$w."'"); 
$whk = get_name_by_id($w, $rm);
$mmsg = "Жители, вы уверены, что хотите казнить $whk?(!да или !нет) $whk, у вас есть время оправдаться.";
$tm = getmicrotime();
$today=date ("H:i");
$rnd = rand(0,99999999);
mysql_query ("Insert into $room set klu4= '".$rnd."', time='".$today."', who='".$mafiozi."', usid = '".$mafid."', message='".$mmsg."', id='".$tm."', towhom='', gamemes='1', komu=''"); 
mysql_query ("Update users set posts = posts + 1 WHERE id = '".$mafid."'");           
}
} 

if ($gmes==1&&$action == "dvote"&&($msg == "!da"||$msg == "!net"||$msg == "!да"||$msg == "!нет")){
$r = mysql_query("select * from $ringame WHERE dvote = '1'");
$a = mysql_fetch_array($r);
$w = $a["id_in_game"];  
$whk = get_name_by_id($w, $rm); 
if ($msg=="!da"||$msg == "!да"){
mysql_query("update $ringame set wholin = '1' WHERE gamer_id = '".$id."'");
$mmsg = "$us голосует за казнь $whk!";
}else{
mysql_query("update $ringame set wholin = '-1' WHERE gamer_id = '".$id."'"); 
$mmsg = "$us голосует против казни $whk!";
}
$tm = getmicrotime();
$today=date ("H:i");
$rnd = rand(0,99999999);
mysql_query ("Insert into $room set klu4= '".$rnd."', time='".$today."', who='".$mafiozi."', usid = '".$mafid."', message='".$mmsg."', id='".$tm."', towhom='', gamemes='1', komu=''");    
mysql_query ("Update users set posts = posts + 1 WHERE id = '".$mafid."'"); 
mysql_query ("select * from $ringame");
$nm = round(mysql_affected_rows()/2-0.5);

mysql_query("select * from $ringame WHERE wholin = '1'");
if (mysql_affected_rows()>$nm){
$tm = time();
mysql_query("update $rmafaction set action = 'game_night', nexttime = '".$tm."', kiked = '1'");
$krole = get_role_by_id($w, $rm);
if ($krole=="мафиози"||$krole=="главарь мафии"){        
$krole = role_to_tpadej($krole);
$mmsg = "Наконец-то мирные жители расправились с $krole $whk!!!";
}else{     
$krole = role_to_rpadej($krole);
$mmsg = "Жители сами усложнили себе задачу, казнив ни в чем не повинного $krole $whk!";
}   
mysql_query("insert into $rscores select gamer_id, creditsingame from $ringame, users WHERE (users.id = $ringame.gamer_id)and(id_in_game = '".$w."')");
mysql_query ("delete from $ringame WHERE id_in_game = '".$w."'");
$tm = getmicrotime();
$today=date ("H:i");
$rnd = rand(0,99999999);
mysql_query ("Insert into $room set klu4= '".$rnd."', time='".$today."', who='".$mafiozi."', usid = '".$mafid."', message='".$mmsg."', id='".$tm."', towhom='', gamemes='1', komu=''");
mysql_query ("Update users set posts = posts + 1 WHERE id = '".$mafid."'");
$vktr = false; 

$r = mysql_query("select count(*) as sm from $ringame");
$a = mysql_fetch_array($r);
$sm = $a["sm"];  

mysql_query ("select * from $ringame WHERE role = 'главарь мафии'");
if (mysql_affected_rows()==0&&$sm!=0){ 
$r = mysql_query ("select * from $ringame WHERE role = 'мафиози'");
if (mysql_affected_rows()==0){  
$vktr = true;
mysql_query ("update $rmafaction set action = 'nogame'");
$r = mysql_query("select role, gamer_id from $ringame");
while (($a = mysql_fetch_array($r))!==false){
$role = $a["role"];
$gamer_id = $a["gamer_id"];
if ($role == "обыватель") mysql_query("update users set creditsingame = creditsingame + 100 WHERE id = '".$gamer_id."'"); 
else mysql_query("update users set creditsingame = creditsingame + 50 WHERE id = '".$gamer_id."'");
}
$mmsg = "Игра окончена, победа мирных жителей! А роли были такие: "; 
$r = mysql_query("Select * from $ringame");
while (($a = mysql_fetch_array($r))!==false){
$gnick = get_name_by_id($a["id_in_game"], $rm);
$grole = get_role_by_id($a["id_in_game"], $rm);
$mmsg = $mmsg."<b>$gnick</b> - $grole, ";
} 
$mmsg = substr($mmsg,0,strlen($mmsg)-2); 
mysql_query("insert into $rscores select gamer_id, creditsingame from $ringame, users WHERE users.id = $ringame.gamer_id");
mysql_query ("delete from $ringame"); 
$tm = getmicrotime();
$today=date ("H:i");
$rnd = rand(0,99999999); 
mysql_query ("Insert into $room set klu4= '".$rnd."', time='".$today."', who='".$mafiozi."', usid='".$mafid."', message='".$mmsg."', id='".$tm."', towhom='', gamemes='1', komu=''"); 
mysql_query ("Update users set posts = posts + 1 WHERE id = '".$mafid."'"); 
$mmsg = "За эту игру заработали столько очков: "; 
$mmes = scores($rm); 
$mmsg = $mmsg.$mmes;
$tm = getmicrotime();
$today=date ("H:i");
$rnd = rand(0,99999999); 
mysql_query ("Insert into $room set klu4= '".$rnd."', time='".$today."', who='".$mafiozi."', usid='".$mafid."', message='".$mmsg."', id='".$tm."', towhom='', gamemes='1', komu=''"); 
mysql_query ("Update users set posts = posts + 1 WHERE id = '".$mafid."'");
}else{ 
$a = mysql_fetch_array($r);  
$id_in_game = $a["id_in_game"];
$gamer_id = $a["gamer_id"];
$igrok = @mysql_fetch_array(@mysql_query ("Select user from users where id='".$gamer_id."' LIMIT 1;"));
mysql_query ("update $ringame set role = 'главарь мафии' WHERE id_in_game = '".$id_in_game."'");
$mmsg = "Теперь вы главарь мафии!";
$tm = getmicrotime(); 
$today=date ("H:i");
$rnd = rand(0,99999999); 
mysql_query ("Insert into $room set klu4= '".$rnd."', time='".$today."', who='".$mafiozi."', usid='".$mafid."', message='".$mmsg."', id='".$tm."', towhom='".$gamer_id."', gamemes='1', komu='".$igrok[0]."'"); 
mysql_query ("Update users set posts = posts + 1 WHERE id = '".$mafid."'");
}
} 

if ($vktr!==true){
$r = mysql_query ("select count(*) as sm from $ringame");
$a = mysql_fetch_array($r);

if ($a["sm"]==2){
mysql_query("select * from $ringame WHERE (role = 'главарь мафии')or(role = 'мафиози')");
if (mysql_affected_rows()==2) $vk = "maf";
if (mysql_affected_rows()==1){ 
mysql_query("select * from $ringame WHERE (role = 'доктор')or(role = 'комиссар катани')or(role = 'путана')or(role = 'маньяк')");   
if (mysql_affected_rows() != 0) $vk = "ni4"; 
else $vk = "maf";
}
}
if ($a["sm"]==1){
mysql_query ("select * from $ringame WHERE (role = 'главарь мафии')or(role = 'мафиози')");
if (mysql_affected_rows() != 0) $vk = "maf";
}
if ($a["sm"]==0) $vk = "ni4"; 

mysql_query("select * from $ringame");
$nm = round(mysql_affected_rows()/2-0.5); 
$r = mysql_query("Select count(*) as sm from $ringame WHERE (role='мафиози')or(role='главарь мафии')");
$a = mysql_fetch_array($r);
$sm = $a["sm"];
if ($sm>$nm) $vk = "maf";

if (isset($vk)){ 
if ($vk == "ni4"){
$vktr = true;
mysql_query ("update $rmafaction set action = 'nogame'"); 
$r = mysql_query("select gamer_id from $ringame");
while (($a = mysql_fetch_array($r))!==false){
$gamer_id = $a["gamer_id"];
mysql_query("update users set creditsingame = creditsingame + 25 WHERE id = '".$gamer_id."'"); 
}
$mmsg = "Силы Мафии и мирных жителей равны, ничья! А роли были такие: "; 
$r = mysql_query("Select * from $ringame");
while (($a = mysql_fetch_array($r))!==false){
$gnick = get_name_by_id($a["id_in_game"], $rm);
$grole = get_role_by_id($a["id_in_game"], $rm);
$mmsg = $mmsg."<b>$gnick</b> - $grole, ";
}    
mysql_query("insert into $rscores select gamer_id, creditsingame from $ringame, users WHERE users.id = $ringame.gamer_id");
mysql_query ("delete from $ringame");   
$mmsg = substr($mmsg,0,strlen($mmsg)-2);
$tm = getmicrotime();
$today=date ("H:i");
$rnd = rand(0,99999999); 
mysql_query ("Insert into $room set klu4= '".$rnd."', time='".$today."', who='".$mafiozi."', usid='".$mafid."', message='".$mmsg."', id='".$tm."', towhom='', gamemes='1', komu=''"); 
mysql_query ("Update users set posts = posts + 1 WHERE id = '".$mafid."'"); 
$mmsg = "За эту игру заработали столько очков: "; 
$mmes = scores($rm); 
$mmsg = $mmsg.$mmes;
$tm = getmicrotime();
$today=date ("H:i");
$rnd = rand(0,99999999); 
mysql_query ("Insert into $room set klu4= '".$rnd."', time='".$today."', who='".$mafiozi."', usid='".$mafid."', message='".$mmsg."', id='".$tm."', towhom='', gamemes='1', komu=''"); 
mysql_query ("Update users set posts = posts + 1 WHERE id = '".$mafid."'");
}
if ($vk == "maf"){
$vktr = true;
mysql_query ("update $rmafaction set action = 'nogame'");
$r = mysql_query("select role, gamer_id from $ringame");
while (($a = mysql_fetch_array($r))!==false){
$role = $a["role"];
$gamer_id = $a["gamer_id"];
if ($role == "мафиози"||$role == "главарь мафии") mysql_query("update users set creditsingame = creditsingame + 50 WHERE id = '".$gamer_id."'"); 
}
$mmsg = "Всем хана, победа Мафов! А роли были такие: "; 
$r = mysql_query("Select * from $ringame");
while (($a = mysql_fetch_array($r))!==false){ 
$gnick = get_name_by_id($a["id_in_game"], $rm);
$grole = get_role_by_id($a["id_in_game"], $rm);
$mmsg = $mmsg."<b>$gnick</b> - $grole, ";
} 
$mmsg = substr($mmsg,0,strlen($mmsg)-2);   
mysql_query("insert into $rscores select gamer_id, creditsingame from $ringame, users WHERE users.id = $ringame.gamer_id");
mysql_query ("delete from $ringame"); 
$tm = getmicrotime();
$today=date ("H:i");
$rnd = rand(0,99999999); 
mysql_query ("Insert into $room set klu4= '".$rnd."', time='".$today."', who='".$mafiozi."', usid='".$mafid."', message='".$mmsg."', id='".$tm."', towhom='', gamemes='1', komu=''");
mysql_query ("Update users set posts = posts + 1 WHERE id = '".$mafid."'");  
$mmsg = "За эту игру заработали столько очков: "; 
$mmes = scores($rm); 
$mmsg = $mmsg.$mmes;
$tm = getmicrotime();
$today=date ("H:i");
$rnd = rand(0,99999999); 
mysql_query ("Insert into $room set klu4= '".$rnd."', time='".$today."', who='".$mafiozi."', usid='".$mafid."', message='".$mmsg."', id='".$tm."', towhom='', gamemes='1', komu=''"); 
mysql_query ("Update users set posts = posts + 1 WHERE id = '".$mafid."'");
}
}
}    
}

mysql_query("select * from $ringame WHERE wholin = '-1'");
if (mysql_affected_rows()>$nm){                
mysql_query("update $rmafaction set action = 'game_night'");
mysql_query("update $ringame set dvote = '0', wholin = '0', gamer_act = ''");
$mmsg = "$whk оправдан!";
$tm = getmicrotime();
$today=date ("H:i");
$rnd = rand(0,99999999);
mysql_query ("Insert into $room set klu4= '".$rnd."', time='".$today."', who='".$mafiozi."', usid = '".$mafid."', message='".$mmsg."', id='".$tm."', towhom='', gamemes='1', komu=''");  
mysql_query ("Update users set posts = posts + 1 WHERE id = '".$mafid."'");          
}
}

if ($gmes==1&&$action == "game_day"&&$towhom == "".$mafid.""){
$r = mysql_query("select * from $ringame WHERE gamer_id = '".$id."'");
$a = mysql_fetch_array($r); 
$role = $a ["role"];
$gamer_act = $a["gamer_act"];   
$state = $a["state"];
if ($role!="обыватель"&&$role!="мафиози"&&$role!="клоун"&&$role!="жена комиссара"){
$s = str_replace("!","",$msg);
$r2 = mysql_query ("select * from $ringame WHERE id_in_game = '".$s."'");
if (mysql_affected_rows()==0){
$mmsg = "Что ж ты мне пишешь!?!?"; 
$tm = getmicrotime();
$today=date ("H:i");
$rnd = rand(0,99999999);
mysql_query ("Insert into $room set klu4= '".$rnd."', time='".$today."', who='".$mafiozi."', usid='".$mafid."', message='".$mmsg."', id='".$tm."', towhom='".$id."', gamemes='1', komu='".$us."'"); 
mysql_query ("Update users set posts = posts + 1 WHERE id = '".$mafid."'");          
}else{ 
if ($gamer_act==""){                      
$b = mysql_fetch_array($r2);
$hid = $b["gamer_id"];
$r3 = mysql_query("select * from users WHERE id = '".$hid."'");
$c = mysql_fetch_array($r3);
$gname = $c ["user"];
unset ($c);
unset ($r3); 
if ($role == "главарь мафии") {
$mmsg = "Заказ на убийство $gname принят!";
$rnd = rand(1,3); 
$re = mysql_query("select night_act from mafia WHERE klu4 = '".$rnd."'"); 
$b = mysql_fetch_array($re); 
$mmsg1=$b["night_act"];
}
if ($role == "комиссар катани"&&strpos($msg,"!!")!==false) {
$mmsg = "Заказ на убийство $gname принят!";
$s="!".$s;
$rnd = rand(1,3); 
$re = mysql_query("select night_act from komissar WHERE klu4 = '".$rnd."'"); 
$b = mysql_fetch_array($re); 
$mmsg1=$b["night_act"];
}
if ($role == "комиссар катани"&&strpos($msg,"!!")===false) {
$mmsg = "Заказ на проверку $gname принят!";
$rnd = rand(1,3); 
$re = mysql_query("select night_act from komissar WHERE klu4 = '".$rnd."'"); 
$b = mysql_fetch_array($re); 
$mmsg1=$b["night_act"];
}
if ($role == "доктор") {
$mmsg = "Заказ на лечение $gname принят!";
$rnd = rand(1,3); 
$re = mysql_query("select night_act from doktor WHERE klu4 = '".$rnd."'"); 
$b = mysql_fetch_array($re); 
$mmsg1=$b["night_act"];
}
if ($role == "маньяк") {
$mmsg = "Изнасилуем $gname =)";
$rnd = rand(1,3); 
$re = mysql_query("select night_act from maniac WHERE klu4 = '".$rnd."'"); 
$b = mysql_fetch_array($re); 
$mmsg1=$b["night_act"];
}
if ($role == "путана") {
$mmsg = "$gname сегодня ночью будет занят)";
$rnd = rand(1,3); 
$re = mysql_query("select night_act from wluha WHERE klu4 = '".$rnd."'"); 
$b = mysql_fetch_array($re); 
$mmsg1=$b["night_act"];
}
if ($role == "бомж") {
$mmsg = "Копаемся в карманах $gname";
$rnd = rand(1,3); 
$re = mysql_query("select night_act from bomj WHERE klu4 = '".$rnd."'"); 
$b = mysql_fetch_array($re); 
$mmsg1=$b["night_act"];
}
mysql_query ("update $ringame set gamer_act='".$s."' WHERE gamer_id = '".$id."'");
$tm = getmicrotime();
$today=date ("H:i");
$rnd = rand(0,99999999);
mysql_query ("Insert into $room set klu4= '".$rnd."', time='".$today."', who='".$mafiozi."', usid='".$mafid."', message='".$mmsg."', id='".$tm."', towhom='".$id."', gamemes='1', komu='".$us."'");
mysql_query ("Update users set posts = posts + 1 WHERE id = '".$mafid."'");           

$tm = getmicrotime();
$today=date ("H:i");
$rnd = rand(0,99999999);
mysql_query ("Insert into $room set klu4= '".$rnd."', time='".$today."', who='".$mafiozi."', usid='".$mafid."', message='".$mmsg1."', id='".$tm."', towhom='', gamemes='1'");  
mysql_query ("Update users set posts = posts + 1 WHERE id = '".$mafid."'");
}else { 
$mmsg = "Ты уже выбрал жертву!";
$tm = getmicrotime();
$today=date ("H:i");
$rnd = rand(0,99999999);
mysql_query ("Insert into $room set klu4= '".$rnd."', time='".$today."', who='".$mafiozi."', usid='".$mafid."', message='".$mmsg."', id='".$tm."', towhom='".$id."', gamemes='1', komu='".$us."'"); 
mysql_query ("Update users set posts = posts + 1 WHERE id = '".$mafid."'");  
}
}

}else if ($role=="клоун"&&$state==0){
$s = str_replace("!","",$msg);
list($g1,$g2) = explode(" ",$s);
mysql_query("select gamer_id from $ringame WHERE (id_in_game='".$g1."')or(id_in_game='".$g2."')"); 
if (mysql_affected_rows()==2){   
mysql_query("update $ringame set gamer_act='".$s."' WHERE gamer_id = '".$id."'");
$r = mysql_query("select id_in_game from $ringame WHERE id_in_game = '".$g1."'");
$a = mysql_fetch_array($r);
$gn1 = get_name_by_id($a["id_in_game"], $rm);
$r = mysql_query("select id_in_game from $ringame WHERE id_in_game = '".$g2."'");
$a = mysql_fetch_array($r);
$gn2 = get_name_by_id($a["id_in_game"], $rm);
$mmsg = "Меняем ролями $gn1 и $gn2!";
$mmsg1 = "Клоун ходит ночью по улицам и запутывает и без того сложное дело...";
$tm = getmicrotime();
$today=date ("H:i");
$rnd = rand(0,99999999);
mysql_query ("Insert into $room set klu4= '".$rnd."', time='".$today."', who='".$mafiozi."', usid='".$mafid."', message='".$mmsg."', id='".$tm."', towhom='".$id."', gamemes='1', komu='".$us."'");
mysql_query ("Update users set posts = posts + 1 WHERE id = '".$mafid."'");  
$tm = getmicrotime();
$today=date ("H:i");
$rnd = rand(0,99999999);
mysql_query ("Insert into $room set klu4= '".$rnd."', time='".$today."', who='".$mafiozi."', usid='".$mafid."', message='".$mmsg1."', id='".$tm."', towhom='', gamemes='1', komu=''");
mysql_query ("Update users set posts = posts + 1 WHERE id = '".$mafid."'"); 
}else{  
$mmsg = "Что ж ты мне пишешь!?!?!?"; 
$tm = getmicrotime();
$today=date ("H:i");
$rnd = rand(0,99999999);
mysql_query ("Insert into $room set klu4= '".$rnd."', time='".$today."', who='".$mafiozi."', usid='".$mafid."', message='".$mmsg."', id='".$tm."', towhom='".$id."', gamemes='1', komu='".$us."'");
mysql_query ("Update users set posts = posts + 1 WHERE id = '".$mafid."'");    
}

}else if ($role=="жена комиссара"&&$state==1){ 
$s = str_replace("!","",$msg);
$r = mysql_query("select * from $ringame WHERE id_in_game = '".$s."'");
if (mysql_affected_rows()!=0){   
mysql_query("update $ringame set state = '2', gamer_act = '".$s."' WHERE gamer_id = '".$id."'");
$a = mysql_fetch_array($r);
$gn = get_name_by_id($a["id_in_game"], $rm);
$mmsg = "$gn поплатится за смерть комиссара!";
$mmsg1 = "Жена комиссара вышла из дома мстить за смерть мужа...";
$tm = getmicrotime();
$today=date ("H:i");
$rnd = rand(0,99999999);
mysql_query ("Insert into $room set klu4= '".$rnd."', time='".$today."', who='".$mafiozi."', usid='".$mafid."', message='".$mmsg."', id='".$tm."', towhom='".$id."', gamemes='1', komu='".$us."'");
mysql_query ("Update users set posts = posts + 1 WHERE id = '".$mafid."'");    
$tm = getmicrotime();
$today=date ("H:i");
$rnd = rand(0,99999999);
mysql_query ("Insert into $room set klu4= '".$rnd."', time='".$today."', who='".$mafiozi."', usid='".$mafid."', message='".$mmsg1."', id='".$tm."', towhom='', gamemes='1', komu=''");
mysql_query ("Update users set posts = posts + 1 WHERE id = '".$mafid."'");    
}else{   
$mmsg = "Что ж ты мне пишешь!?!?!?"; 
$tm = getmicrotime();
$today=date ("H:i");
$rnd = rand(0,99999999);
mysql_query ("Insert into $room set klu4= '".$rnd."', time='".$today."', who='".$mafiozi."', usid='".$mafid."', message='".$mmsg."', id='".$tm."', towhom='".$id."', gamemes='1', komu='".$us."'");
mysql_query ("Update users set posts = posts + 1 WHERE id = '".$mafid."'");             
}
}

$r = mysql_query ("select count(*) as nv from $ringame WHERE (role != 'обыватель')and(gamer_act='')");  
$a = mysql_fetch_array($r);
if ($a["nv"]==0){  
mysql_query("update $rmafaction set action = 'allvoted'");
$mmsg = "Все, что могло свершиться ночью, свершилось.";
$tm = getmicrotime();
$today=date ("H:i");
$rnd = rand(0,99999999);
mysql_query ("Insert into $room set klu4= '".$rnd."', time='".$today."', who='".$mafiozi."', usid='".$mafid."', message='".$mmsg."', id='".$tm."', towhom='', gamemes='1', komu=''"); 
mysql_query ("Update users set posts = posts + 1 WHERE id = '".$mafid."'");      
}
}

if ($action == "nogame"&&($msg=="!start"||$msg=="!старт")){
$tm = time()+180;
mysql_query ("update $rmafaction set action = 'registration', nexttime = '".$tm."'"); 
$mmsg = "Начинается игра \"Мафия\"! Набор игроков будет продолжаться 3 мин. Для участия введите !reg."; 
$tm = getmicrotime();
$today=date ("H:i");
$rnd = rand(0,99999999);
mysql_query ("Insert into $room set klu4= '".$rnd."', time='".$today."', who='".$mafiozi."', usid='".$mafid."', message='".$mmsg."', id='".$tm."', towhom='', gamemes='1', komu=''"); 
mysql_query ("Update users set posts = posts + 1 WHERE id = '".$mafid."'");          
}

if ($action == "registration"&&($msg=="!reg"||$msg=="!рег")){ 
mysql_query ("select * from $ringame WHERE gamer_id = '".$id."'");
if (mysql_affected_rows()==0){
$mmsg = "$us присоединяется к игре!"; 
$rnd = rand(10000,99999999);
$tm = time();
mysql_query("insert into $ringame set gamer_id = '".$id."', onl = '".$tm."'");
}else{
$mmsg = "$us выходит из игры!";
mysql_query("delete from $ringame WHERE gamer_id = '".$id."'");
}
$tm = getmicrotime();
$today=date ("H:i");
$rnd = rand(0,99999999);
mysql_query ("Insert into $room set klu4= '".$rnd."', time='".$today."', who='".$mafiozi."', usid='".$mafid."', message='".$mmsg."', id='".$tm."', towhom='', gamemes='1', komu=''"); 
mysql_query ("Update users set posts = posts + 1 WHERE id = '".$mafid."'");           
}
}
}                     

if ($msg == "!stats"||$msg == "!статс"){
$r = mysql_query("select mafcredits from users WHERE id = '".$id."'");
$a = mysql_fetch_array($r);
$cr = $a["mafcredits"];
$mmsg = "$us, у вас на счету $cr кредитов";   
$tm = getmicrotime();
$today=date ("H:i");
$rnd = rand(0,99999999);
mysql_query ("Insert into $room set klu4= '".$rnd."', time='".$today."', who='".$mafiozi."', usid='".$mafid."', message='".$mmsg."', id='".$tm."', towhom='', gamemes='".$gmes."', komu=''"); 
mysql_query ("Update users set posts = posts + 1 WHERE id = '".$mafid."'");
}
unset($msg);

$bind1=$row['bind1'];
$bind2=$row['bind2'];
$bind3=$row['bind3'];
$bind4=$row['bind4'];
$max = $row["max"];    
$avr = $row["avr"];    
$time=date ("H:i");
$avr2 = $avr/10;

$r = mysql_query ("select count(readd) as num from zapiski WHERE (idtowhom = '".$id."')and(readd = '0')and(ininc = '1')");
$a = mysql_fetch_array($r);
$inb = $a["num"]; 

$takep="&amp;ref=$ref";

$rem = mysql_query("SELECT topic FROM rooms where rm = '".$rm."'"); 
$iname = mysql_fetch_array ($rem); 
$topic = $iname["topic"];

ob_start();
if ($ver=="wml"){
echo $xml;
echo $dtd;
echo "<wml>\n";
if ($avr!==0) echo "<card id=\"maf\" title=\"$topic-$time\" ontimer=\"chat.php?$ses&amp;rm=$rm&amp;ref=$ref\"><timer value=\"$avr\"/>\n";
else echo "<card id=\"maf\" title=\"$topic-$time\" >\n";
if ($row["kn_update"]==0) echo "<do type=\"options\" name=\"refresh\" label=\"Обновить\"><go href=\"chat.php?$ses&amp;rm=$rm&amp;ref=$ref\"/></do>\n";
echo "<do type=\"options\" name=\"add\" label=\"Сказать\"><go href=\"#add\"/></do>";
if ($row["level"]>5) echo "<do type=\"options\" name=\"topic\" label=\"Топик\"><go href=\"topic.php?$ses&amp;rm=$rm&amp;ref=$ref\"/></do>\n";
echo "<do type=\"options\" name=\"help\" label=\"Правила игры\"><go href=\"mafrules.php?$ses&amp;rm=$rm&amp;mod=1&amp;ref=$ref\"/></do>\n";
echo "<do type=\"options\" name=\"help\" label=\"TOP 10\"><go href=\"statistik.php?$ses&amp;mod=10maf&amp;rm=$rm&amp;ref=$ref\"/></do>\n";
echo "<do type=\"options\" name=\"help\" label=\"Помощь\"><go href=\"help.php?$ses&amp;rm=$rm&amp;ref=$ref\"/></do>\n";
if ($row["kn_whochat"]==0) echo "<do type=\"options\" name=\"who\" label=\"Кто где?\"><go href=\"who.php?$ses&amp;rm=$rm&amp;ref=$ref\"/></do>\n";
$tm = time()-300;
$inr=mysql_query("SELECT id FROM room23 WHERE id >'".$tm."' group by who order by id desc");
$kola = mysql_affected_rows();
if ($row["kn_whoroom"]==0) echo "<do type=\"options\" name=\"who_room\" label=\"Кто тут?(".($kola).")\"><go href=\"whoroom.php?$ses&amp;rm=$rm&amp;ref=$ref\"/></do>\n";
if (($row["kn_clroom"]==0)&&($row["level"]>=7)){
//echo "<do type=\"options\" name=\"clear\" label=\"Полная Чистка\"><go href=\"apanel.php?$ses&amp;go=clroom&amp;rm=$rm$takep\"/></do>";
echo "<do type=\"options\" name=\"clear\" label=\"Чистка\"><go href=\"apanel.php?$ses&amp;go=clrm&amp;rm=$rm$takep\"/></do>";
}
echo "<do type=\"options\" name=\"nastr\" label=\"Настройки\"><go href=\"cabinet.php?$ses&amp;rm=$rm&amp;ref=$ref\"/></do>\n";
echo "<p mode=\"wrap\">\n";
}else{
echo "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">";
echo "<html xmlns=\"http://www.w3.org/1999/xhtml\">";
echo "<head><link rel=\"stylesheet\" type=\"text/css\" href=\"css/css.css\"/>";
echo "<title>".$topic."-(".$time.")</title>";
if ($avr==0) echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>";
else echo "<META HTTP-EQUIV=\"Refresh\" CONTENT=\"".$avr2."; URL=chat.php?$ses&amp;rm=$rm$takep\">";
echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/></head><body>";
echo "<div align=\"left\">";
}
echo $fsize1;
if($inb != "0") echo "<img src=\"smile/new.gif\" alt=\"NEW\"/><b>Вам письмо <a href=\"inbox.php?$ses&amp;ref=$ref\">($inb)</a></b><br/>\n";
if ($ver=="wml"){
if (((strpos ($agent,"M3Gate") !== false)||(strpos ($agent,"Opera") !== false)||(strpos ($agent,"emulator") !== false)||(strpos ($agent,"WinWAP") !== false)||(strpos ($agent,"Wapsilon") !== false)||(strpos ($agent,"M3GATE") !== false))){
echo "<a href=\"chat.php?$ses&amp;rm=$rm$takep#add\" accesskey=\"$bind1\">Сказать(".$bind1.")</a><br/>";
}else{
echo "<a href=\"#add\" accesskey=\"$bind1\">Сказать(".$bind1.")</a><br/>";
}
}else{
echo "<div class=\"d1\"><a href=\"add.php?$ses&amp;rm=$rm$takep\" accesskey=\"$bind1\">Сказать(".$bind1.")</a></div>";
}
if ($ver=="wml"){ 
echo "<a href=\"chat.php?$ses&amp;rm=$rm$takep\" accesskey=\"$bind2\">Обновить(".$bind2.")</a><br/>---";
}else{ 
echo "<div class=\"d1\"><a href=\"chat.php?$ses&amp;rm=$rm$takep\" accesskey=\"$bind2\">Обновить(".$bind2.")</a></div>";	
echo "<div class=\"d1\"><a href=\"function.php?$ses&amp;rm=$rm$takep\" accesskey=\"3\">Функции(3)</a></div>";
}
@$total=$kol;
$mread = 0;
$i = 0;

if ($smthwr != 0){                 
$time = time()-30;
mysql_query("select * from $room WHERE (usid = '".$id."')and(id>'".$time."')");
if (mysql_affected_rows()>5&&$row["level"]<4){
$kik = time()+60;
$whokik = "[Система]";
$whykik = "Флуд"; 
mysql_query("update users set kik = '".$kik."', whokik = '".$whokik."', whykik = '".$whykik."' WHERE id = '".$id."'");
}

$i++;
$komu = $usmes["komu"];
$date = $usmes["time"];
$name = $usmes["who"];
$usid = $usmes["usid"];
$msg = $usmes["message"];     
if ($smset==0&&$usmes["messagewosm"]!="") $msg = $usmes["messagewosm"];
if ($smset==2&&$usmes["messagewoasm"]!="") $msg = $usmes["messagewoasm"];
$time = $usmes["id"];
$th = $usmes["towhom"];      
$gm = $usmes["gamemes"];
@mysql_query ("Select * from ignor where usid='".$usid."' and id='".$id."'");
if ((mysql_affected_rows() == false)&&($gmes==0||($gmes==1&&$gm==1))){
if ($th == "") {
if (!empty($komu)) {
if ($us==$komu) $komu = "-<b>".$komu."</b>";
else $komu = "-".$komu."";
}
echo "<br/><b><a href=\"inside.php?$ses&amp;nk=$usid&amp;rm=$rm&amp;ref=$ref\">".$name."</a></b>".$komu."(".$date.")\n".$msg.""; $mread++;}
else if (($th == $id)||($id == $usid)){ 
if (!empty($komu)) {
if ($us==$komu) $komu = "-<b>".$komu."</b>";
else $komu = "-".$komu."";
}
echo "<br/><b><a href=\"inside.php?$ses&amp;nk=$usid&amp;rm=$rm&amp;ref=$ref\">".$name."</a></b>".$komu."(".$date.")<b>[P!]</b>\n".$msg."";$mread++;
}
}    
}
while (($mread < $max)&&($i<$total)){
$lines = mysql_fetch_array ($res);
$komu = $lines["komu"];
$date = $lines["time"];
$name = $lines["who"];
$usid = $lines["usid"];
$msg = $lines["message"];
$gm = $lines["gamemes"];
if ($smset==0&&$lines["messagewosm"]!="") $msg = $lines["messagewosm"];
if ($smset==2&&$lines["messagewoasm"]!="") $msg = $lines["messagewoasm"];
$time = $lines["id"];
$th = $lines["towhom"]; 
$hid = $lines["hid"];
$i++;
@mysql_query ("Select * from ignor where usid='".$usid."' and id='".$id."'");
if ((mysql_affected_rows() == false)&&(($hid != 2)||($id == $usid))&&($gmes==0||($gmes==1&&$gm==1))){
if ($th == "") {
if (!empty($komu)) {
if ($us==$komu) $komu = "-<b>".$komu."</b>";
else $komu = "-".$komu."";
}
echo "<br/><b><a href=\"inside.php?$ses&amp;nk=$usid&amp;rm=$rm&amp;ref=$ref\">".$name."</a></b>".$komu."(".$date.")\n".$msg.""; $mread++;}
else if (($th == $id)||($id == $usid)){ 
if (!empty($komu)) {
if ($us==$komu) $komu = "-<b>".$komu."</b>";
else $komu = "-".$komu."";
}
echo "<br/><b><a href=\"inside.php?$ses&amp;nk=$usid&amp;rm=$rm&amp;ref=$ref\">".$name."</a></b>".$komu."(".$date.")<b>[P!]</b>\n".$msg."";$mread++;}
}    
}
$page_next = $max;
if ($ver=="wml") echo "<br/>---";
else echo "<br/><br/>";
if ($max < $total){
if ($ver=="wml") echo "<br/><a href=\"history.php?$ses&amp;rm=$rm&amp;num=$page_next$takep\" accesskey=\"$bind3\">История(".$bind3.") &#8594;</a>";
else echo "<div class=\"d1\"><a href=\"history.php?$ses&amp;rm=$rm&amp;num=$page_next$takep\" accesskey=\"$bind3\">История(".$bind3.") &#8594;</a></div>";
}
if ($ver=="wml") echo "<br/><a href=\"enter.php?$ses&amp;ref=$ref\" accesskey=\"$bind4\">&#8592; Выйти из игры(".$bind4.")</a><br/>";
else echo "<div class=\"d1\"><a href=\"enter.php?$ses&amp;ref=$ref\" accesskey=\"$bind4\">&#8592; Выйти из игры(".$bind4.")</a></div>";
if ($ver=="wml") echo $divide;
$pagesize=round((ob_get_length()+200)/1024,1);
if ($ver=="wml") echo "[Вес страницы: <a href=\"trafik.php?$ses&amp;rm=$rm$takep\">".$pagesize." кб.</a>]<br/>";
else echo "<div class=\"d1\">[Вес страницы: <a href=\"trafik.php?$ses&amp;rm=$rm$takep\">".$pagesize." кб.</a>]<br/></div>";
info_compress();
echo $fsize2;
if ($ver=="wml")echo "</p></card>";
else echo "</div></body></html>";
if ($ver=="wml"){
echo "<card id=\"add\" title=\"Сказать\">\n";
echo "<p mode=\"wrap\">\n"; 
echo "<input name=\"msg$ref\" maxlength=\"200\" title=\"Text\"/><br/>\n";
if ($row["level"]>=4){
echo $fsize1;
echo "Шрифт<br/>";
echo $fsize2;
echo "<select name=\"shrift$ref\">\n";
echo "<option value=\"0\">Обычный</option>\n";
echo "<option value=\"1\">Наклонный</option>\n";
}
if ($row["level"]>=5) {echo "<option value=\"2\">Подчёркнутый</option>\n";}
if ($row["level"]>=6) {echo "<option value=\"3\">Накл. и подч.</option>\n";}
if ($row["level"]>=6) {echo "<option value=\"4\">Жирный</option>\n";}
if ($row["level"]>=7) {echo "<option value=\"5\">Жирн. и подч.</option>\n";}
if ($row["level"]>=7) {echo "<option value=\"6\">Огромный</option>\n";}
if ($row["level"]>=4) {echo "</select><br/>\n";}
echo $fsize1;
echo "<anchor title=\"send\">Сказать<go href=\"chat.php?$ses&amp;rm=$rm&amp;ref=$ref\" method=\"post\">\n";
echo "<postfield name=\"msg\" value=\"$(msg$ref)\"/>\n";
echo "<postfield name=\"shrift\" value=\"$(shrift$ref)\"/>\n";
echo "</go></anchor>\n";
echo $fsize2;
echo "<br/>\n";
echo $fsize1;
echo "<a href=\"chat.php?$ses&amp;rm=$rm&amp;ref=$ref\">&#8592; В игру</a>\n";
echo $fsize2;
echo "</p></card>";
echo "</wml>";
}
}
$alltraf=$row["alltraf"];
$alltraf=$alltraf+$pagesize;
mysql_query ("Update users set alltraf='".$alltraf."', lasttraf='".$pagesize."' where id='".$id."'");
mysql_close ($link);
ob_end_flush();
?>