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\Logger\LoggerFactory
;
28 use MediaWiki\MediaWikiServices
;
29 use MediaWiki\Session\SessionManager
;
30 use Wikimedia\ScopedCallback
;
33 * Holds shared logic for login and account creation pages.
35 * @ingroup SpecialPage
37 abstract class LoginSignupSpecialPage
extends AuthManagerSpecialPage
{
42 protected $mReturnToQuery;
44 protected $mStickHTTPS;
46 protected $mEntryError = '';
47 protected $mEntryErrorType = 'error';
49 protected $mLoaded = false;
50 protected $mLoadedRequest = false;
51 protected $mSecureLoginUrl;
54 protected $securityLevel;
56 /** @var bool True if the user if creating an account for someone else. Flag used for internal
57 * communication, only set at the very end. */
58 protected $proxyAccountCreation;
59 /** @var User FIXME another flag for passing data. */
60 protected $targetUser;
65 abstract protected function isSignup();
68 * @param bool $direct True if the action was successful just now; false if that happened
69 * pre-redirection (so this handler was called already)
70 * @param StatusValue|null $extraMessages
73 abstract protected function successfulAction( $direct = false, $extraMessages = null );
76 * Logs to the authmanager-stats channel.
77 * @param bool $success
78 * @param string|null $status Error message key
80 abstract protected function logAuthResult( $success, $status = null );
82 public function __construct( $name ) {
83 global $wgUseMediaWikiUIEverywhere;
84 parent
::__construct( $name );
86 // Override UseMediaWikiEverywhere to true, to force login and create form to use mw ui
87 $wgUseMediaWikiUIEverywhere = true;
90 protected function setRequest( array $data, $wasPosted = null ) {
91 parent
::setRequest( $data, $wasPosted );
92 $this->mLoadedRequest
= false;
96 * Load basic request parameters for this Special page.
97 * @param string $subPage
99 private function loadRequestParameters( $subPage ) {
100 if ( $this->mLoadedRequest
) {
103 $this->mLoadedRequest
= true;
104 $request = $this->getRequest();
106 $this->mPosted
= $request->wasPosted();
107 $this->mIsReturn
= $subPage === 'return';
108 $this->mAction
= $request->getVal( 'action' );
109 $this->mFromHTTP
= $request->getBool( 'fromhttp', false )
110 ||
$request->getBool( 'wpFromhttp', false );
111 $this->mStickHTTPS
= ( !$this->mFromHTTP
&& $request->getProtocol() === 'https' )
112 ||
$request->getBool( 'wpForceHttps', false );
113 $this->mLanguage
= $request->getText( 'uselang' );
114 $this->mReturnTo
= $request->getVal( 'returnto', '' );
115 $this->mReturnToQuery
= $request->getVal( 'returntoquery', '' );
119 * Load data from request.
121 * @param string $subPage Subpage of Special:Userlogin
123 protected function load( $subPage ) {
124 global $wgSecureLogin;
126 $this->loadRequestParameters( $subPage );
127 if ( $this->mLoaded
) {
130 $this->mLoaded
= true;
131 $request = $this->getRequest();
133 $securityLevel = $this->getRequest()->getText( 'force' );
135 $securityLevel && AuthManager
::singleton()->securitySensitiveOperationStatus(
136 $securityLevel ) === AuthManager
::SEC_REAUTH
138 $this->securityLevel
= $securityLevel;
141 $this->loadAuth( $subPage );
143 $this->mToken
= $request->getVal( $this->getTokenName() );
145 // Show an error or warning passed on from a previous page
146 $entryError = $this->msg( $request->getVal( 'error', '' ) );
147 $entryWarning = $this->msg( $request->getVal( 'warning', '' ) );
148 // bc: provide login link as a parameter for messages where the translation
150 $loginreqlink = $this->getLinkRenderer()->makeKnownLink(
151 $this->getPageTitle(),
152 $this->msg( 'loginreqlink' )->text(),
155 'returnto' => $this->mReturnTo
,
156 'returntoquery' => $this->mReturnToQuery
,
157 'uselang' => $this->mLanguage ?
: null,
158 'fromhttp' => $wgSecureLogin && $this->mFromHTTP ?
'1' : null,
162 // Only show valid error or warning messages.
163 if ( $entryError->exists()
164 && in_array( $entryError->getKey(), LoginHelper
::getValidErrorMessages(), true )
166 $this->mEntryErrorType
= 'error';
167 $this->mEntryError
= $entryError->rawParams( $loginreqlink )->parse();
169 } elseif ( $entryWarning->exists()
170 && in_array( $entryWarning->getKey(), LoginHelper
::getValidErrorMessages(), true )
172 $this->mEntryErrorType
= 'warning';
173 $this->mEntryError
= $entryWarning->rawParams( $loginreqlink )->parse();
176 # 1. When switching accounts, it sucks to get automatically logged out
177 # 2. Do not return to PasswordReset after a successful password change
178 # but goto Wiki start page (Main_Page) instead ( T35997 )
179 $returnToTitle = Title
::newFromText( $this->mReturnTo
);
180 if ( is_object( $returnToTitle )
181 && ( $returnToTitle->isSpecial( 'Userlogout' )
182 ||
$returnToTitle->isSpecial( 'PasswordReset' ) )
184 $this->mReturnTo
= '';
185 $this->mReturnToQuery
= '';
189 protected function getPreservedParams( $withToken = false ) {
190 global $wgSecureLogin;
192 $params = parent
::getPreservedParams( $withToken );
194 'returnto' => $this->mReturnTo ?
: null,
195 'returntoquery' => $this->mReturnToQuery ?
: null,
197 if ( $wgSecureLogin && !$this->isSignup() ) {
198 $params['fromhttp'] = $this->mFromHTTP ?
'1' : null;
203 protected function beforeExecute( $subPage ) {
204 // finish initializing the class before processing the request - T135924
205 $this->loadRequestParameters( $subPage );
206 return parent
::beforeExecute( $subPage );
210 * @param string|null $subPage
212 public function execute( $subPage ) {
213 if ( $this->mPosted
) {
214 $time = microtime( true );
215 $profilingScope = new ScopedCallback( function () use ( $time ) {
216 $time = microtime( true ) - $time;
217 $statsd = MediaWikiServices
::getInstance()->getStatsdDataFactory();
218 $statsd->timing( "timing.login.ui.{$this->authAction}", $time * 1000 );
222 $authManager = AuthManager
::singleton();
223 $session = SessionManager
::getGlobalSession();
225 // Session data is used for various things in the authentication process, so we must make
226 // sure a session cookie or some equivalent mechanism is set.
229 $this->load( $subPage );
231 $this->checkPermissions();
233 // Make sure the system configuration allows log in / sign up
234 if ( !$this->isSignup() && !$authManager->canAuthenticateNow() ) {
235 if ( !$session->canSetUser() ) {
236 throw new ErrorPageError( 'cannotloginnow-title', 'cannotloginnow-text', [
237 $session->getProvider()->describe( RequestContext
::getMain()->getLanguage() )
240 throw new ErrorPageError( 'cannotlogin-title', 'cannotlogin-text' );
241 } elseif ( $this->isSignup() && !$authManager->canCreateAccounts() ) {
242 throw new ErrorPageError( 'cannotcreateaccount-title', 'cannotcreateaccount-text' );
246 * In the case where the user is already logged in, and was redirected to
247 * the login form from a page that requires login, do not show the login
248 * page. The use case scenario for this is when a user opens a large number
249 * of tabs, is redirected to the login page on all of them, and then logs
250 * in on one, expecting all the others to work properly.
252 * However, do show the form if it was visited intentionally (no 'returnto'
253 * is present). People who often switch between several accounts have grown
254 * accustomed to this behavior.
256 * Also make an exception when force=<level> is set in the URL, which means the user must
257 * reauthenticate for security reasons.
259 if ( !$this->isSignup() && !$this->mPosted
&& !$this->securityLevel
&&
260 ( $this->mReturnTo
!== '' ||
$this->mReturnToQuery
!== '' ) &&
261 $this->getUser()->isLoggedIn()
263 $this->successfulAction();
267 // If logging in and not on HTTPS, either redirect to it or offer a link.
268 global $wgSecureLogin;
269 if ( $this->getRequest()->getProtocol() !== 'https' ) {
270 $title = $this->getFullTitle();
271 $query = $this->getPreservedParams( false ) +
[
273 ( $this->mEntryErrorType
=== 'error' ?
'error'
274 : 'warning' ) => $this->mEntryError
,
275 ] +
$this->getRequest()->getQueryValues();
276 $url = $title->getFullURL( $query, false, PROTO_HTTPS
);
277 if ( $wgSecureLogin && !$this->mFromHTTP
&&
278 wfCanIPUseHTTPS( $this->getRequest()->getIP() )
280 // Avoid infinite redirect
281 $url = wfAppendQuery( $url, 'fromhttp=1' );
282 $this->getOutput()->redirect( $url );
283 // Since we only do this redir to change proto, always vary
284 $this->getOutput()->addVaryHeader( 'X-Forwarded-Proto' );
288 // A wiki without HTTPS login support should set $wgServer to
289 // http://somehost, in which case the secure URL generated
290 // above won't actually start with https://
291 if ( substr( $url, 0, 8 ) === 'https://' ) {
292 $this->mSecureLoginUrl
= $url;
297 if ( !$this->isActionAllowed( $this->authAction
) ) {
298 // FIXME how do we explain this to the user? can we handle session loss better?
299 // messages used: authpage-cannot-login, authpage-cannot-login-continue,
300 // authpage-cannot-create, authpage-cannot-create-continue
301 $this->mainLoginForm( [], 'authpage-cannot-' . $this->authAction
);
305 if ( $this->canBypassForm( $button_name ) ) {
306 $this->setRequest( [], true );
307 $this->getRequest()->setVal( $this->getTokenName(), $this->getToken() );
308 if ( $button_name ) {
309 $this->getRequest()->setVal( $button_name, true );
313 $status = $this->trySubmit();
315 if ( !$status ||
!$status->isGood() ) {
316 $this->mainLoginForm( $this->authRequests
, $status ?
$status->getMessage() : '', 'error' );
320 /** @var AuthenticationResponse $response */
321 $response = $status->getValue();
323 $returnToUrl = $this->getPageTitle( 'return' )
324 ->getFullURL( $this->getPreservedParams( true ), false, PROTO_HTTPS
);
325 switch ( $response->status
) {
326 case AuthenticationResponse
::PASS
:
327 $this->logAuthResult( true );
328 $this->proxyAccountCreation
= $this->isSignup() && !$this->getUser()->isAnon();
329 $this->targetUser
= User
::newFromName( $response->username
);
332 !$this->proxyAccountCreation
333 && $response->loginRequest
334 && $authManager->canAuthenticateNow()
336 // successful registration; log the user in instantly
337 $response2 = $authManager->beginAuthentication( [ $response->loginRequest
],
339 if ( $response2->status
!== AuthenticationResponse
::PASS
) {
340 LoggerFactory
::getInstance( 'login' )
341 ->error( 'Could not log in after account creation' );
342 $this->successfulAction( true, Status
::newFatal( 'createacct-loginerror' ) );
347 if ( !$this->proxyAccountCreation
) {
348 // Ensure that the context user is the same as the session user.
349 $this->setSessionUserForCurrentRequest();
352 $this->successfulAction( true );
354 case AuthenticationResponse
::FAIL
:
356 case AuthenticationResponse
::RESTART
:
357 unset( $this->authForm
);
358 if ( $response->status
=== AuthenticationResponse
::FAIL
) {
359 $action = $this->getDefaultAction( $subPage );
360 $messageType = 'error';
362 $action = $this->getContinueAction( $this->authAction
);
363 $messageType = 'warning';
365 $this->logAuthResult( false, $response->message ?
$response->message
->getKey() : '-' );
366 $this->loadAuth( $subPage, $action, true );
367 $this->mainLoginForm( $this->authRequests
, $response->message
, $messageType );
369 case AuthenticationResponse
::REDIRECT
:
370 unset( $this->authForm
);
371 $this->getOutput()->redirect( $response->redirectTarget
);
373 case AuthenticationResponse
::UI
:
374 unset( $this->authForm
);
375 $this->authAction
= $this->isSignup() ? AuthManager
::ACTION_CREATE_CONTINUE
376 : AuthManager
::ACTION_LOGIN_CONTINUE
;
377 $this->authRequests
= $response->neededRequests
;
378 $this->mainLoginForm( $response->neededRequests
, $response->message
, $response->messageType
);
381 throw new LogicException( 'invalid AuthenticationResponse' );
386 * Determine if the login form can be bypassed. This will be the case when no more than one
387 * button is present and no other user input fields that are not marked as 'skippable' are
388 * present. If the login form were not bypassed, the user would be presented with a
389 * superfluous page on which they must press the single button to proceed with login.
390 * Not only does this cause an additional mouse click and page load, it confuses users,
391 * especially since there are a help link and forgotten password link that are
392 * provided on the login page that do not apply to this situation.
394 * @param string|null &$button_name if the form has a single button, returns
395 * the name of the button; otherwise, returns null
398 private function canBypassForm( &$button_name ) {
400 if ( $this->isContinued() ) {
403 $fields = AuthenticationRequest
::mergeFieldInfo( $this->authRequests
);
404 foreach ( $fields as $fieldname => $field ) {
405 if ( !isset( $field['type'] ) ) {
408 if ( !empty( $field['skippable'] ) ) {
411 if ( $field['type'] === 'button' ) {
412 if ( $button_name !== null ) {
416 $button_name = $fieldname;
418 } elseif ( $field['type'] !== 'null' ) {
426 * Show the success page.
428 * @param string $type Condition of return to; see `executeReturnTo`
429 * @param string|Message $title Page's title
430 * @param string $msgname
431 * @param string $injected_html
432 * @param StatusValue|null $extraMessages
434 protected function showSuccessPage(
435 $type, $title, $msgname, $injected_html, $extraMessages
437 $out = $this->getOutput();
438 $out->setPageTitle( $title );
440 $out->addWikiMsg( $msgname, wfEscapeWikiText( $this->getUser()->getName() ) );
442 if ( $extraMessages ) {
443 $extraMessages = Status
::wrap( $extraMessages );
444 $out->addWikiTextAsInterface( $extraMessages->getWikiText() );
447 $out->addHTML( $injected_html );
449 $helper = new LoginHelper( $this->getContext() );
450 $helper->showReturnToPage( $type, $this->mReturnTo
, $this->mReturnToQuery
, $this->mStickHTTPS
);
454 * Add a "return to" link or redirect to it.
455 * Extensions can use this to reuse the "return to" logic after
456 * inject steps (such as redirection) into the login process.
458 * @param string $type One of the following:
459 * - error: display a return to link ignoring $wgRedirectOnLogin
460 * - signup: display a return to link using $wgRedirectOnLogin if needed
461 * - success: display a return to link using $wgRedirectOnLogin if needed
462 * - successredirect: send an HTTP redirect using $wgRedirectOnLogin if needed
463 * @param string $returnTo
464 * @param array|string $returnToQuery
465 * @param bool $stickHTTPS Keep redirect link on HTTPS
468 public function showReturnToPage(
469 $type, $returnTo = '', $returnToQuery = '', $stickHTTPS = false
471 $helper = new LoginHelper( $this->getContext() );
472 $helper->showReturnToPage( $type, $returnTo, $returnToQuery, $stickHTTPS );
476 * Replace some globals to make sure the fact that the user has just been logged in is
477 * reflected in the current request.
479 protected function setSessionUserForCurrentRequest() {
480 global $wgUser, $wgLang;
482 $context = RequestContext
::getMain();
483 $localContext = $this->getContext();
484 if ( $context !== $localContext ) {
485 // remove AuthManagerSpecialPage context hack
486 $this->setContext( $context );
489 $user = $context->getRequest()->getSession()->getUser();
492 $context->setUser( $user );
494 $code = $this->getRequest()->getVal( 'uselang', $user->getOption( 'language' ) );
495 $userLang = Language
::factory( $code );
497 $context->setLanguage( $userLang );
501 * @param AuthenticationRequest[] $requests A list of AuthorizationRequest objects,
502 * used to generate the form fields. An empty array means a fatal error
503 * (authentication cannot continue).
504 * @param string|Message $msg
505 * @param string $msgtype
506 * @throws ErrorPageError
509 * @throws MWException
510 * @throws PermissionsError
511 * @throws ReadOnlyError
514 protected function mainLoginForm( array $requests, $msg = '', $msgtype = 'error' ) {
515 $user = $this->getUser();
516 $out = $this->getOutput();
518 // FIXME how to handle empty $requests - restart, or no form, just an error message?
519 // no form would be better for no session type errors, restart is better when can* fails.
521 $this->authAction
= $this->getDefaultAction( $this->subPage
);
522 $this->authForm
= null;
523 $requests = AuthManager
::singleton()->getAuthenticationRequests( $this->authAction
, $user );
526 // Generic styles and scripts for both login and signup form
527 $out->addModuleStyles( [
529 'mediawiki.ui.button',
530 'mediawiki.ui.checkbox',
531 'mediawiki.ui.input',
532 'mediawiki.special.userlogin.common.styles'
534 if ( $this->isSignup() ) {
535 // XXX hack pending RL or JS parse() support for complex content messages T27349
536 $out->addJsConfigVars( 'wgCreateacctImgcaptchaHelp',
537 $this->msg( 'createacct-imgcaptcha-help' )->parse() );
539 // Additional styles and scripts for signup form
541 'mediawiki.special.userlogin.signup.js'
543 $out->addModuleStyles( [
544 'mediawiki.special.userlogin.signup.styles'
547 // Additional styles for login form
548 $out->addModuleStyles( [
549 'mediawiki.special.userlogin.login.styles'
552 $out->disallowUserJs(); // just in case...
554 $form = $this->getAuthForm( $requests, $this->authAction
, $msg, $msgtype );
555 $form->prepareForm();
557 $submitStatus = Status
::newGood();
558 if ( $msg && $msgtype === 'warning' ) {
559 $submitStatus->warning( $msg );
560 } elseif ( $msg && $msgtype === 'error' ) {
561 $submitStatus->fatal( $msg );
564 // warning header for non-standard workflows (e.g. security reauthentication)
566 !$this->isSignup() &&
567 $this->getUser()->isLoggedIn() &&
568 $this->authAction
!== AuthManager
::ACTION_LOGIN_CONTINUE
570 $reauthMessage = $this->securityLevel ?
'userlogin-reauth' : 'userlogin-loggedin';
571 $submitStatus->warning( $reauthMessage, $this->getUser()->getName() );
574 $formHtml = $form->getHTML( $submitStatus );
576 $out->addHTML( $this->getPageHtml( $formHtml ) );
580 * Add page elements which are outside the form.
581 * FIXME this should probably be a template, but use a sane language (handlebars?)
582 * @param string $formHtml
585 protected function getPageHtml( $formHtml ) {
586 global $wgLoginLanguageSelector;
588 $loginPrompt = $this->isSignup() ?
'' : Html
::rawElement( 'div',
589 [ 'id' => 'userloginprompt' ], $this->msg( 'loginprompt' )->parseAsBlock() );
590 $languageLinks = $wgLoginLanguageSelector ?
$this->makeLanguageSelector() : '';
591 $signupStartMsg = $this->msg( 'signupstart' );
592 $signupStart = ( $this->isSignup() && !$signupStartMsg->isDisabled() )
593 ? Html
::rawElement( 'div', [ 'id' => 'signupstart' ], $signupStartMsg->parseAsBlock() ) : '';
594 if ( $languageLinks ) {
595 $languageLinks = Html
::rawElement( 'div', [ 'id' => 'languagelinks' ],
596 Html
::rawElement( 'p', [], $languageLinks )
600 $benefitsContainer = '';
601 if ( $this->isSignup() && $this->showExtraInformation() ) {
603 // createacct-benefit-icon1 createacct-benefit-head1 createacct-benefit-body1
604 // createacct-benefit-icon2 createacct-benefit-head2 createacct-benefit-body2
605 // createacct-benefit-icon3 createacct-benefit-head3 createacct-benefit-body3
608 for ( $benefitIdx = 1; $benefitIdx <= $benefitCount; $benefitIdx++
) {
609 $headUnescaped = $this->msg( "createacct-benefit-head$benefitIdx" )->text();
610 $iconClass = $this->msg( "createacct-benefit-icon$benefitIdx" )->text();
611 $benefitList .= Html
::rawElement( 'div', [ 'class' => "mw-number-text $iconClass" ],
612 Html
::rawElement( 'h3', [],
613 $this->msg( "createacct-benefit-head$benefitIdx" )->escaped()
615 . Html
::rawElement( 'p', [],
616 $this->msg( "createacct-benefit-body$benefitIdx" )->params( $headUnescaped )->escaped()
620 $benefitsContainer = Html
::rawElement( 'div', [ 'class' => 'mw-createacct-benefits-container' ],
621 Html
::rawElement( 'h2', [], $this->msg( 'createacct-benefit-heading' )->escaped() )
622 . Html
::rawElement( 'div', [ 'class' => 'mw-createacct-benefits-list' ],
628 $html = Html
::rawElement( 'div', [ 'class' => 'mw-ui-container' ],
632 . Html
::rawElement( 'div', [ 'id' => 'userloginForm' ],
642 * Generates a form from the given request.
643 * @param AuthenticationRequest[] $requests
644 * @param string $action AuthManager action name
645 * @param string|Message $msg
646 * @param string $msgType
649 protected function getAuthForm( array $requests, $action, $msg = '', $msgType = 'error' ) {
650 global $wgSecureLogin;
651 // FIXME merge this with parent
653 if ( isset( $this->authForm
) ) {
654 return $this->authForm
;
657 $usingHTTPS = $this->getRequest()->getProtocol() === 'https';
659 // get basic form description from the auth logic
660 $fieldInfo = AuthenticationRequest
::mergeFieldInfo( $requests );
661 // this will call onAuthChangeFormFields()
662 $formDescriptor = static::fieldInfoToFormDescriptor( $requests, $fieldInfo, $this->authAction
);
663 $this->postProcessFormDescriptor( $formDescriptor, $requests );
665 $context = $this->getContext();
666 if ( $context->getRequest() !== $this->getRequest() ) {
667 // We have overridden the request, need to make sure the form uses that too.
668 $context = new DerivativeContext( $this->getContext() );
669 $context->setRequest( $this->getRequest() );
671 $form = HTMLForm
::factory( 'vform', $formDescriptor, $context );
673 $form->addHiddenField( 'authAction', $this->authAction
);
674 if ( $this->mLanguage
) {
675 $form->addHiddenField( 'uselang', $this->mLanguage
);
677 $form->addHiddenField( 'force', $this->securityLevel
);
678 $form->addHiddenField( $this->getTokenName(), $this->getToken()->toString() );
679 if ( $wgSecureLogin ) {
680 // If using HTTPS coming from HTTP, then the 'fromhttp' parameter must be preserved
681 if ( !$this->isSignup() ) {
682 $form->addHiddenField( 'wpForceHttps', (int)$this->mStickHTTPS
);
683 $form->addHiddenField( 'wpFromhttp', $usingHTTPS );
687 // set properties of the form itself
688 $form->setAction( $this->getPageTitle()->getLocalURL( $this->getReturnToQueryStringFragment() ) );
689 $form->setName( 'userlogin' . ( $this->isSignup() ?
'2' : '' ) );
690 if ( $this->isSignup() ) {
691 $form->setId( 'userlogin2' );
694 $form->suppressDefaultSubmit();
696 $this->authForm
= $form;
701 public function onAuthChangeFormFields(
702 array $requests, array $fieldInfo, array &$formDescriptor, $action
704 $coreFieldDescriptors = $this->getFieldDefinitions();
706 // keep the ordering from getCoreFieldDescriptors() where there is no explicit weight
707 foreach ( $coreFieldDescriptors as $fieldName => $coreField ) {
708 $requestField = $formDescriptor[$fieldName] ??
[];
710 // remove everything that is not in the fieldinfo, is not marked as a supplemental field
711 // to something in the fieldinfo, and is not an info field or a submit button
713 !isset( $fieldInfo[$fieldName] )
715 !isset( $coreField['baseField'] )
716 ||
!isset( $fieldInfo[$coreField['baseField']] )
719 !isset( $coreField['type'] )
720 ||
!in_array( $coreField['type'], [ 'submit', 'info' ], true )
723 $coreFieldDescriptors[$fieldName] = null;
727 // core message labels should always take priority
729 isset( $coreField['label'] )
730 ||
isset( $coreField['label-message'] )
731 ||
isset( $coreField['label-raw'] )
733 unset( $requestField['label'], $requestField['label-message'], $coreField['label-raw'] );
736 $coreFieldDescriptors[$fieldName] +
= $requestField;
739 $formDescriptor = array_filter( $coreFieldDescriptors +
$formDescriptor );
744 * Show extra information such as password recovery information, link from login to signup,
745 * CTA etc? Such information should only be shown on the "landing page", ie. when the user
746 * is at the first step of the authentication process.
749 protected function showExtraInformation() {
750 return $this->authAction
!== $this->getContinueAction( $this->authAction
)
751 && !$this->securityLevel
;
755 * Create a HTMLForm descriptor for the core login fields.
758 protected function getFieldDefinitions() {
759 global $wgEmailConfirmToEdit;
761 $isLoggedIn = $this->getUser()->isLoggedIn();
762 $continuePart = $this->isContinued() ?
'continue-' : '';
763 $anotherPart = $isLoggedIn ?
'another-' : '';
764 $expiration = $this->getRequest()->getSession()->getProvider()->getRememberUserDuration();
765 $expirationDays = ceil( $expiration / ( 3600 * 24 ) );
766 $secureLoginLink = '';
767 if ( $this->mSecureLoginUrl
) {
768 $secureLoginLink = Html
::element( 'a', [
769 'href' => $this->mSecureLoginUrl
,
770 'class' => 'mw-ui-flush-right mw-secure',
771 ], $this->msg( 'userlogin-signwithsecure' )->text() );
773 $usernameHelpLink = '';
774 if ( !$this->msg( 'createacct-helpusername' )->isDisabled() ) {
775 $usernameHelpLink = Html
::rawElement( 'span', [
776 'class' => 'mw-ui-flush-right',
777 ], $this->msg( 'createacct-helpusername' )->parse() );
780 if ( $this->isSignup() ) {
781 $fieldDefinitions = [
783 // used by the mediawiki.special.userlogin.signup.js module for error display
784 // FIXME merge this with HTMLForm's normal status (error) area
787 'default' => Html
::element( 'div', [ 'id' => 'mw-createacct-status-area' ] ),
791 'label-raw' => $this->msg( 'userlogin-yourname' )->escaped() . $usernameHelpLink,
793 'placeholder-message' => $isLoggedIn ?
'createacct-another-username-ph'
794 : 'userlogin-yourname-ph',
797 // create account without providing password, a temporary one will be mailed
799 'label-message' => 'createaccountmail',
800 'name' => 'wpCreateaccountMail',
801 'id' => 'wpCreateaccountMail',
804 'id' => 'wpPassword2',
805 'placeholder-message' => 'createacct-yourpassword-ph',
806 'hide-if' => [ '===', 'wpCreateaccountMail', '1' ],
810 'baseField' => 'password',
811 'type' => 'password',
812 'label-message' => 'createacct-yourpasswordagain',
814 'cssclass' => 'loginPassword',
816 'validation-callback' => function ( $value, $alldata ) {
817 if ( empty( $alldata['mailpassword'] ) && !empty( $alldata['password'] ) ) {
819 return $this->msg( 'htmlform-required' );
820 } elseif ( $value !== $alldata['password'] ) {
821 return $this->msg( 'badretype' );
826 'hide-if' => [ '===', 'wpCreateaccountMail', '1' ],
827 'placeholder-message' => 'createacct-yourpasswordagain-ph',
831 'label-message' => $wgEmailConfirmToEdit ?
'createacct-emailrequired'
832 : 'createacct-emailoptional',
834 'cssclass' => 'loginText',
836 // FIXME will break non-standard providers
837 'required' => $wgEmailConfirmToEdit,
838 'validation-callback' => function ( $value, $alldata ) {
839 global $wgEmailConfirmToEdit;
841 // AuthManager will check most of these, but that will make the auth
842 // session fail and this won't, so nicer to do it this way
843 if ( !$value && $wgEmailConfirmToEdit ) {
844 // no point in allowing registration without email when email is
846 return $this->msg( 'noemailtitle' );
847 } elseif ( !$value && !empty( $alldata['mailpassword'] ) ) {
848 // cannot send password via email when there is no email address
849 return $this->msg( 'noemailcreate' );
850 } elseif ( $value && !Sanitizer
::validateEmail( $value ) ) {
851 return $this->msg( 'invalidemailaddress' );
855 'placeholder-message' => 'createacct-' . $anotherPart . 'email-ph',
859 'help-message' => $isLoggedIn ?
'createacct-another-realname-tip'
860 : 'prefs-help-realname',
861 'label-message' => 'createacct-realname',
862 'cssclass' => 'loginText',
864 'id' => 'wpRealName',
867 // comment for the user creation log
869 'label-message' => 'createacct-reason',
870 'cssclass' => 'loginText',
873 'placeholder-message' => 'createacct-reason-ph',
878 'default' => $this->msg( 'createacct-' . $anotherPart . $continuePart .
880 'name' => 'wpCreateaccount',
881 'id' => 'wpCreateaccount',
886 $fieldDefinitions = [
888 'label-raw' => $this->msg( 'userlogin-yourname' )->escaped() . $secureLoginLink,
890 'placeholder-message' => 'userlogin-yourname-ph',
893 'id' => 'wpPassword1',
894 'placeholder-message' => 'userlogin-yourpassword-ph',
898 // option for saving the user token to a cookie
900 'name' => 'wpRemember',
901 'label-message' => $this->msg( 'userlogin-remembermypassword' )
902 ->numParams( $expirationDays ),
903 'id' => 'wpRemember',
908 'default' => $this->msg( 'pt-login-' . $continuePart . 'button' )->text(),
909 'id' => 'wpLoginAttempt',
915 'cssclass' => 'mw-form-related-link-container mw-userlogin-help',
916 // 'id' => 'mw-userlogin-help', // FIXME HTMLInfoField ignores this
918 'default' => Html
::element( 'a', [
919 'href' => Skin
::makeInternalOrExternalUrl( $this->msg( 'helplogin-url' )
920 ->inContentLanguage()
922 ], $this->msg( 'userlogin-helplink2' )->text() ),
925 // button for ResetPasswordSecondaryAuthenticationProvider
933 $fieldDefinitions['username'] +
= [
936 'cssclass' => 'loginText',
938 // 'required' => true,
940 $fieldDefinitions['password'] +
= [
941 'type' => 'password',
942 // 'label-message' => 'userlogin-yourpassword', // would override the changepassword label
943 'name' => 'wpPassword',
944 'cssclass' => 'loginPassword',
946 // 'required' => true,
949 if ( $this->mEntryError
) {
950 $fieldDefinitions['entryError'] = [
952 'default' => Html
::rawElement( 'div', [ 'class' => $this->mEntryErrorType
. 'box', ],
953 $this->mEntryError
),
959 if ( !$this->showExtraInformation() ) {
960 unset( $fieldDefinitions['linkcontainer'], $fieldDefinitions['signupend'] );
962 if ( $this->isSignup() && $this->showExtraInformation() ) {
963 // blank signup footer for site customization
964 // uses signupend-https for HTTPS requests if it's not blank, signupend otherwise
965 $signupendMsg = $this->msg( 'signupend' );
966 $signupendHttpsMsg = $this->msg( 'signupend-https' );
967 if ( !$signupendMsg->isDisabled() ) {
968 $usingHTTPS = $this->getRequest()->getProtocol() === 'https';
969 $signupendText = ( $usingHTTPS && !$signupendHttpsMsg->isBlank() )
970 ?
$signupendHttpsMsg->parse() : $signupendMsg->parse();
971 $fieldDefinitions['signupend'] = [
974 'default' => Html
::rawElement( 'div', [ 'id' => 'signupend' ], $signupendText ),
979 if ( !$this->isSignup() && $this->showExtraInformation() ) {
980 $passwordReset = new PasswordReset( $this->getConfig(), AuthManager
::singleton() );
981 if ( $passwordReset->isAllowed( $this->getUser() )->isGood() ) {
982 $fieldDefinitions['passwordReset'] = [
985 'cssclass' => 'mw-form-related-link-container',
986 'default' => $this->getLinkRenderer()->makeLink(
987 SpecialPage
::getTitleFor( 'PasswordReset' ),
988 $this->msg( 'userlogin-resetpassword-link' )->text()
994 // Don't show a "create account" link if the user can't.
995 if ( $this->showCreateAccountLink() ) {
996 // link to the other action
997 $linkTitle = $this->getTitleFor( $this->isSignup() ?
'Userlogin' : 'CreateAccount' );
998 $linkq = $this->getReturnToQueryStringFragment();
999 // Pass any language selection on to the mode switch link
1000 if ( $this->mLanguage
) {
1001 $linkq .= '&uselang=' . urlencode( $this->mLanguage
);
1003 $loggedIn = $this->getUser()->isLoggedIn();
1005 $fieldDefinitions['createOrLogin'] = [
1008 'linkQuery' => $linkq,
1009 'default' => function ( $params ) use ( $loggedIn, $linkTitle ) {
1010 return Html
::rawElement( 'div',
1011 [ 'id' => 'mw-createaccount' . ( !$loggedIn ?
'-cta' : '' ),
1012 'class' => ( $loggedIn ?
'mw-form-related-link-container' : 'mw-ui-vform-field' ) ],
1013 ( $loggedIn ?
'' : $this->msg( 'userlogin-noaccount' )->escaped() )
1014 . Html
::element( 'a',
1016 'id' => 'mw-createaccount-join' . ( $loggedIn ?
'-loggedin' : '' ),
1017 'href' => $linkTitle->getLocalURL( $params['linkQuery'] ),
1018 'class' => ( $loggedIn ?
'' : 'mw-ui-button' ),
1022 $loggedIn ?
'userlogin-createanother' : 'userlogin-joinproject'
1032 return $fieldDefinitions;
1036 * Check if a session cookie is present.
1038 * This will not pick up a cookie set during _this_ request, but is meant
1039 * to ensure that the client is returning the cookie which was set on a
1040 * previous pass through the system.
1044 protected function hasSessionCookie() {
1045 global $wgDisableCookieCheck, $wgInitialSessionId;
1047 return $wgDisableCookieCheck ||
(
1048 $wgInitialSessionId &&
1049 $this->getRequest()->getSession()->getId() === (string)$wgInitialSessionId
1054 * Returns a string that can be appended to the URL (without encoding) to preserve the
1055 * return target. Does not include leading '?'/'&'.
1058 protected function getReturnToQueryStringFragment() {
1060 if ( $this->mReturnTo
!== '' ) {
1061 $returnto = 'returnto=' . wfUrlencode( $this->mReturnTo
);
1062 if ( $this->mReturnToQuery
!== '' ) {
1063 $returnto .= '&returntoquery=' . wfUrlencode( $this->mReturnToQuery
);
1070 * Whether the login/create account form should display a link to the
1071 * other form (in addition to whatever the skin provides).
1074 private function showCreateAccountLink() {
1075 if ( $this->isSignup() ) {
1077 } elseif ( $this->getUser()->isAllowed( 'createaccount' ) ) {
1084 protected function getTokenName() {
1085 return $this->isSignup() ?
'wpCreateaccountToken' : 'wpLoginToken';
1089 * Produce a bar of links which allow the user to select another language
1090 * during login/registration but retain "returnto"
1094 protected function makeLanguageSelector() {
1095 $msg = $this->msg( 'loginlanguagelinks' )->inContentLanguage();
1096 if ( $msg->isBlank() ) {
1099 $langs = explode( "\n", $msg->text() );
1101 foreach ( $langs as $lang ) {
1102 $lang = trim( $lang, '* ' );
1103 $parts = explode( '|', $lang );
1104 if ( count( $parts ) >= 2 ) {
1105 $links[] = $this->makeLanguageSelectorLink( $parts[0], trim( $parts[1] ) );
1109 return count( $links ) > 0 ?
$this->msg( 'loginlanguagelabel' )->rawParams(
1110 $this->getLanguage()->pipeList( $links ) )->escaped() : '';
1114 * Create a language selector link for a particular language
1115 * Links back to this page preserving type and returnto
1117 * @param string $text Link text
1118 * @param string $lang Language code
1121 protected function makeLanguageSelectorLink( $text, $lang ) {
1122 if ( $this->getLanguage()->getCode() == $lang ) {
1123 // no link for currently used language
1124 return htmlspecialchars( $text );
1126 $query = [ 'uselang' => $lang ];
1127 if ( $this->mReturnTo
!== '' ) {
1128 $query['returnto'] = $this->mReturnTo
;
1129 $query['returntoquery'] = $this->mReturnToQuery
;
1133 $targetLanguage = Language
::factory( $lang );
1134 $attr['lang'] = $attr['hreflang'] = $targetLanguage->getHtmlCode();
1136 return $this->getLinkRenderer()->makeKnownLink(
1137 $this->getPageTitle(),
1144 protected function getGroupName() {
1149 * @param array &$formDescriptor
1150 * @param array $requests
1152 protected function postProcessFormDescriptor( &$formDescriptor, $requests ) {
1153 // Pre-fill username (if not creating an account, T46775).
1155 isset( $formDescriptor['username'] ) &&
1156 !isset( $formDescriptor['username']['default'] ) &&
1159 $user = $this->getUser();
1160 if ( $user->isLoggedIn() ) {
1161 $formDescriptor['username']['default'] = $user->getName();
1163 $formDescriptor['username']['default'] =
1164 $this->getRequest()->getSession()->suggestLoginUsername();
1168 // don't show a submit button if there is nothing to submit (i.e. the only form content
1169 // is other submit buttons, for redirect flows)
1170 if ( !$this->needsSubmitButton( $requests ) ) {
1171 unset( $formDescriptor['createaccount'], $formDescriptor['loginattempt'] );
1174 if ( !$this->isSignup() ) {
1175 // FIXME HACK don't focus on non-empty field
1176 // maybe there should be an autofocus-if similar to hide-if?
1178 isset( $formDescriptor['username'] )
1179 && empty( $formDescriptor['username']['default'] )
1180 && !$this->getRequest()->getCheck( 'wpName' )
1182 $formDescriptor['username']['autofocus'] = true;
1183 } elseif ( isset( $formDescriptor['password'] ) ) {
1184 $formDescriptor['password']['autofocus'] = true;
1188 $this->addTabIndex( $formDescriptor );