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
!= '' && !MediaWikiServices
::getInstance()
282 ->getPermissionManager()
283 ->groupHasPermission( '*', $this->mRestriction
);
287 * Checks if the given user (identified by an object) can execute this
288 * special page (as defined by $mRestriction). Can be overridden by sub-
289 * classes with more complicated permissions schemes.
291 * @param User $user The user to check
292 * @return bool Does the user have permission to view the page?
294 public function userCanExecute( User
$user ) {
295 return MediaWikiServices
::getInstance()
296 ->getPermissionManager()
297 ->userHasRight( $user, $this->mRestriction
);
301 * Output an error message telling the user what access level they have to have
302 * @throws PermissionsError
304 function displayRestrictionError() {
305 throw new PermissionsError( $this->mRestriction
);
309 * Checks if userCanExecute, and if not throws a PermissionsError
313 * @throws PermissionsError
315 public function checkPermissions() {
316 if ( !$this->userCanExecute( $this->getUser() ) ) {
317 $this->displayRestrictionError();
322 * If the wiki is currently in readonly mode, throws a ReadOnlyError
326 * @throws ReadOnlyError
328 public function checkReadOnly() {
329 if ( wfReadOnly() ) {
330 throw new ReadOnlyError
;
335 * If the user is not logged in, throws UserNotLoggedIn error
337 * The user will be redirected to Special:Userlogin with the given message as an error on
341 * @param string $reasonMsg [optional] Message key to be displayed on login page
342 * @param string $titleMsg [optional] Passed on to UserNotLoggedIn constructor
343 * @throws UserNotLoggedIn
345 public function requireLogin(
346 $reasonMsg = 'exception-nologin-text', $titleMsg = 'exception-nologin'
348 if ( $this->getUser()->isAnon() ) {
349 throw new UserNotLoggedIn( $reasonMsg, $titleMsg );
354 * Tells if the special page does something security-sensitive and needs extra defense against
355 * a stolen account (e.g. a reauthentication). What exactly that will mean is decided by the
356 * authentication framework.
357 * @return bool|string False or the argument for AuthManager::securitySensitiveOperationStatus().
358 * Typically a special page needing elevated security would return its name here.
360 protected function getLoginSecurityLevel() {
365 * Record preserved POST data after a reauthentication.
367 * This is called from checkLoginSecurityLevel() when returning from the
368 * redirect for reauthentication, if the redirect had been served in
369 * response to a POST request.
371 * The base SpecialPage implementation does nothing. If your subclass uses
372 * getLoginSecurityLevel() or checkLoginSecurityLevel(), it should probably
373 * implement this to do something with the data.
378 protected function setReauthPostData( array $data ) {
382 * Verifies that the user meets the security level, possibly reauthenticating them in the process.
384 * This should be used when the page does something security-sensitive and needs extra defense
385 * against a stolen account (e.g. a reauthentication). The authentication framework will make
386 * an extra effort to make sure the user account is not compromised. What that exactly means
387 * will depend on the system and user settings; e.g. the user might be required to log in again
388 * unless their last login happened recently, or they might be given a second-factor challenge.
390 * Calling this method will result in one if these actions:
391 * - return true: all good.
392 * - return false and set a redirect: caller should abort; the redirect will take the user
393 * to the login page for reauthentication, and back.
394 * - throw an exception if there is no way for the user to meet the requirements without using
395 * a different access method (e.g. this functionality is only available from a specific IP).
397 * Note that this does not in any way check that the user is authorized to use this special page
398 * (use checkPermissions() for that).
400 * @param string|null $level A security level. Can be an arbitrary string, defaults to the page
402 * @return bool False means a redirect to the reauthentication page has been set and processing
403 * of the special page should be aborted.
404 * @throws ErrorPageError If the security level cannot be met, even with reauthentication.
406 protected function checkLoginSecurityLevel( $level = null ) {
407 $level = $level ?
: $this->getName();
408 $key = 'SpecialPage:reauth:' . $this->getName();
409 $request = $this->getRequest();
411 $securityStatus = AuthManager
::singleton()->securitySensitiveOperationStatus( $level );
412 if ( $securityStatus === AuthManager
::SEC_OK
) {
413 $uniqueId = $request->getVal( 'postUniqueId' );
415 $key .= ':' . $uniqueId;
416 $session = $request->getSession();
417 $data = $session->getSecret( $key );
419 $session->remove( $key );
420 $this->setReauthPostData( $data );
424 } elseif ( $securityStatus === AuthManager
::SEC_REAUTH
) {
425 $title = self
::getTitleFor( 'Userlogin' );
426 $queryParams = $request->getQueryValues();
428 if ( $request->wasPosted() ) {
429 $data = array_diff_assoc( $request->getValues(), $request->getQueryValues() );
431 // unique ID in case the same special page is open in multiple browser tabs
432 $uniqueId = MWCryptRand
::generateHex( 6 );
433 $key .= ':' . $uniqueId;
434 $queryParams['postUniqueId'] = $uniqueId;
435 $session = $request->getSession();
436 $session->persist(); // Just in case
437 $session->setSecret( $key, $data );
442 'returnto' => $this->getFullTitle()->getPrefixedDBkey(),
443 'returntoquery' => wfArrayToCgi( array_diff_key( $queryParams, [ 'title' => true ] ) ),
446 $url = $title->getFullURL( $query, false, PROTO_HTTPS
);
448 $this->getOutput()->redirect( $url );
452 $titleMessage = wfMessage( 'specialpage-securitylevel-not-allowed-title' );
453 $errorMessage = wfMessage( 'specialpage-securitylevel-not-allowed' );
454 throw new ErrorPageError( $titleMessage, $errorMessage );
458 * Return an array of subpages beginning with $search that this special page will accept.
460 * For example, if a page supports subpages "foo", "bar" and "baz" (as in Special:PageName/foo,
463 * - `prefixSearchSubpages( "ba" )` should return `[ "bar", "baz" ]`
464 * - `prefixSearchSubpages( "f" )` should return `[ "foo" ]`
465 * - `prefixSearchSubpages( "z" )` should return `[]`
466 * - `prefixSearchSubpages( "" )` should return `[ foo", "bar", "baz" ]`
468 * @param string $search Prefix to search for
469 * @param int $limit Maximum number of results to return (usually 10)
470 * @param int $offset Number of results to skip (usually 0)
471 * @return string[] Matching subpages
473 public function prefixSearchSubpages( $search, $limit, $offset ) {
474 $subpages = $this->getSubpagesForPrefixSearch();
479 return self
::prefixSearchArray( $search, $limit, $subpages, $offset );
483 * Return an array of subpages that this special page will accept for prefix
484 * searches. If this method requires a query you might instead want to implement
485 * prefixSearchSubpages() directly so you can support $limit and $offset. This
486 * method is better for static-ish lists of things.
488 * @return string[] subpages to search from
490 protected function getSubpagesForPrefixSearch() {
495 * Perform a regular substring search for prefixSearchSubpages
496 * @param string $search Prefix to search for
497 * @param int $limit Maximum number of results to return (usually 10)
498 * @param int $offset Number of results to skip (usually 0)
499 * @return string[] Matching subpages
501 protected function prefixSearchString( $search, $limit, $offset ) {
502 $title = Title
::newFromText( $search );
503 if ( !$title ||
!$title->canExist() ) {
504 // No prefix suggestion in special and media namespace
508 $searchEngine = MediaWikiServices
::getInstance()->newSearchEngine();
509 $searchEngine->setLimitOffset( $limit, $offset );
510 $searchEngine->setNamespaces( [] );
511 $result = $searchEngine->defaultPrefixSearch( $search );
512 return array_map( function ( Title
$t ) {
513 return $t->getPrefixedText();
518 * Helper function for implementations of prefixSearchSubpages() that
519 * filter the values in memory (as opposed to making a query).
522 * @param string $search
524 * @param array $subpages
528 protected static function prefixSearchArray( $search, $limit, array $subpages, $offset ) {
529 $escaped = preg_quote( $search, '/' );
530 return array_slice( preg_grep( "/^$escaped/i",
531 array_slice( $subpages, $offset ) ), 0, $limit );
535 * Sets headers - this should be called from the execute() method of all derived classes!
537 function setHeaders() {
538 $out = $this->getOutput();
539 $out->setArticleRelated( false );
540 $out->setRobotPolicy( $this->getRobotPolicy() );
541 $out->setPageTitle( $this->getDescription() );
542 if ( $this->getConfig()->get( 'UseMediaWikiUIEverywhere' ) ) {
543 $out->addModuleStyles( [
544 'mediawiki.ui.input',
545 'mediawiki.ui.radio',
546 'mediawiki.ui.checkbox',
556 * @param string|null $subPage
558 final public function run( $subPage ) {
560 * Gets called before @see SpecialPage::execute.
561 * Return false to prevent calling execute() (since 1.27+).
565 * @param SpecialPage $this
566 * @param string|null $subPage
568 if ( !Hooks
::run( 'SpecialPageBeforeExecute', [ $this, $subPage ] ) ) {
572 if ( $this->beforeExecute( $subPage ) === false ) {
575 $this->execute( $subPage );
576 $this->afterExecute( $subPage );
579 * Gets called after @see SpecialPage::execute.
583 * @param SpecialPage $this
584 * @param string|null $subPage
586 Hooks
::run( 'SpecialPageAfterExecute', [ $this, $subPage ] );
590 * Gets called before @see SpecialPage::execute.
591 * Return false to prevent calling execute() (since 1.27+).
595 * @param string|null $subPage
598 protected function beforeExecute( $subPage ) {
603 * Gets called after @see SpecialPage::execute.
607 * @param string|null $subPage
609 protected function afterExecute( $subPage ) {
614 * Default execute method
615 * Checks user permissions
617 * This must be overridden by subclasses; it will be made abstract in a future version
619 * @param string|null $subPage
621 public function execute( $subPage ) {
623 $this->checkPermissions();
624 $securityLevel = $this->getLoginSecurityLevel();
625 if ( $securityLevel !== false && !$this->checkLoginSecurityLevel( $securityLevel ) ) {
628 $this->outputHeader();
632 * Outputs a summary message on top of special pages
633 * Per default the message key is the canonical name of the special page
634 * May be overridden, i.e. by extensions to stick with the naming conventions
635 * for message keys: 'extensionname-xxx'
637 * @param string $summaryMessageKey Message key of the summary
639 function outputHeader( $summaryMessageKey = '' ) {
640 if ( $summaryMessageKey == '' ) {
641 $msg = MediaWikiServices
::getInstance()->getContentLanguage()->lc( $this->getName() ) .
644 $msg = $summaryMessageKey;
646 if ( !$this->msg( $msg )->isDisabled() && !$this->including() ) {
647 $this->getOutput()->wrapWikiMsg(
648 "<div class='mw-specialpage-summary'>\n$1\n</div>", $msg );
653 * Returns the name that goes in the \<h1\> in the special page itself, and
654 * also the name that will be listed in Special:Specialpages
656 * Derived classes can override this, but usually it is easier to keep the
661 function getDescription() {
662 return $this->msg( strtolower( $this->mName
) )->text();
666 * Get a self-referential title object
668 * @param string|bool $subpage
672 function getPageTitle( $subpage = false ) {
673 return self
::getTitleFor( $this->mName
, $subpage );
677 * Sets the context this SpecialPage is executed in
679 * @param IContextSource $context
682 public function setContext( $context ) {
683 $this->mContext
= $context;
687 * Gets the context this SpecialPage is executed in
689 * @return IContextSource|RequestContext
692 public function getContext() {
693 if ( $this->mContext
instanceof IContextSource
) {
694 return $this->mContext
;
696 wfDebug( __METHOD__
. " called and \$mContext is null. " .
697 "Return RequestContext::getMain(); for sanity\n" );
699 return RequestContext
::getMain();
704 * Get the WebRequest being used for this instance
709 public function getRequest() {
710 return $this->getContext()->getRequest();
714 * Get the OutputPage being used for this instance
719 public function getOutput() {
720 return $this->getContext()->getOutput();
724 * Shortcut to get the User executing this instance
729 public function getUser() {
730 return $this->getContext()->getUser();
734 * Shortcut to get the skin being used for this instance
739 public function getSkin() {
740 return $this->getContext()->getSkin();
744 * Shortcut to get user's language
749 public function getLanguage() {
750 return $this->getContext()->getLanguage();
754 * Shortcut to get main config object
758 public function getConfig() {
759 return $this->getContext()->getConfig();
763 * Return the full title, including $par
768 public function getFullTitle() {
769 return $this->getContext()->getTitle();
773 * Return the robot policy. Derived classes that override this can change
774 * the robot policy set by setHeaders() from the default 'noindex,nofollow'.
779 protected function getRobotPolicy() {
780 return 'noindex,nofollow';
784 * Wrapper around wfMessage that sets the current context.
790 public function msg( $key /* $args */ ) {
791 $message = $this->getContext()->msg( ...func_get_args() );
792 // RequestContext passes context to wfMessage, and the language is set from
793 // the context, but setting the language for Message class removes the
794 // interface message status, which breaks for example usernameless gender
795 // invocations. Restore the flag when not including special page in content.
796 if ( $this->including() ) {
797 $message->setInterfaceMessageFlag( false );
804 * Adds RSS/atom links
806 * @param array $params
808 protected function addFeedLinks( $params ) {
809 $feedTemplate = wfScript( 'api' );
811 foreach ( $this->getConfig()->get( 'FeedClasses' ) as $format => $class ) {
812 $theseParams = $params +
[ 'feedformat' => $format ];
813 $url = wfAppendQuery( $feedTemplate, $theseParams );
814 $this->getOutput()->addFeedLink( $format, $url );
819 * Adds help link with an icon via page indicators.
820 * Link target can be overridden by a local message containing a wikilink:
821 * the message key is: lowercase special page name + '-helppage'.
822 * @param string $to Target MediaWiki.org page title or encoded URL.
823 * @param bool $overrideBaseUrl Whether $url is a full URL, to avoid MW.o.
826 public function addHelpLink( $to, $overrideBaseUrl = false ) {
827 if ( $this->including() ) {
832 MediaWikiServices
::getInstance()->getContentLanguage()->lc( $this->getName() ) .
835 if ( !$msg->isDisabled() ) {
836 $helpUrl = Skin
::makeUrl( $msg->plain() );
837 $this->getOutput()->addHelpLink( $helpUrl, true );
839 $this->getOutput()->addHelpLink( $to, $overrideBaseUrl );
844 * Get the group that the special page belongs in on Special:SpecialPage
845 * Use this method, instead of getGroupName to allow customization
846 * of the group name from the wiki side
848 * @return string Group of this special page
851 public function getFinalGroupName() {
852 $name = $this->getName();
854 // Allow overriding the group from the wiki side
855 $msg = $this->msg( 'specialpages-specialpagegroup-' . strtolower( $name ) )->inContentLanguage();
856 if ( !$msg->isBlank() ) {
857 $group = $msg->text();
859 // Than use the group from this object
860 $group = $this->getGroupName();
867 * Indicates whether this special page may perform database writes
872 public function doesWrites() {
877 * Under which header this special page is listed in Special:SpecialPages
878 * See messages 'specialpages-group-*' for valid names
879 * This method defaults to group 'other'
884 protected function getGroupName() {
889 * Call wfTransactionalTimeLimit() if this request was POSTed
892 protected function useTransactionalTimeLimit() {
893 if ( $this->getRequest()->wasPosted() ) {
894 wfTransactionalTimeLimit();
900 * @return \MediaWiki\Linker\LinkRenderer
902 public function getLinkRenderer() {
903 if ( $this->linkRenderer
) {
904 return $this->linkRenderer
;
906 return MediaWikiServices
::getInstance()->getLinkRenderer();
912 * @param \MediaWiki\Linker\LinkRenderer $linkRenderer
914 public function setLinkRenderer( LinkRenderer
$linkRenderer ) {
915 $this->linkRenderer
= $linkRenderer;
919 * Generate (prev x| next x) (20|50|100...) type links for paging
923 * @param array $query Optional URL query parameter string
924 * @param bool $atend Optional param for specified if this is the last page
925 * @param string|bool $subpage Optional param for specifying subpage
928 protected function buildPrevNextNavigation( $offset, $limit,
929 array $query = [], $atend = false, $subpage = false
931 $title = $this->getPageTitle( $subpage );
932 $prevNext = new PrevNextNavigationRenderer( $this );
934 return $prevNext->buildPrevNextNavigation( $title, $offset, $limit, $query, $atend );