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' => 'SpecialUserlogoutPreAuthManager',
88 'CreateAccount' => 'SpecialCreateAccountPreAuthManager',
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 'ChangePassword' => 'SpecialChangePasswordPreAuthManager',
100 'BotPasswords' => 'SpecialBotPasswords',
101 'PasswordReset' => 'SpecialPasswordResetPreAuthManager',
102 'DeletedContributions' => 'DeletedContributionsPage',
103 'Preferences' => 'SpecialPreferences',
104 'ResetTokens' => 'SpecialResetTokens',
105 'Contributions' => 'SpecialContributions',
106 'Listgrouprights' => 'SpecialListGroupRights',
107 'Listgrants' => 'SpecialListGrants',
108 'Listusers' => 'SpecialListUsers',
109 'Listadmins' => 'SpecialListAdmins',
110 'Listbots' => 'SpecialListBots',
111 'Userrights' => 'UserrightsPage',
112 'EditWatchlist' => 'SpecialEditWatchlist',
114 // Recent changes and logs
115 'Newimages' => 'SpecialNewFiles',
116 'Log' => 'SpecialLog',
117 'Watchlist' => 'SpecialWatchlist',
118 'Newpages' => 'SpecialNewpages',
119 'Recentchanges' => 'SpecialRecentChanges',
120 'Recentchangeslinked' => 'SpecialRecentChangesLinked',
121 'Tags' => 'SpecialTags',
123 // Media reports and uploads
124 'Listfiles' => 'SpecialListFiles',
125 'Filepath' => 'SpecialFilepath',
126 'MediaStatistics' => 'MediaStatisticsPage',
127 'MIMEsearch' => 'MIMEsearchPage',
128 'FileDuplicateSearch' => 'FileDuplicateSearchPage',
129 'Upload' => 'SpecialUpload',
130 'UploadStash' => 'SpecialUploadStash',
131 'ListDuplicatedFiles' => 'ListDuplicatedFilesPage',
134 'ApiSandbox' => 'SpecialApiSandbox',
135 'Statistics' => 'SpecialStatistics',
136 'Allmessages' => 'SpecialAllMessages',
137 'Version' => 'SpecialVersion',
138 'Lockdb' => 'SpecialLockdb',
139 'Unlockdb' => 'SpecialUnlockdb',
141 // Redirecting special pages
142 'LinkSearch' => 'LinkSearchPage',
143 'Randompage' => 'RandomPage',
144 'RandomInCategory' => 'SpecialRandomInCategory',
145 'Randomredirect' => 'SpecialRandomredirect',
146 'Randomrootpage' => 'SpecialRandomrootpage',
149 'Mostlinkedcategories' => 'MostlinkedCategoriesPage',
150 'Mostimages' => 'MostimagesPage',
151 'Mostinterwikis' => 'MostinterwikisPage',
152 'Mostlinked' => 'MostlinkedPage',
153 'Mostlinkedtemplates' => 'MostlinkedTemplatesPage',
154 'Mostcategories' => 'MostcategoriesPage',
155 'Mostrevisions' => 'MostrevisionsPage',
158 'ComparePages' => 'SpecialComparePages',
159 'Export' => 'SpecialExport',
160 'Import' => 'SpecialImport',
161 'Undelete' => 'SpecialUndelete',
162 'Whatlinkshere' => 'SpecialWhatLinksHere',
163 'MergeHistory' => 'SpecialMergeHistory',
164 'ExpandTemplates' => 'SpecialExpandTemplates',
167 'Booksources' => 'SpecialBookSources',
169 // Unlisted / redirects
170 'ApiHelp' => 'SpecialApiHelp',
171 'Blankpage' => 'SpecialBlankpage',
172 'Diff' => 'SpecialDiff',
173 'EditTags' => 'SpecialEditTags',
174 'Emailuser' => 'SpecialEmailUser',
175 'Movepage' => 'MovePageForm',
176 'Mycontributions' => 'SpecialMycontributions',
177 'MyLanguage' => 'SpecialMyLanguage',
178 'Mypage' => 'SpecialMypage',
179 'Mytalk' => 'SpecialMytalk',
180 'Myuploads' => 'SpecialMyuploads',
181 'AllMyUploads' => 'SpecialAllMyUploads',
182 'PermanentLink' => 'SpecialPermanentLink',
183 'Redirect' => 'SpecialRedirect',
184 'Revisiondelete' => 'SpecialRevisionDelete',
185 'RunJobs' => 'SpecialRunJobs',
186 'Specialpages' => 'SpecialSpecialpages',
189 private static $list;
190 private static $aliases;
191 private static $pageObjectCache = [];
194 * Reset the internal list of special pages. Useful when changing $wgSpecialPages after
195 * the internal list has already been initialized, e.g. during testing.
197 public static function resetList() {
199 self
::$aliases = null;
200 self
::$pageObjectCache = [];
204 * Returns a list of canonical special page names.
205 * May be used to iterate over all registered special pages.
209 public static function getNames() {
210 return array_keys( self
::getPageList() );
214 * Get the special page list as an array
216 * @deprecated since 1.24, use getNames() instead.
219 public static function getList() {
220 wfDeprecated( __FUNCTION__
, '1.24' );
221 return self
::getPageList();
225 * Get the special page list as an array
229 private static function getPageList() {
230 global $wgSpecialPages;
231 global $wgDisableInternalSearch, $wgEmailAuthentication;
232 global $wgEnableEmail, $wgEnableJavaScriptTest;
233 global $wgPageLanguageUseDB, $wgContentHandlerUseDB;
234 global $wgDisableAuthManager;
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'] = 'SpecialChangeEmailPreAuthManager';
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 // horrible hack to allow selection between old and new classes via a feature flag - T110756
265 // will be removed once AuthManager is stable
266 if ( !$wgDisableAuthManager ) {
267 self
::$list = array_map( function ( $class ) {
268 return preg_replace( '/PreAuthManager$/', '', $class );
270 self
::$list['Userlogout'] = 'SpecialUserLogout'; // case matters
272 self
::$list['Userlogin'] = 'LoginForm';
273 self
::$list = array_diff_key( self
::$list, array_fill_keys( [
274 'LinkAccounts', 'UnlinkAccounts', 'ChangeCredentials', 'RemoveCredentials',
278 // Add extension special pages
279 self
::$list = array_merge( self
::$list, $wgSpecialPages );
281 // This hook can be used to disable unwanted core special pages
282 // or conditionally register special pages.
283 Hooks
::run( 'SpecialPage_initList', [ &self
::$list ] );
291 * Initialise and return the list of special page aliases. Returns an array where
292 * the key is an alias, and the value is the canonical name of the special page.
293 * All registered special pages are guaranteed to map to themselves.
296 private static function getAliasList() {
297 if ( is_null( self
::$aliases ) ) {
299 $aliases = $wgContLang->getSpecialPageAliases();
300 $pageList = self
::getPageList();
305 // Force every canonical name to be an alias for itself.
306 foreach ( $pageList as $name => $stuff ) {
307 $caseFoldedAlias = $wgContLang->caseFold( $name );
308 self
::$aliases[$caseFoldedAlias] = $name;
309 $keepAlias[$caseFoldedAlias] = 'canonical';
312 // Check for $aliases being an array since Language::getSpecialPageAliases can return null
313 if ( is_array( $aliases ) ) {
314 foreach ( $aliases as $realName => $aliasList ) {
315 $aliasList = array_values( $aliasList );
316 foreach ( $aliasList as $i => $alias ) {
317 $caseFoldedAlias = $wgContLang->caseFold( $alias );
319 if ( isset( self
::$aliases[$caseFoldedAlias] ) &&
320 $realName === self
::$aliases[$caseFoldedAlias]
322 // Ignore same-realName conflicts
326 if ( !isset( $keepAlias[$caseFoldedAlias] ) ) {
327 self
::$aliases[$caseFoldedAlias] = $realName;
329 $keepAlias[$caseFoldedAlias] = 'first';
332 wfWarn( "First alias '$alias' for $realName conflicts with " .
333 "{$keepAlias[$caseFoldedAlias]} alias for " .
334 self
::$aliases[$caseFoldedAlias]
342 return self
::$aliases;
346 * Given a special page name with a possible subpage, return an array
347 * where the first element is the special page name and the second is the
350 * @param string $alias
351 * @return array Array( String, String|null ), or array( null, null ) if the page is invalid
353 public static function resolveAlias( $alias ) {
355 $bits = explode( '/', $alias, 2 );
357 $caseFoldedAlias = $wgContLang->caseFold( $bits[0] );
358 $caseFoldedAlias = str_replace( ' ', '_', $caseFoldedAlias );
359 $aliases = self
::getAliasList();
360 if ( isset( $aliases[$caseFoldedAlias] ) ) {
361 $name = $aliases[$caseFoldedAlias];
363 return [ null, null ];
366 if ( !isset( $bits[1] ) ) { // bug 2087
372 return [ $name, $par ];
376 * Check if a given name exist as a special page or as a special page alias
378 * @param string $name Name of a special page
379 * @return bool True if a special page exists with this name
381 public static function exists( $name ) {
382 list( $title, /*...*/ ) = self
::resolveAlias( $name );
384 $specialPageList = self
::getPageList();
385 return isset( $specialPageList[$title] );
389 * Find the object with a given name and return it (or NULL)
391 * @param string $name Special page name, may be localised and/or an alias
392 * @return SpecialPage|null SpecialPage object or null if the page doesn't exist
394 public static function getPage( $name ) {
395 list( $realName, /*...*/ ) = self
::resolveAlias( $name );
397 if ( isset( self
::$pageObjectCache[$realName] ) ) {
398 return self
::$pageObjectCache[$realName];
401 $specialPageList = self
::getPageList();
403 if ( isset( $specialPageList[$realName] ) ) {
404 $rec = $specialPageList[$realName];
406 if ( is_callable( $rec ) ) {
407 // Use callback to instantiate the special page
408 $page = call_user_func( $rec );
409 } elseif ( is_string( $rec ) ) {
411 $page = new $className;
412 } elseif ( is_array( $rec ) ) {
413 $className = array_shift( $rec );
414 // @deprecated, officially since 1.18, unofficially since forever
415 wfDeprecated( "Array syntax for \$wgSpecialPages is deprecated ($className), " .
416 "define a subclass of SpecialPage instead.", '1.18' );
417 $page = ObjectFactory
::getObjectFromSpec( [
418 'class' => $className,
420 'closure_expansion' => false,
422 } elseif ( $rec instanceof SpecialPage
) {
423 $page = $rec; // XXX: we should deep clone here
428 self
::$pageObjectCache[$realName] = $page;
429 if ( $page instanceof SpecialPage
) {
432 // It's not a classname, nor a callback, nor a legacy constructor array,
433 // nor a special page object. Give up.
434 wfLogWarning( "Cannot instantiate special page $realName: bad spec!" );
444 * Return categorised listable special pages which are available
445 * for the current user, and everyone.
447 * @param User $user User object to check permissions, $wgUser will be used
449 * @return array ( string => Specialpage )
451 public static function getUsablePages( User
$user = null ) {
453 if ( $user === null ) {
457 foreach ( self
::getPageList() as $name => $rec ) {
458 $page = self
::getPage( $name );
459 if ( $page ) { // not null
460 $page->setContext( RequestContext
::getMain() );
461 if ( $page->isListed()
462 && ( !$page->isRestricted() ||
$page->userCanExecute( $user ) )
464 $pages[$name] = $page;
473 * Return categorised listable special pages for all users
475 * @return array ( string => Specialpage )
477 public static function getRegularPages() {
479 foreach ( self
::getPageList() as $name => $rec ) {
480 $page = self
::getPage( $name );
481 if ( $page->isListed() && !$page->isRestricted() ) {
482 $pages[$name] = $page;
490 * Return categorised listable special pages which are available
491 * for the current user, but not for everyone
493 * @param User|null $user User object to use or null for $wgUser
494 * @return array ( string => Specialpage )
496 public static function getRestrictedPages( User
$user = null ) {
498 if ( $user === null ) {
502 foreach ( self
::getPageList() as $name => $rec ) {
503 $page = self
::getPage( $name );
506 && $page->isRestricted()
507 && $page->userCanExecute( $user )
509 $pages[$name] = $page;
517 * Execute a special page path.
518 * The path may contain parameters, e.g. Special:Name/Params
519 * Extracts the special page name and call the execute method, passing the parameters
521 * Returns a title object if the page is redirected, false if there was no such special
522 * page, and true if it was successful.
524 * @param Title $title
525 * @param IContextSource $context
526 * @param bool $including Bool output is being captured for use in {{special:whatever}}
527 * @param LinkRenderer|null $linkRenderer (since 1.28)
531 public static function executePath( Title
&$title, IContextSource
&$context, $including = false,
532 LinkRenderer
$linkRenderer = null
534 // @todo FIXME: Redirects broken due to this call
535 $bits = explode( '/', $title->getDBkey(), 2 );
537 if ( !isset( $bits[1] ) ) { // bug 2087
543 $page = self
::getPage( $name );
545 $context->getOutput()->setArticleRelated( false );
546 $context->getOutput()->setRobotPolicy( 'noindex,nofollow' );
548 global $wgSend404Code;
549 if ( $wgSend404Code ) {
550 $context->getOutput()->setStatusCode( 404 );
553 $context->getOutput()->showErrorPage( 'nosuchspecialpage', 'nospecialpagetext' );
559 // Narrow DB query expectations for this HTTP request
560 $trxLimits = $context->getConfig()->get( 'TrxProfilerLimits' );
561 $trxProfiler = Profiler
::instance()->getTransactionProfiler();
562 if ( $context->getRequest()->wasPosted() && !$page->doesWrites() ) {
563 $trxProfiler->setExpectations( $trxLimits['POST-nonwrite'], __METHOD__
);
564 $context->getRequest()->markAsSafeRequest();
568 // Page exists, set the context
569 $page->setContext( $context );
572 // Redirect to canonical alias for GET commands
573 // Not for POST, we'd lose the post data, so it's best to just distribute
574 // the request. Such POST requests are possible for old extensions that
575 // generate self-links without being aware that their default name has
577 if ( $name != $page->getLocalName() && !$context->getRequest()->wasPosted() ) {
578 $query = $context->getRequest()->getQueryValues();
579 unset( $query['title'] );
580 $title = $page->getPageTitle( $par );
581 $url = $title->getFullURL( $query );
582 $context->getOutput()->redirect( $url );
586 $context->setTitle( $page->getPageTitle( $par ) );
588 } elseif ( !$page->isIncludable() ) {
592 $page->including( $including );
593 if ( $linkRenderer ) {
594 $page->setLinkRenderer( $linkRenderer );
597 // Execute special page
604 * Just like executePath() but will override global variables and execute
605 * the page in "inclusion" mode. Returns true if the execution was
606 * successful or false if there was no such special page, or a title object
607 * if it was a redirect.
609 * Also saves the current $wgTitle, $wgOut, $wgRequest, $wgUser and $wgLang
610 * variables so that the special page will get the context it'd expect on a
611 * normal request, and then restores them to their previous values after.
613 * @param Title $title
614 * @param IContextSource $context
615 * @param LinkRenderer|null $linkRenderer (since 1.28)
616 * @return string HTML fragment
618 public static function capturePath(
619 Title
$title, IContextSource
$context, LinkRenderer
$linkRenderer = null
621 global $wgTitle, $wgOut, $wgRequest, $wgUser, $wgLang;
622 $main = RequestContext
::getMain();
624 // Save current globals and main context
628 'request' => $wgRequest,
630 'language' => $wgLang,
633 'title' => $main->getTitle(),
634 'output' => $main->getOutput(),
635 'request' => $main->getRequest(),
636 'user' => $main->getUser(),
637 'language' => $main->getLanguage(),
642 $wgOut = $context->getOutput();
643 $wgRequest = $context->getRequest();
644 $wgUser = $context->getUser();
645 $wgLang = $context->getLanguage();
646 $main->setTitle( $title );
647 $main->setOutput( $context->getOutput() );
648 $main->setRequest( $context->getRequest() );
649 $main->setUser( $context->getUser() );
650 $main->setLanguage( $context->getLanguage() );
653 $ret = self
::executePath( $title, $context, true, $linkRenderer );
655 // Restore old globals and context
656 $wgTitle = $glob['title'];
657 $wgOut = $glob['output'];
658 $wgRequest = $glob['request'];
659 $wgUser = $glob['user'];
660 $wgLang = $glob['language'];
661 $main->setTitle( $ctx['title'] );
662 $main->setOutput( $ctx['output'] );
663 $main->setRequest( $ctx['request'] );
664 $main->setUser( $ctx['user'] );
665 $main->setLanguage( $ctx['language'] );
671 * Get the local name for a specified canonical name
673 * @param string $name
674 * @param string|bool $subpage
677 public static function getLocalNameFor( $name, $subpage = false ) {
679 $aliases = $wgContLang->getSpecialPageAliases();
680 $aliasList = self
::getAliasList();
682 // Find the first alias that maps back to $name
683 if ( isset( $aliases[$name] ) ) {
685 foreach ( $aliases[$name] as $alias ) {
686 $caseFoldedAlias = $wgContLang->caseFold( $alias );
687 $caseFoldedAlias = str_replace( ' ', '_', $caseFoldedAlias );
688 if ( isset( $aliasList[$caseFoldedAlias] ) &&
689 $aliasList[$caseFoldedAlias] === $name
697 wfWarn( "Did not find a usable alias for special page '$name'. " .
698 "It seems all defined aliases conflict?" );
701 // Check if someone misspelled the correct casing
702 if ( is_array( $aliases ) ) {
703 foreach ( $aliases as $n => $values ) {
704 if ( strcasecmp( $name, $n ) === 0 ) {
705 wfWarn( "Found alias defined for $n when searching for " .
706 "special page aliases for $name. Case mismatch?" );
707 return self
::getLocalNameFor( $n, $subpage );
712 wfWarn( "Did not find alias for special page '$name'. " .
713 "Perhaps no aliases are defined for it?" );
716 if ( $subpage !== false && !is_null( $subpage ) ) {
717 $name = "$name/$subpage";
720 return $wgContLang->ucfirst( $name );
724 * Get a title for a given alias
726 * @param string $alias
727 * @return Title|null Title or null if there is no such alias
729 public static function getTitleForAlias( $alias ) {
730 list( $name, $subpage ) = self
::resolveAlias( $alias );
731 if ( $name != null ) {
732 return SpecialPage
::getTitleFor( $name, $subpage );