<?php

#проверяем наличие пользователя
if (!empty($_SESSION['id_user'])) {
    # проверяем наличие пользователя
    $q = $db->query("SELECT `id` FROM `user` WHERE `id` = '" . $_SESSION['id_user'] . "'");
    # если такой нашелся
    if ($db->get_row($q) == 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);
        }
    }
    $user = get_user($_SESSION['id_user']);

    $tmp_us = $db->get_row($db->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 = '" . $db->safesql($ua) . "',";
    } else {
        $sqlup['ua'] = null;
    }

    $sqlup['userlevel'] = "level = '" . $tmp_us['level'] . "',";
    $sqlup['sess'] = "sess = '" . $sess . "'";
    $sqlup['url'] = "url = '" . $db->safesql($_SERVER['REQUEST_URI']) . "',";

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

    unset($sqlup);
} elseif (!isset($input_page) && isset($_COOKIE['id_user']) && isset($_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://soccms.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)) {

    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'])) {
            $row = $db->query("SELECT COUNT(*) FROM `user_ref` WHERE `id_user` = '$user[id]' AND `url` = '" . $db->safesql($ref['host']) . "'");
            if ($db->get_row($row) == 1) {
                $db->query("INSERT INTO `user_ref` (`time`, `id_user`, `type_input`, `url`) VALUES ('" . $time . "', '" . $user['id'] . "', '" . $user['type_input'] . "', '" . $db->safesql($ref['host']) . "')");
            } else {
                $db->query("UPDATE user_ref SET time = '$time' WHERE id_user = '$user[id]' AND url = '" . $db->safesql($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 ($user['set_p_str']) {
        $set['p_str'] = (int) $user['set_p_str'];
    }

    if (isset($user) && isset($_GET['sort']) && ($_GET['sort'] == '0' || $_GET['sort'] == '1')) {
        $db->query("UPDATE user SET sort = '$_GET[sort]' where id = '$user[id]' limit 1");
        header('Location: ' . htmlspecialchars($_SERVER['HTTP_REFERER']));
    }


    #бан пользователя
    if (!isset($banpage)) {
        $r = $db->super_query("SELECT COUNT(*) as count FROM `ban` WHERE `id_user` = '$user[id]' AND (`time` > '$time' OR `view` = '0')");
        if ($r['count'] != 0) {
            header('Location: /ban.php?' . SID);
            exit;
        }
    }

    if (IS_WEB == 1) {
        $db->query("UPDATE `user` SET `browser` = 'web' WHERE `id` = '" . $db->safesql($user['id']) . "' LIMIT 1");
    } else {
        $db->query("UPDATE `user` SET `browser` = 'wap' WHERE `id` = '" . $db->safesql($user['id']) . "' LIMIT 1");
    }

    $collision_q = $db->query("SELECT * FROM `user` WHERE `ip` = '$iplong' AND `ua` = '" . $db->safesql($ua) . "' AND `date_last` > '" . (time() - 600) . "' AND `id` <> '$user[id]'");
    while ($collision = $db->get_row($collision_q)) {
        $coll = $db->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]'");
        if ($db->get_row($coll) == 0) {
            $db->query("INSERT INTO `user_collision` (`id_user`, `id_user2`, `type`) values('$user[id]', '$collision[id]', 'ip_ua_time')");
        }
    }
} else {
    //записываем гостей
    $sc = isset($_SERVER['SCRIPT_NAME']) ? $db->safesql($_SERVER['SCRIPT_NAME']) : '';

    $u2 = $db->super_query("SELECT COUNT(*) as count FROM `guests` WHERE `ip` = '$iplong' AND `ua` = '" . $db->safesql($ua) . "' LIMIT 1");
    $u = $u2['count'];

    if ($ip AND $ua AND ( $u == 1)) {
        $db->query("UPDATE `guests` SET `date_last` = '" . time() . "', `url` = '$sc', `pereh` = pereh+1 WHERE `ip` = '$iplong' AND `ua` = '" . $db->safesql($ua) . "' LIMIT 1");
    } else {
        $db->query("INSERT INTO `guests` (`ip`, `ua`, `date_aut`, `date_last`, `url`) VALUES ('$iplong', '" . $db->safesql($ua) . "', '" . time() . "', '" . time() . "', '$sc')");
    }

    unset($access);
}

if (isset($user)) {
    $sort = ($user['sort'] == 1 ? ' ASC ' : ' DESC ');
} else {
    $sort = 'DESC';
}
if (isset($user)) {
    $SexKomm = "" . ($user['sex'] ? 'прокомментировал' : 'прокомментировала') . "";
    $SexDob = "" . ($user['sex'] ? 'добавил' : 'добавила') . "";
    $SexOtv = "" . ($user['sex'] ? 'ответил' : 'ответила') . "";
    $SexOcen = "" . ($user['sex'] ? 'оценил' : 'оценила') . "";
    $SexOst = "" . ($user['sex'] ? 'оставил' : 'оставила') . "";
    $SexObn = "" . ($user['sex'] ? 'обновил' : 'обновила') . "";
    $SexOpub = "" . ($user['sex'] ? 'опубликовал' : 'опубликовала') . "";
    $SexZapr = "" . ($user['sex'] ? 'запретил' : 'запретила') . "";
    $SexNap = "" . ($user['sex'] ? 'написал' : 'написала') . "";
    $SexOgr = "" . ($user['sex'] ? 'ограничил' : 'ограничила') . "";
    $SexPer = "" . ($user['sex'] ? 'перевел' : 'перевела') . "";
    $SexPos = "" . ($user['sex'] ? 'Посещал' : 'Посещала') . "";
}

#Показ ошибок 
if (isset($user) AND $user['group_access'] > 1 AND $set['show_err_php'] == 1) {
    error_reporting(E_ALL); // E_ALL - отображаем ВСЕ ошибки
    ini_set('display_errors', true);
}

#Включаем режим если гость кидаем на авторизацию 
if (!isset($user) and $set['guest_select'] == 1 and ! isset($show_all)) {
    exit(header('Location: /aut.php'));
}

include_once H . 'sys/inc/browser.php';

