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
;
39 * Factory for handling the special page list and generating SpecialPage objects.
41 * To add a special page in an extension, add to $wgSpecialPages either
42 * an object instance or an array containing the name and constructor
43 * parameters. The latter is preferred for performance reasons.
45 * The object instantiated must be either an instance of SpecialPage or a
46 * sub-class thereof. It must have an execute() method, which sends the HTML
47 * for the special page to $wgOut. The parent class has an execute() method
48 * which distributes the call to the historical global functions. Additionally,
49 * execute() also checks if the user has the necessary access privileges
50 * and bails out if not.
52 * To add a core special page, use the similar static list in
53 * SpecialPageFactory::$list. To remove a core static special page at runtime, use
54 * a SpecialPage_initList hook.
56 * @note There are two classes called SpecialPageFactory. You should use this first one, in
57 * namespace MediaWiki\Special, which is a service. \SpecialPageFactory is a deprecated collection
58 * of static methods that forwards to the global service.
60 * @ingroup SpecialPage
63 class SpecialPageFactory
{
65 * List of special page names to the subclass of SpecialPage which handles them.
66 * @todo Make this a const when we drop HHVM support (T192166). It can still be private in PHP
69 private static $coreList = [
70 // Maintenance Reports
71 'BrokenRedirects' => \BrokenRedirectsPage
::class,
72 'Deadendpages' => \DeadendPagesPage
::class,
73 'DoubleRedirects' => \DoubleRedirectsPage
::class,
74 'Longpages' => \LongPagesPage
::class,
75 'Ancientpages' => \AncientPagesPage
::class,
76 'Lonelypages' => \LonelyPagesPage
::class,
77 'Fewestrevisions' => \FewestrevisionsPage
::class,
78 'Withoutinterwiki' => \WithoutInterwikiPage
::class,
79 'Protectedpages' => \SpecialProtectedpages
::class,
80 'Protectedtitles' => \SpecialProtectedtitles
::class,
81 'Shortpages' => \ShortPagesPage
::class,
82 'Uncategorizedcategories' => \UncategorizedCategoriesPage
::class,
83 'Uncategorizedimages' => \UncategorizedImagesPage
::class,
84 'Uncategorizedpages' => \UncategorizedPagesPage
::class,
85 'Uncategorizedtemplates' => \UncategorizedTemplatesPage
::class,
86 'Unusedcategories' => \UnusedCategoriesPage
::class,
87 'Unusedimages' => \UnusedimagesPage
::class,
88 'Unusedtemplates' => \UnusedtemplatesPage
::class,
89 'Unwatchedpages' => \UnwatchedpagesPage
::class,
90 'Wantedcategories' => \WantedCategoriesPage
::class,
91 'Wantedfiles' => \WantedFilesPage
::class,
92 'Wantedpages' => \WantedPagesPage
::class,
93 'Wantedtemplates' => \WantedTemplatesPage
::class,
96 'Allpages' => \SpecialAllPages
::class,
97 'Prefixindex' => \SpecialPrefixindex
::class,
98 'Categories' => \SpecialCategories
::class,
99 'Listredirects' => \ListredirectsPage
::class,
100 'PagesWithProp' => \SpecialPagesWithProp
::class,
101 'TrackingCategories' => \SpecialTrackingCategories
::class,
104 'Userlogin' => \SpecialUserLogin
::class,
105 'Userlogout' => \SpecialUserLogout
::class,
106 'CreateAccount' => \SpecialCreateAccount
::class,
107 'LinkAccounts' => \SpecialLinkAccounts
::class,
108 'UnlinkAccounts' => \SpecialUnlinkAccounts
::class,
109 'ChangeCredentials' => \SpecialChangeCredentials
::class,
110 'RemoveCredentials' => \SpecialRemoveCredentials
::class,
113 'Activeusers' => \SpecialActiveUsers
::class,
114 'Block' => \SpecialBlock
::class,
115 'Unblock' => \SpecialUnblock
::class,
116 'BlockList' => \SpecialBlockList
::class,
117 'AutoblockList' => \SpecialAutoblockList
::class,
118 'ChangePassword' => \SpecialChangePassword
::class,
119 'BotPasswords' => \SpecialBotPasswords
::class,
120 'PasswordReset' => \SpecialPasswordReset
::class,
121 'DeletedContributions' => \DeletedContributionsPage
::class,
122 'Preferences' => \SpecialPreferences
::class,
123 'ResetTokens' => \SpecialResetTokens
::class,
124 'Contributions' => \SpecialContributions
::class,
125 'Listgrouprights' => \SpecialListGroupRights
::class,
126 'Listgrants' => \SpecialListGrants
::class,
127 'Listusers' => \SpecialListUsers
::class,
128 'Listadmins' => \SpecialListAdmins
::class,
129 'Listbots' => \SpecialListBots
::class,
130 'Userrights' => \UserrightsPage
::class,
131 'EditWatchlist' => \SpecialEditWatchlist
::class,
132 'PasswordPolicies' => \SpecialPasswordPolicies
::class,
134 // Recent changes and logs
135 'Newimages' => \SpecialNewFiles
::class,
136 'Log' => \SpecialLog
::class,
137 'Watchlist' => \SpecialWatchlist
::class,
138 'Newpages' => \SpecialNewpages
::class,
139 'Recentchanges' => \SpecialRecentChanges
::class,
140 'Recentchangeslinked' => \SpecialRecentChangesLinked
::class,
141 'Tags' => \SpecialTags
::class,
143 // Media reports and uploads
144 'Listfiles' => \SpecialListFiles
::class,
145 'Filepath' => \SpecialFilepath
::class,
146 'MediaStatistics' => \MediaStatisticsPage
::class,
147 'MIMEsearch' => \MIMEsearchPage
::class,
148 'FileDuplicateSearch' => \FileDuplicateSearchPage
::class,
149 'Upload' => \SpecialUpload
::class,
150 'UploadStash' => \SpecialUploadStash
::class,
151 'ListDuplicatedFiles' => \ListDuplicatedFilesPage
::class,
154 'ApiSandbox' => \SpecialApiSandbox
::class,
155 'Statistics' => \SpecialStatistics
::class,
156 'Allmessages' => \SpecialAllMessages
::class,
157 'Version' => \SpecialVersion
::class,
158 'Lockdb' => \SpecialLockdb
::class,
159 'Unlockdb' => \SpecialUnlockdb
::class,
161 // Redirecting special pages
162 'LinkSearch' => \LinkSearchPage
::class,
163 'Randompage' => \RandomPage
::class,
164 'RandomInCategory' => \SpecialRandomInCategory
::class,
165 'Randomredirect' => \SpecialRandomredirect
::class,
166 'Randomrootpage' => \SpecialRandomrootpage
::class,
167 'GoToInterwiki' => \SpecialGoToInterwiki
::class,
170 'Mostlinkedcategories' => \MostlinkedCategoriesPage
::class,
171 'Mostimages' => \MostimagesPage
::class,
172 'Mostinterwikis' => \MostinterwikisPage
::class,
173 'Mostlinked' => \MostlinkedPage
::class,
174 'Mostlinkedtemplates' => \MostlinkedTemplatesPage
::class,
175 'Mostcategories' => \MostcategoriesPage
::class,
176 'Mostrevisions' => \MostrevisionsPage
::class,
179 'ComparePages' => \SpecialComparePages
::class,
180 'Export' => \SpecialExport
::class,
181 'Import' => \SpecialImport
::class,
182 'Undelete' => \SpecialUndelete
::class,
183 'Whatlinkshere' => \SpecialWhatLinksHere
::class,
184 'MergeHistory' => \SpecialMergeHistory
::class,
185 'ExpandTemplates' => \SpecialExpandTemplates
::class,
188 'Booksources' => \SpecialBookSources
::class,
190 // Unlisted / redirects
191 'ApiHelp' => \SpecialApiHelp
::class,
192 'Blankpage' => \SpecialBlankpage
::class,
193 'Diff' => \SpecialDiff
::class,
194 'EditTags' => \SpecialEditTags
::class,
195 'Emailuser' => \SpecialEmailUser
::class,
196 'Movepage' => \MovePageForm
::class,
197 'Mycontributions' => \SpecialMycontributions
::class,
198 'MyLanguage' => \SpecialMyLanguage
::class,
199 'Mypage' => \SpecialMypage
::class,
200 'Mytalk' => \SpecialMytalk
::class,
201 'Myuploads' => \SpecialMyuploads
::class,
202 'AllMyUploads' => \SpecialAllMyUploads
::class,
203 'PermanentLink' => \SpecialPermanentLink
::class,
204 'Redirect' => \SpecialRedirect
::class,
205 'Revisiondelete' => \SpecialRevisionDelete
::class,
206 'RunJobs' => \SpecialRunJobs
::class,
207 'Specialpages' => \SpecialSpecialpages
::class,
208 'PageData' => \SpecialPageData
::class,
211 /** @var array Special page name => class name */
224 * @param Config $config
225 * @param Language $contLang
227 public function __construct( Config
$config, Language
$contLang ) {
228 $this->config
= $config;
229 $this->contLang
= $contLang;
233 * Returns a list of canonical special page names.
234 * May be used to iterate over all registered special pages.
238 public function getNames() : array {
239 return array_keys( $this->getPageList() );
243 * Get the special page list as an array
247 private function getPageList() : array {
248 if ( !is_array( $this->list ) ) {
249 $this->list = self
::$coreList;
251 if ( !$this->config
->get( 'DisableInternalSearch' ) ) {
252 $this->list['Search'] = \SpecialSearch
::class;
255 if ( $this->config
->get( 'EmailAuthentication' ) ) {
256 $this->list['Confirmemail'] = \EmailConfirmation
::class;
257 $this->list['Invalidateemail'] = \EmailInvalidation
::class;
260 if ( $this->config
->get( 'EnableEmail' ) ) {
261 $this->list['ChangeEmail'] = \SpecialChangeEmail
::class;
264 if ( $this->config
->get( 'EnableJavaScriptTest' ) ) {
265 $this->list['JavaScriptTest'] = \SpecialJavaScriptTest
::class;
268 if ( $this->config
->get( 'PageLanguageUseDB' ) ) {
269 $this->list['PageLanguage'] = \SpecialPageLanguage
::class;
271 if ( $this->config
->get( 'ContentHandlerUseDB' ) ) {
272 $this->list['ChangeContentModel'] = \SpecialChangeContentModel
::class;
275 // Add extension special pages
276 $this->list = array_merge( $this->list, $this->config
->get( 'SpecialPages' ) );
278 // This hook can be used to disable unwanted core special pages
279 // or conditionally register special pages.
280 Hooks
::run( 'SpecialPage_initList', [ &$this->list ] );
288 * Initialise and return the list of special page aliases. Returns an array where
289 * the key is an alias, and the value is the canonical name of the special page.
290 * All registered special pages are guaranteed to map to themselves.
293 private function getAliasList() : array {
294 if ( is_null( $this->aliases
) ) {
295 $aliases = $this->contLang
->getSpecialPageAliases();
296 $pageList = $this->getPageList();
301 // Force every canonical name to be an alias for itself.
302 foreach ( $pageList as $name => $stuff ) {
303 $caseFoldedAlias = $this->contLang
->caseFold( $name );
304 $this->aliases
[$caseFoldedAlias] = $name;
305 $keepAlias[$caseFoldedAlias] = 'canonical';
308 // Check for $aliases being an array since Language::getSpecialPageAliases can return null
309 if ( is_array( $aliases ) ) {
310 foreach ( $aliases as $realName => $aliasList ) {
311 $aliasList = array_values( $aliasList );
312 foreach ( $aliasList as $i => $alias ) {
313 $caseFoldedAlias = $this->contLang
->caseFold( $alias );
315 if ( isset( $this->aliases
[$caseFoldedAlias] ) &&
316 $realName === $this->aliases
[$caseFoldedAlias]
318 // Ignore same-realName conflicts
322 if ( !isset( $keepAlias[$caseFoldedAlias] ) ) {
323 $this->aliases
[$caseFoldedAlias] = $realName;
325 $keepAlias[$caseFoldedAlias] = 'first';
328 wfWarn( "First alias '$alias' for $realName conflicts with " .
329 "{$keepAlias[$caseFoldedAlias]} alias for " .
330 $this->aliases
[$caseFoldedAlias]
338 return $this->aliases
;
342 * Given a special page name with a possible subpage, return an array
343 * where the first element is the special page name and the second is the
346 * @param string $alias
347 * @return array Array( String, String|null ), or array( null, null ) if the page is invalid
349 public function resolveAlias( $alias ) {
350 $bits = explode( '/', $alias, 2 );
352 $caseFoldedAlias = $this->contLang
->caseFold( $bits[0] );
353 $caseFoldedAlias = str_replace( ' ', '_', $caseFoldedAlias );
354 $aliases = $this->getAliasList();
355 if ( !isset( $aliases[$caseFoldedAlias] ) ) {
356 return [ null, null ];
358 $name = $aliases[$caseFoldedAlias];
359 $par = $bits[1] ??
null; // T4087
361 return [ $name, $par ];
365 * Check if a given name exist as a special page or as a special page alias
367 * @param string $name Name of a special page
368 * @return bool True if a special page exists with this name
370 public function exists( $name ) {
371 list( $title, /*...*/ ) = $this->resolveAlias( $name );
373 $specialPageList = $this->getPageList();
374 return isset( $specialPageList[$title] );
378 * Find the object with a given name and return it (or NULL)
380 * @param string $name Special page name, may be localised and/or an alias
381 * @return SpecialPage|null SpecialPage object or null if the page doesn't exist
383 public function getPage( $name ) {
384 list( $realName, /*...*/ ) = $this->resolveAlias( $name );
386 $specialPageList = $this->getPageList();
388 if ( isset( $specialPageList[$realName] ) ) {
389 $rec = $specialPageList[$realName];
391 if ( is_callable( $rec ) ) {
392 // Use callback to instantiate the special page
394 } elseif ( is_string( $rec ) ) {
396 $page = new $className;
397 } elseif ( $rec instanceof SpecialPage
) {
398 $page = $rec; // XXX: we should deep clone here
403 if ( $page instanceof SpecialPage
) {
407 // It's not a classname, nor a callback, nor a legacy constructor array,
408 // nor a special page object. Give up.
409 wfLogWarning( "Cannot instantiate special page $realName: bad spec!" );
416 * Return categorised listable special pages which are available
417 * for the current user, and everyone.
419 * @param User $user User object to check permissions
421 * @return array ( string => Specialpage )
423 public function getUsablePages( User
$user ) : array {
425 foreach ( $this->getPageList() as $name => $rec ) {
426 $page = $this->getPage( $name );
427 if ( $page ) { // not null
428 $page->setContext( RequestContext
::getMain() );
429 if ( $page->isListed()
430 && ( !$page->isRestricted() ||
$page->userCanExecute( $user ) )
432 $pages[$name] = $page;
441 * Return categorised listable special pages for all users
443 * @return array ( string => Specialpage )
445 public function getRegularPages() : array {
447 foreach ( $this->getPageList() as $name => $rec ) {
448 $page = $this->getPage( $name );
449 if ( $page && $page->isListed() && !$page->isRestricted() ) {
450 $pages[$name] = $page;
458 * Return categorised listable special pages which are available
459 * for the current user, but not for everyone
461 * @param User $user User object to use
462 * @return array ( string => Specialpage )
464 public function getRestrictedPages( User
$user ) : array {
466 foreach ( $this->getPageList() as $name => $rec ) {
467 $page = $this->getPage( $name );
470 && $page->isRestricted()
471 && $page->userCanExecute( $user )
473 $pages[$name] = $page;
481 * Execute a special page path.
482 * The path may contain parameters, e.g. Special:Name/Params
483 * Extracts the special page name and call the execute method, passing the parameters
485 * Returns a title object if the page is redirected, false if there was no such special
486 * page, and true if it was successful.
488 * @param Title &$title
489 * @param IContextSource &$context
490 * @param bool $including Bool output is being captured for use in {{special:whatever}}
491 * @param LinkRenderer|null $linkRenderer (since 1.28)
495 public function executePath( Title
&$title, IContextSource
&$context, $including = false,
496 LinkRenderer
$linkRenderer = null
498 // @todo FIXME: Redirects broken due to this call
499 $bits = explode( '/', $title->getDBkey(), 2 );
501 $par = $bits[1] ??
null; // T4087
503 $page = $this->getPage( $name );
505 $context->getOutput()->setArticleRelated( false );
506 $context->getOutput()->setRobotPolicy( 'noindex,nofollow' );
508 global $wgSend404Code;
509 if ( $wgSend404Code ) {
510 $context->getOutput()->setStatusCode( 404 );
513 $context->getOutput()->showErrorPage( 'nosuchspecialpage', 'nospecialpagetext' );
519 // Narrow DB query expectations for this HTTP request
520 $trxLimits = $context->getConfig()->get( 'TrxProfilerLimits' );
521 $trxProfiler = Profiler
::instance()->getTransactionProfiler();
522 if ( $context->getRequest()->wasPosted() && !$page->doesWrites() ) {
523 $trxProfiler->setExpectations( $trxLimits['POST-nonwrite'], __METHOD__
);
524 $context->getRequest()->markAsSafeRequest();
528 // Page exists, set the context
529 $page->setContext( $context );
532 // Redirect to canonical alias for GET commands
533 // Not for POST, we'd lose the post data, so it's best to just distribute
534 // the request. Such POST requests are possible for old extensions that
535 // generate self-links without being aware that their default name has
537 if ( $name != $page->getLocalName() && !$context->getRequest()->wasPosted() ) {
538 $query = $context->getRequest()->getQueryValues();
539 unset( $query['title'] );
540 $title = $page->getPageTitle( $par );
541 $url = $title->getFullURL( $query );
542 $context->getOutput()->redirect( $url );
547 $context->setTitle( $page->getPageTitle( $par ) );
548 } elseif ( !$page->isIncludable() ) {
552 $page->including( $including );
553 if ( $linkRenderer ) {
554 $page->setLinkRenderer( $linkRenderer );
557 // Execute special page
564 * Just like executePath() but will override global variables and execute
565 * the page in "inclusion" mode. Returns true if the execution was
566 * successful or false if there was no such special page, or a title object
567 * if it was a redirect.
569 * Also saves the current $wgTitle, $wgOut, $wgRequest, $wgUser and $wgLang
570 * variables so that the special page will get the context it'd expect on a
571 * normal request, and then restores them to their previous values after.
573 * @param Title $title
574 * @param IContextSource $context
575 * @param LinkRenderer|null $linkRenderer (since 1.28)
576 * @return string HTML fragment
578 public function capturePath(
579 Title
$title, IContextSource
$context, LinkRenderer
$linkRenderer = null
581 global $wgTitle, $wgOut, $wgRequest, $wgUser, $wgLang;
582 $main = RequestContext
::getMain();
584 // Save current globals and main context
588 'request' => $wgRequest,
590 'language' => $wgLang,
593 'title' => $main->getTitle(),
594 'output' => $main->getOutput(),
595 'request' => $main->getRequest(),
596 'user' => $main->getUser(),
597 'language' => $main->getLanguage(),
599 if ( $main->canUseWikiPage() ) {
600 $ctx['wikipage'] = $main->getWikiPage();
605 $wgOut = $context->getOutput();
606 $wgRequest = $context->getRequest();
607 $wgUser = $context->getUser();
608 $wgLang = $context->getLanguage();
609 $main->setTitle( $title );
610 $main->setOutput( $context->getOutput() );
611 $main->setRequest( $context->getRequest() );
612 $main->setUser( $context->getUser() );
613 $main->setLanguage( $context->getLanguage() );
616 $ret = $this->executePath( $title, $context, true, $linkRenderer );
618 // Restore old globals and context
619 $wgTitle = $glob['title'];
620 $wgOut = $glob['output'];
621 $wgRequest = $glob['request'];
622 $wgUser = $glob['user'];
623 $wgLang = $glob['language'];
624 $main->setTitle( $ctx['title'] );
625 $main->setOutput( $ctx['output'] );
626 $main->setRequest( $ctx['request'] );
627 $main->setUser( $ctx['user'] );
628 $main->setLanguage( $ctx['language'] );
629 if ( isset( $ctx['wikipage'] ) ) {
630 $main->setWikiPage( $ctx['wikipage'] );
637 * Get the local name for a specified canonical name
639 * @param string $name
640 * @param string|bool $subpage
643 public function getLocalNameFor( $name, $subpage = false ) {
644 $aliases = $this->contLang
->getSpecialPageAliases();
645 $aliasList = $this->getAliasList();
647 // Find the first alias that maps back to $name
648 if ( isset( $aliases[$name] ) ) {
650 foreach ( $aliases[$name] as $alias ) {
651 $caseFoldedAlias = $this->contLang
->caseFold( $alias );
652 $caseFoldedAlias = str_replace( ' ', '_', $caseFoldedAlias );
653 if ( isset( $aliasList[$caseFoldedAlias] ) &&
654 $aliasList[$caseFoldedAlias] === $name
662 wfWarn( "Did not find a usable alias for special page '$name'. " .
663 "It seems all defined aliases conflict?" );
666 // Check if someone misspelled the correct casing
667 if ( is_array( $aliases ) ) {
668 foreach ( $aliases as $n => $values ) {
669 if ( strcasecmp( $name, $n ) === 0 ) {
670 wfWarn( "Found alias defined for $n when searching for " .
671 "special page aliases for $name. Case mismatch?" );
672 return $this->getLocalNameFor( $n, $subpage );
677 wfWarn( "Did not find alias for special page '$name'. " .
678 "Perhaps no aliases are defined for it?" );
681 if ( $subpage !== false && !is_null( $subpage ) ) {
682 // Make sure it's in dbkey form
683 $subpage = str_replace( ' ', '_', $subpage );
684 $name = "$name/$subpage";
687 return $this->contLang
->ucfirst( $name );
691 * Get a title for a given alias
693 * @param string $alias
694 * @return Title|null Title or null if there is no such alias
696 public function getTitleForAlias( $alias ) {
697 list( $name, $subpage ) = $this->resolveAlias( $alias );
698 if ( $name != null ) {
699 return SpecialPage
::getTitleFor( $name, $subpage );