MediaWiki REL1_37
LoginSignupSpecialPage.php
Go to the documentation of this file.
1<?php
31use Wikimedia\ScopedCallback;
32
39 protected $mReturnTo;
40 protected $mPosted;
41 protected $mAction;
42 protected $mLanguage;
43 protected $mReturnToQuery;
44 protected $mToken;
45 protected $mStickHTTPS;
46 protected $mFromHTTP;
47 protected $mEntryError = '';
48 protected $mEntryErrorType = 'error';
49
50 protected $mLoaded = false;
51 protected $mLoadedRequest = false;
53 private $reasonValidatorResult = null;
54
56 protected $securityLevel;
57
63 protected $targetUser;
64
66 protected $authForm;
67
68 abstract protected function isSignup();
69
76 abstract protected function successfulAction( $direct = false, $extraMessages = null );
77
83 abstract protected function logAuthResult( $success, $status = null );
84
85 public function __construct( $name, $restriction = '' ) {
87 parent::__construct( $name, $restriction );
88
89 // Override UseMediaWikiEverywhere to true, to force login and create form to use mw ui
91 }
92
93 protected function setRequest( array $data, $wasPosted = null ) {
94 parent::setRequest( $data, $wasPosted );
95 $this->mLoadedRequest = false;
96 }
97
101 private function loadRequestParameters() {
102 if ( $this->mLoadedRequest ) {
103 return;
104 }
105 $this->mLoadedRequest = true;
106 $request = $this->getRequest();
107
108 $this->mPosted = $request->wasPosted();
109 $this->mAction = $request->getRawVal( 'action' );
110 $this->mFromHTTP = $request->getBool( 'fromhttp', false )
111 || $request->getBool( 'wpFromhttp', false );
112 $this->mStickHTTPS = $this->getConfig()->get( 'ForceHTTPS' )
113 || ( !$this->mFromHTTP && $request->getProtocol() === 'https' )
114 || $request->getBool( 'wpForceHttps', false );
115 $this->mLanguage = $request->getText( 'uselang' );
116 $this->mReturnTo = $request->getVal( 'returnto', '' );
117 $this->mReturnToQuery = $request->getVal( 'returntoquery', '' );
118 }
119
125 protected function load( $subPage ) {
126 global $wgSecureLogin;
127
128 $this->loadRequestParameters();
129 if ( $this->mLoaded ) {
130 return;
131 }
132 $this->mLoaded = true;
133 $request = $this->getRequest();
134
135 $securityLevel = $this->getRequest()->getText( 'force' );
136 if (
138 MediaWikiServices::getInstance()->getAuthManager()->securitySensitiveOperationStatus(
139 $securityLevel ) === AuthManager::SEC_REAUTH
140 ) {
141 $this->securityLevel = $securityLevel;
142 }
143
144 $this->loadAuth( $subPage );
145
146 $this->mToken = $request->getVal( $this->getTokenName() );
147
148 // Show an error or warning passed on from a previous page
149 $entryError = $this->msg( $request->getVal( 'error', '' ) );
150 $entryWarning = $this->msg( $request->getVal( 'warning', '' ) );
151 // bc: provide login link as a parameter for messages where the translation
152 // was not updated
153 $loginreqlink = $this->getLinkRenderer()->makeKnownLink(
154 $this->getPageTitle(),
155 $this->msg( 'loginreqlink' )->text(),
156 [],
157 [
158 'returnto' => $this->mReturnTo,
159 'returntoquery' => $this->mReturnToQuery,
160 'uselang' => $this->mLanguage ?: null,
161 'fromhttp' => $wgSecureLogin && $this->mFromHTTP ? '1' : null,
162 ]
163 );
164
165 // Only show valid error or warning messages.
166 if ( $entryError->exists()
167 && in_array( $entryError->getKey(), LoginHelper::getValidErrorMessages(), true )
168 ) {
169 $this->mEntryErrorType = 'error';
170 $this->mEntryError = $entryError->rawParams( $loginreqlink )->parse();
171
172 } elseif ( $entryWarning->exists()
173 && in_array( $entryWarning->getKey(), LoginHelper::getValidErrorMessages(), true )
174 ) {
175 $this->mEntryErrorType = 'warning';
176 $this->mEntryError = $entryWarning->rawParams( $loginreqlink )->parse();
177 }
178
179 # 1. When switching accounts, it sucks to get automatically logged out
180 # 2. Do not return to PasswordReset after a successful password change
181 # but goto Wiki start page (Main_Page) instead ( T35997 )
182 $returnToTitle = Title::newFromText( $this->mReturnTo );
183 if ( is_object( $returnToTitle )
184 && ( $returnToTitle->isSpecial( 'Userlogout' )
185 || $returnToTitle->isSpecial( 'PasswordReset' ) )
186 ) {
187 $this->mReturnTo = '';
188 $this->mReturnToQuery = '';
189 }
190 }
191
192 protected function getPreservedParams( $withToken = false ) {
193 global $wgSecureLogin;
194
195 $params = parent::getPreservedParams( $withToken );
196 $params += [
197 'returnto' => $this->mReturnTo ?: null,
198 'returntoquery' => $this->mReturnToQuery ?: null,
199 ];
200 if ( $wgSecureLogin && !$this->isSignup() ) {
201 $params['fromhttp'] = $this->mFromHTTP ? '1' : null;
202 }
203 return $params;
204 }
205
206 protected function beforeExecute( $subPage ) {
207 // finish initializing the class before processing the request - T135924
208 $this->loadRequestParameters();
209 return parent::beforeExecute( $subPage );
210 }
211
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 );
223 } );
224 }
225
226 $authManager = MediaWikiServices::getInstance()->getAuthManager();
227 $session = SessionManager::getGlobalSession();
228
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.
231 $session->persist();
232 // Explicitly disable cache to ensure cookie blocks may be set (T152462).
233 // (Technically redundant with sessions persisting from this page.)
234 $this->getOutput()->enableClientCache( false );
235
236 $this->load( $subPage );
237 $this->setHeaders();
238 $this->checkPermissions();
239
240 // Make sure the system configuration allows log in / sign up
241 if ( !$this->isSignup() && !$authManager->canAuthenticateNow() ) {
242 if ( !$session->canSetUser() ) {
243 throw new ErrorPageError( 'cannotloginnow-title', 'cannotloginnow-text', [
244 $session->getProvider()->describe( RequestContext::getMain()->getLanguage() )
245 ] );
246 }
247 throw new ErrorPageError( 'cannotlogin-title', 'cannotlogin-text' );
248 } elseif ( $this->isSignup() && !$authManager->canCreateAccounts() ) {
249 throw new ErrorPageError( 'cannotcreateaccount-title', 'cannotcreateaccount-text' );
250 }
251
252 /*
253 * In the case where the user is already logged in, and was redirected to
254 * the login form from a page that requires login, do not show the login
255 * page. The use case scenario for this is when a user opens a large number
256 * of tabs, is redirected to the login page on all of them, and then logs
257 * in on one, expecting all the others to work properly.
258 *
259 * However, do show the form if it was visited intentionally (no 'returnto'
260 * is present). People who often switch between several accounts have grown
261 * accustomed to this behavior.
262 *
263 * Also make an exception when force=<level> is set in the URL, which means the user must
264 * reauthenticate for security reasons.
265 */
266 if ( !$this->isSignup() && !$this->mPosted && !$this->securityLevel &&
267 ( $this->mReturnTo !== '' || $this->mReturnToQuery !== '' ) &&
268 $this->getUser()->isRegistered()
269 ) {
270 $this->successfulAction();
271 return;
272 }
273
274 // If logging in and not on HTTPS, either redirect to it or offer a link.
275 global $wgSecureLogin;
276 if ( $this->getRequest()->getProtocol() !== 'https' ) {
277 $title = $this->getFullTitle();
278 $query = $this->getPreservedParams( false ) + [
279 'title' => null,
280 ( $this->mEntryErrorType === 'error' ? 'error'
281 : 'warning' ) => $this->mEntryError,
282 ] + $this->getRequest()->getQueryValues();
283 $url = $title->getFullURL( $query, false, PROTO_HTTPS );
284 if ( $wgSecureLogin && !$this->mFromHTTP ) {
285 // Avoid infinite redirect
286 $url = wfAppendQuery( $url, 'fromhttp=1' );
287 $this->getOutput()->redirect( $url );
288 // Since we only do this redir to change proto, always vary
289 $this->getOutput()->addVaryHeader( 'X-Forwarded-Proto' );
290
291 return;
292 } else {
293 // A wiki without HTTPS login support should set $wgServer to
294 // http://somehost, in which case the secure URL generated
295 // above won't actually start with https://
296 if ( substr( $url, 0, 8 ) === 'https://' ) {
297 $this->mSecureLoginUrl = $url;
298 }
299 }
300 }
301
302 if ( !$this->isActionAllowed( $this->authAction ) ) {
303 // FIXME how do we explain this to the user? can we handle session loss better?
304 // messages used: authpage-cannot-login, authpage-cannot-login-continue,
305 // authpage-cannot-create, authpage-cannot-create-continue
306 $this->mainLoginForm( [], 'authpage-cannot-' . $this->authAction );
307 return;
308 }
309
310 if ( $this->canBypassForm( $button_name ) ) {
311 $this->setRequest( [], true );
312 $this->getRequest()->setVal( $this->getTokenName(), $this->getToken() );
313 if ( $button_name ) {
314 $this->getRequest()->setVal( $button_name, true );
315 }
316 }
317
318 $status = $this->trySubmit();
319
320 if ( !$status || !$status->isGood() ) {
321 $this->mainLoginForm( $this->authRequests, $status ? $status->getMessage() : '', 'error' );
322 return;
323 }
324
326 $response = $status->getValue();
327
328 $returnToUrl = $this->getPageTitle( 'return' )
329 ->getFullURL( $this->getPreservedParams( true ), false, PROTO_HTTPS );
330 switch ( $response->status ) {
331 case AuthenticationResponse::PASS:
332 $this->logAuthResult( true );
333 $this->proxyAccountCreation = $this->isSignup() && !$this->getUser()->isAnon();
334 $this->targetUser = User::newFromName( $response->username );
335
336 if (
337 !$this->proxyAccountCreation
338 && $response->loginRequest
340 ) {
341 // successful registration; log the user in instantly
342 $response2 = $authManager->beginAuthentication( [ $response->loginRequest ],
343 $returnToUrl );
344 if ( $response2->status !== AuthenticationResponse::PASS ) {
345 LoggerFactory::getInstance( 'login' )
346 ->error( 'Could not log in after account creation' );
347 $this->successfulAction( true, Status::newFatal( 'createacct-loginerror' ) );
348 break;
349 }
350 }
351
352 if ( !$this->proxyAccountCreation ) {
353 // Ensure that the context user is the same as the session user.
355 }
356
357 $this->successfulAction( true );
358 break;
359 case AuthenticationResponse::FAIL:
360 // fall through
361 case AuthenticationResponse::RESTART:
362 unset( $this->authForm );
363 if ( $response->status === AuthenticationResponse::FAIL ) {
364 $action = $this->getDefaultAction( $subPage );
365 $messageType = 'error';
366 } else {
367 $action = $this->getContinueAction( $this->authAction );
368 $messageType = 'warning';
369 }
370 $this->logAuthResult( false, $response->message ? $response->message->getKey() : '-' );
371 $this->loadAuth( $subPage, $action, true );
372 $this->mainLoginForm( $this->authRequests, $response->message, $messageType );
373 break;
374 case AuthenticationResponse::REDIRECT:
375 unset( $this->authForm );
376 $this->getOutput()->redirect( $response->redirectTarget );
377 break;
378 case AuthenticationResponse::UI:
379 unset( $this->authForm );
380 $this->authAction = $this->isSignup() ? AuthManager::ACTION_CREATE_CONTINUE
381 : AuthManager::ACTION_LOGIN_CONTINUE;
382 $this->authRequests = $response->neededRequests;
383 $this->mainLoginForm( $response->neededRequests, $response->message, $response->messageType );
384 break;
385 default:
386 throw new LogicException( 'invalid AuthenticationResponse' );
387 }
388 }
389
403 private function canBypassForm( &$button_name ) {
404 $button_name = null;
405 if ( $this->isContinued() ) {
406 return false;
407 }
408 $fields = AuthenticationRequest::mergeFieldInfo( $this->authRequests );
409 foreach ( $fields as $fieldname => $field ) {
410 if ( !isset( $field['type'] ) ) {
411 return false;
412 }
413 if ( !empty( $field['skippable'] ) ) {
414 continue;
415 }
416 if ( $field['type'] === 'button' ) {
417 if ( $button_name !== null ) {
418 $button_name = null;
419 return false;
420 } else {
421 $button_name = $fieldname;
422 }
423 } elseif ( $field['type'] !== 'null' ) {
424 return false;
425 }
426 }
427 return true;
428 }
429
439 protected function showSuccessPage(
440 $type, $title, $msgname, $injected_html, $extraMessages
441 ) {
442 $out = $this->getOutput();
443 $out->setPageTitle( $title );
444 if ( $msgname ) {
445 $out->addWikiMsg( $msgname, wfEscapeWikiText( $this->getUser()->getName() ) );
446 }
447 if ( $extraMessages ) {
448 $extraMessages = Status::wrap( $extraMessages );
449 $out->addWikiTextAsInterface(
450 $extraMessages->getWikiText( false, false, $this->getLanguage() )
451 );
452 }
453
454 $out->addHTML( $injected_html );
455
456 $helper = new LoginHelper( $this->getContext() );
457 $helper->showReturnToPage( $type, $this->mReturnTo, $this->mReturnToQuery, $this->mStickHTTPS );
458 }
459
475 public function showReturnToPage(
476 $type, $returnTo = '', $returnToQuery = '', $stickHTTPS = false
477 ) {
478 $helper = new LoginHelper( $this->getContext() );
479 $helper->showReturnToPage( $type, $returnTo, $returnToQuery, $stickHTTPS );
480 }
481
486 protected function setSessionUserForCurrentRequest() {
487 global $wgLang;
488
489 $context = RequestContext::getMain();
490 $localContext = $this->getContext();
491 if ( $context !== $localContext ) {
492 // remove AuthManagerSpecialPage context hack
493 $this->setContext( $context );
494 }
495
496 $user = $context->getRequest()->getSession()->getUser();
497
499 $context->setUser( $user );
500
501 $wgLang = $context->getLanguage();
502 }
503
518 protected function mainLoginForm( array $requests, $msg = '', $msgtype = 'error' ) {
519 $user = $this->getUser();
520 $out = $this->getOutput();
521
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.
524 if ( !$requests ) {
525 $this->authAction = $this->getDefaultAction( $this->subPage );
526 $this->authForm = null;
527 $requests = MediaWikiServices::getInstance()->getAuthManager()
528 ->getAuthenticationRequests( $this->authAction, $user );
529 }
530
531 // Generic styles and scripts for both login and signup form
532 $out->addModuleStyles( [
533 'mediawiki.ui',
534 'mediawiki.ui.button',
535 'mediawiki.ui.checkbox',
536 'mediawiki.ui.input',
537 'mediawiki.special.userlogin.common.styles'
538 ] );
539 if ( $this->isSignup() ) {
540 // XXX hack pending RL or JS parse() support for complex content messages T27349
541 $out->addJsConfigVars( 'wgCreateacctImgcaptchaHelp',
542 $this->msg( 'createacct-imgcaptcha-help' )->parse() );
543
544 // Additional styles and scripts for signup form
545 $out->addModules( 'mediawiki.special.createaccount' );
546 $out->addModuleStyles( [
547 'mediawiki.special.userlogin.signup.styles'
548 ] );
549 } else {
550 // Additional styles for login form
551 $out->addModuleStyles( [
552 'mediawiki.special.userlogin.login.styles'
553 ] );
554 }
555 $out->disallowUserJs(); // just in case...
556
557 $form = $this->getAuthForm( $requests, $this->authAction, $msg, $msgtype );
558 $form->prepareForm();
559
560 $submitStatus = Status::newGood();
561 if ( $msg && $msgtype === 'warning' ) {
562 $submitStatus->warning( $msg );
563 } elseif ( $msg && $msgtype === 'error' ) {
564 $submitStatus->fatal( $msg );
565 }
566
567 // warning header for non-standard workflows (e.g. security reauthentication)
568 if (
569 !$this->isSignup() &&
570 $this->getUser()->isRegistered() &&
571 $this->authAction !== AuthManager::ACTION_LOGIN_CONTINUE
572 ) {
573 $reauthMessage = $this->securityLevel ? 'userlogin-reauth' : 'userlogin-loggedin';
574 $submitStatus->warning( $reauthMessage, $this->getUser()->getName() );
575 }
576
577 $formHtml = $form->getHTML( $submitStatus );
578
579 $out->addHTML( $this->getPageHtml( $formHtml ) );
580 }
581
588 protected function getPageHtml( $formHtml ) {
590
591 $loginPrompt = $this->isSignup() ? '' : Html::rawElement( 'div',
592 [ 'id' => 'userloginprompt' ], $this->msg( 'loginprompt' )->parseAsBlock() );
593 $languageLinks = $wgLoginLanguageSelector ? $this->makeLanguageSelector() : '';
594 $signupStartMsg = $this->msg( 'signupstart' );
595 $signupStart = ( $this->isSignup() && !$signupStartMsg->isDisabled() )
596 ? Html::rawElement( 'div', [ 'id' => 'signupstart' ], $signupStartMsg->parseAsBlock() ) : '';
597 if ( $languageLinks ) {
598 $languageLinks = Html::rawElement( 'div', [ 'id' => 'languagelinks' ],
599 Html::rawElement( 'p', [], $languageLinks )
600 );
601 }
602
603 $benefitsContainer = '';
604 if ( $this->isSignup() && $this->showExtraInformation() ) {
605 // messages used:
606 // createacct-benefit-icon1 createacct-benefit-head1 createacct-benefit-body1
607 // createacct-benefit-icon2 createacct-benefit-head2 createacct-benefit-body2
608 // createacct-benefit-icon3 createacct-benefit-head3 createacct-benefit-body3
609 $benefitCount = 3;
610 $benefitList = '';
611 for ( $benefitIdx = 1; $benefitIdx <= $benefitCount; $benefitIdx++ ) {
612 $headUnescaped = $this->msg( "createacct-benefit-head$benefitIdx" )->text();
613 $iconClass = $this->msg( "createacct-benefit-icon$benefitIdx" )->text();
614 $benefitList .= Html::rawElement( 'div', [ 'class' => "mw-number-text $iconClass" ],
615 Html::rawElement( 'h3', [],
616 $this->msg( "createacct-benefit-head$benefitIdx" )->escaped()
617 )
618 . Html::rawElement( 'p', [],
619 $this->msg( "createacct-benefit-body$benefitIdx" )->params( $headUnescaped )->escaped()
620 )
621 );
622 }
623 $benefitsContainer = Html::rawElement( 'div', [ 'class' => 'mw-createacct-benefits-container' ],
624 Html::rawElement( 'h2', [], $this->msg( 'createacct-benefit-heading' )->escaped() )
625 . Html::rawElement( 'div', [ 'class' => 'mw-createacct-benefits-list' ],
626 $benefitList
627 )
628 );
629 }
630
631 $html = Html::rawElement( 'div', [ 'class' => 'mw-ui-container' ],
632 $loginPrompt
633 . $languageLinks
634 . $signupStart
635 . Html::rawElement( 'div', [ 'id' => 'userloginForm' ],
636 $formHtml
637 )
638 . $benefitsContainer
639 );
640
641 return $html;
642 }
643
652 protected function getAuthForm( array $requests, $action, $msg = '', $msgType = 'error' ) {
653 // FIXME merge this with parent
654
655 if ( isset( $this->authForm ) ) {
656 return $this->authForm;
657 }
658
659 $usingHTTPS = $this->getRequest()->getProtocol() === 'https';
660
661 // get basic form description from the auth logic
662 $fieldInfo = AuthenticationRequest::mergeFieldInfo( $requests );
663 // this will call onAuthChangeFormFields()
664 $formDescriptor = $this->fieldInfoToFormDescriptor( $requests, $fieldInfo, $this->authAction );
665 $this->postProcessFormDescriptor( $formDescriptor, $requests );
666
667 $context = $this->getContext();
668 if ( $context->getRequest() !== $this->getRequest() ) {
669 // We have overridden the request, need to make sure the form uses that too.
670 $context = new DerivativeContext( $this->getContext() );
671 $context->setRequest( $this->getRequest() );
672 }
673 $form = HTMLForm::factory( 'vform', $formDescriptor, $context );
674
675 $form->addHiddenField( 'authAction', $this->authAction );
676 if ( $this->mLanguage ) {
677 $form->addHiddenField( 'uselang', $this->mLanguage );
678 }
679 $form->addHiddenField( 'force', $this->securityLevel );
680 $form->addHiddenField( $this->getTokenName(), $this->getToken()->toString() );
681 $config = $this->getConfig();
682 if ( $config->get( 'SecureLogin' ) && !$config->get( 'ForceHTTPS' ) ) {
683 // If using HTTPS coming from HTTP, then the 'fromhttp' parameter must be preserved
684 if ( !$this->isSignup() ) {
685 $form->addHiddenField( 'wpForceHttps', (int)$this->mStickHTTPS );
686 $form->addHiddenField( 'wpFromhttp', $usingHTTPS );
687 }
688 }
689
690 // set properties of the form itself
691 $form->setAction( $this->getPageTitle()->getLocalURL( $this->getReturnToQueryStringFragment() ) );
692 $form->setName( 'userlogin' . ( $this->isSignup() ? '2' : '' ) );
693 if ( $this->isSignup() ) {
694 $form->setId( 'userlogin2' );
695 }
696
697 $form->suppressDefaultSubmit();
698
699 $this->authForm = $form;
700
701 return $form;
702 }
703
705 public function onAuthChangeFormFields(
706 array $requests, array $fieldInfo, array &$formDescriptor, $action
707 ) {
708 $formDescriptor = self::mergeDefaultFormDescriptor( $fieldInfo, $formDescriptor,
709 $this->getFieldDefinitions() );
710 }
711
718 protected function showExtraInformation() {
719 return $this->authAction !== $this->getContinueAction( $this->authAction )
721 }
722
727 protected function getFieldDefinitions() {
729
730 $isRegistered = $this->getUser()->isRegistered();
731 $continuePart = $this->isContinued() ? 'continue-' : '';
732 $anotherPart = $isRegistered ? 'another-' : '';
733 // @phan-suppress-next-line PhanUndeclaredMethod
734 $expiration = $this->getRequest()->getSession()->getProvider()->getRememberUserDuration();
735 $expirationDays = ceil( $expiration / ( 3600 * 24 ) );
736 $secureLoginLink = '';
737 if ( $this->mSecureLoginUrl ) {
738 $secureLoginLink = Html::element( 'a', [
739 'href' => $this->mSecureLoginUrl,
740 'class' => 'mw-ui-flush-right mw-secure',
741 ], $this->msg( 'userlogin-signwithsecure' )->text() );
742 }
743 $usernameHelpLink = '';
744 if ( !$this->msg( 'createacct-helpusername' )->isDisabled() ) {
745 $usernameHelpLink = Html::rawElement( 'span', [
746 'class' => 'mw-ui-flush-right',
747 ], $this->msg( 'createacct-helpusername' )->parse() );
748 }
749
750 if ( $this->isSignup() ) {
751 $fieldDefinitions = [
752 'statusarea' => [
753 // Used by the mediawiki.special.createaccount module for error display.
754 // FIXME: Merge this with HTMLForm's normal status (error) area
755 'type' => 'info',
756 'raw' => true,
757 'default' => Html::element( 'div', [ 'id' => 'mw-createacct-status-area' ] ),
758 'weight' => -105,
759 ],
760 'username' => [
761 'label-raw' => $this->msg( 'userlogin-yourname' )->escaped() . $usernameHelpLink,
762 'id' => 'wpName2',
763 'placeholder-message' => $isRegistered ? 'createacct-another-username-ph'
764 : 'userlogin-yourname-ph',
765 ],
766 'mailpassword' => [
767 // create account without providing password, a temporary one will be mailed
768 'type' => 'check',
769 'label-message' => 'createaccountmail',
770 'name' => 'wpCreateaccountMail',
771 'id' => 'wpCreateaccountMail',
772 ],
773 'password' => [
774 'id' => 'wpPassword2',
775 'autocomplete' => 'new-password',
776 'placeholder-message' => 'createacct-yourpassword-ph',
777 'help-message' => 'createacct-useuniquepass',
778 'hide-if' => [ '===', 'wpCreateaccountMail', '1' ],
779 ],
780 'domain' => [],
781 'retype' => [
782 'type' => 'password',
783 'label-message' => 'createacct-yourpasswordagain',
784 'id' => 'wpRetype',
785 'cssclass' => 'loginPassword',
786 'size' => 20,
787 'autocomplete' => 'new-password',
788 'validation-callback' => function ( $value, $alldata ) {
789 if ( empty( $alldata['mailpassword'] ) && !empty( $alldata['password'] ) ) {
790 if ( !$value ) {
791 return $this->msg( 'htmlform-required' );
792 } elseif ( $value !== $alldata['password'] ) {
793 return $this->msg( 'badretype' );
794 }
795 }
796 return true;
797 },
798 'hide-if' => [ '===', 'wpCreateaccountMail', '1' ],
799 'placeholder-message' => 'createacct-yourpasswordagain-ph',
800 ],
801 'email' => [
802 'type' => 'email',
803 'label-message' => $wgEmailConfirmToEdit ? 'createacct-emailrequired'
804 : 'createacct-emailoptional',
805 'id' => 'wpEmail',
806 'cssclass' => 'loginText',
807 'size' => '20',
808 'maxlength' => 255,
809 'autocomplete' => 'email',
810 // FIXME will break non-standard providers
811 'required' => $wgEmailConfirmToEdit,
812 'validation-callback' => function ( $value, $alldata ) {
814
815 // AuthManager will check most of these, but that will make the auth
816 // session fail and this won't, so nicer to do it this way
817 if ( !$value && $wgEmailConfirmToEdit ) {
818 // no point in allowing registration without email when email is
819 // required to edit
820 return $this->msg( 'noemailtitle' );
821 } elseif ( !$value && !empty( $alldata['mailpassword'] ) ) {
822 // cannot send password via email when there is no email address
823 return $this->msg( 'noemailcreate' );
824 } elseif ( $value && !Sanitizer::validateEmail( $value ) ) {
825 return $this->msg( 'invalidemailaddress' );
826 } elseif ( is_string( $value ) && strlen( $value ) > 255 ) {
827 return $this->msg( 'changeemail-maxlength' );
828 }
829 return true;
830 },
831 'placeholder-message' => 'createacct-' . $anotherPart . 'email-ph',
832 ],
833 'realname' => [
834 'type' => 'text',
835 'help-message' => $isRegistered ? 'createacct-another-realname-tip'
836 : 'prefs-help-realname',
837 'label-message' => 'createacct-realname',
838 'cssclass' => 'loginText',
839 'size' => 20,
840 'id' => 'wpRealName',
841 'autocomplete' => 'name',
842 ],
843 'reason' => [
844 // comment for the user creation log
845 'type' => 'text',
846 'label-message' => 'createacct-reason',
847 'cssclass' => 'loginText',
848 'id' => 'wpReason',
849 'size' => '20',
850 'validation-callback' => function ( $value, $alldata ) {
851 // if the user sets an email address as the user creation reason, confirm that
852 // that was their intent
853 if ( $value && Sanitizer::validateEmail( $value ) ) {
854 if ( $this->reasonValidatorResult !== null ) {
856 }
857 $this->reasonValidatorResult = true;
858 $authManager = MediaWikiServices::getInstance()->getAuthManager();
859 if ( !$authManager->getAuthenticationSessionData( 'reason-retry', false ) ) {
860 $authManager->setAuthenticationSessionData( 'reason-retry', true );
861 $this->reasonValidatorResult = $this->msg( 'createacct-reason-confirm' );
862 }
864 }
865 return true;
866 },
867 'placeholder-message' => 'createacct-reason-ph',
868 ],
869 'createaccount' => [
870 // submit button
871 'type' => 'submit',
872 'default' => $this->msg( 'createacct-' . $anotherPart . $continuePart .
873 'submit' )->text(),
874 'name' => 'wpCreateaccount',
875 'id' => 'wpCreateaccount',
876 'weight' => 100,
877 ],
878 ];
879 } else {
880 // When the user's password is too weak, they might be asked to provide a stronger one
881 // as a followup step. That is a form with only two fields, 'password' and 'retype',
882 // and they should behave more like account creation.
883 $passwordRequest = AuthenticationRequest::getRequestByClass( $this->authRequests,
884 PasswordAuthenticationRequest::class );
885 $changePassword = $passwordRequest && $passwordRequest->action == AuthManager::ACTION_CHANGE;
886 $fieldDefinitions = [
887 'username' => (
888 [
889 'label-raw' => $this->msg( 'userlogin-yourname' )->escaped() . $secureLoginLink,
890 'id' => 'wpName1',
891 'placeholder-message' => 'userlogin-yourname-ph',
892 ] + ( $changePassword ? [
893 // There is no username field on the AuthManager level when changing
894 // passwords. Fake one because password
895 'baseField' => 'password',
896 'nodata' => true,
897 'readonly' => true,
898 'cssclass' => 'mw-htmlform-hidden-field',
899 ] : [] )
900 ),
901 'password' => (
902 $changePassword ? [
903 'autocomplete' => 'new-password',
904 'placeholder-message' => 'createacct-yourpassword-ph',
905 'help-message' => 'createacct-useuniquepass',
906 ] : [
907 'id' => 'wpPassword1',
908 'autocomplete' => 'current-password',
909 'placeholder-message' => 'userlogin-yourpassword-ph',
910 ]
911 ),
912 'retype' => [
913 'type' => 'password',
914 'autocomplete' => 'new-password',
915 'placeholder-message' => 'createacct-yourpasswordagain-ph',
916 ],
917 'domain' => [],
918 'rememberMe' => [
919 // option for saving the user token to a cookie
920 'type' => 'check',
921 'cssclass' => 'mw-userlogin-rememberme',
922 'name' => 'wpRemember',
923 'label-message' => $this->msg( 'userlogin-remembermypassword' )
924 ->numParams( $expirationDays ),
925 'id' => 'wpRemember',
926 ],
927 'loginattempt' => [
928 // submit button
929 'type' => 'submit',
930 'default' => $this->msg( 'pt-login-' . $continuePart . 'button' )->text(),
931 'id' => 'wpLoginAttempt',
932 'weight' => 100,
933 ],
934 'linkcontainer' => [
935 // help link
936 'type' => 'info',
937 'cssclass' => 'mw-form-related-link-container mw-userlogin-help',
938 // 'id' => 'mw-userlogin-help', // FIXME HTMLInfoField ignores this
939 'raw' => true,
940 'default' => Html::element( 'a', [
941 'href' => Skin::makeInternalOrExternalUrl( $this->msg( 'helplogin-url' )
942 ->inContentLanguage()
943 ->text() ),
944 ], $this->msg( 'userlogin-helplink2' )->text() ),
945 'weight' => 200,
946 ],
947 // button for ResetPasswordSecondaryAuthenticationProvider
948 'skipReset' => [
949 'weight' => 110,
950 'flags' => [],
951 ],
952 ];
953 }
954
955 $fieldDefinitions['username'] += [
956 'type' => 'text',
957 'name' => 'wpName',
958 'cssclass' => 'loginText',
959 'size' => 20,
960 'autocomplete' => 'username',
961 // 'required' => true,
962 ];
963 $fieldDefinitions['password'] += [
964 'type' => 'password',
965 // 'label-message' => 'userlogin-yourpassword', // would override the changepassword label
966 'name' => 'wpPassword',
967 'cssclass' => 'loginPassword',
968 'size' => 20,
969 // 'required' => true,
970 ];
971
972 if ( $this->mEntryError ) {
973 $fieldDefinitions['entryError'] = [
974 'type' => 'info',
975 'default' => Html::rawElement( 'div', [ 'class' => $this->mEntryErrorType . 'box', ],
976 $this->mEntryError ),
977 'raw' => true,
978 'rawrow' => true,
979 'weight' => -100,
980 ];
981 }
982 if ( !$this->showExtraInformation() ) {
983 unset( $fieldDefinitions['linkcontainer'], $fieldDefinitions['signupend'] );
984 }
985 if ( $this->isSignup() && $this->showExtraInformation() ) {
986 // blank signup footer for site customization
987 // uses signupend-https for HTTPS requests if it's not blank, signupend otherwise
988 $signupendMsg = $this->msg( 'signupend' );
989 $signupendHttpsMsg = $this->msg( 'signupend-https' );
990 if ( !$signupendMsg->isDisabled() ) {
991 $usingHTTPS = $this->getRequest()->getProtocol() === 'https';
992 $signupendText = ( $usingHTTPS && !$signupendHttpsMsg->isBlank() )
993 ? $signupendHttpsMsg->parse() : $signupendMsg->parse();
994 $fieldDefinitions['signupend'] = [
995 'type' => 'info',
996 'raw' => true,
997 'default' => Html::rawElement( 'div', [ 'id' => 'signupend' ], $signupendText ),
998 'weight' => 225,
999 ];
1000 }
1001 }
1002 if ( !$this->isSignup() && $this->showExtraInformation() ) {
1003 $passwordReset = MediaWikiServices::getInstance()->getPasswordReset();
1004 if ( $passwordReset->isAllowed( $this->getUser() )->isGood() ) {
1005 $fieldDefinitions['passwordReset'] = [
1006 'type' => 'info',
1007 'raw' => true,
1008 'cssclass' => 'mw-form-related-link-container',
1009 'default' => $this->getLinkRenderer()->makeLink(
1010 SpecialPage::getTitleFor( 'PasswordReset' ),
1011 $this->msg( 'userlogin-resetpassword-link' )->text()
1012 ),
1013 'weight' => 230,
1014 ];
1015 }
1016
1017 // Don't show a "create account" link if the user can't.
1018 if ( $this->showCreateAccountLink() ) {
1019 // link to the other action
1020 $linkTitle = $this->getTitleFor( $this->isSignup() ? 'Userlogin' : 'CreateAccount' );
1021 $linkq = $this->getReturnToQueryStringFragment();
1022 // Pass any language selection on to the mode switch link
1023 if ( $this->mLanguage ) {
1024 $linkq .= '&uselang=' . urlencode( $this->mLanguage );
1025 }
1026 $isRegistered = $this->getUser()->isRegistered();
1027
1028 $fieldDefinitions['createOrLogin'] = [
1029 'type' => 'info',
1030 'raw' => true,
1031 'linkQuery' => $linkq,
1032 'default' => function ( $params ) use ( $isRegistered, $linkTitle ) {
1033 return Html::rawElement( 'div',
1034 [ 'id' => 'mw-createaccount' . ( !$isRegistered ? '-cta' : '' ),
1035 'class' => ( $isRegistered ? 'mw-form-related-link-container' : 'mw-ui-vform-field' ) ],
1036 ( $isRegistered ? '' : $this->msg( 'userlogin-noaccount' )->escaped() )
1037 . Html::element( 'a',
1038 [
1039 'id' => 'mw-createaccount-join' . ( $isRegistered ? '-loggedin' : '' ),
1040 'href' => $linkTitle->getLocalURL( $params['linkQuery'] ),
1041 'class' => ( $isRegistered ? '' : 'mw-ui-button' ),
1042 'tabindex' => 100,
1043 ],
1044 $this->msg(
1045 $isRegistered ? 'userlogin-createanother' : 'userlogin-joinproject'
1046 )->text()
1047 )
1048 );
1049 },
1050 'weight' => 235,
1051 ];
1052 }
1053 }
1054
1055 return $fieldDefinitions;
1056 }
1057
1067 protected function hasSessionCookie() {
1069
1070 return $wgDisableCookieCheck || (
1072 $this->getRequest()->getSession()->getId() === (string)$wgInitialSessionId
1073 );
1074 }
1075
1081 protected function getReturnToQueryStringFragment() {
1082 $returnto = '';
1083 if ( $this->mReturnTo !== '' ) {
1084 $returnto = 'returnto=' . wfUrlencode( $this->mReturnTo );
1085 if ( $this->mReturnToQuery !== '' ) {
1086 $returnto .= '&returntoquery=' . wfUrlencode( $this->mReturnToQuery );
1087 }
1088 }
1089 return $returnto;
1090 }
1091
1097 private function showCreateAccountLink() {
1098 return $this->isSignup() ||
1099 $this->getContext()->getAuthority()->isAllowed( 'createaccount' );
1100 }
1101
1102 protected function getTokenName() {
1103 return $this->isSignup() ? 'wpCreateaccountToken' : 'wpLoginToken';
1104 }
1105
1112 protected function makeLanguageSelector() {
1113 $msg = $this->msg( 'loginlanguagelinks' )->inContentLanguage();
1114 if ( $msg->isBlank() ) {
1115 return '';
1116 }
1117 $langs = explode( "\n", $msg->text() );
1118 $links = [];
1119 foreach ( $langs as $lang ) {
1120 $lang = trim( $lang, '* ' );
1121 $parts = explode( '|', $lang );
1122 if ( count( $parts ) >= 2 ) {
1123 $links[] = $this->makeLanguageSelectorLink( $parts[0], trim( $parts[1] ) );
1124 }
1125 }
1126
1127 return count( $links ) > 0 ? $this->msg( 'loginlanguagelabel' )->rawParams(
1128 $this->getLanguage()->pipeList( $links ) )->escaped() : '';
1129 }
1130
1139 protected function makeLanguageSelectorLink( $text, $lang ) {
1140 if ( $this->getLanguage()->getCode() == $lang ) {
1141 // no link for currently used language
1142 return htmlspecialchars( $text );
1143 }
1144 $query = [ 'uselang' => $lang ];
1145 if ( $this->mReturnTo !== '' ) {
1146 $query['returnto'] = $this->mReturnTo;
1147 $query['returntoquery'] = $this->mReturnToQuery;
1148 }
1149
1150 $attr = [];
1151 $targetLanguage = MediaWikiServices::getInstance()->getLanguageFactory()
1152 ->getLanguage( $lang );
1153 $attr['lang'] = $attr['hreflang'] = $targetLanguage->getHtmlCode();
1154
1155 return $this->getLinkRenderer()->makeKnownLink(
1156 $this->getPageTitle(),
1157 $text,
1158 $attr,
1159 $query
1160 );
1161 }
1162
1163 protected function getGroupName() {
1164 return 'login';
1165 }
1166
1171 protected function postProcessFormDescriptor( &$formDescriptor, $requests ) {
1172 // Pre-fill username (if not creating an account, T46775).
1173 if (
1174 isset( $formDescriptor['username'] ) &&
1175 !isset( $formDescriptor['username']['default'] ) &&
1176 !$this->isSignup()
1177 ) {
1178 $user = $this->getUser();
1179 if ( $user->isRegistered() ) {
1180 $formDescriptor['username']['default'] = $user->getName();
1181 } else {
1182 $formDescriptor['username']['default'] =
1183 $this->getRequest()->getSession()->suggestLoginUsername();
1184 }
1185 }
1186
1187 // don't show a submit button if there is nothing to submit (i.e. the only form content
1188 // is other submit buttons, for redirect flows)
1189 if ( !$this->needsSubmitButton( $requests ) ) {
1190 unset( $formDescriptor['createaccount'], $formDescriptor['loginattempt'] );
1191 }
1192
1193 if ( !$this->isSignup() ) {
1194 // FIXME HACK don't focus on non-empty field
1195 // maybe there should be an autofocus-if similar to hide-if?
1196 if (
1197 isset( $formDescriptor['username'] )
1198 && empty( $formDescriptor['username']['default'] )
1199 && !$this->getRequest()->getCheck( 'wpName' )
1200 ) {
1201 $formDescriptor['username']['autofocus'] = true;
1202 } elseif ( isset( $formDescriptor['password'] ) ) {
1203 $formDescriptor['password']['autofocus'] = true;
1204 }
1205 }
1206
1207 $this->addTabIndex( $formDescriptor );
1208 }
1209}
$wgDisableCookieCheck
By default, MediaWiki checks if the client supports cookies during the login process,...
$wgLoginLanguageSelector
Show a bar of language selection links in the user login and user registration forms; edit the "login...
$wgSecureLogin
This is to let user authenticate using https when they come from http.
$wgEmailConfirmToEdit
Should editors be required to have a validated e-mail address before being allowed to edit?
$wgUseMediaWikiUIEverywhere
Temporary variable that applies MediaWiki UI wherever it can be supported.
const PROTO_HTTPS
Definition Defines.php:193
wfUrlencode( $s)
We want some things to be included as literal characters in our title URLs for prettiness,...
wfAppendQuery( $url, $query)
Append a query string to an existing URL, which may or may not already have query string parameters a...
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking,...
if(MW_ENTRY_POINT==='index') MediaWiki Session SessionId null $wgInitialSessionId
The persistent session ID (if any) loaded at startup.
Definition Setup.php:750
$wgLang
Definition Setup.php:831
A special page subclass for authentication-related special pages.
getContinueAction( $action)
Gets the _CONTINUE version of an action.
isActionAllowed( $action)
Checks whether AuthManager is ready to perform the action.
loadAuth( $subPage, $authAction=null, $reset=false)
Load or initialize $authAction, $authRequests and $subPage.
fieldInfoToFormDescriptor(array $requests, array $fieldInfo, $action)
Turns a field info array into a form descriptor.
getDefaultAction( $subPage)
Get the default action for this special page, if none is given via URL/POST data.
needsSubmitButton(array $requests)
Returns true if the form built from the given AuthenticationRequests needs a submit button.
string $subPage
Subpage of the special page.
isContinued()
Returns true if this is not the first step of the authentication.
static mergeDefaultFormDescriptor(array $fieldInfo, array $formDescriptor, array $defaultFormDescriptor)
Apply defaults to a form descriptor, without creating non-existend fields.
getRequest()
Get the WebRequest being used for this instance.
trySubmit()
Attempts to do an authentication step with the submitted data.
getToken()
Returns the CSRF token.
addTabIndex(&$formDescriptor)
Adds a sequential tabindex starting from 1 to all form elements.
An IContextSource implementation which will inherit context from another source but allow individual ...
An error page which can definitely be safely rendered using the OutputPage.
Object handling generic submission, CSRF protection, layout and other logic for UI forms in a reusabl...
Definition HTMLForm.php:143
Helper functions for the login form that need to be shared with other special pages (such as CentralA...
static getValidErrorMessages()
Returns an array of all valid error messages.
Holds shared logic for login and account creation pages.
mainLoginForm(array $requests, $msg='', $msgtype='error')
canBypassForm(&$button_name)
Determine if the login form can be bypassed.
getFieldDefinitions()
Create a HTMLForm descriptor for the core login fields.
getPreservedParams( $withToken=false)
Returns URL query parameters which can be used to reload the page (or leave and return) while preserv...
logAuthResult( $success, $status=null)
Logs to the authmanager-stats channel.
onAuthChangeFormFields(array $requests, array $fieldInfo, array &$formDescriptor, $action)
Change the form descriptor that determines how a field will look in the authentication form....
setSessionUserForCurrentRequest()
Replace some globals to make sure the fact that the user has just been logged in is reflected in the ...
showSuccessPage( $type, $title, $msgname, $injected_html, $extraMessages)
Show the success page.
getReturnToQueryStringFragment()
Returns a string that can be appended to the URL (without encoding) to preserve the return target.
User $targetUser
FIXME another flag for passing data.
successfulAction( $direct=false, $extraMessages=null)
showExtraInformation()
Show extra information such as password recovery information, link from login to signup,...
getPageHtml( $formHtml)
Add page elements which are outside the form.
hasSessionCookie()
Check if a session cookie is present.
loadRequestParameters()
Load basic request parameters for this Special page.
__construct( $name, $restriction='')
getAuthForm(array $requests, $action, $msg='', $msgType='error')
Generates a form from the given request.
getTokenName()
Returns the name of the CSRF token (under which it should be found in the POST or GET data).
makeLanguageSelectorLink( $text, $lang)
Create a language selector link for a particular language Links back to this page preserving type and...
bool $proxyAccountCreation
True if the user if creating an account for someone else.
showCreateAccountLink()
Whether the login/create account form should display a link to the other form (in addition to whateve...
getGroupName()
Under which header this special page is listed in Special:SpecialPages See messages 'specialpages-gro...
postProcessFormDescriptor(&$formDescriptor, $requests)
setRequest(array $data, $wasPosted=null)
Override the POST data, GET data from the real request is preserved.
showReturnToPage( $type, $returnTo='', $returnToQuery='', $stickHTTPS=false)
Add a "return to" link or redirect to it.
makeLanguageSelector()
Produce a bar of links which allow the user to select another language during login/registration but ...
load( $subPage)
Load data from request.
This serves as the entry point to the authentication system.
setAuthenticationSessionData( $key, $data)
Store authentication in the current session.
beginAuthentication(array $reqs, $returnToUrl)
Start an authentication flow.
getAuthenticationSessionData( $key, $default=null)
Fetch authentication data from the current session.
canCreateAccounts()
Determine whether accounts can be created.
canAuthenticateNow()
Indicate whether user authentication is possible.
This is a value object for authentication requests.
This is a value object to hold authentication response data.
This is a value object for authentication requests with a username and password.
PSR-3 logger instance factory.
MediaWikiServices is the service locator for the application scope of MediaWiki.
This serves as the entry point to the MediaWiki session handling system.
setContext( $context)
Sets the context this SpecialPage is executed in.
getName()
Get the name of this Special Page.
setHeaders()
Sets headers - this should be called from the execute() method of all derived classes!
getOutput()
Get the OutputPage being used for this instance.
getUser()
Shortcut to get the User executing this instance.
checkPermissions()
Checks if userCanExecute, and if not throws a PermissionsError.
static getTitleFor( $name, $subpage=false, $fragment='')
Get a localised Title object for a specified special page name If you don't need a full Title object,...
AuthManager null $authManager
getContext()
Gets the context this SpecialPage is executed in.
msg( $key,... $params)
Wrapper around wfMessage that sets the current context.
getConfig()
Shortcut to get main config object.
getPageTitle( $subpage=false)
Get a self-referential title object.
getLanguage()
Shortcut to get user's language.
getFullTitle()
Return the full title, including $par.
static setUser( $user)
Reset the stub global user to a different "real" user object, while ensuring that any method calls on...
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition User.php:69
static newFromName( $name, $validate='valid')
Definition User.php:607
if(!isset( $args[0])) $lang