MediaWiki  master
SessionProvider.php
Go to the documentation of this file.
1 <?php
24 namespace MediaWiki\Session;
25 
28 use Config;
30 use User;
32 
78 abstract class SessionProvider implements SessionProviderInterface, LoggerAwareInterface {
79 
81  protected $logger;
82 
84  protected $config;
85 
87  protected $manager;
88 
92  protected $priority;
93 
100  public function __construct() {
101  $this->priority = SessionInfo::MIN_PRIORITY + 10;
102  }
103 
104  public function setLogger( LoggerInterface $logger ) {
105  $this->logger = $logger;
106  }
107 
112  public function setConfig( Config $config ) {
113  $this->config = $config;
114  }
115 
120  public function setManager( SessionManager $manager ) {
121  $this->manager = $manager;
122  }
123 
128  public function getManager() {
129  return $this->manager;
130  }
131 
154  abstract public function provideSessionInfo( WebRequest $request );
155 
169  public function newSessionInfo( $id = null ) {
170  if ( $this->canChangeUser() && $this->persistsSessionId() ) {
171  return new SessionInfo( $this->priority, [
172  'id' => $id,
173  'provider' => $this,
174  'persisted' => false,
175  'idIsSafe' => true,
176  ] );
177  }
178  return null;
179  }
180 
202  public function mergeMetadata( array $savedMetadata, array $providedMetadata ) {
203  foreach ( $providedMetadata as $k => $v ) {
204  if ( array_key_exists( $k, $savedMetadata ) && $savedMetadata[$k] !== $v ) {
205  $e = new MetadataMergeException( "Key \"$k\" changed" );
206  $e->setContext( [
207  'old_value' => $savedMetadata[$k],
208  'new_value' => $v,
209  ] );
210  throw $e;
211  }
212  }
213  return $providedMetadata;
214  }
215 
229  public function refreshSessionInfo( SessionInfo $info, WebRequest $request, &$metadata ) {
230  return true;
231  }
232 
259  abstract public function persistsSessionId();
260 
286  abstract public function canChangeUser();
287 
294  public function getRememberUserDuration() {
295  return null;
296  }
297 
308  public function sessionIdWasReset( SessionBackend $session, $oldId ) {
309  }
310 
338  abstract public function persistSession( SessionBackend $session, WebRequest $request );
339 
351  abstract public function unpersistSession( WebRequest $request );
352 
374  public function preventSessionsForUser( $username ) {
375  if ( !$this->canChangeUser() ) {
376  throw new \BadMethodCallException(
377  __METHOD__ . ' must be implemented when canChangeUser() is false'
378  );
379  }
380  }
381 
392  public function invalidateSessionsForUser( User $user ) {
393  }
394 
408  public function getVaryHeaders() {
409  return [];
410  }
411 
417  public function getVaryCookies() {
418  return [];
419  }
420 
427  public function suggestLoginUsername( WebRequest $request ) {
428  return null;
429  }
430 
441  public function getAllowedUserRights( SessionBackend $backend ) {
442  if ( $backend->getProvider() !== $this ) {
443  // Not that this should ever happen...
444  throw new \InvalidArgumentException( 'Backend\'s provider isn\'t $this' );
445  }
446 
447  return null;
448  }
449 
457  public function __toString() {
458  return static::class;
459  }
460 
476  protected function describeMessage() {
477  return wfMessage(
478  'sessionprovider-' . str_replace( '\\', '-', strtolower( static::class ) )
479  );
480  }
481 
482  public function describe( Language $lang ) {
483  $msg = $this->describeMessage();
484  $msg->inLanguage( $lang );
485  if ( $msg->isDisabled() ) {
486  $msg = wfMessage( 'sessionprovider-generic', (string)$this )->inLanguage( $lang );
487  }
488  return $msg->plain();
489  }
490 
491  public function whyNoSession() {
492  return null;
493  }
494 
508  final protected function hashToSessionId( $data, $key = null ) {
509  if ( !is_string( $data ) ) {
510  throw new \InvalidArgumentException(
511  '$data must be a string, ' . gettype( $data ) . ' was passed'
512  );
513  }
514  if ( $key !== null && !is_string( $key ) ) {
515  throw new \InvalidArgumentException(
516  '$key must be a string or null, ' . gettype( $key ) . ' was passed'
517  );
518  }
519 
520  $hash = \MWCryptHash::hmac( "$this\n$data", $key ?: $this->config->get( 'SecretKey' ), false );
521  if ( strlen( $hash ) < 32 ) {
522  // Should never happen, even md5 is 128 bits
523  // @codeCoverageIgnoreStart
524  throw new \UnexpectedValueException( 'Hash function returned less than 128 bits' );
525  // @codeCoverageIgnoreEnd
526  }
527  if ( strlen( $hash ) >= 40 ) {
528  $hash = \Wikimedia\base_convert( $hash, 16, 32, 32 );
529  }
530  return substr( $hash, -32 );
531  }
532 
533 }
const MIN_PRIORITY
Minimum allowed priority.
Definition: SessionInfo.php:36
describe(Language $lang)
Return an identifier for this session type.
persistSession(SessionBackend $session, WebRequest $request)
Persist a session into a request/response.
This is the actual workhorse for Session.
getProvider()
Fetch the SessionProvider for this session.
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:187
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2159
unpersistSession(WebRequest $request)
Remove any persisted session from a request/response.
if(!isset( $args[0])) $lang
Subclass of UnexpectedValueException that can be annotated with additional data for debug logging...
canChangeUser()
Indicate whether the user associated with the request can be changed.
The User object encapsulates all of the user-specific settings (user_id, name, rights, email address, options, last login time).
Definition: User.php:51
setManager(SessionManager $manager)
Set the session manager.
getVaryCookies()
Return the list of cookies that need varying on.
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation use $formDescriptor instead default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message additional optional elements are parameters for the key that are processed with wfMessage() -> params() ->parseAsBlock() - offset Set to overwrite offset parameter in $wgRequest set to '' to unset offset - wrap String Wrap the message in html(usually something like "&lt
Interface for configuration instances.
Definition: Config.php:28
persistsSessionId()
Indicate whether self::persistSession() can save arbitrary session IDs.
suggestLoginUsername(WebRequest $request)
Get a suggested username for the login form.
getManager()
Get the session manager.
setLogger(LoggerInterface $logger)
A SessionProvider provides SessionInfo and support for Session.
This exists to make IDEs happy, so they don&#39;t see the internal-but-required-to-be-public methods on S...
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
setConfig(Config $config)
Set configuration.
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
whyNoSession()
Return a Message for why sessions might not be being persisted.
provideSessionInfo(WebRequest $request)
Provide session info for a request.
hashToSessionId( $data, $key=null)
Hash data as a session ID.
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
this hook is for auditing only or null if authentication failed before getting that far $username
Definition: hooks.txt:780
getRememberUserDuration()
Returns the duration (in seconds) for which users will be remembered when Session::setRememberUser() ...
you have access to all of the normal MediaWiki so you can get a DB use the etc For full docs on the Maintenance class
Definition: maintenance.txt:52
preventSessionsForUser( $username)
Prevent future sessions for the user.
mergeMetadata(array $savedMetadata, array $providedMetadata)
Merge saved session provider metadata.
sessionIdWasReset(SessionBackend $session, $oldId)
Notification that the session ID was reset.
describeMessage()
Return a Message identifying this session type.
getVaryHeaders()
Return the HTTP headers that need varying on.
getAllowedUserRights(SessionBackend $backend)
Fetch the rights allowed the user when the specified session is active.
This serves as the entry point to the MediaWiki session handling system.
static hmac( $data, $key, $raw=true)
Generate an acceptably unstable one-way-hmac of some text making use of the best hash algorithm that ...
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:2633
invalidateSessionsForUser(User $user)
Invalidate existing sessions for a user.
refreshSessionInfo(SessionInfo $info, WebRequest $request, &$metadata)
Validate a loaded SessionInfo and refresh provider metadata.
return true to allow those checks to and false if checking is done & $user
Definition: hooks.txt:1473
Value object returned by SessionProvider.
Definition: SessionInfo.php:34
newSessionInfo( $id=null)
Provide session info for a new, empty session.