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
;
27 * Factory for handling the special page list and generating SpecialPage objects.
29 * To add a special page in an extension, add to $wgSpecialPages either
30 * an object instance or an array containing the name and constructor
31 * parameters. The latter is preferred for performance reasons.
33 * The object instantiated must be either an instance of SpecialPage or a
34 * sub-class thereof. It must have an execute() method, which sends the HTML
35 * for the special page to $wgOut. The parent class has an execute() method
36 * which distributes the call to the historical global functions. Additionally,
37 * execute() also checks if the user has the necessary access privileges
38 * and bails out if not.
40 * To add a core special page, use the similar static list in
41 * SpecialPageFactory::$list. To remove a core static special page at runtime, use
42 * a SpecialPage_initList hook.
44 * @ingroup SpecialPage
47 class SpecialPageFactory
{
49 * List of special page names to the subclass of SpecialPage which handles them.
51 private static $coreList = [
52 // Maintenance Reports
53 'BrokenRedirects' => 'BrokenRedirectsPage',
54 'Deadendpages' => 'DeadendPagesPage',
55 'DoubleRedirects' => 'DoubleRedirectsPage',
56 'Longpages' => 'LongPagesPage',
57 'Ancientpages' => 'AncientPagesPage',
58 'Lonelypages' => 'LonelyPagesPage',
59 'Fewestrevisions' => 'FewestrevisionsPage',
60 'Withoutinterwiki' => 'WithoutInterwikiPage',
61 'Protectedpages' => 'SpecialProtectedpages',
62 'Protectedtitles' => 'SpecialProtectedtitles',
63 'Shortpages' => 'ShortPagesPage',
64 'Uncategorizedcategories' => 'UncategorizedCategoriesPage',
65 'Uncategorizedimages' => 'UncategorizedImagesPage',
66 'Uncategorizedpages' => 'UncategorizedPagesPage',
67 'Uncategorizedtemplates' => 'UncategorizedTemplatesPage',
68 'Unusedcategories' => 'UnusedCategoriesPage',
69 'Unusedimages' => 'UnusedimagesPage',
70 'Unusedtemplates' => 'UnusedtemplatesPage',
71 'Unwatchedpages' => 'UnwatchedpagesPage',
72 'Wantedcategories' => 'WantedCategoriesPage',
73 'Wantedfiles' => 'WantedFilesPage',
74 'Wantedpages' => 'WantedPagesPage',
75 'Wantedtemplates' => 'WantedTemplatesPage',
78 'Allpages' => 'SpecialAllPages',
79 'Prefixindex' => 'SpecialPrefixindex',
80 'Categories' => 'SpecialCategories',
81 'Listredirects' => 'ListredirectsPage',
82 'PagesWithProp' => 'SpecialPagesWithProp',
83 'TrackingCategories' => 'SpecialTrackingCategories',
86 'Userlogin' => 'SpecialUserLogin',
87 'Userlogout' => 'SpecialUserLogout',
88 'CreateAccount' => 'SpecialCreateAccount',
89 'LinkAccounts' => 'SpecialLinkAccounts',
90 'UnlinkAccounts' => 'SpecialUnlinkAccounts',
91 'ChangeCredentials' => 'SpecialChangeCredentials',
92 'RemoveCredentials' => 'SpecialRemoveCredentials',
95 'Activeusers' => 'SpecialActiveUsers',
96 'Block' => 'SpecialBlock',
97 'Unblock' => 'SpecialUnblock',
98 'BlockList' => 'SpecialBlockList',
99 'AutoblockList' => 'SpecialAutoblockList',
100 'ChangePassword' => 'SpecialChangePassword',
101 'BotPasswords' => 'SpecialBotPasswords',
102 'PasswordReset' => 'SpecialPasswordReset',
103 'DeletedContributions' => 'DeletedContributionsPage',
104 'Preferences' => 'SpecialPreferences',
105 'ResetTokens' => 'SpecialResetTokens',
106 'Contributions' => 'SpecialContributions',
107 'Listgrouprights' => 'SpecialListGroupRights',
108 'Listgrants' => 'SpecialListGrants',
109 'Listusers' => 'SpecialListUsers',
110 'Listadmins' => 'SpecialListAdmins',
111 'Listbots' => 'SpecialListBots',
112 'Userrights' => 'UserrightsPage',
113 'EditWatchlist' => 'SpecialEditWatchlist',
115 // Recent changes and logs
116 'Newimages' => 'SpecialNewFiles',
117 'Log' => 'SpecialLog',
118 'Watchlist' => 'SpecialWatchlist',
119 'Newpages' => 'SpecialNewpages',
120 'Recentchanges' => 'SpecialRecentChanges',
121 'Recentchangeslinked' => 'SpecialRecentChangesLinked',
122 'Tags' => 'SpecialTags',
124 // Media reports and uploads
125 'Listfiles' => 'SpecialListFiles',
126 'Filepath' => 'SpecialFilepath',
127 'MediaStatistics' => 'MediaStatisticsPage',
128 'MIMEsearch' => 'MIMEsearchPage',
129 'FileDuplicateSearch' => 'FileDuplicateSearchPage',
130 'Upload' => 'SpecialUpload',
131 'UploadStash' => 'SpecialUploadStash',
132 'ListDuplicatedFiles' => 'ListDuplicatedFilesPage',
135 'ApiSandbox' => 'SpecialApiSandbox',
136 'Statistics' => 'SpecialStatistics',
137 'Allmessages' => 'SpecialAllMessages',
138 'Version' => 'SpecialVersion',
139 'Lockdb' => 'SpecialLockdb',
140 'Unlockdb' => 'SpecialUnlockdb',
142 // Redirecting special pages
143 'LinkSearch' => 'LinkSearchPage',
144 'Randompage' => 'RandomPage',
145 'RandomInCategory' => 'SpecialRandomInCategory',
146 'Randomredirect' => 'SpecialRandomredirect',
147 'Randomrootpage' => 'SpecialRandomrootpage',
148 'GoToInterwiki' => 'SpecialGoToInterwiki',
151 'Mostlinkedcategories' => 'MostlinkedCategoriesPage',
152 'Mostimages' => 'MostimagesPage',
153 'Mostinterwikis' => 'MostinterwikisPage',
154 'Mostlinked' => 'MostlinkedPage',
155 'Mostlinkedtemplates' => 'MostlinkedTemplatesPage',
156 'Mostcategories' => 'MostcategoriesPage',
157 'Mostrevisions' => 'MostrevisionsPage',
160 'ComparePages' => 'SpecialComparePages',
161 'Export' => 'SpecialExport',
162 'Import' => 'SpecialImport',
163 'Undelete' => 'SpecialUndelete',
164 'Whatlinkshere' => 'SpecialWhatLinksHere',
165 'MergeHistory' => 'SpecialMergeHistory',
166 'ExpandTemplates' => 'SpecialExpandTemplates',
169 'Booksources' => 'SpecialBookSources',
171 // Unlisted / redirects
172 'ApiHelp' => 'SpecialApiHelp',
173 'Blankpage' => 'SpecialBlankpage',
174 'Diff' => 'SpecialDiff',
175 'EditTags' => 'SpecialEditTags',
176 'Emailuser' => 'SpecialEmailUser',
177 'Movepage' => 'MovePageForm',
178 'Mycontributions' => 'SpecialMycontributions',
179 'MyLanguage' => 'SpecialMyLanguage',
180 'Mypage' => 'SpecialMypage',
181 'Mytalk' => 'SpecialMytalk',
182 'Myuploads' => 'SpecialMyuploads',
183 'AllMyUploads' => 'SpecialAllMyUploads',
184 'PermanentLink' => 'SpecialPermanentLink',
185 'Redirect' => 'SpecialRedirect',
186 'Revisiondelete' => 'SpecialRevisionDelete',
187 'RunJobs' => 'SpecialRunJobs',
188 'Specialpages' => 'SpecialSpecialpages',
189 'PageData' => 'SpecialPageData'
192 private static $list;
193 private static $aliases;
196 * Reset the internal list of special pages. Useful when changing $wgSpecialPages after
197 * the internal list has already been initialized, e.g. during testing.
199 public static function resetList() {
201 self
::$aliases = null;
205 * Returns a list of canonical special page names.
206 * May be used to iterate over all registered special pages.
210 public static function getNames() {
211 return array_keys( self
::getPageList() );
215 * Get the special page list as an array
217 * @deprecated since 1.24, use getNames() instead.
220 public static function getList() {
221 wfDeprecated( __FUNCTION__
, '1.24' );
222 return self
::getPageList();
226 * Get the special page list as an array
230 private static function getPageList() {
231 global $wgSpecialPages;
232 global $wgDisableInternalSearch, $wgEmailAuthentication;
233 global $wgEnableEmail, $wgEnableJavaScriptTest;
234 global $wgPageLanguageUseDB, $wgContentHandlerUseDB;
236 if ( !is_array( self
::$list ) ) {
238 self
::$list = self
::$coreList;
240 if ( !$wgDisableInternalSearch ) {
241 self
::$list['Search'] = 'SpecialSearch';
244 if ( $wgEmailAuthentication ) {
245 self
::$list['Confirmemail'] = 'EmailConfirmation';
246 self
::$list['Invalidateemail'] = 'EmailInvalidation';
249 if ( $wgEnableEmail ) {
250 self
::$list['ChangeEmail'] = 'SpecialChangeEmail';
253 if ( $wgEnableJavaScriptTest ) {
254 self
::$list['JavaScriptTest'] = 'SpecialJavaScriptTest';
257 if ( $wgPageLanguageUseDB ) {
258 self
::$list['PageLanguage'] = 'SpecialPageLanguage';
260 if ( $wgContentHandlerUseDB ) {
261 self
::$list['ChangeContentModel'] = 'SpecialChangeContentModel';
264 // Add extension special pages
265 self
::$list = array_merge( self
::$list, $wgSpecialPages );
267 // This hook can be used to disable unwanted core special pages
268 // or conditionally register special pages.
269 Hooks
::run( 'SpecialPage_initList', [ &self
::$list ] );
277 * Initialise and return the list of special page aliases. Returns an array where
278 * the key is an alias, and the value is the canonical name of the special page.
279 * All registered special pages are guaranteed to map to themselves.
282 private static function getAliasList() {
283 if ( is_null( self
::$aliases ) ) {
285 $aliases = $wgContLang->getSpecialPageAliases();
286 $pageList = self
::getPageList();
291 // Force every canonical name to be an alias for itself.
292 foreach ( $pageList as $name => $stuff ) {
293 $caseFoldedAlias = $wgContLang->caseFold( $name );
294 self
::$aliases[$caseFoldedAlias] = $name;
295 $keepAlias[$caseFoldedAlias] = 'canonical';
298 // Check for $aliases being an array since Language::getSpecialPageAliases can return null
299 if ( is_array( $aliases ) ) {
300 foreach ( $aliases as $realName => $aliasList ) {
301 $aliasList = array_values( $aliasList );
302 foreach ( $aliasList as $i => $alias ) {
303 $caseFoldedAlias = $wgContLang->caseFold( $alias );
305 if ( isset( self
::$aliases[$caseFoldedAlias] ) &&
306 $realName === self
::$aliases[$caseFoldedAlias]
308 // Ignore same-realName conflicts
312 if ( !isset( $keepAlias[$caseFoldedAlias] ) ) {
313 self
::$aliases[$caseFoldedAlias] = $realName;
315 $keepAlias[$caseFoldedAlias] = 'first';
318 wfWarn( "First alias '$alias' for $realName conflicts with " .
319 "{$keepAlias[$caseFoldedAlias]} alias for " .
320 self
::$aliases[$caseFoldedAlias]
328 return self
::$aliases;
332 * Given a special page name with a possible subpage, return an array
333 * where the first element is the special page name and the second is the
336 * @param string $alias
337 * @return array Array( String, String|null ), or array( null, null ) if the page is invalid
339 public static function resolveAlias( $alias ) {
341 $bits = explode( '/', $alias, 2 );
343 $caseFoldedAlias = $wgContLang->caseFold( $bits[0] );
344 $caseFoldedAlias = str_replace( ' ', '_', $caseFoldedAlias );
345 $aliases = self
::getAliasList();
346 if ( isset( $aliases[$caseFoldedAlias] ) ) {
347 $name = $aliases[$caseFoldedAlias];
349 return [ null, null ];
352 if ( !isset( $bits[1] ) ) { // T4087
358 return [ $name, $par ];
362 * Check if a given name exist as a special page or as a special page alias
364 * @param string $name Name of a special page
365 * @return bool True if a special page exists with this name
367 public static function exists( $name ) {
368 list( $title, /*...*/ ) = self
::resolveAlias( $name );
370 $specialPageList = self
::getPageList();
371 return isset( $specialPageList[$title] );
375 * Find the object with a given name and return it (or NULL)
377 * @param string $name Special page name, may be localised and/or an alias
378 * @return SpecialPage|null SpecialPage object or null if the page doesn't exist
380 public static function getPage( $name ) {
381 list( $realName, /*...*/ ) = self
::resolveAlias( $name );
383 $specialPageList = self
::getPageList();
385 if ( isset( $specialPageList[$realName] ) ) {
386 $rec = $specialPageList[$realName];
388 if ( is_callable( $rec ) ) {
389 // Use callback to instantiate the special page
390 $page = call_user_func( $rec );
391 } elseif ( is_string( $rec ) ) {
393 $page = new $className;
394 } elseif ( is_array( $rec ) ) {
395 $className = array_shift( $rec );
396 // @deprecated, officially since 1.18, unofficially since forever
397 wfDeprecated( "Array syntax for \$wgSpecialPages is deprecated ($className), " .
398 "define a subclass of SpecialPage instead.", '1.18' );
399 $page = ObjectFactory
::getObjectFromSpec( [
400 'class' => $className,
402 'closure_expansion' => false,
404 } elseif ( $rec instanceof SpecialPage
) {
405 $page = $rec; // XXX: we should deep clone here
410 if ( $page instanceof SpecialPage
) {
413 // It's not a classname, nor a callback, nor a legacy constructor array,
414 // nor a special page object. Give up.
415 wfLogWarning( "Cannot instantiate special page $realName: bad spec!" );
425 * Return categorised listable special pages which are available
426 * for the current user, and everyone.
428 * @param User $user User object to check permissions, $wgUser will be used
430 * @return array ( string => Specialpage )
432 public static function getUsablePages( User
$user = null ) {
434 if ( $user === null ) {
438 foreach ( self
::getPageList() as $name => $rec ) {
439 $page = self
::getPage( $name );
440 if ( $page ) { // not null
441 $page->setContext( RequestContext
::getMain() );
442 if ( $page->isListed()
443 && ( !$page->isRestricted() ||
$page->userCanExecute( $user ) )
445 $pages[$name] = $page;
454 * Return categorised listable special pages for all users
456 * @return array ( string => Specialpage )
458 public static function getRegularPages() {
460 foreach ( self
::getPageList() as $name => $rec ) {
461 $page = self
::getPage( $name );
462 if ( $page->isListed() && !$page->isRestricted() ) {
463 $pages[$name] = $page;
471 * Return categorised listable special pages which are available
472 * for the current user, but not for everyone
474 * @param User|null $user User object to use or null for $wgUser
475 * @return array ( string => Specialpage )
477 public static function getRestrictedPages( User
$user = null ) {
479 if ( $user === null ) {
483 foreach ( self
::getPageList() as $name => $rec ) {
484 $page = self
::getPage( $name );
487 && $page->isRestricted()
488 && $page->userCanExecute( $user )
490 $pages[$name] = $page;
498 * Execute a special page path.
499 * The path may contain parameters, e.g. Special:Name/Params
500 * Extracts the special page name and call the execute method, passing the parameters
502 * Returns a title object if the page is redirected, false if there was no such special
503 * page, and true if it was successful.
505 * @param Title $title
506 * @param IContextSource $context
507 * @param bool $including Bool output is being captured for use in {{special:whatever}}
508 * @param LinkRenderer|null $linkRenderer (since 1.28)
512 public static function executePath( Title
&$title, IContextSource
&$context, $including = false,
513 LinkRenderer
$linkRenderer = null
515 // @todo FIXME: Redirects broken due to this call
516 $bits = explode( '/', $title->getDBkey(), 2 );
518 if ( !isset( $bits[1] ) ) { // T4087
524 $page = self
::getPage( $name );
526 $context->getOutput()->setArticleRelated( false );
527 $context->getOutput()->setRobotPolicy( 'noindex,nofollow' );
529 global $wgSend404Code;
530 if ( $wgSend404Code ) {
531 $context->getOutput()->setStatusCode( 404 );
534 $context->getOutput()->showErrorPage( 'nosuchspecialpage', 'nospecialpagetext' );
540 // Narrow DB query expectations for this HTTP request
541 $trxLimits = $context->getConfig()->get( 'TrxProfilerLimits' );
542 $trxProfiler = Profiler
::instance()->getTransactionProfiler();
543 if ( $context->getRequest()->wasPosted() && !$page->doesWrites() ) {
544 $trxProfiler->setExpectations( $trxLimits['POST-nonwrite'], __METHOD__
);
545 $context->getRequest()->markAsSafeRequest();
549 // Page exists, set the context
550 $page->setContext( $context );
553 // Redirect to canonical alias for GET commands
554 // Not for POST, we'd lose the post data, so it's best to just distribute
555 // the request. Such POST requests are possible for old extensions that
556 // generate self-links without being aware that their default name has
558 if ( $name != $page->getLocalName() && !$context->getRequest()->wasPosted() ) {
559 $query = $context->getRequest()->getQueryValues();
560 unset( $query['title'] );
561 $title = $page->getPageTitle( $par );
562 $url = $title->getFullURL( $query );
563 $context->getOutput()->redirect( $url );
567 $context->setTitle( $page->getPageTitle( $par ) );
569 } elseif ( !$page->isIncludable() ) {
573 $page->including( $including );
574 if ( $linkRenderer ) {
575 $page->setLinkRenderer( $linkRenderer );
578 // Execute special page
585 * Just like executePath() but will override global variables and execute
586 * the page in "inclusion" mode. Returns true if the execution was
587 * successful or false if there was no such special page, or a title object
588 * if it was a redirect.
590 * Also saves the current $wgTitle, $wgOut, $wgRequest, $wgUser and $wgLang
591 * variables so that the special page will get the context it'd expect on a
592 * normal request, and then restores them to their previous values after.
594 * @param Title $title
595 * @param IContextSource $context
596 * @param LinkRenderer|null $linkRenderer (since 1.28)
597 * @return string HTML fragment
599 public static function capturePath(
600 Title
$title, IContextSource
$context, LinkRenderer
$linkRenderer = null
602 global $wgTitle, $wgOut, $wgRequest, $wgUser, $wgLang;
603 $main = RequestContext
::getMain();
605 // Save current globals and main context
609 'request' => $wgRequest,
611 'language' => $wgLang,
614 'title' => $main->getTitle(),
615 'output' => $main->getOutput(),
616 'request' => $main->getRequest(),
617 'user' => $main->getUser(),
618 'language' => $main->getLanguage(),
623 $wgOut = $context->getOutput();
624 $wgRequest = $context->getRequest();
625 $wgUser = $context->getUser();
626 $wgLang = $context->getLanguage();
627 $main->setTitle( $title );
628 $main->setOutput( $context->getOutput() );
629 $main->setRequest( $context->getRequest() );
630 $main->setUser( $context->getUser() );
631 $main->setLanguage( $context->getLanguage() );
634 $ret = self
::executePath( $title, $context, true, $linkRenderer );
636 // Restore old globals and context
637 $wgTitle = $glob['title'];
638 $wgOut = $glob['output'];
639 $wgRequest = $glob['request'];
640 $wgUser = $glob['user'];
641 $wgLang = $glob['language'];
642 $main->setTitle( $ctx['title'] );
643 $main->setOutput( $ctx['output'] );
644 $main->setRequest( $ctx['request'] );
645 $main->setUser( $ctx['user'] );
646 $main->setLanguage( $ctx['language'] );
652 * Get the local name for a specified canonical name
654 * @param string $name
655 * @param string|bool $subpage
658 public static function getLocalNameFor( $name, $subpage = false ) {
660 $aliases = $wgContLang->getSpecialPageAliases();
661 $aliasList = self
::getAliasList();
663 // Find the first alias that maps back to $name
664 if ( isset( $aliases[$name] ) ) {
666 foreach ( $aliases[$name] as $alias ) {
667 $caseFoldedAlias = $wgContLang->caseFold( $alias );
668 $caseFoldedAlias = str_replace( ' ', '_', $caseFoldedAlias );
669 if ( isset( $aliasList[$caseFoldedAlias] ) &&
670 $aliasList[$caseFoldedAlias] === $name
678 wfWarn( "Did not find a usable alias for special page '$name'. " .
679 "It seems all defined aliases conflict?" );
682 // Check if someone misspelled the correct casing
683 if ( is_array( $aliases ) ) {
684 foreach ( $aliases as $n => $values ) {
685 if ( strcasecmp( $name, $n ) === 0 ) {
686 wfWarn( "Found alias defined for $n when searching for " .
687 "special page aliases for $name. Case mismatch?" );
688 return self
::getLocalNameFor( $n, $subpage );
693 wfWarn( "Did not find alias for special page '$name'. " .
694 "Perhaps no aliases are defined for it?" );
697 if ( $subpage !== false && !is_null( $subpage ) ) {
698 // Make sure it's in dbkey form
699 $subpage = str_replace( ' ', '_', $subpage );
700 $name = "$name/$subpage";
703 return $wgContLang->ucfirst( $name );
707 * Get a title for a given alias
709 * @param string $alias
710 * @return Title|null Title or null if there is no such alias
712 public static function getTitleForAlias( $alias ) {
713 list( $name, $subpage ) = self
::resolveAlias( $alias );
714 if ( $name != null ) {
715 return SpecialPage
::getTitleFor( $name, $subpage );