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 * @var SiteConfiguration
72 * Set the SiteConfiguration object
74 * @param SiteConfiguration $c
76 public function setConfig( SiteConfiguration
$c ) {
81 * Get the SiteConfiguration object
83 * @return SiteConfiguration
85 public function getConfig() {
86 if ( $this->config
=== null ) {
88 $this->config
= $wgConf;
94 * Set the WebRequest object
96 * @param WebRequest $r
98 public function setRequest( WebRequest
$r ) {
103 * Get the WebRequest object
107 public function getRequest() {
108 if ( $this->request
=== null ) {
109 global $wgRequest; # fallback to $wg till we can improve this
110 $this->request
= $wgRequest;
112 return $this->request
;
116 * Set the Title object
120 public function setTitle( $t ) {
121 if ( $t !== null && !$t instanceof Title
) {
122 throw new MWException( __METHOD__
. " expects an instance of Title" );
125 // Erase the WikiPage so a new one with the new title gets created.
126 $this->wikipage
= null;
130 * Get the Title object
134 public function getTitle() {
135 if ( $this->title
=== null ) {
136 global $wgTitle; # fallback to $wg till we can improve this
137 $this->title
= $wgTitle;
143 * Check whether a WikiPage object can be get with getWikiPage().
144 * Callers should expect that an exception is thrown from getWikiPage()
145 * if this method returns false.
150 public function canUseWikiPage() {
151 if ( $this->wikipage
!== null ) {
152 # If there's a WikiPage object set, we can for sure get it
155 $title = $this->getTitle();
156 if ( $title === null ) {
157 # No Title, no WikiPage
160 # Only namespaces whose pages are stored in the database can have WikiPage
161 return $title->canExist();
166 * Set the WikiPage object
171 public function setWikiPage( WikiPage
$p ) {
172 $contextTitle = $this->getTitle();
173 $pageTitle = $p->getTitle();
174 if ( !$contextTitle ||
!$pageTitle->equals( $contextTitle ) ) {
175 $this->setTitle( $pageTitle );
177 // Defer this to the end since setTitle sets it to null.
178 $this->wikipage
= $p;
182 * Get the WikiPage object.
183 * May throw an exception if there's no Title object set or the Title object
184 * belongs to a special namespace that doesn't have WikiPage, so use first
185 * canUseWikiPage() to check whether this method can be called safely.
188 * @throws MWException
191 public function getWikiPage() {
192 if ( $this->wikipage
=== null ) {
193 $title = $this->getTitle();
194 if ( $title === null ) {
195 throw new MWException( __METHOD__
. ' called without Title object set' );
197 $this->wikipage
= WikiPage
::factory( $title );
199 return $this->wikipage
;
203 * @param $o OutputPage
205 public function setOutput( OutputPage
$o ) {
210 * Get the OutputPage object
214 public function getOutput() {
215 if ( $this->output
=== null ) {
216 $this->output
= new OutputPage( $this );
218 return $this->output
;
222 * Set the User object
226 public function setUser( User
$u ) {
231 * Get the User object
235 public function getUser() {
236 if ( $this->user
=== null ) {
237 $this->user
= User
::newFromSession( $this->getRequest() );
243 * Accepts a language code and ensures it's sane. Outputs a cleaned up language
244 * code and replaces with $wgLanguageCode if not sane.
245 * @param string $code Language code
248 public static function sanitizeLangCode( $code ) {
249 global $wgLanguageCode;
251 // BCP 47 - letter case MUST NOT carry meaning
252 $code = strtolower( $code );
255 if ( empty( $code ) ||
!Language
::isValidCode( $code ) ||
( $code === 'qqq' ) ) {
256 wfDebug( "Invalid user language code\n" );
257 $code = $wgLanguageCode;
264 * Set the Language object
266 * @deprecated since 1.19 Use setLanguage instead
267 * @param Language|string $l Language instance or language code
269 public function setLang( $l ) {
270 wfDeprecated( __METHOD__
, '1.19' );
271 $this->setLanguage( $l );
275 * Set the Language object
277 * @param Language|string $l Language instance or language code
278 * @throws MWException
281 public function setLanguage( $l ) {
282 if ( $l instanceof Language
) {
284 } elseif ( is_string( $l ) ) {
285 $l = self
::sanitizeLangCode( $l );
286 $obj = Language
::factory( $l );
289 throw new MWException( __METHOD__
. " was passed an invalid type of data." );
294 * @deprecated since 1.19 Use getLanguage instead
297 public function getLang() {
298 wfDeprecated( __METHOD__
, '1.19' );
299 return $this->getLanguage();
303 * Get the Language object.
304 * Initialization of user or request objects can depend on this.
309 public function getLanguage() {
310 if ( isset( $this->recursion
) ) {
311 trigger_error( "Recursion detected in " . __METHOD__
, E_USER_WARNING
);
313 wfDebugLog( 'recursion-guard', "Recursion detected:\n" . $e->getTraceAsString() );
315 global $wgLanguageCode;
316 $code = ( $wgLanguageCode ) ?
$wgLanguageCode : 'en';
317 $this->lang
= Language
::factory( $code );
318 } elseif ( $this->lang
=== null ) {
319 $this->recursion
= true;
321 global $wgLanguageCode, $wgContLang;
323 $request = $this->getRequest();
324 $user = $this->getUser();
326 $code = $request->getVal( 'uselang', $user->getOption( 'language' ) );
327 $code = self
::sanitizeLangCode( $code );
329 wfRunHooks( 'UserGetLanguageObject', array( $user, &$code, $this ) );
331 if ( $code === $wgLanguageCode ) {
332 $this->lang
= $wgContLang;
334 $obj = Language
::factory( $code );
338 unset( $this->recursion
);
345 * Set the Skin object
349 public function setSkin( Skin
$s ) {
350 $this->skin
= clone $s;
351 $this->skin
->setContext( $this );
355 * Get the Skin object
359 public function getSkin() {
360 if ( $this->skin
=== null ) {
361 wfProfileIn( __METHOD__
. '-createskin' );
364 wfRunHooks( 'RequestContextCreateSkin', array( $this, &$skin ) );
366 // If the hook worked try to set a skin from it
367 if ( $skin instanceof Skin
) {
369 } elseif ( is_string( $skin ) ) {
370 $this->skin
= Skin
::newFromKey( $skin );
373 // If this is still null (the hook didn't run or didn't work)
374 // then go through the normal processing to load a skin
375 if ( $this->skin
=== null ) {
376 global $wgHiddenPrefs;
377 if ( !in_array( 'skin', $wgHiddenPrefs ) ) {
379 $userSkin = $this->getUser()->getOption( 'skin' );
380 $userSkin = $this->getRequest()->getVal( 'useskin', $userSkin );
382 # if we're not allowing users to override, then use the default
383 global $wgDefaultSkin;
384 $userSkin = $wgDefaultSkin;
387 $this->skin
= Skin
::newFromKey( $userSkin );
390 // After all that set a context on whatever skin got created
391 $this->skin
->setContext( $this );
392 wfProfileOut( __METHOD__
. '-createskin' );
397 /** Helpful methods **/
400 * Get a Message object with context set
401 * Parameters are the same as wfMessage()
405 public function msg() {
406 $args = func_get_args();
407 return call_user_func_array( 'wfMessage', $args )->setContext( $this );
410 /** Static methods **/
413 * Get the RequestContext object associated with the main request
415 * @return RequestContext
417 public static function getMain() {
418 static $instance = null;
419 if ( $instance === null ) {
420 $instance = new self
;
426 * Export the resolved user IP, HTTP headers, user ID, and session ID.
427 * The result will be reasonably sized to allow for serialization.
432 public function exportSession() {
434 'ip' => $this->getRequest()->getIP(),
435 'headers' => $this->getRequest()->getAllHeaders(),
436 'sessionId' => session_id(),
437 'userId' => $this->getUser()->getId()
442 * Import the resolved user IP, HTTP headers, user ID, and session ID.
443 * This sets the current session and sets $wgUser and $wgRequest.
444 * Once the return value falls out of scope, the old context is restored.
445 * This function can only be called within CLI mode scripts.
447 * This will setup the session from the given ID. This is useful when
448 * background scripts inherit context when acting on behalf of a user.
450 * @note suhosin.session.encrypt may interfere with this method.
452 * @param array $params Result of RequestContext::exportSession()
453 * @return ScopedCallback
454 * @throws MWException
457 public static function importScopedSession( array $params ) {
458 if ( PHP_SAPI
!== 'cli' ) {
459 // Don't send random private cookies or turn $wgRequest into FauxRequest
460 throw new MWException( "Sessions can only be imported in cli mode." );
461 } elseif ( !strlen( $params['sessionId'] ) ) {
462 throw new MWException( "No session ID was specified." );
465 if ( $params['userId'] ) { // logged-in user
466 $user = User
::newFromId( $params['userId'] );
468 throw new MWException( "No user with ID '{$params['userId']}'." );
470 } elseif ( !IP
::isValid( $params['ip'] ) ) {
471 throw new MWException( "Could not load user '{$params['ip']}'." );
472 } else { // anon user
473 $user = User
::newFromName( $params['ip'], false );
476 $importSessionFunction = function( User
$user, array $params ) {
477 global $wgRequest, $wgUser;
479 $context = RequestContext
::getMain();
480 // Commit and close any current session
481 session_write_close(); // persist
482 session_id( '' ); // detach
483 $_SESSION = array(); // clear in-memory array
484 // Remove any user IP or agent information
485 $context->setRequest( new FauxRequest() );
486 $wgRequest = $context->getRequest(); // b/c
487 // Now that all private information is detached from the user, it should
488 // be safe to load the new user. If errors occur or an exception is thrown
489 // and caught (leaving the main context in a mixed state), there is no risk
490 // of the User object being attached to the wrong IP, headers, or session.
491 $context->setUser( $user );
492 $wgUser = $context->getUser(); // b/c
493 if ( strlen( $params['sessionId'] ) ) { // don't make a new random ID
494 wfSetupSession( $params['sessionId'] ); // sets $_SESSION
496 $request = new FauxRequest( array(), false, $_SESSION );
497 $request->setIP( $params['ip'] );
498 foreach ( $params['headers'] as $name => $value ) {
499 $request->setHeader( $name, $value );
501 // Set the current context to use the new WebRequest
502 $context->setRequest( $request );
503 $wgRequest = $context->getRequest(); // b/c
506 // Stash the old session and load in the new one
507 $oUser = self
::getMain()->getUser();
508 $oParams = self
::getMain()->exportSession();
509 $importSessionFunction( $user, $params );
511 // Set callback to save and close the new session and reload the old one
512 return new ScopedCallback( function() use ( $importSessionFunction, $oUser, $oParams ) {
513 $importSessionFunction( $oUser, $oParams );
518 * Create a new extraneous context. The context is filled with information
519 * external to the current session.
520 * - Title is specified by argument
521 * - Request is a FauxRequest, or a FauxRequest can be specified by argument
522 * - User is an anonymous user, for separation IPv4 localhost is used
523 * - Language will be based on the anonymous user and request, may be content
524 * language or a uselang param in the fauxrequest data may change the lang
525 * - Skin will be based on the anonymous user, should be the wiki's default skin
527 * @param Title $title Title to use for the extraneous request
528 * @param WebRequest|array $request A WebRequest or data to use for a FauxRequest
529 * @return RequestContext
531 public static function newExtraneousContext( Title
$title, $request = array() ) {
533 $context->setTitle( $title );
534 if ( $request instanceof WebRequest
) {
535 $context->setRequest( $request );
537 $context->setRequest( new FauxRequest( $request ) );
539 $context->user
= User
::newFromName( '127.0.0.1', false );