Elgg  Version 7.1
ElggSession.php
Go to the documentation of this file.
1 <?php
2 
3 use Elgg\Config;
4 use Elgg\Database;
5 use Elgg\Database\SessionHandler as ElggSessionHandler;
8 use Symfony\Component\HttpFoundation\Session\Session;
9 use Symfony\Component\HttpFoundation\Session\SessionInterface;
10 use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage;
11 use Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage;
12 
20 class ElggSession {
21 
22  use Profilable;
23 
27  protected $storage;
28 
34  public function __construct(SessionInterface $storage) {
35  $this->storage = $storage;
36  }
37 
44  public function boot(): void {
45  $this->beginTimer([__METHOD__]);
46 
47  $this->start();
48 
49  $migrate_session = false;
50 
51  // test whether we have a user session
52  if ($this->has('guid')) {
53  $user = _elgg_services()->entityTable->get($this->get('guid'), 'user');
54  if (!$user instanceof \ElggUser) {
55  // OMG user has been deleted.
56  $this->invalidate();
57 
58  // redirect to homepage
59  $this->endTimer([__METHOD__]);
60  _elgg_services()->responseFactory->redirect('');
61  }
62  } else {
63  $user = _elgg_services()->persistentLogin->bootSession();
64  if ($user instanceof \ElggUser) {
65  _elgg_services()->persistentLogin->updateTokenUsage($user);
66  _elgg_services()->session_manager->setUserToken($user);
67  $migrate_session = true;
68  }
69  }
70 
71  if ($user instanceof \ElggUser) {
72  _elgg_services()->session_manager->setLoggedInUser($user, $migrate_session);
73  $user->setLastAction();
74 
75  // logout a user with open session who has been banned
76  if ($user->isBanned()) {
77  _elgg_services()->session_manager->logout();
78  }
79 
80  // make sure the user hasn't changed in between requests
81  // e.g. password reset
82  try {
83  _elgg_services()->session_manager->validateUserToken($user);
84  } catch (SecurityException $e) {
85  elgg_register_error_message($e->getMessage());
86  _elgg_services()->session_manager->logout();
87  }
88  }
89 
90  $this->endTimer([__METHOD__]);
91  }
92 
100  public function start() {
101 
102  if ($this->storage->getId()) {
103  return true;
104  }
105 
106  $result = $this->storage->start();
107  $this->generateSessionToken();
108  return $result;
109  }
110 
118  public function migrate(bool $destroy = true) {
119  return $this->storage->migrate($destroy);
120  }
121 
130  public function invalidate() {
131  $this->storage->clear();
132  $result = $this->migrate(true);
133  $this->generateSessionToken();
134  _elgg_services()->accessCache->clear();
135  return $result;
136  }
137 
144  public function save() {
145  $this->storage->save();
146  }
147 
154  public function isStarted() {
155  return $this->storage->isStarted();
156  }
157 
164  public function getID() {
165  return $this->storage->getId();
166  }
167 
175  public function setId($id) {
176  $this->storage->setId($id);
177  }
178 
185  public function getName() {
186  return $this->storage->getName();
187  }
188 
196  public function setName($name) {
197  $this->storage->setName($name);
198  }
199 
207  public function get($name, $default = null) {
208  return $this->storage->get($name, $default);
209  }
210 
218  public function set($name, $value) {
219  $this->storage->set($name, $value);
220  }
221 
229  public function remove($name) {
230  return $this->storage->remove($name);
231  }
232 
240  public function has($name) {
241  return $this->storage->has($name);
242  }
243 
252  protected function generateSessionToken() {
253  // Generate a simple token that we store server side
254  if (!$this->has('__elgg_session')) {
255  $this->set('__elgg_session', _elgg_services()->crypto->getRandomString(22));
256  }
257  }
258 
266  public static function getMock() {
267  $storage = new MockArraySessionStorage();
268  $session = new Session($storage);
269  return new self($session);
270  }
271 
282  public static function fromDatabase(Config $config, Database $db) {
283  $params = $config->getCookieConfig()['session'];
284  $options = [
285  // session.cache_limiter is unfortunately set to "" by the NativeSessionStorage
286  // constructor, so we must capture and inject it directly.
287  'cache_limiter' => session_cache_limiter(),
288 
289  'name' => $params['name'],
290  'cookie_path' => $params['path'],
291  'cookie_domain' => $params['domain'],
292  'cookie_secure' => $params['secure'],
293  'cookie_httponly' => $params['httponly'],
294  'cookie_lifetime' => $params['lifetime'],
295  'cookie_samesite' => $params['samesite'],
296  ];
297 
298  $handler = new ElggSessionHandler($db);
299  $storage = new NativeSessionStorage($options, $handler);
300  $session = new Session($storage);
301  return new self($session);
302  }
303 
313  public static function fromFiles(Config $config) {
314  $params = $config->getCookieConfig()['session'];
315  $options = [
316  // session.cache_limiter is unfortunately set to "" by the NativeSessionStorage
317  // constructor, so we must capture and inject it directly.
318  'cache_limiter' => session_cache_limiter(),
319 
320  'name' => $params['name'],
321  'cookie_path' => $params['path'],
322  'cookie_domain' => $params['domain'],
323  'cookie_secure' => $params['secure'],
324  'cookie_httponly' => $params['httponly'],
325  'cookie_lifetime' => $params['lifetime'],
326  ];
327 
328  $storage = new NativeSessionStorage($options);
329  $session = new Session($storage);
330  return new self($session);
331  }
332 }
if(! $user||! $user->canDelete()) $name
Definition: delete.php:22
$id
Generic annotation delete action.
Definition: delete.php:6
$params
Saves global plugin settings.
Definition: save.php:13
$handler
Definition: add.php:7
$user
Elgg user account settings.
Definition: ban.php:7
Elgg Session Management.
Definition: ElggSession.php:20
has($name)
Has the attribute been defined.
static getMock()
Get an isolated ElggSession that does not persist between requests.
invalidate()
Invalidates the session.
save()
Save the session data and closes the session.
__construct(SessionInterface $storage)
Constructor.
Definition: ElggSession.php:34
migrate(bool $destroy=true)
Migrates the session to a new session id while maintaining session attributes.
boot()
Initializes the session and checks for the remember me cookie.
Definition: ElggSession.php:44
generateSessionToken()
Adds a token to the session.
static fromFiles(Config $config)
Create a session stored in files.
static fromDatabase(Config $config, Database $db)
Create a session stored in the DB.
setId($id)
Set the session ID.
isStarted()
Has the session been started.
getID()
Get the session ID.
start()
Start the session.
getName()
Get the session name.
setName($name)
Set the session name.
Database session handler.
The Elgg database.
Definition: Database.php:26
Throw when a Security Exception occurs.
if(count($css_vars)< 2) $options
$config
Advanced site settings, debugging section.
Definition: debugging.php:6
foreach($recommendedExtensions as $extension) if(empty(ini_get('session.gc_probability'))||empty(ini_get('session.gc_divisor'))) $db
_elgg_services()
Get the global service provider.
Definition: elgglib.php:347
elgg_register_error_message(string|array $options)
Registers a error system message.
Definition: elgglib.php:72
$value
Definition: generic.php:51
$default
Definition: checkbox.php:30
if(isset($_COOKIE['elggperm'])) $session
Definition: login_as.php:28
endTimer(array $keys)
Ends the timer (when enabled)
Definition: Profilable.php:59
trait Profilable
Make an object accept a timer.
Definition: Profilable.php:12
beginTimer(array $keys)
Start the timer (when enabled)
Definition: Profilable.php:43