3 * @copyright Copyright (C) 2010-2022, the Friendica project
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\Cache\Capability\ICanCache;
25 use Friendica\Core\Cache\Exception\CachePersistenceException;
26 use Friendica\Core\Session;
27 use Psr\Log\LoggerInterface;
28 use SessionHandlerInterface;
31 * SessionHandler using Friendica Cache
33 class Cache implements SessionHandlerInterface
37 /** @var LoggerInterface */
40 public function __construct(ICanCache $cache, LoggerInterface $logger)
42 $this->cache = $cache;
43 $this->logger = $logger;
46 public function open($path, $name): bool
51 public function read($id)
58 $data = $this->cache->get('session:' . $id);
60 Session::$exists = true;
63 } catch (CachePersistenceException $exception) {
64 $this->logger->warning('Cannot read session.'. ['id' => $id, 'exception' => $exception]);
72 * Standard PHP session write callback
74 * This callback updates the stored session data and/or the expiration depending
75 * on the case. Uses the Session::expire for existing session, 5 minutes
76 * for newly created session.
78 * @param string $id Session ID with format: [a-z0-9]{26}
79 * @param string $data Serialized session data
81 * @return bool Returns false if parameters are missing, true otherwise
83 public function write($id, $data): bool
90 return $this->destroy($id);
94 return $this->cache->set('session:' . $id, $data, Session::$expire);
95 } catch (CachePersistenceException $exception) {
96 $this->logger->warning('Cannot write session', ['id' => $id, 'exception' => $exception]);
101 public function close(): bool
106 public function destroy($id): bool
109 return $this->cache->delete('session:' . $id);
110 } catch (CachePersistenceException $exception) {
111 $this->logger->warning('Cannot destroy session', ['id' => $id, 'exception' => $exception]);
116 public function gc($max_lifetime): bool