Apply $wgMaxArticleSize more exactly
[mediawiki.git] / includes / specialpage / SpecialPage.php
blob35ecc6e4b6c550f5c33fba8b956bac338051d9cd
1 <?php
2 /**
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
20 * @file
21 * @ingroup SpecialPage
24 use MediaWiki\Auth\AuthManager;
25 use MediaWiki\Linker\LinkRenderer;
26 use MediaWiki\MediaWikiServices;
28 /**
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
36 class SpecialPage {
37 // The canonical name of this special page
38 // Also used for the default <h1> heading, @see getDescription()
39 protected $mName;
41 // The local name of this special page
42 private $mLocalName;
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?
49 private $mListed;
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;
57 /**
58 * Current request context
59 * @var IContextSource
61 protected $mContext;
63 /**
64 * @var LinkRenderer|null
66 private $linkRenderer;
68 /**
69 * Get a localised Title object for a specified special page name
71 * @since 1.9
72 * @since 1.21 $fragment parameter added
74 * @param string $name
75 * @param string|bool $subpage Subpage string, or false to not use a subpage
76 * @param string $fragment The link fragment (after the "#")
77 * @return Title
78 * @throws MWException
80 public static function getTitleFor( $name, $subpage = false, $fragment = '' ) {
81 $name = SpecialPageFactory::getLocalNameFor( $name, $subpage );
83 return Title::makeTitle( NS_SPECIAL, $name, $fragment );
86 /**
87 * Get a localised Title object for a page name with a possibly unvalidated subpage
89 * @param string $name
90 * @param string|bool $subpage Subpage string, or false to not use a subpage
91 * @return Title|null Title object or null if the page doesn't exist
93 public static function getSafeTitleFor( $name, $subpage = false ) {
94 $name = SpecialPageFactory::getLocalNameFor( $name, $subpage );
95 if ( $name ) {
96 return Title::makeTitleSafe( NS_SPECIAL, $name );
97 } else {
98 return null;
103 * Default constructor for special pages
104 * Derivative classes should call this from their constructor
105 * Note that if the user does not have the required level, an error message will
106 * be displayed by the default execute() method, without the global function ever
107 * being called.
109 * If you override execute(), you can recover the default behavior with userCanExecute()
110 * and displayRestrictionError()
112 * @param string $name Name of the special page, as seen in links and URLs
113 * @param string $restriction User right required, e.g. "block" or "delete"
114 * @param bool $listed Whether the page is listed in Special:Specialpages
115 * @param callable|bool $function Unused
116 * @param string $file Unused
117 * @param bool $includable Whether the page can be included in normal pages
119 public function __construct(
120 $name = '', $restriction = '', $listed = true,
121 $function = false, $file = '', $includable = false
123 $this->mName = $name;
124 $this->mRestriction = $restriction;
125 $this->mListed = $listed;
126 $this->mIncludable = $includable;
130 * Get the name of this Special Page.
131 * @return string
133 function getName() {
134 return $this->mName;
138 * Get the permission that a user must have to execute this page
139 * @return string
141 function getRestriction() {
142 return $this->mRestriction;
145 // @todo FIXME: Decide which syntax to use for this, and stick to it
147 * Whether this special page is listed in Special:SpecialPages
148 * @since 1.3 (r3583)
149 * @return bool
151 function isListed() {
152 return $this->mListed;
156 * Set whether this page is listed in Special:Specialpages, at run-time
157 * @since 1.3
158 * @param bool $listed
159 * @return bool
161 function setListed( $listed ) {
162 return wfSetVar( $this->mListed, $listed );
166 * Get or set whether this special page is listed in Special:SpecialPages
167 * @since 1.6
168 * @param bool $x
169 * @return bool
171 function listed( $x = null ) {
172 return wfSetVar( $this->mListed, $x );
176 * Whether it's allowed to transclude the special page via {{Special:Foo/params}}
177 * @return bool
179 public function isIncludable() {
180 return $this->mIncludable;
184 * How long to cache page when it is being included.
186 * @note If cache time is not 0, then the current user becomes an anon
187 * if you want to do any per-user customizations, than this method
188 * must be overriden to return 0.
189 * @since 1.26
190 * @return int Time in seconds, 0 to disable caching altogether,
191 * false to use the parent page's cache settings
193 public function maxIncludeCacheTime() {
194 return $this->getConfig()->get( 'MiserMode' ) ? $this->getCacheTTL() : 0;
198 * @return int Seconds that this page can be cached
200 protected function getCacheTTL() {
201 return 60 * 60;
205 * Whether the special page is being evaluated via transclusion
206 * @param bool $x
207 * @return bool
209 function including( $x = null ) {
210 return wfSetVar( $this->mIncluding, $x );
214 * Get the localised name of the special page
215 * @return string
217 function getLocalName() {
218 if ( !isset( $this->mLocalName ) ) {
219 $this->mLocalName = SpecialPageFactory::getLocalNameFor( $this->mName );
222 return $this->mLocalName;
226 * Is this page expensive (for some definition of expensive)?
227 * Expensive pages are disabled or cached in miser mode. Originally used
228 * (and still overridden) by QueryPage and subclasses, moved here so that
229 * Special:SpecialPages can safely call it for all special pages.
231 * @return bool
233 public function isExpensive() {
234 return false;
238 * Is this page cached?
239 * Expensive pages are cached or disabled in miser mode.
240 * Used by QueryPage and subclasses, moved here so that
241 * Special:SpecialPages can safely call it for all special pages.
243 * @return bool
244 * @since 1.21
246 public function isCached() {
247 return false;
251 * Can be overridden by subclasses with more complicated permissions
252 * schemes.
254 * @return bool Should the page be displayed with the restricted-access
255 * pages?
257 public function isRestricted() {
258 // DWIM: If anons can do something, then it is not restricted
259 return $this->mRestriction != '' && !User::groupHasPermission( '*', $this->mRestriction );
263 * Checks if the given user (identified by an object) can execute this
264 * special page (as defined by $mRestriction). Can be overridden by sub-
265 * classes with more complicated permissions schemes.
267 * @param User $user The user to check
268 * @return bool Does the user have permission to view the page?
270 public function userCanExecute( User $user ) {
271 return $user->isAllowed( $this->mRestriction );
275 * Output an error message telling the user what access level they have to have
276 * @throws PermissionsError
278 function displayRestrictionError() {
279 throw new PermissionsError( $this->mRestriction );
283 * Checks if userCanExecute, and if not throws a PermissionsError
285 * @since 1.19
286 * @return void
287 * @throws PermissionsError
289 public function checkPermissions() {
290 if ( !$this->userCanExecute( $this->getUser() ) ) {
291 $this->displayRestrictionError();
296 * If the wiki is currently in readonly mode, throws a ReadOnlyError
298 * @since 1.19
299 * @return void
300 * @throws ReadOnlyError
302 public function checkReadOnly() {
303 if ( wfReadOnly() ) {
304 throw new ReadOnlyError;
309 * If the user is not logged in, throws UserNotLoggedIn error
311 * The user will be redirected to Special:Userlogin with the given message as an error on
312 * the form.
314 * @since 1.23
315 * @param string $reasonMsg [optional] Message key to be displayed on login page
316 * @param string $titleMsg [optional] Passed on to UserNotLoggedIn constructor
317 * @throws UserNotLoggedIn
319 public function requireLogin(
320 $reasonMsg = 'exception-nologin-text', $titleMsg = 'exception-nologin'
322 if ( $this->getUser()->isAnon() ) {
323 throw new UserNotLoggedIn( $reasonMsg, $titleMsg );
328 * Tells if the special page does something security-sensitive and needs extra defense against
329 * a stolen account (e.g. a reauthentication). What exactly that will mean is decided by the
330 * authentication framework.
331 * @return bool|string False or the argument for AuthManager::securitySensitiveOperationStatus().
332 * Typically a special page needing elevated security would return its name here.
334 protected function getLoginSecurityLevel() {
335 return false;
339 * Verifies that the user meets the security level, possibly reauthenticating them in the process.
341 * This should be used when the page does something security-sensitive and needs extra defense
342 * against a stolen account (e.g. a reauthentication). The authentication framework will make
343 * an extra effort to make sure the user account is not compromised. What that exactly means
344 * will depend on the system and user settings; e.g. the user might be required to log in again
345 * unless their last login happened recently, or they might be given a second-factor challenge.
347 * Calling this method will result in one if these actions:
348 * - return true: all good.
349 * - return false and set a redirect: caller should abort; the redirect will take the user
350 * to the login page for reauthentication, and back.
351 * - throw an exception if there is no way for the user to meet the requirements without using
352 * a different access method (e.g. this functionality is only available from a specific IP).
354 * Note that this does not in any way check that the user is authorized to use this special page
355 * (use checkPermissions() for that).
357 * @param string $level A security level. Can be an arbitrary string, defaults to the page name.
358 * @return bool False means a redirect to the reauthentication page has been set and processing
359 * of the special page should be aborted.
360 * @throws ErrorPageError If the security level cannot be met, even with reauthentication.
362 protected function checkLoginSecurityLevel( $level = null ) {
363 $level = $level ?: $this->getName();
364 $securityStatus = AuthManager::singleton()->securitySensitiveOperationStatus( $level );
365 if ( $securityStatus === AuthManager::SEC_OK ) {
366 return true;
367 } elseif ( $securityStatus === AuthManager::SEC_REAUTH ) {
368 $request = $this->getRequest();
369 $title = SpecialPage::getTitleFor( 'Userlogin' );
370 $query = [
371 'returnto' => $this->getFullTitle()->getPrefixedDBkey(),
372 'returntoquery' => wfArrayToCgi( array_diff_key( $request->getQueryValues(),
373 [ 'title' => true ] ) ),
374 'force' => $level,
376 $url = $title->getFullURL( $query, false, PROTO_HTTPS );
378 $this->getOutput()->redirect( $url );
379 return false;
382 $titleMessage = wfMessage( 'specialpage-securitylevel-not-allowed-title' );
383 $errorMessage = wfMessage( 'specialpage-securitylevel-not-allowed' );
384 throw new ErrorPageError( $titleMessage, $errorMessage );
388 * Return an array of subpages beginning with $search that this special page will accept.
390 * For example, if a page supports subpages "foo", "bar" and "baz" (as in Special:PageName/foo,
391 * etc.):
393 * - `prefixSearchSubpages( "ba" )` should return `array( "bar", "baz" )`
394 * - `prefixSearchSubpages( "f" )` should return `array( "foo" )`
395 * - `prefixSearchSubpages( "z" )` should return `array()`
396 * - `prefixSearchSubpages( "" )` should return `array( foo", "bar", "baz" )`
398 * @param string $search Prefix to search for
399 * @param int $limit Maximum number of results to return (usually 10)
400 * @param int $offset Number of results to skip (usually 0)
401 * @return string[] Matching subpages
403 public function prefixSearchSubpages( $search, $limit, $offset ) {
404 $subpages = $this->getSubpagesForPrefixSearch();
405 if ( !$subpages ) {
406 return [];
409 return self::prefixSearchArray( $search, $limit, $subpages, $offset );
413 * Return an array of subpages that this special page will accept for prefix
414 * searches. If this method requires a query you might instead want to implement
415 * prefixSearchSubpages() directly so you can support $limit and $offset. This
416 * method is better for static-ish lists of things.
418 * @return string[] subpages to search from
420 protected function getSubpagesForPrefixSearch() {
421 return [];
425 * Perform a regular substring search for prefixSearchSubpages
426 * @param string $search Prefix to search for
427 * @param int $limit Maximum number of results to return (usually 10)
428 * @param int $offset Number of results to skip (usually 0)
429 * @return string[] Matching subpages
431 protected function prefixSearchString( $search, $limit, $offset ) {
432 $title = Title::newFromText( $search );
433 if ( !$title || !$title->canExist() ) {
434 // No prefix suggestion in special and media namespace
435 return [];
438 $searchEngine = MediaWikiServices::getInstance()->newSearchEngine();
439 $searchEngine->setLimitOffset( $limit, $offset );
440 $searchEngine->setNamespaces( [] );
441 $result = $searchEngine->defaultPrefixSearch( $search );
442 return array_map( function( Title $t ) {
443 return $t->getPrefixedText();
444 }, $result );
448 * Helper function for implementations of prefixSearchSubpages() that
449 * filter the values in memory (as opposed to making a query).
451 * @since 1.24
452 * @param string $search
453 * @param int $limit
454 * @param array $subpages
455 * @param int $offset
456 * @return string[]
458 protected static function prefixSearchArray( $search, $limit, array $subpages, $offset ) {
459 $escaped = preg_quote( $search, '/' );
460 return array_slice( preg_grep( "/^$escaped/i",
461 array_slice( $subpages, $offset ) ), 0, $limit );
465 * Sets headers - this should be called from the execute() method of all derived classes!
467 function setHeaders() {
468 $out = $this->getOutput();
469 $out->setArticleRelated( false );
470 $out->setRobotPolicy( $this->getRobotPolicy() );
471 $out->setPageTitle( $this->getDescription() );
472 if ( $this->getConfig()->get( 'UseMediaWikiUIEverywhere' ) ) {
473 $out->addModuleStyles( [
474 'mediawiki.ui.input',
475 'mediawiki.ui.radio',
476 'mediawiki.ui.checkbox',
477 ] );
482 * Entry point.
484 * @since 1.20
486 * @param string|null $subPage
488 final public function run( $subPage ) {
490 * Gets called before @see SpecialPage::execute.
491 * Return false to prevent calling execute() (since 1.27+).
493 * @since 1.20
495 * @param SpecialPage $this
496 * @param string|null $subPage
498 if ( !Hooks::run( 'SpecialPageBeforeExecute', [ $this, $subPage ] ) ) {
499 return;
502 if ( $this->beforeExecute( $subPage ) === false ) {
503 return;
505 $this->execute( $subPage );
506 $this->afterExecute( $subPage );
509 * Gets called after @see SpecialPage::execute.
511 * @since 1.20
513 * @param SpecialPage $this
514 * @param string|null $subPage
516 Hooks::run( 'SpecialPageAfterExecute', [ $this, $subPage ] );
520 * Gets called before @see SpecialPage::execute.
521 * Return false to prevent calling execute() (since 1.27+).
523 * @since 1.20
525 * @param string|null $subPage
526 * @return bool|void
528 protected function beforeExecute( $subPage ) {
529 // No-op
533 * Gets called after @see SpecialPage::execute.
535 * @since 1.20
537 * @param string|null $subPage
539 protected function afterExecute( $subPage ) {
540 // No-op
544 * Default execute method
545 * Checks user permissions
547 * This must be overridden by subclasses; it will be made abstract in a future version
549 * @param string|null $subPage
551 public function execute( $subPage ) {
552 $this->setHeaders();
553 $this->checkPermissions();
554 $this->checkLoginSecurityLevel( $this->getLoginSecurityLevel() );
555 $this->outputHeader();
559 * Outputs a summary message on top of special pages
560 * Per default the message key is the canonical name of the special page
561 * May be overridden, i.e. by extensions to stick with the naming conventions
562 * for message keys: 'extensionname-xxx'
564 * @param string $summaryMessageKey Message key of the summary
566 function outputHeader( $summaryMessageKey = '' ) {
567 global $wgContLang;
569 if ( $summaryMessageKey == '' ) {
570 $msg = $wgContLang->lc( $this->getName() ) . '-summary';
571 } else {
572 $msg = $summaryMessageKey;
574 if ( !$this->msg( $msg )->isDisabled() && !$this->including() ) {
575 $this->getOutput()->wrapWikiMsg(
576 "<div class='mw-specialpage-summary'>\n$1\n</div>", $msg );
581 * Returns the name that goes in the \<h1\> in the special page itself, and
582 * also the name that will be listed in Special:Specialpages
584 * Derived classes can override this, but usually it is easier to keep the
585 * default behavior.
587 * @return string
589 function getDescription() {
590 return $this->msg( strtolower( $this->mName ) )->text();
594 * Get a self-referential title object
596 * @param string|bool $subpage
597 * @return Title
598 * @deprecated since 1.23, use SpecialPage::getPageTitle
600 function getTitle( $subpage = false ) {
601 return $this->getPageTitle( $subpage );
605 * Get a self-referential title object
607 * @param string|bool $subpage
608 * @return Title
609 * @since 1.23
611 function getPageTitle( $subpage = false ) {
612 return self::getTitleFor( $this->mName, $subpage );
616 * Sets the context this SpecialPage is executed in
618 * @param IContextSource $context
619 * @since 1.18
621 public function setContext( $context ) {
622 $this->mContext = $context;
626 * Gets the context this SpecialPage is executed in
628 * @return IContextSource|RequestContext
629 * @since 1.18
631 public function getContext() {
632 if ( $this->mContext instanceof IContextSource ) {
633 return $this->mContext;
634 } else {
635 wfDebug( __METHOD__ . " called and \$mContext is null. " .
636 "Return RequestContext::getMain(); for sanity\n" );
638 return RequestContext::getMain();
643 * Get the WebRequest being used for this instance
645 * @return WebRequest
646 * @since 1.18
648 public function getRequest() {
649 return $this->getContext()->getRequest();
653 * Get the OutputPage being used for this instance
655 * @return OutputPage
656 * @since 1.18
658 public function getOutput() {
659 return $this->getContext()->getOutput();
663 * Shortcut to get the User executing this instance
665 * @return User
666 * @since 1.18
668 public function getUser() {
669 return $this->getContext()->getUser();
673 * Shortcut to get the skin being used for this instance
675 * @return Skin
676 * @since 1.18
678 public function getSkin() {
679 return $this->getContext()->getSkin();
683 * Shortcut to get user's language
685 * @return Language
686 * @since 1.19
688 public function getLanguage() {
689 return $this->getContext()->getLanguage();
693 * Shortcut to get main config object
694 * @return Config
695 * @since 1.24
697 public function getConfig() {
698 return $this->getContext()->getConfig();
702 * Return the full title, including $par
704 * @return Title
705 * @since 1.18
707 public function getFullTitle() {
708 return $this->getContext()->getTitle();
712 * Return the robot policy. Derived classes that override this can change
713 * the robot policy set by setHeaders() from the default 'noindex,nofollow'.
715 * @return string
716 * @since 1.23
718 protected function getRobotPolicy() {
719 return 'noindex,nofollow';
723 * Wrapper around wfMessage that sets the current context.
725 * @since 1.16
726 * @return Message
727 * @see wfMessage
729 public function msg( /* $args */ ) {
730 $message = call_user_func_array(
731 [ $this->getContext(), 'msg' ],
732 func_get_args()
734 // RequestContext passes context to wfMessage, and the language is set from
735 // the context, but setting the language for Message class removes the
736 // interface message status, which breaks for example usernameless gender
737 // invocations. Restore the flag when not including special page in content.
738 if ( $this->including() ) {
739 $message->setInterfaceMessageFlag( false );
742 return $message;
746 * Adds RSS/atom links
748 * @param array $params
750 protected function addFeedLinks( $params ) {
751 $feedTemplate = wfScript( 'api' );
753 foreach ( $this->getConfig()->get( 'FeedClasses' ) as $format => $class ) {
754 $theseParams = $params + [ 'feedformat' => $format ];
755 $url = wfAppendQuery( $feedTemplate, $theseParams );
756 $this->getOutput()->addFeedLink( $format, $url );
761 * Adds help link with an icon via page indicators.
762 * Link target can be overridden by a local message containing a wikilink:
763 * the message key is: lowercase special page name + '-helppage'.
764 * @param string $to Target MediaWiki.org page title or encoded URL.
765 * @param bool $overrideBaseUrl Whether $url is a full URL, to avoid MW.o.
766 * @since 1.25
768 public function addHelpLink( $to, $overrideBaseUrl = false ) {
769 global $wgContLang;
770 $msg = $this->msg( $wgContLang->lc( $this->getName() ) . '-helppage' );
772 if ( !$msg->isDisabled() ) {
773 $helpUrl = Skin::makeUrl( $msg->plain() );
774 $this->getOutput()->addHelpLink( $helpUrl, true );
775 } else {
776 $this->getOutput()->addHelpLink( $to, $overrideBaseUrl );
781 * Get the group that the special page belongs in on Special:SpecialPage
782 * Use this method, instead of getGroupName to allow customization
783 * of the group name from the wiki side
785 * @return string Group of this special page
786 * @since 1.21
788 public function getFinalGroupName() {
789 $name = $this->getName();
791 // Allow overbidding the group from the wiki side
792 $msg = $this->msg( 'specialpages-specialpagegroup-' . strtolower( $name ) )->inContentLanguage();
793 if ( !$msg->isBlank() ) {
794 $group = $msg->text();
795 } else {
796 // Than use the group from this object
797 $group = $this->getGroupName();
800 return $group;
804 * Indicates whether this special page may perform database writes
806 * @return bool
807 * @since 1.27
809 public function doesWrites() {
810 return false;
814 * Under which header this special page is listed in Special:SpecialPages
815 * See messages 'specialpages-group-*' for valid names
816 * This method defaults to group 'other'
818 * @return string
819 * @since 1.21
821 protected function getGroupName() {
822 return 'other';
826 * Call wfTransactionalTimeLimit() if this request was POSTed
827 * @since 1.26
829 protected function useTransactionalTimeLimit() {
830 if ( $this->getRequest()->wasPosted() ) {
831 wfTransactionalTimeLimit();
836 * @since 1.28
837 * @return LinkRenderer
839 protected function getLinkRenderer() {
840 if ( $this->linkRenderer ) {
841 return $this->linkRenderer;
842 } else {
843 return MediaWikiServices::getInstance()->getLinkRenderer();
848 * @since 1.28
849 * @param LinkRenderer $linkRenderer
851 public function setLinkRenderer( LinkRenderer $linkRenderer ) {
852 $this->linkRenderer = $linkRenderer;