Fix ApiBase::getErrorFromStatus() and ApiMessages
[mediawiki.git] / includes / specialpage / SpecialPageFactory.php
blob4c869f98dc28837d8305b61548b3bb46f7682dbf
1 <?php
2 /**
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
20 * @file
21 * @ingroup SpecialPage
22 * @defgroup SpecialPage SpecialPage
25 /**
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
44 * @since 1.17
46 class SpecialPageFactory {
47 /**
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',
76 // List of pages
77 'Allpages' => 'SpecialAllPages',
78 'Prefixindex' => 'SpecialPrefixindex',
79 'Categories' => 'SpecialCategories',
80 'Listredirects' => 'ListredirectsPage',
81 'PagesWithProp' => 'SpecialPagesWithProp',
82 'TrackingCategories' => 'SpecialTrackingCategories',
84 // Login/create account
85 'Userlogin' => 'LoginForm',
86 'CreateAccount' => 'SpecialCreateAccount',
88 // Users and rights
89 'Activeusers' => 'SpecialActiveUsers',
90 'Block' => 'SpecialBlock',
91 'Unblock' => 'SpecialUnblock',
92 'BlockList' => 'SpecialBlockList',
93 'ChangePassword' => 'SpecialChangePassword',
94 'BotPasswords' => 'SpecialBotPasswords',
95 'PasswordReset' => 'SpecialPasswordReset',
96 'DeletedContributions' => 'DeletedContributionsPage',
97 'Preferences' => 'SpecialPreferences',
98 'ResetTokens' => 'SpecialResetTokens',
99 'Contributions' => 'SpecialContributions',
100 'Listgrouprights' => 'SpecialListGroupRights',
101 'Listgrants' => 'SpecialListGrants',
102 'Listusers' => 'SpecialListUsers',
103 'Listadmins' => 'SpecialListAdmins',
104 'Listbots' => 'SpecialListBots',
105 'Userrights' => 'UserrightsPage',
106 'EditWatchlist' => 'SpecialEditWatchlist',
108 // Recent changes and logs
109 'Newimages' => 'SpecialNewFiles',
110 'Log' => 'SpecialLog',
111 'Watchlist' => 'SpecialWatchlist',
112 'Newpages' => 'SpecialNewpages',
113 'Recentchanges' => 'SpecialRecentChanges',
114 'Recentchangeslinked' => 'SpecialRecentChangesLinked',
115 'Tags' => 'SpecialTags',
117 // Media reports and uploads
118 'Listfiles' => 'SpecialListFiles',
119 'Filepath' => 'SpecialFilepath',
120 'MediaStatistics' => 'MediaStatisticsPage',
121 'MIMEsearch' => 'MIMEsearchPage',
122 'FileDuplicateSearch' => 'FileDuplicateSearchPage',
123 'Upload' => 'SpecialUpload',
124 'UploadStash' => 'SpecialUploadStash',
125 'ListDuplicatedFiles' => 'ListDuplicatedFilesPage',
127 // Data and tools
128 'ApiSandbox' => 'SpecialApiSandbox',
129 'Statistics' => 'SpecialStatistics',
130 'Allmessages' => 'SpecialAllMessages',
131 'Version' => 'SpecialVersion',
132 'Lockdb' => 'SpecialLockdb',
133 'Unlockdb' => 'SpecialUnlockdb',
135 // Redirecting special pages
136 'LinkSearch' => 'LinkSearchPage',
137 'Randompage' => 'RandomPage',
138 'RandomInCategory' => 'SpecialRandomInCategory',
139 'Randomredirect' => 'SpecialRandomredirect',
140 'Randomrootpage' => 'SpecialRandomrootpage',
142 // High use pages
143 'Mostlinkedcategories' => 'MostlinkedCategoriesPage',
144 'Mostimages' => 'MostimagesPage',
145 'Mostinterwikis' => 'MostinterwikisPage',
146 'Mostlinked' => 'MostlinkedPage',
147 'Mostlinkedtemplates' => 'MostlinkedTemplatesPage',
148 'Mostcategories' => 'MostcategoriesPage',
149 'Mostrevisions' => 'MostrevisionsPage',
151 // Page tools
152 'ComparePages' => 'SpecialComparePages',
153 'Export' => 'SpecialExport',
154 'Import' => 'SpecialImport',
155 'Undelete' => 'SpecialUndelete',
156 'Whatlinkshere' => 'SpecialWhatLinksHere',
157 'MergeHistory' => 'SpecialMergeHistory',
158 'ExpandTemplates' => 'SpecialExpandTemplates',
160 // Other
161 'Booksources' => 'SpecialBookSources',
163 // Unlisted / redirects
164 'ApiHelp' => 'SpecialApiHelp',
165 'Blankpage' => 'SpecialBlankpage',
166 'Diff' => 'SpecialDiff',
167 'EditTags' => 'SpecialEditTags',
168 'Emailuser' => 'SpecialEmailUser',
169 'Movepage' => 'MovePageForm',
170 'Mycontributions' => 'SpecialMycontributions',
171 'MyLanguage' => 'SpecialMyLanguage',
172 'Mypage' => 'SpecialMypage',
173 'Mytalk' => 'SpecialMytalk',
174 'Myuploads' => 'SpecialMyuploads',
175 'AllMyUploads' => 'SpecialAllMyUploads',
176 'PermanentLink' => 'SpecialPermanentLink',
177 'Redirect' => 'SpecialRedirect',
178 'Revisiondelete' => 'SpecialRevisionDelete',
179 'RunJobs' => 'SpecialRunJobs',
180 'Specialpages' => 'SpecialSpecialpages',
181 'Userlogout' => 'SpecialUserlogout',
184 private static $list;
185 private static $aliases;
186 private static $pageObjectCache = [];
189 * Reset the internal list of special pages. Useful when changing $wgSpecialPages after
190 * the internal list has already been initialized, e.g. during testing.
192 public static function resetList() {
193 self::$list = null;
194 self::$aliases = null;
195 self::$pageObjectCache = [];
199 * Returns a list of canonical special page names.
200 * May be used to iterate over all registered special pages.
202 * @return string[]
204 public static function getNames() {
205 return array_keys( self::getPageList() );
209 * Get the special page list as an array
211 * @deprecated since 1.24, use getNames() instead.
212 * @return array
214 public static function getList() {
215 wfDeprecated( __FUNCTION__, '1.24' );
216 return self::getPageList();
220 * Get the special page list as an array
222 * @return array
224 private static function getPageList() {
225 global $wgSpecialPages;
226 global $wgDisableInternalSearch, $wgEmailAuthentication;
227 global $wgEnableEmail, $wgEnableJavaScriptTest;
228 global $wgPageLanguageUseDB, $wgContentHandlerUseDB;
230 if ( !is_array( self::$list ) ) {
232 self::$list = self::$coreList;
234 if ( !$wgDisableInternalSearch ) {
235 self::$list['Search'] = 'SpecialSearch';
238 if ( $wgEmailAuthentication ) {
239 self::$list['Confirmemail'] = 'EmailConfirmation';
240 self::$list['Invalidateemail'] = 'EmailInvalidation';
243 if ( $wgEnableEmail ) {
244 self::$list['ChangeEmail'] = 'SpecialChangeEmail';
247 if ( $wgEnableJavaScriptTest ) {
248 self::$list['JavaScriptTest'] = 'SpecialJavaScriptTest';
251 if ( $wgPageLanguageUseDB ) {
252 self::$list['PageLanguage'] = 'SpecialPageLanguage';
254 if ( $wgContentHandlerUseDB ) {
255 self::$list['ChangeContentModel'] = 'SpecialChangeContentModel';
258 // Add extension special pages
259 self::$list = array_merge( self::$list, $wgSpecialPages );
261 // This hook can be used to disable unwanted core special pages
262 // or conditionally register special pages.
263 Hooks::run( 'SpecialPage_initList', [ &self::$list ] );
267 return self::$list;
271 * Initialise and return the list of special page aliases. Returns an array where
272 * the key is an alias, and the value is the canonical name of the special page.
273 * All registered special pages are guaranteed to map to themselves.
274 * @return array
276 private static function getAliasList() {
277 if ( is_null( self::$aliases ) ) {
278 global $wgContLang;
279 $aliases = $wgContLang->getSpecialPageAliases();
280 $pageList = self::getPageList();
282 self::$aliases = [];
283 $keepAlias = [];
285 // Force every canonical name to be an alias for itself.
286 foreach ( $pageList as $name => $stuff ) {
287 $caseFoldedAlias = $wgContLang->caseFold( $name );
288 self::$aliases[$caseFoldedAlias] = $name;
289 $keepAlias[$caseFoldedAlias] = 'canonical';
292 // Check for $aliases being an array since Language::getSpecialPageAliases can return null
293 if ( is_array( $aliases ) ) {
294 foreach ( $aliases as $realName => $aliasList ) {
295 $aliasList = array_values( $aliasList );
296 foreach ( $aliasList as $i => $alias ) {
297 $caseFoldedAlias = $wgContLang->caseFold( $alias );
299 if ( isset( self::$aliases[$caseFoldedAlias] ) &&
300 $realName === self::$aliases[$caseFoldedAlias]
302 // Ignore same-realName conflicts
303 continue;
306 if ( !isset( $keepAlias[$caseFoldedAlias] ) ) {
307 self::$aliases[$caseFoldedAlias] = $realName;
308 if ( !$i ) {
309 $keepAlias[$caseFoldedAlias] = 'first';
311 } elseif ( !$i ) {
312 wfWarn( "First alias '$alias' for $realName conflicts with " .
313 "{$keepAlias[$caseFoldedAlias]} alias for " .
314 self::$aliases[$caseFoldedAlias]
322 return self::$aliases;
326 * Given a special page name with a possible subpage, return an array
327 * where the first element is the special page name and the second is the
328 * subpage.
330 * @param string $alias
331 * @return array Array( String, String|null ), or array( null, null ) if the page is invalid
333 public static function resolveAlias( $alias ) {
334 global $wgContLang;
335 $bits = explode( '/', $alias, 2 );
337 $caseFoldedAlias = $wgContLang->caseFold( $bits[0] );
338 $caseFoldedAlias = str_replace( ' ', '_', $caseFoldedAlias );
339 $aliases = self::getAliasList();
340 if ( isset( $aliases[$caseFoldedAlias] ) ) {
341 $name = $aliases[$caseFoldedAlias];
342 } else {
343 return [ null, null ];
346 if ( !isset( $bits[1] ) ) { // bug 2087
347 $par = null;
348 } else {
349 $par = $bits[1];
352 return [ $name, $par ];
356 * Check if a given name exist as a special page or as a special page alias
358 * @param string $name Name of a special page
359 * @return bool True if a special page exists with this name
361 public static function exists( $name ) {
362 list( $title, /*...*/ ) = self::resolveAlias( $name );
364 $specialPageList = self::getPageList();
365 return isset( $specialPageList[$title] );
369 * Find the object with a given name and return it (or NULL)
371 * @param string $name Special page name, may be localised and/or an alias
372 * @return SpecialPage|null SpecialPage object or null if the page doesn't exist
374 public static function getPage( $name ) {
375 list( $realName, /*...*/ ) = self::resolveAlias( $name );
377 if ( isset( self::$pageObjectCache[$realName] ) ) {
378 return self::$pageObjectCache[$realName];
381 $specialPageList = self::getPageList();
383 if ( isset( $specialPageList[$realName] ) ) {
384 $rec = $specialPageList[$realName];
386 if ( is_callable( $rec ) ) {
387 // Use callback to instantiate the special page
388 $page = call_user_func( $rec );
389 } elseif ( is_string( $rec ) ) {
390 $className = $rec;
391 $page = new $className;
392 } elseif ( is_array( $rec ) ) {
393 $className = array_shift( $rec );
394 // @deprecated, officially since 1.18, unofficially since forever
395 wfDeprecated( "Array syntax for \$wgSpecialPages is deprecated ($className), " .
396 "define a subclass of SpecialPage instead.", '1.18' );
397 $page = ObjectFactory::getObjectFromSpec( [
398 'class' => $className,
399 'args' => $rec,
400 'closure_expansion' => false,
401 ] );
402 } elseif ( $rec instanceof SpecialPage ) {
403 $page = $rec; // XXX: we should deep clone here
404 } else {
405 $page = null;
408 self::$pageObjectCache[$realName] = $page;
409 if ( $page instanceof SpecialPage ) {
410 return $page;
411 } else {
412 // It's not a classname, nor a callback, nor a legacy constructor array,
413 // nor a special page object. Give up.
414 wfLogWarning( "Cannot instantiate special page $realName: bad spec!" );
415 return null;
418 } else {
419 return null;
424 * Return categorised listable special pages which are available
425 * for the current user, and everyone.
427 * @param User $user User object to check permissions, $wgUser will be used
428 * if not provided
429 * @return array ( string => Specialpage )
431 public static function getUsablePages( User $user = null ) {
432 $pages = [];
433 if ( $user === null ) {
434 global $wgUser;
435 $user = $wgUser;
437 foreach ( self::getPageList() as $name => $rec ) {
438 $page = self::getPage( $name );
439 if ( $page ) { // not null
440 $page->setContext( RequestContext::getMain() );
441 if ( $page->isListed()
442 && ( !$page->isRestricted() || $page->userCanExecute( $user ) )
444 $pages[$name] = $page;
449 return $pages;
453 * Return categorised listable special pages for all users
455 * @return array ( string => Specialpage )
457 public static function getRegularPages() {
458 $pages = [];
459 foreach ( self::getPageList() as $name => $rec ) {
460 $page = self::getPage( $name );
461 if ( $page->isListed() && !$page->isRestricted() ) {
462 $pages[$name] = $page;
466 return $pages;
470 * Return categorised listable special pages which are available
471 * for the current user, but not for everyone
473 * @param User|null $user User object to use or null for $wgUser
474 * @return array ( string => Specialpage )
476 public static function getRestrictedPages( User $user = null ) {
477 $pages = [];
478 if ( $user === null ) {
479 global $wgUser;
480 $user = $wgUser;
482 foreach ( self::getPageList() as $name => $rec ) {
483 $page = self::getPage( $name );
484 if (
485 $page->isListed()
486 && $page->isRestricted()
487 && $page->userCanExecute( $user )
489 $pages[$name] = $page;
493 return $pages;
497 * Execute a special page path.
498 * The path may contain parameters, e.g. Special:Name/Params
499 * Extracts the special page name and call the execute method, passing the parameters
501 * Returns a title object if the page is redirected, false if there was no such special
502 * page, and true if it was successful.
504 * @param Title $title
505 * @param IContextSource $context
506 * @param bool $including Bool output is being captured for use in {{special:whatever}}
508 * @return bool
510 public static function executePath( Title &$title, IContextSource &$context, $including = false ) {
511 // @todo FIXME: Redirects broken due to this call
512 $bits = explode( '/', $title->getDBkey(), 2 );
513 $name = $bits[0];
514 if ( !isset( $bits[1] ) ) { // bug 2087
515 $par = null;
516 } else {
517 $par = $bits[1];
520 $page = self::getPage( $name );
521 if ( !$page ) {
522 $context->getOutput()->setArticleRelated( false );
523 $context->getOutput()->setRobotPolicy( 'noindex,nofollow' );
525 global $wgSend404Code;
526 if ( $wgSend404Code ) {
527 $context->getOutput()->setStatusCode( 404 );
530 $context->getOutput()->showErrorPage( 'nosuchspecialpage', 'nospecialpagetext' );
532 return false;
535 if ( !$including ) {
536 // Narrow DB query expectations for this HTTP request
537 $trxLimits = $context->getConfig()->get( 'TrxProfilerLimits' );
538 $trxProfiler = Profiler::instance()->getTransactionProfiler();
539 if ( $context->getRequest()->wasPosted() && !$page->doesWrites() ) {
540 $trxProfiler->setExpectations( $trxLimits['POST-nonwrite'], __METHOD__ );
541 $context->getRequest()->markAsSafeRequest();
545 // Page exists, set the context
546 $page->setContext( $context );
548 if ( !$including ) {
549 // Redirect to canonical alias for GET commands
550 // Not for POST, we'd lose the post data, so it's best to just distribute
551 // the request. Such POST requests are possible for old extensions that
552 // generate self-links without being aware that their default name has
553 // changed.
554 if ( $name != $page->getLocalName() && !$context->getRequest()->wasPosted() ) {
555 $query = $context->getRequest()->getQueryValues();
556 unset( $query['title'] );
557 $title = $page->getPageTitle( $par );
558 $url = $title->getFullURL( $query );
559 $context->getOutput()->redirect( $url );
561 return $title;
562 } else {
563 $context->setTitle( $page->getPageTitle( $par ) );
565 } elseif ( !$page->isIncludable() ) {
566 return false;
569 $page->including( $including );
571 // Execute special page
572 $page->run( $par );
574 return true;
578 * Just like executePath() but will override global variables and execute
579 * the page in "inclusion" mode. Returns true if the execution was
580 * successful or false if there was no such special page, or a title object
581 * if it was a redirect.
583 * Also saves the current $wgTitle, $wgOut, $wgRequest, $wgUser and $wgLang
584 * variables so that the special page will get the context it'd expect on a
585 * normal request, and then restores them to their previous values after.
587 * @param Title $title
588 * @param IContextSource $context
589 * @return string HTML fragment
591 public static function capturePath( Title $title, IContextSource $context ) {
592 global $wgTitle, $wgOut, $wgRequest, $wgUser, $wgLang;
593 $main = RequestContext::getMain();
595 // Save current globals and main context
596 $glob = [
597 'title' => $wgTitle,
598 'output' => $wgOut,
599 'request' => $wgRequest,
600 'user' => $wgUser,
601 'language' => $wgLang,
603 $ctx = [
604 'title' => $main->getTitle(),
605 'output' => $main->getOutput(),
606 'request' => $main->getRequest(),
607 'user' => $main->getUser(),
608 'language' => $main->getLanguage(),
611 // Override
612 $wgTitle = $title;
613 $wgOut = $context->getOutput();
614 $wgRequest = $context->getRequest();
615 $wgUser = $context->getUser();
616 $wgLang = $context->getLanguage();
617 $main->setTitle( $title );
618 $main->setOutput( $context->getOutput() );
619 $main->setRequest( $context->getRequest() );
620 $main->setUser( $context->getUser() );
621 $main->setLanguage( $context->getLanguage() );
623 // The useful part
624 $ret = self::executePath( $title, $context, true );
626 // Restore old globals and context
627 $wgTitle = $glob['title'];
628 $wgOut = $glob['output'];
629 $wgRequest = $glob['request'];
630 $wgUser = $glob['user'];
631 $wgLang = $glob['language'];
632 $main->setTitle( $ctx['title'] );
633 $main->setOutput( $ctx['output'] );
634 $main->setRequest( $ctx['request'] );
635 $main->setUser( $ctx['user'] );
636 $main->setLanguage( $ctx['language'] );
638 return $ret;
642 * Get the local name for a specified canonical name
644 * @param string $name
645 * @param string|bool $subpage
646 * @return string
648 public static function getLocalNameFor( $name, $subpage = false ) {
649 global $wgContLang;
650 $aliases = $wgContLang->getSpecialPageAliases();
651 $aliasList = self::getAliasList();
653 // Find the first alias that maps back to $name
654 if ( isset( $aliases[$name] ) ) {
655 $found = false;
656 foreach ( $aliases[$name] as $alias ) {
657 $caseFoldedAlias = $wgContLang->caseFold( $alias );
658 $caseFoldedAlias = str_replace( ' ', '_', $caseFoldedAlias );
659 if ( isset( $aliasList[$caseFoldedAlias] ) &&
660 $aliasList[$caseFoldedAlias] === $name
662 $name = $alias;
663 $found = true;
664 break;
667 if ( !$found ) {
668 wfWarn( "Did not find a usable alias for special page '$name'. " .
669 "It seems all defined aliases conflict?" );
671 } else {
672 // Check if someone misspelled the correct casing
673 if ( is_array( $aliases ) ) {
674 foreach ( $aliases as $n => $values ) {
675 if ( strcasecmp( $name, $n ) === 0 ) {
676 wfWarn( "Found alias defined for $n when searching for " .
677 "special page aliases for $name. Case mismatch?" );
678 return self::getLocalNameFor( $n, $subpage );
683 wfWarn( "Did not find alias for special page '$name'. " .
684 "Perhaps no aliases are defined for it?" );
687 if ( $subpage !== false && !is_null( $subpage ) ) {
688 $name = "$name/$subpage";
691 return $wgContLang->ucfirst( $name );
695 * Get a title for a given alias
697 * @param string $alias
698 * @return Title|null Title or null if there is no such alias
700 public static function getTitleForAlias( $alias ) {
701 list( $name, $subpage ) = self::resolveAlias( $alias );
702 if ( $name != null ) {
703 return SpecialPage::getTitleFor( $name, $subpage );
704 } else {
705 return null;