Merge "Typo fix"
[mediawiki.git] / includes / context / RequestContext.php
blobb9dbe77e16ddd60221d7f17842b673711d726b6b
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 * Set the WebRequest object
69 * @param WebRequest $r
71 public function setRequest( WebRequest $r ) {
72 $this->request = $r;
75 /**
76 * Get the WebRequest object
78 * @return WebRequest
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;
88 /**
89 * Set the Title object
91 * @param Title $t
93 public function setTitle( Title $t ) {
94 $this->title = $t;
95 // Erase the WikiPage so a new one with the new title gets created.
96 $this->wikipage = null;
99 /**
100 * Get the Title object
102 * @return Title
104 public function getTitle() {
105 if ( $this->title === null ) {
106 global $wgTitle; # fallback to $wg till we can improve this
107 $this->title = $wgTitle;
109 return $this->title;
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.
117 * @since 1.19
118 * @return bool
120 public function canUseWikiPage() {
121 if ( $this->wikipage !== null ) {
122 # If there's a WikiPage object set, we can for sure get it
123 return true;
125 $title = $this->getTitle();
126 if ( $title === null ) {
127 # No Title, no WikiPage
128 return false;
129 } else {
130 # Only namespaces whose pages are stored in the database can have WikiPage
131 return $title->canExist();
136 * Set the WikiPage object
138 * @since 1.19
139 * @param WikiPage $p
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.
157 * @since 1.19
158 * @throws MWException
159 * @return WikiPage
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 ) {
176 $this->output = $o;
180 * Get the OutputPage object
182 * @return OutputPage
184 public function getOutput() {
185 if ( $this->output === null ) {
186 $this->output = new OutputPage( $this );
188 return $this->output;
192 * Set the User object
194 * @param User $u
196 public function setUser( User $u ) {
197 $this->user = $u;
201 * Get the User object
203 * @return User
205 public function getUser() {
206 if ( $this->user === null ) {
207 $this->user = User::newFromSession( $this->getRequest() );
209 return $this->user;
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
216 * @return string
218 public static function sanitizeLangCode( $code ) {
219 global $wgLanguageCode;
221 // BCP 47 - letter case MUST NOT carry meaning
222 $code = strtolower( $code );
224 # Validate $code
225 if ( empty( $code ) || !Language::isValidCode( $code ) || ( $code === 'qqq' ) ) {
226 wfDebug( "Invalid user language code\n" );
227 $code = $wgLanguageCode;
230 return $code;
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
249 * @since 1.19
251 public function setLanguage( $l ) {
252 if ( $l instanceof Language ) {
253 $this->lang = $l;
254 } elseif ( is_string( $l ) ) {
255 $l = self::sanitizeLangCode( $l );
256 $obj = Language::factory( $l );
257 $this->lang = $obj;
258 } else {
259 throw new MWException( __METHOD__ . " was passed an invalid type of data." );
264 * @deprecated since 1.19 Use getLanguage instead
265 * @return Language
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.
276 * @return Language
277 * @since 1.19
279 public function getLanguage() {
280 if ( isset( $this->recursion ) ) {
281 trigger_error( "Recursion detected in " . __METHOD__, E_USER_WARNING );
282 $e = new Exception;
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;
303 } else {
304 $obj = Language::factory( $code );
305 $this->lang = $obj;
308 unset( $this->recursion );
311 return $this->lang;
315 * Set the Skin object
317 * @param Skin $s
319 public function setSkin( Skin $s ) {
320 $this->skin = clone $s;
321 $this->skin->setContext( $this );
325 * Get the Skin object
327 * @return Skin
329 public function getSkin() {
330 if ( $this->skin === null ) {
331 wfProfileIn( __METHOD__ . '-createskin' );
333 $skin = null;
334 wfRunHooks( 'RequestContextCreateSkin', array( $this, &$skin ) );
336 // If the hook worked try to set a skin from it
337 if ( $skin instanceof Skin ) {
338 $this->skin = $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 ) ) {
348 # get the user skin
349 $userSkin = $this->getUser()->getOption( 'skin' );
350 $userSkin = $this->getRequest()->getVal( 'useskin', $userSkin );
351 } else {
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' );
364 return $this->skin;
367 /** Helpful methods **/
370 * Get a Message object with context set
371 * Parameters are the same as wfMessage()
373 * @return Message
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;
392 return $instance;
396 * Export the resolved user IP, HTTP headers, user ID, and session ID.
397 * The result will be reasonably sized to allow for serialization.
399 * @return Array
400 * @since 1.21
402 public function exportSession() {
403 return array(
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 * @note suhosin.session.encrypt may interfere with this method.
422 * @param array $params Result of RequestContext::exportSession()
423 * @return ScopedCallback
424 * @throws MWException
425 * @since 1.21
427 public static function importScopedSession( array $params ) {
428 if ( PHP_SAPI !== 'cli' ) {
429 // Don't send random private cookies or turn $wgRequest into FauxRequest
430 throw new MWException( "Sessions can only be imported in cli mode." );
431 } elseif ( !strlen( $params['sessionId'] ) ) {
432 throw new MWException( "No session ID was specified." );
435 if ( $params['userId'] ) { // logged-in user
436 $user = User::newFromId( $params['userId'] );
437 if ( !$user ) {
438 throw new MWException( "No user with ID '{$params['userId']}'." );
440 } elseif ( !IP::isValid( $params['ip'] ) ) {
441 throw new MWException( "Could not load user '{$params['ip']}'." );
442 } else { // anon user
443 $user = User::newFromName( $params['ip'], false );
446 $importSessionFunction = function( User $user, array $params ) {
447 global $wgRequest, $wgUser;
449 $context = RequestContext::getMain();
450 // Commit and close any current session
451 session_write_close(); // persist
452 session_id( '' ); // detach
453 $_SESSION = array(); // clear in-memory array
454 // Remove any user IP or agent information
455 $context->setRequest( new FauxRequest() );
456 $wgRequest = $context->getRequest(); // b/c
457 // Now that all private information is detached from the user, it should
458 // be safe to load the new user. If errors occur or an exception is thrown
459 // and caught (leaving the main context in a mixed state), there is no risk
460 // of the User object being attached to the wrong IP, headers, or session.
461 $context->setUser( $user );
462 $wgUser = $context->getUser(); // b/c
463 if ( strlen( $params['sessionId'] ) ) { // don't make a new random ID
464 wfSetupSession( $params['sessionId'] ); // sets $_SESSION
466 $request = new FauxRequest( array(), false, $_SESSION );
467 $request->setIP( $params['ip'] );
468 foreach ( $params['headers'] as $name => $value ) {
469 $request->setHeader( $name, $value );
471 // Set the current context to use the new WebRequest
472 $context->setRequest( $request );
473 $wgRequest = $context->getRequest(); // b/c
476 // Stash the old session and load in the new one
477 $oUser = self::getMain()->getUser();
478 $oParams = self::getMain()->exportSession();
479 $importSessionFunction( $user, $params );
481 // Set callback to save and close the new session and reload the old one
482 return new ScopedCallback( function() use ( $importSessionFunction, $oUser, $oParams ) {
483 $importSessionFunction( $oUser, $oParams );
484 } );
488 * Create a new extraneous context. The context is filled with information
489 * external to the current session.
490 * - Title is specified by argument
491 * - Request is a FauxRequest, or a FauxRequest can be specified by argument
492 * - User is an anonymous user, for separation IPv4 localhost is used
493 * - Language will be based on the anonymous user and request, may be content
494 * language or a uselang param in the fauxrequest data may change the lang
495 * - Skin will be based on the anonymous user, should be the wiki's default skin
497 * @param Title $title Title to use for the extraneous request
498 * @param WebRequest|array $request A WebRequest or data to use for a FauxRequest
499 * @return RequestContext
501 public static function newExtraneousContext( Title $title, $request = array() ) {
502 $context = new self;
503 $context->setTitle( $title );
504 if ( $request instanceof WebRequest ) {
505 $context->setRequest( $request );
506 } else {
507 $context->setRequest( new FauxRequest( $request ) );
509 $context->user = User::newFromName( '127.0.0.1', false );
510 return $context;