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
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\MediaWikiServices
;
30 use MediaWiki\Session\SessionManager
;
31 use Wikimedia\ScopedCallback
;
34 * Holds shared logic for login and account creation pages.
36 * @ingroup SpecialPage
38 abstract class LoginSignupSpecialPage
extends AuthManagerSpecialPage
{
43 protected $mReturnToQuery;
45 protected $mStickHTTPS;
47 protected $mEntryError = '';
48 protected $mEntryErrorType = 'error';
50 protected $mLoaded = false;
51 protected $mLoadedRequest = false;
52 protected $mSecureLoginUrl;
55 protected $securityLevel;
57 /** @var bool True if the user if creating an account for someone else. Flag used for internal
58 * communication, only set at the very end. */
59 protected $proxyAccountCreation;
60 /** @var User FIXME another flag for passing data. */
61 protected $targetUser;
66 /** @var FakeAuthTemplate */
67 protected $fakeTemplate;
69 abstract protected function isSignup();
72 * @param bool $direct True if the action was successful just now; false if that happened
73 * pre-redirection (so this handler was called already)
74 * @param StatusValue|null $extraMessages
77 abstract protected function successfulAction( $direct = false, $extraMessages = null );
80 * Logs to the authmanager-stats channel.
81 * @param bool $success
82 * @param string|null $status Error message key
84 abstract protected function logAuthResult( $success, $status = null );
86 public function __construct( $name ) {
87 global $wgUseMediaWikiUIEverywhere;
88 parent
::__construct( $name );
90 // Override UseMediaWikiEverywhere to true, to force login and create form to use mw ui
91 $wgUseMediaWikiUIEverywhere = true;
94 protected function setRequest( array $data, $wasPosted = null ) {
95 parent
::setRequest( $data, $wasPosted );
96 $this->mLoadedRequest
= false;
100 * Load basic request parameters for this Special page.
101 * @param string $subPage
103 private function loadRequestParameters( $subPage ) {
104 if ( $this->mLoadedRequest
) {
107 $this->mLoadedRequest
= true;
108 $request = $this->getRequest();
110 $this->mPosted
= $request->wasPosted();
111 $this->mIsReturn
= $subPage === 'return';
112 $this->mAction
= $request->getVal( 'action' );
113 $this->mFromHTTP
= $request->getBool( 'fromhttp', false )
114 ||
$request->getBool( 'wpFromhttp', false );
115 $this->mStickHTTPS
= ( !$this->mFromHTTP
&& $request->getProtocol() === 'https' )
116 ||
$request->getBool( 'wpForceHttps', false );
117 $this->mLanguage
= $request->getText( 'uselang' );
118 $this->mReturnTo
= $request->getVal( 'returnto', '' );
119 $this->mReturnToQuery
= $request->getVal( 'returntoquery', '' );
123 * Load data from request.
125 * @param string $subPage Subpage of Special:Userlogin
127 protected function load( $subPage ) {
128 global $wgSecureLogin;
130 $this->loadRequestParameters( $subPage );
131 if ( $this->mLoaded
) {
134 $this->mLoaded
= true;
135 $request = $this->getRequest();
137 $securityLevel = $this->getRequest()->getText( 'force' );
139 $securityLevel && AuthManager
::singleton()->securitySensitiveOperationStatus(
140 $securityLevel ) === AuthManager
::SEC_REAUTH
142 $this->securityLevel
= $securityLevel;
145 $this->loadAuth( $subPage );
147 $this->mToken
= $request->getVal( $this->getTokenName() );
149 // Show an error or warning passed on from a previous page
150 $entryError = $this->msg( $request->getVal( 'error', '' ) );
151 $entryWarning = $this->msg( $request->getVal( 'warning', '' ) );
152 // bc: provide login link as a parameter for messages where the translation
154 $loginreqlink = $this->getLinkRenderer()->makeKnownLink(
155 $this->getPageTitle(),
156 $this->msg( 'loginreqlink' )->text(),
159 'returnto' => $this->mReturnTo
,
160 'returntoquery' => $this->mReturnToQuery
,
161 'uselang' => $this->mLanguage ?
: null,
162 'fromhttp' => $wgSecureLogin && $this->mFromHTTP ?
'1' : null,
166 // Only show valid error or warning messages.
167 if ( $entryError->exists()
168 && in_array( $entryError->getKey(), LoginHelper
::getValidErrorMessages(), true )
170 $this->mEntryErrorType
= 'error';
171 $this->mEntryError
= $entryError->rawParams( $loginreqlink )->parse();
173 } elseif ( $entryWarning->exists()
174 && in_array( $entryWarning->getKey(), LoginHelper
::getValidErrorMessages(), true )
176 $this->mEntryErrorType
= 'warning';
177 $this->mEntryError
= $entryWarning->rawParams( $loginreqlink )->parse();
180 # 1. When switching accounts, it sucks to get automatically logged out
181 # 2. Do not return to PasswordReset after a successful password change
182 # but goto Wiki start page (Main_Page) instead ( T35997 )
183 $returnToTitle = Title
::newFromText( $this->mReturnTo
);
184 if ( is_object( $returnToTitle )
185 && ( $returnToTitle->isSpecial( 'Userlogout' )
186 ||
$returnToTitle->isSpecial( 'PasswordReset' ) )
188 $this->mReturnTo
= '';
189 $this->mReturnToQuery
= '';
193 protected function getPreservedParams( $withToken = false ) {
194 global $wgSecureLogin;
196 $params = parent
::getPreservedParams( $withToken );
198 'returnto' => $this->mReturnTo ?
: null,
199 'returntoquery' => $this->mReturnToQuery ?
: null,
201 if ( $wgSecureLogin && !$this->isSignup() ) {
202 $params['fromhttp'] = $this->mFromHTTP ?
'1' : null;
207 protected function beforeExecute( $subPage ) {
208 // finish initializing the class before processing the request - T135924
209 $this->loadRequestParameters( $subPage );
210 return parent
::beforeExecute( $subPage );
214 * @param string|null $subPage
216 public function execute( $subPage ) {
217 if ( $this->mPosted
) {
218 $time = microtime( true );
219 $profilingScope = new ScopedCallback( function () use ( $time ) {
220 $time = microtime( true ) - $time;
221 $statsd = MediaWikiServices
::getInstance()->getStatsdDataFactory();
222 $statsd->timing( "timing.login.ui.{$this->authAction}", $time * 1000 );
226 $authManager = AuthManager
::singleton();
227 $session = SessionManager
::getGlobalSession();
229 // Session data is used for various things in the authentication process, so we must make
230 // sure a session cookie or some equivalent mechanism is set.
233 $this->load( $subPage );
235 $this->checkPermissions();
237 // Make sure the system configuration allows log in / sign up
238 if ( !$this->isSignup() && !$authManager->canAuthenticateNow() ) {
239 if ( !$session->canSetUser() ) {
240 throw new ErrorPageError( 'cannotloginnow-title', 'cannotloginnow-text', [
241 $session->getProvider()->describe( RequestContext
::getMain()->getLanguage() )
244 throw new ErrorPageError( 'cannotlogin-title', 'cannotlogin-text' );
245 } elseif ( $this->isSignup() && !$authManager->canCreateAccounts() ) {
246 throw new ErrorPageError( 'cannotcreateaccount-title', 'cannotcreateaccount-text' );
250 * In the case where the user is already logged in, and was redirected to
251 * the login form from a page that requires login, do not show the login
252 * page. The use case scenario for this is when a user opens a large number
253 * of tabs, is redirected to the login page on all of them, and then logs
254 * in on one, expecting all the others to work properly.
256 * However, do show the form if it was visited intentionally (no 'returnto'
257 * is present). People who often switch between several accounts have grown
258 * accustomed to this behavior.
260 * Also make an exception when force=<level> is set in the URL, which means the user must
261 * reauthenticate for security reasons.
263 if ( !$this->isSignup() && !$this->mPosted
&& !$this->securityLevel
&&
264 ( $this->mReturnTo
!== '' ||
$this->mReturnToQuery
!== '' ) &&
265 $this->getUser()->isLoggedIn()
267 $this->successfulAction();
271 // If logging in and not on HTTPS, either redirect to it or offer a link.
272 global $wgSecureLogin;
273 if ( $this->getRequest()->getProtocol() !== 'https' ) {
274 $title = $this->getFullTitle();
275 $query = $this->getPreservedParams( false ) +
[
277 ( $this->mEntryErrorType
=== 'error' ?
'error'
278 : 'warning' ) => $this->mEntryError
,
279 ] +
$this->getRequest()->getQueryValues();
280 $url = $title->getFullURL( $query, false, PROTO_HTTPS
);
281 if ( $wgSecureLogin && !$this->mFromHTTP
&&
282 wfCanIPUseHTTPS( $this->getRequest()->getIP() )
284 // Avoid infinite redirect
285 $url = wfAppendQuery( $url, 'fromhttp=1' );
286 $this->getOutput()->redirect( $url );
287 // Since we only do this redir to change proto, always vary
288 $this->getOutput()->addVaryHeader( 'X-Forwarded-Proto' );
292 // A wiki without HTTPS login support should set $wgServer to
293 // http://somehost, in which case the secure URL generated
294 // above won't actually start with https://
295 if ( substr( $url, 0, 8 ) === 'https://' ) {
296 $this->mSecureLoginUrl
= $url;
301 if ( !$this->isActionAllowed( $this->authAction
) ) {
302 // FIXME how do we explain this to the user? can we handle session loss better?
303 // messages used: authpage-cannot-login, authpage-cannot-login-continue,
304 // authpage-cannot-create, authpage-cannot-create-continue
305 $this->mainLoginForm( [], 'authpage-cannot-' . $this->authAction
);
309 if ( $this->canBypassForm( $button_name ) ) {
310 $this->setRequest( [], true );
311 $this->getRequest()->setVal( $this->getTokenName(), $this->getToken() );
312 if ( $button_name ) {
313 $this->getRequest()->setVal( $button_name, true );
317 $status = $this->trySubmit();
319 if ( !$status ||
!$status->isGood() ) {
320 $this->mainLoginForm( $this->authRequests
, $status ?
$status->getMessage() : '', 'error' );
324 /** @var AuthenticationResponse $response */
325 $response = $status->getValue();
327 $returnToUrl = $this->getPageTitle( 'return' )
328 ->getFullURL( $this->getPreservedParams( true ), false, PROTO_HTTPS
);
329 switch ( $response->status
) {
330 case AuthenticationResponse
::PASS
:
331 $this->logAuthResult( true );
332 $this->proxyAccountCreation
= $this->isSignup() && !$this->getUser()->isAnon();
333 $this->targetUser
= User
::newFromName( $response->username
);
336 !$this->proxyAccountCreation
337 && $response->loginRequest
338 && $authManager->canAuthenticateNow()
340 // successful registration; log the user in instantly
341 $response2 = $authManager->beginAuthentication( [ $response->loginRequest
],
343 if ( $response2->status
!== AuthenticationResponse
::PASS
) {
344 LoggerFactory
::getInstance( 'login' )
345 ->error( 'Could not log in after account creation' );
346 $this->successfulAction( true, Status
::newFatal( 'createacct-loginerror' ) );
351 if ( !$this->proxyAccountCreation
) {
352 // Ensure that the context user is the same as the session user.
353 $this->setSessionUserForCurrentRequest();
356 $this->successfulAction( true );
358 case AuthenticationResponse
::FAIL
:
360 case AuthenticationResponse
::RESTART
:
361 unset( $this->authForm
);
362 if ( $response->status
=== AuthenticationResponse
::FAIL
) {
363 $action = $this->getDefaultAction( $subPage );
364 $messageType = 'error';
366 $action = $this->getContinueAction( $this->authAction
);
367 $messageType = 'warning';
369 $this->logAuthResult( false, $response->message ?
$response->message
->getKey() : '-' );
370 $this->loadAuth( $subPage, $action, true );
371 $this->mainLoginForm( $this->authRequests
, $response->message
, $messageType );
373 case AuthenticationResponse
::REDIRECT
:
374 unset( $this->authForm
);
375 $this->getOutput()->redirect( $response->redirectTarget
);
377 case AuthenticationResponse
::UI
:
378 unset( $this->authForm
);
379 $this->authAction
= $this->isSignup() ? AuthManager
::ACTION_CREATE_CONTINUE
380 : AuthManager
::ACTION_LOGIN_CONTINUE
;
381 $this->authRequests
= $response->neededRequests
;
382 $this->mainLoginForm( $response->neededRequests
, $response->message
, $response->messageType
);
385 throw new LogicException( 'invalid AuthenticationResponse' );
390 * Determine if the login form can be bypassed. This will be the case when no more than one
391 * button is present and no other user input fields that are not marked as 'skippable' are
392 * present. If the login form were not bypassed, the user would be presented with a
393 * superfluous page on which they must press the single button to proceed with login.
394 * Not only does this cause an additional mouse click and page load, it confuses users,
395 * especially since there are a help link and forgotten password link that are
396 * provided on the login page that do not apply to this situation.
398 * @param string|null &$button_name if the form has a single button, returns
399 * the name of the button; otherwise, returns null
402 private function canBypassForm( &$button_name ) {
404 if ( $this->isContinued() ) {
407 $fields = AuthenticationRequest
::mergeFieldInfo( $this->authRequests
);
408 foreach ( $fields as $fieldname => $field ) {
409 if ( !isset( $field['type'] ) ) {
412 if ( !empty( $field['skippable'] ) ) {
415 if ( $field['type'] === 'button' ) {
416 if ( $button_name !== null ) {
420 $button_name = $fieldname;
422 } elseif ( $field['type'] !== 'null' ) {
430 * Show the success page.
432 * @param string $type Condition of return to; see `executeReturnTo`
433 * @param string|Message $title Page's title
434 * @param string $msgname
435 * @param string $injected_html
436 * @param StatusValue|null $extraMessages
438 protected function showSuccessPage(
439 $type, $title, $msgname, $injected_html, $extraMessages
441 $out = $this->getOutput();
442 $out->setPageTitle( $title );
444 $out->addWikiMsg( $msgname, wfEscapeWikiText( $this->getUser()->getName() ) );
446 if ( $extraMessages ) {
447 $extraMessages = Status
::wrap( $extraMessages );
448 $out->addWikiText( $extraMessages->getWikiText() );
451 $out->addHTML( $injected_html );
453 $helper = new LoginHelper( $this->getContext() );
454 $helper->showReturnToPage( $type, $this->mReturnTo
, $this->mReturnToQuery
, $this->mStickHTTPS
);
458 * Add a "return to" link or redirect to it.
459 * Extensions can use this to reuse the "return to" logic after
460 * inject steps (such as redirection) into the login process.
462 * @param string $type One of the following:
463 * - error: display a return to link ignoring $wgRedirectOnLogin
464 * - signup: display a return to link using $wgRedirectOnLogin if needed
465 * - success: display a return to link using $wgRedirectOnLogin if needed
466 * - successredirect: send an HTTP redirect using $wgRedirectOnLogin if needed
467 * @param string $returnTo
468 * @param array|string $returnToQuery
469 * @param bool $stickHTTPS Keep redirect link on HTTPS
472 public function showReturnToPage(
473 $type, $returnTo = '', $returnToQuery = '', $stickHTTPS = false
475 $helper = new LoginHelper( $this->getContext() );
476 $helper->showReturnToPage( $type, $returnTo, $returnToQuery, $stickHTTPS );
480 * Replace some globals to make sure the fact that the user has just been logged in is
481 * reflected in the current request.
483 protected function setSessionUserForCurrentRequest() {
484 global $wgUser, $wgLang;
486 $context = RequestContext
::getMain();
487 $localContext = $this->getContext();
488 if ( $context !== $localContext ) {
489 // remove AuthManagerSpecialPage context hack
490 $this->setContext( $context );
493 $user = $context->getRequest()->getSession()->getUser();
496 $context->setUser( $user );
498 $code = $this->getRequest()->getVal( 'uselang', $user->getOption( 'language' ) );
499 $userLang = Language
::factory( $code );
501 $context->setLanguage( $userLang );
505 * @param AuthenticationRequest[] $requests A list of AuthorizationRequest objects,
506 * used to generate the form fields. An empty array means a fatal error
507 * (authentication cannot continue).
508 * @param string|Message $msg
509 * @param string $msgtype
510 * @throws ErrorPageError
513 * @throws MWException
514 * @throws PermissionsError
515 * @throws ReadOnlyError
518 protected function mainLoginForm( array $requests, $msg = '', $msgtype = 'error' ) {
519 $user = $this->getUser();
520 $out = $this->getOutput();
522 // FIXME how to handle empty $requests - restart, or no form, just an error message?
523 // no form would be better for no session type errors, restart is better when can* fails.
525 $this->authAction
= $this->getDefaultAction( $this->subPage
);
526 $this->authForm
= null;
527 $requests = AuthManager
::singleton()->getAuthenticationRequests( $this->authAction
, $user );
530 // Generic styles and scripts for both login and signup form
531 $out->addModuleStyles( [
533 'mediawiki.ui.button',
534 'mediawiki.ui.checkbox',
535 'mediawiki.ui.input',
536 'mediawiki.special.userlogin.common.styles'
538 if ( $this->isSignup() ) {
539 // XXX hack pending RL or JS parse() support for complex content messages T27349
540 $out->addJsConfigVars( 'wgCreateacctImgcaptchaHelp',
541 $this->msg( 'createacct-imgcaptcha-help' )->parse() );
543 // Additional styles and scripts for signup form
545 'mediawiki.special.userlogin.signup.js'
547 $out->addModuleStyles( [
548 'mediawiki.special.userlogin.signup.styles'
551 // Additional styles for login form
552 $out->addModuleStyles( [
553 'mediawiki.special.userlogin.login.styles'
556 $out->disallowUserJs(); // just in case...
558 $form = $this->getAuthForm( $requests, $this->authAction
, $msg, $msgtype );
559 $form->prepareForm();
561 $submitStatus = Status
::newGood();
562 if ( $msg && $msgtype === 'warning' ) {
563 $submitStatus->warning( $msg );
564 } elseif ( $msg && $msgtype === 'error' ) {
565 $submitStatus->fatal( $msg );
568 // warning header for non-standard workflows (e.g. security reauthentication)
570 !$this->isSignup() &&
571 $this->getUser()->isLoggedIn() &&
572 $this->authAction
!== AuthManager
::ACTION_LOGIN_CONTINUE
574 $reauthMessage = $this->securityLevel ?
'userlogin-reauth' : 'userlogin-loggedin';
575 $submitStatus->warning( $reauthMessage, $this->getUser()->getName() );
578 $formHtml = $form->getHTML( $submitStatus );
580 $out->addHTML( $this->getPageHtml( $formHtml ) );
584 * Add page elements which are outside the form.
585 * FIXME this should probably be a template, but use a sane language (handlebars?)
586 * @param string $formHtml
589 protected function getPageHtml( $formHtml ) {
590 global $wgLoginLanguageSelector;
592 $loginPrompt = $this->isSignup() ?
'' : Html
::rawElement( 'div',
593 [ 'id' => 'userloginprompt' ], $this->msg( 'loginprompt' )->parseAsBlock() );
594 $languageLinks = $wgLoginLanguageSelector ?
$this->makeLanguageSelector() : '';
595 $signupStartMsg = $this->msg( 'signupstart' );
596 $signupStart = ( $this->isSignup() && !$signupStartMsg->isDisabled() )
597 ? Html
::rawElement( 'div', [ 'id' => 'signupstart' ], $signupStartMsg->parseAsBlock() ) : '';
598 if ( $languageLinks ) {
599 $languageLinks = Html
::rawElement( 'div', [ 'id' => 'languagelinks' ],
600 Html
::rawElement( 'p', [], $languageLinks )
604 $benefitsContainer = '';
605 if ( $this->isSignup() && $this->showExtraInformation() ) {
607 // createacct-benefit-icon1 createacct-benefit-head1 createacct-benefit-body1
608 // createacct-benefit-icon2 createacct-benefit-head2 createacct-benefit-body2
609 // createacct-benefit-icon3 createacct-benefit-head3 createacct-benefit-body3
612 for ( $benefitIdx = 1; $benefitIdx <= $benefitCount; $benefitIdx++
) {
613 $headUnescaped = $this->msg( "createacct-benefit-head$benefitIdx" )->text();
614 $iconClass = $this->msg( "createacct-benefit-icon$benefitIdx" )->escaped();
615 $benefitList .= Html
::rawElement( 'div', [ 'class' => "mw-number-text $iconClass" ],
616 Html
::rawElement( 'h3', [],
617 $this->msg( "createacct-benefit-head$benefitIdx" )->escaped()
619 . Html
::rawElement( 'p', [],
620 $this->msg( "createacct-benefit-body$benefitIdx" )->params( $headUnescaped )->escaped()
624 $benefitsContainer = Html
::rawElement( 'div', [ 'class' => 'mw-createacct-benefits-container' ],
625 Html
::rawElement( 'h2', [], $this->msg( 'createacct-benefit-heading' )->escaped() )
626 . Html
::rawElement( 'div', [ 'class' => 'mw-createacct-benefits-list' ],
632 $html = Html
::rawElement( 'div', [ 'class' => 'mw-ui-container' ],
636 . Html
::rawElement( 'div', [ 'id' => 'userloginForm' ],
646 * Generates a form from the given request.
647 * @param AuthenticationRequest[] $requests
648 * @param string $action AuthManager action name
649 * @param string|Message $msg
650 * @param string $msgType
653 protected function getAuthForm( array $requests, $action, $msg = '', $msgType = 'error' ) {
654 global $wgSecureLogin;
655 // FIXME merge this with parent
657 if ( isset( $this->authForm
) ) {
658 return $this->authForm
;
661 $usingHTTPS = $this->getRequest()->getProtocol() === 'https';
663 // get basic form description from the auth logic
664 $fieldInfo = AuthenticationRequest
::mergeFieldInfo( $requests );
665 $fakeTemplate = $this->getFakeTemplate( $msg, $msgType );
666 $this->fakeTemplate
= $fakeTemplate; // FIXME there should be a saner way to pass this to the hook
667 // this will call onAuthChangeFormFields()
668 $formDescriptor = static::fieldInfoToFormDescriptor( $requests, $fieldInfo, $this->authAction
);
669 $this->postProcessFormDescriptor( $formDescriptor, $requests );
671 $context = $this->getContext();
672 if ( $context->getRequest() !== $this->getRequest() ) {
673 // We have overridden the request, need to make sure the form uses that too.
674 $context = new DerivativeContext( $this->getContext() );
675 $context->setRequest( $this->getRequest() );
677 $form = HTMLForm
::factory( 'vform', $formDescriptor, $context );
679 $form->addHiddenField( 'authAction', $this->authAction
);
680 if ( $this->mLanguage
) {
681 $form->addHiddenField( 'uselang', $this->mLanguage
);
683 $form->addHiddenField( 'force', $this->securityLevel
);
684 $form->addHiddenField( $this->getTokenName(), $this->getToken()->toString() );
685 if ( $wgSecureLogin ) {
686 // If using HTTPS coming from HTTP, then the 'fromhttp' parameter must be preserved
687 if ( !$this->isSignup() ) {
688 $form->addHiddenField( 'wpForceHttps', (int)$this->mStickHTTPS
);
689 $form->addHiddenField( 'wpFromhttp', $usingHTTPS );
693 // set properties of the form itself
694 $form->setAction( $this->getPageTitle()->getLocalURL( $this->getReturnToQueryStringFragment() ) );
695 $form->setName( 'userlogin' . ( $this->isSignup() ?
'2' : '' ) );
696 if ( $this->isSignup() ) {
697 $form->setId( 'userlogin2' );
700 $form->suppressDefaultSubmit();
702 $this->authForm
= $form;
708 * Temporary B/C method to handle extensions using the UserLoginForm/UserCreateForm hooks.
709 * @param string|Message $msg
710 * @param string $msgType
711 * @return FakeAuthTemplate
713 protected function getFakeTemplate( $msg, $msgType ) {
714 global $wgAuth, $wgEnableEmail, $wgHiddenPrefs, $wgEmailConfirmToEdit, $wgEnableUserEmail,
715 $wgSecureLogin, $wgPasswordResetRoutes;
717 // make a best effort to get the value of fields which used to be fixed in the old login
718 // template but now might or might not exist depending on what providers are used
719 $request = $this->getRequest();
721 'mUsername' => $request->getText( 'wpName' ),
722 'mPassword' => $request->getText( 'wpPassword' ),
723 'mRetype' => $request->getText( 'wpRetype' ),
724 'mEmail' => $request->getText( 'wpEmail' ),
725 'mRealName' => $request->getText( 'wpRealName' ),
726 'mDomain' => $request->getText( 'wpDomain' ),
727 'mReason' => $request->getText( 'wpReason' ),
728 'mRemember' => $request->getCheck( 'wpRemember' ),
731 // Preserves a bunch of logic from the old code that was rewritten in getAuthForm().
732 // There is no code reuse to make this easier to remove .
733 // If an extension tries to change any of these values, they are out of luck - we only
734 // actually use the domain/usedomain/domainnames, extraInput and extrafields keys.
736 $titleObj = $this->getPageTitle();
737 $user = $this->getUser();
738 $template = new FakeAuthTemplate();
740 // Pre-fill username (if not creating an account, T46775).
741 if ( $data->mUsername
== '' && $this->isSignup() ) {
742 if ( $user->isLoggedIn() ) {
743 $data->mUsername
= $user->getName();
745 $data->mUsername
= $this->getRequest()->getSession()->suggestLoginUsername();
749 if ( $this->isSignup() ) {
750 // Must match number of benefits defined in messages
751 $template->set( 'benefitCount', 3 );
753 $q = 'action=submitlogin&type=signup';
754 $linkq = 'type=login';
756 $q = 'action=submitlogin&type=login';
757 $linkq = 'type=signup';
760 if ( $this->mReturnTo
!== '' ) {
761 $returnto = '&returnto=' . wfUrlencode( $this->mReturnTo
);
762 if ( $this->mReturnToQuery
!== '' ) {
763 $returnto .= '&returntoquery=' .
764 wfUrlencode( $this->mReturnToQuery
);
770 # Don't show a "create account" link if the user can't.
771 if ( $this->showCreateAccountLink() ) {
772 # Pass any language selection on to the mode switch link
773 if ( $this->mLanguage
) {
774 $linkq .= '&uselang=' . urlencode( $this->mLanguage
);
776 // Supply URL, login template creates the button.
777 $template->set( 'createOrLoginHref', $titleObj->getLocalURL( $linkq ) );
779 $template->set( 'link', '' );
782 $resetLink = $this->isSignup()
784 : is_array( $wgPasswordResetRoutes )
785 && in_array( true, array_values( $wgPasswordResetRoutes ), true );
787 $template->set( 'header', '' );
788 $template->set( 'formheader', '' );
789 $template->set( 'skin', $this->getSkin() );
791 $template->set( 'name', $data->mUsername
);
792 $template->set( 'password', $data->mPassword
);
793 $template->set( 'retype', $data->mRetype
);
794 $template->set( 'createemailset', false ); // no easy way to get that from AuthManager
795 $template->set( 'email', $data->mEmail
);
796 $template->set( 'realname', $data->mRealName
);
797 $template->set( 'domain', $data->mDomain
);
798 $template->set( 'reason', $data->mReason
);
799 $template->set( 'remember', $data->mRemember
);
801 $template->set( 'action', $titleObj->getLocalURL( $q ) );
802 $template->set( 'message', $msg );
803 $template->set( 'messagetype', $msgType );
804 $template->set( 'createemail', $wgEnableEmail && $user->isLoggedIn() );
805 $template->set( 'userealname', !in_array( 'realname', $wgHiddenPrefs, true ) );
806 $template->set( 'useemail', $wgEnableEmail );
807 $template->set( 'emailrequired', $wgEmailConfirmToEdit );
808 $template->set( 'emailothers', $wgEnableUserEmail );
809 $template->set( 'canreset', $wgAuth->allowPasswordChange() );
810 $template->set( 'resetlink', $resetLink );
811 $template->set( 'canremember', $request->getSession()->getProvider()
812 ->getRememberUserDuration() !== null );
813 $template->set( 'usereason', $user->isLoggedIn() );
814 $template->set( 'cansecurelogin', ( $wgSecureLogin ) );
815 $template->set( 'stickhttps', (int)$this->mStickHTTPS
);
816 $template->set( 'loggedin', $user->isLoggedIn() );
817 $template->set( 'loggedinuser', $user->getName() );
818 $template->set( 'token', $this->getToken()->toString() );
820 $action = $this->isSignup() ?
'signup' : 'login';
821 $wgAuth->modifyUITemplate( $template, $action );
823 $oldTemplate = $template;
825 // Both Hooks::run are explicit here to make findHooks.php happy
826 if ( $this->isSignup() ) {
827 Hooks
::run( 'UserCreateForm', [ &$template ] );
828 if ( $oldTemplate !== $template ) {
829 wfDeprecated( "reference in UserCreateForm hook", '1.27' );
832 Hooks
::run( 'UserLoginForm', [ &$template ] );
833 if ( $oldTemplate !== $template ) {
834 wfDeprecated( "reference in UserLoginForm hook", '1.27' );
841 public function onAuthChangeFormFields(
842 array $requests, array $fieldInfo, array &$formDescriptor, $action
844 $coreFieldDescriptors = $this->getFieldDefinitions( $this->fakeTemplate
);
845 $specialFields = array_merge( [ 'extraInput' ],
846 array_keys( $this->fakeTemplate
->getExtraInputDefinitions() ) );
848 // keep the ordering from getCoreFieldDescriptors() where there is no explicit weight
849 foreach ( $coreFieldDescriptors as $fieldName => $coreField ) {
850 $requestField = $formDescriptor[$fieldName] ??
[];
852 // remove everything that is not in the fieldinfo, is not marked as a supplemental field
853 // to something in the fieldinfo, is not B/C for the pre-AuthManager templates,
854 // and is not an info field or a submit button
856 !isset( $fieldInfo[$fieldName] )
858 !isset( $coreField['baseField'] )
859 ||
!isset( $fieldInfo[$coreField['baseField']] )
861 && !in_array( $fieldName, $specialFields, true )
863 !isset( $coreField['type'] )
864 ||
!in_array( $coreField['type'], [ 'submit', 'info' ], true )
867 $coreFieldDescriptors[$fieldName] = null;
871 // core message labels should always take priority
873 isset( $coreField['label'] )
874 ||
isset( $coreField['label-message'] )
875 ||
isset( $coreField['label-raw'] )
877 unset( $requestField['label'], $requestField['label-message'], $coreField['label-raw'] );
880 $coreFieldDescriptors[$fieldName] +
= $requestField;
883 $formDescriptor = array_filter( $coreFieldDescriptors +
$formDescriptor );
888 * Show extra information such as password recovery information, link from login to signup,
889 * CTA etc? Such information should only be shown on the "landing page", ie. when the user
890 * is at the first step of the authentication process.
893 protected function showExtraInformation() {
894 return $this->authAction
!== $this->getContinueAction( $this->authAction
)
895 && !$this->securityLevel
;
899 * Create a HTMLForm descriptor for the core login fields.
900 * @param FakeAuthTemplate $template B/C data (not used but needed by getBCFieldDefinitions)
903 protected function getFieldDefinitions( $template ) {
904 global $wgEmailConfirmToEdit;
906 $isLoggedIn = $this->getUser()->isLoggedIn();
907 $continuePart = $this->isContinued() ?
'continue-' : '';
908 $anotherPart = $isLoggedIn ?
'another-' : '';
909 $expiration = $this->getRequest()->getSession()->getProvider()->getRememberUserDuration();
910 $expirationDays = ceil( $expiration / ( 3600 * 24 ) );
911 $secureLoginLink = '';
912 if ( $this->mSecureLoginUrl
) {
913 $secureLoginLink = Html
::element( 'a', [
914 'href' => $this->mSecureLoginUrl
,
915 'class' => 'mw-ui-flush-right mw-secure',
916 ], $this->msg( 'userlogin-signwithsecure' )->text() );
918 $usernameHelpLink = '';
919 if ( !$this->msg( 'createacct-helpusername' )->isDisabled() ) {
920 $usernameHelpLink = Html
::rawElement( 'span', [
921 'class' => 'mw-ui-flush-right',
922 ], $this->msg( 'createacct-helpusername' )->parse() );
925 if ( $this->isSignup() ) {
926 $fieldDefinitions = [
928 // used by the mediawiki.special.userlogin.signup.js module for error display
929 // FIXME merge this with HTMLForm's normal status (error) area
932 'default' => Html
::element( 'div', [ 'id' => 'mw-createacct-status-area' ] ),
936 'label-raw' => $this->msg( 'userlogin-yourname' )->escaped() . $usernameHelpLink,
938 'placeholder-message' => $isLoggedIn ?
'createacct-another-username-ph'
939 : 'userlogin-yourname-ph',
942 // create account without providing password, a temporary one will be mailed
944 'label-message' => 'createaccountmail',
945 'name' => 'wpCreateaccountMail',
946 'id' => 'wpCreateaccountMail',
949 'id' => 'wpPassword2',
950 'placeholder-message' => 'createacct-yourpassword-ph',
951 'hide-if' => [ '===', 'wpCreateaccountMail', '1' ],
955 'baseField' => 'password',
956 'type' => 'password',
957 'label-message' => 'createacct-yourpasswordagain',
959 'cssclass' => 'loginPassword',
961 'validation-callback' => function ( $value, $alldata ) {
962 if ( empty( $alldata['mailpassword'] ) && !empty( $alldata['password'] ) ) {
964 return $this->msg( 'htmlform-required' );
965 } elseif ( $value !== $alldata['password'] ) {
966 return $this->msg( 'badretype' );
971 'hide-if' => [ '===', 'wpCreateaccountMail', '1' ],
972 'placeholder-message' => 'createacct-yourpasswordagain-ph',
976 'label-message' => $wgEmailConfirmToEdit ?
'createacct-emailrequired'
977 : 'createacct-emailoptional',
979 'cssclass' => 'loginText',
981 // FIXME will break non-standard providers
982 'required' => $wgEmailConfirmToEdit,
983 'validation-callback' => function ( $value, $alldata ) {
984 global $wgEmailConfirmToEdit;
986 // AuthManager will check most of these, but that will make the auth
987 // session fail and this won't, so nicer to do it this way
988 if ( !$value && $wgEmailConfirmToEdit ) {
989 // no point in allowing registration without email when email is
991 return $this->msg( 'noemailtitle' );
992 } elseif ( !$value && !empty( $alldata['mailpassword'] ) ) {
993 // cannot send password via email when there is no email address
994 return $this->msg( 'noemailcreate' );
995 } elseif ( $value && !Sanitizer
::validateEmail( $value ) ) {
996 return $this->msg( 'invalidemailaddress' );
1000 'placeholder-message' => 'createacct-' . $anotherPart . 'email-ph',
1004 'help-message' => $isLoggedIn ?
'createacct-another-realname-tip'
1005 : 'prefs-help-realname',
1006 'label-message' => 'createacct-realname',
1007 'cssclass' => 'loginText',
1009 'id' => 'wpRealName',
1012 // comment for the user creation log
1014 'label-message' => 'createacct-reason',
1015 'cssclass' => 'loginText',
1018 'placeholder-message' => 'createacct-reason-ph',
1020 'extrainput' => [], // placeholder for fields coming from the template
1021 'createaccount' => [
1024 'default' => $this->msg( 'createacct-' . $anotherPart . $continuePart .
1026 'name' => 'wpCreateaccount',
1027 'id' => 'wpCreateaccount',
1032 $fieldDefinitions = [
1034 'label-raw' => $this->msg( 'userlogin-yourname' )->escaped() . $secureLoginLink,
1036 'placeholder-message' => 'userlogin-yourname-ph',
1039 'id' => 'wpPassword1',
1040 'placeholder-message' => 'userlogin-yourpassword-ph',
1045 // option for saving the user token to a cookie
1047 'name' => 'wpRemember',
1048 'label-message' => $this->msg( 'userlogin-remembermypassword' )
1049 ->numParams( $expirationDays ),
1050 'id' => 'wpRemember',
1055 'default' => $this->msg( 'pt-login-' . $continuePart . 'button' )->text(),
1056 'id' => 'wpLoginAttempt',
1059 'linkcontainer' => [
1062 'cssclass' => 'mw-form-related-link-container mw-userlogin-help',
1063 // 'id' => 'mw-userlogin-help', // FIXME HTMLInfoField ignores this
1065 'default' => Html
::element( 'a', [
1066 'href' => Skin
::makeInternalOrExternalUrl( $this->msg( 'helplogin-url' )
1067 ->inContentLanguage()
1069 ], $this->msg( 'userlogin-helplink2' )->text() ),
1072 // button for ResetPasswordSecondaryAuthenticationProvider
1080 $fieldDefinitions['username'] +
= [
1083 'cssclass' => 'loginText',
1085 // 'required' => true,
1087 $fieldDefinitions['password'] +
= [
1088 'type' => 'password',
1089 // 'label-message' => 'userlogin-yourpassword', // would override the changepassword label
1090 'name' => 'wpPassword',
1091 'cssclass' => 'loginPassword',
1093 // 'required' => true,
1096 if ( $template->get( 'header' ) ||
$template->get( 'formheader' ) ) {
1097 // B/C for old extensions that haven't been converted to AuthManager (or have been
1098 // but somebody is using the old version) and still use templates via the
1099 // UserCreateForm/UserLoginForm hook.
1100 // 'header' used by ConfirmEdit, ConfirmAccount, Persona, WikimediaIncubator, SemanticSignup
1101 // 'formheader' used by MobileFrontend
1102 $fieldDefinitions['header'] = [
1105 'default' => $template->get( 'header' ) ?
: $template->get( 'formheader' ),
1109 if ( $this->mEntryError
) {
1110 $fieldDefinitions['entryError'] = [
1112 'default' => Html
::rawElement( 'div', [ 'class' => $this->mEntryErrorType
. 'box', ],
1113 $this->mEntryError
),
1119 if ( !$this->showExtraInformation() ) {
1120 unset( $fieldDefinitions['linkcontainer'], $fieldDefinitions['signupend'] );
1122 if ( $this->isSignup() && $this->showExtraInformation() ) {
1123 // blank signup footer for site customization
1124 // uses signupend-https for HTTPS requests if it's not blank, signupend otherwise
1125 $signupendMsg = $this->msg( 'signupend' );
1126 $signupendHttpsMsg = $this->msg( 'signupend-https' );
1127 if ( !$signupendMsg->isDisabled() ) {
1128 $usingHTTPS = $this->getRequest()->getProtocol() === 'https';
1129 $signupendText = ( $usingHTTPS && !$signupendHttpsMsg->isBlank() )
1130 ?
$signupendHttpsMsg ->parse() : $signupendMsg->parse();
1131 $fieldDefinitions['signupend'] = [
1134 'default' => Html
::rawElement( 'div', [ 'id' => 'signupend' ], $signupendText ),
1139 if ( !$this->isSignup() && $this->showExtraInformation() ) {
1140 $passwordReset = new PasswordReset( $this->getConfig(), AuthManager
::singleton() );
1141 if ( $passwordReset->isAllowed( $this->getUser() )->isGood() ) {
1142 $fieldDefinitions['passwordReset'] = [
1145 'cssclass' => 'mw-form-related-link-container',
1146 'default' => $this->getLinkRenderer()->makeLink(
1147 SpecialPage
::getTitleFor( 'PasswordReset' ),
1148 $this->msg( 'userlogin-resetpassword-link' )->text()
1154 // Don't show a "create account" link if the user can't.
1155 if ( $this->showCreateAccountLink() ) {
1156 // link to the other action
1157 $linkTitle = $this->getTitleFor( $this->isSignup() ?
'Userlogin' : 'CreateAccount' );
1158 $linkq = $this->getReturnToQueryStringFragment();
1159 // Pass any language selection on to the mode switch link
1160 if ( $this->mLanguage
) {
1161 $linkq .= '&uselang=' . urlencode( $this->mLanguage
);
1163 $loggedIn = $this->getUser()->isLoggedIn();
1165 $fieldDefinitions['createOrLogin'] = [
1168 'linkQuery' => $linkq,
1169 'default' => function ( $params ) use ( $loggedIn, $linkTitle ) {
1170 return Html
::rawElement( 'div',
1171 [ 'id' => 'mw-createaccount' . ( !$loggedIn ?
'-cta' : '' ),
1172 'class' => ( $loggedIn ?
'mw-form-related-link-container' : 'mw-ui-vform-field' ) ],
1173 ( $loggedIn ?
'' : $this->msg( 'userlogin-noaccount' )->escaped() )
1174 . Html
::element( 'a',
1176 'id' => 'mw-createaccount-join' . ( $loggedIn ?
'-loggedin' : '' ),
1177 'href' => $linkTitle->getLocalURL( $params['linkQuery'] ),
1178 'class' => ( $loggedIn ?
'' : 'mw-ui-button' ),
1182 $loggedIn ?
'userlogin-createanother' : 'userlogin-joinproject'
1192 $fieldDefinitions = $this->getBCFieldDefinitions( $fieldDefinitions, $template );
1193 $fieldDefinitions = array_filter( $fieldDefinitions );
1195 return $fieldDefinitions;
1199 * Adds fields provided via the deprecated UserLoginForm / UserCreateForm hooks
1200 * @param array $fieldDefinitions
1201 * @param FakeAuthTemplate $template
1204 protected function getBCFieldDefinitions( $fieldDefinitions, $template ) {
1205 if ( $template->get( 'usedomain', false ) ) {
1206 // TODO probably should be translated to the new domain notation in AuthManager
1207 $fieldDefinitions['domain'] = [
1209 'label-message' => 'yourdomainname',
1210 'options' => array_combine( $template->get( 'domainnames', [] ),
1211 $template->get( 'domainnames', [] ) ),
1212 'default' => $template->get( 'domain', '' ),
1213 'name' => 'wpDomain',
1214 // FIXME id => 'mw-user-domain-section' on the parent div
1218 // poor man's associative array_splice
1219 $extraInputPos = array_search( 'extrainput', array_keys( $fieldDefinitions ), true );
1220 $fieldDefinitions = array_slice( $fieldDefinitions, 0, $extraInputPos, true )
1221 +
$template->getExtraInputDefinitions()
1222 +
array_slice( $fieldDefinitions, $extraInputPos +
1, null, true );
1224 return $fieldDefinitions;
1228 * Check if a session cookie is present.
1230 * This will not pick up a cookie set during _this_ request, but is meant
1231 * to ensure that the client is returning the cookie which was set on a
1232 * previous pass through the system.
1236 protected function hasSessionCookie() {
1237 global $wgDisableCookieCheck, $wgInitialSessionId;
1239 return $wgDisableCookieCheck ||
(
1240 $wgInitialSessionId &&
1241 $this->getRequest()->getSession()->getId() === (string)$wgInitialSessionId
1246 * Returns a string that can be appended to the URL (without encoding) to preserve the
1247 * return target. Does not include leading '?'/'&'.
1250 protected function getReturnToQueryStringFragment() {
1252 if ( $this->mReturnTo
!== '' ) {
1253 $returnto = 'returnto=' . wfUrlencode( $this->mReturnTo
);
1254 if ( $this->mReturnToQuery
!== '' ) {
1255 $returnto .= '&returntoquery=' . wfUrlencode( $this->mReturnToQuery
);
1262 * Whether the login/create account form should display a link to the
1263 * other form (in addition to whatever the skin provides).
1266 private function showCreateAccountLink() {
1267 if ( $this->isSignup() ) {
1269 } elseif ( $this->getUser()->isAllowed( 'createaccount' ) ) {
1276 protected function getTokenName() {
1277 return $this->isSignup() ?
'wpCreateaccountToken' : 'wpLoginToken';
1281 * Produce a bar of links which allow the user to select another language
1282 * during login/registration but retain "returnto"
1286 protected function makeLanguageSelector() {
1287 $msg = $this->msg( 'loginlanguagelinks' )->inContentLanguage();
1288 if ( $msg->isBlank() ) {
1291 $langs = explode( "\n", $msg->text() );
1293 foreach ( $langs as $lang ) {
1294 $lang = trim( $lang, '* ' );
1295 $parts = explode( '|', $lang );
1296 if ( count( $parts ) >= 2 ) {
1297 $links[] = $this->makeLanguageSelectorLink( $parts[0], trim( $parts[1] ) );
1301 return count( $links ) > 0 ?
$this->msg( 'loginlanguagelabel' )->rawParams(
1302 $this->getLanguage()->pipeList( $links ) )->escaped() : '';
1306 * Create a language selector link for a particular language
1307 * Links back to this page preserving type and returnto
1309 * @param string $text Link text
1310 * @param string $lang Language code
1313 protected function makeLanguageSelectorLink( $text, $lang ) {
1314 if ( $this->getLanguage()->getCode() == $lang ) {
1315 // no link for currently used language
1316 return htmlspecialchars( $text );
1318 $query = [ 'uselang' => $lang ];
1319 if ( $this->mReturnTo
!== '' ) {
1320 $query['returnto'] = $this->mReturnTo
;
1321 $query['returntoquery'] = $this->mReturnToQuery
;
1325 $targetLanguage = Language
::factory( $lang );
1326 $attr['lang'] = $attr['hreflang'] = $targetLanguage->getHtmlCode();
1328 return $this->getLinkRenderer()->makeKnownLink(
1329 $this->getPageTitle(),
1336 protected function getGroupName() {
1341 * @param array &$formDescriptor
1342 * @param array $requests
1344 protected function postProcessFormDescriptor( &$formDescriptor, $requests ) {
1345 // Pre-fill username (if not creating an account, T46775).
1347 isset( $formDescriptor['username'] ) &&
1348 !isset( $formDescriptor['username']['default'] ) &&
1351 $user = $this->getUser();
1352 if ( $user->isLoggedIn() ) {
1353 $formDescriptor['username']['default'] = $user->getName();
1355 $formDescriptor['username']['default'] =
1356 $this->getRequest()->getSession()->suggestLoginUsername();
1360 // don't show a submit button if there is nothing to submit (i.e. the only form content
1361 // is other submit buttons, for redirect flows)
1362 if ( !$this->needsSubmitButton( $requests ) ) {
1363 unset( $formDescriptor['createaccount'], $formDescriptor['loginattempt'] );
1366 if ( !$this->isSignup() ) {
1367 // FIXME HACK don't focus on non-empty field
1368 // maybe there should be an autofocus-if similar to hide-if?
1370 isset( $formDescriptor['username'] )
1371 && empty( $formDescriptor['username']['default'] )
1372 && !$this->getRequest()->getCheck( 'wpName' )
1374 $formDescriptor['username']['autofocus'] = true;
1375 } elseif ( isset( $formDescriptor['password'] ) ) {
1376 $formDescriptor['password']['autofocus'] = true;
1380 $this->addTabIndex( $formDescriptor );
1385 * B/C class to try handling login/signup template modifications even though login/signup does not
1386 * actually happen through a template anymore. Just collects extra field definitions and allows
1387 * some other class to do decide what to do with threm..
1388 * TODO find the right place for adding extra fields and kill this
1390 class FakeAuthTemplate
extends BaseTemplate
{
1391 public function execute() {
1392 throw new LogicException( 'not used' );
1396 * Extensions (AntiSpoof and TitleBlacklist) call this in response to
1397 * UserCreateForm hook to add checkboxes to the create account form.
1398 * @param string $name
1399 * @param string $value
1400 * @param string $type
1401 * @param string $msg
1402 * @param string|bool $helptext
1404 public function addInputItem( $name, $value, $type, $msg, $helptext = false ) {
1405 // use the same indexes as UserCreateForm just in case someone adds an item manually
1406 $this->data
['extrainput'][] = [
1411 'helptext' => $helptext,
1416 * Turns addInputItem-style field definitions into HTMLForm field definitions.
1419 public function getExtraInputDefinitions() {
1422 foreach ( $this->get( 'extrainput', [] ) as $field ) {
1424 'type' => $field['type'] === 'checkbox' ?
'check' : $field['type'],
1425 'name' => $field['name'],
1426 'value' => $field['value'],
1427 'id' => $field['name'],
1429 if ( $field['msg'] ) {
1430 $definition['label-message'] = $this->getMsg( $field['msg'] );
1432 if ( $field['helptext'] ) {
1433 $definition['help'] = $this->msgWiki( $field['helptext'] );
1436 // the array key doesn't matter much when name is defined explicitly but
1437 // let's try and follow HTMLForm conventions
1438 $name = preg_replace( '/^wp(?=[A-Z])/', '', $field['name'] );
1439 $definitions[$name] = $definition;
1442 if ( $this->haveData( 'extrafields' ) ) {
1443 $definitions['extrafields'] = [
1446 'default' => $this->get( 'extrafields' ),
1450 return $definitions;
1455 * LoginForm as a special page has been replaced by SpecialUserLogin and SpecialCreateAccount,
1456 * but some extensions called its public methods directly, so the class is retained as a
1457 * B/C wrapper. Anything that used it before should use AuthManager instead.
1459 class LoginForm
extends SpecialPage
{
1463 const WRONG_PLUGIN_PASS
= 3;
1464 const NOT_EXISTS
= 4;
1465 const WRONG_PASS
= 5;
1466 const EMPTY_PASS
= 6;
1467 const RESET_PASS
= 7;
1469 const CREATE_BLOCKED
= 9;
1470 const THROTTLED
= 10;
1471 const USER_BLOCKED
= 11;
1472 const NEED_TOKEN
= 12;
1473 const WRONG_TOKEN
= 13;
1474 const USER_MIGRATED
= 14;
1476 public static $statusCodes = [
1477 self
::SUCCESS
=> 'success',
1478 self
::NO_NAME
=> 'no_name',
1479 self
::ILLEGAL
=> 'illegal',
1480 self
::WRONG_PLUGIN_PASS
=> 'wrong_plugin_pass',
1481 self
::NOT_EXISTS
=> 'not_exists',
1482 self
::WRONG_PASS
=> 'wrong_pass',
1483 self
::EMPTY_PASS
=> 'empty_pass',
1484 self
::RESET_PASS
=> 'reset_pass',
1485 self
::ABORTED
=> 'aborted',
1486 self
::CREATE_BLOCKED
=> 'create_blocked',
1487 self
::THROTTLED
=> 'throttled',
1488 self
::USER_BLOCKED
=> 'user_blocked',
1489 self
::NEED_TOKEN
=> 'need_token',
1490 self
::WRONG_TOKEN
=> 'wrong_token',
1491 self
::USER_MIGRATED
=> 'user_migrated',
1495 * @param WebRequest|null $request
1497 public function __construct( $request = null ) {
1498 wfDeprecated( 'LoginForm', '1.27' );
1499 parent
::__construct();
1503 * @deprecated since 1.27 - call LoginHelper::getValidErrorMessages instead.
1506 public static function getValidErrorMessages() {
1507 return LoginHelper
::getValidErrorMessages();
1511 * @deprecated since 1.27 - don't use LoginForm, use AuthManager instead
1512 * @param string $username
1513 * @return array|false
1515 public static function incrementLoginThrottle( $username ) {
1516 wfDeprecated( __METHOD__
, "1.27" );
1518 $username = User
::getCanonicalName( $username, 'usable' ) ?
: $username;
1519 $throttler = new Throttler();
1520 return $throttler->increase( $username, $wgRequest->getIP(), __METHOD__
);
1524 * @deprecated since 1.27 - don't use LoginForm, use AuthManager instead
1525 * @param string $username
1528 public static function incLoginThrottle( $username ) {
1529 wfDeprecated( __METHOD__
, "1.27" );
1530 $res = self
::incrementLoginThrottle( $username );
1531 return is_array( $res ) ?
true : 0;
1535 * @deprecated since 1.27 - don't use LoginForm, use AuthManager instead
1536 * @param string $username
1539 public static function clearLoginThrottle( $username ) {
1540 wfDeprecated( __METHOD__
, "1.27" );
1542 $username = User
::getCanonicalName( $username, 'usable' ) ?
: $username;
1543 $throttler = new Throttler();
1544 return $throttler->clear( $username, $wgRequest->getIP() );
1548 * @deprecated since 1.27 - don't use LoginForm, use AuthManager instead
1550 public static function getLoginToken() {
1551 wfDeprecated( __METHOD__
, '1.27' );
1553 return $wgRequest->getSession()->getToken( '', 'login' )->toString();
1557 * @deprecated since 1.27 - don't use LoginForm, use AuthManager instead
1559 public static function setLoginToken() {
1560 wfDeprecated( __METHOD__
, '1.27' );
1564 * @deprecated since 1.27 - don't use LoginForm, use AuthManager instead
1566 public static function clearLoginToken() {
1567 wfDeprecated( __METHOD__
, '1.27' );
1569 $wgRequest->getSession()->resetToken( 'login' );
1573 * @deprecated since 1.27 - don't use LoginForm, use AuthManager instead
1576 public static function getCreateaccountToken() {
1577 wfDeprecated( __METHOD__
, '1.27' );
1579 return $wgRequest->getSession()->getToken( '', 'createaccount' )->toString();
1583 * @deprecated since 1.27 - don't use LoginForm, use AuthManager instead
1585 public static function setCreateaccountToken() {
1586 wfDeprecated( __METHOD__
, '1.27' );
1590 * @deprecated since 1.27 - don't use LoginForm, use AuthManager instead
1592 public static function clearCreateaccountToken() {
1593 wfDeprecated( __METHOD__
, '1.27' );
1595 $wgRequest->getSession()->resetToken( 'createaccount' );