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() {
189 return $this->getConfig()->get( 'MiserMode' ) ?
$this->getCacheTTL() : 0;
193 * @return int Seconds that this page can be cached
195 protected function getCacheTTL() {
200 * Whether the special page is being evaluated via transclusion
204 function including( $x = null ) {
205 return wfSetVar( $this->mIncluding
, $x );
209 * Get the localised name of the special page
212 function getLocalName() {
213 if ( !isset( $this->mLocalName
) ) {
214 $this->mLocalName
= SpecialPageFactory
::getLocalNameFor( $this->mName
);
217 return $this->mLocalName
;
221 * Is this page expensive (for some definition of expensive)?
222 * Expensive pages are disabled or cached in miser mode. Originally used
223 * (and still overridden) by QueryPage and subclasses, moved here so that
224 * Special:SpecialPages can safely call it for all special pages.
228 public function isExpensive() {
233 * Is this page cached?
234 * Expensive pages are cached or disabled in miser mode.
235 * Used by QueryPage and subclasses, moved here so that
236 * Special:SpecialPages can safely call it for all special pages.
241 public function isCached() {
246 * Can be overridden by subclasses with more complicated permissions
249 * @return bool Should the page be displayed with the restricted-access
252 public function isRestricted() {
253 // DWIM: If anons can do something, then it is not restricted
254 return $this->mRestriction
!= '' && !User
::groupHasPermission( '*', $this->mRestriction
);
258 * Checks if the given user (identified by an object) can execute this
259 * special page (as defined by $mRestriction). Can be overridden by sub-
260 * classes with more complicated permissions schemes.
262 * @param User $user The user to check
263 * @return bool Does the user have permission to view the page?
265 public function userCanExecute( User
$user ) {
266 return $user->isAllowed( $this->mRestriction
);
270 * Output an error message telling the user what access level they have to have
271 * @throws PermissionsError
273 function displayRestrictionError() {
274 throw new PermissionsError( $this->mRestriction
);
278 * Checks if userCanExecute, and if not throws a PermissionsError
282 * @throws PermissionsError
284 public function checkPermissions() {
285 if ( !$this->userCanExecute( $this->getUser() ) ) {
286 $this->displayRestrictionError();
291 * If the wiki is currently in readonly mode, throws a ReadOnlyError
295 * @throws ReadOnlyError
297 public function checkReadOnly() {
298 if ( wfReadOnly() ) {
299 throw new ReadOnlyError
;
304 * If the user is not logged in, throws UserNotLoggedIn error
306 * The user will be redirected to Special:Userlogin with the given message as an error on
310 * @param string $reasonMsg [optional] Message key to be displayed on login page
311 * @param string $titleMsg [optional] Passed on to UserNotLoggedIn constructor
312 * @throws UserNotLoggedIn
314 public function requireLogin(
315 $reasonMsg = 'exception-nologin-text', $titleMsg = 'exception-nologin'
317 if ( $this->getUser()->isAnon() ) {
318 throw new UserNotLoggedIn( $reasonMsg, $titleMsg );
323 * Tells if the special page does something security-sensitive and needs extra defense against
324 * a stolen account (e.g. a reauthentication). What exactly that will mean is decided by the
325 * authentication framework.
326 * @return bool|string False or the argument for AuthManager::securitySensitiveOperationStatus().
327 * Typically a special page needing elevated security would return its name here.
329 protected function getLoginSecurityLevel() {
334 * Verifies that the user meets the security level, possibly reauthenticating them in the process.
336 * This should be used when the page does something security-sensitive and needs extra defense
337 * against a stolen account (e.g. a reauthentication). The authentication framework will make
338 * an extra effort to make sure the user account is not compromised. What that exactly means
339 * will depend on the system and user settings; e.g. the user might be required to log in again
340 * unless their last login happened recently, or they might be given a second-factor challenge.
342 * Calling this method will result in one if these actions:
343 * - return true: all good.
344 * - return false and set a redirect: caller should abort; the redirect will take the user
345 * to the login page for reauthentication, and back.
346 * - throw an exception if there is no way for the user to meet the requirements without using
347 * a different access method (e.g. this functionality is only available from a specific IP).
349 * Note that this does not in any way check that the user is authorized to use this special page
350 * (use checkPermissions() for that).
352 * @param string $level A security level. Can be an arbitrary string, defaults to the page name.
353 * @return bool False means a redirect to the reauthentication page has been set and processing
354 * of the special page should be aborted.
355 * @throws ErrorPageError If the security level cannot be met, even with reauthentication.
357 protected function checkLoginSecurityLevel( $level = null ) {
358 $level = $level ?
: $this->getName();
359 $securityStatus = AuthManager
::singleton()->securitySensitiveOperationStatus( $level );
360 if ( $securityStatus === AuthManager
::SEC_OK
) {
362 } elseif ( $securityStatus === AuthManager
::SEC_REAUTH
) {
363 $request = $this->getRequest();
364 $title = SpecialPage
::getTitleFor( 'Userlogin' );
366 'returnto' => $this->getFullTitle()->getPrefixedDBkey(),
367 'returntoquery' => wfArrayToCgi( array_diff_key( $request->getQueryValues(),
368 [ 'title' => true ] ) ),
371 $url = $title->getFullURL( $query, false, PROTO_HTTPS
);
373 $this->getOutput()->redirect( $url );
377 $titleMessage = wfMessage( 'specialpage-securitylevel-not-allowed-title' );
378 $errorMessage = wfMessage( 'specialpage-securitylevel-not-allowed' );
379 throw new ErrorPageError( $titleMessage, $errorMessage );
383 * Return an array of subpages beginning with $search that this special page will accept.
385 * For example, if a page supports subpages "foo", "bar" and "baz" (as in Special:PageName/foo,
388 * - `prefixSearchSubpages( "ba" )` should return `array( "bar", "baz" )`
389 * - `prefixSearchSubpages( "f" )` should return `array( "foo" )`
390 * - `prefixSearchSubpages( "z" )` should return `array()`
391 * - `prefixSearchSubpages( "" )` should return `array( foo", "bar", "baz" )`
393 * @param string $search Prefix to search for
394 * @param int $limit Maximum number of results to return (usually 10)
395 * @param int $offset Number of results to skip (usually 0)
396 * @return string[] Matching subpages
398 public function prefixSearchSubpages( $search, $limit, $offset ) {
399 $subpages = $this->getSubpagesForPrefixSearch();
404 return self
::prefixSearchArray( $search, $limit, $subpages, $offset );
408 * Return an array of subpages that this special page will accept for prefix
409 * searches. If this method requires a query you might instead want to implement
410 * prefixSearchSubpages() directly so you can support $limit and $offset. This
411 * method is better for static-ish lists of things.
413 * @return string[] subpages to search from
415 protected function getSubpagesForPrefixSearch() {
420 * Perform a regular substring search for prefixSearchSubpages
421 * @param string $search Prefix to search for
422 * @param int $limit Maximum number of results to return (usually 10)
423 * @param int $offset Number of results to skip (usually 0)
424 * @return string[] Matching subpages
426 protected function prefixSearchString( $search, $limit, $offset ) {
427 $title = Title
::newFromText( $search );
428 if ( !$title ||
!$title->canExist() ) {
429 // No prefix suggestion in special and media namespace
433 $searchEngine = MediaWikiServices
::getInstance()->newSearchEngine();
434 $searchEngine->setLimitOffset( $limit, $offset );
435 $searchEngine->setNamespaces( [] );
436 $result = $searchEngine->defaultPrefixSearch( $search );
437 return array_map( function( Title
$t ) {
438 return $t->getPrefixedText();
443 * Helper function for implementations of prefixSearchSubpages() that
444 * filter the values in memory (as opposed to making a query).
447 * @param string $search
449 * @param array $subpages
453 protected static function prefixSearchArray( $search, $limit, array $subpages, $offset ) {
454 $escaped = preg_quote( $search, '/' );
455 return array_slice( preg_grep( "/^$escaped/i",
456 array_slice( $subpages, $offset ) ), 0, $limit );
460 * Sets headers - this should be called from the execute() method of all derived classes!
462 function setHeaders() {
463 $out = $this->getOutput();
464 $out->setArticleRelated( false );
465 $out->setRobotPolicy( $this->getRobotPolicy() );
466 $out->setPageTitle( $this->getDescription() );
467 if ( $this->getConfig()->get( 'UseMediaWikiUIEverywhere' ) ) {
468 $out->addModuleStyles( [
469 'mediawiki.ui.input',
470 'mediawiki.ui.radio',
471 'mediawiki.ui.checkbox',
481 * @param string|null $subPage
483 final public function run( $subPage ) {
485 * Gets called before @see SpecialPage::execute.
486 * Return false to prevent calling execute() (since 1.27+).
490 * @param SpecialPage $this
491 * @param string|null $subPage
493 if ( !Hooks
::run( 'SpecialPageBeforeExecute', [ $this, $subPage ] ) ) {
497 if ( $this->beforeExecute( $subPage ) === false ) {
500 $this->execute( $subPage );
501 $this->afterExecute( $subPage );
504 * Gets called after @see SpecialPage::execute.
508 * @param SpecialPage $this
509 * @param string|null $subPage
511 Hooks
::run( 'SpecialPageAfterExecute', [ $this, $subPage ] );
515 * Gets called before @see SpecialPage::execute.
516 * Return false to prevent calling execute() (since 1.27+).
520 * @param string|null $subPage
523 protected function beforeExecute( $subPage ) {
528 * Gets called after @see SpecialPage::execute.
532 * @param string|null $subPage
534 protected function afterExecute( $subPage ) {
539 * Default execute method
540 * Checks user permissions
542 * This must be overridden by subclasses; it will be made abstract in a future version
544 * @param string|null $subPage
546 public function execute( $subPage ) {
548 $this->checkPermissions();
549 $this->checkLoginSecurityLevel( $this->getLoginSecurityLevel() );
550 $this->outputHeader();
554 * Outputs a summary message on top of special pages
555 * Per default the message key is the canonical name of the special page
556 * May be overridden, i.e. by extensions to stick with the naming conventions
557 * for message keys: 'extensionname-xxx'
559 * @param string $summaryMessageKey Message key of the summary
561 function outputHeader( $summaryMessageKey = '' ) {
564 if ( $summaryMessageKey == '' ) {
565 $msg = $wgContLang->lc( $this->getName() ) . '-summary';
567 $msg = $summaryMessageKey;
569 if ( !$this->msg( $msg )->isDisabled() && !$this->including() ) {
570 $this->getOutput()->wrapWikiMsg(
571 "<div class='mw-specialpage-summary'>\n$1\n</div>", $msg );
576 * Returns the name that goes in the \<h1\> in the special page itself, and
577 * also the name that will be listed in Special:Specialpages
579 * Derived classes can override this, but usually it is easier to keep the
584 function getDescription() {
585 return $this->msg( strtolower( $this->mName
) )->text();
589 * Get a self-referential title object
591 * @param string|bool $subpage
593 * @deprecated since 1.23, use SpecialPage::getPageTitle
595 function getTitle( $subpage = false ) {
596 return $this->getPageTitle( $subpage );
600 * Get a self-referential title object
602 * @param string|bool $subpage
606 function getPageTitle( $subpage = false ) {
607 return self
::getTitleFor( $this->mName
, $subpage );
611 * Sets the context this SpecialPage is executed in
613 * @param IContextSource $context
616 public function setContext( $context ) {
617 $this->mContext
= $context;
621 * Gets the context this SpecialPage is executed in
623 * @return IContextSource|RequestContext
626 public function getContext() {
627 if ( $this->mContext
instanceof IContextSource
) {
628 return $this->mContext
;
630 wfDebug( __METHOD__
. " called and \$mContext is null. " .
631 "Return RequestContext::getMain(); for sanity\n" );
633 return RequestContext
::getMain();
638 * Get the WebRequest being used for this instance
643 public function getRequest() {
644 return $this->getContext()->getRequest();
648 * Get the OutputPage being used for this instance
653 public function getOutput() {
654 return $this->getContext()->getOutput();
658 * Shortcut to get the User executing this instance
663 public function getUser() {
664 return $this->getContext()->getUser();
668 * Shortcut to get the skin being used for this instance
673 public function getSkin() {
674 return $this->getContext()->getSkin();
678 * Shortcut to get user's language
683 public function getLanguage() {
684 return $this->getContext()->getLanguage();
688 * Shortcut to get main config object
692 public function getConfig() {
693 return $this->getContext()->getConfig();
697 * Return the full title, including $par
702 public function getFullTitle() {
703 return $this->getContext()->getTitle();
707 * Return the robot policy. Derived classes that override this can change
708 * the robot policy set by setHeaders() from the default 'noindex,nofollow'.
713 protected function getRobotPolicy() {
714 return 'noindex,nofollow';
718 * Wrapper around wfMessage that sets the current context.
724 public function msg( /* $args */ ) {
725 $message = call_user_func_array(
726 [ $this->getContext(), 'msg' ],
729 // RequestContext passes context to wfMessage, and the language is set from
730 // the context, but setting the language for Message class removes the
731 // interface message status, which breaks for example usernameless gender
732 // invocations. Restore the flag when not including special page in content.
733 if ( $this->including() ) {
734 $message->setInterfaceMessageFlag( false );
741 * Adds RSS/atom links
743 * @param array $params
745 protected function addFeedLinks( $params ) {
746 $feedTemplate = wfScript( 'api' );
748 foreach ( $this->getConfig()->get( 'FeedClasses' ) as $format => $class ) {
749 $theseParams = $params +
[ 'feedformat' => $format ];
750 $url = wfAppendQuery( $feedTemplate, $theseParams );
751 $this->getOutput()->addFeedLink( $format, $url );
756 * Adds help link with an icon via page indicators.
757 * Link target can be overridden by a local message containing a wikilink:
758 * the message key is: lowercase special page name + '-helppage'.
759 * @param string $to Target MediaWiki.org page title or encoded URL.
760 * @param bool $overrideBaseUrl Whether $url is a full URL, to avoid MW.o.
763 public function addHelpLink( $to, $overrideBaseUrl = false ) {
765 $msg = $this->msg( $wgContLang->lc( $this->getName() ) . '-helppage' );
767 if ( !$msg->isDisabled() ) {
768 $helpUrl = Skin
::makeUrl( $msg->plain() );
769 $this->getOutput()->addHelpLink( $helpUrl, true );
771 $this->getOutput()->addHelpLink( $to, $overrideBaseUrl );
776 * Get the group that the special page belongs in on Special:SpecialPage
777 * Use this method, instead of getGroupName to allow customization
778 * of the group name from the wiki side
780 * @return string Group of this special page
783 public function getFinalGroupName() {
784 $name = $this->getName();
786 // Allow overbidding the group from the wiki side
787 $msg = $this->msg( 'specialpages-specialpagegroup-' . strtolower( $name ) )->inContentLanguage();
788 if ( !$msg->isBlank() ) {
789 $group = $msg->text();
791 // Than use the group from this object
792 $group = $this->getGroupName();
799 * Indicates whether this special page may perform database writes
804 public function doesWrites() {
809 * Under which header this special page is listed in Special:SpecialPages
810 * See messages 'specialpages-group-*' for valid names
811 * This method defaults to group 'other'
816 protected function getGroupName() {
821 * Call wfTransactionalTimeLimit() if this request was POSTed
824 protected function useTransactionalTimeLimit() {
825 if ( $this->getRequest()->wasPosted() ) {
826 wfTransactionalTimeLimit();