Added clarifying comments to IContextSource
[lhc/web/wiklou.git] / includes / context / RequestContext.php
1 <?php
2 /**
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.
7 *
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.
12 *
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
17 *
18 * @since 1.18
19 *
20 * @author Alexandre Emsenhuber
21 * @author Daniel Friesen
22 * @file
23 */
24
25 /**
26 * Group all the pieces relevant to the context of a request into one instance
27 */
28 class RequestContext implements IContextSource {
29 /**
30 * @var WebRequest
31 */
32 private $request;
33
34 /**
35 * @var Title
36 */
37 private $title;
38
39 /**
40 * @var WikiPage
41 */
42 private $wikipage;
43
44 /**
45 * @var OutputPage
46 */
47 private $output;
48
49 /**
50 * @var User
51 */
52 private $user;
53
54 /**
55 * @var Language
56 */
57 private $lang;
58
59 /**
60 * @var Skin
61 */
62 private $skin;
63
64 /**
65 * @var Config
66 */
67 private $config;
68
69 /**
70 * @var RequestContext
71 */
72 private static $instance = null;
73
74 /**
75 * Set the Config object
76 *
77 * @param Config $c
78 */
79 public function setConfig( Config $c ) {
80 $this->config = $c;
81 }
82
83 /**
84 * Get the Config object
85 *
86 * @return Config
87 */
88 public function getConfig() {
89 if ( $this->config === null ) {
90 // @todo In the future, we could move this to WebStart.php so
91 // the Config object is ready for when initialization happens
92 $this->config = ConfigFactory::getDefaultInstance()->makeConfig( 'main' );
93 }
94
95 return $this->config;
96 }
97
98 /**
99 * Set the WebRequest object
100 *
101 * @param WebRequest $r
102 */
103 public function setRequest( WebRequest $r ) {
104 $this->request = $r;
105 }
106
107 /**
108 * Get the WebRequest object
109 *
110 * @return WebRequest
111 */
112 public function getRequest() {
113 if ( $this->request === null ) {
114 global $wgRequest; # fallback to $wg till we can improve this
115 $this->request = $wgRequest;
116 }
117
118 return $this->request;
119 }
120
121 /**
122 * Set the Title object
123 *
124 * @param Title $title
125 */
126 public function setTitle( Title $title ) {
127 $this->title = $title;
128 // Erase the WikiPage so a new one with the new title gets created.
129 $this->wikipage = null;
130 }
131
132 /**
133 * Get the Title object
134 *
135 * @return Title|null
136 */
137 public function getTitle() {
138 if ( $this->title === null ) {
139 global $wgTitle; # fallback to $wg till we can improve this
140 $this->title = $wgTitle;
141 wfDebugLog( 'GlobalTitleFail', __METHOD__ . ' called by ' . wfGetAllCallers( 5 ) . ' with no title set.' );
142 }
143
144 return $this->title;
145 }
146
147 /**
148 * Check, if a Title object is set
149 *
150 * @since 1.25
151 * @return bool
152 */
153 public function hasTitle() {
154 return $this->title !== null;
155 }
156
157 /**
158 * Check whether a WikiPage object can be get with getWikiPage().
159 * Callers should expect that an exception is thrown from getWikiPage()
160 * if this method returns false.
161 *
162 * @since 1.19
163 * @return bool
164 */
165 public function canUseWikiPage() {
166 if ( $this->wikipage ) {
167 // If there's a WikiPage object set, we can for sure get it
168 return true;
169 }
170 // Only pages with legitimate titles can have WikiPages.
171 // That usually means pages in non-virtual namespaces.
172 $title = $this->getTitle();
173 return $title ? $title->canExist() : false;
174 }
175
176 /**
177 * Set the WikiPage object
178 *
179 * @since 1.19
180 * @param WikiPage $p
181 */
182 public function setWikiPage( WikiPage $p ) {
183 $pageTitle = $p->getTitle();
184 if ( !$this->hasTitle() || !$pageTitle->equals( $this->getTitle() ) ) {
185 $this->setTitle( $pageTitle );
186 }
187 // Defer this to the end since setTitle sets it to null.
188 $this->wikipage = $p;
189 }
190
191 /**
192 * Get the WikiPage object.
193 * May throw an exception if there's no Title object set or the Title object
194 * belongs to a special namespace that doesn't have WikiPage, so use first
195 * canUseWikiPage() to check whether this method can be called safely.
196 *
197 * @since 1.19
198 * @throws MWException
199 * @return WikiPage
200 */
201 public function getWikiPage() {
202 if ( $this->wikipage === null ) {
203 $title = $this->getTitle();
204 if ( $title === null ) {
205 throw new MWException( __METHOD__ . ' called without Title object set' );
206 }
207 $this->wikipage = WikiPage::factory( $title );
208 }
209
210 return $this->wikipage;
211 }
212
213 /**
214 * @param OutputPage $o
215 */
216 public function setOutput( OutputPage $o ) {
217 $this->output = $o;
218 }
219
220 /**
221 * Get the OutputPage object
222 *
223 * @return OutputPage
224 */
225 public function getOutput() {
226 if ( $this->output === null ) {
227 $this->output = new OutputPage( $this );
228 }
229
230 return $this->output;
231 }
232
233 /**
234 * Set the User object
235 *
236 * @param User $u
237 */
238 public function setUser( User $u ) {
239 $this->user = $u;
240 }
241
242 /**
243 * Get the User object
244 *
245 * @return User
246 */
247 public function getUser() {
248 if ( $this->user === null ) {
249 $this->user = User::newFromSession( $this->getRequest() );
250 }
251
252 return $this->user;
253 }
254
255 /**
256 * Accepts a language code and ensures it's sane. Outputs a cleaned up language
257 * code and replaces with $wgLanguageCode if not sane.
258 * @param string $code Language code
259 * @return string
260 */
261 public static function sanitizeLangCode( $code ) {
262 global $wgLanguageCode;
263
264 // BCP 47 - letter case MUST NOT carry meaning
265 $code = strtolower( $code );
266
267 # Validate $code
268 if ( !$code || !Language::isValidCode( $code ) || $code === 'qqq' ) {
269 wfDebug( "Invalid user language code\n" );
270 $code = $wgLanguageCode;
271 }
272
273 return $code;
274 }
275
276 /**
277 * Set the Language object
278 *
279 * @param Language|string $l Language instance or language code
280 * @throws MWException
281 * @since 1.19
282 */
283 public function setLanguage( $l ) {
284 if ( $l instanceof Language ) {
285 $this->lang = $l;
286 } elseif ( is_string( $l ) ) {
287 $l = self::sanitizeLangCode( $l );
288 $obj = Language::factory( $l );
289 $this->lang = $obj;
290 } else {
291 throw new MWException( __METHOD__ . " was passed an invalid type of data." );
292 }
293 }
294
295 /**
296 * Get the Language object.
297 * Initialization of user or request objects can depend on this.
298 * @return Language
299 * @throws Exception
300 * @since 1.19
301 */
302 public function getLanguage() {
303 if ( isset( $this->recursion ) ) {
304 trigger_error( "Recursion detected in " . __METHOD__, E_USER_WARNING );
305 $e = new Exception;
306 wfDebugLog( 'recursion-guard', "Recursion detected:\n" . $e->getTraceAsString() );
307
308 $code = $this->getConfig()->get( 'LanguageCode' ) ?: 'en';
309 $this->lang = Language::factory( $code );
310 } elseif ( $this->lang === null ) {
311 $this->recursion = true;
312
313 global $wgContLang;
314
315 try {
316 $request = $this->getRequest();
317 $user = $this->getUser();
318
319 $code = $request->getVal( 'uselang', 'user' );
320 if ( $code === 'user' ) {
321 $code = $user->getOption( 'language' );
322 }
323 $code = self::sanitizeLangCode( $code );
324
325 Hooks::run( 'UserGetLanguageObject', array( $user, &$code, $this ) );
326
327 if ( $code === $this->getConfig()->get( 'LanguageCode' ) ) {
328 $this->lang = $wgContLang;
329 } else {
330 $obj = Language::factory( $code );
331 $this->lang = $obj;
332 }
333
334 unset( $this->recursion );
335 }
336 catch ( Exception $ex ) {
337 unset( $this->recursion );
338 throw $ex;
339 }
340 }
341
342 return $this->lang;
343 }
344
345 /**
346 * Set the Skin object
347 *
348 * @param Skin $s
349 */
350 public function setSkin( Skin $s ) {
351 $this->skin = clone $s;
352 $this->skin->setContext( $this );
353 }
354
355 /**
356 * Get the Skin object
357 *
358 * @return Skin
359 */
360 public function getSkin() {
361 if ( $this->skin === null ) {
362
363 $skin = null;
364 Hooks::run( 'RequestContextCreateSkin', array( $this, &$skin ) );
365 $factory = SkinFactory::getDefaultInstance();
366
367 // If the hook worked try to set a skin from it
368 if ( $skin instanceof Skin ) {
369 $this->skin = $skin;
370 } elseif ( is_string( $skin ) ) {
371 // Normalize the key, just in case the hook did something weird.
372 $normalized = Skin::normalizeKey( $skin );
373 $this->skin = $factory->makeSkin( $normalized );
374 }
375
376 // If this is still null (the hook didn't run or didn't work)
377 // then go through the normal processing to load a skin
378 if ( $this->skin === null ) {
379 if ( !in_array( 'skin', $this->getConfig()->get( 'HiddenPrefs' ) ) ) {
380 # get the user skin
381 $userSkin = $this->getUser()->getOption( 'skin' );
382 $userSkin = $this->getRequest()->getVal( 'useskin', $userSkin );
383 } else {
384 # if we're not allowing users to override, then use the default
385 $userSkin = $this->getConfig()->get( 'DefaultSkin' );
386 }
387
388 // Normalize the key in case the user is passing gibberish
389 // or has old preferences (bug 69566).
390 $normalized = Skin::normalizeKey( $userSkin );
391
392 // Skin::normalizeKey will also validate it, so
393 // this won't throw an exception
394 $this->skin = $factory->makeSkin( $normalized );
395 }
396
397 // After all that set a context on whatever skin got created
398 $this->skin->setContext( $this );
399 }
400
401 return $this->skin;
402 }
403
404 /** Helpful methods **/
405
406 /**
407 * Get a Message object with context set
408 * Parameters are the same as wfMessage()
409 *
410 * @return Message
411 */
412 public function msg() {
413 $args = func_get_args();
414
415 return call_user_func_array( 'wfMessage', $args )->setContext( $this );
416 }
417
418 /** Static methods **/
419
420 /**
421 * Get the RequestContext object associated with the main request
422 *
423 * @return RequestContext
424 */
425 public static function getMain() {
426 if ( self::$instance === null ) {
427 self::$instance = new self;
428 }
429
430 return self::$instance;
431 }
432
433 /**
434 * Get the RequestContext object associated with the main request
435 * and gives a warning to the log, to find places, where a context maybe is missing.
436 *
437 * @param string $func
438 * @return RequestContext
439 * @since 1.24
440 */
441 public static function getMainAndWarn( $func = __METHOD__ ) {
442 wfDebug( $func . ' called without context. ' .
443 "Using RequestContext::getMain() for sanity\n" );
444
445 return self::getMain();
446 }
447
448 /**
449 * Resets singleton returned by getMain(). Should be called only from unit tests.
450 */
451 public static function resetMain() {
452 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
453 throw new MWException( __METHOD__ . '() should be called only from unit tests!' );
454 }
455 self::$instance = null;
456 }
457
458 /**
459 * Export the resolved user IP, HTTP headers, user ID, and session ID.
460 * The result will be reasonably sized to allow for serialization.
461 *
462 * @return array
463 * @since 1.21
464 */
465 public function exportSession() {
466 return array(
467 'ip' => $this->getRequest()->getIP(),
468 'headers' => $this->getRequest()->getAllHeaders(),
469 'sessionId' => session_id(),
470 'userId' => $this->getUser()->getId()
471 );
472 }
473
474 /**
475 * Import an client IP address, HTTP headers, user ID, and session ID
476 *
477 * This sets the current session and sets $wgUser and $wgRequest.
478 * Once the return value falls out of scope, the old context is restored.
479 * This method should only be called in contexts (CLI or HTTP job runners)
480 * where there is no session ID or end user receiving the response. This
481 * is partly enforced, and is done so to avoid leaking cookies if certain
482 * error conditions arise.
483 *
484 * This will setup the session from the given ID. This is useful when
485 * background scripts inherit context when acting on behalf of a user.
486 *
487 * @note suhosin.session.encrypt may interfere with this method.
488 *
489 * @param array $params Result of RequestContext::exportSession()
490 * @return ScopedCallback
491 * @throws MWException
492 * @since 1.21
493 */
494 public static function importScopedSession( array $params ) {
495 if ( session_id() != '' && strlen( $params['sessionId'] ) ) {
496 // Sanity check to avoid sending random cookies for the wrong users.
497 // This method should only called by CLI scripts or by HTTP job runners.
498 throw new MWException( "Sessions can only be imported when none is active." );
499 } elseif ( !IP::isValid( $params['ip'] ) ) {
500 throw new MWException( "Invalid client IP address '{$params['ip']}'." );
501 }
502
503 if ( $params['userId'] ) { // logged-in user
504 $user = User::newFromId( $params['userId'] );
505 $user->load();
506 if ( !$user->getId() ) {
507 throw new MWException( "No user with ID '{$params['userId']}'." );
508 }
509 } else { // anon user
510 $user = User::newFromName( $params['ip'], false );
511 }
512
513 $importSessionFunc = function ( User $user, array $params ) {
514 global $wgRequest, $wgUser;
515
516 $context = RequestContext::getMain();
517 // Commit and close any current session
518 session_write_close(); // persist
519 session_id( '' ); // detach
520 $_SESSION = array(); // clear in-memory array
521 // Remove any user IP or agent information
522 $context->setRequest( new FauxRequest() );
523 $wgRequest = $context->getRequest(); // b/c
524 // Now that all private information is detached from the user, it should
525 // be safe to load the new user. If errors occur or an exception is thrown
526 // and caught (leaving the main context in a mixed state), there is no risk
527 // of the User object being attached to the wrong IP, headers, or session.
528 $context->setUser( $user );
529 $wgUser = $context->getUser(); // b/c
530 if ( strlen( $params['sessionId'] ) ) { // don't make a new random ID
531 wfSetupSession( $params['sessionId'] ); // sets $_SESSION
532 }
533 $request = new FauxRequest( array(), false, $_SESSION );
534 $request->setIP( $params['ip'] );
535 foreach ( $params['headers'] as $name => $value ) {
536 $request->setHeader( $name, $value );
537 }
538 // Set the current context to use the new WebRequest
539 $context->setRequest( $request );
540 $wgRequest = $context->getRequest(); // b/c
541 };
542
543 // Stash the old session and load in the new one
544 $oUser = self::getMain()->getUser();
545 $oParams = self::getMain()->exportSession();
546 $oRequest = self::getMain()->getRequest();
547 $importSessionFunc( $user, $params );
548
549 // Set callback to save and close the new session and reload the old one
550 return new ScopedCallback(
551 function () use ( $importSessionFunc, $oUser, $oParams, $oRequest ) {
552 global $wgRequest;
553 $importSessionFunc( $oUser, $oParams );
554 // Restore the exact previous Request object (instead of leaving FauxRequest)
555 RequestContext::getMain()->setRequest( $oRequest );
556 $wgRequest = RequestContext::getMain()->getRequest(); // b/c
557 }
558 );
559 }
560
561 /**
562 * Create a new extraneous context. The context is filled with information
563 * external to the current session.
564 * - Title is specified by argument
565 * - Request is a FauxRequest, or a FauxRequest can be specified by argument
566 * - User is an anonymous user, for separation IPv4 localhost is used
567 * - Language will be based on the anonymous user and request, may be content
568 * language or a uselang param in the fauxrequest data may change the lang
569 * - Skin will be based on the anonymous user, should be the wiki's default skin
570 *
571 * @param Title $title Title to use for the extraneous request
572 * @param WebRequest|array $request A WebRequest or data to use for a FauxRequest
573 * @return RequestContext
574 */
575 public static function newExtraneousContext( Title $title, $request = array() ) {
576 $context = new self;
577 $context->setTitle( $title );
578 if ( $request instanceof WebRequest ) {
579 $context->setRequest( $request );
580 } else {
581 $context->setRequest( new FauxRequest( $request ) );
582 }
583 $context->user = User::newFromName( '127.0.0.1', false );
584
585 return $context;
586 }
587 }