<?php

/****************************************/
// ИНФОРМАЦИЯ:
// ==== Форум: LogicBoard
// ==== Автор: Никита Курдин (ShapeShifter)
// ==== Copyright © Никита Курдин Игоревич 2011
// ==== Данный код защищен авторскими правами
// ==== Официальный сайт: http://logicboard.ru

/****************************************/

if (! defined ( 'LogicBoard' ))
{
	@include '../../logs/save_log.php';
	exit ( "Error, wrong way to file.<br><a href=\"/\">Go to main</a>." );
}

$secret_key = "";
$logged = false;

if (isset($_POST['autoriz']))
{
    $lang_g_login = language_forum ("board/global/login");
    
	$errors = array ();

    filters_input('post');

	if (!$_POST['password'])
		$errors[] = $lang_g_login['no_pass'];
	if (!$_POST['name'])
		$errors[] = $lang_g_login['no_name'];

	if( preg_match( "/[\||\'|\<|\>|\"|\!|\?|\$|\/|\\\|\&\~\*\+\{\}]/", $_POST['name'] ) )
		$errors[] = $lang_g_login['name_symbols'];
        
    if (utf8_strlen($_POST['name']) < 2)
        $errors[] = str_replace("{num}", "2", $lang_g_login['name_min']);
        
    if ($cache_config['security_logincount']['conf_value'] AND intval($cache_config['security_loginmin']['conf_value']))
    {
        $guest = $DB->one_select( "*", "members_login", "login_ip = '{$_IP}'" );        
        if ($guest['login_count'] >= $cache_config['security_logincount']['conf_value'])
        {     
            $time_logblock = $time - (intval($cache_config['security_loginmin']['conf_value']) * 60);
            
            if ($guest['login_date'] < $time_logblock)
            {
                $DB->delete("login_ip = '{$_IP}'", "members_login");
                $guest['login_count'] = 0;
            }
            else
            {
                $errors[] = $lang_g_login['block'];
                
                $lang_g_login['block2'] = str_replace("{min}", intval($cache_config['security_loginmin']['conf_value']), $lang_g_login['block2']);
                $lang_g_login['block2'] = str_replace("{date}", formatdate($guest['login_date']), $lang_g_login['block2']);
                $errors[] = $lang_g_login['block2'];
            }
        }
    }

	if  ( !$errors[0] )
	{       
		$password_md1 = $DB->addslashes(md5($_POST['password']));
        $password_md2 = $DB->addslashes(md5(md5($_POST['password'])));
        
		$name = $DB->addslashes($_POST['name']);
        
        $DB->prefix = DLE_USER_PREFIX;
        if ($cache_config['security_loginemail']['conf_value'])
            $member_id = $DB->one_select( "*", "users", "password = '{$password_md2}' AND email = '{$name}'" );
        else
            $member_id = $DB->one_select( "*", "users", "password = '{$password_md2}' AND name = '{$name}'" );
        
		if (!$member_id['user_id'])
			$errors[] = $lang_g_login['no_member_id'];

		if ($member_id['user_id'] AND !$errors)
		{
            if ($cache_config['online_status']['conf_value'])
            {
                $DB->delete("mo_ip = '{$_IP}'", "members_online");
            }
          
            if (!$member_id['secret_key'])
            {
                $member_id['secret_key'] = md5(md5($password_md2.time().$_IP));
                $DB->prefix = DLE_USER_PREFIX;
                $DB->update ("secret_key='{$member_id['secret_key']}'", "users", "user_id='{$member_id['user_id']}'");
            }
          
			if (intval($_POST['remember']))
			{
				update_cookie( "dle_user_id", $member_id['user_id'], 365 );
				update_cookie( "dle_password", $password_md1, 365 );
                update_cookie( "LB_member_sc", $member_id['secret_key'], 365 );
			}
			
			$_SESSION['dle_user_id'] = $member_id['user_id'];
			$_SESSION['dle_password'] = $password_md1;
            $_SESSION['member_lasttime'] = $member_id['lastdate'];
			$_SESSION['LB_lastdate'] = $member_id['lastdate'];
            $_SESSION['LB_member_sc'] = $member_id['secret_key'];

			$secret_key = md5( strtolower( $_SERVER['HTTP_HOST'] . $member_id['name'] . sha1($password_md1) . date( "Ymd" ) ) );
            
			$_SESSION['LB_secret_key'] = $secret_key;
          
            $DB->prefix = DLE_USER_PREFIX;
			$DB->update ("lastdate='{$time}', logged_ip='{$_IP}'", "users", "user_id='{$member_id['user_id']}'");
			
			$logged = true;
			header( "Location: {$_SERVER['REQUEST_URI']}" );
            exit();
		}
		else
			message ("Ошибка!", $errors);
	}
	else
    {
        if ($cache_config['security_logincount']['conf_value'] AND $cache_config['security_loginmin']['conf_value'] AND $guest['login_count'] < $cache_config['security_logincount']['conf_value'])
        {
            $DB->insert("login_ip ='{$_IP}', login_count='1', login_date = '{$time}' ON DUPLICATE KEY UPDATE login_ip ='{$_IP}', login_count = login_count+1, login_date = '{$time}'", "members_login");
        }
		message ("Ошибка!", $errors);
    }
}
elseif( intval( $_SESSION['dle_user_id'] ) > 0 OR intval( $_COOKIE['dle_user_id'] ) > 0)
{
    filters_input('coockie|session');
    
	if (intval( $_SESSION['dle_user_id'] ) > 0)
	{
		$id_login = intval( $_SESSION['dle_user_id'] );
		$pass_login = $DB->addslashes($_SESSION['dle_password']);
        $member_sk = $DB->addslashes($_SESSION['LB_member_sc']);
	}
	else
	{
		$id_login = intval( $_COOKIE['dle_user_id'] );
		$pass_login = $DB->addslashes($_COOKIE['dle_password']);
        $member_sk = $DB->addslashes($_COOKIE['LB_member_sc']);
	}

    $DB->prefix = DLE_USER_PREFIX;
	$member_id = $DB->one_select( "*", "users", "user_id='{$id_login}'" );
    $logged = false;
        
	if( $member_id['password'] == md5($pass_login) AND $member_id['secret_key'] == $member_sk AND $member_sk != "")
	{
        if( $member_id['lb_limit_publ'] AND $member_id['lb_limit_days'] AND $member_id['lb_limit_date'] < $time )
        {
    	   $member_id['restricted'] = 0;
    	   $DB->not_filtred( "UPDATE LOW_PRIORITY " . DLE_USER_PREFIX . "_users SET lb_limit_publ='0', lb_limit_days='0', lb_limit_date='0' WHERE user_id='{$member_id['user_id']}'" );
        }
       
        $member_options = unserialize($member_id['mf_options']);
        $member_options = member_options_default($member_options);
        
        if (LB_member_ip($member_id['allowed_ip']))
        {
            $logged = true;
            $secret_key = md5( strtolower( $_SERVER['HTTP_HOST'] . $member_id['name'] . sha1($pass_login) . date( "Ymd" ) ) );
		
            $_SESSION['dle_user_id'] = $member_id['user_id'];
            $_SESSION['dle_password'] = $pass_login;
            $_SESSION['LB_member_sc'] = $member_id['secret_key'];
            
            if (!$_SESSION['LB_lastdate'])
            {
                $_SESSION['LB_lastdate'] = $member_id['lastdate'];
                $_SESSION['member_lasttime'] = $member_id['lastdate'];
                
                if( ($member_id['lastdate'] + (3600 * 4)) < $time ) //4 минуты
                    $DB->not_filtred( "UPDATE LOW_PRIORITY " . DLE_USER_PREFIX . "_users SET lastdate='{$time}' WHERE user_id='{$member_id['user_id']}'" );
            }            
        }
        else
            message ($lang_message['access_denied'], $lang_g_login['block_ip']);
	}
}

if( !$logged)
{
	$member_id = array ();
    $member_id['user_group'] = 5;
	update_cookie( "LB_secret_key", "", 0 );
    update_cookie( "LB_member_sc", "", 0 );
    update_cookie( "dle_user_id", "", 0 );
	update_cookie( "dle_password", "", 0 );
	update_cookie( "dle_hash", "", 0 );
	$_SESSION['dle_user_id'] = 0;
	$_SESSION['dle_password'] = "";
	$_SESSION['LB_secret_key'] = "";
    $_SESSION['LB_member_sc'] = "";
}

if( isset( $_REQUEST['logout'] ) AND $logged )
{
	if (!$_GET['secret_key'] OR $_GET['secret_key'] != $secret_key)
	{
		exit ( "Error, wrong secret key.<br><a href=\"/\">Go to main</a>." );
	}

	$secret_key = "";
	update_cookie( "dle_user_id", "", 0 );
	update_cookie( "dle_password", "", 0 );
	update_cookie( "dle_hash", "", 0 );
	update_cookie( "LB_secret_key", "", 0 );
    update_cookie( "LB_member_sc", "", 0 );
	update_cookie( session_name(), "", 0 );
	@session_unset();
	@session_destroy();
	$logged = false;
    
	header( "Location: {$redirect_url}" );
	exit();
}

?>