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
25 namespace MediaWiki\Special
;
31 use MediaWiki\Linker\LinkRenderer
;
37 use Wikimedia\ObjectFactory
;
40 * Factory for handling the special page list and generating SpecialPage objects.
42 * To add a special page in an extension, add to $wgSpecialPages either
43 * an object instance or an array containing the name and constructor
44 * parameters. The latter is preferred for performance reasons.
46 * The object instantiated must be either an instance of SpecialPage or a
47 * sub-class thereof. It must have an execute() method, which sends the HTML
48 * for the special page to $wgOut. The parent class has an execute() method
49 * which distributes the call to the historical global functions. Additionally,
50 * execute() also checks if the user has the necessary access privileges
51 * and bails out if not.
53 * To add a core special page, use the similar static list in
54 * SpecialPageFactory::$list. To remove a core static special page at runtime, use
55 * a SpecialPage_initList hook.
57 * @note There are two classes called SpecialPageFactory. You should use this first one, in
58 * namespace MediaWiki\Special, which is a service. \SpecialPageFactory is a deprecated collection
59 * of static methods that forwards to the global service.
61 * @ingroup SpecialPage
64 class SpecialPageFactory
{
66 * List of special page names to the subclass of SpecialPage which handles them.
67 * @todo Make this a const when we drop HHVM support (T192166). It can still be private in PHP
70 private static $coreList = [
71 // Maintenance Reports
72 'BrokenRedirects' => \BrokenRedirectsPage
::class,
73 'Deadendpages' => \DeadendPagesPage
::class,
74 'DoubleRedirects' => \DoubleRedirectsPage
::class,
75 'Longpages' => \LongPagesPage
::class,
76 'Ancientpages' => \AncientPagesPage
::class,
77 'Lonelypages' => \LonelyPagesPage
::class,
78 'Fewestrevisions' => \FewestrevisionsPage
::class,
79 'Withoutinterwiki' => \WithoutInterwikiPage
::class,
80 'Protectedpages' => \SpecialProtectedpages
::class,
81 'Protectedtitles' => \SpecialProtectedtitles
::class,
82 'Shortpages' => \ShortPagesPage
::class,
83 'Uncategorizedcategories' => \UncategorizedCategoriesPage
::class,
84 'Uncategorizedimages' => \UncategorizedImagesPage
::class,
85 'Uncategorizedpages' => \UncategorizedPagesPage
::class,
86 'Uncategorizedtemplates' => \UncategorizedTemplatesPage
::class,
87 'Unusedcategories' => \UnusedCategoriesPage
::class,
88 'Unusedimages' => \UnusedimagesPage
::class,
89 'Unusedtemplates' => \UnusedtemplatesPage
::class,
90 'Unwatchedpages' => \UnwatchedpagesPage
::class,
91 'Wantedcategories' => \WantedCategoriesPage
::class,
92 'Wantedfiles' => \WantedFilesPage
::class,
93 'Wantedpages' => \WantedPagesPage
::class,
94 'Wantedtemplates' => \WantedTemplatesPage
::class,
97 'Allpages' => \SpecialAllPages
::class,
98 'Prefixindex' => \SpecialPrefixindex
::class,
99 'Categories' => \SpecialCategories
::class,
100 'Listredirects' => \ListredirectsPage
::class,
101 'PagesWithProp' => \SpecialPagesWithProp
::class,
102 'TrackingCategories' => \SpecialTrackingCategories
::class,
105 'Userlogin' => \SpecialUserLogin
::class,
106 'Userlogout' => \SpecialUserLogout
::class,
107 'CreateAccount' => \SpecialCreateAccount
::class,
108 'LinkAccounts' => \SpecialLinkAccounts
::class,
109 'UnlinkAccounts' => \SpecialUnlinkAccounts
::class,
110 'ChangeCredentials' => \SpecialChangeCredentials
::class,
111 'RemoveCredentials' => \SpecialRemoveCredentials
::class,
114 'Activeusers' => \SpecialActiveUsers
::class,
115 'Block' => \SpecialBlock
::class,
116 'Unblock' => \SpecialUnblock
::class,
117 'BlockList' => \SpecialBlockList
::class,
118 'AutoblockList' => \SpecialAutoblockList
::class,
119 'ChangePassword' => \SpecialChangePassword
::class,
120 'BotPasswords' => \SpecialBotPasswords
::class,
121 'PasswordReset' => \SpecialPasswordReset
::class,
122 'DeletedContributions' => \DeletedContributionsPage
::class,
123 'Preferences' => \SpecialPreferences
::class,
124 'ResetTokens' => \SpecialResetTokens
::class,
125 'Contributions' => \SpecialContributions
::class,
126 'Listgrouprights' => \SpecialListGroupRights
::class,
127 'Listgrants' => \SpecialListGrants
::class,
128 'Listusers' => \SpecialListUsers
::class,
129 'Listadmins' => \SpecialListAdmins
::class,
130 'Listbots' => \SpecialListBots
::class,
131 'Userrights' => \UserrightsPage
::class,
132 'EditWatchlist' => \SpecialEditWatchlist
::class,
133 'PasswordPolicies' => \SpecialPasswordPolicies
::class,
135 // Recent changes and logs
136 'Newimages' => \SpecialNewFiles
::class,
137 'Log' => \SpecialLog
::class,
138 'Watchlist' => \SpecialWatchlist
::class,
139 'Newpages' => \SpecialNewpages
::class,
140 'Recentchanges' => \SpecialRecentChanges
::class,
141 'Recentchangeslinked' => \SpecialRecentChangesLinked
::class,
142 'Tags' => \SpecialTags
::class,
144 // Media reports and uploads
145 'Listfiles' => \SpecialListFiles
::class,
146 'Filepath' => \SpecialFilepath
::class,
147 'MediaStatistics' => \MediaStatisticsPage
::class,
148 'MIMEsearch' => \MIMEsearchPage
::class,
149 'FileDuplicateSearch' => \FileDuplicateSearchPage
::class,
150 'Upload' => \SpecialUpload
::class,
151 'UploadStash' => \SpecialUploadStash
::class,
152 'ListDuplicatedFiles' => \ListDuplicatedFilesPage
::class,
155 'ApiSandbox' => \SpecialApiSandbox
::class,
156 'Statistics' => \SpecialStatistics
::class,
157 'Allmessages' => \SpecialAllMessages
::class,
158 'Version' => \SpecialVersion
::class,
159 'Lockdb' => \SpecialLockdb
::class,
160 'Unlockdb' => \SpecialUnlockdb
::class,
162 // Redirecting special pages
163 'LinkSearch' => \LinkSearchPage
::class,
164 'Randompage' => \RandomPage
::class,
165 'RandomInCategory' => \SpecialRandomInCategory
::class,
166 'Randomredirect' => \SpecialRandomredirect
::class,
167 'Randomrootpage' => \SpecialRandomrootpage
::class,
168 'GoToInterwiki' => \SpecialGoToInterwiki
::class,
171 'Mostlinkedcategories' => \MostlinkedCategoriesPage
::class,
172 'Mostimages' => \MostimagesPage
::class,
173 'Mostinterwikis' => \MostinterwikisPage
::class,
174 'Mostlinked' => \MostlinkedPage
::class,
175 'Mostlinkedtemplates' => \MostlinkedTemplatesPage
::class,
176 'Mostcategories' => \MostcategoriesPage
::class,
177 'Mostrevisions' => \MostrevisionsPage
::class,
180 'ComparePages' => \SpecialComparePages
::class,
181 'Export' => \SpecialExport
::class,
182 'Import' => \SpecialImport
::class,
183 'Undelete' => \SpecialUndelete
::class,
184 'Whatlinkshere' => \SpecialWhatLinksHere
::class,
185 'MergeHistory' => \SpecialMergeHistory
::class,
186 'ExpandTemplates' => \SpecialExpandTemplates
::class,
189 'Booksources' => \SpecialBookSources
::class,
191 // Unlisted / redirects
192 'ApiHelp' => \SpecialApiHelp
::class,
193 'Blankpage' => \SpecialBlankpage
::class,
194 'Diff' => \SpecialDiff
::class,
195 'EditTags' => \SpecialEditTags
::class,
196 'Emailuser' => \SpecialEmailUser
::class,
197 'Movepage' => \MovePageForm
::class,
198 'Mycontributions' => \SpecialMycontributions
::class,
199 'MyLanguage' => \SpecialMyLanguage
::class,
200 'Mypage' => \SpecialMypage
::class,
201 'Mytalk' => \SpecialMytalk
::class,
202 'Myuploads' => \SpecialMyuploads
::class,
203 'AllMyUploads' => \SpecialAllMyUploads
::class,
204 'PermanentLink' => \SpecialPermanentLink
::class,
205 'Redirect' => \SpecialRedirect
::class,
206 'Revisiondelete' => \SpecialRevisionDelete
::class,
207 'RunJobs' => \SpecialRunJobs
::class,
208 'Specialpages' => \SpecialSpecialpages
::class,
209 'PageData' => \SpecialPageData
::class,
212 /** @var array Special page name => class name */
225 * @param Config $config
226 * @param Language $contLang
228 public function __construct( Config
$config, Language
$contLang ) {
229 $this->config
= $config;
230 $this->contLang
= $contLang;
234 * Returns a list of canonical special page names.
235 * May be used to iterate over all registered special pages.
239 public function getNames() : array {
240 return array_keys( $this->getPageList() );
244 * Get the special page list as an array
248 private function getPageList() : array {
249 if ( !is_array( $this->list ) ) {
250 $this->list = self
::$coreList;
252 if ( !$this->config
->get( 'DisableInternalSearch' ) ) {
253 $this->list['Search'] = \SpecialSearch
::class;
256 if ( $this->config
->get( 'EmailAuthentication' ) ) {
257 $this->list['Confirmemail'] = \EmailConfirmation
::class;
258 $this->list['Invalidateemail'] = \EmailInvalidation
::class;
261 if ( $this->config
->get( 'EnableEmail' ) ) {
262 $this->list['ChangeEmail'] = \SpecialChangeEmail
::class;
265 if ( $this->config
->get( 'EnableJavaScriptTest' ) ) {
266 $this->list['JavaScriptTest'] = \SpecialJavaScriptTest
::class;
269 if ( $this->config
->get( 'PageLanguageUseDB' ) ) {
270 $this->list['PageLanguage'] = \SpecialPageLanguage
::class;
272 if ( $this->config
->get( 'ContentHandlerUseDB' ) ) {
273 $this->list['ChangeContentModel'] = \SpecialChangeContentModel
::class;
276 // Add extension special pages
277 $this->list = array_merge( $this->list, $this->config
->get( 'SpecialPages' ) );
279 // This hook can be used to disable unwanted core special pages
280 // or conditionally register special pages.
281 Hooks
::run( 'SpecialPage_initList', [ &$this->list ] );
289 * Initialise and return the list of special page aliases. Returns an array where
290 * the key is an alias, and the value is the canonical name of the special page.
291 * All registered special pages are guaranteed to map to themselves.
294 private function getAliasList() : array {
295 if ( is_null( $this->aliases
) ) {
296 $aliases = $this->contLang
->getSpecialPageAliases();
297 $pageList = $this->getPageList();
302 // Force every canonical name to be an alias for itself.
303 foreach ( $pageList as $name => $stuff ) {
304 $caseFoldedAlias = $this->contLang
->caseFold( $name );
305 $this->aliases
[$caseFoldedAlias] = $name;
306 $keepAlias[$caseFoldedAlias] = 'canonical';
309 // Check for $aliases being an array since Language::getSpecialPageAliases can return null
310 if ( is_array( $aliases ) ) {
311 foreach ( $aliases as $realName => $aliasList ) {
312 $aliasList = array_values( $aliasList );
313 foreach ( $aliasList as $i => $alias ) {
314 $caseFoldedAlias = $this->contLang
->caseFold( $alias );
316 if ( isset( $this->aliases
[$caseFoldedAlias] ) &&
317 $realName === $this->aliases
[$caseFoldedAlias]
319 // Ignore same-realName conflicts
323 if ( !isset( $keepAlias[$caseFoldedAlias] ) ) {
324 $this->aliases
[$caseFoldedAlias] = $realName;
326 $keepAlias[$caseFoldedAlias] = 'first';
329 wfWarn( "First alias '$alias' for $realName conflicts with " .
330 "{$keepAlias[$caseFoldedAlias]} alias for " .
331 $this->aliases
[$caseFoldedAlias]
339 return $this->aliases
;
343 * Given a special page name with a possible subpage, return an array
344 * where the first element is the special page name and the second is the
347 * @param string $alias
348 * @return array Array( String, String|null ), or array( null, null ) if the page is invalid
350 public function resolveAlias( $alias ) {
351 $bits = explode( '/', $alias, 2 );
353 $caseFoldedAlias = $this->contLang
->caseFold( $bits[0] );
354 $caseFoldedAlias = str_replace( ' ', '_', $caseFoldedAlias );
355 $aliases = $this->getAliasList();
356 if ( isset( $aliases[$caseFoldedAlias] ) ) {
357 $name = $aliases[$caseFoldedAlias];
359 return [ null, null ];
362 if ( !isset( $bits[1] ) ) { // T4087
368 return [ $name, $par ];
372 * Check if a given name exist as a special page or as a special page alias
374 * @param string $name Name of a special page
375 * @return bool True if a special page exists with this name
377 public function exists( $name ) {
378 list( $title, /*...*/ ) = $this->resolveAlias( $name );
380 $specialPageList = $this->getPageList();
381 return isset( $specialPageList[$title] );
385 * Find the object with a given name and return it (or NULL)
387 * @param string $name Special page name, may be localised and/or an alias
388 * @return SpecialPage|null SpecialPage object or null if the page doesn't exist
390 public function getPage( $name ) {
391 list( $realName, /*...*/ ) = $this->resolveAlias( $name );
393 $specialPageList = $this->getPageList();
395 if ( isset( $specialPageList[$realName] ) ) {
396 $rec = $specialPageList[$realName];
398 if ( is_callable( $rec ) ) {
399 // Use callback to instantiate the special page
401 } elseif ( is_string( $rec ) ) {
403 $page = new $className;
404 } elseif ( is_array( $rec ) ) {
405 $className = array_shift( $rec );
406 // @deprecated, officially since 1.18, unofficially since forever
407 wfDeprecated( "Array syntax for \$wgSpecialPages is deprecated ($className), " .
408 "define a subclass of SpecialPage instead.", '1.18' );
409 $page = ObjectFactory
::getObjectFromSpec( [
410 'class' => $className,
412 'closure_expansion' => false,
414 } elseif ( $rec instanceof SpecialPage
) {
415 $page = $rec; // XXX: we should deep clone here
420 if ( $page instanceof SpecialPage
) {
423 // It's not a classname, nor a callback, nor a legacy constructor array,
424 // nor a special page object. Give up.
425 wfLogWarning( "Cannot instantiate special page $realName: bad spec!" );
435 * Return categorised listable special pages which are available
436 * for the current user, and everyone.
438 * @param User $user User object to check permissions
440 * @return array ( string => Specialpage )
442 public function getUsablePages( User
$user ) : array {
444 foreach ( $this->getPageList() as $name => $rec ) {
445 $page = $this->getPage( $name );
446 if ( $page ) { // not null
447 $page->setContext( RequestContext
::getMain() );
448 if ( $page->isListed()
449 && ( !$page->isRestricted() ||
$page->userCanExecute( $user ) )
451 $pages[$name] = $page;
460 * Return categorised listable special pages for all users
462 * @return array ( string => Specialpage )
464 public function getRegularPages() : array {
466 foreach ( $this->getPageList() as $name => $rec ) {
467 $page = $this->getPage( $name );
468 if ( $page && $page->isListed() && !$page->isRestricted() ) {
469 $pages[$name] = $page;
477 * Return categorised listable special pages which are available
478 * for the current user, but not for everyone
480 * @param User $user User object to use
481 * @return array ( string => Specialpage )
483 public function getRestrictedPages( User
$user ) : array {
485 foreach ( $this->getPageList() as $name => $rec ) {
486 $page = $this->getPage( $name );
489 && $page->isRestricted()
490 && $page->userCanExecute( $user )
492 $pages[$name] = $page;
500 * Execute a special page path.
501 * The path may contain parameters, e.g. Special:Name/Params
502 * Extracts the special page name and call the execute method, passing the parameters
504 * Returns a title object if the page is redirected, false if there was no such special
505 * page, and true if it was successful.
507 * @param Title &$title
508 * @param IContextSource &$context
509 * @param bool $including Bool output is being captured for use in {{special:whatever}}
510 * @param LinkRenderer|null $linkRenderer (since 1.28)
514 public function executePath( Title
&$title, IContextSource
&$context, $including = false,
515 LinkRenderer
$linkRenderer = null
517 // @todo FIXME: Redirects broken due to this call
518 $bits = explode( '/', $title->getDBkey(), 2 );
520 if ( !isset( $bits[1] ) ) { // T4087
526 $page = $this->getPage( $name );
528 $context->getOutput()->setArticleRelated( false );
529 $context->getOutput()->setRobotPolicy( 'noindex,nofollow' );
531 global $wgSend404Code;
532 if ( $wgSend404Code ) {
533 $context->getOutput()->setStatusCode( 404 );
536 $context->getOutput()->showErrorPage( 'nosuchspecialpage', 'nospecialpagetext' );
542 // Narrow DB query expectations for this HTTP request
543 $trxLimits = $context->getConfig()->get( 'TrxProfilerLimits' );
544 $trxProfiler = Profiler
::instance()->getTransactionProfiler();
545 if ( $context->getRequest()->wasPosted() && !$page->doesWrites() ) {
546 $trxProfiler->setExpectations( $trxLimits['POST-nonwrite'], __METHOD__
);
547 $context->getRequest()->markAsSafeRequest();
551 // Page exists, set the context
552 $page->setContext( $context );
555 // Redirect to canonical alias for GET commands
556 // Not for POST, we'd lose the post data, so it's best to just distribute
557 // the request. Such POST requests are possible for old extensions that
558 // generate self-links without being aware that their default name has
560 if ( $name != $page->getLocalName() && !$context->getRequest()->wasPosted() ) {
561 $query = $context->getRequest()->getQueryValues();
562 unset( $query['title'] );
563 $title = $page->getPageTitle( $par );
564 $url = $title->getFullURL( $query );
565 $context->getOutput()->redirect( $url );
569 $context->setTitle( $page->getPageTitle( $par ) );
571 } elseif ( !$page->isIncludable() ) {
575 $page->including( $including );
576 if ( $linkRenderer ) {
577 $page->setLinkRenderer( $linkRenderer );
580 // Execute special page
587 * Just like executePath() but will override global variables and execute
588 * the page in "inclusion" mode. Returns true if the execution was
589 * successful or false if there was no such special page, or a title object
590 * if it was a redirect.
592 * Also saves the current $wgTitle, $wgOut, $wgRequest, $wgUser and $wgLang
593 * variables so that the special page will get the context it'd expect on a
594 * normal request, and then restores them to their previous values after.
596 * @param Title $title
597 * @param IContextSource $context
598 * @param LinkRenderer|null $linkRenderer (since 1.28)
599 * @return string HTML fragment
601 public function capturePath(
602 Title
$title, IContextSource
$context, LinkRenderer
$linkRenderer = null
604 global $wgTitle, $wgOut, $wgRequest, $wgUser, $wgLang;
605 $main = RequestContext
::getMain();
607 // Save current globals and main context
611 'request' => $wgRequest,
613 'language' => $wgLang,
616 'title' => $main->getTitle(),
617 'output' => $main->getOutput(),
618 'request' => $main->getRequest(),
619 'user' => $main->getUser(),
620 'language' => $main->getLanguage(),
625 $wgOut = $context->getOutput();
626 $wgRequest = $context->getRequest();
627 $wgUser = $context->getUser();
628 $wgLang = $context->getLanguage();
629 $main->setTitle( $title );
630 $main->setOutput( $context->getOutput() );
631 $main->setRequest( $context->getRequest() );
632 $main->setUser( $context->getUser() );
633 $main->setLanguage( $context->getLanguage() );
636 $ret = $this->executePath( $title, $context, true, $linkRenderer );
638 // Restore old globals and context
639 $wgTitle = $glob['title'];
640 $wgOut = $glob['output'];
641 $wgRequest = $glob['request'];
642 $wgUser = $glob['user'];
643 $wgLang = $glob['language'];
644 $main->setTitle( $ctx['title'] );
645 $main->setOutput( $ctx['output'] );
646 $main->setRequest( $ctx['request'] );
647 $main->setUser( $ctx['user'] );
648 $main->setLanguage( $ctx['language'] );
654 * Get the local name for a specified canonical name
656 * @param string $name
657 * @param string|bool $subpage
660 public function getLocalNameFor( $name, $subpage = false ) {
661 $aliases = $this->contLang
->getSpecialPageAliases();
662 $aliasList = $this->getAliasList();
664 // Find the first alias that maps back to $name
665 if ( isset( $aliases[$name] ) ) {
667 foreach ( $aliases[$name] as $alias ) {
668 $caseFoldedAlias = $this->contLang
->caseFold( $alias );
669 $caseFoldedAlias = str_replace( ' ', '_', $caseFoldedAlias );
670 if ( isset( $aliasList[$caseFoldedAlias] ) &&
671 $aliasList[$caseFoldedAlias] === $name
679 wfWarn( "Did not find a usable alias for special page '$name'. " .
680 "It seems all defined aliases conflict?" );
683 // Check if someone misspelled the correct casing
684 if ( is_array( $aliases ) ) {
685 foreach ( $aliases as $n => $values ) {
686 if ( strcasecmp( $name, $n ) === 0 ) {
687 wfWarn( "Found alias defined for $n when searching for " .
688 "special page aliases for $name. Case mismatch?" );
689 return $this->getLocalNameFor( $n, $subpage );
694 wfWarn( "Did not find alias for special page '$name'. " .
695 "Perhaps no aliases are defined for it?" );
698 if ( $subpage !== false && !is_null( $subpage ) ) {
699 // Make sure it's in dbkey form
700 $subpage = str_replace( ' ', '_', $subpage );
701 $name = "$name/$subpage";
704 return $this->contLang
->ucfirst( $name );
708 * Get a title for a given alias
710 * @param string $alias
711 * @return Title|null Title or null if there is no such alias
713 public function getTitleForAlias( $alias ) {
714 list( $name, $subpage ) = $this->resolveAlias( $alias );
715 if ( $name != null ) {
716 return SpecialPage
::getTitleFor( $name, $subpage );