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
;
27 use MediaWiki\Navigation\PrevNextNavigationRenderer
;
30 * Parent class for all special pages.
32 * Includes some static functions for handling the special page list deprecated
33 * in favor of SpecialPageFactory.
35 * @ingroup SpecialPage
37 class SpecialPage
implements MessageLocalizer
{
38 // The canonical name of this special page
39 // Also used for the default <h1> heading, @see getDescription()
42 // The local name of this special page
45 // Minimum user level required to access this page, or "" for anyone.
46 // Also used to categorise the pages in Special:Specialpages
47 protected $mRestriction;
49 // Listed in Special:Specialpages?
52 // Whether or not this special page is being included from an article
53 protected $mIncluding;
55 // Whether the special page can be included in an article
56 protected $mIncludable;
59 * Current request context
65 * @var \MediaWiki\Linker\LinkRenderer|null
67 private $linkRenderer;
70 * Get a localised Title object for a specified special page name
71 * If you don't need a full Title object, consider using TitleValue through
72 * getTitleValueFor() below.
75 * @since 1.21 $fragment parameter added
78 * @param string|bool $subpage Subpage string, or false to not use a subpage
79 * @param string $fragment The link fragment (after the "#")
83 public static function getTitleFor( $name, $subpage = false, $fragment = '' ) {
84 return Title
::newFromTitleValue(
85 self
::getTitleValueFor( $name, $subpage, $fragment )
90 * Get a localised TitleValue object for a specified special page name
94 * @param string|bool $subpage Subpage string, or false to not use a subpage
95 * @param string $fragment The link fragment (after the "#")
98 public static function getTitleValueFor( $name, $subpage = false, $fragment = '' ) {
99 $name = MediaWikiServices
::getInstance()->getSpecialPageFactory()->
100 getLocalNameFor( $name, $subpage );
102 return new TitleValue( NS_SPECIAL
, $name, $fragment );
106 * Get a localised Title object for a page name with a possibly unvalidated subpage
108 * @param string $name
109 * @param string|bool $subpage Subpage string, or false to not use a subpage
110 * @return Title|null Title object or null if the page doesn't exist
112 public static function getSafeTitleFor( $name, $subpage = false ) {
113 $name = MediaWikiServices
::getInstance()->getSpecialPageFactory()->
114 getLocalNameFor( $name, $subpage );
116 return Title
::makeTitleSafe( NS_SPECIAL
, $name );
123 * Default constructor for special pages
124 * Derivative classes should call this from their constructor
125 * Note that if the user does not have the required level, an error message will
126 * be displayed by the default execute() method, without the global function ever
129 * If you override execute(), you can recover the default behavior with userCanExecute()
130 * and displayRestrictionError()
132 * @param string $name Name of the special page, as seen in links and URLs
133 * @param string $restriction User right required, e.g. "block" or "delete"
134 * @param bool $listed Whether the page is listed in Special:Specialpages
135 * @param callable|bool $function Unused
136 * @param string $file Unused
137 * @param bool $includable Whether the page can be included in normal pages
139 public function __construct(
140 $name = '', $restriction = '', $listed = true,
141 $function = false, $file = '', $includable = false
143 $this->mName
= $name;
144 $this->mRestriction
= $restriction;
145 $this->mListed
= $listed;
146 $this->mIncludable
= $includable;
150 * Get the name of this Special Page.
158 * Get the permission that a user must have to execute this page
161 function getRestriction() {
162 return $this->mRestriction
;
165 // @todo FIXME: Decide which syntax to use for this, and stick to it
168 * Whether this special page is listed in Special:SpecialPages
172 function isListed() {
173 return $this->mListed
;
177 * Set whether this page is listed in Special:Specialpages, at run-time
179 * @param bool $listed
182 function setListed( $listed ) {
183 return wfSetVar( $this->mListed
, $listed );
187 * Get or set whether this special page is listed in Special:SpecialPages
189 * @param bool|null $x
192 function listed( $x = null ) {
193 return wfSetVar( $this->mListed
, $x );
197 * Whether it's allowed to transclude the special page via {{Special:Foo/params}}
200 public function isIncludable() {
201 return $this->mIncludable
;
205 * How long to cache page when it is being included.
207 * @note If cache time is not 0, then the current user becomes an anon
208 * if you want to do any per-user customizations, than this method
209 * must be overriden to return 0.
211 * @return int Time in seconds, 0 to disable caching altogether,
212 * false to use the parent page's cache settings
214 public function maxIncludeCacheTime() {
215 return $this->getConfig()->get( 'MiserMode' ) ?
$this->getCacheTTL() : 0;
219 * @return int Seconds that this page can be cached
221 protected function getCacheTTL() {
226 * Whether the special page is being evaluated via transclusion
227 * @param bool|null $x
230 function including( $x = null ) {
231 return wfSetVar( $this->mIncluding
, $x );
235 * Get the localised name of the special page
238 function getLocalName() {
239 if ( !isset( $this->mLocalName
) ) {
240 $this->mLocalName
= MediaWikiServices
::getInstance()->getSpecialPageFactory()->
241 getLocalNameFor( $this->mName
);
244 return $this->mLocalName
;
248 * Is this page expensive (for some definition of expensive)?
249 * Expensive pages are disabled or cached in miser mode. Originally used
250 * (and still overridden) by QueryPage and subclasses, moved here so that
251 * Special:SpecialPages can safely call it for all special pages.
255 public function isExpensive() {
260 * Is this page cached?
261 * Expensive pages are cached or disabled in miser mode.
262 * Used by QueryPage and subclasses, moved here so that
263 * Special:SpecialPages can safely call it for all special pages.
268 public function isCached() {
273 * Can be overridden by subclasses with more complicated permissions
276 * @return bool Should the page be displayed with the restricted-access
279 public function isRestricted() {
280 // DWIM: If anons can do something, then it is not restricted
281 return $this->mRestriction
!= '' && !User
::groupHasPermission( '*', $this->mRestriction
);
285 * Checks if the given user (identified by an object) can execute this
286 * special page (as defined by $mRestriction). Can be overridden by sub-
287 * classes with more complicated permissions schemes.
289 * @param User $user The user to check
290 * @return bool Does the user have permission to view the page?
292 public function userCanExecute( User
$user ) {
293 return $user->isAllowed( $this->mRestriction
);
297 * Output an error message telling the user what access level they have to have
298 * @throws PermissionsError
300 function displayRestrictionError() {
301 throw new PermissionsError( $this->mRestriction
);
305 * Checks if userCanExecute, and if not throws a PermissionsError
309 * @throws PermissionsError
311 public function checkPermissions() {
312 if ( !$this->userCanExecute( $this->getUser() ) ) {
313 $this->displayRestrictionError();
318 * If the wiki is currently in readonly mode, throws a ReadOnlyError
322 * @throws ReadOnlyError
324 public function checkReadOnly() {
325 if ( wfReadOnly() ) {
326 throw new ReadOnlyError
;
331 * If the user is not logged in, throws UserNotLoggedIn error
333 * The user will be redirected to Special:Userlogin with the given message as an error on
337 * @param string $reasonMsg [optional] Message key to be displayed on login page
338 * @param string $titleMsg [optional] Passed on to UserNotLoggedIn constructor
339 * @throws UserNotLoggedIn
341 public function requireLogin(
342 $reasonMsg = 'exception-nologin-text', $titleMsg = 'exception-nologin'
344 if ( $this->getUser()->isAnon() ) {
345 throw new UserNotLoggedIn( $reasonMsg, $titleMsg );
350 * Tells if the special page does something security-sensitive and needs extra defense against
351 * a stolen account (e.g. a reauthentication). What exactly that will mean is decided by the
352 * authentication framework.
353 * @return bool|string False or the argument for AuthManager::securitySensitiveOperationStatus().
354 * Typically a special page needing elevated security would return its name here.
356 protected function getLoginSecurityLevel() {
361 * Record preserved POST data after a reauthentication.
363 * This is called from checkLoginSecurityLevel() when returning from the
364 * redirect for reauthentication, if the redirect had been served in
365 * response to a POST request.
367 * The base SpecialPage implementation does nothing. If your subclass uses
368 * getLoginSecurityLevel() or checkLoginSecurityLevel(), it should probably
369 * implement this to do something with the data.
374 protected function setReauthPostData( array $data ) {
378 * Verifies that the user meets the security level, possibly reauthenticating them in the process.
380 * This should be used when the page does something security-sensitive and needs extra defense
381 * against a stolen account (e.g. a reauthentication). The authentication framework will make
382 * an extra effort to make sure the user account is not compromised. What that exactly means
383 * will depend on the system and user settings; e.g. the user might be required to log in again
384 * unless their last login happened recently, or they might be given a second-factor challenge.
386 * Calling this method will result in one if these actions:
387 * - return true: all good.
388 * - return false and set a redirect: caller should abort; the redirect will take the user
389 * to the login page for reauthentication, and back.
390 * - throw an exception if there is no way for the user to meet the requirements without using
391 * a different access method (e.g. this functionality is only available from a specific IP).
393 * Note that this does not in any way check that the user is authorized to use this special page
394 * (use checkPermissions() for that).
396 * @param string|null $level A security level. Can be an arbitrary string, defaults to the page
398 * @return bool False means a redirect to the reauthentication page has been set and processing
399 * of the special page should be aborted.
400 * @throws ErrorPageError If the security level cannot be met, even with reauthentication.
402 protected function checkLoginSecurityLevel( $level = null ) {
403 $level = $level ?
: $this->getName();
404 $key = 'SpecialPage:reauth:' . $this->getName();
405 $request = $this->getRequest();
407 $securityStatus = AuthManager
::singleton()->securitySensitiveOperationStatus( $level );
408 if ( $securityStatus === AuthManager
::SEC_OK
) {
409 $uniqueId = $request->getVal( 'postUniqueId' );
411 $key .= ':' . $uniqueId;
412 $session = $request->getSession();
413 $data = $session->getSecret( $key );
415 $session->remove( $key );
416 $this->setReauthPostData( $data );
420 } elseif ( $securityStatus === AuthManager
::SEC_REAUTH
) {
421 $title = self
::getTitleFor( 'Userlogin' );
422 $queryParams = $request->getQueryValues();
424 if ( $request->wasPosted() ) {
425 $data = array_diff_assoc( $request->getValues(), $request->getQueryValues() );
427 // unique ID in case the same special page is open in multiple browser tabs
428 $uniqueId = MWCryptRand
::generateHex( 6 );
429 $key .= ':' . $uniqueId;
430 $queryParams['postUniqueId'] = $uniqueId;
431 $session = $request->getSession();
432 $session->persist(); // Just in case
433 $session->setSecret( $key, $data );
438 'returnto' => $this->getFullTitle()->getPrefixedDBkey(),
439 'returntoquery' => wfArrayToCgi( array_diff_key( $queryParams, [ 'title' => true ] ) ),
442 $url = $title->getFullURL( $query, false, PROTO_HTTPS
);
444 $this->getOutput()->redirect( $url );
448 $titleMessage = wfMessage( 'specialpage-securitylevel-not-allowed-title' );
449 $errorMessage = wfMessage( 'specialpage-securitylevel-not-allowed' );
450 throw new ErrorPageError( $titleMessage, $errorMessage );
454 * Return an array of subpages beginning with $search that this special page will accept.
456 * For example, if a page supports subpages "foo", "bar" and "baz" (as in Special:PageName/foo,
459 * - `prefixSearchSubpages( "ba" )` should return `[ "bar", "baz" ]`
460 * - `prefixSearchSubpages( "f" )` should return `[ "foo" ]`
461 * - `prefixSearchSubpages( "z" )` should return `[]`
462 * - `prefixSearchSubpages( "" )` should return `[ foo", "bar", "baz" ]`
464 * @param string $search Prefix to search for
465 * @param int $limit Maximum number of results to return (usually 10)
466 * @param int $offset Number of results to skip (usually 0)
467 * @return string[] Matching subpages
469 public function prefixSearchSubpages( $search, $limit, $offset ) {
470 $subpages = $this->getSubpagesForPrefixSearch();
475 return self
::prefixSearchArray( $search, $limit, $subpages, $offset );
479 * Return an array of subpages that this special page will accept for prefix
480 * searches. If this method requires a query you might instead want to implement
481 * prefixSearchSubpages() directly so you can support $limit and $offset. This
482 * method is better for static-ish lists of things.
484 * @return string[] subpages to search from
486 protected function getSubpagesForPrefixSearch() {
491 * Perform a regular substring search for prefixSearchSubpages
492 * @param string $search Prefix to search for
493 * @param int $limit Maximum number of results to return (usually 10)
494 * @param int $offset Number of results to skip (usually 0)
495 * @return string[] Matching subpages
497 protected function prefixSearchString( $search, $limit, $offset ) {
498 $title = Title
::newFromText( $search );
499 if ( !$title ||
!$title->canExist() ) {
500 // No prefix suggestion in special and media namespace
504 $searchEngine = MediaWikiServices
::getInstance()->newSearchEngine();
505 $searchEngine->setLimitOffset( $limit, $offset );
506 $searchEngine->setNamespaces( [] );
507 $result = $searchEngine->defaultPrefixSearch( $search );
508 return array_map( function ( Title
$t ) {
509 return $t->getPrefixedText();
514 * Helper function for implementations of prefixSearchSubpages() that
515 * filter the values in memory (as opposed to making a query).
518 * @param string $search
520 * @param array $subpages
524 protected static function prefixSearchArray( $search, $limit, array $subpages, $offset ) {
525 $escaped = preg_quote( $search, '/' );
526 return array_slice( preg_grep( "/^$escaped/i",
527 array_slice( $subpages, $offset ) ), 0, $limit );
531 * Sets headers - this should be called from the execute() method of all derived classes!
533 function setHeaders() {
534 $out = $this->getOutput();
535 $out->setArticleRelated( false );
536 $out->setRobotPolicy( $this->getRobotPolicy() );
537 $out->setPageTitle( $this->getDescription() );
538 if ( $this->getConfig()->get( 'UseMediaWikiUIEverywhere' ) ) {
539 $out->addModuleStyles( [
540 'mediawiki.ui.input',
541 'mediawiki.ui.radio',
542 'mediawiki.ui.checkbox',
552 * @param string|null $subPage
554 final public function run( $subPage ) {
556 * Gets called before @see SpecialPage::execute.
557 * Return false to prevent calling execute() (since 1.27+).
561 * @param SpecialPage $this
562 * @param string|null $subPage
564 if ( !Hooks
::run( 'SpecialPageBeforeExecute', [ $this, $subPage ] ) ) {
568 if ( $this->beforeExecute( $subPage ) === false ) {
571 $this->execute( $subPage );
572 $this->afterExecute( $subPage );
575 * Gets called after @see SpecialPage::execute.
579 * @param SpecialPage $this
580 * @param string|null $subPage
582 Hooks
::run( 'SpecialPageAfterExecute', [ $this, $subPage ] );
586 * Gets called before @see SpecialPage::execute.
587 * Return false to prevent calling execute() (since 1.27+).
591 * @param string|null $subPage
594 protected function beforeExecute( $subPage ) {
599 * Gets called after @see SpecialPage::execute.
603 * @param string|null $subPage
605 protected function afterExecute( $subPage ) {
610 * Default execute method
611 * Checks user permissions
613 * This must be overridden by subclasses; it will be made abstract in a future version
615 * @param string|null $subPage
617 public function execute( $subPage ) {
619 $this->checkPermissions();
620 $securityLevel = $this->getLoginSecurityLevel();
621 if ( $securityLevel !== false && !$this->checkLoginSecurityLevel( $securityLevel ) ) {
624 $this->outputHeader();
628 * Outputs a summary message on top of special pages
629 * Per default the message key is the canonical name of the special page
630 * May be overridden, i.e. by extensions to stick with the naming conventions
631 * for message keys: 'extensionname-xxx'
633 * @param string $summaryMessageKey Message key of the summary
635 function outputHeader( $summaryMessageKey = '' ) {
636 if ( $summaryMessageKey == '' ) {
637 $msg = MediaWikiServices
::getInstance()->getContentLanguage()->lc( $this->getName() ) .
640 $msg = $summaryMessageKey;
642 if ( !$this->msg( $msg )->isDisabled() && !$this->including() ) {
643 $this->getOutput()->wrapWikiMsg(
644 "<div class='mw-specialpage-summary'>\n$1\n</div>", $msg );
649 * Returns the name that goes in the \<h1\> in the special page itself, and
650 * also the name that will be listed in Special:Specialpages
652 * Derived classes can override this, but usually it is easier to keep the
657 function getDescription() {
658 return $this->msg( strtolower( $this->mName
) )->text();
662 * Get a self-referential title object
664 * @param string|bool $subpage
668 function getPageTitle( $subpage = false ) {
669 return self
::getTitleFor( $this->mName
, $subpage );
673 * Sets the context this SpecialPage is executed in
675 * @param IContextSource $context
678 public function setContext( $context ) {
679 $this->mContext
= $context;
683 * Gets the context this SpecialPage is executed in
685 * @return IContextSource|RequestContext
688 public function getContext() {
689 if ( $this->mContext
instanceof IContextSource
) {
690 return $this->mContext
;
692 wfDebug( __METHOD__
. " called and \$mContext is null. " .
693 "Return RequestContext::getMain(); for sanity\n" );
695 return RequestContext
::getMain();
700 * Get the WebRequest being used for this instance
705 public function getRequest() {
706 return $this->getContext()->getRequest();
710 * Get the OutputPage being used for this instance
715 public function getOutput() {
716 return $this->getContext()->getOutput();
720 * Shortcut to get the User executing this instance
725 public function getUser() {
726 return $this->getContext()->getUser();
730 * Shortcut to get the skin being used for this instance
735 public function getSkin() {
736 return $this->getContext()->getSkin();
740 * Shortcut to get user's language
745 public function getLanguage() {
746 return $this->getContext()->getLanguage();
750 * Shortcut to get main config object
754 public function getConfig() {
755 return $this->getContext()->getConfig();
759 * Return the full title, including $par
764 public function getFullTitle() {
765 return $this->getContext()->getTitle();
769 * Return the robot policy. Derived classes that override this can change
770 * the robot policy set by setHeaders() from the default 'noindex,nofollow'.
775 protected function getRobotPolicy() {
776 return 'noindex,nofollow';
780 * Wrapper around wfMessage that sets the current context.
786 public function msg( $key /* $args */ ) {
787 $message = $this->getContext()->msg( ...func_get_args() );
788 // RequestContext passes context to wfMessage, and the language is set from
789 // the context, but setting the language for Message class removes the
790 // interface message status, which breaks for example usernameless gender
791 // invocations. Restore the flag when not including special page in content.
792 if ( $this->including() ) {
793 $message->setInterfaceMessageFlag( false );
800 * Adds RSS/atom links
802 * @param array $params
804 protected function addFeedLinks( $params ) {
805 $feedTemplate = wfScript( 'api' );
807 foreach ( $this->getConfig()->get( 'FeedClasses' ) as $format => $class ) {
808 $theseParams = $params +
[ 'feedformat' => $format ];
809 $url = wfAppendQuery( $feedTemplate, $theseParams );
810 $this->getOutput()->addFeedLink( $format, $url );
815 * Adds help link with an icon via page indicators.
816 * Link target can be overridden by a local message containing a wikilink:
817 * the message key is: lowercase special page name + '-helppage'.
818 * @param string $to Target MediaWiki.org page title or encoded URL.
819 * @param bool $overrideBaseUrl Whether $url is a full URL, to avoid MW.o.
822 public function addHelpLink( $to, $overrideBaseUrl = false ) {
823 if ( $this->including() ) {
828 MediaWikiServices
::getInstance()->getContentLanguage()->lc( $this->getName() ) .
831 if ( !$msg->isDisabled() ) {
832 $helpUrl = Skin
::makeUrl( $msg->plain() );
833 $this->getOutput()->addHelpLink( $helpUrl, true );
835 $this->getOutput()->addHelpLink( $to, $overrideBaseUrl );
840 * Get the group that the special page belongs in on Special:SpecialPage
841 * Use this method, instead of getGroupName to allow customization
842 * of the group name from the wiki side
844 * @return string Group of this special page
847 public function getFinalGroupName() {
848 $name = $this->getName();
850 // Allow overriding the group from the wiki side
851 $msg = $this->msg( 'specialpages-specialpagegroup-' . strtolower( $name ) )->inContentLanguage();
852 if ( !$msg->isBlank() ) {
853 $group = $msg->text();
855 // Than use the group from this object
856 $group = $this->getGroupName();
863 * Indicates whether this special page may perform database writes
868 public function doesWrites() {
873 * Under which header this special page is listed in Special:SpecialPages
874 * See messages 'specialpages-group-*' for valid names
875 * This method defaults to group 'other'
880 protected function getGroupName() {
885 * Call wfTransactionalTimeLimit() if this request was POSTed
888 protected function useTransactionalTimeLimit() {
889 if ( $this->getRequest()->wasPosted() ) {
890 wfTransactionalTimeLimit();
896 * @return \MediaWiki\Linker\LinkRenderer
898 public function getLinkRenderer() {
899 if ( $this->linkRenderer
) {
900 return $this->linkRenderer
;
902 return MediaWikiServices
::getInstance()->getLinkRenderer();
908 * @param \MediaWiki\Linker\LinkRenderer $linkRenderer
910 public function setLinkRenderer( LinkRenderer
$linkRenderer ) {
911 $this->linkRenderer
= $linkRenderer;
915 * Generate (prev x| next x) (20|50|100...) type links for paging
919 * @param array $query Optional URL query parameter string
920 * @param bool $atend Optional param for specified if this is the last page
921 * @param string|bool $subpage Optional param for specifying subpage
924 protected function buildPrevNextNavigation( $offset, $limit,
925 array $query = [], $atend = false, $subpage = false
927 $title = $this->getPageTitle( $subpage );
928 $prevNext = new PrevNextNavigationRenderer( $this );
930 return $prevNext->buildPrevNextNavigation( $title, $offset, $limit, $query, $atend );