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 StatsdDataFactory
77 private static $instance = null;
80 * Set the Config object
84 public function setConfig( Config
$c ) {
89 * Get the Config object
93 public function getConfig() {
94 if ( $this->config
=== null ) {
95 // @todo In the future, we could move this to WebStart.php so
96 // the Config object is ready for when initialization happens
97 $this->config
= ConfigFactory
::getDefaultInstance()->makeConfig( 'main' );
100 return $this->config
;
104 * Set the WebRequest object
106 * @param WebRequest $r
108 public function setRequest( WebRequest
$r ) {
113 * Get the WebRequest object
117 public function getRequest() {
118 if ( $this->request
=== null ) {
119 global $wgRequest; # fallback to $wg till we can improve this
120 $this->request
= $wgRequest;
123 return $this->request
;
127 * Get the Stats object
129 * @return BufferingStatsdDataFactory
131 public function getStats() {
132 if ( $this->stats
=== null ) {
133 $config = $this->getConfig();
134 $prefix = $config->get( 'StatsdMetricPrefix' )
135 ?
rtrim( $config->get( 'StatsdMetricPrefix' ), '.' )
137 $this->stats
= new BufferingStatsdDataFactory( $prefix );
143 * Set the Title object
145 * @param Title $title
147 public function setTitle( Title
$title ) {
148 $this->title
= $title;
149 // Erase the WikiPage so a new one with the new title gets created.
150 $this->wikipage
= null;
154 * Get the Title object
158 public function getTitle() {
159 if ( $this->title
=== null ) {
160 global $wgTitle; # fallback to $wg till we can improve this
161 $this->title
= $wgTitle;
162 wfDebugLog( 'GlobalTitleFail', __METHOD__
. ' called by ' . wfGetAllCallers( 5 ) . ' with no title set.' );
169 * Check, if a Title object is set
174 public function hasTitle() {
175 return $this->title
!== null;
179 * Check whether a WikiPage object can be get with getWikiPage().
180 * Callers should expect that an exception is thrown from getWikiPage()
181 * if this method returns false.
186 public function canUseWikiPage() {
187 if ( $this->wikipage
) {
188 // If there's a WikiPage object set, we can for sure get it
191 // Only pages with legitimate titles can have WikiPages.
192 // That usually means pages in non-virtual namespaces.
193 $title = $this->getTitle();
194 return $title ?
$title->canExist() : false;
198 * Set the WikiPage object
203 public function setWikiPage( WikiPage
$p ) {
204 $pageTitle = $p->getTitle();
205 if ( !$this->hasTitle() ||
!$pageTitle->equals( $this->getTitle() ) ) {
206 $this->setTitle( $pageTitle );
208 // Defer this to the end since setTitle sets it to null.
209 $this->wikipage
= $p;
213 * Get the WikiPage object.
214 * May throw an exception if there's no Title object set or the Title object
215 * belongs to a special namespace that doesn't have WikiPage, so use first
216 * canUseWikiPage() to check whether this method can be called safely.
219 * @throws MWException
222 public function getWikiPage() {
223 if ( $this->wikipage
=== null ) {
224 $title = $this->getTitle();
225 if ( $title === null ) {
226 throw new MWException( __METHOD__
. ' called without Title object set' );
228 $this->wikipage
= WikiPage
::factory( $title );
231 return $this->wikipage
;
235 * @param OutputPage $o
237 public function setOutput( OutputPage
$o ) {
242 * Get the OutputPage object
246 public function getOutput() {
247 if ( $this->output
=== null ) {
248 $this->output
= new OutputPage( $this );
251 return $this->output
;
255 * Set the User object
259 public function setUser( User
$u ) {
264 * Get the User object
268 public function getUser() {
269 if ( $this->user
=== null ) {
270 $this->user
= User
::newFromSession( $this->getRequest() );
277 * Accepts a language code and ensures it's sane. Outputs a cleaned up language
278 * code and replaces with $wgLanguageCode if not sane.
279 * @param string $code Language code
282 public static function sanitizeLangCode( $code ) {
283 global $wgLanguageCode;
285 // BCP 47 - letter case MUST NOT carry meaning
286 $code = strtolower( $code );
289 if ( !$code ||
!Language
::isValidCode( $code ) ||
$code === 'qqq' ) {
290 wfDebug( "Invalid user language code\n" );
291 $code = $wgLanguageCode;
298 * Set the Language object
300 * @param Language|string $l Language instance or language code
301 * @throws MWException
304 public function setLanguage( $l ) {
305 if ( $l instanceof Language
) {
307 } elseif ( is_string( $l ) ) {
308 $l = self
::sanitizeLangCode( $l );
309 $obj = Language
::factory( $l );
312 throw new MWException( __METHOD__
. " was passed an invalid type of data." );
317 * Get the Language object.
318 * Initialization of user or request objects can depend on this.
323 public function getLanguage() {
324 if ( isset( $this->recursion
) ) {
325 trigger_error( "Recursion detected in " . __METHOD__
, E_USER_WARNING
);
327 wfDebugLog( 'recursion-guard', "Recursion detected:\n" . $e->getTraceAsString() );
329 $code = $this->getConfig()->get( 'LanguageCode' ) ?
: 'en';
330 $this->lang
= Language
::factory( $code );
331 } elseif ( $this->lang
=== null ) {
332 $this->recursion
= true;
337 $request = $this->getRequest();
338 $user = $this->getUser();
340 $code = $request->getVal( 'uselang', 'user' );
341 if ( $code === 'user' ) {
342 $code = $user->getOption( 'language' );
344 $code = self
::sanitizeLangCode( $code );
346 Hooks
::run( 'UserGetLanguageObject', array( $user, &$code, $this ) );
348 if ( $code === $this->getConfig()->get( 'LanguageCode' ) ) {
349 $this->lang
= $wgContLang;
351 $obj = Language
::factory( $code );
355 unset( $this->recursion
);
357 catch ( Exception
$ex ) {
358 unset( $this->recursion
);
367 * Set the Skin object
371 public function setSkin( Skin
$s ) {
372 $this->skin
= clone $s;
373 $this->skin
->setContext( $this );
377 * Get the Skin object
381 public function getSkin() {
382 if ( $this->skin
=== null ) {
384 Hooks
::run( 'RequestContextCreateSkin', array( $this, &$skin ) );
385 $factory = SkinFactory
::getDefaultInstance();
387 // If the hook worked try to set a skin from it
388 if ( $skin instanceof Skin
) {
390 } elseif ( is_string( $skin ) ) {
391 // Normalize the key, just in case the hook did something weird.
392 $normalized = Skin
::normalizeKey( $skin );
393 $this->skin
= $factory->makeSkin( $normalized );
396 // If this is still null (the hook didn't run or didn't work)
397 // then go through the normal processing to load a skin
398 if ( $this->skin
=== null ) {
399 if ( !in_array( 'skin', $this->getConfig()->get( 'HiddenPrefs' ) ) ) {
401 $userSkin = $this->getUser()->getOption( 'skin' );
402 $userSkin = $this->getRequest()->getVal( 'useskin', $userSkin );
404 # if we're not allowing users to override, then use the default
405 $userSkin = $this->getConfig()->get( 'DefaultSkin' );
408 // Normalize the key in case the user is passing gibberish
409 // or has old preferences (bug 69566).
410 $normalized = Skin
::normalizeKey( $userSkin );
412 // Skin::normalizeKey will also validate it, so
413 // this won't throw an exception
414 $this->skin
= $factory->makeSkin( $normalized );
417 // After all that set a context on whatever skin got created
418 $this->skin
->setContext( $this );
424 /** Helpful methods **/
427 * Get a Message object with context set
428 * Parameters are the same as wfMessage()
432 public function msg() {
433 $args = func_get_args();
435 return call_user_func_array( 'wfMessage', $args )->setContext( $this );
438 /** Static methods **/
441 * Get the RequestContext object associated with the main request
443 * @return RequestContext
445 public static function getMain() {
446 if ( self
::$instance === null ) {
447 self
::$instance = new self
;
450 return self
::$instance;
454 * Get the RequestContext object associated with the main request
455 * and gives a warning to the log, to find places, where a context maybe is missing.
457 * @param string $func
458 * @return RequestContext
461 public static function getMainAndWarn( $func = __METHOD__
) {
462 wfDebug( $func . ' called without context. ' .
463 "Using RequestContext::getMain() for sanity\n" );
465 return self
::getMain();
469 * Resets singleton returned by getMain(). Should be called only from unit tests.
471 public static function resetMain() {
472 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
473 throw new MWException( __METHOD__
. '() should be called only from unit tests!' );
475 self
::$instance = null;
479 * Export the resolved user IP, HTTP headers, user ID, and session ID.
480 * The result will be reasonably sized to allow for serialization.
485 public function exportSession() {
487 'ip' => $this->getRequest()->getIP(),
488 'headers' => $this->getRequest()->getAllHeaders(),
489 'sessionId' => session_id(),
490 'userId' => $this->getUser()->getId()
495 * Import an client IP address, HTTP headers, user ID, and session ID
497 * This sets the current session, $wgUser, and $wgRequest from $params.
498 * Once the return value falls out of scope, the old context is restored.
499 * This method should only be called in contexts where there is no session
500 * ID or end user receiving the response (CLI or HTTP job runners). This
501 * is partly enforced, and is done so to avoid leaking cookies if certain
502 * error conditions arise.
504 * This is useful when background scripts inherit context when acting on
505 * behalf of a user. In general the 'sessionId' parameter should be set
506 * to an empty string unless session importing is *truly* needed. This
507 * feature is somewhat deprecated.
509 * @note suhosin.session.encrypt may interfere with this method.
511 * @param array $params Result of RequestContext::exportSession()
512 * @return ScopedCallback
513 * @throws MWException
516 public static function importScopedSession( array $params ) {
517 if ( session_id() != '' && strlen( $params['sessionId'] ) ) {
518 // Sanity check to avoid sending random cookies for the wrong users.
519 // This method should only called by CLI scripts or by HTTP job runners.
520 throw new MWException( "Sessions can only be imported when none is active." );
521 } elseif ( !IP
::isValid( $params['ip'] ) ) {
522 throw new MWException( "Invalid client IP address '{$params['ip']}'." );
525 if ( $params['userId'] ) { // logged-in user
526 $user = User
::newFromId( $params['userId'] );
528 if ( !$user->getId() ) {
529 throw new MWException( "No user with ID '{$params['userId']}'." );
531 } else { // anon user
532 $user = User
::newFromName( $params['ip'], false );
535 $importSessionFunc = function ( User
$user, array $params ) {
536 global $wgRequest, $wgUser;
538 $context = RequestContext
::getMain();
539 // Commit and close any current session
540 session_write_close(); // persist
541 session_id( '' ); // detach
542 $_SESSION = array(); // clear in-memory array
543 // Remove any user IP or agent information
544 $context->setRequest( new FauxRequest() );
545 $wgRequest = $context->getRequest(); // b/c
546 // Now that all private information is detached from the user, it should
547 // be safe to load the new user. If errors occur or an exception is thrown
548 // and caught (leaving the main context in a mixed state), there is no risk
549 // of the User object being attached to the wrong IP, headers, or session.
550 $context->setUser( $user );
551 $wgUser = $context->getUser(); // b/c
552 if ( strlen( $params['sessionId'] ) ) { // don't make a new random ID
553 wfSetupSession( $params['sessionId'] ); // sets $_SESSION
555 $request = new FauxRequest( array(), false, $_SESSION );
556 $request->setIP( $params['ip'] );
557 foreach ( $params['headers'] as $name => $value ) {
558 $request->setHeader( $name, $value );
560 // Set the current context to use the new WebRequest
561 $context->setRequest( $request );
562 $wgRequest = $context->getRequest(); // b/c
565 // Stash the old session and load in the new one
566 $oUser = self
::getMain()->getUser();
567 $oParams = self
::getMain()->exportSession();
568 $oRequest = self
::getMain()->getRequest();
569 $importSessionFunc( $user, $params );
571 // Set callback to save and close the new session and reload the old one
572 return new ScopedCallback(
573 function () use ( $importSessionFunc, $oUser, $oParams, $oRequest ) {
575 $importSessionFunc( $oUser, $oParams );
576 // Restore the exact previous Request object (instead of leaving FauxRequest)
577 RequestContext
::getMain()->setRequest( $oRequest );
578 $wgRequest = RequestContext
::getMain()->getRequest(); // b/c
584 * Create a new extraneous context. The context is filled with information
585 * external to the current session.
586 * - Title is specified by argument
587 * - Request is a FauxRequest, or a FauxRequest can be specified by argument
588 * - User is an anonymous user, for separation IPv4 localhost is used
589 * - Language will be based on the anonymous user and request, may be content
590 * language or a uselang param in the fauxrequest data may change the lang
591 * - Skin will be based on the anonymous user, should be the wiki's default skin
593 * @param Title $title Title to use for the extraneous request
594 * @param WebRequest|array $request A WebRequest or data to use for a FauxRequest
595 * @return RequestContext
597 public static function newExtraneousContext( Title
$title, $request = array() ) {
599 $context->setTitle( $title );
600 if ( $request instanceof WebRequest
) {
601 $context->setRequest( $request );
603 $context->setRequest( new FauxRequest( $request ) );
605 $context->user
= User
::newFromName( '127.0.0.1', false );