3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
20 * @author Alexandre Emsenhuber
21 * @author Daniel Friesen
26 * Group all the pieces relevant to the context of a request into one instance
28 class RequestContext
implements IContextSource
, MutableContext
{
65 * @var \Liuggio\StatsdClient\Factory\StatsdDataFactory
82 private static $instance = null;
85 * Set the Config object
89 public function setConfig( Config
$c ) {
94 * Get the Config object
98 public function getConfig() {
99 if ( $this->config
=== null ) {
100 // @todo In the future, we could move this to WebStart.php so
101 // the Config object is ready for when initialization happens
102 $this->config
= ConfigFactory
::getDefaultInstance()->makeConfig( 'main' );
105 return $this->config
;
109 * Set the WebRequest object
111 * @param WebRequest $r
113 public function setRequest( WebRequest
$r ) {
118 * Get the WebRequest object
122 public function getRequest() {
123 if ( $this->request
=== null ) {
124 global $wgCommandLineMode;
125 // create the WebRequest object on the fly
126 if ( $wgCommandLineMode ) {
127 $this->request
= new FauxRequest( array() );
129 $this->request
= new WebRequest();
133 return $this->request
;
137 * Get the Stats object
139 * @return BufferingStatsdDataFactory
141 public function getStats() {
142 if ( $this->stats
=== null ) {
143 $config = $this->getConfig();
144 $prefix = $config->get( 'StatsdMetricPrefix' )
145 ?
rtrim( $config->get( 'StatsdMetricPrefix' ), '.' )
147 $this->stats
= new BufferingStatsdDataFactory( $prefix );
153 * Get the timing object
157 public function getTiming() {
158 if ( $this->timing
=== null ) {
159 $this->timing
= new Timing();
161 return $this->timing
;
165 * Set the Title object
167 * @param Title $title
169 public function setTitle( Title
$title ) {
170 $this->title
= $title;
171 // Erase the WikiPage so a new one with the new title gets created.
172 $this->wikipage
= null;
176 * Get the Title object
180 public function getTitle() {
181 if ( $this->title
=== null ) {
182 global $wgTitle; # fallback to $wg till we can improve this
183 $this->title
= $wgTitle;
186 __METHOD__
. ' called by ' . wfGetAllCallers( 5 ) . ' with no title set.'
194 * Check, if a Title object is set
199 public function hasTitle() {
200 return $this->title
!== null;
204 * Check whether a WikiPage object can be get with getWikiPage().
205 * Callers should expect that an exception is thrown from getWikiPage()
206 * if this method returns false.
211 public function canUseWikiPage() {
212 if ( $this->wikipage
) {
213 // If there's a WikiPage object set, we can for sure get it
216 // Only pages with legitimate titles can have WikiPages.
217 // That usually means pages in non-virtual namespaces.
218 $title = $this->getTitle();
219 return $title ?
$title->canExist() : false;
223 * Set the WikiPage object
228 public function setWikiPage( WikiPage
$p ) {
229 $pageTitle = $p->getTitle();
230 if ( !$this->hasTitle() ||
!$pageTitle->equals( $this->getTitle() ) ) {
231 $this->setTitle( $pageTitle );
233 // Defer this to the end since setTitle sets it to null.
234 $this->wikipage
= $p;
238 * Get the WikiPage object.
239 * May throw an exception if there's no Title object set or the Title object
240 * belongs to a special namespace that doesn't have WikiPage, so use first
241 * canUseWikiPage() to check whether this method can be called safely.
244 * @throws MWException
247 public function getWikiPage() {
248 if ( $this->wikipage
=== null ) {
249 $title = $this->getTitle();
250 if ( $title === null ) {
251 throw new MWException( __METHOD__
. ' called without Title object set' );
253 $this->wikipage
= WikiPage
::factory( $title );
256 return $this->wikipage
;
260 * @param OutputPage $o
262 public function setOutput( OutputPage
$o ) {
267 * Get the OutputPage object
271 public function getOutput() {
272 if ( $this->output
=== null ) {
273 $this->output
= new OutputPage( $this );
276 return $this->output
;
280 * Set the User object
284 public function setUser( User
$u ) {
289 * Get the User object
293 public function getUser() {
294 if ( $this->user
=== null ) {
295 $this->user
= User
::newFromSession( $this->getRequest() );
302 * Accepts a language code and ensures it's sane. Outputs a cleaned up language
303 * code and replaces with $wgLanguageCode if not sane.
304 * @param string $code Language code
307 public static function sanitizeLangCode( $code ) {
308 global $wgLanguageCode;
310 // BCP 47 - letter case MUST NOT carry meaning
311 $code = strtolower( $code );
314 if ( !$code ||
!Language
::isValidCode( $code ) ||
$code === 'qqq' ) {
315 wfDebug( "Invalid user language code\n" );
316 $code = $wgLanguageCode;
323 * Set the Language object
325 * @param Language|string $l Language instance or language code
326 * @throws MWException
329 public function setLanguage( $l ) {
330 if ( $l instanceof Language
) {
332 } elseif ( is_string( $l ) ) {
333 $l = self
::sanitizeLangCode( $l );
334 $obj = Language
::factory( $l );
337 throw new MWException( __METHOD__
. " was passed an invalid type of data." );
342 * Get the Language object.
343 * Initialization of user or request objects can depend on this.
348 public function getLanguage() {
349 if ( isset( $this->recursion
) ) {
350 trigger_error( "Recursion detected in " . __METHOD__
, E_USER_WARNING
);
352 wfDebugLog( 'recursion-guard', "Recursion detected:\n" . $e->getTraceAsString() );
354 $code = $this->getConfig()->get( 'LanguageCode' ) ?
: 'en';
355 $this->lang
= Language
::factory( $code );
356 } elseif ( $this->lang
=== null ) {
357 $this->recursion
= true;
362 $request = $this->getRequest();
363 $user = $this->getUser();
365 $code = $request->getVal( 'uselang', 'user' );
366 if ( $code === 'user' ) {
367 $code = $user->getOption( 'language' );
369 $code = self
::sanitizeLangCode( $code );
371 Hooks
::run( 'UserGetLanguageObject', array( $user, &$code, $this ) );
373 if ( $code === $this->getConfig()->get( 'LanguageCode' ) ) {
374 $this->lang
= $wgContLang;
376 $obj = Language
::factory( $code );
380 unset( $this->recursion
);
382 catch ( Exception
$ex ) {
383 unset( $this->recursion
);
392 * Set the Skin object
396 public function setSkin( Skin
$s ) {
397 $this->skin
= clone $s;
398 $this->skin
->setContext( $this );
402 * Get the Skin object
406 public function getSkin() {
407 if ( $this->skin
=== null ) {
409 Hooks
::run( 'RequestContextCreateSkin', array( $this, &$skin ) );
410 $factory = SkinFactory
::getDefaultInstance();
412 // If the hook worked try to set a skin from it
413 if ( $skin instanceof Skin
) {
415 } elseif ( is_string( $skin ) ) {
416 // Normalize the key, just in case the hook did something weird.
417 $normalized = Skin
::normalizeKey( $skin );
418 $this->skin
= $factory->makeSkin( $normalized );
421 // If this is still null (the hook didn't run or didn't work)
422 // then go through the normal processing to load a skin
423 if ( $this->skin
=== null ) {
424 if ( !in_array( 'skin', $this->getConfig()->get( 'HiddenPrefs' ) ) ) {
426 $userSkin = $this->getUser()->getOption( 'skin' );
427 $userSkin = $this->getRequest()->getVal( 'useskin', $userSkin );
429 # if we're not allowing users to override, then use the default
430 $userSkin = $this->getConfig()->get( 'DefaultSkin' );
433 // Normalize the key in case the user is passing gibberish
434 // or has old preferences (bug 69566).
435 $normalized = Skin
::normalizeKey( $userSkin );
437 // Skin::normalizeKey will also validate it, so
438 // this won't throw an exception
439 $this->skin
= $factory->makeSkin( $normalized );
442 // After all that set a context on whatever skin got created
443 $this->skin
->setContext( $this );
449 /** Helpful methods **/
452 * Get a Message object with context set
453 * Parameters are the same as wfMessage()
458 public function msg() {
459 $args = func_get_args();
461 return call_user_func_array( 'wfMessage', $args )->setContext( $this );
464 /** Static methods **/
467 * Get the RequestContext object associated with the main request
469 * @return RequestContext
471 public static function getMain() {
472 if ( self
::$instance === null ) {
473 self
::$instance = new self
;
476 return self
::$instance;
480 * Get the RequestContext object associated with the main request
481 * and gives a warning to the log, to find places, where a context maybe is missing.
483 * @param string $func
484 * @return RequestContext
487 public static function getMainAndWarn( $func = __METHOD__
) {
488 wfDebug( $func . ' called without context. ' .
489 "Using RequestContext::getMain() for sanity\n" );
491 return self
::getMain();
495 * Resets singleton returned by getMain(). Should be called only from unit tests.
497 public static function resetMain() {
498 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
499 throw new MWException( __METHOD__
. '() should be called only from unit tests!' );
501 self
::$instance = null;
505 * Export the resolved user IP, HTTP headers, user ID, and session ID.
506 * The result will be reasonably sized to allow for serialization.
511 public function exportSession() {
513 'ip' => $this->getRequest()->getIP(),
514 'headers' => $this->getRequest()->getAllHeaders(),
515 'sessionId' => session_id(),
516 'userId' => $this->getUser()->getId()
521 * Import an client IP address, HTTP headers, user ID, and session ID
523 * This sets the current session, $wgUser, and $wgRequest from $params.
524 * Once the return value falls out of scope, the old context is restored.
525 * This method should only be called in contexts where there is no session
526 * ID or end user receiving the response (CLI or HTTP job runners). This
527 * is partly enforced, and is done so to avoid leaking cookies if certain
528 * error conditions arise.
530 * This is useful when background scripts inherit context when acting on
531 * behalf of a user. In general the 'sessionId' parameter should be set
532 * to an empty string unless session importing is *truly* needed. This
533 * feature is somewhat deprecated.
535 * @note suhosin.session.encrypt may interfere with this method.
537 * @param array $params Result of RequestContext::exportSession()
538 * @return ScopedCallback
539 * @throws MWException
542 public static function importScopedSession( array $params ) {
543 if ( session_id() != '' && strlen( $params['sessionId'] ) ) {
544 // Sanity check to avoid sending random cookies for the wrong users.
545 // This method should only called by CLI scripts or by HTTP job runners.
546 throw new MWException( "Sessions can only be imported when none is active." );
547 } elseif ( !IP
::isValid( $params['ip'] ) ) {
548 throw new MWException( "Invalid client IP address '{$params['ip']}'." );
551 if ( $params['userId'] ) { // logged-in user
552 $user = User
::newFromId( $params['userId'] );
554 if ( !$user->getId() ) {
555 throw new MWException( "No user with ID '{$params['userId']}'." );
557 } else { // anon user
558 $user = User
::newFromName( $params['ip'], false );
561 $importSessionFunc = function ( User
$user, array $params ) {
562 global $wgRequest, $wgUser;
564 $context = RequestContext
::getMain();
565 // Commit and close any current session
566 session_write_close(); // persist
567 session_id( '' ); // detach
568 $_SESSION = array(); // clear in-memory array
569 // Remove any user IP or agent information
570 $context->setRequest( new FauxRequest() );
571 $wgRequest = $context->getRequest(); // b/c
572 // Now that all private information is detached from the user, it should
573 // be safe to load the new user. If errors occur or an exception is thrown
574 // and caught (leaving the main context in a mixed state), there is no risk
575 // of the User object being attached to the wrong IP, headers, or session.
576 $context->setUser( $user );
577 $wgUser = $context->getUser(); // b/c
578 if ( strlen( $params['sessionId'] ) ) { // don't make a new random ID
579 wfSetupSession( $params['sessionId'] ); // sets $_SESSION
581 $request = new FauxRequest( array(), false, $_SESSION );
582 $request->setIP( $params['ip'] );
583 foreach ( $params['headers'] as $name => $value ) {
584 $request->setHeader( $name, $value );
586 // Set the current context to use the new WebRequest
587 $context->setRequest( $request );
588 $wgRequest = $context->getRequest(); // b/c
591 // Stash the old session and load in the new one
592 $oUser = self
::getMain()->getUser();
593 $oParams = self
::getMain()->exportSession();
594 $oRequest = self
::getMain()->getRequest();
595 $importSessionFunc( $user, $params );
597 // Set callback to save and close the new session and reload the old one
598 return new ScopedCallback(
599 function () use ( $importSessionFunc, $oUser, $oParams, $oRequest ) {
601 $importSessionFunc( $oUser, $oParams );
602 // Restore the exact previous Request object (instead of leaving FauxRequest)
603 RequestContext
::getMain()->setRequest( $oRequest );
604 $wgRequest = RequestContext
::getMain()->getRequest(); // b/c
610 * Create a new extraneous context. The context is filled with information
611 * external to the current session.
612 * - Title is specified by argument
613 * - Request is a FauxRequest, or a FauxRequest can be specified by argument
614 * - User is an anonymous user, for separation IPv4 localhost is used
615 * - Language will be based on the anonymous user and request, may be content
616 * language or a uselang param in the fauxrequest data may change the lang
617 * - Skin will be based on the anonymous user, should be the wiki's default skin
619 * @param Title $title Title to use for the extraneous request
620 * @param WebRequest|array $request A WebRequest or data to use for a FauxRequest
621 * @return RequestContext
623 public static function newExtraneousContext( Title
$title, $request = array() ) {
625 $context->setTitle( $title );
626 if ( $request instanceof WebRequest
) {
627 $context->setRequest( $request );
629 $context->setRequest( new FauxRequest( $request ) );
631 $context->user
= User
::newFromName( '127.0.0.1', false );