Merge "JSDuck-ify /resources/mediawiki.action/*"
[mediawiki.git] / includes / context / RequestContext.php
blob6f27a7ae82f3a35f82afc2e8c222f1d4c0048ec5
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 * Set the Config object
74 * @param Config $c
76 public function setConfig( Config $c ) {
77 $this->config = $c;
80 /**
81 * Get the Config object
83 * @return Config
85 public function getConfig() {
86 if ( $this->config === null ) {
87 $this->config = Config::factory();
90 return $this->config;
93 /**
94 * Set the WebRequest object
96 * @param WebRequest $r
98 public function setRequest( WebRequest $r ) {
99 $this->request = $r;
103 * Get the WebRequest object
105 * @return WebRequest
107 public function getRequest() {
108 if ( $this->request === null ) {
109 global $wgRequest; # fallback to $wg till we can improve this
110 $this->request = $wgRequest;
113 return $this->request;
117 * Set the Title object
119 * @param Title $t
120 * @throws MWException
122 public function setTitle( $t ) {
123 if ( $t !== null && !$t instanceof Title ) {
124 throw new MWException( __METHOD__ . " expects an instance of Title" );
126 $this->title = $t;
127 // Erase the WikiPage so a new one with the new title gets created.
128 $this->wikipage = null;
132 * Get the Title object
134 * @return Title
136 public function getTitle() {
137 if ( $this->title === null ) {
138 global $wgTitle; # fallback to $wg till we can improve this
139 $this->title = $wgTitle;
142 return $this->title;
146 * Check whether a WikiPage object can be get with getWikiPage().
147 * Callers should expect that an exception is thrown from getWikiPage()
148 * if this method returns false.
150 * @since 1.19
151 * @return bool
153 public function canUseWikiPage() {
154 if ( $this->wikipage !== null ) {
155 # If there's a WikiPage object set, we can for sure get it
156 return true;
158 $title = $this->getTitle();
159 if ( $title === null ) {
160 # No Title, no WikiPage
161 return false;
162 } else {
163 # Only namespaces whose pages are stored in the database can have WikiPage
164 return $title->canExist();
169 * Set the WikiPage object
171 * @since 1.19
172 * @param WikiPage $p
174 public function setWikiPage( WikiPage $p ) {
175 $contextTitle = $this->getTitle();
176 $pageTitle = $p->getTitle();
177 if ( !$contextTitle || !$pageTitle->equals( $contextTitle ) ) {
178 $this->setTitle( $pageTitle );
180 // Defer this to the end since setTitle sets it to null.
181 $this->wikipage = $p;
185 * Get the WikiPage object.
186 * May throw an exception if there's no Title object set or the Title object
187 * belongs to a special namespace that doesn't have WikiPage, so use first
188 * canUseWikiPage() to check whether this method can be called safely.
190 * @since 1.19
191 * @throws MWException
192 * @return WikiPage
194 public function getWikiPage() {
195 if ( $this->wikipage === null ) {
196 $title = $this->getTitle();
197 if ( $title === null ) {
198 throw new MWException( __METHOD__ . ' called without Title object set' );
200 $this->wikipage = WikiPage::factory( $title );
203 return $this->wikipage;
207 * @param OutputPage $o
209 public function setOutput( OutputPage $o ) {
210 $this->output = $o;
214 * Get the OutputPage object
216 * @return OutputPage
218 public function getOutput() {
219 if ( $this->output === null ) {
220 $this->output = new OutputPage( $this );
223 return $this->output;
227 * Set the User object
229 * @param User $u
231 public function setUser( User $u ) {
232 $this->user = $u;
236 * Get the User object
238 * @return User
240 public function getUser() {
241 if ( $this->user === null ) {
242 $this->user = User::newFromSession( $this->getRequest() );
245 return $this->user;
249 * Accepts a language code and ensures it's sane. Outputs a cleaned up language
250 * code and replaces with $wgLanguageCode if not sane.
251 * @param string $code Language code
252 * @return string
254 public static function sanitizeLangCode( $code ) {
255 global $wgLanguageCode;
257 // BCP 47 - letter case MUST NOT carry meaning
258 $code = strtolower( $code );
260 # Validate $code
261 if ( empty( $code ) || !Language::isValidCode( $code ) || ( $code === 'qqq' ) ) {
262 wfDebug( "Invalid user language code\n" );
263 $code = $wgLanguageCode;
266 return $code;
270 * Set the Language object
272 * @deprecated since 1.19 Use setLanguage instead
273 * @param Language|string $l Language instance or language code
275 public function setLang( $l ) {
276 wfDeprecated( __METHOD__, '1.19' );
277 $this->setLanguage( $l );
281 * Set the Language object
283 * @param Language|string $l Language instance or language code
284 * @throws MWException
285 * @since 1.19
287 public function setLanguage( $l ) {
288 if ( $l instanceof Language ) {
289 $this->lang = $l;
290 } elseif ( is_string( $l ) ) {
291 $l = self::sanitizeLangCode( $l );
292 $obj = Language::factory( $l );
293 $this->lang = $obj;
294 } else {
295 throw new MWException( __METHOD__ . " was passed an invalid type of data." );
300 * @deprecated since 1.19 Use getLanguage instead
301 * @return Language
303 public function getLang() {
304 wfDeprecated( __METHOD__, '1.19' );
306 return $this->getLanguage();
310 * Get the Language object.
311 * Initialization of user or request objects can depend on this.
313 * @return Language
314 * @since 1.19
316 public function getLanguage() {
317 if ( isset( $this->recursion ) ) {
318 trigger_error( "Recursion detected in " . __METHOD__, E_USER_WARNING );
319 $e = new Exception;
320 wfDebugLog( 'recursion-guard', "Recursion detected:\n" . $e->getTraceAsString() );
322 global $wgLanguageCode;
323 $code = ( $wgLanguageCode ) ? $wgLanguageCode : 'en';
324 $this->lang = Language::factory( $code );
325 } elseif ( $this->lang === null ) {
326 $this->recursion = true;
328 global $wgLanguageCode, $wgContLang;
330 $request = $this->getRequest();
331 $user = $this->getUser();
333 $code = $request->getVal( 'uselang', $user->getOption( 'language' ) );
334 $code = self::sanitizeLangCode( $code );
336 wfRunHooks( 'UserGetLanguageObject', array( $user, &$code, $this ) );
338 if ( $code === $wgLanguageCode ) {
339 $this->lang = $wgContLang;
340 } else {
341 $obj = Language::factory( $code );
342 $this->lang = $obj;
345 unset( $this->recursion );
348 return $this->lang;
352 * Set the Skin object
354 * @param Skin $s
356 public function setSkin( Skin $s ) {
357 $this->skin = clone $s;
358 $this->skin->setContext( $this );
362 * Get the Skin object
364 * @return Skin
366 public function getSkin() {
367 if ( $this->skin === null ) {
368 wfProfileIn( __METHOD__ . '-createskin' );
370 $skin = null;
371 wfRunHooks( 'RequestContextCreateSkin', array( $this, &$skin ) );
373 // If the hook worked try to set a skin from it
374 if ( $skin instanceof Skin ) {
375 $this->skin = $skin;
376 } elseif ( is_string( $skin ) ) {
377 $this->skin = Skin::newFromKey( $skin );
380 // If this is still null (the hook didn't run or didn't work)
381 // then go through the normal processing to load a skin
382 if ( $this->skin === null ) {
383 global $wgHiddenPrefs;
384 if ( !in_array( 'skin', $wgHiddenPrefs ) ) {
385 # get the user skin
386 $userSkin = $this->getUser()->getOption( 'skin' );
387 $userSkin = $this->getRequest()->getVal( 'useskin', $userSkin );
388 } else {
389 # if we're not allowing users to override, then use the default
390 global $wgDefaultSkin;
391 $userSkin = $wgDefaultSkin;
394 $this->skin = Skin::newFromKey( $userSkin );
397 // After all that set a context on whatever skin got created
398 $this->skin->setContext( $this );
399 wfProfileOut( __METHOD__ . '-createskin' );
402 return $this->skin;
405 /** Helpful methods **/
408 * Get a Message object with context set
409 * Parameters are the same as wfMessage()
411 * @return Message
413 public function msg() {
414 $args = func_get_args();
416 return call_user_func_array( 'wfMessage', $args )->setContext( $this );
419 /** Static methods **/
422 * Get the RequestContext object associated with the main request
424 * @return RequestContext
426 public static function getMain() {
427 static $instance = null;
428 if ( $instance === null ) {
429 $instance = new self;
432 return $instance;
436 * Export the resolved user IP, HTTP headers, user ID, and session ID.
437 * The result will be reasonably sized to allow for serialization.
439 * @return array
440 * @since 1.21
442 public function exportSession() {
443 return array(
444 'ip' => $this->getRequest()->getIP(),
445 'headers' => $this->getRequest()->getAllHeaders(),
446 'sessionId' => session_id(),
447 'userId' => $this->getUser()->getId()
452 * Import the resolved user IP, HTTP headers, user ID, and session ID.
453 * This sets the current session and sets $wgUser and $wgRequest.
454 * Once the return value falls out of scope, the old context is restored.
455 * This function can only be called within CLI mode scripts.
457 * This will setup the session from the given ID. This is useful when
458 * background scripts inherit context when acting on behalf of a user.
460 * @note suhosin.session.encrypt may interfere with this method.
462 * @param array $params Result of RequestContext::exportSession()
463 * @return ScopedCallback
464 * @throws MWException
465 * @since 1.21
467 public static function importScopedSession( array $params ) {
468 if ( PHP_SAPI !== 'cli' ) {
469 // Don't send random private cookies or turn $wgRequest into FauxRequest
470 throw new MWException( "Sessions can only be imported in cli mode." );
471 } elseif ( !strlen( $params['sessionId'] ) ) {
472 throw new MWException( "No session ID was specified." );
475 if ( $params['userId'] ) { // logged-in user
476 $user = User::newFromId( $params['userId'] );
477 if ( !$user ) {
478 throw new MWException( "No user with ID '{$params['userId']}'." );
480 } elseif ( !IP::isValid( $params['ip'] ) ) {
481 throw new MWException( "Could not load user '{$params['ip']}'." );
482 } else { // anon user
483 $user = User::newFromName( $params['ip'], false );
486 $importSessionFunction = function ( User $user, array $params ) {
487 global $wgRequest, $wgUser;
489 $context = RequestContext::getMain();
490 // Commit and close any current session
491 session_write_close(); // persist
492 session_id( '' ); // detach
493 $_SESSION = array(); // clear in-memory array
494 // Remove any user IP or agent information
495 $context->setRequest( new FauxRequest() );
496 $wgRequest = $context->getRequest(); // b/c
497 // Now that all private information is detached from the user, it should
498 // be safe to load the new user. If errors occur or an exception is thrown
499 // and caught (leaving the main context in a mixed state), there is no risk
500 // of the User object being attached to the wrong IP, headers, or session.
501 $context->setUser( $user );
502 $wgUser = $context->getUser(); // b/c
503 if ( strlen( $params['sessionId'] ) ) { // don't make a new random ID
504 wfSetupSession( $params['sessionId'] ); // sets $_SESSION
506 $request = new FauxRequest( array(), false, $_SESSION );
507 $request->setIP( $params['ip'] );
508 foreach ( $params['headers'] as $name => $value ) {
509 $request->setHeader( $name, $value );
511 // Set the current context to use the new WebRequest
512 $context->setRequest( $request );
513 $wgRequest = $context->getRequest(); // b/c
516 // Stash the old session and load in the new one
517 $oUser = self::getMain()->getUser();
518 $oParams = self::getMain()->exportSession();
519 $importSessionFunction( $user, $params );
521 // Set callback to save and close the new session and reload the old one
522 return new ScopedCallback( function () use ( $importSessionFunction, $oUser, $oParams ) {
523 $importSessionFunction( $oUser, $oParams );
524 } );
528 * Create a new extraneous context. The context is filled with information
529 * external to the current session.
530 * - Title is specified by argument
531 * - Request is a FauxRequest, or a FauxRequest can be specified by argument
532 * - User is an anonymous user, for separation IPv4 localhost is used
533 * - Language will be based on the anonymous user and request, may be content
534 * language or a uselang param in the fauxrequest data may change the lang
535 * - Skin will be based on the anonymous user, should be the wiki's default skin
537 * @param Title $title Title to use for the extraneous request
538 * @param WebRequest|array $request A WebRequest or data to use for a FauxRequest
539 * @return RequestContext
541 public static function newExtraneousContext( Title $title, $request = array() ) {
542 $context = new self;
543 $context->setTitle( $title );
544 if ( $request instanceof WebRequest ) {
545 $context->setRequest( $request );
546 } else {
547 $context->setRequest( new FauxRequest( $request ) );
549 $context->user = User::newFromName( '127.0.0.1', false );
551 return $context;