<?
if ($level != 0) {
  header('Location: /index.php');
  exit;
}

require FUNC . 'user.browser.php';
	//$browser = browser($_SERVER['HTTP_USER_AGENT']);
	$browser = $_SERVER['HTTP_USER_AGENT'];

if (isset($_POST['nick']) && isset($_POST['pass']) && !isset($user['id'])) {
	$password = $sql->esc($_POST['pass']);
    $login = $sql->esc($_POST['nick']);
	
	if ($sql -> selectCount("SELECT COUNT(*) FROM `users` WHERE `email` = '" . $login . "' AND `password` = '" . md5($password) . "'") == 0) {
	        $_SESSION['fail_aut'] ++;

	if ($_SESSION['fail_aut'] > 1){
		$msg = 'Человек с IP адресом [b]'.$_SERVER['REMOTE_ADDR'].'[/b] попытался войти в профиль '.$login.', но указал неверный пароль.

С уважением, Служба безопасности сайта!';
$sql -> insert("INSERT INTO `mail` (`id_user`, `id_contact`, `msg`, `time`) values('2', '1', '".$sql->esc($msg)."', '".$time."')");


$sql -> update("UPDATE `contacts` SET `time_last` = '$time', `id_last` = '1' WHERE (`id_user` = '1' AND `id_contact` = '2') OR (`id_user` = '2' AND `id_contact` = '1') LIMIT 1");


	}	
	

$err[] = __('Неверный логин или пароль');

	}
/*
    if ($system['captcha_auth'] == 1) {
        $captcha = (int) $_POST['captcha'];
        if ($captcha != $_SESSION['captcha']) {
          $err[] = __('Неверный код с картинки');
        }
    }
*/
    if ($_SESSION['fail_aut'] > 1) {
        $captcha = (int) $_POST['captcha'];
        if ($captcha != $_SESSION['captcha']) {
          $err[] = __('Неверный код с картинки');
        }
    }

	if (!isset($err)) {
		$user = $sql -> fetch("SELECT * FROM `users` WHERE `email` = '" . $login . "' AND `password` = '" . md5($password) . "' LIMIT 1");
    
		$sql -> insert("INSERT INTO `users_log` (`ua`, `ip`, `time`, `type`, `id_user`, `idkey`) VALUES ('" . $sql->esc($browser) . "', '" . $sql->esc($iplong) . "', '$time', 'login', '$user[id]','".md5(time().mt_rand(1,9999))."')");
		//$sql -> insert("INSERT INTO `users_log` (`ua`, `ip`, `time`, `type`, `id_user`) VALUES ('" . $sql->esc($ua) . "', '$time', 'login', '$user[id]')");
    
		$sql -> update("UPDATE `users` SET `date_last` = '$time', `ip` = '" . $sql->esc($iplong) . "', `ua` = '" . $sql->esc($browser) . "', `sess` = '$signature' WHERE `id` = '$user[id]' LIMIT 1");
		
		$_SESSION['id_user'] = $user['id'];

                            setcookie('id_user', $user['id'], time() + 60 * 60 * 24 * 365);
			    setcookie('pass', cookie_encrypt($password, $user['id']), time() + 60 * 60 * 24 * 365);      
		
                if (isset($_POST['save'])) {
			setcookie('id_user', $user['id'], time() + 60 * 60 * 24 * 365);
			setcookie('pass', cookie_encrypt($password, $user['id']), time() + 60 * 60 * 24 * 365);
		}
		header('Location: ?func=user.main&log');
		exit;	
	}
} elseif (isset($_COOKIE['id_user']) && isset($_COOKIE['pass']) && $_COOKIE['id_user'] && $_COOKIE['pass'] && !isset($user['id'])) {
	if ($sql -> selectCount("SELECT COUNT(*) FROM `users` WHERE `id` = '" . intval($_COOKIE['id_user']) . "' AND 
  `password` = '" . md5(cookie_decrypt($_COOKIE['pass'], intval($_COOKIE['id_user']))) . "' AND `sess` = '$signature'") == 1) {
    
		$user = $sql -> fetch("SELECT * FROM `users` WHERE  `id` = '" . intval($_COOKIE['id_user']) . "' AND 
    `password` = '" . md5(cookie_decrypt($_COOKIE['pass'],intval($_COOKIE['id_user']))) . "' LIMIT 1");
    
		$_SESSION['id_user'] = $user['id'];
    
        $sql -> insert("INSERT INTO `users_log` (`ua`, `ip`, `time`, `type`, `id_user`,`idkey`) VALUES ('" . $sql->esc($browser) . "', '" . $sql->esc($iplong) . "', '$time', 'cookie', '$user[id]' ,'".md5(time().mt_rand(1,9999))."')");
    	$sql -> update("UPDATE `users` SET `date_last` = '$time', `ip` = '" . $sql->esc($iplong) . "', `ua` = '" . $sql->esc($browser) . "', `sess` = '$signature' WHERE `id` = '$user[id]' LIMIT 1");

		if (isset($_GET['return'])) {
			header('Location: ' . urldecode($_GET['return']));
		} else {
			header('Location: ?func=user.main&log');
		}
		exit;	
	} else {
		setcookie('id_user');
		setcookie('pass');
		$err[] = __('Ошибка авторизации по Cookie');
	}
}

$system['title'] = 'Авторизация';
require SYS . 'header.php';
?>
<form class="form-horizontal" action="?func=user.auth" method="POST">
  <div class="control-group">
    <label class="control-label" for="inputLogin"><font color="red"><b><?= __('Email')?></b></font></label>
    <div class="controls">
      <input type="text" id="inputLogin" name="nick" placeholder="<?= __('Email')?>.." value="<?= (isset($login) ? text($login) : '')?>" />
    </div>
  </div>
  
  <div class="control-group">
    <label class="control-label" for="inputPass"><?= __('Пароль')?></label>
    <div class="controls">
      <input type="password" id="inputPass" name="pass" placeholder="<?= __('Пароль')?>.." value="<?= (isset($password) ? text($password) : '')?>" />
    </div>
  </div>
  
  <? /*if ($system['captcha_auth'] == 1)*/ if ($_SESSION['fail_aut'] > 1) { ?>
  <div class="control-group">
    <label class="control-label" for="captcha"><?= __('Код с картинки')?></label>
    <div class="controls">
     <img src="/_src/captcha.php?sid=<?= mt_rand(10000, 99999); ?>" id="captcha" class="captcha" /> <input type="text" id="captcha" class="captcha" name="captcha" placeholder="<?= __('Введите код с картинки')?>..">
    </div>
  </div>
  <? } ?>
  
  <div class="control-group">
    <div class="controls">
	  <label class="checkbox">
        <input type="checkbox" name="save" value="1" checked> <?= __('Запомнить меня')?>
      </label>
	  
      <button type="submit" class="btn"><?= __('Войти')?></button>  <a href="?func=recovery.password"><?= __('Забыли пароль?')?></a>
    </div>
  </div>
</form>
