KXStudio Website https://kx.studio/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

96 lines
2.8KB

  1. <?php
  2. /**
  3. * Class: Session
  4. * Handles their session.
  5. */
  6. class Session {
  7. # Variable: $data
  8. # Caches session data.
  9. static $data = "";
  10. /**
  11. * Function: open
  12. * Returns: @true@
  13. */
  14. static function open() {
  15. return true;
  16. }
  17. /**
  18. * Function: close
  19. * Returns: @true@
  20. */
  21. static function close() {
  22. return true;
  23. }
  24. /**
  25. * Function: read
  26. * Reads their session from the database.
  27. *
  28. * Parameters:
  29. * $id - Session ID.
  30. */
  31. static function read($id) {
  32. self::$data = SQL::current()->select("sessions",
  33. "data",
  34. array("id" => $id),
  35. "id")->fetchColumn();
  36. return fallback(self::$data, "");
  37. }
  38. /**
  39. * Function: write
  40. * Writes their session to the database, or updates it if it already exists.
  41. *
  42. * Parameters:
  43. * $id - Session ID.
  44. * $data - Data to write.
  45. */
  46. static function write($id, $data) {
  47. if (empty($data) or $data == self::$data)
  48. return;
  49. $sql = SQL::current();
  50. if ($sql->count("sessions", array("id" => $id)))
  51. $sql->update("sessions",
  52. array("id" => $id),
  53. array("data" => $data,
  54. "user_id" => Visitor::current()->id,
  55. "updated_at" => datetime()));
  56. else
  57. $sql->insert("sessions",
  58. array("id" => $id,
  59. "data" => $data,
  60. "user_id" => Visitor::current()->id,
  61. "created_at" => datetime()));
  62. }
  63. /**
  64. * Function: destroy
  65. * Destroys their session.
  66. *
  67. * Parameters:
  68. * $id - Session ID.
  69. */
  70. static function destroy($id) {
  71. if (SQL::current()->delete("sessions", array("id" => $id)))
  72. return true;
  73. return false;
  74. }
  75. /**
  76. * Function: gc
  77. * Garbage collector. Removes sessions older than 30 days and sessions with no stored data.
  78. */
  79. static function gc() {
  80. SQL::current()->delete("sessions",
  81. "created_at >= :thirty_days OR data = '' OR data IS NULL",
  82. array(":thirty_days" => datetime(strtotime("+30 days"))));
  83. return true;
  84. }
  85. }