MediaWiki  1.27.1
RequestContext.php
Go to the documentation of this file.
1 <?php
28 
36  private $request;
37 
41  private $title;
42 
46  private $wikipage;
47 
51  private $output;
52 
56  private $user;
57 
61  private $lang;
62 
66  private $skin;
67 
71  private $timing;
72 
76  private $config;
77 
81  private static $instance = null;
82 
88  public function setConfig( Config $c ) {
89  $this->config = $c;
90  }
91 
97  public function getConfig() {
98  if ( $this->config === null ) {
99  // @todo In the future, we could move this to WebStart.php so
100  // the Config object is ready for when initialization happens
101  $this->config = ConfigFactory::getDefaultInstance()->makeConfig( 'main' );
102  }
103 
104  return $this->config;
105  }
106 
112  public function setRequest( WebRequest $r ) {
113  $this->request = $r;
114  }
115 
121  public function getRequest() {
122  if ( $this->request === null ) {
124  // create the WebRequest object on the fly
125  if ( $wgCommandLineMode ) {
126  $this->request = new FauxRequest( [] );
127  } else {
128  $this->request = new WebRequest();
129  }
130  }
131 
132  return $this->request;
133  }
134 
142  public function getStats() {
143  return MediaWikiServices::getInstance()->getStatsdDataFactory();
144  }
145 
151  public function getTiming() {
152  if ( $this->timing === null ) {
153  $this->timing = new Timing( [
154  'logger' => LoggerFactory::getInstance( 'Timing' )
155  ] );
156  }
157  return $this->timing;
158  }
159 
165  public function setTitle( Title $title = null ) {
166  $this->title = $title;
167  // Erase the WikiPage so a new one with the new title gets created.
168  $this->wikipage = null;
169  }
170 
176  public function getTitle() {
177  if ( $this->title === null ) {
178  global $wgTitle; # fallback to $wg till we can improve this
179  $this->title = $wgTitle;
180  wfDebugLog(
181  'GlobalTitleFail',
182  __METHOD__ . ' called by ' . wfGetAllCallers( 5 ) . ' with no title set.'
183  );
184  }
185 
186  return $this->title;
187  }
188 
195  public function hasTitle() {
196  return $this->title !== null;
197  }
198 
207  public function canUseWikiPage() {
208  if ( $this->wikipage ) {
209  // If there's a WikiPage object set, we can for sure get it
210  return true;
211  }
212  // Only pages with legitimate titles can have WikiPages.
213  // That usually means pages in non-virtual namespaces.
214  $title = $this->getTitle();
215  return $title ? $title->canExist() : false;
216  }
217 
224  public function setWikiPage( WikiPage $p ) {
225  $pageTitle = $p->getTitle();
226  if ( !$this->hasTitle() || !$pageTitle->equals( $this->getTitle() ) ) {
227  $this->setTitle( $pageTitle );
228  }
229  // Defer this to the end since setTitle sets it to null.
230  $this->wikipage = $p;
231  }
232 
243  public function getWikiPage() {
244  if ( $this->wikipage === null ) {
245  $title = $this->getTitle();
246  if ( $title === null ) {
247  throw new MWException( __METHOD__ . ' called without Title object set' );
248  }
249  $this->wikipage = WikiPage::factory( $title );
250  }
251 
252  return $this->wikipage;
253  }
254 
258  public function setOutput( OutputPage $o ) {
259  $this->output = $o;
260  }
261 
267  public function getOutput() {
268  if ( $this->output === null ) {
269  $this->output = new OutputPage( $this );
270  }
271 
272  return $this->output;
273  }
274 
280  public function setUser( User $u ) {
281  $this->user = $u;
282  }
283 
289  public function getUser() {
290  if ( $this->user === null ) {
291  $this->user = User::newFromSession( $this->getRequest() );
292  }
293 
294  return $this->user;
295  }
296 
303  public static function sanitizeLangCode( $code ) {
305 
306  // BCP 47 - letter case MUST NOT carry meaning
307  $code = strtolower( $code );
308 
309  # Validate $code
310  if ( !$code || !Language::isValidCode( $code ) || $code === 'qqq' ) {
311  wfDebug( "Invalid user language code\n" );
313  }
314 
315  return $code;
316  }
317 
325  public function setLanguage( $l ) {
326  if ( $l instanceof Language ) {
327  $this->lang = $l;
328  } elseif ( is_string( $l ) ) {
329  $l = self::sanitizeLangCode( $l );
330  $obj = Language::factory( $l );
331  $this->lang = $obj;
332  } else {
333  throw new MWException( __METHOD__ . " was passed an invalid type of data." );
334  }
335  }
336 
344  public function getLanguage() {
345  if ( isset( $this->recursion ) ) {
346  trigger_error( "Recursion detected in " . __METHOD__, E_USER_WARNING );
347  $e = new Exception;
348  wfDebugLog( 'recursion-guard', "Recursion detected:\n" . $e->getTraceAsString() );
349 
350  $code = $this->getConfig()->get( 'LanguageCode' ) ?: 'en';
351  $this->lang = Language::factory( $code );
352  } elseif ( $this->lang === null ) {
353  $this->recursion = true;
354 
356 
357  try {
358  $request = $this->getRequest();
359  $user = $this->getUser();
360 
361  $code = $request->getVal( 'uselang', 'user' );
362  if ( $code === 'user' ) {
363  $code = $user->getOption( 'language' );
364  }
365  $code = self::sanitizeLangCode( $code );
366 
367  Hooks::run( 'UserGetLanguageObject', [ $user, &$code, $this ] );
368 
369  if ( $code === $this->getConfig()->get( 'LanguageCode' ) ) {
370  $this->lang = $wgContLang;
371  } else {
372  $obj = Language::factory( $code );
373  $this->lang = $obj;
374  }
375 
376  unset( $this->recursion );
377  }
378  catch ( Exception $ex ) {
379  unset( $this->recursion );
380  throw $ex;
381  }
382  }
383 
384  return $this->lang;
385  }
386 
392  public function setSkin( Skin $s ) {
393  $this->skin = clone $s;
394  $this->skin->setContext( $this );
395  }
396 
402  public function getSkin() {
403  if ( $this->skin === null ) {
404  $skin = null;
405  Hooks::run( 'RequestContextCreateSkin', [ $this, &$skin ] );
407 
408  // If the hook worked try to set a skin from it
409  if ( $skin instanceof Skin ) {
410  $this->skin = $skin;
411  } elseif ( is_string( $skin ) ) {
412  // Normalize the key, just in case the hook did something weird.
413  $normalized = Skin::normalizeKey( $skin );
414  $this->skin = $factory->makeSkin( $normalized );
415  }
416 
417  // If this is still null (the hook didn't run or didn't work)
418  // then go through the normal processing to load a skin
419  if ( $this->skin === null ) {
420  if ( !in_array( 'skin', $this->getConfig()->get( 'HiddenPrefs' ) ) ) {
421  # get the user skin
422  $userSkin = $this->getUser()->getOption( 'skin' );
423  $userSkin = $this->getRequest()->getVal( 'useskin', $userSkin );
424  } else {
425  # if we're not allowing users to override, then use the default
426  $userSkin = $this->getConfig()->get( 'DefaultSkin' );
427  }
428 
429  // Normalize the key in case the user is passing gibberish
430  // or has old preferences (bug 69566).
431  $normalized = Skin::normalizeKey( $userSkin );
432 
433  // Skin::normalizeKey will also validate it, so
434  // this won't throw an exception
435  $this->skin = $factory->makeSkin( $normalized );
436  }
437 
438  // After all that set a context on whatever skin got created
439  $this->skin->setContext( $this );
440  }
441 
442  return $this->skin;
443  }
444 
454  public function msg() {
455  $args = func_get_args();
456 
457  return call_user_func_array( 'wfMessage', $args )->setContext( $this );
458  }
459 
467  public static function getMain() {
468  if ( self::$instance === null ) {
469  self::$instance = new self;
470  }
471 
472  return self::$instance;
473  }
474 
483  public static function getMainAndWarn( $func = __METHOD__ ) {
484  wfDebug( $func . ' called without context. ' .
485  "Using RequestContext::getMain() for sanity\n" );
486 
487  return self::getMain();
488  }
489 
493  public static function resetMain() {
494  if ( !( defined( 'MW_PHPUNIT_TEST' ) || defined( 'MW_PARSER_TEST' ) ) ) {
495  throw new MWException( __METHOD__ . '() should be called only from unit tests!' );
496  }
497  self::$instance = null;
498  }
499 
507  public function exportSession() {
509  return [
510  'ip' => $this->getRequest()->getIP(),
511  'headers' => $this->getRequest()->getAllHeaders(),
512  'sessionId' => $session->isPersistent() ? $session->getId() : '',
513  'userId' => $this->getUser()->getId()
514  ];
515  }
516 
539  public static function importScopedSession( array $params ) {
540  if ( strlen( $params['sessionId'] ) &&
541  MediaWiki\Session\SessionManager::getGlobalSession()->isPersistent()
542  ) {
543  // Sanity check to avoid sending random cookies for the wrong users.
544  // This method should only called by CLI scripts or by HTTP job runners.
545  throw new MWException( "Sessions can only be imported when none is active." );
546  } elseif ( !IP::isValid( $params['ip'] ) ) {
547  throw new MWException( "Invalid client IP address '{$params['ip']}'." );
548  }
549 
550  if ( $params['userId'] ) { // logged-in user
551  $user = User::newFromId( $params['userId'] );
552  $user->load();
553  if ( !$user->getId() ) {
554  throw new MWException( "No user with ID '{$params['userId']}'." );
555  }
556  } else { // anon user
557  $user = User::newFromName( $params['ip'], false );
558  }
559 
560  $importSessionFunc = function ( User $user, array $params ) {
562 
564 
565  // Commit and close any current session
566  if ( MediaWiki\Session\PHPSessionHandler::isEnabled() ) {
567  session_write_close(); // persist
568  session_id( '' ); // detach
569  $_SESSION = []; // clear in-memory array
570  }
571 
572  // Get new session, if applicable
573  $session = null;
574  if ( strlen( $params['sessionId'] ) ) { // don't make a new random ID
576  $session = $manager->getSessionById( $params['sessionId'], true )
577  ?: $manager->getEmptySession();
578  }
579 
580  // Remove any user IP or agent information, and attach the request
581  // with the new session.
582  $context->setRequest( new FauxRequest( [], false, $session ) );
583  $wgRequest = $context->getRequest(); // b/c
584 
585  // Now that all private information is detached from the user, it should
586  // be safe to load the new user. If errors occur or an exception is thrown
587  // and caught (leaving the main context in a mixed state), there is no risk
588  // of the User object being attached to the wrong IP, headers, or session.
589  $context->setUser( $user );
590  $wgUser = $context->getUser(); // b/c
591  if ( $session && MediaWiki\Session\PHPSessionHandler::isEnabled() ) {
592  session_id( $session->getId() );
593  MediaWiki\quietCall( 'session_start' );
594  }
595  $request = new FauxRequest( [], false, $session );
596  $request->setIP( $params['ip'] );
597  foreach ( $params['headers'] as $name => $value ) {
598  $request->setHeader( $name, $value );
599  }
600  // Set the current context to use the new WebRequest
601  $context->setRequest( $request );
602  $wgRequest = $context->getRequest(); // b/c
603  };
604 
605  // Stash the old session and load in the new one
606  $oUser = self::getMain()->getUser();
607  $oParams = self::getMain()->exportSession();
608  $oRequest = self::getMain()->getRequest();
609  $importSessionFunc( $user, $params );
610 
611  // Set callback to save and close the new session and reload the old one
612  return new ScopedCallback(
613  function () use ( $importSessionFunc, $oUser, $oParams, $oRequest ) {
615  $importSessionFunc( $oUser, $oParams );
616  // Restore the exact previous Request object (instead of leaving FauxRequest)
617  RequestContext::getMain()->setRequest( $oRequest );
618  $wgRequest = RequestContext::getMain()->getRequest(); // b/c
619  }
620  );
621  }
622 
637  public static function newExtraneousContext( Title $title, $request = [] ) {
638  $context = new self;
639  $context->setTitle( $title );
640  if ( $request instanceof WebRequest ) {
641  $context->setRequest( $request );
642  } else {
643  $context->setRequest( new FauxRequest( $request ) );
644  }
645  $context->user = User::newFromName( '127.0.0.1', false );
646 
647  return $context;
648  }
649 }
static newFromName($name, $validate= 'valid')
Static factory method for creation from username.
Definition: User.php:568
static factory(Title $title)
Create a WikiPage object of the appropriate class for the given title.
Definition: WikiPage.php:99
setContext(IContextSource $context)
Set the IContextSource object.
setWikiPage(WikiPage $p)
Set the WikiPage object.
Interface for objects which can provide a MediaWiki context on request.
the array() calling protocol came about after MediaWiki 1.4rc1.
getTiming()
Get the timing object.
getConfig()
Get the Config object.
The main skin class which provides methods and properties for all other skins.
Definition: Skin.php:34
setRequest(WebRequest $r)
Set the WebRequest object.
Group all the pieces relevant to the context of a request into one instance.
$context
Definition: load.php:44
load($flags=self::READ_NORMAL)
Load the user table data for this object from the source given by mFrom.
Definition: User.php:362
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:1932
$value
static newFromId($id)
Static factory method for creation from a given user ID.
Definition: User.php:591
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
A helper class for throttling authentication attempts.
Represents a title within MediaWiki.
Definition: Title.php:34
when a variable name is used in a it is silently declared as a new local masking the global
Definition: design.txt:93
exportSession()
Export the resolved user IP, HTTP headers, user ID, and session ID.
wfDebug($text, $dest= 'all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
static importScopedSession(array $params)
Import an client IP address, HTTP headers, user ID, and session ID.
static sanitizeLangCode($code)
Accepts a language code and ensures it's sane.
if($line===false) $args
Definition: cdb.php:64
$factory
$wgLanguageCode
Site language code.
Class for asserting that a callback happens when an dummy object leaves scope.
wfDebugLog($logGroup, $text, $dest= 'all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not...
global $wgCommandLineMode
Definition: Setup.php:513
getSkin()
Get the Skin object.
static getMain()
Static methods.
static isValid($ip)
Validate an IP address.
Definition: IP.php:113
getUser()
Get the User object.
canExist()
Is this in a namespace that allows actual pages?
Definition: Title.php:1027
canUseWikiPage()
Check whether a WikiPage object can be get with getWikiPage().
getTitle()
Get the Title object.
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.
Definition: distributors.txt:9
static isValidCode($code)
Returns true if a language code string is of a valid form, whether or not it exists.
Definition: Language.php:333
$params
getTitle()
Get the title object of the article.
Definition: WikiPage.php:217
static resetMain()
Resets singleton returned by getMain().
OutputPage $output
static newExtraneousContext(Title $title, $request=[])
Create a new extraneous context.
setOutput(OutputPage $o)
hasTitle()
Check, if a Title object is set.
setTitle(Title $title=null)
Set the Title object.
An interface to help developers measure the performance of their applications.
Definition: Timing.php:45
title
static run($event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:131
getOutput()
Get the OutputPage object.
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
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub 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 & $code
Definition: hooks.txt:762
This class should be covered by a general architecture document which does not exist as of January 20...
Definition: OutputPage.php:42
getWikiPage()
Get the WikiPage object.
static singleton()
Get the global SessionManager.
static normalizeKey($key)
Normalize a skin preference value to a form that can be loaded.
Definition: Skin.php:93
setLanguage($l)
Set the Language object.
setConfig(Config $c)
Set the Config object.
getOption($oname, $defaultOverride=null, $ignoreHidden=false)
Get the user's current setting for a given option.
Definition: User.php:2748
getVal($name, $default=null)
Fetch a scalar from the input or return $default if it's not set.
Definition: WebRequest.php:404
static getDefaultInstance()
Class representing a MediaWiki article and history.
Definition: WikiPage.php:29
wfGetAllCallers($limit=3)
Return a string consisting of callers in the stack.
static getGlobalSession()
Get the "global" session.
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
setUser(User $u)
Set the User object.
getId()
Get the user's ID.
Definition: User.php:2063
WikiPage $wikipage
getStats()
Get the Stats object.
msg()
Helpful methods.
getRequest()
Get the WebRequest object.
static newFromSession(WebRequest $request=null)
Create a new user object using data from session.
Definition: User.php:634
static getMainAndWarn($func=__METHOD__)
Get the RequestContext object associated with the main request and gives a warning to the log...
this class mediates it Skin Encapsulates a look and feel for the wiki All of the functions that render HTML and make choices about how to render it are here and are called from various other places when and is meant to be subclassed with other skins that may override some of its functions The User object contains a reference to a and so rather than having a global skin object we just rely on the global User and get the skin with $wgUser and also has some character encoding functions and other locale stuff The current user interface language is instantiated as and the local content language as $wgContLang
Definition: design.txt:56
MediaWiki Logger LoggerFactory implements a PSR[0] compatible message logging system Named Psr Log LoggerInterface instances can be obtained from the MediaWiki Logger LoggerFactory::getInstance() static method.MediaWiki\Logger\LoggerFactory expects a class implementing the MediaWiki\Logger\Spi interface to act as a factory for new Psr\Log\LoggerInterface instances.The"Spi"in MediaWiki\Logger\Spi stands for"service provider interface".An SPI is an API intended to be implemented or extended by a third party.This software design pattern is intended to enable framework extension and replaceable components.It is specifically used in the MediaWiki\Logger\LoggerFactory service to allow alternate PSR-3 logging implementations to be easily integrated with MediaWiki.The service provider interface allows the backend logging library to be implemented in multiple ways.The $wgMWLoggerDefaultSpi global provides the classname of the default MediaWiki\Logger\Spi implementation to be loaded at runtime.This can either be the name of a class implementing the MediaWiki\Logger\Spi with a zero argument const ructor or a callable that will return an MediaWiki\Logger\Spi instance.Alternately the MediaWiki\Logger\LoggerFactory MediaWiki Logger LoggerFactory
Definition: logger.txt:5
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at etc Handles the details of getting and saving to the user table of the and dealing with sessions and cookies OutputPage Encapsulates the entire HTML page that will be sent in response to any server request It is used by calling its functions to add in any and then calling output() to send it all.It could be easily changed to send incrementally if that becomes useful
WebRequest $request
setSkin(Skin $s)
Set the Skin object.
if(!$wgRequest->checkUrlExtension()) if(!$wgEnableAPI) $wgTitle
Definition: api.php:57
this hook is for auditing only etc instead of letting the login form give the generic error message that the account does not exist For when the account has been renamed or deleted or an array to pass a message key and parameters create2 Corresponds to logging log_action database field and which is displayed in the UI similar to $comment this hook should only be used to add variables that depend on the current page request
Definition: hooks.txt:1946
static factory($code)
Get a cached or new language object for a given language code.
Definition: Language.php:179
getLanguage()
Get the Language object.
static getDefaultInstance()
Definition: SkinFactory.php:50
if(is_null($wgLocalTZoffset)) if(!$wgDBerrorLogTZ) $wgRequest
Definition: Setup.php:657
this class mediates it Skin Encapsulates a look and feel for the wiki All of the functions that render HTML and make choices about how to render it are here and are called from various other places when and is meant to be subclassed with other skins that may override some of its functions The User object contains a reference to a skin(according to that user's preference)
static RequestContext $instance
$wgUser
Definition: Setup.php:794
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:310