PHPSessionHandler: Implement SessionHandlerInterface
[mediawiki.git] / includes / specialpage / SpecialPageFactory.php
blob030e7e59a40372819205f06259668c6f0c711891
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 = array(
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 'Block' => 'SpecialBlock',
90 'Unblock' => 'SpecialUnblock',
91 'BlockList' => 'SpecialBlockList',
92 'ChangePassword' => 'SpecialChangePassword',
93 'BotPasswords' => 'SpecialBotPasswords',
94 'PasswordReset' => 'SpecialPasswordReset',
95 'DeletedContributions' => 'DeletedContributionsPage',
96 'Preferences' => 'SpecialPreferences',
97 'ResetTokens' => 'SpecialResetTokens',
98 'Contributions' => 'SpecialContributions',
99 'Listgrouprights' => 'SpecialListGroupRights',
100 'Listgrants' => 'SpecialListGrants',
101 'Listusers' => 'SpecialListUsers',
102 'Listadmins' => 'SpecialListAdmins',
103 'Listbots' => 'SpecialListBots',
104 'Userrights' => 'UserrightsPage',
105 'EditWatchlist' => 'SpecialEditWatchlist',
107 // Recent changes and logs
108 'Newimages' => 'SpecialNewFiles',
109 'Log' => 'SpecialLog',
110 'Watchlist' => 'SpecialWatchlist',
111 'Newpages' => 'SpecialNewpages',
112 'Recentchanges' => 'SpecialRecentChanges',
113 'Recentchangeslinked' => 'SpecialRecentChangesLinked',
114 'Tags' => 'SpecialTags',
116 // Media reports and uploads
117 'Listfiles' => 'SpecialListFiles',
118 'Filepath' => 'SpecialFilepath',
119 'MediaStatistics' => 'MediaStatisticsPage',
120 'MIMEsearch' => 'MIMEsearchPage',
121 'FileDuplicateSearch' => 'FileDuplicateSearchPage',
122 'Upload' => 'SpecialUpload',
123 'UploadStash' => 'SpecialUploadStash',
124 'ListDuplicatedFiles' => 'ListDuplicatedFilesPage',
126 // Data and tools
127 'ApiSandbox' => 'SpecialApiSandbox',
128 'Statistics' => 'SpecialStatistics',
129 'Allmessages' => 'SpecialAllMessages',
130 'Version' => 'SpecialVersion',
131 'Lockdb' => 'SpecialLockdb',
132 'Unlockdb' => 'SpecialUnlockdb',
134 // Redirecting special pages
135 'LinkSearch' => 'LinkSearchPage',
136 'Randompage' => 'RandomPage',
137 'RandomInCategory' => 'SpecialRandomInCategory',
138 'Randomredirect' => 'SpecialRandomredirect',
139 'Randomrootpage' => 'SpecialRandomrootpage',
141 // High use pages
142 'Mostlinkedcategories' => 'MostlinkedCategoriesPage',
143 'Mostimages' => 'MostimagesPage',
144 'Mostinterwikis' => 'MostinterwikisPage',
145 'Mostlinked' => 'MostlinkedPage',
146 'Mostlinkedtemplates' => 'MostlinkedTemplatesPage',
147 'Mostcategories' => 'MostcategoriesPage',
148 'Mostrevisions' => 'MostrevisionsPage',
150 // Page tools
151 'ComparePages' => 'SpecialComparePages',
152 'Export' => 'SpecialExport',
153 'Import' => 'SpecialImport',
154 'Undelete' => 'SpecialUndelete',
155 'Whatlinkshere' => 'SpecialWhatLinksHere',
156 'MergeHistory' => 'SpecialMergeHistory',
157 'ExpandTemplates' => 'SpecialExpandTemplates',
159 // Other
160 'Booksources' => 'SpecialBookSources',
162 // Unlisted / redirects
163 'ApiHelp' => 'SpecialApiHelp',
164 'Blankpage' => 'SpecialBlankpage',
165 'Diff' => 'SpecialDiff',
166 'EditTags' => 'SpecialEditTags',
167 'Emailuser' => 'SpecialEmailUser',
168 'Movepage' => 'MovePageForm',
169 'Mycontributions' => 'SpecialMycontributions',
170 'MyLanguage' => 'SpecialMyLanguage',
171 'Mypage' => 'SpecialMypage',
172 'Mytalk' => 'SpecialMytalk',
173 'Myuploads' => 'SpecialMyuploads',
174 'AllMyUploads' => 'SpecialAllMyUploads',
175 'PermanentLink' => 'SpecialPermanentLink',
176 'Redirect' => 'SpecialRedirect',
177 'Revisiondelete' => 'SpecialRevisionDelete',
178 'RunJobs' => 'SpecialRunJobs',
179 'Specialpages' => 'SpecialSpecialpages',
180 'Userlogout' => 'SpecialUserlogout',
183 private static $list;
184 private static $aliases;
187 * Reset the internal list of special pages. Useful when changing $wgSpecialPages after
188 * the internal list has already been initialized, e.g. during testing.
190 public static function resetList() {
191 self::$list = null;
192 self::$aliases = null;
196 * Returns a list of canonical special page names.
197 * May be used to iterate over all registered special pages.
199 * @return string[]
201 public static function getNames() {
202 return array_keys( self::getPageList() );
206 * Get the special page list as an array
208 * @deprecated since 1.24, use getNames() instead.
209 * @return array
211 public static function getList() {
212 wfDeprecated( __FUNCTION__, '1.24' );
213 return self::getPageList();
217 * Get the special page list as an array
219 * @return array
221 private static function getPageList() {
222 global $wgSpecialPages;
223 global $wgDisableInternalSearch, $wgEmailAuthentication;
224 global $wgEnableEmail, $wgEnableJavaScriptTest;
225 global $wgPageLanguageUseDB, $wgContentHandlerUseDB;
227 if ( !is_array( self::$list ) ) {
229 self::$list = self::$coreList;
231 if ( !$wgDisableInternalSearch ) {
232 self::$list['Search'] = 'SpecialSearch';
235 if ( $wgEmailAuthentication ) {
236 self::$list['Confirmemail'] = 'EmailConfirmation';
237 self::$list['Invalidateemail'] = 'EmailInvalidation';
240 if ( $wgEnableEmail ) {
241 self::$list['ChangeEmail'] = 'SpecialChangeEmail';
244 if ( $wgEnableJavaScriptTest ) {
245 self::$list['JavaScriptTest'] = 'SpecialJavaScriptTest';
248 if ( $wgPageLanguageUseDB ) {
249 self::$list['PageLanguage'] = 'SpecialPageLanguage';
251 if ( $wgContentHandlerUseDB ) {
252 self::$list['ChangeContentModel'] = 'SpecialChangeContentModel';
255 self::$list['Activeusers'] = 'SpecialActiveUsers';
257 // Add extension special pages
258 self::$list = array_merge( self::$list, $wgSpecialPages );
260 // This hook can be used to disable unwanted core special pages
261 // or conditionally register special pages.
262 Hooks::run( 'SpecialPage_initList', array( &self::$list ) );
266 return self::$list;
270 * Initialise and return the list of special page aliases. Returns an array where
271 * the key is an alias, and the value is the canonical name of the special page.
272 * All registered special pages are guaranteed to map to themselves.
273 * @return array
275 private static function getAliasList() {
276 if ( is_null( self::$aliases ) ) {
277 global $wgContLang;
278 $aliases = $wgContLang->getSpecialPageAliases();
279 $pageList = self::getPageList();
281 self::$aliases = array();
282 $keepAlias = array();
284 // Force every canonical name to be an alias for itself.
285 foreach ( $pageList as $name => $stuff ) {
286 $caseFoldedAlias = $wgContLang->caseFold( $name );
287 self::$aliases[$caseFoldedAlias] = $name;
288 $keepAlias[$caseFoldedAlias] = 'canonical';
291 // Check for $aliases being an array since Language::getSpecialPageAliases can return null
292 if ( is_array( $aliases ) ) {
293 foreach ( $aliases as $realName => $aliasList ) {
294 $aliasList = array_values( $aliasList );
295 foreach ( $aliasList as $i => $alias ) {
296 $caseFoldedAlias = $wgContLang->caseFold( $alias );
298 if ( isset( self::$aliases[$caseFoldedAlias] ) &&
299 $realName === self::$aliases[$caseFoldedAlias]
301 // Ignore same-realName conflicts
302 continue;
305 if ( !isset( $keepAlias[$caseFoldedAlias] ) ) {
306 self::$aliases[$caseFoldedAlias] = $realName;
307 if ( !$i ) {
308 $keepAlias[$caseFoldedAlias] = 'first';
310 } elseif ( !$i ) {
311 wfWarn( "First alias '$alias' for $realName conflicts with " .
312 "{$keepAlias[$caseFoldedAlias]} alias for " .
313 self::$aliases[$caseFoldedAlias]
321 return self::$aliases;
325 * Given a special page name with a possible subpage, return an array
326 * where the first element is the special page name and the second is the
327 * subpage.
329 * @param string $alias
330 * @return array Array( String, String|null ), or array( null, null ) if the page is invalid
332 public static function resolveAlias( $alias ) {
333 global $wgContLang;
334 $bits = explode( '/', $alias, 2 );
336 $caseFoldedAlias = $wgContLang->caseFold( $bits[0] );
337 $caseFoldedAlias = str_replace( ' ', '_', $caseFoldedAlias );
338 $aliases = self::getAliasList();
339 if ( isset( $aliases[$caseFoldedAlias] ) ) {
340 $name = $aliases[$caseFoldedAlias];
341 } else {
342 return array( null, null );
345 if ( !isset( $bits[1] ) ) { // bug 2087
346 $par = null;
347 } else {
348 $par = $bits[1];
351 return array( $name, $par );
355 * Check if a given name exist as a special page or as a special page alias
357 * @param string $name Name of a special page
358 * @return bool True if a special page exists with this name
360 public static function exists( $name ) {
361 list( $title, /*...*/ ) = self::resolveAlias( $name );
363 $specialPageList = self::getPageList();
364 return isset( $specialPageList[$title] );
368 * Find the object with a given name and return it (or NULL)
370 * @param string $name Special page name, may be localised and/or an alias
371 * @return SpecialPage|null SpecialPage object or null if the page doesn't exist
373 public static function getPage( $name ) {
374 list( $realName, /*...*/ ) = self::resolveAlias( $name );
376 $specialPageList = self::getPageList();
378 if ( isset( $specialPageList[$realName] ) ) {
379 $rec = $specialPageList[$realName];
381 if ( is_callable( $rec ) ) {
382 // Use callback to instantiate the special page
383 $page = call_user_func( $rec );
384 } elseif ( is_string( $rec ) ) {
385 $className = $rec;
386 $page = new $className;
387 } elseif ( is_array( $rec ) ) {
388 $className = array_shift( $rec );
389 // @deprecated, officially since 1.18, unofficially since forever
390 wfDeprecated( "Array syntax for \$wgSpecialPages is deprecated ($className), " .
391 "define a subclass of SpecialPage instead.", '1.18' );
392 $page = ObjectFactory::getObjectFromSpec( array(
393 'class' => $className,
394 'args' => $rec,
395 'closure_expansion' => false,
396 ) );
397 } elseif ( $rec instanceof SpecialPage ) {
398 $page = $rec; // XXX: we should deep clone here
399 } else {
400 $page = null;
403 if ( $page instanceof SpecialPage ) {
404 return $page;
405 } else {
406 // It's not a classname, nor a callback, nor a legacy constructor array,
407 // nor a special page object. Give up.
408 wfLogWarning( "Cannot instantiate special page $realName: bad spec!" );
409 return null;
412 } else {
413 return null;
418 * Return categorised listable special pages which are available
419 * for the current user, and everyone.
421 * @param User $user User object to check permissions, $wgUser will be used
422 * if not provided
423 * @return array ( string => Specialpage )
425 public static function getUsablePages( User $user = null ) {
426 $pages = array();
427 if ( $user === null ) {
428 global $wgUser;
429 $user = $wgUser;
431 foreach ( self::getPageList() as $name => $rec ) {
432 $page = self::getPage( $name );
433 if ( $page ) { // not null
434 $page->setContext( RequestContext::getMain() );
435 if ( $page->isListed()
436 && ( !$page->isRestricted() || $page->userCanExecute( $user ) )
438 $pages[$name] = $page;
443 return $pages;
447 * Return categorised listable special pages for all users
449 * @return array ( string => Specialpage )
451 public static function getRegularPages() {
452 $pages = array();
453 foreach ( self::getPageList() as $name => $rec ) {
454 $page = self::getPage( $name );
455 if ( $page->isListed() && !$page->isRestricted() ) {
456 $pages[$name] = $page;
460 return $pages;
464 * Return categorised listable special pages which are available
465 * for the current user, but not for everyone
467 * @param User|null $user User object to use or null for $wgUser
468 * @return array ( string => Specialpage )
470 public static function getRestrictedPages( User $user = null ) {
471 $pages = array();
472 if ( $user === null ) {
473 global $wgUser;
474 $user = $wgUser;
476 foreach ( self::getPageList() as $name => $rec ) {
477 $page = self::getPage( $name );
478 if (
479 $page->isListed()
480 && $page->isRestricted()
481 && $page->userCanExecute( $user )
483 $pages[$name] = $page;
487 return $pages;
491 * Execute a special page path.
492 * The path may contain parameters, e.g. Special:Name/Params
493 * Extracts the special page name and call the execute method, passing the parameters
495 * Returns a title object if the page is redirected, false if there was no such special
496 * page, and true if it was successful.
498 * @param Title $title
499 * @param IContextSource $context
500 * @param bool $including Bool output is being captured for use in {{special:whatever}}
502 * @return bool
504 public static function executePath( Title &$title, IContextSource &$context, $including = false ) {
505 // @todo FIXME: Redirects broken due to this call
506 $bits = explode( '/', $title->getDBkey(), 2 );
507 $name = $bits[0];
508 if ( !isset( $bits[1] ) ) { // bug 2087
509 $par = null;
510 } else {
511 $par = $bits[1];
514 $page = self::getPage( $name );
515 if ( !$page ) {
516 $context->getOutput()->setArticleRelated( false );
517 $context->getOutput()->setRobotPolicy( 'noindex,nofollow' );
519 global $wgSend404Code;
520 if ( $wgSend404Code ) {
521 $context->getOutput()->setStatusCode( 404 );
524 $context->getOutput()->showErrorPage( 'nosuchspecialpage', 'nospecialpagetext' );
526 return false;
529 if ( !$including ) {
530 // Narrow DB query expectations for this HTTP request
531 $trxLimits = $context->getConfig()->get( 'TrxProfilerLimits' );
532 $trxProfiler = Profiler::instance()->getTransactionProfiler();
533 if ( $context->getRequest()->wasPosted() && !$page->doesWrites() ) {
534 $trxProfiler->setExpectations( $trxLimits['POST-nonwrite'], __METHOD__ );
538 // Page exists, set the context
539 $page->setContext( $context );
541 if ( !$including ) {
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
546 // changed.
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 );
554 return $title;
555 } else {
556 $context->setTitle( $page->getPageTitle( $par ) );
558 } elseif ( !$page->isIncludable() ) {
559 return false;
562 $page->including( $including );
564 // Execute special page
565 $page->run( $par );
567 return true;
571 * Just like executePath() but will override global variables and execute
572 * the page in "inclusion" mode. Returns true if the execution was
573 * successful or false if there was no such special page, or a title object
574 * if it was a redirect.
576 * Also saves the current $wgTitle, $wgOut, $wgRequest, $wgUser and $wgLang
577 * variables so that the special page will get the context it'd expect on a
578 * normal request, and then restores them to their previous values after.
580 * @param Title $title
581 * @param IContextSource $context
582 * @return string HTML fragment
584 public static function capturePath( Title $title, IContextSource $context ) {
585 global $wgOut, $wgTitle, $wgRequest, $wgUser, $wgLang;
587 // Save current globals
588 $oldTitle = $wgTitle;
589 $oldOut = $wgOut;
590 $oldRequest = $wgRequest;
591 $oldUser = $wgUser;
592 $oldLang = $wgLang;
594 // Set the globals to the current context
595 $wgTitle = $title;
596 $wgOut = $context->getOutput();
597 $wgRequest = $context->getRequest();
598 $wgUser = $context->getUser();
599 $wgLang = $context->getLanguage();
601 // The useful part
602 $ret = self::executePath( $title, $context, true );
604 // And restore the old globals
605 $wgTitle = $oldTitle;
606 $wgOut = $oldOut;
607 $wgRequest = $oldRequest;
608 $wgUser = $oldUser;
609 $wgLang = $oldLang;
611 return $ret;
615 * Get the local name for a specified canonical name
617 * @param string $name
618 * @param string|bool $subpage
619 * @return string
621 public static function getLocalNameFor( $name, $subpage = false ) {
622 global $wgContLang;
623 $aliases = $wgContLang->getSpecialPageAliases();
624 $aliasList = self::getAliasList();
626 // Find the first alias that maps back to $name
627 if ( isset( $aliases[$name] ) ) {
628 $found = false;
629 foreach ( $aliases[$name] as $alias ) {
630 $caseFoldedAlias = $wgContLang->caseFold( $alias );
631 $caseFoldedAlias = str_replace( ' ', '_', $caseFoldedAlias );
632 if ( isset( $aliasList[$caseFoldedAlias] ) &&
633 $aliasList[$caseFoldedAlias] === $name
635 $name = $alias;
636 $found = true;
637 break;
640 if ( !$found ) {
641 wfWarn( "Did not find a usable alias for special page '$name'. " .
642 "It seems all defined aliases conflict?" );
644 } else {
645 // Check if someone misspelled the correct casing
646 if ( is_array( $aliases ) ) {
647 foreach ( $aliases as $n => $values ) {
648 if ( strcasecmp( $name, $n ) === 0 ) {
649 wfWarn( "Found alias defined for $n when searching for " .
650 "special page aliases for $name. Case mismatch?" );
651 return self::getLocalNameFor( $n, $subpage );
656 wfWarn( "Did not find alias for special page '$name'. " .
657 "Perhaps no aliases are defined for it?" );
660 if ( $subpage !== false && !is_null( $subpage ) ) {
661 $name = "$name/$subpage";
664 return $wgContLang->ucfirst( $name );
668 * Get a title for a given alias
670 * @param string $alias
671 * @return Title|null Title or null if there is no such alias
673 public static function getTitleForAlias( $alias ) {
674 list( $name, $subpage ) = self::resolveAlias( $alias );
675 if ( $name != null ) {
676 return SpecialPage::getTitleFor( $name, $subpage );
677 } else {
678 return null;