]> git.mxchange.org Git - friendica.git/commitdiff
Add Session Management instances (including Depenency Injection)
authornupplaPhil <admin@philipp.info>
Mon, 9 Dec 2019 23:44:56 +0000 (00:44 +0100)
committernupplaPhil <admin@philipp.info>
Mon, 9 Dec 2019 23:44:56 +0000 (00:44 +0100)
- Prerequesite for mocking Sessions
- Reduce "App" class complexity

12 files changed:
src/App.php
src/App/Authentication.php
src/Core/Session.php
src/Core/Session/CacheSession.php [new file with mode: 0644]
src/Core/Session/CacheSessionHandler.php [deleted file]
src/Core/Session/DatabaseSession.php [new file with mode: 0644]
src/Core/Session/DatabaseSessionHandler.php [deleted file]
src/Core/Session/ISession.php [new file with mode: 0644]
src/Core/Session/MemorySession.php [new file with mode: 0644]
src/Core/Session/NativeSession.php [new file with mode: 0644]
src/Factory/SessionFactory.php [new file with mode: 0644]
static/dependencies.config.php

index 7a52139d6a4176f624291272dfc9f36ef1a6bacb..eed91769fd9f6b23099f47438ecd714da36a9e10 100644 (file)
@@ -670,15 +670,11 @@ class App
                                        System::externalRedirect($this->baseURL->get() . '/' . $this->args->getQueryString());
                                }
 
-                               Core\Session::init();
                                Core\Hook::callAll('init_1');
                        }
 
                        // Exclude the backend processes from the session management
                        if (!$this->mode->isBackend()) {
-                               $stamp1 = microtime(true);
-                               session_start();
-                               $this->profiler->saveTimestamp($stamp1, 'parser', Core\System::callstack());
                                $this->l10n->setSessionVariable();
                                $this->l10n->setLangFromSession();
                        } else {
index bf62cf8a4f5b0bdd12aa9c836a9dbedb8246cb30..5da0f875b4dc6ecfd747ff1e690c90629fe95f46 100644 (file)
@@ -41,6 +41,8 @@ class Authentication
        private $logger;
        /** @var User\Cookie */
        private $cookie;
+       /** @var Session\ISession */
+       private $session;
 
        /**
         * Authentication constructor.
@@ -51,8 +53,9 @@ class Authentication
         * @param Database        $dba
         * @param LoggerInterface $logger
         * @param User\Cookie     $cookie
+        * @param Session\ISession $session
         */
-       public function __construct(Configuration $config, App\BaseURL $baseUrl, L10n $l10n, Database $dba, LoggerInterface $logger, User\Cookie $cookie)
+       public function __construct(Configuration $config, App\BaseURL $baseUrl, L10n $l10n, Database $dba, LoggerInterface $logger, User\Cookie $cookie, Session\ISession $session)
        {
                $this->config  = $config;
                $this->baseUrl = $baseUrl;
@@ -60,6 +63,7 @@ class Authentication
                $this->dba     = $dba;
                $this->logger  = $logger;
                $this->cookie = $cookie;
+               $this->session = $session;
        }
 
        /**
@@ -88,12 +92,12 @@ class Authentication
                                        'verified'        => true,
                                ]
                        );
-                       if (DBA::isResult($user)) {
+                       if ($this->dba->isResult($user)) {
                                if (!$this->cookie->check($data->hash,
                                        $user['password'] ?? '',
                                        $user['prvKey'] ?? '')) {
                                        $this->logger->notice("Hash doesn't fit.", ['user' => $data->uid]);
-                                       Session::delete();
+                                       $this->session->delete();
                                        $this->baseUrl->redirect();
                                }
 
@@ -101,34 +105,34 @@ class Authentication
                                $this->cookie->set($user['uid'], $user['password'], $user['prvKey']);
 
                                // Do the authentification if not done by now
-                               if (!Session::get('authenticated')) {
+                               if (!$this->session->get('authenticated')) {
                                        $this->setForUser($a, $user);
 
                                        if ($this->config->get('system', 'paranoia')) {
-                                               Session::set('addr', $data->ip);
+                                               $this->session->set('addr', $data->ip);
                                        }
                                }
                        }
                }
 
-               if (Session::get('authenticated')) {
-                       if (Session::get('visitor_id') && !Session::get('uid')) {
-                               $contact = $this->dba->selectFirst('contact', [], ['id' => Session::get('visitor_id')]);
+               if ($this->session->get('authenticated')) {
+                       if ($this->session->get('visitor_id') && !$this->session->get('uid')) {
+                               $contact = $this->dba->selectFirst('contact', [], ['id' => $this->session->get('visitor_id')]);
                                if ($this->dba->isResult($contact)) {
                                        $a->contact = $contact;
                                }
                        }
 
-                       if (Session::get('uid')) {
+                       if ($this->session->get('uid')) {
                                // already logged in user returning
                                $check = $this->config->get('system', 'paranoia');
                                // extra paranoia - if the IP changed, log them out
-                               if ($check && (Session::get('addr') != $_SERVER['REMOTE_ADDR'])) {
+                               if ($check && ($this->session->get('addr') != $_SERVER['REMOTE_ADDR'])) {
                                        $this->logger->notice('Session address changed. Paranoid setting in effect, blocking session. ', [
-                                                       'addr'        => Session::get('addr'),
+                                                       'addr'        => $this->session->get('addr'),
                                                        'remote_addr' => $_SERVER['REMOTE_ADDR']]
                                        );
-                                       Session::delete();
+                                       $this->session->delete();
                                        $this->baseUrl->redirect();
                                }
 
@@ -136,7 +140,7 @@ class Authentication
                                        'user',
                                        [],
                                        [
-                                               'uid'             => Session::get('uid'),
+                                               'uid'             => $this->session->get('uid'),
                                                'blocked'         => false,
                                                'account_expired' => false,
                                                'account_removed' => false,
@@ -144,18 +148,18 @@ class Authentication
                                        ]
                                );
                                if (!$this->dba->isResult($user)) {
-                                       Session::delete();
+                                       $this->session->delete();
                                        $this->baseUrl->redirect();
                                }
 
                                // Make sure to refresh the last login time for the user if the user
                                // stays logged in for a long time, e.g. with "Remember Me"
                                $login_refresh = false;
-                               if (!Session::get('last_login_date')) {
-                                       Session::set('last_login_date', DateTimeFormat::utcNow());
+                               if (!$this->session->get('last_login_date')) {
+                                       $this->session->set('last_login_date', DateTimeFormat::utcNow());
                                }
-                               if (strcmp(DateTimeFormat::utc('now - 12 hours'), Session::get('last_login_date')) > 0) {
-                                       Session::set('last_login_date', DateTimeFormat::utcNow());
+                               if (strcmp(DateTimeFormat::utc('now - 12 hours'), $this->session->get('last_login_date')) > 0) {
+                                       $this->session->set('last_login_date', DateTimeFormat::utcNow());
                                        $login_refresh = true;
                                }
 
@@ -186,8 +190,8 @@ class Authentication
                try {
                        $openid           = new LightOpenID($this->baseUrl->getHostname());
                        $openid->identity = $openid_url;
-                       Session::set('openid', $openid_url);
-                       Session::set('remember', $remember);
+                       $this->session->set('openid', $openid_url);
+                       $this->session->set('remember', $remember);
                        $openid->returnUrl = $this->baseUrl->get(true) . '/openid';
                        $openid->optional  = ['namePerson/friendly', 'contact/email', 'namePerson', 'namePerson/first', 'media/image/aspect11', 'media/image/default'];
                        System::externalRedirect($openid->authUrl());
@@ -250,11 +254,11 @@ class Authentication
                }
 
                // if we haven't failed up this point, log them in.
-               Session::set('remember', $remember);
-               Session::set('last_login_date', DateTimeFormat::utcNow());
+               $this->session->set('remember', $remember);
+               $this->session->set('last_login_date', DateTimeFormat::utcNow());
 
-               $openid_identity = Session::get('openid_identity');
-               $openid_server   = Session::get('openid_server');
+               $openid_identity = $this->session->get('openid_identity');
+               $openid_server   = $this->session->get('openid_server');
 
                if (!empty($openid_identity) || !empty($openid_server)) {
                        $this->dba->update('user', ['openid' => $openid_identity, 'openidserver' => $openid_server], ['uid' => $record['uid']]);
@@ -262,8 +266,8 @@ class Authentication
 
                $this->setForUser($a, $record, true, true);
 
-               $return_path = Session::get('return_path', '');
-               Session::remove('return_path');
+               $return_path = $this->session->get('return_path', '');
+               $this->session->remove('return_path');
 
                $this->baseUrl->redirect($return_path);
        }
@@ -282,7 +286,7 @@ class Authentication
         */
        public function setForUser(App $a, array $user_record, bool $login_initial = false, bool $interactive = false, bool $login_refresh = false)
        {
-               Session::setMultiple([
+               $this->session->setMultiple([
                        'uid'           => $user_record['uid'],
                        'theme'         => $user_record['theme'],
                        'mobile-theme'  => PConfig::get($user_record['uid'], 'system', 'mobile_theme'),
@@ -296,7 +300,7 @@ class Authentication
                Session::setVisitorsContacts();
 
                $member_since = strtotime($user_record['register_date']);
-               Session::set('new_member', time() < ($member_since + (60 * 60 * 24 * 14)));
+               $this->session->set('new_member', time() < ($member_since + (60 * 60 * 24 * 14)));
 
                if (strlen($user_record['timezone'])) {
                        date_default_timezone_set($user_record['timezone']);
@@ -305,8 +309,8 @@ class Authentication
 
                $masterUid = $user_record['uid'];
 
-               if (Session::get('submanage')) {
-                       $user = $this->dba->selectFirst('user', ['uid'], ['uid' => Session::get('submanage')]);
+               if ($this->session->get('submanage')) {
+                       $user = $this->dba->selectFirst('user', ['uid'], ['uid' => $this->session->get('submanage')]);
                        if ($this->dba->isResult($user)) {
                                $masterUid = $user['uid'];
                        }
@@ -326,7 +330,7 @@ class Authentication
                if ($this->dba->isResult($contact)) {
                        $a->contact = $contact;
                        $a->cid     = $contact['id'];
-                       Session::set('cid', $a->cid);
+                       $this->session->set('cid', $a->cid);
                }
 
                header('X-Account-Management-Status: active; name="' . $user_record['username'] . '"; id="' . $user_record['nickname'] . '"');
@@ -346,10 +350,10 @@ class Authentication
                         * The cookie will be renewed automatically.
                         * The week ensures that sessions will expire after some inactivity.
                         */;
-                       if (Session::get('remember')) {
+                       if ($this->session->get('remember')) {
                                $a->getLogger()->info('Injecting cookie for remembered user ' . $user_record['nickname']);
                                $this->cookie->set($user_record['uid'], $user_record['password'], $user_record['prvKey']);
-                               Session::remove('remember');
+                               $this->session->remove('remember');
                        }
                }
 
@@ -370,8 +374,8 @@ class Authentication
                if ($login_initial) {
                        Hook::callAll('logged_in', $a->user);
 
-                       if ($a->module !== 'home' && Session::exists('return_path')) {
-                               $this->baseUrl->redirect(Session::get('return_path'));
+                       if ($a->module !== 'home' && $this->session->exists('return_path')) {
+                               $this->baseUrl->redirect($this->session->get('return_path'));
                        }
                }
        }
@@ -395,7 +399,7 @@ class Authentication
                }
 
                // Case 1: 2FA session present and valid: return
-               if (Session::get('2fa')) {
+               if ($this->session->get('2fa')) {
                        return;
                }
 
index 140781d1c644e659107803f1e71e4f0754eb6755..ef26cd929edc1dfd69f73b1f7f7004c8d6ee470e 100644 (file)
  */
 namespace Friendica\Core;
 
-use Friendica\App;
 use Friendica\BaseObject;
-use Friendica\Core\Cache\ICache;
-use Friendica\Core\Session\CacheSessionHandler;
-use Friendica\Core\Session\DatabaseSessionHandler;
-use Friendica\Database\Database;
+use Friendica\Core\Session\ISession;
 use Friendica\Database\DBA;
 use Friendica\Model\Contact;
-use Friendica\Model\User;
 use Friendica\Util\Strings;
-use Psr\Log\LoggerInterface;
 
 /**
  * High-level Session service class
  *
  * @author Hypolite Petovan <hypolite@mrpetovan.com>
  */
-class Session
+class Session extends BaseObject
 {
        public static $exists = false;
        public static $expire = 180000;
 
-       public static function init()
-       {
-               ini_set('session.gc_probability', 50);
-               ini_set('session.use_only_cookies', 1);
-               ini_set('session.cookie_httponly', 1);
-
-               if (Config::get('system', 'ssl_policy') == App\BaseURL::SSL_POLICY_FULL) {
-                       ini_set('session.cookie_secure', 1);
-               }
-
-               $session_handler = Config::get('system', 'session_handler', 'database');
-               if ($session_handler != 'native') {
-                       if ($session_handler == 'cache' && Config::get('system', 'cache_driver', 'database') != 'database') {
-                               $SessionHandler = new CacheSessionHandler(
-                                       BaseObject::getClass(ICache::class),
-                                       BaseObject::getClass(LoggerInterface::class),
-                                       $_SERVER
-                               );
-                       } else {
-                               $SessionHandler = new DatabaseSessionHandler(
-                                       BaseObject::getClass(Database::class),
-                                       BaseObject::getClass(LoggerInterface::class),
-                                       $_SERVER
-                               );
-                       }
-
-                       session_set_save_handler($SessionHandler);
-               }
-       }
-
        public static function exists($name)
        {
-               return isset($_SESSION[$name]);
+               return self::getClass(ISession::class)->exists($name);
        }
 
-       /**
-        * Retrieves a key from the session super global or the defaults if the key is missing or the value is falsy.
-        *
-        * Handle the case where session_start() hasn't been called and the super global isn't available.
-        *
-        * @param string $name
-        * @param mixed $defaults
-        * @return mixed
-        */
        public static function get($name, $defaults = null)
        {
-               return $_SESSION[$name] ?? $defaults;
+               return self::getClass(ISession::class)->get($name, $defaults);
        }
 
-       /**
-        * Sets a single session variable.
-        * Overrides value of existing key.
-        *
-        * @param string $name
-        * @param mixed $value
-        */
        public static function set($name, $value)
        {
-               $_SESSION[$name] = $value;
+               self::getClass(ISession::class)->set($name, $value);
        }
 
-       /**
-        * Sets multiple session variables.
-        * Overrides values for existing keys.
-        *
-        * @param array $values
-        */
        public static function setMultiple(array $values)
        {
-               $_SESSION = $values + $_SESSION;
+               self::getClass(ISession::class)->setMultiple($values);
        }
 
-       /**
-        * Removes a session variable.
-        * Ignores missing keys.
-        *
-        * @param $name
-        */
        public static function remove($name)
        {
-               unset($_SESSION[$name]);
+               self::getClass(ISession::class)->remove($name);
        }
 
-       /**
-        * Clears the current session array
-        */
        public static function clear()
        {
-               session_unset();
-               session_start();
-               $_SESSION = [];
+               self::getClass(ISession::class)->clear();
        }
 
        /**
@@ -184,16 +115,8 @@ class Session
                return $_SESSION['authenticated'];
        }
 
-       /**
-        * @brief Kills the "Friendica" cookie and all session data
-        */
        public static function delete()
        {
-               /** @var User\Cookie $cookie */
-               $cookie = BaseObject::getClass(User\Cookie::class);
-               $cookie->clear();
-               $_SESSION = [];
-               session_unset();
-               session_destroy();
+               self::getClass(ISession::class)->delete();
        }
 }
diff --git a/src/Core/Session/CacheSession.php b/src/Core/Session/CacheSession.php
new file mode 100644 (file)
index 0000000..fdf9aa6
--- /dev/null
@@ -0,0 +1,99 @@
+<?php
+
+namespace Friendica\Core\Session;
+
+use Friendica\Core\Cache\ICache;
+use Friendica\Core\Config\Configuration;
+use Friendica\Core\Session;
+use Friendica\Model\User\Cookie;
+use Psr\Log\LoggerInterface;
+use SessionHandlerInterface;
+
+/**
+ * SessionHandler using Friendica Cache
+ *
+ * @author Hypolite Petovan <hypolite@mrpetovan.com>
+ */
+final class CacheSession extends NativeSession implements SessionHandlerInterface
+{
+       /** @var ICache */
+       private $cache;
+       /** @var LoggerInterface */
+       private $logger;
+       /** @var array The $_SERVER array */
+       private $server;
+
+       public function __construct(Configuration $config, Cookie $cookie, ICache $cache, LoggerInterface $logger, array $server)
+       {
+               parent::__construct($config, $cookie);
+
+               $this->cache  = $cache;
+               $this->logger = $logger;
+               $this->server = $server;
+
+               session_set_save_handler($this);
+       }
+
+       public function open($save_path, $session_name)
+       {
+               return true;
+       }
+
+       public function read($session_id)
+       {
+               if (empty($session_id)) {
+                       return '';
+               }
+
+               $data = $this->cache->get('session:' . $session_id);
+               if (!empty($data)) {
+                       Session::$exists = true;
+                       return $data;
+               }
+
+               $this->logger->notice('no data for session', ['session_id' => $session_id, 'uri' => $this->server['REQUEST_URI'] ?? '']);
+
+               return '';
+       }
+
+       /**
+        * @brief Standard PHP session write callback
+        *
+        * This callback updates the stored session data and/or the expiration depending
+        * on the case. Uses the Session::expire for existing session, 5 minutes
+        * for newly created session.
+        *
+        * @param string $session_id   Session ID with format: [a-z0-9]{26}
+        * @param string $session_data Serialized session data
+        *
+        * @return boolean Returns false if parameters are missing, true otherwise
+        * @throws \Exception
+        */
+       public function write($session_id, $session_data)
+       {
+               if (!$session_id) {
+                       return false;
+               }
+
+               if (!$session_data) {
+                       return true;
+               }
+
+               return $this->cache->set('session:' . $session_id, $session_data, Session::$expire);
+       }
+
+       public function close()
+       {
+               return true;
+       }
+
+       public function destroy($id)
+       {
+               return $this->cache->delete('session:' . $id);
+       }
+
+       public function gc($maxlifetime)
+       {
+               return true;
+       }
+}
diff --git a/src/Core/Session/CacheSessionHandler.php b/src/Core/Session/CacheSessionHandler.php
deleted file mode 100644 (file)
index 218ec14..0000000
+++ /dev/null
@@ -1,99 +0,0 @@
-<?php
-
-namespace Friendica\Core\Session;
-
-use Friendica\Core\Cache\ICache;
-use Friendica\Core\Session;
-use Psr\Log\LoggerInterface;
-use SessionHandlerInterface;
-
-/**
- * SessionHandler using Friendica Cache
- *
- * @author Hypolite Petovan <hypolite@mrpetovan.com>
- */
-class CacheSessionHandler implements SessionHandlerInterface
-{
-       /** @var ICache */
-       private $cache;
-       /** @var LoggerInterface */
-       private $logger;
-       /** @var array The $_SERVER array */
-       private $server;
-
-       /**
-        * CacheSessionHandler constructor.
-        *
-        * @param ICache          $cache
-        * @param LoggerInterface $logger
-        * @param array           $server
-        */
-       public function __construct(ICache $cache, LoggerInterface $logger, array $server)
-       {
-               $this->cache  = $cache;
-               $this->logger = $logger;
-               $this->server = $server;
-       }
-
-       public function open($save_path, $session_name)
-       {
-               return true;
-       }
-
-       public function read($session_id)
-       {
-               if (empty($session_id)) {
-                       return '';
-               }
-
-               $data = $this->cache->get('session:' . $session_id);
-               if (!empty($data)) {
-                       Session::$exists = true;
-                       return $data;
-               }
-
-               $this->logger->notice('no data for session', ['session_id' => $session_id, 'uri' => $this->server['REQUEST_URI'] ?? '']);
-
-               return '';
-       }
-
-       /**
-        * @brief Standard PHP session write callback
-        *
-        * This callback updates the stored session data and/or the expiration depending
-        * on the case. Uses the Session::expire for existing session, 5 minutes
-        * for newly created session.
-        *
-        * @param  string $session_id   Session ID with format: [a-z0-9]{26}
-        * @param  string $session_data Serialized session data
-        * @return boolean Returns false if parameters are missing, true otherwise
-        * @throws \Exception
-        */
-       public function write($session_id, $session_data)
-       {
-               if (!$session_id) {
-                       return false;
-               }
-
-               if (!$session_data) {
-                       return true;
-               }
-
-               return $this->cache->set('session:' . $session_id, $session_data, Session::$expire);
-       }
-
-       public function close()
-       {
-               return true;
-       }
-
-       public function destroy($id)
-       {
-               return $this->cache->delete('session:' . $id);
-       }
-
-       public function gc($maxlifetime)
-       {
-               return true;
-       }
-}
diff --git a/src/Core/Session/DatabaseSession.php b/src/Core/Session/DatabaseSession.php
new file mode 100644 (file)
index 0000000..c431be9
--- /dev/null
@@ -0,0 +1,118 @@
+<?php
+
+namespace Friendica\Core\Session;
+
+use Friendica\Core\Config\Configuration;
+use Friendica\Core\Session;
+use Friendica\Database\Database;
+use Friendica\Model\User\Cookie;
+use Psr\Log\LoggerInterface;
+use SessionHandlerInterface;
+
+/**
+ * SessionHandler using database
+ *
+ * @author Hypolite Petovan <hypolite@mrpetovan.com>
+ */
+final class DatabaseSession extends NativeSession implements SessionHandlerInterface
+{
+       /** @var Database */
+       private $dba;
+       /** @var LoggerInterface */
+       private $logger;
+       /** @var array The $_SERVER variable */
+       private $server;
+
+       /**
+        * DatabaseSessionHandler constructor.
+        *
+        * @param Database        $dba
+        * @param LoggerInterface $logger
+        * @param array           $server
+        */
+       public function __construct(Configuration $config, Cookie $cookie, Database $dba, LoggerInterface $logger, array $server)
+       {
+               parent::__construct($config, $cookie);
+
+               $this->dba    = $dba;
+               $this->logger = $logger;
+               $this->server = $server;
+
+               session_set_save_handler($this);
+       }
+
+       public function open($save_path, $session_name)
+       {
+               return true;
+       }
+
+       public function read($session_id)
+       {
+               if (empty($session_id)) {
+                       return '';
+               }
+
+               $session = $this->dba->selectFirst('session', ['data'], ['sid' => $session_id]);
+               if ($this->dba->isResult($session)) {
+                       Session::$exists = true;
+                       return $session['data'];
+               }
+
+               $this->logger->notice('no data for session', ['session_id' => $session_id, 'uri' => $this->server['REQUEST_URI'] ?? '']);
+
+               return '';
+       }
+
+       /**
+        * @brief Standard PHP session write callback
+        *
+        * This callback updates the DB-stored session data and/or the expiration depending
+        * on the case. Uses the Session::expire global for existing session, 5 minutes
+        * for newly created session.
+        *
+        * @param string $session_id   Session ID with format: [a-z0-9]{26}
+        * @param string $session_data Serialized session data
+        *
+        * @return boolean Returns false if parameters are missing, true otherwise
+        * @throws \Exception
+        */
+       public function write($session_id, $session_data)
+       {
+               if (!$session_id) {
+                       return false;
+               }
+
+               if (!$session_data) {
+                       return true;
+               }
+
+               $expire         = time() + Session::$expire;
+               $default_expire = time() + 300;
+
+               if (Session::$exists) {
+                       $fields    = ['data' => $session_data, 'expire' => $expire];
+                       $condition = ["`sid` = ? AND (`data` != ? OR `expire` != ?)", $session_id, $session_data, $expire];
+                       $this->dba->update('session', $fields, $condition);
+               } else {
+                       $fields = ['sid' => $session_id, 'expire' => $default_expire, 'data' => $session_data];
+                       $this->dba->insert('session', $fields);
+               }
+
+               return true;
+       }
+
+       public function close()
+       {
+               return true;
+       }
+
+       public function destroy($id)
+       {
+               return $this->dba->delete('session', ['sid' => $id]);
+       }
+
+       public function gc($maxlifetime)
+       {
+               return $this->dba->delete('session', ["`expire` < ?", time()]);
+       }
+}
diff --git a/src/Core/Session/DatabaseSessionHandler.php b/src/Core/Session/DatabaseSessionHandler.php
deleted file mode 100644 (file)
index 5d8441e..0000000
+++ /dev/null
@@ -1,111 +0,0 @@
-<?php
-
-namespace Friendica\Core\Session;
-
-use Friendica\Core\Session;
-use Friendica\Database\Database;
-use Psr\Log\LoggerInterface;
-use SessionHandlerInterface;
-
-/**
- * SessionHandler using database
- *
- * @author Hypolite Petovan <hypolite@mrpetovan.com>
- */
-class DatabaseSessionHandler implements SessionHandlerInterface
-{
-       /** @var Database */
-       private $dba;
-       /** @var LoggerInterface */
-       private $logger;
-       /** @var array The $_SERVER variable */
-       private $server;
-
-       /**
-        * DatabaseSessionHandler constructor.
-        *
-        * @param Database        $dba
-        * @param LoggerInterface $logger
-        * @param array           $server
-        */
-       public function __construct(Database $dba, LoggerInterface $logger, array $server)
-       {
-               $this->dba    = $dba;
-               $this->logger = $logger;
-               $this->server = $server;
-       }
-
-       public function open($save_path, $session_name)
-       {
-               return true;
-       }
-
-       public function read($session_id)
-       {
-               if (empty($session_id)) {
-                       return '';
-               }
-
-               $session = $this->dba->selectFirst('session', ['data'], ['sid' => $session_id]);
-               if ($this->dba->isResult($session)) {
-                       Session::$exists = true;
-                       return $session['data'];
-               }
-
-               $this->logger->notice('no data for session', ['session_id' => $session_id, 'uri' => $this->server['REQUEST_URI'] ?? '']);
-
-               return '';
-       }
-
-       /**
-        * @brief Standard PHP session write callback
-        *
-        * This callback updates the DB-stored session data and/or the expiration depending
-        * on the case. Uses the Session::expire global for existing session, 5 minutes
-        * for newly created session.
-        *
-        * @param  string $session_id   Session ID with format: [a-z0-9]{26}
-        * @param  string $session_data Serialized session data
-        * @return boolean Returns false if parameters are missing, true otherwise
-        * @throws \Exception
-        */
-       public function write($session_id, $session_data)
-       {
-               if (!$session_id) {
-                       return false;
-               }
-
-               if (!$session_data) {
-                       return true;
-               }
-
-               $expire = time() + Session::$expire;
-               $default_expire = time() + 300;
-
-               if (Session::$exists) {
-                       $fields = ['data' => $session_data, 'expire' => $expire];
-                       $condition = ["`sid` = ? AND (`data` != ? OR `expire` != ?)", $session_id, $session_data, $expire];
-                       $this->dba->update('session', $fields, $condition);
-               } else {
-                       $fields = ['sid' => $session_id, 'expire' => $default_expire, 'data' => $session_data];
-                       $this->dba->insert('session', $fields);
-               }
-
-               return true;
-       }
-
-       public function close()
-       {
-               return true;
-       }
-
-       public function destroy($id)
-       {
-               return $this->dba->delete('session', ['sid' => $id]);
-       }
-
-       public function gc($maxlifetime)
-       {
-               return $this->dba->delete('session', ["`expire` < ?", time()]);
-       }
-}
diff --git a/src/Core/Session/ISession.php b/src/Core/Session/ISession.php
new file mode 100644 (file)
index 0000000..006cc6c
--- /dev/null
@@ -0,0 +1,70 @@
+<?php
+
+namespace Friendica\Core\Session;
+
+use Friendica\BaseObject;
+
+interface ISession
+{
+       /**
+        * Start the current session
+        *
+        * @return self The own Session instance
+        */
+       public function start();
+
+       /**
+        * Checks if the key exists in this session
+        *
+        * @param string $name
+        *
+        * @return boolean True, if it exists
+        */
+       public function exists(string $name);
+
+       /**
+        * Retrieves a key from the session super global or the defaults if the key is missing or the value is falsy.
+        *
+        * Handle the case where session_start() hasn't been called and the super global isn't available.
+        *
+        * @param string $name
+        * @param mixed $defaults
+        * @return mixed
+        */
+       public function get(string $name, $defaults = null);
+
+       /**
+        * Sets a single session variable.
+        * Overrides value of existing key.
+        *
+        * @param string $name
+        * @param mixed $value
+        */
+       public function set(string $name, $value);
+
+       /**
+        * Sets multiple session variables.
+        * Overrides values for existing keys.
+        *
+        * @param array $values
+        */
+       public function setMultiple(array $values);
+
+       /**
+        * Removes a session variable.
+        * Ignores missing keys.
+        *
+        * @param string $name
+        */
+       public function remove(string $name);
+
+       /**
+        * Clears the current session array
+        */
+       public function clear();
+
+       /**
+        * Kills the "Friendica" cookie and all session data
+        */
+       public function delete();
+}
diff --git a/src/Core/Session/MemorySession.php b/src/Core/Session/MemorySession.php
new file mode 100644 (file)
index 0000000..08838c4
--- /dev/null
@@ -0,0 +1,84 @@
+<?php
+
+namespace Friendica\Core\Session;
+
+/**
+ * Native Session functions for internal Session usage.
+ *
+ * Usable for backend processes (daemon/worker) and testing
+ */
+final class MemorySession implements ISession
+{
+       private $data = [];
+
+       public function start()
+       {
+               $this->clear();
+               return $this;
+       }
+
+       /**
+        * @inheritDoc
+        */
+       public function exists(string $name)
+       {
+               return isset($this->data[$name]);
+       }
+
+       /**
+        * @inheritDoc
+        */
+       public function get(string $name, $defaults = null)
+       {
+               return $this->data[$name] ?? $defaults;
+       }
+
+       /**
+        * @inheritDoc
+        */
+       public function set(string $name, $value)
+       {
+               $this->data[$name] = $value;
+       }
+
+       /**
+        * @inheritDoc
+        */
+       public function setMultiple(array $values)
+       {
+               foreach ($values as $key => $value) {
+                       $this->data[$key] = $value;
+               }
+       }
+
+       /**
+        * @inheritDoc
+        */
+       public function remove(string $name)
+       {
+               if ($this->exists($name)) {
+                       unset($this->data[$name]);
+                       return true;
+               }
+
+               return false;
+       }
+
+       /**
+        * @inheritDoc
+        */
+       public function clear()
+       {
+               $this->data = [];
+               return true;
+       }
+
+       /**
+        * @inheritDoc
+        */
+       public function delete()
+       {
+               $this->data = [];
+               return true;
+       }
+}
\ No newline at end of file
diff --git a/src/Core/Session/NativeSession.php b/src/Core/Session/NativeSession.php
new file mode 100644 (file)
index 0000000..2c1507d
--- /dev/null
@@ -0,0 +1,94 @@
+<?php
+
+namespace Friendica\Core\Session;
+
+use Friendica\Core\Config\Configuration;
+use Friendica\App;
+use Friendica\Model\User\Cookie;
+
+class NativeSession implements ISession
+{
+       /** @var Cookie */
+       protected $cookie;
+
+       public function __construct(Configuration $config, Cookie $cookie)
+       {
+               ini_set('session.gc_probability', 50);
+               ini_set('session.use_only_cookies', 1);
+               ini_set('session.cookie_httponly', 1);
+
+               if ($config->get('system', 'ssl_policy') == App\BaseURL::SSL_POLICY_FULL) {
+                       ini_set('session.cookie_secure', 1);
+               }
+
+               $this->cookie = $cookie;
+       }
+
+       /**
+        * {@inheritDoc}
+        */
+       public function start()
+       {
+               session_start();
+               return $this;
+       }
+
+       /**
+        * {@inheritDoc}}
+        */
+       public function exists(string $name)
+       {
+               return isset($_SESSION[$name]);
+       }
+
+       /**
+        * {@inheritDoc}
+        */
+       public function get(string $name, $defaults = null)
+       {
+               return $_SESSION[$name] ?? $defaults;
+       }
+
+       /**
+        * {@inheritDoc}
+        */
+       public function set(string $name, $value)
+       {
+               $_SESSION[$name] = $value;
+       }
+
+       /**
+        * {@inheritDoc}
+        */
+       public function setMultiple(array $values)
+       {
+               $_SESSION = $values + $_SESSION;
+       }
+
+       /**
+        * {@inheritDoc}
+        */
+       public function remove(string $name)
+       {
+               unset($_SESSION[$name]);
+       }
+
+       /**
+        * {@inheritDoc}
+        */
+       public function clear()
+       {
+               $_SESSION = [];
+       }
+
+       /**
+        * @brief Kills the "Friendica" cookie and all session data
+        */
+       public function delete()
+       {
+               $this->cookie->clear();
+               $_SESSION = [];
+               session_unset();
+               session_destroy();
+       }
+}
diff --git a/src/Factory/SessionFactory.php b/src/Factory/SessionFactory.php
new file mode 100644 (file)
index 0000000..ed2f787
--- /dev/null
@@ -0,0 +1,79 @@
+<?php
+
+namespace Friendica\Factory;
+
+use Friendica\App;
+use Friendica\Core\Cache\Cache;
+use Friendica\Core\Cache\ICache;
+use Friendica\Core\Config\Configuration;
+use Friendica\Core\Session\CacheSession;
+use Friendica\Core\Session\DatabaseSession;
+use Friendica\Core\Session\ISession;
+use Friendica\Core\Session\Memory;
+use Friendica\Core\Session\MemorySession;
+use Friendica\Core\Session\NativeSession;
+use Friendica\Core\System;
+use Friendica\Database\Database;
+use Friendica\Model\User\Cookie;
+use Friendica\Util\Profiler;
+use Psr\Log\LoggerInterface;
+
+class SessionFactory
+{
+       /** @var string The plain, PHP internal session management */
+       const INTERNAL = 'native';
+       /** @var string Using the database for session management */
+       const DATABASE = 'database';
+       /** @var string Using the cache for session management */
+       const CACHE = 'cache';
+       /** @var string A temporary cached session */
+       const MEMORY  = 'memory';
+       /** @var string The default type for Session management in case of no config */
+       const DEFAULT = self::DATABASE;
+
+       /**
+        * @param App\Mode        $mode
+        * @param Configuration   $config
+        * @param Cookie          $cookie
+        * @param Database        $dba
+        * @param ICache          $cache
+        * @param LoggerInterface $logger
+        * @param array           $server
+        *
+        * @return ISession
+        */
+       public function createSession(App\Mode $mode, Configuration $config, Cookie $cookie, Database $dba, ICache $cache, LoggerInterface $logger, Profiler $profiler, array $server = [])
+       {
+               $stamp1  = microtime(true);
+               $session = null;
+
+               try {
+                       if ($mode->isInstall() || $mode->isBackend()) {
+                               $session = new MemorySession();
+                       } else {
+                               $session_handler = $config->get('system', 'session_handler', self::DEFAULT);
+
+                               switch ($session_handler) {
+                                       case self::INTERNAL:
+                                               $session = new NativeSession($config, $cookie);
+                                               break;
+                                       case self::DATABASE:
+                                       default:
+                                               $session = new DatabaseSession($config, $cookie, $dba, $logger, $server);
+                                               break;
+                                       case self::CACHE:
+                                               // In case we're using the db as cache driver, use the native db session, not the cache
+                                               if ($config->get('system', 'cache_driver') === Cache::TYPE_DATABASE) {
+                                                       $session = new DatabaseSession($config, $cookie, $dba, $logger, $server);
+                                               } else {
+                                                       $session = new CacheSession($config, $cookie, $cache, $logger, $server);
+                                               }
+                                               break;
+                               }
+                       }
+               } finally {
+                       $profiler->saveTimestamp($stamp1, 'parser', System::callstack());
+                       return $session;
+               }
+       }
+}
index fbc085f4bc347dcc8dae17fecb7cb3eb79e29b61..ea9830679f426d74a609bc34407e74da2d83d006 100644 (file)
@@ -6,6 +6,7 @@ use Friendica\Core\Cache;
 use Friendica\Core\Config;
 use Friendica\Core\L10n\L10n;
 use Friendica\Core\Lock\ILock;
+use Friendica\Core\Session\ISession;
 use Friendica\Database\Database;
 use Friendica\Factory;
 use Friendica\Util;
@@ -179,4 +180,11 @@ return [
                        $_SERVER, $_GET
                ],
        ],
+       ISession::class => [
+               'instanceOf' => Factory\SessionFactory::class,
+               'call' => [
+                       ['createSession', [$_SERVER], Dice::CHAIN_CALL],
+                       ['start', [], Dice::CHAIN_CALL],
+               ],
+       ],
 ];