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.
59 protected $proxyAccountCreation;
60 /** @var User FIXME another flag for passing data. */
61 protected $targetUser;
66 abstract protected function isSignup();
69 * @param bool $direct True if the action was successful just now; false if that happened
70 * pre-redirection (so this handler was called already)
71 * @param StatusValue|null $extraMessages
74 abstract protected function successfulAction( $direct = false, $extraMessages = null );
77 * Logs to the authmanager-stats channel.
78 * @param bool $success
79 * @param string|null $status Error message key
81 abstract protected function logAuthResult( $success, $status = null );
83 public function __construct( $name ) {
84 global $wgUseMediaWikiUIEverywhere;
85 parent
::__construct( $name );
87 // Override UseMediaWikiEverywhere to true, to force login and create form to use mw ui
88 $wgUseMediaWikiUIEverywhere = true;
91 protected function setRequest( array $data, $wasPosted = null ) {
92 parent
::setRequest( $data, $wasPosted );
93 $this->mLoadedRequest
= false;
97 * Load basic request parameters for this Special page.
98 * @param string $subPage
100 private function loadRequestParameters( $subPage ) {
101 if ( $this->mLoadedRequest
) {
104 $this->mLoadedRequest
= true;
105 $request = $this->getRequest();
107 $this->mPosted
= $request->wasPosted();
108 $this->mIsReturn
= $subPage === 'return';
109 $this->mAction
= $request->getVal( 'action' );
110 $this->mFromHTTP
= $request->getBool( 'fromhttp', false )
111 ||
$request->getBool( 'wpFromhttp', false );
112 $this->mStickHTTPS
= ( !$this->mFromHTTP
&& $request->getProtocol() === 'https' )
113 ||
$request->getBool( 'wpForceHttps', false );
114 $this->mLanguage
= $request->getText( 'uselang' );
115 $this->mReturnTo
= $request->getVal( 'returnto', '' );
116 $this->mReturnToQuery
= $request->getVal( 'returntoquery', '' );
120 * Load data from request.
122 * @param string $subPage Subpage of Special:Userlogin
124 protected function load( $subPage ) {
125 global $wgSecureLogin;
127 $this->loadRequestParameters( $subPage );
128 if ( $this->mLoaded
) {
131 $this->mLoaded
= true;
132 $request = $this->getRequest();
134 $securityLevel = $this->getRequest()->getText( 'force' );
136 $securityLevel && AuthManager
::singleton()->securitySensitiveOperationStatus(
137 $securityLevel ) === AuthManager
::SEC_REAUTH
139 $this->securityLevel
= $securityLevel;
142 $this->loadAuth( $subPage );
144 $this->mToken
= $request->getVal( $this->getTokenName() );
146 // Show an error or warning passed on from a previous page
147 $entryError = $this->msg( $request->getVal( 'error', '' ) );
148 $entryWarning = $this->msg( $request->getVal( 'warning', '' ) );
149 // bc: provide login link as a parameter for messages where the translation
151 $loginreqlink = $this->getLinkRenderer()->makeKnownLink(
152 $this->getPageTitle(),
153 $this->msg( 'loginreqlink' )->text(),
156 'returnto' => $this->mReturnTo
,
157 'returntoquery' => $this->mReturnToQuery
,
158 'uselang' => $this->mLanguage ?
: null,
159 'fromhttp' => $wgSecureLogin && $this->mFromHTTP ?
'1' : null,
163 // Only show valid error or warning messages.
164 if ( $entryError->exists()
165 && in_array( $entryError->getKey(), LoginHelper
::getValidErrorMessages(), true )
167 $this->mEntryErrorType
= 'error';
168 $this->mEntryError
= $entryError->rawParams( $loginreqlink )->parse();
170 } elseif ( $entryWarning->exists()
171 && in_array( $entryWarning->getKey(), LoginHelper
::getValidErrorMessages(), true )
173 $this->mEntryErrorType
= 'warning';
174 $this->mEntryError
= $entryWarning->rawParams( $loginreqlink )->parse();
177 # 1. When switching accounts, it sucks to get automatically logged out
178 # 2. Do not return to PasswordReset after a successful password change
179 # but goto Wiki start page (Main_Page) instead ( T35997 )
180 $returnToTitle = Title
::newFromText( $this->mReturnTo
);
181 if ( is_object( $returnToTitle )
182 && ( $returnToTitle->isSpecial( 'Userlogout' )
183 ||
$returnToTitle->isSpecial( 'PasswordReset' ) )
185 $this->mReturnTo
= '';
186 $this->mReturnToQuery
= '';
190 protected function getPreservedParams( $withToken = false ) {
191 global $wgSecureLogin;
193 $params = parent
::getPreservedParams( $withToken );
195 'returnto' => $this->mReturnTo ?
: null,
196 'returntoquery' => $this->mReturnToQuery ?
: null,
198 if ( $wgSecureLogin && !$this->isSignup() ) {
199 $params['fromhttp'] = $this->mFromHTTP ?
'1' : null;
204 protected function beforeExecute( $subPage ) {
205 // finish initializing the class before processing the request - T135924
206 $this->loadRequestParameters( $subPage );
207 return parent
::beforeExecute( $subPage );
211 * @param string|null $subPage
213 public function execute( $subPage ) {
214 if ( $this->mPosted
) {
215 $time = microtime( true );
216 $profilingScope = new ScopedCallback( function () use ( $time ) {
217 $time = microtime( true ) - $time;
218 $statsd = MediaWikiServices
::getInstance()->getStatsdDataFactory();
219 $statsd->timing( "timing.login.ui.{$this->authAction}", $time * 1000 );
223 $authManager = AuthManager
::singleton();
224 $session = SessionManager
::getGlobalSession();
226 // Session data is used for various things in the authentication process, so we must make
227 // sure a session cookie or some equivalent mechanism is set.
230 $this->load( $subPage );
232 $this->checkPermissions();
234 // Make sure the system configuration allows log in / sign up
235 if ( !$this->isSignup() && !$authManager->canAuthenticateNow() ) {
236 if ( !$session->canSetUser() ) {
237 throw new ErrorPageError( 'cannotloginnow-title', 'cannotloginnow-text', [
238 $session->getProvider()->describe( RequestContext
::getMain()->getLanguage() )
241 throw new ErrorPageError( 'cannotlogin-title', 'cannotlogin-text' );
242 } elseif ( $this->isSignup() && !$authManager->canCreateAccounts() ) {
243 throw new ErrorPageError( 'cannotcreateaccount-title', 'cannotcreateaccount-text' );
247 * In the case where the user is already logged in, and was redirected to
248 * the login form from a page that requires login, do not show the login
249 * page. The use case scenario for this is when a user opens a large number
250 * of tabs, is redirected to the login page on all of them, and then logs
251 * in on one, expecting all the others to work properly.
253 * However, do show the form if it was visited intentionally (no 'returnto'
254 * is present). People who often switch between several accounts have grown
255 * accustomed to this behavior.
257 * Also make an exception when force=<level> is set in the URL, which means the user must
258 * reauthenticate for security reasons.
260 if ( !$this->isSignup() && !$this->mPosted
&& !$this->securityLevel
&&
261 ( $this->mReturnTo
!== '' ||
$this->mReturnToQuery
!== '' ) &&
262 $this->getUser()->isLoggedIn()
264 $this->successfulAction();
268 // If logging in and not on HTTPS, either redirect to it or offer a link.
269 global $wgSecureLogin;
270 if ( $this->getRequest()->getProtocol() !== 'https' ) {
271 $title = $this->getFullTitle();
272 $query = $this->getPreservedParams( false ) +
[
274 ( $this->mEntryErrorType
=== 'error' ?
'error'
275 : 'warning' ) => $this->mEntryError
,
276 ] +
$this->getRequest()->getQueryValues();
277 $url = $title->getFullURL( $query, false, PROTO_HTTPS
);
278 if ( $wgSecureLogin && !$this->mFromHTTP
&&
279 wfCanIPUseHTTPS( $this->getRequest()->getIP() )
281 // Avoid infinite redirect
282 $url = wfAppendQuery( $url, 'fromhttp=1' );
283 $this->getOutput()->redirect( $url );
284 // Since we only do this redir to change proto, always vary
285 $this->getOutput()->addVaryHeader( 'X-Forwarded-Proto' );
289 // A wiki without HTTPS login support should set $wgServer to
290 // http://somehost, in which case the secure URL generated
291 // above won't actually start with https://
292 if ( substr( $url, 0, 8 ) === 'https://' ) {
293 $this->mSecureLoginUrl
= $url;
298 if ( !$this->isActionAllowed( $this->authAction
) ) {
299 // FIXME how do we explain this to the user? can we handle session loss better?
300 // messages used: authpage-cannot-login, authpage-cannot-login-continue,
301 // authpage-cannot-create, authpage-cannot-create-continue
302 $this->mainLoginForm( [], 'authpage-cannot-' . $this->authAction
);
306 if ( $this->canBypassForm( $button_name ) ) {
307 $this->setRequest( [], true );
308 $this->getRequest()->setVal( $this->getTokenName(), $this->getToken() );
309 if ( $button_name ) {
310 $this->getRequest()->setVal( $button_name, true );
314 $status = $this->trySubmit();
316 if ( !$status ||
!$status->isGood() ) {
317 $this->mainLoginForm( $this->authRequests
, $status ?
$status->getMessage() : '', 'error' );
321 /** @var AuthenticationResponse $response */
322 $response = $status->getValue();
324 $returnToUrl = $this->getPageTitle( 'return' )
325 ->getFullURL( $this->getPreservedParams( true ), false, PROTO_HTTPS
);
326 switch ( $response->status
) {
327 case AuthenticationResponse
::PASS
:
328 $this->logAuthResult( true );
329 $this->proxyAccountCreation
= $this->isSignup() && !$this->getUser()->isAnon();
330 $this->targetUser
= User
::newFromName( $response->username
);
333 !$this->proxyAccountCreation
334 && $response->loginRequest
335 && $authManager->canAuthenticateNow()
337 // successful registration; log the user in instantly
338 $response2 = $authManager->beginAuthentication( [ $response->loginRequest
],
340 if ( $response2->status
!== AuthenticationResponse
::PASS
) {
341 LoggerFactory
::getInstance( 'login' )
342 ->error( 'Could not log in after account creation' );
343 $this->successfulAction( true, Status
::newFatal( 'createacct-loginerror' ) );
348 if ( !$this->proxyAccountCreation
) {
349 // Ensure that the context user is the same as the session user.
350 $this->setSessionUserForCurrentRequest();
353 $this->successfulAction( true );
355 case AuthenticationResponse
::FAIL
:
357 case AuthenticationResponse
::RESTART
:
358 unset( $this->authForm
);
359 if ( $response->status
=== AuthenticationResponse
::FAIL
) {
360 $action = $this->getDefaultAction( $subPage );
361 $messageType = 'error';
363 $action = $this->getContinueAction( $this->authAction
);
364 $messageType = 'warning';
366 $this->logAuthResult( false, $response->message ?
$response->message
->getKey() : '-' );
367 $this->loadAuth( $subPage, $action, true );
368 $this->mainLoginForm( $this->authRequests
, $response->message
, $messageType );
370 case AuthenticationResponse
::REDIRECT
:
371 unset( $this->authForm
);
372 $this->getOutput()->redirect( $response->redirectTarget
);
374 case AuthenticationResponse
::UI
:
375 unset( $this->authForm
);
376 $this->authAction
= $this->isSignup() ? AuthManager
::ACTION_CREATE_CONTINUE
377 : AuthManager
::ACTION_LOGIN_CONTINUE
;
378 $this->authRequests
= $response->neededRequests
;
379 $this->mainLoginForm( $response->neededRequests
, $response->message
, $response->messageType
);
382 throw new LogicException( 'invalid AuthenticationResponse' );
387 * Determine if the login form can be bypassed. This will be the case when no more than one
388 * button is present and no other user input fields that are not marked as 'skippable' are
389 * present. If the login form were not bypassed, the user would be presented with a
390 * superfluous page on which they must press the single button to proceed with login.
391 * Not only does this cause an additional mouse click and page load, it confuses users,
392 * especially since there are a help link and forgotten password link that are
393 * provided on the login page that do not apply to this situation.
395 * @param string|null &$button_name if the form has a single button, returns
396 * the name of the button; otherwise, returns null
399 private function canBypassForm( &$button_name ) {
401 if ( $this->isContinued() ) {
404 $fields = AuthenticationRequest
::mergeFieldInfo( $this->authRequests
);
405 foreach ( $fields as $fieldname => $field ) {
406 if ( !isset( $field['type'] ) ) {
409 if ( !empty( $field['skippable'] ) ) {
412 if ( $field['type'] === 'button' ) {
413 if ( $button_name !== null ) {
417 $button_name = $fieldname;
419 } elseif ( $field['type'] !== 'null' ) {
427 * Show the success page.
429 * @param string $type Condition of return to; see `executeReturnTo`
430 * @param string|Message $title Page's title
431 * @param string $msgname
432 * @param string $injected_html
433 * @param StatusValue|null $extraMessages
435 protected function showSuccessPage(
436 $type, $title, $msgname, $injected_html, $extraMessages
438 $out = $this->getOutput();
439 $out->setPageTitle( $title );
441 $out->addWikiMsg( $msgname, wfEscapeWikiText( $this->getUser()->getName() ) );
443 if ( $extraMessages ) {
444 $extraMessages = Status
::wrap( $extraMessages );
445 $out->addWikiTextAsInterface( $extraMessages->getWikiText() );
448 $out->addHTML( $injected_html );
450 $helper = new LoginHelper( $this->getContext() );
451 $helper->showReturnToPage( $type, $this->mReturnTo
, $this->mReturnToQuery
, $this->mStickHTTPS
);
455 * Add a "return to" link or redirect to it.
456 * Extensions can use this to reuse the "return to" logic after
457 * inject steps (such as redirection) into the login process.
459 * @param string $type One of the following:
460 * - error: display a return to link ignoring $wgRedirectOnLogin
461 * - signup: display a return to link using $wgRedirectOnLogin if needed
462 * - success: display a return to link using $wgRedirectOnLogin if needed
463 * - successredirect: send an HTTP redirect using $wgRedirectOnLogin if needed
464 * @param string $returnTo
465 * @param array|string $returnToQuery
466 * @param bool $stickHTTPS Keep redirect link on HTTPS
469 public function showReturnToPage(
470 $type, $returnTo = '', $returnToQuery = '', $stickHTTPS = false
472 $helper = new LoginHelper( $this->getContext() );
473 $helper->showReturnToPage( $type, $returnTo, $returnToQuery, $stickHTTPS );
477 * Replace some globals to make sure the fact that the user has just been logged in is
478 * reflected in the current request.
480 protected function setSessionUserForCurrentRequest() {
481 global $wgUser, $wgLang;
483 $context = RequestContext
::getMain();
484 $localContext = $this->getContext();
485 if ( $context !== $localContext ) {
486 // remove AuthManagerSpecialPage context hack
487 $this->setContext( $context );
490 $user = $context->getRequest()->getSession()->getUser();
493 $context->setUser( $user );
495 $wgLang = $context->getLanguage();
499 * @param AuthenticationRequest[] $requests A list of AuthorizationRequest objects,
500 * used to generate the form fields. An empty array means a fatal error
501 * (authentication cannot continue).
502 * @param string|Message $msg
503 * @param string $msgtype
504 * @throws ErrorPageError
507 * @throws MWException
508 * @throws PermissionsError
509 * @throws ReadOnlyError
512 protected function mainLoginForm( array $requests, $msg = '', $msgtype = 'error' ) {
513 $user = $this->getUser();
514 $out = $this->getOutput();
516 // FIXME how to handle empty $requests - restart, or no form, just an error message?
517 // no form would be better for no session type errors, restart is better when can* fails.
519 $this->authAction
= $this->getDefaultAction( $this->subPage
);
520 $this->authForm
= null;
521 $requests = AuthManager
::singleton()->getAuthenticationRequests( $this->authAction
, $user );
524 // Generic styles and scripts for both login and signup form
525 $out->addModuleStyles( [
527 'mediawiki.ui.button',
528 'mediawiki.ui.checkbox',
529 'mediawiki.ui.input',
530 'mediawiki.special.userlogin.common.styles'
532 if ( $this->isSignup() ) {
533 // XXX hack pending RL or JS parse() support for complex content messages T27349
534 $out->addJsConfigVars( 'wgCreateacctImgcaptchaHelp',
535 $this->msg( 'createacct-imgcaptcha-help' )->parse() );
537 // Additional styles and scripts for signup form
539 'mediawiki.special.userlogin.signup.js'
541 $out->addModuleStyles( [
542 'mediawiki.special.userlogin.signup.styles'
545 // Additional styles for login form
546 $out->addModuleStyles( [
547 'mediawiki.special.userlogin.login.styles'
550 $out->disallowUserJs(); // just in case...
552 $form = $this->getAuthForm( $requests, $this->authAction
, $msg, $msgtype );
553 $form->prepareForm();
555 $submitStatus = Status
::newGood();
556 if ( $msg && $msgtype === 'warning' ) {
557 $submitStatus->warning( $msg );
558 } elseif ( $msg && $msgtype === 'error' ) {
559 $submitStatus->fatal( $msg );
562 // warning header for non-standard workflows (e.g. security reauthentication)
564 !$this->isSignup() &&
565 $this->getUser()->isLoggedIn() &&
566 $this->authAction
!== AuthManager
::ACTION_LOGIN_CONTINUE
568 $reauthMessage = $this->securityLevel ?
'userlogin-reauth' : 'userlogin-loggedin';
569 $submitStatus->warning( $reauthMessage, $this->getUser()->getName() );
572 $formHtml = $form->getHTML( $submitStatus );
574 $out->addHTML( $this->getPageHtml( $formHtml ) );
578 * Add page elements which are outside the form.
579 * FIXME this should probably be a template, but use a sane language (handlebars?)
580 * @param string $formHtml
583 protected function getPageHtml( $formHtml ) {
584 global $wgLoginLanguageSelector;
586 $loginPrompt = $this->isSignup() ?
'' : Html
::rawElement( 'div',
587 [ 'id' => 'userloginprompt' ], $this->msg( 'loginprompt' )->parseAsBlock() );
588 $languageLinks = $wgLoginLanguageSelector ?
$this->makeLanguageSelector() : '';
589 $signupStartMsg = $this->msg( 'signupstart' );
590 $signupStart = ( $this->isSignup() && !$signupStartMsg->isDisabled() )
591 ? Html
::rawElement( 'div', [ 'id' => 'signupstart' ], $signupStartMsg->parseAsBlock() ) : '';
592 if ( $languageLinks ) {
593 $languageLinks = Html
::rawElement( 'div', [ 'id' => 'languagelinks' ],
594 Html
::rawElement( 'p', [], $languageLinks )
598 $benefitsContainer = '';
599 if ( $this->isSignup() && $this->showExtraInformation() ) {
601 // createacct-benefit-icon1 createacct-benefit-head1 createacct-benefit-body1
602 // createacct-benefit-icon2 createacct-benefit-head2 createacct-benefit-body2
603 // createacct-benefit-icon3 createacct-benefit-head3 createacct-benefit-body3
606 for ( $benefitIdx = 1; $benefitIdx <= $benefitCount; $benefitIdx++
) {
607 $headUnescaped = $this->msg( "createacct-benefit-head$benefitIdx" )->text();
608 $iconClass = $this->msg( "createacct-benefit-icon$benefitIdx" )->text();
609 $benefitList .= Html
::rawElement( 'div', [ 'class' => "mw-number-text $iconClass" ],
610 Html
::rawElement( 'h3', [],
611 $this->msg( "createacct-benefit-head$benefitIdx" )->escaped()
613 . Html
::rawElement( 'p', [],
614 $this->msg( "createacct-benefit-body$benefitIdx" )->params( $headUnescaped )->escaped()
618 $benefitsContainer = Html
::rawElement( 'div', [ 'class' => 'mw-createacct-benefits-container' ],
619 Html
::rawElement( 'h2', [], $this->msg( 'createacct-benefit-heading' )->escaped() )
620 . Html
::rawElement( 'div', [ 'class' => 'mw-createacct-benefits-list' ],
626 $html = Html
::rawElement( 'div', [ 'class' => 'mw-ui-container' ],
630 . Html
::rawElement( 'div', [ 'id' => 'userloginForm' ],
640 * Generates a form from the given request.
641 * @param AuthenticationRequest[] $requests
642 * @param string $action AuthManager action name
643 * @param string|Message $msg
644 * @param string $msgType
647 protected function getAuthForm( array $requests, $action, $msg = '', $msgType = 'error' ) {
648 global $wgSecureLogin;
649 // FIXME merge this with parent
651 if ( isset( $this->authForm
) ) {
652 return $this->authForm
;
655 $usingHTTPS = $this->getRequest()->getProtocol() === 'https';
657 // get basic form description from the auth logic
658 $fieldInfo = AuthenticationRequest
::mergeFieldInfo( $requests );
659 // this will call onAuthChangeFormFields()
660 $formDescriptor = static::fieldInfoToFormDescriptor( $requests, $fieldInfo, $this->authAction
);
661 $this->postProcessFormDescriptor( $formDescriptor, $requests );
663 $context = $this->getContext();
664 if ( $context->getRequest() !== $this->getRequest() ) {
665 // We have overridden the request, need to make sure the form uses that too.
666 $context = new DerivativeContext( $this->getContext() );
667 $context->setRequest( $this->getRequest() );
669 $form = HTMLForm
::factory( 'vform', $formDescriptor, $context );
671 $form->addHiddenField( 'authAction', $this->authAction
);
672 if ( $this->mLanguage
) {
673 $form->addHiddenField( 'uselang', $this->mLanguage
);
675 $form->addHiddenField( 'force', $this->securityLevel
);
676 $form->addHiddenField( $this->getTokenName(), $this->getToken()->toString() );
677 if ( $wgSecureLogin ) {
678 // If using HTTPS coming from HTTP, then the 'fromhttp' parameter must be preserved
679 if ( !$this->isSignup() ) {
680 $form->addHiddenField( 'wpForceHttps', (int)$this->mStickHTTPS
);
681 $form->addHiddenField( 'wpFromhttp', $usingHTTPS );
685 // set properties of the form itself
686 $form->setAction( $this->getPageTitle()->getLocalURL( $this->getReturnToQueryStringFragment() ) );
687 $form->setName( 'userlogin' . ( $this->isSignup() ?
'2' : '' ) );
688 if ( $this->isSignup() ) {
689 $form->setId( 'userlogin2' );
692 $form->suppressDefaultSubmit();
694 $this->authForm
= $form;
699 public function onAuthChangeFormFields(
700 array $requests, array $fieldInfo, array &$formDescriptor, $action
702 $coreFieldDescriptors = $this->getFieldDefinitions();
704 // keep the ordering from getCoreFieldDescriptors() where there is no explicit weight
705 foreach ( $coreFieldDescriptors as $fieldName => $coreField ) {
706 $requestField = $formDescriptor[$fieldName] ??
[];
708 // remove everything that is not in the fieldinfo, is not marked as a supplemental field
709 // to something in the fieldinfo, and is not an info field or a submit button
711 !isset( $fieldInfo[$fieldName] )
713 !isset( $coreField['baseField'] )
714 ||
!isset( $fieldInfo[$coreField['baseField']] )
717 !isset( $coreField['type'] )
718 ||
!in_array( $coreField['type'], [ 'submit', 'info' ], true )
721 $coreFieldDescriptors[$fieldName] = null;
725 // core message labels should always take priority
727 isset( $coreField['label'] )
728 ||
isset( $coreField['label-message'] )
729 ||
isset( $coreField['label-raw'] )
731 unset( $requestField['label'], $requestField['label-message'], $coreField['label-raw'] );
734 $coreFieldDescriptors[$fieldName] +
= $requestField;
737 $formDescriptor = array_filter( $coreFieldDescriptors +
$formDescriptor );
742 * Show extra information such as password recovery information, link from login to signup,
743 * CTA etc? Such information should only be shown on the "landing page", ie. when the user
744 * is at the first step of the authentication process.
747 protected function showExtraInformation() {
748 return $this->authAction
!== $this->getContinueAction( $this->authAction
)
749 && !$this->securityLevel
;
753 * Create a HTMLForm descriptor for the core login fields.
756 protected function getFieldDefinitions() {
757 global $wgEmailConfirmToEdit;
759 $isLoggedIn = $this->getUser()->isLoggedIn();
760 $continuePart = $this->isContinued() ?
'continue-' : '';
761 $anotherPart = $isLoggedIn ?
'another-' : '';
762 $expiration = $this->getRequest()->getSession()->getProvider()->getRememberUserDuration();
763 $expirationDays = ceil( $expiration / ( 3600 * 24 ) );
764 $secureLoginLink = '';
765 if ( $this->mSecureLoginUrl
) {
766 $secureLoginLink = Html
::element( 'a', [
767 'href' => $this->mSecureLoginUrl
,
768 'class' => 'mw-ui-flush-right mw-secure',
769 ], $this->msg( 'userlogin-signwithsecure' )->text() );
771 $usernameHelpLink = '';
772 if ( !$this->msg( 'createacct-helpusername' )->isDisabled() ) {
773 $usernameHelpLink = Html
::rawElement( 'span', [
774 'class' => 'mw-ui-flush-right',
775 ], $this->msg( 'createacct-helpusername' )->parse() );
778 if ( $this->isSignup() ) {
779 $fieldDefinitions = [
781 // used by the mediawiki.special.userlogin.signup.js module for error display
782 // FIXME merge this with HTMLForm's normal status (error) area
785 'default' => Html
::element( 'div', [ 'id' => 'mw-createacct-status-area' ] ),
789 'label-raw' => $this->msg( 'userlogin-yourname' )->escaped() . $usernameHelpLink,
791 'placeholder-message' => $isLoggedIn ?
'createacct-another-username-ph'
792 : 'userlogin-yourname-ph',
795 // create account without providing password, a temporary one will be mailed
797 'label-message' => 'createaccountmail',
798 'name' => 'wpCreateaccountMail',
799 'id' => 'wpCreateaccountMail',
802 'id' => 'wpPassword2',
803 'placeholder-message' => 'createacct-yourpassword-ph',
804 'hide-if' => [ '===', 'wpCreateaccountMail', '1' ],
808 'baseField' => 'password',
809 'type' => 'password',
810 'label-message' => 'createacct-yourpasswordagain',
812 'cssclass' => 'loginPassword',
814 'validation-callback' => function ( $value, $alldata ) {
815 if ( empty( $alldata['mailpassword'] ) && !empty( $alldata['password'] ) ) {
817 return $this->msg( 'htmlform-required' );
818 } elseif ( $value !== $alldata['password'] ) {
819 return $this->msg( 'badretype' );
824 'hide-if' => [ '===', 'wpCreateaccountMail', '1' ],
825 'placeholder-message' => 'createacct-yourpasswordagain-ph',
829 'label-message' => $wgEmailConfirmToEdit ?
'createacct-emailrequired'
830 : 'createacct-emailoptional',
832 'cssclass' => 'loginText',
834 // FIXME will break non-standard providers
835 'required' => $wgEmailConfirmToEdit,
836 'validation-callback' => function ( $value, $alldata ) {
837 global $wgEmailConfirmToEdit;
839 // AuthManager will check most of these, but that will make the auth
840 // session fail and this won't, so nicer to do it this way
841 if ( !$value && $wgEmailConfirmToEdit ) {
842 // no point in allowing registration without email when email is
844 return $this->msg( 'noemailtitle' );
845 } elseif ( !$value && !empty( $alldata['mailpassword'] ) ) {
846 // cannot send password via email when there is no email address
847 return $this->msg( 'noemailcreate' );
848 } elseif ( $value && !Sanitizer
::validateEmail( $value ) ) {
849 return $this->msg( 'invalidemailaddress' );
853 'placeholder-message' => 'createacct-' . $anotherPart . 'email-ph',
857 'help-message' => $isLoggedIn ?
'createacct-another-realname-tip'
858 : 'prefs-help-realname',
859 'label-message' => 'createacct-realname',
860 'cssclass' => 'loginText',
862 'id' => 'wpRealName',
865 // comment for the user creation log
867 'label-message' => 'createacct-reason',
868 'cssclass' => 'loginText',
871 'placeholder-message' => 'createacct-reason-ph',
876 'default' => $this->msg( 'createacct-' . $anotherPart . $continuePart .
878 'name' => 'wpCreateaccount',
879 'id' => 'wpCreateaccount',
884 $fieldDefinitions = [
886 'label-raw' => $this->msg( 'userlogin-yourname' )->escaped() . $secureLoginLink,
888 'placeholder-message' => 'userlogin-yourname-ph',
891 'id' => 'wpPassword1',
892 'placeholder-message' => 'userlogin-yourpassword-ph',
896 // option for saving the user token to a cookie
898 'name' => 'wpRemember',
899 'label-message' => $this->msg( 'userlogin-remembermypassword' )
900 ->numParams( $expirationDays ),
901 'id' => 'wpRemember',
906 'default' => $this->msg( 'pt-login-' . $continuePart . 'button' )->text(),
907 'id' => 'wpLoginAttempt',
913 'cssclass' => 'mw-form-related-link-container mw-userlogin-help',
914 // 'id' => 'mw-userlogin-help', // FIXME HTMLInfoField ignores this
916 'default' => Html
::element( 'a', [
917 'href' => Skin
::makeInternalOrExternalUrl( $this->msg( 'helplogin-url' )
918 ->inContentLanguage()
920 ], $this->msg( 'userlogin-helplink2' )->text() ),
923 // button for ResetPasswordSecondaryAuthenticationProvider
931 $fieldDefinitions['username'] +
= [
934 'cssclass' => 'loginText',
936 // 'required' => true,
938 $fieldDefinitions['password'] +
= [
939 'type' => 'password',
940 // 'label-message' => 'userlogin-yourpassword', // would override the changepassword label
941 'name' => 'wpPassword',
942 'cssclass' => 'loginPassword',
944 // 'required' => true,
947 if ( $this->mEntryError
) {
948 $fieldDefinitions['entryError'] = [
950 'default' => Html
::rawElement( 'div', [ 'class' => $this->mEntryErrorType
. 'box', ],
951 $this->mEntryError
),
957 if ( !$this->showExtraInformation() ) {
958 unset( $fieldDefinitions['linkcontainer'], $fieldDefinitions['signupend'] );
960 if ( $this->isSignup() && $this->showExtraInformation() ) {
961 // blank signup footer for site customization
962 // uses signupend-https for HTTPS requests if it's not blank, signupend otherwise
963 $signupendMsg = $this->msg( 'signupend' );
964 $signupendHttpsMsg = $this->msg( 'signupend-https' );
965 if ( !$signupendMsg->isDisabled() ) {
966 $usingHTTPS = $this->getRequest()->getProtocol() === 'https';
967 $signupendText = ( $usingHTTPS && !$signupendHttpsMsg->isBlank() )
968 ?
$signupendHttpsMsg->parse() : $signupendMsg->parse();
969 $fieldDefinitions['signupend'] = [
972 'default' => Html
::rawElement( 'div', [ 'id' => 'signupend' ], $signupendText ),
977 if ( !$this->isSignup() && $this->showExtraInformation() ) {
978 $passwordReset = new PasswordReset( $this->getConfig(), AuthManager
::singleton() );
979 if ( $passwordReset->isAllowed( $this->getUser() )->isGood() ) {
980 $fieldDefinitions['passwordReset'] = [
983 'cssclass' => 'mw-form-related-link-container',
984 'default' => $this->getLinkRenderer()->makeLink(
985 SpecialPage
::getTitleFor( 'PasswordReset' ),
986 $this->msg( 'userlogin-resetpassword-link' )->text()
992 // Don't show a "create account" link if the user can't.
993 if ( $this->showCreateAccountLink() ) {
994 // link to the other action
995 $linkTitle = $this->getTitleFor( $this->isSignup() ?
'Userlogin' : 'CreateAccount' );
996 $linkq = $this->getReturnToQueryStringFragment();
997 // Pass any language selection on to the mode switch link
998 if ( $this->mLanguage
) {
999 $linkq .= '&uselang=' . urlencode( $this->mLanguage
);
1001 $loggedIn = $this->getUser()->isLoggedIn();
1003 $fieldDefinitions['createOrLogin'] = [
1006 'linkQuery' => $linkq,
1007 'default' => function ( $params ) use ( $loggedIn, $linkTitle ) {
1008 return Html
::rawElement( 'div',
1009 [ 'id' => 'mw-createaccount' . ( !$loggedIn ?
'-cta' : '' ),
1010 'class' => ( $loggedIn ?
'mw-form-related-link-container' : 'mw-ui-vform-field' ) ],
1011 ( $loggedIn ?
'' : $this->msg( 'userlogin-noaccount' )->escaped() )
1012 . Html
::element( 'a',
1014 'id' => 'mw-createaccount-join' . ( $loggedIn ?
'-loggedin' : '' ),
1015 'href' => $linkTitle->getLocalURL( $params['linkQuery'] ),
1016 'class' => ( $loggedIn ?
'' : 'mw-ui-button' ),
1020 $loggedIn ?
'userlogin-createanother' : 'userlogin-joinproject'
1030 return $fieldDefinitions;
1034 * Check if a session cookie is present.
1036 * This will not pick up a cookie set during _this_ request, but is meant
1037 * to ensure that the client is returning the cookie which was set on a
1038 * previous pass through the system.
1042 protected function hasSessionCookie() {
1043 global $wgDisableCookieCheck, $wgInitialSessionId;
1045 return $wgDisableCookieCheck ||
(
1046 $wgInitialSessionId &&
1047 $this->getRequest()->getSession()->getId() === (string)$wgInitialSessionId
1052 * Returns a string that can be appended to the URL (without encoding) to preserve the
1053 * return target. Does not include leading '?'/'&'.
1056 protected function getReturnToQueryStringFragment() {
1058 if ( $this->mReturnTo
!== '' ) {
1059 $returnto = 'returnto=' . wfUrlencode( $this->mReturnTo
);
1060 if ( $this->mReturnToQuery
!== '' ) {
1061 $returnto .= '&returntoquery=' . wfUrlencode( $this->mReturnToQuery
);
1068 * Whether the login/create account form should display a link to the
1069 * other form (in addition to whatever the skin provides).
1072 private function showCreateAccountLink() {
1073 if ( $this->isSignup() ) {
1075 } elseif ( $this->getUser()->isAllowed( 'createaccount' ) ) {
1082 protected function getTokenName() {
1083 return $this->isSignup() ?
'wpCreateaccountToken' : 'wpLoginToken';
1087 * Produce a bar of links which allow the user to select another language
1088 * during login/registration but retain "returnto"
1092 protected function makeLanguageSelector() {
1093 $msg = $this->msg( 'loginlanguagelinks' )->inContentLanguage();
1094 if ( $msg->isBlank() ) {
1097 $langs = explode( "\n", $msg->text() );
1099 foreach ( $langs as $lang ) {
1100 $lang = trim( $lang, '* ' );
1101 $parts = explode( '|', $lang );
1102 if ( count( $parts ) >= 2 ) {
1103 $links[] = $this->makeLanguageSelectorLink( $parts[0], trim( $parts[1] ) );
1107 return count( $links ) > 0 ?
$this->msg( 'loginlanguagelabel' )->rawParams(
1108 $this->getLanguage()->pipeList( $links ) )->escaped() : '';
1112 * Create a language selector link for a particular language
1113 * Links back to this page preserving type and returnto
1115 * @param string $text Link text
1116 * @param string $lang Language code
1119 protected function makeLanguageSelectorLink( $text, $lang ) {
1120 if ( $this->getLanguage()->getCode() == $lang ) {
1121 // no link for currently used language
1122 return htmlspecialchars( $text );
1124 $query = [ 'uselang' => $lang ];
1125 if ( $this->mReturnTo
!== '' ) {
1126 $query['returnto'] = $this->mReturnTo
;
1127 $query['returntoquery'] = $this->mReturnToQuery
;
1131 $targetLanguage = Language
::factory( $lang );
1132 $attr['lang'] = $attr['hreflang'] = $targetLanguage->getHtmlCode();
1134 return $this->getLinkRenderer()->makeKnownLink(
1135 $this->getPageTitle(),
1142 protected function getGroupName() {
1147 * @param array &$formDescriptor
1148 * @param array $requests
1150 protected function postProcessFormDescriptor( &$formDescriptor, $requests ) {
1151 // Pre-fill username (if not creating an account, T46775).
1153 isset( $formDescriptor['username'] ) &&
1154 !isset( $formDescriptor['username']['default'] ) &&
1157 $user = $this->getUser();
1158 if ( $user->isLoggedIn() ) {
1159 $formDescriptor['username']['default'] = $user->getName();
1161 $formDescriptor['username']['default'] =
1162 $this->getRequest()->getSession()->suggestLoginUsername();
1166 // don't show a submit button if there is nothing to submit (i.e. the only form content
1167 // is other submit buttons, for redirect flows)
1168 if ( !$this->needsSubmitButton( $requests ) ) {
1169 unset( $formDescriptor['createaccount'], $formDescriptor['loginattempt'] );
1172 if ( !$this->isSignup() ) {
1173 // FIXME HACK don't focus on non-empty field
1174 // maybe there should be an autofocus-if similar to hide-if?
1176 isset( $formDescriptor['username'] )
1177 && empty( $formDescriptor['username']['default'] )
1178 && !$this->getRequest()->getCheck( 'wpName' )
1180 $formDescriptor['username']['autofocus'] = true;
1181 } elseif ( isset( $formDescriptor['password'] ) ) {
1182 $formDescriptor['password']['autofocus'] = true;
1186 $this->addTabIndex( $formDescriptor );