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
{
67 * Set the WebRequest object
69 * @param WebRequest $r
71 public function setRequest( WebRequest
$r ) {
76 * Get the WebRequest object
80 public function getRequest() {
81 if ( $this->request
=== null ) {
82 global $wgRequest; # fallback to $wg till we can improve this
83 $this->request
= $wgRequest;
85 return $this->request
;
89 * Set the Title object
93 public function setTitle( Title
$t ) {
95 // Erase the WikiPage so a new one with the new title gets created.
96 $this->wikipage
= null;
100 * Get the Title object
104 public function getTitle() {
105 if ( $this->title
=== null ) {
106 global $wgTitle; # fallback to $wg till we can improve this
107 $this->title
= $wgTitle;
113 * Check whether a WikiPage object can be get with getWikiPage().
114 * Callers should expect that an exception is thrown from getWikiPage()
115 * if this method returns false.
120 public function canUseWikiPage() {
121 if ( $this->wikipage
!== null ) {
122 # If there's a WikiPage object set, we can for sure get it
125 $title = $this->getTitle();
126 if ( $title === null ) {
127 # No Title, no WikiPage
130 # Only namespaces whose pages are stored in the database can have WikiPage
131 return $title->canExist();
136 * Set the WikiPage object
141 public function setWikiPage( WikiPage
$p ) {
142 $contextTitle = $this->getTitle();
143 $pageTitle = $p->getTitle();
144 if ( !$contextTitle ||
!$pageTitle->equals( $contextTitle ) ) {
145 $this->setTitle( $pageTitle );
147 // Defer this to the end since setTitle sets it to null.
148 $this->wikipage
= $p;
152 * Get the WikiPage object.
153 * May throw an exception if there's no Title object set or the Title object
154 * belongs to a special namespace that doesn't have WikiPage, so use first
155 * canUseWikiPage() to check whether this method can be called safely.
158 * @throws MWException
161 public function getWikiPage() {
162 if ( $this->wikipage
=== null ) {
163 $title = $this->getTitle();
164 if ( $title === null ) {
165 throw new MWException( __METHOD__
. ' called without Title object set' );
167 $this->wikipage
= WikiPage
::factory( $title );
169 return $this->wikipage
;
173 * @param $o OutputPage
175 public function setOutput( OutputPage
$o ) {
180 * Get the OutputPage object
184 public function getOutput() {
185 if ( $this->output
=== null ) {
186 $this->output
= new OutputPage( $this );
188 return $this->output
;
192 * Set the User object
196 public function setUser( User
$u ) {
201 * Get the User object
205 public function getUser() {
206 if ( $this->user
=== null ) {
207 $this->user
= User
::newFromSession( $this->getRequest() );
213 * Accepts a language code and ensures it's sane. Outputs a cleaned up language
214 * code and replaces with $wgLanguageCode if not sane.
215 * @param string $code Language code
218 public static function sanitizeLangCode( $code ) {
219 global $wgLanguageCode;
221 // BCP 47 - letter case MUST NOT carry meaning
222 $code = strtolower( $code );
225 if ( empty( $code ) ||
!Language
::isValidCode( $code ) ||
( $code === 'qqq' ) ) {
226 wfDebug( "Invalid user language code\n" );
227 $code = $wgLanguageCode;
234 * Set the Language object
236 * @deprecated since 1.19 Use setLanguage instead
237 * @param Language|string $l Language instance or language code
239 public function setLang( $l ) {
240 wfDeprecated( __METHOD__
, '1.19' );
241 $this->setLanguage( $l );
245 * Set the Language object
247 * @param Language|string $l Language instance or language code
248 * @throws MWException
251 public function setLanguage( $l ) {
252 if ( $l instanceof Language
) {
254 } elseif ( is_string( $l ) ) {
255 $l = self
::sanitizeLangCode( $l );
256 $obj = Language
::factory( $l );
259 throw new MWException( __METHOD__
. " was passed an invalid type of data." );
264 * @deprecated since 1.19 Use getLanguage instead
267 public function getLang() {
268 wfDeprecated( __METHOD__
, '1.19' );
269 return $this->getLanguage();
273 * Get the Language object.
274 * Initialization of user or request objects can depend on this.
279 public function getLanguage() {
280 if ( isset( $this->recursion
) ) {
281 trigger_error( "Recursion detected in " . __METHOD__
, E_USER_WARNING
);
283 wfDebugLog( 'recursion-guard', "Recursion detected:\n" . $e->getTraceAsString() );
285 global $wgLanguageCode;
286 $code = ( $wgLanguageCode ) ?
$wgLanguageCode : 'en';
287 $this->lang
= Language
::factory( $code );
288 } elseif ( $this->lang
=== null ) {
289 $this->recursion
= true;
291 global $wgLanguageCode, $wgContLang;
293 $request = $this->getRequest();
294 $user = $this->getUser();
296 $code = $request->getVal( 'uselang', $user->getOption( 'language' ) );
297 $code = self
::sanitizeLangCode( $code );
299 wfRunHooks( 'UserGetLanguageObject', array( $user, &$code, $this ) );
301 if ( $code === $wgLanguageCode ) {
302 $this->lang
= $wgContLang;
304 $obj = Language
::factory( $code );
308 unset( $this->recursion
);
315 * Set the Skin object
319 public function setSkin( Skin
$s ) {
320 $this->skin
= clone $s;
321 $this->skin
->setContext( $this );
325 * Get the Skin object
329 public function getSkin() {
330 if ( $this->skin
=== null ) {
331 wfProfileIn( __METHOD__
. '-createskin' );
334 wfRunHooks( 'RequestContextCreateSkin', array( $this, &$skin ) );
336 // If the hook worked try to set a skin from it
337 if ( $skin instanceof Skin
) {
339 } elseif ( is_string( $skin ) ) {
340 $this->skin
= Skin
::newFromKey( $skin );
343 // If this is still null (the hook didn't run or didn't work)
344 // then go through the normal processing to load a skin
345 if ( $this->skin
=== null ) {
346 global $wgHiddenPrefs;
347 if ( !in_array( 'skin', $wgHiddenPrefs ) ) {
349 $userSkin = $this->getUser()->getOption( 'skin' );
350 $userSkin = $this->getRequest()->getVal( 'useskin', $userSkin );
352 # if we're not allowing users to override, then use the default
353 global $wgDefaultSkin;
354 $userSkin = $wgDefaultSkin;
357 $this->skin
= Skin
::newFromKey( $userSkin );
360 // After all that set a context on whatever skin got created
361 $this->skin
->setContext( $this );
362 wfProfileOut( __METHOD__
. '-createskin' );
367 /** Helpful methods **/
370 * Get a Message object with context set
371 * Parameters are the same as wfMessage()
375 public function msg() {
376 $args = func_get_args();
377 return call_user_func_array( 'wfMessage', $args )->setContext( $this );
380 /** Static methods **/
383 * Get the RequestContext object associated with the main request
385 * @return RequestContext
387 public static function getMain() {
388 static $instance = null;
389 if ( $instance === null ) {
390 $instance = new self
;
396 * Export the resolved user IP, HTTP headers, user ID, and session ID.
397 * The result will be reasonably sized to allow for serialization.
402 public function exportSession() {
404 'ip' => $this->getRequest()->getIP(),
405 'headers' => $this->getRequest()->getAllHeaders(),
406 'sessionId' => session_id(),
407 'userId' => $this->getUser()->getId()
412 * Import the resolved user IP, HTTP headers, user ID, and session ID.
413 * This sets the current session and sets $wgUser and $wgRequest.
414 * Once the return value falls out of scope, the old context is restored.
415 * This function can only be called within CLI mode scripts.
417 * This will setup the session from the given ID. This is useful when
418 * background scripts inherit context when acting on behalf of a user.
420 * $param array $params Result of RequestContext::exportSession()
421 * @return ScopedCallback
422 * @throws MWException
425 public static function importScopedSession( array $params ) {
426 if ( PHP_SAPI
!== 'cli' ) {
427 // Don't send random private cookies or turn $wgRequest into FauxRequest
428 throw new MWException( "Sessions can only be imported in cli mode." );
429 } elseif ( !strlen( $params['sessionId'] ) ) {
430 throw new MWException( "No session ID was specified." );
433 if ( $params['userId'] ) { // logged-in user
434 $user = User
::newFromId( $params['userId'] );
436 throw new MWException( "No user with ID '{$params['userId']}'." );
438 } elseif ( !IP
::isValid( $params['ip'] ) ) {
439 throw new MWException( "Could not load user '{$params['ip']}'." );
440 } else { // anon user
441 $user = User
::newFromName( $params['ip'], false );
444 $importSessionFunction = function( User
$user, array $params ) {
445 global $wgRequest, $wgUser;
447 $context = RequestContext
::getMain();
448 // Commit and close any current session
449 session_write_close(); // persist
450 session_id( '' ); // detach
451 $_SESSION = array(); // clear in-memory array
452 // Remove any user IP or agent information
453 $context->setRequest( new FauxRequest() );
454 $wgRequest = $context->getRequest(); // b/c
455 // Now that all private information is detached from the user, it should
456 // be safe to load the new user. If errors occur or an exception is thrown
457 // and caught (leaving the main context in a mixed state), there is no risk
458 // of the User object being attached to the wrong IP, headers, or session.
459 $context->setUser( $user );
460 $wgUser = $context->getUser(); // b/c
461 if ( strlen( $params['sessionId'] ) ) { // don't make a new random ID
462 wfSetupSession( $params['sessionId'] ); // sets $_SESSION
464 $request = new FauxRequest( array(), false, $_SESSION );
465 $request->setIP( $params['ip'] );
466 foreach ( $params['headers'] as $name => $value ) {
467 $request->setHeader( $name, $value );
469 // Set the current context to use the new WebRequest
470 $context->setRequest( $request );
471 $wgRequest = $context->getRequest(); // b/c
474 // Stash the old session and load in the new one
475 $oUser = self
::getMain()->getUser();
476 $oParams = self
::getMain()->exportSession();
477 $importSessionFunction( $user, $params );
479 // Set callback to save and close the new session and reload the old one
480 return new ScopedCallback( function() use ( $importSessionFunction, $oUser, $oParams ) {
481 $importSessionFunction( $oUser, $oParams );
486 * Create a new extraneous context. The context is filled with information
487 * external to the current session.
488 * - Title is specified by argument
489 * - Request is a FauxRequest, or a FauxRequest can be specified by argument
490 * - User is an anonymous user, for separation IPv4 localhost is used
491 * - Language will be based on the anonymous user and request, may be content
492 * language or a uselang param in the fauxrequest data may change the lang
493 * - Skin will be based on the anonymous user, should be the wiki's default skin
495 * @param Title $title Title to use for the extraneous request
496 * @param WebRequest|array $request A WebRequest or data to use for a FauxRequest
497 * @return RequestContext
499 public static function newExtraneousContext( Title
$title, $request = array() ) {
501 $context->setTitle( $title );
502 if ( $request instanceof WebRequest
) {
503 $context->setRequest( $request );
505 $context->setRequest( new FauxRequest( $request ) );
507 $context->user
= User
::newFromName( '127.0.0.1', false );