3 namespace Friendica\Core\Session\Handler;
5 use Friendica\Core\Session;
6 use Friendica\Database\Database as DBA;
7 use Psr\Log\LoggerInterface;
8 use SessionHandlerInterface;
11 * SessionHandler using database
13 * @author Hypolite Petovan <hypolite@mrpetovan.com>
15 final class Database implements SessionHandlerInterface
19 /** @var LoggerInterface */
21 /** @var array The $_SERVER variable */
25 * DatabaseSessionHandler constructor.
28 * @param LoggerInterface $logger
29 * @param array $server
31 public function __construct(DBA $dba, LoggerInterface $logger, array $server)
34 $this->logger = $logger;
35 $this->server = $server;
38 public function open($save_path, $session_name)
43 public function read($session_id)
45 if (empty($session_id)) {
49 $session = $this->dba->selectFirst('session', ['data'], ['sid' => $session_id]);
50 if ($this->dba->isResult($session)) {
51 Session::$exists = true;
52 return $session['data'];
55 $this->logger->notice('no data for session', ['session_id' => $session_id, 'uri' => $this->server['REQUEST_URI'] ?? '']);
61 * Standard PHP session write callback
63 * This callback updates the DB-stored session data and/or the expiration depending
64 * on the case. Uses the Session::expire global for existing session, 5 minutes
65 * for newly created session.
67 * @param string $session_id Session ID with format: [a-z0-9]{26}
68 * @param string $session_data Serialized session data
70 * @return boolean Returns false if parameters are missing, true otherwise
73 public function write($session_id, $session_data)
83 $expire = time() + Session::$expire;
84 $default_expire = time() + 300;
86 if (Session::$exists) {
87 $fields = ['data' => $session_data, 'expire' => $expire];
88 $condition = ["`sid` = ? AND (`data` != ? OR `expire` != ?)", $session_id, $session_data, $expire];
89 $this->dba->update('session', $fields, $condition);
91 $fields = ['sid' => $session_id, 'expire' => $default_expire, 'data' => $session_data];
92 $this->dba->insert('session', $fields);
98 public function close()
103 public function destroy($id)
105 return $this->dba->delete('session', ['sid' => $id]);
108 public function gc($maxlifetime)
110 return $this->dba->delete('session', ["`expire` < ?", time()]);