3 * Parent class for all special pages.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @ingroup SpecialPage
24 use MediaWiki\Auth\AuthManager
;
25 use MediaWiki\Linker\LinkRenderer
;
26 use MediaWiki\MediaWikiServices
;
29 * Parent class for all special pages.
31 * Includes some static functions for handling the special page list deprecated
32 * in favor of SpecialPageFactory.
34 * @ingroup SpecialPage
36 class SpecialPage
implements MessageLocalizer
{
37 // The canonical name of this special page
38 // Also used for the default <h1> heading, @see getDescription()
41 // The local name of this special page
44 // Minimum user level required to access this page, or "" for anyone.
45 // Also used to categorise the pages in Special:Specialpages
46 protected $mRestriction;
48 // Listed in Special:Specialpages?
51 // Whether or not this special page is being included from an article
52 protected $mIncluding;
54 // Whether the special page can be included in an article
55 protected $mIncludable;
58 * Current request context
64 * @var \MediaWiki\Linker\LinkRenderer|null
66 private $linkRenderer;
69 * Get a localised Title object for a specified special page name
70 * If you don't need a full Title object, consider using TitleValue through
71 * getTitleValueFor() below.
74 * @since 1.21 $fragment parameter added
77 * @param string|bool $subpage Subpage string, or false to not use a subpage
78 * @param string $fragment The link fragment (after the "#")
82 public static function getTitleFor( $name, $subpage = false, $fragment = '' ) {
83 return Title
::newFromTitleValue(
84 self
::getTitleValueFor( $name, $subpage, $fragment )
89 * Get a localised TitleValue object for a specified special page name
93 * @param string|bool $subpage Subpage string, or false to not use a subpage
94 * @param string $fragment The link fragment (after the "#")
97 public static function getTitleValueFor( $name, $subpage = false, $fragment = '' ) {
98 $name = SpecialPageFactory
::getLocalNameFor( $name, $subpage );
100 return new TitleValue( NS_SPECIAL
, $name, $fragment );
104 * Get a localised Title object for a page name with a possibly unvalidated subpage
106 * @param string $name
107 * @param string|bool $subpage Subpage string, or false to not use a subpage
108 * @return Title|null Title object or null if the page doesn't exist
110 public static function getSafeTitleFor( $name, $subpage = false ) {
111 $name = SpecialPageFactory
::getLocalNameFor( $name, $subpage );
113 return Title
::makeTitleSafe( NS_SPECIAL
, $name );
120 * Default constructor for special pages
121 * Derivative classes should call this from their constructor
122 * Note that if the user does not have the required level, an error message will
123 * be displayed by the default execute() method, without the global function ever
126 * If you override execute(), you can recover the default behavior with userCanExecute()
127 * and displayRestrictionError()
129 * @param string $name Name of the special page, as seen in links and URLs
130 * @param string $restriction User right required, e.g. "block" or "delete"
131 * @param bool $listed Whether the page is listed in Special:Specialpages
132 * @param callable|bool $function Unused
133 * @param string $file Unused
134 * @param bool $includable Whether the page can be included in normal pages
136 public function __construct(
137 $name = '', $restriction = '', $listed = true,
138 $function = false, $file = '', $includable = false
140 $this->mName
= $name;
141 $this->mRestriction
= $restriction;
142 $this->mListed
= $listed;
143 $this->mIncludable
= $includable;
147 * Get the name of this Special Page.
155 * Get the permission that a user must have to execute this page
158 function getRestriction() {
159 return $this->mRestriction
;
162 // @todo FIXME: Decide which syntax to use for this, and stick to it
164 * Whether this special page is listed in Special:SpecialPages
168 function isListed() {
169 return $this->mListed
;
173 * Set whether this page is listed in Special:Specialpages, at run-time
175 * @param bool $listed
178 function setListed( $listed ) {
179 return wfSetVar( $this->mListed
, $listed );
183 * Get or set whether this special page is listed in Special:SpecialPages
188 function listed( $x = null ) {
189 return wfSetVar( $this->mListed
, $x );
193 * Whether it's allowed to transclude the special page via {{Special:Foo/params}}
196 public function isIncludable() {
197 return $this->mIncludable
;
201 * How long to cache page when it is being included.
203 * @note If cache time is not 0, then the current user becomes an anon
204 * if you want to do any per-user customizations, than this method
205 * must be overriden to return 0.
207 * @return int Time in seconds, 0 to disable caching altogether,
208 * false to use the parent page's cache settings
210 public function maxIncludeCacheTime() {
211 return $this->getConfig()->get( 'MiserMode' ) ?
$this->getCacheTTL() : 0;
215 * @return int Seconds that this page can be cached
217 protected function getCacheTTL() {
222 * Whether the special page is being evaluated via transclusion
226 function including( $x = null ) {
227 return wfSetVar( $this->mIncluding
, $x );
231 * Get the localised name of the special page
234 function getLocalName() {
235 if ( !isset( $this->mLocalName
) ) {
236 $this->mLocalName
= SpecialPageFactory
::getLocalNameFor( $this->mName
);
239 return $this->mLocalName
;
243 * Is this page expensive (for some definition of expensive)?
244 * Expensive pages are disabled or cached in miser mode. Originally used
245 * (and still overridden) by QueryPage and subclasses, moved here so that
246 * Special:SpecialPages can safely call it for all special pages.
250 public function isExpensive() {
255 * Is this page cached?
256 * Expensive pages are cached or disabled in miser mode.
257 * Used by QueryPage and subclasses, moved here so that
258 * Special:SpecialPages can safely call it for all special pages.
263 public function isCached() {
268 * Can be overridden by subclasses with more complicated permissions
271 * @return bool Should the page be displayed with the restricted-access
274 public function isRestricted() {
275 // DWIM: If anons can do something, then it is not restricted
276 return $this->mRestriction
!= '' && !User
::groupHasPermission( '*', $this->mRestriction
);
280 * Checks if the given user (identified by an object) can execute this
281 * special page (as defined by $mRestriction). Can be overridden by sub-
282 * classes with more complicated permissions schemes.
284 * @param User $user The user to check
285 * @return bool Does the user have permission to view the page?
287 public function userCanExecute( User
$user ) {
288 return $user->isAllowed( $this->mRestriction
);
292 * Output an error message telling the user what access level they have to have
293 * @throws PermissionsError
295 function displayRestrictionError() {
296 throw new PermissionsError( $this->mRestriction
);
300 * Checks if userCanExecute, and if not throws a PermissionsError
304 * @throws PermissionsError
306 public function checkPermissions() {
307 if ( !$this->userCanExecute( $this->getUser() ) ) {
308 $this->displayRestrictionError();
313 * If the wiki is currently in readonly mode, throws a ReadOnlyError
317 * @throws ReadOnlyError
319 public function checkReadOnly() {
320 if ( wfReadOnly() ) {
321 throw new ReadOnlyError
;
326 * If the user is not logged in, throws UserNotLoggedIn error
328 * The user will be redirected to Special:Userlogin with the given message as an error on
332 * @param string $reasonMsg [optional] Message key to be displayed on login page
333 * @param string $titleMsg [optional] Passed on to UserNotLoggedIn constructor
334 * @throws UserNotLoggedIn
336 public function requireLogin(
337 $reasonMsg = 'exception-nologin-text', $titleMsg = 'exception-nologin'
339 if ( $this->getUser()->isAnon() ) {
340 throw new UserNotLoggedIn( $reasonMsg, $titleMsg );
345 * Tells if the special page does something security-sensitive and needs extra defense against
346 * a stolen account (e.g. a reauthentication). What exactly that will mean is decided by the
347 * authentication framework.
348 * @return bool|string False or the argument for AuthManager::securitySensitiveOperationStatus().
349 * Typically a special page needing elevated security would return its name here.
351 protected function getLoginSecurityLevel() {
356 * Record preserved POST data after a reauthentication.
358 * This is called from checkLoginSecurityLevel() when returning from the
359 * redirect for reauthentication, if the redirect had been served in
360 * response to a POST request.
362 * The base SpecialPage implementation does nothing. If your subclass uses
363 * getLoginSecurityLevel() or checkLoginSecurityLevel(), it should probably
364 * implement this to do something with the data.
369 protected function setReauthPostData( array $data ) {
373 * Verifies that the user meets the security level, possibly reauthenticating them in the process.
375 * This should be used when the page does something security-sensitive and needs extra defense
376 * against a stolen account (e.g. a reauthentication). The authentication framework will make
377 * an extra effort to make sure the user account is not compromised. What that exactly means
378 * will depend on the system and user settings; e.g. the user might be required to log in again
379 * unless their last login happened recently, or they might be given a second-factor challenge.
381 * Calling this method will result in one if these actions:
382 * - return true: all good.
383 * - return false and set a redirect: caller should abort; the redirect will take the user
384 * to the login page for reauthentication, and back.
385 * - throw an exception if there is no way for the user to meet the requirements without using
386 * a different access method (e.g. this functionality is only available from a specific IP).
388 * Note that this does not in any way check that the user is authorized to use this special page
389 * (use checkPermissions() for that).
391 * @param string $level A security level. Can be an arbitrary string, defaults to the page name.
392 * @return bool False means a redirect to the reauthentication page has been set and processing
393 * of the special page should be aborted.
394 * @throws ErrorPageError If the security level cannot be met, even with reauthentication.
396 protected function checkLoginSecurityLevel( $level = null ) {
397 $level = $level ?
: $this->getName();
398 $key = 'SpecialPage:reauth:' . $this->getName();
399 $request = $this->getRequest();
401 $securityStatus = AuthManager
::singleton()->securitySensitiveOperationStatus( $level );
402 if ( $securityStatus === AuthManager
::SEC_OK
) {
403 $uniqueId = $request->getVal( 'postUniqueId' );
405 $key = $key . ':' . $uniqueId;
406 $session = $request->getSession();
407 $data = $session->getSecret( $key );
409 $session->remove( $key );
410 $this->setReauthPostData( $data );
414 } elseif ( $securityStatus === AuthManager
::SEC_REAUTH
) {
415 $title = self
::getTitleFor( 'Userlogin' );
416 $queryParams = $request->getQueryValues();
418 if ( $request->wasPosted() ) {
419 $data = array_diff_assoc( $request->getValues(), $request->getQueryValues() );
421 // unique ID in case the same special page is open in multiple browser tabs
422 $uniqueId = MWCryptRand
::generateHex( 6 );
423 $key = $key . ':' . $uniqueId;
424 $queryParams['postUniqueId'] = $uniqueId;
425 $session = $request->getSession();
426 $session->persist(); // Just in case
427 $session->setSecret( $key, $data );
432 'returnto' => $this->getFullTitle()->getPrefixedDBkey(),
433 'returntoquery' => wfArrayToCgi( array_diff_key( $queryParams, [ 'title' => true ] ) ),
436 $url = $title->getFullURL( $query, false, PROTO_HTTPS
);
438 $this->getOutput()->redirect( $url );
442 $titleMessage = wfMessage( 'specialpage-securitylevel-not-allowed-title' );
443 $errorMessage = wfMessage( 'specialpage-securitylevel-not-allowed' );
444 throw new ErrorPageError( $titleMessage, $errorMessage );
448 * Return an array of subpages beginning with $search that this special page will accept.
450 * For example, if a page supports subpages "foo", "bar" and "baz" (as in Special:PageName/foo,
453 * - `prefixSearchSubpages( "ba" )` should return `array( "bar", "baz" )`
454 * - `prefixSearchSubpages( "f" )` should return `array( "foo" )`
455 * - `prefixSearchSubpages( "z" )` should return `array()`
456 * - `prefixSearchSubpages( "" )` should return `array( foo", "bar", "baz" )`
458 * @param string $search Prefix to search for
459 * @param int $limit Maximum number of results to return (usually 10)
460 * @param int $offset Number of results to skip (usually 0)
461 * @return string[] Matching subpages
463 public function prefixSearchSubpages( $search, $limit, $offset ) {
464 $subpages = $this->getSubpagesForPrefixSearch();
469 return self
::prefixSearchArray( $search, $limit, $subpages, $offset );
473 * Return an array of subpages that this special page will accept for prefix
474 * searches. If this method requires a query you might instead want to implement
475 * prefixSearchSubpages() directly so you can support $limit and $offset. This
476 * method is better for static-ish lists of things.
478 * @return string[] subpages to search from
480 protected function getSubpagesForPrefixSearch() {
485 * Perform a regular substring search for prefixSearchSubpages
486 * @param string $search Prefix to search for
487 * @param int $limit Maximum number of results to return (usually 10)
488 * @param int $offset Number of results to skip (usually 0)
489 * @return string[] Matching subpages
491 protected function prefixSearchString( $search, $limit, $offset ) {
492 $title = Title
::newFromText( $search );
493 if ( !$title ||
!$title->canExist() ) {
494 // No prefix suggestion in special and media namespace
498 $searchEngine = MediaWikiServices
::getInstance()->newSearchEngine();
499 $searchEngine->setLimitOffset( $limit, $offset );
500 $searchEngine->setNamespaces( [] );
501 $result = $searchEngine->defaultPrefixSearch( $search );
502 return array_map( function ( Title
$t ) {
503 return $t->getPrefixedText();
508 * Helper function for implementations of prefixSearchSubpages() that
509 * filter the values in memory (as opposed to making a query).
512 * @param string $search
514 * @param array $subpages
518 protected static function prefixSearchArray( $search, $limit, array $subpages, $offset ) {
519 $escaped = preg_quote( $search, '/' );
520 return array_slice( preg_grep( "/^$escaped/i",
521 array_slice( $subpages, $offset ) ), 0, $limit );
525 * Sets headers - this should be called from the execute() method of all derived classes!
527 function setHeaders() {
528 $out = $this->getOutput();
529 $out->setArticleRelated( false );
530 $out->setRobotPolicy( $this->getRobotPolicy() );
531 $out->setPageTitle( $this->getDescription() );
532 if ( $this->getConfig()->get( 'UseMediaWikiUIEverywhere' ) ) {
533 $out->addModuleStyles( [
534 'mediawiki.ui.input',
535 'mediawiki.ui.radio',
536 'mediawiki.ui.checkbox',
546 * @param string|null $subPage
548 final public function run( $subPage ) {
550 * Gets called before @see SpecialPage::execute.
551 * Return false to prevent calling execute() (since 1.27+).
555 * @param SpecialPage $this
556 * @param string|null $subPage
558 if ( !Hooks
::run( 'SpecialPageBeforeExecute', [ $this, $subPage ] ) ) {
562 if ( $this->beforeExecute( $subPage ) === false ) {
565 $this->execute( $subPage );
566 $this->afterExecute( $subPage );
569 * Gets called after @see SpecialPage::execute.
573 * @param SpecialPage $this
574 * @param string|null $subPage
576 Hooks
::run( 'SpecialPageAfterExecute', [ $this, $subPage ] );
580 * Gets called before @see SpecialPage::execute.
581 * Return false to prevent calling execute() (since 1.27+).
585 * @param string|null $subPage
588 protected function beforeExecute( $subPage ) {
593 * Gets called after @see SpecialPage::execute.
597 * @param string|null $subPage
599 protected function afterExecute( $subPage ) {
604 * Default execute method
605 * Checks user permissions
607 * This must be overridden by subclasses; it will be made abstract in a future version
609 * @param string|null $subPage
611 public function execute( $subPage ) {
613 $this->checkPermissions();
614 $securityLevel = $this->getLoginSecurityLevel();
615 if ( $securityLevel !== false && !$this->checkLoginSecurityLevel( $securityLevel ) ) {
618 $this->outputHeader();
622 * Outputs a summary message on top of special pages
623 * Per default the message key is the canonical name of the special page
624 * May be overridden, i.e. by extensions to stick with the naming conventions
625 * for message keys: 'extensionname-xxx'
627 * @param string $summaryMessageKey Message key of the summary
629 function outputHeader( $summaryMessageKey = '' ) {
632 if ( $summaryMessageKey == '' ) {
633 $msg = $wgContLang->lc( $this->getName() ) . '-summary';
635 $msg = $summaryMessageKey;
637 if ( !$this->msg( $msg )->isDisabled() && !$this->including() ) {
638 $this->getOutput()->wrapWikiMsg(
639 "<div class='mw-specialpage-summary'>\n$1\n</div>", $msg );
644 * Returns the name that goes in the \<h1\> in the special page itself, and
645 * also the name that will be listed in Special:Specialpages
647 * Derived classes can override this, but usually it is easier to keep the
652 function getDescription() {
653 return $this->msg( strtolower( $this->mName
) )->text();
657 * Get a self-referential title object
659 * @param string|bool $subpage
661 * @deprecated since 1.23, use SpecialPage::getPageTitle
663 function getTitle( $subpage = false ) {
664 wfDeprecated( __METHOD__
, '1.23' );
665 return $this->getPageTitle( $subpage );
669 * Get a self-referential title object
671 * @param string|bool $subpage
675 function getPageTitle( $subpage = false ) {
676 return self
::getTitleFor( $this->mName
, $subpage );
680 * Sets the context this SpecialPage is executed in
682 * @param IContextSource $context
685 public function setContext( $context ) {
686 $this->mContext
= $context;
690 * Gets the context this SpecialPage is executed in
692 * @return IContextSource|RequestContext
695 public function getContext() {
696 if ( $this->mContext
instanceof IContextSource
) {
697 return $this->mContext
;
699 wfDebug( __METHOD__
. " called and \$mContext is null. " .
700 "Return RequestContext::getMain(); for sanity\n" );
702 return RequestContext
::getMain();
707 * Get the WebRequest being used for this instance
712 public function getRequest() {
713 return $this->getContext()->getRequest();
717 * Get the OutputPage being used for this instance
722 public function getOutput() {
723 return $this->getContext()->getOutput();
727 * Shortcut to get the User executing this instance
732 public function getUser() {
733 return $this->getContext()->getUser();
737 * Shortcut to get the skin being used for this instance
742 public function getSkin() {
743 return $this->getContext()->getSkin();
747 * Shortcut to get user's language
752 public function getLanguage() {
753 return $this->getContext()->getLanguage();
757 * Shortcut to get main config object
761 public function getConfig() {
762 return $this->getContext()->getConfig();
766 * Return the full title, including $par
771 public function getFullTitle() {
772 return $this->getContext()->getTitle();
776 * Return the robot policy. Derived classes that override this can change
777 * the robot policy set by setHeaders() from the default 'noindex,nofollow'.
782 protected function getRobotPolicy() {
783 return 'noindex,nofollow';
787 * Wrapper around wfMessage that sets the current context.
793 public function msg( $key /* $args */ ) {
794 $message = $this->getContext()->msg( ...func_get_args() );
795 // RequestContext passes context to wfMessage, and the language is set from
796 // the context, but setting the language for Message class removes the
797 // interface message status, which breaks for example usernameless gender
798 // invocations. Restore the flag when not including special page in content.
799 if ( $this->including() ) {
800 $message->setInterfaceMessageFlag( false );
807 * Adds RSS/atom links
809 * @param array $params
811 protected function addFeedLinks( $params ) {
812 $feedTemplate = wfScript( 'api' );
814 foreach ( $this->getConfig()->get( 'FeedClasses' ) as $format => $class ) {
815 $theseParams = $params +
[ 'feedformat' => $format ];
816 $url = wfAppendQuery( $feedTemplate, $theseParams );
817 $this->getOutput()->addFeedLink( $format, $url );
822 * Adds help link with an icon via page indicators.
823 * Link target can be overridden by a local message containing a wikilink:
824 * the message key is: lowercase special page name + '-helppage'.
825 * @param string $to Target MediaWiki.org page title or encoded URL.
826 * @param bool $overrideBaseUrl Whether $url is a full URL, to avoid MW.o.
829 public function addHelpLink( $to, $overrideBaseUrl = false ) {
830 if ( $this->including() ) {
835 $msg = $this->msg( $wgContLang->lc( $this->getName() ) . '-helppage' );
837 if ( !$msg->isDisabled() ) {
838 $helpUrl = Skin
::makeUrl( $msg->plain() );
839 $this->getOutput()->addHelpLink( $helpUrl, true );
841 $this->getOutput()->addHelpLink( $to, $overrideBaseUrl );
846 * Get the group that the special page belongs in on Special:SpecialPage
847 * Use this method, instead of getGroupName to allow customization
848 * of the group name from the wiki side
850 * @return string Group of this special page
853 public function getFinalGroupName() {
854 $name = $this->getName();
856 // Allow overriding the group from the wiki side
857 $msg = $this->msg( 'specialpages-specialpagegroup-' . strtolower( $name ) )->inContentLanguage();
858 if ( !$msg->isBlank() ) {
859 $group = $msg->text();
861 // Than use the group from this object
862 $group = $this->getGroupName();
869 * Indicates whether this special page may perform database writes
874 public function doesWrites() {
879 * Under which header this special page is listed in Special:SpecialPages
880 * See messages 'specialpages-group-*' for valid names
881 * This method defaults to group 'other'
886 protected function getGroupName() {
891 * Call wfTransactionalTimeLimit() if this request was POSTed
894 protected function useTransactionalTimeLimit() {
895 if ( $this->getRequest()->wasPosted() ) {
896 wfTransactionalTimeLimit();
902 * @return \MediaWiki\Linker\LinkRenderer
904 public function getLinkRenderer() {
905 if ( $this->linkRenderer
) {
906 return $this->linkRenderer
;
908 return MediaWikiServices
::getInstance()->getLinkRenderer();
914 * @param \MediaWiki\Linker\LinkRenderer $linkRenderer
916 public function setLinkRenderer( LinkRenderer
$linkRenderer ) {
917 $this->linkRenderer
= $linkRenderer;