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
26 * Factory for handling the special page list and generating SpecialPage objects.
28 * To add a special page in an extension, add to $wgSpecialPages either
29 * an object instance or an array containing the name and constructor
30 * parameters. The latter is preferred for performance reasons.
32 * The object instantiated must be either an instance of SpecialPage or a
33 * sub-class thereof. It must have an execute() method, which sends the HTML
34 * for the special page to $wgOut. The parent class has an execute() method
35 * which distributes the call to the historical global functions. Additionally,
36 * execute() also checks if the user has the necessary access privileges
37 * and bails out if not.
39 * To add a core special page, use the similar static list in
40 * SpecialPageFactory::$list. To remove a core static special page at runtime, use
41 * a SpecialPage_initList hook.
43 * @ingroup SpecialPage
46 class SpecialPageFactory
{
48 * List of special page names to the subclass of SpecialPage which handles them.
50 private static $coreList = [
51 // Maintenance Reports
52 'BrokenRedirects' => 'BrokenRedirectsPage',
53 'Deadendpages' => 'DeadendPagesPage',
54 'DoubleRedirects' => 'DoubleRedirectsPage',
55 'Longpages' => 'LongPagesPage',
56 'Ancientpages' => 'AncientPagesPage',
57 'Lonelypages' => 'LonelyPagesPage',
58 'Fewestrevisions' => 'FewestrevisionsPage',
59 'Withoutinterwiki' => 'WithoutInterwikiPage',
60 'Protectedpages' => 'SpecialProtectedpages',
61 'Protectedtitles' => 'SpecialProtectedtitles',
62 'Shortpages' => 'ShortPagesPage',
63 'Uncategorizedcategories' => 'UncategorizedCategoriesPage',
64 'Uncategorizedimages' => 'UncategorizedImagesPage',
65 'Uncategorizedpages' => 'UncategorizedPagesPage',
66 'Uncategorizedtemplates' => 'UncategorizedTemplatesPage',
67 'Unusedcategories' => 'UnusedCategoriesPage',
68 'Unusedimages' => 'UnusedimagesPage',
69 'Unusedtemplates' => 'UnusedtemplatesPage',
70 'Unwatchedpages' => 'UnwatchedpagesPage',
71 'Wantedcategories' => 'WantedCategoriesPage',
72 'Wantedfiles' => 'WantedFilesPage',
73 'Wantedpages' => 'WantedPagesPage',
74 'Wantedtemplates' => 'WantedTemplatesPage',
77 'Allpages' => 'SpecialAllPages',
78 'Prefixindex' => 'SpecialPrefixindex',
79 'Categories' => 'SpecialCategories',
80 'Listredirects' => 'ListredirectsPage',
81 'PagesWithProp' => 'SpecialPagesWithProp',
82 'TrackingCategories' => 'SpecialTrackingCategories',
85 'Userlogin' => 'SpecialUserLogin',
86 'Userlogout' => 'SpecialUserlogoutPreAuthManager',
87 'CreateAccount' => 'SpecialCreateAccountPreAuthManager',
88 'LinkAccounts' => 'SpecialLinkAccounts',
89 'UnlinkAccounts' => 'SpecialUnlinkAccounts',
90 'ChangeCredentials' => 'SpecialChangeCredentials',
91 'RemoveCredentials' => 'SpecialRemoveCredentials',
94 'Activeusers' => 'SpecialActiveUsers',
95 'Block' => 'SpecialBlock',
96 'Unblock' => 'SpecialUnblock',
97 'BlockList' => 'SpecialBlockList',
98 'ChangePassword' => 'SpecialChangePasswordPreAuthManager',
99 'BotPasswords' => 'SpecialBotPasswords',
100 'PasswordReset' => 'SpecialPasswordResetPreAuthManager',
101 'DeletedContributions' => 'DeletedContributionsPage',
102 'Preferences' => 'SpecialPreferences',
103 'ResetTokens' => 'SpecialResetTokens',
104 'Contributions' => 'SpecialContributions',
105 'Listgrouprights' => 'SpecialListGroupRights',
106 'Listgrants' => 'SpecialListGrants',
107 'Listusers' => 'SpecialListUsers',
108 'Listadmins' => 'SpecialListAdmins',
109 'Listbots' => 'SpecialListBots',
110 'Userrights' => 'UserrightsPage',
111 'EditWatchlist' => 'SpecialEditWatchlist',
113 // Recent changes and logs
114 'Newimages' => 'SpecialNewFiles',
115 'Log' => 'SpecialLog',
116 'Watchlist' => 'SpecialWatchlist',
117 'Newpages' => 'SpecialNewpages',
118 'Recentchanges' => 'SpecialRecentChanges',
119 'Recentchangeslinked' => 'SpecialRecentChangesLinked',
120 'Tags' => 'SpecialTags',
122 // Media reports and uploads
123 'Listfiles' => 'SpecialListFiles',
124 'Filepath' => 'SpecialFilepath',
125 'MediaStatistics' => 'MediaStatisticsPage',
126 'MIMEsearch' => 'MIMEsearchPage',
127 'FileDuplicateSearch' => 'FileDuplicateSearchPage',
128 'Upload' => 'SpecialUpload',
129 'UploadStash' => 'SpecialUploadStash',
130 'ListDuplicatedFiles' => 'ListDuplicatedFilesPage',
133 'ApiSandbox' => 'SpecialApiSandbox',
134 'Statistics' => 'SpecialStatistics',
135 'Allmessages' => 'SpecialAllMessages',
136 'Version' => 'SpecialVersion',
137 'Lockdb' => 'SpecialLockdb',
138 'Unlockdb' => 'SpecialUnlockdb',
140 // Redirecting special pages
141 'LinkSearch' => 'LinkSearchPage',
142 'Randompage' => 'RandomPage',
143 'RandomInCategory' => 'SpecialRandomInCategory',
144 'Randomredirect' => 'SpecialRandomredirect',
145 'Randomrootpage' => 'SpecialRandomrootpage',
148 'Mostlinkedcategories' => 'MostlinkedCategoriesPage',
149 'Mostimages' => 'MostimagesPage',
150 'Mostinterwikis' => 'MostinterwikisPage',
151 'Mostlinked' => 'MostlinkedPage',
152 'Mostlinkedtemplates' => 'MostlinkedTemplatesPage',
153 'Mostcategories' => 'MostcategoriesPage',
154 'Mostrevisions' => 'MostrevisionsPage',
157 'ComparePages' => 'SpecialComparePages',
158 'Export' => 'SpecialExport',
159 'Import' => 'SpecialImport',
160 'Undelete' => 'SpecialUndelete',
161 'Whatlinkshere' => 'SpecialWhatLinksHere',
162 'MergeHistory' => 'SpecialMergeHistory',
163 'ExpandTemplates' => 'SpecialExpandTemplates',
166 'Booksources' => 'SpecialBookSources',
168 // Unlisted / redirects
169 'ApiHelp' => 'SpecialApiHelp',
170 'Blankpage' => 'SpecialBlankpage',
171 'Diff' => 'SpecialDiff',
172 'EditTags' => 'SpecialEditTags',
173 'Emailuser' => 'SpecialEmailUser',
174 'Movepage' => 'MovePageForm',
175 'Mycontributions' => 'SpecialMycontributions',
176 'MyLanguage' => 'SpecialMyLanguage',
177 'Mypage' => 'SpecialMypage',
178 'Mytalk' => 'SpecialMytalk',
179 'Myuploads' => 'SpecialMyuploads',
180 'AllMyUploads' => 'SpecialAllMyUploads',
181 'PermanentLink' => 'SpecialPermanentLink',
182 'Redirect' => 'SpecialRedirect',
183 'Revisiondelete' => 'SpecialRevisionDelete',
184 'RunJobs' => 'SpecialRunJobs',
185 'Specialpages' => 'SpecialSpecialpages',
188 private static $list;
189 private static $aliases;
190 private static $pageObjectCache = [];
193 * Reset the internal list of special pages. Useful when changing $wgSpecialPages after
194 * the internal list has already been initialized, e.g. during testing.
196 public static function resetList() {
198 self
::$aliases = null;
199 self
::$pageObjectCache = [];
203 * Returns a list of canonical special page names.
204 * May be used to iterate over all registered special pages.
208 public static function getNames() {
209 return array_keys( self
::getPageList() );
213 * Get the special page list as an array
215 * @deprecated since 1.24, use getNames() instead.
218 public static function getList() {
219 wfDeprecated( __FUNCTION__
, '1.24' );
220 return self
::getPageList();
224 * Get the special page list as an array
228 private static function getPageList() {
229 global $wgSpecialPages;
230 global $wgDisableInternalSearch, $wgEmailAuthentication;
231 global $wgEnableEmail, $wgEnableJavaScriptTest;
232 global $wgPageLanguageUseDB, $wgContentHandlerUseDB;
233 global $wgDisableAuthManager;
235 if ( !is_array( self
::$list ) ) {
237 self
::$list = self
::$coreList;
239 if ( !$wgDisableInternalSearch ) {
240 self
::$list['Search'] = 'SpecialSearch';
243 if ( $wgEmailAuthentication ) {
244 self
::$list['Confirmemail'] = 'EmailConfirmation';
245 self
::$list['Invalidateemail'] = 'EmailInvalidation';
248 if ( $wgEnableEmail ) {
249 self
::$list['ChangeEmail'] = 'SpecialChangeEmailPreAuthManager';
252 if ( $wgEnableJavaScriptTest ) {
253 self
::$list['JavaScriptTest'] = 'SpecialJavaScriptTest';
256 if ( $wgPageLanguageUseDB ) {
257 self
::$list['PageLanguage'] = 'SpecialPageLanguage';
259 if ( $wgContentHandlerUseDB ) {
260 self
::$list['ChangeContentModel'] = 'SpecialChangeContentModel';
263 // horrible hack to allow selection between old and new classes via a feature flag - T110756
264 // will be removed once AuthManager is stable
265 if ( !$wgDisableAuthManager ) {
266 self
::$list = array_map( function ( $class ) {
267 return preg_replace( '/PreAuthManager$/', '', $class );
269 self
::$list['Userlogout'] = 'SpecialUserLogout'; // case matters
271 self
::$list['Userlogin'] = 'LoginForm';
272 self
::$list = array_diff_key( self
::$list, array_fill_keys( [
273 'LinkAccounts', 'UnlinkAccounts', 'ChangeCredentials', 'RemoveCredentials',
277 // Add extension special pages
278 self
::$list = array_merge( self
::$list, $wgSpecialPages );
280 // This hook can be used to disable unwanted core special pages
281 // or conditionally register special pages.
282 Hooks
::run( 'SpecialPage_initList', [ &self
::$list ] );
290 * Initialise and return the list of special page aliases. Returns an array where
291 * the key is an alias, and the value is the canonical name of the special page.
292 * All registered special pages are guaranteed to map to themselves.
295 private static function getAliasList() {
296 if ( is_null( self
::$aliases ) ) {
298 $aliases = $wgContLang->getSpecialPageAliases();
299 $pageList = self
::getPageList();
304 // Force every canonical name to be an alias for itself.
305 foreach ( $pageList as $name => $stuff ) {
306 $caseFoldedAlias = $wgContLang->caseFold( $name );
307 self
::$aliases[$caseFoldedAlias] = $name;
308 $keepAlias[$caseFoldedAlias] = 'canonical';
311 // Check for $aliases being an array since Language::getSpecialPageAliases can return null
312 if ( is_array( $aliases ) ) {
313 foreach ( $aliases as $realName => $aliasList ) {
314 $aliasList = array_values( $aliasList );
315 foreach ( $aliasList as $i => $alias ) {
316 $caseFoldedAlias = $wgContLang->caseFold( $alias );
318 if ( isset( self
::$aliases[$caseFoldedAlias] ) &&
319 $realName === self
::$aliases[$caseFoldedAlias]
321 // Ignore same-realName conflicts
325 if ( !isset( $keepAlias[$caseFoldedAlias] ) ) {
326 self
::$aliases[$caseFoldedAlias] = $realName;
328 $keepAlias[$caseFoldedAlias] = 'first';
331 wfWarn( "First alias '$alias' for $realName conflicts with " .
332 "{$keepAlias[$caseFoldedAlias]} alias for " .
333 self
::$aliases[$caseFoldedAlias]
341 return self
::$aliases;
345 * Given a special page name with a possible subpage, return an array
346 * where the first element is the special page name and the second is the
349 * @param string $alias
350 * @return array Array( String, String|null ), or array( null, null ) if the page is invalid
352 public static function resolveAlias( $alias ) {
354 $bits = explode( '/', $alias, 2 );
356 $caseFoldedAlias = $wgContLang->caseFold( $bits[0] );
357 $caseFoldedAlias = str_replace( ' ', '_', $caseFoldedAlias );
358 $aliases = self
::getAliasList();
359 if ( isset( $aliases[$caseFoldedAlias] ) ) {
360 $name = $aliases[$caseFoldedAlias];
362 return [ null, null ];
365 if ( !isset( $bits[1] ) ) { // bug 2087
371 return [ $name, $par ];
375 * Check if a given name exist as a special page or as a special page alias
377 * @param string $name Name of a special page
378 * @return bool True if a special page exists with this name
380 public static function exists( $name ) {
381 list( $title, /*...*/ ) = self
::resolveAlias( $name );
383 $specialPageList = self
::getPageList();
384 return isset( $specialPageList[$title] );
388 * Find the object with a given name and return it (or NULL)
390 * @param string $name Special page name, may be localised and/or an alias
391 * @return SpecialPage|null SpecialPage object or null if the page doesn't exist
393 public static function getPage( $name ) {
394 list( $realName, /*...*/ ) = self
::resolveAlias( $name );
396 if ( isset( self
::$pageObjectCache[$realName] ) ) {
397 return self
::$pageObjectCache[$realName];
400 $specialPageList = self
::getPageList();
402 if ( isset( $specialPageList[$realName] ) ) {
403 $rec = $specialPageList[$realName];
405 if ( is_callable( $rec ) ) {
406 // Use callback to instantiate the special page
407 $page = call_user_func( $rec );
408 } elseif ( is_string( $rec ) ) {
410 $page = new $className;
411 } elseif ( is_array( $rec ) ) {
412 $className = array_shift( $rec );
413 // @deprecated, officially since 1.18, unofficially since forever
414 wfDeprecated( "Array syntax for \$wgSpecialPages is deprecated ($className), " .
415 "define a subclass of SpecialPage instead.", '1.18' );
416 $page = ObjectFactory
::getObjectFromSpec( [
417 'class' => $className,
419 'closure_expansion' => false,
421 } elseif ( $rec instanceof SpecialPage
) {
422 $page = $rec; // XXX: we should deep clone here
427 self
::$pageObjectCache[$realName] = $page;
428 if ( $page instanceof SpecialPage
) {
431 // It's not a classname, nor a callback, nor a legacy constructor array,
432 // nor a special page object. Give up.
433 wfLogWarning( "Cannot instantiate special page $realName: bad spec!" );
443 * Return categorised listable special pages which are available
444 * for the current user, and everyone.
446 * @param User $user User object to check permissions, $wgUser will be used
448 * @return array ( string => Specialpage )
450 public static function getUsablePages( User
$user = null ) {
452 if ( $user === null ) {
456 foreach ( self
::getPageList() as $name => $rec ) {
457 $page = self
::getPage( $name );
458 if ( $page ) { // not null
459 $page->setContext( RequestContext
::getMain() );
460 if ( $page->isListed()
461 && ( !$page->isRestricted() ||
$page->userCanExecute( $user ) )
463 $pages[$name] = $page;
472 * Return categorised listable special pages for all users
474 * @return array ( string => Specialpage )
476 public static function getRegularPages() {
478 foreach ( self
::getPageList() as $name => $rec ) {
479 $page = self
::getPage( $name );
480 if ( $page->isListed() && !$page->isRestricted() ) {
481 $pages[$name] = $page;
489 * Return categorised listable special pages which are available
490 * for the current user, but not for everyone
492 * @param User|null $user User object to use or null for $wgUser
493 * @return array ( string => Specialpage )
495 public static function getRestrictedPages( User
$user = null ) {
497 if ( $user === null ) {
501 foreach ( self
::getPageList() as $name => $rec ) {
502 $page = self
::getPage( $name );
505 && $page->isRestricted()
506 && $page->userCanExecute( $user )
508 $pages[$name] = $page;
516 * Execute a special page path.
517 * The path may contain parameters, e.g. Special:Name/Params
518 * Extracts the special page name and call the execute method, passing the parameters
520 * Returns a title object if the page is redirected, false if there was no such special
521 * page, and true if it was successful.
523 * @param Title $title
524 * @param IContextSource $context
525 * @param bool $including Bool output is being captured for use in {{special:whatever}}
529 public static function executePath( Title
&$title, IContextSource
&$context, $including = false ) {
530 // @todo FIXME: Redirects broken due to this call
531 $bits = explode( '/', $title->getDBkey(), 2 );
533 if ( !isset( $bits[1] ) ) { // bug 2087
539 $page = self
::getPage( $name );
541 $context->getOutput()->setArticleRelated( false );
542 $context->getOutput()->setRobotPolicy( 'noindex,nofollow' );
544 global $wgSend404Code;
545 if ( $wgSend404Code ) {
546 $context->getOutput()->setStatusCode( 404 );
549 $context->getOutput()->showErrorPage( 'nosuchspecialpage', 'nospecialpagetext' );
555 // Narrow DB query expectations for this HTTP request
556 $trxLimits = $context->getConfig()->get( 'TrxProfilerLimits' );
557 $trxProfiler = Profiler
::instance()->getTransactionProfiler();
558 if ( $context->getRequest()->wasPosted() && !$page->doesWrites() ) {
559 $trxProfiler->setExpectations( $trxLimits['POST-nonwrite'], __METHOD__
);
560 $context->getRequest()->markAsSafeRequest();
564 // Page exists, set the context
565 $page->setContext( $context );
568 // Redirect to canonical alias for GET commands
569 // Not for POST, we'd lose the post data, so it's best to just distribute
570 // the request. Such POST requests are possible for old extensions that
571 // generate self-links without being aware that their default name has
573 if ( $name != $page->getLocalName() && !$context->getRequest()->wasPosted() ) {
574 $query = $context->getRequest()->getQueryValues();
575 unset( $query['title'] );
576 $title = $page->getPageTitle( $par );
577 $url = $title->getFullURL( $query );
578 $context->getOutput()->redirect( $url );
582 $context->setTitle( $page->getPageTitle( $par ) );
584 } elseif ( !$page->isIncludable() ) {
588 $page->including( $including );
590 // Execute special page
597 * Just like executePath() but will override global variables and execute
598 * the page in "inclusion" mode. Returns true if the execution was
599 * successful or false if there was no such special page, or a title object
600 * if it was a redirect.
602 * Also saves the current $wgTitle, $wgOut, $wgRequest, $wgUser and $wgLang
603 * variables so that the special page will get the context it'd expect on a
604 * normal request, and then restores them to their previous values after.
606 * @param Title $title
607 * @param IContextSource $context
608 * @return string HTML fragment
610 public static function capturePath( Title
$title, IContextSource
$context ) {
611 global $wgTitle, $wgOut, $wgRequest, $wgUser, $wgLang;
612 $main = RequestContext
::getMain();
614 // Save current globals and main context
618 'request' => $wgRequest,
620 'language' => $wgLang,
623 'title' => $main->getTitle(),
624 'output' => $main->getOutput(),
625 'request' => $main->getRequest(),
626 'user' => $main->getUser(),
627 'language' => $main->getLanguage(),
632 $wgOut = $context->getOutput();
633 $wgRequest = $context->getRequest();
634 $wgUser = $context->getUser();
635 $wgLang = $context->getLanguage();
636 $main->setTitle( $title );
637 $main->setOutput( $context->getOutput() );
638 $main->setRequest( $context->getRequest() );
639 $main->setUser( $context->getUser() );
640 $main->setLanguage( $context->getLanguage() );
643 $ret = self
::executePath( $title, $context, true );
645 // Restore old globals and context
646 $wgTitle = $glob['title'];
647 $wgOut = $glob['output'];
648 $wgRequest = $glob['request'];
649 $wgUser = $glob['user'];
650 $wgLang = $glob['language'];
651 $main->setTitle( $ctx['title'] );
652 $main->setOutput( $ctx['output'] );
653 $main->setRequest( $ctx['request'] );
654 $main->setUser( $ctx['user'] );
655 $main->setLanguage( $ctx['language'] );
661 * Get the local name for a specified canonical name
663 * @param string $name
664 * @param string|bool $subpage
667 public static function getLocalNameFor( $name, $subpage = false ) {
669 $aliases = $wgContLang->getSpecialPageAliases();
670 $aliasList = self
::getAliasList();
672 // Find the first alias that maps back to $name
673 if ( isset( $aliases[$name] ) ) {
675 foreach ( $aliases[$name] as $alias ) {
676 $caseFoldedAlias = $wgContLang->caseFold( $alias );
677 $caseFoldedAlias = str_replace( ' ', '_', $caseFoldedAlias );
678 if ( isset( $aliasList[$caseFoldedAlias] ) &&
679 $aliasList[$caseFoldedAlias] === $name
687 wfWarn( "Did not find a usable alias for special page '$name'. " .
688 "It seems all defined aliases conflict?" );
691 // Check if someone misspelled the correct casing
692 if ( is_array( $aliases ) ) {
693 foreach ( $aliases as $n => $values ) {
694 if ( strcasecmp( $name, $n ) === 0 ) {
695 wfWarn( "Found alias defined for $n when searching for " .
696 "special page aliases for $name. Case mismatch?" );
697 return self
::getLocalNameFor( $n, $subpage );
702 wfWarn( "Did not find alias for special page '$name'. " .
703 "Perhaps no aliases are defined for it?" );
706 if ( $subpage !== false && !is_null( $subpage ) ) {
707 $name = "$name/$subpage";
710 return $wgContLang->ucfirst( $name );
714 * Get a title for a given alias
716 * @param string $alias
717 * @return Title|null Title or null if there is no such alias
719 public static function getTitleForAlias( $alias ) {
720 list( $name, $subpage ) = self
::resolveAlias( $alias );
721 if ( $name != null ) {
722 return SpecialPage
::getTitleFor( $name, $subpage );