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