3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Core\Session\Handler;
24 use Friendica\Core\Session;
25 use Friendica\Database\Database as DBA;
26 use Psr\Log\LoggerInterface;
27 use SessionHandlerInterface;
30 * SessionHandler using database
32 class Database implements SessionHandlerInterface
36 /** @var LoggerInterface */
38 /** @var array The $_SERVER variable */
42 * DatabaseSessionHandler constructor.
45 * @param LoggerInterface $logger
46 * @param array $server
48 public function __construct(DBA $dba, LoggerInterface $logger, array $server)
51 $this->logger = $logger;
52 $this->server = $server;
55 public function open($save_path, $session_name)
60 public function read($session_id)
62 if (empty($session_id)) {
66 $session = $this->dba->selectFirst('session', ['data'], ['sid' => $session_id]);
67 if ($this->dba->isResult($session)) {
68 Session::$exists = true;
69 return $session['data'];
72 $this->logger->notice('no data for session', ['session_id' => $session_id, 'uri' => $this->server['REQUEST_URI'] ?? '']);
78 * Standard PHP session write callback
80 * This callback updates the DB-stored session data and/or the expiration depending
81 * on the case. Uses the Session::expire global for existing session, 5 minutes
82 * for newly created session.
84 * @param string $session_id Session ID with format: [a-z0-9]{26}
85 * @param string $session_data Serialized session data
87 * @return boolean Returns false if parameters are missing, true otherwise
90 public function write($session_id, $session_data)
100 $expire = time() + Session::$expire;
101 $default_expire = time() + 300;
103 if (Session::$exists) {
104 $fields = ['data' => $session_data, 'expire' => $expire];
105 $condition = ["`sid` = ? AND (`data` != ? OR `expire` != ?)", $session_id, $session_data, $expire];
106 $this->dba->update('session', $fields, $condition);
108 $fields = ['sid' => $session_id, 'expire' => $default_expire, 'data' => $session_data];
109 $this->dba->insert('session', $fields);
115 public function close()
120 public function destroy($id)
122 return $this->dba->delete('session', ['sid' => $id]);
125 public function gc($maxlifetime)
127 return $this->dba->delete('session', ["`expire` < ?", time()]);