Debian Codegraph @

includes/specialpage/SpecialPage.php

raw symbols SCIP
1 <?php
2 /**
3 * Parent class for all special pages.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @ingroup SpecialPage
22 */
23
24 namespace MediaWiki\SpecialPage;
25
26 use ErrorPageError;
27 use MediaWiki\Auth\AuthManager;
28 use MediaWiki\Config\Config;
29 use MediaWiki\Context\IContextSource;
30 use MediaWiki\Context\RequestContext;
31 use MediaWiki\HookContainer\HookContainer;
32 use MediaWiki\HookContainer\HookRunner;
33 use MediaWiki\Language\Language;
34 use MediaWiki\Language\RawMessage;
35 use MediaWiki\Linker\LinkRenderer;
36 use MediaWiki\MainConfigNames;
37 use MediaWiki\MediaWikiServices;
38 use MediaWiki\Message\Message;
39 use MediaWiki\Navigation\PagerNavigationBuilder;
40 use MediaWiki\Output\OutputPage;
41 use MediaWiki\Permissions\Authority;
42 use MediaWiki\Permissions\PermissionStatus;
43 use MediaWiki\Request\WebRequest;
44 use MediaWiki\Title\Title;
45 use MediaWiki\Title\TitleValue;
46 use MediaWiki\User\User;
47 use MessageLocalizer;
48 use MWCryptRand;
49 use PermissionsError;
50 use ReadOnlyError;
51 use SearchEngineFactory;
52 use Skin;
53 use UserNotLoggedIn;
54 use Wikimedia\Message\MessageSpecifier;
55
56 /**
57 * Parent class for all special pages.
58 *
59 * Includes some static functions for handling the special page list deprecated
60 * in favor of SpecialPageFactory.
61 *
62 * @stable to extend
63 *
64 * @ingroup SpecialPage
65 */
66 class SpecialPage implements MessageLocalizer {
67 /**
68 * @var string The canonical name of this special page
69 * Also used as the message key for the default <h1> heading,
70 * @see getDescription()
71 */
72 protected $mName;
73
74 /** @var string The local name of this special page */
75 private $mLocalName;
76
77 /**
78 * @var string Minimum user level required to access this page, or "" for anyone.
79 * Also used to categorise the pages in Special:Specialpages
80 */
81 protected $mRestriction;
82
83 /** @var bool Listed in Special:Specialpages? */
84 private $mListed;
85
86 /** @var bool Whether or not this special page is being included from an article */
87 protected $mIncluding;
88
89 /** @var bool Whether the special page can be included in an article */
90 protected $mIncludable;
91
92 /**
93 * Current request context
94 * @var IContextSource
95 */
96 protected $mContext;
97
98 /** @var Language|null */
99 private $contentLanguage;
100
101 /**
102 * @var LinkRenderer|null
103 */
104 private $linkRenderer = null;
105
106 /** @var HookContainer|null */
107 private $hookContainer;
108 /** @var HookRunner|null */
109 private $hookRunner;
110
111 /** @var AuthManager|null */
112 private $authManager = null;
113
114 /** @var SpecialPageFactory */
115 private $specialPageFactory;
116
117 /**
118 * Get the users preferred search page.
119 *
120 * It will fall back to Special:Search if the preference points to a page
121 * that doesn't exist or is not defined.
122 *
123 * @since 1.38
124 * @param User $user Search page can be customized by user preference.
125 * @return Title
126 */
127 public static function newSearchPage( User $user ) {
128 // Try user preference first
129 $userOptionsManager = MediaWikiServices::getInstance()->getUserOptionsManager();
130 $title = $userOptionsManager->getOption( $user, 'search-special-page' );
131 if ( $title ) {
132 $page = self::getTitleFor( $title );
133 $factory = MediaWikiServices::getInstance()->getSpecialPageFactory();
134 if ( $factory->exists( $page->getText() ) ) {
135 return $page;
136 }
137 }
138 return self::getTitleFor( 'Search' );
139 }
140
141 /**
142 * Get a localised Title object for a specified special page name
143 * If you don't need a full Title object, consider using TitleValue through
144 * getTitleValueFor() below.
145 *
146 * @since 1.9
147 * @since 1.21 $fragment parameter added
148 *
149 * @param string $name
150 * @param string|false|null $subpage Subpage string, or false/null to not use a subpage
151 * @param string $fragment The link fragment (after the "#")
152 * @return Title
153 */
154 public static function getTitleFor( $name, $subpage = false, $fragment = '' ) {
155 return Title::newFromLinkTarget(
156 self::getTitleValueFor( $name, $subpage, $fragment )
157 );
158 }
159
160 /**
161 * Get a localised TitleValue object for a specified special page name
162 *
163 * @since 1.28
164 * @param string $name
165 * @param string|false|null $subpage Subpage string, or false/null to not use a subpage
166 * @param string $fragment The link fragment (after the "#")
167 * @return TitleValue
168 */
169 public static function getTitleValueFor( $name, $subpage = false, $fragment = '' ) {
170 $name = MediaWikiServices::getInstance()->getSpecialPageFactory()->
171 getLocalNameFor( $name, $subpage );
172
173 return new TitleValue( NS_SPECIAL, $name, $fragment );
174 }
175
176 /**
177 * Get a localised Title object for a page name with a possibly unvalidated subpage
178 *
179 * @param string $name
180 * @param string|false $subpage Subpage string, or false to not use a subpage
181 * @return Title|null Title object or null if the page doesn't exist
182 */
183 public static function getSafeTitleFor( $name, $subpage = false ) {
184 $name = MediaWikiServices::getInstance()->getSpecialPageFactory()->
185 getLocalNameFor( $name, $subpage );
186 if ( $name ) {
187 return Title::makeTitleSafe( NS_SPECIAL, $name );
188 } else {
189 return null;
190 }
191 }
192
193 /**
194 * Default constructor for special pages
195 * Derivative classes should call this from their constructor
196 * Note that if the user does not have the required level, an error message will
197 * be displayed by the default execute() method, without the global function ever
198 * being called.
199 *
200 * If you override execute(), you can recover the default behavior with userCanExecute()
201 * and displayRestrictionError()
202 *
203 * @stable to call
204 *
205 * @param string $name Name of the special page, as seen in links and URLs
206 * @param string $restriction User right required, e.g. "block" or "delete"
207 * @param bool $listed Whether the page is listed in Special:Specialpages
208 * @param callable|bool $function Unused
209 * @param string $file Unused
210 * @param bool $includable Whether the page can be included in normal pages
211 */
212 public function __construct(
213 $name = '', $restriction = '', $listed = true,
214 $function = false, $file = '', $includable = false
215 ) {
216 $this->mName = $name;
217 $this->mRestriction = $restriction;
218 $this->mListed = $listed;
219 $this->mIncludable = $includable;
220 }
221
222 /**
223 * Get the canonical, unlocalized name of this special page without namespace.
224 * @return string
225 */
226 public function getName() {
227 return $this->mName;
228 }
229
230 /**
231 * Get the permission that a user must have to execute this page
232 * @return string
233 */
234 public function getRestriction() {
235 return $this->mRestriction;
236 }
237
238 // @todo FIXME: Decide which syntax to use for this, and stick to it
239
240 /**
241 * Whether this special page is listed in Special:SpecialPages
242 * @stable to override
243 * @since 1.3 (r3583)
244 * @return bool
245 */
246 public function isListed() {
247 return $this->mListed;
248 }
249
250 /**
251 * Whether it's allowed to transclude the special page via {{Special:Foo/params}}
252 * @stable to override
253 * @return bool
254 */
255 public function isIncludable() {
256 return $this->mIncludable;
257 }
258
259 /**
260 * How long to cache page when it is being included.
261 *
262 * @note If cache time is not 0, then the current user becomes an anon
263 * if you want to do any per-user customizations, than this method
264 * must be overridden to return 0.
265 * @since 1.26
266 * @stable to override
267 * @return int Time in seconds, 0 to disable caching altogether,
268 * false to use the parent page's cache settings
269 */
270 public function maxIncludeCacheTime() {
271 return $this->getConfig()->get( MainConfigNames::MiserMode ) ? $this->getCacheTTL() : 0;
272 }
273
274 /**
275 * @stable to override
276 * @return int Seconds that this page can be cached
277 */
278 protected function getCacheTTL() {
279 return 60 * 60;
280 }
281
282 /**
283 * Whether the special page is being evaluated via transclusion
284 * @param bool|null $x
285 * @return bool
286 */
287 public function including( $x = null ) {
288 return wfSetVar( $this->mIncluding, $x );
289 }
290
291 /**
292 * Get the localised name of the special page
293 * @stable to override
294 * @return string
295 */
296 public function getLocalName() {
297 if ( !isset( $this->mLocalName ) ) {
298 $this->mLocalName = $this->getSpecialPageFactory()->getLocalNameFor( $this->mName );
299 }
300
301 return $this->mLocalName;
302 }
303
304 /**
305 * Is this page expensive (for some definition of expensive)?
306 * Expensive pages are disabled or cached in miser mode. Originally used
307 * (and still overridden) by QueryPage and subclasses, moved here so that
308 * Special:SpecialPages can safely call it for all special pages.
309 *
310 * @stable to override
311 * @return bool
312 */
313 public function isExpensive() {
314 return false;
315 }
316
317 /**
318 * Is this page cached?
319 * Expensive pages are cached or disabled in miser mode.
320 * Used by QueryPage and subclasses, moved here so that
321 * Special:SpecialPages can safely call it for all special pages.
322 *
323 * @stable to override
324 * @return bool
325 * @since 1.21
326 */
327 public function isCached() {
328 return false;
329 }
330
331 /**
332 * Can be overridden by subclasses with more complicated permissions
333 * schemes.
334 *
335 * @stable to override
336 * @return bool Should the page be displayed with the restricted-access
337 * pages?
338 */
339 public function isRestricted() {
340 // DWIM: If anons can do something, then it is not restricted
341 return $this->mRestriction != '' && !MediaWikiServices::getInstance()
342 ->getGroupPermissionsLookup()
343 ->groupHasPermission( '*', $this->mRestriction );
344 }
345
346 /**
347 * Checks if the given user (identified by an object) can execute this
348 * special page (as defined by $mRestriction). Can be overridden by sub-
349 * classes with more complicated permissions schemes.
350 *
351 * @stable to override
352 * @param User $user The user to check
353 * @return bool Does the user have permission to view the page?
354 */
355 public function userCanExecute( User $user ) {
356 return MediaWikiServices::getInstance()
357 ->getPermissionManager()
358 ->userHasRight( $user, $this->mRestriction );
359 }
360
361 /**
362 * Utility function for authorizing an action to be performed by the special
363 * page. User blocks and rate limits are enforced implicitly.
364 *
365 * @see Authority::authorizeAction.
366 *
367 * @param ?string $action If not given, the action returned by
368 * getRestriction() will be used.
369 *
370 * @return PermissionStatus
371 */
372 protected function authorizeAction( ?string $action = null ): PermissionStatus {
373 $action ??= $this->getRestriction();
374
375 if ( !$action ) {
376 return PermissionStatus::newGood();
377 }
378
379 $status = PermissionStatus::newEmpty();
380 $this->getAuthority()->authorizeAction( $action, $status );
381 return $status;
382 }
383
384 /**
385 * Output an error message telling the user what access level they have to have
386 * @stable to override
387 * @throws PermissionsError
388 * @return never
389 */
390 protected function displayRestrictionError() {
391 throw new PermissionsError( $this->mRestriction );
392 }
393
394 /**
395 * Checks if userCanExecute, and if not throws a PermissionsError
396 *
397 * @stable to override
398 * @since 1.19
399 * @return void
400 * @throws PermissionsError
401 */
402 public function checkPermissions() {
403 if ( !$this->userCanExecute( $this->getUser() ) ) {
404 $this->displayRestrictionError();
405 }
406 }
407
408 /**
409 * If the wiki is currently in readonly mode, throws a ReadOnlyError
410 *
411 * @since 1.19
412 * @return void
413 * @throws ReadOnlyError
414 */
415 public function checkReadOnly() {
416 // Can not inject the ReadOnlyMode as it would break the installer since
417 // it instantiates SpecialPageFactory before the DB (via ParserFactory for message parsing)
418 if ( MediaWikiServices::getInstance()->getReadOnlyMode()->isReadOnly() ) {
419 throw new ReadOnlyError;
420 }
421 }
422
423 /**
424 * If the user is not logged in, throws UserNotLoggedIn error
425 *
426 * The user will be redirected to Special:Userlogin with the given message as an error on
427 * the form.
428 *
429 * @since 1.23
430 * @param string $reasonMsg [optional] Message key to be displayed on login page
431 * @param string $titleMsg [optional] Passed on to UserNotLoggedIn constructor
432 * @throws UserNotLoggedIn
433 */
434 public function requireLogin(
435 $reasonMsg = 'exception-nologin-text', $titleMsg = 'exception-nologin'
436 ) {
437 if ( $this->getUser()->isAnon() ) {
438 throw new UserNotLoggedIn( $reasonMsg, $titleMsg );
439 }
440 }
441
442 /**
443 * If the user is not logged in or is a temporary user, throws UserNotLoggedIn
444 *
445 * @since 1.39
446 * @param string $reasonMsg [optional] Message key to be displayed on login page
447 * @param string $titleMsg [optional] Passed on to UserNotLoggedIn constructor. Default 'exception-nologin'
448 * which is used when $titleMsg is null.
449 * @param bool $alwaysRedirectToLoginPage [optional] Should the redirect always go to Special:UserLogin?
450 * If false (the default), the redirect will be to Special:CreateAccount when the user is logged in to
451 * a temporary account.
452 * @throws UserNotLoggedIn
453 */
454 public function requireNamedUser(
455 $reasonMsg = 'exception-nologin-text', $titleMsg = 'exception-nologin', bool $alwaysRedirectToLoginPage = false
456 ) {
457 if ( !$this->getUser()->isNamed() ) {
458 throw new UserNotLoggedIn( $reasonMsg, $titleMsg, [], $alwaysRedirectToLoginPage );
459 }
460 }
461
462 /**
463 * Tells if the special page does something security-sensitive and needs extra defense against
464 * a stolen account (e.g. a reauthentication). What exactly that will mean is decided by the
465 * authentication framework.
466 * @stable to override
467 * @return string|false False or the argument for AuthManager::securitySensitiveOperationStatus().
468 * Typically a special page needing elevated security would return its name here.
469 */
470 protected function getLoginSecurityLevel() {
471 return false;
472 }
473
474 /**
475 * Record preserved POST data after a reauthentication.
476 *
477 * This is called from checkLoginSecurityLevel() when returning from the
478 * redirect for reauthentication, if the redirect had been served in
479 * response to a POST request.
480 *
481 * The base SpecialPage implementation does nothing. If your subclass uses
482 * getLoginSecurityLevel() or checkLoginSecurityLevel(), it should probably
483 * implement this to do something with the data.
484 *
485 * @note Call self::setAuthManager from special page constructor when overriding
486 *
487 * @stable to override
488 * @since 1.32
489 * @param array $data
490 */
491 protected function setReauthPostData( array $data ) {
492 }
493
494 /**
495 * Verifies that the user meets the security level, possibly reauthenticating them in the process.
496 *
497 * This should be used when the page does something security-sensitive and needs extra defense
498 * against a stolen account (e.g. a reauthentication). The authentication framework will make
499 * an extra effort to make sure the user account is not compromised. What that exactly means
500 * will depend on the system and user settings; e.g. the user might be required to log in again
501 * unless their last login happened recently, or they might be given a second-factor challenge.
502 *
503 * Calling this method will result in one if these actions:
504 * - return true: all good.
505 * - return false and set a redirect: caller should abort; the redirect will take the user
506 * to the login page for reauthentication, and back.
507 * - throw an exception if there is no way for the user to meet the requirements without using
508 * a different access method (e.g. this functionality is only available from a specific IP).
509 *
510 * Note that this does not in any way check that the user is authorized to use this special page
511 * (use checkPermissions() for that).
512 *
513 * @param string|null $level A security level. Can be an arbitrary string, defaults to the page
514 * name.
515 * @return bool False means a redirect to the reauthentication page has been set and processing
516 * of the special page should be aborted.
517 * @throws ErrorPageError If the security level cannot be met, even with reauthentication.
518 */
519 protected function checkLoginSecurityLevel( $level = null ) {
520 $level = $level ?: $this->getName();
521 $key = 'SpecialPage:reauth:' . $this->getName();
522 $request = $this->getRequest();
523
524 $securityStatus = $this->getAuthManager()->securitySensitiveOperationStatus( $level );
525 if ( $securityStatus === AuthManager::SEC_OK ) {
526 $uniqueId = $request->getVal( 'postUniqueId' );
527 if ( $uniqueId ) {
528 $key .= ':' . $uniqueId;
529 $session = $request->getSession();
530 $data = $session->getSecret( $key );
531 if ( $data ) {
532 $session->remove( $key );
533 $this->setReauthPostData( $data );
534 }
535 }
536 return true;
537 } elseif ( $securityStatus === AuthManager::SEC_REAUTH ) {
538 $title = self::getTitleFor( 'Userlogin' );
539 $queryParams = $request->getQueryValues();
540
541 if ( $request->wasPosted() ) {
542 $data = array_diff_assoc( $request->getValues(), $request->getQueryValues() );
543 if ( $data ) {
544 // unique ID in case the same special page is open in multiple browser tabs
545 $uniqueId = MWCryptRand::generateHex( 6 );
546 $key .= ':' . $uniqueId;
547 $queryParams['postUniqueId'] = $uniqueId;
548 $session = $request->getSession();
549 $session->persist(); // Just in case
550 $session->setSecret( $key, $data );
551 }
552 }
553
554 $query = [
555 'returnto' => $this->getFullTitle()->getPrefixedDBkey(),
556 'returntoquery' => wfArrayToCgi( array_diff_key( $queryParams, [ 'title' => true ] ) ),
557 'force' => $level,
558 ];
559 $url = $title->getFullURL( $query, false, PROTO_HTTPS );
560
561 $this->getOutput()->redirect( $url );
562 return false;
563 }
564
565 $titleMessage = wfMessage( 'specialpage-securitylevel-not-allowed-title' );
566 $errorMessage = wfMessage( 'specialpage-securitylevel-not-allowed' );
567 throw new ErrorPageError( $titleMessage, $errorMessage );
568 }
569
570 /**
571 * Set the injected AuthManager from the special page constructor
572 *
573 * @since 1.36
574 * @param AuthManager $authManager
575 */
576 final protected function setAuthManager( AuthManager $authManager ) {
577 $this->authManager = $authManager;
578 }
579
580 /**
581 * @note Call self::setAuthManager from special page constructor when using
582 *
583 * @since 1.36
584 * @return AuthManager
585 */
586 final protected function getAuthManager(): AuthManager {
587 if ( $this->authManager === null ) {
588 // Fallback if not provided
589 // TODO Change to wfWarn in a future release
590 $this->authManager = MediaWikiServices::getInstance()->getAuthManager();
591 }
592 return $this->authManager;
593 }
594
595 /**
596 * Return an array of subpages beginning with $search that this special page will accept.
597 *
598 * For example, if a page supports subpages "foo", "bar" and "baz" (as in Special:PageName/foo,
599 * etc.):
600 *
601 * - `prefixSearchSubpages( "ba" )` should return `[ "bar", "baz" ]`
602 * - `prefixSearchSubpages( "f" )` should return `[ "foo" ]`
603 * - `prefixSearchSubpages( "z" )` should return `[]`
604 * - `prefixSearchSubpages( "" )` should return `[ foo", "bar", "baz" ]`
605 *
606 * @stable to override
607 * @param string $search Prefix to search for
608 * @param int $limit Maximum number of results to return (usually 10)
609 * @param int $offset Number of results to skip (usually 0)
610 * @return string[] Matching subpages
611 */
612 public function prefixSearchSubpages( $search, $limit, $offset ) {
613 $subpages = $this->getSubpagesForPrefixSearch();
614 if ( !$subpages ) {
615 return [];
616 }
617
618 return self::prefixSearchArray( $search, $limit, $subpages, $offset );
619 }
620
621 /**
622 * Return an array of subpages that this special page will accept for prefix
623 * searches. If this method requires a query you might instead want to implement
624 * prefixSearchSubpages() directly so you can support $limit and $offset. This
625 * method is better for static-ish lists of things.
626 *
627 * @stable to override
628 * @return string[] subpages to search from
629 */
630 protected function getSubpagesForPrefixSearch() {
631 return [];
632 }
633
634 /**
635 * Return an array of strings representing page titles that are discoverable to end users via UI.
636 *
637 * @since 1.39
638 * @stable to call or override
639 * @return string[] strings representing page titles that can be rendered by skins if required.
640 */
641 public function getAssociatedNavigationLinks() {
642 return [];
643 }
644
645 /**
646 * Perform a regular substring search for prefixSearchSubpages
647 * @since 1.36 Added $searchEngineFactory parameter
648 * @param string $search Prefix to search for
649 * @param int $limit Maximum number of results to return (usually 10)
650 * @param int $offset Number of results to skip (usually 0)
651 * @param SearchEngineFactory|null $searchEngineFactory Provide the service
652 * @return string[] Matching subpages
653 */
654 protected function prefixSearchString(
655 $search,
656 $limit,
657 $offset,
658 ?SearchEngineFactory $searchEngineFactory = null
659 ) {
660 $title = Title::newFromText( $search );
661 if ( !$title || !$title->canExist() ) {
662 // No prefix suggestion in special and media namespace
663 return [];
664 }
665
666 $searchEngine = $searchEngineFactory
667 ? $searchEngineFactory->create()
668 // Fallback if not provided
669 // TODO Change to wfWarn in a future release
670 : MediaWikiServices::getInstance()->newSearchEngine();
671 $searchEngine->setLimitOffset( $limit, $offset );
672 $searchEngine->setNamespaces( [] );
673 $result = $searchEngine->defaultPrefixSearch( $search );
674 return array_map( static function ( Title $t ) {
675 return $t->getPrefixedText();
676 }, $result );
677 }
678
679 /**
680 * Helper function for implementations of prefixSearchSubpages() that
681 * filter the values in memory (as opposed to making a query).
682 *
683 * @since 1.24
684 * @param string $search
685 * @param int $limit
686 * @param array $subpages
687 * @param int $offset
688 * @return string[]
689 */
690 protected static function prefixSearchArray( $search, $limit, array $subpages, $offset ) {
691 $escaped = preg_quote( $search, '/' );
692 return array_slice( preg_grep( "/^$escaped/i",
693 array_slice( $subpages, $offset ) ), 0, $limit );
694 }
695
696 /**
697 * Sets headers - this should be called from the execute() method of all derived classes!
698 * @stable to override
699 */
700 protected function setHeaders() {
701 $out = $this->getOutput();
702 $out->setArticleRelated( false );
703 $out->setRobotPolicy( $this->getRobotPolicy() );
704 $title = $this->getDescription();
705 // T343849
706 if ( is_string( $title ) ) {
707 wfDeprecated( "string return from {$this->getName()}::getDescription()", '1.41' );
708 $title = ( new RawMessage( '$1' ) )->rawParams( $title );
709 }
710 $out->setPageTitleMsg( $title );
711 }
712
713 /**
714 * Entry point.
715 *
716 * @since 1.20
717 *
718 * @param string|null $subPage
719 */
720 final public function run( $subPage ) {
721 if ( !$this->getHookRunner()->onSpecialPageBeforeExecute( $this, $subPage ) ) {
722 return;
723 }
724
725 if ( $this->beforeExecute( $subPage ) === false ) {
726 return;
727 }
728 $this->execute( $subPage );
729 $this->afterExecute( $subPage );
730
731 $this->getHookRunner()->onSpecialPageAfterExecute( $this, $subPage );
732 }
733
734 /**
735 * Gets called before @see SpecialPage::execute.
736 * Return false to prevent calling execute() (since 1.27+).
737 *
738 * @stable to override
739 * @since 1.20
740 *
741 * @param string|null $subPage
742 * @return bool|void
743 */
744 protected function beforeExecute( $subPage ) {
745 // No-op
746 }
747
748 /**
749 * Gets called after @see SpecialPage::execute.
750 *
751 * @stable to override
752 * @since 1.20
753 *
754 * @param string|null $subPage
755 */
756 protected function afterExecute( $subPage ) {
757 // No-op
758 }
759
760 /**
761 * Default execute method
762 * Checks user permissions
763 *
764 * This must be overridden by subclasses; it will be made abstract in a future version
765 *
766 * @stable to override
767 *
768 * @param string|null $subPage
769 */
770 public function execute( $subPage ) {
771 $this->setHeaders();
772 $this->checkPermissions();
773 $securityLevel = $this->getLoginSecurityLevel();
774 if ( $securityLevel !== false && !$this->checkLoginSecurityLevel( $securityLevel ) ) {
775 return;
776 }
777 $this->outputHeader();
778 }
779
780 /**
781 * Outputs a summary message on top of special pages
782 * By default the message key is the canonical name of the special page
783 * May be overridden, i.e. by extensions to stick with the naming conventions
784 * for message keys: 'extensionname-xxx'
785 *
786 * @stable to override
787 *
788 * @param string $summaryMessageKey Message key of the summary
789 */
790 protected function outputHeader( $summaryMessageKey = '' ) {
791 if ( $summaryMessageKey == '' ) {
792 $msg = strtolower( $this->getName() ) . '-summary';
793 } else {
794 $msg = $summaryMessageKey;
795 }
796 if ( !$this->msg( $msg )->isDisabled() && !$this->including() ) {
797 $this->getOutput()->wrapWikiMsg(
798 "<div class='mw-specialpage-summary'>\n$1\n</div>", $msg );
799 }
800 }
801
802 /**
803 * Returns the name that goes in the \<h1\> in the special page itself, and
804 * also the name that will be listed in Special:Specialpages
805 *
806 * Derived classes can override this, but usually it is easier to keep the
807 * default behavior.
808 *
809 * Returning a string from this method has been deprecated since 1.41.
810 *
811 * @stable to override
812 *
813 * @return string|Message
814 */
815 public function getDescription() {
816 return $this->msg( strtolower( $this->mName ) );
817 }
818
819 /**
820 * Similar to getDescription, but takes into account subpages and designed for display
821 * in tabs.
822 *
823 * @since 1.39
824 * @stable to override if special page has complex parameter handling. Use default message keys
825 * where possible.
826 *
827 * @param string $path (optional)
828 * @return string
829 */
830 public function getShortDescription( string $path = '' ): string {
831 $lowerPath = strtolower( str_replace( '/', '-', $path ) );
832 $shortKey = 'special-tab-' . $lowerPath;
833 $shortKey .= '-short';
834 $msgShort = $this->msg( $shortKey );
835 return $msgShort->text();
836 }
837
838 /**
839 * Get a self-referential title object
840 *
841 * @param string|false|null $subpage
842 * @return Title
843 * @since 1.23
844 */
845 public function getPageTitle( $subpage = false ) {
846 return self::getTitleFor( $this->mName, $subpage );
847 }
848
849 /**
850 * Sets the context this SpecialPage is executed in
851 *
852 * @param IContextSource $context
853 * @since 1.18
854 */
855 public function setContext( $context ) {
856 $this->mContext = $context;
857 }
858
859 /**
860 * Gets the context this SpecialPage is executed in
861 *
862 * @return IContextSource|RequestContext
863 * @since 1.18
864 */
865 public function getContext() {
866 if ( !( $this->mContext instanceof IContextSource ) ) {
867 wfDebug( __METHOD__ . " called and \$mContext is null. " .
868 "Using RequestContext::getMain()" );
869
870 $this->mContext = RequestContext::getMain();
871 }
872 return $this->mContext;
873 }
874
875 /**
876 * Get the WebRequest being used for this instance
877 *
878 * @return WebRequest
879 * @since 1.18
880 */
881 public function getRequest() {
882 return $this->getContext()->getRequest();
883 }
884
885 /**
886 * Get the OutputPage being used for this instance
887 *
888 * @return OutputPage
889 * @since 1.18
890 */
891 public function getOutput() {
892 return $this->getContext()->getOutput();
893 }
894
895 /**
896 * Shortcut to get the User executing this instance
897 *
898 * @return User
899 * @since 1.18
900 */
901 public function getUser() {
902 return $this->getContext()->getUser();
903 }
904
905 /**
906 * Shortcut to get the Authority executing this instance
907 *
908 * @return Authority
909 * @since 1.36
910 */
911 public function getAuthority(): Authority {
912 return $this->getContext()->getAuthority();
913 }
914
915 /**
916 * Shortcut to get the skin being used for this instance
917 *
918 * @return Skin
919 * @since 1.18
920 */
921 public function getSkin() {
922 return $this->getContext()->getSkin();
923 }
924
925 /**
926 * Shortcut to get user's language
927 *
928 * @return Language
929 * @since 1.19
930 */
931 public function getLanguage() {
932 return $this->getContext()->getLanguage();
933 }
934
935 /**
936 * Shortcut to get content language
937 *
938 * @return Language
939 * @since 1.36
940 */
941 final public function getContentLanguage(): Language {
942 if ( $this->contentLanguage === null ) {
943 // Fallback if not provided
944 // TODO Change to wfWarn in a future release
945 $this->contentLanguage = MediaWikiServices::getInstance()->getContentLanguage();
946 }
947 return $this->contentLanguage;
948 }
949
950 /**
951 * Set content language
952 *
953 * @internal For factory only
954 * @param Language $contentLanguage
955 * @since 1.36
956 */
957 final public function setContentLanguage( Language $contentLanguage ) {
958 $this->contentLanguage = $contentLanguage;
959 }
960
961 /**
962 * Shortcut to get main config object
963 * @return Config
964 * @since 1.24
965 */
966 public function getConfig() {
967 return $this->getContext()->getConfig();
968 }
969
970 /**
971 * Return the full title, including $par
972 *
973 * @return Title
974 * @since 1.18
975 */
976 public function getFullTitle() {
977 return $this->getContext()->getTitle();
978 }
979
980 /**
981 * Return the robot policy. Derived classes that override this can change
982 * the robot policy set by setHeaders() from the default 'noindex,nofollow'.
983 *
984 * @return string
985 * @since 1.23
986 */
987 protected function getRobotPolicy() {
988 return 'noindex,nofollow';
989 }
990
991 /**
992 * Wrapper around wfMessage that sets the current context.
993 *
994 * @since 1.16
995 * @param string|string[]|MessageSpecifier $key
996 * @param mixed ...$params
997 * @return Message
998 * @see wfMessage
999 */
1000 public function msg( $key, ...$params ) {
1001 $message = $this->getContext()->msg( $key, ...$params );
1002 // RequestContext passes context to wfMessage, and the language is set from
1003 // the context, but setting the language for Message class removes the
1004 // interface message status, which breaks for example usernameless gender
1005 // invocations. Restore the flag when not including special page in content.
1006 if ( $this->including() ) {
1007 $message->setInterfaceMessageFlag( false );
1008 }
1009
1010 return $message;
1011 }
1012
1013 /**
1014 * Adds RSS/atom links
1015 *
1016 * @param array $params
1017 */
1018 protected function addFeedLinks( $params ) {
1019 $feedTemplate = wfScript( 'api' );
1020
1021 foreach ( $this->getConfig()->get( MainConfigNames::FeedClasses ) as $format => $class ) {
1022 $theseParams = $params + [ 'feedformat' => $format ];
1023 $url = wfAppendQuery( $feedTemplate, $theseParams );
1024 $this->getOutput()->addFeedLink( $format, $url );
1025 }
1026 }
1027
1028 /**
1029 * Adds help link with an icon via page indicators.
1030 * Link target can be overridden by a local message containing a wikilink:
1031 * the message key is: lowercase special page name + '-helppage'.
1032 * @param string $to Target MediaWiki.org page title or encoded URL.
1033 * @param bool $overrideBaseUrl Whether $url is a full URL, to avoid MW.o.
1034 * @since 1.25
1035 */
1036 public function addHelpLink( $to, $overrideBaseUrl = false ) {
1037 if ( $this->including() ) {
1038 return;
1039 }
1040
1041 $msg = $this->msg( strtolower( $this->getName() ) . '-helppage' );
1042
1043 if ( !$msg->isDisabled() ) {
1044 $title = Title::newFromText( $msg->plain() );
1045 if ( $title instanceof Title ) {
1046 $this->getOutput()->addHelpLink( $title->getLocalURL(), true );
1047 }
1048 } else {
1049 $this->getOutput()->addHelpLink( $to, $overrideBaseUrl );
1050 }
1051 }
1052
1053 /**
1054 * Get the group that the special page belongs in on Special:SpecialPage
1055 * Use this method, instead of getGroupName to allow customization
1056 * of the group name from the wiki side
1057 *
1058 * @return string Group of this special page
1059 * @since 1.21
1060 */
1061 public function getFinalGroupName() {
1062 $name = $this->getName();
1063
1064 // Allow overriding the group from the wiki side
1065 $msg = $this->msg( 'specialpages-specialpagegroup-' . strtolower( $name ) )->inContentLanguage();
1066 if ( !$msg->isBlank() ) {
1067 $group = $msg->text();
1068 } else {
1069 // Than use the group from this object
1070 $group = $this->getGroupName();
1071 }
1072
1073 return $group;
1074 }
1075
1076 /**
1077 * Indicates whether POST requests to this special page require write access to the wiki.
1078 *
1079 * Subclasses must override this method to return true if any of the operations that
1080 * they perform on POST requests are not "safe" per RFC 7231 section 4.2.1. A subclass's
1081 * operation is "safe" if it is essentially read-only, i.e. the client does not request
1082 * nor expect any state change that would be observable in the responses to future requests.
1083 *
1084 * Implementations of this method must always return the same value, regardless of the
1085 * parameters passed to the constructor or system state.
1086 *
1087 * When handling GET/HEAD requests, subclasses should only perform "safe" operations.
1088 * Note that some subclasses might only perform "safe" operations even for POST requests,
1089 * particularly in the case where large input parameters are required.
1090 *
1091 * @stable to override
1092 *
1093 * @return bool
1094 * @since 1.27
1095 */
1096 public function doesWrites() {
1097 return false;
1098 }
1099
1100 /**
1101 * Under which header this special page is listed in Special:SpecialPages
1102 * See messages 'specialpages-group-*' for valid names
1103 * This method defaults to group 'other'
1104 *
1105 * @stable to override
1106 *
1107 * @return string
1108 * @since 1.21
1109 */
1110 protected function getGroupName() {
1111 return 'other';
1112 }
1113
1114 /**
1115 * Call wfTransactionalTimeLimit() if this request was POSTed
1116 * @since 1.26
1117 */
1118 protected function useTransactionalTimeLimit() {
1119 if ( $this->getRequest()->wasPosted() ) {
1120 wfTransactionalTimeLimit();
1121 }
1122 }
1123
1124 /**
1125 * @since 1.28
1126 * @return LinkRenderer
1127 */
1128 public function getLinkRenderer(): LinkRenderer {
1129 if ( $this->linkRenderer === null ) {
1130 // TODO Inject the service
1131 $this->linkRenderer = MediaWikiServices::getInstance()->getLinkRendererFactory()
1132 ->create();
1133 }
1134 return $this->linkRenderer;
1135 }
1136
1137 /**
1138 * @since 1.28
1139 * @param LinkRenderer $linkRenderer
1140 */
1141 public function setLinkRenderer( LinkRenderer $linkRenderer ) {
1142 $this->linkRenderer = $linkRenderer;
1143 }
1144
1145 /**
1146 * Generate (prev x| next x) (20|50|100...) type links for paging
1147 *
1148 * @param int $offset
1149 * @param int $limit
1150 * @param array $query Optional URL query parameter string
1151 * @param bool $atend Optional param for specified if this is the last page
1152 * @param string|false $subpage Optional param for specifying subpage
1153 * @return string
1154 */
1155 protected function buildPrevNextNavigation(
1156 $offset,
1157 $limit,
1158 array $query = [],
1159 $atend = false,
1160 $subpage = false
1161 ) {
1162 $navBuilder = new PagerNavigationBuilder( $this );
1163 $navBuilder
1164 ->setPage( $this->getPageTitle( $subpage ) )
1165 ->setLinkQuery( [ 'limit' => $limit, 'offset' => $offset ] + $query )
1166 ->setLimitLinkQueryParam( 'limit' )
1167 ->setCurrentLimit( $limit )
1168 ->setPrevTooltipMsg( 'prevn-title' )
1169 ->setNextTooltipMsg( 'nextn-title' )
1170 ->setLimitTooltipMsg( 'shown-title' );
1171
1172 if ( $offset > 0 ) {
1173 $navBuilder->setPrevLinkQuery( [ 'offset' => (string)max( $offset - $limit, 0 ) ] );
1174 }
1175 if ( !$atend ) {
1176 $navBuilder->setNextLinkQuery( [ 'offset' => (string)( $offset + $limit ) ] );
1177 }
1178
1179 return $navBuilder->getHtml();
1180 }
1181
1182 /**
1183 * @since 1.35
1184 * @internal
1185 * @param HookContainer $hookContainer
1186 */
1187 public function setHookContainer( HookContainer $hookContainer ) {
1188 $this->hookContainer = $hookContainer;
1189 $this->hookRunner = new HookRunner( $hookContainer );
1190 }
1191
1192 /**
1193 * @since 1.35
1194 * @return HookContainer
1195 */
1196 protected function getHookContainer() {
1197 if ( !$this->hookContainer ) {
1198 $this->hookContainer = MediaWikiServices::getInstance()->getHookContainer();
1199 }
1200 return $this->hookContainer;
1201 }
1202
1203 /**
1204 * @internal This is for use by core only. Hook interfaces may be removed
1205 * without notice.
1206 * @since 1.35
1207 * @return HookRunner
1208 */
1209 protected function getHookRunner() {
1210 if ( !$this->hookRunner ) {
1211 $this->hookRunner = new HookRunner( $this->getHookContainer() );
1212 }
1213 return $this->hookRunner;
1214 }
1215
1216 /**
1217 * @internal For factory only
1218 * @since 1.36
1219 * @param SpecialPageFactory $specialPageFactory
1220 */
1221 final public function setSpecialPageFactory( SpecialPageFactory $specialPageFactory ) {
1222 $this->specialPageFactory = $specialPageFactory;
1223 }
1224
1225 /**
1226 * @since 1.36
1227 * @return SpecialPageFactory
1228 */
1229 final protected function getSpecialPageFactory(): SpecialPageFactory {
1230 if ( !$this->specialPageFactory ) {
1231 // Fallback if not provided
1232 // TODO Change to wfWarn in a future release
1233 $this->specialPageFactory = MediaWikiServices::getInstance()->getSpecialPageFactory();
1234 }
1235 return $this->specialPageFactory;
1236 }
1237 }
1238
1239 /** @deprecated class alias since 1.41 */
1240 class_alias( SpecialPage::class, 'SpecialPage' );