<?
if (isset($_SESSION['id_user']) && mysql_result(mysql_query("SELECT COUNT(*) FROM `user` WHERE `id` = '$_SESSION[id_user]' LIMIT 1"), 0)==1)
{
$user=mysql_fetch_assoc(mysql_query("SELECT * FROM `user` WHERE `id` = $_SESSION[id_user] LIMIT 1"));
mysql_query("UPDATE `user` SET `date_last` = '$time' WHERE `id` = '$user[id]' LIMIT 1");

$user['type_input']='session';
}
elseif (!isset($input_page) && isset($_COOKIE['id_user']) && isset($_COOKIE['pass']) && $_COOKIE['id_user'] && $_COOKIE['pass'])
{
header("Location: /login.php?return=".urlencode($_SERVER['REQUEST_URI'])."&$passgen");exit;
}

if (!isset($_SERVER['HTTP_REFERER']))$_SERVER['HTTP_REFERER'] = '/index.php';

if (isset($user['activation']) && $user['activation']!=NULL) // если аккаунт не активирован
{
$err[]='Вам необходимо активировать Ваш аккаунт по ссылке, высланной на Email, указанный при регистрации';
unset($user);
}


if (isset($user))
{

$tmp_us=mysql_fetch_assoc(mysql_query("SELECT `level` FROM `user_group` WHERE `id` = '$user[group_access]' LIMIT 1"));
$user['level']=$tmp_us['level'];

$timeactiv=time() - $user['date_last'];
if($timeactiv < 120)
{
$newtimeactiv=$user['time']+$timeactiv;
mysql_query("UPDATE `user` SET `time` ='$newtimeactiv' WHERE `id` = '$user[id]' LIMIT 1");
echo mysql_error();
}

if (isset($user['type_input']) && isset($_SERVER['HTTP_REFERER']) && !preg_match('#'.preg_quote($_SERVER['HTTP_HOST']).'#', $_SERVER['HTTP_REFERER']) && preg_match('#^https?://#i', $_SERVER['HTTP_REFERER']) && $ref=@parse_url($_SERVER['HTTP_REFERER']))
{
if (isset($ref['host']))
{
if (mysql_result(mysql_query("SELECT COUNT(*) FROM `user_ref` WHERE `id_user` = '$user[id]' AND `url` = '".my_esc($ref['host'])."'"), 0)==0)
mysql_query("INSERT INTO `user_ref` (`time`, `id_user`, `type_input`, `url`) VALUES ('$time', '$user[id]', '$user[type_input]', '".my_esc($ref['host'])."')");
else
mysql_query("UPDATE `user_ref` SET `time` = '$time' WHERE `id_user` = '$user[id]' AND `url` = '".my_esc($ref['host'])."'");
}

}

if ($user['set_time_chat']!=NULL)$set['time_chat']=$user['set_time_chat'];
if ($user['set_p_str']!=NULL)$set['p_str']=$user['set_p_str'];
$set['set_show_icon']=$user['set_show_icon'];

if ($webbrowser) // для web темы
{
if (is_dir(H.'style/themes/'.$user['set_them2']))$set['set_them']=$user['set_them2'];
else mysql_query("UPDATE `user` SET `set_them2` = '$set[set_them]' WHERE `id` = '$user[id]' LIMIT 1");
}
else
{
if (is_dir(H.'style/themes/'.$user['set_them']))$set['set_them']=$user['set_them'];
else mysql_query("UPDATE `user` SET `set_them` = '$set[set_them]' WHERE `id` = '$user[id]' LIMIT 1");
}

if (!isset($banpage)) // бан пользователя
{
if (mysql_result(mysql_query("SELECT COUNT(*) FROM `ban` WHERE `razdel` = 'all' AND `id_user` = '$user[id]' AND (`time` > '$time' OR `view` = '0' OR `navsegda` = '1')"), 0)!=0)
{
header('Location: /ban.php?'.SID);exit;
}
}




if (isset($ip2['add']))mysql_query("UPDATE `user` SET `ip` = ".ip2long($ip2['add'])." WHERE `id` = '$user[id]' LIMIT 1");
else mysql_query("UPDATE `user` SET `ip` = null WHERE `id` = '$user[id]' LIMIT 1");
if (isset($ip2['cl']))mysql_query("UPDATE `user` SET `ip_cl` = ".ip2long($ip2['cl'])." WHERE `id` = '$user[id]' LIMIT 1");
else mysql_query("UPDATE `user` SET `ip_cl` = null WHERE `id` = '$user[id]' LIMIT 1");
if (isset($ip2['xff']))mysql_query("UPDATE `user` SET `ip_xff` = ".ip2long($ip2['xff'])." WHERE `id` = '$user[id]' LIMIT 1");
else mysql_query("UPDATE `user` SET `ip_xff` = null WHERE `id` = '$user[id]' LIMIT 1");
if ($ua)mysql_query("UPDATE `user` SET `ua` = '".my_esc($ua)."' WHERE `id` = '$user[id]' LIMIT 1");


mysql_query("UPDATE `user` SET `url` = '".my_esc($_SERVER['SCRIPT_NAME'])."' WHERE `id` = '$user[id]' LIMIT 1");
mysql_query("UPDATE `user` SET `sess` = '$sess' WHERE `id` = '$user[id]' LIMIT 1");


if ($webbrowser=='WEB')
{
$browser='web';
}
else
{
$browser='wap';
}

if ($user['browser']!=$browser)
mysql_query("UPDATE `user` SET `browser` = '$browser' WHERE `id` = '$user[id]' LIMIT 1");





$collision_q=mysql_query("SELECT * FROM `user` WHERE `ip` = '$iplong' AND `ua` = '".my_esc($ua)."' AND `date_last` > '".(time()-600)."' AND `id` <> '$user[id]'");
while ($collision = mysql_fetch_assoc($collision_q))
{
if (mysql_result(mysql_query("SELECT COUNT(*) FROM `user_collision` WHERE `id_user` = '$user[id]' AND `id_user2` = '$collision[id]' OR `id_user2` = '$user[id]' AND `id_user` = '$collision[id]'"), 0)==0)
mysql_query("INSERT INTO `user_collision` (`id_user`, `id_user2`, `type`) values('$user[id]', '$collision[id]', 'ip_ua_time')");
}

}
else
{
if ($webbrowser)
$set['set_them']=$set['set_them2'];
if ($ip && $ua)
{
if (mysql_result(mysql_query("SELECT COUNT(*) FROM `guests` WHERE `ip` = '$iplong' AND `ua` = '".my_esc($ua)."' LIMIT 1"), 0)==1)
{
$guests=mysql_fetch_assoc(mysql_query("SELECT * FROM `guests` WHERE `ip` = '$iplong' AND `ua` = '".my_esc($ua)."' LIMIT 1"));


mysql_query("UPDATE `guests` SET `date_last` = ".time().", `url` = '".my_esc($_SERVER['SCRIPT_NAME'])."', `pereh` = '".($guests['pereh']+1)."' WHERE `ip` = '$iplong' AND `ua` = '".my_esc($ua)."' LIMIT 1");
}
else
{
mysql_query("INSERT INTO `guests` (`ip`, `ua`, `date_aut`, `date_last`, `url`) VALUES ('$iplong', '".my_esc($ua)."', '".time()."', '".time()."', '".my_esc($_SERVER['SCRIPT_NAME'])."')");
}

}
unset($access);
}


if (!isset($user) || $user['level']==0)
{
@error_reporting(0);
@ini_set('display_errors',false); // показ ошибок
if (function_exists('set_time_limit'))@set_time_limit(20); // Ставим ограничение на 20 сек
}

if (!isset($user) && $set['guest_select']=='1' && !isset($show_all) && $_SERVER['PHP_SELF']!='/index.php' && $_SERVER['PHP_SELF']!='/vklogin.php')
{
header("Location: /aut.php");
exit;
}

 // LoginAPI
  if (isset($_POST['token']))
$users = json_decode($s, true);

if (isset($user))
{
$user_gr=mysql_fetch_assoc(mysql_query("SELECT * FROM `user_group` WHERE `id` = $user[group_access] LIMIT 1"));
$user['group_name'] = $user_gr['name'];


if (isset($_GET['sess_abuld']) && $_GET['sess_abuld'] == 1) // Продолжаем просмотр файла с меткой 18+
{
$_SESSION['abuld'] = 1;
}
if (isset($_SESSION['abuld']) && $_SESSION['abuld'] == 1)$user['abuld'] = 1;
}
//-------------------------автоантиспам---------------------------//
if (isset($_POST['msg']))
{
if (preg_match("/$_SERVER[SERVER_NAME]/i", $_POST['msg'])) {
$to_go = true;
} else {
$to_go = false;
}
if ((mysql_result(mysql_query("SELECT COUNT(*) FROM `mail` WHERE `id_user` = '$user[id]' AND `msg` like '%".mysql_escape_string('http://')."%' AND `time` > '".(time()-300)."'"),0)>=2 && $to_go == false) || 
(mysql_result(mysql_query("SELECT COUNT(*) FROM `guest` WHERE `id_user` = '$user[id]' AND `msg` like '%".mysql_escape_string('http://')."%' AND `time` > '".(time()-300)."'"),0)>=2 && $to_go == false) || 
(mysql_result(mysql_query("SELECT COUNT(*) FROM `forum_p` WHERE `id_user` = '$user[id]' AND `msg` like '%".mysql_escape_string('http://')."%' AND `time` > '".(time()-300)."'"),0)>=2 && $to_go == false) ||
(mysql_result(mysql_query("SELECT COUNT(*) FROM `gallery_komm` WHERE `id_user` = '$user[id]' AND `msg` like '%".mysql_escape_string('http://')."%' AND `time` > '".(time()-300)."'"),0)>=2 && $to_go == false) || 
(mysql_result(mysql_query("SELECT COUNT(*) FROM `obmennik_komm` WHERE `id_user` = '$user[id]' AND `msg` like '%".mysql_escape_string('http://')."%' AND `time` > '".(time()-300)."'"),0)>=2 && $to_go == false) || 
(mysql_result(mysql_query("SELECT COUNT(*) FROM `news_komm` WHERE `id_user` = '$user[id]' AND `msg` like '%".mysql_escape_string('http://')."%' AND `time` > '".(time()-300)."'"),0)>=2 && $to_go == false) ||
(mysql_result(mysql_query("SELECT COUNT(*) FROM `chat_post` WHERE `id_user` = '$user[id]' AND `msg` like '%".mysql_escape_string('http://')."%' AND `time` > '".(time()-300)."'"),0)>=2 && $to_go == false))
{
if ($_SESSION['spam']==true)$err[] = 'Вы заподозрены в рассылке спама, и поэтому не можете писать новые сообщения в течении 5и минут';
$_SESSION['spam']=true;
$_POST['msg'] = preg_replace('#http://(.*)ru#isU',' [red]Реклама[/red] ', $_POST['msg']);
$_POST['msg'] = preg_replace('#http://(.*)com#isU',' [red]Реклама[/red] ', $_POST['msg']);
$_POST['msg'] = preg_replace('#http://(.*)net#isU',' [red]Реклама[/red] ', $_POST['msg']);
$_POST['msg'] = preg_replace('#http://(.*)org#isU',' [red]Реклама[/red] ', $_POST['msg']);
$_POST['msg'] = preg_replace('#http://(.*)info#isU',' [red]Реклама[/red] ', $_POST['msg']);
$_POST['msg'] = preg_replace('#http://(.*)su#isU',' [red]Реклама[/red] ', $_POST['msg']);
$_POST['msg'] = preg_replace('#http://(.*)kz#isU',' [red]Реклама[/red] ', $_POST['msg']);
}
}
//----------------------------------------------------------------//




/*----------------Смена тем для гостей--------------*/
if (isset($_GET['t']) && $_GET['t']=='wap' && !isset($user))
{
$_SESSION['guest_theme']='wap';
header("Location: $_SERVER[HTTP_REFERER]");
exit;
}
elseif (isset($_GET['t']) && $_GET['t']=='web' && !isset($user))
{
$_SESSION['guest_theme']='web';
header("Location: $_SERVER[HTTP_REFERER]");
exit;
}
if (isset($_SESSION['guest_theme']) && $_SESSION['guest_theme']=='web' && !isset($user))
{
$set['set_them']='web';$set['set_them2']='web';
}
elseif (isset($_SESSION['guest_theme']) && $_SESSION['guest_theme']=='wap' && !isset($user))
{
$set['set_them']='default';$set['set_them2']='default';
}
/*--------------------alex-borisi-------------------*/



/*----------------Смена тем для юзеров--------------*/
if (isset($user) && isset($_GET['t']))
{
if ($webbrowser=='WEB')
{$set_t='set_them2';}
else
{$set_t='set_them';}
$wap='default';
$web='web';
if ($_GET['t']=='wap')
mysql_query("update `user` set `$set_t`='$wap' where `id`='$user[id]' limit 1");
elseif ($_GET['t']=='web')
mysql_query("update `user` set `$set_t`='$web' where `id`='$user[id]' limit 1");
header("location:  $_SERVER[HTTP_REFERER]");
}
/*--------------------alex-borisi---------------------*/



/*-------------сортировка по времени------------------*/
if (isset($user) && isset($_GET['sort']) && ($_GET['sort']=='0' || $_GET['sort']=='1'))
{

mysql_query("update `user` set `sort` = '$_GET[sort]' where `id` = '$user[id]' limit 1");

header("location:  $_SERVER[HTTP_REFERER]");
}
if (isset($user))$sort = ($user['sort']==1?' ASC ':' DESC ');
else $sort = 'DESC';

if (isset($user) && $user['sort'] == 1)$pageEnd = 'end'; else $pageEnd = '1';
/*--------------------alex-borisi---------------------*/



/*-------------------Ответ в комментариях-------------*/
if (isset($user) && isset($_GET['response'])){

if (mysql_result(mysql_query("SELECT COUNT(*) FROM `user` WHERE `id` = '".intval($_GET['response'])."'"),0)==1)
{
$id_response=intval($_GET['response']);
$ank_response=get_user($id_response);
}
else
{
$id_response=NULL;
$ank_response=NULL;
}
}
if (isset($_GET['go_otv']) && mysql_result(mysql_query("SELECT COUNT(*) FROM `user` WHERE `id` = '".intval($_GET['go_otv'])."'"),0)==1)
{
$otv_ank=intval($_GET['go_otv']);
$ank_otv=get_user($otv_ank);
$respons=TRUE;
}
else
{
$otv_ank=NULL;
$ank_otv=NULL;
$respons=false;
}
if (isset($_GET['response'])){ 
$otvet="$ank_response[nick], ";
$go_otv='?' . $passgen . '&amp;go_otv=' . $ank_response['id'] . '';
}else{
$otvet=NULL;
$go_otv=NULL;
}

if (isset($_GET['response']))
{
$id_response=intval($_GET['response']);
$ank_response=get_user($id_response);
$respons_msg=''.$ank_response['nick'].', ';
}
else
{
$id_response=NULL;
$ank_response=NULL;
$respons_msg=NULL;
}
/*--------------------alex-borisi---------------------*/


if (isset($user) && mysql_result(mysql_query("SELECT COUNT(*) FROM `user_set` WHERE `id_user` = '$user[id]'"), 0)==0)
mysql_query("INSERT INTO `user_set` (`id_user`) VALUES ('$user[id]')");

if (isset($user) && mysql_result(mysql_query("SELECT COUNT(*) FROM `discussions_set` WHERE `id_user` = '$user[id]'"), 0)==0)
mysql_query("INSERT INTO `discussions_set` (`id_user`) VALUES ('$user[id]')");

if (isset($user) && mysql_result(mysql_query("SELECT COUNT(*) FROM `tape_set` WHERE `id_user` = '$user[id]'"), 0)==0)
mysql_query("INSERT INTO `tape_set` (`id_user`) VALUES ('$user[id]')");

if (isset($user) && mysql_result(mysql_query("SELECT COUNT(*) FROM `notification_set` WHERE `id_user` = '$user[id]'"), 0)==0)
mysql_query("INSERT INTO `notification_set` (`id_user`) VALUES ('$user[id]')");


/*--------------------Рейтинг-------------------------*/
if (isset($user) && $user['rating_tmp']>1000)
{
$col = $user['rating_tmp']; // Счетчик активности
$col = $col / 1000; // Делим на 100 что бы получить процент
$col = intval($col); // Округляем 
mysql_query("update `user` set `rating` = '" . ($user['rating'] + $col) . "' where `id` = '$user[id]' limit 1"); // Прибавляем % рейтинга
$_SESSION['message'] = "Поздравляем! Вам за вашу активность начислено $col% рейтинга!"; // Оповещаем
$col = $user['rating_tmp'] - ($col * 1000); // Вычисляем остаток счетчика активности
mysql_query("update `user` set `rating_tmp` = '$col' where `id` = '$user[id]' limit 1"); // Сбрасываем 
}

/*--------------------alex-borisi---------------------*/



/*----------------Скрытие новости---------------------*/
if (isset($user) && isset($_GET['news_read']))
{
mysql_query("update `user` set `news_read` = '1' where `id` = '$user[id]' limit 1");
$_SESSION['message'] = "Новость успешно скрыта"; // Оповещаем
header("Location: /?");
exit;
}
/*--------------------alex-borisi---------------------*/


$tPanel = "<div id='comments' class='tpanel'>
<div class='tmenu'><a href='/plugins/smiles/'>Смайлы</a></div>
</div>";


/*
=====================================
Причины бана
=====================================
*/
$pBan[0] = "Другое";
$pBan[1] = "Спам/Реклама";
$pBan[2] = "Мошенничество";
$pBan[3] = "Нецензурная брань";
$pBan[4] = "Клонирование ников";
$pBan[5] = "Подстрекательство, провокация и побуждение к агрессии";
$pBan[6] = "Флуд";
$pBan[7] = "Флейм";

/*
=====================================
Раздел бана
=====================================
*/
$rBan['all'] = "Весь сайт";
$rBan['notes'] = "Дневники";
$rBan['forum'] = "Форум";
$rBan['files'] = "Файлы";
$rBan['guest'] = "Весь сайт";
$rBan['chat'] = "Чат";
$rBan['lib'] = "Библиотека";
$rBan['foto'] = "Фотографии";

/*
=====================================
Сообщение в комментариях
=====================================
*/
$banMess = '[red]Это сообщение ушло париться вместе с автором в баню![/red]';

if (isset($_POST['msg']) && !isset($user)){echo "Сам иди на хуй мудак не доделанный! ЧМО!"; exit;}


/*
=====================================
Валюта
=====================================
*/
$sMonet[0] = 'монет';
$sMonet[1] = 'монета';
$sMonet[2] = 'монеты';




?>

