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 * Whether the special page is being evaluated via transclusion
183 function including( $x = null ) {
184 return wfSetVar( $this->mIncluding
, $x );
188 * Get the localised name of the special page
191 function getLocalName() {
192 if ( !isset( $this->mLocalName
) ) {
193 $this->mLocalName
= SpecialPageFactory
::getLocalNameFor( $this->mName
);
196 return $this->mLocalName
;
200 * Is this page expensive (for some definition of expensive)?
201 * Expensive pages are disabled or cached in miser mode. Originally used
202 * (and still overridden) by QueryPage and subclasses, moved here so that
203 * Special:SpecialPages can safely call it for all special pages.
207 public function isExpensive() {
212 * Is this page cached?
213 * Expensive pages are cached or disabled in miser mode.
214 * Used by QueryPage and subclasses, moved here so that
215 * Special:SpecialPages can safely call it for all special pages.
220 public function isCached() {
225 * Can be overridden by subclasses with more complicated permissions
228 * @return bool Should the page be displayed with the restricted-access
231 public function isRestricted() {
232 // DWIM: If anons can do something, then it is not restricted
233 return $this->mRestriction
!= '' && !User
::groupHasPermission( '*', $this->mRestriction
);
237 * Checks if the given user (identified by an object) can execute this
238 * special page (as defined by $mRestriction). Can be overridden by sub-
239 * classes with more complicated permissions schemes.
241 * @param User $user The user to check
242 * @return bool Does the user have permission to view the page?
244 public function userCanExecute( User
$user ) {
245 return $user->isAllowed( $this->mRestriction
);
249 * Output an error message telling the user what access level they have to have
250 * @throws PermissionsError
252 function displayRestrictionError() {
253 throw new PermissionsError( $this->mRestriction
);
257 * Checks if userCanExecute, and if not throws a PermissionsError
261 * @throws PermissionsError
263 public function checkPermissions() {
264 if ( !$this->userCanExecute( $this->getUser() ) ) {
265 $this->displayRestrictionError();
270 * If the wiki is currently in readonly mode, throws a ReadOnlyError
274 * @throws ReadOnlyError
276 public function checkReadOnly() {
277 if ( wfReadOnly() ) {
278 throw new ReadOnlyError
;
283 * If the user is not logged in, throws UserNotLoggedIn error
285 * The user will be redirected to Special:Userlogin with the given message as an error on
289 * @param string $reasonMsg [optional] Message key to be displayed on login page
290 * @param string $titleMsg [optional] Passed on to UserNotLoggedIn constructor
291 * @throws UserNotLoggedIn
293 public function requireLogin(
294 $reasonMsg = 'exception-nologin-text', $titleMsg = 'exception-nologin'
296 if ( $this->getUser()->isAnon() ) {
297 throw new UserNotLoggedIn( $reasonMsg, $titleMsg );
302 * Tells if the special page does something security-sensitive and needs extra defense against
303 * a stolen account (e.g. a reauthentication). What exactly that will mean is decided by the
304 * authentication framework.
305 * @return bool|string False or the argument for AuthManager::securitySensitiveOperationStatus().
306 * Typically a special page needing elevated security would return its name here.
308 protected function getLoginSecurityLevel() {
313 * Verifies that the user meets the security level, possibly reauthenticating them in the process.
315 * This should be used when the page does something security-sensitive and needs extra defense
316 * against a stolen account (e.g. a reauthentication). The authentication framework will make
317 * an extra effort to make sure the user account is not compromised. What that exactly means
318 * will depend on the system and user settings; e.g. the user might be required to log in again
319 * unless their last login happened recently, or they might be given a second-factor challenge.
321 * Calling this method will result in one if these actions:
322 * - return true: all good.
323 * - return false and set a redirect: caller should abort; the redirect will take the user
324 * to the login page for reauthentication, and back.
325 * - throw an exception if there is no way for the user to meet the requirements without using
326 * a different access method (e.g. this functionality is only available from a specific IP).
328 * Note that this does not in any way check that the user is authorized to use this special page
329 * (use checkPermissions() for that).
331 * @param string $level A security level. Can be an arbitrary string, defaults to the page name.
332 * @return bool False means a redirect to the reauthentication page has been set and processing
333 * of the special page should be aborted.
334 * @throws ErrorPageError If the security level cannot be met, even with reauthentication.
336 protected function checkLoginSecurityLevel( $level = null ) {
337 $level = $level ?
: $this->getName();
338 $securityStatus = AuthManager
::singleton()->securitySensitiveOperationStatus( $level );
339 if ( $securityStatus === AuthManager
::SEC_OK
) {
341 } elseif ( $securityStatus === AuthManager
::SEC_REAUTH
) {
342 $request = $this->getRequest();
343 $title = SpecialPage
::getTitleFor( 'Userlogin' );
345 'returnto' => $this->getFullTitle()->getPrefixedDBkey(),
346 'returntoquery' => wfArrayToCgi( array_diff_key( $request->getQueryValues(),
347 [ 'title' => true ] ) ),
350 $url = $title->getFullURL( $query, false, PROTO_HTTPS
);
352 $this->getOutput()->redirect( $url );
356 $titleMessage = wfMessage( 'specialpage-securitylevel-not-allowed-title' );
357 $errorMessage = wfMessage( 'specialpage-securitylevel-not-allowed' );
358 throw new ErrorPageError( $titleMessage, $errorMessage );
362 * Return an array of subpages beginning with $search that this special page will accept.
364 * For example, if a page supports subpages "foo", "bar" and "baz" (as in Special:PageName/foo,
367 * - `prefixSearchSubpages( "ba" )` should return `array( "bar", "baz" )`
368 * - `prefixSearchSubpages( "f" )` should return `array( "foo" )`
369 * - `prefixSearchSubpages( "z" )` should return `array()`
370 * - `prefixSearchSubpages( "" )` should return `array( foo", "bar", "baz" )`
372 * @param string $search Prefix to search for
373 * @param int $limit Maximum number of results to return (usually 10)
374 * @param int $offset Number of results to skip (usually 0)
375 * @return string[] Matching subpages
377 public function prefixSearchSubpages( $search, $limit, $offset ) {
378 $subpages = $this->getSubpagesForPrefixSearch();
383 return self
::prefixSearchArray( $search, $limit, $subpages, $offset );
387 * Return an array of subpages that this special page will accept for prefix
388 * searches. If this method requires a query you might instead want to implement
389 * prefixSearchSubpages() directly so you can support $limit and $offset. This
390 * method is better for static-ish lists of things.
392 * @return string[] subpages to search from
394 protected function getSubpagesForPrefixSearch() {
399 * Perform a regular substring search for prefixSearchSubpages
400 * @param string $search Prefix to search for
401 * @param int $limit Maximum number of results to return (usually 10)
402 * @param int $offset Number of results to skip (usually 0)
403 * @return string[] Matching subpages
405 protected function prefixSearchString( $search, $limit, $offset ) {
406 $title = Title
::newFromText( $search );
407 if ( !$title ||
!$title->canExist() ) {
408 // No prefix suggestion in special and media namespace
412 $searchEngine = MediaWikiServices
::getInstance()->newSearchEngine();
413 $searchEngine->setLimitOffset( $limit, $offset );
414 $searchEngine->setNamespaces( [] );
415 $result = $searchEngine->defaultPrefixSearch( $search );
416 return array_map( function( Title
$t ) {
417 return $t->getPrefixedText();
422 * Helper function for implementations of prefixSearchSubpages() that
423 * filter the values in memory (as opposed to making a query).
426 * @param string $search
428 * @param array $subpages
432 protected static function prefixSearchArray( $search, $limit, array $subpages, $offset ) {
433 $escaped = preg_quote( $search, '/' );
434 return array_slice( preg_grep( "/^$escaped/i",
435 array_slice( $subpages, $offset ) ), 0, $limit );
439 * Sets headers - this should be called from the execute() method of all derived classes!
441 function setHeaders() {
442 $out = $this->getOutput();
443 $out->setArticleRelated( false );
444 $out->setRobotPolicy( $this->getRobotPolicy() );
445 $out->setPageTitle( $this->getDescription() );
446 if ( $this->getConfig()->get( 'UseMediaWikiUIEverywhere' ) ) {
447 $out->addModuleStyles( [
448 'mediawiki.ui.input',
449 'mediawiki.ui.radio',
450 'mediawiki.ui.checkbox',
460 * @param string|null $subPage
462 final public function run( $subPage ) {
464 * Gets called before @see SpecialPage::execute.
465 * Return false to prevent calling execute() (since 1.27+).
469 * @param SpecialPage $this
470 * @param string|null $subPage
472 if ( !Hooks
::run( 'SpecialPageBeforeExecute', [ $this, $subPage ] ) ) {
476 if ( $this->beforeExecute( $subPage ) === false ) {
479 $this->execute( $subPage );
480 $this->afterExecute( $subPage );
483 * Gets called after @see SpecialPage::execute.
487 * @param SpecialPage $this
488 * @param string|null $subPage
490 Hooks
::run( 'SpecialPageAfterExecute', [ $this, $subPage ] );
494 * Gets called before @see SpecialPage::execute.
495 * Return false to prevent calling execute() (since 1.27+).
499 * @param string|null $subPage
502 protected function beforeExecute( $subPage ) {
507 * Gets called after @see SpecialPage::execute.
511 * @param string|null $subPage
513 protected function afterExecute( $subPage ) {
518 * Default execute method
519 * Checks user permissions
521 * This must be overridden by subclasses; it will be made abstract in a future version
523 * @param string|null $subPage
525 public function execute( $subPage ) {
527 $this->checkPermissions();
528 $this->checkLoginSecurityLevel( $this->getLoginSecurityLevel() );
529 $this->outputHeader();
533 * Outputs a summary message on top of special pages
534 * Per default the message key is the canonical name of the special page
535 * May be overridden, i.e. by extensions to stick with the naming conventions
536 * for message keys: 'extensionname-xxx'
538 * @param string $summaryMessageKey Message key of the summary
540 function outputHeader( $summaryMessageKey = '' ) {
543 if ( $summaryMessageKey == '' ) {
544 $msg = $wgContLang->lc( $this->getName() ) . '-summary';
546 $msg = $summaryMessageKey;
548 if ( !$this->msg( $msg )->isDisabled() && !$this->including() ) {
549 $this->getOutput()->wrapWikiMsg(
550 "<div class='mw-specialpage-summary'>\n$1\n</div>", $msg );
555 * Returns the name that goes in the \<h1\> in the special page itself, and
556 * also the name that will be listed in Special:Specialpages
558 * Derived classes can override this, but usually it is easier to keep the
563 function getDescription() {
564 return $this->msg( strtolower( $this->mName
) )->text();
568 * Get a self-referential title object
570 * @param string|bool $subpage
572 * @deprecated since 1.23, use SpecialPage::getPageTitle
574 function getTitle( $subpage = false ) {
575 return $this->getPageTitle( $subpage );
579 * Get a self-referential title object
581 * @param string|bool $subpage
585 function getPageTitle( $subpage = false ) {
586 return self
::getTitleFor( $this->mName
, $subpage );
590 * Sets the context this SpecialPage is executed in
592 * @param IContextSource $context
595 public function setContext( $context ) {
596 $this->mContext
= $context;
600 * Gets the context this SpecialPage is executed in
602 * @return IContextSource|RequestContext
605 public function getContext() {
606 if ( $this->mContext
instanceof IContextSource
) {
607 return $this->mContext
;
609 wfDebug( __METHOD__
. " called and \$mContext is null. " .
610 "Return RequestContext::getMain(); for sanity\n" );
612 return RequestContext
::getMain();
617 * Get the WebRequest being used for this instance
622 public function getRequest() {
623 return $this->getContext()->getRequest();
627 * Get the OutputPage being used for this instance
632 public function getOutput() {
633 return $this->getContext()->getOutput();
637 * Shortcut to get the User executing this instance
642 public function getUser() {
643 return $this->getContext()->getUser();
647 * Shortcut to get the skin being used for this instance
652 public function getSkin() {
653 return $this->getContext()->getSkin();
657 * Shortcut to get user's language
662 public function getLanguage() {
663 return $this->getContext()->getLanguage();
667 * Shortcut to get main config object
671 public function getConfig() {
672 return $this->getContext()->getConfig();
676 * Return the full title, including $par
681 public function getFullTitle() {
682 return $this->getContext()->getTitle();
686 * Return the robot policy. Derived classes that override this can change
687 * the robot policy set by setHeaders() from the default 'noindex,nofollow'.
692 protected function getRobotPolicy() {
693 return 'noindex,nofollow';
697 * Wrapper around wfMessage that sets the current context.
703 public function msg( /* $args */ ) {
704 $message = call_user_func_array(
705 [ $this->getContext(), 'msg' ],
708 // RequestContext passes context to wfMessage, and the language is set from
709 // the context, but setting the language for Message class removes the
710 // interface message status, which breaks for example usernameless gender
711 // invocations. Restore the flag when not including special page in content.
712 if ( $this->including() ) {
713 $message->setInterfaceMessageFlag( false );
720 * Adds RSS/atom links
722 * @param array $params
724 protected function addFeedLinks( $params ) {
725 $feedTemplate = wfScript( 'api' );
727 foreach ( $this->getConfig()->get( 'FeedClasses' ) as $format => $class ) {
728 $theseParams = $params +
[ 'feedformat' => $format ];
729 $url = wfAppendQuery( $feedTemplate, $theseParams );
730 $this->getOutput()->addFeedLink( $format, $url );
735 * Adds help link with an icon via page indicators.
736 * Link target can be overridden by a local message containing a wikilink:
737 * the message key is: lowercase special page name + '-helppage'.
738 * @param string $to Target MediaWiki.org page title or encoded URL.
739 * @param bool $overrideBaseUrl Whether $url is a full URL, to avoid MW.o.
742 public function addHelpLink( $to, $overrideBaseUrl = false ) {
744 $msg = $this->msg( $wgContLang->lc( $this->getName() ) . '-helppage' );
746 if ( !$msg->isDisabled() ) {
747 $helpUrl = Skin
::makeUrl( $msg->plain() );
748 $this->getOutput()->addHelpLink( $helpUrl, true );
750 $this->getOutput()->addHelpLink( $to, $overrideBaseUrl );
755 * Get the group that the special page belongs in on Special:SpecialPage
756 * Use this method, instead of getGroupName to allow customization
757 * of the group name from the wiki side
759 * @return string Group of this special page
762 public function getFinalGroupName() {
763 $name = $this->getName();
765 // Allow overbidding the group from the wiki side
766 $msg = $this->msg( 'specialpages-specialpagegroup-' . strtolower( $name ) )->inContentLanguage();
767 if ( !$msg->isBlank() ) {
768 $group = $msg->text();
770 // Than use the group from this object
771 $group = $this->getGroupName();
778 * Indicates whether this special page may perform database writes
783 public function doesWrites() {
788 * Under which header this special page is listed in Special:SpecialPages
789 * See messages 'specialpages-group-*' for valid names
790 * This method defaults to group 'other'
795 protected function getGroupName() {
800 * Call wfTransactionalTimeLimit() if this request was POSTed
803 protected function useTransactionalTimeLimit() {
804 if ( $this->getRequest()->wasPosted() ) {
805 wfTransactionalTimeLimit();