MediaWiki REL1_33
SessionBackend.php
Go to the documentation of this file.
1<?php
24namespace MediaWiki\Session;
25
27use Psr\Log\LoggerInterface;
28use User;
30
49final class SessionBackend {
51 private $id;
52
54 private $persist = false;
55
57 private $remember = false;
58
60 private $forceHTTPS = false;
61
63 private $data = null;
64
66 private $forcePersist = false;
67
69 private $metaDirty = false;
70
72 private $dataDirty = false;
73
75 private $dataHash = null;
76
78 private $store;
79
81 private $logger;
82
84 private $lifetime;
85
87 private $user;
88
90 private $curIndex = 0;
91
93 private $requests = [];
94
96 private $provider;
97
99 private $providerMetadata = null;
100
102 private $expires = 0;
103
105 private $loggedOut = 0;
106
108 private $delaySave = 0;
109
114
116 private $shutdown = false;
117
125 public function __construct(
127 ) {
128 $phpSessionHandling = \RequestContext::getMain()->getConfig()->get( 'PHPSessionHandling' );
129 $this->usePhpSessionHandling = $phpSessionHandling !== 'disable';
130
131 if ( $info->getUserInfo() && !$info->getUserInfo()->isVerified() ) {
132 throw new \InvalidArgumentException(
133 "Refusing to create session for unverified user {$info->getUserInfo()}"
134 );
135 }
136 if ( $info->getProvider() === null ) {
137 throw new \InvalidArgumentException( 'Cannot create session without a provider' );
138 }
139 if ( $info->getId() !== $id->getId() ) {
140 throw new \InvalidArgumentException( 'SessionId and SessionInfo don\'t match' );
141 }
142
143 $this->id = $id;
144 $this->user = $info->getUserInfo() ? $info->getUserInfo()->getUser() : new User;
145 $this->store = $store;
146 $this->logger = $logger;
147 $this->lifetime = $lifetime;
148 $this->provider = $info->getProvider();
149 $this->persist = $info->wasPersisted();
150 $this->remember = $info->wasRemembered();
151 $this->forceHTTPS = $info->forceHTTPS();
152 $this->providerMetadata = $info->getProviderMetadata();
153
154 $blob = $store->get( $store->makeKey( 'MWSession', (string)$this->id ) );
155 if ( !is_array( $blob ) ||
156 !isset( $blob['metadata'] ) || !is_array( $blob['metadata'] ) ||
157 !isset( $blob['data'] ) || !is_array( $blob['data'] )
158 ) {
159 $this->data = [];
160 $this->dataDirty = true;
161 $this->metaDirty = true;
162 $this->logger->debug(
163 'SessionBackend "{session}" is unsaved, marking dirty in constructor',
164 [
165 'session' => $this->id,
166 ] );
167 } else {
168 $this->data = $blob['data'];
169 if ( isset( $blob['metadata']['loggedOut'] ) ) {
170 $this->loggedOut = (int)$blob['metadata']['loggedOut'];
171 }
172 if ( isset( $blob['metadata']['expires'] ) ) {
173 $this->expires = (int)$blob['metadata']['expires'];
174 } else {
175 $this->metaDirty = true;
176 $this->logger->debug(
177 'SessionBackend "{session}" metadata dirty due to missing expiration timestamp',
178 [
179 'session' => $this->id,
180 ] );
181 }
182 }
183 $this->dataHash = md5( serialize( $this->data ) );
184 }
185
191 public function getSession( WebRequest $request ) {
192 $index = ++$this->curIndex;
193 $this->requests[$index] = $request;
194 $session = new Session( $this, $index, $this->logger );
195 return $session;
196 }
197
203 public function deregisterSession( $index ) {
204 unset( $this->requests[$index] );
205 if ( !$this->shutdown && !count( $this->requests ) ) {
206 $this->save( true );
207 $this->provider->getManager()->deregisterSessionBackend( $this );
208 }
209 }
210
215 public function shutdown() {
216 $this->save( true );
217 $this->shutdown = true;
218 }
219
224 public function getId() {
225 return (string)$this->id;
226 }
227
233 public function getSessionId() {
234 return $this->id;
235 }
236
241 public function resetId() {
242 if ( $this->provider->persistsSessionId() ) {
243 $oldId = (string)$this->id;
244 $restart = $this->usePhpSessionHandling && $oldId === session_id() &&
246
247 if ( $restart ) {
248 // If this session is the one behind PHP's $_SESSION, we need
249 // to close then reopen it.
250 session_write_close();
251 }
252
253 $this->provider->getManager()->changeBackendId( $this );
254 $this->provider->sessionIdWasReset( $this, $oldId );
255 $this->metaDirty = true;
256 $this->logger->debug(
257 'SessionBackend "{session}" metadata dirty due to ID reset (formerly "{oldId}")',
258 [
259 'session' => $this->id,
260 'oldId' => $oldId,
261 ] );
262
263 if ( $restart ) {
264 session_id( (string)$this->id );
265 \Wikimedia\quietCall( 'session_start' );
266 }
267
268 $this->autosave();
269
270 // Delete the data for the old session ID now
271 $this->store->delete( $this->store->makeKey( 'MWSession', $oldId ) );
272 }
273
274 return $this->id;
275 }
276
281 public function getProvider() {
282 return $this->provider;
283 }
284
292 public function isPersistent() {
293 return $this->persist;
294 }
295
302 public function persist() {
303 if ( !$this->persist ) {
304 $this->persist = true;
305 $this->forcePersist = true;
306 $this->metaDirty = true;
307 $this->logger->debug(
308 'SessionBackend "{session}" force-persist due to persist()',
309 [
310 'session' => $this->id,
311 ] );
312 $this->autosave();
313 } else {
314 $this->renew();
315 }
316 }
317
321 public function unpersist() {
322 if ( $this->persist ) {
323 // Close the PHP session, if we're the one that's open
324 if ( $this->usePhpSessionHandling && PHPSessionHandler::isEnabled() &&
325 session_id() === (string)$this->id
326 ) {
327 $this->logger->debug(
328 'SessionBackend "{session}" Closing PHP session for unpersist',
329 [ 'session' => $this->id ]
330 );
331 session_write_close();
332 session_id( '' );
333 }
334
335 $this->persist = false;
336 $this->forcePersist = true;
337 $this->metaDirty = true;
338
339 // Delete the session data, so the local cache-only write in
340 // self::save() doesn't get things out of sync with the backend.
341 $this->store->delete( $this->store->makeKey( 'MWSession', (string)$this->id ) );
342
343 $this->autosave();
344 }
345 }
346
352 public function shouldRememberUser() {
353 return $this->remember;
354 }
355
361 public function setRememberUser( $remember ) {
362 if ( $this->remember !== (bool)$remember ) {
363 $this->remember = (bool)$remember;
364 $this->metaDirty = true;
365 $this->logger->debug(
366 'SessionBackend "{session}" metadata dirty due to remember-user change',
367 [
368 'session' => $this->id,
369 ] );
370 $this->autosave();
371 }
372 }
373
379 public function getRequest( $index ) {
380 if ( !isset( $this->requests[$index] ) ) {
381 throw new \InvalidArgumentException( 'Invalid session index' );
382 }
383 return $this->requests[$index];
384 }
385
390 public function getUser() {
391 return $this->user;
392 }
393
398 public function getAllowedUserRights() {
399 return $this->provider->getAllowedUserRights( $this );
400 }
401
406 public function canSetUser() {
407 return $this->provider->canChangeUser();
408 }
409
417 public function setUser( $user ) {
418 if ( !$this->canSetUser() ) {
419 throw new \BadMethodCallException(
420 'Cannot set user on this session; check $session->canSetUser() first'
421 );
422 }
423
424 $this->user = $user;
425 $this->metaDirty = true;
426 $this->logger->debug(
427 'SessionBackend "{session}" metadata dirty due to user change',
428 [
429 'session' => $this->id,
430 ] );
431 $this->autosave();
432 }
433
439 public function suggestLoginUsername( $index ) {
440 if ( !isset( $this->requests[$index] ) ) {
441 throw new \InvalidArgumentException( 'Invalid session index' );
442 }
443 return $this->provider->suggestLoginUsername( $this->requests[$index] );
444 }
445
450 public function shouldForceHTTPS() {
451 return $this->forceHTTPS;
452 }
453
458 public function setForceHTTPS( $force ) {
459 if ( $this->forceHTTPS !== (bool)$force ) {
460 $this->forceHTTPS = (bool)$force;
461 $this->metaDirty = true;
462 $this->logger->debug(
463 'SessionBackend "{session}" metadata dirty due to force-HTTPS change',
464 [
465 'session' => $this->id,
466 ] );
467 $this->autosave();
468 }
469 }
470
475 public function getLoggedOutTimestamp() {
476 return $this->loggedOut;
477 }
478
483 public function setLoggedOutTimestamp( $ts = null ) {
484 $ts = (int)$ts;
485 if ( $this->loggedOut !== $ts ) {
486 $this->loggedOut = $ts;
487 $this->metaDirty = true;
488 $this->logger->debug(
489 'SessionBackend "{session}" metadata dirty due to logged-out-timestamp change',
490 [
491 'session' => $this->id,
492 ] );
493 $this->autosave();
494 }
495 }
496
502 public function getProviderMetadata() {
504 }
505
511 public function setProviderMetadata( $metadata ) {
512 if ( $metadata !== null && !is_array( $metadata ) ) {
513 throw new \InvalidArgumentException( '$metadata must be an array or null' );
514 }
515 if ( $this->providerMetadata !== $metadata ) {
516 $this->providerMetadata = $metadata;
517 $this->metaDirty = true;
518 $this->logger->debug(
519 'SessionBackend "{session}" metadata dirty due to provider metadata change',
520 [
521 'session' => $this->id,
522 ] );
523 $this->autosave();
524 }
525 }
526
536 public function &getData() {
537 return $this->data;
538 }
539
547 public function addData( array $newData ) {
548 $data = &$this->getData();
549 foreach ( $newData as $key => $value ) {
550 if ( !array_key_exists( $key, $data ) || $data[$key] !== $value ) {
551 $data[$key] = $value;
552 $this->dataDirty = true;
553 $this->logger->debug(
554 'SessionBackend "{session}" data dirty due to addData(): {callers}',
555 [
556 'session' => $this->id,
557 'callers' => wfGetAllCallers( 5 ),
558 ] );
559 }
560 }
561 }
562
567 public function dirty() {
568 $this->dataDirty = true;
569 $this->logger->debug(
570 'SessionBackend "{session}" data dirty due to dirty(): {callers}',
571 [
572 'session' => $this->id,
573 'callers' => wfGetAllCallers( 5 ),
574 ] );
575 }
576
583 public function renew() {
584 if ( time() + $this->lifetime / 2 > $this->expires ) {
585 $this->metaDirty = true;
586 $this->logger->debug(
587 'SessionBackend "{callers}" metadata dirty for renew(): {callers}',
588 [
589 'session' => $this->id,
590 'callers' => wfGetAllCallers( 5 ),
591 ] );
592 if ( $this->persist ) {
593 $this->forcePersist = true;
594 $this->logger->debug(
595 'SessionBackend "{session}" force-persist for renew(): {callers}',
596 [
597 'session' => $this->id,
598 'callers' => wfGetAllCallers( 5 ),
599 ] );
600 }
601 }
602 $this->autosave();
603 }
604
612 public function delaySave() {
613 $this->delaySave++;
614 return new \Wikimedia\ScopedCallback( function () {
615 if ( --$this->delaySave <= 0 ) {
616 $this->delaySave = 0;
617 $this->save();
618 }
619 } );
620 }
621
626 private function autosave() {
627 if ( $this->delaySave <= 0 ) {
628 $this->save();
629 }
630 }
631
641 public function save( $closing = false ) {
642 $anon = $this->user->isAnon();
643
644 if ( !$anon && $this->provider->getManager()->isUserSessionPrevented( $this->user->getName() ) ) {
645 $this->logger->debug(
646 'SessionBackend "{session}" not saving, user {user} was ' .
647 'passed to SessionManager::preventSessionsForUser',
648 [
649 'session' => $this->id,
650 'user' => $this->user,
651 ] );
652 return;
653 }
654
655 // Ensure the user has a token
656 // @codeCoverageIgnoreStart
657 if ( !$anon && !$this->user->getToken( false ) ) {
658 $this->logger->debug(
659 'SessionBackend "{session}" creating token for user {user} on save',
660 [
661 'session' => $this->id,
662 'user' => $this->user,
663 ] );
664 $this->user->setToken();
665 if ( !wfReadOnly() ) {
666 // Promise that the token set here will be valid; save it at end of request
668 \DeferredUpdates::addCallableUpdate( function () use ( $user ) {
670 } );
671 }
672 $this->metaDirty = true;
673 }
674 // @codeCoverageIgnoreEnd
675
676 if ( !$this->metaDirty && !$this->dataDirty &&
677 $this->dataHash !== md5( serialize( $this->data ) )
678 ) {
679 $this->logger->debug(
680 'SessionBackend "{session}" data dirty due to hash mismatch, {expected} !== {got}',
681 [
682 'session' => $this->id,
683 'expected' => $this->dataHash,
684 'got' => md5( serialize( $this->data ) ),
685 ] );
686 $this->dataDirty = true;
687 }
688
689 if ( !$this->metaDirty && !$this->dataDirty && !$this->forcePersist ) {
690 return;
691 }
692
693 $this->logger->debug(
694 'SessionBackend "{session}" save: dataDirty={dataDirty} ' .
695 'metaDirty={metaDirty} forcePersist={forcePersist}',
696 [
697 'session' => $this->id,
698 'dataDirty' => (int)$this->dataDirty,
699 'metaDirty' => (int)$this->metaDirty,
700 'forcePersist' => (int)$this->forcePersist,
701 ] );
702
703 // Persist or unpersist to the provider, if necessary
704 if ( $this->metaDirty || $this->forcePersist ) {
705 if ( $this->persist ) {
706 foreach ( $this->requests as $request ) {
707 $request->setSessionId( $this->getSessionId() );
708 $this->provider->persistSession( $this, $request );
709 }
710 if ( !$closing ) {
711 $this->checkPHPSession();
712 }
713 } else {
714 foreach ( $this->requests as $request ) {
715 if ( $request->getSessionId() === $this->id ) {
716 $this->provider->unpersistSession( $request );
717 }
718 }
719 }
720 }
721
722 $this->forcePersist = false;
723
724 if ( !$this->metaDirty && !$this->dataDirty ) {
725 return;
726 }
727
728 // Save session data to store, if necessary
729 $metadata = $origMetadata = [
730 'provider' => (string)$this->provider,
731 'providerMetadata' => $this->providerMetadata,
732 'userId' => $anon ? 0 : $this->user->getId(),
733 'userName' => User::isValidUserName( $this->user->getName() ) ? $this->user->getName() : null,
734 'userToken' => $anon ? null : $this->user->getToken(),
735 'remember' => !$anon && $this->remember,
736 'forceHTTPS' => $this->forceHTTPS,
737 'expires' => time() + $this->lifetime,
738 'loggedOut' => $this->loggedOut,
739 'persisted' => $this->persist,
740 ];
741
742 \Hooks::run( 'SessionMetadata', [ $this, &$metadata, $this->requests ] );
743
744 foreach ( $origMetadata as $k => $v ) {
745 if ( $metadata[$k] !== $v ) {
746 throw new \UnexpectedValueException( "SessionMetadata hook changed metadata key \"$k\"" );
747 }
748 }
749
750 $flags = $this->persist ? 0 : CachedBagOStuff::WRITE_CACHE_ONLY;
751 $flags |= CachedBagOStuff::WRITE_SYNC; // write to all datacenters
752 $this->store->set(
753 $this->store->makeKey( 'MWSession', (string)$this->id ),
754 [
755 'data' => $this->data,
756 'metadata' => $metadata,
757 ],
758 $metadata['expires'],
759 $flags
760 );
761
762 $this->metaDirty = false;
763 $this->dataDirty = false;
764 $this->dataHash = md5( serialize( $this->data ) );
765 $this->expires = $metadata['expires'];
766 }
767
772 private function checkPHPSession() {
773 if ( !$this->checkPHPSessionRecursionGuard ) {
774 $this->checkPHPSessionRecursionGuard = true;
775 $reset = new \Wikimedia\ScopedCallback( function () {
776 $this->checkPHPSessionRecursionGuard = false;
777 } );
778
779 if ( $this->usePhpSessionHandling && session_id() === '' && PHPSessionHandler::isEnabled() &&
780 SessionManager::getGlobalSession()->getId() === (string)$this->id
781 ) {
782 $this->logger->debug(
783 'SessionBackend "{session}" Taking over PHP session',
784 [
785 'session' => $this->id,
786 ] );
787 session_id( (string)$this->id );
788 \Wikimedia\quietCall( 'session_start' );
789 }
790 }
791 }
792
793}
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
serialize()
wfReadOnly()
Check whether the wiki is in read-only mode.
wfGetAllCallers( $limit=3)
Return a string consisting of callers in the stack.
Wrapper around a BagOStuff that caches data in memory.
makeKey( $class, $component=null)
Make a cache key, scoped to this instance's keyspace.
get( $key, $flags=0)
Get an item with the given key.
static isEnabled()
Test whether the handler is installed and enabled.
This is the actual workhorse for Session.
setLoggedOutTimestamp( $ts=null)
Set the "logged out" timestamp.
addData(array $newData)
Add data to the session.
suggestLoginUsername( $index)
Get a suggested username for the login form.
isPersistent()
Indicate whether this session is persisted across requests.
getSession(WebRequest $request)
Return a new Session for this backend.
__construct(SessionId $id, SessionInfo $info, CachedBagOStuff $store, LoggerInterface $logger, $lifetime)
shouldForceHTTPS()
Whether HTTPS should be forced.
& getData()
Fetch the session data array.
getProviderMetadata()
Fetch provider metadata.
deregisterSession( $index)
Deregister a Session.
getSessionId()
Fetch the SessionId object.
canSetUser()
Indicate whether the session user info can be changed.
delaySave()
Delay automatic saving while multiple updates are being made.
checkPHPSession()
For backwards compatibility, open the PHP session when the global session is persisted.
unpersist()
Make this session not persisted across requests.
WebRequest[] $requests
Session requests.
setProviderMetadata( $metadata)
Set provider metadata.
array null $providerMetadata
provider-specified metadata
setForceHTTPS( $force)
Set whether HTTPS should be forced.
getProvider()
Fetch the SessionProvider for this session.
getId()
Returns the session ID.
getLoggedOutTimestamp()
Fetch the "logged out" timestamp.
resetId()
Changes the session ID.
setUser( $user)
Set a new user for this session.
save( $closing=false)
Save the session.
getUser()
Returns the authenticated user for this session.
autosave()
Save the session, unless delayed.
renew()
Renew the session by resaving everything.
SessionProvider $provider
provider
string $dataHash
Used to detect subarray modifications.
getAllowedUserRights()
Fetch the rights allowed the user when this session is active.
getRequest( $index)
Returns the request associated with a Session.
persist()
Make this session persisted across requests.
setRememberUser( $remember)
Set whether the user should be remembered independently of the session ID.
shouldRememberUser()
Indicate whether the user should be remembered independently of the session ID.
Value object holding the session ID in a manner that can be globally updated.
Definition SessionId.php:38
Value object returned by SessionProvider.
getProviderMetadata()
Return provider metadata.
getId()
Return the session ID.
getProvider()
Return the provider.
getUserInfo()
Return the user.
wasPersisted()
Return whether the session is persisted.
wasRemembered()
Return whether the user was remembered.
forceHTTPS()
Whether this session should only be used over HTTPS.
static getGlobalSession()
Get the "global" session.
A SessionProvider provides SessionInfo and support for Session.
Manages data for an an authenticated session.
Definition Session.php:48
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition User.php:48
static isValidUserName( $name)
Is the input a valid username?
Definition User.php:993
saveSettings()
Save this user's settings into the database.
Definition User.php:4187
The WebRequest class encapsulates getting at data passed in the URL or via a POSTed form stripping il...
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a save
Definition deferred.txt:5
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such and we might be restricted by PHP settings such as safe mode or open_basedir We cannot assume that the software even has read access anywhere useful Many shared hosts run all users web applications under the same user
Wikitext formatted, in the key only.
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction you ll probably need to make sure the header is varied on $request
Definition hooks.txt:2843
This code would result in ircNotify being run twice when an article is and once for brion Hooks can return three possible true was required This is the default since MediaWiki *some string
Definition hooks.txt:181
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
Definition hooks.txt:783
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition injection.txt:37
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
This document describes the state of Postgres support in and is fairly well maintained The main code is very well while extensions are very hit and miss it is probably the most supported database after MySQL Much of the work in making MediaWiki database agnostic came about through the work of creating Postgres but without copying over all the usage comments General notes on the but these can almost always be programmed around *Although Postgres has a true BOOLEAN boolean columns are always mapped to as the code does not always treat the column as a and VARBINARY columns should simply be TEXT The only exception is when VARBINARY is used to store true binary data
Definition postgres.txt:37