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 Wikimedia\ObjectFactory
;
28 * Factory for handling the special page list and generating SpecialPage objects.
30 * To add a special page in an extension, add to $wgSpecialPages either
31 * an object instance or an array containing the name and constructor
32 * parameters. The latter is preferred for performance reasons.
34 * The object instantiated must be either an instance of SpecialPage or a
35 * sub-class thereof. It must have an execute() method, which sends the HTML
36 * for the special page to $wgOut. The parent class has an execute() method
37 * which distributes the call to the historical global functions. Additionally,
38 * execute() also checks if the user has the necessary access privileges
39 * and bails out if not.
41 * To add a core special page, use the similar static list in
42 * SpecialPageFactory::$list. To remove a core static special page at runtime, use
43 * a SpecialPage_initList hook.
45 * @ingroup SpecialPage
48 class SpecialPageFactory
{
50 * List of special page names to the subclass of SpecialPage which handles them.
52 private static $coreList = [
53 // Maintenance Reports
54 'BrokenRedirects' => BrokenRedirectsPage
::class,
55 'Deadendpages' => DeadendPagesPage
::class,
56 'DoubleRedirects' => DoubleRedirectsPage
::class,
57 'Longpages' => LongPagesPage
::class,
58 'Ancientpages' => AncientPagesPage
::class,
59 'Lonelypages' => LonelyPagesPage
::class,
60 'Fewestrevisions' => FewestrevisionsPage
::class,
61 'Withoutinterwiki' => WithoutInterwikiPage
::class,
62 'Protectedpages' => SpecialProtectedpages
::class,
63 'Protectedtitles' => SpecialProtectedtitles
::class,
64 'Shortpages' => ShortPagesPage
::class,
65 'Uncategorizedcategories' => UncategorizedCategoriesPage
::class,
66 'Uncategorizedimages' => UncategorizedImagesPage
::class,
67 'Uncategorizedpages' => UncategorizedPagesPage
::class,
68 'Uncategorizedtemplates' => UncategorizedTemplatesPage
::class,
69 'Unusedcategories' => UnusedCategoriesPage
::class,
70 'Unusedimages' => UnusedimagesPage
::class,
71 'Unusedtemplates' => UnusedtemplatesPage
::class,
72 'Unwatchedpages' => UnwatchedpagesPage
::class,
73 'Wantedcategories' => WantedCategoriesPage
::class,
74 'Wantedfiles' => WantedFilesPage
::class,
75 'Wantedpages' => WantedPagesPage
::class,
76 'Wantedtemplates' => WantedTemplatesPage
::class,
79 'Allpages' => SpecialAllPages
::class,
80 'Prefixindex' => SpecialPrefixindex
::class,
81 'Categories' => SpecialCategories
::class,
82 'Listredirects' => ListredirectsPage
::class,
83 'PagesWithProp' => SpecialPagesWithProp
::class,
84 'TrackingCategories' => SpecialTrackingCategories
::class,
87 'Userlogin' => SpecialUserLogin
::class,
88 'Userlogout' => SpecialUserLogout
::class,
89 'CreateAccount' => SpecialCreateAccount
::class,
90 'LinkAccounts' => SpecialLinkAccounts
::class,
91 'UnlinkAccounts' => SpecialUnlinkAccounts
::class,
92 'ChangeCredentials' => SpecialChangeCredentials
::class,
93 'RemoveCredentials' => SpecialRemoveCredentials
::class,
96 'Activeusers' => SpecialActiveUsers
::class,
97 'Block' => SpecialBlock
::class,
98 'Unblock' => SpecialUnblock
::class,
99 'BlockList' => SpecialBlockList
::class,
100 'AutoblockList' => SpecialAutoblockList
::class,
101 'ChangePassword' => SpecialChangePassword
::class,
102 'BotPasswords' => SpecialBotPasswords
::class,
103 'PasswordReset' => SpecialPasswordReset
::class,
104 'DeletedContributions' => DeletedContributionsPage
::class,
105 'Preferences' => SpecialPreferences
::class,
106 'ResetTokens' => SpecialResetTokens
::class,
107 'Contributions' => SpecialContributions
::class,
108 'Listgrouprights' => SpecialListGroupRights
::class,
109 'Listgrants' => SpecialListGrants
::class,
110 'Listusers' => SpecialListUsers
::class,
111 'Listadmins' => SpecialListAdmins
::class,
112 'Listbots' => SpecialListBots
::class,
113 'Userrights' => UserrightsPage
::class,
114 'EditWatchlist' => SpecialEditWatchlist
::class,
116 // Recent changes and logs
117 'Newimages' => SpecialNewFiles
::class,
118 'Log' => SpecialLog
::class,
119 'Watchlist' => SpecialWatchlist
::class,
120 'Newpages' => SpecialNewpages
::class,
121 'Recentchanges' => SpecialRecentChanges
::class,
122 'Recentchangeslinked' => SpecialRecentChangesLinked
::class,
123 'Tags' => SpecialTags
::class,
125 // Media reports and uploads
126 'Listfiles' => SpecialListFiles
::class,
127 'Filepath' => SpecialFilepath
::class,
128 'MediaStatistics' => MediaStatisticsPage
::class,
129 'MIMEsearch' => MIMEsearchPage
::class,
130 'FileDuplicateSearch' => FileDuplicateSearchPage
::class,
131 'Upload' => SpecialUpload
::class,
132 'UploadStash' => SpecialUploadStash
::class,
133 'ListDuplicatedFiles' => ListDuplicatedFilesPage
::class,
136 'ApiSandbox' => SpecialApiSandbox
::class,
137 'Statistics' => SpecialStatistics
::class,
138 'Allmessages' => SpecialAllMessages
::class,
139 'Version' => SpecialVersion
::class,
140 'Lockdb' => SpecialLockdb
::class,
141 'Unlockdb' => SpecialUnlockdb
::class,
143 // Redirecting special pages
144 'LinkSearch' => LinkSearchPage
::class,
145 'Randompage' => RandomPage
::class,
146 'RandomInCategory' => SpecialRandomInCategory
::class,
147 'Randomredirect' => SpecialRandomredirect
::class,
148 'Randomrootpage' => SpecialRandomrootpage
::class,
149 'GoToInterwiki' => SpecialGoToInterwiki
::class,
152 'Mostlinkedcategories' => MostlinkedCategoriesPage
::class,
153 'Mostimages' => MostimagesPage
::class,
154 'Mostinterwikis' => MostinterwikisPage
::class,
155 'Mostlinked' => MostlinkedPage
::class,
156 'Mostlinkedtemplates' => MostlinkedTemplatesPage
::class,
157 'Mostcategories' => MostcategoriesPage
::class,
158 'Mostrevisions' => MostrevisionsPage
::class,
161 'ComparePages' => SpecialComparePages
::class,
162 'Export' => SpecialExport
::class,
163 'Import' => SpecialImport
::class,
164 'Undelete' => SpecialUndelete
::class,
165 'Whatlinkshere' => SpecialWhatLinksHere
::class,
166 'MergeHistory' => SpecialMergeHistory
::class,
167 'ExpandTemplates' => SpecialExpandTemplates
::class,
170 'Booksources' => SpecialBookSources
::class,
172 // Unlisted / redirects
173 'ApiHelp' => SpecialApiHelp
::class,
174 'Blankpage' => SpecialBlankpage
::class,
175 'Diff' => SpecialDiff
::class,
176 'EditTags' => SpecialEditTags
::class,
177 'Emailuser' => SpecialEmailUser
::class,
178 'Movepage' => MovePageForm
::class,
179 'Mycontributions' => SpecialMycontributions
::class,
180 'MyLanguage' => SpecialMyLanguage
::class,
181 'Mypage' => SpecialMypage
::class,
182 'Mytalk' => SpecialMytalk
::class,
183 'Myuploads' => SpecialMyuploads
::class,
184 'AllMyUploads' => SpecialAllMyUploads
::class,
185 'PermanentLink' => SpecialPermanentLink
::class,
186 'Redirect' => SpecialRedirect
::class,
187 'Revisiondelete' => SpecialRevisionDelete
::class,
188 'RunJobs' => SpecialRunJobs
::class,
189 'Specialpages' => SpecialSpecialpages
::class,
190 'PageData' => SpecialPageData
::class,
193 private static $list;
194 private static $aliases;
197 * Reset the internal list of special pages. Useful when changing $wgSpecialPages after
198 * the internal list has already been initialized, e.g. during testing.
200 public static function resetList() {
202 self
::$aliases = null;
206 * Returns a list of canonical special page names.
207 * May be used to iterate over all registered special pages.
211 public static function getNames() {
212 return array_keys( self
::getPageList() );
216 * Get the special page list as an array
220 private static function getPageList() {
221 global $wgSpecialPages;
222 global $wgDisableInternalSearch, $wgEmailAuthentication;
223 global $wgEnableEmail, $wgEnableJavaScriptTest;
224 global $wgPageLanguageUseDB, $wgContentHandlerUseDB;
226 if ( !is_array( self
::$list ) ) {
227 self
::$list = self
::$coreList;
229 if ( !$wgDisableInternalSearch ) {
230 self
::$list['Search'] = SpecialSearch
::class;
233 if ( $wgEmailAuthentication ) {
234 self
::$list['Confirmemail'] = EmailConfirmation
::class;
235 self
::$list['Invalidateemail'] = EmailInvalidation
::class;
238 if ( $wgEnableEmail ) {
239 self
::$list['ChangeEmail'] = SpecialChangeEmail
::class;
242 if ( $wgEnableJavaScriptTest ) {
243 self
::$list['JavaScriptTest'] = SpecialJavaScriptTest
::class;
246 if ( $wgPageLanguageUseDB ) {
247 self
::$list['PageLanguage'] = SpecialPageLanguage
::class;
249 if ( $wgContentHandlerUseDB ) {
250 self
::$list['ChangeContentModel'] = SpecialChangeContentModel
::class;
253 // Add extension special pages
254 self
::$list = array_merge( self
::$list, $wgSpecialPages );
256 // This hook can be used to disable unwanted core special pages
257 // or conditionally register special pages.
258 Hooks
::run( 'SpecialPage_initList', [ &self
::$list ] );
266 * Initialise and return the list of special page aliases. Returns an array where
267 * the key is an alias, and the value is the canonical name of the special page.
268 * All registered special pages are guaranteed to map to themselves.
271 private static function getAliasList() {
272 if ( is_null( self
::$aliases ) ) {
274 $aliases = $wgContLang->getSpecialPageAliases();
275 $pageList = self
::getPageList();
280 // Force every canonical name to be an alias for itself.
281 foreach ( $pageList as $name => $stuff ) {
282 $caseFoldedAlias = $wgContLang->caseFold( $name );
283 self
::$aliases[$caseFoldedAlias] = $name;
284 $keepAlias[$caseFoldedAlias] = 'canonical';
287 // Check for $aliases being an array since Language::getSpecialPageAliases can return null
288 if ( is_array( $aliases ) ) {
289 foreach ( $aliases as $realName => $aliasList ) {
290 $aliasList = array_values( $aliasList );
291 foreach ( $aliasList as $i => $alias ) {
292 $caseFoldedAlias = $wgContLang->caseFold( $alias );
294 if ( isset( self
::$aliases[$caseFoldedAlias] ) &&
295 $realName === self
::$aliases[$caseFoldedAlias]
297 // Ignore same-realName conflicts
301 if ( !isset( $keepAlias[$caseFoldedAlias] ) ) {
302 self
::$aliases[$caseFoldedAlias] = $realName;
304 $keepAlias[$caseFoldedAlias] = 'first';
307 wfWarn( "First alias '$alias' for $realName conflicts with " .
308 "{$keepAlias[$caseFoldedAlias]} alias for " .
309 self
::$aliases[$caseFoldedAlias]
317 return self
::$aliases;
321 * Given a special page name with a possible subpage, return an array
322 * where the first element is the special page name and the second is the
325 * @param string $alias
326 * @return array Array( String, String|null ), or array( null, null ) if the page is invalid
328 public static function resolveAlias( $alias ) {
330 $bits = explode( '/', $alias, 2 );
332 $caseFoldedAlias = $wgContLang->caseFold( $bits[0] );
333 $caseFoldedAlias = str_replace( ' ', '_', $caseFoldedAlias );
334 $aliases = self
::getAliasList();
335 if ( isset( $aliases[$caseFoldedAlias] ) ) {
336 $name = $aliases[$caseFoldedAlias];
338 return [ null, null ];
341 if ( !isset( $bits[1] ) ) { // T4087
347 return [ $name, $par ];
351 * Check if a given name exist as a special page or as a special page alias
353 * @param string $name Name of a special page
354 * @return bool True if a special page exists with this name
356 public static function exists( $name ) {
357 list( $title, /*...*/ ) = self
::resolveAlias( $name );
359 $specialPageList = self
::getPageList();
360 return isset( $specialPageList[$title] );
364 * Find the object with a given name and return it (or NULL)
366 * @param string $name Special page name, may be localised and/or an alias
367 * @return SpecialPage|null SpecialPage object or null if the page doesn't exist
369 public static function getPage( $name ) {
370 list( $realName, /*...*/ ) = self
::resolveAlias( $name );
372 $specialPageList = self
::getPageList();
374 if ( isset( $specialPageList[$realName] ) ) {
375 $rec = $specialPageList[$realName];
377 if ( is_callable( $rec ) ) {
378 // Use callback to instantiate the special page
379 $page = call_user_func( $rec );
380 } elseif ( is_string( $rec ) ) {
382 $page = new $className;
383 } elseif ( is_array( $rec ) ) {
384 $className = array_shift( $rec );
385 // @deprecated, officially since 1.18, unofficially since forever
386 wfDeprecated( "Array syntax for \$wgSpecialPages is deprecated ($className), " .
387 "define a subclass of SpecialPage instead.", '1.18' );
388 $page = ObjectFactory
::getObjectFromSpec( [
389 'class' => $className,
391 'closure_expansion' => false,
393 } elseif ( $rec instanceof SpecialPage
) {
394 $page = $rec; // XXX: we should deep clone here
399 if ( $page instanceof SpecialPage
) {
402 // It's not a classname, nor a callback, nor a legacy constructor array,
403 // nor a special page object. Give up.
404 wfLogWarning( "Cannot instantiate special page $realName: bad spec!" );
414 * Return categorised listable special pages which are available
415 * for the current user, and everyone.
417 * @param User $user User object to check permissions, $wgUser will be used
419 * @return array ( string => Specialpage )
421 public static function getUsablePages( User
$user = null ) {
423 if ( $user === null ) {
427 foreach ( self
::getPageList() as $name => $rec ) {
428 $page = self
::getPage( $name );
429 if ( $page ) { // not null
430 $page->setContext( RequestContext
::getMain() );
431 if ( $page->isListed()
432 && ( !$page->isRestricted() ||
$page->userCanExecute( $user ) )
434 $pages[$name] = $page;
443 * Return categorised listable special pages for all users
445 * @return array ( string => Specialpage )
447 public static function getRegularPages() {
449 foreach ( self
::getPageList() as $name => $rec ) {
450 $page = self
::getPage( $name );
451 if ( $page && $page->isListed() && !$page->isRestricted() ) {
452 $pages[$name] = $page;
460 * Return categorised listable special pages which are available
461 * for the current user, but not for everyone
463 * @param User|null $user User object to use or null for $wgUser
464 * @return array ( string => Specialpage )
466 public static function getRestrictedPages( User
$user = null ) {
468 if ( $user === null ) {
472 foreach ( self
::getPageList() as $name => $rec ) {
473 $page = self
::getPage( $name );
476 && $page->isRestricted()
477 && $page->userCanExecute( $user )
479 $pages[$name] = $page;
487 * Execute a special page path.
488 * The path may contain parameters, e.g. Special:Name/Params
489 * Extracts the special page name and call the execute method, passing the parameters
491 * Returns a title object if the page is redirected, false if there was no such special
492 * page, and true if it was successful.
494 * @param Title &$title
495 * @param IContextSource &$context
496 * @param bool $including Bool output is being captured for use in {{special:whatever}}
497 * @param LinkRenderer|null $linkRenderer (since 1.28)
501 public static function executePath( Title
&$title, IContextSource
&$context, $including = false,
502 LinkRenderer
$linkRenderer = null
504 // @todo FIXME: Redirects broken due to this call
505 $bits = explode( '/', $title->getDBkey(), 2 );
507 if ( !isset( $bits[1] ) ) { // T4087
513 $page = self
::getPage( $name );
515 $context->getOutput()->setArticleRelated( false );
516 $context->getOutput()->setRobotPolicy( 'noindex,nofollow' );
518 global $wgSend404Code;
519 if ( $wgSend404Code ) {
520 $context->getOutput()->setStatusCode( 404 );
523 $context->getOutput()->showErrorPage( 'nosuchspecialpage', 'nospecialpagetext' );
529 // Narrow DB query expectations for this HTTP request
530 $trxLimits = $context->getConfig()->get( 'TrxProfilerLimits' );
531 $trxProfiler = Profiler
::instance()->getTransactionProfiler();
532 if ( $context->getRequest()->wasPosted() && !$page->doesWrites() ) {
533 $trxProfiler->setExpectations( $trxLimits['POST-nonwrite'], __METHOD__
);
534 $context->getRequest()->markAsSafeRequest();
538 // Page exists, set the context
539 $page->setContext( $context );
542 // Redirect to canonical alias for GET commands
543 // Not for POST, we'd lose the post data, so it's best to just distribute
544 // the request. Such POST requests are possible for old extensions that
545 // generate self-links without being aware that their default name has
547 if ( $name != $page->getLocalName() && !$context->getRequest()->wasPosted() ) {
548 $query = $context->getRequest()->getQueryValues();
549 unset( $query['title'] );
550 $title = $page->getPageTitle( $par );
551 $url = $title->getFullURL( $query );
552 $context->getOutput()->redirect( $url );
556 $context->setTitle( $page->getPageTitle( $par ) );
558 } elseif ( !$page->isIncludable() ) {
562 $page->including( $including );
563 if ( $linkRenderer ) {
564 $page->setLinkRenderer( $linkRenderer );
567 // Execute special page
574 * Just like executePath() but will override global variables and execute
575 * the page in "inclusion" mode. Returns true if the execution was
576 * successful or false if there was no such special page, or a title object
577 * if it was a redirect.
579 * Also saves the current $wgTitle, $wgOut, $wgRequest, $wgUser and $wgLang
580 * variables so that the special page will get the context it'd expect on a
581 * normal request, and then restores them to their previous values after.
583 * @param Title $title
584 * @param IContextSource $context
585 * @param LinkRenderer|null $linkRenderer (since 1.28)
586 * @return string HTML fragment
588 public static function capturePath(
589 Title
$title, IContextSource
$context, LinkRenderer
$linkRenderer = null
591 global $wgTitle, $wgOut, $wgRequest, $wgUser, $wgLang;
592 $main = RequestContext
::getMain();
594 // Save current globals and main context
598 'request' => $wgRequest,
600 'language' => $wgLang,
603 'title' => $main->getTitle(),
604 'output' => $main->getOutput(),
605 'request' => $main->getRequest(),
606 'user' => $main->getUser(),
607 'language' => $main->getLanguage(),
612 $wgOut = $context->getOutput();
613 $wgRequest = $context->getRequest();
614 $wgUser = $context->getUser();
615 $wgLang = $context->getLanguage();
616 $main->setTitle( $title );
617 $main->setOutput( $context->getOutput() );
618 $main->setRequest( $context->getRequest() );
619 $main->setUser( $context->getUser() );
620 $main->setLanguage( $context->getLanguage() );
623 $ret = self
::executePath( $title, $context, true, $linkRenderer );
625 // Restore old globals and context
626 $wgTitle = $glob['title'];
627 $wgOut = $glob['output'];
628 $wgRequest = $glob['request'];
629 $wgUser = $glob['user'];
630 $wgLang = $glob['language'];
631 $main->setTitle( $ctx['title'] );
632 $main->setOutput( $ctx['output'] );
633 $main->setRequest( $ctx['request'] );
634 $main->setUser( $ctx['user'] );
635 $main->setLanguage( $ctx['language'] );
641 * Get the local name for a specified canonical name
643 * @param string $name
644 * @param string|bool $subpage
647 public static function getLocalNameFor( $name, $subpage = false ) {
649 $aliases = $wgContLang->getSpecialPageAliases();
650 $aliasList = self
::getAliasList();
652 // Find the first alias that maps back to $name
653 if ( isset( $aliases[$name] ) ) {
655 foreach ( $aliases[$name] as $alias ) {
656 $caseFoldedAlias = $wgContLang->caseFold( $alias );
657 $caseFoldedAlias = str_replace( ' ', '_', $caseFoldedAlias );
658 if ( isset( $aliasList[$caseFoldedAlias] ) &&
659 $aliasList[$caseFoldedAlias] === $name
667 wfWarn( "Did not find a usable alias for special page '$name'. " .
668 "It seems all defined aliases conflict?" );
671 // Check if someone misspelled the correct casing
672 if ( is_array( $aliases ) ) {
673 foreach ( $aliases as $n => $values ) {
674 if ( strcasecmp( $name, $n ) === 0 ) {
675 wfWarn( "Found alias defined for $n when searching for " .
676 "special page aliases for $name. Case mismatch?" );
677 return self
::getLocalNameFor( $n, $subpage );
682 wfWarn( "Did not find alias for special page '$name'. " .
683 "Perhaps no aliases are defined for it?" );
686 if ( $subpage !== false && !is_null( $subpage ) ) {
687 // Make sure it's in dbkey form
688 $subpage = str_replace( ' ', '_', $subpage );
689 $name = "$name/$subpage";
692 return $wgContLang->ucfirst( $name );
696 * Get a title for a given alias
698 * @param string $alias
699 * @return Title|null Title or null if there is no such alias
701 public static function getTitleForAlias( $alias ) {
702 list( $name, $subpage ) = self
::resolveAlias( $alias );
703 if ( $name != null ) {
704 return SpecialPage
::getTitleFor( $name, $subpage );