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