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