Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
14.83% covered (danger)
14.83%
35 / 236
20.00% covered (danger)
20.00%
14 / 70
CRAP
0.00% covered (danger)
0.00%
0 / 1
SpecialPage
14.89% covered (danger)
14.89%
35 / 235
20.00% covered (danger)
20.00%
14 / 70
8267.34
0.00% covered (danger)
0.00%
0 / 1
 newSearchPage
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
12
 getTitleFor
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 getTitleValueFor
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 getSafeTitleFor
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
6
 __construct
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 getName
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getRestriction
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 isListed
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 isIncludable
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 maxIncludeCacheTime
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
6
 getCacheTTL
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 including
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getLocalName
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 isExpensive
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 isCached
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 isRestricted
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 userCanExecute
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 authorizeAction
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
6
 displayRestrictionError
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 checkPermissions
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
6
 checkReadOnly
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
6
 requireLogin
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 requireNamedUser
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 getLoginSecurityLevel
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 setReauthPostData
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 checkLoginSecurityLevel
0.00% covered (danger)
0.00%
0 / 37
0.00% covered (danger)
0.00%
0 / 1
72
 setAuthManager
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getAuthManager
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 prefixSearchSubpages
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 getSubpagesForPrefixSearch
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getAssociatedNavigationLinks
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 prefixSearchString
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
20
 prefixSearchArray
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 setHeaders
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
2
 run
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
12
 beforeExecute
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 afterExecute
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 execute
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
12
 outputHeader
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
20
 getDescription
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getShortDescription
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
2
 getPageTitle
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 setContext
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getContext
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
 getRequest
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 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getUser
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getAuthority
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getSkin
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getLanguage
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getContentLanguage
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 setContentLanguage
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getConfig
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getFullTitle
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getRobotPolicy
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 msg
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
2.06
 addFeedLinks
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
6
 addHelpLink
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
20
 getFinalGroupName
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
6
 doesWrites
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getGroupName
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 useTransactionalTimeLimit
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
6
 getLinkRenderer
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 setLinkRenderer
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 buildPrevNextNavigation
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
12
 setHookContainer
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 getHookContainer
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 getHookRunner
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
2.15
 setSpecialPageFactory
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getSpecialPageFactory
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
1<?php
2/**
3 * @license GPL-2.0-or-later
4 * @file
5 * @ingroup SpecialPage
6 */
7
8namespace MediaWiki\SpecialPage;
9
10use MediaWiki\Auth\AuthManager;
11use MediaWiki\Config\Config;
12use MediaWiki\Context\IContextSource;
13use MediaWiki\Context\RequestContext;
14use MediaWiki\Exception\ErrorPageError;
15use MediaWiki\Exception\PermissionsError;
16use MediaWiki\Exception\ReadOnlyError;
17use MediaWiki\Exception\UserNotLoggedIn;
18use MediaWiki\HookContainer\HookContainer;
19use MediaWiki\HookContainer\HookRunner;
20use MediaWiki\Language\Language;
21use MediaWiki\Language\MessageLocalizer;
22use MediaWiki\Linker\LinkRenderer;
23use MediaWiki\Logger\LoggerFactory;
24use MediaWiki\MainConfigNames;
25use MediaWiki\MediaWikiServices;
26use MediaWiki\Message\Message;
27use MediaWiki\Navigation\PagerNavigationBuilder;
28use MediaWiki\Output\OutputPage;
29use MediaWiki\Permissions\Authority;
30use MediaWiki\Permissions\PermissionStatus;
31use MediaWiki\Request\WebRequest;
32use MediaWiki\Search\SearchEngineFactory;
33use MediaWiki\Skin\Skin;
34use MediaWiki\Title\Title;
35use MediaWiki\Title\TitleValue;
36use MediaWiki\User\User;
37use MediaWiki\Utils\MWCryptRand;
38use Wikimedia\Message\MessageParam;
39use Wikimedia\Message\MessageSpecifier;
40
41/**
42 * Parent class for all special pages.
43 *
44 * Includes some static functions for handling the special page list deprecated
45 * in favor of SpecialPageFactory.
46 *
47 * @stable to extend
48 *
49 * @ingroup SpecialPage
50 */
51class SpecialPage implements MessageLocalizer {
52    /**
53     * @var string The canonical name of this special page
54     * Also used as the message key for the default <h1> heading,
55     * @see getDescription()
56     */
57    protected $mName;
58
59    /** @var string The local name of this special page */
60    private $mLocalName;
61
62    /**
63     * @var string Minimum user level required to access this page, or "" for anyone.
64     * Also used to categorise the pages in Special:Specialpages
65     */
66    protected $mRestriction;
67
68    /** @var bool Listed in Special:Specialpages? */
69    private $mListed;
70
71    /** @var bool Whether or not this special page is being included from an article */
72    protected $mIncluding;
73
74    /** @var bool Whether the special page can be included in an article */
75    protected $mIncludable;
76
77    /**
78     * Current request context
79     * @var IContextSource
80     */
81    protected $mContext;
82
83    /** @var Language|null */
84    private $contentLanguage;
85
86    /**
87     * @var LinkRenderer|null
88     */
89    private $linkRenderer = null;
90
91    /** @var HookContainer|null */
92    private $hookContainer;
93    /** @var HookRunner|null */
94    private $hookRunner;
95
96    /** @var AuthManager|null */
97    private $authManager = null;
98
99    /** @var SpecialPageFactory */
100    private $specialPageFactory;
101
102    /**
103     * Get the users preferred search page.
104     *
105     * It will fall back to Special:Search if the preference points to a page
106     * that doesn't exist or is not defined.
107     *
108     * @since 1.38
109     * @param User $user Search page can be customized by user preference.
110     * @return Title
111     */
112    public static function newSearchPage( User $user ) {
113        // Try user preference first
114        $userOptionsManager = MediaWikiServices::getInstance()->getUserOptionsManager();
115        $title = $userOptionsManager->getOption( $user, 'search-special-page' );
116        if ( $title ) {
117            $page = self::getTitleFor( $title );
118            $factory = MediaWikiServices::getInstance()->getSpecialPageFactory();
119            if ( $factory->exists( $page->getText() ) ) {
120                return $page;
121            }
122        }
123        return self::getTitleFor( 'Search' );
124    }
125
126    /**
127     * Get a localised Title object for a specified special page name
128     * If you don't need a full Title object, consider using TitleValue through
129     * getTitleValueFor() below.
130     *
131     * @since 1.9
132     * @since 1.21 $fragment parameter added
133     *
134     * @param string $name
135     * @param string|false|null $subpage Subpage string, or false/null to not use a subpage
136     * @param string $fragment The link fragment (after the "#")
137     * @return Title
138     */
139    public static function getTitleFor( $name, $subpage = false, $fragment = '' ) {
140        return Title::newFromLinkTarget(
141            self::getTitleValueFor( $name, $subpage, $fragment )
142        );
143    }
144
145    /**
146     * Get a localised TitleValue object for a specified special page name
147     *
148     * @since 1.28
149     * @param string $name
150     * @param string|false|null $subpage Subpage string, or false/null to not use a subpage
151     * @param string $fragment The link fragment (after the "#")
152     * @return TitleValue
153     */
154    public static function getTitleValueFor( $name, $subpage = false, $fragment = '' ) {
155        $name = MediaWikiServices::getInstance()->getSpecialPageFactory()->
156            getLocalNameFor( $name, $subpage );
157
158        return new TitleValue( NS_SPECIAL, $name, $fragment );
159    }
160
161    /**
162     * Get a localised Title object for a page name with a possibly unvalidated subpage
163     *
164     * @param string $name
165     * @param string|false $subpage Subpage string, or false to not use a subpage
166     * @return Title|null Title object or null if the page doesn't exist
167     */
168    public static function getSafeTitleFor( $name, $subpage = false ) {
169        $name = MediaWikiServices::getInstance()->getSpecialPageFactory()->
170            getLocalNameFor( $name, $subpage );
171        if ( $name ) {
172            return Title::makeTitleSafe( NS_SPECIAL, $name );
173        } else {
174            return null;
175        }
176    }
177
178    /**
179     * Default constructor for special pages
180     * Derivative classes should call this from their constructor
181     *     Note that if the user does not have the required level, an error message will
182     *     be displayed by the default execute() method, without the global function ever
183     *     being called.
184     *
185     *     If you override execute(), you can recover the default behavior with userCanExecute()
186     *     and displayRestrictionError()
187     *
188     * @stable to call
189     *
190     * @param string $name Name of the special page, as seen in links and URLs
191     * @param string $restriction User right required, e.g. "block" or "delete"
192     * @param bool $listed Whether the page is listed in Special:SpecialPages
193     * @param callable|bool $function Unused
194     * @param string $file Unused
195     * @param bool $includable Whether the page can be included in normal pages
196     */
197    public function __construct(
198        $name = '', $restriction = '', $listed = true,
199        $function = false, $file = '', $includable = false
200    ) {
201        $this->mName = $name;
202        $this->mRestriction = $restriction;
203        $this->mListed = $listed;
204        $this->mIncludable = $includable;
205    }
206
207    /**
208     * Get the canonical, unlocalized name of this special page without namespace.
209     * @return string
210     */
211    public function getName() {
212        return $this->mName;
213    }
214
215    /**
216     * Get the permission that a user must have to execute this page
217     * @return string
218     */
219    public function getRestriction() {
220        return $this->mRestriction;
221    }
222
223    // @todo FIXME: Decide which syntax to use for this, and stick to it
224
225    /**
226     * Whether this special page is listed in Special:SpecialPages
227     * @stable to override
228     * @since 1.3 (r3583)
229     * @return bool
230     */
231    public function isListed() {
232        return $this->mListed;
233    }
234
235    /**
236     * Whether it's allowed to transclude the special page via {{Special:Foo/params}}
237     * @stable to override
238     * @return bool
239     */
240    public function isIncludable() {
241        return $this->mIncludable;
242    }
243
244    /**
245     * How long to cache page when it is being included.
246     *
247     * @note If cache time is not 0, then the current user becomes an anon.
248     *   If you want to do any per-user customizations, then this method
249     *   must be overridden to return 0.
250     * @since 1.26
251     * @stable to override
252     * @return int Time in seconds, 0 to disable caching altogether,
253     *  false to use the parent page's cache settings
254     */
255    public function maxIncludeCacheTime() {
256        return $this->getConfig()->get( MainConfigNames::MiserMode ) ? $this->getCacheTTL() : 0;
257    }
258
259    /**
260     * @stable to override
261     * @return int Seconds that this page can be cached
262     */
263    protected function getCacheTTL() {
264        return 60 * 60;
265    }
266
267    /**
268     * Whether the special page is being evaluated via transclusion
269     * @param bool|null $x
270     * @return bool
271     */
272    public function including( $x = null ) {
273        return wfSetVar( $this->mIncluding, $x );
274    }
275
276    /**
277     * Get the localised name of the special page
278     * @stable to override
279     * @return string
280     */
281    public function getLocalName() {
282        if ( $this->mLocalName === null ) {
283            $this->mLocalName = $this->getSpecialPageFactory()->getLocalNameFor( $this->mName );
284        }
285
286        return $this->mLocalName;
287    }
288
289    /**
290     * Is this page expensive (for some definition of expensive)?
291     * Expensive pages are disabled or cached in miser mode.  Originally used
292     * (and still overridden) by QueryPage and subclasses, moved here so that
293     * Special:SpecialPages can safely call it for all special pages.
294     *
295     * @stable to override
296     * @return bool
297     */
298    public function isExpensive() {
299        return false;
300    }
301
302    /**
303     * Is this page cached?
304     * Expensive pages are cached or disabled in miser mode.
305     * Used by QueryPage and subclasses, moved here so that
306     * Special:SpecialPages can safely call it for all special pages.
307     *
308     * @stable to override
309     * @return bool
310     * @since 1.21
311     */
312    public function isCached() {
313        return false;
314    }
315
316    /**
317     * Can be overridden by subclasses with more complicated permissions
318     * schemes.
319     *
320     * @stable to override
321     * @return bool Should the page be displayed with the restricted-access
322     *   pages?
323     */
324    public function isRestricted() {
325        // DWIM: If anons can do something, then it is not restricted
326        return $this->mRestriction != '' && !MediaWikiServices::getInstance()
327            ->getGroupPermissionsLookup()
328            ->groupHasPermission( '*', $this->mRestriction );
329    }
330
331    /**
332     * Checks if the given user (identified by an object) can execute this
333     * special page (as defined by $mRestriction).  Can be overridden by sub-
334     * classes with more complicated permissions schemes.
335     *
336     * @stable to override
337     * @param User $user The user to check
338     * @return bool Does the user have permission to view the page?
339     */
340    public function userCanExecute( User $user ) {
341        return MediaWikiServices::getInstance()
342            ->getPermissionManager()
343            ->userHasRight( $user, $this->mRestriction );
344    }
345
346    /**
347     * Utility function for authorizing an action to be performed by the special
348     * page. User blocks and rate limits are enforced implicitly.
349     *
350     * @see Authority::authorizeAction.
351     *
352     * @param ?string $action If not given, the action returned by
353     *        getRestriction() will be used.
354     *
355     * @return PermissionStatus
356     */
357    protected function authorizeAction( ?string $action = null ): PermissionStatus {
358        $action ??= $this->getRestriction();
359
360        if ( !$action ) {
361            return PermissionStatus::newGood();
362        }
363
364        $status = PermissionStatus::newEmpty();
365        $this->getAuthority()->authorizeAction( $action, $status );
366        return $status;
367    }
368
369    /**
370     * Output an error message telling the user what access level they have to have
371     * @stable to override
372     * @throws PermissionsError
373     * @return never
374     */
375    protected function displayRestrictionError() {
376        throw new PermissionsError( $this->mRestriction );
377    }
378
379    /**
380     * Checks if userCanExecute, and if not throws a PermissionsError
381     *
382     * @stable to override
383     * @since 1.19
384     * @return void
385     * @throws PermissionsError
386     */
387    public function checkPermissions() {
388        if ( !$this->userCanExecute( $this->getUser() ) ) {
389            $this->displayRestrictionError();
390        }
391    }
392
393    /**
394     * If the wiki is currently in readonly mode, throws a ReadOnlyError
395     *
396     * @since 1.19
397     * @return void
398     * @throws ReadOnlyError
399     */
400    public function checkReadOnly() {
401        // Can not inject the ReadOnlyMode as it would break the installer since
402        // it instantiates SpecialPageFactory before the DB (via ParserFactory for message parsing)
403        if ( MediaWikiServices::getInstance()->getReadOnlyMode()->isReadOnly() ) {
404            throw new ReadOnlyError;
405        }
406    }
407
408    /**
409     * If the user is not logged in, throws UserNotLoggedIn error
410     *
411     * The user will be redirected to Special:Userlogin with the given message as an error on
412     * the form.
413     *
414     * @since 1.23
415     * @param string $reasonMsg [optional] Message key to be displayed on login page
416     * @param string $titleMsg [optional] Passed on to UserNotLoggedIn constructor
417     * @throws UserNotLoggedIn
418     */
419    public function requireLogin(
420        $reasonMsg = 'exception-nologin-text', $titleMsg = 'exception-nologin'
421    ) {
422        if ( $this->getUser()->isAnon() ) {
423            throw new UserNotLoggedIn( $reasonMsg, $titleMsg );
424        }
425    }
426
427    /**
428     * If the user is not logged in or is a temporary user, throws UserNotLoggedIn
429     *
430     * @since 1.39
431     * @param string $reasonMsg [optional] Message key to be displayed on login page
432     * @param string $titleMsg [optional] Passed on to UserNotLoggedIn constructor. Default 'exception-nologin'
433     *    which is used when $titleMsg is null.
434     * @param bool $alwaysRedirectToLoginPage [optional] Should the redirect always go to Special:UserLogin?
435     *    If false (the default), the redirect will go to Special:CreateAccount when the user is logged-in to
436     *    a temporary account.
437     * @throws UserNotLoggedIn
438     */
439    public function requireNamedUser(
440        $reasonMsg = 'exception-nologin-text', $titleMsg = 'exception-nologin', bool $alwaysRedirectToLoginPage = false
441    ) {
442        if ( !$this->getUser()->isNamed() ) {
443            throw new UserNotLoggedIn( $reasonMsg, $titleMsg, [], $alwaysRedirectToLoginPage );
444        }
445    }
446
447    /**
448     * Tells if the special page does something security-sensitive and needs extra defense against
449     * a stolen account (e.g. a reauthentication). What exactly that will mean is decided by the
450     * authentication framework.
451     * @stable to override
452     * @return string|false False or the argument for AuthManager::securitySensitiveOperationStatus().
453     *   Typically, a special page needing elevated security would return its name here.
454     */
455    protected function getLoginSecurityLevel() {
456        return false;
457    }
458
459    /**
460     * Record preserved POST data after a reauthentication.
461     *
462     * This is called from checkLoginSecurityLevel() when returning from the
463     * redirect for reauthentication, if the redirect had been served in
464     * response to a POST request.
465     *
466     * The base SpecialPage implementation does nothing. If your subclass uses
467     * getLoginSecurityLevel() or checkLoginSecurityLevel(), it should probably
468     * implement this to do something with the data.
469     *
470     * @note Call self::setAuthManager from special page constructor when overriding
471     *
472     * @stable to override
473     * @since 1.32
474     * @param array $data
475     */
476    protected function setReauthPostData( array $data ) {
477    }
478
479    /**
480     * Verifies that the user meets the security level, possibly reauthenticating them in the process.
481     *
482     * This should be used when the page does something security-sensitive and needs extra defense
483     * against a stolen account (e.g. a reauthentication). The authentication framework will make
484     * an extra effort to make sure the user account is not compromised. What that exactly means
485     * will depend on the system and user settings; e.g. the user might be required to log in again
486     * unless their last login happened recently, or they might be given a second-factor challenge.
487     *
488     * Calling this method will result in one if these actions:
489     * - return true: all good.
490     * - return false and set a redirect: caller should abort; the redirect will take the user
491     *   to the login page for reauthentication, and back.
492     * - throw an exception if there is no way for the user to meet the requirements without using
493     *   a different access method (e.g. this functionality is only available from a specific IP).
494     *
495     * Note that this does not in any way check that the user is authorized to use this special page
496     * (use checkPermissions() for that).
497     *
498     * @param string|null $level A security level. Can be an arbitrary string, defaults to the page
499     *   name.
500     * @return bool False means a redirect to the reauthentication page has been set and processing
501     *   of the special page should be aborted.
502     * @throws ErrorPageError If the security level cannot be met, even with reauthentication.
503     */
504    protected function checkLoginSecurityLevel( $level = null ) {
505        $level = $level ?: $this->getName();
506        $key = 'SpecialPage:reauth:' . $this->getName();
507        $request = $this->getRequest();
508
509        $securityStatus = $this->getAuthManager()->securitySensitiveOperationStatus( $level );
510        if ( $securityStatus === AuthManager::SEC_OK ) {
511            $uniqueId = $request->getVal( 'postUniqueId' );
512            if ( $uniqueId ) {
513                $key .= ':' . $uniqueId;
514                $session = $request->getSession();
515                $data = $session->getSecret( $key );
516                if ( $data ) {
517                    $session->remove( $key );
518                    $this->setReauthPostData( $data );
519                }
520            }
521            return true;
522        } elseif ( $securityStatus === AuthManager::SEC_REAUTH ) {
523            $title = self::getTitleFor( 'Userlogin' );
524            $queryParams = $request->getQueryValues();
525
526            if ( $request->wasPosted() ) {
527                $data = array_diff_assoc( $request->getValues(), $request->getQueryValues() );
528                if ( $data ) {
529                    // unique ID in case the same special page is open in multiple browser tabs
530                    $uniqueId = MWCryptRand::generateHex( 6 );
531                    $key .= ':' . $uniqueId;
532                    $queryParams['postUniqueId'] = $uniqueId;
533                    $session = $request->getSession();
534                    $session->persist(); // Just in case
535                    $session->setSecret( $key, $data );
536                }
537            }
538
539            $query = [
540                'returnto' => $this->getFullTitle()->getPrefixedDBkey(),
541                'returntoquery' => wfArrayToCgi( array_diff_key( $queryParams, [ 'title' => true ] ) ),
542                'force' => $level,
543            ];
544            $url = $title->getFullURL( $query, false, PROTO_HTTPS );
545
546            $this->getOutput()->redirect( $url );
547            return false;
548        }
549
550        $titleMessage = wfMessage( 'specialpage-securitylevel-not-allowed-title' );
551        $errorMessage = wfMessage( 'specialpage-securitylevel-not-allowed' );
552        throw new ErrorPageError( $titleMessage, $errorMessage );
553    }
554
555    /**
556     * Set the injected AuthManager from the special page constructor
557     *
558     * @since 1.36
559     * @param AuthManager $authManager
560     */
561    final protected function setAuthManager( AuthManager $authManager ): void {
562        $this->authManager = $authManager;
563    }
564
565    /**
566     * @note Call self::setAuthManager from special page constructor when using
567     *
568     * @since 1.36
569     * @return AuthManager
570     */
571    final protected function getAuthManager(): AuthManager {
572        if ( $this->authManager === null ) {
573            // Fallback if not provided
574            // TODO Change to wfWarn in a future release
575            $this->authManager = MediaWikiServices::getInstance()->getAuthManager();
576        }
577        return $this->authManager;
578    }
579
580    /**
581     * Return an array of subpages beginning with $search that this special page will accept.
582     *
583     * For example, if a page supports subpages "foo", "bar" and "baz" (as in Special:PageName/foo,
584     * etc.):
585     *
586     *   - `prefixSearchSubpages( "ba" )` should return `[ "bar", "baz" ]`
587     *   - `prefixSearchSubpages( "f" )` should return `[ "foo" ]`
588     *   - `prefixSearchSubpages( "z" )` should return `[]`
589     *   - `prefixSearchSubpages( "" )` should return `[ foo", "bar", "baz" ]`
590     *
591     * @stable to override
592     * @param string $search Prefix to search for
593     * @param int $limit Maximum number of results to return (usually 10)
594     * @param int $offset Number of results to skip (usually 0)
595     * @return string[] Matching subpages
596     */
597    public function prefixSearchSubpages( $search, $limit, $offset ) {
598        $subpages = $this->getSubpagesForPrefixSearch();
599        if ( !$subpages ) {
600            return [];
601        }
602
603        return self::prefixSearchArray( $search, $limit, $subpages, $offset );
604    }
605
606    /**
607     * Return an array of subpages that this special page will accept for prefix
608     * searches. If this method requires a query you might instead want to implement
609     * prefixSearchSubpages() directly so you can support $limit and $offset. This
610     * method is better for static-ish lists of things.
611     *
612     * @stable to override
613     * @return string[] subpages to search from
614     */
615    protected function getSubpagesForPrefixSearch() {
616        return [];
617    }
618
619    /**
620     * Return an array of strings representing page titles that are discoverable to end users via UI.
621     *
622     * @since 1.39
623     * @stable to call or override
624     * @return string[] strings representing page titles that can be rendered by skins if required.
625     */
626    public function getAssociatedNavigationLinks() {
627        return [];
628    }
629
630    /**
631     * Perform a regular substring search for prefixSearchSubpages
632     * @since 1.36 Added $searchEngineFactory parameter
633     * @param string $search Prefix to search for
634     * @param int $limit Maximum number of results to return (usually 10)
635     * @param int $offset Number of results to skip (usually 0)
636     * @param SearchEngineFactory|null $searchEngineFactory Provide the service
637     * @return string[] Matching subpages
638     */
639    protected function prefixSearchString(
640        $search,
641        $limit,
642        $offset,
643        ?SearchEngineFactory $searchEngineFactory = null
644    ) {
645        $title = Title::newFromText( $search );
646        if ( !$title || !$title->canExist() ) {
647            // No prefix suggestion in special and media namespace
648            return [];
649        }
650
651        $searchEngine = $searchEngineFactory
652            ? $searchEngineFactory->create()
653            // Fallback if not provided
654            // TODO Change to wfWarn in a future release
655            : MediaWikiServices::getInstance()->newSearchEngine();
656        $searchEngine->setLimitOffset( $limit, $offset );
657        $searchEngine->setNamespaces( [] );
658        $result = $searchEngine->defaultPrefixSearch( $search );
659        return array_map( static function ( Title $t ) {
660            return $t->getPrefixedText();
661        }, $result );
662    }
663
664    /**
665     * Helper function for implementations of prefixSearchSubpages() that
666     * filter the values in memory (as opposed to making a query).
667     *
668     * @since 1.24
669     * @param string $search
670     * @param int $limit
671     * @param array $subpages
672     * @param int $offset
673     * @return string[]
674     */
675    protected static function prefixSearchArray( $search, $limit, array $subpages, $offset ) {
676        $escaped = preg_quote( $search, '/' );
677        return array_slice( preg_grep( "/^$escaped/i",
678            array_slice( $subpages, $offset ) ), 0, $limit );
679    }
680
681    /**
682     * Sets headers - this should be called from the execute() method of all derived classes!
683     * @stable to override
684     */
685    protected function setHeaders() {
686        $out = $this->getOutput();
687        $out->setArticleRelated( false );
688        $out->setRobotPolicy( $this->getRobotPolicy() );
689        $out->setPageTitleMsg( $this->getDescription() );
690    }
691
692    /**
693     * Entry point.
694     *
695     * @since 1.20
696     *
697     * @param string|null $subPage
698     */
699    final public function run( $subPage ) {
700        $scope = LoggerFactory::getContext()->addScoped( [
701            'context.special_page_name' => $this->getName(),
702            'context.special_page_subpage' => $subPage ?? '',
703        ] );
704        if ( !$this->getHookRunner()->onSpecialPageBeforeExecute( $this, $subPage ) ) {
705            return;
706        }
707
708        if ( $this->beforeExecute( $subPage ) === false ) {
709            return;
710        }
711        $this->execute( $subPage );
712        $this->afterExecute( $subPage );
713
714        $this->getHookRunner()->onSpecialPageAfterExecute( $this, $subPage );
715    }
716
717    /**
718     * Gets called before {@link execute}.
719     * Return false to prevent calling execute() (since 1.27+).
720     *
721     * @stable to override
722     * @since 1.20
723     *
724     * @param string|null $subPage
725     * @return bool|void
726     */
727    protected function beforeExecute( $subPage ) {
728        // No-op
729    }
730
731    /**
732     * Gets called after {@link execute}.
733     *
734     * @stable to override
735     * @since 1.20
736     *
737     * @param string|null $subPage
738     */
739    protected function afterExecute( $subPage ) {
740        // No-op
741    }
742
743    /**
744     * Default execute method
745     * Checks user permissions
746     *
747     * This must be overridden by subclasses; it will be made abstract in a future version
748     *
749     * @stable to override
750     *
751     * @param string|null $subPage
752     */
753    public function execute( $subPage ) {
754        $this->setHeaders();
755        $this->checkPermissions();
756        $securityLevel = $this->getLoginSecurityLevel();
757        if ( $securityLevel !== false && !$this->checkLoginSecurityLevel( $securityLevel ) ) {
758            return;
759        }
760        $this->outputHeader();
761    }
762
763    /**
764     * Outputs a summary message on top of special pages
765     * By default the message key is the canonical name of the special page
766     * May be overridden, i.e. by extensions to stick with the naming conventions
767     * for message keys: 'extensionname-xxx'
768     *
769     * @stable to override
770     *
771     * @param string $summaryMessageKey Message key of the summary
772     */
773    protected function outputHeader( $summaryMessageKey = '' ) {
774        if ( $summaryMessageKey == '' ) {
775            $msg = strtolower( $this->getName() ) . '-summary';
776        } else {
777            $msg = $summaryMessageKey;
778        }
779        if ( !$this->msg( $msg )->isDisabled() && !$this->including() ) {
780            $this->getOutput()->wrapWikiMsg(
781                "<div class='mw-specialpage-summary'>\n$1\n</div>", $msg );
782        }
783    }
784
785    /**
786     * Returns the name that goes in the \<h1\> in the special page itself, and
787     * also the name that will be listed in Special:SpecialPages
788     *
789     * Derived classes can override this, but usually it is easier to keep the
790     * default behavior.
791     *
792     * Since 1.45, returning a string from this method is no longer allowed.
793     *
794     * @stable to override
795     *
796     * @return Message
797     */
798    public function getDescription() {
799        return $this->msg( strtolower( $this->mName ) );
800    }
801
802    /**
803     * Similar to SpecialPage::getDescription, but takes into account subpages and designed for display
804     * in tabs.
805     *
806     * @since 1.39
807     * @stable to override if special page has complex parameter handling. Use default message keys
808     * where possible.
809     *
810     * @param string $path (optional)
811     * @return string
812     */
813    public function getShortDescription( string $path = '' ): string {
814        $lowerPath = strtolower( str_replace( '/', '-', $path ) );
815        $shortKey = 'special-tab-' . $lowerPath;
816        $shortKey .= '-short';
817        $msgShort = $this->msg( $shortKey );
818        return $msgShort->text();
819    }
820
821    /**
822     * Get a self-referential title object
823     *
824     * @param string|false|null $subpage
825     * @return Title
826     * @since 1.23
827     */
828    public function getPageTitle( $subpage = false ) {
829        return self::getTitleFor( $this->mName, $subpage );
830    }
831
832    /**
833     * Sets the context this SpecialPage is executed in
834     *
835     * @param IContextSource $context
836     * @since 1.18
837     */
838    public function setContext( $context ) {
839        $this->mContext = $context;
840    }
841
842    /**
843     * Gets the context this SpecialPage is executed in
844     *
845     * @return IContextSource|RequestContext
846     * @since 1.18
847     */
848    public function getContext() {
849        if ( !( $this->mContext instanceof IContextSource ) ) {
850            wfDebug( __METHOD__ . " called and \$mContext is null. " .
851                "Using RequestContext::getMain()" );
852
853            $this->mContext = RequestContext::getMain();
854        }
855        return $this->mContext;
856    }
857
858    /**
859     * Get the WebRequest being used for this instance
860     *
861     * @return WebRequest
862     * @since 1.18
863     */
864    public function getRequest() {
865        return $this->getContext()->getRequest();
866    }
867
868    /**
869     * Get the OutputPage being used for this instance
870     *
871     * @return OutputPage
872     * @since 1.18
873     */
874    public function getOutput() {
875        return $this->getContext()->getOutput();
876    }
877
878    /**
879     * Shortcut to get the User executing this instance
880     *
881     * @return User
882     * @since 1.18
883     */
884    public function getUser() {
885        return $this->getContext()->getUser();
886    }
887
888    /**
889     * Shortcut to get the Authority executing this instance
890     *
891     * @return Authority
892     * @since 1.36
893     */
894    public function getAuthority(): Authority {
895        return $this->getContext()->getAuthority();
896    }
897
898    /**
899     * Shortcut to get the skin being used for this instance
900     *
901     * @return Skin
902     * @since 1.18
903     */
904    public function getSkin() {
905        return $this->getContext()->getSkin();
906    }
907
908    /**
909     * Shortcut to get user's language
910     *
911     * @return Language
912     * @since 1.19
913     */
914    public function getLanguage() {
915        return $this->getContext()->getLanguage();
916    }
917
918    /**
919     * Shortcut to get content language
920     *
921     * @return Language
922     * @since 1.36
923     */
924    final public function getContentLanguage(): Language {
925        if ( $this->contentLanguage === null ) {
926            // Fallback if not provided
927            // TODO Change to wfWarn in a future release
928            $this->contentLanguage = MediaWikiServices::getInstance()->getContentLanguage();
929        }
930        return $this->contentLanguage;
931    }
932
933    /**
934     * Set content language
935     *
936     * @internal For factory only
937     * @param Language $contentLanguage
938     * @since 1.36
939     */
940    final public function setContentLanguage( Language $contentLanguage ) {
941        $this->contentLanguage = $contentLanguage;
942    }
943
944    /**
945     * Shortcut to get main config object
946     * @return Config
947     * @since 1.24
948     */
949    public function getConfig() {
950        return $this->getContext()->getConfig();
951    }
952
953    /**
954     * Return the full title, including $par
955     *
956     * @return Title
957     * @since 1.18
958     */
959    public function getFullTitle() {
960        return $this->getContext()->getTitle();
961    }
962
963    /**
964     * Return the robot policy. Derived classes that override this can change
965     * the robot policy set by setHeaders() from the default 'noindex,nofollow'.
966     *
967     * @return string
968     * @since 1.23
969     */
970    protected function getRobotPolicy() {
971        return 'noindex,nofollow';
972    }
973
974    /**
975     * Wrapper around wfMessage that sets the current context.
976     *
977     * @since 1.16
978     * @param string|string[]|MessageSpecifier $key
979     * @phpcs:ignore Generic.Files.LineLength
980     * @param MessageParam|MessageSpecifier|string|int|float|list<MessageParam|MessageSpecifier|string|int|float> ...$params
981     *   See Message::params()
982     * @return Message
983     * @see wfMessage
984     */
985    public function msg( $key, ...$params ) {
986        $message = $this->getContext()->msg( $key, ...$params );
987        // RequestContext passes context to wfMessage, and the language is set from
988        // the context, but setting the language for Message class removes the
989        // interface message status, which breaks for example usernameless gender
990        // invocations. Restore the flag when not including special page in content.
991        if ( $this->including() ) {
992            $message->setInterfaceMessageFlag( false );
993        }
994
995        return $message;
996    }
997
998    /**
999     * Adds RSS/atom links
1000     *
1001     * @param array $params
1002     */
1003    protected function addFeedLinks( $params ) {
1004        $feedTemplate = wfScript( 'api' );
1005
1006        foreach ( $this->getConfig()->get( MainConfigNames::FeedClasses ) as $format => $class ) {
1007            $theseParams = $params + [ 'feedformat' => $format ];
1008            $url = wfAppendQuery( $feedTemplate, $theseParams );
1009            $this->getOutput()->addFeedLink( $format, $url );
1010        }
1011    }
1012
1013    /**
1014     * Adds help link with an icon via page indicators.
1015     * Link target can be overridden by a local message containing a wikilink:
1016     * the message key is: lowercase special page name + '-helppage'.
1017     * @param string $to Target MediaWiki.org page title or encoded URL.
1018     * @param bool $overrideBaseUrl Whether $url is a full URL, to avoid MW.o.
1019     * @since 1.25
1020     */
1021    public function addHelpLink( $to, $overrideBaseUrl = false ) {
1022        if ( $this->including() ) {
1023            return;
1024        }
1025
1026        $msg = $this->msg( strtolower( $this->getName() ) . '-helppage' );
1027
1028        if ( !$msg->isDisabled() ) {
1029            $title = Title::newFromText( $msg->plain() );
1030            if ( $title instanceof Title ) {
1031                $this->getOutput()->addHelpLink( $title->getLocalURL(), true );
1032            }
1033        } else {
1034            $this->getOutput()->addHelpLink( $to, $overrideBaseUrl );
1035        }
1036    }
1037
1038    /**
1039     * Get the group that the special page belongs in on Special:SpecialPage
1040     * Use this method, instead of getGroupName to allow customization
1041     * of the group name from the wiki side
1042     *
1043     * @return string Group of this special page
1044     * @since 1.21
1045     */
1046    public function getFinalGroupName() {
1047        $name = $this->getName();
1048
1049        // Allow overriding the group from the wiki side
1050        $msg = $this->msg( 'specialpages-specialpagegroup-' . strtolower( $name ) )->inContentLanguage();
1051        if ( !$msg->isBlank() ) {
1052            $group = $msg->text();
1053        } else {
1054            // Than use the group from this object
1055            $group = $this->getGroupName();
1056        }
1057
1058        return $group;
1059    }
1060
1061    /**
1062     * Indicates whether POST requests to this special page require write access to the wiki.
1063     *
1064     * Subclasses must override this method to return true if any of the operations that
1065     * they perform on POST requests are not "safe" per RFC 7231 section 4.2.1. A subclass's
1066     * operation is "safe" if it is essentially read-only, i.e. the client does not request
1067     * nor expect any state change that would be observable in the responses to future requests.
1068     *
1069     * Implementations of this method must always return the same value, regardless of the
1070     * parameters passed to the constructor or system state.
1071     *
1072     * When handling GET/HEAD requests, subclasses should only perform "safe" operations.
1073     * Note that some subclasses might only perform "safe" operations even for POST requests,
1074     * particularly in the case where large input parameters are required.
1075     *
1076     * @stable to override
1077     *
1078     * @return bool
1079     * @since 1.27
1080     */
1081    public function doesWrites() {
1082        return false;
1083    }
1084
1085    /**
1086     * Under which header this special page is listed in Special:SpecialPages
1087     * See messages 'specialpages-group-*' for valid names
1088     * This method defaults to group 'other'
1089     *
1090     * @stable to override
1091     *
1092     * @return string
1093     * @since 1.21
1094     */
1095    protected function getGroupName() {
1096        return 'other';
1097    }
1098
1099    /**
1100     * Call wfTransactionalTimeLimit() if this request was POSTed
1101     * @since 1.26
1102     */
1103    protected function useTransactionalTimeLimit() {
1104        if ( $this->getRequest()->wasPosted() ) {
1105            wfTransactionalTimeLimit();
1106        }
1107    }
1108
1109    /**
1110     * @since 1.28
1111     * @return LinkRenderer
1112     */
1113    public function getLinkRenderer(): LinkRenderer {
1114        if ( $this->linkRenderer === null ) {
1115            // TODO Inject the service
1116            $this->linkRenderer = MediaWikiServices::getInstance()->getLinkRendererFactory()
1117                ->create();
1118        }
1119        return $this->linkRenderer;
1120    }
1121
1122    /**
1123     * @since 1.28
1124     * @param LinkRenderer $linkRenderer
1125     */
1126    public function setLinkRenderer( LinkRenderer $linkRenderer ) {
1127        $this->linkRenderer = $linkRenderer;
1128    }
1129
1130    /**
1131     * Generate (prev x| next x) (20|50|100...) type links for paging
1132     *
1133     * @param int $offset
1134     * @param int $limit
1135     * @param array $query Optional URL query parameter string
1136     * @param bool $atEnd Optional param for specified if this is the last page
1137     * @param string|false $subpage Optional param for specifying subpage
1138     * @return string
1139     */
1140    protected function buildPrevNextNavigation(
1141        $offset,
1142        $limit,
1143        array $query = [],
1144        $atEnd = false,
1145        $subpage = false
1146    ) {
1147        $navBuilder = new PagerNavigationBuilder( $this );
1148        $navBuilder
1149            ->setPage( $this->getPageTitle( $subpage ) )
1150            ->setLinkQuery( [ 'limit' => $limit, 'offset' => $offset ] + $query )
1151            ->setLimitLinkQueryParam( 'limit' )
1152            ->setCurrentLimit( $limit )
1153            ->setPrevTooltipMsg( 'prevn-title' )
1154            ->setNextTooltipMsg( 'nextn-title' )
1155            ->setLimitTooltipMsg( 'shown-title' );
1156
1157        if ( $offset > 0 ) {
1158            $navBuilder->setPrevLinkQuery( [ 'offset' => (string)max( $offset - $limit, 0 ) ] );
1159        }
1160        if ( !$atEnd ) {
1161            $navBuilder->setNextLinkQuery( [ 'offset' => (string)( $offset + $limit ) ] );
1162        }
1163
1164        return $navBuilder->getHtml();
1165    }
1166
1167    /**
1168     * @since 1.35
1169     * @internal
1170     * @param HookContainer $hookContainer
1171     */
1172    public function setHookContainer( HookContainer $hookContainer ) {
1173        $this->hookContainer = $hookContainer;
1174        $this->hookRunner = new HookRunner( $hookContainer );
1175    }
1176
1177    /**
1178     * @since 1.35
1179     * @return HookContainer
1180     */
1181    protected function getHookContainer() {
1182        if ( !$this->hookContainer ) {
1183            $this->hookContainer = MediaWikiServices::getInstance()->getHookContainer();
1184        }
1185        return $this->hookContainer;
1186    }
1187
1188    /**
1189     * @internal This is for use by core only. Hook interfaces may be removed
1190     *   without notice.
1191     * @since 1.35
1192     * @return HookRunner
1193     */
1194    protected function getHookRunner() {
1195        if ( !$this->hookRunner ) {
1196            $this->hookRunner = new HookRunner( $this->getHookContainer() );
1197        }
1198        return $this->hookRunner;
1199    }
1200
1201    /**
1202     * @internal For factory only
1203     * @since 1.36
1204     * @param SpecialPageFactory $specialPageFactory
1205     */
1206    final public function setSpecialPageFactory( SpecialPageFactory $specialPageFactory ) {
1207        $this->specialPageFactory = $specialPageFactory;
1208    }
1209
1210    /**
1211     * @since 1.36
1212     * @return SpecialPageFactory
1213     */
1214    final protected function getSpecialPageFactory(): SpecialPageFactory {
1215        if ( !$this->specialPageFactory ) {
1216            // Fallback if not provided
1217            // TODO Change to wfWarn in a future release
1218            $this->specialPageFactory = MediaWikiServices::getInstance()->getSpecialPageFactory();
1219        }
1220        return $this->specialPageFactory;
1221    }
1222}
1223
1224/** @deprecated class alias since 1.41 */
1225class_alias( SpecialPage::class, 'SpecialPage' );