session.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. <?php
  2. require_once 'database.php';
  3. class Session {
  4. public static function is_valid ()
  5. {
  6. return isset ($_SESSION) && !is_null ($_SESSION) && !empty ($_SESSION);
  7. }
  8. public static function get_user ()
  9. {
  10. if (self::is_valid ())
  11. return $_SESSION['user'];
  12. else
  13. return NULL;
  14. }
  15. public static function get_username ()
  16. {
  17. if (self::is_valid ())
  18. return $_SESSION['user']['name'];
  19. else
  20. return '';
  21. }
  22. public static function get_userid ()
  23. {
  24. if (self::is_valid ())
  25. return $_SESSION['user']['id'];
  26. else
  27. return '';
  28. }
  29. /**
  30. * Set user information to the session
  31. *
  32. * @param user Associative array of user properties
  33. */
  34. public static function set ($user)
  35. {
  36. if (is_null ($user) || empty ($user))
  37. return;
  38. // Set session variable
  39. $_SESSION = array (
  40. 'user' => array (
  41. 'id' => $user['id'],
  42. 'hash_id' => $user['hashId'],
  43. 'email' => $user['email'],
  44. 'email_notifications' => $user['email_notifications'],
  45. 'registered' => $user['registered'],
  46. 'name' => $user['username'],
  47. 'about' => $user['about']));
  48. }
  49. /**
  50. * Set user information to the session.
  51. * This is like "set ($user)", but instead of $user we are given
  52. * a single property.
  53. */
  54. public static function set_property ($property, $value)
  55. {
  56. $_SESSION['user'][$property] = $value;
  57. }
  58. // Retrieve session from cookie
  59. public static function remember_me ()
  60. {
  61. // We already have a session, nothing to do here
  62. if (Session::is_valid ())
  63. return;
  64. // Check if user does not have a "remember_me" cookie
  65. if (!isset ($_COOKIE['remember_me']))
  66. return;
  67. // Validate token
  68. $db = new Database ();
  69. $db->connect ();
  70. $user = $db->get_remember_me ($_COOKIE['remember_me']);
  71. self::set ($user);
  72. }
  73. public static function delete ()
  74. {
  75. unset ($_SESSION);
  76. session_destroy ();
  77. // Delete session
  78. $_SESSION = NULL;
  79. }
  80. }
  81. session_name ('freepost');
  82. session_start ();
  83. /* Once the session is started, check for "remember_me" tokens.
  84. * If the session is already set, this function doesn't do anything.
  85. * If session is not set, and a valid token is set on user's cookies,
  86. * than the user is retrieved.
  87. */
  88. Session::remember_me ();