Merge "Update set of files cleaned up after parserTests"
[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 $list = 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
83 // Login/create account
84 'Userlogin' => 'LoginForm',
85 'CreateAccount' => 'SpecialCreateAccount',
86
87 // Users and rights
88 'Block' => 'SpecialBlock',
89 'Unblock' => 'SpecialUnblock',
90 'BlockList' => 'SpecialBlockList',
91 'ChangePassword' => 'SpecialChangePassword',
92 'PasswordReset' => 'SpecialPasswordReset',
93 'DeletedContributions' => 'DeletedContributionsPage',
94 'Preferences' => 'SpecialPreferences',
95 'ResetTokens' => 'SpecialResetTokens',
96 'Contributions' => 'SpecialContributions',
97 'Listgrouprights' => 'SpecialListGroupRights',
98 'Listusers' => 'SpecialListUsers',
99 'Listadmins' => 'SpecialListAdmins',
100 'Listbots' => 'SpecialListBots',
101 'Userrights' => 'UserrightsPage',
102 'EditWatchlist' => 'SpecialEditWatchlist',
103
104 // Recent changes and logs
105 'Newimages' => 'SpecialNewFiles',
106 'Log' => 'SpecialLog',
107 'Watchlist' => 'SpecialWatchlist',
108 'Newpages' => 'SpecialNewpages',
109 'Recentchanges' => 'SpecialRecentChanges',
110 'Recentchangeslinked' => 'SpecialRecentChangesLinked',
111 'Tags' => 'SpecialTags',
112
113 // Media reports and uploads
114 'Listfiles' => 'SpecialListFiles',
115 'Filepath' => 'SpecialFilepath',
116 'MIMEsearch' => 'MIMEsearchPage',
117 'FileDuplicateSearch' => 'FileDuplicateSearchPage',
118 'Upload' => 'SpecialUpload',
119 'UploadStash' => 'SpecialUploadStash',
120 'ListDuplicatedFiles' => 'ListDuplicatedFilesPage',
121
122 // Data and tools
123 'Statistics' => 'SpecialStatistics',
124 'Allmessages' => 'SpecialAllmessages',
125 'Version' => 'SpecialVersion',
126 'Lockdb' => 'SpecialLockdb',
127 'Unlockdb' => 'SpecialUnlockdb',
128
129 // Redirecting special pages
130 'LinkSearch' => 'LinkSearchPage',
131 'Randompage' => 'RandomPage',
132 'RandomInCategory' => 'SpecialRandomInCategory',
133 'Randomredirect' => 'SpecialRandomredirect',
134
135 // High use pages
136 'Mostlinkedcategories' => 'MostlinkedCategoriesPage',
137 'Mostimages' => 'MostimagesPage',
138 'Mostinterwikis' => 'MostinterwikisPage',
139 'Mostlinked' => 'MostlinkedPage',
140 'Mostlinkedtemplates' => 'MostlinkedTemplatesPage',
141 'Mostcategories' => 'MostcategoriesPage',
142 'Mostrevisions' => 'MostrevisionsPage',
143
144 // Page tools
145 'ComparePages' => 'SpecialComparePages',
146 'Export' => 'SpecialExport',
147 'Import' => 'SpecialImport',
148 'Undelete' => 'SpecialUndelete',
149 'Whatlinkshere' => 'SpecialWhatLinksHere',
150 'MergeHistory' => 'SpecialMergeHistory',
151 'ExpandTemplates' => 'SpecialExpandTemplates',
152
153 // Other
154 'Booksources' => 'SpecialBookSources',
155
156 // Unlisted / redirects
157 'Blankpage' => 'SpecialBlankpage',
158 'Diff' => 'SpecialDiff',
159 'Emailuser' => 'SpecialEmailUser',
160 'Movepage' => 'MovePageForm',
161 'Mycontributions' => 'SpecialMycontributions',
162 'Mypage' => 'SpecialMypage',
163 'Mytalk' => 'SpecialMytalk',
164 'Myuploads' => 'SpecialMyuploads',
165 'AllMyUploads' => 'SpecialAllMyUploads',
166 'PermanentLink' => 'SpecialPermanentLink',
167 'Redirect' => 'SpecialRedirect',
168 'Revisiondelete' => 'SpecialRevisionDelete',
169 'RunJobs' => 'SpecialRunJobs',
170 'Specialpages' => 'SpecialSpecialpages',
171 'Userlogout' => 'SpecialUserlogout',
172 );
173
174 private static $aliases;
175
176 /**
177 * Get the special page list
178 *
179 * @return array
180 */
181 static function getList() {
182 global $wgSpecialPages;
183 global $wgDisableCounters, $wgDisableInternalSearch, $wgEmailAuthentication;
184 global $wgEnableEmail, $wgEnableJavaScriptTest;
185
186 if ( !is_object( self::$list ) ) {
187 wfProfileIn( __METHOD__ );
188
189 if ( !$wgDisableCounters ) {
190 self::$list['Popularpages'] = 'PopularPagesPage';
191 }
192
193 if ( !$wgDisableInternalSearch ) {
194 self::$list['Search'] = 'SpecialSearch';
195 }
196
197 if ( $wgEmailAuthentication ) {
198 self::$list['Confirmemail'] = 'EmailConfirmation';
199 self::$list['Invalidateemail'] = 'EmailInvalidation';
200 }
201
202 if ( $wgEnableEmail ) {
203 self::$list['ChangeEmail'] = 'SpecialChangeEmail';
204 }
205
206 if ( $wgEnableJavaScriptTest ) {
207 self::$list['JavaScriptTest'] = 'SpecialJavaScriptTest';
208 }
209
210 self::$list['Activeusers'] = 'SpecialActiveUsers';
211
212 // Add extension special pages
213 self::$list = array_merge( self::$list, $wgSpecialPages );
214
215 // Run hooks
216 // This hook can be used to remove undesired built-in special pages
217 wfRunHooks( 'SpecialPage_initList', array( &self::$list ) );
218
219 // Cast to object: func()[$key] doesn't work, but func()->$key does
220 settype( self::$list, 'object' );
221
222 wfProfileOut( __METHOD__ );
223 }
224
225 return self::$list;
226 }
227
228 /**
229 * Initialise and return the list of special page aliases. Returns an object with
230 * properties which can be accessed $obj->pagename - each property is an array of
231 * aliases; the first in the array is the canonical alias. All registered special
232 * pages are guaranteed to have a property entry, and for that property array to
233 * contain at least one entry (English fallbacks will be added if necessary).
234 * @return Object
235 */
236 static function getAliasList() {
237 if ( !is_object( self::$aliases ) ) {
238 global $wgContLang;
239 $aliases = $wgContLang->getSpecialPageAliases();
240
241 // Objects are passed by reference by default, need to create a copy
242 $missingPages = clone self::getList();
243
244 self::$aliases = array();
245 foreach ( $aliases as $realName => $aliasList ) {
246 foreach ( $aliasList as $alias ) {
247 self::$aliases[$wgContLang->caseFold( $alias )] = $realName;
248 }
249 unset( $missingPages->$realName );
250 }
251 foreach ( $missingPages as $name => $stuff ) {
252 self::$aliases[$wgContLang->caseFold( $name )] = $name;
253 }
254
255 // Cast to object: func()[$key] doesn't work, but func()->$key does
256 self::$aliases = (object)self::$aliases;
257 }
258
259 return self::$aliases;
260 }
261
262 /**
263 * Given a special page name with a possible subpage, return an array
264 * where the first element is the special page name and the second is the
265 * subpage.
266 *
267 * @param string $alias
268 * @return array Array( String, String|null ), or array( null, null ) if the page is invalid
269 */
270 public static function resolveAlias( $alias ) {
271 global $wgContLang;
272 $bits = explode( '/', $alias, 2 );
273
274 $caseFoldedAlias = $wgContLang->caseFold( $bits[0] );
275 $caseFoldedAlias = str_replace( ' ', '_', $caseFoldedAlias );
276 if ( isset( self::getAliasList()->$caseFoldedAlias ) ) {
277 $name = self::getAliasList()->$caseFoldedAlias;
278 } else {
279 return array( null, null );
280 }
281
282 if ( !isset( $bits[1] ) ) { // bug 2087
283 $par = null;
284 } else {
285 $par = $bits[1];
286 }
287
288 return array( $name, $par );
289 }
290
291 /**
292 * Add a page to a certain display group for Special:SpecialPages
293 *
294 * @param SpecialPage|string $page
295 * @param string $group
296 * @deprecated since 1.21 Override SpecialPage::getGroupName
297 */
298 public static function setGroup( $page, $group ) {
299 wfDeprecated( __METHOD__, '1.21' );
300
301 global $wgSpecialPageGroups;
302 $name = is_object( $page ) ? $page->getName() : $page;
303 $wgSpecialPageGroups[$name] = $group;
304 }
305
306 /**
307 * Get the group that the special page belongs in on Special:SpecialPage
308 *
309 * @param SpecialPage $page
310 * @return string
311 * @deprecated since 1.21 Use SpecialPage::getFinalGroupName
312 */
313 public static function getGroup( &$page ) {
314 wfDeprecated( __METHOD__, '1.21' );
315
316 return $page->getFinalGroupName();
317 }
318
319 /**
320 * Check if a given name exist as a special page or as a special page alias
321 *
322 * @param string $name Name of a special page
323 * @return bool True if a special page exists with this name
324 */
325 public static function exists( $name ) {
326 list( $title, /*...*/ ) = self::resolveAlias( $name );
327
328 return property_exists( self::getList(), $title );
329 }
330
331 /**
332 * Find the object with a given name and return it (or NULL)
333 *
334 * @param string $name Special page name, may be localised and/or an alias
335 * @return SpecialPage|null SpecialPage object or null if the page doesn't exist
336 */
337 public static function getPage( $name ) {
338 list( $realName, /*...*/ ) = self::resolveAlias( $name );
339 if ( property_exists( self::getList(), $realName ) ) {
340 $rec = self::getList()->$realName;
341 if ( is_string( $rec ) ) {
342 $className = $rec;
343
344 return new $className;
345 } elseif ( is_array( $rec ) ) {
346 // @deprecated, officially since 1.18, unofficially since forever
347 wfDebug( "Array syntax for \$wgSpecialPages is deprecated, " .
348 "define a subclass of SpecialPage instead." );
349 $className = array_shift( $rec );
350 self::getList()->$realName = MWFunction::newObj( $className, $rec );
351 }
352
353 return self::getList()->$realName;
354 } else {
355 return null;
356 }
357 }
358
359 /**
360 * Return categorised listable special pages which are available
361 * for the current user, and everyone.
362 *
363 * @param $user User object to check permissions, $wgUser will be used if
364 * if not provided
365 * @return array ( string => Specialpage )
366 */
367 public static function getUsablePages( User $user = null ) {
368 $pages = array();
369 if ( $user === null ) {
370 global $wgUser;
371 $user = $wgUser;
372 }
373 foreach ( self::getList() as $name => $rec ) {
374 $page = self::getPage( $name );
375 if ( $page ) { // not null
376 $page->setContext( RequestContext::getMain() );
377 if ( $page->isListed()
378 && ( !$page->isRestricted() || $page->userCanExecute( $user ) )
379 ) {
380 $pages[$name] = $page;
381 }
382 }
383 }
384
385 return $pages;
386 }
387
388 /**
389 * Return categorised listable special pages for all users
390 *
391 * @return array ( string => Specialpage )
392 */
393 public static function getRegularPages() {
394 $pages = array();
395 foreach ( self::getList() as $name => $rec ) {
396 $page = self::getPage( $name );
397 if ( $page->isListed() && !$page->isRestricted() ) {
398 $pages[$name] = $page;
399 }
400 }
401
402 return $pages;
403 }
404
405 /**
406 * Return categorised listable special pages which are available
407 * for the current user, but not for everyone
408 *
409 * @return array ( string => Specialpage )
410 */
411 public static function getRestrictedPages() {
412 global $wgUser;
413 $pages = array();
414 foreach ( self::getList() as $name => $rec ) {
415 $page = self::getPage( $name );
416 if (
417 $page->isListed()
418 && $page->isRestricted()
419 && $page->userCanExecute( $wgUser )
420 ) {
421 $pages[$name] = $page;
422 }
423 }
424
425 return $pages;
426 }
427
428 /**
429 * Execute a special page path.
430 * The path may contain parameters, e.g. Special:Name/Params
431 * Extracts the special page name and call the execute method, passing the parameters
432 *
433 * Returns a title object if the page is redirected, false if there was no such special
434 * page, and true if it was successful.
435 *
436 * @param Title $title
437 * @param IContextSource $context
438 * @param bool $including Bool output is being captured for use in {{special:whatever}}
439 *
440 * @return bool
441 */
442 public static function executePath( Title &$title, IContextSource &$context, $including = false ) {
443 wfProfileIn( __METHOD__ );
444
445 // @todo FIXME: Redirects broken due to this call
446 $bits = explode( '/', $title->getDBkey(), 2 );
447 $name = $bits[0];
448 if ( !isset( $bits[1] ) ) { // bug 2087
449 $par = null;
450 } else {
451 $par = $bits[1];
452 }
453 $page = self::getPage( $name );
454 // Nonexistent?
455 if ( !$page ) {
456 $context->getOutput()->setArticleRelated( false );
457 $context->getOutput()->setRobotPolicy( 'noindex,nofollow' );
458
459 global $wgSend404Code;
460 if ( $wgSend404Code ) {
461 $context->getOutput()->setStatusCode( 404 );
462 }
463
464 $context->getOutput()->showErrorPage( 'nosuchspecialpage', 'nospecialpagetext' );
465 wfProfileOut( __METHOD__ );
466
467 return false;
468 }
469
470 // Page exists, set the context
471 $page->setContext( $context );
472
473 if ( !$including ) {
474 // Redirect to canonical alias for GET commands
475 // Not for POST, we'd lose the post data, so it's best to just distribute
476 // the request. Such POST requests are possible for old extensions that
477 // generate self-links without being aware that their default name has
478 // changed.
479 if ( $name != $page->getLocalName() && !$context->getRequest()->wasPosted() ) {
480 $query = $context->getRequest()->getQueryValues();
481 unset( $query['title'] );
482 $title = $page->getPageTitle( $par );
483 $url = $title->getFullURL( $query );
484 $context->getOutput()->redirect( $url );
485 wfProfileOut( __METHOD__ );
486
487 return $title;
488 } else {
489 $context->setTitle( $page->getPageTitle( $par ) );
490 }
491 } elseif ( !$page->isIncludable() ) {
492 wfProfileOut( __METHOD__ );
493
494 return false;
495 }
496
497 $page->including( $including );
498
499 // Execute special page
500 $profName = 'Special:' . $page->getName();
501 wfProfileIn( $profName );
502 $page->run( $par );
503 wfProfileOut( $profName );
504 wfProfileOut( __METHOD__ );
505
506 return true;
507 }
508
509 /**
510 * Just like executePath() but will override global variables and execute
511 * the page in "inclusion" mode. Returns true if the execution was
512 * successful or false if there was no such special page, or a title object
513 * if it was a redirect.
514 *
515 * Also saves the current $wgTitle, $wgOut, $wgRequest, $wgUser and $wgLang
516 * variables so that the special page will get the context it'd expect on a
517 * normal request, and then restores them to their previous values after.
518 *
519 * @param Title $title
520 * @param IContextSource $context
521 * @return string HTML fragment
522 */
523 static function capturePath( Title $title, IContextSource $context ) {
524 global $wgOut, $wgTitle, $wgRequest, $wgUser, $wgLang;
525
526 // Save current globals
527 $oldTitle = $wgTitle;
528 $oldOut = $wgOut;
529 $oldRequest = $wgRequest;
530 $oldUser = $wgUser;
531 $oldLang = $wgLang;
532
533 // Set the globals to the current context
534 $wgTitle = $title;
535 $wgOut = $context->getOutput();
536 $wgRequest = $context->getRequest();
537 $wgUser = $context->getUser();
538 $wgLang = $context->getLanguage();
539
540 // The useful part
541 $ret = self::executePath( $title, $context, true );
542
543 // And restore the old globals
544 $wgTitle = $oldTitle;
545 $wgOut = $oldOut;
546 $wgRequest = $oldRequest;
547 $wgUser = $oldUser;
548 $wgLang = $oldLang;
549
550 return $ret;
551 }
552
553 /**
554 * Get the local name for a specified canonical name
555 *
556 * @param string $name
557 * @param string|bool $subpage
558 * @return string
559 */
560 static function getLocalNameFor( $name, $subpage = false ) {
561 global $wgContLang;
562 $aliases = $wgContLang->getSpecialPageAliases();
563
564 if ( isset( $aliases[$name][0] ) ) {
565 $name = $aliases[$name][0];
566 } else {
567 // Try harder in case someone misspelled the correct casing
568 $found = false;
569 foreach ( $aliases as $n => $values ) {
570 if ( strcasecmp( $name, $n ) === 0 ) {
571 wfWarn( "Found alias defined for $n when searching for " .
572 "special page aliases for $name. Case mismatch?" );
573 $name = $values[0];
574 $found = true;
575 break;
576 }
577 }
578 if ( !$found ) {
579 wfWarn( "Did not find alias for special page '$name'. " .
580 "Perhaps no aliases are defined for it?" );
581 }
582 }
583 if ( $subpage !== false && !is_null( $subpage ) ) {
584 $name = "$name/$subpage";
585 }
586
587 return $wgContLang->ucfirst( $name );
588 }
589
590 /**
591 * Get a title for a given alias
592 *
593 * @param string $alias
594 * @return Title|null Title or null if there is no such alias
595 */
596 static function getTitleForAlias( $alias ) {
597 $name = self::resolveAlias( $alias );
598 if ( $name ) {
599 return SpecialPage::getTitleFor( $name );
600 } else {
601 return null;
602 }
603 }
604 }