Implement extension registration from an extension.json file
[mediawiki.git] / includes / context / RequestContext.php
bloba0e7f999d285eb78eb42a0eac89efbe841ccab4b
1 <?php
2 /**
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
20 * @since 1.18
22 * @author Alexandre Emsenhuber
23 * @author Daniel Friesen
24 * @file
27 /**
28 * Group all the pieces relevant to the context of a request into one instance
30 class RequestContext implements IContextSource {
31 /**
32 * @var WebRequest
34 private $request;
36 /**
37 * @var Title
39 private $title;
41 /**
42 * @var WikiPage
44 private $wikipage;
46 /**
47 * @var OutputPage
49 private $output;
51 /**
52 * @var User
54 private $user;
56 /**
57 * @var Language
59 private $lang;
61 /**
62 * @var Skin
64 private $skin;
66 /**
67 * @var Config
69 private $config;
71 /**
72 * @var RequestContext
74 private static $instance = null;
76 /**
77 * Set the Config object
79 * @param Config $c
81 public function setConfig( Config $c ) {
82 $this->config = $c;
85 /**
86 * Get the Config object
88 * @return Config
90 public function getConfig() {
91 if ( $this->config === null ) {
92 // @todo In the future, we could move this to WebStart.php so
93 // the Config object is ready for when initialization happens
94 $this->config = ConfigFactory::getDefaultInstance()->makeConfig( 'main' );
97 return $this->config;
101 * Set the WebRequest object
103 * @param WebRequest $r
105 public function setRequest( WebRequest $r ) {
106 $this->request = $r;
110 * Get the WebRequest object
112 * @return WebRequest
114 public function getRequest() {
115 if ( $this->request === null ) {
116 global $wgRequest; # fallback to $wg till we can improve this
117 $this->request = $wgRequest;
120 return $this->request;
124 * Set the Title object
126 * @param Title $title
128 public function setTitle( Title $title ) {
129 $this->title = $title;
130 // Erase the WikiPage so a new one with the new title gets created.
131 $this->wikipage = null;
135 * Get the Title object
137 * @return Title|null
139 public function getTitle() {
140 if ( $this->title === null ) {
141 global $wgTitle; # fallback to $wg till we can improve this
142 $this->title = $wgTitle;
143 wfDebugLog( 'GlobalTitleFail', __METHOD__ . ' called by ' . wfGetAllCallers( 5 ) . ' with no title set.' );
146 return $this->title;
150 * Check, if a Title object is set
152 * @since 1.25
153 * @return bool
155 public function hasTitle() {
156 return $this->title !== null;
160 * Check whether a WikiPage object can be get with getWikiPage().
161 * Callers should expect that an exception is thrown from getWikiPage()
162 * if this method returns false.
164 * @since 1.19
165 * @return bool
167 public function canUseWikiPage() {
168 if ( $this->wikipage ) {
169 // If there's a WikiPage object set, we can for sure get it
170 return true;
172 // Only pages with legitimate titles can have WikiPages.
173 // That usually means pages in non-virtual namespaces.
174 $title = $this->getTitle();
175 return $title ? $title->canExist() : false;
179 * Set the WikiPage object
181 * @since 1.19
182 * @param WikiPage $p
184 public function setWikiPage( WikiPage $p ) {
185 $pageTitle = $p->getTitle();
186 if ( !$this->hasTitle() || !$pageTitle->equals( $this->getTitle() ) ) {
187 $this->setTitle( $pageTitle );
189 // Defer this to the end since setTitle sets it to null.
190 $this->wikipage = $p;
194 * Get the WikiPage object.
195 * May throw an exception if there's no Title object set or the Title object
196 * belongs to a special namespace that doesn't have WikiPage, so use first
197 * canUseWikiPage() to check whether this method can be called safely.
199 * @since 1.19
200 * @throws MWException
201 * @return WikiPage
203 public function getWikiPage() {
204 if ( $this->wikipage === null ) {
205 $title = $this->getTitle();
206 if ( $title === null ) {
207 throw new MWException( __METHOD__ . ' called without Title object set' );
209 $this->wikipage = WikiPage::factory( $title );
212 return $this->wikipage;
216 * @param OutputPage $o
218 public function setOutput( OutputPage $o ) {
219 $this->output = $o;
223 * Get the OutputPage object
225 * @return OutputPage
227 public function getOutput() {
228 if ( $this->output === null ) {
229 $this->output = new OutputPage( $this );
232 return $this->output;
236 * Set the User object
238 * @param User $u
240 public function setUser( User $u ) {
241 $this->user = $u;
245 * Get the User object
247 * @return User
249 public function getUser() {
250 if ( $this->user === null ) {
251 $this->user = User::newFromSession( $this->getRequest() );
254 return $this->user;
258 * Accepts a language code and ensures it's sane. Outputs a cleaned up language
259 * code and replaces with $wgLanguageCode if not sane.
260 * @param string $code Language code
261 * @return string
263 public static function sanitizeLangCode( $code ) {
264 global $wgLanguageCode;
266 // BCP 47 - letter case MUST NOT carry meaning
267 $code = strtolower( $code );
269 # Validate $code
270 if ( !$code || !Language::isValidCode( $code ) || $code === 'qqq' ) {
271 wfDebug( "Invalid user language code\n" );
272 $code = $wgLanguageCode;
275 return $code;
279 * Set the Language object
281 * @param Language|string $l Language instance or language code
282 * @throws MWException
283 * @since 1.19
285 public function setLanguage( $l ) {
286 if ( $l instanceof Language ) {
287 $this->lang = $l;
288 } elseif ( is_string( $l ) ) {
289 $l = self::sanitizeLangCode( $l );
290 $obj = Language::factory( $l );
291 $this->lang = $obj;
292 } else {
293 throw new MWException( __METHOD__ . " was passed an invalid type of data." );
298 * Get the Language object.
299 * Initialization of user or request objects can depend on this.
300 * @return Language
301 * @throws Exception
302 * @since 1.19
304 public function getLanguage() {
305 if ( isset( $this->recursion ) ) {
306 trigger_error( "Recursion detected in " . __METHOD__, E_USER_WARNING );
307 $e = new Exception;
308 wfDebugLog( 'recursion-guard', "Recursion detected:\n" . $e->getTraceAsString() );
310 $code = $this->getConfig()->get( 'LanguageCode' ) ?: 'en';
311 $this->lang = Language::factory( $code );
312 } elseif ( $this->lang === null ) {
313 $this->recursion = true;
315 global $wgContLang;
317 try {
318 $request = $this->getRequest();
319 $user = $this->getUser();
321 $code = $request->getVal( 'uselang', 'user' );
322 if ( $code === 'user' ) {
323 $code = $user->getOption( 'language' );
325 $code = self::sanitizeLangCode( $code );
327 Hooks::run( 'UserGetLanguageObject', array( $user, &$code, $this ) );
329 if ( $code === $this->getConfig()->get( 'LanguageCode' ) ) {
330 $this->lang = $wgContLang;
331 } else {
332 $obj = Language::factory( $code );
333 $this->lang = $obj;
336 unset( $this->recursion );
338 catch ( Exception $ex ) {
339 unset( $this->recursion );
340 throw $ex;
344 return $this->lang;
348 * Set the Skin object
350 * @param Skin $s
352 public function setSkin( Skin $s ) {
353 $this->skin = clone $s;
354 $this->skin->setContext( $this );
358 * Get the Skin object
360 * @return Skin
362 public function getSkin() {
363 if ( $this->skin === null ) {
364 wfProfileIn( __METHOD__ . '-createskin' );
366 $skin = null;
367 Hooks::run( 'RequestContextCreateSkin', array( $this, &$skin ) );
368 $factory = SkinFactory::getDefaultInstance();
370 // If the hook worked try to set a skin from it
371 if ( $skin instanceof Skin ) {
372 $this->skin = $skin;
373 } elseif ( is_string( $skin ) ) {
374 // Normalize the key, just in case the hook did something weird.
375 $normalized = Skin::normalizeKey( $skin );
376 $this->skin = $factory->makeSkin( $normalized );
379 // If this is still null (the hook didn't run or didn't work)
380 // then go through the normal processing to load a skin
381 if ( $this->skin === null ) {
382 if ( !in_array( 'skin', $this->getConfig()->get( 'HiddenPrefs' ) ) ) {
383 # get the user skin
384 $userSkin = $this->getUser()->getOption( 'skin' );
385 $userSkin = $this->getRequest()->getVal( 'useskin', $userSkin );
386 } else {
387 # if we're not allowing users to override, then use the default
388 $userSkin = $this->getConfig()->get( 'DefaultSkin' );
391 // Normalize the key in case the user is passing gibberish
392 // or has old preferences (bug 69566).
393 $normalized = Skin::normalizeKey( $userSkin );
395 // Skin::normalizeKey will also validate it, so
396 // this won't throw an exception
397 $this->skin = $factory->makeSkin( $normalized );
400 // After all that set a context on whatever skin got created
401 $this->skin->setContext( $this );
402 wfProfileOut( __METHOD__ . '-createskin' );
405 return $this->skin;
408 /** Helpful methods **/
411 * Get a Message object with context set
412 * Parameters are the same as wfMessage()
414 * @return Message
416 public function msg() {
417 $args = func_get_args();
419 return call_user_func_array( 'wfMessage', $args )->setContext( $this );
422 /** Static methods **/
425 * Get the RequestContext object associated with the main request
427 * @return RequestContext
429 public static function getMain() {
430 if ( self::$instance === null ) {
431 self::$instance = new self;
434 return self::$instance;
438 * Get the RequestContext object associated with the main request
439 * and gives a warning to the log, to find places, where a context maybe is missing.
441 * @param string $func
442 * @return RequestContext
443 * @since 1.24
445 public static function getMainAndWarn( $func = __METHOD__ ) {
446 wfDebug( $func . ' called without context. ' .
447 "Using RequestContext::getMain() for sanity\n" );
449 return self::getMain();
453 * Resets singleton returned by getMain(). Should be called only from unit tests.
455 public static function resetMain() {
456 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
457 throw new MWException( __METHOD__ . '() should be called only from unit tests!' );
459 self::$instance = null;
463 * Export the resolved user IP, HTTP headers, user ID, and session ID.
464 * The result will be reasonably sized to allow for serialization.
466 * @return array
467 * @since 1.21
469 public function exportSession() {
470 return array(
471 'ip' => $this->getRequest()->getIP(),
472 'headers' => $this->getRequest()->getAllHeaders(),
473 'sessionId' => session_id(),
474 'userId' => $this->getUser()->getId()
479 * Import an client IP address, HTTP headers, user ID, and session ID
481 * This sets the current session and sets $wgUser and $wgRequest.
482 * Once the return value falls out of scope, the old context is restored.
483 * This method should only be called in contexts (CLI or HTTP job runners)
484 * where there is no session ID or end user receiving the response. This
485 * is partly enforced, and is done so to avoid leaking cookies if certain
486 * error conditions arise.
488 * This will setup the session from the given ID. This is useful when
489 * background scripts inherit context when acting on behalf of a user.
491 * @note suhosin.session.encrypt may interfere with this method.
493 * @param array $params Result of RequestContext::exportSession()
494 * @return ScopedCallback
495 * @throws MWException
496 * @since 1.21
498 public static function importScopedSession( array $params ) {
499 if ( session_id() != '' && strlen( $params['sessionId'] ) ) {
500 // Sanity check to avoid sending random cookies for the wrong users.
501 // This method should only called by CLI scripts or by HTTP job runners.
502 throw new MWException( "Sessions can only be imported when none is active." );
503 } elseif ( !IP::isValid( $params['ip'] ) ) {
504 throw new MWException( "Invalid client IP address '{$params['ip']}'." );
507 if ( $params['userId'] ) { // logged-in user
508 $user = User::newFromId( $params['userId'] );
509 $user->load();
510 if ( !$user->getId() ) {
511 throw new MWException( "No user with ID '{$params['userId']}'." );
513 } else { // anon user
514 $user = User::newFromName( $params['ip'], false );
517 $importSessionFunc = function ( User $user, array $params ) {
518 global $wgRequest, $wgUser;
520 $context = RequestContext::getMain();
521 // Commit and close any current session
522 session_write_close(); // persist
523 session_id( '' ); // detach
524 $_SESSION = array(); // clear in-memory array
525 // Remove any user IP or agent information
526 $context->setRequest( new FauxRequest() );
527 $wgRequest = $context->getRequest(); // b/c
528 // Now that all private information is detached from the user, it should
529 // be safe to load the new user. If errors occur or an exception is thrown
530 // and caught (leaving the main context in a mixed state), there is no risk
531 // of the User object being attached to the wrong IP, headers, or session.
532 $context->setUser( $user );
533 $wgUser = $context->getUser(); // b/c
534 if ( strlen( $params['sessionId'] ) ) { // don't make a new random ID
535 wfSetupSession( $params['sessionId'] ); // sets $_SESSION
537 $request = new FauxRequest( array(), false, $_SESSION );
538 $request->setIP( $params['ip'] );
539 foreach ( $params['headers'] as $name => $value ) {
540 $request->setHeader( $name, $value );
542 // Set the current context to use the new WebRequest
543 $context->setRequest( $request );
544 $wgRequest = $context->getRequest(); // b/c
547 // Stash the old session and load in the new one
548 $oUser = self::getMain()->getUser();
549 $oParams = self::getMain()->exportSession();
550 $oRequest = self::getMain()->getRequest();
551 $importSessionFunc( $user, $params );
553 // Set callback to save and close the new session and reload the old one
554 return new ScopedCallback(
555 function () use ( $importSessionFunc, $oUser, $oParams, $oRequest ) {
556 global $wgRequest;
557 $importSessionFunc( $oUser, $oParams );
558 // Restore the exact previous Request object (instead of leaving FauxRequest)
559 RequestContext::getMain()->setRequest( $oRequest );
560 $wgRequest = RequestContext::getMain()->getRequest(); // b/c
566 * Create a new extraneous context. The context is filled with information
567 * external to the current session.
568 * - Title is specified by argument
569 * - Request is a FauxRequest, or a FauxRequest can be specified by argument
570 * - User is an anonymous user, for separation IPv4 localhost is used
571 * - Language will be based on the anonymous user and request, may be content
572 * language or a uselang param in the fauxrequest data may change the lang
573 * - Skin will be based on the anonymous user, should be the wiki's default skin
575 * @param Title $title Title to use for the extraneous request
576 * @param WebRequest|array $request A WebRequest or data to use for a FauxRequest
577 * @return RequestContext
579 public static function newExtraneousContext( Title $title, $request = array() ) {
580 $context = new self;
581 $context->setTitle( $title );
582 if ( $request instanceof WebRequest ) {
583 $context->setRequest( $request );
584 } else {
585 $context->setRequest( new FauxRequest( $request ) );
587 $context->user = User::newFromName( '127.0.0.1', false );
589 return $context;