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