3 namespace Friendica\Core\Session;
5 use Friendica\Core\Config\Configuration;
6 use Friendica\Core\Session;
7 use Friendica\Database\Database as DBA;
8 use Friendica\Model\User\Cookie;
9 use Psr\Log\LoggerInterface;
10 use SessionHandlerInterface;
13 * SessionHandler using database
15 * @author Hypolite Petovan <hypolite@mrpetovan.com>
17 final class Database extends Native implements SessionHandlerInterface
21 /** @var LoggerInterface */
23 /** @var array The $_SERVER variable */
27 * DatabaseSessionHandler constructor.
29 * @param Database $dba
30 * @param LoggerInterface $logger
31 * @param array $server
33 public function __construct(Configuration $config, Cookie $cookie, DBA $dba, LoggerInterface $logger, array $server)
35 parent::__construct($config, $cookie);
38 $this->logger = $logger;
39 $this->server = $server;
41 session_set_save_handler($this);
44 public function open($save_path, $session_name)
49 public function read($session_id)
51 if (empty($session_id)) {
55 $session = $this->dba->selectFirst('session', ['data'], ['sid' => $session_id]);
56 if ($this->dba->isResult($session)) {
57 Session::$exists = true;
58 return $session['data'];
61 $this->logger->notice('no data for session', ['session_id' => $session_id, 'uri' => $this->server['REQUEST_URI'] ?? '']);
67 * @brief Standard PHP session write callback
69 * This callback updates the DB-stored session data and/or the expiration depending
70 * on the case. Uses the Session::expire global for existing session, 5 minutes
71 * for newly created session.
73 * @param string $session_id Session ID with format: [a-z0-9]{26}
74 * @param string $session_data Serialized session data
76 * @return boolean Returns false if parameters are missing, true otherwise
79 public function write($session_id, $session_data)
89 $expire = time() + Session::$expire;
90 $default_expire = time() + 300;
92 if (Session::$exists) {
93 $fields = ['data' => $session_data, 'expire' => $expire];
94 $condition = ["`sid` = ? AND (`data` != ? OR `expire` != ?)", $session_id, $session_data, $expire];
95 $this->dba->update('session', $fields, $condition);
97 $fields = ['sid' => $session_id, 'expire' => $default_expire, 'data' => $session_data];
98 $this->dba->insert('session', $fields);
104 public function close()
109 public function destroy($id)
111 return $this->dba->delete('session', ['sid' => $id]);
114 public function gc($maxlifetime)
116 return $this->dba->delete('session', ["`expire` < ?", time()]);