<?php
include H.'guard/inc/ini.php'; //класс для работы с ini

$posts=get_defined_vars();
if ($_SERVER['PHP_SELF']!=='adm_panel/mysql.php')
{
foreach ($posts['_POST'] as $key=>$val)
	{
	$_POST[$key]=htmlentities($_POST[$key], ENT_QUOTES, 'UTF-8');
	}
foreach ($posts['_GET'] as $key=>$val)
	{
	$_GET[$key]=my_esc($_GET[$key]);
	}
}
$sys_ini = new TIniFileEx(H.'guard/system.ini'); // создаем объект
$gsets=parse_ini_file(H.'guard/sets.ini',true);
$gsys=parse_ini_file(H.'guard/system.ini',true);
$ps['guard']=true;
$spam=false;
$guard_hack=null;
$sys_ini->write('server','last_step',$time); //последний переход

class notify
{
function mail($msg)
	{
	global $gsets,$time,$user;
	mysql_query("INSERT INTO `mail` (`id_user`, `id_kont`, `msg`, `time`) values('0',".$gsets['notify']['adm_id'].", '".my_esc($msg)."', '$time')");
	}

function email($msg,$subject)
	{
	global $gsets,$time,$set;
	$adds="From: \"siteguard@$_SERVER[HTTP_HOST]\" <siteguard@$_SERVER[HTTP_HOST]>\n";
	$adds .= "Content-Type: text/html; charset=utf-8\n";
	mail($gsets['notify']['adm_email'],'=?utf-8?B?'.base64_encode($subject).'?=',$msg,$adds);
	}
}

$ntf=new notify();

if (empty($gsys['server']['overload']))
$gsys['server']['overload']=null;

if ($gsys['server']['overload']>$time && $gsets['server']['overload_state']==1) //проверка состояния перегрузки
{
if ($user['group_access']==15)
echo '<b>Аварийный режим (осталось '.($gsys['server']['overload']-$time).' секунд)</b><br />';
elseif ($gsys['server']['last_step']>($time-0.3))
	{
	echo "Предохранительные меры (временно). Пожалуйста, не обновляйте страницы так часто.<br />
	Извините за неудобства.<br />
	<a href='/'>Вернуться на главную</a>"; 	
	exit();
	}
}

if ($gsets['antispam']['state']==1) //антиспам
{
	if (isset($_POST['msg']) && isset($user))
	{
	function retrans($in)
		{
		$trans1= array("'",'`',',',' ',"Ё","Ж","Ч","Ш","Щ","Э","Ю","Я","ё","ж","ч","ш","щ","э","ю","я","А","Б","В","Г","Д","Е","З","И","Й","К","Л","М","Н","О","П","Р","С","Т","У","Ф","Х","Ц","Ь","Ы","а","б","в","г","д","е","з","и","й","к","л","м","н","о","п","р","с","т","у","ф","х","ц","ь","ы");
		$trans2= array('_','_','_','_',"jo","zh","ch","sh","sch","je","jy","ja","jo","zh","ch","sh","sch","je","jy","ja","a","b","v","g","d","e","z","i","j","c","l","m","n","o","p","r","s","t","u","f","h","c","","y","a","b","v","g","d","e","z","i","j","c","l","m","n","o","p","r","s","t","u","f","h","c","","y");
		return str_replace($trans1,$trans2,$in);
		}
	$antispam=retrans(my_esc($_POST['msg']));
	if ($gsets['antispam']['type']=='full')  //антиспам - full
		{
		$as_domains=array('.ru','.ua','.org','.net','.com','.biz','.info','.name','.mobi','.su','.us','.tk');
		if (str_replace($as_domains,'СПАМ',$antispam)!==$antispam)
			{
			$spam=true;
			}
		}
		else
		{
		$cspam=mysql_query("SELECT * FROM `guard_links`");
		while($post=mysql_fetch_assoc($cspam))
			{
			$spammsg=str_replace($post['link'],'СПАМ',$antispam);
			if ($antispam!==$spammsg)
				$spam=true;
			}
		//антиспам - selective
		}
	}
	
if ($spam==true)
	{
	if ($gsets['antispam']['type']=='selective') //только для выборочного антиспама
		{
		if ($gsets['antispam']['write_spam']==1) //запись спама
			mysql_query("INSERT INTO `guard_suspic_msgs` (`user`,`msg`,`module`,`time`) VALUES ('$user[id]','".my_esc($_POST['msg'])."','".my_esc($_SERVER['PHP_SELF'])."','$time')");
		if ($gsets['antispam']['ban_spamers']) //бан
			mysql_query("INSERT INTO `ban` (`id_user`, `id_ban`, `prich`, `time`) VALUES ('$user[id]', '0', 'Распространение рекламы', '".($time+$gsets['antispam']['ban_time']*3600)."')");
		}
	if ($gsets['antispam']['write_spamers']==1) //запись спамеров
		{
		if (mysql_num_rows(mysql_query("SELECT (`user`) FROM `guard_potential_spamers` WHERE `user` = '$user[id]'"))==0)
			{
			mysql_query("INSERT INTO `guard_potential_spamers` (`user`,`time`) VALUES ('$user[id]','$time')");
			}
		} 
	$err[]='В Вашем сообщении обнаружена реклама постороннего ресурса';	
	
	if ($gsets['notify']['to_mail'] && $gsets['notify']['spam'])
	$ntf->mail("Пользователь [url=/info.php?id=$user[id]]$user[nick][/url] отправил подозрительное сообщение &quot;".my_esc($_POST['msg'])."&quot;");
	
	if ($gsets['notify']['to_email'] && $gsets['notify']['spam'])
	$ntf->email("Пользователь <a href='/info.php?id=$user[id]'>$user[nick]</a> отправил подозрительное сообщение &quot;".my_esc($_POST['msg'])."&quot;",'SiteGuard - подозрительное сообщение');
		
	}
} //защита от спама

if ((preg_match('/[\'\"\$\@\+\^\<\>]/', $_SERVER['QUERY_STRING']) && str_replace(array('/obmen/','/loads/'), '', $_SERVER['PHP_SELF']) == $_SERVER['PHP_SELF']) || preg_match('/[\'\"\$\@\^\<\>]/', $_SERVER['QUERY_STRING']))
{
$guard_hack=1;
if ($gsets['guard']['write_hacks']==1) //запись попыток взлома
	mysql_query("INSERT INTO `guard_attempt_hacks` (`user`,`query`,`time`) VALUES ('$user[id]','".my_esc($_SERVER['PHP_SELF']).'?'.my_esc($_SERVER['QUERY_STRING'])."','$time')");

if (mysql_result(mysql_query("SELECT COUNT(*) FROM `ban` WHERE `id_user` = '$user[id]' AND (`time` > '$time' OR `view` = '0')"), 0)==0) //что бы не задосила свинья 
	{
	if ($gsets['guard']['ban_hackers']) //бан
		mysql_query("INSERT INTO `ban` (`id_user`, `id_ban`, `prich`, `time`) VALUES ('$user[id]', '0', 'Попытка взлома сайта', '".($time+($gsets['guard']['ban_time']==0?1000000:$gsets['guard']['ban_time'])*3600)."')");

	if ($gsets['guard']['ban_hackers_ip'] && $user['ip_xff']!=NULL) //бан по ip
		{
		$ip_xff=ip2long($user['ip_xff']);
		mysql_query("INSERT INTO `ban_ip` (`min`, `max`) VALUES ('$ip_xff', '$ip_xff')");
		}
	}
if ($gsets['guard']['write_hackers']==1)
	{
	if (mysql_num_rows(mysql_query("SELECT (`user`) FROM `guard_hackers` WHERE `user` = '$user[id]'"))==0)
		{
		mysql_query("INSERT INTO `guard_hackers` (`user`,`time`) VALUES ('$user[id]','$time')");
		}
	} //запись хакеров

if ($gsets['notify']['to_mail'] && $gsets['notify']['hack'])
	$ntf->mail("Пользователь [url=/info.php?id=$user[id]]$user[nick][/url] произвел попытку взлома &quot;".my_esc($_SERVER['PHP_SELF']).'?'.my_esc($_SERVER['QUERY_STRING'])."&quot;");
	
if ($gsets['notify']['to_email'] && $gsets['notify']['hack'])
	$ntf->email("Пользователь <a href='$user[id]'>$user[nick]</a> произвел попытку взлома &quot;".my_esc($_SERVER['PHP_SELF']).'?'.my_esc($_SERVER['QUERY_STRING'])."&quot;",'SiteGuard - попытка взлома');	
}
//защита от взлома

?>