3abc986921c2431e19ce0a9d4acdc1433896f0d0
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
{
72 private static $instance = null;
75 * Set the Config object
79 public function setConfig( Config
$c ) {
84 * Get the Config object
88 public function getConfig() {
89 if ( $this->config
=== null ) {
90 // @todo In the future, we could move this to WebStart.php so
91 // the Config object is ready for when initialization happens
92 $this->config
= ConfigFactory
::getDefaultInstance()->makeConfig( 'main' );
99 * Set the WebRequest object
101 * @param WebRequest $r
103 public function setRequest( WebRequest
$r ) {
108 * Get the WebRequest object
112 public function getRequest() {
113 if ( $this->request
=== null ) {
114 global $wgRequest; # fallback to $wg till we can improve this
115 $this->request
= $wgRequest;
118 return $this->request
;
122 * Set the Title object
124 * @param Title $title
126 public function setTitle( Title
$title ) {
127 $this->title
= $title;
128 // Erase the WikiPage so a new one with the new title gets created.
129 $this->wikipage
= null;
133 * Get the Title object
137 public function getTitle() {
138 if ( $this->title
=== null ) {
139 global $wgTitle; # fallback to $wg till we can improve this
140 $this->title
= $wgTitle;
141 wfDebugLog( 'GlobalTitleFail', __METHOD__
. ' called by ' . wfGetAllCallers( 5 ) . ' with no title set.' );
148 * Check, if a Title object is set
153 public function hasTitle() {
154 return $this->title
!== null;
158 * Check whether a WikiPage object can be get with getWikiPage().
159 * Callers should expect that an exception is thrown from getWikiPage()
160 * if this method returns false.
165 public function canUseWikiPage() {
166 if ( $this->wikipage
) {
167 // If there's a WikiPage object set, we can for sure get it
170 // Only pages with legitimate titles can have WikiPages.
171 // That usually means pages in non-virtual namespaces.
172 $title = $this->getTitle();
173 return $title ?
$title->canExist() : false;
177 * Set the WikiPage object
182 public function setWikiPage( WikiPage
$p ) {
183 $pageTitle = $p->getTitle();
184 if ( !$this->hasTitle() ||
!$pageTitle->equals( $this->getTitle() ) ) {
185 $this->setTitle( $pageTitle );
187 // Defer this to the end since setTitle sets it to null.
188 $this->wikipage
= $p;
192 * Get the WikiPage object.
193 * May throw an exception if there's no Title object set or the Title object
194 * belongs to a special namespace that doesn't have WikiPage, so use first
195 * canUseWikiPage() to check whether this method can be called safely.
198 * @throws MWException
201 public function getWikiPage() {
202 if ( $this->wikipage
=== null ) {
203 $title = $this->getTitle();
204 if ( $title === null ) {
205 throw new MWException( __METHOD__
. ' called without Title object set' );
207 $this->wikipage
= WikiPage
::factory( $title );
210 return $this->wikipage
;
214 * @param OutputPage $o
216 public function setOutput( OutputPage
$o ) {
221 * Get the OutputPage object
225 public function getOutput() {
226 if ( $this->output
=== null ) {
227 $this->output
= new OutputPage( $this );
230 return $this->output
;
234 * Set the User object
238 public function setUser( User
$u ) {
243 * Get the User object
247 public function getUser() {
248 if ( $this->user
=== null ) {
249 $this->user
= User
::newFromSession( $this->getRequest() );
256 * Accepts a language code and ensures it's sane. Outputs a cleaned up language
257 * code and replaces with $wgLanguageCode if not sane.
258 * @param string $code Language code
261 public static function sanitizeLangCode( $code ) {
262 global $wgLanguageCode;
264 // BCP 47 - letter case MUST NOT carry meaning
265 $code = strtolower( $code );
268 if ( !$code ||
!Language
::isValidCode( $code ) ||
$code === 'qqq' ) {
269 wfDebug( "Invalid user language code\n" );
270 $code = $wgLanguageCode;
277 * Set the Language object
279 * @param Language|string $l Language instance or language code
280 * @throws MWException
283 public function setLanguage( $l ) {
284 if ( $l instanceof Language
) {
286 } elseif ( is_string( $l ) ) {
287 $l = self
::sanitizeLangCode( $l );
288 $obj = Language
::factory( $l );
291 throw new MWException( __METHOD__
. " was passed an invalid type of data." );
296 * Get the Language object.
297 * Initialization of user or request objects can depend on this.
302 public function getLanguage() {
303 if ( isset( $this->recursion
) ) {
304 trigger_error( "Recursion detected in " . __METHOD__
, E_USER_WARNING
);
306 wfDebugLog( 'recursion-guard', "Recursion detected:\n" . $e->getTraceAsString() );
308 $code = $this->getConfig()->get( 'LanguageCode' ) ?
: 'en';
309 $this->lang
= Language
::factory( $code );
310 } elseif ( $this->lang
=== null ) {
311 $this->recursion
= true;
316 $request = $this->getRequest();
317 $user = $this->getUser();
319 $code = $request->getVal( 'uselang', 'user' );
320 if ( $code === 'user' ) {
321 $code = $user->getOption( 'language' );
323 $code = self
::sanitizeLangCode( $code );
325 Hooks
::run( 'UserGetLanguageObject', array( $user, &$code, $this ) );
327 if ( $code === $this->getConfig()->get( 'LanguageCode' ) ) {
328 $this->lang
= $wgContLang;
330 $obj = Language
::factory( $code );
334 unset( $this->recursion
);
336 catch ( Exception
$ex ) {
337 unset( $this->recursion
);
346 * Set the Skin object
350 public function setSkin( Skin
$s ) {
351 $this->skin
= clone $s;
352 $this->skin
->setContext( $this );
356 * Get the Skin object
360 public function getSkin() {
361 if ( $this->skin
=== null ) {
364 Hooks
::run( 'RequestContextCreateSkin', array( $this, &$skin ) );
365 $factory = SkinFactory
::getDefaultInstance();
367 // If the hook worked try to set a skin from it
368 if ( $skin instanceof Skin
) {
370 } elseif ( is_string( $skin ) ) {
371 // Normalize the key, just in case the hook did something weird.
372 $normalized = Skin
::normalizeKey( $skin );
373 $this->skin
= $factory->makeSkin( $normalized );
376 // If this is still null (the hook didn't run or didn't work)
377 // then go through the normal processing to load a skin
378 if ( $this->skin
=== null ) {
379 if ( !in_array( 'skin', $this->getConfig()->get( 'HiddenPrefs' ) ) ) {
381 $userSkin = $this->getUser()->getOption( 'skin' );
382 $userSkin = $this->getRequest()->getVal( 'useskin', $userSkin );
384 # if we're not allowing users to override, then use the default
385 $userSkin = $this->getConfig()->get( 'DefaultSkin' );
388 // Normalize the key in case the user is passing gibberish
389 // or has old preferences (bug 69566).
390 $normalized = Skin
::normalizeKey( $userSkin );
392 // Skin::normalizeKey will also validate it, so
393 // this won't throw an exception
394 $this->skin
= $factory->makeSkin( $normalized );
397 // After all that set a context on whatever skin got created
398 $this->skin
->setContext( $this );
404 /** Helpful methods **/
407 * Get a Message object with context set
408 * Parameters are the same as wfMessage()
412 public function msg() {
413 $args = func_get_args();
415 return call_user_func_array( 'wfMessage', $args )->setContext( $this );
418 /** Static methods **/
421 * Get the RequestContext object associated with the main request
423 * @return RequestContext
425 public static function getMain() {
426 if ( self
::$instance === null ) {
427 self
::$instance = new self
;
430 return self
::$instance;
434 * Get the RequestContext object associated with the main request
435 * and gives a warning to the log, to find places, where a context maybe is missing.
437 * @param string $func
438 * @return RequestContext
441 public static function getMainAndWarn( $func = __METHOD__
) {
442 wfDebug( $func . ' called without context. ' .
443 "Using RequestContext::getMain() for sanity\n" );
445 return self
::getMain();
449 * Resets singleton returned by getMain(). Should be called only from unit tests.
451 public static function resetMain() {
452 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
453 throw new MWException( __METHOD__
. '() should be called only from unit tests!' );
455 self
::$instance = null;
459 * Export the resolved user IP, HTTP headers, user ID, and session ID.
460 * The result will be reasonably sized to allow for serialization.
465 public function exportSession() {
467 'ip' => $this->getRequest()->getIP(),
468 'headers' => $this->getRequest()->getAllHeaders(),
469 'sessionId' => session_id(),
470 'userId' => $this->getUser()->getId()
475 * Import an client IP address, HTTP headers, user ID, and session ID
477 * This sets the current session and sets $wgUser and $wgRequest.
478 * Once the return value falls out of scope, the old context is restored.
479 * This method should only be called in contexts (CLI or HTTP job runners)
480 * where there is no session ID or end user receiving the response. This
481 * is partly enforced, and is done so to avoid leaking cookies if certain
482 * error conditions arise.
484 * This will setup the session from the given ID. This is useful when
485 * background scripts inherit context when acting on behalf of a user.
487 * @note suhosin.session.encrypt may interfere with this method.
489 * @param array $params Result of RequestContext::exportSession()
490 * @return ScopedCallback
491 * @throws MWException
494 public static function importScopedSession( array $params ) {
495 if ( session_id() != '' && strlen( $params['sessionId'] ) ) {
496 // Sanity check to avoid sending random cookies for the wrong users.
497 // This method should only called by CLI scripts or by HTTP job runners.
498 throw new MWException( "Sessions can only be imported when none is active." );
499 } elseif ( !IP
::isValid( $params['ip'] ) ) {
500 throw new MWException( "Invalid client IP address '{$params['ip']}'." );
503 if ( $params['userId'] ) { // logged-in user
504 $user = User
::newFromId( $params['userId'] );
506 if ( !$user->getId() ) {
507 throw new MWException( "No user with ID '{$params['userId']}'." );
509 } else { // anon user
510 $user = User
::newFromName( $params['ip'], false );
513 $importSessionFunc = function ( User
$user, array $params ) {
514 global $wgRequest, $wgUser;
516 $context = RequestContext
::getMain();
517 // Commit and close any current session
518 session_write_close(); // persist
519 session_id( '' ); // detach
520 $_SESSION = array(); // clear in-memory array
521 // Remove any user IP or agent information
522 $context->setRequest( new FauxRequest() );
523 $wgRequest = $context->getRequest(); // b/c
524 // Now that all private information is detached from the user, it should
525 // be safe to load the new user. If errors occur or an exception is thrown
526 // and caught (leaving the main context in a mixed state), there is no risk
527 // of the User object being attached to the wrong IP, headers, or session.
528 $context->setUser( $user );
529 $wgUser = $context->getUser(); // b/c
530 if ( strlen( $params['sessionId'] ) ) { // don't make a new random ID
531 wfSetupSession( $params['sessionId'] ); // sets $_SESSION
533 $request = new FauxRequest( array(), false, $_SESSION );
534 $request->setIP( $params['ip'] );
535 foreach ( $params['headers'] as $name => $value ) {
536 $request->setHeader( $name, $value );
538 // Set the current context to use the new WebRequest
539 $context->setRequest( $request );
540 $wgRequest = $context->getRequest(); // b/c
543 // Stash the old session and load in the new one
544 $oUser = self
::getMain()->getUser();
545 $oParams = self
::getMain()->exportSession();
546 $oRequest = self
::getMain()->getRequest();
547 $importSessionFunc( $user, $params );
549 // Set callback to save and close the new session and reload the old one
550 return new ScopedCallback(
551 function () use ( $importSessionFunc, $oUser, $oParams, $oRequest ) {
553 $importSessionFunc( $oUser, $oParams );
554 // Restore the exact previous Request object (instead of leaving FauxRequest)
555 RequestContext
::getMain()->setRequest( $oRequest );
556 $wgRequest = RequestContext
::getMain()->getRequest(); // b/c
562 * Create a new extraneous context. The context is filled with information
563 * external to the current session.
564 * - Title is specified by argument
565 * - Request is a FauxRequest, or a FauxRequest can be specified by argument
566 * - User is an anonymous user, for separation IPv4 localhost is used
567 * - Language will be based on the anonymous user and request, may be content
568 * language or a uselang param in the fauxrequest data may change the lang
569 * - Skin will be based on the anonymous user, should be the wiki's default skin
571 * @param Title $title Title to use for the extraneous request
572 * @param WebRequest|array $request A WebRequest or data to use for a FauxRequest
573 * @return RequestContext
575 public static function newExtraneousContext( Title
$title, $request = array() ) {
577 $context->setTitle( $title );
578 if ( $request instanceof WebRequest
) {
579 $context->setRequest( $request );
581 $context->setRequest( new FauxRequest( $request ) );
583 $context->user
= User
::newFromName( '127.0.0.1', false );