3 * Factory for handling the special page list and generating SpecialPage objects.
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
21 * @ingroup SpecialPage
22 * @defgroup SpecialPage SpecialPage
24 use MediaWiki\Linker\LinkRenderer
;
25 use MediaWiki\MediaWikiServices
;
26 use Wikimedia\ObjectFactory
;
29 * Factory for handling the special page list and generating SpecialPage objects.
31 * To add a special page in an extension, add to $wgSpecialPages either
32 * an object instance or an array containing the name and constructor
33 * parameters. The latter is preferred for performance reasons.
35 * The object instantiated must be either an instance of SpecialPage or a
36 * sub-class thereof. It must have an execute() method, which sends the HTML
37 * for the special page to $wgOut. The parent class has an execute() method
38 * which distributes the call to the historical global functions. Additionally,
39 * execute() also checks if the user has the necessary access privileges
40 * and bails out if not.
42 * To add a core special page, use the similar static list in
43 * SpecialPageFactory::$list. To remove a core static special page at runtime, use
44 * a SpecialPage_initList hook.
46 * @ingroup SpecialPage
49 class SpecialPageFactory
{
51 * List of special page names to the subclass of SpecialPage which handles them.
53 private static $coreList = [
54 // Maintenance Reports
55 'BrokenRedirects' => BrokenRedirectsPage
::class,
56 'Deadendpages' => DeadendPagesPage
::class,
57 'DoubleRedirects' => DoubleRedirectsPage
::class,
58 'Longpages' => LongPagesPage
::class,
59 'Ancientpages' => AncientPagesPage
::class,
60 'Lonelypages' => LonelyPagesPage
::class,
61 'Fewestrevisions' => FewestrevisionsPage
::class,
62 'Withoutinterwiki' => WithoutInterwikiPage
::class,
63 'Protectedpages' => SpecialProtectedpages
::class,
64 'Protectedtitles' => SpecialProtectedtitles
::class,
65 'Shortpages' => ShortPagesPage
::class,
66 'Uncategorizedcategories' => UncategorizedCategoriesPage
::class,
67 'Uncategorizedimages' => UncategorizedImagesPage
::class,
68 'Uncategorizedpages' => UncategorizedPagesPage
::class,
69 'Uncategorizedtemplates' => UncategorizedTemplatesPage
::class,
70 'Unusedcategories' => UnusedCategoriesPage
::class,
71 'Unusedimages' => UnusedimagesPage
::class,
72 'Unusedtemplates' => UnusedtemplatesPage
::class,
73 'Unwatchedpages' => UnwatchedpagesPage
::class,
74 'Wantedcategories' => WantedCategoriesPage
::class,
75 'Wantedfiles' => WantedFilesPage
::class,
76 'Wantedpages' => WantedPagesPage
::class,
77 'Wantedtemplates' => WantedTemplatesPage
::class,
80 'Allpages' => SpecialAllPages
::class,
81 'Prefixindex' => SpecialPrefixindex
::class,
82 'Categories' => SpecialCategories
::class,
83 'Listredirects' => ListredirectsPage
::class,
84 'PagesWithProp' => SpecialPagesWithProp
::class,
85 'TrackingCategories' => SpecialTrackingCategories
::class,
88 'Userlogin' => SpecialUserLogin
::class,
89 'Userlogout' => SpecialUserLogout
::class,
90 'CreateAccount' => SpecialCreateAccount
::class,
91 'LinkAccounts' => SpecialLinkAccounts
::class,
92 'UnlinkAccounts' => SpecialUnlinkAccounts
::class,
93 'ChangeCredentials' => SpecialChangeCredentials
::class,
94 'RemoveCredentials' => SpecialRemoveCredentials
::class,
97 'Activeusers' => SpecialActiveUsers
::class,
98 'Block' => SpecialBlock
::class,
99 'Unblock' => SpecialUnblock
::class,
100 'BlockList' => SpecialBlockList
::class,
101 'AutoblockList' => SpecialAutoblockList
::class,
102 'ChangePassword' => SpecialChangePassword
::class,
103 'BotPasswords' => SpecialBotPasswords
::class,
104 'PasswordReset' => SpecialPasswordReset
::class,
105 'DeletedContributions' => DeletedContributionsPage
::class,
106 'Preferences' => SpecialPreferences
::class,
107 'ResetTokens' => SpecialResetTokens
::class,
108 'Contributions' => SpecialContributions
::class,
109 'Listgrouprights' => SpecialListGroupRights
::class,
110 'Listgrants' => SpecialListGrants
::class,
111 'Listusers' => SpecialListUsers
::class,
112 'Listadmins' => SpecialListAdmins
::class,
113 'Listbots' => SpecialListBots
::class,
114 'Userrights' => UserrightsPage
::class,
115 'EditWatchlist' => SpecialEditWatchlist
::class,
116 'PasswordPolicies' => SpecialPasswordPolicies
::class,
118 // Recent changes and logs
119 'Newimages' => SpecialNewFiles
::class,
120 'Log' => SpecialLog
::class,
121 'Watchlist' => SpecialWatchlist
::class,
122 'Newpages' => SpecialNewpages
::class,
123 'Recentchanges' => SpecialRecentChanges
::class,
124 'Recentchangeslinked' => SpecialRecentChangesLinked
::class,
125 'Tags' => SpecialTags
::class,
127 // Media reports and uploads
128 'Listfiles' => SpecialListFiles
::class,
129 'Filepath' => SpecialFilepath
::class,
130 'MediaStatistics' => MediaStatisticsPage
::class,
131 'MIMEsearch' => MIMEsearchPage
::class,
132 'FileDuplicateSearch' => FileDuplicateSearchPage
::class,
133 'Upload' => SpecialUpload
::class,
134 'UploadStash' => SpecialUploadStash
::class,
135 'ListDuplicatedFiles' => ListDuplicatedFilesPage
::class,
138 'ApiSandbox' => SpecialApiSandbox
::class,
139 'Statistics' => SpecialStatistics
::class,
140 'Allmessages' => SpecialAllMessages
::class,
141 'Version' => SpecialVersion
::class,
142 'Lockdb' => SpecialLockdb
::class,
143 'Unlockdb' => SpecialUnlockdb
::class,
145 // Redirecting special pages
146 'LinkSearch' => LinkSearchPage
::class,
147 'Randompage' => RandomPage
::class,
148 'RandomInCategory' => SpecialRandomInCategory
::class,
149 'Randomredirect' => SpecialRandomredirect
::class,
150 'Randomrootpage' => SpecialRandomrootpage
::class,
151 'GoToInterwiki' => SpecialGoToInterwiki
::class,
154 'Mostlinkedcategories' => MostlinkedCategoriesPage
::class,
155 'Mostimages' => MostimagesPage
::class,
156 'Mostinterwikis' => MostinterwikisPage
::class,
157 'Mostlinked' => MostlinkedPage
::class,
158 'Mostlinkedtemplates' => MostlinkedTemplatesPage
::class,
159 'Mostcategories' => MostcategoriesPage
::class,
160 'Mostrevisions' => MostrevisionsPage
::class,
163 'ComparePages' => SpecialComparePages
::class,
164 'Export' => SpecialExport
::class,
165 'Import' => SpecialImport
::class,
166 'Undelete' => SpecialUndelete
::class,
167 'Whatlinkshere' => SpecialWhatLinksHere
::class,
168 'MergeHistory' => SpecialMergeHistory
::class,
169 'ExpandTemplates' => SpecialExpandTemplates
::class,
172 'Booksources' => SpecialBookSources
::class,
174 // Unlisted / redirects
175 'ApiHelp' => SpecialApiHelp
::class,
176 'Blankpage' => SpecialBlankpage
::class,
177 'Diff' => SpecialDiff
::class,
178 'EditTags' => SpecialEditTags
::class,
179 'Emailuser' => SpecialEmailUser
::class,
180 'Movepage' => MovePageForm
::class,
181 'Mycontributions' => SpecialMycontributions
::class,
182 'MyLanguage' => SpecialMyLanguage
::class,
183 'Mypage' => SpecialMypage
::class,
184 'Mytalk' => SpecialMytalk
::class,
185 'Myuploads' => SpecialMyuploads
::class,
186 'AllMyUploads' => SpecialAllMyUploads
::class,
187 'PermanentLink' => SpecialPermanentLink
::class,
188 'Redirect' => SpecialRedirect
::class,
189 'Revisiondelete' => SpecialRevisionDelete
::class,
190 'RunJobs' => SpecialRunJobs
::class,
191 'Specialpages' => SpecialSpecialpages
::class,
192 'PageData' => SpecialPageData
::class,
195 private static $list;
196 private static $aliases;
199 * Reset the internal list of special pages. Useful when changing $wgSpecialPages after
200 * the internal list has already been initialized, e.g. during testing.
202 public static function resetList() {
204 self
::$aliases = null;
208 * Returns a list of canonical special page names.
209 * May be used to iterate over all registered special pages.
213 public static function getNames() {
214 return array_keys( self
::getPageList() );
218 * Get the special page list as an array
222 private static function getPageList() {
223 global $wgSpecialPages;
224 global $wgDisableInternalSearch, $wgEmailAuthentication;
225 global $wgEnableEmail, $wgEnableJavaScriptTest;
226 global $wgPageLanguageUseDB, $wgContentHandlerUseDB;
228 if ( !is_array( self
::$list ) ) {
229 self
::$list = self
::$coreList;
231 if ( !$wgDisableInternalSearch ) {
232 self
::$list['Search'] = SpecialSearch
::class;
235 if ( $wgEmailAuthentication ) {
236 self
::$list['Confirmemail'] = EmailConfirmation
::class;
237 self
::$list['Invalidateemail'] = EmailInvalidation
::class;
240 if ( $wgEnableEmail ) {
241 self
::$list['ChangeEmail'] = SpecialChangeEmail
::class;
244 if ( $wgEnableJavaScriptTest ) {
245 self
::$list['JavaScriptTest'] = SpecialJavaScriptTest
::class;
248 if ( $wgPageLanguageUseDB ) {
249 self
::$list['PageLanguage'] = SpecialPageLanguage
::class;
251 if ( $wgContentHandlerUseDB ) {
252 self
::$list['ChangeContentModel'] = SpecialChangeContentModel
::class;
255 // Add extension special pages
256 self
::$list = array_merge( self
::$list, $wgSpecialPages );
258 // This hook can be used to disable unwanted core special pages
259 // or conditionally register special pages.
260 Hooks
::run( 'SpecialPage_initList', [ &self
::$list ] );
268 * Initialise and return the list of special page aliases. Returns an array where
269 * the key is an alias, and the value is the canonical name of the special page.
270 * All registered special pages are guaranteed to map to themselves.
273 private static function getAliasList() {
274 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
275 if ( is_null( self
::$aliases ) ) {
276 $aliases = $contLang->getSpecialPageAliases();
277 $pageList = self
::getPageList();
282 // Force every canonical name to be an alias for itself.
283 foreach ( $pageList as $name => $stuff ) {
284 $caseFoldedAlias = $contLang->caseFold( $name );
285 self
::$aliases[$caseFoldedAlias] = $name;
286 $keepAlias[$caseFoldedAlias] = 'canonical';
289 // Check for $aliases being an array since Language::getSpecialPageAliases can return null
290 if ( is_array( $aliases ) ) {
291 foreach ( $aliases as $realName => $aliasList ) {
292 $aliasList = array_values( $aliasList );
293 foreach ( $aliasList as $i => $alias ) {
294 $caseFoldedAlias = $contLang->caseFold( $alias );
296 if ( isset( self
::$aliases[$caseFoldedAlias] ) &&
297 $realName === self
::$aliases[$caseFoldedAlias]
299 // Ignore same-realName conflicts
303 if ( !isset( $keepAlias[$caseFoldedAlias] ) ) {
304 self
::$aliases[$caseFoldedAlias] = $realName;
306 $keepAlias[$caseFoldedAlias] = 'first';
309 wfWarn( "First alias '$alias' for $realName conflicts with " .
310 "{$keepAlias[$caseFoldedAlias]} alias for " .
311 self
::$aliases[$caseFoldedAlias]
319 return self
::$aliases;
323 * Given a special page name with a possible subpage, return an array
324 * where the first element is the special page name and the second is the
327 * @param string $alias
328 * @return array Array( String, String|null ), or array( null, null ) if the page is invalid
330 public static function resolveAlias( $alias ) {
331 $bits = explode( '/', $alias, 2 );
333 $caseFoldedAlias = MediaWikiServices
::getInstance()->getContentLanguage()->
334 caseFold( $bits[0] );
335 $caseFoldedAlias = str_replace( ' ', '_', $caseFoldedAlias );
336 $aliases = self
::getAliasList();
337 if ( isset( $aliases[$caseFoldedAlias] ) ) {
338 $name = $aliases[$caseFoldedAlias];
340 return [ null, null ];
343 if ( !isset( $bits[1] ) ) { // T4087
349 return [ $name, $par ];
353 * Check if a given name exist as a special page or as a special page alias
355 * @param string $name Name of a special page
356 * @return bool True if a special page exists with this name
358 public static function exists( $name ) {
359 list( $title, /*...*/ ) = self
::resolveAlias( $name );
361 $specialPageList = self
::getPageList();
362 return isset( $specialPageList[$title] );
366 * Find the object with a given name and return it (or NULL)
368 * @param string $name Special page name, may be localised and/or an alias
369 * @return SpecialPage|null SpecialPage object or null if the page doesn't exist
371 public static function getPage( $name ) {
372 list( $realName, /*...*/ ) = self
::resolveAlias( $name );
374 $specialPageList = self
::getPageList();
376 if ( isset( $specialPageList[$realName] ) ) {
377 $rec = $specialPageList[$realName];
379 if ( is_callable( $rec ) ) {
380 // Use callback to instantiate the special page
381 $page = call_user_func( $rec );
382 } elseif ( is_string( $rec ) ) {
384 $page = new $className;
385 } elseif ( is_array( $rec ) ) {
386 $className = array_shift( $rec );
387 // @deprecated, officially since 1.18, unofficially since forever
388 wfDeprecated( "Array syntax for \$wgSpecialPages is deprecated ($className), " .
389 "define a subclass of SpecialPage instead.", '1.18' );
390 $page = ObjectFactory
::getObjectFromSpec( [
391 'class' => $className,
393 'closure_expansion' => false,
395 } elseif ( $rec instanceof SpecialPage
) {
396 $page = $rec; // XXX: we should deep clone here
401 if ( $page instanceof SpecialPage
) {
404 // It's not a classname, nor a callback, nor a legacy constructor array,
405 // nor a special page object. Give up.
406 wfLogWarning( "Cannot instantiate special page $realName: bad spec!" );
416 * Return categorised listable special pages which are available
417 * for the current user, and everyone.
419 * @param User|null $user User object to check permissions, $wgUser will be used
421 * @return array ( string => Specialpage )
423 public static function getUsablePages( User
$user = null ) {
425 if ( $user === null ) {
429 foreach ( self
::getPageList() as $name => $rec ) {
430 $page = self
::getPage( $name );
431 if ( $page ) { // not null
432 $page->setContext( RequestContext
::getMain() );
433 if ( $page->isListed()
434 && ( !$page->isRestricted() ||
$page->userCanExecute( $user ) )
436 $pages[$name] = $page;
445 * Return categorised listable special pages for all users
447 * @return array ( string => Specialpage )
449 public static function getRegularPages() {
451 foreach ( self
::getPageList() as $name => $rec ) {
452 $page = self
::getPage( $name );
453 if ( $page && $page->isListed() && !$page->isRestricted() ) {
454 $pages[$name] = $page;
462 * Return categorised listable special pages which are available
463 * for the current user, but not for everyone
465 * @param User|null $user User object to use or null for $wgUser
466 * @return array ( string => Specialpage )
468 public static function getRestrictedPages( User
$user = null ) {
470 if ( $user === null ) {
474 foreach ( self
::getPageList() as $name => $rec ) {
475 $page = self
::getPage( $name );
478 && $page->isRestricted()
479 && $page->userCanExecute( $user )
481 $pages[$name] = $page;
489 * Execute a special page path.
490 * The path may contain parameters, e.g. Special:Name/Params
491 * Extracts the special page name and call the execute method, passing the parameters
493 * Returns a title object if the page is redirected, false if there was no such special
494 * page, and true if it was successful.
496 * @param Title &$title
497 * @param IContextSource &$context
498 * @param bool $including Bool output is being captured for use in {{special:whatever}}
499 * @param LinkRenderer|null $linkRenderer (since 1.28)
503 public static function executePath( Title
&$title, IContextSource
&$context, $including = false,
504 LinkRenderer
$linkRenderer = null
506 // @todo FIXME: Redirects broken due to this call
507 $bits = explode( '/', $title->getDBkey(), 2 );
509 if ( !isset( $bits[1] ) ) { // T4087
515 $page = self
::getPage( $name );
517 $context->getOutput()->setArticleRelated( false );
518 $context->getOutput()->setRobotPolicy( 'noindex,nofollow' );
520 global $wgSend404Code;
521 if ( $wgSend404Code ) {
522 $context->getOutput()->setStatusCode( 404 );
525 $context->getOutput()->showErrorPage( 'nosuchspecialpage', 'nospecialpagetext' );
531 // Narrow DB query expectations for this HTTP request
532 $trxLimits = $context->getConfig()->get( 'TrxProfilerLimits' );
533 $trxProfiler = Profiler
::instance()->getTransactionProfiler();
534 if ( $context->getRequest()->wasPosted() && !$page->doesWrites() ) {
535 $trxProfiler->setExpectations( $trxLimits['POST-nonwrite'], __METHOD__
);
536 $context->getRequest()->markAsSafeRequest();
540 // Page exists, set the context
541 $page->setContext( $context );
544 // Redirect to canonical alias for GET commands
545 // Not for POST, we'd lose the post data, so it's best to just distribute
546 // the request. Such POST requests are possible for old extensions that
547 // generate self-links without being aware that their default name has
549 if ( $name != $page->getLocalName() && !$context->getRequest()->wasPosted() ) {
550 $query = $context->getRequest()->getQueryValues();
551 unset( $query['title'] );
552 $title = $page->getPageTitle( $par );
553 $url = $title->getFullURL( $query );
554 $context->getOutput()->redirect( $url );
558 $context->setTitle( $page->getPageTitle( $par ) );
560 } elseif ( !$page->isIncludable() ) {
564 $page->including( $including );
565 if ( $linkRenderer ) {
566 $page->setLinkRenderer( $linkRenderer );
569 // Execute special page
576 * Just like executePath() but will override global variables and execute
577 * the page in "inclusion" mode. Returns true if the execution was
578 * successful or false if there was no such special page, or a title object
579 * if it was a redirect.
581 * Also saves the current $wgTitle, $wgOut, $wgRequest, $wgUser and $wgLang
582 * variables so that the special page will get the context it'd expect on a
583 * normal request, and then restores them to their previous values after.
585 * @param Title $title
586 * @param IContextSource $context
587 * @param LinkRenderer|null $linkRenderer (since 1.28)
588 * @return string HTML fragment
590 public static function capturePath(
591 Title
$title, IContextSource
$context, LinkRenderer
$linkRenderer = null
593 global $wgTitle, $wgOut, $wgRequest, $wgUser, $wgLang;
594 $main = RequestContext
::getMain();
596 // Save current globals and main context
600 'request' => $wgRequest,
602 'language' => $wgLang,
605 'title' => $main->getTitle(),
606 'output' => $main->getOutput(),
607 'request' => $main->getRequest(),
608 'user' => $main->getUser(),
609 'language' => $main->getLanguage(),
614 $wgOut = $context->getOutput();
615 $wgRequest = $context->getRequest();
616 $wgUser = $context->getUser();
617 $wgLang = $context->getLanguage();
618 $main->setTitle( $title );
619 $main->setOutput( $context->getOutput() );
620 $main->setRequest( $context->getRequest() );
621 $main->setUser( $context->getUser() );
622 $main->setLanguage( $context->getLanguage() );
625 $ret = self
::executePath( $title, $context, true, $linkRenderer );
627 // Restore old globals and context
628 $wgTitle = $glob['title'];
629 $wgOut = $glob['output'];
630 $wgRequest = $glob['request'];
631 $wgUser = $glob['user'];
632 $wgLang = $glob['language'];
633 $main->setTitle( $ctx['title'] );
634 $main->setOutput( $ctx['output'] );
635 $main->setRequest( $ctx['request'] );
636 $main->setUser( $ctx['user'] );
637 $main->setLanguage( $ctx['language'] );
643 * Get the local name for a specified canonical name
645 * @param string $name
646 * @param string|bool $subpage
649 public static function getLocalNameFor( $name, $subpage = false ) {
650 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
651 $aliases = $contLang->getSpecialPageAliases();
652 $aliasList = self
::getAliasList();
654 // Find the first alias that maps back to $name
655 if ( isset( $aliases[$name] ) ) {
657 foreach ( $aliases[$name] as $alias ) {
658 $caseFoldedAlias = $contLang->caseFold( $alias );
659 $caseFoldedAlias = str_replace( ' ', '_', $caseFoldedAlias );
660 if ( isset( $aliasList[$caseFoldedAlias] ) &&
661 $aliasList[$caseFoldedAlias] === $name
669 wfWarn( "Did not find a usable alias for special page '$name'. " .
670 "It seems all defined aliases conflict?" );
673 // Check if someone misspelled the correct casing
674 if ( is_array( $aliases ) ) {
675 foreach ( $aliases as $n => $values ) {
676 if ( strcasecmp( $name, $n ) === 0 ) {
677 wfWarn( "Found alias defined for $n when searching for " .
678 "special page aliases for $name. Case mismatch?" );
679 return self
::getLocalNameFor( $n, $subpage );
684 wfWarn( "Did not find alias for special page '$name'. " .
685 "Perhaps no aliases are defined for it?" );
688 if ( $subpage !== false && !is_null( $subpage ) ) {
689 // Make sure it's in dbkey form
690 $subpage = str_replace( ' ', '_', $subpage );
691 $name = "$name/$subpage";
694 return $contLang->ucfirst( $name );
698 * Get a title for a given alias
700 * @param string $alias
701 * @return Title|null Title or null if there is no such alias
703 public static function getTitleForAlias( $alias ) {
704 list( $name, $subpage ) = self
::resolveAlias( $alias );
705 if ( $name != null ) {
706 return SpecialPage
::getTitleFor( $name, $subpage );