session.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. namespace Model;
  3. class Session extends \Model {
  4. protected
  5. $_table_name = "session",
  6. $cookie_name = "phproj_token";
  7. /**
  8. * Create a new session
  9. * @param int $user_id
  10. * @param bool $auto_save
  11. */
  12. public function __construct($user_id = null, $auto_save = true) {
  13. // Run model constructor
  14. parent::__construct();
  15. if($user_id !== null) {
  16. $this->user_id = $user_id;
  17. $this->token = \Helper\Security::instance()->salt_sha2();
  18. $this->created = date("Y-m-d H:i:s");
  19. if($auto_save) {
  20. $this->save();
  21. }
  22. }
  23. }
  24. /**
  25. * Load the current session
  26. * @return Session
  27. */
  28. public function loadCurrent() {
  29. $f3 = \Base::instance();
  30. $token = $f3->get("COOKIE.{$this->cookie_name}");
  31. if($token) {
  32. $this->load(array("token = ?", $token));
  33. $expire = $f3->get("JAR.expire");
  34. if(time() - $expire > strtotime($this->created)) {
  35. $this->delete();
  36. }
  37. }
  38. return $this;
  39. }
  40. /**
  41. * Set the user's cookie to the current session
  42. * @return Session
  43. */
  44. public function setCurrent() {
  45. $f3 = \Base::instance();
  46. $f3->set("COOKIE.{$this->cookie_name}", $this->token, $f3->get("JAR.expire"));
  47. return $this;
  48. }
  49. /**
  50. * Delete the session
  51. * @return Session
  52. */
  53. public function delete() {
  54. // Empty the session cookie if it matches the current token
  55. $f3 = \Base::instance();
  56. if($this->token = $f3->get("COOKIE.{$this->cookie_name}")) {
  57. $f3->set("COOKIE.{$this->cookie_name}", "");
  58. }
  59. // Delete the session row
  60. parent::delete();
  61. return $this;
  62. }
  63. }