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