Session.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. ApplicationSettings::RegisterDefaultSetting("session", "expiry_window", "604800"); //a week
  3. class Session extends DBObject {
  4. private static $_instance,$_user;
  5. public function __construct($id=0) {
  6. parent::__construct("sessions", "session_id", $id);
  7. }
  8. public function Save() {
  9. if ($this->SessionId==null)
  10. $this->SessionId=Utils::GenerateRandomString(32);
  11. $expiryWindow=(int)ApplicationSettings::GetSetting("session", "expiry_window");
  12. $this->SessionExpiry=time()+$expiryWindow;
  13. setcookie("session_id",$this->SessionId,$this->SessionExpiry,'/');
  14. parent::Save();
  15. }
  16. public function HasExpired(){
  17. return $this->SessionExpiry<time();
  18. }
  19. private static function Instantiate(){
  20. if (self::$_instance!=null)
  21. return;
  22. $instance=null;
  23. if (isset($_COOKIE['session_id'])){
  24. $instance=new Session($_COOKIE['session_id']);
  25. if ($instance->HasExpired())
  26. $instance=new Session();
  27. } else
  28. $instance=new Session();
  29. self::$_instance=$instance;
  30. }
  31. public static function Destroy(){
  32. self::Instantiate();
  33. $PDO=BaseRepository::GetPDO();
  34. $prep=$PDO->prepare("DELETE FROM sessions WHERE session_id=?");
  35. $prep->execute(array(self::$_instance->SessionId));
  36. self::$_instance=null;
  37. }
  38. public static function IsUserLoggedIn() {
  39. self::Instantiate();
  40. $user=self::GetLoggedInUser();
  41. return $user->UserId!=null;
  42. }
  43. public static function GetLoggedInUser() {
  44. self::Instantiate();
  45. if (isset(self::$_user))
  46. return self::$_user;
  47. self::$_user=new User(self::$_instance->UserId);
  48. return self::$_user;
  49. }
  50. public static function SetLoggedInUser($user) {
  51. self::Instantiate();
  52. self::$_instance->UserId=$user->UserId;
  53. self::$_instance->Save();
  54. }
  55. }