2 use MediaWiki\MediaWikiServices
;
5 * Parent class for all special pages.
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * http://www.gnu.org/copyleft/gpl.html
23 * @ingroup SpecialPage
26 use MediaWiki\Auth\AuthManager
;
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
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 * Get a localised Title object for a specified special page name
67 * @since 1.21 $fragment parameter added
70 * @param string|bool $subpage Subpage string, or false to not use a subpage
71 * @param string $fragment The link fragment (after the "#")
75 public static function getTitleFor( $name, $subpage = false, $fragment = '' ) {
76 $name = SpecialPageFactory
::getLocalNameFor( $name, $subpage );
78 return Title
::makeTitle( NS_SPECIAL
, $name, $fragment );
82 * Get a localised Title object for a page name with a possibly unvalidated subpage
85 * @param string|bool $subpage Subpage string, or false to not use a subpage
86 * @return Title|null Title object or null if the page doesn't exist
88 public static function getSafeTitleFor( $name, $subpage = false ) {
89 $name = SpecialPageFactory
::getLocalNameFor( $name, $subpage );
91 return Title
::makeTitleSafe( NS_SPECIAL
, $name );
98 * Default constructor for special pages
99 * Derivative classes should call this from their constructor
100 * Note that if the user does not have the required level, an error message will
101 * be displayed by the default execute() method, without the global function ever
104 * If you override execute(), you can recover the default behavior with userCanExecute()
105 * and displayRestrictionError()
107 * @param string $name Name of the special page, as seen in links and URLs
108 * @param string $restriction User right required, e.g. "block" or "delete"
109 * @param bool $listed Whether the page is listed in Special:Specialpages
110 * @param callable|bool $function Unused
111 * @param string $file Unused
112 * @param bool $includable Whether the page can be included in normal pages
114 public function __construct(
115 $name = '', $restriction = '', $listed = true,
116 $function = false, $file = '', $includable = false
118 $this->mName
= $name;
119 $this->mRestriction
= $restriction;
120 $this->mListed
= $listed;
121 $this->mIncludable
= $includable;
125 * Get the name of this Special Page.
133 * Get the permission that a user must have to execute this page
136 function getRestriction() {
137 return $this->mRestriction
;
140 // @todo FIXME: Decide which syntax to use for this, and stick to it
142 * Whether this special page is listed in Special:SpecialPages
146 function isListed() {
147 return $this->mListed
;
151 * Set whether this page is listed in Special:Specialpages, at run-time
153 * @param bool $listed
156 function setListed( $listed ) {
157 return wfSetVar( $this->mListed
, $listed );
161 * Get or set whether this special page is listed in Special:SpecialPages
166 function listed( $x = null ) {
167 return wfSetVar( $this->mListed
, $x );
171 * Whether it's allowed to transclude the special page via {{Special:Foo/params}}
174 public function isIncludable() {
175 return $this->mIncludable
;
179 * How long to cache page when it is being included.
181 * @note If cache time is not 0, then the current user becomes an anon
182 * if you want to do any per-user customizations, than this method
183 * must be overriden to return 0.
185 * @return int Time in seconds, 0 to disable caching altogether,
186 * false to use the parent page's cache settings
188 public function maxIncludeCacheTime() {
190 if ( !$wgMiserMode ) {
198 * Whether the special page is being evaluated via transclusion
202 function including( $x = null ) {
203 return wfSetVar( $this->mIncluding
, $x );
207 * Get the localised name of the special page
210 function getLocalName() {
211 if ( !isset( $this->mLocalName
) ) {
212 $this->mLocalName
= SpecialPageFactory
::getLocalNameFor( $this->mName
);
215 return $this->mLocalName
;
219 * Is this page expensive (for some definition of expensive)?
220 * Expensive pages are disabled or cached in miser mode. Originally used
221 * (and still overridden) by QueryPage and subclasses, moved here so that
222 * Special:SpecialPages can safely call it for all special pages.
226 public function isExpensive() {
231 * Is this page cached?
232 * Expensive pages are cached or disabled in miser mode.
233 * Used by QueryPage and subclasses, moved here so that
234 * Special:SpecialPages can safely call it for all special pages.
239 public function isCached() {
244 * Can be overridden by subclasses with more complicated permissions
247 * @return bool Should the page be displayed with the restricted-access
250 public function isRestricted() {
251 // DWIM: If anons can do something, then it is not restricted
252 return $this->mRestriction
!= '' && !User
::groupHasPermission( '*', $this->mRestriction
);
256 * Checks if the given user (identified by an object) can execute this
257 * special page (as defined by $mRestriction). Can be overridden by sub-
258 * classes with more complicated permissions schemes.
260 * @param User $user The user to check
261 * @return bool Does the user have permission to view the page?
263 public function userCanExecute( User
$user ) {
264 return $user->isAllowed( $this->mRestriction
);
268 * Output an error message telling the user what access level they have to have
269 * @throws PermissionsError
271 function displayRestrictionError() {
272 throw new PermissionsError( $this->mRestriction
);
276 * Checks if userCanExecute, and if not throws a PermissionsError
280 * @throws PermissionsError
282 public function checkPermissions() {
283 if ( !$this->userCanExecute( $this->getUser() ) ) {
284 $this->displayRestrictionError();
289 * If the wiki is currently in readonly mode, throws a ReadOnlyError
293 * @throws ReadOnlyError
295 public function checkReadOnly() {
296 if ( wfReadOnly() ) {
297 throw new ReadOnlyError
;
302 * If the user is not logged in, throws UserNotLoggedIn error
304 * The user will be redirected to Special:Userlogin with the given message as an error on
308 * @param string $reasonMsg [optional] Message key to be displayed on login page
309 * @param string $titleMsg [optional] Passed on to UserNotLoggedIn constructor
310 * @throws UserNotLoggedIn
312 public function requireLogin(
313 $reasonMsg = 'exception-nologin-text', $titleMsg = 'exception-nologin'
315 if ( $this->getUser()->isAnon() ) {
316 throw new UserNotLoggedIn( $reasonMsg, $titleMsg );
321 * Tells if the special page does something security-sensitive and needs extra defense against
322 * a stolen account (e.g. a reauthentication). What exactly that will mean is decided by the
323 * authentication framework.
324 * @return bool|string False or the argument for AuthManager::securitySensitiveOperationStatus().
325 * Typically a special page needing elevated security would return its name here.
327 protected function getLoginSecurityLevel() {
332 * Verifies that the user meets the security level, possibly reauthenticating them in the process.
334 * This should be used when the page does something security-sensitive and needs extra defense
335 * against a stolen account (e.g. a reauthentication). The authentication framework will make
336 * an extra effort to make sure the user account is not compromised. What that exactly means
337 * will depend on the system and user settings; e.g. the user might be required to log in again
338 * unless their last login happened recently, or they might be given a second-factor challenge.
340 * Calling this method will result in one if these actions:
341 * - return true: all good.
342 * - return false and set a redirect: caller should abort; the redirect will take the user
343 * to the login page for reauthentication, and back.
344 * - throw an exception if there is no way for the user to meet the requirements without using
345 * a different access method (e.g. this functionality is only available from a specific IP).
347 * Note that this does not in any way check that the user is authorized to use this special page
348 * (use checkPermissions() for that).
350 * @param string $level A security level. Can be an arbitrary string, defaults to the page name.
351 * @return bool False means a redirect to the reauthentication page has been set and processing
352 * of the special page should be aborted.
353 * @throws ErrorPageError If the security level cannot be met, even with reauthentication.
355 protected function checkLoginSecurityLevel( $level = null ) {
356 $level = $level ?
: $this->getName();
357 $securityStatus = AuthManager
::singleton()->securitySensitiveOperationStatus( $level );
358 if ( $securityStatus === AuthManager
::SEC_OK
) {
360 } elseif ( $securityStatus === AuthManager
::SEC_REAUTH
) {
361 $request = $this->getRequest();
362 $title = SpecialPage
::getTitleFor( 'Userlogin' );
364 'returnto' => $this->getFullTitle()->getPrefixedDBkey(),
365 'returntoquery' => wfArrayToCgi( array_diff_key( $request->getQueryValues(),
366 [ 'title' => true ] ) ),
369 $url = $title->getFullURL( $query, false, PROTO_HTTPS
);
371 $this->getOutput()->redirect( $url );
375 $titleMessage = wfMessage( 'specialpage-securitylevel-not-allowed-title' );
376 $errorMessage = wfMessage( 'specialpage-securitylevel-not-allowed' );
377 throw new ErrorPageError( $titleMessage, $errorMessage );
381 * Return an array of subpages beginning with $search that this special page will accept.
383 * For example, if a page supports subpages "foo", "bar" and "baz" (as in Special:PageName/foo,
386 * - `prefixSearchSubpages( "ba" )` should return `array( "bar", "baz" )`
387 * - `prefixSearchSubpages( "f" )` should return `array( "foo" )`
388 * - `prefixSearchSubpages( "z" )` should return `array()`
389 * - `prefixSearchSubpages( "" )` should return `array( foo", "bar", "baz" )`
391 * @param string $search Prefix to search for
392 * @param int $limit Maximum number of results to return (usually 10)
393 * @param int $offset Number of results to skip (usually 0)
394 * @return string[] Matching subpages
396 public function prefixSearchSubpages( $search, $limit, $offset ) {
397 $subpages = $this->getSubpagesForPrefixSearch();
402 return self
::prefixSearchArray( $search, $limit, $subpages, $offset );
406 * Return an array of subpages that this special page will accept for prefix
407 * searches. If this method requires a query you might instead want to implement
408 * prefixSearchSubpages() directly so you can support $limit and $offset. This
409 * method is better for static-ish lists of things.
411 * @return string[] subpages to search from
413 protected function getSubpagesForPrefixSearch() {
418 * Perform a regular substring search for prefixSearchSubpages
419 * @param string $search Prefix to search for
420 * @param int $limit Maximum number of results to return (usually 10)
421 * @param int $offset Number of results to skip (usually 0)
422 * @return string[] Matching subpages
424 protected function prefixSearchString( $search, $limit, $offset ) {
425 $title = Title
::newFromText( $search );
426 if ( !$title ||
!$title->canExist() ) {
427 // No prefix suggestion in special and media namespace
431 $searchEngine = MediaWikiServices
::getInstance()->newSearchEngine();
432 $searchEngine->setLimitOffset( $limit, $offset );
433 $searchEngine->setNamespaces( [] );
434 $result = $searchEngine->defaultPrefixSearch( $search );
435 return array_map( function( Title
$t ) {
436 return $t->getPrefixedText();
441 * Helper function for implementations of prefixSearchSubpages() that
442 * filter the values in memory (as opposed to making a query).
445 * @param string $search
447 * @param array $subpages
451 protected static function prefixSearchArray( $search, $limit, array $subpages, $offset ) {
452 $escaped = preg_quote( $search, '/' );
453 return array_slice( preg_grep( "/^$escaped/i",
454 array_slice( $subpages, $offset ) ), 0, $limit );
458 * Sets headers - this should be called from the execute() method of all derived classes!
460 function setHeaders() {
461 $out = $this->getOutput();
462 $out->setArticleRelated( false );
463 $out->setRobotPolicy( $this->getRobotPolicy() );
464 $out->setPageTitle( $this->getDescription() );
465 if ( $this->getConfig()->get( 'UseMediaWikiUIEverywhere' ) ) {
466 $out->addModuleStyles( [
467 'mediawiki.ui.input',
468 'mediawiki.ui.radio',
469 'mediawiki.ui.checkbox',
479 * @param string|null $subPage
481 final public function run( $subPage ) {
483 * Gets called before @see SpecialPage::execute.
484 * Return false to prevent calling execute() (since 1.27+).
488 * @param SpecialPage $this
489 * @param string|null $subPage
491 if ( !Hooks
::run( 'SpecialPageBeforeExecute', [ $this, $subPage ] ) ) {
495 if ( $this->beforeExecute( $subPage ) === false ) {
498 $this->execute( $subPage );
499 $this->afterExecute( $subPage );
502 * Gets called after @see SpecialPage::execute.
506 * @param SpecialPage $this
507 * @param string|null $subPage
509 Hooks
::run( 'SpecialPageAfterExecute', [ $this, $subPage ] );
513 * Gets called before @see SpecialPage::execute.
514 * Return false to prevent calling execute() (since 1.27+).
518 * @param string|null $subPage
521 protected function beforeExecute( $subPage ) {
526 * Gets called after @see SpecialPage::execute.
530 * @param string|null $subPage
532 protected function afterExecute( $subPage ) {
537 * Default execute method
538 * Checks user permissions
540 * This must be overridden by subclasses; it will be made abstract in a future version
542 * @param string|null $subPage
544 public function execute( $subPage ) {
546 $this->checkPermissions();
547 $this->checkLoginSecurityLevel( $this->getLoginSecurityLevel() );
548 $this->outputHeader();
552 * Outputs a summary message on top of special pages
553 * Per default the message key is the canonical name of the special page
554 * May be overridden, i.e. by extensions to stick with the naming conventions
555 * for message keys: 'extensionname-xxx'
557 * @param string $summaryMessageKey Message key of the summary
559 function outputHeader( $summaryMessageKey = '' ) {
562 if ( $summaryMessageKey == '' ) {
563 $msg = $wgContLang->lc( $this->getName() ) . '-summary';
565 $msg = $summaryMessageKey;
567 if ( !$this->msg( $msg )->isDisabled() && !$this->including() ) {
568 $this->getOutput()->wrapWikiMsg(
569 "<div class='mw-specialpage-summary'>\n$1\n</div>", $msg );
574 * Returns the name that goes in the \<h1\> in the special page itself, and
575 * also the name that will be listed in Special:Specialpages
577 * Derived classes can override this, but usually it is easier to keep the
582 function getDescription() {
583 return $this->msg( strtolower( $this->mName
) )->text();
587 * Get a self-referential title object
589 * @param string|bool $subpage
591 * @deprecated since 1.23, use SpecialPage::getPageTitle
593 function getTitle( $subpage = false ) {
594 return $this->getPageTitle( $subpage );
598 * Get a self-referential title object
600 * @param string|bool $subpage
604 function getPageTitle( $subpage = false ) {
605 return self
::getTitleFor( $this->mName
, $subpage );
609 * Sets the context this SpecialPage is executed in
611 * @param IContextSource $context
614 public function setContext( $context ) {
615 $this->mContext
= $context;
619 * Gets the context this SpecialPage is executed in
621 * @return IContextSource|RequestContext
624 public function getContext() {
625 if ( $this->mContext
instanceof IContextSource
) {
626 return $this->mContext
;
628 wfDebug( __METHOD__
. " called and \$mContext is null. " .
629 "Return RequestContext::getMain(); for sanity\n" );
631 return RequestContext
::getMain();
636 * Get the WebRequest being used for this instance
641 public function getRequest() {
642 return $this->getContext()->getRequest();
646 * Get the OutputPage being used for this instance
651 public function getOutput() {
652 return $this->getContext()->getOutput();
656 * Shortcut to get the User executing this instance
661 public function getUser() {
662 return $this->getContext()->getUser();
666 * Shortcut to get the skin being used for this instance
671 public function getSkin() {
672 return $this->getContext()->getSkin();
676 * Shortcut to get user's language
681 public function getLanguage() {
682 return $this->getContext()->getLanguage();
686 * Shortcut to get main config object
690 public function getConfig() {
691 return $this->getContext()->getConfig();
695 * Return the full title, including $par
700 public function getFullTitle() {
701 return $this->getContext()->getTitle();
705 * Return the robot policy. Derived classes that override this can change
706 * the robot policy set by setHeaders() from the default 'noindex,nofollow'.
711 protected function getRobotPolicy() {
712 return 'noindex,nofollow';
716 * Wrapper around wfMessage that sets the current context.
722 public function msg( /* $args */ ) {
723 $message = call_user_func_array(
724 [ $this->getContext(), 'msg' ],
727 // RequestContext passes context to wfMessage, and the language is set from
728 // the context, but setting the language for Message class removes the
729 // interface message status, which breaks for example usernameless gender
730 // invocations. Restore the flag when not including special page in content.
731 if ( $this->including() ) {
732 $message->setInterfaceMessageFlag( false );
739 * Adds RSS/atom links
741 * @param array $params
743 protected function addFeedLinks( $params ) {
744 $feedTemplate = wfScript( 'api' );
746 foreach ( $this->getConfig()->get( 'FeedClasses' ) as $format => $class ) {
747 $theseParams = $params +
[ 'feedformat' => $format ];
748 $url = wfAppendQuery( $feedTemplate, $theseParams );
749 $this->getOutput()->addFeedLink( $format, $url );
754 * Adds help link with an icon via page indicators.
755 * Link target can be overridden by a local message containing a wikilink:
756 * the message key is: lowercase special page name + '-helppage'.
757 * @param string $to Target MediaWiki.org page title or encoded URL.
758 * @param bool $overrideBaseUrl Whether $url is a full URL, to avoid MW.o.
761 public function addHelpLink( $to, $overrideBaseUrl = false ) {
763 $msg = $this->msg( $wgContLang->lc( $this->getName() ) . '-helppage' );
765 if ( !$msg->isDisabled() ) {
766 $helpUrl = Skin
::makeUrl( $msg->plain() );
767 $this->getOutput()->addHelpLink( $helpUrl, true );
769 $this->getOutput()->addHelpLink( $to, $overrideBaseUrl );
774 * Get the group that the special page belongs in on Special:SpecialPage
775 * Use this method, instead of getGroupName to allow customization
776 * of the group name from the wiki side
778 * @return string Group of this special page
781 public function getFinalGroupName() {
782 $name = $this->getName();
784 // Allow overbidding the group from the wiki side
785 $msg = $this->msg( 'specialpages-specialpagegroup-' . strtolower( $name ) )->inContentLanguage();
786 if ( !$msg->isBlank() ) {
787 $group = $msg->text();
789 // Than use the group from this object
790 $group = $this->getGroupName();
797 * Indicates whether this special page may perform database writes
802 public function doesWrites() {
807 * Under which header this special page is listed in Special:SpecialPages
808 * See messages 'specialpages-group-*' for valid names
809 * This method defaults to group 'other'
814 protected function getGroupName() {
819 * Call wfTransactionalTimeLimit() if this request was POSTed
822 protected function useTransactionalTimeLimit() {
823 if ( $this->getRequest()->wasPosted() ) {
824 wfTransactionalTimeLimit();