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