3 * Request-dependant objects containers.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
22 * @author Alexandre Emsenhuber
23 * @author Daniel Friesen
28 * Group all the pieces relevant to the context of a request into one instance
30 class RequestContext
implements IContextSource
{
72 * Set the Config object
76 public function setConfig( Config
$c ) {
81 * Get the Config object
85 public function getConfig() {
86 if ( $this->config
=== null ) {
87 // @todo In the future, we could move this to WebStart.php so
88 // the Config object is ready for when initialization happens
89 $this->config
= ConfigFactory
::getDefaultInstance()->makeConfig( 'main' );
96 * Set the WebRequest object
98 * @param WebRequest $r
100 public function setRequest( WebRequest
$r ) {
105 * Get the WebRequest object
109 public function getRequest() {
110 if ( $this->request
=== null ) {
111 global $wgRequest; # fallback to $wg till we can improve this
112 $this->request
= $wgRequest;
115 return $this->request
;
119 * Set the Title object
122 * @throws MWException
124 public function setTitle( $t ) {
125 if ( $t !== null && !$t instanceof Title
) {
126 throw new MWException( __METHOD__
. " expects an instance of Title" );
129 // Erase the WikiPage so a new one with the new title gets created.
130 $this->wikipage
= null;
134 * Get the Title object
138 public function getTitle() {
139 if ( $this->title
=== null ) {
140 global $wgTitle; # fallback to $wg till we can improve this
141 $this->title
= $wgTitle;
148 * Check whether a WikiPage object can be get with getWikiPage().
149 * Callers should expect that an exception is thrown from getWikiPage()
150 * if this method returns false.
155 public function canUseWikiPage() {
156 if ( $this->wikipage
!== null ) {
157 # If there's a WikiPage object set, we can for sure get it
160 $title = $this->getTitle();
161 if ( $title === null ) {
162 # No Title, no WikiPage
165 # Only namespaces whose pages are stored in the database can have WikiPage
166 return $title->canExist();
171 * Set the WikiPage object
176 public function setWikiPage( WikiPage
$p ) {
177 $contextTitle = $this->getTitle();
178 $pageTitle = $p->getTitle();
179 if ( !$contextTitle ||
!$pageTitle->equals( $contextTitle ) ) {
180 $this->setTitle( $pageTitle );
182 // Defer this to the end since setTitle sets it to null.
183 $this->wikipage
= $p;
187 * Get the WikiPage object.
188 * May throw an exception if there's no Title object set or the Title object
189 * belongs to a special namespace that doesn't have WikiPage, so use first
190 * canUseWikiPage() to check whether this method can be called safely.
193 * @throws MWException
196 public function getWikiPage() {
197 if ( $this->wikipage
=== null ) {
198 $title = $this->getTitle();
199 if ( $title === null ) {
200 throw new MWException( __METHOD__
. ' called without Title object set' );
202 $this->wikipage
= WikiPage
::factory( $title );
205 return $this->wikipage
;
209 * @param OutputPage $o
211 public function setOutput( OutputPage
$o ) {
216 * Get the OutputPage object
220 public function getOutput() {
221 if ( $this->output
=== null ) {
222 $this->output
= new OutputPage( $this );
225 return $this->output
;
229 * Set the User object
233 public function setUser( User
$u ) {
238 * Get the User object
242 public function getUser() {
243 if ( $this->user
=== null ) {
244 $this->user
= User
::newFromSession( $this->getRequest() );
251 * Accepts a language code and ensures it's sane. Outputs a cleaned up language
252 * code and replaces with $wgLanguageCode if not sane.
253 * @param string $code Language code
256 public static function sanitizeLangCode( $code ) {
257 global $wgLanguageCode;
259 // BCP 47 - letter case MUST NOT carry meaning
260 $code = strtolower( $code );
263 if ( empty( $code ) ||
!Language
::isValidCode( $code ) ||
( $code === 'qqq' ) ) {
264 wfDebug( "Invalid user language code\n" );
265 $code = $wgLanguageCode;
272 * Set the Language object
274 * @param Language|string $l Language instance or language code
275 * @throws MWException
278 public function setLanguage( $l ) {
279 if ( $l instanceof Language
) {
281 } elseif ( is_string( $l ) ) {
282 $l = self
::sanitizeLangCode( $l );
283 $obj = Language
::factory( $l );
286 throw new MWException( __METHOD__
. " was passed an invalid type of data." );
291 * Get the Language object.
292 * Initialization of user or request objects can depend on this.
297 public function getLanguage() {
298 if ( isset( $this->recursion
) ) {
299 trigger_error( "Recursion detected in " . __METHOD__
, E_USER_WARNING
);
301 wfDebugLog( 'recursion-guard', "Recursion detected:\n" . $e->getTraceAsString() );
303 global $wgLanguageCode;
304 $code = ( $wgLanguageCode ) ?
$wgLanguageCode : 'en';
305 $this->lang
= Language
::factory( $code );
306 } elseif ( $this->lang
=== null ) {
307 $this->recursion
= true;
309 global $wgLanguageCode, $wgContLang;
312 $request = $this->getRequest();
313 $user = $this->getUser();
315 $code = $request->getVal( 'uselang', $user->getOption( 'language' ) );
316 $code = self
::sanitizeLangCode( $code );
318 wfRunHooks( 'UserGetLanguageObject', array( $user, &$code, $this ) );
320 if ( $code === $wgLanguageCode ) {
321 $this->lang
= $wgContLang;
323 $obj = Language
::factory( $code );
327 unset( $this->recursion
);
329 catch ( Exception
$ex ) {
330 unset( $this->recursion
);
339 * Set the Skin object
343 public function setSkin( Skin
$s ) {
344 $this->skin
= clone $s;
345 $this->skin
->setContext( $this );
349 * Get the Skin object
353 public function getSkin() {
354 if ( $this->skin
=== null ) {
355 wfProfileIn( __METHOD__
. '-createskin' );
358 wfRunHooks( 'RequestContextCreateSkin', array( $this, &$skin ) );
360 // If the hook worked try to set a skin from it
361 if ( $skin instanceof Skin
) {
363 } elseif ( is_string( $skin ) ) {
364 $this->skin
= Skin
::newFromKey( $skin );
367 // If this is still null (the hook didn't run or didn't work)
368 // then go through the normal processing to load a skin
369 if ( $this->skin
=== null ) {
370 global $wgHiddenPrefs;
371 if ( !in_array( 'skin', $wgHiddenPrefs ) ) {
373 $userSkin = $this->getUser()->getOption( 'skin' );
374 $userSkin = $this->getRequest()->getVal( 'useskin', $userSkin );
376 # if we're not allowing users to override, then use the default
377 global $wgDefaultSkin;
378 $userSkin = $wgDefaultSkin;
381 $this->skin
= Skin
::newFromKey( $userSkin );
384 // After all that set a context on whatever skin got created
385 $this->skin
->setContext( $this );
386 wfProfileOut( __METHOD__
. '-createskin' );
392 /** Helpful methods **/
395 * Get a Message object with context set
396 * Parameters are the same as wfMessage()
400 public function msg() {
401 $args = func_get_args();
403 return call_user_func_array( 'wfMessage', $args )->setContext( $this );
406 /** Static methods **/
409 * Get the RequestContext object associated with the main request
411 * @return RequestContext
413 public static function getMain() {
414 static $instance = null;
415 if ( $instance === null ) {
416 $instance = new self
;
423 * Export the resolved user IP, HTTP headers, user ID, and session ID.
424 * The result will be reasonably sized to allow for serialization.
429 public function exportSession() {
431 'ip' => $this->getRequest()->getIP(),
432 'headers' => $this->getRequest()->getAllHeaders(),
433 'sessionId' => session_id(),
434 'userId' => $this->getUser()->getId()
439 * Import the resolved user IP, HTTP headers, user ID, and session ID.
440 * This sets the current session and sets $wgUser and $wgRequest.
441 * Once the return value falls out of scope, the old context is restored.
442 * This function can only be called within CLI mode scripts.
444 * This will setup the session from the given ID. This is useful when
445 * background scripts inherit context when acting on behalf of a user.
447 * @note suhosin.session.encrypt may interfere with this method.
449 * @param array $params Result of RequestContext::exportSession()
450 * @return ScopedCallback
451 * @throws MWException
454 public static function importScopedSession( array $params ) {
455 if ( PHP_SAPI
!== 'cli' ) {
456 // Don't send random private cookies or turn $wgRequest into FauxRequest
457 throw new MWException( "Sessions can only be imported in cli mode." );
458 } elseif ( !strlen( $params['sessionId'] ) ) {
459 throw new MWException( "No session ID was specified." );
462 if ( $params['userId'] ) { // logged-in user
463 $user = User
::newFromId( $params['userId'] );
465 throw new MWException( "No user with ID '{$params['userId']}'." );
467 } elseif ( !IP
::isValid( $params['ip'] ) ) {
468 throw new MWException( "Could not load user '{$params['ip']}'." );
469 } else { // anon user
470 $user = User
::newFromName( $params['ip'], false );
473 $importSessionFunction = function ( User
$user, array $params ) {
474 global $wgRequest, $wgUser;
476 $context = RequestContext
::getMain();
477 // Commit and close any current session
478 session_write_close(); // persist
479 session_id( '' ); // detach
480 $_SESSION = array(); // clear in-memory array
481 // Remove any user IP or agent information
482 $context->setRequest( new FauxRequest() );
483 $wgRequest = $context->getRequest(); // b/c
484 // Now that all private information is detached from the user, it should
485 // be safe to load the new user. If errors occur or an exception is thrown
486 // and caught (leaving the main context in a mixed state), there is no risk
487 // of the User object being attached to the wrong IP, headers, or session.
488 $context->setUser( $user );
489 $wgUser = $context->getUser(); // b/c
490 if ( strlen( $params['sessionId'] ) ) { // don't make a new random ID
491 wfSetupSession( $params['sessionId'] ); // sets $_SESSION
493 $request = new FauxRequest( array(), false, $_SESSION );
494 $request->setIP( $params['ip'] );
495 foreach ( $params['headers'] as $name => $value ) {
496 $request->setHeader( $name, $value );
498 // Set the current context to use the new WebRequest
499 $context->setRequest( $request );
500 $wgRequest = $context->getRequest(); // b/c
503 // Stash the old session and load in the new one
504 $oUser = self
::getMain()->getUser();
505 $oParams = self
::getMain()->exportSession();
506 $importSessionFunction( $user, $params );
508 // Set callback to save and close the new session and reload the old one
509 return new ScopedCallback( function () use ( $importSessionFunction, $oUser, $oParams ) {
510 $importSessionFunction( $oUser, $oParams );
515 * Create a new extraneous context. The context is filled with information
516 * external to the current session.
517 * - Title is specified by argument
518 * - Request is a FauxRequest, or a FauxRequest can be specified by argument
519 * - User is an anonymous user, for separation IPv4 localhost is used
520 * - Language will be based on the anonymous user and request, may be content
521 * language or a uselang param in the fauxrequest data may change the lang
522 * - Skin will be based on the anonymous user, should be the wiki's default skin
524 * @param Title $title Title to use for the extraneous request
525 * @param WebRequest|array $request A WebRequest or data to use for a FauxRequest
526 * @return RequestContext
528 public static function newExtraneousContext( Title
$title, $request = array() ) {
530 $context->setTitle( $title );
531 if ( $request instanceof WebRequest
) {
532 $context->setRequest( $request );
534 $context->setRequest( new FauxRequest( $request ) );
536 $context->user
= User
::newFromName( '127.0.0.1', false );