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