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