MediaWiki  1.33.1
SessionManager.php
Go to the documentation of this file.
1 <?php
24 namespace MediaWiki\Session;
25 
28 use Psr\Log\LoggerInterface;
31 use Config;
33 use User;
35 use Wikimedia\ObjectFactory;
36 
50 final class SessionManager implements SessionManagerInterface {
52  private static $instance = null;
53 
55  private static $globalSession = null;
56 
58  private static $globalSessionRequest = null;
59 
61  private $logger;
62 
64  private $config;
65 
67  private $store;
68 
70  private $sessionProviders = null;
71 
73  private $varyCookies = null;
74 
76  private $varyHeaders = null;
77 
79  private $allSessionBackends = [];
80 
82  private $allSessionIds = [];
83 
85  private $preventUsers = [];
86 
92  public static function singleton() {
93  if ( self::$instance === null ) {
94  self::$instance = new self();
95  }
96  return self::$instance;
97  }
98 
107  public static function getGlobalSession() {
108  if ( !PHPSessionHandler::isEnabled() ) {
109  $id = '';
110  } else {
111  $id = session_id();
112  }
113 
114  $request = \RequestContext::getMain()->getRequest();
115  if (
116  !self::$globalSession // No global session is set up yet
117  || self::$globalSessionRequest !== $request // The global WebRequest changed
118  || $id !== '' && self::$globalSession->getId() !== $id // Someone messed with session_id()
119  ) {
120  self::$globalSessionRequest = $request;
121  if ( $id === '' ) {
122  // session_id() wasn't used, so fetch the Session from the WebRequest.
123  // We use $request->getSession() instead of $singleton->getSessionForRequest()
124  // because doing the latter would require a public
125  // "$request->getSessionId()" method that would confuse end
126  // users by returning SessionId|null where they'd expect it to
127  // be short for $request->getSession()->getId(), and would
128  // wind up being a duplicate of the code in
129  // $request->getSession() anyway.
130  self::$globalSession = $request->getSession();
131  } else {
132  // Someone used session_id(), so we need to follow suit.
133  // Note this overwrites whatever session might already be
134  // associated with $request with the one for $id.
135  self::$globalSession = self::singleton()->getSessionById( $id, true, $request )
136  ?: $request->getSession();
137  }
138  }
139  return self::$globalSession;
140  }
141 
148  public function __construct( $options = [] ) {
149  if ( isset( $options['config'] ) ) {
150  $this->config = $options['config'];
151  if ( !$this->config instanceof Config ) {
152  throw new \InvalidArgumentException(
153  '$options[\'config\'] must be an instance of Config'
154  );
155  }
156  } else {
157  $this->config = MediaWikiServices::getInstance()->getMainConfig();
158  }
159 
160  if ( isset( $options['logger'] ) ) {
161  if ( !$options['logger'] instanceof LoggerInterface ) {
162  throw new \InvalidArgumentException(
163  '$options[\'logger\'] must be an instance of LoggerInterface'
164  );
165  }
166  $this->setLogger( $options['logger'] );
167  } else {
168  $this->setLogger( \MediaWiki\Logger\LoggerFactory::getInstance( 'session' ) );
169  }
170 
171  if ( isset( $options['store'] ) ) {
172  if ( !$options['store'] instanceof BagOStuff ) {
173  throw new \InvalidArgumentException(
174  '$options[\'store\'] must be an instance of BagOStuff'
175  );
176  }
177  $store = $options['store'];
178  } else {
179  $store = \ObjectCache::getInstance( $this->config->get( 'SessionCacheType' ) );
180  }
181  $this->store = $store instanceof CachedBagOStuff ? $store : new CachedBagOStuff( $store );
182 
183  register_shutdown_function( [ $this, 'shutdown' ] );
184  }
185 
186  public function setLogger( LoggerInterface $logger ) {
187  $this->logger = $logger;
188  }
189 
191  $info = $this->getSessionInfoForRequest( $request );
192 
193  if ( !$info ) {
194  $session = $this->getEmptySession( $request );
195  } else {
196  $session = $this->getSessionFromInfo( $info, $request );
197  }
198  return $session;
199  }
200 
201  public function getSessionById( $id, $create = false, WebRequest $request = null ) {
202  if ( !self::validateSessionId( $id ) ) {
203  throw new \InvalidArgumentException( 'Invalid session ID' );
204  }
205  if ( !$request ) {
206  $request = new FauxRequest;
207  }
208 
209  $session = null;
210  $info = new SessionInfo( SessionInfo::MIN_PRIORITY, [ 'id' => $id, 'idIsSafe' => true ] );
211 
212  // If we already have the backend loaded, use it directly
213  if ( isset( $this->allSessionBackends[$id] ) ) {
214  return $this->getSessionFromInfo( $info, $request );
215  }
216 
217  // Test if the session is in storage, and if so try to load it.
218  $key = $this->store->makeKey( 'MWSession', $id );
219  if ( is_array( $this->store->get( $key ) ) ) {
220  $create = false; // If loading fails, don't bother creating because it probably will fail too.
221  if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
222  $session = $this->getSessionFromInfo( $info, $request );
223  }
224  }
225 
226  if ( $create && $session === null ) {
227  $ex = null;
228  try {
229  $session = $this->getEmptySessionInternal( $request, $id );
230  } catch ( \Exception $ex ) {
231  $this->logger->error( 'Failed to create empty session: {exception}',
232  [
233  'method' => __METHOD__,
234  'exception' => $ex,
235  ] );
236  $session = null;
237  }
238  }
239 
240  return $session;
241  }
242 
243  public function getEmptySession( WebRequest $request = null ) {
244  return $this->getEmptySessionInternal( $request );
245  }
246 
253  private function getEmptySessionInternal( WebRequest $request = null, $id = null ) {
254  if ( $id !== null ) {
255  if ( !self::validateSessionId( $id ) ) {
256  throw new \InvalidArgumentException( 'Invalid session ID' );
257  }
258 
259  $key = $this->store->makeKey( 'MWSession', $id );
260  if ( is_array( $this->store->get( $key ) ) ) {
261  throw new \InvalidArgumentException( 'Session ID already exists' );
262  }
263  }
264  if ( !$request ) {
265  $request = new FauxRequest;
266  }
267 
268  $infos = [];
269  foreach ( $this->getProviders() as $provider ) {
270  $info = $provider->newSessionInfo( $id );
271  if ( !$info ) {
272  continue;
273  }
274  if ( $info->getProvider() !== $provider ) {
275  throw new \UnexpectedValueException(
276  "$provider returned an empty session info for a different provider: $info"
277  );
278  }
279  if ( $id !== null && $info->getId() !== $id ) {
280  throw new \UnexpectedValueException(
281  "$provider returned empty session info with a wrong id: " .
282  $info->getId() . ' != ' . $id
283  );
284  }
285  if ( !$info->isIdSafe() ) {
286  throw new \UnexpectedValueException(
287  "$provider returned empty session info with id flagged unsafe"
288  );
289  }
290  $compare = $infos ? SessionInfo::compare( $infos[0], $info ) : -1;
291  if ( $compare > 0 ) {
292  continue;
293  }
294  if ( $compare === 0 ) {
295  $infos[] = $info;
296  } else {
297  $infos = [ $info ];
298  }
299  }
300 
301  // Make sure there's exactly one
302  if ( count( $infos ) > 1 ) {
303  throw new \UnexpectedValueException(
304  'Multiple empty sessions tied for top priority: ' . implode( ', ', $infos )
305  );
306  } elseif ( count( $infos ) < 1 ) {
307  throw new \UnexpectedValueException( 'No provider could provide an empty session!' );
308  }
309 
310  return $this->getSessionFromInfo( $infos[0], $request );
311  }
312 
313  public function invalidateSessionsForUser( User $user ) {
314  $user->setToken();
315  $user->saveSettings();
316 
317  foreach ( $this->getProviders() as $provider ) {
318  $provider->invalidateSessionsForUser( $user );
319  }
320  }
321 
322  public function getVaryHeaders() {
323  // @codeCoverageIgnoreStart
324  if ( defined( 'MW_NO_SESSION' ) && MW_NO_SESSION !== 'warn' ) {
325  return [];
326  }
327  // @codeCoverageIgnoreEnd
328  if ( $this->varyHeaders === null ) {
329  $headers = [];
330  foreach ( $this->getProviders() as $provider ) {
331  foreach ( $provider->getVaryHeaders() as $header => $options ) {
332  if ( !isset( $headers[$header] ) ) {
333  $headers[$header] = [];
334  }
335  if ( is_array( $options ) ) {
336  $headers[$header] = array_unique( array_merge( $headers[$header], $options ) );
337  }
338  }
339  }
340  $this->varyHeaders = $headers;
341  }
342  return $this->varyHeaders;
343  }
344 
345  public function getVaryCookies() {
346  // @codeCoverageIgnoreStart
347  if ( defined( 'MW_NO_SESSION' ) && MW_NO_SESSION !== 'warn' ) {
348  return [];
349  }
350  // @codeCoverageIgnoreEnd
351  if ( $this->varyCookies === null ) {
352  $cookies = [];
353  foreach ( $this->getProviders() as $provider ) {
354  $cookies = array_merge( $cookies, $provider->getVaryCookies() );
355  }
356  $this->varyCookies = array_values( array_unique( $cookies ) );
357  }
358  return $this->varyCookies;
359  }
360 
366  public static function validateSessionId( $id ) {
367  return is_string( $id ) && preg_match( '/^[a-zA-Z0-9_-]{32,}$/', $id );
368  }
369 
384  public function preventSessionsForUser( $username ) {
385  $this->preventUsers[$username] = true;
386 
387  // Instruct the session providers to kill any other sessions too.
388  foreach ( $this->getProviders() as $provider ) {
389  $provider->preventSessionsForUser( $username );
390  }
391  }
392 
399  public function isUserSessionPrevented( $username ) {
400  return !empty( $this->preventUsers[$username] );
401  }
402 
407  protected function getProviders() {
408  if ( $this->sessionProviders === null ) {
409  $this->sessionProviders = [];
410  foreach ( $this->config->get( 'SessionProviders' ) as $spec ) {
411  $provider = ObjectFactory::getObjectFromSpec( $spec );
412  $provider->setLogger( $this->logger );
413  $provider->setConfig( $this->config );
414  $provider->setManager( $this );
415  if ( isset( $this->sessionProviders[(string)$provider] ) ) {
416  throw new \UnexpectedValueException( "Duplicate provider name \"$provider\"" );
417  }
418  $this->sessionProviders[(string)$provider] = $provider;
419  }
420  }
422  }
423 
434  public function getProvider( $name ) {
435  $providers = $this->getProviders();
436  return $providers[$name] ?? null;
437  }
438 
443  public function shutdown() {
444  if ( $this->allSessionBackends ) {
445  $this->logger->debug( 'Saving all sessions on shutdown' );
446  if ( session_id() !== '' ) {
447  // @codeCoverageIgnoreStart
448  session_write_close();
449  }
450  // @codeCoverageIgnoreEnd
451  foreach ( $this->allSessionBackends as $backend ) {
452  $backend->shutdown();
453  }
454  }
455  }
456 
463  // Call all providers to fetch "the" session
464  $infos = [];
465  foreach ( $this->getProviders() as $provider ) {
466  $info = $provider->provideSessionInfo( $request );
467  if ( !$info ) {
468  continue;
469  }
470  if ( $info->getProvider() !== $provider ) {
471  throw new \UnexpectedValueException(
472  "$provider returned session info for a different provider: $info"
473  );
474  }
475  $infos[] = $info;
476  }
477 
478  // Sort the SessionInfos. Then find the first one that can be
479  // successfully loaded, and then all the ones after it with the same
480  // priority.
481  usort( $infos, 'MediaWiki\\Session\\SessionInfo::compare' );
482  $retInfos = [];
483  while ( $infos ) {
484  $info = array_pop( $infos );
485  if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
486  $retInfos[] = $info;
487  while ( $infos ) {
488  $info = array_pop( $infos );
489  if ( SessionInfo::compare( $retInfos[0], $info ) ) {
490  // We hit a lower priority, stop checking.
491  break;
492  }
493  if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
494  // This is going to error out below, but we want to
495  // provide a complete list.
496  $retInfos[] = $info;
497  } else {
498  // Session load failed, so unpersist it from this request
499  $info->getProvider()->unpersistSession( $request );
500  }
501  }
502  } else {
503  // Session load failed, so unpersist it from this request
504  $info->getProvider()->unpersistSession( $request );
505  }
506  }
507 
508  if ( count( $retInfos ) > 1 ) {
509  $ex = new \OverflowException(
510  'Multiple sessions for this request tied for top priority: ' . implode( ', ', $retInfos )
511  );
512  $ex->sessionInfos = $retInfos;
513  throw $ex;
514  }
515 
516  return $retInfos ? $retInfos[0] : null;
517  }
518 
527  $key = $this->store->makeKey( 'MWSession', $info->getId() );
528  $blob = $this->store->get( $key );
529 
530  // If we got data from the store and the SessionInfo says to force use,
531  // "fail" means to delete the data from the store and retry. Otherwise,
532  // "fail" is just return false.
533  if ( $info->forceUse() && $blob !== false ) {
534  $failHandler = function () use ( $key, &$info, $request ) {
535  $this->store->delete( $key );
536  return $this->loadSessionInfoFromStore( $info, $request );
537  };
538  } else {
539  $failHandler = function () {
540  return false;
541  };
542  }
543 
544  $newParams = [];
545 
546  if ( $blob !== false ) {
547  // Sanity check: blob must be an array, if it's saved at all
548  if ( !is_array( $blob ) ) {
549  $this->logger->warning( 'Session "{session}": Bad data', [
550  'session' => $info,
551  ] );
552  $this->store->delete( $key );
553  return $failHandler();
554  }
555 
556  // Sanity check: blob has data and metadata arrays
557  if ( !isset( $blob['data'] ) || !is_array( $blob['data'] ) ||
558  !isset( $blob['metadata'] ) || !is_array( $blob['metadata'] )
559  ) {
560  $this->logger->warning( 'Session "{session}": Bad data structure', [
561  'session' => $info,
562  ] );
563  $this->store->delete( $key );
564  return $failHandler();
565  }
566 
567  $data = $blob['data'];
568  $metadata = $blob['metadata'];
569 
570  // Sanity check: metadata must be an array and must contain certain
571  // keys, if it's saved at all
572  if ( !array_key_exists( 'userId', $metadata ) ||
573  !array_key_exists( 'userName', $metadata ) ||
574  !array_key_exists( 'userToken', $metadata ) ||
575  !array_key_exists( 'provider', $metadata )
576  ) {
577  $this->logger->warning( 'Session "{session}": Bad metadata', [
578  'session' => $info,
579  ] );
580  $this->store->delete( $key );
581  return $failHandler();
582  }
583 
584  // First, load the provider from metadata, or validate it against the metadata.
585  $provider = $info->getProvider();
586  if ( $provider === null ) {
587  $newParams['provider'] = $provider = $this->getProvider( $metadata['provider'] );
588  if ( !$provider ) {
589  $this->logger->warning(
590  'Session "{session}": Unknown provider ' . $metadata['provider'],
591  [
592  'session' => $info,
593  ]
594  );
595  $this->store->delete( $key );
596  return $failHandler();
597  }
598  } elseif ( $metadata['provider'] !== (string)$provider ) {
599  $this->logger->warning( 'Session "{session}": Wrong provider ' .
600  $metadata['provider'] . ' !== ' . $provider,
601  [
602  'session' => $info,
603  ] );
604  return $failHandler();
605  }
606 
607  // Load provider metadata from metadata, or validate it against the metadata
608  $providerMetadata = $info->getProviderMetadata();
609  if ( isset( $metadata['providerMetadata'] ) ) {
610  if ( $providerMetadata === null ) {
611  $newParams['metadata'] = $metadata['providerMetadata'];
612  } else {
613  try {
614  $newProviderMetadata = $provider->mergeMetadata(
615  $metadata['providerMetadata'], $providerMetadata
616  );
617  if ( $newProviderMetadata !== $providerMetadata ) {
618  $newParams['metadata'] = $newProviderMetadata;
619  }
620  } catch ( MetadataMergeException $ex ) {
621  $this->logger->warning(
622  'Session "{session}": Metadata merge failed: {exception}',
623  [
624  'session' => $info,
625  'exception' => $ex,
626  ] + $ex->getContext()
627  );
628  return $failHandler();
629  }
630  }
631  }
632 
633  // Next, load the user from metadata, or validate it against the metadata.
634  $userInfo = $info->getUserInfo();
635  if ( !$userInfo ) {
636  // For loading, id is preferred to name.
637  try {
638  if ( $metadata['userId'] ) {
639  $userInfo = UserInfo::newFromId( $metadata['userId'] );
640  } elseif ( $metadata['userName'] !== null ) { // Shouldn't happen, but just in case
641  $userInfo = UserInfo::newFromName( $metadata['userName'] );
642  } else {
643  $userInfo = UserInfo::newAnonymous();
644  }
645  } catch ( \InvalidArgumentException $ex ) {
646  $this->logger->error( 'Session "{session}": {exception}', [
647  'session' => $info,
648  'exception' => $ex,
649  ] );
650  return $failHandler();
651  }
652  $newParams['userInfo'] = $userInfo;
653  } else {
654  // User validation passes if user ID matches, or if there
655  // is no saved ID and the names match.
656  if ( $metadata['userId'] ) {
657  if ( $metadata['userId'] !== $userInfo->getId() ) {
658  $this->logger->warning(
659  'Session "{session}": User ID mismatch, {uid_a} !== {uid_b}',
660  [
661  'session' => $info,
662  'uid_a' => $metadata['userId'],
663  'uid_b' => $userInfo->getId(),
664  ] );
665  return $failHandler();
666  }
667 
668  // If the user was renamed, probably best to fail here.
669  if ( $metadata['userName'] !== null &&
670  $userInfo->getName() !== $metadata['userName']
671  ) {
672  $this->logger->warning(
673  'Session "{session}": User ID matched but name didn\'t (rename?), {uname_a} !== {uname_b}',
674  [
675  'session' => $info,
676  'uname_a' => $metadata['userName'],
677  'uname_b' => $userInfo->getName(),
678  ] );
679  return $failHandler();
680  }
681 
682  } elseif ( $metadata['userName'] !== null ) { // Shouldn't happen, but just in case
683  if ( $metadata['userName'] !== $userInfo->getName() ) {
684  $this->logger->warning(
685  'Session "{session}": User name mismatch, {uname_a} !== {uname_b}',
686  [
687  'session' => $info,
688  'uname_a' => $metadata['userName'],
689  'uname_b' => $userInfo->getName(),
690  ] );
691  return $failHandler();
692  }
693  } elseif ( !$userInfo->isAnon() ) {
694  // Metadata specifies an anonymous user, but the passed-in
695  // user isn't anonymous.
696  $this->logger->warning(
697  'Session "{session}": Metadata has an anonymous user, but a non-anon user was provided',
698  [
699  'session' => $info,
700  ] );
701  return $failHandler();
702  }
703  }
704 
705  // And if we have a token in the metadata, it must match the loaded/provided user.
706  if ( $metadata['userToken'] !== null &&
707  $userInfo->getToken() !== $metadata['userToken']
708  ) {
709  $this->logger->warning( 'Session "{session}": User token mismatch', [
710  'session' => $info,
711  ] );
712  return $failHandler();
713  }
714  if ( !$userInfo->isVerified() ) {
715  $newParams['userInfo'] = $userInfo->verified();
716  }
717 
718  if ( !empty( $metadata['remember'] ) && !$info->wasRemembered() ) {
719  $newParams['remembered'] = true;
720  }
721  if ( !empty( $metadata['forceHTTPS'] ) && !$info->forceHTTPS() ) {
722  $newParams['forceHTTPS'] = true;
723  }
724  if ( !empty( $metadata['persisted'] ) && !$info->wasPersisted() ) {
725  $newParams['persisted'] = true;
726  }
727 
728  if ( !$info->isIdSafe() ) {
729  $newParams['idIsSafe'] = true;
730  }
731  } else {
732  // No metadata, so we can't load the provider if one wasn't given.
733  if ( $info->getProvider() === null ) {
734  $this->logger->warning(
735  'Session "{session}": Null provider and no metadata',
736  [
737  'session' => $info,
738  ] );
739  return $failHandler();
740  }
741 
742  // If no user was provided and no metadata, it must be anon.
743  if ( !$info->getUserInfo() ) {
744  if ( $info->getProvider()->canChangeUser() ) {
745  $newParams['userInfo'] = UserInfo::newAnonymous();
746  } else {
747  $this->logger->info(
748  'Session "{session}": No user provided and provider cannot set user',
749  [
750  'session' => $info,
751  ] );
752  return $failHandler();
753  }
754  } elseif ( !$info->getUserInfo()->isVerified() ) {
755  // probably just a session timeout
756  $this->logger->info(
757  'Session "{session}": Unverified user provided and no metadata to auth it',
758  [
759  'session' => $info,
760  ] );
761  return $failHandler();
762  }
763 
764  $data = false;
765  $metadata = false;
766 
767  if ( !$info->getProvider()->persistsSessionId() && !$info->isIdSafe() ) {
768  // The ID doesn't come from the user, so it should be safe
769  // (and if not, nothing we can do about it anyway)
770  $newParams['idIsSafe'] = true;
771  }
772  }
773 
774  // Construct the replacement SessionInfo, if necessary
775  if ( $newParams ) {
776  $newParams['copyFrom'] = $info;
777  $info = new SessionInfo( $info->getPriority(), $newParams );
778  }
779 
780  // Allow the provider to check the loaded SessionInfo
781  $providerMetadata = $info->getProviderMetadata();
782  if ( !$info->getProvider()->refreshSessionInfo( $info, $request, $providerMetadata ) ) {
783  return $failHandler();
784  }
785  if ( $providerMetadata !== $info->getProviderMetadata() ) {
786  $info = new SessionInfo( $info->getPriority(), [
787  'metadata' => $providerMetadata,
788  'copyFrom' => $info,
789  ] );
790  }
791 
792  // Give hooks a chance to abort. Combined with the SessionMetadata
793  // hook, this can allow for tying a session to an IP address or the
794  // like.
795  $reason = 'Hook aborted';
796  if ( !\Hooks::run(
797  'SessionCheckInfo',
798  [ &$reason, $info, $request, $metadata, $data ]
799  ) ) {
800  $this->logger->warning( 'Session "{session}": ' . $reason, [
801  'session' => $info,
802  ] );
803  return $failHandler();
804  }
805 
806  return true;
807  }
808 
817  public function getSessionFromInfo( SessionInfo $info, WebRequest $request ) {
818  // @codeCoverageIgnoreStart
819  if ( defined( 'MW_NO_SESSION' ) ) {
820  if ( MW_NO_SESSION === 'warn' ) {
821  // Undocumented safety case for converting existing entry points
822  $this->logger->error( 'Sessions are supposed to be disabled for this entry point', [
823  'exception' => new \BadMethodCallException( 'Sessions are disabled for this entry point' ),
824  ] );
825  } else {
826  throw new \BadMethodCallException( 'Sessions are disabled for this entry point' );
827  }
828  }
829  // @codeCoverageIgnoreEnd
830 
831  $id = $info->getId();
832 
833  if ( !isset( $this->allSessionBackends[$id] ) ) {
834  if ( !isset( $this->allSessionIds[$id] ) ) {
835  $this->allSessionIds[$id] = new SessionId( $id );
836  }
837  $backend = new SessionBackend(
838  $this->allSessionIds[$id],
839  $info,
840  $this->store,
841  $this->logger,
842  $this->config->get( 'ObjectCacheSessionExpiry' )
843  );
844  $this->allSessionBackends[$id] = $backend;
845  $delay = $backend->delaySave();
846  } else {
847  $backend = $this->allSessionBackends[$id];
848  $delay = $backend->delaySave();
849  if ( $info->wasPersisted() ) {
850  $backend->persist();
851  }
852  if ( $info->wasRemembered() ) {
853  $backend->setRememberUser( true );
854  }
855  }
856 
857  $request->setSessionId( $backend->getSessionId() );
858  $session = $backend->getSession( $request );
859 
860  if ( !$info->isIdSafe() ) {
861  $session->resetId();
862  }
863 
864  \Wikimedia\ScopedCallback::consume( $delay );
865  return $session;
866  }
867 
873  public function deregisterSessionBackend( SessionBackend $backend ) {
874  $id = $backend->getId();
875  if ( !isset( $this->allSessionBackends[$id] ) || !isset( $this->allSessionIds[$id] ) ||
876  $this->allSessionBackends[$id] !== $backend ||
877  $this->allSessionIds[$id] !== $backend->getSessionId()
878  ) {
879  throw new \InvalidArgumentException( 'Backend was not registered with this SessionManager' );
880  }
881 
882  unset( $this->allSessionBackends[$id] );
883  // Explicitly do not unset $this->allSessionIds[$id]
884  }
885 
891  public function changeBackendId( SessionBackend $backend ) {
892  $sessionId = $backend->getSessionId();
893  $oldId = (string)$sessionId;
894  if ( !isset( $this->allSessionBackends[$oldId] ) || !isset( $this->allSessionIds[$oldId] ) ||
895  $this->allSessionBackends[$oldId] !== $backend ||
896  $this->allSessionIds[$oldId] !== $sessionId
897  ) {
898  throw new \InvalidArgumentException( 'Backend was not registered with this SessionManager' );
899  }
900 
901  $newId = $this->generateSessionId();
902 
903  unset( $this->allSessionBackends[$oldId], $this->allSessionIds[$oldId] );
904  $sessionId->setId( $newId );
905  $this->allSessionBackends[$newId] = $backend;
906  $this->allSessionIds[$newId] = $sessionId;
907  }
908 
913  public function generateSessionId() {
914  do {
915  $id = \Wikimedia\base_convert( \MWCryptRand::generateHex( 40 ), 16, 32, 32 );
916  $key = $this->store->makeKey( 'MWSession', $id );
917  } while ( isset( $this->allSessionIds[$id] ) || is_array( $this->store->get( $key ) ) );
918  return $id;
919  }
920 
927  $handler->setManager( $this, $this->store, $this->logger );
928  }
929 
934  public static function resetCache() {
935  if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
936  // @codeCoverageIgnoreStart
937  throw new MWException( __METHOD__ . ' may only be called from unit tests!' );
938  // @codeCoverageIgnoreEnd
939  }
940 
941  self::$globalSession = null;
942  self::$globalSessionRequest = null;
943  }
944 
947 }
MediaWiki\Session\SessionManager\isUserSessionPrevented
isUserSessionPrevented( $username)
Test if a user is prevented.
Definition: SessionManager.php:399
MediaWiki\Session\UserInfo\newAnonymous
static newAnonymous()
Create an instance for an anonymous (i.e.
Definition: UserInfo.php:75
MediaWiki\Session\SessionManager\getEmptySessionInternal
getEmptySessionInternal(WebRequest $request=null, $id=null)
Definition: SessionManager.php:253
$user
return true to allow those checks to and false if checking is done & $user
Definition: hooks.txt:1476
FauxRequest
WebRequest clone which takes values from a provided array.
Definition: FauxRequest.php:33
MediaWiki\Session\SessionInfo\forceHTTPS
forceHTTPS()
Whether this session should only be used over HTTPS.
Definition: SessionInfo.php:277
MediaWiki\Session\SessionManager\loadSessionInfoFromStore
loadSessionInfoFromStore(SessionInfo &$info, WebRequest $request)
Load and verify the session info against the store.
Definition: SessionManager.php:526
MW_NO_SESSION
const MW_NO_SESSION
Definition: load.php:29
false
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:187
MediaWiki\Session\SessionManager\generateSessionId
generateSessionId()
Generate a new random session ID.
Definition: SessionManager.php:913
MediaWiki\Session\SessionManager\getVaryCookies
getVaryCookies()
Return the list of cookies that need varying on.
Definition: SessionManager.php:345
MediaWiki\Session\SessionManager\$globalSessionRequest
static WebRequest null $globalSessionRequest
Definition: SessionManager.php:58
MediaWiki\Session\SessionManager\getProviders
getProviders()
Get the available SessionProviders.
Definition: SessionManager.php:407
captcha-old.count
count
Definition: captcha-old.py:249
MediaWiki\Session\SessionBackend\getId
getId()
Returns the session ID.
Definition: SessionBackend.php:224
MediaWiki\Session\SessionManager\setupPHPSessionHandler
setupPHPSessionHandler(PHPSessionHandler $handler)
Call setters on a PHPSessionHandler.
Definition: SessionManager.php:926
MediaWiki\Session\SessionInfo\compare
static compare( $a, $b)
Compare two SessionInfo objects by priority.
Definition: SessionInfo.php:293
MediaWiki\Session\SessionManager\$varyHeaders
array $varyHeaders
Definition: SessionManager.php:76
MediaWiki\Session\SessionManager\preventSessionsForUser
preventSessionsForUser( $username)
Prevent future sessions for the user.
Definition: SessionManager.php:384
MediaWiki\Session\SessionManager\$instance
static SessionManager null $instance
Definition: SessionManager.php:52
MediaWiki\Session\MetadataMergeException
Subclass of UnexpectedValueException that can be annotated with additional data for debug logging.
Definition: MetadataMergeException.php:35
MediaWiki\Session\SessionManager\getSessionById
getSessionById( $id, $create=false, WebRequest $request=null)
Fetch a session by ID.
Definition: SessionManager.php:201
MediaWiki\Session\PHPSessionHandler\isEnabled
static isEnabled()
Test whether the handler is installed and enabled.
Definition: PHPSessionHandler.php:102
MediaWiki\Session\SessionInfo\getPriority
getPriority()
Return the priority.
Definition: SessionInfo.php:226
MediaWiki\Session\SessionInfo\getId
getId()
Return the session ID.
Definition: SessionInfo.php:187
MediaWiki\Session\SessionManager\$allSessionBackends
SessionBackend[] $allSessionBackends
Definition: SessionManager.php:79
MediaWiki\Session\SessionInfo\forceUse
forceUse()
Force use of this SessionInfo if validation fails.
Definition: SessionInfo.php:218
BagOStuff
Class representing a cache/ephemeral data store.
Definition: BagOStuff.php:58
User
User
Definition: All_system_messages.txt:425
php
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:35
MediaWiki\Session\MetadataMergeException\getContext
getContext()
Get context data.
Definition: MetadataMergeException.php:59
Config
Interface for configuration instances.
Definition: Config.php:28
$data
$data
Utility to generate mapping file used in mw.Title (phpCharToUpper.json)
Definition: generatePhpCharToUpperMappings.php:13
MWException
MediaWiki exception.
Definition: MWException.php:26
MediaWiki\Session\SessionManager\$config
Config $config
Definition: SessionManager.php:64
MediaWiki\Session\SessionManager\deregisterSessionBackend
deregisterSessionBackend(SessionBackend $backend)
Deregister a SessionBackend.
Definition: SessionManager.php:873
MediaWiki\Session\SessionManager\validateSessionId
static validateSessionId( $id)
Validate a session ID.
Definition: SessionManager.php:366
MediaWiki\Session\Session
Manages data for an an authenticated session.
Definition: Session.php:48
MediaWiki\Session\SessionProvider
A SessionProvider provides SessionInfo and support for Session.
Definition: SessionProvider.php:78
MediaWiki\Session\SessionInfo\getProvider
getProvider()
Return the provider.
Definition: SessionInfo.php:179
$blob
$blob
Definition: testCompression.php:65
$handler
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 it can be in the form of< username >< more info > e g for bot passwords intended to be added to log contexts Fields it might only if the login was with a bot password it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable modifiable after all normalizations have been except for the $wgMaxImageArea check set to true or false to override the $wgMaxImageArea check result gives extension the possibility to transform it themselves $handler
Definition: hooks.txt:780
MediaWiki\Session\SessionManager\invalidateSessionsForUser
invalidateSessionsForUser(User $user)
Invalidate sessions for a user.
Definition: SessionManager.php:313
MediaWiki\Session\SessionManager\$allSessionIds
SessionId[] $allSessionIds
Definition: SessionManager.php:82
MediaWiki
A helper class for throttling authentication attempts.
MediaWiki\Session\SessionManager\$globalSession
static Session null $globalSession
Definition: SessionManager.php:55
ObjectCache\getInstance
static getInstance( $id)
Get a cached instance of the specified type of cache object.
Definition: ObjectCache.php:92
MediaWiki\Session\SessionManager\singleton
static singleton()
Get the global SessionManager.
Definition: SessionManager.php:92
use
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
Definition: MIT-LICENSE.txt:10
MediaWiki\Session\SessionManager\shutdown
shutdown()
Save all active sessions on shutdown.
Definition: SessionManager.php:443
MediaWiki\Session
Definition: BotPasswordSessionProvider.php:24
MediaWiki\Session\SessionInfo\wasPersisted
wasPersisted()
Return whether the session is persisted.
Definition: SessionInfo.php:242
array
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))
MediaWiki\Session\SessionManager\resetCache
static resetCache()
Reset the internal caching for unit testing.
Definition: SessionManager.php:934
string
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:175
MediaWiki\Session\SessionManager\getVaryHeaders
getVaryHeaders()
Return the HTTP headers that need varying on.
Definition: SessionManager.php:322
MediaWiki\Session\SessionInfo\getProviderMetadata
getProviderMetadata()
Return provider metadata.
Definition: SessionInfo.php:250
null
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:780
MediaWiki\Session\PHPSessionHandler
Adapter for PHP's session handling.
Definition: PHPSessionHandler.php:34
$request
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:2644
$name
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:271
MediaWiki\Session\SessionManager\$sessionProviders
SessionProvider[] $sessionProviders
Definition: SessionManager.php:70
MediaWiki\MediaWikiServices\getInstance
static getInstance()
Returns the global default instance of the top level service locator.
Definition: MediaWikiServices.php:124
MediaWiki\Session\SessionManager\getGlobalSession
static getGlobalSession()
Get the "global" session.
Definition: SessionManager.php:107
MediaWiki\Session\SessionManager\getSessionInfoForRequest
getSessionInfoForRequest(WebRequest $request)
Fetch the SessionInfo(s) for a request.
Definition: SessionManager.php:462
MediaWiki\Session\SessionBackend\getSessionId
getSessionId()
Fetch the SessionId object.
Definition: SessionBackend.php:233
MediaWiki\Session\SessionManager\setLogger
setLogger(LoggerInterface $logger)
Definition: SessionManager.php:186
MediaWiki\Session\SessionManager\getEmptySession
getEmptySession(WebRequest $request=null)
Create a new, empty session.
Definition: SessionManager.php:243
$header
$header
Definition: updateCredits.php:41
MediaWiki\Session\UserInfo\newFromName
static newFromName( $name, $verified=false)
Create an instance for a logged-in user by name.
Definition: UserInfo.php:103
MediaWiki\Session\SessionManager
This serves as the entry point to the MediaWiki session handling system.
Definition: SessionManager.php:50
CachedBagOStuff
Wrapper around a BagOStuff that caches data in memory.
Definition: CachedBagOStuff.php:37
MediaWiki\Session\SessionManager\$store
CachedBagOStuff null $store
Definition: SessionManager.php:67
MediaWiki\Session\SessionManager\$preventUsers
string[] $preventUsers
Definition: SessionManager.php:85
MWCryptRand\generateHex
static generateHex( $chars)
Generate a run of cryptographically random data and return it in hexadecimal string format.
Definition: MWCryptRand.php:74
RequestContext\getMain
static getMain()
Get the RequestContext object associated with the main request.
Definition: RequestContext.php:430
WebRequest
The WebRequest class encapsulates getting at data passed in the URL or via a POSTed form stripping il...
Definition: WebRequest.php:41
MediaWiki\Session\SessionManager\getSessionFromInfo
getSessionFromInfo(SessionInfo $info, WebRequest $request)
Create a Session corresponding to the passed SessionInfo.
Definition: SessionManager.php:817
MediaWiki\Session\SessionInfo
Value object returned by SessionProvider.
Definition: SessionInfo.php:34
MediaWiki\Session\SessionManagerInterface
This exists to make IDEs happy, so they don't see the internal-but-required-to-be-public methods on S...
Definition: SessionManagerInterface.php:37
$options
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped & $options
Definition: hooks.txt:1993
MediaWiki\Session\SessionBackend\delaySave
delaySave()
Delay automatic saving while multiple updates are being made.
Definition: SessionBackend.php:612
MediaWiki\Session\SessionId
Value object holding the session ID in a manner that can be globally updated.
Definition: SessionId.php:38
MediaWiki\Session\UserInfo\newFromId
static newFromId( $id, $verified=false)
Create an instance for a logged-in user by ID.
Definition: UserInfo.php:85
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 as
Definition: distributors.txt:9
MediaWikiServices
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 MediaWikiServices
Definition: injection.txt:23
MediaWiki\Session\SessionManager\getProvider
getProvider( $name)
Get a session provider by name.
Definition: SessionManager.php:434
MediaWiki\Session\SessionManager\changeBackendId
changeBackendId(SessionBackend $backend)
Change a SessionBackend's ID.
Definition: SessionManager.php:891
User
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition: User.php:48
MediaWiki\Session\SessionInfo\MIN_PRIORITY
const MIN_PRIORITY
Minimum allowed priority.
Definition: SessionInfo.php:36
Hooks\run
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:200
$username
this hook is for auditing only or null if authentication failed before getting that far $username
Definition: hooks.txt:780
MediaWiki\Session\SessionManager\getSessionForRequest
getSessionForRequest(WebRequest $request)
Fetch the session for a request (or a new empty session if none is attached to it)
Definition: SessionManager.php:190
MediaWiki\Session\SessionManager\$logger
LoggerInterface $logger
Definition: SessionManager.php:61
MediaWiki\Session\SessionManager\$varyCookies
string[] $varyCookies
Definition: SessionManager.php:73
MediaWiki\Session\SessionInfo\getUserInfo
getUserInfo()
Return the user.
Definition: SessionInfo.php:234
MediaWiki\Session\SessionInfo\wasRemembered
wasRemembered()
Return whether the user was remembered.
Definition: SessionInfo.php:269
MediaWiki\Session\SessionInfo\isIdSafe
isIdSafe()
Indicate whether the ID is "safe".
Definition: SessionInfo.php:203
MediaWiki\Session\SessionManager\__construct
__construct( $options=[])
Definition: SessionManager.php:148
MediaWiki\Session\SessionBackend
This is the actual workhorse for Session.
Definition: SessionBackend.php:49