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