Friendica Communications Platform (please note that this is a clone of the repository at github, issues are handled there) https://friendi.ca
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.

92 lines
2.1KB

  1. <?php
  2. namespace Friendica\Core\Session;
  3. use Friendica\BaseObject;
  4. use Friendica\Core\Logger;
  5. use Friendica\Core\Session;
  6. use Friendica\Database\DBA;
  7. use SessionHandlerInterface;
  8. /**
  9. * SessionHandler using database
  10. *
  11. * @author Hypolite Petovan <hypolite@mrpetovan.com>
  12. */
  13. class DatabaseSessionHandler extends BaseObject implements SessionHandlerInterface
  14. {
  15. public function open($save_path, $session_name)
  16. {
  17. return true;
  18. }
  19. public function read($session_id)
  20. {
  21. if (empty($session_id)) {
  22. return '';
  23. }
  24. $session = DBA::selectFirst('session', ['data'], ['sid' => $session_id]);
  25. if (DBA::isResult($session)) {
  26. Session::$exists = true;
  27. return $session['data'];
  28. }
  29. Logger::log("no data for session $session_id", Logger::TRACE);
  30. return '';
  31. }
  32. /**
  33. * @brief Standard PHP session write callback
  34. *
  35. * This callback updates the DB-stored session data and/or the expiration depending
  36. * on the case. Uses the Session::expire global for existing session, 5 minutes
  37. * for newly created session.
  38. *
  39. * @param string $session_id Session ID with format: [a-z0-9]{26}
  40. * @param string $session_data Serialized session data
  41. * @return boolean Returns false if parameters are missing, true otherwise
  42. */
  43. public function write($session_id, $session_data)
  44. {
  45. if (!$session_id) {
  46. return false;
  47. }
  48. if (!$session_data) {
  49. return true;
  50. }
  51. $expire = time() + Session::$expire;
  52. $default_expire = time() + 300;
  53. if (Session::$exists) {
  54. $fields = ['data' => $session_data, 'expire' => $expire];
  55. $condition = ["`sid` = ? AND (`data` != ? OR `expire` != ?)", $session_id, $session_data, $expire];
  56. DBA::update('session', $fields, $condition);
  57. } else {
  58. $fields = ['sid' => $session_id, 'expire' => $default_expire, 'data' => $session_data];
  59. DBA::insert('session', $fields);
  60. }
  61. return true;
  62. }
  63. public function close()
  64. {
  65. return true;
  66. }
  67. public function destroy($id)
  68. {
  69. DBA::delete('session', ['sid' => $id]);
  70. return true;
  71. }
  72. public function gc($maxlifetime)
  73. {
  74. DBA::delete('session', ["`expire` < ?", time()]);
  75. return true;
  76. }
  77. }