c94c358f3ff53332d68e773e8515a530168a75bc
[lhc/web/wiklou.git] / includes / 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 * SpecialPage::$mList. 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 /**
49 * List of special page names to the subclass of SpecialPage which handles them.
50 */
51 private static $mList = array(
52 // Maintenance Reports
53 'BrokenRedirects' => 'BrokenRedirectsPage',
54 'Deadendpages' => 'DeadendpagesPage',
55 'DoubleRedirects' => 'DoubleRedirectsPage',
56 'Longpages' => 'LongpagesPage',
57 'Ancientpages' => 'AncientpagesPage',
58 'Lonelypages' => 'LonelypagesPage',
59 'Fewestrevisions' => 'FewestrevisionsPage',
60 'Withoutinterwiki' => 'WithoutinterwikiPage',
61 'Protectedpages' => 'SpecialProtectedpages',
62 'Protectedtitles' => 'SpecialProtectedtitles',
63 'Shortpages' => 'ShortpagesPage',
64 'Uncategorizedcategories' => 'UncategorizedcategoriesPage',
65 'Uncategorizedimages' => 'UncategorizedimagesPage',
66 'Uncategorizedpages' => 'UncategorizedpagesPage',
67 'Uncategorizedtemplates' => 'UncategorizedtemplatesPage',
68 'Unusedcategories' => 'UnusedcategoriesPage',
69 'Unusedimages' => 'UnusedimagesPage',
70 'Unusedtemplates' => 'UnusedtemplatesPage',
71 'Unwatchedpages' => 'UnwatchedpagesPage',
72 'Wantedcategories' => 'WantedcategoriesPage',
73 'Wantedfiles' => 'WantedfilesPage',
74 'Wantedpages' => 'WantedpagesPage',
75 'Wantedtemplates' => 'WantedtemplatesPage',
76
77 // List of pages
78 'Allpages' => 'SpecialAllpages',
79 'Prefixindex' => 'SpecialPrefixindex',
80 'Categories' => 'SpecialCategories',
81 'Disambiguations' => 'DisambiguationsPage',
82 'Listredirects' => 'ListredirectsPage',
83 'PagesWithProp' => 'SpecialPagesWithProp',
84
85 // Login/create account
86 'Userlogin' => 'LoginForm',
87 'CreateAccount' => 'SpecialCreateAccount',
88
89 // Users and rights
90 'Block' => 'SpecialBlock',
91 'Unblock' => 'SpecialUnblock',
92 'BlockList' => 'SpecialBlockList',
93 'ChangePassword' => 'SpecialChangePassword',
94 'PasswordReset' => 'SpecialPasswordReset',
95 'DeletedContributions' => 'DeletedContributionsPage',
96 'Preferences' => 'SpecialPreferences',
97 'Contributions' => 'SpecialContributions',
98 'Listgrouprights' => 'SpecialListGroupRights',
99 'Listusers' => 'SpecialListUsers',
100 'Listadmins' => 'SpecialListAdmins',
101 'Listbots' => 'SpecialListBots',
102 'Activeusers' => 'SpecialActiveUsers',
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 'MIMEsearch' => 'MIMEsearchPage',
119 'FileDuplicateSearch' => 'FileDuplicateSearchPage',
120 'Upload' => 'SpecialUpload',
121 'UploadStash' => 'SpecialUploadStash',
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 'Randomredirect' => 'SpecialRandomredirect',
134
135 // High use pages
136 'Mostlinkedcategories' => 'MostlinkedCategoriesPage',
137 'Mostimages' => 'MostimagesPage',
138 'Mostinterwikis' => 'MostinterwikisPage',
139 'Mostlinked' => 'MostlinkedPage',
140 'Mostlinkedtemplates' => 'MostlinkedTemplatesPage',
141 'Mostcategories' => 'MostcategoriesPage',
142 'Mostrevisions' => 'MostrevisionsPage',
143
144 // Page tools
145 'ComparePages' => 'SpecialComparePages',
146 'Export' => 'SpecialExport',
147 'Import' => 'SpecialImport',
148 'Undelete' => 'SpecialUndelete',
149 'Whatlinkshere' => 'SpecialWhatlinkshere',
150 'MergeHistory' => 'SpecialMergeHistory',
151
152 // Other
153 'Booksources' => 'SpecialBookSources',
154
155 // Unlisted / redirects
156 'Blankpage' => 'SpecialBlankpage',
157 'Blockme' => 'SpecialBlockme',
158 'Emailuser' => 'SpecialEmailUser',
159 'Movepage' => 'MovePageForm',
160 'Mycontributions' => 'SpecialMycontributions',
161 'Mypage' => 'SpecialMypage',
162 'Mytalk' => 'SpecialMytalk',
163 'Myuploads' => 'SpecialMyuploads',
164 'PermanentLink' => 'SpecialPermanentLink',
165 'Revisiondelete' => 'SpecialRevisionDelete',
166 'Specialpages' => 'SpecialSpecialpages',
167 'Userlogout' => 'SpecialUserlogout',
168 );
169
170 private static $mAliases;
171
172 /**
173 * Initialise the special page list
174 * This must be called before accessing SpecialPage::$mList
175 *
176 * @return array
177 */
178 static function getList() {
179 global $wgSpecialPages;
180 global $wgDisableCounters, $wgDisableInternalSearch, $wgEmailAuthentication;
181 global $wgEnableEmail, $wgEnableJavaScriptTest;
182
183 if ( !is_object( self::$mList ) ) {
184 wfProfileIn( __METHOD__ );
185
186 if ( !$wgDisableCounters ) {
187 self::$mList['Popularpages'] = 'PopularpagesPage';
188 }
189
190 if ( !$wgDisableInternalSearch ) {
191 self::$mList['Search'] = 'SpecialSearch';
192 }
193
194 if ( $wgEmailAuthentication ) {
195 self::$mList['Confirmemail'] = 'EmailConfirmation';
196 self::$mList['Invalidateemail'] = 'EmailInvalidation';
197 }
198
199 if ( $wgEnableEmail ) {
200 self::$mList['ChangeEmail'] = 'SpecialChangeEmail';
201 }
202
203 if( $wgEnableJavaScriptTest ) {
204 self::$mList['JavaScriptTest'] = 'SpecialJavaScriptTest';
205 }
206
207 // Add extension special pages
208 self::$mList = array_merge( self::$mList, $wgSpecialPages );
209
210 // Run hooks
211 // This hook can be used to remove undesired built-in special pages
212 wfRunHooks( 'SpecialPage_initList', array( &self::$mList ) );
213
214 // Cast to object: func()[$key] doesn't work, but func()->$key does
215 settype( self::$mList, 'object' );
216
217 wfProfileOut( __METHOD__ );
218 }
219 return self::$mList;
220 }
221
222 /**
223 * Initialise and return the list of special page aliases. Returns an object with
224 * properties which can be accessed $obj->pagename - each property is an array of
225 * aliases; the first in the array is the cannonical alias. All registered special
226 * pages are guaranteed to have a property entry, and for that property array to
227 * contain at least one entry (English fallbacks will be added if necessary).
228 * @return Object
229 */
230 static function getAliasList() {
231 if ( !is_object( self::$mAliases ) ) {
232 global $wgContLang;
233 $aliases = $wgContLang->getSpecialPageAliases();
234
235 // Objects are passed by reference by default, need to create a copy
236 $missingPages = clone self::getList();
237
238 self::$mAliases = array();
239 foreach ( $aliases as $realName => $aliasList ) {
240 foreach ( $aliasList as $alias ) {
241 self::$mAliases[$wgContLang->caseFold( $alias )] = $realName;
242 }
243 unset( $missingPages->$realName );
244 }
245 foreach ( $missingPages as $name => $stuff ) {
246 self::$mAliases[$wgContLang->caseFold( $name )] = $name;
247 }
248
249 // Cast to object: func()[$key] doesn't work, but func()->$key does
250 self::$mAliases = (object)self::$mAliases;
251 }
252 return self::$mAliases;
253 }
254
255 /**
256 * Given a special page name with a possible subpage, return an array
257 * where the first element is the special page name and the second is the
258 * subpage.
259 *
260 * @param $alias String
261 * @return Array( String, String|null ), or array( null, null ) if the page is invalid
262 */
263 public static function resolveAlias( $alias ) {
264 global $wgContLang;
265 $bits = explode( '/', $alias, 2 );
266
267 $caseFoldedAlias = $wgContLang->caseFold( $bits[0] );
268 $caseFoldedAlias = str_replace( ' ', '_', $caseFoldedAlias );
269 if ( isset( self::getAliasList()->$caseFoldedAlias ) ) {
270 $name = self::getAliasList()->$caseFoldedAlias;
271 } else {
272 return array( null, null );
273 }
274
275 if ( !isset( $bits[1] ) ) { // bug 2087
276 $par = null;
277 } else {
278 $par = $bits[1];
279 }
280
281 return array( $name, $par );
282 }
283
284 /**
285 * Add a page to a certain display group for Special:SpecialPages
286 *
287 * @param $page Mixed: SpecialPage or string
288 * @param $group String
289 */
290 public static function setGroup( $page, $group ) {
291 global $wgSpecialPageGroups;
292 $name = is_object( $page ) ? $page->getName() : $page;
293 $wgSpecialPageGroups[$name] = $group;
294 }
295
296 /**
297 * Get the group that the special page belongs in on Special:SpecialPage
298 *
299 * @param $page SpecialPage
300 * @return String
301 */
302 public static function getGroup( &$page ) {
303 $name = $page->getName();
304
305 global $wgSpecialPageGroups;
306 static $specialPageGroupsCache = array();
307 if ( isset( $specialPageGroupsCache[$name] ) ) {
308 return $specialPageGroupsCache[$name];
309 }
310 $msg = wfMessage( 'specialpages-specialpagegroup-' . strtolower( $name ) );
311 if ( !$msg->isBlank() ) {
312 $group = $msg->text();
313 } else {
314 $group = isset( $wgSpecialPageGroups[$name] )
315 ? $wgSpecialPageGroups[$name]
316 : '-';
317 }
318 if ( $group == '-' ) {
319 $group = 'other';
320 }
321 $specialPageGroupsCache[$name] = $group;
322 return $group;
323 }
324
325 /**
326 * Check if a given name exist as a special page or as a special page alias
327 *
328 * @param $name String: name of a special page
329 * @return Boolean: true if a special page exists with this name
330 */
331 public static function exists( $name ) {
332 list( $title, /*...*/ ) = self::resolveAlias( $name );
333 return property_exists( self::getList(), $title );
334 }
335
336 /**
337 * Find the object with a given name and return it (or NULL)
338 *
339 * @param $name String Special page name, may be localised and/or an alias
340 * @return SpecialPage|null SpecialPage object or null if the page doesn't exist
341 */
342 public static function getPage( $name ) {
343 list( $realName, /*...*/ ) = self::resolveAlias( $name );
344 if ( property_exists( self::getList(), $realName ) ) {
345 $rec = self::getList()->$realName;
346 if ( is_string( $rec ) ) {
347 $className = $rec;
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, define a subclass of SpecialPage instead." );
352 $className = array_shift( $rec );
353 self::getList()->$realName = MWFunction::newObj( $className, $rec );
354 }
355 return self::getList()->$realName;
356 } else {
357 return null;
358 }
359 }
360
361 /**
362 * Return categorised listable special pages which are available
363 * for the current user, and everyone.
364 *
365 * @param $user User object to check permissions, $wgUser will be used
366 * if not provided
367 * @return Array( String => Specialpage )
368 */
369 public static function getUsablePages( User $user = null ) {
370 $pages = array();
371 if ( $user === null ) {
372 global $wgUser;
373 $user = $wgUser;
374 }
375 foreach ( self::getList() as $name => $rec ) {
376 $page = self::getPage( $name );
377 if ( $page ) { // not null
378 $page->setContext( RequestContext::getMain() );
379 if ( $page->isListed()
380 && ( !$page->isRestricted() || $page->userCanExecute( $user ) )
381 ) {
382 $pages[$name] = $page;
383 }
384 }
385 }
386 return $pages;
387 }
388
389 /**
390 * Return categorised listable special pages for all users
391 *
392 * @return Array( String => Specialpage )
393 */
394 public static function getRegularPages() {
395 $pages = array();
396 foreach ( self::getList() as $name => $rec ) {
397 $page = self::getPage( $name );
398 if ( $page->isListed() && !$page->isRestricted() ) {
399 $pages[$name] = $page;
400 }
401 }
402 return $pages;
403 }
404
405 /**
406 * Return categorised listable special pages which are available
407 * for the current user, but not for everyone
408 *
409 * @return Array( String => Specialpage )
410 */
411 public static function getRestrictedPages() {
412 global $wgUser;
413 $pages = array();
414 foreach ( self::getList() as $name => $rec ) {
415 $page = self::getPage( $name );
416 if (
417 $page->isListed()
418 && $page->isRestricted()
419 && $page->userCanExecute( $wgUser )
420 ) {
421 $pages[$name] = $page;
422 }
423 }
424 return $pages;
425 }
426
427 /**
428 * Execute a special page path.
429 * The path may contain parameters, e.g. Special:Name/Params
430 * Extracts the special page name and call the execute method, passing the parameters
431 *
432 * Returns a title object if the page is redirected, false if there was no such special
433 * page, and true if it was successful.
434 *
435 * @param $title Title object
436 * @param $context IContextSource
437 * @param $including Bool output is being captured for use in {{special:whatever}}
438 *
439 * @return bool
440 */
441 public static function executePath( Title &$title, IContextSource &$context, $including = false ) {
442 wfProfileIn( __METHOD__ );
443
444 // @todo FIXME: Redirects broken due to this call
445 $bits = explode( '/', $title->getDBkey(), 2 );
446 $name = $bits[0];
447 if ( !isset( $bits[1] ) ) { // bug 2087
448 $par = null;
449 } else {
450 $par = $bits[1];
451 }
452 $page = self::getPage( $name );
453 // Nonexistent?
454 if ( !$page ) {
455 $context->getOutput()->setArticleRelated( false );
456 $context->getOutput()->setRobotPolicy( 'noindex,nofollow' );
457
458 global $wgSend404Code;
459 if ( $wgSend404Code ) {
460 $context->getOutput()->setStatusCode( 404 );
461 }
462
463 $context->getOutput()->showErrorPage( 'nosuchspecialpage', 'nospecialpagetext' );
464 wfProfileOut( __METHOD__ );
465 return false;
466 }
467
468 // Page exists, set the context
469 $page->setContext( $context );
470
471 if ( !$including ) {
472 // Redirect to canonical alias for GET commands
473 // Not for POST, we'd lose the post data, so it's best to just distribute
474 // the request. Such POST requests are possible for old extensions that
475 // generate self-links without being aware that their default name has
476 // changed.
477 if ( $name != $page->getLocalName() && !$context->getRequest()->wasPosted() ) {
478 $query = $context->getRequest()->getQueryValues();
479 unset( $query['title'] );
480 $query = wfArrayToCgi( $query );
481 $title = $page->getTitle( $par );
482 $url = $title->getFullUrl( $query );
483 $context->getOutput()->redirect( $url );
484 wfProfileOut( __METHOD__ );
485 return $title;
486 } else {
487 $context->setTitle( $page->getTitle( $par ) );
488 }
489
490 } elseif ( !$page->isIncludable() ) {
491 wfProfileOut( __METHOD__ );
492 return false;
493 }
494
495 $page->including( $including );
496
497 // Execute special page
498 $profName = 'Special:' . $page->getName();
499 wfProfileIn( $profName );
500 $page->run( $par );
501 wfProfileOut( $profName );
502 wfProfileOut( __METHOD__ );
503 return true;
504 }
505
506 /**
507 * Just like executePath() but will override global variables and execute
508 * the page in "inclusion" mode. Returns true if the execution was
509 * successful or false if there was no such special page, or a title object
510 * if it was a redirect.
511 *
512 * Also saves the current $wgTitle, $wgOut, $wgRequest, $wgUser and $wgLang
513 * variables so that the special page will get the context it'd expect on a
514 * normal request, and then restores them to their previous values after.
515 *
516 * @param $title Title
517 * @param $context IContextSource
518 *
519 * @return String: HTML fragment
520 */
521 static function capturePath( Title $title, IContextSource $context ) {
522 global $wgOut, $wgTitle, $wgRequest, $wgUser, $wgLang;
523
524 // Save current globals
525 $oldTitle = $wgTitle;
526 $oldOut = $wgOut;
527 $oldRequest = $wgRequest;
528 $oldUser = $wgUser;
529 $oldLang = $wgLang;
530
531 // Set the globals to the current context
532 $wgTitle = $title;
533 $wgOut = $context->getOutput();
534 $wgRequest = $context->getRequest();
535 $wgUser = $context->getUser();
536 $wgLang = $context->getLanguage();
537
538 // The useful part
539 $ret = self::executePath( $title, $context, true );
540
541 // And restore the old globals
542 $wgTitle = $oldTitle;
543 $wgOut = $oldOut;
544 $wgRequest = $oldRequest;
545 $wgUser = $oldUser;
546 $wgLang = $oldLang;
547
548 return $ret;
549 }
550
551 /**
552 * Get the local name for a specified canonical name
553 *
554 * @param $name String
555 * @param $subpage String|Bool
556 *
557 * @return String
558 */
559 static function getLocalNameFor( $name, $subpage = false ) {
560 global $wgContLang;
561 $aliases = $wgContLang->getSpecialPageAliases();
562
563 if ( isset( $aliases[$name][0] ) ) {
564 $name = $aliases[$name][0];
565 } else {
566 // Try harder in case someone misspelled the correct casing
567 $found = false;
568 foreach ( $aliases as $n => $values ) {
569 if ( strcasecmp( $name, $n ) === 0 ) {
570 wfWarn( "Found alias defined for $n when searching for " .
571 "special page aliases for $name. Case mismatch?" );
572 $name = $values[0];
573 $found = true;
574 break;
575 }
576 }
577 if ( !$found ) {
578 wfWarn( "Did not find alias for special page '$name'. " .
579 "Perhaps no aliases are defined for it?" );
580 }
581 }
582 if ( $subpage !== false && !is_null( $subpage ) ) {
583 $name = "$name/$subpage";
584 }
585 return $wgContLang->ucfirst( $name );
586 }
587
588 /**
589 * Get a title for a given alias
590 *
591 * @param $alias String
592 *
593 * @return Title or null if there is no such alias
594 */
595 static function getTitleForAlias( $alias ) {
596 $name = self::resolveAlias( $alias );
597 if ( $name ) {
598 return SpecialPage::getTitleFor( $name );
599 } else {
600 return null;
601 }
602 }
603 }