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