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