Debian Codegraph @

includes/context/RequestContext.php

raw symbols SCIP
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 namespace MediaWiki\Context;
26
27 use BadMethodCallException;
28 use InvalidArgumentException;
29 use LogicException;
30 use MediaWiki\Config\Config;
31 use MediaWiki\HookContainer\HookRunner;
32 use MediaWiki\Language\Language;
33 use MediaWiki\Logger\LoggerFactory;
34 use MediaWiki\MainConfigNames;
35 use MediaWiki\MediaWikiServices;
36 use MediaWiki\Message\Message;
37 use MediaWiki\Output\OutputPage;
38 use MediaWiki\Permissions\Authority;
39 use MediaWiki\Request\FauxRequest;
40 use MediaWiki\Request\WebRequest;
41 use MediaWiki\Session\CsrfTokenSet;
42 use MediaWiki\Session\PHPSessionHandler;
43 use MediaWiki\Session\SessionManager;
44 use MediaWiki\StubObject\StubGlobalUser;
45 use MediaWiki\Title\Title;
46 use MediaWiki\User\User;
47 use MediaWiki\User\UserRigorOptions;
48 use RuntimeException;
49 use Skin;
50 use Timing;
51 use Wikimedia\Assert\Assert;
52 use Wikimedia\AtEase\AtEase;
53 use Wikimedia\Bcp47Code\Bcp47Code;
54 use Wikimedia\IPUtils;
55 use Wikimedia\Message\MessageSpecifier;
56 use Wikimedia\NonSerializable\NonSerializableTrait;
57 use Wikimedia\ScopedCallback;
58 use WikiPage;
59
60 /**
61 * Group all the pieces relevant to the context of a request into one instance
62 * @newable
63 * @note marked as newable in 1.35 for lack of a better alternative,
64 * but should use a factory in the future and should be narrowed
65 * down to not expose heavy weight objects.
66 */
67 class RequestContext implements IContextSource, MutableContext {
68 use NonSerializableTrait;
69
70 /**
71 * @var WebRequest
72 */
73 private $request;
74
75 /**
76 * @var Title
77 */
78 private $title;
79
80 /**
81 * @var WikiPage|null
82 */
83 private $wikipage;
84
85 /**
86 * @var null|string
87 */
88 private $action;
89
90 /**
91 * @var OutputPage
92 */
93 private $output;
94
95 /**
96 * @var User|null
97 */
98 private $user;
99
100 /**
101 * @var Authority
102 */
103 private $authority;
104
105 /**
106 * @var Language|null
107 */
108 private $lang;
109
110 /**
111 * @var Skin|null
112 */
113 private $skin;
114
115 /**
116 * @var Timing
117 */
118 private $timing;
119
120 /**
121 * @var Config
122 */
123 private $config;
124
125 /**
126 * @var RequestContext|null
127 */
128 private static $instance = null;
129
130 /**
131 * Boolean flag to guard against recursion in getLanguage
132 * @var bool
133 */
134 private $languageRecursion = false;
135
136 /** @var Skin|string|null */
137 private $skinFromHook;
138
139 /** @var bool */
140 private $skinHookCalled = false;
141
142 /** @var string|null */
143 private $skinName;
144
145 /**
146 * @param Config $config
147 */
148 public function setConfig( Config $config ) {
149 $this->config = $config;
150 }
151
152 /**
153 * @return Config
154 */
155 public function getConfig() {
156 // @todo In the future, we could move this to WebStart.php so
157 // the Config object is ready for when initialization happens
158 $this->config ??= MediaWikiServices::getInstance()->getMainConfig();
159
160 return $this->config;
161 }
162
163 /**
164 * @param WebRequest $request
165 */
166 public function setRequest( WebRequest $request ) {
167 $this->request = $request;
168 }
169
170 /**
171 * @return WebRequest
172 */
173 public function getRequest() {
174 if ( $this->request === null ) {
175 // create the WebRequest object on the fly
176 if ( MW_ENTRY_POINT === 'cli' ) {
177 // Don't use real WebRequest in CLI mode, it throws errors when trying to access
178 // things that don't exist, e.g. "Unable to determine IP".
179 $this->request = new FauxRequest( [] );
180 } else {
181 $this->request = new WebRequest();
182 }
183 }
184
185 return $this->request;
186 }
187
188 /**
189 * @return Timing
190 */
191 public function getTiming() {
192 $this->timing ??= new Timing( [
193 'logger' => LoggerFactory::getInstance( 'Timing' )
194 ] );
195 return $this->timing;
196 }
197
198 /**
199 * @param Title|null $title
200 */
201 public function setTitle( ?Title $title = null ) {
202 $this->title = $title;
203 // Clear cache of derived getters
204 $this->wikipage = null;
205 $this->clearActionName();
206 }
207
208 /**
209 * @return Title|null
210 */
211 public function getTitle() {
212 if ( $this->title === null ) {
213 // phpcs:ignore MediaWiki.Usage.DeprecatedGlobalVariables.Deprecated$wgTitle
214 global $wgTitle; # fallback to $wg till we can improve this
215 $this->title = $wgTitle;
216 $logger = LoggerFactory::getInstance( 'GlobalTitleFail' );
217 $logger->info(
218 __METHOD__ . ' called with no title set.',
219 [ 'exception' => new RuntimeException ]
220 );
221 }
222
223 return $this->title;
224 }
225
226 /**
227 * Check, if a Title object is set
228 *
229 * @since 1.25
230 * @return bool
231 */
232 public function hasTitle() {
233 return $this->title !== null;
234 }
235
236 /**
237 * Check whether a WikiPage object can be get with getWikiPage().
238 * Callers should expect that an exception is thrown from getWikiPage()
239 * if this method returns false.
240 *
241 * @since 1.19
242 * @return bool
243 */
244 public function canUseWikiPage() {
245 if ( $this->wikipage ) {
246 // If there's a WikiPage object set, we can for sure get it
247 return true;
248 }
249 // Only pages with legitimate titles can have WikiPages.
250 // That usually means pages in non-virtual namespaces.
251 $title = $this->getTitle();
252 return $title && $title->canExist();
253 }
254
255 /**
256 * @since 1.19
257 * @param WikiPage $wikiPage
258 */
259 public function setWikiPage( WikiPage $wikiPage ) {
260 $pageTitle = $wikiPage->getTitle();
261 if ( !$this->hasTitle() || !$pageTitle->equals( $this->getTitle() ) ) {
262 $this->setTitle( $pageTitle );
263 }
264 // Defer this to the end since setTitle sets it to null.
265 $this->wikipage = $wikiPage;
266 // Clear cache of derived getter
267 $this->clearActionName();
268 }
269
270 /**
271 * Get the WikiPage object.
272 * May throw an exception if there's no Title object set or the Title object
273 * belongs to a special namespace that doesn't have WikiPage, so use first
274 * canUseWikiPage() to check whether this method can be called safely.
275 *
276 * @since 1.19
277 * @return WikiPage
278 */
279 public function getWikiPage() {
280 if ( $this->wikipage === null ) {
281 $title = $this->getTitle();
282 if ( $title === null ) {
283 throw new BadMethodCallException( __METHOD__ . ' called without Title object set' );
284 }
285 $this->wikipage = MediaWikiServices::getInstance()->getWikiPageFactory()->newFromTitle( $title );
286 }
287
288 return $this->wikipage;
289 }
290
291 /**
292 * @since 1.38
293 * @param string $action
294 */
295 public function setActionName( string $action ): void {
296 $this->action = $action;
297 }
298
299 /**
300 * Get the action name for the current web request.
301 *
302 * This generally returns "view" if the current request or process is
303 * not for a skinned index.php web request (e.g. load.php, thumb.php,
304 * job runner, CLI, API).
305 *
306 * @warning This must not be called before or during the Setup.php phase,
307 * and may cause an error or warning if called too early.
308 *
309 * @since 1.38
310 * @return string Action
311 */
312 public function getActionName(): string {
313 // Optimisation: This is cached to avoid repeated running of the
314 // expensive operations to compute this. The computation involves creation
315 // of Article, WikiPage, and ContentHandler objects (and the various
316 // database queries these classes require to be instantiated), as well
317 // as potentially slow extension hooks in these classes.
318 //
319 // This value is frequently needed in OutputPage and in various
320 // Skin-related methods and classes.
321 $this->action ??= MediaWikiServices::getInstance()
322 ->getActionFactory()
323 ->getActionName( $this );
324
325 return $this->action;
326 }
327
328 private function clearActionName(): void {
329 if ( $this->action !== null ) {
330 // If we're clearing after something else has actually already computed the action,
331 // emit a warning.
332 //
333 // Doing so is unstable, given the first caller got something that turns out to be
334 // incomplete or incorrect. Even if we end up re-creating an instance of the same
335 // class, we may now be acting on a different title/skin/user etc.
336 //
337 // Re-computing the action is expensive and can be a performance problem (T302623).
338 trigger_error( 'Unexpected clearActionName after getActionName already called' );
339 $this->action = null;
340 }
341 }
342
343 /**
344 * @param OutputPage $output
345 */
346 public function setOutput( OutputPage $output ) {
347 $this->output = $output;
348 }
349
350 /**
351 * @return OutputPage
352 */
353 public function getOutput() {
354 $this->output ??= new OutputPage( $this );
355
356 return $this->output;
357 }
358
359 /**
360 * @param User $user
361 */
362 public function setUser( User $user ) {
363 $this->user = $user;
364 // Keep authority consistent
365 $this->authority = $user;
366 // Invalidate cached user interface language and skin
367 $this->lang = null;
368 $this->skin = null;
369 $this->skinName = null;
370 }
371
372 /**
373 * @return User
374 */
375 public function getUser() {
376 if ( $this->user === null ) {
377 if ( $this->authority !== null ) {
378 // Keep user consistent by using a possible set authority
379 $this->user = MediaWikiServices::getInstance()
380 ->getUserFactory()
381 ->newFromAuthority( $this->authority );
382 } else {
383 $this->user = User::newFromSession( $this->getRequest() );
384 }
385 }
386
387 return $this->user;
388 }
389
390 /**
391 * @param Authority $authority
392 */
393 public function setAuthority( Authority $authority ) {
394 $this->authority = $authority;
395 // If needed, a User object is constructed from this authority
396 $this->user = null;
397 // Invalidate cached user interface language and skin
398 $this->lang = null;
399 $this->skin = null;
400 $this->skinName = null;
401 }
402
403 /**
404 * @since 1.36
405 * @return Authority
406 */
407 public function getAuthority(): Authority {
408 return $this->authority ?: $this->getUser();
409 }
410
411 /**
412 * Accepts a language code and ensures it's sensible. Outputs a cleaned up language
413 * code and replaces with $wgLanguageCode if not sensible.
414 * @param ?string $code Language code
415 * @return string
416 */
417 public static function sanitizeLangCode( $code ) {
418 global $wgLanguageCode;
419
420 if ( !$code ) {
421 return $wgLanguageCode;
422 }
423
424 // BCP 47 - letter case MUST NOT carry meaning
425 $code = strtolower( $code );
426
427 # Validate $code
428 if ( !MediaWikiServices::getInstance()->getLanguageNameUtils()
429 ->isValidCode( $code )
430 || $code === 'qqq'
431 ) {
432 $code = $wgLanguageCode;
433 }
434
435 return $code;
436 }
437
438 /**
439 * @param Language|string $language Language instance or language code
440 * @since 1.19
441 */
442 public function setLanguage( $language ) {
443 Assert::parameterType( [ Language::class, 'string' ], $language, '$language' );
444 if ( $language instanceof Language ) {
445 $this->lang = $language;
446 } else {
447 $language = self::sanitizeLangCode( $language );
448 $obj = MediaWikiServices::getInstance()->getLanguageFactory()->getLanguage( $language );
449 $this->lang = $obj;
450 }
451 OutputPage::resetOOUI();
452 }
453
454 /**
455 * Get the Language object.
456 * Initialization of user or request objects can depend on this.
457 * @return Language
458 * @throws LogicException
459 * @since 1.19
460 */
461 public function getLanguage() {
462 if ( $this->languageRecursion === true ) {
463 throw new LogicException( 'Recursion detected' );
464 }
465
466 if ( $this->lang === null ) {
467 $this->languageRecursion = true;
468
469 try {
470 $request = $this->getRequest();
471 $user = $this->getUser();
472 $services = MediaWikiServices::getInstance();
473
474 // Optimisation: Avoid slow getVal(), this isn't user-generated content.
475 $code = $request->getRawVal( 'uselang' ) ?? 'user';
476 if ( $code === 'user' ) {
477 $userOptionsLookup = $services->getUserOptionsLookup();
478 $code = $userOptionsLookup->getOption( $user, 'language' );
479 }
480
481 // There are certain characters we don't allow in language code strings,
482 // but by and large almost any valid UTF-8 string will makes it past
483 // this check and the LanguageNameUtils::isValidCode method it uses.
484 // This is to support on-wiki interface message overrides for
485 // non-existent language codes. Also known as "Uselang hacks".
486 // See <https://www.mediawiki.org/wiki/Manual:Uselang_hack>
487 // For something like "en-whatever" or "de-whatever" it will end up
488 // with a mostly "en" or "de" interface, but with an extra layer of
489 // possible MessageCache overrides from `MediaWiki:*/<code>` titles.
490 // While non-ASCII works here, it is required that they are in
491 // NFC form given this will not convert to normalised form.
492 $code = self::sanitizeLangCode( $code );
493
494 ( new HookRunner( $services->getHookContainer() ) )->onUserGetLanguageObject( $user, $code, $this );
495
496 if ( $code === $this->getConfig()->get( MainConfigNames::LanguageCode ) ) {
497 $this->lang = $services->getContentLanguage();
498 } else {
499 $obj = $services->getLanguageFactory()
500 ->getLanguage( $code );
501 $this->lang = $obj;
502 }
503 } finally {
504 $this->languageRecursion = false;
505 }
506 }
507
508 return $this->lang;
509 }
510
511 /**
512 * @since 1.42
513 * @return Bcp47Code
514 */
515 public function getLanguageCode() {
516 return $this->getLanguage();
517 }
518
519 /**
520 * @param Skin $skin
521 */
522 public function setSkin( Skin $skin ) {
523 $this->skin = clone $skin;
524 $this->skin->setContext( $this );
525 $this->skinName = $skin->getSkinName();
526 OutputPage::resetOOUI();
527 }
528
529 /**
530 * Get the name of the skin
531 *
532 * @since 1.41
533 * @return string
534 */
535 public function getSkinName() {
536 if ( $this->skinName === null ) {
537 $this->skinName = $this->fetchSkinName();
538 }
539 return $this->skinName;
540 }
541
542 /**
543 * Get the name of the skin, without caching
544 *
545 * @return string
546 */
547 private function fetchSkinName() {
548 $skinFromHook = $this->getSkinFromHook();
549 if ( $skinFromHook instanceof Skin ) {
550 // The hook provided a skin object
551 return $skinFromHook->getSkinName();
552 } elseif ( is_string( $skinFromHook ) ) {
553 // The hook provided a skin name
554 $skinName = $skinFromHook;
555 } elseif ( !in_array( 'skin', $this->getConfig()->get( MainConfigNames::HiddenPrefs ) ) ) {
556 // The normal case
557 $userOptionsLookup = MediaWikiServices::getInstance()->getUserOptionsLookup();
558 $userSkin = $userOptionsLookup->getOption( $this->getUser(), 'skin' );
559 // Optimisation: Avoid slow getVal(), this isn't user-generated content.
560 $skinName = $this->getRequest()->getRawVal( 'useskin' ) ?? $userSkin;
561 } else {
562 // User preference disabled
563 $skinName = $this->getConfig()->get( MainConfigNames::DefaultSkin );
564 }
565 return Skin::normalizeKey( $skinName );
566 }
567
568 /**
569 * Get the skin set by the RequestContextCreateSkin hook, if there is any.
570 *
571 * @return Skin|string|null
572 */
573 private function getSkinFromHook() {
574 if ( !$this->skinHookCalled ) {
575 $this->skinHookCalled = true;
576 ( new HookRunner( MediaWikiServices::getInstance()->getHookContainer() ) )
577 ->onRequestContextCreateSkin( $this, $this->skinFromHook );
578 }
579 return $this->skinFromHook;
580 }
581
582 /**
583 * @return Skin
584 */
585 public function getSkin() {
586 if ( $this->skin === null ) {
587 $skinFromHook = $this->getSkinFromHook();
588 if ( $skinFromHook instanceof Skin ) {
589 $this->skin = $skinFromHook;
590 } else {
591 $skinName = is_string( $skinFromHook )
592 ? Skin::normalizeKey( $skinFromHook )
593 : $this->getSkinName();
594 $factory = MediaWikiServices::getInstance()->getSkinFactory();
595 $this->skin = $factory->makeSkin( $skinName );
596 }
597 $this->skin->setContext( $this );
598 }
599 return $this->skin;
600 }
601
602 /**
603 * Get a Message object with context set
604 * Parameters are the same as wfMessage()
605 *
606 * @param string|string[]|MessageSpecifier $key Message key, or array of keys,
607 * or a MessageSpecifier.
608 * @param mixed ...$params
609 * @return Message
610 */
611 public function msg( $key, ...$params ) {
612 return wfMessage( $key, ...$params )->setContext( $this );
613 }
614
615 /**
616 * Get the RequestContext object associated with the main request
617 *
618 * @return RequestContext
619 */
620 public static function getMain(): RequestContext {
621 self::$instance ??= new self;
622
623 return self::$instance;
624 }
625
626 /**
627 * Get the RequestContext object associated with the main request
628 * and gives a warning to the log, to find places, where a context maybe is missing.
629 *
630 * @param string $func @phan-mandatory-param
631 * @return RequestContext
632 * @since 1.24
633 */
634 public static function getMainAndWarn( $func = __METHOD__ ) {
635 wfDebug( $func . ' called without context. ' .
636 "Using RequestContext::getMain()" );
637
638 return self::getMain();
639 }
640
641 /**
642 * Resets singleton returned by getMain(). Should be called only from unit tests.
643 */
644 public static function resetMain() {
645 if ( !defined( 'MW_PHPUNIT_TEST' ) && !defined( 'MW_PARSER_TEST' ) ) {
646 throw new LogicException( __METHOD__ . '() should be called only from unit tests!' );
647 }
648 self::$instance = null;
649 }
650
651 /**
652 * Export the resolved user IP, HTTP headers, user ID, and session ID.
653 * The result will be reasonably sized to allow for serialization.
654 *
655 * @return array
656 * @since 1.21
657 */
658 public function exportSession() {
659 $session = SessionManager::getGlobalSession();
660 return [
661 'ip' => $this->getRequest()->getIP(),
662 'headers' => $this->getRequest()->getAllHeaders(),
663 'sessionId' => $session->isPersistent() ? $session->getId() : '',
664 'userId' => $this->getUser()->getId()
665 ];
666 }
667
668 public function getCsrfTokenSet(): CsrfTokenSet {
669 return new CsrfTokenSet( $this->getRequest() );
670 }
671
672 /**
673 * Import a client IP address, HTTP headers, user ID, and session ID
674 *
675 * This sets the current session, $wgUser, and $wgRequest from $params.
676 * Once the return value falls out of scope, the old context is restored.
677 * This method should only be called in contexts where there is no session
678 * ID or end user receiving the response (CLI or HTTP job runners). This
679 * is partly enforced, and is done so to avoid leaking cookies if certain
680 * error conditions arise.
681 *
682 * This is useful when background scripts inherit context when acting on
683 * behalf of a user. In general the 'sessionId' parameter should be set
684 * to an empty string unless session importing is *truly* needed. This
685 * feature is somewhat deprecated.
686 *
687 * @param array $params Result of RequestContext::exportSession()
688 * @return ScopedCallback
689 * @since 1.21
690 */
691 public static function importScopedSession( array $params ) {
692 if ( strlen( $params['sessionId'] ) &&
693 SessionManager::getGlobalSession()->isPersistent()
694 ) {
695 // Check to avoid sending random cookies for the wrong users.
696 // This method should only called by CLI scripts or by HTTP job runners.
697 throw new BadMethodCallException( "Sessions can only be imported when none is active." );
698 } elseif ( !IPUtils::isValid( $params['ip'] ) ) {
699 throw new InvalidArgumentException( "Invalid client IP address '{$params['ip']}'." );
700 }
701
702 $userFactory = MediaWikiServices::getInstance()->getUserFactory();
703
704 if ( $params['userId'] ) { // logged-in user
705 $user = $userFactory->newFromId( (int)$params['userId'] );
706 $user->load();
707 if ( !$user->isRegistered() ) {
708 throw new InvalidArgumentException( "No user with ID '{$params['userId']}'." );
709 }
710 } else { // anon user
711 $user = $userFactory->newFromName( $params['ip'], UserRigorOptions::RIGOR_NONE );
712 }
713
714 $importSessionFunc = static function ( User $user, array $params ) {
715 global $wgRequest;
716
717 $context = RequestContext::getMain();
718
719 // Commit and close any current session
720 if ( PHPSessionHandler::isEnabled() ) {
721 session_write_close(); // persist
722 session_id( '' ); // detach
723 $_SESSION = []; // clear in-memory array
724 }
725
726 // Get new session, if applicable
727 $session = null;
728 if ( strlen( $params['sessionId'] ) ) { // don't make a new random ID
729 $manager = SessionManager::singleton();
730 $session = $manager->getSessionById( $params['sessionId'], true )
731 ?: $manager->getEmptySession();
732 }
733
734 // Remove any user IP or agent information, and attach the request
735 // with the new session.
736 $context->setRequest( new FauxRequest( [], false, $session ) );
737 $wgRequest = $context->getRequest(); // b/c
738
739 // Now that all private information is detached from the user, it should
740 // be safe to load the new user. If errors occur or an exception is thrown
741 // and caught (leaving the main context in a mixed state), there is no risk
742 // of the User object being attached to the wrong IP, headers, or session.
743 $context->setUser( $user );
744 StubGlobalUser::setUser( $context->getUser() ); // b/c
745 if ( $session && PHPSessionHandler::isEnabled() ) {
746 session_id( $session->getId() );
747 AtEase::quietCall( 'session_start' );
748 }
749 $request = new FauxRequest( [], false, $session );
750 $request->setIP( $params['ip'] );
751 foreach ( $params['headers'] as $name => $value ) {
752 $request->setHeader( $name, $value );
753 }
754 // Set the current context to use the new WebRequest
755 $context->setRequest( $request );
756 $wgRequest = $context->getRequest(); // b/c
757 };
758
759 // Stash the old session and load in the new one
760 $oUser = self::getMain()->getUser();
761 $oParams = self::getMain()->exportSession();
762 $oRequest = self::getMain()->getRequest();
763 // @phan-suppress-next-line PhanTypeMismatchArgumentNullable exceptions triggered above prevent the null case
764 $importSessionFunc( $user, $params );
765
766 // Set callback to save and close the new session and reload the old one
767 return new ScopedCallback(
768 static function () use ( $importSessionFunc, $oUser, $oParams, $oRequest ) {
769 global $wgRequest;
770 $importSessionFunc( $oUser, $oParams );
771 // Restore the exact previous Request object (instead of leaving MediaWiki\Request\FauxRequest)
772 RequestContext::getMain()->setRequest( $oRequest );
773 $wgRequest = RequestContext::getMain()->getRequest(); // b/c
774 }
775 );
776 }
777
778 /**
779 * Create a new extraneous context. The context is filled with information
780 * external to the current session.
781 * - Title is specified by argument
782 * - Request is a MediaWiki\Request\FauxRequest, or a MediaWiki\Request\FauxRequest can be specified by argument
783 * - User is an anonymous user, for separation IPv4 localhost is used
784 * - Language will be based on the anonymous user and request, may be content
785 * language or a uselang param in the fauxrequest data may change the lang
786 * - Skin will be based on the anonymous user, should be the wiki's default skin
787 *
788 * @param Title $title Title to use for the extraneous request
789 * @param WebRequest|array $request A WebRequest or data to use for a MediaWiki\Request\FauxRequest
790 * @return RequestContext
791 */
792 public static function newExtraneousContext( Title $title, $request = [] ) {
793 $context = new self;
794 $context->setTitle( $title );
795 if ( $request instanceof WebRequest ) {
796 $context->setRequest( $request );
797 } else {
798 $context->setRequest( new FauxRequest( $request ) );
799 }
800 $context->user = MediaWikiServices::getInstance()->getUserFactory()->newFromName(
801 '127.0.0.1',
802 UserRigorOptions::RIGOR_NONE
803 );
804
805 return $context;
806 }
807
808 /** @return never */
809 public function __clone() {
810 throw new LogicException(
811 __CLASS__ . ' should not be cloned, use DerivativeContext instead.'
812 );
813 }
814
815 }
816
817 /** @deprecated class alias since 1.42 */
818 class_alias( RequestContext::class, 'RequestContext' );