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