Added release notes for 'ContentHandler::runLegacyHooks' removal
[mediawiki.git] / includes / specialpage / LoginSignupSpecialPage.php
blobc3ee32120b285eb511249fd92fa8108bfdecf146
1 <?php
2 /**
3 * Holds shared logic for login and account creation pages.
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.
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.
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
20 * @file
21 * @ingroup SpecialPage
24 use MediaWiki\Auth\AuthenticationRequest;
25 use MediaWiki\Auth\AuthenticationResponse;
26 use MediaWiki\Auth\AuthManager;
27 use MediaWiki\Auth\Throttler;
28 use MediaWiki\Logger\LoggerFactory;
29 use MediaWiki\Session\SessionManager;
31 /**
32 * Holds shared logic for login and account creation pages.
34 * @ingroup SpecialPage
36 abstract class LoginSignupSpecialPage extends AuthManagerSpecialPage {
37 protected $mReturnTo;
38 protected $mPosted;
39 protected $mAction;
40 protected $mLanguage;
41 protected $mReturnToQuery;
42 protected $mToken;
43 protected $mStickHTTPS;
44 protected $mFromHTTP;
45 protected $mEntryError = '';
46 protected $mEntryErrorType = 'error';
48 protected $mLoaded = false;
49 protected $mLoadedRequest = false;
50 protected $mSecureLoginUrl;
52 /** @var string */
53 protected $securityLevel;
55 /** @var bool True if the user if creating an account for someone else. Flag used for internal
56 * communication, only set at the very end. */
57 protected $proxyAccountCreation;
58 /** @var User FIXME another flag for passing data. */
59 protected $targetUser;
61 /** @var HTMLForm */
62 protected $authForm;
64 /** @var FakeAuthTemplate */
65 protected $fakeTemplate;
67 abstract protected function isSignup();
69 /**
70 * @param bool $direct True if the action was successful just now; false if that happened
71 * pre-redirection (so this handler was called already)
72 * @param StatusValue|null $extraMessages
73 * @return void
75 abstract protected function successfulAction( $direct = false, $extraMessages = null );
77 /**
78 * Logs to the authmanager-stats channel.
79 * @param bool $success
80 * @param string|null $status Error message key
82 abstract protected function logAuthResult( $success, $status = null );
84 public function __construct( $name ) {
85 global $wgUseMediaWikiUIEverywhere;
86 parent::__construct( $name );
88 // Override UseMediaWikiEverywhere to true, to force login and create form to use mw ui
89 $wgUseMediaWikiUIEverywhere = true;
92 protected function setRequest( array $data, $wasPosted = null ) {
93 parent::setRequest( $data, $wasPosted );
94 $this->mLoadedRequest = false;
97 /**
98 * Load basic request parameters for this Special page.
99 * @param $subPage
101 private function loadRequestParameters( $subPage ) {
102 if ( $this->mLoadedRequest ) {
103 return;
105 $this->mLoadedRequest = true;
106 $request = $this->getRequest();
108 $this->mPosted = $request->wasPosted();
109 $this->mIsReturn = $subPage === 'return';
110 $this->mAction = $request->getVal( 'action' );
111 $this->mFromHTTP = $request->getBool( 'fromhttp', false )
112 || $request->getBool( 'wpFromhttp', false );
113 $this->mStickHTTPS = ( !$this->mFromHTTP && $request->getProtocol() === 'https' )
114 || $request->getBool( 'wpForceHttps', false );
115 $this->mLanguage = $request->getText( 'uselang' );
116 $this->mReturnTo = $request->getVal( 'returnto', '' );
117 $this->mReturnToQuery = $request->getVal( 'returntoquery', '' );
121 * Load data from request.
122 * @private
123 * @param string $subPage Subpage of Special:Userlogin
125 protected function load( $subPage ) {
126 global $wgSecureLogin;
128 $this->loadRequestParameters( $subPage );
129 if ( $this->mLoaded ) {
130 return;
132 $this->mLoaded = true;
133 $request = $this->getRequest();
135 $securityLevel = $this->getRequest()->getText( 'force' );
136 if (
137 $securityLevel && AuthManager::singleton()->securitySensitiveOperationStatus(
138 $securityLevel ) === AuthManager::SEC_REAUTH
140 $this->securityLevel = $securityLevel;
143 $this->loadAuth( $subPage );
145 $this->mToken = $request->getVal( $this->getTokenName() );
147 // Show an error or warning passed on from a previous page
148 $entryError = $this->msg( $request->getVal( 'error', '' ) );
149 $entryWarning = $this->msg( $request->getVal( 'warning', '' ) );
150 // bc: provide login link as a parameter for messages where the translation
151 // was not updated
152 $loginreqlink = $this->getLinkRenderer()->makeKnownLink(
153 $this->getPageTitle(),
154 $this->msg( 'loginreqlink' )->text(),
157 'returnto' => $this->mReturnTo,
158 'returntoquery' => $this->mReturnToQuery,
159 'uselang' => $this->mLanguage ?: null,
160 'fromhttp' => $wgSecureLogin && $this->mFromHTTP ? '1' : null,
164 // Only show valid error or warning messages.
165 if ( $entryError->exists()
166 && in_array( $entryError->getKey(), LoginHelper::getValidErrorMessages(), true )
168 $this->mEntryErrorType = 'error';
169 $this->mEntryError = $entryError->rawParams( $loginreqlink )->parse();
171 } elseif ( $entryWarning->exists()
172 && in_array( $entryWarning->getKey(), LoginHelper::getValidErrorMessages(), true )
174 $this->mEntryErrorType = 'warning';
175 $this->mEntryError = $entryWarning->rawParams( $loginreqlink )->parse();
178 # 1. When switching accounts, it sucks to get automatically logged out
179 # 2. Do not return to PasswordReset after a successful password change
180 # but goto Wiki start page (Main_Page) instead ( bug 33997 )
181 $returnToTitle = Title::newFromText( $this->mReturnTo );
182 if ( is_object( $returnToTitle )
183 && ( $returnToTitle->isSpecial( 'Userlogout' )
184 || $returnToTitle->isSpecial( 'PasswordReset' ) )
186 $this->mReturnTo = '';
187 $this->mReturnToQuery = '';
191 protected function getPreservedParams( $withToken = false ) {
192 global $wgSecureLogin;
194 $params = parent::getPreservedParams( $withToken );
195 $params += [
196 'returnto' => $this->mReturnTo ?: null,
197 'returntoquery' => $this->mReturnToQuery ?: null,
199 if ( $wgSecureLogin && !$this->isSignup() ) {
200 $params['fromhttp'] = $this->mFromHTTP ? '1' : null;
202 return $params;
205 protected function beforeExecute( $subPage ) {
206 // finish initializing the class before processing the request - T135924
207 $this->loadRequestParameters( $subPage );
208 return parent::beforeExecute( $subPage );
212 * @param string|null $subPage
214 public function execute( $subPage ) {
215 $authManager = AuthManager::singleton();
216 $session = SessionManager::getGlobalSession();
218 // Session data is used for various things in the authentication process, so we must make
219 // sure a session cookie or some equivalent mechanism is set.
220 $session->persist();
222 $this->load( $subPage );
223 $this->setHeaders();
224 $this->checkPermissions();
226 // Make sure the system configuration allows log in / sign up
227 if ( !$this->isSignup() && !$authManager->canAuthenticateNow() ) {
228 if ( !$session->canSetUser() ) {
229 throw new ErrorPageError( 'cannotloginnow-title', 'cannotloginnow-text', [
230 $session->getProvider()->describe( RequestContext::getMain()->getLanguage() )
231 ] );
233 throw new ErrorPageError( 'cannotlogin-title', 'cannotlogin-text' );
234 } elseif ( $this->isSignup() && !$authManager->canCreateAccounts() ) {
235 throw new ErrorPageError( 'cannotcreateaccount-title', 'cannotcreateaccount-text' );
239 * In the case where the user is already logged in, and was redirected to
240 * the login form from a page that requires login, do not show the login
241 * page. The use case scenario for this is when a user opens a large number
242 * of tabs, is redirected to the login page on all of them, and then logs
243 * in on one, expecting all the others to work properly.
245 * However, do show the form if it was visited intentionally (no 'returnto'
246 * is present). People who often switch between several accounts have grown
247 * accustomed to this behavior.
249 * Also make an exception when force=<level> is set in the URL, which means the user must
250 * reauthenticate for security reasons.
252 if ( !$this->isSignup() && !$this->mPosted && !$this->securityLevel &&
253 ( $this->mReturnTo !== '' || $this->mReturnToQuery !== '' ) &&
254 $this->getUser()->isLoggedIn()
256 $this->successfulAction();
259 // If logging in and not on HTTPS, either redirect to it or offer a link.
260 global $wgSecureLogin;
261 if ( $this->getRequest()->getProtocol() !== 'https' ) {
262 $title = $this->getFullTitle();
263 $query = $this->getPreservedParams( false ) + [
264 'title' => null,
265 ( $this->mEntryErrorType === 'error' ? 'error'
266 : 'warning' ) => $this->mEntryError,
267 ] + $this->getRequest()->getQueryValues();
268 $url = $title->getFullURL( $query, false, PROTO_HTTPS );
269 if ( $wgSecureLogin && !$this->mFromHTTP &&
270 wfCanIPUseHTTPS( $this->getRequest()->getIP() )
272 // Avoid infinite redirect
273 $url = wfAppendQuery( $url, 'fromhttp=1' );
274 $this->getOutput()->redirect( $url );
275 // Since we only do this redir to change proto, always vary
276 $this->getOutput()->addVaryHeader( 'X-Forwarded-Proto' );
278 return;
279 } else {
280 // A wiki without HTTPS login support should set $wgServer to
281 // http://somehost, in which case the secure URL generated
282 // above won't actually start with https://
283 if ( substr( $url, 0, 8 ) === 'https://' ) {
284 $this->mSecureLoginUrl = $url;
289 if ( !$this->isActionAllowed( $this->authAction ) ) {
290 // FIXME how do we explain this to the user? can we handle session loss better?
291 // messages used: authpage-cannot-login, authpage-cannot-login-continue,
292 // authpage-cannot-create, authpage-cannot-create-continue
293 $this->mainLoginForm( [], 'authpage-cannot-' . $this->authAction );
294 return;
297 if ( $this->canBypassForm( $button_name ) ) {
298 $this->setRequest( [], true );
299 $this->getRequest()->setVal( $this->getTokenName(), $this->getToken() );
300 if ( $button_name ) {
301 $this->getRequest()->setVal( $button_name, true );
305 $status = $this->trySubmit();
307 if ( !$status || !$status->isGood() ) {
308 $this->mainLoginForm( $this->authRequests, $status ? $status->getMessage() : '', 'error' );
309 return;
312 /** @var AuthenticationResponse $response */
313 $response = $status->getValue();
315 $returnToUrl = $this->getPageTitle( 'return' )
316 ->getFullURL( $this->getPreservedParams( true ), false, PROTO_HTTPS );
317 switch ( $response->status ) {
318 case AuthenticationResponse::PASS:
319 $this->logAuthResult( true );
320 $this->proxyAccountCreation = $this->isSignup() && !$this->getUser()->isAnon();
321 $this->targetUser = User::newFromName( $response->username );
323 if (
324 !$this->proxyAccountCreation
325 && $response->loginRequest
326 && $authManager->canAuthenticateNow()
328 // successful registration; log the user in instantly
329 $response2 = $authManager->beginAuthentication( [ $response->loginRequest ],
330 $returnToUrl );
331 if ( $response2->status !== AuthenticationResponse::PASS ) {
332 LoggerFactory::getInstance( 'login' )
333 ->error( 'Could not log in after account creation' );
334 $this->successfulAction( true, Status::newFatal( 'createacct-loginerror' ) );
335 break;
339 if ( !$this->proxyAccountCreation ) {
340 // Ensure that the context user is the same as the session user.
341 $this->setSessionUserForCurrentRequest();
344 $this->successfulAction( true );
345 break;
346 case AuthenticationResponse::FAIL:
347 // fall through
348 case AuthenticationResponse::RESTART:
349 unset( $this->authForm );
350 if ( $response->status === AuthenticationResponse::FAIL ) {
351 $action = $this->getDefaultAction( $subPage );
352 $messageType = 'error';
353 } else {
354 $action = $this->getContinueAction( $this->authAction );
355 $messageType = 'warning';
357 $this->logAuthResult( false, $response->message ? $response->message->getKey() : '-' );
358 $this->loadAuth( $subPage, $action, true );
359 $this->mainLoginForm( $this->authRequests, $response->message, $messageType );
360 break;
361 case AuthenticationResponse::REDIRECT:
362 unset( $this->authForm );
363 $this->getOutput()->redirect( $response->redirectTarget );
364 break;
365 case AuthenticationResponse::UI:
366 unset( $this->authForm );
367 $this->authAction = $this->isSignup() ? AuthManager::ACTION_CREATE_CONTINUE
368 : AuthManager::ACTION_LOGIN_CONTINUE;
369 $this->authRequests = $response->neededRequests;
370 $this->mainLoginForm( $response->neededRequests, $response->message, $response->messageType );
371 break;
372 default:
373 throw new LogicException( 'invalid AuthenticationResponse' );
378 * Determine if the login form can be bypassed. This will be the case when no more than one
379 * button is present and no other user input fields that are not marked as 'skippable' are
380 * present. If the login form were not bypassed, the user would be presented with a
381 * superfluous page on which they must press the single button to proceed with login.
382 * Not only does this cause an additional mouse click and page load, it confuses users,
383 * especially since there are a help link and forgotten password link that are
384 * provided on the login page that do not apply to this situation.
386 * @param string|null &$button_name if the form has a single button, returns
387 * the name of the button; otherwise, returns null
388 * @return bool
390 private function canBypassForm( &$button_name ) {
391 $button_name = null;
392 if ( $this->isContinued() ) {
393 return false;
395 $fields = AuthenticationRequest::mergeFieldInfo( $this->authRequests );
396 foreach ( $fields as $fieldname => $field ) {
397 if ( !isset( $field['type'] ) ) {
398 return false;
400 if ( !empty( $field['skippable'] ) ) {
401 continue;
403 if ( $field['type'] === 'button' ) {
404 if ( $button_name !== null ) {
405 $button_name = null;
406 return false;
407 } else {
408 $button_name = $fieldname;
410 } elseif ( $field['type'] !== 'null' ) {
411 return false;
414 return true;
418 * Show the success page.
420 * @param string $type Condition of return to; see `executeReturnTo`
421 * @param string|Message $title Page's title
422 * @param string $msgname
423 * @param string $injected_html
424 * @param StatusValue|null $extraMessages
426 protected function showSuccessPage(
427 $type, $title, $msgname, $injected_html, $extraMessages
429 $out = $this->getOutput();
430 $out->setPageTitle( $title );
431 if ( $msgname ) {
432 $out->addWikiMsg( $msgname, wfEscapeWikiText( $this->getUser()->getName() ) );
434 if ( $extraMessages ) {
435 $extraMessages = Status::wrap( $extraMessages );
436 $out->addWikiText( $extraMessages->getWikiText() );
439 $out->addHTML( $injected_html );
441 $helper = new LoginHelper( $this->getContext() );
442 $helper->showReturnToPage( $type, $this->mReturnTo, $this->mReturnToQuery, $this->mStickHTTPS );
446 * Add a "return to" link or redirect to it.
447 * Extensions can use this to reuse the "return to" logic after
448 * inject steps (such as redirection) into the login process.
450 * @param string $type One of the following:
451 * - error: display a return to link ignoring $wgRedirectOnLogin
452 * - signup: display a return to link using $wgRedirectOnLogin if needed
453 * - success: display a return to link using $wgRedirectOnLogin if needed
454 * - successredirect: send an HTTP redirect using $wgRedirectOnLogin if needed
455 * @param string $returnTo
456 * @param array|string $returnToQuery
457 * @param bool $stickHTTPS Keep redirect link on HTTPS
458 * @since 1.22
460 public function showReturnToPage(
461 $type, $returnTo = '', $returnToQuery = '', $stickHTTPS = false
463 $helper = new LoginHelper( $this->getContext() );
464 $helper->showReturnToPage( $type, $returnTo, $returnToQuery, $stickHTTPS );
468 * Replace some globals to make sure the fact that the user has just been logged in is
469 * reflected in the current request.
470 * @param User $user
472 protected function setSessionUserForCurrentRequest() {
473 global $wgUser, $wgLang;
475 $context = RequestContext::getMain();
476 $localContext = $this->getContext();
477 if ( $context !== $localContext ) {
478 // remove AuthManagerSpecialPage context hack
479 $this->setContext( $context );
482 $user = $context->getRequest()->getSession()->getUser();
484 $wgUser = $user;
485 $context->setUser( $user );
487 $code = $this->getRequest()->getVal( 'uselang', $user->getOption( 'language' ) );
488 $userLang = Language::factory( $code );
489 $wgLang = $userLang;
490 $context->setLanguage( $userLang );
494 * @param AuthenticationRequest[] $requests A list of AuthorizationRequest objects,
495 * used to generate the form fields. An empty array means a fatal error
496 * (authentication cannot continue).
497 * @param string|Message $msg
498 * @param string $msgtype
499 * @throws ErrorPageError
500 * @throws Exception
501 * @throws FatalError
502 * @throws MWException
503 * @throws PermissionsError
504 * @throws ReadOnlyError
505 * @private
507 protected function mainLoginForm( array $requests, $msg = '', $msgtype = 'error' ) {
508 $titleObj = $this->getPageTitle();
509 $user = $this->getUser();
510 $out = $this->getOutput();
512 // FIXME how to handle empty $requests - restart, or no form, just an error message?
513 // no form would be better for no session type errors, restart is better when can* fails.
514 if ( !$requests ) {
515 $this->authAction = $this->getDefaultAction( $this->subPage );
516 $this->authForm = null;
517 $requests = AuthManager::singleton()->getAuthenticationRequests( $this->authAction, $user );
520 // Generic styles and scripts for both login and signup form
521 $out->addModuleStyles( [
522 'mediawiki.ui',
523 'mediawiki.ui.button',
524 'mediawiki.ui.checkbox',
525 'mediawiki.ui.input',
526 'mediawiki.special.userlogin.common.styles'
527 ] );
528 if ( $this->isSignup() ) {
529 // XXX hack pending RL or JS parse() support for complex content messages T27349
530 $out->addJsConfigVars( 'wgCreateacctImgcaptchaHelp',
531 $this->msg( 'createacct-imgcaptcha-help' )->parse() );
533 // Additional styles and scripts for signup form
534 $out->addModules( [
535 'mediawiki.special.userlogin.signup.js'
536 ] );
537 $out->addModuleStyles( [
538 'mediawiki.special.userlogin.signup.styles'
539 ] );
540 } else {
541 // Additional styles for login form
542 $out->addModuleStyles( [
543 'mediawiki.special.userlogin.login.styles'
544 ] );
546 $out->disallowUserJs(); // just in case...
548 $form = $this->getAuthForm( $requests, $this->authAction, $msg, $msgtype );
549 $form->prepareForm();
551 $submitStatus = Status::newGood();
552 if ( $msg && $msgtype === 'warning' ) {
553 $submitStatus->warning( $msg );
554 } elseif ( $msg && $msgtype === 'error' ) {
555 $submitStatus->fatal( $msg );
558 // warning header for non-standard workflows (e.g. security reauthentication)
559 if (
560 !$this->isSignup() &&
561 $this->getUser()->isLoggedIn() &&
562 $this->authAction !== AuthManager::ACTION_LOGIN_CONTINUE
564 $reauthMessage = $this->securityLevel ? 'userlogin-reauth' : 'userlogin-loggedin';
565 $submitStatus->warning( $reauthMessage, $this->getUser()->getName() );
568 $formHtml = $form->getHTML( $submitStatus );
570 $out->addHTML( $this->getPageHtml( $formHtml ) );
574 * Add page elements which are outside the form.
575 * FIXME this should probably be a template, but use a sane language (handlebars?)
576 * @param string $formHtml
577 * @return string
579 protected function getPageHtml( $formHtml ) {
580 global $wgLoginLanguageSelector;
582 $loginPrompt = $this->isSignup() ? '' : Html::rawElement( 'div',
583 [ 'id' => 'userloginprompt' ], $this->msg( 'loginprompt' )->parseAsBlock() );
584 $languageLinks = $wgLoginLanguageSelector ? $this->makeLanguageSelector() : '';
585 $signupStartMsg = $this->msg( 'signupstart' );
586 $signupStart = ( $this->isSignup() && !$signupStartMsg->isDisabled() )
587 ? Html::rawElement( 'div', [ 'id' => 'signupstart' ], $signupStartMsg->parseAsBlock() ) : '';
588 if ( $languageLinks ) {
589 $languageLinks = Html::rawElement( 'div', [ 'id' => 'languagelinks' ],
590 Html::rawElement( 'p', [], $languageLinks )
594 $benefitsContainer = '';
595 if ( $this->isSignup() && $this->showExtraInformation() ) {
596 // messages used:
597 // createacct-benefit-icon1 createacct-benefit-head1 createacct-benefit-body1
598 // createacct-benefit-icon2 createacct-benefit-head2 createacct-benefit-body2
599 // createacct-benefit-icon3 createacct-benefit-head3 createacct-benefit-body3
600 $benefitCount = 3;
601 $benefitList = '';
602 for ( $benefitIdx = 1; $benefitIdx <= $benefitCount; $benefitIdx++ ) {
603 $headUnescaped = $this->msg( "createacct-benefit-head$benefitIdx" )->text();
604 $iconClass = $this->msg( "createacct-benefit-icon$benefitIdx" )->escaped();
605 $benefitList .= Html::rawElement( 'div', [ 'class' => "mw-number-text $iconClass" ],
606 Html::rawElement( 'h3', [],
607 $this->msg( "createacct-benefit-head$benefitIdx" )->escaped()
609 . Html::rawElement( 'p', [],
610 $this->msg( "createacct-benefit-body$benefitIdx" )->params( $headUnescaped )->escaped()
614 $benefitsContainer = Html::rawElement( 'div', [ 'class' => 'mw-createacct-benefits-container' ],
615 Html::rawElement( 'h2', [], $this->msg( 'createacct-benefit-heading' )->escaped() )
616 . Html::rawElement( 'div', [ 'class' => 'mw-createacct-benefits-list' ],
617 $benefitList
622 $html = Html::rawElement( 'div', [ 'class' => 'mw-ui-container' ],
623 $loginPrompt
624 . $languageLinks
625 . $signupStart
626 . Html::rawElement( 'div', [ 'id' => 'userloginForm' ],
627 $formHtml
629 . $benefitsContainer
632 return $html;
636 * Generates a form from the given request.
637 * @param AuthenticationRequest[] $requests
638 * @param string $action AuthManager action name
639 * @param string|Message $msg
640 * @param string $msgType
641 * @return HTMLForm
643 protected function getAuthForm( array $requests, $action, $msg = '', $msgType = 'error' ) {
644 global $wgSecureLogin;
645 // FIXME merge this with parent
647 if ( isset( $this->authForm ) ) {
648 return $this->authForm;
651 $usingHTTPS = $this->getRequest()->getProtocol() === 'https';
653 // get basic form description from the auth logic
654 $fieldInfo = AuthenticationRequest::mergeFieldInfo( $requests );
655 $fakeTemplate = $this->getFakeTemplate( $msg, $msgType );
656 $this->fakeTemplate = $fakeTemplate; // FIXME there should be a saner way to pass this to the hook
657 // this will call onAuthChangeFormFields()
658 $formDescriptor = static::fieldInfoToFormDescriptor( $requests, $fieldInfo, $this->authAction );
659 $this->postProcessFormDescriptor( $formDescriptor, $requests );
661 $context = $this->getContext();
662 if ( $context->getRequest() !== $this->getRequest() ) {
663 // We have overridden the request, need to make sure the form uses that too.
664 $context = new DerivativeContext( $this->getContext() );
665 $context->setRequest( $this->getRequest() );
667 $form = HTMLForm::factory( 'vform', $formDescriptor, $context );
669 $form->addHiddenField( 'authAction', $this->authAction );
670 if ( $this->mLanguage ) {
671 $form->addHiddenField( 'uselang', $this->mLanguage );
673 $form->addHiddenField( 'force', $this->securityLevel );
674 $form->addHiddenField( $this->getTokenName(), $this->getToken()->toString() );
675 if ( $wgSecureLogin ) {
676 // If using HTTPS coming from HTTP, then the 'fromhttp' parameter must be preserved
677 if ( !$this->isSignup() ) {
678 $form->addHiddenField( 'wpForceHttps', (int)$this->mStickHTTPS );
679 $form->addHiddenField( 'wpFromhttp', $usingHTTPS );
683 // set properties of the form itself
684 $form->setAction( $this->getPageTitle()->getLocalURL( $this->getReturnToQueryStringFragment() ) );
685 $form->setName( 'userlogin' . ( $this->isSignup() ? '2' : '' ) );
686 if ( $this->isSignup() ) {
687 $form->setId( 'userlogin2' );
690 $form->suppressDefaultSubmit();
692 $this->authForm = $form;
694 return $form;
698 * Temporary B/C method to handle extensions using the UserLoginForm/UserCreateForm hooks.
699 * @param string|Message $msg
700 * @param string $msgType
701 * @return FakeAuthTemplate
703 protected function getFakeTemplate( $msg, $msgType ) {
704 global $wgAuth, $wgEnableEmail, $wgHiddenPrefs, $wgEmailConfirmToEdit, $wgEnableUserEmail,
705 $wgSecureLogin, $wgPasswordResetRoutes;
707 // make a best effort to get the value of fields which used to be fixed in the old login
708 // template but now might or might not exist depending on what providers are used
709 $request = $this->getRequest();
710 $data = (object)[
711 'mUsername' => $request->getText( 'wpName' ),
712 'mPassword' => $request->getText( 'wpPassword' ),
713 'mRetype' => $request->getText( 'wpRetype' ),
714 'mEmail' => $request->getText( 'wpEmail' ),
715 'mRealName' => $request->getText( 'wpRealName' ),
716 'mDomain' => $request->getText( 'wpDomain' ),
717 'mReason' => $request->getText( 'wpReason' ),
718 'mRemember' => $request->getCheck( 'wpRemember' ),
721 // Preserves a bunch of logic from the old code that was rewritten in getAuthForm().
722 // There is no code reuse to make this easier to remove .
723 // If an extension tries to change any of these values, they are out of luck - we only
724 // actually use the domain/usedomain/domainnames, extraInput and extrafields keys.
726 $titleObj = $this->getPageTitle();
727 $user = $this->getUser();
728 $template = new FakeAuthTemplate();
730 // Pre-fill username (if not creating an account, bug 44775).
731 if ( $data->mUsername == '' && $this->isSignup() ) {
732 if ( $user->isLoggedIn() ) {
733 $data->mUsername = $user->getName();
734 } else {
735 $data->mUsername = $this->getRequest()->getSession()->suggestLoginUsername();
739 if ( $this->isSignup() ) {
740 // Must match number of benefits defined in messages
741 $template->set( 'benefitCount', 3 );
743 $q = 'action=submitlogin&type=signup';
744 $linkq = 'type=login';
745 } else {
746 $q = 'action=submitlogin&type=login';
747 $linkq = 'type=signup';
750 if ( $this->mReturnTo !== '' ) {
751 $returnto = '&returnto=' . wfUrlencode( $this->mReturnTo );
752 if ( $this->mReturnToQuery !== '' ) {
753 $returnto .= '&returntoquery=' .
754 wfUrlencode( $this->mReturnToQuery );
756 $q .= $returnto;
757 $linkq .= $returnto;
760 # Don't show a "create account" link if the user can't.
761 if ( $this->showCreateAccountLink() ) {
762 # Pass any language selection on to the mode switch link
763 if ( $this->mLanguage ) {
764 $linkq .= '&uselang=' . $this->mLanguage;
766 // Supply URL, login template creates the button.
767 $template->set( 'createOrLoginHref', $titleObj->getLocalURL( $linkq ) );
768 } else {
769 $template->set( 'link', '' );
772 $resetLink = $this->isSignup()
773 ? null
774 : is_array( $wgPasswordResetRoutes )
775 && in_array( true, array_values( $wgPasswordResetRoutes ), true );
777 $template->set( 'header', '' );
778 $template->set( 'formheader', '' );
779 $template->set( 'skin', $this->getSkin() );
781 $template->set( 'name', $data->mUsername );
782 $template->set( 'password', $data->mPassword );
783 $template->set( 'retype', $data->mRetype );
784 $template->set( 'createemailset', false ); // no easy way to get that from AuthManager
785 $template->set( 'email', $data->mEmail );
786 $template->set( 'realname', $data->mRealName );
787 $template->set( 'domain', $data->mDomain );
788 $template->set( 'reason', $data->mReason );
789 $template->set( 'remember', $data->mRemember );
791 $template->set( 'action', $titleObj->getLocalURL( $q ) );
792 $template->set( 'message', $msg );
793 $template->set( 'messagetype', $msgType );
794 $template->set( 'createemail', $wgEnableEmail && $user->isLoggedIn() );
795 $template->set( 'userealname', !in_array( 'realname', $wgHiddenPrefs, true ) );
796 $template->set( 'useemail', $wgEnableEmail );
797 $template->set( 'emailrequired', $wgEmailConfirmToEdit );
798 $template->set( 'emailothers', $wgEnableUserEmail );
799 $template->set( 'canreset', $wgAuth->allowPasswordChange() );
800 $template->set( 'resetlink', $resetLink );
801 $template->set( 'canremember', $request->getSession()->getProvider()
802 ->getRememberUserDuration() !== null );
803 $template->set( 'usereason', $user->isLoggedIn() );
804 $template->set( 'cansecurelogin', ( $wgSecureLogin ) );
805 $template->set( 'stickhttps', (int)$this->mStickHTTPS );
806 $template->set( 'loggedin', $user->isLoggedIn() );
807 $template->set( 'loggedinuser', $user->getName() );
808 $template->set( 'token', $this->getToken()->toString() );
810 $action = $this->isSignup() ? 'signup' : 'login';
811 $wgAuth->modifyUITemplate( $template, $action );
813 $oldTemplate = $template;
815 // Both Hooks::run are explicit here to make findHooks.php happy
816 if ( $this->isSignup() ) {
817 Hooks::run( 'UserCreateForm', [ &$template ] );
818 if ( $oldTemplate !== $template ) {
819 wfDeprecated( "reference in UserCreateForm hook", '1.27' );
821 } else {
822 Hooks::run( 'UserLoginForm', [ &$template ] );
823 if ( $oldTemplate !== $template ) {
824 wfDeprecated( "reference in UserLoginForm hook", '1.27' );
828 return $template;
831 public function onAuthChangeFormFields(
832 array $requests, array $fieldInfo, array &$formDescriptor, $action
834 $coreFieldDescriptors = $this->getFieldDefinitions( $this->fakeTemplate );
835 $specialFields = array_merge( [ 'extraInput' ],
836 array_keys( $this->fakeTemplate->getExtraInputDefinitions() ) );
838 // keep the ordering from getCoreFieldDescriptors() where there is no explicit weight
839 foreach ( $coreFieldDescriptors as $fieldName => $coreField ) {
840 $requestField = isset( $formDescriptor[$fieldName] ) ?
841 $formDescriptor[$fieldName] : [];
843 // remove everything that is not in the fieldinfo, is not marked as a supplemental field
844 // to something in the fieldinfo, is not B/C for the pre-AuthManager templates,
845 // and is not an info field or a submit button
846 if (
847 !isset( $fieldInfo[$fieldName] )
848 && (
849 !isset( $coreField['baseField'] )
850 || !isset( $fieldInfo[$coreField['baseField']] )
852 && !in_array( $fieldName, $specialFields, true )
853 && (
854 !isset( $coreField['type'] )
855 || !in_array( $coreField['type'], [ 'submit', 'info' ], true )
858 $coreFieldDescriptors[$fieldName] = null;
859 continue;
862 // core message labels should always take priority
863 if (
864 isset( $coreField['label'] )
865 || isset( $coreField['label-message'] )
866 || isset( $coreField['label-raw'] )
868 unset( $requestField['label'], $requestField['label-message'], $coreField['label-raw'] );
871 $coreFieldDescriptors[$fieldName] += $requestField;
874 $formDescriptor = array_filter( $coreFieldDescriptors + $formDescriptor );
875 return true;
879 * Show extra information such as password recovery information, link from login to signup,
880 * CTA etc? Such information should only be shown on the "landing page", ie. when the user
881 * is at the first step of the authentication process.
882 * @return bool
884 protected function showExtraInformation() {
885 return $this->authAction !== $this->getContinueAction( $this->authAction )
886 && !$this->securityLevel;
890 * Create a HTMLForm descriptor for the core login fields.
891 * @param FakeAuthTemplate $template B/C data (not used but needed by getBCFieldDefinitions)
892 * @return array
894 protected function getFieldDefinitions( $template ) {
895 global $wgEmailConfirmToEdit;
897 $isLoggedIn = $this->getUser()->isLoggedIn();
898 $continuePart = $this->isContinued() ? 'continue-' : '';
899 $anotherPart = $isLoggedIn ? 'another-' : '';
900 $expiration = $this->getRequest()->getSession()->getProvider()->getRememberUserDuration();
901 $expirationDays = ceil( $expiration / ( 3600 * 24 ) );
902 $secureLoginLink = '';
903 if ( $this->mSecureLoginUrl ) {
904 $secureLoginLink = Html::element( 'a', [
905 'href' => $this->mSecureLoginUrl,
906 'class' => 'mw-ui-flush-right mw-secure',
907 ], $this->msg( 'userlogin-signwithsecure' )->text() );
909 $usernameHelpLink = '';
910 if ( !$this->msg( 'createacct-helpusername' )->isDisabled() ) {
911 $usernameHelpLink = Html::rawElement( 'span', [
912 'class' => 'mw-ui-flush-right',
913 ], $this->msg( 'createacct-helpusername' )->parse() );
916 if ( $this->isSignup() ) {
917 $fieldDefinitions = [
918 'statusarea' => [
919 // used by the mediawiki.special.userlogin.signup.js module for error display
920 // FIXME merge this with HTMLForm's normal status (error) area
921 'type' => 'info',
922 'raw' => true,
923 'default' => Html::element( 'div', [ 'id' => 'mw-createacct-status-area' ] ),
924 'weight' => -105,
926 'username' => [
927 'label-raw' => $this->msg( 'userlogin-yourname' )->escaped() . $usernameHelpLink,
928 'id' => 'wpName2',
929 'placeholder-message' => $isLoggedIn ? 'createacct-another-username-ph'
930 : 'userlogin-yourname-ph',
932 'mailpassword' => [
933 // create account without providing password, a temporary one will be mailed
934 'type' => 'check',
935 'label-message' => 'createaccountmail',
936 'name' => 'wpCreateaccountMail',
937 'id' => 'wpCreateaccountMail',
939 'password' => [
940 'id' => 'wpPassword2',
941 'placeholder-message' => 'createacct-yourpassword-ph',
942 'hide-if' => [ '===', 'wpCreateaccountMail', '1' ],
944 'domain' => [],
945 'retype' => [
946 'baseField' => 'password',
947 'type' => 'password',
948 'label-message' => 'createacct-yourpasswordagain',
949 'id' => 'wpRetype',
950 'cssclass' => 'loginPassword',
951 'size' => 20,
952 'validation-callback' => function ( $value, $alldata ) {
953 if ( empty( $alldata['mailpassword'] ) && !empty( $alldata['password'] ) ) {
954 if ( !$value ) {
955 return $this->msg( 'htmlform-required' );
956 } elseif ( $value !== $alldata['password'] ) {
957 return $this->msg( 'badretype' );
960 return true;
962 'hide-if' => [ '===', 'wpCreateaccountMail', '1' ],
963 'placeholder-message' => 'createacct-yourpasswordagain-ph',
965 'email' => [
966 'type' => 'email',
967 'label-message' => $wgEmailConfirmToEdit ? 'createacct-emailrequired'
968 : 'createacct-emailoptional',
969 'id' => 'wpEmail',
970 'cssclass' => 'loginText',
971 'size' => '20',
972 // FIXME will break non-standard providers
973 'required' => $wgEmailConfirmToEdit,
974 'validation-callback' => function ( $value, $alldata ) {
975 global $wgEmailConfirmToEdit;
977 // AuthManager will check most of these, but that will make the auth
978 // session fail and this won't, so nicer to do it this way
979 if ( !$value && $wgEmailConfirmToEdit ) {
980 // no point in allowing registration without email when email is
981 // required to edit
982 return $this->msg( 'noemailtitle' );
983 } elseif ( !$value && !empty( $alldata['mailpassword'] ) ) {
984 // cannot send password via email when there is no email address
985 return $this->msg( 'noemailcreate' );
986 } elseif ( $value && !Sanitizer::validateEmail( $value ) ) {
987 return $this->msg( 'invalidemailaddress' );
989 return true;
991 'placeholder-message' => 'createacct-' . $anotherPart . 'email-ph',
993 'realname' => [
994 'type' => 'text',
995 'help-message' => $isLoggedIn ? 'createacct-another-realname-tip'
996 : 'prefs-help-realname',
997 'label-message' => 'createacct-realname',
998 'cssclass' => 'loginText',
999 'size' => 20,
1000 'id' => 'wpRealName',
1002 'reason' => [
1003 // comment for the user creation log
1004 'type' => 'text',
1005 'label-message' => 'createacct-reason',
1006 'cssclass' => 'loginText',
1007 'id' => 'wpReason',
1008 'size' => '20',
1009 'placeholder-message' => 'createacct-reason-ph',
1011 'extrainput' => [], // placeholder for fields coming from the template
1012 'createaccount' => [
1013 // submit button
1014 'type' => 'submit',
1015 'default' => $this->msg( 'createacct-' . $anotherPart . $continuePart .
1016 'submit' )->text(),
1017 'name' => 'wpCreateaccount',
1018 'id' => 'wpCreateaccount',
1019 'weight' => 100,
1022 } else {
1023 $fieldDefinitions = [
1024 'username' => [
1025 'label-raw' => $this->msg( 'userlogin-yourname' )->escaped() . $secureLoginLink,
1026 'id' => 'wpName1',
1027 'placeholder-message' => 'userlogin-yourname-ph',
1029 'password' => [
1030 'id' => 'wpPassword1',
1031 'placeholder-message' => 'userlogin-yourpassword-ph',
1033 'domain' => [],
1034 'extrainput' => [],
1035 'rememberMe' => [
1036 // option for saving the user token to a cookie
1037 'type' => 'check',
1038 'name' => 'wpRemember',
1039 'label-message' => $this->msg( 'userlogin-remembermypassword' )
1040 ->numParams( $expirationDays ),
1041 'id' => 'wpRemember',
1043 'loginattempt' => [
1044 // submit button
1045 'type' => 'submit',
1046 'default' => $this->msg( 'pt-login-' . $continuePart . 'button' )->text(),
1047 'id' => 'wpLoginAttempt',
1048 'weight' => 100,
1050 'linkcontainer' => [
1051 // help link
1052 'type' => 'info',
1053 'cssclass' => 'mw-form-related-link-container mw-userlogin-help',
1054 // 'id' => 'mw-userlogin-help', // FIXME HTMLInfoField ignores this
1055 'raw' => true,
1056 'default' => Html::element( 'a', [
1057 'href' => Skin::makeInternalOrExternalUrl( wfMessage( 'helplogin-url' )
1058 ->inContentLanguage()
1059 ->text() ),
1060 ], $this->msg( 'userlogin-helplink2' )->text() ),
1061 'weight' => 200,
1063 // button for ResetPasswordSecondaryAuthenticationProvider
1064 'skipReset' => [
1065 'weight' => 110,
1066 'flags' => [],
1071 $fieldDefinitions['username'] += [
1072 'type' => 'text',
1073 'name' => 'wpName',
1074 'cssclass' => 'loginText',
1075 'size' => 20,
1076 // 'required' => true,
1078 $fieldDefinitions['password'] += [
1079 'type' => 'password',
1080 // 'label-message' => 'userlogin-yourpassword', // would override the changepassword label
1081 'name' => 'wpPassword',
1082 'cssclass' => 'loginPassword',
1083 'size' => 20,
1084 // 'required' => true,
1087 if ( $template->get( 'header' ) || $template->get( 'formheader' ) ) {
1088 // B/C for old extensions that haven't been converted to AuthManager (or have been
1089 // but somebody is using the old version) and still use templates via the
1090 // UserCreateForm/UserLoginForm hook.
1091 // 'header' used by ConfirmEdit, ConfirmAccount, Persona, WikimediaIncubator, SemanticSignup
1092 // 'formheader' used by MobileFrontend
1093 $fieldDefinitions['header'] = [
1094 'type' => 'info',
1095 'raw' => true,
1096 'default' => $template->get( 'header' ) ?: $template->get( 'formheader' ),
1097 'weight' => -110,
1100 if ( $this->mEntryError ) {
1101 $fieldDefinitions['entryError'] = [
1102 'type' => 'info',
1103 'default' => Html::rawElement( 'div', [ 'class' => $this->mEntryErrorType . 'box', ],
1104 $this->mEntryError ),
1105 'raw' => true,
1106 'rawrow' => true,
1107 'weight' => -100,
1110 if ( !$this->showExtraInformation() ) {
1111 unset( $fieldDefinitions['linkcontainer'], $fieldDefinitions['signupend'] );
1113 if ( $this->isSignup() && $this->showExtraInformation() ) {
1114 // blank signup footer for site customization
1115 // uses signupend-https for HTTPS requests if it's not blank, signupend otherwise
1116 $signupendMsg = $this->msg( 'signupend' );
1117 $signupendHttpsMsg = $this->msg( 'signupend-https' );
1118 if ( !$signupendMsg->isDisabled() ) {
1119 $usingHTTPS = $this->getRequest()->getProtocol() === 'https';
1120 $signupendText = ( $usingHTTPS && !$signupendHttpsMsg->isBlank() )
1121 ? $signupendHttpsMsg ->parse() : $signupendMsg->parse();
1122 $fieldDefinitions['signupend'] = [
1123 'type' => 'info',
1124 'raw' => true,
1125 'default' => Html::rawElement( 'div', [ 'id' => 'signupend' ], $signupendText ),
1126 'weight' => 225,
1130 if ( !$this->isSignup() && $this->showExtraInformation() ) {
1131 $passwordReset = new PasswordReset( $this->getConfig(), AuthManager::singleton() );
1132 if ( $passwordReset->isAllowed( $this->getUser() )->isGood() ) {
1133 $fieldDefinitions['passwordReset'] = [
1134 'type' => 'info',
1135 'raw' => true,
1136 'cssclass' => 'mw-form-related-link-container',
1137 'default' => $this->getLinkRenderer()->makeLink(
1138 SpecialPage::getTitleFor( 'PasswordReset' ),
1139 $this->msg( 'userlogin-resetpassword-link' )->text()
1141 'weight' => 230,
1145 // Don't show a "create account" link if the user can't.
1146 if ( $this->showCreateAccountLink() ) {
1147 // link to the other action
1148 $linkTitle = $this->getTitleFor( $this->isSignup() ? 'Userlogin' :'CreateAccount' );
1149 $linkq = $this->getReturnToQueryStringFragment();
1150 // Pass any language selection on to the mode switch link
1151 if ( $this->mLanguage ) {
1152 $linkq .= '&uselang=' . $this->mLanguage;
1154 $loggedIn = $this->getUser()->isLoggedIn();
1156 $fieldDefinitions['createOrLogin'] = [
1157 'type' => 'info',
1158 'raw' => true,
1159 'linkQuery' => $linkq,
1160 'default' => function ( $params ) use ( $loggedIn, $linkTitle ) {
1161 return Html::rawElement( 'div',
1162 [ 'id' => 'mw-createaccount' . ( !$loggedIn ? '-cta' : '' ),
1163 'class' => ( $loggedIn ? 'mw-form-related-link-container' : 'mw-ui-vform-field' ) ],
1164 ( $loggedIn ? '' : $this->msg( 'userlogin-noaccount' )->escaped() )
1165 . Html::element( 'a',
1167 'id' => 'mw-createaccount-join' . ( $loggedIn ? '-loggedin' : '' ),
1168 'href' => $linkTitle->getLocalURL( $params['linkQuery'] ),
1169 'class' => ( $loggedIn ? '' : 'mw-ui-button' ),
1170 'tabindex' => 100,
1172 $this->msg(
1173 $loggedIn ? 'userlogin-createanother' : 'userlogin-joinproject'
1174 )->escaped()
1178 'weight' => 235,
1183 $fieldDefinitions = $this->getBCFieldDefinitions( $fieldDefinitions, $template );
1184 $fieldDefinitions = array_filter( $fieldDefinitions );
1186 return $fieldDefinitions;
1190 * Adds fields provided via the deprecated UserLoginForm / UserCreateForm hooks
1191 * @param $fieldDefinitions array
1192 * @param FakeAuthTemplate $template
1193 * @return array
1195 protected function getBCFieldDefinitions( $fieldDefinitions, $template ) {
1196 if ( $template->get( 'usedomain', false ) ) {
1197 // TODO probably should be translated to the new domain notation in AuthManager
1198 $fieldDefinitions['domain'] = [
1199 'type' => 'select',
1200 'label-message' => 'yourdomainname',
1201 'options' => array_combine( $template->get( 'domainnames', [] ),
1202 $template->get( 'domainnames', [] ) ),
1203 'default' => $template->get( 'domain', '' ),
1204 'name' => 'wpDomain',
1205 // FIXME id => 'mw-user-domain-section' on the parent div
1209 // poor man's associative array_splice
1210 $extraInputPos = array_search( 'extrainput', array_keys( $fieldDefinitions ), true );
1211 $fieldDefinitions = array_slice( $fieldDefinitions, 0, $extraInputPos, true )
1212 + $template->getExtraInputDefinitions()
1213 + array_slice( $fieldDefinitions, $extraInputPos + 1, null, true );
1215 return $fieldDefinitions;
1219 * Check if a session cookie is present.
1221 * This will not pick up a cookie set during _this_ request, but is meant
1222 * to ensure that the client is returning the cookie which was set on a
1223 * previous pass through the system.
1225 * @return bool
1227 protected function hasSessionCookie() {
1228 global $wgDisableCookieCheck, $wgInitialSessionId;
1230 return $wgDisableCookieCheck || (
1231 $wgInitialSessionId &&
1232 $this->getRequest()->getSession()->getId() === (string)$wgInitialSessionId
1237 * Returns a string that can be appended to the URL (without encoding) to preserve the
1238 * return target. Does not include leading '?'/'&'.
1240 protected function getReturnToQueryStringFragment() {
1241 $returnto = '';
1242 if ( $this->mReturnTo !== '' ) {
1243 $returnto = 'returnto=' . wfUrlencode( $this->mReturnTo );
1244 if ( $this->mReturnToQuery !== '' ) {
1245 $returnto .= '&returntoquery=' . wfUrlencode( $this->mReturnToQuery );
1248 return $returnto;
1252 * Whether the login/create account form should display a link to the
1253 * other form (in addition to whatever the skin provides).
1254 * @return bool
1256 private function showCreateAccountLink() {
1257 if ( $this->isSignup() ) {
1258 return true;
1259 } elseif ( $this->getUser()->isAllowed( 'createaccount' ) ) {
1260 return true;
1261 } else {
1262 return false;
1266 protected function getTokenName() {
1267 return $this->isSignup() ? 'wpCreateaccountToken' : 'wpLoginToken';
1271 * Produce a bar of links which allow the user to select another language
1272 * during login/registration but retain "returnto"
1274 * @return string
1276 protected function makeLanguageSelector() {
1277 $msg = $this->msg( 'loginlanguagelinks' )->inContentLanguage();
1278 if ( $msg->isBlank() ) {
1279 return '';
1281 $langs = explode( "\n", $msg->text() );
1282 $links = [];
1283 foreach ( $langs as $lang ) {
1284 $lang = trim( $lang, '* ' );
1285 $parts = explode( '|', $lang );
1286 if ( count( $parts ) >= 2 ) {
1287 $links[] = $this->makeLanguageSelectorLink( $parts[0], trim( $parts[1] ) );
1291 return count( $links ) > 0 ? $this->msg( 'loginlanguagelabel' )->rawParams(
1292 $this->getLanguage()->pipeList( $links ) )->escaped() : '';
1296 * Create a language selector link for a particular language
1297 * Links back to this page preserving type and returnto
1299 * @param string $text Link text
1300 * @param string $lang Language code
1301 * @return string
1303 protected function makeLanguageSelectorLink( $text, $lang ) {
1304 if ( $this->getLanguage()->getCode() == $lang ) {
1305 // no link for currently used language
1306 return htmlspecialchars( $text );
1308 $query = [ 'uselang' => $lang ];
1309 if ( $this->mReturnTo !== '' ) {
1310 $query['returnto'] = $this->mReturnTo;
1311 $query['returntoquery'] = $this->mReturnToQuery;
1314 $attr = [];
1315 $targetLanguage = Language::factory( $lang );
1316 $attr['lang'] = $attr['hreflang'] = $targetLanguage->getHtmlCode();
1318 return $this->getLinkRenderer()->makeKnownLink(
1319 $this->getPageTitle(),
1320 $text,
1321 $attr,
1322 $query
1326 protected function getGroupName() {
1327 return 'login';
1331 * @param array $formDescriptor
1333 protected function postProcessFormDescriptor( &$formDescriptor, $requests ) {
1334 // Pre-fill username (if not creating an account, T46775).
1335 if (
1336 isset( $formDescriptor['username'] ) &&
1337 !isset( $formDescriptor['username']['default'] ) &&
1338 !$this->isSignup()
1340 $user = $this->getUser();
1341 if ( $user->isLoggedIn() ) {
1342 $formDescriptor['username']['default'] = $user->getName();
1343 } else {
1344 $formDescriptor['username']['default'] =
1345 $this->getRequest()->getSession()->suggestLoginUsername();
1349 // don't show a submit button if there is nothing to submit (i.e. the only form content
1350 // is other submit buttons, for redirect flows)
1351 if ( !$this->needsSubmitButton( $requests ) ) {
1352 unset( $formDescriptor['createaccount'], $formDescriptor['loginattempt'] );
1355 if ( !$this->isSignup() ) {
1356 // FIXME HACK don't focus on non-empty field
1357 // maybe there should be an autofocus-if similar to hide-if?
1358 if (
1359 isset( $formDescriptor['username'] )
1360 && empty( $formDescriptor['username']['default'] )
1361 && !$this->getRequest()->getCheck( 'wpName' )
1363 $formDescriptor['username']['autofocus'] = true;
1364 } elseif ( isset( $formDescriptor['password'] ) ) {
1365 $formDescriptor['password']['autofocus'] = true;
1369 $this->addTabIndex( $formDescriptor );
1374 * B/C class to try handling login/signup template modifications even though login/signup does not
1375 * actually happen through a template anymore. Just collects extra field definitions and allows
1376 * some other class to do decide what to do with threm..
1377 * TODO find the right place for adding extra fields and kill this
1379 class FakeAuthTemplate extends BaseTemplate {
1380 public function execute() {
1381 throw new LogicException( 'not used' );
1385 * Extensions (AntiSpoof and TitleBlacklist) call this in response to
1386 * UserCreateForm hook to add checkboxes to the create account form.
1388 public function addInputItem( $name, $value, $type, $msg, $helptext = false ) {
1389 // use the same indexes as UserCreateForm just in case someone adds an item manually
1390 $this->data['extrainput'][] = [
1391 'name' => $name,
1392 'value' => $value,
1393 'type' => $type,
1394 'msg' => $msg,
1395 'helptext' => $helptext,
1400 * Turns addInputItem-style field definitions into HTMLForm field definitions.
1401 * @return array
1403 public function getExtraInputDefinitions() {
1404 $definitions = [];
1406 foreach ( $this->get( 'extrainput', [] ) as $field ) {
1407 $definition = [
1408 'type' => $field['type'] === 'checkbox' ? 'check' : $field['type'],
1409 'name' => $field['name'],
1410 'value' => $field['value'],
1411 'id' => $field['name'],
1413 if ( $field['msg'] ) {
1414 $definition['label-message'] = $this->getMsg( $field['msg'] );
1416 if ( $field['helptext'] ) {
1417 $definition['help'] = $this->msgWiki( $field['helptext'] );
1420 // the array key doesn't matter much when name is defined explicitly but
1421 // let's try and follow HTMLForm conventions
1422 $name = preg_replace( '/^wp(?=[A-Z])/', '', $field['name'] );
1423 $definitions[$name] = $definition;
1426 if ( $this->haveData( 'extrafields' ) ) {
1427 $definitions['extrafields'] = [
1428 'type' => 'info',
1429 'raw' => true,
1430 'default' => $this->get( 'extrafields' ),
1434 return $definitions;
1439 * LoginForm as a special page has been replaced by SpecialUserLogin and SpecialCreateAccount,
1440 * but some extensions called its public methods directly, so the class is retained as a
1441 * B/C wrapper. Anything that used it before should use AuthManager instead.
1443 class LoginForm extends SpecialPage {
1444 const SUCCESS = 0;
1445 const NO_NAME = 1;
1446 const ILLEGAL = 2;
1447 const WRONG_PLUGIN_PASS = 3;
1448 const NOT_EXISTS = 4;
1449 const WRONG_PASS = 5;
1450 const EMPTY_PASS = 6;
1451 const RESET_PASS = 7;
1452 const ABORTED = 8;
1453 const CREATE_BLOCKED = 9;
1454 const THROTTLED = 10;
1455 const USER_BLOCKED = 11;
1456 const NEED_TOKEN = 12;
1457 const WRONG_TOKEN = 13;
1458 const USER_MIGRATED = 14;
1460 public static $statusCodes = [
1461 self::SUCCESS => 'success',
1462 self::NO_NAME => 'no_name',
1463 self::ILLEGAL => 'illegal',
1464 self::WRONG_PLUGIN_PASS => 'wrong_plugin_pass',
1465 self::NOT_EXISTS => 'not_exists',
1466 self::WRONG_PASS => 'wrong_pass',
1467 self::EMPTY_PASS => 'empty_pass',
1468 self::RESET_PASS => 'reset_pass',
1469 self::ABORTED => 'aborted',
1470 self::CREATE_BLOCKED => 'create_blocked',
1471 self::THROTTLED => 'throttled',
1472 self::USER_BLOCKED => 'user_blocked',
1473 self::NEED_TOKEN => 'need_token',
1474 self::WRONG_TOKEN => 'wrong_token',
1475 self::USER_MIGRATED => 'user_migrated',
1479 * @param WebRequest $request
1481 public function __construct( $request = null ) {
1482 wfDeprecated( 'LoginForm', '1.27' );
1483 parent::__construct();
1487 * @deprecated since 1.27 - call LoginHelper::getValidErrorMessages instead.
1489 public static function getValidErrorMessages() {
1490 return LoginHelper::getValidErrorMessages();
1494 * @deprecated since 1.27 - don't use LoginForm, use AuthManager instead
1496 public static function incrementLoginThrottle( $username ) {
1497 wfDeprecated( __METHOD__, "1.27" );
1498 global $wgRequest;
1499 $username = User::getCanonicalName( $username, 'usable' ) ?: $username;
1500 $throttler = new Throttler();
1501 return $throttler->increase( $username, $wgRequest->getIP(), __METHOD__ );
1505 * @deprecated since 1.27 - don't use LoginForm, use AuthManager instead
1507 public static function incLoginThrottle( $username ) {
1508 wfDeprecated( __METHOD__, "1.27" );
1509 $res = self::incrementLoginThrottle( $username );
1510 return is_array( $res ) ? true : 0;
1514 * @deprecated since 1.27 - don't use LoginForm, use AuthManager instead
1516 public static function clearLoginThrottle( $username ) {
1517 wfDeprecated( __METHOD__, "1.27" );
1518 global $wgRequest;
1519 $username = User::getCanonicalName( $username, 'usable' ) ?: $username;
1520 $throttler = new Throttler();
1521 return $throttler->clear( $username, $wgRequest->getIP() );
1525 * @deprecated since 1.27 - don't use LoginForm, use AuthManager instead
1527 public static function getLoginToken() {
1528 wfDeprecated( __METHOD__, '1.27' );
1529 global $wgRequest;
1530 return $wgRequest->getSession()->getToken( '', 'login' )->toString();
1534 * @deprecated since 1.27 - don't use LoginForm, use AuthManager instead
1536 public static function setLoginToken() {
1537 wfDeprecated( __METHOD__, '1.27' );
1541 * @deprecated since 1.27 - don't use LoginForm, use AuthManager instead
1543 public static function clearLoginToken() {
1544 wfDeprecated( __METHOD__, '1.27' );
1545 global $wgRequest;
1546 $wgRequest->getSession()->resetToken( 'login' );
1550 * @deprecated since 1.27 - don't use LoginForm, use AuthManager instead
1552 public static function getCreateaccountToken() {
1553 wfDeprecated( __METHOD__, '1.27' );
1554 global $wgRequest;
1555 return $wgRequest->getSession()->getToken( '', 'createaccount' )->toString();
1559 * @deprecated since 1.27 - don't use LoginForm, use AuthManager instead
1561 public static function setCreateaccountToken() {
1562 wfDeprecated( __METHOD__, '1.27' );
1566 * @deprecated since 1.27 - don't use LoginForm, use AuthManager instead
1568 public static function clearCreateaccountToken() {
1569 wfDeprecated( __METHOD__, '1.27' );
1570 global $wgRequest;
1571 $wgRequest->getSession()->resetToken( 'createaccount' );