3 * MediaWiki session backend
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 namespace MediaWiki\Session
;
27 use Psr\Log\LoggerInterface
;
32 * This is the actual workhorse for Session.
34 * Most code does not need to use this class, you want \\MediaWiki\\Session\\Session.
35 * The exceptions are SessionProviders and SessionMetadata hook functions,
36 * which get an instance of this class rather than Session.
38 * The reasons for this split are:
39 * 1. A session can be attached to multiple requests, but we want the Session
40 * object to have some features that correspond to just one of those
42 * 2. We want reasonable garbage collection behavior, but we also want the
43 * SessionManager to hold a reference to every active session so it can be
44 * saved when the request ends.
49 final class SessionBackend
{
53 private $persist = false;
54 private $remember = false;
55 private $forceHTTPS = false;
57 /** @var array|null */
60 private $forcePersist = false;
61 private $metaDirty = false;
62 private $dataDirty = false;
64 /** @var string Used to detect subarray modifications */
65 private $dataHash = null;
67 /** @var CachedBagOStuff */
70 /** @var LoggerInterface */
79 private $curIndex = 0;
81 /** @var WebRequest[] Session requests */
82 private $requests = [];
84 /** @var SessionProvider provider */
87 /** @var array|null provider-specified metadata */
88 private $providerMetadata = null;
91 private $loggedOut = 0;
92 private $delaySave = 0;
94 private $usePhpSessionHandling = true;
95 private $checkPHPSessionRecursionGuard = false;
98 * @param SessionId $id Session ID object
99 * @param SessionInfo $info Session info to populate from
100 * @param CachedBagOStuff $store Backend data store
101 * @param LoggerInterface $logger
102 * @param int $lifetime Session data lifetime in seconds
104 public function __construct(
105 SessionId
$id, SessionInfo
$info, CachedBagOStuff
$store, LoggerInterface
$logger, $lifetime
107 $phpSessionHandling = \RequestContext
::getMain()->getConfig()->get( 'PHPSessionHandling' );
108 $this->usePhpSessionHandling
= $phpSessionHandling !== 'disable';
110 if ( $info->getUserInfo() && !$info->getUserInfo()->isVerified() ) {
111 throw new \
InvalidArgumentException(
112 "Refusing to create session for unverified user {$info->getUserInfo()}"
115 if ( $info->getProvider() === null ) {
116 throw new \
InvalidArgumentException( 'Cannot create session without a provider' );
118 if ( $info->getId() !== $id->getId() ) {
119 throw new \
InvalidArgumentException( 'SessionId and SessionInfo don\'t match' );
123 $this->user
= $info->getUserInfo() ?
$info->getUserInfo()->getUser() : new User
;
124 $this->store
= $store;
125 $this->logger
= $logger;
126 $this->lifetime
= $lifetime;
127 $this->provider
= $info->getProvider();
128 $this->persist
= $info->wasPersisted();
129 $this->remember
= $info->wasRemembered();
130 $this->forceHTTPS
= $info->forceHTTPS();
131 $this->providerMetadata
= $info->getProviderMetadata();
133 $blob = $store->get( wfMemcKey( 'MWSession', (string)$this->id
) );
134 if ( !is_array( $blob ) ||
135 !isset( $blob['metadata'] ) ||
!is_array( $blob['metadata'] ) ||
136 !isset( $blob['data'] ) ||
!is_array( $blob['data'] )
139 $this->dataDirty
= true;
140 $this->metaDirty
= true;
141 $this->logger
->debug(
142 'SessionBackend "{session}" is unsaved, marking dirty in constructor',
144 'session' => $this->id
,
147 $this->data
= $blob['data'];
148 if ( isset( $blob['metadata']['loggedOut'] ) ) {
149 $this->loggedOut
= (int)$blob['metadata']['loggedOut'];
151 if ( isset( $blob['metadata']['expires'] ) ) {
152 $this->expires
= (int)$blob['metadata']['expires'];
154 $this->metaDirty
= true;
155 $this->logger
->debug(
156 'SessionBackend "{session}" metadata dirty due to missing expiration timestamp',
158 'session' => $this->id
,
162 $this->dataHash
= md5( serialize( $this->data
) );
166 * Return a new Session for this backend
167 * @param WebRequest $request
170 public function getSession( WebRequest
$request ) {
171 $index = ++
$this->curIndex
;
172 $this->requests
[$index] = $request;
173 $session = new Session( $this, $index, $this->logger
);
178 * Deregister a Session
179 * @private For use by \\MediaWiki\\Session\\Session::__destruct() only
182 public function deregisterSession( $index ) {
183 unset( $this->requests
[$index] );
184 if ( !count( $this->requests
) ) {
186 $this->provider
->getManager()->deregisterSessionBackend( $this );
191 * Returns the session ID.
194 public function getId() {
195 return (string)$this->id
;
199 * Fetch the SessionId object
200 * @private For internal use by WebRequest
203 public function getSessionId() {
208 * Changes the session ID
209 * @return string New ID (might be the same as the old)
211 public function resetId() {
212 if ( $this->provider
->persistsSessionId() ) {
213 $oldId = (string)$this->id
;
214 $restart = $this->usePhpSessionHandling
&& $oldId === session_id() &&
215 PHPSessionHandler
::isEnabled();
218 // If this session is the one behind PHP's $_SESSION, we need
219 // to close then reopen it.
220 session_write_close();
223 $this->provider
->getManager()->changeBackendId( $this );
224 $this->provider
->sessionIdWasReset( $this, $oldId );
225 $this->metaDirty
= true;
226 $this->logger
->debug(
227 'SessionBackend "{session}" metadata dirty due to ID reset (formerly "{oldId}")',
229 'session' => $this->id
,
234 session_id( (string)$this->id
);
235 \MediaWiki\
quietCall( 'session_start' );
240 // Delete the data for the old session ID now
241 $this->store
->delete( wfMemcKey( 'MWSession', $oldId ) );
246 * Fetch the SessionProvider for this session
247 * @return SessionProviderInterface
249 public function getProvider() {
250 return $this->provider
;
254 * Indicate whether this session is persisted across requests
256 * For example, if cookies are set.
260 public function isPersistent() {
261 return $this->persist
;
265 * Make this session persisted across requests
267 * If the session is already persistent, equivalent to calling
270 public function persist() {
271 if ( !$this->persist
) {
272 $this->persist
= true;
273 $this->forcePersist
= true;
274 $this->metaDirty
= true;
275 $this->logger
->debug(
276 'SessionBackend "{session}" force-persist due to persist()',
278 'session' => $this->id
,
287 * Make this session not persisted across requests
289 public function unpersist() {
290 if ( $this->persist
) {
291 // Close the PHP session, if we're the one that's open
292 if ( $this->usePhpSessionHandling
&& PHPSessionHandler
::isEnabled() &&
293 session_id() === (string)$this->id
295 $this->logger
->debug(
296 'SessionBackend "{session}" Closing PHP session for unpersist',
297 [ 'session' => $this->id
]
299 session_write_close();
303 $this->persist
= false;
304 $this->forcePersist
= true;
305 $this->metaDirty
= true;
307 // Delete the session data, so the local cache-only write in
308 // self::save() doesn't get things out of sync with the backend.
309 $this->store
->delete( wfMemcKey( 'MWSession', (string)$this->id
) );
316 * Indicate whether the user should be remembered independently of the
320 public function shouldRememberUser() {
321 return $this->remember
;
325 * Set whether the user should be remembered independently of the session
327 * @param bool $remember
329 public function setRememberUser( $remember ) {
330 if ( $this->remember
!== (bool)$remember ) {
331 $this->remember
= (bool)$remember;
332 $this->metaDirty
= true;
333 $this->logger
->debug(
334 'SessionBackend "{session}" metadata dirty due to remember-user change',
336 'session' => $this->id
,
343 * Returns the request associated with a Session
344 * @param int $index Session index
347 public function getRequest( $index ) {
348 if ( !isset( $this->requests
[$index] ) ) {
349 throw new \
InvalidArgumentException( 'Invalid session index' );
351 return $this->requests
[$index];
355 * Returns the authenticated user for this session
358 public function getUser() {
363 * Fetch the rights allowed the user when this session is active.
364 * @return null|string[] Allowed user rights, or null to allow all.
366 public function getAllowedUserRights() {
367 return $this->provider
->getAllowedUserRights( $this );
371 * Indicate whether the session user info can be changed
374 public function canSetUser() {
375 return $this->provider
->canChangeUser();
379 * Set a new user for this session
380 * @note This should only be called when the user has been authenticated via a login process
381 * @param User $user User to set on the session.
382 * This may become a "UserValue" in the future, or User may be refactored
385 public function setUser( $user ) {
386 if ( !$this->canSetUser() ) {
387 throw new \
BadMethodCallException(
388 'Cannot set user on this session; check $session->canSetUser() first'
393 $this->metaDirty
= true;
394 $this->logger
->debug(
395 'SessionBackend "{session}" metadata dirty due to user change',
397 'session' => $this->id
,
403 * Get a suggested username for the login form
404 * @param int $index Session index
405 * @return string|null
407 public function suggestLoginUsername( $index ) {
408 if ( !isset( $this->requests
[$index] ) ) {
409 throw new \
InvalidArgumentException( 'Invalid session index' );
411 return $this->provider
->suggestLoginUsername( $this->requests
[$index] );
415 * Whether HTTPS should be forced
418 public function shouldForceHTTPS() {
419 return $this->forceHTTPS
;
423 * Set whether HTTPS should be forced
426 public function setForceHTTPS( $force ) {
427 if ( $this->forceHTTPS
!== (bool)$force ) {
428 $this->forceHTTPS
= (bool)$force;
429 $this->metaDirty
= true;
430 $this->logger
->debug(
431 'SessionBackend "{session}" metadata dirty due to force-HTTPS change',
433 'session' => $this->id
,
440 * Fetch the "logged out" timestamp
443 public function getLoggedOutTimestamp() {
444 return $this->loggedOut
;
448 * Set the "logged out" timestamp
451 public function setLoggedOutTimestamp( $ts = null ) {
453 if ( $this->loggedOut
!== $ts ) {
454 $this->loggedOut
= $ts;
455 $this->metaDirty
= true;
456 $this->logger
->debug(
457 'SessionBackend "{session}" metadata dirty due to logged-out-timestamp change',
459 'session' => $this->id
,
466 * Fetch provider metadata
467 * @protected For use by SessionProvider subclasses only
470 public function getProviderMetadata() {
471 return $this->providerMetadata
;
475 * Set provider metadata
476 * @protected For use by SessionProvider subclasses only
477 * @param array|null $metadata
479 public function setProviderMetadata( $metadata ) {
480 if ( $metadata !== null && !is_array( $metadata ) ) {
481 throw new \
InvalidArgumentException( '$metadata must be an array or null' );
483 if ( $this->providerMetadata
!== $metadata ) {
484 $this->providerMetadata
= $metadata;
485 $this->metaDirty
= true;
486 $this->logger
->debug(
487 'SessionBackend "{session}" metadata dirty due to provider metadata change',
489 'session' => $this->id
,
496 * Fetch the session data array
498 * Note the caller is responsible for calling $this->dirty() if anything in
499 * the array is changed.
501 * @private For use by \\MediaWiki\\Session\\Session only.
504 public function &getData() {
509 * Add data to the session.
511 * Overwrites any existing data under the same keys.
513 * @param array $newData Key-value pairs to add to the session
515 public function addData( array $newData ) {
516 $data = &$this->getData();
517 foreach ( $newData as $key => $value ) {
518 if ( !array_key_exists( $key, $data ) ||
$data[$key] !== $value ) {
519 $data[$key] = $value;
520 $this->dataDirty
= true;
521 $this->logger
->debug(
522 'SessionBackend "{session}" data dirty due to addData(): {callers}',
524 'session' => $this->id
,
525 'callers' => wfGetAllCallers( 5 ),
533 * @private For use by \\MediaWiki\\Session\\Session only.
535 public function dirty() {
536 $this->dataDirty
= true;
537 $this->logger
->debug(
538 'SessionBackend "{session}" data dirty due to dirty(): {callers}',
540 'session' => $this->id
,
541 'callers' => wfGetAllCallers( 5 ),
546 * Renew the session by resaving everything
548 * Resets the TTL in the backend store if the session is near expiring, and
549 * re-persists the session to any active WebRequests if persistent.
551 public function renew() {
552 if ( time() +
$this->lifetime
/ 2 > $this->expires
) {
553 $this->metaDirty
= true;
554 $this->logger
->debug(
555 'SessionBackend "{callers}" metadata dirty for renew(): {callers}',
557 'session' => $this->id
,
558 'callers' => wfGetAllCallers( 5 ),
560 if ( $this->persist
) {
561 $this->forcePersist
= true;
562 $this->logger
->debug(
563 'SessionBackend "{session}" force-persist for renew(): {callers}',
565 'session' => $this->id
,
566 'callers' => wfGetAllCallers( 5 ),
574 * Delay automatic saving while multiple updates are being made
576 * Calls to save() will not be delayed.
578 * @return \ScopedCallback When this goes out of scope, a save will be triggered
580 public function delaySave() {
582 return new \
ScopedCallback( function () {
583 if ( --$this->delaySave
<= 0 ) {
584 $this->delaySave
= 0;
591 * Save and persist session data, unless delayed
593 private function autosave() {
594 if ( $this->delaySave
<= 0 ) {
600 * Save and persist session data
601 * @param bool $closing Whether the session is being closed
603 public function save( $closing = false ) {
604 $anon = $this->user
->isAnon();
606 if ( !$anon && $this->provider
->getManager()->isUserSessionPrevented( $this->user
->getName() ) ) {
607 $this->logger
->debug(
608 'SessionBackend "{session}" not saving, user {user} was ' .
609 'passed to SessionManager::preventSessionsForUser',
611 'session' => $this->id
,
612 'user' => $this->user
,
617 // Ensure the user has a token
618 // @codeCoverageIgnoreStart
619 if ( !$anon && !$this->user
->getToken( false ) ) {
620 $this->logger
->debug(
621 'SessionBackend "{session}" creating token for user {user} on save',
623 'session' => $this->id
,
624 'user' => $this->user
,
626 $this->user
->setToken();
627 if ( !wfReadOnly() ) {
628 $this->user
->saveSettings();
630 $this->metaDirty
= true;
632 // @codeCoverageIgnoreEnd
634 if ( !$this->metaDirty
&& !$this->dataDirty
&&
635 $this->dataHash
!== md5( serialize( $this->data
) )
637 $this->logger
->debug(
638 'SessionBackend "{session}" data dirty due to hash mismatch, {expected} !== {got}',
640 'session' => $this->id
,
641 'expected' => $this->dataHash
,
642 'got' => md5( serialize( $this->data
) ),
644 $this->dataDirty
= true;
647 if ( !$this->metaDirty
&& !$this->dataDirty
&& !$this->forcePersist
) {
651 $this->logger
->debug(
652 'SessionBackend "{session}" save: dataDirty={dataDirty} ' .
653 'metaDirty={metaDirty} forcePersist={forcePersist}',
655 'session' => $this->id
,
656 'dataDirty' => (int)$this->dataDirty
,
657 'metaDirty' => (int)$this->metaDirty
,
658 'forcePersist' => (int)$this->forcePersist
,
661 // Persist or unpersist to the provider, if necessary
662 if ( $this->metaDirty ||
$this->forcePersist
) {
663 if ( $this->persist
) {
664 foreach ( $this->requests
as $request ) {
665 $request->setSessionId( $this->getSessionId() );
666 $this->provider
->persistSession( $this, $request );
669 $this->checkPHPSession();
672 foreach ( $this->requests
as $request ) {
673 if ( $request->getSessionId() === $this->id
) {
674 $this->provider
->unpersistSession( $request );
680 $this->forcePersist
= false;
682 if ( !$this->metaDirty
&& !$this->dataDirty
) {
686 // Save session data to store, if necessary
687 $metadata = $origMetadata = [
688 'provider' => (string)$this->provider
,
689 'providerMetadata' => $this->providerMetadata
,
690 'userId' => $anon ?
0 : $this->user
->getId(),
691 'userName' => User
::isValidUserName( $this->user
->getName() ) ?
$this->user
->getName() : null,
692 'userToken' => $anon ?
null : $this->user
->getToken(),
693 'remember' => !$anon && $this->remember
,
694 'forceHTTPS' => $this->forceHTTPS
,
695 'expires' => time() +
$this->lifetime
,
696 'loggedOut' => $this->loggedOut
,
697 'persisted' => $this->persist
,
700 \Hooks
::run( 'SessionMetadata', [ $this, &$metadata, $this->requests
] );
702 foreach ( $origMetadata as $k => $v ) {
703 if ( $metadata[$k] !== $v ) {
704 throw new \
UnexpectedValueException( "SessionMetadata hook changed metadata key \"$k\"" );
709 wfMemcKey( 'MWSession', (string)$this->id
),
711 'data' => $this->data
,
712 'metadata' => $metadata,
714 $metadata['expires'],
715 $this->persist ?
0 : CachedBagOStuff
::WRITE_CACHE_ONLY
718 $this->metaDirty
= false;
719 $this->dataDirty
= false;
720 $this->dataHash
= md5( serialize( $this->data
) );
721 $this->expires
= $metadata['expires'];
725 * For backwards compatibility, open the PHP session when the global
726 * session is persisted
728 private function checkPHPSession() {
729 if ( !$this->checkPHPSessionRecursionGuard
) {
730 $this->checkPHPSessionRecursionGuard
= true;
731 $reset = new \
ScopedCallback( function () {
732 $this->checkPHPSessionRecursionGuard
= false;
735 if ( $this->usePhpSessionHandling
&& session_id() === '' && PHPSessionHandler
::isEnabled() &&
736 SessionManager
::getGlobalSession()->getId() === (string)$this->id
738 $this->logger
->debug(
739 'SessionBackend "{session}" Taking over PHP session',
741 'session' => $this->id
,
743 session_id( (string)$this->id
);
744 \MediaWiki\
quietCall( 'session_start' );