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 \Liuggio\StatsdClient\Factory\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;
164 __METHOD__
. ' called by ' . wfGetAllCallers( 5 ) . ' with no title set.'
172 * Check, if a Title object is set
177 public function hasTitle() {
178 return $this->title
!== null;
182 * Check whether a WikiPage object can be get with getWikiPage().
183 * Callers should expect that an exception is thrown from getWikiPage()
184 * if this method returns false.
189 public function canUseWikiPage() {
190 if ( $this->wikipage
) {
191 // If there's a WikiPage object set, we can for sure get it
194 // Only pages with legitimate titles can have WikiPages.
195 // That usually means pages in non-virtual namespaces.
196 $title = $this->getTitle();
197 return $title ?
$title->canExist() : false;
201 * Set the WikiPage object
206 public function setWikiPage( WikiPage
$p ) {
207 $pageTitle = $p->getTitle();
208 if ( !$this->hasTitle() ||
!$pageTitle->equals( $this->getTitle() ) ) {
209 $this->setTitle( $pageTitle );
211 // Defer this to the end since setTitle sets it to null.
212 $this->wikipage
= $p;
216 * Get the WikiPage object.
217 * May throw an exception if there's no Title object set or the Title object
218 * belongs to a special namespace that doesn't have WikiPage, so use first
219 * canUseWikiPage() to check whether this method can be called safely.
222 * @throws MWException
225 public function getWikiPage() {
226 if ( $this->wikipage
=== null ) {
227 $title = $this->getTitle();
228 if ( $title === null ) {
229 throw new MWException( __METHOD__
. ' called without Title object set' );
231 $this->wikipage
= WikiPage
::factory( $title );
234 return $this->wikipage
;
238 * @param OutputPage $o
240 public function setOutput( OutputPage
$o ) {
245 * Get the OutputPage object
249 public function getOutput() {
250 if ( $this->output
=== null ) {
251 $this->output
= new OutputPage( $this );
254 return $this->output
;
258 * Set the User object
262 public function setUser( User
$u ) {
267 * Get the User object
271 public function getUser() {
272 if ( $this->user
=== null ) {
273 $this->user
= User
::newFromSession( $this->getRequest() );
280 * Accepts a language code and ensures it's sane. Outputs a cleaned up language
281 * code and replaces with $wgLanguageCode if not sane.
282 * @param string $code Language code
285 public static function sanitizeLangCode( $code ) {
286 global $wgLanguageCode;
288 // BCP 47 - letter case MUST NOT carry meaning
289 $code = strtolower( $code );
292 if ( !$code ||
!Language
::isValidCode( $code ) ||
$code === 'qqq' ) {
293 wfDebug( "Invalid user language code\n" );
294 $code = $wgLanguageCode;
301 * Set the Language object
303 * @param Language|string $l Language instance or language code
304 * @throws MWException
307 public function setLanguage( $l ) {
308 if ( $l instanceof Language
) {
310 } elseif ( is_string( $l ) ) {
311 $l = self
::sanitizeLangCode( $l );
312 $obj = Language
::factory( $l );
315 throw new MWException( __METHOD__
. " was passed an invalid type of data." );
320 * Get the Language object.
321 * Initialization of user or request objects can depend on this.
326 public function getLanguage() {
327 if ( isset( $this->recursion
) ) {
328 trigger_error( "Recursion detected in " . __METHOD__
, E_USER_WARNING
);
330 wfDebugLog( 'recursion-guard', "Recursion detected:\n" . $e->getTraceAsString() );
332 $code = $this->getConfig()->get( 'LanguageCode' ) ?
: 'en';
333 $this->lang
= Language
::factory( $code );
334 } elseif ( $this->lang
=== null ) {
335 $this->recursion
= true;
340 $request = $this->getRequest();
341 $user = $this->getUser();
343 $code = $request->getVal( 'uselang', 'user' );
344 if ( $code === 'user' ) {
345 $code = $user->getOption( 'language' );
347 $code = self
::sanitizeLangCode( $code );
349 Hooks
::run( 'UserGetLanguageObject', array( $user, &$code, $this ) );
351 if ( $code === $this->getConfig()->get( 'LanguageCode' ) ) {
352 $this->lang
= $wgContLang;
354 $obj = Language
::factory( $code );
358 unset( $this->recursion
);
360 catch ( Exception
$ex ) {
361 unset( $this->recursion
);
370 * Set the Skin object
374 public function setSkin( Skin
$s ) {
375 $this->skin
= clone $s;
376 $this->skin
->setContext( $this );
380 * Get the Skin object
384 public function getSkin() {
385 if ( $this->skin
=== null ) {
387 Hooks
::run( 'RequestContextCreateSkin', array( $this, &$skin ) );
388 $factory = SkinFactory
::getDefaultInstance();
390 // If the hook worked try to set a skin from it
391 if ( $skin instanceof Skin
) {
393 } elseif ( is_string( $skin ) ) {
394 // Normalize the key, just in case the hook did something weird.
395 $normalized = Skin
::normalizeKey( $skin );
396 $this->skin
= $factory->makeSkin( $normalized );
399 // If this is still null (the hook didn't run or didn't work)
400 // then go through the normal processing to load a skin
401 if ( $this->skin
=== null ) {
402 if ( !in_array( 'skin', $this->getConfig()->get( 'HiddenPrefs' ) ) ) {
404 $userSkin = $this->getUser()->getOption( 'skin' );
405 $userSkin = $this->getRequest()->getVal( 'useskin', $userSkin );
407 # if we're not allowing users to override, then use the default
408 $userSkin = $this->getConfig()->get( 'DefaultSkin' );
411 // Normalize the key in case the user is passing gibberish
412 // or has old preferences (bug 69566).
413 $normalized = Skin
::normalizeKey( $userSkin );
415 // Skin::normalizeKey will also validate it, so
416 // this won't throw an exception
417 $this->skin
= $factory->makeSkin( $normalized );
420 // After all that set a context on whatever skin got created
421 $this->skin
->setContext( $this );
427 /** Helpful methods **/
430 * Get a Message object with context set
431 * Parameters are the same as wfMessage()
436 public function msg() {
437 $args = func_get_args();
439 return call_user_func_array( 'wfMessage', $args )->setContext( $this );
442 /** Static methods **/
445 * Get the RequestContext object associated with the main request
447 * @return RequestContext
449 public static function getMain() {
450 if ( self
::$instance === null ) {
451 self
::$instance = new self
;
454 return self
::$instance;
458 * Get the RequestContext object associated with the main request
459 * and gives a warning to the log, to find places, where a context maybe is missing.
461 * @param string $func
462 * @return RequestContext
465 public static function getMainAndWarn( $func = __METHOD__
) {
466 wfDebug( $func . ' called without context. ' .
467 "Using RequestContext::getMain() for sanity\n" );
469 return self
::getMain();
473 * Resets singleton returned by getMain(). Should be called only from unit tests.
475 public static function resetMain() {
476 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
477 throw new MWException( __METHOD__
. '() should be called only from unit tests!' );
479 self
::$instance = null;
483 * Export the resolved user IP, HTTP headers, user ID, and session ID.
484 * The result will be reasonably sized to allow for serialization.
489 public function exportSession() {
491 'ip' => $this->getRequest()->getIP(),
492 'headers' => $this->getRequest()->getAllHeaders(),
493 'sessionId' => session_id(),
494 'userId' => $this->getUser()->getId()
499 * Import an client IP address, HTTP headers, user ID, and session ID
501 * This sets the current session, $wgUser, and $wgRequest from $params.
502 * Once the return value falls out of scope, the old context is restored.
503 * This method should only be called in contexts where there is no session
504 * ID or end user receiving the response (CLI or HTTP job runners). This
505 * is partly enforced, and is done so to avoid leaking cookies if certain
506 * error conditions arise.
508 * This is useful when background scripts inherit context when acting on
509 * behalf of a user. In general the 'sessionId' parameter should be set
510 * to an empty string unless session importing is *truly* needed. This
511 * feature is somewhat deprecated.
513 * @note suhosin.session.encrypt may interfere with this method.
515 * @param array $params Result of RequestContext::exportSession()
516 * @return ScopedCallback
517 * @throws MWException
520 public static function importScopedSession( array $params ) {
521 if ( session_id() != '' && strlen( $params['sessionId'] ) ) {
522 // Sanity check to avoid sending random cookies for the wrong users.
523 // This method should only called by CLI scripts or by HTTP job runners.
524 throw new MWException( "Sessions can only be imported when none is active." );
525 } elseif ( !IP
::isValid( $params['ip'] ) ) {
526 throw new MWException( "Invalid client IP address '{$params['ip']}'." );
529 if ( $params['userId'] ) { // logged-in user
530 $user = User
::newFromId( $params['userId'] );
532 if ( !$user->getId() ) {
533 throw new MWException( "No user with ID '{$params['userId']}'." );
535 } else { // anon user
536 $user = User
::newFromName( $params['ip'], false );
539 $importSessionFunc = function ( User
$user, array $params ) {
540 global $wgRequest, $wgUser;
542 $context = RequestContext
::getMain();
543 // Commit and close any current session
544 session_write_close(); // persist
545 session_id( '' ); // detach
546 $_SESSION = array(); // clear in-memory array
547 // Remove any user IP or agent information
548 $context->setRequest( new FauxRequest() );
549 $wgRequest = $context->getRequest(); // b/c
550 // Now that all private information is detached from the user, it should
551 // be safe to load the new user. If errors occur or an exception is thrown
552 // and caught (leaving the main context in a mixed state), there is no risk
553 // of the User object being attached to the wrong IP, headers, or session.
554 $context->setUser( $user );
555 $wgUser = $context->getUser(); // b/c
556 if ( strlen( $params['sessionId'] ) ) { // don't make a new random ID
557 wfSetupSession( $params['sessionId'] ); // sets $_SESSION
559 $request = new FauxRequest( array(), false, $_SESSION );
560 $request->setIP( $params['ip'] );
561 foreach ( $params['headers'] as $name => $value ) {
562 $request->setHeader( $name, $value );
564 // Set the current context to use the new WebRequest
565 $context->setRequest( $request );
566 $wgRequest = $context->getRequest(); // b/c
569 // Stash the old session and load in the new one
570 $oUser = self
::getMain()->getUser();
571 $oParams = self
::getMain()->exportSession();
572 $oRequest = self
::getMain()->getRequest();
573 $importSessionFunc( $user, $params );
575 // Set callback to save and close the new session and reload the old one
576 return new ScopedCallback(
577 function () use ( $importSessionFunc, $oUser, $oParams, $oRequest ) {
579 $importSessionFunc( $oUser, $oParams );
580 // Restore the exact previous Request object (instead of leaving FauxRequest)
581 RequestContext
::getMain()->setRequest( $oRequest );
582 $wgRequest = RequestContext
::getMain()->getRequest(); // b/c
588 * Create a new extraneous context. The context is filled with information
589 * external to the current session.
590 * - Title is specified by argument
591 * - Request is a FauxRequest, or a FauxRequest can be specified by argument
592 * - User is an anonymous user, for separation IPv4 localhost is used
593 * - Language will be based on the anonymous user and request, may be content
594 * language or a uselang param in the fauxrequest data may change the lang
595 * - Skin will be based on the anonymous user, should be the wiki's default skin
597 * @param Title $title Title to use for the extraneous request
598 * @param WebRequest|array $request A WebRequest or data to use for a FauxRequest
599 * @return RequestContext
601 public static function newExtraneousContext( Title
$title, $request = array() ) {
603 $context->setTitle( $title );
604 if ( $request instanceof WebRequest
) {
605 $context->setRequest( $request );
607 $context->setRequest( new FauxRequest( $request ) );
609 $context->user
= User
::newFromName( '127.0.0.1', false );