<?php

//class User
//last change 19.6.2012

// User licence levels
define('LICENCE_ANONYMOUS', -1);
define('LICENCE_USER', 0);
define('LICENCE_MODERATOR', 1);
define('LICENCE_ADMIN', 2);

class User
{
  var $Id;
  var $Name;
  var $Team;
  var $Role;
  var $Database;
  
  function __construct($Database)
  {
	$this->Database =  $Database;
    if(isset($_SESSION)) $this->Restore();    
      else $this->SetAnonymous();
  }
  
  function __destroy()
  {
    if(isset($_SESSION)) $this->Store();
  }
  
  function Login($Name, $Password)
  {
	  ECHO 'TES';
    $DbResult = $this->Database->query('SELECT `ID` FROM `User` WHERE LOWER(`Name`) = LOWER("'.$Name.'") AND `Pass` = '.$this->CryptPasswordSQL('"'.$Password.'"', '`Salt`'));
    if($DbResult->num_rows > 0)
    {
      $User = $DbResult->fetch_assoc();
      $this->Id = $User['ID'];      
      $this->Load();
   //TODO:   WriteLog('Login: '.$Name, LOG_TYPE_USER);
      $this->UpdateState();
    } else $ŧhis->Role = LICENCE_ANONYMOUS;
  }
  
  function Logout()
  {
    if($this->Role != LICENCE_ANONYMOUS)
      $this->Database->query('UPDATE `User` SET `LastLogout` = NOW() WHERE `ID` = '.$this->Id);
    $this->SetAnonymous();
  }
  
  function Load()
  {
    $DbResult = $this->Database->query('SELECT * FROM `User` WHERE `ID` = '.$this->Id);
    $User = $DbResult->fetch_assoc();
    // Security: Password and Salt hash should not be loaded to variables
    $this->Id = $User['ID'];
    $this->Team = $User['Team'];
    $this->Name = $User['Name'];
    $this->Role = $User['GM'];
    $this->Email = $User['Email'];
  }
  
  function Restore()
  {
    if(array_key_exists('UserId', $_SESSION))
    {
      $this->Id = $_SESSION['UserId'];
      if($this->Id != 0)
      {
        $this->Load();
        $this->UpdateState();
      } else $this->SetAnonymous();
    } else $this->SetAnonymous();
  }
  
  protected function Store()
  {
    $_SESSION['UserId'] = $this->Id;
  }
  
  protected function SetAnonymous()
  {
    $this->Id = 0;
    $this->Name = 'anonymous';
    $this->Role = LICENCE_ANONYMOUS;
    $this->Language = 1;
    $this->Redirecting = 1; 
    $this->Team = 0;
    $this->Email = '';
  }
  
  function Licence($Licence)
  {
    if(!isset($_SERVER['REMOTE_ADDR'])) return(true); // Execution from command line
    else return($this->Role >= $Licence);    
  }

  protected function GetPasswordSalt()
  {
    return(substr(sha1(mt_rand()), 0, 8));
  }
  
  protected function CryptPasswordSQL($Password, $Salt)
  {
    return('sha1(CONCAT(sha1('.$Password.'), '.$Salt.'))');
  } 
  
  function UpdateState()
  {
    if(array_key_exists('REMOTE_ADDR', $_SERVER)) 
      $this->Database->query('UPDATE `User` SET `LastIP` = "'.$_SERVER['REMOTE_ADDR'].'", `LastLogin` = NOW() WHERE `ID` = '.$this->Id);
  }
}

?>
