Merge "dispatchUser() should use a 302 http status code"
[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 namespace MediaWiki\Special;
26
27 use Hooks;
28 use IContextSource;
29 use Language;
30 use MediaWiki\Config\ServiceOptions;
31 use MediaWiki\Linker\LinkRenderer;
32 use Profiler;
33 use RequestContext;
34 use SpecialPage;
35 use Title;
36 use User;
37 use Wikimedia\ObjectFactory;
38
39 /**
40 * Factory for handling the special page list and generating SpecialPage objects.
41 *
42 * To add a special page in an extension, add to $wgSpecialPages either
43 * an object instance or an array containing the name and constructor
44 * parameters. The latter is preferred for performance reasons.
45 *
46 * The object instantiated must be either an instance of SpecialPage or a
47 * sub-class thereof. It must have an execute() method, which sends the HTML
48 * for the special page to $wgOut. The parent class has an execute() method
49 * which distributes the call to the historical global functions. Additionally,
50 * execute() also checks if the user has the necessary access privileges
51 * and bails out if not.
52 *
53 * To add a core special page, use the similar static list in
54 * SpecialPageFactory::$list. To remove a core static special page at runtime, use
55 * a SpecialPage_initList hook.
56 *
57 * @note There are two classes called SpecialPageFactory. You should use this first one, in
58 * namespace MediaWiki\Special, which is a service. \SpecialPageFactory is a deprecated collection
59 * of static methods that forwards to the global service.
60 *
61 * @ingroup SpecialPage
62 * @since 1.17
63 */
64 class SpecialPageFactory {
65 /**
66 * List of special page names to the subclass of SpecialPage which handles them.
67 * @todo Make this a const when we drop HHVM support (T192166). It can still be private in PHP
68 * 7.1.
69 */
70 private static $coreList = [
71 // Maintenance Reports
72 'BrokenRedirects' => \SpecialBrokenRedirects::class,
73 'Deadendpages' => \SpecialDeadendPages::class,
74 'DoubleRedirects' => \SpecialDoubleRedirects::class,
75 'Longpages' => \SpecialLongPages::class,
76 'Ancientpages' => \SpecialAncientPages::class,
77 'Lonelypages' => \SpecialLonelyPages::class,
78 'Fewestrevisions' => \SpecialFewestRevisions::class,
79 'Withoutinterwiki' => \SpecialWithoutInterwiki::class,
80 'Protectedpages' => \SpecialProtectedpages::class,
81 'Protectedtitles' => \SpecialProtectedtitles::class,
82 'Shortpages' => \SpecialShortPages::class,
83 'Uncategorizedcategories' => \SpecialUncategorizedCategories::class,
84 'Uncategorizedimages' => \SpecialUncategorizedImages::class,
85 'Uncategorizedpages' => \SpecialUncategorizedPages::class,
86 'Uncategorizedtemplates' => \SpecialUncategorizedTemplates::class,
87 'Unusedcategories' => \SpecialUnusedCategories::class,
88 'Unusedimages' => \SpecialUnusedImages::class,
89 'Unusedtemplates' => \SpecialUnusedTemplates::class,
90 'Unwatchedpages' => \SpecialUnwatchedPages::class,
91 'Wantedcategories' => \SpecialWantedCategories::class,
92 'Wantedfiles' => \WantedFilesPage::class,
93 'Wantedpages' => \WantedPagesPage::class,
94 'Wantedtemplates' => \SpecialWantedTemplates::class,
95
96 // List of pages
97 'Allpages' => \SpecialAllPages::class,
98 'Prefixindex' => \SpecialPrefixindex::class,
99 'Categories' => \SpecialCategories::class,
100 'Listredirects' => \SpecialListRedirects::class,
101 'PagesWithProp' => \SpecialPagesWithProp::class,
102 'TrackingCategories' => \SpecialTrackingCategories::class,
103
104 // Authentication
105 'Userlogin' => \SpecialUserLogin::class,
106 'Userlogout' => \SpecialUserLogout::class,
107 'CreateAccount' => \SpecialCreateAccount::class,
108 'LinkAccounts' => \SpecialLinkAccounts::class,
109 'UnlinkAccounts' => \SpecialUnlinkAccounts::class,
110 'ChangeCredentials' => \SpecialChangeCredentials::class,
111 'RemoveCredentials' => \SpecialRemoveCredentials::class,
112
113 // Users and rights
114 'Activeusers' => \SpecialActiveUsers::class,
115 'Block' => \SpecialBlock::class,
116 'Unblock' => \SpecialUnblock::class,
117 'BlockList' => \SpecialBlockList::class,
118 'AutoblockList' => \SpecialAutoblockList::class,
119 'ChangePassword' => \SpecialChangePassword::class,
120 'BotPasswords' => \SpecialBotPasswords::class,
121 'PasswordReset' => \SpecialPasswordReset::class,
122 'DeletedContributions' => \SpecialDeletedContributions::class,
123 'Preferences' => \SpecialPreferences::class,
124 'ResetTokens' => \SpecialResetTokens::class,
125 'Contributions' => \SpecialContributions::class,
126 'Listgrouprights' => \SpecialListGroupRights::class,
127 'Listgrants' => \SpecialListGrants::class,
128 'Listusers' => \SpecialListUsers::class,
129 'Listadmins' => \SpecialListAdmins::class,
130 'Listbots' => \SpecialListBots::class,
131 'Userrights' => \UserrightsPage::class,
132 'EditWatchlist' => \SpecialEditWatchlist::class,
133 'PasswordPolicies' => \SpecialPasswordPolicies::class,
134
135 // Recent changes and logs
136 'Newimages' => \SpecialNewFiles::class,
137 'Log' => \SpecialLog::class,
138 'Watchlist' => \SpecialWatchlist::class,
139 'Newpages' => \SpecialNewpages::class,
140 'Recentchanges' => \SpecialRecentChanges::class,
141 'Recentchangeslinked' => \SpecialRecentChangesLinked::class,
142 'Tags' => \SpecialTags::class,
143
144 // Media reports and uploads
145 'Listfiles' => \SpecialListFiles::class,
146 'Filepath' => \SpecialFilepath::class,
147 'MediaStatistics' => \SpecialMediaStatistics::class,
148 'MIMEsearch' => \SpecialMIMESearch::class,
149 'FileDuplicateSearch' => \SpecialFileDuplicateSearch::class,
150 'Upload' => \SpecialUpload::class,
151 'UploadStash' => \SpecialUploadStash::class,
152 'ListDuplicatedFiles' => \SpecialListDuplicatedFiles::class,
153
154 // Data and tools
155 'ApiSandbox' => \SpecialApiSandbox::class,
156 'Statistics' => \SpecialStatistics::class,
157 'Allmessages' => \SpecialAllMessages::class,
158 'Version' => \SpecialVersion::class,
159 'Lockdb' => \SpecialLockdb::class,
160 'Unlockdb' => \SpecialUnlockdb::class,
161
162 // Redirecting special pages
163 'LinkSearch' => \SpecialLinkSearch::class,
164 'Randompage' => \RandomPage::class,
165 'RandomInCategory' => \SpecialRandomInCategory::class,
166 'Randomredirect' => \SpecialRandomredirect::class,
167 'Randomrootpage' => \SpecialRandomrootpage::class,
168 'GoToInterwiki' => \SpecialGoToInterwiki::class,
169
170 // High use pages
171 'Mostlinkedcategories' => \SpecialMostLinkedCategories::class,
172 'Mostimages' => \MostimagesPage::class,
173 'Mostinterwikis' => \SpecialMostInterwikis::class,
174 'Mostlinked' => \SpecialMostLinked::class,
175 'Mostlinkedtemplates' => \SpecialMostLinkedTemplates::class,
176 'Mostcategories' => \SpecialMostCategories::class,
177 'Mostrevisions' => \SpecialMostRevisions::class,
178
179 // Page tools
180 'ComparePages' => \SpecialComparePages::class,
181 'Export' => \SpecialExport::class,
182 'Import' => \SpecialImport::class,
183 'Undelete' => \SpecialUndelete::class,
184 'Whatlinkshere' => \SpecialWhatLinksHere::class,
185 'MergeHistory' => \SpecialMergeHistory::class,
186 'ExpandTemplates' => \SpecialExpandTemplates::class,
187
188 // Other
189 'Booksources' => \SpecialBookSources::class,
190
191 // Unlisted / redirects
192 'ApiHelp' => \SpecialApiHelp::class,
193 'Blankpage' => \SpecialBlankpage::class,
194 'Diff' => \SpecialDiff::class,
195 'EditTags' => \SpecialEditTags::class,
196 'Emailuser' => \SpecialEmailUser::class,
197 'Movepage' => \MovePageForm::class,
198 'Mycontributions' => \SpecialMycontributions::class,
199 'MyLanguage' => \SpecialMyLanguage::class,
200 'Mypage' => \SpecialMypage::class,
201 'Mytalk' => \SpecialMytalk::class,
202 'Myuploads' => \SpecialMyuploads::class,
203 'AllMyUploads' => \SpecialAllMyUploads::class,
204 'NewSection' => \SpecialNewSection::class,
205 'PermanentLink' => \SpecialPermanentLink::class,
206 'Redirect' => \SpecialRedirect::class,
207 'Revisiondelete' => \SpecialRevisionDelete::class,
208 'RunJobs' => \SpecialRunJobs::class,
209 'Specialpages' => \SpecialSpecialpages::class,
210 'PageData' => \SpecialPageData::class,
211 ];
212
213 /** @var array Special page name => class name */
214 private $list;
215
216 /** @var array */
217 private $aliases;
218
219 /** @var ServiceOptions */
220 private $options;
221
222 /** @var Language */
223 private $contLang;
224
225 /** @var ObjectFactory */
226 private $objectFactory;
227
228 /**
229 * TODO Make this a const when HHVM support is dropped (T192166)
230 *
231 * @var array
232 * @since 1.33
233 */
234 public static $constructorOptions = [
235 'ContentHandlerUseDB',
236 'DisableInternalSearch',
237 'EmailAuthentication',
238 'EnableEmail',
239 'EnableJavaScriptTest',
240 'EnableSpecialMute',
241 'PageLanguageUseDB',
242 'SpecialPages',
243 ];
244
245 /**
246 * @param ServiceOptions $options
247 * @param Language $contLang
248 * @param ObjectFactory $objectFactory
249 */
250 public function __construct(
251 ServiceOptions $options,
252 Language $contLang,
253 ObjectFactory $objectFactory
254 ) {
255 $options->assertRequiredOptions( self::$constructorOptions );
256 $this->options = $options;
257 $this->contLang = $contLang;
258 $this->objectFactory = $objectFactory;
259 }
260
261 /**
262 * Returns a list of canonical special page names.
263 * May be used to iterate over all registered special pages.
264 *
265 * @return string[]
266 */
267 public function getNames() : array {
268 return array_keys( $this->getPageList() );
269 }
270
271 /**
272 * Get the special page list as an array
273 *
274 * @return array
275 */
276 private function getPageList() : array {
277 if ( !is_array( $this->list ) ) {
278 $this->list = self::$coreList;
279
280 if ( !$this->options->get( 'DisableInternalSearch' ) ) {
281 $this->list['Search'] = \SpecialSearch::class;
282 }
283
284 if ( $this->options->get( 'EmailAuthentication' ) ) {
285 $this->list['Confirmemail'] = \SpecialConfirmEmail::class;
286 $this->list['Invalidateemail'] = \SpecialEmailInvalidate::class;
287 }
288
289 if ( $this->options->get( 'EnableEmail' ) ) {
290 $this->list['ChangeEmail'] = \SpecialChangeEmail::class;
291 }
292
293 if ( $this->options->get( 'EnableJavaScriptTest' ) ) {
294 $this->list['JavaScriptTest'] = \SpecialJavaScriptTest::class;
295 }
296
297 if ( $this->options->get( 'EnableSpecialMute' ) ) {
298 $this->list['Mute'] = \SpecialMute::class;
299 }
300
301 if ( $this->options->get( 'PageLanguageUseDB' ) ) {
302 $this->list['PageLanguage'] = \SpecialPageLanguage::class;
303 }
304
305 if ( $this->options->get( 'ContentHandlerUseDB' ) ) {
306 $this->list['ChangeContentModel'] = \SpecialChangeContentModel::class;
307 }
308
309 // Add extension special pages
310 $this->list = array_merge( $this->list, $this->options->get( 'SpecialPages' ) );
311
312 // This hook can be used to disable unwanted core special pages
313 // or conditionally register special pages.
314 Hooks::run( 'SpecialPage_initList', [ &$this->list ] );
315
316 }
317
318 return $this->list;
319 }
320
321 /**
322 * Initialise and return the list of special page aliases. Returns an array where
323 * the key is an alias, and the value is the canonical name of the special page.
324 * All registered special pages are guaranteed to map to themselves.
325 * @return array
326 */
327 private function getAliasList() : array {
328 if ( is_null( $this->aliases ) ) {
329 $aliases = $this->contLang->getSpecialPageAliases();
330 $pageList = $this->getPageList();
331
332 $this->aliases = [];
333 $keepAlias = [];
334
335 // Force every canonical name to be an alias for itself.
336 foreach ( $pageList as $name => $stuff ) {
337 $caseFoldedAlias = $this->contLang->caseFold( $name );
338 $this->aliases[$caseFoldedAlias] = $name;
339 $keepAlias[$caseFoldedAlias] = 'canonical';
340 }
341
342 // Check for $aliases being an array since Language::getSpecialPageAliases can return null
343 if ( is_array( $aliases ) ) {
344 foreach ( $aliases as $realName => $aliasList ) {
345 $aliasList = array_values( $aliasList );
346 foreach ( $aliasList as $i => $alias ) {
347 $caseFoldedAlias = $this->contLang->caseFold( $alias );
348
349 if ( isset( $this->aliases[$caseFoldedAlias] ) &&
350 $realName === $this->aliases[$caseFoldedAlias]
351 ) {
352 // Ignore same-realName conflicts
353 continue;
354 }
355
356 if ( !isset( $keepAlias[$caseFoldedAlias] ) ) {
357 $this->aliases[$caseFoldedAlias] = $realName;
358 if ( !$i ) {
359 $keepAlias[$caseFoldedAlias] = 'first';
360 }
361 } elseif ( !$i ) {
362 wfWarn( "First alias '$alias' for $realName conflicts with " .
363 "{$keepAlias[$caseFoldedAlias]} alias for " .
364 $this->aliases[$caseFoldedAlias]
365 );
366 }
367 }
368 }
369 }
370 }
371
372 return $this->aliases;
373 }
374
375 /**
376 * Given a special page name with a possible subpage, return an array
377 * where the first element is the special page name and the second is the
378 * subpage.
379 *
380 * @param string $alias
381 * @return array [ String, String|null ], or [ null, null ] if the page is invalid
382 */
383 public function resolveAlias( $alias ) {
384 $bits = explode( '/', $alias, 2 );
385
386 $caseFoldedAlias = $this->contLang->caseFold( $bits[0] );
387 $caseFoldedAlias = str_replace( ' ', '_', $caseFoldedAlias );
388 $aliases = $this->getAliasList();
389 if ( !isset( $aliases[$caseFoldedAlias] ) ) {
390 return [ null, null ];
391 }
392 $name = $aliases[$caseFoldedAlias];
393 $par = $bits[1] ?? null; // T4087
394
395 return [ $name, $par ];
396 }
397
398 /**
399 * Check if a given name exist as a special page or as a special page alias
400 *
401 * @param string $name Name of a special page
402 * @return bool True if a special page exists with this name
403 */
404 public function exists( $name ) {
405 list( $title, /*...*/ ) = $this->resolveAlias( $name );
406
407 $specialPageList = $this->getPageList();
408 return isset( $specialPageList[$title] );
409 }
410
411 /**
412 * Find the object with a given name and return it (or NULL)
413 *
414 * @param string $name Special page name, may be localised and/or an alias
415 * @return SpecialPage|null SpecialPage object or null if the page doesn't exist
416 */
417 public function getPage( $name ) {
418 list( $realName, /*...*/ ) = $this->resolveAlias( $name );
419
420 $specialPageList = $this->getPageList();
421
422 if ( isset( $specialPageList[$realName] ) ) {
423 $rec = $specialPageList[$realName];
424
425 if ( $rec instanceof SpecialPage ) {
426 wfDeprecated(
427 "a SpecialPage instance (for $realName) in " .
428 '$wgSpecialPages or from the SpecialPage_initList hook',
429 '1.34'
430 );
431
432 $page = $rec; // XXX: we should deep clone here
433 } elseif ( is_array( $rec ) || is_string( $rec ) || is_callable( $rec ) ) {
434 $page = $this->objectFactory->createObject(
435 $rec,
436 [
437 'allowClassName' => true,
438 'allowCallable' => true
439 ]
440 );
441 } else {
442 $page = null;
443 }
444
445 if ( $page instanceof SpecialPage ) {
446 return $page;
447 }
448
449 // It's not a classname, nor a callback, nor a legacy constructor array,
450 // nor a special page object. Give up.
451 wfLogWarning( "Cannot instantiate special page $realName: bad spec!" );
452 }
453
454 return null;
455 }
456
457 /**
458 * Return categorised listable special pages which are available
459 * for the current user, and everyone.
460 *
461 * @param User $user User object to check permissions
462 * provided
463 * @return array ( string => Specialpage )
464 */
465 public function getUsablePages( User $user ) : array {
466 $pages = [];
467 foreach ( $this->getPageList() as $name => $rec ) {
468 $page = $this->getPage( $name );
469 if ( $page ) { // not null
470 $page->setContext( RequestContext::getMain() );
471 if ( $page->isListed()
472 && ( !$page->isRestricted() || $page->userCanExecute( $user ) )
473 ) {
474 $pages[$name] = $page;
475 }
476 }
477 }
478
479 return $pages;
480 }
481
482 /**
483 * Return categorised listable special pages for all users
484 *
485 * @return array ( string => Specialpage )
486 */
487 public function getRegularPages() : array {
488 $pages = [];
489 foreach ( $this->getPageList() as $name => $rec ) {
490 $page = $this->getPage( $name );
491 if ( $page && $page->isListed() && !$page->isRestricted() ) {
492 $pages[$name] = $page;
493 }
494 }
495
496 return $pages;
497 }
498
499 /**
500 * Return categorised listable special pages which are available
501 * for the current user, but not for everyone
502 *
503 * @param User $user User object to use
504 * @return array ( string => Specialpage )
505 */
506 public function getRestrictedPages( User $user ) : array {
507 $pages = [];
508 foreach ( $this->getPageList() as $name => $rec ) {
509 $page = $this->getPage( $name );
510 if ( $page
511 && $page->isListed()
512 && $page->isRestricted()
513 && $page->userCanExecute( $user )
514 ) {
515 $pages[$name] = $page;
516 }
517 }
518
519 return $pages;
520 }
521
522 /**
523 * Execute a special page path.
524 * The path may contain parameters, e.g. Special:Name/Params
525 * Extracts the special page name and call the execute method, passing the parameters
526 *
527 * Returns a title object if the page is redirected, false if there was no such special
528 * page, and true if it was successful.
529 *
530 * @param Title &$title
531 * @param IContextSource &$context
532 * @param bool $including Bool output is being captured for use in {{special:whatever}}
533 * @param LinkRenderer|null $linkRenderer (since 1.28)
534 *
535 * @return bool|Title
536 */
537 public function executePath( Title &$title, IContextSource &$context, $including = false,
538 LinkRenderer $linkRenderer = null
539 ) {
540 // @todo FIXME: Redirects broken due to this call
541 $bits = explode( '/', $title->getDBkey(), 2 );
542 $name = $bits[0];
543 $par = $bits[1] ?? null; // T4087
544
545 $page = $this->getPage( $name );
546 if ( !$page ) {
547 $context->getOutput()->setArticleRelated( false );
548 $context->getOutput()->setRobotPolicy( 'noindex,nofollow' );
549
550 global $wgSend404Code;
551 if ( $wgSend404Code ) {
552 $context->getOutput()->setStatusCode( 404 );
553 }
554
555 $context->getOutput()->showErrorPage( 'nosuchspecialpage', 'nospecialpagetext' );
556
557 return false;
558 }
559
560 if ( !$including ) {
561 // Narrow DB query expectations for this HTTP request
562 $trxLimits = $context->getConfig()->get( 'TrxProfilerLimits' );
563 $trxProfiler = Profiler::instance()->getTransactionProfiler();
564 if ( $context->getRequest()->wasPosted() && !$page->doesWrites() ) {
565 $trxProfiler->setExpectations( $trxLimits['POST-nonwrite'], __METHOD__ );
566 $context->getRequest()->markAsSafeRequest();
567 }
568 }
569
570 // Page exists, set the context
571 $page->setContext( $context );
572
573 if ( !$including ) {
574 // Redirect to canonical alias for GET commands
575 // Not for POST, we'd lose the post data, so it's best to just distribute
576 // the request. Such POST requests are possible for old extensions that
577 // generate self-links without being aware that their default name has
578 // changed.
579 if ( $name != $page->getLocalName() && !$context->getRequest()->wasPosted() ) {
580 $query = $context->getRequest()->getQueryValues();
581 unset( $query['title'] );
582 $title = $page->getPageTitle( $par );
583 $url = $title->getFullURL( $query );
584 $context->getOutput()->redirect( $url );
585
586 return $title;
587 }
588
589 // @phan-suppress-next-line PhanUndeclaredMethod
590 $context->setTitle( $page->getPageTitle( $par ) );
591 } elseif ( !$page->isIncludable() ) {
592 return false;
593 }
594
595 $page->including( $including );
596 if ( $linkRenderer ) {
597 $page->setLinkRenderer( $linkRenderer );
598 }
599
600 // Execute special page
601 $page->run( $par );
602
603 return true;
604 }
605
606 /**
607 * Just like executePath() but will override global variables and execute
608 * the page in "inclusion" mode. Returns true if the execution was
609 * successful or false if there was no such special page, or a title object
610 * if it was a redirect.
611 *
612 * Also saves the current $wgTitle, $wgOut, $wgRequest, $wgUser and $wgLang
613 * variables so that the special page will get the context it'd expect on a
614 * normal request, and then restores them to their previous values after.
615 *
616 * @param Title $title
617 * @param IContextSource $context
618 * @param LinkRenderer|null $linkRenderer (since 1.28)
619 * @return string HTML fragment
620 */
621 public function capturePath(
622 Title $title, IContextSource $context, LinkRenderer $linkRenderer = null
623 ) {
624 global $wgTitle, $wgOut, $wgRequest, $wgUser, $wgLang;
625 $main = RequestContext::getMain();
626
627 // Save current globals and main context
628 $glob = [
629 'title' => $wgTitle,
630 'output' => $wgOut,
631 'request' => $wgRequest,
632 'user' => $wgUser,
633 'language' => $wgLang,
634 ];
635 $ctx = [
636 'title' => $main->getTitle(),
637 'output' => $main->getOutput(),
638 'request' => $main->getRequest(),
639 'user' => $main->getUser(),
640 'language' => $main->getLanguage(),
641 ];
642 if ( $main->canUseWikiPage() ) {
643 $ctx['wikipage'] = $main->getWikiPage();
644 }
645
646 // Override
647 $wgTitle = $title;
648 $wgOut = $context->getOutput();
649 $wgRequest = $context->getRequest();
650 $wgUser = $context->getUser();
651 $wgLang = $context->getLanguage();
652 $main->setTitle( $title );
653 $main->setOutput( $context->getOutput() );
654 $main->setRequest( $context->getRequest() );
655 $main->setUser( $context->getUser() );
656 $main->setLanguage( $context->getLanguage() );
657
658 // The useful part
659 $ret = $this->executePath( $title, $context, true, $linkRenderer );
660
661 // Restore old globals and context
662 $wgTitle = $glob['title'];
663 $wgOut = $glob['output'];
664 $wgRequest = $glob['request'];
665 $wgUser = $glob['user'];
666 $wgLang = $glob['language'];
667 $main->setTitle( $ctx['title'] );
668 $main->setOutput( $ctx['output'] );
669 $main->setRequest( $ctx['request'] );
670 $main->setUser( $ctx['user'] );
671 $main->setLanguage( $ctx['language'] );
672 if ( isset( $ctx['wikipage'] ) ) {
673 $main->setWikiPage( $ctx['wikipage'] );
674 }
675
676 return $ret;
677 }
678
679 /**
680 * Get the local name for a specified canonical name
681 *
682 * @param string $name
683 * @param string|bool $subpage
684 * @return string
685 */
686 public function getLocalNameFor( $name, $subpage = false ) {
687 $aliases = $this->contLang->getSpecialPageAliases();
688 $aliasList = $this->getAliasList();
689
690 // Find the first alias that maps back to $name
691 if ( isset( $aliases[$name] ) ) {
692 $found = false;
693 foreach ( $aliases[$name] as $alias ) {
694 $caseFoldedAlias = $this->contLang->caseFold( $alias );
695 $caseFoldedAlias = str_replace( ' ', '_', $caseFoldedAlias );
696 if ( isset( $aliasList[$caseFoldedAlias] ) &&
697 $aliasList[$caseFoldedAlias] === $name
698 ) {
699 $name = $alias;
700 $found = true;
701 break;
702 }
703 }
704 if ( !$found ) {
705 wfWarn( "Did not find a usable alias for special page '$name'. " .
706 "It seems all defined aliases conflict?" );
707 }
708 } else {
709 // Check if someone misspelled the correct casing
710 if ( is_array( $aliases ) ) {
711 foreach ( $aliases as $n => $values ) {
712 if ( strcasecmp( $name, $n ) === 0 ) {
713 wfWarn( "Found alias defined for $n when searching for " .
714 "special page aliases for $name. Case mismatch?" );
715 return $this->getLocalNameFor( $n, $subpage );
716 }
717 }
718 }
719
720 wfWarn( "Did not find alias for special page '$name'. " .
721 "Perhaps no aliases are defined for it?" );
722 }
723
724 if ( $subpage !== false && !is_null( $subpage ) ) {
725 // Make sure it's in dbkey form
726 $subpage = str_replace( ' ', '_', $subpage );
727 $name = "$name/$subpage";
728 }
729
730 return $this->contLang->ucfirst( $name );
731 }
732
733 /**
734 * Get a title for a given alias
735 *
736 * @param string $alias
737 * @return Title|null Title or null if there is no such alias
738 */
739 public function getTitleForAlias( $alias ) {
740 list( $name, $subpage ) = $this->resolveAlias( $alias );
741 if ( $name != null ) {
742 return SpecialPage::getTitleFor( $name, $subpage );
743 }
744
745 return null;
746 }
747 }