Database = $Database; if(isset($_SESSION)) $this->Restore(); else $this->SetAnonymous(); } function __destroy() { if(isset($_SESSION)) $this->Store(); } function Login($Name, $Password) { $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 Register($Email,$RegUser,$RegPass,$RegPass2) { if ($RegPass != $RegPass2) return -1; $Salt = $this->GetPasswordSalt(); $DbResult = $this->Database->insert('User', array( 'Email' => '"'.$Email.'"', 'Name' => '"'.$RegUser.'"', 'Pass' => $this->CryptPasswordSQL('"'.$RegPass.'"', '"'.$Salt.'"'), 'LastIP' => '"'.$_SERVER['REMOTE_ADDR'].'"', 'Salt' => '"'.$Salt.'"', ) ); return $DbResult; } 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->Name = $User['Name']; $this->Role = LICENCE_USER; $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->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); } } ?>