<?php

#Определение юзера
if (isset($_SESSION['id_user']) && mysql_result(query("SELECT COUNT(*) FROM `user` WHERE `id` = '" . intval($_SESSION['id_user']) . "' LIMIT 1"), 0) == 1) {
    $user = get_user($_SESSION['id_user']);
    include_once H . 'sys/inc/shif.php';

    if (empty($_COOKIE['pass']) OR empty($_COOKIE['id_user'])) {
        setcookie('id_user', $user['id'], time() + 60 * 60 * 24 * 365);
        setcookie('pass', cookie_encrypt($user['pass'], $user['id']), time() + 60 * 60 * 24 * 365);
    }


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

    $timeactiv = time() - $user['date_last'];
    if ($timeactiv < 120) {
        $newtimeactiv = $user['time'] + $timeactiv;
        $sqlup['timeactiv'] = ", `time` = '" . $newtimeactiv . "'";
        unset($nevtimeactiv, $timeactiv);
    } else {
        $sqlup['timeactiv'] = NULL;
    }

    if (isset($ip2['add'])) {
        $sqlup['ip'] = ", `ip` = '" . ip2long($ip2['add']) . "'";
    } else {
        $sqlup['ip'] = NULL;
    }

    if (isset($ip2['cl'])) {
        $sqlup['ip_cl'] = ", `ip_cl` = '" . ip2long($ip2['cl']) . "'";
    } else {
        $sqlup['ip_cl'] = NULL;
    }

    if (isset($ip2['xff'])) {
        $sqlup['ip_xff'] = ", `ip_xff` = '" . ip2long($ip2['xff']) . "'";
    } else {
        $sqlup['ip_xff'] = NULL;
    }

    if ($ua) {
        $sqlup['ua'] = ", `ua` = '" . mysql_real_escape_string($ua) . "'";
    } else {
        $sqlup['ua'] = NULL;
    }

    $sqlup['userlevel'] = ", `level` = '" . $tmp_us['level'] . "'";
    $sqlup['sess'] = ", `sess` = '" . $sess . "'";
    $sqlup['url'] = ", `url` = '" . mysql_real_escape_string($_SERVER['REQUEST_URI']) . "'";

    mysql_query("UPDATE `user` SET `hash` = '" . md5(md5($ip . md5($ua) . $user['id'])) . "', `date_last` = '" . $time . "'" . $sqlup['userlevel'] . "" . $sqlup['timeactiv'] . "" . $sqlup['ip'] . "" . $sqlup['ip_cl'] . "" . $sqlup['ip_xff'] . "" . $sqlup['ua'] . "" . $sqlup['url'] . "" . $sqlup['sess'] . " WHERE `id` = '" . $user['id'] . "' LIMIT 1");
    $user['type_input'] = 'session';

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

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

$lic = "http://sevfo.com/license/$_SERVER[HTTP_HOST].key";
$lic = @get_headers($lic);
$license = null;
if ($lic[0] == 'HTTP/1.1 404 Not Found') {
    $license = 'Lite';
} else {
    $license = 'Pro';
}

if (isset($user)) {

    $timeactiv = time() - $user['date_last'];
    if ($timeactiv < 120) {
        $newtimeactiv = $user['time'] + $timeactiv;
        mysql_query("UPDATE `user` SET `time` ='" . mysql_real_escape_string($newtimeactiv) . "', `perehodu` = '" . mysql_real_escape_string($user['perehodu'] + 1) . "' WHERE `id` = '" . mysql_real_escape_string($user['id']) . "' LIMIT 1");
        echo mysql_error();
    }
    $tmp_us = mysql_fetch_assoc(mysql_query("SELECT `level` FROM `user_group` WHERE `id` = '$user[group_access]' LIMIT 1"));
    $user['level'] = $tmp_us['level'];

// Добавление отсутствующих полей 
    if (!isset($user['activation'])) {
        mysql_query('ALTER TABLE `user` ADD `activation` VARCHAR( 32 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL AFTER `sess`');
    }

    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` = '" . mysql_real_escape_string($user['id']) . "' AND `url` = '" . mysql_real_escape_string($ref['host']) . "'"), 0) == 0) {
                mysql_query("INSERT INTO `user_ref` (`time`, `id_user`, `type_input`, `url`) VALUES ('" . mysql_real_escape_string($time) . "', '" . mysql_real_escape_string($user['id']) . "', '" . mysql_real_escape_string($user['type_input']) . "', '" . mysql_real_escape_string($ref['host']) . "')");
            } else {
                mysql_query("UPDATE `user_ref` SET `time` = '" . mysql_real_escape_string($time) . "' WHERE `id_user` = '" . mysql_real_escape_string($user['id']) . "' AND `url` = '" . mysql_real_escape_string($ref['host']) . "'");
            }
        }
    }

    if (empty($user)) {
        $set['lang'] = isset($_SESSION['lang']) ? $_SESSION['lang'] : $set['lang'];
    }
    if (!preg_match('#^[A-z0-9-._]$#ui', $set['lang'])) {
        $set['lang'] = $set['lang'];
    } else { //если что-то не так
        $set['lang'] = 'ru';
    }

    if (isset($user)) {
        $set['lang'] = $user['lang'];
    }
    if ($set['lang'] == null) {
        $set['lang'] = 'ru';
    }
    if (isset($_SESSION['lang']) && $_SESSION['lang'] == null) {
        $_SESSION['lang'] = $set['lang'];
    }

    if (!isset($user['autorization'])) {
        mysql_query("ALTER TABLE `user` ADD `autorization` SET( '0', '1' ) NOT NULL DEFAULT '0'");
    }
    if (!isset($user['ip_cl'])) {
        mysql_query("ALTER TABLE `user` ADD `ip_cl` BIGINT( 20 ) NOT NULL AFTER `ip` , ADD `ip_xff` BIGINT( 20 ) NOT NULL AFTER `ip_cl`");
    }

    if ($user['set_p_str']) {
        $set['p_str'] = (int) $user['set_p_str'];
    }

    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']));
    }


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

// бан пользователя
    if (!isset($banpage) && mysql_result(mysql_query("SELECT COUNT(*) FROM `ban` WHERE `id_user` = '$user[id]' AND (`time` > '$time' OR `view` = '0')"), 0)) {
        header('Location: /ban.php?' . SID);
        exit;
    }
    if (isset($ip2['add'])) {
        mysql_query("UPDATE `user` SET `ip` = " . ip2long($ip2['add']) . " WHERE `id` = '" . mysql_real_escape_string($user['id']) . "' LIMIT 1");
    } else {
        mysql_query("UPDATE `user` SET `ip` = null WHERE `id` = '" . mysql_real_escape_string($user['id']) . "' LIMIT 1");
    }
    if (isset($ip2['cl'])) {
        mysql_query("UPDATE `user` SET `ip_cl` = " . ip2long($ip2['cl']) . " WHERE `id` = '" . mysql_real_escape_string($user['id']) . "' LIMIT 1");
    } else {
        mysql_query("UPDATE `user` SET `ip_cl` = null WHERE `id` = '" . mysql_real_escape_string($user['id']) . "' LIMIT 1");
    }
    if (isset($ip2['xff'])) {
        mysql_query("UPDATE `user` SET `ip_xff` = " . ip2long($ip2['xff']) . " WHERE `id` = '" . mysql_real_escape_string($user['id']) . "' LIMIT 1");
    } else {
        mysql_query("UPDATE `user` SET `ip_xff` = null WHERE `id` = '" . mysql_real_escape_string($user['id']) . "' LIMIT 1");
    }
    if ($ua) {
        mysql_query("UPDATE `user` SET `ua` = '" . mysql_real_escape_string($ua) . "' WHERE `id` = '" . mysql_real_escape_string($user['id']) . "' LIMIT 1");
    }

    mysql_query("UPDATE `user` SET `url` = '" . mysql_real_escape_string($_SERVER['SCRIPT_NAME']) . "' WHERE `id` = '" . mysql_real_escape_string($user['id']) . "' LIMIT 1");
    if (!preg_match("/\bforum\b/i", mysql_real_escape_string($_SERVER['SCRIPT_NAME']))) {
        unset($_SESSION['sort_' . $user['id']]);
    }
    mysql_query('UPDATE `user` SET `forum_url` = "' . mysql_real_escape_string($_SERVER["REQUEST_URI"]) . '" WHERE `id` = ' . $user['id']);
    mysql_query("UPDATE `user` SET `sess` = '" . mysql_real_escape_string($sess) . "' WHERE `id` = '" . mysql_real_escape_string($user['id']) . "' LIMIT 1");

    if (IS_WEB == 1) {
        mysql_query("UPDATE `user` SET `browser` = 'web' WHERE `id` = '" . mysql_real_escape_string($user['id']) . "' LIMIT 1");
    } else {
        mysql_query("UPDATE `user` SET `browser` = 'wap' WHERE `id` = '" . mysql_real_escape_string($user['id']) . "' LIMIT 1");
    }

    $collision_q = mysql_query("SELECT * FROM `user` WHERE `ip` = '" . mysql_real_escape_string($iplong) . "' AND `ua` = '" . mysql_real_escape_string($ua) . "' AND `date_last` > '" . mysql_real_escape_string(time() - 600) . "' AND `id` <> '" . mysql_real_escape_string($user['id']) . "'");
    while ($collision = mysql_fetch_assoc($collision_q)) {
        if (mysql_result(mysql_query("SELECT COUNT(*) FROM `user_collision` WHERE `id_user` = '" . mysql_real_escape_string($user['id']) . "' AND `id_user2` = '" . mysql_real_escape_string($collision['id']) . "' OR `id_user2` = '" . mysql_real_escape_string($user['id']) . "' AND `id_user` = '" . mysql_real_escape_string($collision['id']) . "'"), 0) == 0) {
            mysql_query("INSERT INTO `user_collision` (`id_user`, `id_user2`, `type`) values('" . mysql_real_escape_string($user['id']) . "', '" . mysql_real_escape_string($collision['id']) . "', 'ip_ua_time')");
        }
    }
} else {
    if ($ip && $ua) {
        if (mysql_result(mysql_query("SELECT COUNT(*) FROM `guests` WHERE `ip` = '" . mysql_real_escape_string($iplong) . "' AND `ua` = '" . mysql_real_escape_string($ua) . "' LIMIT 1"), 0) == 1) {
            $guests = mysql_fetch_assoc(mysql_query("SELECT * FROM `guests` WHERE `ip` = '" . mysql_real_escape_string($iplong) . "' AND `ua` = '" . mysql_real_escape_string($ua) . "' LIMIT 1"));
            mysql_query("UPDATE `guests` SET `date_last` = '" . mysql_real_escape_string(time()) . "', `url` = '" . mysql_real_escape_string($_SERVER['SCRIPT_NAME']) . "', `pereh` = '" . mysql_real_escape_string($guests['pereh'] + 1) . "' WHERE `ip` = '" . mysql_real_escape_string($iplong) . "' AND `ua` = '" . mysql_real_escape_string($ua) . "' LIMIT 1");
        } else {
            mysql_query("INSERT INTO `guests` (`ip`, `ua`, `date_aut`, `date_last`, `url`) VALUES ('" . mysql_real_escape_string($iplong) . "', '" . mysql_real_escape_string($ua) . "', '" . mysql_real_escape_string(time()) . "', '" . mysql_real_escape_string(time()) . "', '" . mysql_real_escape_string($_SERVER['SCRIPT_NAME']) . "')");
        }
    }
    unset($access);
}
if (isset($user)) {
    $SexKomm = "" . ($user['sex'] ? 'прокомментировал' : 'прокомментировала') . "";
    $SexDob = "" . ($user['sex'] ? 'добавил' : 'добавила') . "";
    $SexOtv = "" . ($user['sex'] ? 'ответил' : 'ответила') . "";
    $SexOcen = "" . ($user['sex'] ? 'оценил' : 'оценила') . "";
    $SexOst = "" . ($user['sex'] ? 'оставил' : 'оставила') . "";
    $SexObn = "" . ($user['sex'] ? 'обновил' : 'обновила') . "";
    $SexZapr = "" . ($user['sex'] ? 'запретил' : 'запретила') . "";
    $SexNap = "" . ($user['sex'] ? 'написал' : 'написала') . "";
    $SexOgr = "" . ($user['sex'] ? 'ограничил' : 'ограничила') . "";
    $SexPer = "" . ($user['sex'] ? 'перевел' : 'перевела') . "";
    $SexPos = "" . ($user['sex'] ? 'Посещал' : 'Посещала') . "";
}

if (!isset($user) || $user['level'] == 0) {
    ini_set('display_errors', 'On'); // сообщения с ошибками будут показываться
    error_reporting(E_ALL); // E_ALL - отображаем ВСЕ ошибки

    if (function_exists('set_time_limit')) {
        set_time_limit(20);
    } // Ставим ограничение на 20 сек
}
if (!isset($user) && $set['guest_select'] == '1' && !isset($show_all)) {
    header("Location: /aut.php");
    exit;
}
