New code (optimizations/simplifications):
class Users {
private static $key, $table, $logtable;
public static function init($key) {
self::$key = $key;
self::$table = DBPREFIX.$key.'s';
self::$logtable = self::$table.'_access_log';
}
public static function isLogged() {
if(isset($_SESSION[self::$key]) and isset($_SESSION[self::$key]['uid'])) { # Combined ifs
$uid = intval($_SESSION[self::$key]['uid']);
$user = DB::select()->from(self::$table)->where('id', '=', $uid)->execute()->object();
return count($user) > 0; # Simplified
}
return false; # Removed unnecesary elses
}
public static function userExist($login) {
$user = DB::select()->from(self::$table)->where('login', '=', $login)->execute()->object();
return count($user) > 0; # Simplified
}
public static function getUser($login) {
$user = DB::select()->from(self::$table)->where('login', '=', $login)->execute()->object();
if(count($user) > 0) {
return $user[0];
}
return false; # Removed unnecessary else
}
public static function generateHash($password) {
$salt = self::generateSalt();
$hashedPassword = crypt($password, $salt);
return array('hashed_password' => $hashedPassword, 'salt' => $salt);
}
private static function generateSalt($blowfishPre = '$2y$10$', $blowfishEnd = '$', $allowedChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789./', $saltLength = 20) { # Added arguments for future customization
$charsLength = strlen($allowedChars);
$salt = "";
for($i=0; $i < $saltLength; $i++)
{
$salt .= $allowedChars[mt_rand(0,$charsLength)];
}
return $blowfishPre . $salt . $blowfishEnd; # Removed unnecessary variable
}
public static function comparePasswords($input, $uid) {
$user = DB::select()->from(self::$table)->where('id', '=', $uid)->execute()->object();
if(count($user) > 0) {
$user = $user[0];
$password = $user->password;
return crypt($input, $password) === $password;
}
return false; # Removed unnecessary else
}
public static function userExit() {
if(isset($_SESSION[self::$key])) {
unset($_SESSION[self::$key]);
}
}
public static function changePassword($password, $uid) {
$newPassword = self::generateHash($password);
if(isset($newPassword['hashed_password']) && isset($newPassword['salt'])) {
DB::update(self::$table)->set(array('password' => $newPassword['hashed_password'], 'salt' => $newPassword['salt']))->where('id', '=', $uid)->execute();
}
}
public static function updateTime($uid) {
DB::update(self::$table)->set(array('last_login' => time()))->where('id', '=', $uid)->execute();
}
public static function writeAccessLog($uid, $success) {
DB::insert(self::$logtable)->set(array('admin_id' => $uid, 'date' => time(), 'success' => $success ? '1' : '0'))->execute(); # Inlined success var.
}
}