<?
Class Auth{
  public $ID     = 0;
  public $solt   = '';
  public $error  = array();
  public $Data = array();
  private $RememberTime = 1814400; /* Запомнить меня на 3 недели */
  
  public function __construct(){
  	global $config;
    $this->solt = $config['solt_auth'];
	}
  
  function Check(){
    if(isset($_COOKIE['sevalrml']) && isset($_COOKIE['sevalrmp'])){
		$_SESSION['AUTH']['email'] = $_COOKIE['sevalrml'];
		$_SESSION['AUTH']['password'] = $_COOKIE['sevalrmp'];
	}
	if(isset($_SESSION['AUTH']['email']) && isset($_SESSION['AUTH']['password'])){
		$q_email    = Serval::call('db')->quote($_SESSION['AUTH']['email']);
		$q_password = Serval::call('db')->quote($_SESSION['AUTH']['password']);
		if($get = Serval::call('db')->SelectRecord("mod_users","*","email=$q_email AND is_active='yes' AND password=$q_password")){
			unset($get['password']);
			$this->ID = $get['id'];
			$this->Data = $get;
			
			if(isset($_COOKIE['sevalrml']) && isset($_COOKIE['sevalrmp'])){
				@setcookie("sevalrml", $_COOKIE['sevalrml'], time()+$this->RememberTime, "/");
				@setcookie("sevalrmp", $_COOKIE['sevalrmp'], time()+$this->RememberTime, "/");
			}
			return true;
		}
    }
    $this->Logout();
    return false;
	}
	
	function Login(){
    $email   = isset($_POST['email']) ? trim($_POST['email']) : '';
    $password = isset($_POST['password']) ? md5(trim($_POST['password']).$this->solt) : '';
    if(!empty($email) && !empty($password)){ 
      $q_email    = Serval::call('db')->quote($email);
      $q_password = Serval::call('db')->quote($password);
		if($get = Serval::call('db')->SelectRecord("mod_users","","email=$q_email AND is_active='yes' AND password=$q_password")){
    		$this->ID = $get['id'];
	    	
			$_SESSION['AUTH']['email']    = $get['email'];
	    	$_SESSION['AUTH']['password'] = $get['password'];
			
			if(isset($_POST['remember']) && $_POST['remember']=="yes"){
				setcookie("sevalrml", $get['email'], time()+$this->RememberTime, "/");
				setcookie("sevalrmp", $get['password'], time()+$this->RememberTime, "/");
			}
			
			return true;
    	}
    }
    $this->error[] = "E-Mail или пароль указан неверно...";
    return false;
	}
	
	function createUser(){  
    $email    = isset($_POST['email']) ? trim($_POST['email']) : '';
    $password = isset($_POST['password']) ? trim($_POST['password']) : '';
		$password2 = isset($_POST['password2']) ? trim($_POST['password2']) : ''; 	
		if(empty($email)){
			$this->error[] = "Укажите E-Mail";	
		}elseif(empty($password)){
			$this->error[] = "Укажите пароль";	
		}elseif($password!=$password2){
			$this->error[] = "Укажите пароль правильно";	
		}else{
			if( $check = Serval::call('db')->SelectRecord("mod_users","id","email=".Serval::call('db')->Quote($email) ) ){
				$this->error[] = "Пользователь с таким E-Mail уже существует";	
			}else{
				Serval::call('db')->insert("mod_users",array(
					'email'=>$email,
					'password'=>md5($_POST['password'].$this->solt),
					'fio'=>$_POST['fio'],
					'type'=>($_POST['type']=="admin" ? 'admin' : 'user'),
					'is_active'=>'yes',
					'date'=>"SQL_TIME_NOW()"
				));
				return true;
			}
		}
	  return false;
	}
	
	function saveUser(){  
    if($checkUser = Serval::call('db')->SelectRecord("mod_users","id","id=".Serval::call('db')->Quote($_POST['id']))){
			$email    = isset($_POST['email']) ? trim($_POST['email']) : '';
			if($this->Data['type']!="admin"){
				$this->error[] = "У вас нет доступа делать это";
			}elseif(empty($email)){
				$this->error[] = "Укажите E-Mail";
			}elseif($check = Serval::call('db')->SelectRecord("mod_users","id","id!=".Serval::call('db')->Quote($_POST['id'])." AND email=".Serval::call('db')->Quote($email) )){
				$this->error[] = "Пользователь с таким E-Mail уже существует";
			}elseif(!empty($_POST['password']) && $_POST['password']!=$_POST['password2']){
				$this->error[] = "Укажите пароль правильно";	
			}else{
				$row = array(
					'fio'=>clearText($_POST['fio']),
					'email'=>$email,
					'type'=>($_POST['type']=="admin" ? 'admin' : 'user')
				);
				if(!empty($_POST['password'])){
					$row['password'] = md5(trim($_POST['password']).$this->solt);
				}
				Serval::call('db')->update("mod_users",$row,"id='{$checkUser['id']}'");
				return true;
			}
		}else{
			$this->error[] = "Пользователя не существует";
		}
		return false;
	}
	
	function deleteUser(){
		switch($this->Data['type']){
			case 'admin':
				Serval::call('db')->run("DELETE FROM mod_users WHERE id=".Serval::call('db')->Quote($_POST['id']));
				Serval::call('db')->run("DELETE FROM mod_projects2users WHERE users_id=".Serval::call('db')->Quote($_POST['id']));
			return true;
		}
		$this->error[] = "У вас нет доступа делать это";
		return false;
	}
	
	function new_password($key){
		if($get = Serval::call('db')->SelectRecord("mod_users","id,email","renew_key!='' AND renew_key=".Serval::call('db')->Quote($_GET['renew_key']) )){
			$password = generate_password(rand(7,15));
			Serval::call('db')->update("mod_users",array('password'=>md5($password.$this->solt),'renew_key'=>''),"id=".$get['id']);
      $message="
      <html><head></head><body>
        <p>Ваш пароль от {$_SERVER['HTTP_HOST']} изменен.</p>
        <p>
          <b>Для входа используйте:</b><br>
          E-mail: {$get['email']}<br>
          Пароль: {$password}
        </p>
      </body></html>";
			sendEmail($get['email'],"SERVAL: ".$_SERVER["HTTP_HOST"], $message );
			return true;
		}
		return false;
	}
	
	function renewpassword_link(){
		global $config;
		$email  = trim($_POST['email']);
		if($get = Serval::call('db')->SelectRecord("mod_users","id,email","email=".Serval::call('db')->Quote($email))){
			$code = md5($get['id'].$get['email'].time().rand(10,999).$this->solt);
			Serval::call('db')->update("mod_users",array('renew_key'=>$code),"id=".$get['id']);
        $LINK = "http://{$_SERVER["HTTP_HOST"]}".(isset($config['http_dir']) ? $config['http_dir'] : '/')."?renew_key={$code}";
        $message="
        <html><head></head><body>
          <p>Вы или кто-то другой просили прислать пароль от {$_SERVER['HTTP_HOST']}</p>
          <p>Для смены пароля, пожалуйста, пройдите по этой ссылке:
        <br />
        <a href='{$LINK}'>{$LINK}</a></p>
        <p><b>Если Вы не запрашивали пароль, проигнорируйте данное сообщение.</b></p>
        </body></html>";
			
			sendEmail($get['email'],"SERVAL: ".$_SERVER["HTTP_HOST"], $message );
			return true;
		}
		$this->error[] = "E-Mail не найден";
		return false;
	}
	
	function changePassword(){
		$oldPassword = $_POST['oldpassword'];
		$newPassword = $_POST['password'];
		$q_password = Serval::call('db')->quote(md5(trim($oldPassword).$this->solt));
		if(!Serval::call('db')->SelectRecord("mod_users","id","id='".$this->ID."' AND is_active='yes' AND password=$q_password")){
			$this->error[] = "Пароль указан неверно!";
		}elseif($newPassword!=$_POST['password2']){
			$this->error[] = "Пароли не совпадают";
		}else{
			Serval::call('db')->update("mod_users",array(
				'password'=>md5(trim($newPassword).$this->solt),
			),"id='".$this->ID."'");
			$_POST['email'] = $this->Data['email'];
			$_POST['password'] = $newPassword;
			$this->Login();
			return true;
		}
		return false;
	}
	
	function Logout(){
		unset($_SESSION['AUTH']);
		if(isset($_COOKIE['sevalrml']) && isset($_COOKIE['sevalrmp'])){
			setcookie("sevalrml", "", time()+$this->RememberTime, "/");
			setcookie("sevalrmp", "", time()+$this->RememberTime, "/");
		}
		return true;
	}

}
?>