<?php

// Определение юзера
if (isset($_SESSION['id_user']) && @mysql_result(mysql_query("SELECT COUNT(*) FROM `user` WHERE `id` = '$_SESSION[id_user]' LIMIT 1"), 0) == 1) {

    
	$user = get_user($_SESSION['id_user']);
    
	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']) {
    
//	if (!isset($_POST['token'])) {
//		header("Location: /module/sign-in/checkup.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_p_str'] != NULL) {
        $set['p_str'] = $user['set_p_str'];
    }
	


    // бан пользователя
	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;
		}
	}

	/*
	========================================
	Создание настроек юзера 
	========================================
	*/


	
	
	

	// Записываем url 
	mysql_query("UPDATE `user` SET `url` = '".my_esc($_SERVER['SCRIPT_NAME'])."' WHERE `id` = '$user[id]' LIMIT 1");
	
	// для web темы
	if ($webbrowser) {
		if (is_dir(H.'kernel/theme/' . $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.'kernel/theme/'.$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");
        }
	}

	// Пишем ip пользователя
	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 `sess` = '$sess' WHERE `id` = '$user[id]' LIMIT 1");

/*
	========================================
	Ответы в комм > v.1.7.4
	========================================
	*/
	
	if (!isset($insert)) {
        $insert = null;
    }
	
	if (isset($_GET['response']) && mysql_result(mysql_query("SELECT COUNT(*) FROM `user` WHERE `id` = '" . intval($_GET['response']) . "'"), 0) == 1) {
		$ank_reply = mysql_fetch_assoc(mysql_query("SELECT * FROM `user` WHERE `id` = '" . intval($_GET['response']) . "' LIMIT 1"));
		$insert = $ank_reply['nick'] . ', ';
		$go_link = '?' . $passgen . '&amp;response=' . $ank_reply['id'];	
	} else {
		$go_link = NULL;
	}

	// Ссылка при ответе
	define("REPLY", $go_link);
} 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); 
    
    // Ставим ограничение на 20 сек
	if (function_exists('set_time_limit')) { @set_time_limit(20); }
}

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

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'];
    
    // Продолжаем просмотр файла с меткой 18+
	if (isset($_GET['sess_abuld']) && $_GET['sess_abuld']  ==  1) {
		$_SESSION['abuld'] = 1;
	}
	
	if (isset($_SESSION['abuld']) && $_SESSION['abuld']  ==  1) {
        $user['abuld'] = 1;
    }
}




/*
========================================
Смена тем для юзеров папки wap и web
========================================

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: ' . htmlspecialchars($_SERVER['HTTP_REFERER']));
	exit;
}

/*
========================================
Сортировка списка по времени
========================================
*/

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: ' . htmlspecialchars($_SERVER['HTTP_REFERER']));
    exit;
}

if (isset($user))$sort = ($user['sort'] == 1?' ASC ':' DESC ');
else $sort = 'DESC';

// Страницы 
if (isset($user) && $user['sort']  ==  1) {
    $pageEnd = 'end';
} else {
    $pageEnd = '1';
}

/*
========================================
Ответы в комм [DELETE]
========================================
*/


/*
========================================
Причины бана
========================================
*/

$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['foto'] = "Фотографии";

/*
========================================
Сообщение в комментариях
========================================
*/

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

if (isset($_POST['msg']) && !isset($user) && $_SERVER['PHP_SELF'] != '/guest/index.php') {
    die(__('Вы не авторизованы!'));
}

/*
========================================
Валюта
========================================
*/

$sMonet[0] = 'монет';
$sMonet[1] = 'монета';
$sMonet[2] = 'монеты';


    
?>